{"record":{"id":"47284f1d72350b40","repo":"shareAI-lab/learn-claude-code","slug":"agent-cap-reached-agent-cap","errorCode":null,"errorMessage":"agent() cap reached ({AGENT_CAP})","messagePattern":"agent\\(\\) cap reached \\((.+?)\\)","errorType":"validation","errorClass":"WorkflowInputError","httpStatus":null,"severity":"error","filePath":"s16_workflow_runtime/code.py","lineNumber":426,"sourceCode":"\n    def progress_event(self, ptype, **data):\n        self.progress.append({\"type\": ptype, **data})\n        line = \" \".join(f\"{k}={v}\" for k, v in data.items())\n        print(f\"  progress   {ptype:<16} {line}\")\n\n\n# -- Workflow Primitives --\nclass ExecutionLimits:\n    \"\"\"Shared run-wide limits, including nested workflows.\"\"\"\n\n    def __init__(self):\n        self.agents = 0\n        self.semaphore = asyncio.Semaphore(CONCURRENCY)\n\n    def claim_agent(self):\n        self.agents += 1\n        if self.agents > AGENT_CAP:\n            raise WorkflowInputError(f\"agent() cap reached ({AGENT_CAP})\")\n\n\nclass ExecutionState:\n    \"\"\"Injected into the workflow script with the orchestration primitives.\"\"\"\n\n    def __init__(self, task, journal, runner, budget, args, depth=0, limits=None):\n        self.task = task\n        self.journal = journal\n        self.runner = runner\n        self.budget = budget\n        self.args = args\n        self._depth = depth\n        self._phase = None\n        self._phases_seen = set()\n        self._limits = limits or ExecutionLimits()\n\n    def phase(self, title):\n        \"\"\"Start a phase; subsequent agent()s group under it. Upsert: emitting the","sourceCodeStart":408,"sourceCodeEnd":444,"githubUrl":"https://github.com/shareAI-lab/learn-claude-code/blob/985456f4adea6f4df8fbad4112245dbd97444eae/s16_workflow_runtime/code.py#L408-L444","documentation":"ExecutionLimits.claim_agent increments a run-wide counter on every agent() invocation and raises WorkflowInputError once it exceeds AGENT_CAP (1000). The cap applies across nested workflows because the same ExecutionLimits instance is shared by depth, preventing runaway recursion or generate-loops from spawning unbounded agent calls. Note the counter is never decremented — it counts total invocations, not concurrency (which the semaphore caps separately).","triggerScenarios":"A loop whose condition never turns false calling agent() each iteration. Recursive sub-workflows that spawn agents before recursing. Legitimate very large fan-outs (map over >1000 items) hitting the hard ceiling.","commonSituations":"Termination bugs in goal-loop style workflows. Batch jobs sized above the cap after data growth. Recursion that passes the same limits object down through nested runs.","solutions":["Fix the loop/recursion termination — the cap is almost always a symptom of a runaway workflow, not the defect itself","For legitimate large fan-outs, batch the work: aggregate items so each agent() call handles many, staying under 1000 calls","Track usage via state and stop cleanly before the cap: guard with a counter of your own if you can run near 1000"],"exampleFix":"# before (runaway)\nwhile not done:\n    result = state.agent(\"check status\")  # 'done' never becomes True\n\n# after\nfor attempt in range(50):\n    result = state.agent(\"check status\")\n    if result[\"done\"]:\n        break","handlingStrategy":"validation","validationCode":"# inside the workflow, before fanning out:\nPLANNED = len(items)\nif state.limits.agents + PLANNED > AGENT_CAP:\n    # batch items so each agent() call covers several, or split into multiple runs\n    items = [items[i:i + 10] for i in range(0, len(items), 10)]","typeGuard":null,"tryCatchPattern":"try:\n    result = state.agent(prompt)\nexcept WorkflowInputError as exc:\n    if \"agent() cap reached\" not in str(exc):\n        raise\n    state.task.update(\"halted: agent cap reached — check loop termination\")\n    raise  # a runaway loop must fail loudly; do not swallow","preventionTips":["Bound every loop that calls agent() with an explicit iteration cap","Batch fan-outs so 1000 calls cover arbitrarily many items","Treat hitting AGENT_CAP as a termination bug to fix, not a limit to raise"],"tags":["workflow","limits","runaway","agents","recursion"],"backgroundTag":null,"analyzedSha":"985456f4adea6f4df8fbad4112245dbd97444eae","analyzedAt":"2026-08-14T22:02:26.028Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}