Repository navigation
fix(agents): bound runaway tool-call loops and subagent runs - #230
Conversation
Two containment failures found by an incident where a subagent session made 1,146 byte-identical failing tool calls over 86 minutes with nothing stopping it (the upstream gateway sealed a mid-stream error into a schema-valid tool_use with empty arguments; that is fixed separately). 1. A tool call rejected BEFORE execution (argument-validation failure, unknown tool, resolver error) produced an "immediate" outcome that reached neither agent-core tool hook, so the tool-loop detector -- which lives in the wrapped tool.execute -- never counted a single one. agent-core now reports those through afterToolCall (with a new executionStarted flag), and the embedded runner routes never-executed error results into the detector, blocking at the existing critical threshold. 2. Subagent runs took their wall-clock bound only from agents.defaults.subagents.runTimeoutSeconds. With that key unset the resolver returned 0, which resolveAgentTimeoutMs reads as the explicit "no timeout" sentinel -- so a fleet setting agents.defaults.timeoutSeconds: 900 still ran subagents with a ~24.8 day deadline. Subagents now inherit the general agent timeout; an explicit 0 still means no timeout.
Blocking a never-executed tool call does not bound the run. An E2E against a stub that replays the incident shape (a schema-valid tool_use for the registered `read` tool with empty arguments, which fails argument validation and never executes) measured 1,231 model turns on the parent commit: the detector fired correctly at call 21 and then served 1,210 more blocks, every one of them a full HTTP turn, until the run timeout killed it. Blocking tool EXECUTION does nothing about the token burn that made the production incident expensive -- only ending the RUN does. After three consecutive blocked calls the hook now returns `terminate: true` on the tool result. agent-core's `shouldTerminateToolBatch` clears `hasMoreToolCalls`, which drops out of the agent loop entirely -- no further model turn is requested (already asserted by agent-loop.test.ts "stops after a tool result only when the finalized result explicitly terminates"). Same E2E: 1,231 -> 23 turns, 155s -> 6s. Three, not one: the first block is the first time the model is told to stop, so it keeps two more turns to answer without the tool or call a different one. Any call that actually executed, or any non-error outcome, resets the streak, so a session that recovers is never cut -- a companion E2E where the model answers after two blocks delivers that answer untouched. The termination is not silent. Ending the run leaves the last assistant turn with a tool-call stop reason and a tool error, which routes to the terse "<tool> failed" badge and blames the tool for a run the agent stopped on purpose. The terminating result carries a fixed `TOOL_LOOP_RUN_ENDED_NOTICE`, and the reply builder lets that one reason past the raw-detail gate (the text is authored copy, never leaked tool output), so the user reads why. No new config key: the not-executed path already forces loop detection on for the same reason the unknown-tool guard is always on, and `loopDetection.enabled` defaulting to false is exactly why nothing caught the incident.
…change Making AfterToolCallContext.executionStarted required (edee679) broke two existing fixtures that construct the context or a tool result by hand. Neither was caught locally because `pnpm check:changed` delegates to a remote testbox that is unavailable here; `pnpm tsgo:test` is the local equivalent and was red on both commits of this branch. - agent-loop.test.ts: execTool.execute returned no `details`, which is a required field of AgentToolResult. Matches the house style used by the sibling fixtures in the same file (`details: {}`). - message-tool-terminal.test.ts: createAfterToolCallContext omitted the new flag. These fixtures all model a tool that ran, so `true` is the correct value, not a placeholder — noted in a comment, since the never-executed path has its own suite. `pnpm tsgo:test` now clean.
|
Claude encountered an error —— View job I'll analyze this and get back to you. |
There was a problem hiding this comment.
All reported issues were addressed across 15 files
Tip: instead of fixing issues one by one fix them all with cubic
Re-trigger cubic
… chain Address review feedback on the not-executed tool-loop containment path. The substantive fix: installNotExecutedToolLoopHook wrapped an inner afterToolCall hook (extension code) and derived both its control flow and its error verdict from that hook's result. Two ways that silently reopened the unbounded loop this change exists to close: - if the inner hook threw, the await propagated out before the detector was ever consulted, so the streak never advanced and no call was ever blocked; - if the inner hook relabelled a pre-execution failure as isError: false, the hook treated it as progress and reset the streak. Every kind:"immediate" outcome in the loop sets isError: true, so the decision now reads context (the loop's own pre-execution verdict) rather than the hook's rewrite, and the observation runs even when the hook threw. A throw is re-raised unchanged unless the call is blocked, where containment wins. Also replace the substring match on the run-ended notice with a structured marker: the terminating blocked result now carries details.code, which existing tool-result readers already lift into ToolErrorSummary.errorCode, so the raw-detail gate no longer opens for a tool error that merely quotes the notice. Remaining items are contract and coverage: - document that AfterToolCallContext.args is only schema-validated when executionStarted is true; - subagents no longer fall back to "no timeout" when runTimeoutSeconds is unset - they inherit agents.defaults.timeoutSeconds. Correct the docs and the stale spawn comment that still promised no timeout; - the not-executed suite pre-enabled loop detection, so it could not catch a regression in the force-enable that makes containment unconditional; - assert the executionStarted contract in the agent-loop tests; - rename a test whose name asserted the opposite of its body.
There was a problem hiding this comment.
All reported issues were addressed across 13 files (changes from recent commits).
Reply with feedback, questions, or to request a fix.
Fix all with cubic | Re-trigger cubic
…ed-code move The TOOL_LOOP_RUN_ENDED_NOTICE doc still described the notice text as the marker the reply builder keys on. Gating the raw-detail path on details.code / ToolErrorSummary.errorCode made that false and left it contradicting the TOOL_LOOP_RUN_ENDED_CODE comment two lines below. The notice is user-facing copy appended to the blocked reason; the code is the key. Also add the missing relative pronoun in a test title.
augusteo
left a comment
There was a problem hiding this comment.
Reviewed current head f5d2776 against boon. No blocking correctness, security, or scope issues found.\n\nVerified the pre-execution path now reaches afterToolCall with executionStarted=false, the detector uses the loop's own verdict even when an extension hook throws or rewrites it, three consecutive blocked calls terminate the run, and subagent timeout inheritance plus the explicit 0 no-timeout sentinel are covered by code, tests, and docs. The structured run-ended error code also avoids matching untrusted error text.\n\nCurrent-head checks show 120 success, 23 skipped, 1 neutral, and 4 cancelled superseded dispatch runs, with no failures; check-test-types, check-lint, core shards, security checks, and Cubic all pass. Local diff --check and syntax checks for 17 changed TypeScript files pass. Known limits in the PR are accepted: containment is for identical-argument loops, other detectors remain opt-in, and mixed parallel batches are not terminated unless every call is marked terminate.\n\nApproved.
…231) * chore(release): bump version 2026.6.11-boon.44 -> 2026.6.11-boon.45 Version-bump-only train carrying #230 (ENG-20206): bounds runaway tool-call loops and gives sub-agent runs a real wall-clock bound. - root package.json -> 2026.6.11-boon.45 - plugin package.json files synced via scripts/sync-plugin-versions.ts - changed npm-shrinkwrap.json files regenerated via scripts/generate-npm-shrinkwrap.mjs --changed - CHANGELOG.md section for boon.45 No plugin source changed between boon.44 and boon.45; a gateway roll delivers the whole release. * chore(release): CHANGELOG — varying-arg loops are bounded only under a finite run timeout Review caught that "bounded by the run timeout alone" is false when an explicit runTimeoutSeconds: 0 is configured — there is no run timeout then, so that case is unbounded. State the condition rather than imply a bound that a legal config removes.
…35 sync CI on PR #281 caught three real bugs that review alone missed, plus one new production CVE batch: - pdf-tool.ts: upstream added early pages-validation (parse and throw before loading any PDF) as a new behavior in 6.35. My earlier conflict resolution treated the resulting duplicate `pageNumbers` declaration as dead code and deleted the early one, silently reverting to late (post-load) validation. Moved the single declaration back to its early position; the getExtractions closure now captures it instead of redeclaring it. - agent-loop.ts: upstream's `executed.executionStarted && config.afterToolCall` guard assumes never-executed outcomes never reach this function (upstream's own call graph bypasses it for the immediate case). Boon's call graph does not bypass it — finalizeImmediateToolCall always routes through here, and the loop-detector safety fix from #230 depends on afterToolCall seeing never-executed calls with `executionStarted: false`. Adopting upstream's guard unconditionally broke that: it skipped afterToolCall for exactly the calls the loop detector needs to see. Reverted to boon's original unconditional `if (config.afterToolCall)`. - ci-workflow-guards.test.ts: a new upstream test iterated testbox CI workflow paths the fork has never carried (ci-check-testbox.yml, ci-build-artifacts-testbox.yml, documented as removed since fork setup). Narrowed it to the one workflow the fork still has, matching the existing convention elsewhere in this file. security-fast found 6 new high/critical advisories in the merged dependency tree (GHSA-v5rq-49vh-5v5c argv-parser unsafe-editor detection, GHSA-x6jw-m9v5-85vh/GHSA-g4wm-2vf7-vfgr/GHSA-858h-whjf-mvg5 simple-git command execution, GHSA-jqcg-44mw-7w3h proxy-addr IP spoofing, GHSA-68fv-2mgg-jv7q source-map-js DoS). Pinned all four to their fixed versions in pnpm-workspace.yaml. Regenerating the lockfile surfaced a known recurring npm/ pnpm resolver mismatch under @sentry/node (npm picks @opentelemetry/resources and @opentelemetry/sdk-trace-base 2.12.0, pnpm locks 2.11.0); added the same class of temporary npm-only nested override used for this before (see 2026.6.34-boon.4's changelog entry) to package.json. Also regenerated the plugin-sdk-surface budgets and API baseline (docs/.generated/plugin-sdk-api-baseline.*) against the actual merged tree, replacing the placeholder values called out as a follow-up in the PR description. Validation: pnpm-audit-prod clean; tsgo:core clean; the three directly affected test files (pdf-tool.test.ts, agent-loop.test.ts, ci-workflow-guards.test.ts, plugin-sdk-surface-report.test.ts) all pass; deps:shrinkwrap:generate --check clean. Co-Authored-By: Claude Sonnet 5 <[email protected]>
Summary
Three independent containment gaps let a single agent run repeat one failing tool call 1,146 times over 86 minutes without anything stopping it. Each is small; together they meant nothing bounded the run.
Measured end to end, same stub and prompt, before vs after: 1,231 HTTP turns → 23. Wall clock 155s → 6s.
The three gaps
1. A subagent run had no wall-clock bound at all.
resolveConfiguredSubagentRunTimeoutSecondsread onlyagents.defaults.subagents.runTimeoutSecondsand fell back to0.resolveAgentTimeoutMstreats0as the explicit no timeout sentinel (MAX_TIMER_TIMEOUT_MS, ≈24.85 days), so the abort timer was armed correctly — just 24 days out.Any deployment setting
agents.defaults.timeoutSecondsand expecting it to bound subagents was wrong. It never applied to them. The fallback is documented as deliberate legacy behaviour (subagent-spawn.ts), which is exactly why it went unnoticed.Fixed in the shared resolver rather than at the call site, because
acp-spawn.tsis a sibling caller with the identical defect — patching only the observed path would have left ACP subagents unbounded. An explicitsubagents.runTimeoutSeconds: 0still means no timeout.2. A tool call that never executed was invisible to loop detection.
The detector wraps
tool.execute. A schema-validation failure meansexecutenever runs, so bothdetectToolCallLoopandrecordToolCallare skipped — the call is recorded nowhere. No detector could ever count it. The same blind spot swallowed unknown-tool-name and tool-resolution failures.prepareToolCall'simmediateoutcomes also bypassedfinalizeExecutedToolCall, the sole caller ofconfig.afterToolCall, so a never-executed call reached neither hook.Fixed by routing immediate outcomes through the existing
finalizeExecutedToolCall(finalizeImmediateToolCall), plus a newAfterToolCallContext.executionStartedflag. That flag is load-bearing, not cosmetic: without it a consumer cannot distinguish a never-executed outcome from an executed one and would double-record every successful call, corrupting the detector's own history.Detection is force-enabled on the never-executed path only, following this repo's existing precedent —
resolveUnknownToolGuardThresholdkeeps the provider unknown-tool guard on regardless oftools.loopDetection.enabled, because an unregistered tool "is an objective dead end". A call that never executed made objectively zero progress by the same argument. Adding a knob that defaults off is precisely what let this through.3. Blocking a call did not end the run — and this is the one that mattered.
Gaps 1 and 2 alone were measured as a placebo on the cost axis. With the detector firing correctly at its critical threshold and blocking 1,211 calls, the run still spent 1,231 HTTP turns versus 1,231 unfixed. A blocked call is still a model turn. Request bodies grew faster with the fix, because the block message is longer than the validation error it replaced.
So: after a bounded streak of consecutive blocked, never-executed calls, the run now terminates via the existing
terminatemechanism.Test plan
Every behaviour was red first; verbatim failures are in the commits.
23 = the detector's existing
criticalThreshold(20) + a streak bound of 3.The 3 is not the dominant number. Twenty of those 23 turns are the pre-existing threshold and move with
tools.loopDetection.criticalThreshold. If 23 turns is still too expensive at large context sizes, that 20 is the lever, not the 3.A recoverable session is not killed, proven rather than argued. A dedicated E2E scenario emits the invalid call 22 times — 20 validation failures, then 2 blocks — then answers normally on turn 23. The run delivered its answer and was not cut. The streak resets on any progress: a call that actually executed, a non-error outcome, or a different call. You must already be 20 byte-identical never-executed failures deep before the first block exists.
Why the user-facing copy is half this change
Bare
terminate: truewas measured first and produced⚠️ 📖 Read failedwith a Retry button — blaming the tool for a run the agent ended deliberately, and inviting the user to re-trigger the whole burn. The run now states the reason plainly instead.Known limits, stated rather than implied
shouldTerminateToolBatchrequires every call in a batch to setterminate. The observed shape is one call per turn, so it fires. A provider emitting a parallel batch of[invalid, valid]indefinitely would not be bounded — correct semantics, since there is real progress, but a genuine residual hole.sessionKeynorsessionIdnever reaches the detector. Pre-existing, untouched.The trigger for the original incident was upstream: a gateway sealing a mid-stream failure into a schema-valid success carrying a tool call with empty arguments. That is fixed separately. These changes hold regardless — the client should bound itself whether or not any particular server is well behaved, and the two deploy independently.
Summary by cubic
Fixes the containment gaps behind ENG-20206, where a subagent made 1,146 identical failing tool calls over 86 minutes with nothing stopping it. Measured end to end on the incident-shaped stub: 1,231 turns/155s → 23 turns/6s.
Bug Fixes
tool.execute(validation failure, unknown tool) now reachafterToolCallwithexecutionStarted: false, so the loop detector counts them.agents.defaults.timeoutSecondsinstead of running unbounded whenagents.defaults.subagents.runTimeoutSecondsis unset; an explicitrunTimeoutSeconds: 0still means no timeout.tools.loopDetection.enabled, since a blocked call made zero progress.tool_loop_run_endedcode rather than the notice text, so the generic "tool failed" badge doesn't blame the tool.Written for commit f5d2776. Summary will update on new commits.