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|DSML| invoke>\n|DSML| calls>\r\n|DSML| invoke>\n|DSML| calls>\r\n\r\n|DSML| parameter>\n";
const recordedControlTokenReply = "<|begin▁of▁sentence|>\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.|DSML| parameter>\n|DSML| invoke>\n|DSML| calls>";
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|DSML| invoke>`, ["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;
}