From 8718375b32ccb212c83b1a66e778fe936b814154 Mon Sep 17 00:00:00 2001 From: liuedcson <332840681+liuedcson@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:39:01 +0800 Subject: [PATCH 1/7] fix(providers): refuse tool calls whose arguments never arrived whole Streamed tool-call deltas are parsed speculatively so a UI can render a call before it is complete. That parse was also what the finished call kept, so a stream that ended inside the arguments left a call the model never wrote: a write cut off at the output token limit reached the filesystem as a truncated file instead of failing. A finished call now carries only what the provider completed. `parseFinalToolArguments` still repairs invalid escapes, which restores the encoding the model meant without inventing structure, but it never fills in missing structure. When the arguments cannot be read the block keeps empty `arguments` and an `argumentsError`, and `validateToolArguments` refuses it, so the call comes back to the model as a tool error it can re-issue. Two provider gaps that let an unfinished call look finished are closed with it: an Anthropic stream that stops after `message_delta` without closing a tool block, and a block whose scratch buffer survived finalization, are both reported instead of being executed on the last streamed preview. --- CHANGELOG.md | 1 + packages/agent-core/README.md | 3 +- packages/agent-core/src/agent-loop.ts | 11 +- .../agent-core/test/tool-lifecycle.test.ts | 23 ++ packages/coding-agent/src/step/stdio-host.ts | 3 + packages/providers/README.md | 11 +- .../providers/src/api/anthropic-messages.ts | 27 ++- .../providers/src/api/openai-completions.ts | 10 +- .../src/api/openai-responses-shared.ts | 9 +- packages/providers/src/types.ts | 9 + packages/providers/src/utils/json-parse.ts | 46 ++++ packages/providers/src/utils/validation.ts | 10 + .../test/anthropic-sse-parsing.test.ts | 172 ++++++++++++++ .../test/final-tool-arguments.test.ts | 224 ++++++++++++++++++ ...nai-responses-partial-json-cleanup.test.ts | 35 +++ 15 files changed, 580 insertions(+), 14 deletions(-) create mode 100644 packages/providers/test/final-tool-arguments.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index da69dc6d6..347902cc2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,7 @@ ### Fixed +- A tool call whose arguments never arrived whole is no longer executed. Streamed deltas are parsed speculatively so a UI can preview them, but a finished call now carries only what the provider completed: when the stream ends mid-argument, or a tool block never closes, that block keeps empty `arguments` and an `argumentsError`, and `validateToolCall` / `validateToolArguments` refuse it. Previously the best-effort parser filled in whatever had arrived, so a write cut off at the output token limit reached the filesystem as a truncated file. - Fixed automatic compaction silently doing nothing when the newest message alone exceeded `keepRecentTokens` and was a tool result (for example one large file read near the threshold): no cut point qualified, so the whole history was kept and nothing was summarized. The cut now falls back to the newest valid cut point, matching upstream pi, so older history is summarized and the oversized tool batch is kept. - An OpenAI Responses stream that finishes with a tool call whose `output_item.done` never arrived now ends with an error instead of handing that call to the agent loop. Non-compliant servers that reuse or omit `output_index` (observed with OpenAI-compatible gateways) could otherwise produce duplicate or mixed-up tool calls in one assistant message, which ran the same tool twice and then failed every later turn on replay with `Duplicate value for 'tool_call_id'`. - Recover a normal assistant response that contains neither visible text nor an executable tool call: keep the original message in history unchanged, append one hidden user-role recovery prompt, and continue. Recovery is bounded by a streak of consecutive empty turns. Only a turn with visible text or an executed tool call resets it, and so does any user input, so a long autonomous run is not ended by one transient empty response and a provider error in between does not refill the budget. Automatic compaction runs first when the response also exceeded the context window. diff --git a/packages/agent-core/README.md b/packages/agent-core/README.md index 51b132939..0cf0a08d2 100644 --- a/packages/agent-core/README.md +++ b/packages/agent-core/README.md @@ -134,8 +134,7 @@ Tool timing and outcomes: - `tool_execution_start` and `tool_execution_end` carry `at`, the epoch milliseconds when the loop emitted them. `tool_execution_start` fires before approval and argument validation, so it marks when a call was queued, not when it ran. - `onToolExecutionStarted({ assistantMessage, toolCall, at })` (on `AgentOptions`, `AgentLoopConfig`, or the `Agent` instance) is called immediately before a tool's `execute`. It is not called for calls that never run. In parallel mode it fires per call when execution actually begins, after the whole batch was prepared. It is synchronous and best-effort; a throw is ignored. -- `tool_execution_end.executed` is `false` when the call never ran, and `notExecuted` says why: `{ kind: "blocked", by }` when `beforeToolCall` returned `block: true` (`by` is the hook's optional `blockedBy` code) or threw (`by: "hook_error"`); `{ kind: "not_run", reason }` with `tool_not_found`, `invalid_arguments`, `output_truncated`, `skipped_after_stop`, or `aborted_before_start`. - +- `tool_execution_end.executed` is `false` when the call never ran, and `notExecuted` says why: `{ kind: "blocked", by }` when `beforeToolCall` returned `block: true` (`by` is the hook's optional `blockedBy` code) or threw (`by: "hook_error"`); `{ kind: "not_run", reason }` with `tool_not_found`, `invalid_arguments`, `output_truncated`, `skipped_after_stop`, or `aborted_before_start`. `invalid_arguments` covers both a schema mismatch and a call whose arguments the provider never finished sending (`ToolCall.argumentsError`); `output_truncated` is a different fact — the whole assistant message hit the output token limit, so its calls are failed as a batch even when each one parses. `transformToolResult` is an optional final content-only transform on `AgentOptions` and `AgentLoopConfig`. It runs before terminal tool events and result messages for all outcomes, including validation failures, denied calls and rejected truncated diff --git a/packages/agent-core/src/agent-loop.ts b/packages/agent-core/src/agent-loop.ts index c6cbd201c..19fa40a63 100644 --- a/packages/agent-core/src/agent-loop.ts +++ b/packages/agent-core/src/agent-loop.ts @@ -490,10 +490,13 @@ function interruptedResponse( /** * Fail all tool calls from an assistant message that was truncated by the - * output token limit. Streamed tool-call arguments are finalized with a - * best-effort JSON salvage parser, so a truncated message can yield tool calls - * whose arguments parse and validate but are silently incomplete. None of them - * are safe to execute; report each as an error so the model can re-issue them. + * output token limit. A `length` stop says the model was cut off somewhere in + * this message, so a call can be complete while the reasoning that would have + * corrected it never arrived. A call whose arguments could not be parsed is + * refused separately, per call, by `validateToolArguments`. + * + * None of them are safe to execute; report each as an error so the model can + * re-issue them. */ async function failToolCallsFromTruncatedMessage( toolCalls: AgentToolCall[], diff --git a/packages/agent-core/test/tool-lifecycle.test.ts b/packages/agent-core/test/tool-lifecycle.test.ts index b1d2bc069..176f49e80 100644 --- a/packages/agent-core/test/tool-lifecycle.test.ts +++ b/packages/agent-core/test/tool-lifecycle.test.ts @@ -211,6 +211,29 @@ describe("tool execution lifecycle", () => { expect(truncated.started).toHaveLength(0); }); + it("refuses a call whose finished arguments never arrived whole", async () => { + // A provider stream that ends inside the arguments of a large write leaves a + // call whose `arguments` cannot be trusted. It must not reach the tool, even + // though the type of every field it looks like it has is valid. + const unfinished = await runBatch( + [ + { + type: "toolCall", + id: "u", + name: "write", + arguments: {}, + argumentsError: "could not be read as JSON (114082 characters)", + }, + ], + [tool("write")], + ); + + const end = ends(unfinished.events)[0]; + expect(end?.notExecuted).toEqual({ kind: "not_run", reason: "invalid_arguments" }); + expect(unfinished.started).toHaveLength(0); + expect(JSON.stringify(end?.result.content)).toContain("did not arrive whole"); + }); + it("marks calls after a sequential turn barrier as skipped", async () => { const barrier: AgentTool = { ...tool("barrier"), diff --git a/packages/coding-agent/src/step/stdio-host.ts b/packages/coding-agent/src/step/stdio-host.ts index 953498055..693052e44 100644 --- a/packages/coding-agent/src/step/stdio-host.ts +++ b/packages/coding-agent/src/step/stdio-host.ts @@ -1553,6 +1553,9 @@ function projectContent(content: unknown): unknown[] { if (!Array.isArray(content)) return [{ type: "text", text: String(content ?? "") }]; return content.map((block) => { const item = asRecord(block); + // The wire shape carries the model's call, not a verdict on it: a call whose + // arguments never arrived is already reported to the model as a tool error + // and is never handed to this host to execute, so `input` alone is enough. if (item.type === "toolCall") return { type: "tool_use", id: item.id, name: item.name, input: item.arguments ?? {} }; if (item.type === "thinking") return { type: "thinking", thinking: item.thinking ?? item.text ?? "" }; diff --git a/packages/providers/README.md b/packages/providers/README.md index ef5f4784e..6127d84d4 100644 --- a/packages/providers/README.md +++ b/packages/providers/README.md @@ -575,7 +575,8 @@ for await (const event of s) { } if (event.type === 'toolcall_end') { - // Here toolCall.arguments is complete (but not yet validated) + // Here toolCall.arguments is complete — or {} with `argumentsError` set + // when the provider never finished sending it. Validate before executing. const toolCall = event.toolCall; console.log(`Tool completed: ${toolCall.name}`, toolCall.arguments); } @@ -591,6 +592,12 @@ for await (const event of s) { - At minimum, `arguments` will be an empty object `{}`, never `undefined` - The Google provider does not support function call streaming. Instead, you will receive a single `toolcall_delta` event with the full arguments. +**Partial parsing is for previews, not for execution.** `toolcall_end` reports the +arguments the provider finished sending. When the stream ended mid-argument, or a +tool block never closed, `arguments` is `{}` and `argumentsError` says why. Execute +a call only after `validateToolCall` / `validateToolArguments` accepts it: both +refuse a call that carries `argumentsError`. + ### Validating Tool Arguments When implementing your own tool execution loop, use `validateToolCall` to validate arguments before passing them to your tools: @@ -640,7 +647,7 @@ All streaming events emitted during assistant message generation: | `thinking_end` | Thinking block complete | `content`: Full thinking, `contentIndex`: Position | | `toolcall_start` | Tool call begins | `contentIndex`: Position in content array | | `toolcall_delta` | Tool arguments streaming | `delta`: JSON chunk, `partial.content[contentIndex].arguments`: Partial parsed args | -| `toolcall_end` | Tool call complete | `toolCall`: Complete validated tool call with `id`, `name`, `arguments` | +| `toolcall_end` | Tool call complete | `toolCall`: Tool call with `id`, `name`, `arguments` (empty with `argumentsError` when the provider did not finish sending them) | | `done` | Stream complete | `reason`: Stop reason ("stop", "length", "toolUse"), `message`: Final assistant message | | `error` | Error occurred | `reason`: Error type ("error" or "aborted"), `error`: AssistantMessage with partial content | diff --git a/packages/providers/src/api/anthropic-messages.ts b/packages/providers/src/api/anthropic-messages.ts index 63b79c9ea..3294de2be 100644 --- a/packages/providers/src/api/anthropic-messages.ts +++ b/packages/providers/src/api/anthropic-messages.ts @@ -32,7 +32,7 @@ import { splitDeferredTools } from "../utils/deferred-tools.ts"; import { classifyProviderError, ProviderStreamError } from "../utils/error-kind.ts"; import { AssistantMessageEventStream } from "../utils/event-stream.ts"; import { headersToRecord } from "../utils/headers.ts"; -import { parseJsonWithRepair, parseStreamingJson } from "../utils/json-parse.ts"; +import { parseFinalToolArguments, parseJsonWithRepair, parseStreamingJson } from "../utils/json-parse.ts"; import { getPiUserAgent } from "../utils/pi-user-agent.ts"; import { providerRetryAfterMs, retryProviderRequest } from "../utils/provider-retry.ts"; import { sanitizeSurrogates } from "../utils/sanitize-unicode.ts"; @@ -667,7 +667,14 @@ export const stream: StreamFunction<"anthropic-messages", AnthropicOptions> = ( partial: output, }); } else if (block.type === "toolCall") { - block.arguments = parseStreamingJson(block.partialJson); + // Some gateways send the whole `input` on content_block_start and + // no deltas. `partialJson` is then empty, and the block already + // carries the complete value the provider sent. + if (block.partialJson !== "") { + const parsed = parseFinalToolArguments(block.partialJson); + block.arguments = parsed.arguments; + if (parsed.error !== undefined) block.argumentsError = parsed.error; + } // Finalize in-place and strip the scratch buffer so replay only // carries parsed arguments. delete (block as { partialJson?: string }).partialJson; @@ -730,6 +737,22 @@ export const stream: StreamFunction<"anthropic-messages", AnthropicOptions> = ( throw new Error(output.errorMessage || "An unknown error occurred"); } + // Finalizing a tool call drops its scratch buffer, so a surviving buffer + // means no `content_block_stop` arrived for it. Some gateways stop after + // `message_delta`, and then `arguments` still holds the last streamed + // preview: the call must not run on a value the model never finished. + for (const block of output.content) { + if (block.type !== "toolCall") continue; + const scratch = (block as { partialJson?: string }).partialJson; + if (scratch === undefined) continue; + delete (block as { partialJson?: string }).partialJson; + // No deltas at all means the block never received arguments in the + // stream, so whatever `content_block_start` supplied is what it has. + if (scratch === "") continue; + block.arguments = {}; + block.argumentsError = `the stream ended before the arguments were complete (${scratch.length} characters)`; + } + stream.push({ type: "done", reason: output.stopReason, message: output }); stream.end(); } catch (error) { diff --git a/packages/providers/src/api/openai-completions.ts b/packages/providers/src/api/openai-completions.ts index 1be207270..98254d98d 100644 --- a/packages/providers/src/api/openai-completions.ts +++ b/packages/providers/src/api/openai-completions.ts @@ -40,7 +40,7 @@ import { classifyProviderError } from "../utils/error-kind.ts"; import { AssistantMessageEventStream } from "../utils/event-stream.ts"; import { shortHash } from "../utils/hash.ts"; import { headersToRecord } from "../utils/headers.ts"; -import { parseStreamingJson } from "../utils/json-parse.ts"; +import { parseFinalToolArguments, parseStreamingJson } from "../utils/json-parse.ts"; import { getPiUserAgent } from "../utils/pi-user-agent.ts"; import { providerRetryAfterMs, retryProviderRequest } from "../utils/provider-retry.ts"; import { sanitizeSurrogates } from "../utils/sanitize-unicode.ts"; @@ -432,6 +432,10 @@ export const stream: StreamFunction<"openai-completions", OpenAICompletionsOptio }); } else if (block.type === "toolCall") { if (block.customInput) { + // Grammar-constrained input is free text with no JSON structure to + // close, so a cut-off stream cannot be told from a short one here: + // a shell command cut at `ls -l` is still a valid command. The tool + // that consumes it owns any completeness check. const delta = appendCustomToolCallInput(block, getCustomToolCallInput(block), true); if (delta !== undefined) { stream.push({ @@ -442,7 +446,9 @@ export const stream: StreamFunction<"openai-completions", OpenAICompletionsOptio }); } } else { - block.arguments = parseStreamingJson(block.partialArgs); + const parsed = parseFinalToolArguments(block.partialArgs); + block.arguments = parsed.arguments; + if (parsed.error !== undefined) block.argumentsError = parsed.error; } // Finalize in-place and strip the scratch buffers so replay only // carries parsed arguments. diff --git a/packages/providers/src/api/openai-responses-shared.ts b/packages/providers/src/api/openai-responses-shared.ts index 3ea14cbe8..c7349b828 100644 --- a/packages/providers/src/api/openai-responses-shared.ts +++ b/packages/providers/src/api/openai-responses-shared.ts @@ -31,7 +31,7 @@ import type { import { ProviderStreamError } from "../utils/error-kind.ts"; import type { AssistantMessageEventStream } from "../utils/event-stream.ts"; import { shortHash } from "../utils/hash.ts"; -import { parseStreamingJson } from "../utils/json-parse.ts"; +import { parseFinalToolArguments, parseStreamingJson } from "../utils/json-parse.ts"; import { sanitizeSurrogates } from "../utils/sanitize-unicode.ts"; import { appendGrammarToolInputJsonDelta, @@ -711,7 +711,9 @@ export async function processResponsesStream( slot?.type === "toolCall" && slot.block.partialJson !== undefined ) { - slot.block.arguments = parseStreamingJson(item.arguments || slot.block.partialJson || "{}"); + const parsed = parseFinalToolArguments(item.arguments || slot.block.partialJson || "{}"); + slot.block.arguments = parsed.arguments; + if (parsed.error !== undefined) slot.block.argumentsError = parsed.error; if (item.namespace !== undefined) slot.block.namespace = item.namespace; // Finalize in-place and strip the scratch buffer so replay only // carries parsed arguments. @@ -724,6 +726,9 @@ export async function processResponsesStream( }); outputSlots.delete(event.output_index); } else if (item.type === "custom_tool_call" && slot?.type === "toolCall" && slot.block.customInput) { + // Free-form input has no JSON structure to close, so a cut-off stream is + // indistinguishable from a short one here. The tool that consumes it owns + // any completeness check. pushToolCallDelta( slot, appendCustomToolCallInput(slot.block, item.input ?? getCustomToolCallInput(slot.block), true), diff --git a/packages/providers/src/types.ts b/packages/providers/src/types.ts index dea195668..1feb43434 100644 --- a/packages/providers/src/types.ts +++ b/packages/providers/src/types.ts @@ -316,6 +316,15 @@ export interface ToolCall { thoughtSignature?: string; // Google-specific: opaque signature for reusing thought context /** OpenAI Responses namespace for calls to dynamically loaded or namespaced tools. */ namespace?: string; + /** + * Why the provider's finished arguments could not be read as JSON. + * + * Streamed deltas are parsed speculatively so a UI can preview them, but a + * finished call must carry what the model actually sent. When the stream ends + * mid-argument the call is kept with empty `arguments` and this reason; + * `validateToolArguments` refuses such a call instead of running it. + */ + argumentsError?: string; } export interface Usage { diff --git a/packages/providers/src/utils/json-parse.ts b/packages/providers/src/utils/json-parse.ts index f39f9f09d..98458e1bc 100644 --- a/packages/providers/src/utils/json-parse.ts +++ b/packages/providers/src/utils/json-parse.ts @@ -122,3 +122,49 @@ export function parseStreamingJson>(partialJson: str } } } + +/** The arguments of a finished tool call, or why they could not be read. */ +export interface FinalToolArguments { + /** Never a guess: empty when the arguments did not arrive whole. */ + arguments: Record; + /** Set when the finished arguments could not be read as a JSON object. */ + error?: string; +} + +/** + * Read the arguments of a finished tool call. + * + * `parseStreamingJson` exists for previews: it fills in whatever the model has + * written so far, so a UI can render a call before it is complete. That is the + * wrong input for execution. A finished call either delivered all of its + * arguments or the stream ended inside them, and a salvaged object turns the + * second case into a call the model never asked for — a truncated write of + * unknown length looks exactly like a deliberate one. + * + * `repairJson` still runs: escaping a raw control character or an invalid escape + * restores the encoding the model meant without inventing structure, so a call + * that only has that flaw still runs. Anything that needs structure filled in is + * reported instead. + */ +export function parseFinalToolArguments(raw: string | undefined): FinalToolArguments { + // A tool with no parameters legitimately sends nothing, and a stream that died + // before the first byte of a large argument looks the same here. Both settle to + // `{}`: the first is what the tool asked for, and the second cannot run because + // the required fields a real call would have are missing. + if (raw === undefined || raw.trim() === "") return { arguments: {} }; + + let parsed: unknown; + try { + parsed = parseJsonWithRepair(raw); + } catch (error) { + const detail = error instanceof SyntaxError ? `: ${error.message}` : ""; + return { arguments: {}, error: `could not be read as JSON (${raw.length} characters)${detail}` }; + } + + if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) { + const received = parsed === null ? "null" : Array.isArray(parsed) ? "an array" : typeof parsed; + return { arguments: {}, error: `expected a JSON object, received ${received}` }; + } + + return { arguments: parsed as Record }; +} diff --git a/packages/providers/src/utils/validation.ts b/packages/providers/src/utils/validation.ts index 8809f317d..22340f30e 100644 --- a/packages/providers/src/utils/validation.ts +++ b/packages/providers/src/utils/validation.ts @@ -323,6 +323,16 @@ export function validateToolCall(tools: Tool[], toolCall: ToolCall): any { * @throws Error with formatted message if validation fails */ export function validateToolArguments(tool: Tool, toolCall: ToolCall): any { + // A call whose arguments did not arrive whole must never run: its `arguments` + // is empty by construction, so schema validation below would happily accept + // the wrong shape and execute a call the model never finished. + if (toolCall.argumentsError !== undefined) { + throw new Error( + `Arguments for tool "${toolCall.name}" did not arrive whole (${toolCall.argumentsError}). ` + + "The call was not executed. Re-issue it with complete arguments; if the content is large, write it in smaller pieces.", + ); + } + const args = structuredClone(toolCall.arguments); normalizeOptionalNulls(args, tool.parameters as JsonSchemaObject); Value.Convert(tool.parameters, args); diff --git a/packages/providers/test/anthropic-sse-parsing.test.ts b/packages/providers/test/anthropic-sse-parsing.test.ts index 08ae28aae..e7cd8ded7 100644 --- a/packages/providers/test/anthropic-sse-parsing.test.ts +++ b/packages/providers/test/anthropic-sse-parsing.test.ts @@ -472,4 +472,176 @@ describe("Anthropic raw SSE parsing", () => { expect(result.errorMessage).toBeUndefined(); expect(result.content).toEqual([{ type: "text", text: "Hello" }]); }); + + /** + * A gateway may stop after `message_delta` without closing the tool block. + * The call then still carries its last streamed preview, which is not what + * the model finished writing. + */ + it("refuses a tool call whose block never closed", async () => { + const response = createSseResponse([ + { + event: "message_start", + data: JSON.stringify({ + type: "message_start", + message: { + id: "msg_cut", + usage: { + input_tokens: 12, + output_tokens: 0, + cache_read_input_tokens: 0, + cache_creation_input_tokens: 0, + }, + }, + }), + }, + { + event: "content_block_start", + data: JSON.stringify({ + type: "content_block_start", + index: 0, + content_block: { type: "tool_use", id: "toolu_cut", name: "write_file", input: {} }, + }), + }, + { + event: "content_block_delta", + data: JSON.stringify({ + type: "content_block_delta", + index: 0, + delta: { type: "input_json_delta", partial_json: '{"path":"a.md","content":"half' }, + }), + }, + { + event: "message_delta", + data: JSON.stringify({ + type: "message_delta", + delta: { stop_reason: "tool_use" }, + usage: { input_tokens: 12, output_tokens: 20 }, + }), + }, + { event: "message_stop", data: JSON.stringify({ type: "message_stop" }) }, + ]); + + const result = await streamAnthropic( + anthropicModel(), + { messages: [{ role: "user", content: "Write it", timestamp: Date.now() }] }, + { client: createFakeAnthropicClient(response) }, + ).result(); + + const call = result.content.find((block) => block.type === "toolCall"); + if (call?.type !== "toolCall") throw new Error("expected a tool call"); + expect(call.argumentsError).toBeDefined(); + expect(call.arguments).toEqual({}); + }); + + it("keeps the input a gateway sent on content_block_start without deltas", async () => { + const response = createSseResponse([ + { + event: "message_start", + data: JSON.stringify({ + type: "message_start", + message: { + id: "msg_eager", + usage: { + input_tokens: 12, + output_tokens: 0, + cache_read_input_tokens: 0, + cache_creation_input_tokens: 0, + }, + }, + }), + }, + { + event: "content_block_start", + data: JSON.stringify({ + type: "content_block_start", + index: 0, + content_block: { + type: "tool_use", + id: "toolu_eager", + name: "write_file", + input: { path: "a.md", content: "whole" }, + }, + }), + }, + { event: "content_block_stop", data: JSON.stringify({ type: "content_block_stop", index: 0 }) }, + { + event: "message_delta", + data: JSON.stringify({ + type: "message_delta", + delta: { stop_reason: "tool_use" }, + usage: { input_tokens: 12, output_tokens: 20 }, + }), + }, + { event: "message_stop", data: JSON.stringify({ type: "message_stop" }) }, + ]); + + const result = await streamAnthropic( + anthropicModel(), + { messages: [{ role: "user", content: "Write it", timestamp: Date.now() }] }, + { client: createFakeAnthropicClient(response) }, + ).result(); + + const call = result.content.find((block) => block.type === "toolCall"); + if (call?.type !== "toolCall") throw new Error("expected a tool call"); + expect(call.argumentsError).toBeUndefined(); + expect(call.arguments).toEqual({ path: "a.md", content: "whole" }); + }); + + it("keeps a tool call whose block closed", async () => { + const response = createSseResponse([ + { + event: "message_start", + data: JSON.stringify({ + type: "message_start", + message: { + id: "msg_ok", + usage: { + input_tokens: 12, + output_tokens: 0, + cache_read_input_tokens: 0, + cache_creation_input_tokens: 0, + }, + }, + }), + }, + { + event: "content_block_start", + data: JSON.stringify({ + type: "content_block_start", + index: 0, + content_block: { type: "tool_use", id: "toolu_ok", name: "write_file", input: {} }, + }), + }, + { + event: "content_block_delta", + data: JSON.stringify({ + type: "content_block_delta", + index: 0, + delta: { type: "input_json_delta", partial_json: '{"path":"a.md"}' }, + }), + }, + { event: "content_block_stop", data: JSON.stringify({ type: "content_block_stop", index: 0 }) }, + { + event: "message_delta", + data: JSON.stringify({ + type: "message_delta", + delta: { stop_reason: "tool_use" }, + usage: { input_tokens: 12, output_tokens: 20 }, + }), + }, + { event: "message_stop", data: JSON.stringify({ type: "message_stop" }) }, + ]); + + const result = await streamAnthropic( + anthropicModel(), + { messages: [{ role: "user", content: "Write it", timestamp: Date.now() }] }, + { client: createFakeAnthropicClient(response) }, + ).result(); + + const call = result.content.find((block) => block.type === "toolCall"); + if (call?.type !== "toolCall") throw new Error("expected a tool call"); + expect(call.argumentsError).toBeUndefined(); + expect(call.arguments).toEqual({ path: "a.md" }); + }); }); diff --git a/packages/providers/test/final-tool-arguments.test.ts b/packages/providers/test/final-tool-arguments.test.ts new file mode 100644 index 000000000..01c83435d --- /dev/null +++ b/packages/providers/test/final-tool-arguments.test.ts @@ -0,0 +1,224 @@ +import { Type } from "typebox"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { streamSimple } from "../src/compat.ts"; +import type { Model, Tool } from "../src/types.ts"; +import { parseFinalToolArguments } from "../src/utils/json-parse.ts"; +import { validateToolArguments } from "../src/utils/validation.ts"; +import { stepModel } from "./helpers/step-fixtures.ts"; + +const mockState = vi.hoisted(() => ({ + chunks: undefined as + | Array; finish_reason: string | null }>; + }> + | undefined, +})); + +vi.mock("openai", () => { + class FakeOpenAI { + chat = { + completions: { + create: () => { + const stream = { + async *[Symbol.asyncIterator]() { + for (const chunk of mockState.chunks ?? []) yield chunk; + }, + }; + const promise = Promise.resolve(stream) as Promise & { + withResponse: () => Promise<{ + data: typeof stream; + response: { status: number; headers: Headers }; + }>; + }; + promise.withResponse = async () => ({ + data: stream, + response: { status: 200, headers: new Headers() }, + }); + return promise; + }, + }, + }; + } + + return { default: FakeOpenAI }; +}); + +describe("parseFinalToolArguments", () => { + it("reads complete arguments", () => { + const parsed = parseFinalToolArguments('{"path":"a.ts","content":"x"}'); + expect(parsed.error).toBeUndefined(); + expect(parsed.arguments).toEqual({ path: "a.ts", content: "x" }); + }); + + it("reads an absent argument list as an empty object", () => { + expect(parseFinalToolArguments(undefined)).toEqual({ arguments: {} }); + expect(parseFinalToolArguments("")).toEqual({ arguments: {} }); + expect(parseFinalToolArguments(" ")).toEqual({ arguments: {} }); + }); + + it("rejects arguments the stream ended in the middle of", () => { + const raw = `{"path":"report.md","content":"${"x".repeat(4000)}`; + const parsed = parseFinalToolArguments(raw); + expect(parsed.error).toBeDefined(); + expect(parsed.error).toContain(String(raw.length)); + expect(parsed.arguments).toEqual({}); + }); + + it("rejects a truncated tail that ends inside an escape", () => { + expect(parseFinalToolArguments('{"a":"value\\').error).toBeDefined(); + }); + + it("still repairs an invalid escape, which restores the encoding the model meant", () => { + const parsed = parseFinalToolArguments('{"a":"v\\qalue"}'); + expect(parsed.error).toBeUndefined(); + expect(parsed.arguments).toEqual({ a: "v\\qalue" }); + }); + + it("rejects a top-level value that is not an object", () => { + expect(parseFinalToolArguments("[1,2]").error).toBeDefined(); + expect(parseFinalToolArguments('"text"').error).toBeDefined(); + expect(parseFinalToolArguments("42").error).toBeDefined(); + }); + + it("rejects malformed JSON that is nonetheless complete", () => { + const parsed = parseFinalToolArguments('{"a" 1}'); + expect(parsed.error).toBeDefined(); + expect(parsed.arguments).toEqual({}); + }); +}); + +describe("validateToolArguments with unfinished arguments", () => { + const tool: Tool = { + name: "write_file", + description: "Write a file", + parameters: Type.Object({ path: Type.String(), content: Type.String() }), + }; + + it("refuses a call whose arguments never arrived whole, even though the types match", () => { + expect(() => + validateToolArguments(tool, { + type: "toolCall", + id: "call_1", + name: "write_file", + arguments: { path: "a.md", content: "half of a file" }, + argumentsError: "could not be read as JSON (114082 characters)", + }), + ).toThrow(/did not arrive whole/); + }); + + it("names the tool and says the call did not run", () => { + let message = ""; + try { + validateToolArguments(tool, { + type: "toolCall", + id: "call_1", + name: "write_file", + arguments: {}, + argumentsError: "could not be read as JSON (10 characters)", + }); + } catch (error) { + message = error instanceof Error ? error.message : String(error); + } + expect(message).toContain('"write_file"'); + expect(message).toContain("did not arrive whole"); + expect(message).toContain("was not executed"); + }); + + it("still validates complete arguments as before", () => { + const args = validateToolArguments(tool, { + type: "toolCall", + id: "call_1", + name: "write_file", + arguments: { path: "a.md", content: "whole" }, + }); + expect(args).toEqual({ path: "a.md", content: "whole" }); + }); +}); + +describe("openai-completions unfinished tool arguments", () => { + beforeEach(() => { + mockState.chunks = undefined; + }); + + it("marks a tool call whose arguments were cut off instead of salvaging them", async () => { + const truncatedContent = `{"path":"report.md","content":"${"x".repeat(4000)}`; + mockState.chunks = [ + { + id: "chatcmpl-cut", + choices: [ + { + delta: { + tool_calls: [ + { + index: 0, + id: "call_cut", + type: "function", + function: { name: "write_file", arguments: truncatedContent }, + }, + ], + }, + finish_reason: null, + }, + ], + }, + { id: "chatcmpl-cut", choices: [{ delta: {}, finish_reason: "tool_calls" }] }, + ]; + + const { compat: _compat, ...baseModel } = stepModel(); + const model = { ...baseModel, api: "openai-completions" } as Model<"openai-completions">; + const response = await streamSimple( + model, + { + messages: [{ role: "user", content: "Write the report", timestamp: Date.now() }], + tools: [{ name: "write_file", description: "Write a file", parameters: Type.Object({}) }], + }, + { apiKey: "test" }, + ).result(); + + const call = response.content.find((block) => block.type === "toolCall"); + expect(call).toBeDefined(); + if (call?.type !== "toolCall") throw new Error("expected a tool call"); + expect(call.argumentsError).toBeDefined(); + expect(call.arguments).toEqual({}); + }); + + it("keeps a complete tool call unchanged", async () => { + mockState.chunks = [ + { + id: "chatcmpl-ok", + choices: [ + { + delta: { + tool_calls: [ + { + index: 0, + id: "call_ok", + type: "function", + function: { name: "read_file", arguments: '{"path":"README.md"}' }, + }, + ], + }, + finish_reason: "tool_calls", + }, + ], + }, + ]; + + const { compat: _compat, ...baseModel } = stepModel(); + const model = { ...baseModel, api: "openai-completions" } as Model<"openai-completions">; + const response = await streamSimple( + model, + { + messages: [{ role: "user", content: "Read", timestamp: Date.now() }], + tools: [{ name: "read_file", description: "Read a file", parameters: Type.Object({}) }], + }, + { apiKey: "test" }, + ).result(); + + const call = response.content.find((block) => block.type === "toolCall"); + if (call?.type !== "toolCall") throw new Error("expected a tool call"); + expect(call.argumentsError).toBeUndefined(); + expect(call.arguments).toEqual({ path: "README.md" }); + }); +}); diff --git a/packages/providers/test/openai-responses-partial-json-cleanup.test.ts b/packages/providers/test/openai-responses-partial-json-cleanup.test.ts index d01800c48..30e1f0040 100644 --- a/packages/providers/test/openai-responses-partial-json-cleanup.test.ts +++ b/packages/providers/test/openai-responses-partial-json-cleanup.test.ts @@ -103,4 +103,39 @@ describe("openai responses partialJson cleanup", () => { expect(toolCallEnd.toolCall).toBe(persistedToolCall); expect("partialJson" in toolCallEnd.toolCall).toBe(false); }); + + async function runResponses( + events: AsyncIterable, + ): Promise { + const model: Model<"openai-responses"> = { + id: "gpt-5-mini", + name: "GPT-5 Mini", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text"], + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + contextWindow: 400000, + maxTokens: 128000, + }; + const output = createOutput(model); + await processResponsesStream(events, output, new AssistantMessageEventStream(), model); + return output.content.find((block) => block.type === "toolCall"); + } + + it("marks a tool call whose done arguments were cut off", async () => { + const truncated = `{"path":"report.md","content":"${"x".repeat(4000)}`; + const call = await runResponses(createFunctionCallEvents(truncated)); + if (call?.type !== "toolCall") throw new Error("Expected toolCall block"); + expect(call.argumentsError).toBeDefined(); + expect(call.arguments).toEqual({}); + }); + + it("keeps a tool call whose done arguments arrived whole", async () => { + const call = await runResponses(createFunctionCallEvents('{"path":"README.md","content":"updated"}')); + if (call?.type !== "toolCall") throw new Error("Expected toolCall block"); + expect(call.argumentsError).toBeUndefined(); + expect(call.arguments).toEqual({ path: "README.md", content: "updated" }); + }); }); From 13fe88015b43283a6e6d03e3d7e86bca62052f19 Mon Sep 17 00:00:00 2001 From: liuedcson <332840681+liuedcson@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:39:43 +0800 Subject: [PATCH 2/7] fix(coding-agent): end a run that hit the output limit with nothing to act on MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A provider that reported `length` with no visible text and no tool call ended the run as if it had finished. Nothing was recorded, nothing was retried, and the turn read as ordinary completion even though the model had spent its whole output budget and produced no work. The turn is now classified as `truncated_without_output` and reported as the run's failure on `agent_settled`, so print, JSON, subagent lanes and goal continuation all see it. It does not enter the empty-turn recovery loop: a recovery prompt would resend whatever filled the budget, which is how a degenerate reply becomes the input for the next one. A truncated turn that did produce text or a tool call keeps its existing handling — compaction owns that case, and `isRecoverableLength` still decides whether a compact-and-retry is worth asking for. --- CHANGELOG.md | 1 + .../coding-agent/src/core/agent-session.ts | 18 ++++++++++- .../src/core/incomplete-turn-recovery.ts | 4 +++ .../suite/incomplete-turn-recovery.test.ts | 31 +++++++++++++++++++ .../providers/src/utils/incomplete-turn.ts | 25 ++++++++++++++- .../providers/test/incomplete-turn.test.ts | 22 +++++++++++++ 6 files changed, 99 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 347902cc2..77b33ca77 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,7 @@ ### Fixed - A tool call whose arguments never arrived whole is no longer executed. Streamed deltas are parsed speculatively so a UI can preview them, but a finished call now carries only what the provider completed: when the stream ends mid-argument, or a tool block never closes, that block keeps empty `arguments` and an `argumentsError`, and `validateToolCall` / `validateToolArguments` refuse it. Previously the best-effort parser filled in whatever had arrived, so a write cut off at the output token limit reached the filesystem as a truncated file. +- A model reply that reaches its output token limit without producing an answer or a tool call now ends the run as a failure instead of ending silently. The provider's `length` stop is kept on the message; the run is reported on `agent_settled` and named in print/JSON exit codes, because there is nothing to act on and compaction cannot repair it. - Fixed automatic compaction silently doing nothing when the newest message alone exceeded `keepRecentTokens` and was a tool result (for example one large file read near the threshold): no cut point qualified, so the whole history was kept and nothing was summarized. The cut now falls back to the newest valid cut point, matching upstream pi, so older history is summarized and the oversized tool batch is kept. - An OpenAI Responses stream that finishes with a tool call whose `output_item.done` never arrived now ends with an error instead of handing that call to the agent loop. Non-compliant servers that reuse or omit `output_index` (observed with OpenAI-compatible gateways) could otherwise produce duplicate or mixed-up tool calls in one assistant message, which ran the same tool twice and then failed every later turn on replay with `Duplicate value for 'tool_call_id'`. - Recover a normal assistant response that contains neither visible text nor an executable tool call: keep the original message in history unchanged, append one hidden user-role recovery prompt, and continue. Recovery is bounded by a streak of consecutive empty turns. Only a turn with visible text or an executed tool call resets it, and so does any user input, so a long autonomous run is not ended by one transient empty response and a provider error in between does not refill the budget. Automatic compaction runs first when the response also exceeded the context window. diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts index fe7fa8cb2..bc8866801 100644 --- a/packages/coding-agent/src/core/agent-session.ts +++ b/packages/coding-agent/src/core/agent-session.ts @@ -33,6 +33,7 @@ import { INCOMPLETE_TURN_MESSAGES, type IncompleteTurnReason, isIncompleteAssistantTurn, + isTruncatedWithoutOutput, } from "@step-harness/providers"; import type { AssistantMessage, @@ -1636,9 +1637,24 @@ export class AgentSession { */ private _classifyAssistantTurn(message: AssistantMessage): void { const reason = classifyIncompleteAssistantTurn(message); + // A turn that hit the output limit with nothing actionable is terminal: no + // recovery prompt can help, and replaying it would resend whatever filled + // the budget. Classify it so the persisted message says what happened. + const truncated = reason === undefined && isTruncatedWithoutOutput(message); // Always describe the message that is persisted, even when this host owns // completion: `incomplete` is a property of the turn, not of our policy. - message.incomplete = reason; + message.incomplete = reason ?? (truncated ? "truncated_without_output" : undefined); + if (truncated) { + recordIncompleteTurn(message, "truncated_without_output", { + streak: this._incompleteTurnStreak + 1, + maxAttempts: INCOMPLETE_TURN_RECOVERY_ATTEMPTS, + }); + this._recordIncompleteRunFailure( + "truncated_without_output", + `${INCOMPLETE_TURN_MESSAGES.truncated_without_output} Raise the model's max output, or ask for the work in smaller pieces.`, + ); + return; + } if (!reason) { // Only real progress refills the budget and resolves the run. An error, an // abort, or a truncated turn also fails to classify as incomplete, but diff --git a/packages/coding-agent/src/core/incomplete-turn-recovery.ts b/packages/coding-agent/src/core/incomplete-turn-recovery.ts index ae2a2647b..3c5ab42d2 100644 --- a/packages/coding-agent/src/core/incomplete-turn-recovery.ts +++ b/packages/coding-agent/src/core/incomplete-turn-recovery.ts @@ -34,6 +34,10 @@ const RECOVERY_PROMPTS: Record = { "If work remains, call the appropriate tool now; otherwise finish with a clear answer for me.", "Do not put tool calls or commands inside reasoning only.", ].join("\n"), + // Terminal, so this prompt is never sent; every reason carries one so the map + // stays exhaustive. + truncated_without_output: + "[Step runtime recovery] The last turn reached its output limit before producing an answer or a tool call.", }; export interface IncompleteTurnRecoveryOptions { diff --git a/packages/coding-agent/test/suite/incomplete-turn-recovery.test.ts b/packages/coding-agent/test/suite/incomplete-turn-recovery.test.ts index 7e754eab2..30526c3ee 100644 --- a/packages/coding-agent/test/suite/incomplete-turn-recovery.test.ts +++ b/packages/coding-agent/test/suite/incomplete-turn-recovery.test.ts @@ -29,6 +29,37 @@ describe("incomplete assistant turn recovery", () => { while (harnesses.length > 0) harnesses.pop()?.cleanup(); }); + it("ends the run when the output limit was reached with nothing to act on", async () => { + const harness = await createHarness(); + harnesses.push(harness); + harness.setResponses([ + () => { + // The incident's shape: the whole output budget was spent, so this is + // a max-output stop rather than the context-pressure kind compaction owns. + const message = fauxAssistantMessage( + [fauxThinking("A very long chain of reasoning that never reaches an answer.")], + { stopReason: "length" }, + ); + message.usage.output = harness.models[0].maxTokens; + message.usage.totalTokens = message.usage.output; + return message; + }, + ]); + + await harness.session.prompt("Do the work."); + + // No recovery prompt: replaying the turn would resend what filled the budget. + expect(recoveryEntries(harness)).toHaveLength(0); + expect(settledFailures(harness)).toMatchObject([{ kind: "incomplete_turn", reason: "truncated_without_output" }]); + // The classification lands on the message that gets persisted, even though + // overflow recovery may later drop it from the working context. + const persisted = harness + .eventsOfType("message_end") + .map((event) => event.message) + .filter((message): message is AssistantMessage => message.role === "assistant"); + expect(persisted[0]?.incomplete).toBe("truncated_without_output"); + }); + it("preserves a thinking-only turn and retries with a recovery message", async () => { const harness = await createHarness(); harnesses.push(harness); diff --git a/packages/providers/src/utils/incomplete-turn.ts b/packages/providers/src/utils/incomplete-turn.ts index 2841c3d5b..81c6f2a32 100644 --- a/packages/providers/src/utils/incomplete-turn.ts +++ b/packages/providers/src/utils/incomplete-turn.ts @@ -7,12 +7,14 @@ import type { AssistantMessage } from "../types.ts"; * a normal stop while offering neither will end a run with nothing visible and * no work done, which reads as the task stopping early. */ -export type IncompleteTurnReason = "missing_tool_call" | "no_visible_output"; +export type IncompleteTurnReason = "missing_tool_call" | "no_visible_output" | "truncated_without_output"; /** Neutral, user-facing description of each reason. */ export const INCOMPLETE_TURN_MESSAGES: Record = { no_visible_output: "The model returned no visible answer or executable tool call.", missing_tool_call: "The model ended a tool-use turn without an executable tool call.", + truncated_without_output: + "The model reached its output token limit before producing an answer or a tool call. The work was not done.", }; type ContentBlocks = AssistantMessage["content"]; @@ -65,6 +67,20 @@ export function isIncompleteAssistantTurn(message: AssistantMessage): boolean { return classifyIncompleteAssistantTurn(message) !== undefined; } +/** + * Whether a turn hit the output limit without producing anything actionable. + * + * Compaction cannot repair this: the model spent its whole output budget, so + * there is no text or tool call to act on and no context pressure to relieve. + * Replaying the turn would resend whatever filled that budget — which is how a + * degenerate reply becomes the input that produces the next one. + */ +export function isTruncatedWithoutOutput(message: AssistantMessage): boolean { + if (message.stopReason !== "length") return false; + const content = contentBlocks(message); + return !hasVisibleText(content) && !content.some((block) => block.type === "toolCall"); +} + /** Why a run may treat this assistant message as its terminal failure. */ export interface AssistantTerminalFailure { kind: "error" | "aborted" | "incomplete"; @@ -87,6 +103,13 @@ export function assistantTerminalFailure(message: AssistantMessage): AssistantTe if (message.stopReason === "aborted") { return { kind: "aborted", message: message.errorMessage || "The model request was cancelled." }; } + if (isTruncatedWithoutOutput(message)) { + return { + kind: "incomplete", + message: INCOMPLETE_TURN_MESSAGES.truncated_without_output, + incompleteReason: "truncated_without_output", + }; + } const reason = classifyIncompleteAssistantTurn(message); if (reason) return { kind: "incomplete", message: INCOMPLETE_TURN_MESSAGES[reason], incompleteReason: reason }; return undefined; diff --git a/packages/providers/test/incomplete-turn.test.ts b/packages/providers/test/incomplete-turn.test.ts index 9ffa872e1..688c01db0 100644 --- a/packages/providers/test/incomplete-turn.test.ts +++ b/packages/providers/test/incomplete-turn.test.ts @@ -105,4 +105,26 @@ describe("assistantTerminalFailure", () => { it("reports nothing for a completed turn", () => { expect(assistantTerminalFailure(assistant([{ type: "text" as const, text: "done" }], "stop"))).toBeUndefined(); }); + + it("reports a turn that hit the output limit with nothing to act on", () => { + const message = assistant([{ type: "thinking" as const, thinking: "reasoning" }], "length"); + expect(assistantTerminalFailure(message)).toEqual({ + kind: "incomplete", + message: INCOMPLETE_TURN_MESSAGES.truncated_without_output, + incompleteReason: "truncated_without_output", + }); + // The provider's own stop reason is a fact and is left alone. + expect(message.stopReason).toBe("length"); + }); + + it("does not report a truncated turn that produced something", () => { + expect( + assistantTerminalFailure(assistant([{ type: "text" as const, text: "partial answer" }], "length")), + ).toBeUndefined(); + expect( + assistantTerminalFailure( + assistant([{ type: "toolCall" as const, id: "c1", name: "read", arguments: {} }], "length"), + ), + ).toBeUndefined(); + }); }); From a685b1a91157de0eda7d4f6fce0d0b44bc68a776 Mon Sep 17 00:00:00 2001 From: liuedcson <332840681+liuedcson@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:40:10 +0800 Subject: [PATCH 3/7] feat(agent-core): bound an oversized historical reply in the request view MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A reply that filled its whole output budget with a degenerate loop stays in the transcript, and every later request resends it. That makes one bad reply the input for the next one, so a single failure can seed a series of them. The cap is a size bound, not a repetition detector. Judging whether text looks repetitive needs a threshold that misfires on legitimate long output — a generated table, a file listing, a detailed report. The size of one reply is a fact, so the bound is derived from what the model could actually have written: its output limit priced at four characters a token, with a 400,000-character floor. An answer the model could legitimately emit is never shortened. Only the request view changes. The transcript, the session file and compaction boundaries keep the original, the most recent reply is left alone because it is the current turn, and the rewrite is deterministic so a shortened prefix stays byte-identical and the provider cache stays warm. --- CHANGELOG.md | 1 + .../harness/compaction/assistant-text-cap.ts | 96 ++++++++++++++++++ packages/agent-core/src/index.ts | 5 + .../test/harness/assistant-text-cap.test.ts | 99 +++++++++++++++++++ .../coding-agent/src/core/agent-session.ts | 21 +++- .../src/core/compaction/projection.ts | 3 + 6 files changed, 221 insertions(+), 4 deletions(-) create mode 100644 packages/agent-core/src/harness/compaction/assistant-text-cap.ts create mode 100644 packages/agent-core/test/harness/assistant-text-cap.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 77b33ca77..c4916002d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,7 @@ - A tool call whose arguments never arrived whole is no longer executed. Streamed deltas are parsed speculatively so a UI can preview them, but a finished call now carries only what the provider completed: when the stream ends mid-argument, or a tool block never closes, that block keeps empty `arguments` and an `argumentsError`, and `validateToolCall` / `validateToolArguments` refuse it. Previously the best-effort parser filled in whatever had arrived, so a write cut off at the output token limit reached the filesystem as a truncated file. - A model reply that reaches its output token limit without producing an answer or a tool call now ends the run as a failure instead of ending silently. The provider's `length` stop is kept on the message; the run is reported on `agent_settled` and named in print/JSON exit codes, because there is nothing to act on and compaction cannot repair it. +- A historical assistant reply far larger than the active model's output budget could have produced is shortened in the request view before it is replayed, keeping its start and end and marking what was dropped. The transcript and the session file keep the original. The bound follows the model (its output limit priced at four characters a token, with a 400,000-character floor), so an answer the model could legitimately have written is never shortened. - Fixed automatic compaction silently doing nothing when the newest message alone exceeded `keepRecentTokens` and was a tool result (for example one large file read near the threshold): no cut point qualified, so the whole history was kept and nothing was summarized. The cut now falls back to the newest valid cut point, matching upstream pi, so older history is summarized and the oversized tool batch is kept. - An OpenAI Responses stream that finishes with a tool call whose `output_item.done` never arrived now ends with an error instead of handing that call to the agent loop. Non-compliant servers that reuse or omit `output_index` (observed with OpenAI-compatible gateways) could otherwise produce duplicate or mixed-up tool calls in one assistant message, which ran the same tool twice and then failed every later turn on replay with `Duplicate value for 'tool_call_id'`. - Recover a normal assistant response that contains neither visible text nor an executable tool call: keep the original message in history unchanged, append one hidden user-role recovery prompt, and continue. Recovery is bounded by a streak of consecutive empty turns. Only a turn with visible text or an executed tool call resets it, and so does any user input, so a long autonomous run is not ended by one transient empty response and a provider error in between does not refill the budget. Automatic compaction runs first when the response also exceeded the context window. diff --git a/packages/agent-core/src/harness/compaction/assistant-text-cap.ts b/packages/agent-core/src/harness/compaction/assistant-text-cap.ts new file mode 100644 index 000000000..e39a575f3 --- /dev/null +++ b/packages/agent-core/src/harness/compaction/assistant-text-cap.ts @@ -0,0 +1,96 @@ +/** + * Bound the size of a historical assistant reply in the request view. + * + * A reply that filled its whole output budget with a degenerate loop is not + * history worth replaying: it is the input that produces the next one. Once it + * is in the transcript, every later request resends it, so one bad reply can + * seed a cascade. + * + * This is a size cap, not a repetition detector. Judging whether text "looks + * repetitive" needs a threshold nobody can defend and misfires on legitimate + * long output (a generated table, a file listing); the size of a single reply + * is a fact. The cap sits far above any ordinary answer and only shortens what + * would already be pathological. + * + * Only the request view changes: the transcript, the session file, and + * compaction boundaries keep the original message. The output is deterministic, + * so the shortened prefix is byte-identical on every later request and the + * provider cache stays warm. + */ + +import type { Message } from "@step-harness/providers"; + +/** + * Floor for the cap, in characters. + * + * A single reply can legitimately be very large: at a 64k-token output budget, + * English prose reaches roughly 256k characters. So a cap is only a bound on + * the absurd — a reply no output budget could have produced — and it must never + * be tighter than what the model can legitimately emit. Callers pass a cap + * derived from the model's own output limit and this floor keeps a small model + * from being capped below a large answer's size. + */ +export const ASSISTANT_TEXT_CAP_FLOOR_CHARS = 400_000; +/** Share of the model's output budget kept, priced at four characters a token. */ +const CHARS_PER_TOKEN = 4; + +/** The cap for a model whose output budget is `maxTokens`. */ +export function assistantTextCapFor(maxTokens: number | undefined): number { + const budget = Math.max(0, maxTokens ?? 0) * CHARS_PER_TOKEN * 2; + return Math.max(ASSISTANT_TEXT_CAP_FLOOR_CHARS, budget); +} + +/** What the shortened block keeps from its start and its end. */ +const HEAD_CHARS = 20_000; +const TAIL_CHARS = 5_000; + +const CAP_MARKER_PREFIX = "[reply truncated:"; + +function shortenText(text: string): string { + let head = text.slice(0, HEAD_CHARS); + let tail = text.slice(text.length - TAIL_CHARS); + // Never split a surrogate pair: a lone half is not a character. + if (/[\uD800-\uDBFF]/.test(head.slice(-1))) head = head.slice(0, -1); + if (/[\uDC00-\uDFFF]/.test(tail.slice(0, 1))) tail = tail.slice(1); + const removed = text.length - head.length - tail.length; + return `${head}\n\n${CAP_MARKER_PREFIX} ${removed} characters of this reply were not replayed]\n\n${tail}`; +} + +/** + * Shorten oversized assistant text in a request's message list. + * + * The most recent assistant message is left alone: it is the current turn, not + * history, and shortening it would change what the model sees of its own latest + * reply. Returns the input array itself when nothing needed shortening, so an + * untouched request keeps the exact objects its caller built. + */ +export function capOversizedAssistantText(messages: Message[], options: { maxChars?: number } = {}): Message[] { + const cap = Math.max(ASSISTANT_TEXT_CAP_FLOOR_CHARS, options.maxChars ?? ASSISTANT_TEXT_CAP_FLOOR_CHARS); + let lastAssistant = -1; + for (let index = messages.length - 1; index >= 0; index--) { + if (messages[index]?.role === "assistant") { + lastAssistant = index; + break; + } + } + + let result: Message[] | undefined; + for (let index = 0; index < messages.length; index++) { + if (index === lastAssistant) continue; + const message = messages[index]; + if (message?.role !== "assistant") continue; + + let changed = false; + const content = message.content.map((block) => { + if (block.type !== "text" || block.text.length <= cap) return block; + changed = true; + return { ...block, text: shortenText(block.text) }; + }); + if (!changed) continue; + + result ??= [...messages]; + result[index] = { ...message, content }; + } + + return result ?? messages; +} diff --git a/packages/agent-core/src/index.ts b/packages/agent-core/src/index.ts index 16b6c2a2c..f6bf3714b 100644 --- a/packages/agent-core/src/index.ts +++ b/packages/agent-core/src/index.ts @@ -45,6 +45,11 @@ export * from "./agent.ts"; export * from "./agent-loop.ts"; export * from "./harness/agent-harness.ts"; export * from "./harness/command-outcome.ts"; +export { + ASSISTANT_TEXT_CAP_FLOOR_CHARS, + assistantTextCapFor, + capOversizedAssistantText, +} from "./harness/compaction/assistant-text-cap.ts"; export { type BranchPreparation, type BranchSummaryDetails, diff --git a/packages/agent-core/test/harness/assistant-text-cap.test.ts b/packages/agent-core/test/harness/assistant-text-cap.test.ts new file mode 100644 index 000000000..ad76cdedc --- /dev/null +++ b/packages/agent-core/test/harness/assistant-text-cap.test.ts @@ -0,0 +1,99 @@ +import type { AssistantMessage, Message, Usage } from "@step-harness/providers"; +import { describe, expect, it } from "vitest"; +import { + ASSISTANT_TEXT_CAP_FLOOR_CHARS, + capOversizedAssistantText, +} from "../../src/harness/compaction/assistant-text-cap.ts"; + +const usage: Usage = { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, +}; + +function assistant(text: string): AssistantMessage { + return { + role: "assistant", + content: [{ type: "text", text }], + api: "openai-responses", + provider: "openai", + model: "mock", + usage, + stopReason: "stop", + timestamp: 1, + }; +} + +function user(text: string): Message { + return { role: "user", content: [{ type: "text", text }], timestamp: 1 }; +} + +const huge = "x".repeat(ASSISTANT_TEXT_CAP_FLOOR_CHARS + 10_000); + +describe("capOversizedAssistantText", () => { + it("shortens an oversized historical reply and says how much was dropped", () => { + const messages = [user("go"), assistant(huge), user("next"), assistant("done")]; + const capped = capOversizedAssistantText(messages); + const text = capped[1]?.role === "assistant" ? (capped[1].content[0] as { text: string }).text : ""; + expect(text.length).toBeLessThan(ASSISTANT_TEXT_CAP_FLOOR_CHARS); + expect(text).toContain("[reply truncated:"); + expect(text).toContain("characters of this reply were not replayed]"); + }); + + it("leaves the most recent reply alone, because it is the current turn", () => { + const messages = [user("go"), assistant(huge)]; + expect(capOversizedAssistantText(messages)).toBe(messages); + }); + + it("returns the same array when nothing is oversized", () => { + const messages = [user("go"), assistant("a normal answer"), user("next"), assistant("done")]; + expect(capOversizedAssistantText(messages)).toBe(messages); + }); + + it("keeps the head and the tail, dropping only the middle", () => { + const body = `HEAD${"m".repeat(ASSISTANT_TEXT_CAP_FLOOR_CHARS)}TAIL`; + const capped = capOversizedAssistantText([assistant(body), assistant("done")]); + const text = capped[0]?.role === "assistant" ? (capped[0].content[0] as { text: string }).text : ""; + expect(text.startsWith("HEAD")).toBe(true); + expect(text.endsWith("TAIL")).toBe(true); + }); + + it("is deterministic, so a shortened prefix stays byte-identical", () => { + const messages = [assistant(huge), assistant("done")]; + const once = capOversizedAssistantText(messages); + const twice = capOversizedAssistantText(messages); + expect((once[0] as AssistantMessage).content).toEqual((twice[0] as AssistantMessage).content); + }); + + it("leaves tool calls and thinking blocks untouched", () => { + const message: AssistantMessage = { + ...assistant(huge), + content: [ + { type: "thinking", thinking: "reasoning" }, + { type: "toolCall", id: "c1", name: "write", arguments: { path: "a", content: huge } }, + { type: "text", text: huge }, + ], + }; + const capped = capOversizedAssistantText([message, assistant("done")]); + const content = capped[0]?.role === "assistant" ? capped[0].content : []; + expect(content[0]).toEqual({ type: "thinking", thinking: "reasoning" }); + expect(content[1]).toEqual({ + type: "toolCall", + id: "c1", + name: "write", + arguments: { path: "a", content: huge }, + }); + }); + + it("does not split a surrogate pair at the cut", () => { + // An odd prefix puts the head boundary in the middle of an emoji pair. + const body = `a${"🙂".repeat(ASSISTANT_TEXT_CAP_FLOOR_CHARS)}`; + const capped = capOversizedAssistantText([assistant(body), assistant("done")]); + const text = capped[0]?.role === "assistant" ? (capped[0].content[0] as { text: string }).text : ""; + expect(text).not.toMatch(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/); + expect(text).not.toMatch(/(?:^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]/); + }); +}); diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts index bc8866801..f92cb1a9a 100644 --- a/packages/coding-agent/src/core/agent-session.ts +++ b/packages/coding-agent/src/core/agent-session.ts @@ -77,10 +77,12 @@ import { normalizeToolResultImages } from "../utils/tool-result-images.ts"; import { formatNoApiKeyFoundMessage, formatNoModelSelectedMessage } from "./auth-guidance.ts"; import { type BashResult, executeBashWithOperations } from "./bash-executor.ts"; import { + assistantTextCapFor, type CompactionPreparation, type CompactionResult, type CompactionSettings, calculateContextTokens, + capOversizedAssistantText, collectEntriesForBranchSummary, compact, estimateContextTokens, @@ -993,15 +995,26 @@ export class AgentSession { /** * Wrap the agent's `convertToLlm` with request-time lightweight context * projection. Runs right before each model request, after the base - * AgentMessage -> Message conversion. Controlled by - * `step.compaction.contextProjection = "lightweight-v1"`; the session - * transcript is never modified, only the outgoing request messages. + * AgentMessage -> Message conversion. The transcript is never modified, only + * the outgoing request messages. + * + * Two things happen here, and they differ in when they apply: + * - Oversized historical assistant replies are capped unconditionally. A reply + * that filled its output budget with a loop is unsafe to replay at any + * context size, so this is not subject to the projection setting. + * - Everything else is controlled by + * `step.compaction.contextProjection = "lightweight-v1"`. */ private _installContextProjection(): void { const baseConvertToLlm = this.agent.convertToLlm; this.agent.convertToLlm = async (agentMessages: AgentMessage[]): Promise => { const llmMessages = await baseConvertToLlm(agentMessages); - return this._projectLlmContext(agentMessages, llmMessages); + // The cap follows the active model: a reply the model could legitimately + // have produced is never shortened. + const capped = capOversizedAssistantText(llmMessages, { + maxChars: assistantTextCapFor(this.model?.maxTokens), + }); + return this._projectLlmContext(agentMessages, capped); }; } diff --git a/packages/coding-agent/src/core/compaction/projection.ts b/packages/coding-agent/src/core/compaction/projection.ts index b4eee41b2..e3713aa5a 100644 --- a/packages/coding-agent/src/core/compaction/projection.ts +++ b/packages/coding-agent/src/core/compaction/projection.ts @@ -11,7 +11,10 @@ */ export { + ASSISTANT_TEXT_CAP_FLOOR_CHARS, + assistantTextCapFor, type ContextProjectionMode, + capOversizedAssistantText, cutTextWithSalientLines, estimateProjectionTokens, PROJECTION_CUT_MARKER_PREFIX, From 3f04175db5a4c5cc6f1db40fb7a6d1411215fd7b Mon Sep 17 00:00:00 2001 From: liuedcson <332840681+liuedcson@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:40:27 +0800 Subject: [PATCH 4/7] feat(coding-agent): notice and stop repeated identical tool calls MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A model can keep issuing one call — reading the same file, running the same command — and nothing in the loop notices. The signal is deliberately exact: tool name plus canonical arguments, compared by length and a digest so a written file body never has to be held in memory. That is a fact about the request the client sent, not a guess about how repetitive the wording looks, so no ordinary answer can trip it. Three consecutive successful identical calls add one hidden notice to the next request. Ten stop the call and end the turn. Stopping is far from the reminder because repeats can be legitimate, and blocking is only for a loop that already ignored the notice. At most one notice joins a request, so a stuck run cannot spend prompt space on repeating it. A failed or blocked call resets the streak, because a retry after an error is not a repetition, and a new user message starts a new count. --- CHANGELOG.md | 1 + packages/coding-agent/AGENTS.md | 2 +- .../src/features/repeat-tool-call.ts | 176 +++++++++++++ packages/coding-agent/src/features/step.ts | 4 + .../test/step-plan-extension.test.ts | 5 +- .../test/step-repeat-tool-call.test.ts | 243 ++++++++++++++++++ .../test/suite/repeat-tool-call.test.ts | 80 ++++++ 7 files changed, 509 insertions(+), 2 deletions(-) create mode 100644 packages/coding-agent/src/features/repeat-tool-call.ts create mode 100644 packages/coding-agent/test/step-repeat-tool-call.test.ts create mode 100644 packages/coding-agent/test/suite/repeat-tool-call.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index c4916002d..51b1a48a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,7 @@ ### Fixed - A tool call whose arguments never arrived whole is no longer executed. Streamed deltas are parsed speculatively so a UI can preview them, but a finished call now carries only what the provider completed: when the stream ends mid-argument, or a tool block never closes, that block keeps empty `arguments` and an `argumentsError`, and `validateToolCall` / `validateToolArguments` refuse it. Previously the best-effort parser filled in whatever had arrived, so a write cut off at the output token limit reached the filesystem as a truncated file. +- A tool re-issued with identical arguments is noticed at the third consecutive successful call, and a loop that keeps going is stopped at the tenth: the call is blocked and the turn ends instead of running the same work again. At most one notice joins a request, and only a successful repeat counts — a failed call resets the streak, because a retry after an error is not a repetition. - A model reply that reaches its output token limit without producing an answer or a tool call now ends the run as a failure instead of ending silently. The provider's `length` stop is kept on the message; the run is reported on `agent_settled` and named in print/JSON exit codes, because there is nothing to act on and compaction cannot repair it. - A historical assistant reply far larger than the active model's output budget could have produced is shortened in the request view before it is replayed, keeping its start and end and marking what was dropped. The transcript and the session file keep the original. The bound follows the model (its output limit priced at four characters a token, with a 400,000-character floor), so an answer the model could legitimately have written is never shortened. - Fixed automatic compaction silently doing nothing when the newest message alone exceeded `keepRecentTokens` and was a tool result (for example one large file read near the threshold): no cut point qualified, so the whole history was kept and nothing was summarized. The cut now falls back to the newest valid cut point, matching upstream pi, so older history is summarized and the oversized tool batch is kept. diff --git a/packages/coding-agent/AGENTS.md b/packages/coding-agent/AGENTS.md index 34dd791c9..a8ade07a0 100644 --- a/packages/coding-agent/AGENTS.md +++ b/packages/coding-agent/AGENTS.md @@ -44,7 +44,7 @@ Core provides mechanisms that product features compose. Do not put a feature's s | Subagents | `step-subagent.ts`, `step-subagent-agents.ts`, `subagent/` | Agent definition discovery, persistent RPC children, lane lifecycles, notifications, results, and timeouts | | Workflows | `workflow/` | QuickJS VM, host bridge, agent runner, journal, budgets, path ACLs, progress, and session-scoped Ultracode activation | | Goal / cron | `step-schedule.ts`, `step-cron.ts` | Session-goal budgets and continuation; cron scheduling and durable jobs in trusted projects | -| Other product capabilities | `step-questionnaire.ts`, `step-stream-recovery.ts`, `llama/` | User questionnaires, stream recovery, and local model integration | +| Other product capabilities | `step-questionnaire.ts`, `step-stream-recovery.ts`, `repeat-tool-call.ts`, `llama/` | User questionnaires, stream recovery, repeated-call notices, and local model integration | Features connect through existing extension and session-event interfaces. Reuse core tools, sessions, and completion semantics rather than maintain another execution loop. diff --git a/packages/coding-agent/src/features/repeat-tool-call.ts b/packages/coding-agent/src/features/repeat-tool-call.ts new file mode 100644 index 000000000..86048613d --- /dev/null +++ b/packages/coding-agent/src/features/repeat-tool-call.ts @@ -0,0 +1,176 @@ +import { shortContentHash } from "@step-harness/agent-core"; +import type { ExtensionAPI } from "../core/extensions/types.ts"; +import type { CustomMessage } from "../core/messages.ts"; + +export const REPEAT_TOOL_CALL_NOTICE = "step-repeat-tool-call"; + +/** + * Tools whose repeated call writes the same bytes again. + * + * A repeat of these cannot express new work: the file either already holds that + * content or the earlier call failed, and a failed call resets the streak. The + * set only selects the wording — every tool is held to the same limits. Shell + * tools stay out because their side effects cannot be read off the arguments. + */ +const MUTATING_TOOL_NAMES = new Set(["write", "edit", "write_file", "edit_file"]); + +/** + * Consecutive identical successful calls before the model is told, and before + * the loop is stopped. Stopping is deliberately far away: repeats can be + * legitimate (polling a command, re-reading a file that another process may + * have changed), so the first notice invites a correction and only an + * unrecoverable loop is cut. + */ +export const REPEAT_REMINDER_LIMIT = 3; +export const REPEAT_STOP_LIMIT = 10; + +/** Unfinished calls kept for pairing; a run that never settles one must not grow the map. */ +export const MAX_TRACKED_CALLS = 64; + +/** + * Canonical JSON, so key order cannot make one call look different from itself. + * Input arrives from `JSON.parse`, so it holds no cycle and no BigInt; the catch + * only keeps a malformed host payload from throwing inside a tool hook. + */ +function stableJson(value: unknown): string { + const canonical = (entry: unknown): unknown => { + if (Array.isArray(entry)) return entry.map(canonical); + if (entry !== null && typeof entry === "object") { + const source = entry as Record; + return Object.fromEntries( + Object.keys(source) + .sort() + .map((key) => [key, canonical(source[key])]), + ); + } + return entry; + }; + try { + return JSON.stringify(canonical(value)) ?? ""; + } catch { + return ""; + } +} + +/** + * Identify one call: the tool, its canonical length, and a digest of the + * canonical JSON. Comparing fixed-size digests keeps a large argument — a + * written file body — out of memory while two calls are told apart. A digest + * collision within one streak is a 2^-64 event, and the length has to match too. + */ +function callKey(toolName: string, args: unknown): string { + const canonical = stableJson(args); + return `${toolName}\u0000${canonical.length}\u0000${shortContentHash(canonical)}`; +} + +function noticeContent(toolName: string, count: number): string { + // No other tool ran in between, so a read-only call sees the same workspace and + // a write overwrites what it already wrote. Not "no new information": a shell + // command can legitimately report different state each run. + const shared = `[Step runtime notice] ${toolName} has now run ${count} times in a row with exactly the same arguments, and no other tool ran in between.`; + return MUTATING_TOOL_NAMES.has(toolName) + ? `${shared} The earlier call already wrote this exact content, so this repetition changes nothing.` + : `${shared} Change the arguments to make progress, or stop and report what is blocking you.`; +} + +function stopReason(toolName: string, count: number): string { + return ( + `${toolName} was called ${count} times in a row with exactly the same arguments and no other tool ran in between, ` + + "so it was stopped instead of running again. Report what is blocking, and change the approach rather than repeating this call." + ); +} + +/** + * Notice a model that keeps issuing the same call, and stop an unrecoverable loop. + * + * The signal is deliberately exact: tool name plus canonical arguments. That is + * a fact about the request the client sent, not a guess about how repetitive the + * wording looks, so no ordinary answer can trip it. The notice joins at most one + * request per turn — repeating it would cost prompt space without adding + * information — and only a run that keeps going is stopped. + */ +export function registerRepeatToolCallNotice(pi: ExtensionAPI): void { + /** + * Every started call's arguments, keyed by id until its result lands. Started + * calls include ones a policy later blocks, and the arguments here are the + * request's, before any approval-time rewrite. + */ + const issued = new Map(); + /** Consecutive identical *successful* calls. */ + let streak: { key: string; count: number } = { key: "", count: 0 }; + /** A notice waiting for the next request; consumed once to keep prompts small. */ + let pending: CustomMessage | undefined; + /** The current turn already spent its one notice. */ + let noticeSentThisTurn = false; + + const resetStreak = (): void => { + streak = { key: "", count: 0 }; + pending = undefined; + noticeSentThisTurn = false; + }; + + const remember = (toolCallId: string, toolName: string, args: unknown): void => { + issued.set(toolCallId, { toolName, key: callKey(toolName, args) }); + // An aborted or crashed run may never deliver the matching end. Keep the + // map bounded rather than holding one entry per unfinished call forever. + if (issued.size > MAX_TRACKED_CALLS) { + const oldest = issued.keys().next().value; + if (oldest !== undefined) issued.delete(oldest); + } + }; + + pi.on("tool_execution_start", (event) => { + remember(event.toolCallId, event.toolName, event.args); + }); + + pi.on("tool_call", (event) => { + // The start event normally arrived first; a host that dispatches the policy + // hook first still gets a decision from the arguments themselves. + const call = issued.get(event.toolCallId) ?? { + toolName: event.toolName, + key: callKey(event.toolName, event.input), + }; + const prospective = call.key === streak.key ? streak.count + 1 : 1; + if (prospective < REPEAT_STOP_LIMIT) return; + return { block: true, terminate: true, reason: stopReason(call.toolName, prospective) }; + }); + + pi.on("tool_execution_end", (event) => { + const call = issued.get(event.toolCallId); + issued.delete(event.toolCallId); + if (!call) return; + // A call that never ran, or that failed, cannot be repeated work: the next + // identical call is the model trying again after an error. + if (event.executed === false || event.isError) { + streak = { key: "", count: 0 }; + return; + } + streak = call.key === streak.key ? { key: call.key, count: streak.count + 1 } : { key: call.key, count: 1 }; + if (streak.count !== REPEAT_REMINDER_LIMIT || noticeSentThisTurn) return; + noticeSentThisTurn = true; + pending = { + role: "custom", + customType: REPEAT_TOOL_CALL_NOTICE, + content: noticeContent(call.toolName, streak.count), + display: false, + details: { toolName: call.toolName, count: streak.count }, + timestamp: Date.now(), + }; + }); + + pi.on("context", (event) => { + if (!pending) return; + const message = pending; + pending = undefined; + // The request view only: the notice is never appended to the transcript. + return { messages: [...event.messages, message] }; + }); + + // One notice per turn, and a new instruction restarts the count: repeating + // across it is a new task. In-flight calls stay tracked — they belong to the + // run, not to the streak. + pi.on("turn_start", () => { + noticeSentThisTurn = false; + }); + pi.on("input", resetStreak); +} diff --git a/packages/coding-agent/src/features/step.ts b/packages/coding-agent/src/features/step.ts index 4ca72f6db..459568452 100644 --- a/packages/coding-agent/src/features/step.ts +++ b/packages/coding-agent/src/features/step.ts @@ -39,6 +39,7 @@ import { type StepTelemetryReporter, trackStepTelemetry } from "../step/telemetr import type { TraceHeaderPolicy } from "../step/telemetry-contract.ts"; import { getThenRunCommand } from "../step/then-run.ts"; import { applyStepTraceHeaders } from "../step/trace-headers.ts"; +import { registerRepeatToolCallNotice } from "./repeat-tool-call.ts"; import { isPlanExtensionMounted, planModeToolCallDecision } from "./step-plan.ts"; import { fetchStepModelEfforts, @@ -551,6 +552,9 @@ export function createStepExtension(options: StepExtensionOptions = {}): Extensi await handlePermissionCommand(args, ctx); }, }); + + // Observe settled calls; blocking stays with the policies registered above. + registerRepeatToolCallNotice(pi); }; } diff --git a/packages/coding-agent/test/step-plan-extension.test.ts b/packages/coding-agent/test/step-plan-extension.test.ts index d23cd304c..6c2ea6ca2 100644 --- a/packages/coding-agent/test/step-plan-extension.test.ts +++ b/packages/coding-agent/test/step-plan-extension.test.ts @@ -2343,10 +2343,13 @@ test("the plan pre-check sees a plan extension loaded through a different API ob let result: unknown; for (const handler of stepHandlers.get("tool_call") ?? []) { - result = await handler( + const outcome = await handler( { type: "tool_call", toolName: "write_file", toolCallId: "split", input: { path: "src/app.ts" } } as never, context, ); + // Mirror the runner: a block short-circuits, and a handler that returns + // nothing leaves the decision it did not make alone. + if (outcome !== undefined && outcome !== null) result = outcome; } expect(result).toMatchObject({ block: true }); expect(confirm).not.toHaveBeenCalled(); diff --git a/packages/coding-agent/test/step-repeat-tool-call.test.ts b/packages/coding-agent/test/step-repeat-tool-call.test.ts new file mode 100644 index 000000000..521f962bb --- /dev/null +++ b/packages/coding-agent/test/step-repeat-tool-call.test.ts @@ -0,0 +1,243 @@ +import { describe, expect, it } from "vitest"; +import type { ExtensionAPI, ExtensionContext } from "../src/core/extensions/types.ts"; +import { + MAX_TRACKED_CALLS, + REPEAT_REMINDER_LIMIT, + REPEAT_STOP_LIMIT, + registerRepeatToolCallNotice, +} from "../src/features/repeat-tool-call.ts"; + +interface CallOptions { + isError?: boolean; + executed?: boolean; +} + +interface Harness { + /** One full call: start, the policy decision, then the result. Returns the decision. */ + call(id: string, toolName: string, input: Record, options?: CallOptions): unknown; + /** Start a call and ask for the policy decision without settling it. */ + decide(id: string, toolName: string, input: Record): unknown; + /** Emit one raw host event, for cases the helpers cannot express. */ + fire(name: string, event: unknown): unknown; + /** Whether the feature takes part in the tool_call decision chain at all. */ + hasToolCallHandler(): boolean; + /** The request view the host would send, or undefined when no notice is pending. */ + context(): { content?: unknown }[] | undefined; + userMessage(): void; + turnStart(): void; +} + +function harness(): Harness { + const handlers = new Map unknown>(); + const registered: string[] = []; + const pi = { + on(name: string, handler: (event: unknown, ctx: unknown) => unknown) { + handlers.set(name, handler); + registered.push(name); + }, + } as unknown as ExtensionAPI; + registerRepeatToolCallNotice(pi); + + const fire = (name: string, event: unknown): unknown => handlers.get(name)?.(event, {} as ExtensionContext); + + const start = (id: string, toolName: string, input: Record): void => { + fire("tool_execution_start", { type: "tool_execution_start", toolCallId: id, toolName, args: input }); + }; + const settle = (id: string, toolName: string, options: CallOptions = {}): void => { + fire("tool_execution_end", { + type: "tool_execution_end", + toolCallId: id, + toolName, + result: {}, + isError: options.isError ?? false, + executed: options.executed ?? true, + }); + }; + + return { + call(id, toolName, input, options) { + start(id, toolName, input); + const decision = fire("tool_call", { type: "tool_call", toolCallId: id, toolName, input }); + settle(id, toolName, options); + return decision; + }, + decide(id, toolName, input) { + start(id, toolName, input); + return fire("tool_call", { type: "tool_call", toolCallId: id, toolName, input }); + }, + fire, + hasToolCallHandler() { + return registered.includes("tool_call"); + }, + context() { + const result = fire("context", { type: "context", messages: [] }) as + | { messages?: { content?: unknown }[] } + | undefined; + return result?.messages; + }, + userMessage() { + fire("input", { type: "input", text: "next task" }); + }, + turnStart() { + fire("turn_start", { type: "turn_start" }); + }, + }; +} + +function noticeText(messages: { content?: unknown }[] | undefined): string { + return String(messages?.[0]?.content ?? ""); +} + +describe("registerRepeatToolCallNotice", () => { + it("notices at the reminder limit", () => { + const h = harness(); + for (let i = 1; i < REPEAT_REMINDER_LIMIT; i++) h.call(`c${i}`, "read", { path: "a.ts" }); + expect(h.context()).toBeUndefined(); + + h.call("last", "read", { path: "a.ts" }); + const messages = h.context(); + expect(messages).toHaveLength(1); + expect(noticeText(messages)).toContain("read"); + expect(noticeText(messages)).toContain(String(REPEAT_REMINDER_LIMIT)); + }); + + it("uses the write wording for a write tool", () => { + const h = harness(); + for (let i = 1; i < REPEAT_REMINDER_LIMIT; i++) h.call(`c${i}`, "write_file", { path: "a.md", content: "x" }); + h.call("last", "write_file", { path: "a.md", content: "x" }); + expect(noticeText(h.context())).toContain("changes nothing"); + }); + + it("keeps the stop limit well above the reminder limit", () => { + expect(REPEAT_STOP_LIMIT).toBeGreaterThan(REPEAT_REMINDER_LIMIT); + }); + + it("does not stop a call below the stop limit", () => { + const h = harness(); + for (let i = 1; i < REPEAT_STOP_LIMIT; i++) { + expect(h.call(`c${i}`, "read", { path: "a.ts" })).toBeUndefined(); + } + }); + + it("stops the run at the stop limit", () => { + const h = harness(); + for (let i = 1; i < REPEAT_STOP_LIMIT; i++) h.call(`c${i}`, "read", { path: "a.ts" }); + const decision = h.decide("stop", "read", { path: "a.ts" }); + expect(decision).toMatchObject({ block: true, terminate: true }); + expect(String((decision as { reason?: string }).reason)).toContain(String(REPEAT_STOP_LIMIT)); + }); + + it("says nothing about different arguments", () => { + const h = harness(); + for (let i = 1; i <= REPEAT_STOP_LIMIT; i++) h.call(`c${i}`, "read", { path: `file-${i}.md` }); + expect(h.context()).toBeUndefined(); + }); + + it("treats argument key order as irrelevant", () => { + const h = harness(); + for (let i = 1; i <= REPEAT_REMINDER_LIMIT - 1; i++) + h.call(`c${i}`, "write_file", { path: "a.md", content: "x" }); + h.call("last", "write_file", { content: "x", path: "a.md" }); + expect(h.context()).toHaveLength(1); + }); + + it("resets on a failed call, so a retry is not a repeat", () => { + const h = harness(); + for (let i = 1; i < REPEAT_REMINDER_LIMIT; i++) h.call(`c${i}`, "read", { path: "a.ts" }); + h.call("boom", "read", { path: "a.ts" }, { isError: true }); + h.call("retry", "read", { path: "a.ts" }); + expect(h.context()).toBeUndefined(); + }); + + it("resets when the call never ran", () => { + const h = harness(); + for (let i = 1; i < REPEAT_REMINDER_LIMIT; i++) h.call(`c${i}`, "read", { path: "a.ts" }); + h.call("blocked", "read", { path: "a.ts" }, { executed: false, isError: true }); + h.call("next", "read", { path: "a.ts" }); + expect(h.context()).toBeUndefined(); + }); + + it("resets on a user message", () => { + const h = harness(); + for (let i = 1; i < REPEAT_REMINDER_LIMIT; i++) h.call(`c${i}`, "read", { path: "a.ts" }); + h.userMessage(); + h.call("next", "read", { path: "a.ts" }); + expect(h.context()).toBeUndefined(); + }); + + it("resets when the repeated call is a different tool", () => { + const h = harness(); + for (let i = 1; i < REPEAT_REMINDER_LIMIT; i++) h.call(`c${i}`, "read", { path: "a.ts" }); + h.call("other", "grep", { pattern: "x" }); + expect(h.context()).toBeUndefined(); + }); + + it("keeps the streak across turns but spends one notice per turn", () => { + const h = harness(); + // Three of one call, then three of another, in the same turn: one notice. + for (let i = 1; i <= REPEAT_REMINDER_LIMIT; i++) h.call(`a${i}`, "read", { path: "a.ts" }); + expect(h.context()).toHaveLength(1); + for (let i = 1; i <= REPEAT_REMINDER_LIMIT; i++) h.call(`b${i}`, "grep", { pattern: "x" }); + expect(h.context()).toBeUndefined(); + + // The next turn may speak again. + h.turnStart(); + for (let i = 1; i <= REPEAT_REMINDER_LIMIT; i++) h.call(`c${i}`, "read", { path: "b.ts" }); + expect(h.context()).toHaveLength(1); + }); + + it("keeps the stop decision even after the notice was spent", () => { + const h = harness(); + for (let i = 1; i < REPEAT_STOP_LIMIT; i++) h.call(`c${i}`, "read", { path: "a.ts" }); + const decision = h.decide("stop", "read", { path: "a.ts" }); + expect(decision).toMatchObject({ block: true, terminate: true }); + }); + + it("keeps the decision available when the host dispatches the policy hook first", () => { + const h = harness(); + for (let i = 1; i < REPEAT_STOP_LIMIT; i++) h.call(`c${i}`, "read", { path: "a.ts" }); + // No start event for this call: the decision must still come from the input. + const decision = h.fire("tool_call", { + type: "tool_call", + toolCallId: "policy-first", + toolName: "read", + input: { path: "a.ts" }, + }); + expect(decision).toMatchObject({ block: true, terminate: true }); + }); + + it("takes part in the decision chain only to stop a loop", () => { + const h = harness(); + expect(h.hasToolCallHandler()).toBe(true); + expect(h.call("first", "read", { path: "a.ts" })).toBeUndefined(); + }); + + it("evicts the oldest unfinished call instead of growing without bound", () => { + const h = harness(); + h.fire("tool_execution_start", { + type: "tool_execution_start", + toolCallId: "oldest", + toolName: "read", + args: { path: "a.ts" }, + }); + for (let i = 0; i < MAX_TRACKED_CALLS; i++) { + h.fire("tool_execution_start", { + type: "tool_execution_start", + toolCallId: `orphan-${i}`, + toolName: "read", + args: { path: "a.ts" }, + }); + } + // The first entry was evicted, so its result no longer resolves to a call + // and cannot extend a streak. Without eviction this would count. + h.fire("tool_execution_end", { + type: "tool_execution_end", + toolCallId: "oldest", + toolName: "read", + result: {}, + isError: false, + executed: true, + }); + expect(h.context()).toBeUndefined(); + }); +}); diff --git a/packages/coding-agent/test/suite/repeat-tool-call.test.ts b/packages/coding-agent/test/suite/repeat-tool-call.test.ts new file mode 100644 index 000000000..41527f18a --- /dev/null +++ b/packages/coding-agent/test/suite/repeat-tool-call.test.ts @@ -0,0 +1,80 @@ +import { type Context, fauxAssistantMessage, fauxToolCall } from "@step-harness/providers"; +import { afterEach, describe, expect, it } from "vitest"; +import { REPEAT_TOOL_CALL_NOTICE, registerRepeatToolCallNotice } from "../../src/features/repeat-tool-call.ts"; +import { createHarness, getMessageText, type Harness } from "./harness.ts"; + +const all: Harness[] = []; +afterEach(() => { + for (const h of all.splice(0)) h.cleanup(); +}); + +function notices(context: Context): string[] { + return context.messages.map(getMessageText).filter((text) => text.startsWith("[Step runtime notice]")); +} + +describe("repeated identical tool calls in a real session", () => { + it("tells the model once, in the request only", async () => { + const h = await createHarness({ + extensionFactories: [{ name: "repeat-tool-call", factory: (pi) => registerRepeatToolCallNotice(pi) }], + }); + all.push(h); + await h.session.bindExtensions({}); + + const requests: Context[] = []; + const capture = (context: Context) => { + requests.push({ systemPrompt: context.systemPrompt, messages: structuredClone(context.messages) }); + return fauxAssistantMessage(fauxToolCall("write", { path: "notes.md", content: "same" }), { + stopReason: "toolUse", + }); + }; + h.setResponses([ + capture, + capture, + capture, + (context) => { + capture(context); + return fauxAssistantMessage("Stopped: the file already holds that content."); + }, + ]); + + await h.session.prompt("Write notes.md."); + + // The third identical successful write reaches the reminder limit, so the + // request after it carries the notice — and earlier requests do not. + for (const request of requests.slice(0, 3)) expect(notices(request)).toEqual([]); + const withNotice = requests.filter((context) => notices(context).length > 0); + expect(withNotice).toHaveLength(1); + expect(notices(withNotice[0]!)[0]).toContain("write"); + expect(notices(withNotice[0]!)[0]).toContain("changes nothing"); + + // It is a request view: the transcript keeps only real messages. + expect( + h.session.messages.some( + (message) => message.role === "custom" && message.customType === REPEAT_TOOL_CALL_NOTICE, + ), + ).toBe(false); + }); + + it("says nothing when the arguments differ", async () => { + const h = await createHarness({ + extensionFactories: [{ name: "repeat-tool-call", factory: (pi) => registerRepeatToolCallNotice(pi) }], + }); + all.push(h); + await h.session.bindExtensions({}); + + const requests: Context[] = []; + let step = 0; + const capture = (context: Context) => { + requests.push({ systemPrompt: context.systemPrompt, messages: structuredClone(context.messages) }); + step += 1; + return step <= 3 + ? fauxAssistantMessage(fauxToolCall("read", { path: `file-${step}.md` }), { stopReason: "toolUse" }) + : fauxAssistantMessage("Done reading distinct files."); + }; + h.setResponses([capture, capture, capture, capture]); + + await h.session.prompt("Read three different files."); + + expect(requests.some((context) => notices(context).length > 0)).toBe(false); + }); +}); From 33847bedb2309116d947deb19fb51560c0045d05 Mon Sep 17 00:00:00 2001 From: liuedcson <332840681+liuedcson@users.noreply.github.com> Date: Wed, 2 Dec 2026 14:13:31 +0800 Subject: [PATCH 5/7] feat(coding-agent): notice a tool-call cycle, and make the guard configurable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The repeat guard recognised one call repeating. A run that alternates between two or three calls — read, test, read, test — never extended a same-call streak, so it went unnoticed however long it ran. A cycle is now detected as the shortest period of 2 to 4 calls that repeats three times in a row, compared with the same key the streak uses: tool name plus the complete arguments. That comparison is what keeps ordinary work out of it. An `edit` that changes something followed by a `test` is keyed by different arguments, so a real edit/test cycle is `ABCB`, not `ABAB`, and does not match. Only a cycle reissuing the exact same calls does. The cycle is reported, never stopped. A repeat cycle can be a legitimate retry loop over external state, and a notice costs a few lines while a stop costs the run. One call repeating keeps its own limits — reported at three, stopped at ten — and is excluded from the cycle check so `AAAAAA` is not reported twice. Both are now controlled by `[tools] repeat_call_guard` (JSON config: `tools.repeatCallGuard`), default on. It is read on every call, so a reload takes effect without a new session. --- docs/step-configuration.md | 31 ++++ .../coding-agent/schema/config.schema.json | 8 + .../src/features/repeat-tool-call.ts | 131 ++++++++++++++-- packages/coding-agent/src/features/step.ts | 4 +- .../coding-agent/src/step/config-schema.ts | 10 +- .../coding-agent/src/step/settings-manager.ts | 14 ++ .../coding-agent/src/step/stepcode-config.ts | 3 + .../test/step-repeat-tool-call.test.ts | 141 +++++++++++++++++- .../stepcode-repeat-guard-setting.test.ts | 53 +++++++ 9 files changed, 380 insertions(+), 15 deletions(-) create mode 100644 packages/coding-agent/test/stepcode-repeat-guard-setting.test.ts diff --git a/docs/step-configuration.md b/docs/step-configuration.md index b7c2fce1f..5f308d8b7 100644 --- a/docs/step-configuration.md +++ b/docs/step-configuration.md @@ -162,6 +162,37 @@ Step screens pass the Step agent directory; generic TUI callers default to the system temporary directory. Rendering equivalence tests select the uncached renderer through a test-process argument. +### Repeated tool calls + +A run that keeps issuing the same tool call is noticed, and a run that keeps +going is stopped: + +```toml +[tools] +repeat_call_guard = true # default; false turns both the notice and the stop off +``` + +Two shapes are recognised, and both compare the **tool name and the complete +arguments** — two calls with different arguments are never treated as a repeat, +so ordinary work is not interrupted: + +- One call repeating (`read a.ts` four times in a row) is reported at the third + consecutive success and stopped at the tenth. +- A short cycle of distinct calls repeating in the same order (`ABAB`, + `ABCABC`) is reported once it has repeated three times. It is never stopped: a + cycle can be a legitimate retry loop over external state, and an `edit` that + changes something followed by a `test` keyed by different arguments does not + match. + +At most one notice joins a request, so a stuck run cannot spend prompt space +repeating it. A call that failed or never ran resets the count — a retry after an +error is not a repetition — and a new user message starts a new count. The +notice is a hidden request-only message and never enters the transcript. + +The setting is read on every call, so a config reload takes effect without a +restart. With a StepCode JSON config the same switch lives under +`tools.repeatCallGuard`. + ### Subagents The `[subagent]` table controls subagent concurrency and background lanes: diff --git a/packages/coding-agent/schema/config.schema.json b/packages/coding-agent/schema/config.schema.json index 5e80a4888..08f3e2a07 100644 --- a/packages/coding-agent/schema/config.schema.json +++ b/packages/coding-agent/schema/config.schema.json @@ -1119,6 +1119,10 @@ "type": "boolean", "description": "Allow the feedback submission flow (default true)." }, + "repeatToolCallGuard": { + "type": "boolean", + "description": "Notice and stop repeated identical tool calls (default true)." + }, "subagentBackground": { "type": "boolean", "description": "Flat form of `[subagent] background`." @@ -1478,6 +1482,10 @@ }, "additionalProperties": false, "description": "Approval tier overrides." + }, + "repeat_call_guard": { + "type": "boolean", + "description": "Notice and stop repeated identical tool calls (default true)." } }, "additionalProperties": false, diff --git a/packages/coding-agent/src/features/repeat-tool-call.ts b/packages/coding-agent/src/features/repeat-tool-call.ts index 86048613d..15a6c201d 100644 --- a/packages/coding-agent/src/features/repeat-tool-call.ts +++ b/packages/coding-agent/src/features/repeat-tool-call.ts @@ -24,8 +24,29 @@ const MUTATING_TOOL_NAMES = new Set(["write", "edit", "write_file", "edit_file"] export const REPEAT_REMINDER_LIMIT = 3; export const REPEAT_STOP_LIMIT = 10; +/** + * Period detection for a loop that alternates instead of repeating one call. + * + * `ABAB` and `ABCABC` never extend a same-call streak, so the limit above cannot + * see them. They are still a loop: the same few calls, in the same order, with + * identical arguments each time. + * + * The shorter period bound is what separates a loop from ordinary work. An + * `edit` that changes something and a `test` that checks it is `ABCB` — keyed by + * arguments, the second edit differs from the first — so a real edit/test cycle + * does not match. Only a cycle reissuing the exact same calls does, and even then + * it is reported rather than stopped: a repeat cycle can be a legitimate retry + * loop over external state, and a notice is cheap where a stop is not. + */ +export const CYCLE_MIN_PERIOD = 2; +export const CYCLE_MAX_PERIOD = 4; +/** Full periods that must repeat before the cycle is reported. */ +export const CYCLE_REPEATS = 3; + /** Unfinished calls kept for pairing; a run that never settles one must not grow the map. */ export const MAX_TRACKED_CALLS = 64; +/** Successful calls kept for cycle detection: enough for the longest reported period. */ +const CYCLE_HISTORY_SIZE = CYCLE_MAX_PERIOD * CYCLE_REPEATS + CYCLE_MAX_PERIOD; /** * Canonical JSON, so key order cannot make one call look different from itself. @@ -80,16 +101,69 @@ function stopReason(toolName: string, count: number): string { ); } +/** + * The shortest period that repeats at the end of `history`, if any. + * + * "Repeats" means the last `period * CYCLE_REPEATS` entries are the same + * `period` entries over and over, compared by call identity. A tail of one + * distinct call is left to the same-call streak, which owns that case and has a + * stronger response, so `AAAAAA` is never reported as an `ABAB`-shaped cycle. + */ +export function detectCycle(history: readonly string[]): { period: number } | undefined { + for (let period = CYCLE_MIN_PERIOD; period <= CYCLE_MAX_PERIOD; period++) { + const span = period * CYCLE_REPEATS; + if (history.length < span) continue; + const tail = history.slice(history.length - span); + // One distinct call repeating is a streak, not a cycle; the streak path + // reports it with wording and a stop limit that fit it. + if (new Set(tail).size < 2) continue; + let repeats = true; + for (let index = period; index < span; index++) { + if (tail[index] !== tail[index - period]) { + repeats = false; + break; + } + } + if (repeats) return { period }; + } + return undefined; +} + +function cycleNoticeContent(period: number, toolNames: readonly string[]): string { + const sequence = toolNames.join(" -> "); + return ( + `[Step runtime notice] The last ${period * CYCLE_REPEATS} calls were the same ${period} calls repeating in the same order ` + + `with exactly the same arguments: ${sequence}. Repeating the cycle cannot produce new information. ` + + "Change what you pass to at least one of them, or stop and report what is blocking you." + ); +} + /** * Notice a model that keeps issuing the same call, and stop an unrecoverable loop. * - * The signal is deliberately exact: tool name plus canonical arguments. That is - * a fact about the request the client sent, not a guess about how repetitive the - * wording looks, so no ordinary answer can trip it. The notice joins at most one + * Two shapes are recognised, and the response differs by how unusual each is: + * - One call repeating (`AAAA`) is almost certainly stuck, so it is reported at + * three and stopped at ten. + * - A short cycle of distinct calls (`ABAB`, `ABCABC`) can be legitimate work, so + * it is only reported — never stopped — once it has repeated three times. + * + * Both signals are exact: tool name plus canonical arguments. That is a fact + * about the request the client sent, not a guess about how repetitive the wording + * looks, so no ordinary answer can trip either. The notice joins at most one * request per turn — repeating it would cost prompt space without adding - * information — and only a run that keeps going is stopped. + * information. */ -export function registerRepeatToolCallNotice(pi: ExtensionAPI): void { +export interface RepeatToolCallOptions { + /** + * Read once per call so a settings change takes effect without a new session. + * Defaults to enabled. + */ + enabled?: () => boolean; +} + +export function registerRepeatToolCallNotice(pi: ExtensionAPI, options: RepeatToolCallOptions = {}): void { + const enabled = (): boolean => options.enabled?.() ?? true; + /** * Every started call's arguments, keyed by id until its result lands. Started * calls include ones a policy later blocks, and the arguments here are the @@ -98,6 +172,8 @@ export function registerRepeatToolCallNotice(pi: ExtensionAPI): void { const issued = new Map(); /** Consecutive identical *successful* calls. */ let streak: { key: string; count: number } = { key: "", count: 0 }; + /** Recent successful calls, for spotting a cycle that a streak cannot see. */ + let history: string[] = []; /** A notice waiting for the next request; consumed once to keep prompts small. */ let pending: CustomMessage | undefined; /** The current turn already spent its one notice. */ @@ -105,10 +181,17 @@ export function registerRepeatToolCallNotice(pi: ExtensionAPI): void { const resetStreak = (): void => { streak = { key: "", count: 0 }; + history = []; pending = undefined; noticeSentThisTurn = false; }; + const queueNotice = (message: CustomMessage): void => { + if (noticeSentThisTurn) return; + noticeSentThisTurn = true; + pending = message; + }; + const remember = (toolCallId: string, toolName: string, args: unknown): void => { issued.set(toolCallId, { toolName, key: callKey(toolName, args) }); // An aborted or crashed run may never deliver the matching end. Keep the @@ -120,10 +203,12 @@ export function registerRepeatToolCallNotice(pi: ExtensionAPI): void { }; pi.on("tool_execution_start", (event) => { + if (!enabled()) return; remember(event.toolCallId, event.toolName, event.args); }); pi.on("tool_call", (event) => { + if (!enabled()) return; // The start event normally arrived first; a host that dispatches the policy // hook first still gets a decision from the arguments themselves. const call = issued.get(event.toolCallId) ?? { @@ -136,26 +221,48 @@ export function registerRepeatToolCallNotice(pi: ExtensionAPI): void { }); pi.on("tool_execution_end", (event) => { + if (!enabled()) return; const call = issued.get(event.toolCallId); issued.delete(event.toolCallId); if (!call) return; // A call that never ran, or that failed, cannot be repeated work: the next - // identical call is the model trying again after an error. + // identical call is the model trying again after an error. A failure also + // breaks any cycle: the same calls returning different results is progress. if (event.executed === false || event.isError) { streak = { key: "", count: 0 }; + history = []; return; } + streak = call.key === streak.key ? { key: call.key, count: streak.count + 1 } : { key: call.key, count: 1 }; - if (streak.count !== REPEAT_REMINDER_LIMIT || noticeSentThisTurn) return; - noticeSentThisTurn = true; - pending = { + // Every successful call joins the cycle history before either check runs, so + // an entry that also spends the streak's notice is not a gap in the sequence. + history.push(call.key); + if (history.length > CYCLE_HISTORY_SIZE) history = history.slice(history.length - CYCLE_HISTORY_SIZE); + + if (streak.count === REPEAT_REMINDER_LIMIT) { + queueNotice({ + role: "custom", + customType: REPEAT_TOOL_CALL_NOTICE, + content: noticeContent(call.toolName, streak.count), + display: false, + details: { toolName: call.toolName, count: streak.count }, + timestamp: Date.now(), + }); + return; + } + + const cycle = detectCycle(history); + if (!cycle) return; + const toolNames = history.slice(history.length - cycle.period).map((key) => key.slice(0, key.indexOf("\u0000"))); + queueNotice({ role: "custom", customType: REPEAT_TOOL_CALL_NOTICE, - content: noticeContent(call.toolName, streak.count), + content: cycleNoticeContent(cycle.period, toolNames), display: false, - details: { toolName: call.toolName, count: streak.count }, + details: { period: cycle.period, toolNames }, timestamp: Date.now(), - }; + }); }); pi.on("context", (event) => { diff --git a/packages/coding-agent/src/features/step.ts b/packages/coding-agent/src/features/step.ts index 459568452..56e857350 100644 --- a/packages/coding-agent/src/features/step.ts +++ b/packages/coding-agent/src/features/step.ts @@ -554,7 +554,9 @@ export function createStepExtension(options: StepExtensionOptions = {}): Extensi }); // Observe settled calls; blocking stays with the policies registered above. - registerRepeatToolCallNotice(pi); + registerRepeatToolCallNotice(pi, { + enabled: () => options.stepSettings?.()?.getStepSettings().repeatToolCallGuard ?? true, + }); }; } diff --git a/packages/coding-agent/src/step/config-schema.ts b/packages/coding-agent/src/step/config-schema.ts index 32a556a26..46b9b84cc 100644 --- a/packages/coding-agent/src/step/config-schema.ts +++ b/packages/coding-agent/src/step/config-schema.ts @@ -258,6 +258,9 @@ const StepProductProperties = { autopilot: Type.Optional(Type.Boolean({ description: "Accepted for older files; prefer `autoResume`." })), fullAccessAcknowledged: Type.Optional(Type.Boolean({ description: "Recorded Full Access risk acknowledgment." })), feedbackEnabled: Type.Optional(Type.Boolean({ description: "Allow the feedback submission flow (default true)." })), + repeatToolCallGuard: Type.Optional( + Type.Boolean({ description: "Notice and stop repeated identical tool calls (default true)." }), + ), subagentBackground: Type.Optional(Type.Boolean({ description: "Flat form of `[subagent] background`." })), subagentBackgroundTimeoutSeconds: Type.Optional( Type.Integer({ @@ -272,7 +275,12 @@ const StepProductProperties = { approval: Type.Optional(ApprovalTableSchema), tools: Type.Optional( Type.Object( - { approval: Type.Optional(ApprovalTableSchema) }, + { + approval: Type.Optional(ApprovalTableSchema), + repeat_call_guard: Type.Optional( + Type.Boolean({ description: "Notice and stop repeated identical tool calls (default true)." }), + ), + }, { additionalProperties: false, description: "Tool policy tables." }, ), ), diff --git a/packages/coding-agent/src/step/settings-manager.ts b/packages/coding-agent/src/step/settings-manager.ts index 5c3da07e8..2d36bedf4 100644 --- a/packages/coding-agent/src/step/settings-manager.ts +++ b/packages/coding-agent/src/step/settings-manager.ts @@ -49,6 +49,11 @@ export interface StepSettings { fullAccessAcknowledged?: boolean; /** Enables the user feedback submission flow. Defaults to enabled. */ feedbackEnabled?: boolean; + /** + * `[tools] repeat_call_guard`: notice a run that keeps issuing the same tool + * call, and stop it once the repeat is unrecoverable. Defaults to enabled. + */ + repeatToolCallGuard?: boolean; /** `[subagent] background`: `false` runs `run_in_background` subagent calls in the foreground. */ subagentBackground?: boolean; /** `[subagent] background_timeout_seconds`: default per-turn wall-clock limit of a background lane. */ @@ -260,6 +265,10 @@ function normalizeSettings(value: JsonObject, resetLegacy = true): StepSettings break; } } + const repeatToolCallGuard = [value.repeatToolCallGuard, asObject(value.tools)?.repeat_call_guard].find( + (candidate): candidate is boolean => typeof candidate === "boolean", + ); + if (repeatToolCallGuard !== undefined) result.repeatToolCallGuard = repeatToolCallGuard; const subagent = asObject(value.subagent); const subagentBackground = [value.subagentBackground, subagent?.background].find( (candidate): candidate is boolean => typeof candidate === "boolean", @@ -310,6 +319,7 @@ export const STEP_SETTING_ALIASES: Record autoResume: ["autopilot"], fullAccessAcknowledged: [], feedbackEnabled: [], + repeatToolCallGuard: [], subagentBackground: [], subagentBackgroundTimeoutSeconds: [], subagentMaxConcurrency: [], @@ -342,6 +352,7 @@ export const STEP_SETTING_NESTED_ALIASES: Record): Partial { if (settings.feedbackEnabled !== undefined && typeof settings.feedbackEnabled !== "boolean") { throw new Error(`Invalid Step feedbackEnabled setting: ${String(settings.feedbackEnabled)}`); } + if (settings.repeatToolCallGuard !== undefined && typeof settings.repeatToolCallGuard !== "boolean") { + throw new Error(`Invalid Step repeatToolCallGuard setting: ${String(settings.repeatToolCallGuard)}`); + } if (settings.subagentBackground !== undefined && typeof settings.subagentBackground !== "boolean") { throw new Error(`Invalid Step subagentBackground setting: ${String(settings.subagentBackground)}`); } diff --git a/packages/coding-agent/src/step/stepcode-config.ts b/packages/coding-agent/src/step/stepcode-config.ts index 65e2cdce6..052b8edb4 100644 --- a/packages/coding-agent/src/step/stepcode-config.ts +++ b/packages/coding-agent/src/step/stepcode-config.ts @@ -365,6 +365,7 @@ function readStepCodeSettings(root: JsonObject, report?: (error: Error) => void) const fullAccessAcknowledged = readBoolean(approval?.fullAccessAcknowledged); const feedback = asObject(root.feedback); const feedbackEnabled = readBoolean(feedback?.enabled); + const repeatToolCallGuard = readBoolean(asObject(root.tools)?.repeatCallGuard); const subagent = asObject(root.subagent); const subagentBackground = readBoolean(subagent?.background); const subagentTimeout = subagent?.backgroundTimeoutSeconds; @@ -384,6 +385,7 @@ function readStepCodeSettings(root: JsonObject, report?: (error: Error) => void) ...(autoResume !== undefined ? { autoResume } : {}), ...(fullAccessAcknowledged !== undefined ? { fullAccessAcknowledged } : {}), ...(feedbackEnabled !== undefined ? { feedbackEnabled } : {}), + ...(repeatToolCallGuard !== undefined ? { repeatToolCallGuard } : {}), ...(subagentBackground !== undefined ? { subagentBackground } : {}), ...(isValidSubagentBackgroundTimeout(subagentTimeout) ? { subagentBackgroundTimeoutSeconds: subagentTimeout } @@ -403,6 +405,7 @@ function writeStepCodeSettings(root: Record, patch: Partial unknown>(); const registered: string[] = []; const pi = { @@ -36,7 +42,7 @@ function harness(): Harness { registered.push(name); }, } as unknown as ExtensionAPI; - registerRepeatToolCallNotice(pi); + registerRepeatToolCallNotice(pi, options); const fire = (name: string, event: unknown): unknown => handlers.get(name)?.(event, {} as ExtensionContext); @@ -241,3 +247,136 @@ describe("registerRepeatToolCallNotice", () => { expect(h.context()).toBeUndefined(); }); }); + +describe("the guard can be turned off", () => { + it("says nothing and stops nothing when disabled", () => { + const h = harnessWith({ enabled: () => false }); + for (let i = 1; i <= REPEAT_STOP_LIMIT + 2; i++) { + expect(h.call(`c${i}`, "read", { path: "a.ts" })).toBeUndefined(); + } + expect(h.context()).toBeUndefined(); + }); + + it("reads the setting on every call, so a change lands without a new session", () => { + let on = true; + const h = harnessWith({ enabled: () => on }); + for (let i = 1; i <= REPEAT_REMINDER_LIMIT; i++) h.call(`c${i}`, "read", { path: "a.ts" }); + expect(h.context()).toHaveLength(1); + + on = false; + for (let i = 1; i <= REPEAT_STOP_LIMIT + 2; i++) h.call(`d${i}`, "read", { path: "b.ts" }); + expect(h.context()).toBeUndefined(); + }); +}); + +describe("detectCycle", () => { + const a = "read\u00004\u0000aaaa"; + const b = "test\u00004\u0000bbbb"; + const c = "grep\u00004\u0000cccc"; + + it("does not see a cycle in a short tail", () => { + expect(detectCycle([a, b])).toBeUndefined(); + }); + + it("detects ABAB repeated three times", () => { + expect(detectCycle([a, b, a, b, a, b])).toEqual({ period: 2 }); + }); + + it("detects ABCABC repeated three times", () => { + expect(detectCycle([a, b, c, a, b, c, a, b, c])).toEqual({ period: 3 }); + }); + + it("leaves a single repeated call to the streak", () => { + expect(detectCycle([a, a, a, a, a, a])).toBeUndefined(); + }); + + it("does not treat an advancing sequence as a cycle", () => { + expect(detectCycle([a, b, c, a, b, c].map((k, i) => `${k}-${i}`))).toBeUndefined(); + }); + + it("finds the shortest repeating period first", () => { + expect(detectCycle([a, b, a, b, a, b, a, b])).toEqual({ period: 2 }); + }); +}); + +describe("repeated call cycles", () => { + it("notices a repeating two-call cycle without stopping it", () => { + const h = harness(); + for (let round = 1; round <= 3; round++) { + expect(h.call(`a${round}`, "read", { path: "a.ts" })).toBeUndefined(); + expect(h.call(`b${round}`, "test", { path: "." })).toBeUndefined(); + } + const messages = h.context(); + expect(messages).toHaveLength(1); + const text = String(messages?.[0]?.content ?? ""); + expect(text).toContain("read -> test"); + expect(text).toContain("same 2 calls repeating"); + }); + + it("notices a repeating three-call cycle", () => { + const h = harness(); + for (let round = 1; round <= 3; round++) { + h.call(`a${round}`, "read", { path: "a.ts" }); + h.call(`b${round}`, "test", { path: "." }); + h.call(`c${round}`, "grep", { pattern: "x" }); + } + const text = String(h.context()?.[0]?.content ?? ""); + expect(text).toContain("same 3 calls repeating"); + }); + + it("stays quiet when the second call differs, which is what real work looks like", () => { + const h = harness(); + // edit -> test -> edit -> test, but the two edits differ. + h.call("e1", "edit", { path: "a.ts", search: "x", replace: "y" }); + h.call("t1", "test", { path: "." }); + h.call("e2", "edit", { path: "a.ts", search: "y", replace: "z" }); + h.call("t2", "test", { path: "." }); + h.call("e3", "edit", { path: "a.ts", search: "z", replace: "w" }); + h.call("t3", "test", { path: "." }); + expect(h.context()).toBeUndefined(); + }); + + it("does not stop a cycle, only reports it", () => { + const h = harness(); + for (let round = 1; round <= 8; round++) { + expect(h.call(`a${round}`, "read", { path: "a.ts" })).toBeUndefined(); + expect(h.call(`b${round}`, "test", { path: "." })).toBeUndefined(); + } + }); + + it("shares the one-notice-per-turn budget with the streak", () => { + const h = harness(); + // A streak notice first. + for (let i = 1; i <= REPEAT_REMINDER_LIMIT; i++) h.call(`s${i}`, "read", { path: "a.ts" }); + expect(h.context()).toHaveLength(1); + // The cycle that follows is silent for the rest of the turn. + for (let round = 1; round <= 3; round++) { + h.call(`c${round}a`, "grep", { pattern: "x" }); + h.call(`c${round}b`, "read", { path: "b.ts" }); + } + expect(h.context()).toBeUndefined(); + }); + + it("clears the cycle history on a failure", () => { + const h = harness(); + h.call("a1", "read", { path: "a.ts" }); + h.call("b1", "test", { path: "." }); + h.call("a2", "read", { path: "a.ts" }); + h.call("boom", "test", { path: "." }, { isError: true }); + h.call("a3", "read", { path: "a.ts" }); + h.call("b3", "test", { path: "." }); + expect(h.context()).toBeUndefined(); + }); + + it("keeps counting across turns so a long cycle is still seen", () => { + const h = harness(); + h.call("a1", "read", { path: "a.ts" }); + h.call("b1", "test", { path: "." }); + h.turnStart(); + h.call("a2", "read", { path: "a.ts" }); + h.call("b2", "test", { path: "." }); + h.call("a3", "read", { path: "a.ts" }); + h.call("b3", "test", { path: "." }); + expect(h.context()).toHaveLength(1); + }); +}); diff --git a/packages/coding-agent/test/stepcode-repeat-guard-setting.test.ts b/packages/coding-agent/test/stepcode-repeat-guard-setting.test.ts new file mode 100644 index 000000000..57cba287b --- /dev/null +++ b/packages/coding-agent/test/stepcode-repeat-guard-setting.test.ts @@ -0,0 +1,53 @@ +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { createStepSettingsManager } from "../src/step/settings-manager.ts"; +import { decorateStepCodeSettingsManager, loadStepCodeConfig } from "../src/step/stepcode-config.ts"; + +const directories: string[] = []; +afterEach(() => { + while (directories.length > 0) rmSync(directories.pop()!, { recursive: true, force: true }); +}); + +function fixture(config: Record) { + const root = mkdtempSync(join(tmpdir(), "stepcode-repeat-guard-")); + directories.push(root); + const path = join(root, "config.json"); + writeFileSync( + path, + JSON.stringify({ + activeModel: "alpha", + providers: { + custom: { api: "openai-completions", baseUrl: "https://example.invalid/v1", models: [{ id: "alpha" }] }, + }, + ...config, + }), + ); + return { root, path }; +} + +async function settings(config: Record) { + const { root, path } = fixture(config); + const loaded = await loadStepCodeConfig({ STEPCODE_CONFIG_PATH: path }); + const paths = { global: join(root, "global.toml"), project: join(root, "project.toml") }; + const manager = decorateStepCodeSettingsManager(createStepSettingsManager(root, undefined, { paths }), loaded!); + return manager.getStepSettings(); +} + +describe("repeat call guard setting in a StepCode JSON config", () => { + it("defaults to enabled when the file says nothing", async () => { + expect((await settings({})).repeatToolCallGuard).toBeUndefined(); + }); + + it("reads tools.repeatCallGuard", async () => { + expect((await settings({ tools: { repeatCallGuard: false } })).repeatToolCallGuard).toBe(false); + expect((await settings({ tools: { repeatCallGuard: true } })).repeatToolCallGuard).toBe(true); + }); + + it("keeps the approval table it shares with", async () => { + const value = await settings({ tools: { approval: { preset: "ask" }, repeatCallGuard: false } }); + expect(value.repeatToolCallGuard).toBe(false); + expect(value.permissionPreset).toBe("ask"); + }); +}); From 0609032236a787624913559534e6dd714d69ed81 Mon Sep 17 00:00:00 2001 From: liuedcson <332840681+liuedcson@users.noreply.github.com> Date: Wed, 2 Dec 2026 14:15:33 +0800 Subject: [PATCH 6/7] docs(coding-agent): document the repeat tool call guard setting Every configurable top-level key needs a row in the settings table, and the guard added one without it. --- packages/coding-agent/docs/settings.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/coding-agent/docs/settings.md b/packages/coding-agent/docs/settings.md index fb8ca6b2d..b154d5fd3 100644 --- a/packages/coding-agent/docs/settings.md +++ b/packages/coding-agent/docs/settings.md @@ -256,6 +256,12 @@ preset = "approve-for-me" |---------|------|---------|-------------| | `feedbackEnabled` | boolean | `true` | Allow the feedback submission flow. `[feedback] enabled` is the older spelling | +### Repeated tool calls + +| Setting | Type | Default | Description | +|---------|------|---------|-------------| +| `repeatToolCallGuard` | boolean | `true` | Notice a run that keeps issuing the same tool call and stop one that never stops. `[tools] repeat_call_guard` is the same setting; see [repeated tool calls](../../../docs/step-configuration.md#repeated-tool-calls) | + ### Search | Setting | Type | Default | Description | From 44f2f313aab71dc8de03a9f7012a18a6717ea558 Mon Sep 17 00:00:00 2001 From: liuedcson <332840681+liuedcson@users.noreply.github.com> Date: Wed, 2 Dec 2026 14:23:22 +0800 Subject: [PATCH 7/7] docs(coding-agent): correct what a turn boundary resets in the repeat guard The comment predated cycle detection and claimed the turn boundary restarts the count. Only the one-notice budget resets there; the streak and the cycle history deliberately survive it, because a loop does not care where a turn ends. --- packages/coding-agent/src/features/repeat-tool-call.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/coding-agent/src/features/repeat-tool-call.ts b/packages/coding-agent/src/features/repeat-tool-call.ts index 15a6c201d..306ffb648 100644 --- a/packages/coding-agent/src/features/repeat-tool-call.ts +++ b/packages/coding-agent/src/features/repeat-tool-call.ts @@ -273,11 +273,11 @@ export function registerRepeatToolCallNotice(pi: ExtensionAPI, options: RepeatTo return { messages: [...event.messages, message] }; }); - // One notice per turn, and a new instruction restarts the count: repeating - // across it is a new task. In-flight calls stay tracked — they belong to the - // run, not to the streak. + // A new turn may spend one notice again. The streak and the cycle history + // survive it: a loop does not care where a turn boundary falls. pi.on("turn_start", () => { noticeSentThisTurn = false; }); + // A new instruction starts a new count: repeating across it is a new task. pi.on("input", resetStreak); }