Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed
| `compress.reasoningGuard` | object | off | — | Auto-repair of reasoning-lattice truncation on gpt-5.x/6.x (up to 3 continue-nudge rounds). |
| `compress.outputSteering` | object { enabled?, verbosityLevel?, effortRouting? } | enabled false · verbosityLevel 2 | — | Appends a conciseness directive to the system-prompt tail; clamps mechanical continuation requests. |
| `compress.priceProfile` | { w?, r?, q? } | unset (registry, kernel fallback {1, 0.1, 4}) | — | w/r/q ratios normalized to the input price (write/cache-read/output); report-only — never affects triggers or the wire. |
| `compress.externalSummary` | object | opt-in (disabled) | — | Sends compression summaries to separately configured models referenced from the providers table; whole-chain replace semantics at all three compress levels. |
| `compress.acknowledgePromptsRisk` | boolean | false | — | Must be true before custom prompts take effect. |
| `compress.absorb.enabled` | boolean | false | — | Enable the absorb distillation block. |
| `compress.absorb.minToolTokens` | number | 1000 | — | Minimum estimated token size of a tool result eligible for absorption. |
Expand Down
1 change: 1 addition & 0 deletions CONFIGURATION.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,7 @@
| `compress.reasoningGuard` | object | off | — | gpt-5.x/6.x 推理格截断自动修复(最多 3 轮继续提示)。 |
| `compress.outputSteering` | object { enabled?, verbosityLevel?, effortRouting? } | enabled false · verbosityLevel 2 | — | 向系统提示词尾部附加简洁度指令;只收紧机械延续请求。 |
| `compress.priceProfile` | { w?, r?, q? } | unset (registry, kernel fallback {1, 0.1, 4}) | — | w/r/q 相对输入价的比率(写入/缓存读/输出);仅供报告,不影响触发条件或线上行为。 |
| `compress.externalSummary` | object | opt-in (disabled) | — | 把压缩摘要交给 providers 表引用的独立配置模型;三级 compress 均为整链替换语义。 |
| `compress.acknowledgePromptsRisk` | boolean | false | — | 必须先置 true,自定义 prompts 才会生效。 |
| `compress.absorb.enabled` | boolean | false | — | 启用 absorb 蒸馏块。 |
| `compress.absorb.minToolTokens` | number | 1000 | — | 可被吸收的工具结果的最小估算 token 大小。 |
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 7 additions & 1 deletion scripts/config-surface-guard.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,13 @@ function namedTypeBodies(src) {

// Extract the quoted identifiers of `const <varName> = new Set([ ... ]);`.
export function extractStringSet(src, varName) {
const i = src.indexOf(varName);
// Locate the DEFINITION (`const <name> = new Set([`), not the first textual
// mention: doc comments legitimately reference the identifier above its
// definition (#3675's header did exactly that and fed the extractor the
// wrong bracket window — the join(", ") in unrelated code parsed as a
// leaf named ", ").
const def = src.indexOf(varName + " = new Set([");
const i = def >= 0 ? def : src.indexOf(varName);
if (i < 0) throw new Error(varName + " not found");
const open = src.indexOf("[", i);
const close = src.indexOf("]", open);
Expand Down
12 changes: 12 additions & 0 deletions src/acp-status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { getUnrecognizedPathStats } from "./server/observability.js";
import { ccrEnabled, ccrLoopConfig, contentStoreOf } from "./store.js";
import { coveredRefSpan } from "./decompress-shared.js";
import { describeUncoveredRuns, shortTokenCount, uncoveredHistoryRuns } from "./uncovered.js";
import { forkAdoptionSkippedOf } from "./fork-adoption.js";
import { preCompactionArchiveOf, statusInputBaseline, type Session } from "./session.js";
import { compressBreakerDetail, compressLastFailureCause } from "./stream.js";
import { describeAdvisory, getAdvisoryState } from "./advisory.js";
Expand Down Expand Up @@ -182,6 +183,17 @@ export function handleAcpStatus(args: Record<string, unknown>, ctx: AcpStatusCtx
});
if (scope) return toolOk(base);
const extra: string[] = [];
// #3925 → #3011 C9: a fork that started with zero inherited blocks used to
// be invisible here — "COMPRESSED BLOCKS — none" reads as "nothing folded
// yet", not "inheritance was skipped". Name the gap and its recovery path:
// the lineage link recorded at fork detection means a bili restart lets the
// startup sweep inherit the parent's blocks. Suppressed once any active
// block exists (the gap is closed by then, however it was closed).
const forkSkipped = forkAdoptionSkippedOf(ctx.session);
if (forkSkipped && !ctx.session.state.blocks.some((b) => b.active)) {
extra.push("");
extra.push(`FORK ADOPTION SKIPPED — this session forked from ${forkSkipped.parentId} with ${forkSkipped.blocks} parent block(s) (~${Math.round(forkSkipped.tokens / 1000)}K tokens) NOT inherited because forkAdoption is disabled; the parent's already-folded history replays raw and will re-fold from scratch. Set "forkAdoption": true (or BILI_FORK_ADOPTION=1) and restart bili — the recorded lineage link lets the startup sweep inherit those blocks.`);
}
// #2366: everything in the report above is LOCAL ESTIMATES (defaultCountTokens);
// on CJK-heavy routes upstream billing runs 2–4× higher, so an agent judging
// pressure from those figures misreads a filling window as healthy and folds
Expand Down
4 changes: 2 additions & 2 deletions src/agent/dsh-native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ import { markNativeHost, nativeAttachOrigin, nativeBootstrapGate, nativeProxyScr
import { installNativeFetchIntercept, liveStateSlotEffect, noteRoutedOrigin, observeRoutedOrigin, routedBiliModelUrl, type GateVerdict, type NativeInterceptState } from "./native-intercept.js";
import { asciiHeaderValue, fetchManifest, fetchProxyVersion, fetchStatus, fetchStatusLatest, forwardTool, reportAttributionHealth, reportRuntimeInfo, waitForProxyVersion, type ManifestTool } from "./shared.js";
import { createForkAdopter, sideShapedBody } from "./fork-adopt.js";
import { clearIncrementalProbe, createPrepareDirectSend, INCREMENTAL_TURN_MARKER_HEADER, INCREMENTAL_TURN_ID_HEADER, newIncrementalTurnId, noteIncrementalRejection, noteIncrementalAck, planIncrementalTurn, probeIncrementalTurns, rememberOriginalBody, sweepStale, type IncrementalWireMessage } from "./incremental-client.js";
import { clearIncrementalProbe, createPrepareDirectSend, INCREMENTAL_TURN_MARKER_HEADER, INCREMENTAL_TURN_ID_HEADER, newIncrementalTurnId, noteIncrementalRejection, noteIncrementalAck, planIncrementalTurn, probeIncrementalTurns, rememberOriginalBody, sweepStale, wireMessagesLookAnthropic, type IncrementalWireMessage } from "./incremental-client.js";
import { declareDshCompactionActive, detectCompactionOverlayGap, dshCompactionGateTelemetry } from "./dsh-compaction-disable.js";
import { maskUrlForDiagnostics } from "../log-mask.js";
import { mediaBytesOfWireBody } from "./media-bytes.js";
Expand Down Expand Up @@ -2342,7 +2342,7 @@ export function apply(ctx: PluginContext): void {
} catch {
return;
}
if (!Array.isArray(parsed.messages) || typeof parsed.model !== "string") return; // anthropic wire only
if (typeof parsed.model !== "string" || !wireMessagesLookAnthropic(parsed.messages)) return; // anthropic wire only — OpenAI tool shapes (tool_calls / role:"tool") resend full (#3433)
const base = register.base ?? state.origin;
if (base === undefined) return;
if (!(await probeIncrementalTurns(base))) return;
Expand Down
7 changes: 4 additions & 3 deletions src/agent/pi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { disposeSubagentSelfReg, selfRegisterForSession, type SubagentSelfRegSta
import { isModelApiUrl, nativeInterceptInstalled } from "./native-intercept.js";
import { wirePiSubagents } from "./pi-subagents.js";
import { wireToolGuardrails } from "./tool-guardrails.js";
import { clearIncrementalProbe, noteHostMsgIdHint, INCREMENTAL_TURN_MARKER_HEADER, incrementalEnvelopeConversationId, incrementalWireHash, noteIncrementalRejection, noteIncrementalAck, planIncrementalTurn, probeIncrementalTurns, pullIncrementalReceipt, sweepStale, type HostMsgIdHintEntry, type IncrementalWireMessage } from "./incremental-client.js";
import { clearIncrementalProbe, noteHostMsgIdHint, INCREMENTAL_TURN_MARKER_HEADER, incrementalEnvelopeConversationId, incrementalWireHash, noteIncrementalRejection, noteIncrementalAck, planIncrementalTurn, probeIncrementalTurns, pullIncrementalReceipt, sweepStale, wireMessagesLookAnthropic, type HostMsgIdHintEntry, type IncrementalWireMessage } from "./incremental-client.js";
import { laneMsgIdsForWire, lanePinnableContent } from "./pi-msgids.js";
import { validateMsgIds } from "../msgid-pin.js";
import type { DirectSendPrep } from "./native-intercept.js";
Expand Down Expand Up @@ -599,7 +599,7 @@ function manifestToTool(proxyBase: string, tool: ManifestTool, agent: string): T
description: tool.description,
parameters: tool.inputSchema,
loadMode: "essential",
execute: async (_toolCallId, params, signal, _onUpdate, ctx) => {
execute: async (toolCallId, params, signal, _onUpdate, ctx) => {
const conversationId = sessionIdOf(ctx) ?? "unknown";
try {
// #2416: read the LIVE base — a native respawn after a proxy
Expand All @@ -619,7 +619,7 @@ function manifestToTool(proxyBase: string, tool: ManifestTool, agent: string): T
// rebinding (onRoutedOriginObserved) converges env back to the
// observed routed origin.
const base = proxyBaseForCtx(ctx) ?? proxyBase;
const output = await forwardTool(base, conversationId, tool.name, params, signal, conversationId !== "unknown");
const output = await forwardTool(base, conversationId, tool.name, params, signal, conversationId !== "unknown", toolCallId);
// #2204: a business failure (e.g. a refused export) must reach
// the host as isError — rendering it as plain success text is
// what hid the #2204 write failures from OMP.
Expand Down Expand Up @@ -1399,6 +1399,7 @@ export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalM
if (state.toolsReady !== true) return undefined; // no marker stamped → must not replace
const payload = event.payload as { messages?: unknown; system?: unknown } | undefined;
if (payload === null || typeof payload !== "object" || !Array.isArray((payload as { messages?: unknown }).messages)) return undefined;
if (!wireMessagesLookAnthropic(payload.messages)) return undefined; // anthropic wire only — OpenAI tool shapes resend full (#3433)
const sid = sessionIdOf(ctx);
if (sid === undefined || sid.length === 0) return undefined;
let proxyBase = proxyBaseForCtx(ctx);
Expand Down
5 changes: 3 additions & 2 deletions src/agent/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -376,8 +376,9 @@ export async function reportAttributionHealth(proxyBase: string, health: Attribu
* partial note in `text`. Absent on legacy envelopes without the fields. */
export type ForwardedToolResult = { text: string; failed: boolean; outcome?: ToolOutcomeKind; blocksCreated?: number };

export async function forwardTool(proxyBase: string, conversationId: string, tool: string, args: unknown, signal?: AbortSignal, nativeCaller: boolean = false): Promise<ForwardedToolResult> {
const body: { conversationId: string; tool: string; args: unknown; nativeCaller?: boolean } = { conversationId, tool, args: args ?? {} };
export async function forwardTool(proxyBase: string, conversationId: string, tool: string, args: unknown, signal?: AbortSignal, nativeCaller: boolean = false, toolCallId?: string): Promise<ForwardedToolResult> {
const body: { conversationId: string; tool: string; args: unknown; nativeCaller?: boolean; toolCallId?: string } = { conversationId, tool, args: args ?? {} };
if (toolCallId !== undefined) body.toolCallId = toolCallId;
// #2072: host-native agents (pi / dsh / opencode) stamp a per-call id minted
// by the host's own session manager — declare it so a stale sibling witness
// can neither redirect nor fail-closed the call (ladder rung 0, #2024/#2016).
Expand Down
7 changes: 7 additions & 0 deletions src/external-summary-settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,13 @@ function text(value: unknown, limit: number): string {
export const AUTO_FOLD_TARGET_MIN = 8_192;
const AUTO_FOLD_TARGET_MAX = 10_000_000;

/** [#3444] A growth fold must be EXPECTED to save at least this much to run,
* and a fold that actually saved less arms the backoff instead of re-firing
* next request: below this, the fixed cost of an external-summary round trip
* (latency + quota + cache invalidation) outweighs the saving — a sub-floor
* target used to burn such marginal folds on EVERY request (fold storm). */
export const AUTO_FOLD_MIN_BENEFIT_TOKENS = 4_096;

/** [#autoFold] Both parsers share the exact switch/target semantics: the
* target is only meaningful with the switch on; the switch defaults to
* half the model window at trigger time. */
Expand Down
20 changes: 16 additions & 4 deletions src/external-summary-surface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,15 @@ export function armAutoFoldBackoff(session: { metadata?: Record<string, unknown>
(session.metadata ?? (session.metadata = {})).autoFoldBackoffUntil = Date.now() + AUTO_FOLD_BACKOFF_MS;
}

/** [#3444] Measured irreducible floor of this session (system prompt + tool
* schemas + live tail), recorded by an exhausted growth pass that could not
* reach its target. Latest measurement wins (tracks baseline drift both ways);
* a fresh session id starts unmeasured. Undefined until measured or invalid. */
export function autoFoldFloor(session: { metadata?: Record<string, unknown> } | undefined): number | undefined {
const value = session?.metadata?.autoFoldFloorTokens;
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
}

/** #2662: every external-summary batch of this invocation was dropped by the
* shared pool before a single candidate call dispatched. That shape is
* scheduler congestion (transient by nature), NOT evidence the summary chain
Expand All @@ -91,16 +100,19 @@ export function autoFoldEngaged(config: unknown, session: { metadata?: Record<st
* no fold and no backoff able to arm (PR #2581 review) — suppression must
* require a target strictly below the overflow bar. overflowTarget:
* preflight's effective bar (the codex lane lowers it); omit to use
* config.modelContextLimit. Mirrors the target math in server.ts's
* preflight — keep the two in sync. */
export function growthFoldingArmed(config: unknown, overflowTarget?: number): boolean {
* config.modelContextLimit. measuredFloor: the session's measured
* irreducible floor (#3444) — a floor at/above the bar means even an
* exhausted fold cannot reach the target, so the bar itself is unreachable
* and suppression must release (classic nudges are the remaining channel).
* Mirrors the target math in server.ts's preflight — keep the two in sync. */
export function growthFoldingArmed(config: unknown, overflowTarget?: number, measuredFloor?: number): boolean {
const resolved = config as ResolvedKernelConfig | undefined;
const ext = resolved?.externalSummary;
if (ext?.enabled !== true || ext.autoFold !== true) return false;
const overflow = overflowTarget ?? resolved?.modelContextLimit ?? 0;
if (!(overflow > 0)) return false;
const configured = ext.autoFoldTargetTokens ?? Math.round(overflow / 2);
const target = Math.max(AUTO_FOLD_TARGET_MIN, Math.min(configured, overflow));
const target = Math.max(AUTO_FOLD_TARGET_MIN, Math.min(configured, overflow), measuredFloor ?? 0);
return target < overflow;
}

Expand Down
2 changes: 1 addition & 1 deletion src/fold-decomposition-lookup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export interface StoredRow {
content: string;
}

export interface DecompositionSource {
interface DecompositionSource {
/** null = no index available (legacy/shadow/degraded); [] = index has none of them. */
rows(sessionId: string, msgIds: readonly string[]): StoredRow[] | null;
}
Expand Down
Loading
Loading