diff --git a/src/degenerate-turn.ts b/src/degenerate-turn.ts
index 2092f58f32..346f7ee7c4 100644
--- a/src/degenerate-turn.ts
+++ b/src/degenerate-turn.ts
@@ -72,6 +72,41 @@ export function endsWithDraftClose(text: string): boolean {
return text.length > 0 && DRAFT_CLOSE_TAIL.test(text);
}
+// #3905: the announcement-tail shape. Unlike #2303 there is no draft tag: the
+// ENTIRE visible output of the turn is a short promise of the next action
+// ("Running verify after formatting:") that ends on a colon or ellipsis, with
+// no tool call and a clean stop. The upstream reports a healthy turn, the host
+// gets nothing actionable, and the session stalls until the user types
+// something. Observed verbatim at 24 output tokens / 32 visible chars behind a
+// deepseek-v4.1-flash combo member.
+//
+// Three precision boundaries — each one denies a real answer class that the
+// raw tail shape alone would misread as a stall (a false positive burns the
+// one-shot BILLED retry on a turn that was already complete):
+// 1. length cap: a genuine answer that happens to end on a colon is prose,
+// and prose is long. 400 chars sits an order of magnitude above the
+// observed stub and well below any real answer tail.
+// 2. action-intent cue: a bare colon/ellipsis appears in legitimate short
+// answers ("The answer is 42:", "I'm not sure…"). Only progressive-form
+// action verbs and first-person intent phrases count as cues — the forms
+// the production stubs actually use. The list is English-first by design:
+// non-English announcements keep pre-#3905 behavior (no retry) until
+// traffic evidence justifies more languages.
+// 3. closed code fence: an UNCLOSED fence means the output was cut inside a
+// code block — the truncated-output defect class (#1755/#2190), not a
+// stalled promise; retrying it as an announcement would double-bill a
+// length cut.
+const ANNOUNCE_TAIL = /(?::|…|\.\.\.)\s*$/;
+const ANNOUNCE_MAX_CHARS = 400;
+const ANNOUNCE_CUE = /\b(?:let me|i(?:'ll| will)|going to|gonna|running|checking|testing|inspecting|examining|looking|applying|adding|removing|updating|fixing|building|installing|scanning|verifying|formatting|cleaning|writing|reading|searching|starting|committing|pushing|deploying|restarting|compiling|linting|patching)\b/i;
+export function endsWithAnnouncement(text: string): boolean {
+ const t = text.trimEnd();
+ if (t.length === 0 || t.length > ANNOUNCE_MAX_CHARS) return false;
+ if ((t.match(/```/g)?.length ?? 0) % 2 === 1) return false;
+ if (!ANNOUNCE_TAIL.test(t)) return false;
+ return ANNOUNCE_CUE.test(t);
+}
+
// #2612: the #2303 draft-tail shape has a legitimate producer — the CLIENT's
// own summarization request. Claude Code's compaction (/compact, auto-compact,
// precomputed compression) instructs the model, in the final user message, to
diff --git a/src/loop/core.ts b/src/loop/core.ts
index dc21c65327..160e0ffd86 100644
--- a/src/loop/core.ts
+++ b/src/loop/core.ts
@@ -48,7 +48,7 @@ import { isStrictReasoningEcho, modelIdOf, normalizeStrictEchoBody } from "../st
import { log as loggerLog } from "../logger.js";
import { promptInputTotal, type WireProtocol } from "../util.js";
import { DEGENERATE_RETRY_NUDGE } from "../degenerate-retry.js";
-import { endsWithDraftClose, lastUserSummaryInstruction, requestExpectsProseSummary } from "../degenerate-turn.js";
+import { endsWithAnnouncement, endsWithDraftClose, lastUserSummaryInstruction, requestExpectsProseSummary } from "../degenerate-turn.js";
import { safePrefix, safeSuffix, scrubLoneSurrogateEscapesOnJson } from "../text-safe.js";
export const MAX_LOOP_ROUNDS = 10;
@@ -1268,6 +1268,18 @@ export async function* runCompressLoop(
}
}
+ // #2303 / #3905: classify the terminal tail shape. Both shapes are
+ // non-converged handoffs — visible prose with no tool call — and share
+ // the budget, the openai/anthropic framing boundary and the #2612
+ // exemption below.
+ const stalledTail: "draft" | "announce" | null =
+ assistantText.length === 0 || calls.length > 0
+ ? null
+ : endsWithDraftClose(assistantText)
+ ? "draft"
+ : endsWithAnnouncement(assistantText)
+ ? "announce"
+ : null;
// #2303: a terminal turn that DID deliver visible prose but ends with a
// compression-draft closing tag (summary/analysis close forms) and no
// tool call — the model wrote a handoff/compression draft in prose
@@ -1293,7 +1305,7 @@ export async function* runCompressLoop(
!ctx.textProtocol &&
assistantText.length > 0 &&
calls.length === 0 &&
- endsWithDraftClose(assistantText) &&
+ (stalledTail === "draft" || stalledTail === "announce") &&
// #2612: the client's own compaction request instructs the
// model to answer with a plain-text summary block and no
// tool call — that compliant reply is a draft tail by
@@ -1303,8 +1315,13 @@ export async function* runCompressLoop(
!signal?.aborted
) {
degenerateRetried = true;
- ctx.log(`[acp-loop] round ${round}: terminal turn ends with a compression-draft closing tag and no tool call; retrying once with continuation nudge (#2303)`);
- loggerLog("warn", `[acp-loop] draft-tail auto-retry round ${round} (session ${ctx.session.id})`);
+ if (stalledTail === "announce") {
+ ctx.log(`[acp-loop] round ${round}: terminal turn is a bare announcement (ends mid-promise, no tool call); retrying once with continuation nudge (#3905)`);
+ loggerLog("warn", `[acp-loop] announcement-tail auto-retry round ${round} (session ${ctx.session.id})`);
+ } else {
+ ctx.log(`[acp-loop] round ${round}: terminal turn ends with a compression-draft closing tag and no tool call; retrying once with continuation nudge (#2303)`);
+ loggerLog("warn", `[acp-loop] draft-tail auto-retry round ${round} (session ${ctx.session.id})`);
+ }
const nudge: CoreMessage = {
id: `acp_draft_tail_retry_r${round}`,
role: "user",
@@ -1324,11 +1341,11 @@ export async function* runCompressLoop(
continue;
} catch (e) {
if (e instanceof UpstreamHttpError) {
- ctx.log(`[acp-loop] round ${round}: draft-tail retry failed (upstream error ${e.status}: ${e.body.slice(0, 200)}); passing the turn through`);
+ ctx.log(`[acp-loop] round ${round}: stalled-tail retry failed (upstream error ${e.status}: ${e.body.slice(0, 200)}); passing the turn through`);
} else {
- ctx.log(`[acp-loop] round ${round}: draft-tail retry failed (${e instanceof Error ? e.message : String(e)}); passing the turn through`);
+ ctx.log(`[acp-loop] round ${round}: stalled-tail retry failed (${e instanceof Error ? e.message : String(e)}); passing the turn through`);
}
- loggerLog("warn", `[acp-loop] draft-tail auto-retry failed round ${round}: ${e instanceof Error ? e.message : String(e)}`);
+ loggerLog("warn", `[acp-loop] stalled-tail auto-retry failed round ${round}: ${e instanceof Error ? e.message : String(e)}`);
}
}
break;
diff --git a/src/plugin.ts b/src/plugin.ts
index a4824a39d0..27a3bc2204 100644
--- a/src/plugin.ts
+++ b/src/plugin.ts
@@ -59,7 +59,7 @@ function tailLooksTerminal(tail: string, protocol: WireProtocol | "responses"):
return /event: response\.(?:completed|failed|incomplete)/.test(tail.slice(0, 64)) ||
/"type"\s*:\s*"response\.(?:completed|failed|incomplete)"/.test(tail);
}
-import { degenerateTurnWarning, endsWithDraftClose, requestExpectsProseSummary } from "./degenerate-turn.js";
+import { degenerateTurnWarning, endsWithAnnouncement, endsWithDraftClose, requestExpectsProseSummary } from "./degenerate-turn.js";
import { getChangelog, latestChangelog, warmChangelogOnce } from "./web/changelog.js";
import { warmBlogRefreshOnce } from "./web/blog-refresh.js";
import { PANEL_BOX_FOOTER } from "./acp-panel.js";
@@ -2920,6 +2920,17 @@ export async function pipePluginChatWithStrip(
// answer — a client compaction asking for a plain-text block
// must not be retried (its compliant reply IS a draft tail).
const draftTail = visibleTextChars > 0 && !sawToolUse && endsWithDraftClose(proseAcc) && !requestExpectsProseSummary(requestText);
+ // #3905: the same non-convergence without a draft tag — the whole visible
+ // output is a one-line promise of the next action ("Running verify after
+ // formatting:"). Without this branch the answerChars gate below would read
+ // that promise as a delivered answer and refuse the retry.
+ // The detector reads ANSWER prose, not proseAcc: proseAcc also carries
+ // the thinking/reasoning channel, and a thought that ends mid-sentence on
+ // ":" or "…" is internal monologue, not an announcement — feeding it here
+ // reclassified #2756's whitespace-only degenerate stops as announcements
+ // and swallowed their refusal/retry logs.
+ const announceTail = !draftTail && visibleTextChars > 0 && !sawToolUse && endsWithAnnouncement(answerProse) && !requestExpectsProseSummary(requestText);
+ const stalledTail = draftTail || announceTail;
// #2756: the gate asks "did the host receive ANSWER text?" — prose that
// is nothing but whitespace (a bare "\n\n" from a degenerate stop, the
// B-accident shape) is not an answer; the empty-turn retry must fire for
@@ -2927,9 +2938,9 @@ export async function pipePluginChatWithStrip(
// chars are already excluded here), and real text keeps refusing the
// retry byte-for-byte, so a delivered answer is never duplicated.
const answerChars = answerProse.trim().length;
- if (!draftTail && (answerChars > 0 || sawToolUse)) return false;
+ if (!stalledTail && (answerChars > 0 || sawToolUse)) return false;
if (reason === undefined || !CLEAN_TURN_REASONS.has(reason)) {
- if (!sawToolUse && !draftTail && answerChars === 0) log?.(`[plugin] degenerate terminal turn not retried (finish ${reason ?? "none"} is not a clean stop): visibleTextChars=${visibleTextChars}, releasedMarkupChars=${releasedMarkupChars} (#2756)`);
+ if (!sawToolUse && !stalledTail && answerChars === 0) log?.(`[plugin] degenerate terminal turn not retried (finish ${reason ?? "none"} is not a clean stop): visibleTextChars=${visibleTextChars}, releasedMarkupChars=${releasedMarkupChars} (#2756)`);
return false;
}
if (res.destroyed || res.writableEnded) return false;
@@ -2955,14 +2966,16 @@ export async function pipePluginChatWithStrip(
// re-issuing it double-bills an empty completion (#732/#821 keep the
// same boundary in the compress loop). A draft-tail turn is NOT bare:
// it delivered a full handoff draft, which is precisely the stall signal.
- if (!sawThinking && !sawStrippedEcho && releasedMarkupChars === 0 && !draftTail) {
+ if (!sawThinking && !sawStrippedEcho && releasedMarkupChars === 0 && !stalledTail) {
log?.(`[plugin] degenerate terminal turn not retried (bare: no thinking, no stripped echo, no released markup): visibleTextChars=${visibleTextChars}, releasedMarkupChars=${releasedMarkupChars} (#2756)`);
return false;
}
degenerateRetried = true;
- log?.(draftTail
- ? "[plugin] terminal turn ends with a compression-draft closing tag and no tool call; retrying once with a continuation nudge (#2303)"
- : "[plugin] degenerate terminal turn (no usable output); retrying once with a continuation nudge (#732/#821)");
+ log?.(announceTail
+ ? "[plugin] terminal turn is a bare announcement (ends mid-promise, no tool call); retrying once with a continuation nudge (#3905)"
+ : draftTail
+ ? "[plugin] terminal turn ends with a compression-draft closing tag and no tool call; retrying once with a continuation nudge (#2303)"
+ : "[plugin] degenerate terminal turn (no usable output); retrying once with a continuation nudge (#732/#821)");
let next: ReadableStream | null = null;
try {
next = await refetch();
@@ -4586,6 +4599,10 @@ export async function pipePluginResponsesWithStrip(
// #2612: except when the request itself demands that shape (client
// compaction summary instruction) — see the chat-pipe twin.
const draftTail = (visibleTextChars > 0 || heldVisibleChars > 0) && !sawFunctionCall && endsWithDraftClose(proseAcc) && !requestExpectsProseSummary(requestText);
+ // #3905: bare-announcement twin — see the chat-pipe twin above
+ // (including why the detector reads answerProse, not proseAcc).
+ const announceTail = !draftTail && (visibleTextChars > 0 || heldVisibleChars > 0) && !sawFunctionCall && endsWithAnnouncement(answerProse) && !requestExpectsProseSummary(requestText);
+ const stalledTail = draftTail || announceTail;
// #2756: same question as the chat-pipe twin — "did the host receive
// ANSWER text?". Reasoning inlined into item.content[] (vLLM/
// llama.cpp reasoning_text) and whitespace-only output_text (a bare
@@ -4593,9 +4610,9 @@ export async function pipePluginResponsesWithStrip(
// bare check below, but whitespace-only answer prose must also retry.
// Real answer text still refuses the retry byte-for-byte.
const answerChars = answerProse.trim().length;
- if (!draftTail && (answerChars > 0 || sawFunctionCall)) return false;
+ if (!stalledTail && (answerChars > 0 || sawFunctionCall)) return false;
if (status !== "completed") {
- if (!sawFunctionCall && !draftTail && answerChars === 0) log?.(`[plugin] degenerate terminal turn not retried (status ${status ?? "none"} is not completed): visibleTextChars=${visibleTextChars}, heldVisibleChars=${heldVisibleChars} (#2756)`);
+ if (!sawFunctionCall && !stalledTail && answerChars === 0) log?.(`[plugin] degenerate terminal turn not retried (status ${status ?? "none"} is not completed): visibleTextChars=${visibleTextChars}, heldVisibleChars=${heldVisibleChars} (#2756)`);
return false;
}
if (res.destroyed || res.writableEnded) return false;
@@ -4604,14 +4621,16 @@ export async function pipePluginResponsesWithStrip(
// double-bills an empty completion (#732/#821 keep the same boundary in
// the compress loop). A draft-tail turn delivered a full handoff draft:
// precisely the stall signal.
- if (!sawReasoning && !sawStrippedEcho && !draftTail) {
+ if (!sawReasoning && !sawStrippedEcho && !stalledTail) {
log?.(`[plugin] degenerate terminal turn not retried (bare: no reasoning, no stripped echo): visibleTextChars=${visibleTextChars}, heldVisibleChars=${heldVisibleChars} (#2756)`);
return false;
}
degenerateRetried = true;
- log?.(draftTail
- ? "[plugin] terminal turn ends with a compression-draft closing tag and no function call; retrying once with a continuation nudge (#2303)"
- : "[plugin] degenerate terminal turn (no visible output); retrying once with a continuation nudge (#732/#821)");
+ log?.(announceTail
+ ? "[plugin] terminal turn is a bare announcement (ends mid-promise, no function call); retrying once with a continuation nudge (#3905)"
+ : draftTail
+ ? "[plugin] terminal turn ends with a compression-draft closing tag and no function call; retrying once with a continuation nudge (#2303)"
+ : "[plugin] degenerate terminal turn (no visible output); retrying once with a continuation nudge (#732/#821)");
let next: ReadableStream | null = null;
try {
next = await refetch();
diff --git a/tests/issue3905-announcement-tail.test.ts b/tests/issue3905-announcement-tail.test.ts
new file mode 100644
index 0000000000..e8a88e19fd
--- /dev/null
+++ b/tests/issue3905-announcement-tail.test.ts
@@ -0,0 +1,420 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import type { Config, CoreMessage } from "acp-kernel";
+import { createCore, createInitialState } from "acp-kernel";
+import { pipePluginChatWithStrip, pipePluginResponsesWithStrip } from "../src/plugin.ts";
+import { endsWithAnnouncement, endsWithDraftClose } from "../src/degenerate-turn.ts";
+import type { Session } from "../src/session.ts";
+import { runCompressLoop, createOpenaiAdapter } from "../src/loop/index.ts";
+import { buildCompressSystemPrompt } from "../src/compress-tool.ts";
+
+// #3905: a terminal turn whose ENTIRE visible output is a short promise of the
+// next action ("Running verify after formatting:") ending on a colon or
+// ellipsis, with no tool call and a clean stop, used to read as a healthy
+// completed turn — the model announced the action instead of issuing it, and
+// the session stalls until the user types something (verbatim production stub:
+// ses_eb6da0d60ffeYpnNQDoGz000Pc, deepseek-v4.1-flash combo member, 24 output
+// tokens / 32 visible chars, finish=stop). All three terminal-verdict lanes
+// must treat it as non-converged and spend their one-shot continuation nudge
+// on it: the plugin chat pipe, the plugin responses pipe, and the compress
+// loop — mirroring the #2303 draft-tail suite.
+
+// ---------- detector unit ----------
+
+const ANNOUNCE_STUB = "Running verify after formatting:";
+
+test("endsWithAnnouncement: the production stubs and their ellipsis forms", () => {
+ assert.equal(endsWithAnnouncement("\n" + ANNOUNCE_STUB), true, "leading newline is stream residue");
+ assert.equal(endsWithAnnouncement(ANNOUNCE_STUB), true);
+ assert.equal(endsWithAnnouncement("Now I'll check the three suites:"), true);
+ assert.equal(endsWithAnnouncement("Let me look at that output\u2026"), true, "unicode ellipsis");
+ assert.equal(endsWithAnnouncement("Let me look at that output..."), true, "ascii ellipsis");
+ assert.equal(endsWithAnnouncement(`${ANNOUNCE_STUB} \r\n`), true, "trailing whitespace");
+});
+
+test("endsWithAnnouncement: legitimate short answers ending on a colon or ellipsis are NOT stubs", () => {
+ assert.equal(endsWithAnnouncement(""), false);
+ assert.equal(endsWithAnnouncement(" \n\t "), false, "whitespace-only is the empty-turn shape, not this one");
+ assert.equal(endsWithAnnouncement("All done."), false, "a normal sentence end is not a promise");
+ assert.equal(endsWithAnnouncement("Deleted."), false);
+ assert.equal(endsWithAnnouncement("The answer is 42:"), false, "colon without an action-intent cue is a complete short answer");
+ assert.equal(endsWithAnnouncement("I'm not sure\u2026"), false, "ellipsis without a cue is prose");
+ assert.equal(endsWithAnnouncement("I'm not sure..."), false);
+ assert.equal(endsWithAnnouncement("Here is how to run it:"), false, "base-form 'run' inside an explanation is not a cue (progressive forms + intent phrases only)");
+});
+
+test("endsWithAnnouncement: the 400-char cap stays the length boundary once a cue is present", () => {
+ const pad = (total: number) => `${ANNOUNCE_STUB.slice(0, -1)}${"a".repeat(total - ANNOUNCE_STUB.length)}:`;
+ assert.equal(endsWithAnnouncement(pad(400)), true, "exactly 400 chars is still inside the cap");
+ assert.equal(endsWithAnnouncement(pad(401)), false, "401 chars is past the cap");
+ assert.equal(endsWithAnnouncement("y".repeat(400)), false, "no promise tail at all");
+});
+
+test("endsWithAnnouncement: an unclosed code fence is the truncation class, not a stall (#1755/#2190)", () => {
+ assert.equal(endsWithAnnouncement("Running the tests:\n```\nstep one:"), false, "odd fence count — cut inside a code block");
+ assert.equal(endsWithAnnouncement("Running the tests:\n```\nconst a = 1;\n```"), false, "closed fence, and no promise tail either");
+});
+
+test("endsWithAnnouncement: disjoint from endsWithDraftClose", () => {
+ assert.equal(endsWithAnnouncement("handoff draft\n"), false, "#2303 owns the draft-close shape");
+ assert.equal(endsWithDraftClose(ANNOUNCE_STUB), false, "#3905 owns the announcement shape");
+});
+
+// ---------- shared fixtures ----------
+
+function makeSession(): Session {
+ return {
+ id: "testsess",
+ protocol: "openai",
+ upstreamOrigin: "http://127.0.0.1:9/v1",
+ label: "test",
+ createdAt: 0,
+ lastUsedAt: 0,
+ requests: 0,
+ lastInputTokens: 0,
+ stats: {},
+ dirty: false,
+ } as unknown as Session;
+}
+
+function makeRes(chunks: string[]) {
+ return {
+ writes: chunks,
+ write(b: Buffer | string) {
+ chunks.push(typeof b === "string" ? b : b.toString("utf8"));
+ return true;
+ },
+ end(b?: Buffer | string) {
+ if (b !== undefined) chunks.push(typeof b === "string" ? b : b.toString("utf8"));
+ },
+ once() {},
+ destroyed: false,
+ writableEnded: false,
+ } as unknown as import("node:http").ServerResponse;
+}
+
+function streamOf(events: string[]): ReadableStream {
+ const enc = new TextEncoder();
+ let i = 0;
+ return new ReadableStream({
+ pull(controller) {
+ if (i < events.length) {
+ controller.enqueue(enc.encode(events[i]));
+ i += 1;
+ } else {
+ controller.close();
+ }
+ },
+ });
+}
+
+function chatChunk(delta: Record): string {
+ return `data: ${JSON.stringify({ id: "chatcmpl-1", object: "chat.completion.chunk", created: 1, model: "qwen", choices: [{ index: 0, delta, finish_reason: null }] })}\n\n`;
+}
+
+const DONE = "data: [DONE]\n\n";
+
+function chatStop(reason = "stop"): string {
+ return `data: ${JSON.stringify({ id: "chatcmpl-1", object: "chat.completion.chunk", created: 1, model: "qwen", choices: [{ index: 0, delta: {}, finish_reason: reason }] })}\n\n`;
+}
+
+const sse = (event: string, data: unknown): string => `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
+
+/** The production shape (sanitized): the whole visible output is the one-line
+ * promise, delivered as the message's text with no tool call. */
+function announceTurn(): string[] {
+ return [chatChunk({ role: "assistant" }), chatChunk({ content: `\n${ANNOUNCE_STUB}` }), chatStop(), DONE];
+}
+
+function proseTurn(text: string): string[] {
+ return [chatChunk({ role: "assistant" }), chatChunk({ content: text }), chatStop(), DONE];
+}
+
+function textDeltas(raw: string): string {
+ return [...raw.matchAll(/"content":"((?:[^"\\]|\\.)*)"/g)].map((m) => JSON.parse(`"${m[1]}"`) as string).join("");
+}
+
+// ---------- plugin chat pipe (the DSH native evidence lane) ----------
+
+test("#3905 chat(openai): bare-announcement terminal turn spends the continuation nudge once", async () => {
+ const out: string[] = [];
+ const logs: string[] = [];
+ let calls = 0;
+ const refetch = () => {
+ calls += 1;
+ return Promise.resolve(streamOf(proseTurn("real action issued after the nudge")));
+ };
+ await pipePluginChatWithStrip(streamOf(announceTurn()), makeRes(out), "openai", makeSession(), (m) => logs.push(m), refetch);
+ const text = out.join("");
+ assert.equal(calls, 1, "exactly one re-issue");
+ assert.ok(textDeltas(text).includes(ANNOUNCE_STUB), "the first attempt's stub still reaches the client");
+ assert.ok(textDeltas(text).endsWith("real action issued after the nudge"), "the retry's content appends to the same stream");
+ assert.equal((text.match(/\[DONE\]/g) ?? []).length, 1, "one turn, one terminal");
+ assert.equal((text.match(/"finish_reason":"stop"/g) ?? []).length, 1, "the first attempt's terminal is dropped, not doubled");
+ assert.ok(logs.some((l) => l.includes("#3905")), `the distinct #3905 log line fired, got: ${JSON.stringify(logs)}`);
+});
+
+test("#3905 chat: a legitimate short answer ending on a colon is NOT retried", async () => {
+ const out: string[] = [];
+ let calls = 0;
+ const refetch = () => {
+ calls += 1;
+ return Promise.resolve(streamOf(proseTurn("unwanted")));
+ };
+ await pipePluginChatWithStrip(streamOf(proseTurn("The answer is 42:")), makeRes(out), "openai", makeSession(), undefined, refetch);
+ assert.equal(calls, 0, "no action-intent cue — the delivered answer is never duplicated or re-billed");
+});
+
+test("#3905 chat: a legitimate short answer ending on an ellipsis is NOT retried", async () => {
+ const out: string[] = [];
+ let calls = 0;
+ const refetch = () => {
+ calls += 1;
+ return Promise.resolve(streamOf(proseTurn("unwanted")));
+ };
+ await pipePluginChatWithStrip(streamOf(proseTurn("I'm not sure\u2026")), makeRes(out), "openai", makeSession(), undefined, refetch);
+ assert.equal(calls, 0, "ellipsis without a cue is prose, not a promise");
+});
+
+test("#3905 chat: a bare announcement WITH a tool call is NOT retried", async () => {
+ const out: string[] = [];
+ let calls = 0;
+ const refetch = () => {
+ calls += 1;
+ return Promise.resolve(streamOf(proseTurn("unwanted")));
+ };
+ const events = [
+ chatChunk({ role: "assistant" }),
+ chatChunk({ content: ANNOUNCE_STUB }),
+ `data: ${JSON.stringify({ id: "chatcmpl-1", object: "chat.completion.chunk", created: 1, model: "qwen", choices: [{ index: 0, delta: { tool_calls: [{ index: 0, id: "call_1", type: "function", function: { name: "compress", arguments: "{}" } }] }, finish_reason: null }] })}\n\n`,
+ chatStop("tool_calls"),
+ DONE,
+ ];
+ await pipePluginChatWithStrip(streamOf(events), makeRes(out), "openai", makeSession(), undefined, refetch);
+ assert.equal(calls, 0, "a tool call means the step converges");
+ assert.ok(out.join("").includes("compress"), "the agent's own tool call still passes through");
+});
+
+test("#3905 chat: an announcement RETRY degenerates into the in-band error (#870 path)", async () => {
+ const out: string[] = [];
+ const refetch = () => Promise.resolve(streamOf(announceTurn()));
+ await pipePluginChatWithStrip(streamOf(announceTurn()), makeRes(out), "openai", makeSession(), undefined, refetch);
+ const text = out.join("");
+ // #5958: the double-degenerate #870 terminal now ships as the protocol-native
+ // error frame (the global default) instead of the legacy "[ACP] stream error"
+ // completion shape — assert the native openai frame carrying the #3905 message.
+ assert.ok(
+ text.includes('"code":"stream_error"') &&
+ text.includes("[acp-proxy: the turn degenerated again after the continuation nudge]"),
+ "the client is told (native error frame), rather than left with a second silent announcement",
+ );
+});
+
+// ---------- plugin responses pipe ----------
+
+function responsesAnnounceTurn(responseId = "resp_1", itemId = "item_1"): string[] {
+ const text = ANNOUNCE_STUB;
+ return [
+ sse("response.created", { type: "response.created", response: { id: responseId, status: "in_progress" } }),
+ sse("response.output_item.added", { type: "response.output_item.added", output_index: 0, item: { id: itemId, type: "message", content: [] } }),
+ sse("response.content_part.added", { type: "response.content_part.added", item_id: itemId, output_index: 0, part: { type: "output_text", text: "" } }),
+ sse("response.output_text.delta", { type: "response.output_text.delta", item_id: itemId, output_index: 0, delta: text }),
+ sse("response.output_text.done", { type: "response.output_text.done", item_id: itemId, output_index: 0, text }),
+ sse("response.output_item.done", { type: "response.output_item.done", output_index: 0, item: { id: itemId, type: "message", content: [{ type: "output_text", text }] } }),
+ sse("response.completed", { type: "response.completed", response: { id: responseId, status: "completed", output: [{ id: itemId, type: "message", content: [{ type: "output_text", text }] }] } }),
+ ];
+}
+
+function responsesProseTurn(text: string, responseId = "resp_2", itemId = "item_2"): string[] {
+ return [
+ sse("response.created", { type: "response.created", response: { id: responseId, status: "in_progress" } }),
+ sse("response.output_item.added", { type: "response.output_item.added", output_index: 0, item: { id: itemId, type: "message", content: [] } }),
+ sse("response.content_part.added", { type: "response.content_part.added", item_id: itemId, output_index: 0, part: { type: "output_text", text: "" } }),
+ sse("response.output_text.delta", { type: "response.output_text.delta", item_id: itemId, output_index: 0, delta: text }),
+ sse("response.output_text.done", { type: "response.output_text.done", item_id: itemId, output_index: 0, text }),
+ sse("response.output_item.done", { type: "response.output_item.done", output_index: 0, item: { id: itemId, type: "message", content: [{ type: "output_text", text }] } }),
+ sse("response.completed", { type: "response.completed", response: { id: responseId, status: "completed", output: [{ id: itemId, type: "message", content: [{ type: "output_text", text }] }] } }),
+ ];
+}
+
+function responsesDeltas(raw: string): string {
+ return [...raw.matchAll(/"delta":"((?:[^"\\]|\\.)*)"/g)].map((m) => JSON.parse(`"${m[1]}"`) as string).join("");
+}
+
+test("#3905 responses: bare-announcement completed turn spends the continuation nudge once", async () => {
+ const out: string[] = [];
+ const logs: string[] = [];
+ let calls = 0;
+ const refetch = () => {
+ calls += 1;
+ return Promise.resolve(streamOf(responsesProseTurn("recovered after the nudge")));
+ };
+ await pipePluginResponsesWithStrip(streamOf(responsesAnnounceTurn()), makeRes(out), makeSession(), (m) => logs.push(m), refetch);
+ const text = out.join("");
+ assert.equal(calls, 1, "exactly one re-issue");
+ assert.ok(responsesDeltas(text).includes(ANNOUNCE_STUB), "the first attempt's stub still reaches the client");
+ assert.ok(responsesDeltas(text).endsWith("recovered after the nudge"), "the retry's prose appends to the same item");
+ assert.equal((text.match(/"type":"response\.created"/g) ?? []).length, 1, "the retry does not open a second response");
+ assert.equal((text.match(/"type":"response\.completed"/g) ?? []).length, 1, "one turn, one terminal");
+ assert.ok(!text.includes("item_2") && !text.includes("resp_2"), `the retry's ids are rewritten onto the client's, got: ${text}`);
+ assert.ok(logs.some((l) => l.includes("#3905")), `the distinct #3905 log line fired, got: ${JSON.stringify(logs)}`);
+});
+
+test("#3905 responses: a legitimate short answer ending on an ellipsis is NOT retried", async () => {
+ const out: string[] = [];
+ let calls = 0;
+ const refetch = () => {
+ calls += 1;
+ return Promise.resolve(streamOf(responsesProseTurn("unwanted")));
+ };
+ await pipePluginResponsesWithStrip(streamOf(responsesProseTurn("I'm not sure...")), makeRes(out), makeSession(), undefined, refetch);
+ assert.equal(calls, 0, "ellipsis without a cue is prose, not a promise");
+});
+
+test("#3905 responses: a bare announcement WITH a function call is NOT retried", async () => {
+ const out: string[] = [];
+ let calls = 0;
+ const refetch = () => {
+ calls += 1;
+ return Promise.resolve(streamOf(responsesProseTurn("unwanted")));
+ };
+ const events = [
+ sse("response.created", { type: "response.created", response: { id: "resp_1", status: "in_progress" } }),
+ sse("response.output_item.added", { type: "response.output_item.added", output_index: 0, item: { id: "item_1", type: "function_call", name: "read" } }),
+ sse("response.output_text.delta", { type: "response.output_text.delta", item_id: "item_1", output_index: 0, delta: ANNOUNCE_STUB }),
+ sse("response.completed", { type: "response.completed", response: { id: "resp_1", status: "completed", output: [{ id: "item_1", type: "function_call" }] } }),
+ ];
+ await pipePluginResponsesWithStrip(streamOf(events), makeRes(out), makeSession(), undefined, refetch);
+ assert.equal(calls, 0, "a function call means the step converges");
+});
+
+// ---------- compress loop (proxy mode) ----------
+
+function makeCtx(id: string, protocol: "responses" | "openai" = "openai") {
+ return {
+ core: createCore(),
+ config: { modelContextLimit: 200000 } as Config,
+ messages: [] as CoreMessage[],
+ session: {
+ id,
+ meta: {},
+ stats: { requests: 0, tokensSaved: 0, inputTokens: 0, cachedTokens: 0, outputTokens: 0, cacheSamples: 0, lastInputTokens: 0, contextTokens: 0 },
+ metadata: {},
+ state: createInitialState(),
+ createdAt: Date.now(),
+ lastSeen: Date.now(),
+ blockContents: new Map(),
+ inFlight: 0,
+ persisted: false,
+ } as unknown as Session,
+ log: () => {},
+ protocol,
+ };
+}
+
+function openaiSse(frames: Array>): string {
+ return frames.map((f) => `data: ${JSON.stringify(f)}\n\n`).join("") + "data: [DONE]\n\n";
+}
+
+const OPENAI_ANNOUNCE = openaiSse([
+ { id: "chatcmpl_a1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "" }, finish_reason: null }] },
+ { id: "chatcmpl_a1", choices: [{ index: 0, delta: { content: ANNOUNCE_STUB }, finish_reason: null }] },
+ { id: "chatcmpl_a1", choices: [{ index: 0, delta: {}, finish_reason: "stop" }] },
+]);
+
+const OPENAI_GOOD = openaiSse([
+ { id: "chatcmpl_g1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "" }, finish_reason: null }] },
+ { id: "chatcmpl_g1", choices: [{ index: 0, delta: { content: "continued after nudge" }, finish_reason: null }] },
+ { id: "chatcmpl_g1", choices: [{ index: 0, delta: {}, finish_reason: "stop" }] },
+]);
+
+async function drainOpenai(first: string, retries: string[], id: string): Promise<{ out: string; fetchCalls: number; bodies: string[] }> {
+ let fetchCalls = 0;
+ const bodies: string[] = [];
+ const orig = globalThis.fetch;
+ globalThis.fetch = (async (_url: unknown, init?: { body?: unknown }) => {
+ fetchCalls++;
+ if (init?.body !== undefined) bodies.push(typeof init.body === "string" ? init.body : String(init.body));
+ const body = retries[fetchCalls - 1] ?? "";
+ return new Response(body, { status: 200 });
+ }) as typeof fetch;
+ const chunks: Buffer[] = [];
+ try {
+ const ctx = makeCtx(id, "openai");
+ for await (const chunk of runCompressLoop(
+ new Response(first, { status: 200 }).body!,
+ ctx,
+ { model: "deepseek-chat", stream: true },
+ { url: "http://mock", headers: {} },
+ createOpenaiAdapter({ model: "deepseek-chat", stream: true }),
+ buildCompressSystemPrompt(),
+ )) {
+ chunks.push(chunk);
+ }
+ } finally {
+ globalThis.fetch = orig;
+ }
+ return { out: Buffer.concat(chunks).toString("utf8"), fetchCalls, bodies };
+}
+
+test("#3905 loop: a bare announcement → one invisible retry with the continuation nudge", async () => {
+ const { out, fetchCalls, bodies } = await drainOpenai(OPENAI_ANNOUNCE, [OPENAI_GOOD], "at-l1");
+ assert.equal(fetchCalls, 1, "exactly one announcement-tail auto-retry");
+ assert.ok(bodies[0]!.includes("ended without a tool call"), "the retry carries the continuation nudge");
+ assert.ok(out.includes(ANNOUNCE_STUB), "the stub itself reached the client (the host already rendered it)");
+ assert.ok(out.includes("continued after nudge"), "the retried turn's content was delivered");
+});
+
+test("#3905 loop: one-shot bound — an announcement RETRY is not retried again", async () => {
+ const { fetchCalls } = await drainOpenai(OPENAI_ANNOUNCE, [OPENAI_ANNOUNCE], "at-l2");
+ assert.equal(fetchCalls, 1, "one retry max; a second announcement falls through to the plain completion");
+});
+
+test("#3905 loop: a cue-bearing answer PAST the 400-char cap is NOT retried", async () => {
+ // 441 chars with a real action cue ("Running") and a colon tail: ONLY the
+ // length cap can deny it, so this pins the cap itself at loop level.
+ const longCueAnswer = ("Running through the failing suites: " + "lorem ipsum dolor sit amet ".repeat(15)).trimEnd() + ":";
+ assert.ok(longCueAnswer.length > 400, `fixture drifted: ${longCueAnswer.length}`);
+ const longTurn = openaiSse([
+ { id: "chatcmpl_n1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "" }, finish_reason: null }] },
+ { id: "chatcmpl_n1", choices: [{ index: 0, delta: { content: longCueAnswer }, finish_reason: null }] },
+ { id: "chatcmpl_n1", choices: [{ index: 0, delta: {}, finish_reason: "stop" }] },
+ ]);
+ const { fetchCalls } = await drainOpenai(longTurn, [OPENAI_GOOD], "at-l3");
+ assert.equal(fetchCalls, 0, "the 400-char cap keeps real prose out of the retry");
+});
+
+test("#3905 loop: a normal completed turn is NOT retried", async () => {
+ const normal = openaiSse([
+ { id: "chatcmpl_z1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "" }, finish_reason: null }] },
+ { id: "chatcmpl_z1", choices: [{ index: 0, delta: { content: "all steps finished, nothing pending" }, finish_reason: null }] },
+ { id: "chatcmpl_z1", choices: [{ index: 0, delta: {}, finish_reason: "stop" }] },
+ ]);
+ const { fetchCalls } = await drainOpenai(normal, [OPENAI_GOOD], "at-l4");
+ assert.equal(fetchCalls, 0);
+});
+
+test("#3905 loop: an announcement WITH a tool call is NOT retried", async () => {
+ const withCall = openaiSse([
+ { id: "chatcmpl_t1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "" }, finish_reason: null }] },
+ { id: "chatcmpl_t1", choices: [{ index: 0, delta: { content: ANNOUNCE_STUB }, finish_reason: null }] },
+ { id: "chatcmpl_t1", choices: [{ index: 0, delta: { tool_calls: [{ index: 0, id: "call_1", type: "function", function: { name: "bash", arguments: "{}" } }] }, finish_reason: null }] },
+ { id: "chatcmpl_t1", choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] },
+ ]);
+ const { fetchCalls } = await drainOpenai(withCall, [OPENAI_GOOD], "at-l5");
+ assert.equal(fetchCalls, 0, "a tool call means the step converges");
+});
+
+test("#3905 loop: a length-cut announcement retries like the #2303 sibling", async () => {
+ const lengthCut = openaiSse([
+ { id: "chatcmpl_l1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "" }, finish_reason: null }] },
+ { id: "chatcmpl_l1", choices: [{ index: 0, delta: { content: ANNOUNCE_STUB }, finish_reason: null }] },
+ { id: "chatcmpl_l1", choices: [{ index: 0, delta: {}, finish_reason: "length" }] },
+ ]);
+ const { fetchCalls } = await drainOpenai(lengthCut, [OPENAI_GOOD], "at-l6");
+ // Verified against the shipped #2303 implementation: a draft tail ending on
+ // finish=length is retried there too (fetchCalls === 1). The loop's gate
+ // excludes only failed/incomplete/error, so `length` is in scope for both
+ // shapes — matching the sibling rather than inventing a stricter rule.
+ assert.equal(fetchCalls, 1, "matches the #2303 sibling's treatment of finish=length");
+});