Skip to content
11 changes: 9 additions & 2 deletions src/loop/adapter-anthropic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,14 @@ function rewriteTextDeltaEvent(eventStr: string, newIndex: number, newText: stri
return Buffer.from(rebuilt.join("\n") + "\n\n", "utf8");
}

// The loop's own early ends say "length", OpenAI's word; Anthropic has no
// such stop reason, and Claude Code stops mid-task on one it does not know.
// "max_tokens" makes it resume the turn instead (#5179).
function anthropicStopReason(reason: string | undefined): string {
if (!reason) return "end_turn";
return reason === "length" ? "max_tokens" : reason;
}

function buildTextDeltaEvent(index: number, text: string): Buffer {
return Buffer.from(
`event: content_block_delta\n` +
Expand Down Expand Up @@ -738,9 +746,8 @@ export function createAnthropicAdapter(requestBody: Record<string, unknown>, ori
},

emitCompletion(opts?: EmitCompletionOpts) {
const stopReason = opts?.finishReason ?? "end_turn";
return buildTerminal(
stopReason,
anthropicStopReason(opts?.finishReason),
opts?.usage?.outputTokens ?? 0,
opts?.usage?.inputTokens ?? 0,
opts?.usage?.cachedTokens ?? 0,
Expand Down
116 changes: 101 additions & 15 deletions src/loop/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,30 @@ import { safePrefix, safeSuffix, scrubLoneSurrogatesOnWire } from "../text-safe.

export const MAX_LOOP_ROUNDS = 10;

/** #5220: canonical signature of a failed proxy call — sorted-key JSON so
* argument-order noise doesn't defeat the repeat-detection set. Unparseable
* arguments fall back to the raw string (byte equality still catches the
* pathological identical-resubmit ping-pong the original #156 guard existed
* for). Takes the RAW model argument bytes (pr.arguments, per #3661/#156).
*/
export function failedCallSignature(name: string, argsJson: string): string {
let norm = argsJson;
try {
const obj = JSON.parse(argsJson);
if (obj !== null && typeof obj === "object" && !Array.isArray(obj)) {
norm = JSON.stringify(
Object.keys(obj as Record<string, unknown>).sort().reduce<Record<string, unknown>>((acc, k) => {
acc[k] = (obj as Record<string, unknown>)[k];
return acc;
}, {}),
);
}
} catch {
/* keep raw */
}
return `${name}:${norm}`;
}

export function buildVisibilityMarker(toolName: string, result: string): string {
const lines = result.split("\n").map((l) => l.trim()).filter((l) => l.length > 0);
const failed = lines.some((l) =>
Expand Down Expand Up @@ -597,11 +621,19 @@ export async function* runCompressLoop(

// #3302 (Ask 6): probe-family observability — a model failing compress with
// one endpoint fixed and the other varying is enumerating a sparse ref
// space; every attempt carries different args, so the failed-only breaker
// below ends such turns without ever flagging them. Log it once as an
// operator signal; the failure receipts carry the live range table.
// space; every attempt carries different args, so the repeat-signature
// breaker below lets such turns run (bounded by MAX_LOOP_ROUNDS) without
// ever flagging them. Log it once as an operator signal; the failure
// receipts carry the live range table.
const probeFailures = new Map<string, Set<string>>();
let probeWarned = false;
// #5220: canonical signatures of compress/decompress calls already FAILED
// in an earlier round of this request. A failed-only round whose signatures
// are ALL previously seen is pure ping-pong (the original #156 guard,
// restored in narrow form): breaking there costs nothing the model could
// have learned from. First-time failures feed the model a recovery
// receipt instead (see the failed-only handler below).
const failedSigs = new Set<string>();

// #762,#1479: strict-echo origin for re-request normalization (the learned
// flag rides on ctx.session.metadata; mirrors prepareOpenai's static gate).
Expand Down Expand Up @@ -1191,6 +1223,13 @@ export async function* runCompressLoop(
let realCalls = 0;
const realToolCalls: ToolCallEmit[] = [];
const proxyResults: { name: string; callId: string; result: string; arguments: string; wireArguments: string; signature?: string; image?: { base64: string; mediaType: string } }[] = [];
// #5220: the marker lines ACTUALLY streamed to the client this round
// (deduped, same order as the stream). On a failed-only round this IS
// the recovery receipt the retry body must carry — reconstructing it
// afterwards from seenMarkers would be impossible (the set no longer
// remembers which entries are new) and would drift from what the
// client saw.
const streamedMarkers: string[] = [];

for (const call of allCalls) {
if (call.name.length === 0) {
Expand Down Expand Up @@ -1222,6 +1261,7 @@ export async function* runCompressLoop(
} else {
seenMarkers.add(markerKey);
yield adapter.emitMarker(call.name, result.text);
streamedMarkers.push(buildVisibilityMarker(call.name, result.text));
}
}
} else {
Expand Down Expand Up @@ -1481,14 +1521,26 @@ export async function* runCompressLoop(
return;
}

// #156/#4186: if this round is only failed compress/decompress, stop
// here instead of re-requesting. The failed frames spliced into the
// retry body above are ephemeral (#1548): never persisted, never seen
// by the client. Letting them reach upstream and then vanish from the
// next request rewrites the provider's frozen prefix mid-history —
// an unsanctioned cache seam. Breaking keeps them off the wire; the
// receipt already streamed to the client carries why it failed, and a
// later turn can retry with a different range.
// Failed-only-round contract — history #156/#4186/#4217, current #5220:
// a round whose proxy results are ALL failed compress/decompress used
// to end the turn here with a fabricated "length" finish. Cache-clean
// (the ephemeral failure frames never reach upstream, #1548) but fatal
// to the user: no client on any wire auto-continues "length" (OpenAI:
// no such convention; Anthropic: not even a legal stop reason), so one
// bad compress call killed a running task mid-work (#5220 report;
// #5179 Anthropic field case). #5220 flips the default: feed the
// failure to the MODEL and let IT decide. The retry body carries ONE
// plain assistant receipt whose bytes are exactly the visibility
// markers already streamed to the client, so the client's transcript
// carries the same bytes into its next request and the provider's
// frozen prefix never diverges — no ephemeral frames, no seam, fuzz
// stays green. Bounded twice over: the narrow #156 breaker (every
// signature in the round already failed before → ping-pong → break)
// and MAX_LOOP_ROUNDS above. Threads-continue turns and
// visibilityMarkers=false requests keep the old contract: their client/
// delta view lacks the marker bytes, so a receipt-only body would
// carry server-invisible bytes upstream — exactly the seam #4186
// forbids.
const failedMutating = proxyResults.filter(
(pr) => (pr.name === "compress" || pr.name === "decompress") && pr.result.includes("FAILED"),
);
Expand All @@ -1503,10 +1555,44 @@ export async function* runCompressLoop(
}

if (reRequest && failedMutating.length > 0 && failedMutating.length === proxyResults.length) {
ctx.log(`[acp-loop] round ${round}: failed-only mutating round; completing after ${round} round(s) instead of re-requesting (#156/#4186)`);
loggerLog("warn", `[acp-loop] failed compress/decompress round at round ${round}; breaking early (#156/#4186)`);
yield adapter.emitCompletion({ finishReason: "length", usage, terminalExtra });
return;
const sigs = failedMutating.map((pr) => failedCallSignature(pr.name, pr.arguments));
const stuck = sigs.every((s) => failedSigs.has(s));
const receiptable = !stuck && ctx.visibilityMarkers !== false && !threadContinue;
if (!receiptable) {
const why = stuck
? "every failing signature already failed in an earlier round"
: "receipt channel unavailable (" + ([threadContinue ? "threads-delta" : null, ctx.visibilityMarkers === false ? "visibility markers off" : null].filter(Boolean).join(", ")) + ")";
ctx.log(`[acp-loop] round ${round}: failed-only mutating round (${why}); completing after ${round} round(s) instead of re-requesting (#156/#4186/#5220)`);
loggerLog("warn", `[acp-loop] failed compress/decompress round at round ${round}; breaking early (${why}) (#156/#4186/#5220)`);
yield adapter.emitCompletion({ finishReason: "length", usage, terminalExtra });
return;
}
sigs.forEach((s) => failedSigs.add(s));
// Splice the retry body: strip THIS round's ephemeral failure
// frames (they must never reach upstream — #1548/#4186) and
// append the recovery receipt as a plain assistant message —
// bytes identical to what emitMarker already streamed to the
// client this round (same order, same dedup: seenMarkers holds
// exactly what went out). Falls through to the normal
// re-request path below.
const dropIds = new Set<string>();
for (const pr of failedMutating) {
dropIds.add(`acp_loop_r${round}_asst_tc_${pr.callId}`);
dropIds.add(`acp_loop_r${round}_tool_${pr.callId}`);
}
coreMessages.splice(0, coreMessages.length, ...coreMessages.filter((m) => !dropIds.has(m.id)));
if (streamedMarkers.length > 0) {
ctx.log(`[acp-loop] round ${round}: failed-only mutating round; feeding the model a recovery receipt (${streamedMarkers.length} marker line(s)) and re-requesting (#5220)`);
coreMessages.push({ id: `acp_loop_r${round}_rcpt`, role: "assistant", contentType: "text", text: streamedMarkers.join("") });
} else {
// Every failure marker of this round was deduped against an
// earlier round — the client saw nothing new, so a receipt
// would be a zero-byte assistant frame (strict wires reject
// empty text blocks). Skip it: the body degrades to history +
// prose, stays cache-clean, and the signature breaker /
// MAX_LOOP_ROUNDS bound any resulting ping-pong.
ctx.log(`[acp-loop] round ${round}: failed-only mutating round; all markers deduped (nothing new reached the client), re-requesting without a receipt (#5220)`);
}
}

ctx.log(`[acp-loop] round ${round}: proxy tool executed; re-requesting so the model sees the result`);
Expand Down
2 changes: 1 addition & 1 deletion src/loop/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export { runCompressLoop, executeProxyTool, MAX_LOOP_ROUNDS } from "./core.js";
export { runCompressLoop, executeProxyTool, MAX_LOOP_ROUNDS, failedCallSignature } from "./core.js";
export type {
LoopCtx,
RequestOptions,
Expand Down
12 changes: 7 additions & 5 deletions tests/ccr-v2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -401,11 +401,13 @@ test("e2e CCR v2 opt-in: no ccr config at any level leaves the session unarmed
});
const sse = await res.text();
assert.ok(res.ok, `client turn failed: HTTP ${res.status}: ${sse}`);
// The refused decompress is a failed-only round: under #156/#4186 its
// ephemeral frame never reaches upstream again, so the turn ends after
// the compress re-request and the refusal surfaces to the client as the
// failure receipt instead of riding a third request.
assert.equal(captured.length, 2, "initial + compress re-request only; refused decompress is never re-requested");
// The refused decompress is a failed-only round: under #5220 it gets
// ONE recovery-receipt re-request (the third captured forward), which
// resubmits the identical refusal — where the restored #156 signature
// breaker ends the turn. Its ephemeral frame never rides that re-
// request upstream; the refusal surfaces to the client as the failure
// receipt.
assert.equal(captured.length, 3, "initial + compress re-request + one recovery-receipt re-request for the refused decompress (#5220)");
assert.match(captured[1]!, /Early history: messages 1-7 covered initial setup\./, "compress fold landed before the decompress attempt");
// [#1207 owner decision] CCR is opt-in on every lane: with no ccr key
// at any level the session never arms, so the range restore ack is the
Expand Down
10 changes: 5 additions & 5 deletions tests/compress-credit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,11 @@ test("#252: post-compress re-request usage is netted by the compress credit", as

test("#252: failed compress accrues no credit", async () => {
const ctx = makeCompressibleCtx();
// Sub-viability range (kernel minCompressRange) → compress FAILS.
// Sub-viability range (kernel minCompressRange) → compress FAILS. Under #5220
// such a round re-requests with a recovery receipt (round 2 below carries no
// usage report) — and the point still stands: NO credit may be netted off the
// turn's only real usage figure.
const badArgs = JSON.stringify({ content: [{ startId: "m00007", endId: "m00007", summary: "s" }] });
// Usage rides the round-1 completion: the failed-only breaker (#156/#4186)
// ends the turn before any re-request, so this is the only usage report of
// the turn — it must still land raw (no credit netting).
const round1 = [
sse("response.created", { response: { id: "resp_1", status: "in_progress" } }),
fcEvents(0, "call_c", "compress", badArgs),
Expand All @@ -138,7 +138,7 @@ test("#252: failed compress accrues no credit", async () => {
{ model: "gpt-4o", input: [], stream: true },
{ url: "http://mock", headers: {} },
);
assert.equal(fetchCalls, 0, "failed-only round breaks before any re-request (#4186)");
assert.equal(fetchCalls, 1, "first-time failure re-requests once via recovery receipt (#5220)");
assert.equal(ctx.session.stats.compressCreditTokens, 0, "no credit on failed compress");
assert.equal(ctx.session.stats.lastInputTokens, 50000, "usage lands raw when nothing was compressed");
} finally {
Expand Down
21 changes: 12 additions & 9 deletions tests/issue1195-overflow-refold.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,12 +263,15 @@ test("#2777: a failed compress after an accepted overflow fold keeps the fold fo
assert.equal(response.status, 200);
const stream = await response.text();
const forwards = () => upstream.bodies.filter((raw) => (JSON.parse(raw) as { stream?: boolean }).stream !== false);
// #4186: the failed-only compress round ends the turn — there is no internal
// continuation re-request, and its ephemeral failure frame never reaches
// the upstream (old contract asserted three forwards here).
assert.equal(forwards().length, 2, "original overflow + accepted folded retry only");
// #4186→#5220: the failed-only compress round no longer ends the turn —
// the receipt re-request is the third forward. It must carry the streamed
// ❌ receipt (client-visible bytes) and NONE of this round's ephemeral
// failure frames (#1548/#4186 seam invariant).
assert.equal(forwards().length, 3, "original overflow + accepted folded retry + recovery-receipt re-request (#5220)");
assert.ok(forwards()[0].includes("MARKER_1_"), "original request contains early history");
assert.ok(forwards()[1].includes(SUMMARY_TEXT) && !forwards()[1].includes("MARKER_1_"), "accepted retry folded early history");
assert.ok(forwards()[2].includes("Compression FAILED"), "receipt re-request carries the ❌ receipt as assistant text");
assert.ok(!forwards()[2].includes("tool_result"), "ephemeral failure frames stay off the wire (#1548/#4186)");
assert.match(stream, /Compression FAILED/, "the invalid-range receipt reaches the client");
// #2777 core property under the new contract: the accepted fold survives
// the failed compress into the NEXT turn's rebuild.
Expand All @@ -279,11 +282,11 @@ test("#2777: a failed compress after an accepted overflow fold keeps the fold fo
});
assert.equal(r2.status, 200);
const f = forwards();
assert.equal(f.length, 3, "next turn hits the upstream once more");
assert.ok(f[2].includes(SUMMARY_TEXT), "next-turn rebuild retains the accepted summary");
assert.ok(!f[2].includes("MARKER_1_"), "next-turn rebuild does not resurrect folded early history");
assert.ok(f[2].includes("MARKER_11_"), "next-turn rebuild preserves the recent tail");
assert.ok(f[2].length < f[0].length, "rebuild stays smaller than the rejected original");
assert.equal(f.length, 4, "next turn hits the upstream once more");
assert.ok(f[3].includes(SUMMARY_TEXT), "next-turn rebuild retains the accepted summary");
assert.ok(!f[3].includes("MARKER_1_"), "next-turn rebuild does not resurrect folded early history");
assert.ok(f[3].includes("MARKER_11_"), "next-turn rebuild preserves the recent tail");
assert.ok(f[3].length < f[0].length, "rebuild stays smaller than the rejected original");
});

test("e2e #1195 C: when the folded retry is ALSO rejected, the client sees the RETRY's verdict, not the stale first 400 — and the arm stays for the next turn", async (t) => {
Expand Down
9 changes: 5 additions & 4 deletions tests/issue1502-raw-args-salvage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,10 +206,11 @@ test("#1502 loop: garbage args log head+tail and yield the corruption marker, no
assert.doesNotMatch(output, /executing with \{\}/, "old degradation wording gone");
assert.match(output, /were not parseable JSON/, "corruption marker streamed to client");
assert.doesNotMatch(output, /carried no content at all/, "not mislabeled as empty");
// #4186: a failed-only round ends the turn — the corruption receipt is
// surfaced to the client above and NO re-request carries the ephemeral
// failure frame upstream (old contract asserted refetches === 1).
assert.equal(refetches, 0, "failed-only compress round ends the turn without a re-request");
// #4186→#5220: the corruption receipt is surfaced to the client above;
// the turn no longer ends there — ONE recovery-receipt re-request fires
// (this mock answers it with plain "ok" text). The ephemeral failure
// frame itself never rides that re-request upstream.
assert.equal(refetches, 1, "failed-only round re-requests once via recovery receipt (#5220)");
} finally {
globalThis.fetch = originalFetch;
}
Expand Down
Loading
Loading