Skip to content
Closed
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
35 changes: 35 additions & 0 deletions src/degenerate-turn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
31 changes: 24 additions & 7 deletions src/loop/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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",
Expand All @@ -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;
Expand Down
45 changes: 32 additions & 13 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -2920,16 +2920,27 @@ export async function pipePluginChatWithStrip(
// answer — a client compaction asking for a plain-text <summary> 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
// it just like for the tag-echo case. Released markup never counts (its
// 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;
Expand All @@ -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<Uint8Array> | null = null;
try {
next = await refetch();
Expand Down Expand Up @@ -4586,16 +4599,20 @@ 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
// "\n\n") are not answers; reasoning-only turns already passed the
// 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;
Expand All @@ -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<Uint8Array> | null = null;
try {
next = await refetch();
Expand Down
Loading
Loading