Skip to content

Hooks & Resilience

A significant portion of the 80+ React hooks directly participate in runtime resilience — from permission decisions and session recovery to resource monitoring and exit safety, they form a distributed error recovery network across multiple nodes.

Core Question

AI agent runtime resilience cannot rely on a single try/catch. When the API returns max_tokens, when context exceeds limits, when the terminal loses focus, when the IDE connection drops — the system needs recovery capability at multiple independent nodes simultaneously, rather than centralized exception handling.

Resilience Categories

CategoryRepresentative HookResilience Responsibility
Permission decisionstoolPermission/handlers/Three parallel handlers: interactiveHandler (interactive confirmation), coordinatorHandler (orchestration mode), swarmWorkerHandler (Worker mode) — selected by runtime identity
Session recoveryuseSessionBackgrounding.tsDetects terminal defocus/backgrounding, triggers session save and restore
Connection healthuseIdeConnectionStatus.ts, useDirectConnect.tsDegradation path when IDE connection drops
Resource monitoringuseMemoryUsage.ts, useTerminalSize.tsReal-time response to memory pressure and terminal size changes
Task watchinguseScheduledTasks.ts, useTaskListWatcher.tsBackground task status polling and anomaly notification
Exit safetyuseExitOnCtrlCD.tsPrevents state loss from accidental exit

Distributed Recovery Architecture

    flowchart TB
    subgraph APILayer ["API-Side Recovery"]
        MaxTokens["max_tokens retry<br/>maxOutputTokensRecoveryCount<br/>max 3 attempts"]
        ReactiveCompact["Reactive compaction<br/>hasAttemptedReactiveCompact"]
    end

    subgraph PermLayer ["Permission-Side Degradation"]
        Interactive["interactiveHandler<br/>Interactive confirmation"]
        Coordinator["coordinatorHandler<br/>Orchestration mode"]
        Worker["swarmWorkerHandler<br/>Worker mode"]
    end

    subgraph SessionLayer ["Session-Side Persistence"]
        Background["useSessionBackgrounding<br/>Terminal backgrounding"]
        IDE["useIdeConnectionStatus<br/>IDE connection health"]
    end

    subgraph ResourceLayer ["Resource-Side Monitoring"]
        Memory["useMemoryUsage<br/>Memory pressure"]
        Terminal["useTerminalSize<br/>Terminal size"]
        Exit["useExitOnCtrlCD<br/>Exit safety"]
    end

    APILayer -.->|"Any node failure"| PermLayer
    PermLayer -.->|"Other nodes still operational"| SessionLayer
    SessionLayer -.->|"Independent recovery"| ResourceLayer
  

Core design: Four recovery nodes are mutually independent. API-side retry failure doesn’t affect session persistence; permission degradation doesn’t affect resource monitoring; any single node failure still allows other nodes to maintain basic system operation.

Key Recovery Mechanisms

API-Side: max_tokens Recovery

When the API returns max_tokens (model output truncated), queryLoop controls retry via maxOutputTokensRecoveryCount. Maximum 3 retries then gives up — this is a circuit breaker pattern preventing infinite retry token burn.

API-Side: Reactive Compaction

When context approaches the budget ceiling, hasAttemptedReactiveCompact ensures reactive compaction is tried only once. If still over-limit after compaction, the system enters a more aggressive recovery path (dropping the oldest API turn groups).

Permission-Side: Three Handler Types

Permission decisions are not a single function but select different handlers based on runtime identity:

  • Interactive: Shows confirmation dialog, waits for user decision
  • Orchestration mode: Lead Agent makes permission decisions on behalf of the user
  • Worker mode: Worker permissions are preset by the Lead Agent

Session-Side: Backgrounding Protection

useSessionBackgrounding detects terminal defocus (user switches to another window) or entering background. Once triggered, it automatically saves session state, ensuring that even if the process is killed by the OS, the next launch can recover.

Exit-Side: Cascading Timeout

useExitOnCtrlCD is not a simple process.exit(). The exit flow is cascading:

  1. Terminal UI cleanup
  2. Running tool interruption
  3. Hook callbacks (SessionEnd, 1.5-second timeout)
  4. Telemetry data drain
  5. 5-second failsafe — if above steps hang, force exit

Hook System Overview

Claude Code’s Hooks are not just UI state management — 26 event types cover the complete lifecycle from session start to tool execution to session end:

Event GroupRepresentative EventsPurpose
Tool executionPreToolUse, PostToolUse, PostToolUseFailurePre/post tool execution interception
PermissionsPermissionRequest, PermissionDeniedPermission decision hook points
SessionSessionStart, SessionEndSession lifecycle
User interactionUserPromptSubmit, StopUser input and stop signals
File changesFileChangedFilesystem change notifications

Hook Execution Model

  • Async generators: Hook callbacks execute via async generators
  • Timeout protection: Default 10 minutes; SessionEnd is 1.5 seconds
  • Trust gating: In interactive mode, all hooks require trust dialog confirmation
  • Exit code semantics: 0 = allow, 2 = blocking error (enqueued as task notification)

Lessons for Agent Builders

PatternDescription
Distributed recoveryDon’t put all exception handling in one try/catch — set recovery points at API, permission, session, and resource layers
Circuit breakerRetries must have limits (max_tokens max 3), preventing runaway loops from burning resources
Cascading exitExit is not process.exit(0) but orderly cleanup — with a “last resort” timeout
Backgrounding protectionAgent processes can be killed by the OS at any time; session state needs continuous saving, not just write-on-exit
Identity awarenessThe same permission decision follows completely different paths depending on runtime identity (interactive/orchestration/Worker)

Path Evidence

PathRole
src/hooks/toolPermission/handlers/Three permission handlers
src/hooks/useSessionBackgrounding.tsSession backgrounding
src/hooks/useIdeConnectionStatus.tsIDE connection health
src/hooks/useMemoryUsage.tsMemory monitoring
src/hooks/useScheduledTasks.tsTask scheduling
src/hooks/useExitOnCtrlCD.tsExit safety
src/query.ts lines 268-279Cross-iteration recovery state

Further Reading

  1. Runtime Loop — Where hooks sit in queryLoop
  2. Execution Governance — Full permission handler chain
  3. Memory System — Session recovery and memory persistence