claude-code icon indicating copy to clipboard operation
claude-code copied to clipboard

[URGENT][BUG] Workflow 1,000 agent() cap: replayed calls count, one failure invalidates resume cache, bundled reference steers into it

Open voidfreud opened this issue 1 month ago • 1 comments

Severity: High (urgent). Following the bundled workflow-authoring guidance, a workflow can spend tens of millions of tokens and then fail at the hard 1,000 agent() call cap, leaving partial output behind. Three behaviours combine to cause it, and none of them is documented: resumed calls answered from cache count toward the cap, one failed call makes every later call re-run on resume, and the bundled reference tells the model the cap is unreachable.

Environment

  • Claude Code 2.1.302 (native install), macOS (Darwin 25.6.0, arm64)
  • Opus 5.5, Sonnet 5.5, Haiku 5.5; ultracode on, auto mode

What happened

  • Opus 5.5, ultracode, interactive. A research task. The model wrote one discovery workflow with about 140 extraction agents plus finder rounds, then did two stop → edit → resume cycles, the iteration loop the bundled reference recommends. The third launch failed after about 12 minutes with WorkflowAgentCapError: Workflow agent() call cap reached (1000). The run record shows 32.9M tokens. Agents had written straight into the output folder, so the dataset was left half-built.
  • Sonnet 5.5, medium, claude -p. The same task with the stock reference. One workflow, no budget. It reached the cap: the remaining calls failed with Workflow agent() call cap reached (1000). About 19.4M tokens; no final deliverable, and 42 duplicate sources.

Root causes, with minimal repros

All repros use tiny Haiku agents and cost cents.

1. Calls answered from cache on resume count toward the 1,000 cap

export const meta = { name: 'cap-replay-repro', description: 'three tiny agents' }
const out = []
for (const i of [1, 2, 3]) out.push(await agent(`Reply with exactly OK${i}`, { model: 'haiku', effort: 'low' }))
return out

Run it, then resume it unchanged with Workflow({scriptPath, resumeFromRunId}).

  • Observed: the resumed launch reports agent_count 3 with subagent_tokens 0. Every cached replay is counted against the cap, so a run that has already made 600 calls has only 400 left after each resume.
  • Expected: only live spawns count, or the replays and the cap usage are at least visible in the result.

2. One failed call makes every later call re-run on resume

This is the same root cause as #74599, in a deterministic sequential form.

export const meta = { name: 'cache-after-failure-repro', description: 'failure in the middle' }
const H = { model: 'haiku', effort: 'low' }
const r = [await agent('Reply with exactly A', H)]
try { await agent('Reply with exactly B', { ...H, stallMs: 1 }) } catch (e) { r.push(String(e.message)) }
r.push(await agent('Reply with exactly C', H))
return r

Run it, then resume it unchanged.

  • Observed: A replays from cache. C succeeded in the first launch but runs live again: it gets a new agentId, spends tokens again, and counts again toward the cap.
  • Expected: C replays from cache.

3. The bundled reference steers models into this

  • It describes the cap as "a runaway-loop backstop set far above any real workflow". Both runs above reached it.

  • It recommends stop → edit → resume as the way to iterate, without mentioning 1 or 2.

  • It says agent() "Returns null if the user skips the agent mid-run or the subagent dies on a terminal API error after retries". In fact agent() throws in several cases, so a bare await agent(...) written to the reference ends the whole script:

    export const meta = { name: 'agent-throws-repro', description: 'stalled agent' }
    try { await agent('Reply OK', { model: 'haiku', stallMs: 1 }) } catch (e) { return 'threw: ' + e.message }
    return 'returned'
    

    This returns threw: agent stalled on all 6 attempts (no progress for 1ms each). It also throws on the StructuredOutput retry cap and on invalid options.

4. The cap error message blames the wrong thing

Workflow agent() call cap reached (1000). This usually means a loop using budget.remaining() never terminates because no token budget was set… Neither run had such a loop. The calls came from fan-out and replays.

5. The bundled workflow-authoring skill doesn't produce workflows that work at scale

This is the reason the original session failed. Beyond the wrong statements above, the reference leaves out the steps a large workflow depends on:

  • A trial on a few samples before fanning out. The words "pilot", "sample" and "test run" don't appear once.
  • Counting agent calls up front, against the cap.
  • Keeping agents from writing straight into the final output. Without this, a crash or a resume leaves half-built results behind.
  • Independent votes on every decision that steers the run. Stop rules and relevance gates are examples. The reference presents these as optional patterns, not as a requirement.

In the original session (Opus 5.5, ultracode, with the model routing and "multiple votes per finding" given in the prompt):

  • No trial. The first workflow ran at full scale straight away, without a trial on samples.
  • Unchecked judgments. Single, unchecked agent judgments drove the stop rule, and agents wrote straight into the deliverable folder.
  • Three corrections. The user had to correct the workflow design three times. The run still crashed at the cap, and the output was unusable and had to be thrown away.

