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
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ The full file-by-file map lives in [reference/architecture.md](reference/archite
8. **Nudge cadence is flat 50K by design (kernel contract)** — acp-kernel pins the growth interval at 50000 for every window size (`nudge.growthFloor == nudge.growthCap == 50000`; window-percentage scaling was deliberately removed — #379/#380 settled "growth-driven, no usage/count proxy gates"). Do NOT re-scale the interval with the context window or reintroduce percentage gates; a 1M-window session folding every 50K of growth is intended lean-context behavior. User escape hatch: `compress.nudgeGrowthTokens` (flattens `growthFloor`+`growthCap` to a fixed step) — big-window users who want a lazier cadence set it explicitly. Prompt wording is kernel-owned (`src/nudge-text.ts`).
9. **Hosts that reuse ONE session id across personas get id + system-hash session keys ("hash 不一样自动分裂")** — when a plugin host stamps the SAME conversation id on every model request of a session INCLUDING auxiliary personas (dsh auto-review `classifyRisk()`: fixed REVIEW_POLICY system + a fresh flattened blob before every tool call — #1916/#1307/#1314), those auxiliary requests must be keyed by `subagentNamespace(id, systemText)` so the persona forks onto its own `<id>|sub:<fp>` session instead of overwriting the main session's baseline/snapshots. The FIRST system seen under the id keeps the raw key (kernel anchor), so main turns never fork; an empty system is non-anchoring (verbatim). This is an EVIDENCE-PERMITLIST (`dshPersonaFingerprintApplies` in `src/session-id.ts`), the same discipline as the instructions fingerprint (#1104/#1107): do NOT enable it wholesale — for everyone else system drift mid-id means "same conversation, evolved", and forking resets compression for no defending bug (#1106). A future host found reusing session ids across personas gets added to that predicate WITH traffic evidence (shape + stability proof: the host's main system must be session-stable, e.g. dsh composes it once per session and puts volatile time-context in a USER message). The fork must record itself under its suffixed id (`personaForked` → `recordPluginSession`) so the single-valued conversations map keeps the raw key owned by the main session (#970 discipline). Tests: `tests/dsh-persona-fingerprint.test.ts`.

10. **Thinking-family blocks are signature-verified — NEVER rewrite them (#1960)** — Anthropic `thinking`/`redacted_thinking` blocks and Gemini `thoughtSignature` parts are verified byte-for-byte when the latest assistant message is replayed ("thinking blocks ... cannot be modified"). The bytes the proxy forwards become the client's persisted history, and the bytes the loop accumulates become the re-request rebuild — BOTH must stay verbatim. Any transformation (tag/marker stripping, dedup, trimming, re-laying-out block order, dropping empty segments) desynchronizes text from signature and bricks the session: first on the in-turn re-request, then on every subsequent request via the client's echo. #1882 put a prose filter on the thinking channel and it was exactly this bug. Treat ANY future change touching thinking-family payloads as high-risk: it needs loop-level byte-equality tests (re-request body AND client-visible stream) on both signed wires, not just adapter-level ones. The prose filters (#206/#1881) are for the TEXT channel only.

### Install-Lane & Update-Ownership Contract (#1196)

Every bili presence on a machine follows ONE contract — decide changes against it, not ad hoc:
Expand Down
8 changes: 4 additions & 4 deletions package-lock.json

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

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
"@types/node": "^22.0.0",
"@types/node-forge": "^1.3.14",
"@types/semver": "^7.7.1",
"acp-kernel": "0.0.100",
"acp-kernel": "0.0.101",
"fzstd": "0.1.1",
"jsonc-parser": "^3.3.1",
"node-forge": "^1.4.0",
Expand Down
92 changes: 33 additions & 59 deletions src/loop/adapter-anthropic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,37 +152,6 @@ function buildTextDeltaEvent(index: number, text: string): Buffer {
);
}

function rewriteThinkingDeltaEvent(eventStr: string, newIndex: number, newThinking: string): Buffer {
const lines = eventStr.split("\n");
const rebuilt: string[] = [];
for (const l of lines) {
if (l.startsWith("data:")) {
const jsonStr = l.slice(5).replace(/^ /, "");
try {
const obj = JSON.parse(jsonStr) as Record<string, unknown>;
if (typeof obj === "object" && obj !== null && typeof obj.index === "number") {
obj.index = newIndex;
const d = obj.delta as Record<string, unknown> | undefined;
if (d && typeof d.thinking === "string") d.thinking = newThinking;
rebuilt.push(`data: ${JSON.stringify(obj)}`);
continue;
}
} catch {
}
}
rebuilt.push(l);
}
return Buffer.from(rebuilt.join("\n") + "\n\n", "utf8");
}

function buildThinkingDeltaEvent(index: number, thinking: string): Buffer {
return Buffer.from(
`event: content_block_delta\n` +
`data: ${JSON.stringify({ type: "content_block_delta", index, delta: { type: "thinking_delta", thinking } })}\n\n`,
"utf8",
);
}

export function createAnthropicAdapter(requestBody: Record<string, unknown>, originalSystem?: AnthropicRequestBody["system"], notes?: string[], errorShape: "protocol" | "completion" = "protocol", cacheMarks?: Map<string, { type: "ephemeral" }>): CompressLoopAdapter {
const model = (requestBody.model as string) ?? undefined;
let messageId: string | undefined;
Expand Down Expand Up @@ -304,6 +273,10 @@ export function createAnthropicAdapter(requestBody: Record<string, unknown>, ori
let usageYielded = false;
const indexMap = new Map<number, number>();
const thinkingIndexes = new Set<number>();
// #1960: a redacted_thinking block arrives whole in content_block_start
// (no deltas) — capture its opaque payload so the rebuilt tail replays it
// byte-exact in position.
const redactedPayloads = new Map<number, string>();
// #206: strip model-imitated render tags from PROSE deltas before
// they reach the client (and before the loop accumulates them for
// re-request rounds). Flush at the owning block's stop so held-back
Expand All @@ -325,7 +298,6 @@ export function createAnthropicAdapter(requestBody: Record<string, unknown>, ori
}),
);
const tagFilter = makeFilter();
const thinkingFilter = makeFilter();
let lastTextIndex: number | null = null;
let lastThinkingIndex: number | null = null;
let sawThinking = false;
Expand Down Expand Up @@ -405,6 +377,9 @@ export function createAnthropicAdapter(requestBody: Record<string, unknown>, ori
if (block.type === "thinking" || block.type === "redacted_thinking") {
thinkingIndexes.add(upstreamIndex);
sawThinking = true;
if (block.type === "redacted_thinking" && typeof block.data === "string") {
redactedPayloads.set(upstreamIndex, block.data);
}
}
const ci = clientIndex++;
indexMap.set(upstreamIndex, ci);
Expand All @@ -427,20 +402,23 @@ export function createAnthropicAdapter(requestBody: Record<string, unknown>, ori
yield { kind: "text", delta: clean, raw } as ParsedStreamEvent;
}
} else if (delta.type === "thinking_delta" && typeof delta.thinking === "string" && delta.thinking.length > 0) {
// #1881: thinking prose goes through its own filter —
// the raw passthrough here was the leak path. Signature
// deltas below stay verbatim (opaque, not prose).
// #1960: thinking is a SIGNED payload — Anthropic verifies it
// byte-for-byte when the latest assistant message is replayed
// ("thinking blocks ... cannot be modified"), and Gemini's
// thoughtSignature has the same contract. Any filtering here —
// of the bytes forwarded to the client OR of the text the loop
// accumulates for the re-request rebuild — desynchronizes the
// text from its signature and bricks the session (the client
// persists the filtered bytes and re-sends them forever). So the
// #1881/#1882 prose filters NEVER touch thinking; cosmetic
// tag/marker echoes inside a thinking pane are accepted.
const ci = indexMap.get(upstreamIndex) ?? upstreamIndex;
lastThinkingIndex = ci;
const clean = thinkingFilter.push(delta.thinking);
if (clean.length > 0) {
const raw = clean === delta.thinking ? remapIndexInEvent(eventStr, ci) : rewriteThinkingDeltaEvent(eventStr, ci, clean);
yield {
kind: "reasoning",
delta: clean,
raw,
} as ParsedStreamEvent;
}
yield {
kind: "reasoning",
delta: delta.thinking,
raw: remapIndexInEvent(eventStr, ci),
} as ParsedStreamEvent;
} else if (delta.type === "signature_delta" && typeof delta.signature === "string") {
const ci = indexMap.get(upstreamIndex) ?? upstreamIndex;
yield {
Expand Down Expand Up @@ -469,17 +447,19 @@ export function createAnthropicAdapter(requestBody: Record<string, unknown>, ori
} else if (thinkingIndexes.delete(upstreamIndex)) {
// Seal the current thinking segment so interleaved thinking
// blocks each keep their own signature on rebuild.
// #1960: a redacted block has no captured reasoning — replay its
// opaque payload instead of sealing an empty segment.
const ci = indexMap.get(upstreamIndex) ?? upstreamIndex;
removeOpenBlock(ci);
if (lastThinkingIndex !== null) {
const tail = thinkingFilter.flush();
if (tail.length > 0) {
yield { kind: "reasoning", delta: tail, raw: buildThinkingDeltaEvent(lastThinkingIndex, tail) } as ParsedStreamEvent;
}
lastThinkingIndex = null;
}
lastThinkingIndex = null;
yield { kind: "meta", chunk: remapIndexInEvent(eventStr, ci), firstRoundOnly: false } as ParsedStreamEvent;
yield { kind: "reasoning", delta: "", blockEnd: true } as ParsedStreamEvent;
const redactedData = redactedPayloads.get(upstreamIndex);
if (redactedData !== undefined) {
redactedPayloads.delete(upstreamIndex);
yield { kind: "redacted_thinking", data: redactedData } as ParsedStreamEvent;
} else {
yield { kind: "reasoning", delta: "", blockEnd: true } as ParsedStreamEvent;
}
} else {
const ci = indexMap.get(upstreamIndex) ?? upstreamIndex;
removeOpenBlock(ci);
Expand Down Expand Up @@ -548,13 +528,7 @@ export function createAnthropicAdapter(requestBody: Record<string, unknown>, ori
}
lastTextIndex = null;
}
if (lastThinkingIndex !== null) {
const tail = thinkingFilter.flush();
if (tail.length > 0) {
yield { kind: "reasoning", delta: tail, raw: buildThinkingDeltaEvent(lastThinkingIndex, tail) } as ParsedStreamEvent;
}
lastThinkingIndex = null;
}
lastThinkingIndex = null;
const stopExtras = terminalExtrasOf(data, MESSAGE_STOP_KNOWN_KEYS);
if (!usageYielded) {
usageYielded = true;
Expand Down
41 changes: 15 additions & 26 deletions src/loop/adapter-google.ts
Original file line number Diff line number Diff line change
Expand Up @@ -286,9 +286,14 @@ export function createGoogleAdapter(
const rawCallChunks: { json: string; parsed: Record<string, unknown>; callIndexes: number[] }[] = [];
// #206/#717: strip model-imitated render tags and forged ACP
// confirmation markers from prose parts; filters may hold back a
// short tail, flushed on finish (and at stream end). #1881: thought
// parts get their own instance — interleaved text/thought deltas on
// one shared state would misattribute held tails between fields.
// short tail, flushed on finish (and at stream end).
// #1960: there is deliberately NO filter instance for thought parts —
// thought text is signed (thoughtSignature is verified byte-for-byte
// on replay, the same fatality class as Anthropic thinking), so any
// filtering of the forwarded or accumulated bytes desynchronizes
// text from signature and bricks the session. Thought echoes are
// forwarded verbatim; cosmetic leaks inside a thought pane are
// accepted (#1960 verdict).
const makeFilter = () => composeStreamFilters(
composeStreamFilters(
createTagEchoFilter((snippet) => {
Expand All @@ -303,16 +308,11 @@ export function createGoogleAdapter(
}),
);
const tagFilter = makeFilter();
const thoughtFilter = makeFilter();
const flushFilter = function* (): Generator<ParsedStreamEvent> {
const tail = tagFilter.flush();
if (tail.length > 0) {
yield { kind: "text", delta: tail, raw: buildChunk([{ text: tail }]) } as ParsedStreamEvent;
}
const ttail = thoughtFilter.flush();
if (ttail.length > 0) {
yield { kind: "reasoning", delta: ttail, raw: buildChunk([{ text: ttail, thought: true }]) } as ParsedStreamEvent;
}
};
let callIndex = 0;
let sawReasoning = false;
Expand Down Expand Up @@ -500,28 +500,17 @@ export function createGoogleAdapter(
if (typeof part.text !== "string" || part.text.length === 0) continue;
if (part.thought === true) {
sawReasoning = true;
const clean = thoughtFilter.push(part.text);
if (clean.length === 0) continue;
// #1960: thought parts replay VERBATIM — never filtered
// (thoughtSignature is verified byte-for-byte; see the
// makeFilter note above).
emitted = true;
let raw: Buffer | undefined;
if (clean === part.text) {
// A chunk that also carries functionCall parts is replayed
// whole at settle, so its text must not be forwarded twice.
if (!hasCallPart) raw = finishReason ? sseFrame(cloneChunk(parsed, { dropFinishReason: true })) : rawBuf;
} else {
editedParts = (editedParts ?? [...parts]).map((p, j) => (j === i ? { ...p, text: clean } : p));
if (!hasCallPart) {
raw = sseFrame(cloneChunk(parsed, {
parts: parts
.map((p, j) => (j === i ? { ...p, text: clean } : p))
.filter((p) => !p || typeof p !== "object" || p.functionCall === undefined),
dropFinishReason: true,
}));
}
}
// A chunk that also carries functionCall parts is replayed
// whole at settle, so its text must not be forwarded twice.
if (!hasCallPart) raw = finishReason ? sseFrame(cloneChunk(parsed, { dropFinishReason: true })) : rawBuf;
yield {
kind: "reasoning",
delta: clean,
delta: part.text,
...(raw ? { raw } : {}),
...(typeof part.thoughtSignature === "string" && part.thoughtSignature.length > 0
? { signature: part.thoughtSignature }
Expand Down
Loading
Loading