From d939c64a6bc100a9fd2c781091a38eaa202a55da Mon Sep 17 00:00:00 2001 From: paperclipbugbot Date: Fri, 4 Dec 2026 17:38:02 -0800 Subject: [PATCH] fix(opencode): keep the text-first answer when only the completion call is written as text (#23806) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The Paperclip runner drives OpenCode models and asks again when a turn ends without a final answer > - The second request asks for a plain-text answer first, then the `paperclip_finish` call > - DeepSeek v4.1 flash sometimes sends that answer and then writes `paperclip_finish` as DSML text, not as a real tool call > - The runner discards the full reply when it finds tool-call text, so it also discards the answer it asked for, and the turn fails with `opencode_empty_response` > - This pull request keeps that answer when the only text call after it is the completion call > - The benefit is that a turn that already did its work ends with an answer, not a failed run and a full retry ## Linked Issues or Issue Description Refs #21361 Refs #21761 **What happened?** After real tool work, a reviewer agent on DeepSeek v4.1 flash (OpenRouter) ended its turn with a tool call written as text. The runner sent two corrections. For the second correction, the model wrote a correct plain-text answer, a blank line, and then `paperclip_finish` as DSML text. The runner discarded the full reply and failed the turn with `opencode_empty_response` ("after two corrections"). The work was already done. In one run, the model had published a PR review. In a different run, it had posted a GitHub reply. The automatic retry then ran the full session again. This occurred three times on staging in three weeks, and two of the three were on the same day. **Expected behavior** The second correction asks for exactly this shape: an answer, then the completion call. When the completion call is the only text call, the runner should keep the answer. A completion call starts no work, so the answer cannot describe an action that did not occur. **Steps to reproduce** 1. Start an OpenCode turn that does tool work and then sends an empty reply two times. 2. For the text-first correction, send `Here is the actual final answer.` followed by a DSML `paperclip_paperclip_finish` call as text. 3. Before this change, the turn fails with `opencode_empty_response`. The new `tool-work-text-finish-markup` case in `empty-response.test.ts` does these steps. **Paperclip version or commit** `master` at bf49fce70f. ## What Changed - `tool-call-markup.ts`: add `toolCallMarkupNames()`. It finds each call that the text opens: a DSML invoke, a `` invoke, a `` object, or a DeepSeek `tool▁call▁begin` token. It returns the name of each call. When it cannot read the name of one call, it returns `null`. Markup that opens no call (for example, closing tags only) gives an empty list. - `opencode-server-driver.ts`: the runner keeps the prose before the markup as the final answer only when all of these are true: - the reply is for the second (text-first) correction of the same turn - there is prose before the markup - the runner can read the name of each call in the markup, and each name is `paperclip_finish` or `paperclip_block` after the usual OpenCode MCP prefix is removed The kept answer stops at the first model control token or markup. If no prose remains, the runner does not keep the reply. The runner records a new `opencode_textual_completion_call_discarded` diagnostic. It does not use the text call. In all other cases, the reply is discarded as before. - `tool-call-markup.test.ts`: add unit tests for `toolCallMarkupNames()`. The tests include readable forms, closing tags only, and forms with an unreadable call. One form has a DeepSeek call token before a DSML finish call. - `empty-response.test.ts`: add five cases: - `tool-work-text-finish-markup`: the turn completes and the final answer is the prose. - `tool-work-text-work-markup`: the same reply shape with a text `paperclip_call_assigned_tool` call. The turn still fails after two corrections. - `finish-markup-first-reply`: prose and a text finish call in an ordinary reply. The runner still discards the reply, and the prose is not used as the answer. - `tool-work-text-mixed-markup`: prose, an unreadable DeepSeek call-token work call, and then a DSML finish call. The turn still fails after two corrections. - `tool-work-text-finish-markup-control`: prose, `<|end▁of▁sentence|>`, and then a DSML finish call. The final answer is the prose without the token. ## Verification - `npx vitest run src/drivers/opencode/empty-response.test.ts src/drivers/opencode/tool-call-markup.test.ts` (in `packages/paperclip-runner`): 83/83 pass. With the driver change removed, `tool-work-text-finish-markup` fails with `turn.failed`. This is the same failure as on staging. With the first commit's implementation, the review-finding cases (`tool-work-text-mixed-markup`, `tool-work-text-finish-markup-control`, and the four `null` unit cases) fail. - `npx vitest run src/drivers/opencode/`: the result is the same as on unchanged `master` in this sandbox. Nine tests fail in `opencode-server-driver.test.ts` and `output-custody.test.ts`, both with and without this change. All other tests pass. - `tsc -p tsconfig.json --noEmit`: no errors in the changed files. The only errors come from an unbuilt eval-kernel workspace package in this sandbox. ## Risks - Low risk. The change applies only to the last correction, which fails the turn today. It accepts only prose followed by completion calls. A text work call, prose in an ordinary reply, and markup with no readable names keep the current discard behavior. - The text completion call is not run. The turn ends with a final answer and no completion report. The runner already handles this path for models that answer without `paperclip_finish`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used as a coding agent with tool use and shell execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../drivers/opencode/empty-response.test.ts | 39 +++++++++++++++++-- .../opencode/opencode-server-driver.ts | 39 ++++++++++++++++++- .../drivers/opencode/tool-call-markup.test.ts | 24 +++++++++++- .../src/drivers/opencode/tool-call-markup.ts | 26 +++++++++++++ 4 files changed, 122 insertions(+), 6 deletions(-) diff --git a/packages/paperclip-runner/src/drivers/opencode/empty-response.test.ts b/packages/paperclip-runner/src/drivers/opencode/empty-response.test.ts index 10036e90ab5..7a389051339 100644 --- a/packages/paperclip-runner/src/drivers/opencode/empty-response.test.ts +++ b/packages/paperclip-runner/src/drivers/opencode/empty-response.test.ts @@ -5,7 +5,7 @@ import { expect, it, vi } from "vitest"; import { OpenCodeServerDriver } from "./opencode-server-driver.js"; import type { PrpEvent } from "../../protocol/replay-contract.js"; -it.each(["reply", "reply-no-finish", "reply-tool-finish", "two-turn-idle", "slow-native-tool", "idle-stall", "tool-idle-stall", "empty-again", "request-fails", "normal", "foreign-idle", "queued-tool", "reasoning-echo", "reasoning-echo-text-first", "reasoning-echo-reasoning-after", "reasoning-echo-correction-matches", "tool-call-markup", "closing-markup", "control-token-reply", "control-token-trailing", "tool-work-text", "tool-work-empty", "stale-tool-work"] as const)("handles an empty OpenCode response: %s", async mode => { +it.each(["reply", "reply-no-finish", "reply-tool-finish", "two-turn-idle", "slow-native-tool", "idle-stall", "tool-idle-stall", "empty-again", "request-fails", "normal", "foreign-idle", "queued-tool", "reasoning-echo", "reasoning-echo-text-first", "reasoning-echo-reasoning-after", "reasoning-echo-correction-matches", "tool-call-markup", "closing-markup", "control-token-reply", "control-token-trailing", "tool-work-text", "tool-work-empty", "tool-work-text-finish-markup", "tool-work-text-finish-markup-control", "tool-work-text-work-markup", "tool-work-text-mixed-markup", "finish-markup-first-reply", "stale-tool-work"] as const)("handles an empty OpenCode response: %s", async mode => { const root = await mkdtemp(join(tmpdir(), "opencode-empty-response-")); const command = join(root, "fake-opencode.mjs"); await copyFile(resolve("test/fixtures/fake-opencode-server.mjs"), command); @@ -22,6 +22,15 @@ it.each(["reply", "reply-no-finish", "reply-tool-finish", "two-turn-idle", "slow // (cases.case-history). const recordedClosingMarkup = "\r\n\n\r\n\n\r\n\r\n\n"; const recordedControlTokenReply = "<|begin▁of▁sentence|>\n\nSearch output truncated. Let me search more specifically for \"case document\" and \"case events\".\n"; + // Recorded shape from staging runs 04d348f3 and fbcecd8d (DeepSeek v4.1 + // flash through OpenRouter): after real tool work, the text-first + // correction returned the requested answer, a blank line, then the + // completion call written as DSML text. + const recordedWorkMarkup = recordedMarkup.replace("paperclip_paperclip_finish", "paperclip_call_assigned_tool"); + // A work call in DeepSeek's call-token form names no tool the runner can + // read, so a readable completion call after it cannot vouch for the reply. + const unreadableWorkThenFinish = `\n\n<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>bash\n${recordedMarkup.trimStart()}`; + const textFirstMarkup = mode === "tool-work-text-work-markup" ? recordedWorkMarkup : mode === "tool-work-text-mixed-markup" ? unreadableWorkThenFinish : recordedMarkup; const leakedText = mode === "closing-markup" ? recordedClosingMarkup : mode === "control-token-reply" ? recordedControlTokenReply : recordedMarkup; let toolTimer: ReturnType | undefined; let stream: ReadableStreamDefaultController | undefined; @@ -102,6 +111,14 @@ it.each(["reply", "reply-no-finish", "reply-tool-finish", "two-turn-idle", "slow emit({ type: "session.status", properties: { sessionID, status: { type: "idle" } } }); return; } + if (mode === "finish-markup-first-reply" && number === 1 || mode.startsWith("tool-work-text-") && number === 3) { + const prose = number === 1 ? "Premature prose before a textual call." : `Here is the actual final answer.${mode === "tool-work-text-finish-markup-control" ? "<|end▁of▁sentence|>" : ""}`; + const text = `${prose}${textFirstMarkup}`; + emit({ type: "message.part.updated", properties: { sessionID, part: { id: `part-${number}-text`, messageID, sessionID, type: "text", text, time: { start: 1, end: 2 } } } }); + emit({ type: "session.idle", properties: { sessionID } }); + emit({ type: "session.status", properties: { sessionID, status: { type: "idle" } } }); + return; + } if (["tool-call-markup", "closing-markup", "control-token-reply"].includes(mode) && number === 1) { const leaked = { id: "part-1-text", messageID, sessionID, type: "text", text: "", time: { start: 1 } }; emit({ type: "message.part.updated", properties: { sessionID, part: leaked } }); @@ -112,7 +129,7 @@ it.each(["reply", "reply-no-finish", "reply-tool-finish", "two-turn-idle", "slow emit({ type: "session.status", properties: { sessionID, status: { type: "idle" } } }); return; } - const answer = mode === "normal" || mode === "control-token-trailing" || mode === "stale-tool-work" && number === 1 || mode === "foreign-idle" || mode === "queued-tool" || number === 3 && mode === "tool-work-text" || number === 2 && ["reply", "reply-no-finish", "reply-tool-finish", "two-turn-idle", "reasoning-echo", "reasoning-echo-text-first", "reasoning-echo-reasoning-after", "reasoning-echo-correction-matches", "tool-call-markup", "closing-markup", "control-token-reply"].includes(mode); + const answer = mode === "normal" || mode === "control-token-trailing" || mode === "stale-tool-work" && number === 1 || mode === "foreign-idle" || mode === "queued-tool" || number === 3 && mode === "tool-work-text" || number === 2 && ["reply", "reply-no-finish", "reply-tool-finish", "two-turn-idle", "reasoning-echo", "reasoning-echo-text-first", "reasoning-echo-reasoning-after", "reasoning-echo-correction-matches", "tool-call-markup", "closing-markup", "control-token-reply", "finish-markup-first-reply"].includes(mode); emit({ type: "message.part.updated", properties: { sessionID, part: { id: `part-${number}`, messageID, type: answer ? "text" : "reasoning", text: answer ? (mode === "reasoning-echo-correction-matches" ? recordedReasoning : mode === "control-token-trailing" ? "Here is the actual final answer.<|end▁of▁sentence|>" : "Here is the actual final answer.") : "Synthetic reasoning must not become the answer.", time: { start: 1, end: 2 } } } }); emit({ type: "session.idle", properties: { sessionID } }); @@ -152,7 +169,7 @@ it.each(["reply", "reply-no-finish", "reply-tool-finish", "two-turn-idle", "slow } await vi.advanceTimersByTimeAsync(mode.endsWith("idle-stall") ? 20_001 : mode === "slow-native-tool" ? 1_999 : 5_001); const events = await completed; - const succeeds = ["stale-tool-work", "tool-work-text", "reply", "reply-no-finish", "reply-tool-finish", "two-turn-idle", "slow-native-tool", "normal", "foreign-idle", "queued-tool", "reasoning-echo", "reasoning-echo-text-first", "reasoning-echo-reasoning-after", "reasoning-echo-correction-matches", "tool-call-markup", "closing-markup", "control-token-reply", "control-token-trailing"].includes(mode); + const succeeds = ["stale-tool-work", "tool-work-text", "tool-work-text-finish-markup", "tool-work-text-finish-markup-control", "finish-markup-first-reply", "reply", "reply-no-finish", "reply-tool-finish", "two-turn-idle", "slow-native-tool", "normal", "foreign-idle", "queued-tool", "reasoning-echo", "reasoning-echo-text-first", "reasoning-echo-reasoning-after", "reasoning-echo-correction-matches", "tool-call-markup", "closing-markup", "control-token-reply", "control-token-trailing"].includes(mode); expect(events.at(-1)?.eventType).toBe(succeeds ? "turn.completed" : "turn.failed"); expect(events.filter(event => event.eventType === "turn.started")).toHaveLength(1); expect(events.every(event => !event.turnId || event.turnId === turnId)).toBe(true); @@ -168,7 +185,21 @@ it.each(["reply", "reply-no-finish", "reply-tool-finish", "two-turn-idle", "slow expect(JSON.stringify(prompts[2]!.parts)).toContain("Start this response with a short plain-text final answer"); expect(JSON.stringify(prompts[2]!.parts)).toContain("After that text, submit paperclip_finish"); } - if (mode === "tool-work-empty") expect(events.at(-1)?.payload).toMatchObject({ error: { code: "opencode_empty_response", + if (mode.startsWith("tool-work-text-") || mode === "finish-markup-first-reply") { + // The textual call never reaches the person. Only an answer the + // text-first correction requested, followed by nothing but the + // completion call, is kept; prose beside a textual work call, or in an + // ordinary reply, stays discarded. + const assistantText = events.filter(event => event.payload.kind === "agentMessage").map(event => String(event.payload.text ?? "")); + expect(assistantText.join("")).not.toContain("DSML"); + expect(assistantText.join("")).not.toContain("<|"); + expect(final.map(event => event.payload.text).join("")).not.toContain("Premature prose"); + const keepsAnswer = ["tool-work-text-finish-markup", "tool-work-text-finish-markup-control"].includes(mode); + const kept = events.some(event => event.eventType === "harness.diagnostic" && event.payload.code === "opencode_textual_completion_call_discarded"); + expect(kept).toBe(keepsAnswer); + expect(events.some(event => event.eventType === "harness.diagnostic" && event.payload.code === "opencode_tool_call_markup_discarded")).toBe(!keepsAnswer); + } + if (["tool-work-empty", "tool-work-text-work-markup", "tool-work-text-mixed-markup"].includes(mode)) expect(events.at(-1)?.payload).toMatchObject({ error: { code: "opencode_empty_response", message: "OpenCode ended without a final answer or accepted completion report after two corrections." } }); if (prompts.length >= 2) { expect(prompts[0]!.variant).toBe(mode === "empty-again" || mode === "reply" || mode.startsWith("reasoning-echo") ? "paperclip-default" : "paperclip-no-reasoning"); diff --git a/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts b/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts index 33e4c17ea74..838c2ac61f8 100644 --- a/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts +++ b/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts @@ -109,7 +109,7 @@ import { type OpenCodeMcpBridge, type OpenCodeMcpBridgeOptions, } from "./mcp-bridge.js"; -import { controlTokenStart, toolCallMarkupStart, visibleBeforeModelScaffolding } from "./tool-call-markup.js"; +import { controlTokenStart, toolCallMarkupNames, toolCallMarkupStart, visibleBeforeModelScaffolding } from "./tool-call-markup.js"; import { materializeNativeRuntimeSkills, releaseMaterializedNativeRuntimeSkills, @@ -915,6 +915,23 @@ class OpenCodeHarnessSession implements HarnessSession { return false; } + /** + * The answer from a text-first correction reply whose only tool-call markup + * is the completion call written as text, or "". Any other textual call, + * or one whose name cannot be read, keeps the whole reply discarded: prose + * beside it may describe work that never ran. The answer ends at the first + * model control token or markup, whichever comes first. + */ + #textFirstAnswerBeforeTextualCompletion(turnId: string, content: string, markupStart: number, controlStart: number): string { + const recovery = this.#emptyResponseRecovery; + if (recovery?.turnId !== turnId || recovery.attempt !== 2) return ""; + const answer = content.slice(0, controlStart >= 0 ? Math.min(controlStart, markupStart) : markupStart).trim(); + if (!answer) return ""; + const names = toolCallMarkupNames(content.slice(markupStart)); + const terminal = (name: string) => [PRP_COMPLETION_TOOL_NAME, PRP_BLOCK_TOOL_NAME].includes(canonicalOpenCodeMcpToolName(name) as typeof PRP_COMPLETION_TOOL_NAME); + return names !== null && names.length > 0 && names.every(terminal) ? answer : ""; + } + #recoverEmptyResponse(turnId: string): boolean { if (this.#result !== null || this.#pendingRuntimeRequests.size > 0) return false; if (this.#pendingToolCalls > 0 || this.#runningNativeToolParts.size > 0) return true; @@ -2379,6 +2396,26 @@ class OpenCodeHarnessSession implements HarnessSession { ); return; } + const textFirstAnswer = markupStart >= 0 ? this.#textFirstAnswerBeforeTextualCompletion(turnId, content, markupStart, controlStart) : ""; + if (textFirstAnswer) { + // The text-first correction asked for exactly this shape: an answer, + // then the completion call. Only the completion call was written as + // text, and it runs no work, so the answer cannot describe an action + // that never ran. Keep it as the reply; the call itself stays unused. + this.#emit( + "harness.diagnostic", + { code: "opencode_textual_completion_call_discarded", message: "OpenCode wrote its completion call as text after the requested answer; the answer was kept and the call was not used." }, + { turnId }, + ); + this.#completedTextParts.push({ + partId, + messageId, + text: textFirstAnswer, + item: bounded({ ...part, type: "agentMessage", phase: "final_answer", text: textFirstAnswer }), + observedSourceSeq: this.#sourceSequence, + }); + return; + } if (markupStart >= 0) { this.#lastToolCallMarkupSourceSeq = this.#sourceSequence; this.#emit( diff --git a/packages/paperclip-runner/src/drivers/opencode/tool-call-markup.test.ts b/packages/paperclip-runner/src/drivers/opencode/tool-call-markup.test.ts index 470c576b6ef..7b361e09d2b 100644 --- a/packages/paperclip-runner/src/drivers/opencode/tool-call-markup.test.ts +++ b/packages/paperclip-runner/src/drivers/opencode/tool-call-markup.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { containsToolCallMarkup, controlTokenStart, visibleBeforeModelScaffolding, visibleBeforeToolCallMarkup } from "./tool-call-markup.js"; +import { containsToolCallMarkup, controlTokenStart, toolCallMarkupNames, visibleBeforeModelScaffolding, visibleBeforeToolCallMarkup } from "./tool-call-markup.js"; const dsml = "<|DSML| calls>\n<|DSML| invoke name=\"paperclip_paperclip_finish\">\n<|DSML| parameter name=\"summary\" string=\"true\">Done.\n\n"; const markupForms = { @@ -111,3 +111,25 @@ describe("model control tokens", () => { expect(shown).toBe("Riley changed it."); }); }); + +describe("textual call names", () => { + it.each([ + ["recorded DSML block", dsml, ["paperclip_paperclip_finish"]], + ["function_calls wrapper", markupForms["function_calls wrapper"], ["paperclip_finish"]], + ["tool_call wrapper", markupForms["tool_call wrapper"], ["paperclip_finish"]], + ["two DSML calls", `${dsml}\n<|DSML| invoke name="paperclip_call_assigned_tool">\n`, ["paperclip_paperclip_finish", "paperclip_call_assigned_tool"]], + ["closing tags only", markupForms["closing DSML tags only"], []], + ] as const)("reads every call in %s", (_label, markup, names) => { + expect(toolCallMarkupNames(markup)).toEqual(names); + }); + + it.each([ + ["DeepSeek call tokens", markupForms["DeepSeek call tokens"]], + ["ASCII call tokens", markupForms["ASCII call tokens"]], + // An unreadable work call must not hide behind a readable completion call. + ["call tokens before a DSML finish", `<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>bash\n${dsml}`], + ["an invoke without a name", "\n\n\n"], + ])("returns null when a call in %s cannot be read", (_label, markup) => { + expect(toolCallMarkupNames(markup)).toBeNull(); + }); +}); diff --git a/packages/paperclip-runner/src/drivers/opencode/tool-call-markup.ts b/packages/paperclip-runner/src/drivers/opencode/tool-call-markup.ts index e7e3d457d26..c9120b39748 100644 --- a/packages/paperclip-runner/src/drivers/opencode/tool-call-markup.ts +++ b/packages/paperclip-runner/src/drivers/opencode/tool-call-markup.ts @@ -169,6 +169,32 @@ function scaffoldingStart(content: string, forms: readonly string[], lineForms: return -1; } +// Where each textual call opens: a DSML or `` invoke, a +// `` object, or a DeepSeek call-begin token. Closing tags and +// wrappers open no call. +const CALL_OPENING = /<[||]DSML[||]\s*invoke\b||<[||]tool[▁_]call[▁_]begin[||]>/g; +const OPENING_NAME = [ + /^<[||]DSML[||]\s*invoke\s+name\s*=\s*"([^"]+)"/, + /^\s*\{\s*"name"\s*:\s*"([^"]+)"/, +]; + +/** + * The tool name of every call that textual markup opens, in order, or null + * when any call's name cannot be read (DeepSeek call-begin tokens, say). + * Markup that opens no call, such as closing tags alone, yields []. + */ +export function toolCallMarkupNames(markup: string): string[] | null { + const names: string[] = []; + for (const opening of markup.matchAll(CALL_OPENING)) { + const rest = markup.slice(opening.index); + const name = OPENING_NAME.map(pattern => pattern.exec(rest)?.[1]?.trim()).find(Boolean); + if (!name) return null; + names.push(name); + } + return names; +} + export function containsToolCallMarkup(content: string): boolean { return toolCallMarkupStart(content) >= 0; }