6. Executing Tools: Validation, Hooks, Concurrency, and Streaming Execution
Status: written. Reverse-engineered from the Claude Code 2.1.88 source snapshot (see the Prologue (
prologue-how-to-read-a-1900-file-agent.md) for snapshot caveats).Layer: Layer 2 (The Agent Engine) Prerequisites: Chapter 01 (
utils/generators.tsall()), Chapter 02 (Tool.ts,ToolUseContext,isConcurrencySafe,maxResultSizeChars), Chapter 03 (utils/messages.tsnormalizeMessagesForAPI,tool_use/tool_resultpairing), Chapter 04 (prompt-cache prefix stability), Chapter 05 (queryModelWithStreaming,AssistantMessage/ToolUseBlock[],FallbackTriggeredError) Primary Source Files:•
services/tools/toolExecution.ts— single-tool 8-step lifecycle, streaming progress bridge, error classification, and telemetry (1,745 lines)•
services/tools/toolHooks.ts—PreToolUse/PostToolUse/PostToolUseFailureadapters and hook-vs-rule permission arbitration (650 lines)•
services/tools/toolOrchestration.ts— fail-closed concurrency partitioning,all()batching, and block-ordercontextModifierreplay (188 lines)•
services/tools/StreamingToolExecutor.ts— mid-stream execution overlapping SSE chunks, 3-levelAbortControllertree, and fallbackdiscard()(530 lines)•
utils/toolResultStorage.ts— two-stage<persisted-output>spill-to-disk and prompt-cache-safeContentReplacementStatebudgeting (1,040 lines)
Why This Layer Exists
Once Chapter 05's queryModelWithStreaming() yields AssistantMessage records containing ToolUseBlock[], executing them looks like a one-liner: await tool.call(block.input). In production, that one-liner breaks in five ways:
- Untrusted inputs: Models invoke deprecated aliases, guess deferred-tool schemas (stringifying arrays and booleans), forge internal fields, or send unexpanded
~paths that evade hook allowlists. - Policy bypasses: User
PreToolUsehooks can approve or rewrite calls, yet hookallowmust never bypasssettings.jsondeny/askrules or protected-path safety guards. - Throughput vs. determinism: Serial reads waste seconds; concurrent edits corrupt files; applying
contextModifiercallbacks in completion order creates timing races. - Streaming overlap & blast radius: Launching tools mid-stream hides latency, but a failed
Bashcommand must cancel sibling commands without killing the turn, a user permission rejection must abort the turn, and a streaming or model fallback must discard orphaned work. - Context blowup vs. prompt cache: Giant outputs overflow context, spilling
FileReadToolcreates an infiniteRead→ file →Readloop, and recomputing aggregate budgets on older turns mutates wire history and busts the prompt cache.
These five files (4,153 lines) solve all five problems.
1. The Single-Tool Lifecycle: From tool_use to tool_result
The Problem
One tool invocation spans schema validation, hooks, permissions, and arbitrary I/O while streaming live UI progress and guaranteeing every exit path emits a paired tool_result (Chapter 03).
The Real Implementation (services/tools/toolExecution.ts)
Every call enters runToolUse() (services/tools/toolExecution.ts:337-490) and walks an exact 8-step pipeline:
- Lookup & alias-only fallback (
services/tools/toolExecution.ts:343-411). SearchestoolUseContext.options.toolsviafindToolByName()(Tool.ts:358-360). If absent, checksgetAllBaseTools()only whenfallbackTool.aliases?.includes(toolName)(services/tools/toolExecution.ts:350-356), rescuing deprecated names likeKillShell(alias onTaskStopToolattools/TaskStopTool/TaskStopTool.ts:44) without bypassingdisallowedToolsfor primary tool names. Unknown tools emit anis_error: true<tool_use_error>and return. Deferred tools remain inoptions.toolsand pass Step 1; missing schemas surface in Step 4. - Pre-execution abort check (
services/tools/toolExecution.ts:413-453). IftoolUseContext.abortController.signal.abortedis set, yieldscreateToolResultStopMessage()(utils/messages.ts:622-631) carryingwithMemoryCorrectionHint(CANCEL_MESSAGE)(services/tools/toolExecution.ts:444, appending a memory hint when auto-memory and GrowthBook'tengu_amber_prism'are active atutils/messages.ts:185-193) and returns. - Push-to-pull progress bridge (
services/tools/toolExecution.ts:455-570).checkPermissionsAndCallTool()(services/tools/toolExecution.ts:599-1745) returnsPromise<MessageUpdateLazy[]>, while hooks andtool.call()push live progress viaonToolProgress.streamedCheckPermissionsAndCallTool()(services/tools/toolExecution.ts:492-570) bridges them withStream<MessageUpdateLazy>(utils/stream.ts:1-76), enqueueing eachProgressMessageimmediately (services/tools/toolExecution.ts:549-555) before flushing final results in.then()and closing in.finally(). An outertry/catch(services/tools/toolExecution.ts:414-489) catches unexpected escapes into<tool_use_error>. - Validation, prefetch & input isolation (
services/tools/toolExecution.ts:614-793). - Zod parse + schema hint (
services/tools/toolExecution.ts:615-680):tool.inputSchema.safeParse(input)formats failures viaformatZodValidationError()(utils/toolErrors.ts:66-132) and callsbuildSchemaNotSentHint()(services/tools/toolExecution.ts:578-597): whenisToolSearchEnabledOptimistic()(utils/toolSearch.ts:270-320;CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETASatutils/toolSearch.ts:181insidegetToolSearchMode()atutils/toolSearch.ts:172-198,ENABLE_TOOL_SEARCH, andANTHROPIC_BASE_URLparsed inisFirstPartyAnthropicBaseUrl()atutils/model/providers.ts:25-40),isToolSearchToolAvailable(), andisDeferredTool()hold and the tool is absent fromextractDiscoveredToolNames(messages), it tells the model to callToolSearchwithselect:<tool.name>and retry. - Semantic validation & Bash prefetch (
services/tools/toolExecution.ts:683-752): Runstool.validateInput?.()before hooks/permissions, then callsstartSpeculativeClassifierCheck()(tools/BashTool/bashPermissions.ts:1497-1527) forBashcommands so allow-classification can overlapPreToolUsehooks—gated onisClassifierPermissionsEnabled(), an ANT-ONLY stub hardcoded toreturn falsein this external checkout (utils/permissions/bashClassifier.ts:1,utils/permissions/bashClassifier.ts:24-26, making the prefetch a no-op here), and explicitly skipped whenfeature('TRANSCRIPT_CLASSIFIER') && toolPermissionContext.mode === 'auto'ortoolPermissionContext.mode === 'bypassPermissions'(tools/BashTool/bashPermissions.ts:1504-1507). _simulatedSedEditstrip &backfillObservableInputclone (services/tools/toolExecution.ts:761-793): First strips any model-supplied_simulatedSedEditfield fromBashinputs (services/tools/toolExecution.ts:761-773) as defense-in-depth against schema regressions. Then isolates observer normalization on a shallow clone:
// services/tools/toolExecution.ts:775-793// Backfill legacy/derived fields on a shallow clone so hooks/canUseTool see// them without affecting tool.call(). SendMessageTool adds fields; file// tools overwrite file_path with expandPath — that mutation must not reach// call() because tool results embed the input path verbatim (e.g. "File// created successfully at: {path}"), and changing it alters the serialized// transcript and VCR fixture hashes. If a hook/permission later returns a// fresh updatedInput, callInput converges on it below — that replacement// is intentional and should reach call().let callInput = processedInputconst backfilledClone = tool.backfillObservableInput && typeof processedInput === 'object' && processedInput !== null ? ({ ...processedInput } as typeof processedInput) : nullif (backfilledClone) { tool.backfillObservableInput!(backfilledClone as Record<string, unknown>) processedInput = backfilledClone} File tools expand ~/relative paths in backfillObservableInput() (e.g., tools/FileReadTool/FileReadTool.ts:388-394) so hook allowlists see canonical paths, while callInput stays pinned to the model's input. Before tool.call() (services/tools/toolExecution.ts:1181-1205), even if a hook/permission flow returns a fresh object whose file_path still matches backfilledClone.file_path, Claude Code restores the model's original file_path to keep transcript and VCR fixture hashes stable while keeping other hook edits.
PreToolUsehooks (services/tools/toolExecution.ts:795-891). RunsrunPreToolUseHooks()(Section 2), logs debug warnings pastSLOW_PHASE_LOG_THRESHOLD_MS(2000ms atservices/tools/toolExecution.ts:137), and—gated byprocess.env.USER_TYPE === 'ant'—emits an inline wall-clock timing summary aboveHOOK_TIMING_DISPLAY_THRESHOLD_MS(500ms atservices/tools/toolExecution.ts:134,services/tools/toolExecution.ts:874-891) since hooks run in parallel.- Permission reconciliation &
canUseTool(services/tools/toolExecution.ts:909-1132). Starts OTel spans (attachingprocessedInputJSON only underisBetaTracingEnabled()—env varsENABLE_BETA_TRACING_DETAILED,BETA_TRACING_ENDPOINT, and forprocess.env.USER_TYPE !== 'ant', SDK/non-interactive mode viagetIsNonInteractiveSession()or GrowthBook'tengu_trace_lantern'atutils/telemetry/betaSessionTracing.ts:78-98), callsresolveHookPermissionDecision()(Section 2), and restricts the>= 2000ms slow-permission log topermissionMode === 'auto'(services/tools/toolExecution.ts:937-946) to ignore human think time. On denial (services/tools/toolExecution.ts:995-1104), emits a text-onlyis_error: truetool_resultwith any user-pasted rejection images placed as top-level sibling blocks (services/tools/toolExecution.ts:1029-1062), because the Anthropic API rejects non-text blocks insideis_error: truetool_results. tool.call(), single pre-mapping & Stage A spill (services/tools/toolExecution.ts:1134-1479). Guards OTeltoolParametersbehindisToolDetailsLoggingEnabled()(OTEL_LOG_TOOL_DETAILSatservices/analytics/metadata.ts:86-88), startsstartSessionActivity('tool_exec'), runstool.call(), and mapsresult.dataonce viamapToolResultToToolResultBlockParam()(services/tools/toolExecution.ts:1292-1301) for telemetry size measurement and reuse. Non-MCP tools immediately calladdToolResult(toolOutput, mappedToolResultBlock)(services/tools/toolExecution.ts:1403-1479), invoking Stage AprocessPreMappedToolResultBlock(), appendingacceptFeedback/images, trimmingtoolUseResult(unlesspreserveToolUseResults) andmcpMetafor subagents (services/tools/toolExecution.ts:1460-1464), and wrappingresult.contextModifier.PostToolUsevs.PostToolUseFailurehooks (services/tools/toolExecution.ts:1481-1744). Success runsrunPostToolUseHooks()(with the sameUSER_TYPE === 'ant'> 500ms wall-clock summary atservices/tools/toolExecution.ts:1546-1563), appendsresult.newMessages, and emitshook_stopped_continuationifPreToolUsesetshouldPreventContinuation(services/tools/toolExecution.ts:1572-1582). Exceptions insidetool.call()'stryentercatch (error)(services/tools/toolExecution.ts:1589-1737), transitionMcpAuthErrorclients to'needs-auth', classify non-abort errors viaclassifyToolError(), and runrunPostToolUseFailureHooks().finally(services/tools/toolExecution.ts:1738-1744) always callsstopSessionActivity('tool_exec')and deletestoolUseContext.toolDecisions?.delete(toolUseID).
Hidden Invariants & Failure Modes
- Minification-safe error classification (
services/tools/toolExecution.ts:150-171): Bundled builds mangleerror.constructor.nameto 3-char tokens ("nJT").classifyToolError()checksTelemetrySafeError, then Node errno codes (Error:ENOENT), and acceptserror.nameonly whenerror.name.length > 3(services/tools/toolExecution.ts:165), else'Error'or'UnknownError'. - Exact
runPostToolUseFailureHooksboundary: Fires strictly ontool.call()-region exceptions (services/tools/toolExecution.ts:1589-1737)—runtime errors (isInterrupt: false, includingShellErrorandMcpAuthError) and mid-executionAbortError(isInterrupt: true). Never fires on unknown tools (services/tools/toolExecution.ts:369-411), pre-execution aborts (services/tools/toolExecution.ts:415-453), Zod/validateInputfailures (services/tools/toolExecution.ts:615-733),PreToolUse{ type: 'stop' }(services/tools/toolExecution.ts:848-860), or permission denials (services/tools/toolExecution.ts:995-1104). Note thatcatchreturns a fresh array[{ message: createUserMessage(...) }, ...hookMessages](services/tools/toolExecution.ts:1715-1737), dropping earlierPreToolUseattachments inresultingMessages.
2. Hook Arbitration & Permission Handoff
The Problem
Hooks allow custom linters, secret scanners, and input rewriters, yet an overly permissive PreToolUse hook returning allow must never become a privilege-escalation vector that overrides settings.json deny rules, ask rules, or sensitive-path guards (.git/, .claude/, .vscode/).
The Real Implementation (services/tools/toolHooks.ts)
services/tools/toolHooks.ts bridges utils/hooks.ts into four typed lifecycle adapters (containing zero direct feature(), USER_TYPE, GrowthBook, or env-var gates):
runPreToolUseHooks()(services/tools/toolHooks.ts:435-650): TranslatesexecutePreToolHooks()(utils/hooks.ts:3394-3436) results into typed events:blockingError(exit code 2 or JSONdecision: "block") →{ type: 'hookPermissionResult', hookPermissionResult: { behavior: 'deny', ... } }(services/tools/toolHooks.ts:481-498).permissionBehavior('allow' | 'ask' | 'deny') →hookPermissionResult(withupdatedInputfor'allow'/'ask').- Passthrough
updatedInputwithoutpermissionBehavior→{ type: 'hookUpdatedInput' }(services/tools/toolHooks.ts:558-563), updatingprocessedInputbefore permission evaluation. additionalContexts→hook_additional_context;preventContinuation/stopReason→ deferred post-call stop flag; signal abort or thrown hook error →hook_cancelled/hook_error_during_execution+{ type: 'stop' }(services/tools/toolHooks.ts:582-648), halting beforecanUseTool.resolveHookPermissionDecision()(services/tools/toolHooks.ts:332-433): Arbitrates hook permission decisions against rule-based permissions andcanUseTool:
// services/tools/toolHooks.ts:347-406if (hookPermissionResult?.behavior === 'allow') { const hookInput = hookPermissionResult.updatedInput ?? input // ... const interactionSatisfied = requiresInteraction && hookPermissionResult.updatedInput !== undefined if ((requiresInteraction && !interactionSatisfied) || requireCanUseTool) { // ... } // Hook allow skips the interactive prompt, but deny/ask rules still apply. const ruleCheck = await checkRuleBasedPermissions( tool, hookInput, toolUseContext, ) if (ruleCheck === null) { // ... return { decision: hookPermissionResult, input: hookInput } } if (ruleCheck.behavior === 'deny') { // ... return { decision: ruleCheck, input: hookInput } } // ask rule — dialog required despite hook approval // ...}'allow': Only skips the interactive prompt whenrequiresUserInteraction()is false (or satisfied viaupdatedInput),requireCanUseToolis false, andcheckRuleBasedPermissions()(utils/permissions/permissions.ts:1071-1155) returnsnull. A'deny'rule overrides immediately; an'ask'rule orsafetyChecksensitive-path guard forcescanUseTool().'deny'(services/tools/toolHooks.ts:408-411): Short-circuitscanUseTool().'ask'orundefined(services/tools/toolHooks.ts:413-432): PassesforceDecisionon'ask'socanUseTool()prompts with the hook's message even when allow rules or modes would auto-approve.
- Auto-mode
PermissionDeniedhooks (services/tools/toolExecution.ts:1075-1101): Behind compile-timefeature('TRANSCRIPT_CLASSIFIER'), when theauto-modeclassifier denies a tool,executePermissionDeniedHooks()runs; any{ retry: true }appends anisMeta: trueretry hint. runPostToolUseHooks()&runPostToolUseFailureHooks()(services/tools/toolHooks.ts:39-319):- Both fix
#31301: JSON{ decision: "block" }hooks yield both{ blockingError }and{ message: hook_blocking_error }, so both adapters drophook_blocking_errorfromresult.messageand emit it once fromresult.blockingError(services/tools/toolHooks.ts:90-115,services/tools/toolHooks.ts:245-267). - On
preventContinuation,runPostToolUseHooks()yieldshook_stopped_continuationand returns early (services/tools/toolHooks.ts:118-130). - MCP-only
updatedMCPToolOutput(services/tools/toolHooks.ts:146-151): Explains the// TOOD(hackyon)split atservices/tools/toolExecution.ts:1476: non-MCP tools runaddToolResult(toolOutput, mappedToolResultBlock)beforePostToolUse(reusingprocessPreMappedToolResultBlock()), while MCP tools runPostToolUsefirst—buffering hook messages inhookResults(services/tools/toolExecution.ts:1498-1513)—and then calladdToolResult(toolOutput)(services/tools/toolExecution.ts:1540-1542) soprocessToolResultBlock()maps the possibly rewritten output from scratch before flushinghookResults(services/tools/toolExecution.ts:1585-1587).
Explicit Forward Seams
- Chapter 11:
CanUseToolFn(hooks/useCanUseTool.tsx:27),PermissionDecision/PermissionResult(types/permissions.ts:174-324), andcheckRuleBasedPermissions()steps 1a–1d and 1f–1g (utils/permissions/permissions.ts:1069-1156; step 1e is pre-checked byresolveHookPermissionDecision()). - Chapter 13 (The Hook System): Hook execution backends (
utils/hooks.ts:3394-3562), multi-hookdeny > ask > allowaggregation (utils/hooks.ts:2820-2847), andsuppressOutputfiltering (utils/hooks.ts:2557-2596).
3. Batch Orchestration: Partitioning Concurrency & Context Modifiers
The Problem
An assistant turn emitting [Read1, Read2, Edit1, Read3, Bash1, Bash2] needs parallel reads without overlapping mutations. Worse, racing concurrent async generators delivers updates in completion order—eagerly applying contextModifier callbacks (Tool.ts:329-330) as tools finish would make ToolUseContext depend on I/O timing.
The Real Implementation (services/tools/toolOrchestration.ts)
- Fail-closed partitioning (
partitionToolCalls(),services/tools/toolOrchestration.ts:91-116):
// services/tools/toolOrchestration.ts:91-116function partitionToolCalls( toolUseMessages: ToolUseBlock[], toolUseContext: ToolUseContext,): Batch[] { return toolUseMessages.reduce((acc: Batch[], toolUse) => { const tool = findToolByName(toolUseContext.options.tools, toolUse.name) const parsedInput = tool?.inputSchema.safeParse(toolUse.input) const isConcurrencySafe = parsedInput?.success ? (() => { try { return Boolean(tool?.isConcurrencySafe(parsedInput.data)) } catch { // If isConcurrencySafe throws (e.g., due to shell-quote parse failure), // treat as not concurrency-safe to be conservative return false } })() : false if (isConcurrencySafe && acc[acc.length - 1]?.isConcurrencySafe) { acc[acc.length - 1]!.blocks.push(toolUse) } else { acc.push({ isConcurrencySafe, blocks: [toolUse] }) } return acc }, [])} Unknown tools, invalid Zod inputs, and throwing isConcurrencySafe() predicates all fail closed to false, isolating each unsafe call into a singleton serial batch while coalescing contiguous safe calls and preserving relative order ([concurrent(Read1, Read2), serial(Edit1), concurrent(Read3), serial(Bash1), serial(Bash2)]).
- Bounded concurrency via
all()(services/tools/toolOrchestration.ts:8-12,services/tools/toolOrchestration.ts:152-177):runToolsConcurrently()trackssetInProgressToolUseIDsand feeds per-toolrunToolUse()generators into Chapter 01'sall()(utils/generators.ts:32-72), capped bygetMaxToolUseConcurrency():parseInt(process.env.CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY || '', 10) || 10. Note honestly: there is no upper/lower clamp beyond|| 10—unset,0, orNaNfall back to10, positive integers pass through unbounded, and a negative integer like'-1'is truthy and would starveall()'s fill loop (utils/generators.ts:51). - Deterministic block-order modifier replay (
services/tools/toolOrchestration.ts:30-80): During a concurrent batch (services/tools/toolOrchestration.ts:31-63), all tools share the pre-batchcurrentContext; anyupdate.contextModifieris buffered inqueuedContextModifiers[toolUseID]while messages yield with untouchedcurrentContext. After the batch finishes,services/tools/toolOrchestration.ts:54-63replaysqueuedContextModifiers[block.id]in originalblocksorder and yields{ newContext: currentContext }. Serial batches (runToolsSerially(),services/tools/toolOrchestration.ts:118-150) apply each modifier immediately (services/tools/toolOrchestration.ts:140-142). Today,tools/SkillTool/SkillTool.ts:775-839(allowedTools,mainLoopModel, andeffortValue, inheriting fail-closedisConcurrencySafe: false) is the solecontextModifierproducer in this checkout.
4. Executing While the Model Still Talks: StreamingToolExecutor
The Problem
Waiting for stream completion before launching tools leaves I/O idle while the model streams prose. Executing mid-stream requires three guarantees: serial tools must still block concurrent execution, parallel Bash failures must cancel sibling commands without killing the turn while permission rejections must end the turn, and streaming/model fallbacks must cleanly discard orphaned work.
The Real Implementation (services/tools/StreamingToolExecutor.ts)
Enabled by GrowthBook gate 'tengu_streaming_tool_execution2' (query/config.ts:33-35), StreamingToolExecutor (services/tools/StreamingToolExecutor.ts:40-530) tracks each tool through 'queued' | 'executing' | 'completed' | 'yielded' (services/tools/StreamingToolExecutor.ts:19-32):
- Admission & serial barrier (
services/tools/StreamingToolExecutor.ts:76-151):query.ts:842callsaddTool(block, message)mid-stream. Unknown tools become'completed'immediately with<tool_use_error>(services/tools/StreamingToolExecutor.ts:78-102). Known tools run fail-closedsafeParse+isConcurrencySafe(), enqueue, and invokeprocessQueue().canExecuteTool()(services/tools/StreamingToolExecutor.ts:129-135) enforces exclusive access for unsafe tools; insideprocessQueue(),if (!tool.isConcurrencySafe) break(services/tools/StreamingToolExecutor.ts:148) prevents later safe tools from leapfrogging a waiting mutator. - Progress wake-up & draining (
services/tools/StreamingToolExecutor.ts:412-490): Mid-streamgetCompletedResults()drains synchronously; post-streamgetRemainingResults()races active tool promises against aprogressPromisewoken byprogressAvailableResolve(services/tools/StreamingToolExecutor.ts:371-374,services/tools/StreamingToolExecutor.ts:467-484) so live progress streams immediately. - 3-level
AbortControllertree (utils/abortController.ts:68-99):createChildAbortController()links parent→child viaWeakRef+{ once: true }for downward-only cascades:
toolUseContext.abortController (Level 1: turn-scoped, query.ts)
│ downward WeakRef cascade ▲ upward bubble-up ONLY if
▼ │ reason !== 'sibling_error'
this.siblingAbortController (Level 2: batch-scoped, Bash cancel)
│ downward WeakRef cascade │ && !parent.aborted
▼ │ && !this.discarded
toolAbortController (per tool) ─────────────┘ (Level 3: passed to runToolUse)executeTool() wires Level 3 (services/tools/StreamingToolExecutor.ts:294-325):
// services/tools/StreamingToolExecutor.ts:294-325// Per-tool child controller. Lets siblingAbortController kill running// subprocesses (Bash spawns listen to this signal) when a Bash error// cascades. Permission-dialog rejection also aborts this controller// (PermissionContext.ts cancelAndAbort) — that abort must bubble up to// the query controller so the query loop's post-tool abort check ends// the turn. Without bubble-up, ExitPlanMode "clear context + auto"// sends REJECT_MESSAGE to the model instead of aborting (#21056 regression).const toolAbortController = createChildAbortController( this.siblingAbortController,)toolAbortController.signal.addEventListener( 'abort', () => { if ( toolAbortController.signal.reason !== 'sibling_error' && !this.toolUseContext.abortController.signal.aborted && !this.discarded ) { this.toolUseContext.abortController.abort( toolAbortController.signal.reason, ) } }, { once: true },)const generator = runToolUse( tool.block, tool.assistantMessage, this.canUseTool, { ...this.toolUseContext, abortController: toolAbortController },)And handles errors and contextModifiers on completion (services/tools/StreamingToolExecutor.ts:354-395):
// services/tools/StreamingToolExecutor.ts:354-395 if (isErrorResult) { thisToolErrored = true // Only Bash errors cancel siblings. Bash commands often have implicit // dependency chains (e.g. mkdir fails → subsequent commands pointless). // Read/WebFetch/etc are independent — one failure shouldn't nuke the rest. if (tool.block.name === BASH_TOOL_NAME) { this.hasErrored = true this.erroredToolDescription = this.getToolDescription(tool) this.siblingAbortController.abort('sibling_error') } }// ...// NOTE: we currently don't support context modifiers for concurrent// tools. None are actively being used, but if we want to use// them in concurrent tools, we need to support that here.if (!tool.isConcurrencySafe && contextModifiers.length > 0) { for (const modifier of contextModifiers) { this.toolUseContext = modifier(this.toolUseContext) }}- Why the asymmetry works:
siblingAbortController.abort('sibling_error')kills siblingBashsubprocesses without triggering the upward bubble-up, keepingtoolUseContext.abortControllerun-aborted soquery.ts:1485returns the error and synthetic sibling cancellations to the model. Permission-dialog rejection (hooks/toolPermission/PermissionContext.ts:154-173,cancelAndAbort) abortstoolAbortControllerwith a non-'sibling_error'reason, bubbling up to Level 1 to end the turn (#21056 regression). - Interrupts, synthetic pairing &
discard():getAbortReason()(services/tools/StreamingToolExecutor.ts:210-231) checksdiscarded→hasErrored→ parent abort; on submit-interrupt (reason === 'interrupt'), only tools whoseinterruptBehavior()returns'cancel'(Tool.ts:407-416, fail-safe'block'atservices/tools/StreamingToolExecutor.ts:235) cancel.createSyntheticErrorMessage()(services/tools/StreamingToolExecutor.ts:153-205, usingwithMemoryCorrectionHint(REJECT_MESSAGE)transitively behind GrowthBook'tengu_amber_prism') guarantees validtool_resultpairing (Chapter 03). On streaming-to-non-streaming fallback (query.ts:733-740, triggered fromservices/api/claude.ts:2509-2511andservices/api/claude.ts:2629-2631) andFallbackTriggeredError(query.ts:912-919),query.tscallsdiscard()(services/tools/StreamingToolExecutor.ts:69-71), which drops future yields and blocks orphaned bubble-up via!this.discarded.
5. Two-Stage Result Persistence & Cache-Safe Budgeting
The Problem
Naive output capping breaks in three ways: spilling FileReadTool to disk traps the model in an infinite Read → file → Read cycle; ten parallel 40K tools slip past a 50K per-tool cap to form a 400K wire message (constants/toolLimits.ts:43-44); and re-evaluating an aggregate budget on historical turns mutates wire bytes and busts the prompt cache (Chapter 04).
The Real Implementation (utils/toolResultStorage.ts)
Stage A — Per-Tool Spill at Execution Time (utils/toolResultStorage.ts:55-365)
Called from services/tools/toolExecution.ts:1409-1415 (processPreMappedToolResultBlock() for non-MCP; processToolResultBlock() for MCP after PostToolUse). Both resolve thresholds via getPersistenceThreshold() (utils/toolResultStorage.ts:55-78):
// utils/toolResultStorage.ts:55-78export function getPersistenceThreshold( toolName: string, declaredMaxResultSizeChars: number,): number { // Infinity = hard opt-out. Read self-bounds via maxTokens; persisting its // output to a file the model reads back with Read is circular. Checked // before the GB override so tengu_satin_quoll can't force it back on. if (!Number.isFinite(declaredMaxResultSizeChars)) { return declaredMaxResultSizeChars } const overrides = getFeatureValue_CACHED_MAY_BE_STALE<Record< string, number > | null>(PERSIST_THRESHOLD_OVERRIDE_FLAG, {}) const override = overrides?.[toolName] if ( typeof override === 'number' && Number.isFinite(override) && override > 0 ) { return override } return Math.min(declaredMaxResultSizeChars, DEFAULT_MAX_RESULT_SIZE_CHARS)}Checking !Number.isFinite before GrowthBook 'tengu_satin_quoll' (utils/toolResultStorage.ts:43) guarantees a remote flag can never force FileReadTool—the sole maxResultSizeChars: Infinity tool (tools/FileReadTool/FileReadTool.ts:342, self-bounded by DEFAULT_MAX_OUTPUT_TOKENS = 25000 in tools/FileReadTool/limits.ts:18, env var CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS at tools/FileReadTool/limits.ts:25)—into a circular spill loop. Finite declarations clamp to DEFAULT_MAX_RESULT_SIZE_CHARS = 50_000 (constants/toolLimits.ts:13) while keeping lower caps (BashTool/PowerShellTool 30_000, GrepTool 20_000).
Four scars shape maybePersistLargeToolResult() (utils/toolResultStorage.ts:272-334) and persistToolResult() (utils/toolResultStorage.ts:137-184):
inc-4586empty-result guard (utils/toolResultStorage.ts:280-295): Bare</function_results>\n\nat the prompt tail causedcapybarato emit\n\nHuman:and end its turn empty; empty results become(${toolName} completed with no output).- Image bypass & non-text fail-open (
utils/toolResultStorage.ts:144-151,utils/toolResultStorage.ts:302-319): Image blocks pass untouched; arrays with non-textblocks fail persistence and fail open. flag: 'wx'&EEXISTidempotency (utils/toolResultStorage.ts:153-183): Writes<projectDir>/<sessionId>/tool-results/<toolUseId>.(txt|json)exclusively withflag: 'wx', avoiding stat-then-write races and treatingEEXISTas an idempotent hit on microcompact replay.- Line-snapped preview (
utils/toolResultStorage.ts:189-199,utils/toolResultStorage.ts:339-356):generatePreview()slicesPREVIEW_SIZE_BYTES = 2000chars (utils/toolResultStorage.ts:109), snapping back tolastNewlineonly if> maxBytes * 0.5, then wraps size, path, and preview inside<persisted-output>...</persisted-output>.
Stage B — Per-Message Aggregate Budget & Cache Invariance (utils/toolResultStorage.ts:367-1012)
Invoked at the top of query.ts (query.ts:376-394) via applyToolResultBudget(), gated by GrowthBook master kill-switch 'tengu_hawthorn_steeple' (default false in provisionContentReplacementState(), utils/toolResultStorage.ts:447-463) and window override 'tengu_hawthorn_window' (default MAX_TOOL_RESULTS_PER_MESSAGE_CHARS = 200_000 at constants/toolLimits.ts:49, utils/toolResultStorage.ts:421-434).
ContentReplacementState (utils/toolResultStorage.ts:390-393) freezes every decision in seenIds: Set<string> and stores exact <persisted-output> strings in replacements: Map<string, string> for zero-I/O, byte-identical replay. collectCandidatesByMessage() (utils/toolResultStorage.ts:600-639) mirrors Chapter 03's normalizeMessagesForAPI()—flushing groups only on unseen assistant message.id (seenAsstIds, utils/toolResultStorage.ts:623-632) and matching compacted blocks via .startsWith('<persisted-output>') (utils/toolResultStorage.ts:498-505) so reading utils/toolResultStorage.ts itself is never misclassified. enforceToolResultBudget() (utils/toolResultStorage.ts:769-909) repeats the Infinity skip (query.ts:389-393) and enforces atomic state updates:
// utils/toolResultStorage.ts:816-846 // Tools with maxResultSizeChars: Infinity (Read) — never persist. // Mark as seen (frozen) so the decision sticks across turns. They don't // count toward freshSize; if that lets the group slip under budget and // the wire message is still large, that's the contract — Read's own // maxTokens is the bound, not this wrapper. const skipped = fresh.filter(c => shouldSkip(c.toolUseId)) skipped.forEach(c => state.seenIds.add(c.toolUseId)) const eligible = fresh.filter(c => !shouldSkip(c.toolUseId)) const frozenSize = frozen.reduce((sum, c) => sum + c.size, 0) const freshSize = eligible.reduce((sum, c) => sum + c.size, 0) const selected = frozenSize + freshSize > limit ? selectFreshToReplace(eligible, frozenSize, limit) : [] // Mark non-persisting candidates as seen NOW (synchronously). IDs // selected for persist are marked seen AFTER the await, alongside // replacements.set — keeps the pair atomic under observation so no // concurrent reader (once subagents share state) ever sees X∈seenIds // but X∉replacements, which would misclassify X as frozen and send // full content while the main thread sends the preview → cache miss. const selectedIds = new Set(selected.map(c => c.toolUseId)) candidates .filter(c => !selectedIds.has(c.toolUseId)) .forEach(c => state.seenIds.add(c.toolUseId)) if (selected.length === 0) continue messagesOverBudget++ toPersist.push(...selected)Selected blocks are chosen largest-first (selectFreshToReplace(), utils/toolResultStorage.ts:675-692), persisted concurrently via Promise.all(), and committed to seenIds + replacements together post-await (utils/toolResultStorage.ts:855-869). Cache-sharing forks call cloneContentReplacementState() (utils/forkedAgent.ts:399-403, utils/toolResultStorage.ts:405-412); resumable transcripts (agent:*, repl_main_thread*) persist records via recordContentReplacement() (utils/sessionStorage.ts:1494-1499) and rebuild state on resume via reconstructContentReplacementState() (screens/REPL.tsx:1924, utils/toolResultStorage.ts:960-988) and reconstructForSubagentResume() (tools/AgentTool/resumeAgent.ts:75-79, utils/toolResultStorage.ts:1001-1012).
Putting the Layer Together
How This Snaps Into the Next Layer
Every mechanism in this chapter snaps directly into query.ts in Chapter 07:
- Pre-API Stage B budget (
query.ts:379-394): RunsapplyToolResultBudget()withtoolUseContext.contentReplacementStateand the!Number.isFinite(t.maxResultSizeChars)opt-out set. - Mid-stream bridge & fallback resets (
query.ts:561-568,query.ts:733-740,query.ts:826-862,query.ts:912-919): Underconfig.gates.streamingToolExecution(query/config.ts:33-35),query.tsfeedsToolUseBlocks intoStreamingToolExecutor.addTool(), drainsgetCompletedResults()mid-stream, and callsdiscard()+ swaps in a fresh executor on streaming fallback orFallbackTriggeredError. - Post-stream drain, hook stop & next turn (
query.ts:1380-1408,query.ts:1485-1521,query.ts:1715-1727): DrainsgetRemainingResults()or callsrunTools(), setsshouldPreventContinuationonhook_stopped_continuation(query.ts:1388-1393), carriesupdate.newContextintoupdatedToolUseContext(query.ts:1402-1407), checkstoolUseContext.abortController.signal.aborted(query.ts:1485-1516), and loops[...messagesForQuery, ...assistantMessages, ...toolResults]withupdatedToolUseContextinto the next turn.
Downstream seams continue in Chapter 09 (compaction Stages 2–5 after applyToolResultBudget()), Chapter 11 (canUseTool and checkRuleBasedPermissions()), and Chapter 13 (The Hook System) (utils/hooks.ts).
Reading Exercises & Code Checkpoints
- Audit the
inc-4788hook-vs-rule permission boundary:
rg -n "checkRuleBasedPermissions|requiresUserInteraction|forceDecision" services/tools/toolHooks.ts Trace all three branches in resolveHookPermissionDecision() (services/tools/toolHooks.ts:332-433) and verify which combinations of hook allow + updatedInput still invoke canUseTool().
- Verify concurrency partitioning and block-order
contextModifierreplay:
rg -n "partitionToolCalls|queuedContextModifiers|CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY" services/tools/toolOrchestration.ts Trace how runTools() (services/tools/toolOrchestration.ts:19-82) handles [Read, Read, Skill, Read], and explain what happens when CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY is '0' versus '-1'.
- Inspect the 3-level
AbortControllertree and real-code caveats inStreamingToolExecutor:
rg -n "createChildAbortController|siblingAbortController|BASH_TOOL_NAME|sibling_error|isConcurrencySafe && contextModifiers" services/tools/StreamingToolExecutor.ts Cross-reference services/tools/StreamingToolExecutor.ts:304-318 and services/tools/StreamingToolExecutor.ts:359-363 with query.ts:1485-1516 to see why a failed Bash command keeps the turn alive while a permission rejection aborts it.
- Trace
maxResultSizeChars: Infinityand all three GrowthBook gates across Stages A and B:
rg -n "Number\.isFinite|maxResultSizeChars: Infinity|tengu_(satin_quoll|hawthorn_)" utils/toolResultStorage.ts tools/FileReadTool/FileReadTool.ts query.ts Verify why !Number.isFinite is checked in both getPersistenceThreshold() (utils/toolResultStorage.ts:62) and query.ts:391, and trace what happens when 'tengu_hawthorn_steeple' is false.