Skip to content
Open
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@

### 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.
- 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.
Expand Down
31 changes: 31 additions & 0 deletions docs/step-configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
3 changes: 1 addition & 2 deletions packages/agent-core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 7 additions & 4 deletions packages/agent-core/src/agent-loop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[],
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
}
5 changes: 5 additions & 0 deletions packages/agent-core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
99 changes: 99 additions & 0 deletions packages/agent-core/test/harness/assistant-text-cap.test.ts
Original file line number Diff line number Diff line change
@@ -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]/);
});
});
23 changes: 23 additions & 0 deletions packages/agent-core/test/tool-lifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down
2 changes: 1 addition & 1 deletion packages/coding-agent/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
6 changes: 6 additions & 0 deletions packages/coding-agent/docs/settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
8 changes: 8 additions & 0 deletions packages/coding-agent/schema/config.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -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`."
Expand Down Expand Up @@ -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,
Expand Down
Loading