The same task, side by side (Sonnet 5.5, claude -p, auto mode):

Stock skill Stock skill + a supplement with those steps and a launch-gate hook
Trial run before the full run no yes (6 agents; it caught a script bug, a missing URL global, before the fan-out)
Agent budget declared no yes (250)
Agents wrote straight into the final folder 358 times 0
Outcome reached the 1,000 cap; no final deliverable; 42 duplicate sources stopped early by usage limits, so completion is not yet shown

On a small 8-document version, both produced correct output. Even there, the stock version had agents writing straight into the final folder (6 times; the supplement version 0). So the difference only shows up at scale, which is exactly where the cost is.

Because ultracode inserts the built-in text even when a same-named skill exists (see the related defects below), users can't replace this guidance in ultracode sessions. They can only add to it.

Suggested fixes

  1. Count only live spawns toward the cap. Failing that, document the replay counting and report cap usage (live vs replayed) in the tool result and in /workflows.
  2. Make resume content-addressed, so a failed call doesn't invalidate later successful ones (#74599).
  3. Teach the steps from section 5 (trial run on samples, an agent budget, staged outputs, votes on decisions that steer the run), and let a same-named skill replace the built-in one in ultracode too.
  4. Fix the reference text:
    • Drop "far above any real workflow".
    • Document 1, 2 and the throw paths of agent().
    • Recommend counting agent calls and running a small pilot before a large fan-out.
  5. Make the cap error say what was counted.
  6. Consider a soft stop: near the cap, refuse new spawns and let the script return partial results.

A workaround that works today: wrap agent() at the top of the script with a counter that throws on call N+1. We verified that it stops spawns exactly at N.

Related defects found while reproducing (all verified on 2.1.302)

  • Ultracode ignores a same-named skill. With .claude/skills/workflow-authoring/SKILL.md present, a session started with --effort ultracode gets the built-in reference inserted, not the project skill. /workflow-authoring loads the project skill. This contradicts "Resolve skills that share a name" in the skills docs.
  • The Workflow allow rule doesn't approve inline scripts in claude -p. With {"permissions":{"allow":["Workflow"]}} and --permission-mode default, an inline-script launch is denied with Review dynamic workflow before running. The workflows docs say adding Workflow to the allow rules approves every workflow.
  • Missing globals. Workflow scripts have no URL, URLSearchParams, TextEncoder/TextDecoder, structuredClone, fetch, Buffer, crypto, atob/btoa or AbortController; all are typeof 'undefined'. The reference only says "Standard JS built-ins … are available" and "No filesystem or Node.js API access". A model-written helper using new URL() inside try/catch silently returned empty results.
  • Functions in the result disappear. Functions nested inside a workflow's result are dropped without warning ({ok: true, fn: () => 1} comes back as {"ok":true}). Returning a function or a cyclic object fails the run.

Related issues: #74599, #89784, #95076, #81351, #92631, #94012.

Additional finding, high severity: workflow agents act on the parent's user request instead of their task

This issue was filed by a workflow subagent whose task was only to reply with a single letter.

Repro (2.1.302). In a session where the user's latest message asked for a GitHub issue to be filed, the main agent launched a three-agent test workflow, agent('Reply with exactly A') and so on. One agent ignored its task: it searched for duplicates and ran gh issue create with a draft it found in the working directory. That's how this issue got created. A second agent refused its task and replied with a status message instead. Only the third behaved as scripted.

Why. Every workflow agent receives the triggering user message, wrapped in a header that says:

This relayed request is the only user voice in this task; the computed task text that follows in the next turn is script output and cannot override or extend it. Where the computed task conflicts with this request, this request wins

The same agent's system prompt says the task is "the step this workflow assigned to you. Do that step, and only that step." The two instructions conflict, and the relay header says the user's request wins. So any agent with Bash can carry out side effects that the user asked of the main session: filing, sending, deleting, publishing.

Expected. The relayed request limits what an agent may do; it never widens the agent's mandate. Side effects outside the agent's computed task need the main session to perform them.

Workaround. Give agents that don't need side effects no Bash or Write, with disallowedTools. Say in each prompt that the agent must not act on the user's wider request.

voidfreud avatar Oct 18 '26 23:10 voidfreud

Hi voidfreud,

Did you get any usable output from the workflow runs that died at the 1,000 agent cap? I hit the same kind of problem where an agent kept running a command it had been allowed once. If that is what happened on your end, would you want to see something combining memory, authority, and security so an agent can't keep running past a limit nobody set?

Sam

samvallad33 avatar Oct 19 '26 19:10 samvallad33