@cloudflare/ai-chat 0.11.0 → 0.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +250 -121
- package/dist/index.js +840 -313
- package/dist/index.js.map +1 -1
- package/dist/react.d.ts +4 -0
- package/package.json +4 -3
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["agentContext","withInvocationScope"],"sources":["../src/index.ts"],"sourcesContent":["import type {\n UIMessage,\n GenerateTextOnFinishCallback,\n TextUIPart,\n ToolSet,\n UIMessageChunk\n} from \"ai\";\nimport {\n Agent,\n isDurableObjectMemoryLimitReset,\n __DO_NOT_USE_WILL_BREAK__agentContext as agentContext,\n __DO_NOT_USE_WILL_BREAK__withInvocationScope as withInvocationScope,\n type AgentToolLifecycleResult,\n type AgentToolMilestone,\n type AgentToolProgress,\n type AgentToolProgressSnapshot,\n type AgentToolRunInfo,\n type AgentToolRunInspection,\n type AgentToolStoredChunk,\n type AgentContext,\n type Connection,\n type ConnectionContext,\n type FiberRecoveryContext,\n type WSMessage\n} from \"agents\";\n\nimport { MessageType, type OutgoingMessage } from \"./types\";\nimport { autoTransformMessages } from \"./ai-chat-v5-migration\";\nimport {\n reconcileMessages,\n resolveToolMergeId,\n reconcileOrphanPartial,\n repairInterruptedToolParts,\n persistReconstructedOrphan,\n createChatFiberSnapshot,\n unwrapChatFiberSnapshot,\n wrapChatFiberSnapshot,\n type OrphanPersistStore\n} from \"agents/chat\";\nimport {\n applyChunkToParts,\n AgentToolProgressEmitter,\n aiSdkRecoveryCodec,\n ResumeHandshake,\n isReplayChunk,\n sanitizeMessage,\n enforceRowSizeLimit,\n parseProtocolMessage,\n sendIfOpen,\n TurnQueue,\n SubmitConcurrencyController,\n hasIncompleteToolBatch,\n partAwaitsClientInteraction,\n clientResolvableToolNames,\n toolApprovalUpdate,\n type TurnResult,\n type MessagePart,\n type StreamChunkData,\n type SubmitConcurrencyDecision,\n type ChatFiberSnapshot\n} from \"agents/chat\";\nimport {\n ResumableStream,\n cleanupStreamBuffers,\n STREAM_CLEANUP_DELAY_SECONDS\n} from \"agents/chat\";\nimport { MAX_BOUND_PARAMS, buildInClauseStrings } from \"agents/chat\";\nimport {\n ContinuationState,\n PreStreamTurns,\n AutoContinuationController,\n AbortRegistry,\n TIMED_OUT,\n awaitWithDeadline,\n drainInteractionApplies,\n interceptAgentToolBroadcast,\n type ClientToolSchema\n} from \"agents/chat\";\nimport {\n resolveChatRecoveryConfig,\n chatRecoverySchedulePolicy,\n ChatRecoveryEngine,\n runChatRecoveryExhaustion,\n ChatStreamStalledError,\n iterateWithStallWatchdog,\n sweepStaleChatRecoveryIncidents,\n listActiveChatRecoveryIncidents,\n classifyAgentToolChildRecovery,\n readChatRecoveryProgress,\n bumpChatRecoveryProgress,\n recordChatTerminal,\n clearChatTerminal,\n pendingChatTerminal,\n buildChatRecoveringFrame,\n setChatRecovering,\n AgentToolStreamProgressThrottle,\n StreamProgressCreditThrottle,\n shouldCreditStreamProgress,\n type ChatRecoveryAdapter,\n type ChatFiberWakeHooks,\n type ResolvedRecoveryStream,\n type ClassifyRecoveredTurnInput,\n type DispatchRecoveredTurnInput,\n type ChatRecoveryScheduleCallback,\n type ChatRecoveryIncident,\n type ChatRecoveryKind\n} from \"agents/chat\";\nimport type {\n ChatResponseResult,\n ChatRecoveryConfig,\n ChatRecoveryContext,\n ChatRecoveryOptions,\n MessageConcurrency,\n ResolvedChatRecoveryConfig,\n SaveMessagesOptions,\n SaveMessagesResult\n} from \"agents/chat\";\nimport { nanoid } from \"nanoid\";\n\n// Re-export lifecycle types from the shared chat toolkit so existing\n// consumers (`import type { ChatResponseResult } from \"@cloudflare/ai-chat\"`)\n// continue to work.\nexport type {\n ChatResponseResult,\n ChatRecoveryConfig,\n ChatRecoveryContext,\n ChatRecoveryExhaustedContext,\n ChatRecoveryProgressContext,\n ChatRecoveryOptions,\n MessageConcurrency,\n ResolvedChatRecoveryConfig,\n SaveMessagesOptions,\n SaveMessagesResult\n} from \"agents/chat\";\n\ntype AgentSpanAttributes = Readonly<\n Record<string, string | number | boolean | undefined>\n>;\n\ntype UpdateAgentSpan = (attributes: AgentSpanAttributes) => void;\n\ntype AgentSpanHost = {\n _withAgentSpan<T>(\n operation: string,\n storagePhase: string,\n attributes: AgentSpanAttributes,\n run: (update: UpdateAgentSpan) => T | Promise<T>\n ): T | Promise<T>;\n};\n\nfunction withAgentSpan<T>(\n host: object,\n operation: string,\n storagePhase: string,\n attributes: AgentSpanAttributes,\n run: (update: UpdateAgentSpan) => Promise<T>\n): Promise<T>;\nfunction withAgentSpan<T>(\n host: object,\n operation: string,\n storagePhase: string,\n attributes: AgentSpanAttributes,\n run: (update: UpdateAgentSpan) => T\n): T;\nfunction withAgentSpan<T>(\n host: object,\n operation: string,\n storagePhase: string,\n attributes: AgentSpanAttributes,\n run: (update: UpdateAgentSpan) => T | Promise<T>\n): T | Promise<T> {\n return (host as AgentSpanHost)._withAgentSpan(\n operation,\n storagePhase,\n attributes,\n run\n );\n}\n\ntype ChatRecoveryRetryData = {\n targetUserId?: string;\n originalRequestId?: string;\n incidentId?: string;\n lastBody?: Record<string, unknown> | null;\n lastClientTools?: ClientToolSchema[] | null;\n};\n\ntype ChatRecoveryContinueData = {\n targetAssistantId?: string;\n originalRequestId?: string;\n incidentId?: string;\n lastBody?: Record<string, unknown> | null;\n lastClientTools?: ClientToolSchema[] | null;\n};\n\n/**\n * `AIChatAgent`'s `classifyRecoveredTurn` detail (the {@link ChatFiberWakeHooks}\n * generic). `shouldRetryPreStream` is the only classification bit the dispatch\n * decision needs that it cannot cheaply recompute post-persist; the lost-partial\n * branch is re-derived in `_dispatchRecoveredChatTurn` from the (now-updated) leaf.\n */\ntype AIChatRecoveryClassification = { shouldRetryPreStream: boolean };\n\n// `ChatRecoveryIncident` / `ChatRecoveryKind` / `CHAT_RECOVERY_INCIDENT_KEY_PREFIX`\n// are the canonical shared symbols from `agents/chat` (imported above); the\n// persisted incident shape and key prefix are owned by the engine package so\n// both consumers round-trip the same record across the deploy that ships them.\n\n// The durable, monotonic forward-progress counter (`CHAT_RECOVERY_PROGRESS_KEY`)\n// and its read/bump helpers now live in the shared engine (agents/chat) —\n// `readChatRecoveryProgress` / `bumpChatRecoveryProgress`. Bumped at production\n// time when new content is streamed (`_storeStreamChunk`), so it reflects\n// genuinely new content and is immune to reconnects/re-persists; never recomputed\n// from the (compactable) transcript.\n// Recovery budget defaults (maxAttempts, maxRecoveryWork, stableTimeoutMs,\n// terminalMessage, noProgressTimeoutMs, alarm debounce) now live in the shared\n// incident engine (agents/chat) and are applied by `resolveChatRecoveryConfig`\n// / `evaluateChatRecoveryIncident`. See design/rfc-chat-recovery-foundation.md.\n// Auto-continuation barrier (#1649/#1650): when the model emits parallel tool\n// calls, the client answers each one independently and sends a tool result with\n// `autoContinue` per result. A fast tool's result must NOT trigger inference\n// while a slower sibling is still `input-available` — that feeds the provider\n// an incomplete tool-result set. The barrier is event-driven (converged onto\n// `@cloudflare/think`'s model): we only fire the continuation once the leaf\n// step's batch is fully answered, re-arming on each applied result and on stream\n// finalize, with NO orphan timeout — an incomplete batch simply never\n// auto-continues until it completes (a later user turn / chat recovery repairs\n// the transcript). See design/rfc-chat-recovery-foundation.md.\n// (Stable-state retry delay `CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS` now lives\n// in agents/chat; the reschedule that consumes it is owned by the shared engine.\n// The recovering-flag key/TTL and the terminal-record key now live in agents/chat\n// too — the durable recovery UX is driven via the shared `setChatRecovering` /\n// `buildChatRecoveringFrame` / `recordChatTerminal` helpers — and the incident\n// sweep via the shared `sweepStaleChatRecoveryIncidents` helper.)\n// (N9 throttle now lives in the shared engine as `AgentToolStreamProgressThrottle`\n// / `AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS`; the stream-cleanup delay and\n// re-arm loop now live in agents/chat as `STREAM_CLEANUP_DELAY_SECONDS` /\n// `cleanupStreamBuffers`. The `sendIfOpen` / `isWebSocketClosedSendError` WS send\n// guard is shared via agents/chat.)\n\ntype StreamResultStatus = {\n status: Exclude<SaveMessagesResult[\"status\"], \"skipped\">;\n error?: string;\n};\n\nexport type ChatMessage = UIMessage;\n\n/**\n * Provider-executed tool fields that contain opaque replay tokens and must be\n * persisted exactly as returned by the provider.\n */\nconst PROVIDER_TOOL_OPAQUE_STRING_KEY_PREFIX = \"encrypted\";\n\n/**\n * Max string length preserved in `input`/`output` of provider-executed tool\n * parts (e.g. Anthropic code_execution / text_editor). Strings exceeding this\n * limit are truncated with a marker so persisted messages stay small.\n */\nconst PROVIDER_TOOL_MAX_STRING_LENGTH = 500;\n\n/**\n * Validates that a parsed message has the minimum required structure.\n * Returns false for messages that would cause runtime errors downstream\n * (e.g. in convertToModelMessages or the UI layer).\n *\n * Checks:\n * - `id` is a non-empty string\n * - `role` is one of the valid roles\n * - `parts` is an array (may be empty — the AI SDK enforces nonempty\n * on incoming messages, but we are lenient on persisted data)\n */\nfunction isValidMessageStructure(msg: unknown): msg is UIMessage {\n if (typeof msg !== \"object\" || msg === null) return false;\n const m = msg as Record<string, unknown>;\n\n if (typeof m.id !== \"string\" || m.id.length === 0) return false;\n\n if (m.role !== \"user\" && m.role !== \"assistant\" && m.role !== \"system\") {\n return false;\n }\n\n if (!Array.isArray(m.parts)) return false;\n\n return true;\n}\n\n/**\n * Schema for a client-defined tool sent from the browser.\n * These tools are executed on the client, not the server.\n *\n * **For most apps**, define tools on the server with `tool()` from `\"ai\"` —\n * you get schema-derived type safety, server-side execution, and simpler code.\n * Use `onToolCall` in `useAgentChat` for tools that need client-side execution.\n *\n * **For SDKs and platforms** where the tool surface is determined dynamically\n * by the embedding application at runtime, client tool schemas let the\n * client register tools the server does not know about at deploy time.\n *\n * Note: Uses `parameters` (JSONSchema7) rather than AI SDK's `inputSchema`\n * because this is the wire format. Runtime validation schemas cannot be\n * serialized.\n */\nexport type { ClientToolSchema } from \"agents/chat\";\n\ntype ChatRequestTrigger = \"submit-message\" | \"regenerate-message\";\ntype AIChatAgentToolRunStatus = \"running\" | \"completed\" | \"error\" | \"aborted\";\ntype AIChatAgentToolRunRow = {\n run_id: string;\n request_id: string | null;\n status: AIChatAgentToolRunStatus;\n input_json: string | null;\n output_json: string | null;\n summary: string | null;\n error_message: string | null;\n started_at: number;\n completed_at: number | null;\n progress_json?: string | null;\n last_signal_at?: number | null;\n};\ntype AIChatStreamMetadataRow = {\n id: string;\n status: string;\n request_id: string;\n};\n\n/**\n * Options passed to the onChatMessage handler.\n */\nexport type OnChatMessageOptions = {\n /**\n * Unique ID for this chat message exchange.\n *\n * For initial user messages this is the client-generated ID from the\n * `CF_AGENT_USE_CHAT_REQUEST` WebSocket frame. For tool continuations\n * (auto-continue after client tool results or approvals) this is a\n * server-generated ID.\n */\n requestId: string;\n /** AbortSignal for cancelling the request */\n abortSignal?: AbortSignal;\n /**\n * Tool schemas sent from the client for dynamic tool registration.\n * These represent tools that will be executed on the client side.\n * Use `createToolsFromClientSchemas()` to convert these to AI SDK tool format.\n *\n * **For most apps**, you do not need this — define tools on the server with\n * `tool()` from `\"ai\"` and use `onToolCall` for client-side execution.\n *\n * **For SDKs and platforms** where tools are defined dynamically by the\n * client at runtime and the server does not know the tool surface ahead\n * of time, this field carries the client-provided tool schemas.\n */\n clientTools?: ClientToolSchema[];\n /**\n * Custom body data sent from the client via `prepareSendMessagesRequest`\n * or the AI SDK's `body` option in `sendMessage`.\n *\n * Contains all fields from the request body except `messages` and `clientTools`,\n * which are handled separately.\n *\n * During tool continuations (auto-continue after client tool results), this\n * contains the body from the most recent chat request. The value is persisted\n * to SQLite so it survives Durable Object hibernation. It is cleared when the\n * chat is cleared via `CF_AGENT_CHAT_CLEAR`.\n */\n body?: Record<string, unknown>;\n /**\n * Whether this turn is a continuation of a previous assistant message\n * (auto-continue after tool result, `continueLastTurn`, or recovery).\n *\n * Use this to adjust system prompts, select different models, skip\n * expensive context assembly, or log differently for continuations.\n */\n continuation?: boolean;\n};\n\nexport { createToolsFromClientSchemas } from \"agents/chat\";\n\nconst decoder = new TextDecoder();\nconst agentToolChunkEncoder = new TextEncoder();\n\n/**\n * Extension of Agent with built-in chat capabilities\n * @template Env Environment type containing bindings\n */\nexport class AIChatAgent<\n Env extends Cloudflare.Env = Cloudflare.Env,\n State = unknown,\n Props extends Record<string, unknown> = Record<string, unknown>\n> extends Agent<Env, State, Props> {\n private _activeChatRecoveryRootRequestId: string | undefined;\n\n /**\n * Registry of per-request AbortControllers.\n * Used to propagate cancellation signals for any external calls made by the agent.\n */\n private _abortRegistry: AbortRegistry;\n\n /**\n * Resumable stream manager -- handles chunk buffering, persistence, and replay.\n * @internal Protected for testing purposes.\n */\n protected _resumableStream!: ResumableStream;\n\n /**\n * The message currently being streamed. Used to apply tool results\n * before the message is persisted.\n * @internal\n */\n private _streamingMessage: UIMessage | null = null;\n\n /**\n * Queued by `_reply` so the hook can fire after the turn lock releases.\n * Uses an array to avoid losing results when multiple turns complete\n * during a single `onChatResponse` call.\n * @internal\n */\n private _pendingChatResponseResults: ChatResponseResult[] = [];\n\n /**\n * Re-entrancy guard: true while `onChatResponse` is executing.\n * Prevents recursive hook calls when the hook triggers `saveMessages`.\n * @internal\n */\n private _insideResponseHook = false;\n\n /**\n * Resolves when the current pending client-tool interaction (tool result or\n * approval) has been written to state. Set when an apply promise is created,\n * cleared when it settles. Used by waitUntilStable to avoid polling.\n */\n private _pendingInteractionPromise: Promise<boolean> | null = null;\n\n /**\n * Serialization tail for client-tool result/approval applies (#1649). Each\n * apply is a read-modify-write of the full message; running siblings from a\n * parallel tool batch concurrently lets last-write-wins clobber the others\n * back to `input-available`. Chaining every apply off this tail makes them\n * commit atomically in arrival order.\n */\n private _interactionApplyTail: Promise<void> = Promise.resolve();\n\n /**\n * Tracks the ID of a streaming message that was persisted early due to\n * a tool entering approval-requested state. When set, stream completion\n * updates the existing persisted message instead of appending a new one.\n * @internal\n */\n private _approvalPersistedMessageId: string | null = null;\n\n /**\n * Serial queue for chat turns. Handles promise-chain serialization,\n * generation-based invalidation on clear, and active-request tracking.\n */\n private _turnQueue = new TurnQueue();\n\n /**\n * Durable chat recovery configuration. Every chat turn runs in `runFiber`,\n * enabling `onChatRecovery` and `this.stash()` during streaming. Assign an\n * object to tune recovery budgets and terminal behavior.\n *\n * Assign this as a class field or in the constructor — NOT in `onStart()`.\n * On every wake the SDK evaluates recovery budgets (and may seal an\n * interrupted turn, firing `onExhausted`) before `onStart()` runs, so a config\n * set in `onStart()` is applied too late and the built-in defaults are used\n * for the recovery that matters. See {@link ChatRecoveryConfig}.\n */\n chatRecovery: ChatRecoveryConfig = true;\n\n /**\n * Inactivity watchdog for the live model/transport stream, in milliseconds.\n * If more than this many ms elapse between stream chunks, the turn is aborted\n * and routed into bounded recovery (the same continuation machinery as a\n * deploy or eviction interruption, #1626) rather than parking forever on a\n * hung provider.\n *\n * Default `0` disables the watchdog (opt-in), matching `@cloudflare/think`.\n * A value such as `60_000` (60s) is a reasonable starting point; tune it\n * above your slowest legitimate inter-chunk gap (slow reasoning models, long\n * tool calls) to avoid aborting healthy turns. Because the watchdog measures\n * the gap between chunks — not total turn duration — a steadily streaming\n * turn never trips it regardless of overall length.\n *\n * Assign as a class field or in the constructor, like {@link chatRecovery}.\n */\n chatStreamStallTimeoutMs = 0;\n\n /** First queued overlap message index for merge strategy, keyed by epoch. */\n private _mergeQueuedUserStartIndexByEpoch = new Map<number, number>();\n\n /** Shared admission policy state for overlapping submit-message requests. */\n private _submitConcurrency = new SubmitConcurrencyController({\n defaultDebounceMs: AIChatAgent.MESSAGE_DEBOUNCE_MS\n });\n\n /**\n * Set of connection IDs that are pending stream resume.\n * These connections have received CF_AGENT_STREAM_RESUMING but haven't sent ACK yet.\n * They should be excluded from live stream broadcasts until they ACK.\n * @internal\n */\n private _pendingResumeConnections: Set<string> = new Set();\n\n /** Lazily-built shared resume-handshake driver (Tier-2). */\n private _resumeHandshakeInstance: ResumeHandshake | null = null;\n\n /**\n * Continuation lifecycle state: pending, deferred, active, and\n * connections awaiting a continuation stream to start.\n */\n private _continuation = new ContinuationState<Connection>();\n\n /**\n * Accepted-but-not-yet-streamed turns and the connections parked waiting for\n * one (#1784). Lets a client that reconnects/re-mounts during a turn's\n * pre-stream window (queue, MCP wait, model latency) keep waiting instead of\n * giving up — see the {@link ResumeHandshake} `preStream` seam.\n *\n * HIBERNATION INVARIANT: this is in-memory only and is NOT persisted. It is\n * safe precisely because the pre-stream window cannot overlap hibernation: a\n * turn between `begin()` and `_startStream()` is an unresolved `onMessage`\n * handler promise (queue/debounce/MCP/model awaits) that pins the DO in\n * memory, so the DO is only evicted once the turn either recorded a durable\n * stream (resumed via `ResumableStream` on wake) or finished. This breaks if a\n * pre-stream wait is ever moved onto a durable alarm that releases the DO; if\n * that changes, this state must become durable.\n */\n private _preStream = new PreStreamTurns<Connection>();\n private _agentToolForwarders = new Map<\n string,\n Set<(chunk: AgentToolStoredChunk) => void>\n >();\n private _agentToolClosers = new Map<string, Set<() => void>>();\n private _agentToolAbortControllers = new Map<string, AbortController>();\n private _agentToolLastErrors = new Map<string, string>();\n private _agentToolPreTurnAssistantIds = new Map<string, Set<string>>();\n private _agentToolLiveSequences = new Map<string, number>();\n /**\n * Request id → run id for in-flight agent-tool turns (null = resolved as\n * not an agent-tool turn, cached so unrelated turns don't re-query SQLite\n * per frame). Drives frame attribution in {@link broadcast}: a frame\n * belongs to a run iff it carries that run's turn request id, so an error\n * in a user-driven turn or a concurrent run can never leak into another\n * run's state (#1575).\n */\n private _agentToolRunsByRequestId = new Map<string, string | null>();\n\n /**\n * Client tool schemas from the most recent chat request.\n * Stored so they can be passed to onChatMessage during tool continuations.\n * @internal\n */\n protected _lastClientTools: ClientToolSchema[] | undefined;\n\n /**\n * Custom body data from the most recent chat request.\n * Stored so it can be passed to onChatMessage during tool continuations.\n * @internal\n */\n protected _lastBody: Record<string, unknown> | undefined;\n\n /**\n * Cache of last-persisted JSON for each message ID.\n * Used for incremental persistence: skip SQL writes for unchanged messages.\n * Lost on hibernation, repopulated from SQLite on wake.\n * @internal\n */\n private _persistedMessageCache: Map<string, string> = new Map();\n\n /**\n * Shared auto-continuation barrier (#1649 / #1650): owns the coalesce timer\n * and the double-fire guard. Parameterized by this agent's stream-active\n * signal, apply-drain, and continuation-turn pipeline (`_fireAutoContinuation`).\n */\n private _autoContinuation = new AutoContinuationController<Connection>({\n continuation: this._continuation,\n generateRequestId: () => nanoid(),\n isStreamActive: () => this._streamingTurnActive,\n hasPendingInteraction: () => this._pendingInteractionPromise !== null,\n hasIncompleteToolBatch: () => this._hasIncompleteToolBatch(),\n drainInteractionApplies: () => this._drainInteractionApplies(),\n keepAliveWhile: <T>(fn: () => Promise<T>) => this.keepAliveWhile(fn),\n fire: () => this._fireAutoContinuation()\n });\n\n /**\n * Stream-active gate for the auto-continuation barrier (#1650). True while an\n * assistant turn is streaming in `_reply`: the parallel tool batch can still\n * grow with tool calls the model hasn't emitted yet, so no completeness check\n * is meaningful until the stream finalizes. `_onStreamingTurnFinalized`\n * clears it and re-runs the barrier once the batch is fully materialized.\n */\n private _streamingTurnActive = false;\n\n /** Default wait for trailing-edge debounced overlapping submits. */\n private static MESSAGE_DEBOUNCE_MS = 750;\n\n /**\n * Maximum number of messages to keep in SQLite storage.\n * When the conversation exceeds this limit, oldest messages are deleted\n * after each persist. Set to `undefined` (default) for no limit.\n *\n * This controls storage only — it does not affect what's sent to the LLM.\n * Use `pruneMessages()` from the AI SDK in your `onChatMessage` to control\n * LLM context separately.\n *\n * @example\n * ```typescript\n * class MyAgent extends AIChatAgent<Env> {\n * maxPersistedMessages = 100; // Keep last 100 messages in storage\n * }\n * ```\n */\n maxPersistedMessages: number | undefined = undefined;\n\n /**\n * Controls how overlapping user submit requests behave while another chat\n * turn is already active or queued.\n *\n * - `\"queue\"` (default) — queue every submit and process them in order.\n * - `\"latest\"` — keep only the latest overlapping submit; superseded submits\n * still persist their user messages, but do not start their own model turn.\n * - `\"merge\"` — queue overlapping submits, then collapse their trailing user\n * messages into one combined user turn before the latest queued turn runs.\n * - `\"drop\"` — ignore overlapping submits entirely.\n * - `{ strategy: \"debounce\" }` — trailing-edge latest with a quiet window.\n *\n * This setting only applies to `sendMessage()` / `trigger: \"submit-message\"`\n * requests. Regenerations, tool continuations, approvals, clears, and\n * programmatic `saveMessages()` calls keep their existing serialized\n * behavior.\n */\n messageConcurrency: MessageConcurrency = \"queue\";\n\n /**\n * When enabled, waits for all MCP server connections to be ready before\n * calling `onChatMessage`. This prevents the race condition where\n * `getAITools()` returns an incomplete set because connections are still\n * restoring after Durable Object hibernation.\n *\n * - `false` (default) — non-blocking; `onChatMessage` runs immediately.\n * - `true` — waits indefinitely for all connections to settle.\n * - `{ timeout: number }` — waits up to `timeout` milliseconds.\n *\n * For lower-level control, call `this.mcp.waitForConnections()` directly\n * inside your `onChatMessage` instead.\n *\n * @example\n * ```typescript\n * class MyAgent extends AIChatAgent<Env> {\n * waitForMcpConnections = true;\n * }\n * ```\n *\n * @example\n * ```typescript\n * class MyAgent extends AIChatAgent<Env> {\n * waitForMcpConnections = { timeout: 10_000 };\n * }\n * ```\n */\n waitForMcpConnections: boolean | { timeout: number } = { timeout: 10_000 };\n\n private async _runChatRecoveryFiber<T>(\n requestId: string,\n continuation: boolean,\n fn: () => Promise<T>\n ): Promise<T> {\n const snapshot = createChatFiberSnapshot({\n kind: \"ai-chat-turn\",\n requestId,\n recoveryRootRequestId: this._activeChatRecoveryRootRequestId ?? requestId,\n continuation,\n messages: this.messages,\n lastBody: this._lastBody,\n lastClientTools: this._lastClientTools\n });\n\n return this._runFiberWithStashWrapper(\n `${(this.constructor as typeof AIChatAgent).CHAT_FIBER_NAME}:${requestId}`,\n async () => fn(),\n {\n initialSnapshot: wrapChatFiberSnapshot(\n \"__cfAIChatFiberSnapshot\",\n snapshot,\n null\n ),\n wrapStash: (data) =>\n wrapChatFiberSnapshot(\"__cfAIChatFiberSnapshot\", snapshot, data)\n }\n );\n }\n\n /**\n * Array of chat messages for the current conversation.\n *\n * Public and mutable for backwards compatibility. Framework code\n * generally writes through `saveMessages` / `persistMessages`, but\n * existing subclasses may still assign `this.messages = [...]` or\n * mutate the array directly.\n */\n messages: UIMessage[] = [];\n\n override broadcast(\n msg: string | ArrayBuffer | ArrayBufferView,\n without?: string[]\n ): void {\n // Cheap idle guard so the common (no agent-tool child) broadcast path stays\n // allocation-free — only build the snoop hooks while a run is in flight.\n if (\n this._agentToolForwarders.size > 0 ||\n this._agentToolLiveSequences.size > 0\n ) {\n interceptAgentToolBroadcast(msg, {\n forwarders: this._agentToolForwarders,\n liveSequences: this._agentToolLiveSequences,\n lastErrors: this._agentToolLastErrors,\n responseType: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n runForRequest: (requestId) => this._agentToolRunForRequest(requestId)\n });\n }\n super.broadcast(msg, without);\n }\n\n /**\n * Resolve the agent-tool run whose turn owns a request id, or null when the\n * request is not an agent-tool turn. Falls back to the persisted run row\n * (written when the turn starts, see `_registerAgentToolTurn`) so\n * attribution survives a DO restart mid-run; either outcome is cached.\n */\n private _agentToolRunForRequest(requestId: string): string | null {\n const cached = this._agentToolRunsByRequestId.get(requestId);\n if (cached !== undefined) return cached;\n // Active-run predicate: a child run is in flight while `status` is\n // `starting`/`running`. ai-chat inserts rows directly as `running` (no\n // `starting` phase), but we match on both for parity with\n // `@cloudflare/think` and to stay correct if a `starting` phase is ever\n // added. Terminal rows set `status` AND `completed_at` together.\n const rows = this.sql<{ run_id: string }>`\n select run_id from cf_ai_chat_agent_tool_runs\n where request_id = ${requestId} and status in ('starting', 'running')\n limit 1\n `;\n const runId = rows?.[0]?.run_id ?? null;\n this._agentToolRunsByRequestId.set(requestId, runId);\n return runId;\n }\n\n /**\n * Re-bind this facet's in-flight agent-tool child run to the CURRENT turn's\n * request id. Parity with `@cloudflare/think`'s\n * `_rebindAgentToolChildRunRequestId`.\n *\n * When this facet runs as an agent-tool child and its turn is interrupted, the\n * recovery continuation (`continueLastTurn` / `_retryLastUserTurn`) mints a NEW\n * request id but never flows through `startAgentToolRun`'s\n * `_registerAgentToolTurn`. So `cf_ai_chat_agent_tool_runs.request_id` (and the\n * in-memory attribution map) still point at the pre-eviction turn, and\n * `broadcast` can no longer attribute the recovered turn's frames to the run.\n * A long-running child then forwards nothing to the parent's re-attach tail,\n * its no-progress budget elapses, and a healthy child is abandoned as\n * `interrupted`. Re-binding keeps attribution alive across recovery.\n *\n * Safe to call on EVERY recovery continuation:\n * - Facets that never ran as an agent-tool child have no\n * `cf_ai_chat_agent_tool_runs` table → the guarded SELECT throws → no-op.\n * - A facet whose run already settled has no active row → no-op.\n * - A child DO is addressed by its `runId` (`subAgent(cls, runId)`), so it\n * owns AT MOST ONE child-run row for its whole lifetime and is never reused\n * as a top-level chat agent — the single active row is unambiguously this\n * recovery's run. The `order by started_at desc limit 1` is defensive\n * belt-and-suspenders for that invariant.\n *\n * Uses the same `status in ('starting','running')` active-run predicate as\n * `_agentToolRunForRequest` and the `@cloudflare/think` counterpart.\n */\n private _rebindAgentToolChildRunRequestId(requestId: string): void {\n let runId: string | undefined;\n try {\n const rows = this.sql<{ run_id: string }>`\n select run_id from cf_ai_chat_agent_tool_runs\n where status in ('starting', 'running')\n order by started_at desc\n limit 1\n `;\n runId = rows?.[0]?.run_id;\n } catch {\n // No child-run table on this facet (it never ran as a child).\n return;\n }\n if (!runId) return;\n this._agentToolRunsByRequestId.set(requestId, runId);\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set request_id = ${requestId}\n where run_id = ${runId}\n `;\n }\n\n constructor(ctx: AgentContext, env: Env) {\n super(ctx, env);\n withAgentSpan(\n this,\n \"chat_initialization\",\n \"initialization\",\n { \"cloudflare.agents.component\": \"ai_chat\" },\n (update) => {\n withAgentSpan(\n this,\n \"initialize_chat_storage\",\n \"initialization\",\n { \"cloudflare.agents.component\": \"ai_chat\" },\n () => {\n this.sql`create table if not exists cf_ai_chat_agent_messages (\n id text primary key,\n message text not null,\n created_at datetime default current_timestamp\n )`;\n\n // Key-value table for request context that must survive hibernation\n // (e.g., custom body fields, client tools from the last chat request).\n this.sql`create table if not exists cf_ai_chat_request_context (\n key text primary key,\n value text not null\n )`;\n\n this._ensureAgentToolTables();\n }\n );\n\n // Restore request context from SQLite (survives hibernation)\n withAgentSpan(\n this,\n \"restore_chat_request_context\",\n \"initialization\",\n { \"cloudflare.agents.component\": \"ai_chat\" },\n () => this._restoreRequestContext()\n );\n\n // Initialize resumable stream manager (creates its own tables + restores state)\n withAgentSpan(\n this,\n \"initialize_resumable_stream\",\n \"initialization\",\n { \"cloudflare.agents.component\": \"ai_chat\" },\n () => {\n this._resumableStream = new ResumableStream(this.sql.bind(this));\n }\n );\n\n const rawMessages = withAgentSpan(\n this,\n \"load_chat_messages\",\n \"initialization\",\n { \"cloudflare.agents.component\": \"ai_chat\" },\n () => this._loadMessagesFromDb()\n );\n\n // Automatic migration following https://jhak.im/blog/ai-sdk-migration-handling-previously-saved-messages\n this.messages = autoTransformMessages(rawMessages);\n update({\n \"cloudflare.agents.chat.messages.loaded\": rawMessages.length,\n \"cloudflare.agents.chat.active_stream.restored\":\n this._resumableStream.hasActiveStream()\n });\n }\n );\n\n this._abortRegistry = new AbortRegistry();\n const _onConnect = this.onConnect.bind(this);\n this.onConnect = async (connection: Connection, ctx: ConnectionContext) => {\n if (this._cf_requestTargetsSubAgent(ctx.request)) {\n return _onConnect(connection, ctx);\n }\n\n // Notify client about active streams that can be resumed\n if (this._resumableStream.hasActiveStream()) {\n this._notifyStreamResuming(connection);\n } else if (this._preStream.park(connection)) {\n // A turn is accepted but its stream hasn't started yet (#1784): park\n // this connection and tell it to keep waiting. `park` sent the\n // keep-waiting frame; the turn flushes it into STREAM_RESUMING on\n // _startStream or releases it with STREAM_RESUME_NONE on settle.\n } else {\n // No active stream to resume: if a recovery is in progress (between\n // attempts — the interrupted stream ended and the continuation hasn't\n // started yet), replay the live \"recovering…\" status so a client that\n // connects mid-recovery reads the turn as working rather than frozen\n // (#1620). This converges `AIChatAgent` onto `@cloudflare/think`'s\n // behavior. Unlike the terminal outcome (which must go through the\n // resume handshake to reach the client's stream reader), the recovering\n // frame is a plain status the client reflects directly into state.\n const recoveringFrame = await this._buildRecoveringConnectFrame();\n if (recoveringFrame) {\n sendIfOpen(connection, JSON.stringify(recoveringFrame));\n }\n }\n // Call consumer's onConnect\n return _onConnect(connection, ctx);\n };\n\n // Wrap onClose to clean up pending resume connections\n const _onClose = this.onClose.bind(this);\n this.onClose = async (\n connection: Connection,\n code: number,\n reason: string,\n wasClean: boolean\n ) => {\n // Clean up pending resume state for this connection\n this._pendingResumeConnections.delete(connection.id);\n this._continuation.releaseConnection(connection.id);\n this._preStream.release(connection.id);\n // Call consumer's onClose\n return _onClose(connection, code, reason, wasClean);\n };\n\n // Wrap onMessage\n const _onMessage = this.onMessage.bind(this);\n const handleMessage = async (\n connection: Connection,\n message: WSMessage\n ) => {\n if (this._cf_connectionTargetsSubAgent(connection)) {\n return _onMessage(connection, message);\n }\n\n // Handle AIChatAgent's internal messages first. Classification is shared\n // with `@cloudflare/think` via `parseProtocolMessage`; the handler bodies\n // below stay AIChatAgent-specific (e.g. the `messages` event persists the\n // client snapshot, where Think no-ops it).\n if (typeof message === \"string\") {\n const event = parseProtocolMessage(message);\n if (!event) {\n // Not JSON, or not a recognized chat protocol message — forward to\n // the consumer's onMessage.\n return _onMessage(connection, message);\n }\n\n // Handle chat request\n if (event.type === \"chat-request\" && event.init.method === \"POST\") {\n const { body } = event.init;\n if (!body) {\n console.warn(\n \"[AIChatAgent] Received chat request with empty body, ignoring\"\n );\n return;\n }\n\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(body as string);\n } catch (_parseError) {\n console.warn(\n \"[AIChatAgent] Received chat request with invalid JSON body, ignoring\"\n );\n return;\n }\n\n const {\n messages,\n clientTools,\n trigger: _trigger,\n ...customBody\n } = parsed as {\n messages: UIMessage[];\n clientTools?: ClientToolSchema[];\n trigger?: string;\n [key: string]: unknown;\n };\n const chatMessageId = event.id;\n const transformedMessages = autoTransformMessages(messages);\n const requestTrigger: ChatRequestTrigger =\n _trigger === \"regenerate-message\"\n ? \"regenerate-message\"\n : \"submit-message\";\n const requestClientTools = clientTools?.length\n ? clientTools\n : undefined;\n const requestBody =\n Object.keys(customBody).length > 0 ? customBody : undefined;\n const epoch = this._turnQueue.generation;\n const concurrencyDecision =\n this._getSubmitConcurrencyDecision(requestTrigger);\n\n if (concurrencyDecision.action === \"drop\") {\n this._rollbackDroppedSubmit(connection);\n this._completeSkippedRequest(connection, chatMessageId);\n return;\n }\n\n // A genuinely-new turn supersedes any pending terminal record (#1645)\n // so a stale exhaustion can't replay on a later reconnect once the\n // user has moved on.\n await withAgentSpan(\n this,\n \"clear_previous_chat_state\",\n \"interaction\",\n {\n \"cloudflare.agents.component\": \"ai_chat\",\n \"cloudflare.agents.turn.request_id\": chatMessageId,\n \"cloudflare.agents.turn.trigger\": requestTrigger\n },\n () => this._clearChatTerminal()\n );\n\n // Mark this turn as accepted-but-not-yet-streamed (#1784) so a client\n // that reconnects/re-mounts before the stream starts is parked and\n // told to keep waiting (see _resumeHandshake / onConnect), then\n // flushed into STREAM_RESUMING on _startStream or released on settle.\n this._preStream.begin(chatMessageId);\n\n // Outer finally so the accepted pre-stream turn ALWAYS settles\n // (#1784). begin() runs before the pre-turn-body steps below\n // (persistMessages, _mergeQueuedUserMessages, and inside the queued\n // execute callback mcp.waitForConnections / _setRequestContext); if\n // any of those throws, chatTurnBody's own finally never runs. Without\n // this backstop the request id would stay stuck in _preStream —\n // hasInFlight() true forever — so every future client would be parked\n // on STREAM_PENDING (60s) instead of getting an immediate\n // STREAM_RESUME_NONE, until chat clear or DO eviction. Mirrors\n // @cloudflare/think's _handleChatRequest.\n try {\n // Track that this request is past the concurrency decision but\n // not yet enqueued in _turnQueue. Decremented synchronously\n // before _runExclusiveChatTurn (which increments queuedCount).\n const releasePendingEnqueue =\n this._submitConcurrency.beginEnqueue();\n try {\n // Persist and broadcast user messages before entering the turn\n // queue so other tabs see the new message immediately and so\n // overlapping submits under latest/merge/debounce can inspect\n // the full message list when their turn starts.\n await withAgentSpan(\n this,\n \"persist_incoming_messages\",\n \"interaction\",\n {\n \"cloudflare.agents.component\": \"ai_chat\",\n \"cloudflare.agents.turn.request_id\": chatMessageId,\n \"cloudflare.agents.turn.trigger\": requestTrigger\n },\n async () => {\n this._broadcastChatMessage(\n {\n messages: transformedMessages,\n type: MessageType.CF_AGENT_CHAT_MESSAGES\n },\n [connection.id]\n );\n\n await this.persistMessages(\n transformedMessages,\n [connection.id],\n { _deleteStaleRows: true }\n );\n\n if (concurrencyDecision.strategy === \"merge\") {\n await this._mergeQueuedUserMessages(epoch);\n }\n }\n );\n } finally {\n releasePendingEnqueue();\n }\n await this._runExclusiveChatTurn(\n chatMessageId,\n async () => {\n if (\n this._submitConcurrency.isSuperseded(\n concurrencyDecision.submitSequence\n )\n ) {\n this._completeSkippedRequest(connection, chatMessageId);\n return;\n }\n\n if (concurrencyDecision.debounceUntilMs !== null) {\n await this._submitConcurrency.waitForTimestamp(\n concurrencyDecision.debounceUntilMs\n );\n\n if (this._turnQueue.generation !== epoch) {\n this._completeSkippedRequest(connection, chatMessageId);\n return;\n }\n\n if (\n this._submitConcurrency.isSuperseded(\n concurrencyDecision.submitSequence\n )\n ) {\n this._completeSkippedRequest(connection, chatMessageId);\n return;\n }\n }\n\n // Re-merge inside the lock: more overlapping submits may have\n // persisted additional user messages while this turn was queued.\n if (concurrencyDecision.strategy === \"merge\") {\n await withAgentSpan(\n this,\n \"merge_queued_messages\",\n \"turn\",\n {\n \"cloudflare.agents.component\": \"ai_chat\",\n \"cloudflare.agents.turn.request_id\": chatMessageId,\n \"cloudflare.agents.turn.trigger\": requestTrigger,\n \"cloudflare.agents.turn.admission\": \"queue\",\n \"cloudflare.agents.turn.generation\": epoch\n },\n () => this._mergeQueuedUserMessages(epoch)\n );\n\n if (this._turnQueue.generation !== epoch) {\n this._completeSkippedRequest(connection, chatMessageId);\n return;\n }\n\n if (\n this._submitConcurrency.isSuperseded(\n concurrencyDecision.submitSequence\n )\n ) {\n this._completeSkippedRequest(connection, chatMessageId);\n return;\n }\n }\n\n await withAgentSpan(\n this,\n \"prepare_chat_context\",\n \"turn\",\n {\n \"cloudflare.agents.component\": \"ai_chat\",\n \"cloudflare.agents.turn.request_id\": chatMessageId,\n \"cloudflare.agents.turn.trigger\": requestTrigger,\n \"cloudflare.agents.turn.admission\": \"queue\",\n \"cloudflare.agents.turn.generation\": epoch\n },\n async () => {\n // Optionally wait for in-flight MCP connections to settle (e.g. after hibernation restore)\n // so that getAITools() returns the full set of tools in onChatMessage\n if (this.waitForMcpConnections) {\n const timeout =\n typeof this.waitForMcpConnections === \"object\"\n ? this.waitForMcpConnections.timeout\n : undefined;\n await this.mcp.waitForConnections(\n timeout != null ? { timeout } : undefined\n );\n }\n\n this._setRequestContext(requestClientTools, requestBody);\n }\n );\n\n this._emit(\"message:request\");\n\n const abortSignal =\n this._abortRegistry.getSignal(chatMessageId);\n\n return this._tryCatchChat(async () => {\n // Wrap in agentContext.run() to propagate connection context to onChatMessage\n // This ensures getCurrentAgent() returns the connection inside tool execute functions\n return agentContext.run(\n {\n agent: this,\n connection,\n request: undefined,\n email: undefined\n },\n async () => {\n const chatTurnBody = async () => {\n try {\n await withAgentSpan(\n this,\n \"repair_interrupted_tools\",\n \"turn\",\n {\n \"cloudflare.agents.component\": \"ai_chat\",\n \"cloudflare.agents.turn.request_id\":\n chatMessageId,\n \"cloudflare.agents.turn.trigger\": requestTrigger,\n \"cloudflare.agents.turn.admission\": \"queue\",\n \"cloudflare.agents.turn.generation\": epoch\n },\n () => this._repairInterruptedToolsBeforeTurn()\n );\n const response = await this.onChatMessage(\n async (_finishResult) => {\n // User-provided hook. Cleanup is now handled by _reply,\n // so this is optional for the user to pass to streamText.\n },\n {\n requestId: chatMessageId,\n abortSignal,\n clientTools: requestClientTools,\n body: requestBody,\n continuation: false\n }\n );\n\n if (response) {\n await withAgentSpan(\n this,\n \"persist_chat_result\",\n \"turn\",\n {\n \"cloudflare.agents.component\": \"ai_chat\",\n \"cloudflare.agents.turn.request_id\":\n chatMessageId,\n \"cloudflare.agents.turn.trigger\":\n requestTrigger,\n \"cloudflare.agents.turn.admission\": \"queue\",\n \"cloudflare.agents.turn.generation\": epoch\n },\n () =>\n this._reply(\n chatMessageId,\n response,\n [connection.id],\n { chatMessageId }\n )\n );\n } else {\n console.warn(\n `[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`\n );\n this._broadcastChatMessage(\n {\n body: \"No response was generated by the agent.\",\n done: true,\n id: chatMessageId,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE\n },\n [connection.id]\n );\n }\n } finally {\n this._abortRegistry.remove(chatMessageId);\n // Settle the pre-stream turn on the normal path (#1784):\n // a no-op release when the turn streamed (already flushed\n // into STREAM_RESUMING on _startStream) or a release on\n // the no-response path. A throw BEFORE chatTurnBody runs\n // is caught by the outer finally instead.\n this._settlePreStreamTurn(chatMessageId);\n }\n };\n\n await this._runChatRecoveryFiber(\n chatMessageId,\n false,\n chatTurnBody\n );\n }\n );\n });\n },\n {\n epoch,\n onStale: () =>\n this._completeSkippedRequest(connection, chatMessageId)\n }\n );\n } finally {\n // Guaranteed settle (#1784): on the happy path chatTurnBody /\n // _completeSkippedRequest already settled (idempotent here); this\n // covers a throw in a pre-turn-body step before chatTurnBody's\n // finally could run.\n this._settlePreStreamTurn(chatMessageId);\n }\n return;\n }\n\n // Handle clear chat\n if (event.type === \"clear\") {\n this.resetTurnState();\n this.sql`delete from cf_ai_chat_agent_messages`;\n // Drop any pending terminal record (#1645) so a stale exhaustion\n // can't replay onto a freshly-cleared (empty) conversation when a\n // client reconnects and runs the resume probe.\n await this._clearChatTerminal();\n this._resumableStream.clearAll();\n this._pendingResumeConnections.clear();\n this._preStream.releaseAwaiting();\n this._preStream.reset();\n this._lastClientTools = undefined;\n this._lastBody = undefined;\n this._persistRequestContext();\n this._persistedMessageCache.clear();\n this.messages = [];\n this._broadcastChatMessage(\n { type: MessageType.CF_AGENT_CHAT_CLEAR },\n [connection.id]\n );\n this._emit(\"message:clear\");\n return;\n }\n\n // Handle message replacement\n if (event.type === \"messages\") {\n const transformedMessages = autoTransformMessages(event.messages);\n await this.persistMessages(transformedMessages, [connection.id]);\n return;\n }\n\n // Handle request cancellation\n if (event.type === \"cancel\") {\n this._abortRegistry.cancel(event.id);\n this._emit(\"message:cancel\", { requestId: event.id });\n return;\n }\n\n // Handle client-initiated stream resume request.\n // The client sends this after its message handler is registered,\n // avoiding the race condition where CF_AGENT_STREAM_RESUMING sent\n // in onConnect arrives before the client's handler is ready.\n if (event.type === \"stream-resume-request\") {\n await this._resumeHandshake().handleResumeRequest(\n connection,\n event.probeId\n );\n return;\n }\n\n // Handle stream resume acknowledgment\n if (event.type === \"stream-resume-ack\") {\n await this._resumeHandshake().handleResumeAck(connection, event.id);\n return;\n }\n\n // Handle client-side tool result\n if (event.type === \"tool-result\") {\n const {\n toolCallId,\n toolName,\n output,\n state,\n errorText,\n autoContinue,\n clientTools\n } = event;\n\n // Update cached client tools so subsequent continuations use the latest schemas\n if (clientTools?.length) {\n this._lastClientTools = clientTools as ClientToolSchema[];\n this._persistRequestContext();\n }\n\n const overrideState =\n state === \"output-error\" ? \"output-error\" : undefined;\n\n this._emit(\"tool:result\", { toolCallId, toolName });\n\n this._enqueueInteractionApply(() =>\n this._applyToolResult(\n toolCallId,\n toolName,\n output,\n overrideState,\n errorText\n )\n );\n\n if (autoContinue) {\n this._scheduleAutoContinuation(\n connection,\n (clientTools as ClientToolSchema[] | undefined) ??\n this._lastClientTools,\n this._lastBody,\n \"[AIChatAgent] Tool continuation failed:\"\n );\n } else {\n // A result that arrived WITHOUT autoContinue (e.g. a standalone\n // errored tool) can still be the one that completes a parallel batch\n // a sibling already opted to continue — re-arm the barrier so that\n // continuation fires once the batch is whole (#1650). Never CREATES\n // a pending continuation.\n this._rearmPendingAutoContinuationForBatch();\n }\n return;\n }\n\n // Handle client-side tool approval response\n if (event.type === \"tool-approval\") {\n const { toolCallId, approved, autoContinue } = event;\n this._emit(\"tool:approval\", { toolCallId, approved });\n this._enqueueInteractionApply(() =>\n this._applyToolApproval(toolCallId, approved)\n );\n\n if (autoContinue) {\n this._scheduleAutoContinuation(\n connection,\n this._lastClientTools,\n this._lastBody,\n \"[AIChatAgent] Tool approval continuation failed:\"\n );\n } else {\n this._rearmPendingAutoContinuationForBatch();\n }\n return;\n }\n }\n\n // Forward unhandled messages to consumer's onMessage\n return _onMessage(connection, message);\n };\n this.onMessage = (connection: Connection, message: WSMessage) => {\n const event =\n typeof message === \"string\" ? parseProtocolMessage(message) : null;\n if (event?.type === \"chat-request\") {\n return withAgentSpan(\n this,\n \"chat_interaction\",\n \"interaction\",\n {\n \"cloudflare.agents.component\": \"ai_chat\",\n \"cloudflare.agents.turn.request_id\": event.id\n },\n () => handleMessage(connection, message)\n );\n }\n return handleMessage(connection, message);\n };\n\n const _onRequest = this.onRequest.bind(this);\n this.onRequest = async (request: Request) => {\n return this._tryCatchChat(async () => {\n const url = new URL(request.url);\n if (url.pathname.split(\"/\").pop() === \"get-messages\") {\n return Response.json(this._loadMessagesFromDb());\n }\n return _onRequest(request);\n });\n };\n }\n\n private _ensureAgentToolTables() {\n this.sql`create table if not exists cf_ai_chat_agent_tool_runs (\n run_id text primary key,\n request_id text,\n status text not null,\n input_json text,\n output_json text,\n summary text,\n error_message text,\n started_at integer not null,\n completed_at integer\n )`;\n const addColumnIfNotExists = (sql: string) => {\n try {\n this.ctx.storage.sql.exec(sql);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (!message.toLowerCase().includes(\"duplicate column\")) {\n throw error;\n }\n }\n };\n addColumnIfNotExists(\n \"alter table cf_ai_chat_agent_tool_runs add column input_json text\"\n );\n addColumnIfNotExists(\n \"alter table cf_ai_chat_agent_tool_runs add column output_json text\"\n );\n addColumnIfNotExists(\n \"alter table cf_ai_chat_agent_tool_runs add column summary text\"\n );\n // Latest progress snapshot (rfc-detached-agent-tools §progress); only the\n // most recent `reportProgress` is retained. `last_signal_at` drives the\n // parent's resetting no-progress budget across eviction.\n addColumnIfNotExists(\n \"alter table cf_ai_chat_agent_tool_runs add column progress_json text\"\n );\n addColumnIfNotExists(\n \"alter table cf_ai_chat_agent_tool_runs add column last_signal_at integer\"\n );\n this.sql`create index if not exists idx_ai_chat_agent_tool_request_id\n on cf_ai_chat_agent_tool_runs(request_id)`;\n // Durable milestones (rfc-detached-agent-tools §progress, 4b). One row per\n // milestone; `sequence` is monotonic per run so replay/live races dedupe.\n this.sql`create table if not exists cf_ai_chat_agent_tool_milestones (\n run_id text not null,\n sequence integer not null,\n name text not null,\n data_json text,\n at integer not null,\n primary key (run_id, sequence)\n )`;\n }\n\n private _persistAgentToolMilestone(\n runId: string,\n name: string,\n data: unknown,\n at: number\n ): number {\n this._ensureAgentToolTables();\n const rows = this.sql<{ next: number }>`\n select coalesce(max(sequence), -1) + 1 as next\n from cf_ai_chat_agent_tool_milestones where run_id = ${runId}\n `;\n const sequence = rows[0]?.next ?? 0;\n this.sql`\n insert or ignore into cf_ai_chat_agent_tool_milestones\n (run_id, sequence, name, data_json, at)\n values (\n ${runId}, ${sequence}, ${name},\n ${data !== undefined ? JSON.stringify(data) : null}, ${at}\n )\n `;\n // A milestone is a progress signal too: advance the no-progress clock.\n this.sql`update cf_ai_chat_agent_tool_runs set last_signal_at = ${at}\n where run_id = ${runId}`;\n return sequence;\n }\n\n private _readAgentToolMilestones(runId: string): AgentToolMilestone[] {\n this._ensureAgentToolTables();\n return this.sql<{\n sequence: number;\n name: string;\n data_json: string | null;\n at: number;\n }>`\n select sequence, name, data_json, at\n from cf_ai_chat_agent_tool_milestones\n where run_id = ${runId} order by sequence asc\n `.map((row) => ({\n name: row.name,\n sequence: row.sequence,\n at: row.at,\n ...(row.data_json != null\n ? { data: JSON.parse(row.data_json) as unknown }\n : {})\n }));\n }\n\n private _flushAwaitingStreamStartConnections() {\n if (!this._resumableStream.hasActiveStream()) {\n return;\n }\n\n this._continuation.flushAwaitingConnections((c) =>\n this._notifyStreamResuming(c)\n );\n }\n\n private _activateDeferredAutoContinuation() {\n // Run the freshly-activated continuation through the event-driven barrier\n // (#1650) rather than enqueuing it directly — its batch may still be\n // incomplete (or a stream may be active), in which case it parks and\n // re-arms instead of firing inference against a half-complete transcript.\n this._autoContinuation.activateDeferredAndReschedule();\n }\n\n private _clearAllAutoContinuationState(sendNone = false) {\n this._clearPendingAutoContinuation(sendNone);\n this._continuation.clearDeferred();\n }\n\n private _clearPendingAutoContinuation(sendNone = false) {\n if (sendNone) {\n this._continuation.sendResumeNone();\n }\n this._continuation.clearPending();\n }\n\n /**\n * The shared resume-handshake driver (Tier-2). Lazily built; the\n * `ResumableStream` / `ContinuationState` / pending set are stable after the\n * constructor, so a single instance threads them for the agent's lifetime.\n */\n private _resumeHandshake(): ResumeHandshake {\n return (this._resumeHandshakeInstance ??= new ResumeHandshake({\n responseMessageType: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n resumableStream: this._resumableStream,\n continuation: this._continuation,\n preStream: this._preStream,\n pendingResumeConnections: this._pendingResumeConnections,\n pendingChatTerminal: () => this._pendingChatTerminal(),\n persistOrphanedStream: (streamId) =>\n this._persistOrphanedStream(streamId),\n isConnectionPresent: (connectionId) =>\n this._isConnectionPresent(connectionId)\n }));\n }\n\n /**\n * Notify a connection about an active stream that can be resumed — delegates\n * to the shared {@link ResumeHandshake}. Kept as a thin method because it is\n * also called proactively from onConnect and the broadcast loop. See the\n * driver for the #1733 double-send contract.\n * @param connection - The WebSocket connection to notify\n */\n private _notifyStreamResuming(connection: Connection) {\n this._resumeHandshake().notifyStreamResuming(connection);\n }\n\n // ── Delegate methods for backward compatibility with tests ─────────\n // These protected methods delegate to _resumableStream so existing\n // test workers that call them directly continue to work.\n\n /** @internal Delegate to _resumableStream */\n protected get _activeStreamId(): string | null {\n return this._resumableStream?.activeStreamId ?? null;\n }\n\n /** @internal Delegate to _resumableStream */\n protected get _activeRequestId(): string | null {\n return this._resumableStream?.activeRequestId ?? null;\n }\n\n /** @internal Delegate to _resumableStream */\n protected _startStream(\n requestId: string,\n options: { messageId?: string; continuation?: boolean } = {}\n ): string {\n const streamId = this._resumableStream.start(requestId, options);\n // Flush connections parked during this turn's pre-stream window (#1784)\n // into the normal STREAM_RESUMING path now that a stream exists. Safe for\n // every turn — the awaiting set is empty unless a client reconnected before\n // the first chunk. (Continuation-turn parks live in `_continuation` and are\n // flushed below.)\n this._preStream.flushOnStreamStart((c) => this._notifyStreamResuming(c));\n if (this._continuation.pending?.requestId === requestId) {\n this._continuation.activatePending();\n this._flushAwaitingStreamStartConnections();\n this._activateDeferredAutoContinuation();\n }\n // Arm on START as well as finish so cleanup still has a belt-and-suspenders\n // wake if fiber recovery cannot finalize a stream. The last-activity sweep\n // threshold keeps an actively streaming run from being reclaimed before it\n // goes quiet (#1706).\n void this._ensureStreamCleanupScheduled();\n return streamId;\n }\n\n /** @internal Delegate to _resumableStream */\n protected _completeStream(streamId: string) {\n const completedRequestId = this._resumableStream.activeRequestId;\n this._resumableStream.complete(streamId);\n this._pendingResumeConnections.clear();\n if (completedRequestId === this._continuation.activeRequestId) {\n this._continuation.activeRequestId = null;\n this._continuation.activeConnectionId = null;\n }\n void this._ensureStreamCleanupScheduled();\n }\n\n /**\n * Ensure a single cleanup alarm is pending for this DO's resumable-stream\n * buffers. Armed whenever a stream finishes (completes or errors) so that\n * idle/one-off chat DOs still reclaim their buffers — the lazy sweep in\n * {@link ResumableStream} only fires when a *subsequent* stream completes,\n * which never happens for a chat that receives a single turn (#1706).\n *\n * `idempotent` dedupes on (callback, payload, owner) so repeated finishes\n * collapse onto one pending alarm rather than stacking.\n * @internal\n */\n protected async _ensureStreamCleanupScheduled({\n idempotent = true\n }: { idempotent?: boolean } = {}): Promise<void> {\n await this.schedule(\n STREAM_CLEANUP_DELAY_SECONDS,\n \"_cleanupStreamBuffers\",\n undefined,\n { idempotent }\n );\n }\n\n /**\n * Alarm callback: sweep aged stream buffers, re-arming while rows remain (see\n * the shared {@link cleanupStreamBuffers}). Public so it is reachable as a\n * schedule callback.\n * @internal\n */\n async _cleanupStreamBuffers(): Promise<void> {\n await cleanupStreamBuffers(this._resumableStream, () =>\n this._ensureStreamCleanupScheduled({ idempotent: false })\n );\n }\n\n /** @internal Delegate to _resumableStream. Also advances the recovery\n * progress counter at production time (see `_maybeBumpRecoveryProgress`). */\n protected async _storeStreamChunk(streamId: string, body: string) {\n this._resumableStream.storeChunk(streamId, body);\n let type: string | undefined;\n try {\n type = (JSON.parse(body) as { type?: string }).type;\n } catch {\n // non-JSON chunk body — nothing to credit\n }\n await this._maybeBumpRecoveryProgress(type);\n }\n\n /** Per-isolate throttle for crediting recovery progress from mid-segment\n * streaming-content deltas (the shared `agents/chat` rule); reset per isolate\n * so the first delta after a restart always credits. */\n private _streamProgressCredit = new StreamProgressCreditThrottle();\n\n /** Advance the recovery-progress counter when a chunk represents genuinely\n * new produced content. Uses the shared host-agnostic rule\n * ({@link shouldCreditStreamProgress}): a milestone (started segment / settled\n * tool) always credits, and a long single segment's streaming deltas credit\n * through a time throttle so the no-progress window doesn't false-fire while\n * content streams across crashes. Bumped at production time, so it reflects\n * real forward progress and is immune to client reconnects / recovery\n * re-persists (which replay or re-materialize stored chunks rather than flow\n * through here). This is what the recovery no-progress window keys off\n * (#1637), and stays compaction-proof (#1628). */\n private async _maybeBumpRecoveryProgress(\n type: string | undefined\n ): Promise<void> {\n if (\n shouldCreditStreamProgress({\n codec: aiSdkRecoveryCodec,\n type,\n throttle: this._streamProgressCredit,\n now: Date.now()\n })\n ) {\n await this._bumpChatRecoveryProgress();\n }\n }\n\n /** @internal Delegate to _resumableStream */\n protected _flushChunkBuffer() {\n this._resumableStream.flushBuffer();\n }\n\n /** @internal Delegate to _resumableStream */\n protected _restoreActiveStream() {\n this._resumableStream.restore();\n }\n\n /** @internal Delegate to _resumableStream */\n protected _markStreamError(streamId: string) {\n const erroredRequestId = this._resumableStream.activeRequestId;\n this._resumableStream.markError(streamId);\n this._pendingResumeConnections.clear();\n if (erroredRequestId === this._continuation.activeRequestId) {\n this._continuation.activeRequestId = null;\n this._continuation.activeConnectionId = null;\n }\n void this._ensureStreamCleanupScheduled();\n }\n\n /**\n * Reconstruct and persist a partial assistant message from an orphaned\n * stream's stored chunks. Called when the DO wakes from hibernation and\n * discovers an active stream with no live LLM reader.\n *\n * Built from the three orphan-persist seams the chat-recovery RFC factored\n * out — all three are ai-chat's substrate-specific realizations of a shape\n * `Think` shares:\n * - (a) reconstruct via the shared `StreamAccumulator` (the same primitive\n * `Think` and the client reducer use), replacing a hand-rolled chunk\n * switch; it owns the `start` / `finish` / `message-metadata` handling;\n * - (b) {@link _resolveOrphanTargetId} — the id to persist under (#1691);\n * - (c)+(d) upsert-by-id over the flat array, the `SessionProvider`-subset\n * store-write shape (`getMessage` → `updateMessage` / `appendMessage`)\n * that `Think._upsertMessageInHistory` implements over a Session tree.\n * When a row already owns the id, the shared `reconcileOrphanPartial`\n * merge preserves an in-place tool result rather than letting a replayed\n * chunk re-advance it (ai-chat has an early tool-approval persist; hosts\n * without one append straight through).\n * @internal\n */\n protected async _persistOrphanedStream(streamId: string): Promise<void> {\n const chunks = this._resumableStream.getStreamChunks(streamId);\n if (!chunks.length) return;\n\n // The accumulate loop and the `getMessage → update(merge) XOR append` upsert\n // are the shared `persistReconstructedOrphan` core. ai-chat supplies the two\n // host-specific hooks:\n // - prepare: resolve the persist-target id (#1691) — the one per-package\n // step (a flat array can't express the tree a Session uses). A provider\n // `start.messageId` is adopted by the accumulator (the live path adopts\n // it for new turns too); continuations have it stripped before storage\n // (#1229), so the unconditional adopt matches the live path.\n // - merge: a row may already own this id (an early persist during tool\n // approval, or a continuation resuming the last assistant message) —\n // reconcile onto it via the shared `reconcileOrphanPartial` so an\n // in-place tool result isn't re-advanced by a replayed chunk.\n // The store routes each write through `persistMessages` (exactly one write →\n // one `persistMessages` → one broadcast), so no explicit broadcast here.\n // NOTE: progress is bumped at production/flush time in `_storeStreamChunk`\n // (#1637), NOT here — persisting on recovery or a client reconnect must not\n // be miscounted as new forward progress.\n const fallbackId = `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;\n await persistReconstructedOrphan(chunks, {\n store: this._orphanStore(),\n fallbackId,\n prepare: (message) => {\n message.id = this._resolveOrphanTargetId(\n streamId,\n message.id,\n fallbackId\n );\n return message;\n },\n merge: (existing, incoming) => reconcileOrphanPartial(existing, incoming)\n });\n }\n\n /**\n * Resolve the id an orphaned partial should persist under — orphan-persist\n * step **(b)**, and the one legitimately per-package piece of the path: a\n * flat `UIMessage[]` can't express the parent/child a Session tree uses to\n * resolve this structurally, so ai-chat reads it from stream metadata.\n *\n * When the reconstructed message already adopted a provider `start.messageId`\n * (kept as-is — the live path adopts it for new turns too) `reconstructedId`\n * differs from `fallbackId` and is returned unchanged. Otherwise resolve to:\n * - the id allocated when the stream started, recorded in stream metadata\n * (#1691) — the SAME id the live path persists under (it only adopts a\n * provider id, never invents one). A new turn stored its own fresh id, so\n * it becomes its own message; a continuation stored the cloned\n * last-assistant id, so it merges. This is what stops a new turn after a\n * later user message from being folded into the previous assistant\n * message (the #1691 corruption); or\n * - (legacy rows written before the metadata column existed) the last\n * assistant message, matching pre-#1691 behavior.\n * @internal\n */\n protected _resolveOrphanTargetId(\n streamId: string,\n reconstructedId: string,\n fallbackId: string\n ): string {\n if (reconstructedId !== fallbackId) return reconstructedId;\n const storedId = this._resumableStream.getStreamMessageId(streamId);\n if (storedId != null) return storedId;\n for (let i = this.messages.length - 1; i >= 0; i--) {\n if (this.messages[i].role === \"assistant\") return this.messages[i].id;\n }\n return reconstructedId;\n }\n\n /**\n * The orphan-persist store adapter — orphan-persist steps **(c)/(d)** route\n * their write through this shared `OrphanPersistStore` seam (the\n * `SessionProvider` write-subset). Backed by ai-chat's flat `this.messages`\n * array + the existing `persistMessages` whole-array write path, so\n * reconcile/sanitize/row-size/broadcast all stay intact. Each mutating call\n * is exactly one `persistMessages` invocation; `parentId` is unused (a flat\n * array has no tree to attach to).\n * @internal\n */\n protected _orphanStore(): OrphanPersistStore {\n return {\n getMessage: (id) => this.messages.find((m) => m.id === id) ?? null,\n appendMessage: (message) =>\n this.persistMessages([...this.messages, message]),\n updateMessage: (message) =>\n this.persistMessages(\n this.messages.map((m) => (m.id === message.id ? message : m))\n )\n };\n }\n\n /**\n * Repair a single interrupted tool call — a tool part with no settled result,\n * left behind when a stream was cut off mid-flight (e.g. a SERVER tool whose\n * `execute()` died with an evicted isolate, leaving an `input-available`\n * orphan that nothing will ever resolve). Returns the replacement part that\n * takes its place in the transcript; `input` has already been normalized to a\n * valid object.\n *\n * The default flips it to an errored tool result so the record survives (no\n * \"disappearing\" tool call) and `convertToModelMessages` still gets a\n * tool-result for it, avoiding `AI_MissingToolResultsError` on the next\n * provider call. This mirrors `@cloudflare/think` so ai-chat RECOVERS an\n * interrupted server tool (repairs, then continues) instead of waiting on a\n * dead orphan until its budget is spent.\n *\n * Override to customize the repaired shape for client-resolved tools — e.g.\n * convert an interrupted question tool (no server `execute`, normally answered\n * by the user's next message) into a plain text part so the model sees it as\n * ordinary conversation rather than a tool error. A returned tool part MUST\n * carry a settled result (`output-available` / `output-error` /\n * `output-denied` or an `output` / `result` field); returning a non-tool part\n * (e.g. text) is fine.\n */\n protected repairInterruptedToolPart(\n part: UIMessage[\"parts\"][number]\n ): UIMessage[\"parts\"][number] {\n return {\n ...part,\n state: \"output-error\",\n errorText: \"The tool call was interrupted before a result was recorded.\"\n } as UIMessage[\"parts\"][number];\n }\n\n /**\n * Transcript repair, run before EVERY inference chokepoint (live submit, tool\n * auto-continuation, `continueLastTurn`, `saveMessages`/retry, and the chat\n * recovery callbacks). An interrupted server-tool orphan is flipped to a\n * settled (errored) result — via the shared `agents/chat`\n * `repairInterruptedToolParts` primitive, the SAME logic `@cloudflare/think`\n * runs before its own inference (`_assembleModelMessages`) — so the app's next\n * `convertToModelMessages(this.messages)` doesn't 400 with\n * `AI_MissingToolResultsError`. Because the app owns the inference call, the\n * framework can't repair \"inside\" it the way Think does; it repairs\n * `this.messages` at each point right before handing control to\n * `onChatMessage` instead. This reaches the cases the recovery-only repair\n * missed, including a mixed client+server orphan whose client replay drives\n * an auto-continuation.\n *\n * Scope: repair only ever flips a DEAD SERVER orphan (an interrupted tool with\n * no settled result whose `execute()` died with the evicted isolate). A part\n * still legitimately awaiting a CLIENT interaction — an `input-available`\n * client tool the SPA replays, or an `approval-requested` part the user may\n * still answer — is left verbatim via the shared `shouldRepair` skip, so it is\n * never clobbered with an error. This is per-part (not a whole-transcript\n * guard), so a fresh dead-server orphan at the leaf is still repaired even if\n * an unrelated abandoned client orphan sits earlier in history.\n *\n * Repair only ever reshapes ASSISTANT tool parts; it never touches user\n * messages, so per-channel policy carried on the user message's\n * `metadata.channel` (re-resolved on wake) is structurally untouched. It is a\n * no-op (no write, no broadcast) when nothing needs repair — the common case\n * for a healthy transcript. When anything changes, the corrected transcript is\n * persisted and broadcast through the normal `persistMessages` write path (one\n * write, one broadcast), which also refreshes `this.messages`.\n * @internal\n */\n private async _repairInterruptedToolsBeforeTurn(): Promise<void> {\n const clientResolvable = this._clientResolvableToolNames();\n const repaired = repairInterruptedToolParts(this.messages, {\n repairPart: (part) => this.repairInterruptedToolPart(part),\n shouldRepair: (part) =>\n !this._partAwaitsClientInteraction(part, clientResolvable)\n });\n if (repaired.removedToolCalls === 0 && repaired.normalizedInputs === 0) {\n return;\n }\n await this.persistMessages(repaired.messages);\n }\n\n /**\n * Restore _lastBody and _lastClientTools from SQLite.\n * Called in the constructor so these values survive DO hibernation.\n * @internal\n */\n private _restoreRequestContext() {\n const rows =\n this.sql<{ key: string; value: string }>`\n select key, value from cf_ai_chat_request_context\n ` || [];\n\n for (const row of rows) {\n try {\n if (row.key === \"lastBody\") {\n this._lastBody = JSON.parse(row.value);\n } else if (row.key === \"lastClientTools\") {\n this._lastClientTools = JSON.parse(row.value);\n }\n } catch {\n // Corrupted row — ignore and let the next request overwrite it\n }\n }\n }\n\n /**\n * Persist _lastBody and _lastClientTools to SQLite so they survive hibernation.\n * Uses upsert (INSERT OR REPLACE) so repeated calls are safe.\n * @internal\n */\n private _persistRequestContext() {\n // Persist or delete body\n if (this._lastBody) {\n this.sql`\n insert or replace into cf_ai_chat_request_context (key, value)\n values ('lastBody', ${JSON.stringify(this._lastBody)})\n `;\n } else {\n this.sql`delete from cf_ai_chat_request_context where key = 'lastBody'`;\n }\n // Persist or delete client tools\n if (this._lastClientTools) {\n this.sql`\n insert or replace into cf_ai_chat_request_context (key, value)\n values ('lastClientTools', ${JSON.stringify(this._lastClientTools)})\n `;\n } else {\n this\n .sql`delete from cf_ai_chat_request_context where key = 'lastClientTools'`;\n }\n }\n\n private _broadcastChatMessage(message: OutgoingMessage, exclude?: string[]) {\n // Combine explicit exclusions with connections pending stream resume.\n // Pending connections should not receive live stream chunks until they ACK,\n // at which point they'll receive the full replay via _sendStreamChunks.\n const allExclusions = [\n ...(exclude || []),\n ...this._pendingResumeConnections\n ];\n this.broadcast(JSON.stringify(message), allExclusions);\n }\n\n /**\n * Broadcasts a text event for non-SSE responses.\n * This ensures plain text responses follow the AI SDK v5 stream protocol.\n *\n * @param streamId - The stream identifier for chunk storage\n * @param event - The text event payload (text-start, text-delta with delta, or text-end)\n * @param continuation - Whether this is a continuation of a previous stream\n */\n private async _broadcastTextEvent(\n streamId: string,\n event:\n | { type: \"text-start\"; id: string }\n | { type: \"text-delta\"; id: string; delta: string }\n | { type: \"text-end\"; id: string },\n continuation: boolean\n ) {\n const body = JSON.stringify(event);\n await this._storeStreamChunk(streamId, body);\n this._broadcastChatMessage({\n body,\n done: false,\n id: event.id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n ...(continuation && { continuation: true })\n });\n }\n\n private _loadMessagesFromDb(): UIMessage[] {\n const rows =\n this.sql`select * from cf_ai_chat_agent_messages order by created_at` ||\n [];\n\n // Populate the persistence cache from DB so incremental persistence\n // can skip SQL writes for messages already stored.\n this._persistedMessageCache.clear();\n\n return rows\n .map((row) => {\n try {\n const messageStr = row.message as string;\n const parsed = JSON.parse(messageStr) as UIMessage;\n\n // Structural validation: ensure required fields exist and have\n // the correct types. This catches corrupted rows, manual tampering,\n // or schema drift from older versions without crashing the agent.\n if (!isValidMessageStructure(parsed)) {\n console.warn(\n `[AIChatAgent] Skipping invalid message ${row.id}: ` +\n \"missing or malformed id, role, or parts\"\n );\n return null;\n }\n\n // Cache the raw JSON keyed by message ID\n this._persistedMessageCache.set(parsed.id, messageStr);\n return parsed;\n } catch (error) {\n console.error(`Failed to parse message ${row.id}:`, error);\n return null;\n }\n })\n .filter((msg): msg is UIMessage => msg !== null);\n }\n\n private async _tryCatchChat<T>(fn: () => T | Promise<T>) {\n try {\n return await fn();\n } catch (e) {\n throw this.onError(e);\n }\n }\n\n private isChatTurnActive(): boolean {\n return this._turnQueue.isActive;\n }\n\n /**\n * Wait until the agent is fully idle — both the turn queue is drained\n * AND no submits are in flight between the concurrency decision and\n * `_runExclusiveChatTurn` (mid-`persistMessages` etc.).\n *\n * Just awaiting `_turnQueue.waitForIdle()` would miss submits whose\n * handlers have bumped `_latestOverlappingSubmitSequence` and\n * incremented `_pendingEnqueueCount` but haven't yet reached\n * `_runExclusiveChatTurn` — those would race with anything calling\n * `waitForIdle()` (tests, `waitUntilStable`, recovery code).\n */\n private async waitForIdle(): Promise<void> {\n for (;;) {\n await this._submitConcurrency.waitForIdle(() =>\n this._turnQueue.waitForIdle()\n );\n // An armed coalesce timer / in-flight barrier drain means an\n // auto-continuation decision is imminent (#1650): it will either enqueue\n // a continuation turn (re-busying the queue) or park on an incomplete\n // batch. Wait for that decision to resolve before reporting idle so a\n // debounced continuation isn't missed by idle observers (tests,\n // recovery).\n if (!this._hasArmedContinuation()) return;\n await new Promise<void>((resolve) =>\n setTimeout(resolve, AutoContinuationController.COALESCE_MS)\n );\n }\n }\n\n /**\n * `true` when an auto-continuation is armed and going to fire on its own —\n * its coalesce timer is still pending or its completeness barrier is\n * mid-drain (#1650). Such an agent is NOT idle/stable: a continuation turn is\n * imminent, so idle observers (recovery, idle-eviction, tests) must keep\n * waiting until it either enqueues a turn or parks on an incomplete batch.\n * A continuation that has already entered its turn (`pastCoalesce`) is\n * covered by the turn queue, and a parked one (waiting on an unanswered\n * sibling) is covered by `hasPendingInteraction()`, so neither is reported\n * here.\n */\n private _hasArmedContinuation(): boolean {\n return (\n this._continuation.pending !== null &&\n !this._continuation.pending.pastCoalesce &&\n this._autoContinuation.isArmed()\n );\n }\n\n private _getSubmitConcurrencyDecision(\n trigger: ChatRequestTrigger\n ): SubmitConcurrencyDecision {\n const decision = this._submitConcurrency.decide({\n concurrency: this.messageConcurrency,\n isSubmitMessage: trigger === \"submit-message\",\n queuedTurns: this._turnQueue.queuedCount()\n });\n\n if (decision.strategy === \"merge\") {\n if (\n !this._mergeQueuedUserStartIndexByEpoch.has(this._turnQueue.generation)\n ) {\n this._mergeQueuedUserStartIndexByEpoch.set(\n this._turnQueue.generation,\n this.messages.length\n );\n }\n }\n\n return decision;\n }\n\n private async _mergeQueuedUserMessages(\n epoch = this._turnQueue.generation\n ): Promise<void> {\n const mergedMessages = this._getMergedQueuedUserMessages(epoch);\n if (!mergedMessages) {\n return;\n }\n\n await this.persistMessages(mergedMessages, [], {\n _deleteStaleRows: true\n });\n }\n\n private _getMergedQueuedUserMessages(epoch: number): UIMessage[] | null {\n const queuedUserStart = this._mergeQueuedUserStartIndexByEpoch.get(epoch);\n if (queuedUserStart === undefined) {\n return null;\n }\n\n let queuedUserEnd = queuedUserStart;\n while (this.messages[queuedUserEnd]?.role === \"user\") {\n queuedUserEnd++;\n }\n\n if (\n queuedUserEnd === queuedUserStart &&\n queuedUserStart < this.messages.length\n ) {\n console.warn(\n `[AIChatAgent] merge: expected user messages at index ${queuedUserStart} ` +\n `but found role=\"${this.messages[queuedUserStart]?.role}\"; skipping merge`\n );\n }\n\n const queuedUserMessages = this.messages.slice(\n queuedUserStart,\n queuedUserEnd\n );\n if (queuedUserMessages.length < 2) {\n return null;\n }\n\n return [\n ...this.messages.slice(0, queuedUserStart),\n AIChatAgent._mergeUserMessages(queuedUserMessages),\n ...this.messages.slice(queuedUserEnd)\n ];\n }\n\n private static _mergeUserMessages(messages: UIMessage[]): UIMessage {\n const [firstMessage, ...remainingMessages] = messages;\n if (!firstMessage) {\n throw new Error(\"cannot merge an empty message list\");\n }\n\n let mergedParts = AIChatAgent._cloneMessageParts(firstMessage.parts);\n for (const message of remainingMessages) {\n AIChatAgent._appendMergedText(mergedParts, \"\\n\\n\");\n mergedParts = AIChatAgent._mergeMessageParts(mergedParts, message.parts);\n }\n\n const lastMessage = messages[messages.length - 1] ?? firstMessage;\n return {\n ...lastMessage,\n parts: mergedParts\n };\n }\n\n private static _mergeMessageParts(\n currentParts: UIMessage[\"parts\"],\n nextParts: UIMessage[\"parts\"]\n ): UIMessage[\"parts\"] {\n const mergedParts = AIChatAgent._cloneMessageParts(currentParts);\n\n for (const part of nextParts) {\n if (part.type === \"text\") {\n AIChatAgent._appendMergedText(mergedParts, part.text);\n continue;\n }\n\n mergedParts.push(part);\n }\n\n return mergedParts;\n }\n\n private static _cloneMessageParts(\n parts: UIMessage[\"parts\"]\n ): UIMessage[\"parts\"] {\n return [...parts];\n }\n\n private static _appendMergedText(\n parts: UIMessage[\"parts\"],\n text: string\n ): void {\n if (text.length === 0) {\n return;\n }\n\n const lastPart = parts[parts.length - 1];\n if (lastPart?.type === \"text\") {\n parts[parts.length - 1] = {\n ...lastPart,\n text: lastPart.text + text\n };\n return;\n }\n\n const textPart: TextUIPart = {\n type: \"text\",\n text\n };\n parts.push(textPart);\n }\n\n private _setRequestContext(\n clientTools?: ClientToolSchema[],\n body?: Record<string, unknown>\n ) {\n this._lastClientTools = clientTools?.length ? clientTools : undefined;\n this._lastBody = body && Object.keys(body).length > 0 ? body : undefined;\n this._persistRequestContext();\n }\n\n private _messagesForClientSync(): readonly UIMessage[] {\n if (!this._streamingMessage || this._streamingMessage.parts.length === 0) {\n return this.messages;\n }\n\n const existingIdx = this.messages.findIndex(\n (message) => message.id === this._streamingMessage?.id\n );\n\n if (existingIdx >= 0) {\n return this.messages.map((message, idx) =>\n idx === existingIdx && this._streamingMessage\n ? this._streamingMessage\n : message\n );\n }\n\n return [...this.messages, this._streamingMessage];\n }\n\n private _sendDirectMessage(\n connection: Connection,\n message: OutgoingMessage\n ): void {\n try {\n connection.send(JSON.stringify(message));\n } catch {\n // Connection closed before the server could reply.\n }\n }\n\n private _completeSkippedRequest(connection: Connection, requestId: string) {\n this._sendDirectMessage(connection, {\n body: \"\",\n done: true,\n id: requestId,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE\n });\n // A skipped turn settles out of the pre-stream set, but must NOT release\n // parked connections (#1784): a skip happens because a NEWER turn was\n // admitted (latest/merge supersede) or the queue generation advanced. The\n // earliest \"successor exists\" signal (`SubmitConcurrencyController.decide`)\n // fires before the successor's `_preStream.begin()`, so releasing here would\n // race a `begin()` that hasn't run yet and cut a parked client loose right\n // before the successor streams. Leave it parked: the successor flushes it on\n // `_startStream`, or the final surviving turn's settle releases it. (Chat\n // clear releases parked connections explicitly via `resetTurnState`.)\n this._settlePreStreamTurn(requestId, { releaseParked: false });\n }\n\n /** Whether a connection with this id is still attached. */\n private _isConnectionPresent(connectionId: string): boolean {\n return this.getConnection(connectionId) !== undefined;\n }\n\n /**\n * Mark an accepted turn (#1784) as settled. When `releaseParked` (the default)\n * and no accepted turn remains in flight and no stream is active, release every\n * parked connection with STREAM_RESUME_NONE so a client that reconnected during\n * the pre-stream window stops waiting. A no-op when the parked set was already\n * flushed on stream start. Skip paths pass `releaseParked: false` so a parked\n * client survives onto the successor turn (see `_completeSkippedRequest`).\n */\n private _settlePreStreamTurn(\n requestId: string,\n options: { releaseParked?: boolean } = {}\n ): void {\n const idle = this._preStream.settle(requestId);\n const releaseParked = options.releaseParked ?? true;\n if (releaseParked && idle && !this._resumableStream.hasActiveStream()) {\n this._preStream.releaseAwaiting();\n }\n }\n\n private _rollbackDroppedSubmit(connection: Connection) {\n this._sendDirectMessage(connection, {\n messages: this._messagesForClientSync(),\n type: MessageType.CF_AGENT_CHAT_MESSAGES\n });\n }\n\n /** `true` when an assistant message is waiting on a client tool result or approval. */\n protected hasPendingInteraction(): boolean {\n if (\n this._streamingMessage &&\n this._messageHasPendingInteraction(this._streamingMessage)\n ) {\n return true;\n }\n\n return this.messages.some(\n (message) =>\n message.role === \"assistant\" &&\n this._messageHasPendingInteraction(message)\n );\n }\n\n /**\n * Waits until the conversation is fully stable — no active stream, no\n * pending client-tool interactions, and no queued continuation turns.\n *\n * Returns `true` when stable. Returns `false` if `timeout` expires before\n * a pending interaction resolves. Safe to call at any time; if there is\n * nothing pending it returns immediately.\n *\n * `pendingInteraction` overrides which \"still waiting\" predicate gates\n * stability. It defaults to the broad {@link hasPendingInteraction} (any\n * `input-available` / `approval-requested` part) to preserve the documented\n * semantics for app overrides. The recovery paths pass the narrower\n * {@link hasPendingClientInteraction} so a DEAD server-tool `input-available`\n * orphan (its `execute()` died with the evicted isolate; nothing will resolve\n * it) does NOT block stability — recovery then repairs it to an errored\n * result and continues, instead of waiting until the budget is spent. This\n * mirrors `@cloudflare/think`, whose single pending predicate is already\n * client-only by construction.\n */\n protected async waitUntilStable(options?: {\n timeout?: number;\n pendingInteraction?: () => boolean;\n }): Promise<boolean> {\n const deadline =\n options?.timeout != null ? Date.now() + options.timeout : null;\n const hasPendingInteraction =\n options?.pendingInteraction ?? (() => this.hasPendingInteraction());\n\n while (true) {\n // Drain active turns AND any in-flight submits past the concurrency\n // decision (mid-`persistMessages`) so `hasPendingInteraction()`\n // reflects settled message state rather than in-flight streaming\n // state. Just `_turnQueue.waitForIdle()` would miss submits whose\n // handlers have bumped `_latestOverlappingSubmitSequence` and\n // incremented `_pendingEnqueueCount` but haven't yet enqueued.\n while (true) {\n if (\n (await this._awaitWithDeadline(\n this._turnQueue.waitForIdle(),\n deadline\n )) === TIMED_OUT\n ) {\n return false;\n }\n if (this._submitConcurrency.pendingEnqueueCount === 0) break;\n if (\n (await this._awaitWithDeadline(\n new Promise<void>((resolve) => setTimeout(resolve, 5)),\n deadline\n )) === TIMED_OUT\n ) {\n return false;\n }\n }\n\n if (!hasPendingInteraction()) {\n if (!this._hasArmedContinuation()) {\n return true;\n }\n // An auto-continuation is armed (#1650) — not stable yet. Wait for it\n // to fire (enqueuing a turn the outer loop then drains) or park, then\n // re-check.\n if (\n (await this._awaitWithDeadline(\n new Promise<void>((resolve) =>\n setTimeout(resolve, AutoContinuationController.COALESCE_MS)\n ),\n deadline\n )) === TIMED_OUT\n ) {\n return false;\n }\n continue;\n }\n\n const pending = this._pendingInteractionPromise;\n if (pending) {\n let result: boolean | typeof TIMED_OUT;\n try {\n result = await this._awaitWithDeadline(pending, deadline);\n } catch {\n continue;\n }\n\n if (result === TIMED_OUT) {\n return false;\n }\n } else {\n // No tool result/approval apply is currently in flight; we are still\n // waiting for the user to resolve the interaction.\n if (\n (await this._awaitWithDeadline(\n new Promise<void>((resolve) => setTimeout(resolve, 100)),\n deadline\n )) === TIMED_OUT\n ) {\n return false;\n }\n }\n }\n }\n\n private abortActiveTurn(): boolean {\n if (!this._turnQueue.activeRequestId) {\n return false;\n }\n\n this._abortRegistry.cancel(this._turnQueue.activeRequestId);\n return true;\n }\n\n /**\n * Aborts the active turn and invalidates queued continuations. Call this\n * when intercepting `CF_AGENT_CHAT_CLEAR` before the SDK sees the message —\n * the built-in handler calls it automatically.\n */\n protected resetTurnState(): void {\n this._mergeQueuedUserStartIndexByEpoch.delete(this._turnQueue.generation);\n this._turnQueue.reset();\n this._abortRegistry.destroyAll();\n this._submitConcurrency.reset();\n this._pendingInteractionPromise = null;\n // Drop the apply chain so new interactions don't serialize behind a stale\n // (possibly hung) apply from the turn we just reset (#1649).\n this._interactionApplyTail = Promise.resolve();\n // Tear down the event-driven auto-continuation barrier (#1650): cancel the\n // coalesce timer and clear the double-fire / stream-active gates so a reset\n // mid-park can't leave a stale flag pinning future continuations.\n this._autoContinuation.reset();\n this._streamingTurnActive = false;\n this._continuation.sendResumeNone();\n this._continuation.clearAll();\n this._preStream.releaseAwaiting();\n this._preStream.reset();\n this._pendingChatResponseResults.length = 0;\n }\n\n /**\n * Abort a single in-flight chat turn by request id.\n *\n * Equivalent to the cancel path that fires when a client sends a\n * `chat-request-cancel` WebSocket message — the inference loop's\n * signal aborts and the turn's `ChatResponseResult` reports\n * `status: \"aborted\"`. No-op if no controller exists for `requestId`.\n *\n * Most callers don't have the request id and want\n * {@link abortAllRequests} instead. Prefer\n * {@link SaveMessagesOptions.signal} when driving a turn\n * programmatically — it threads the abort intent in from the start\n * without requiring the caller to know the id.\n */\n protected abortRequest(requestId: string, reason?: unknown): void {\n this._abortRegistry.cancel(requestId, reason);\n }\n\n /**\n * Abort every in-flight chat turn on this agent.\n *\n * Aborts all controllers in the registry and clears it. Used by\n * subclasses that drive single-purpose turns (e.g. an RPC-driven\n * sub-agent helper that runs one turn at a time) and want a coarse\n * \"cancel whatever is running\" handle without tracking request ids.\n *\n * Does NOT reset queued turns, continuation timers, or submit\n * concurrency state — use {@link resetTurnState} for the full\n * teardown that runs on `chat-clear`.\n */\n protected abortAllRequests(reason?: unknown): void {\n this._abortRegistry.destroyAll(reason);\n }\n\n private _awaitWithDeadline<T>(\n promise: Promise<T>,\n deadline: number | null\n ): Promise<T | typeof TIMED_OUT> {\n return awaitWithDeadline(promise, deadline);\n }\n\n private _messageHasPendingInteraction(message: UIMessage): boolean {\n return message.parts.some(\n (part) =>\n \"state\" in part &&\n (part.state === \"input-available\" ||\n part.state === \"approval-requested\")\n );\n }\n\n /**\n * `true` when the turn is parked on a pending interaction that the CLIENT can\n * still resolve after a restart — an `approval-requested` part, or an\n * `input-available` part for a CLIENT tool (no server `execute`) whose\n * `tool-result` the SPA replays over the WebSocket on reconnect.\n *\n * This is intentionally NARROWER than `hasPendingInteraction()` (which\n * `waitUntilStable` uses): a SERVER tool's `input-available` orphan is\n * excluded, because its `execute()` promise died with the evicted isolate and\n * nothing will ever post its result — so it must NOT be treated as a healthy\n * \"waiting on the human\" wait. Used to make a HITL turn budget-free during\n * recovery so a slow human can't trip the no-progress / attempt / stable-\n * timeout budgets; see `_beginChatRecoveryIncident` and\n * `_parkRecoveryForPendingInteraction`. Mirrors `@cloudflare/think`'s\n * `hasPendingInteraction`, which is already client-only by construction.\n */\n protected hasPendingClientInteraction(): boolean {\n const clientResolvable = this._clientResolvableToolNames();\n if (\n this._streamingMessage &&\n this._messageAwaitsClientInteraction(\n this._streamingMessage,\n clientResolvable\n )\n ) {\n return true;\n }\n return this.messages.some(\n (message) =>\n message.role === \"assistant\" &&\n this._messageAwaitsClientInteraction(message, clientResolvable)\n );\n }\n\n private _messageAwaitsClientInteraction(\n message: UIMessage,\n clientResolvable: Set<string>\n ): boolean {\n return message.parts.some((part) =>\n this._partAwaitsClientInteraction(part, clientResolvable)\n );\n }\n\n /**\n * Whether a part is still awaiting a CLIENT interaction that can genuinely\n * arrive after a restart: an `approval-requested` part (a reconnecting client\n * replays the approval) or an `input-available` part for a CLIENT tool (the\n * SPA replays the `tool-result`). A SERVER tool's `input-available` is NOT\n * pending — its `execute()` died with the isolate. Mirrors `@cloudflare/think`.\n */\n private _partAwaitsClientInteraction(\n part: UIMessage[\"parts\"][number],\n clientResolvable: Set<string>\n ): boolean {\n return partAwaitsClientInteraction(part, clientResolvable);\n }\n\n /**\n * Names of the CLIENT-resolvable tools (the client-provided schemas from the\n * last request, which have no server `execute`). Mirrors `@cloudflare/think`.\n */\n private _clientResolvableToolNames(): Set<string> {\n return clientResolvableToolNames(this._lastClientTools);\n }\n\n /**\n * Run a chat turn exclusively so `_reply()` never overlaps with another\n * streaming turn.\n */\n private async _runExclusiveChatTurn<T>(\n requestId: string,\n fn: () => Promise<T>,\n options?: { epoch?: number; onStale?: () => void }\n ): Promise<T> {\n const generation = options?.epoch;\n let result: TurnResult<T>;\n try {\n result = await this._turnQueue.enqueue(\n requestId,\n () =>\n // A turn owns its own traced boundary, never that of whatever\n // admitted it: an auto-continuation fires from a coalescing timer\n // long after the handler that armed it returned, and a turn started\n // without being awaited outlives its caller. Either way the caller's\n // boundary would close every span in a turn that is still running.\n withInvocationScope(\n () =>\n withAgentSpan(\n this,\n \"chat_turn\",\n \"turn\",\n {\n \"cloudflare.agents.component\": \"ai_chat\",\n \"cloudflare.agents.turn.request_id\": requestId,\n \"cloudflare.agents.turn.admission\": \"queue\",\n \"cloudflare.agents.turn.generation\": generation\n },\n fn\n ),\n { detached: true }\n ),\n { generation }\n );\n } finally {\n // Clean merge map when all turns for a generation complete\n const gen = generation ?? this._turnQueue.generation;\n if (this._turnQueue.queuedCount(gen) === 0) {\n this._mergeQueuedUserStartIndexByEpoch.delete(gen);\n }\n\n if (\n this._pendingChatResponseResults.length > 0 &&\n !this._insideResponseHook\n ) {\n this._insideResponseHook = true;\n try {\n await this.keepAliveWhile(async () => {\n while (this._pendingChatResponseResults.length > 0) {\n const chatResult = this._pendingChatResponseResults.shift()!;\n // A later turn that ends in a non-error outcome supersedes any\n // pending terminal record (#1645) — both a successful turn and an\n // aborted one (the conversation has moved on either way; only a\n // fresh error should leave a terminal to replay). The\n // client-request handler already clears on a new submit; this\n // covers turns driven purely server-side (`saveMessages`,\n // auto-continuation) with no client request in between, so a\n // stale exhaustion can't replay on a later reconnect. Mirrors\n // Think's `_recordTerminalChatStatus`, which clears on any\n // non-error/non-interrupted status.\n if (\n chatResult.status === \"completed\" ||\n chatResult.status === \"aborted\"\n ) {\n await this._clearChatTerminal();\n } else if (chatResult.status === \"error\") {\n // A terminal (non-recovered) error — e.g. a provider 500 surfaced\n // as a stream `error` part — has no durable trace otherwise, so a\n // client disconnected at this moment never learns the turn failed\n // and stays frozen on reconnect (#1645). Record it so it replays\n // over the resume handshake (shared\n // `ResumeHandshake._replayTerminalOnResume`). Mirrors\n // Think's `_fireResponseHook`, which records on `error` too.\n // Recoverable failures (deploy/eviction/stall) don't arrive here\n // as `error` — they reach the drain loop as `aborted`, or not at\n // all (the isolate is gone), and exhaustion records its own\n // terminal — so this can't pre-empt recovery.\n await this._recordChatTerminal(\n chatResult.requestId,\n chatResult.error ?? \"The assistant encountered an error.\"\n );\n }\n try {\n await this.onChatResponse(chatResult);\n } catch (hookError) {\n console.error(\"[AIChatAgent] onChatResponse threw:\", hookError);\n }\n }\n });\n } finally {\n this._insideResponseHook = false;\n }\n }\n }\n\n if (result!.status === \"stale\") {\n options?.onStale?.();\n return undefined as T;\n }\n return result!.value;\n }\n\n /**\n * Schedule an auto-continuation for a tool result/approval that opted in with\n * `autoContinue: true` (#1650). Thin host wrapper that builds the\n * {@link ContinuationSpec} and delegates to the shared\n * {@link AutoContinuationController}, which owns the coalesce timer and the\n * completeness-gated fire (shared with `@cloudflare/think`).\n */\n private _scheduleAutoContinuation(\n connection: Connection,\n clientTools: ClientToolSchema[] | undefined,\n body: Record<string, unknown> | undefined,\n errorPrefix: string\n ) {\n this._autoContinuation.schedule({\n connection,\n clientTools,\n body,\n errorPrefix\n });\n }\n\n /**\n * Re-arm the barrier for a result/approval that arrived WITHOUT `autoContinue`\n * (#1650). A standalone errored result declines to continue on its own, but in\n * a parallel batch a SIBLING may already have opted in — and this result can be\n * the one that completes the batch, so we must re-run the barrier check. Unlike\n * `_scheduleAutoContinuation` this NEVER creates a pending continuation (a\n * standalone errored tool with no opted-in sibling must not auto-continue), and\n * it no-ops once the continuation is running (`pastCoalesce`).\n */\n private _rearmPendingAutoContinuationForBatch(): void {\n this._autoContinuation.rearmForBatch();\n }\n\n /**\n * Called when a streaming assistant turn finalizes (its message, with ALL tool\n * parts, is now persisted). Clears the stream-active gate and re-runs the\n * barrier for a continuation the gate held (#1650). Essential for an all-fast\n * parallel batch whose every result landed mid-stream: once the stream ends\n * there is no further tool-result event to re-arm, so without this the held\n * continuation would never fire. A slow batch is re-checked here and simply\n * keeps holding (event-driven) until its remaining siblings answer.\n */\n private _onStreamingTurnFinalized(): void {\n this._streamingTurnActive = false;\n this._autoContinuation.rearmForBatch();\n }\n\n /**\n * Drain every in-flight tool-result/approval apply, including any enqueued\n * while we wait, so the subsequent `_hasIncompleteToolBatch()` re-check sees\n * every result that has ALREADY arrived. Bounded by real apply activity (a\n * storage write each), never by a fixed timer: the loop re-reads\n * `_interactionApplyTail` after each await because a sibling can extend the\n * tail mid-drain, and stops once the tail stops advancing. Mirrors\n * `@cloudflare/think`'s `_drainInteractionApplies`.\n */\n private _drainInteractionApplies(): Promise<void> {\n return drainInteractionApplies(\n () => this._continuation.pending !== null,\n () => this._interactionApplyTail\n );\n }\n\n /**\n * `true` when the latest assistant message is mid-batch: it carries at least\n * one settled tool result AND at least one tool call/approval still awaiting a\n * client result. That is the #1649 signature — the model fanned out parallel\n * tool calls and only some have been answered. Scoped to the leaf (the step\n * the continuation answers) so an unrelated dangling tool in an earlier\n * message doesn't block a legitimate follow-up continuation.\n */\n private _hasIncompleteToolBatch(): boolean {\n return hasIncompleteToolBatch(this.messages);\n }\n\n private _fireAutoContinuation() {\n const pending = this._continuation.pending;\n if (!pending) return;\n const requestId = pending.requestId;\n\n const epoch = this._turnQueue.generation;\n // _runExclusiveChatTurn must be called synchronously so the chat turn\n // queue is set up immediately — otherwise waitForIdle() can resolve\n // before the continuation starts. keepAlive() is called inside the\n // turn to prevent hibernation while streaming, without deferring the queue\n // registration.\n this._runExclusiveChatTurn(\n requestId,\n async () => {\n const dispose = await this.keepAlive();\n try {\n const connection = this._continuation.pending?.connection;\n if (!connection) {\n this._clearAllAutoContinuationState(true);\n return;\n }\n\n const clientTools = this._continuation.pending?.clientTools;\n const body = this._continuation.pending?.body;\n if (this._continuation.pending) {\n this._continuation.pending.pastCoalesce = true;\n }\n\n const abortSignal = this._abortRegistry.getSignal(requestId);\n\n return this._tryCatchChat(async () => {\n return agentContext.run(\n {\n agent: this,\n connection,\n request: undefined,\n email: undefined\n },\n async () => {\n const autoContinuationBody = async () => {\n try {\n await this._repairInterruptedToolsBeforeTurn();\n const response = await this.onChatMessage(\n async (_finishResult) => {},\n {\n requestId,\n abortSignal,\n clientTools,\n body,\n continuation: true\n }\n );\n\n if (response) {\n const replyResult = await this._reply(\n requestId,\n response,\n [],\n {\n continuation: true,\n chatMessageId: requestId\n }\n );\n if (replyResult.status === \"error\") {\n this._clearAllAutoContinuationState(true);\n return;\n }\n this._activateDeferredAutoContinuation();\n } else {\n this._clearPendingAutoContinuation(true);\n this._activateDeferredAutoContinuation();\n }\n } finally {\n this._abortRegistry.remove(requestId);\n }\n };\n\n await this._runChatRecoveryFiber(\n requestId,\n true,\n autoContinuationBody\n );\n }\n );\n });\n } finally {\n dispose();\n }\n },\n {\n epoch,\n onStale: () => this._clearAllAutoContinuationState(true)\n }\n ).catch((error) => {\n const errorPrefix =\n this._continuation.pending?.errorPrefix ??\n \"[AIChatAgent] Auto-continuation failed:\";\n this._clearAllAutoContinuationState(true);\n console.error(errorPrefix, error);\n });\n }\n\n /**\n * @returns Terminal status for the turn.\n */\n private async _runProgrammaticChatTurn(\n requestId: string,\n clientTools?: ClientToolSchema[],\n body?: Record<string, unknown>,\n externalSignal?: AbortSignal\n ): Promise<StreamResultStatus> {\n this._setRequestContext(clientTools, body);\n let wasAborted = false;\n let status: StreamResultStatus = { status: \"completed\" };\n\n await this._tryCatchChat(async () => {\n return agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n async () => {\n const abortSignal = this._abortRegistry.getSignal(requestId);\n // Wire the optional external signal to the registry's\n // controller. Detacher MUST run in `finally` to avoid leaking\n // listeners on long-lived parent signals — including the case\n // where `runFiber` itself throws (e.g. SQLite error inserting\n // the fiber row) before `programmaticBody` is ever invoked.\n const detachExternal = this._abortRegistry.linkExternal(\n requestId,\n externalSignal\n );\n try {\n const programmaticBody = async () => {\n await this._repairInterruptedToolsBeforeTurn();\n const response = await this.onChatMessage(() => {}, {\n requestId,\n abortSignal,\n clientTools,\n body,\n continuation: false\n });\n\n if (response) {\n status = await this._reply(requestId, response, [], {\n chatMessageId: requestId\n });\n }\n };\n\n await this._runChatRecoveryFiber(\n requestId,\n false,\n programmaticBody\n );\n } finally {\n if (abortSignal?.aborted) wasAborted = true;\n detachExternal();\n this._abortRegistry.remove(requestId);\n }\n }\n );\n });\n\n if (status.status === \"completed\" && wasAborted) {\n return { status: \"aborted\" };\n }\n return status;\n }\n\n /**\n * Handle incoming chat messages and generate a response\n * @param onFinish Callback to be called when the response is finished\n * @param options Options including abort signal and client-defined tools\n * @returns Response to send to the client or undefined\n */\n async onChatMessage(\n // oxlint-disable-next-line eslint(no-unused-vars) -- params used by subclass overrides\n _onFinish: GenerateTextOnFinishCallback<ToolSet>,\n // oxlint-disable-next-line eslint(no-unused-vars) -- params used by subclass overrides\n _options?: OnChatMessageOptions\n ): Promise<Response | undefined> {\n throw new Error(\n \"received a chat message, override onChatMessage and return a Response to send to the client\"\n );\n }\n\n /**\n * Called after a chat turn completes and the assistant message has been\n * persisted. The turn lock is released before this hook runs, so it is\n * safe to call `saveMessages` from inside.\n *\n * Fires for all turn completion paths: WebSocket chat requests,\n * `saveMessages`, and auto-continuation.\n *\n * Responses triggered from inside `onChatResponse` (e.g. via `saveMessages`)\n * do not fire `onChatResponse` recursively.\n *\n * The default implementation is a no-op.\n *\n * @param result - Information about the completed turn\n *\n * @example\n * ```ts\n * class MyAgent extends AIChatAgent<Env> {\n * protected async onChatResponse(result: ChatResponseResult) {\n * if (result.status === \"completed\") {\n * this.broadcast(JSON.stringify({ streaming: false }));\n * }\n * }\n * }\n * ```\n */\n protected onChatResponse(\n // oxlint-disable-next-line eslint(no-unused-vars) -- params used by subclass overrides\n _result: ChatResponseResult\n ): void | Promise<void> {}\n\n /**\n * Override this method to apply custom transformations to messages before\n * they are persisted to storage. This hook runs **after** the built-in\n * sanitization (OpenAI metadata stripping, Anthropic provider-executed tool\n * payload truncation, empty reasoning part filtering).\n *\n * The default implementation returns the message unchanged.\n *\n * @param message - The pre-sanitized message about to be persisted\n * @returns The transformed message to persist\n *\n * @example\n * ```ts\n * class MyAgent extends AIChatAgent<Env> {\n * protected sanitizeMessageForPersistence(\n * message: UIMessage\n * ): UIMessage {\n * return {\n * ...message,\n * parts: message.parts.map(part => {\n * if (\"output\" in part && typeof part.output === \"string\"\n * && part.output.length > 1000) {\n * return { ...part, output: \"[redacted]\" };\n * }\n * return part;\n * })\n * };\n * }\n * }\n * ```\n */\n protected sanitizeMessageForPersistence(\n // oxlint-disable-next-line eslint(no-unused-vars) -- params used by subclass overrides\n message: UIMessage\n ): UIMessage {\n return message;\n }\n\n /**\n * Convert an agent-tool input payload into the synthetic user message that\n * starts a headless `AIChatAgent` turn.\n */\n protected formatAgentToolInput(\n input: unknown,\n request: { runId: string }\n ): UIMessage {\n let text: string;\n try {\n text = typeof input === \"string\" ? input : JSON.stringify(input, null, 2);\n } catch {\n text = String(input);\n }\n\n return {\n id: `agent-tool-${request.runId}-input`,\n role: \"user\",\n parts: [{ type: \"text\", text }]\n };\n }\n\n private _agentToolProgressEmitterInstance: AgentToolProgressEmitter | null =\n null;\n\n private get _agentToolProgressEmitter(): AgentToolProgressEmitter {\n if (!this._agentToolProgressEmitterInstance) {\n this._agentToolProgressEmitterInstance = new AgentToolProgressEmitter({\n resolveActiveRun: () => {\n const requestId = this._activeRequestId;\n if (!requestId) return null;\n const runId = this._agentToolRunsByRequestId.get(requestId);\n return runId ? { runId, requestId } : null;\n },\n broadcast: (requestId, chunkBody) => {\n this._broadcastChatMessage({\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n id: requestId,\n body: chunkBody,\n done: false\n });\n },\n persistSnapshot: (runId, snapshot, at) => {\n this._ensureAgentToolTables();\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set progress_json = ${JSON.stringify(snapshot)},\n last_signal_at = ${at}\n where run_id = ${runId}\n `;\n },\n persistMilestone: (runId, name, data, at) =>\n this._persistAgentToolMilestone(runId, name, data, at)\n });\n }\n return this._agentToolProgressEmitterInstance;\n }\n\n override async reportProgress<T = unknown>(\n progress: AgentToolProgress<T>,\n options?: { persist?: boolean }\n ): Promise<void> {\n const result = this._agentToolProgressEmitter.report(progress, options);\n if (result === \"inactive\") {\n console.warn(\n \"[ai-chat] reportProgress() was called outside of an active agent-tool run; ignoring. Call it from within an onChatMessage turn that is running as a sub-agent.\"\n );\n }\n }\n\n /**\n * Override to return structured agent-tool output instead of the default\n * final assistant text.\n */\n protected getAgentToolOutput(\n _request: { runId: string; input: unknown },\n messagesAfterStart: readonly UIMessage[]\n ): unknown {\n return AIChatAgent._extractLatestAssistantText(messagesAfterStart);\n }\n\n /**\n * Override to customize the concise summary stored on the parent run.\n */\n protected getAgentToolSummary(\n _request: { runId: string; input: unknown },\n output: unknown,\n messagesAfterStart: readonly UIMessage[]\n ): string {\n if (typeof output === \"string\") return output;\n if (output === undefined) {\n return AIChatAgent._extractLatestAssistantText(messagesAfterStart) ?? \"\";\n }\n try {\n return JSON.stringify(output);\n } catch {\n return String(output);\n }\n }\n\n /** True while running inside this agent's own serialized detached-delivery\n * turn slot (set by {@link _runDetachedDelivery}); lets a `react` notify run\n * its reply inline rather than enqueuing (which would deadlock) or interleaving\n * with a foreign turn. */\n private _inSerializedDetachedDeliverySlot = false;\n\n /** Notification ids (`detached-finish:*` / `detached-ms:*`) currently being\n * injected, to dedupe a concurrent warm-tail + backbone delivery of the same\n * milestone within one isolate before the persisted message exists. */\n private _inFlightDetachedNotifications = new Set<string>();\n\n /**\n * Serialize detached terminal delivery against the chat turn queue. A\n * fast-path push or backbone tick can land mid-turn, and an `onFinish` that\n * mutates chat state (`saveMessages`, `setState`, a follow-up\n * `runAgentTool`) running concurrently with an active LLM turn is a data\n * race. Those paths never run synchronously inside a turn body (they fire\n * from `waitUntil` / a scheduled alarm), so enqueuing on the turn queue runs\n * the delivery strictly between turns without risk of self-deadlock.\n *\n * An explicit `cancelAgentTool` (`serialize` unset) may be invoked from\n * inside the very turn that triggers it, where enqueuing WOULD self-deadlock,\n * so it runs inline in the caller's (or a fresh) `agentContext`.\n */\n protected override async _runDetachedDelivery(\n invoke: () => Promise<void>,\n options?: { serialize?: boolean }\n ): Promise<void> {\n const inContext = () =>\n agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n invoke\n );\n if (!options?.serialize) {\n if (agentContext.getStore()?.agent === this) {\n await invoke();\n return;\n }\n await inContext();\n return;\n }\n await this.keepAliveWhile(() =>\n this._turnQueue.enqueue(\n `detached-delivery:${crypto.randomUUID()}`,\n // Mark the slot so `_injectDetachedNotification` knows it owns the active\n // turn and can run a `react` reply INLINE (vs a foreign active turn,\n // where inline would interleave and enqueue-await would deadlock).\n async () => {\n this._inSerializedDetachedDeliverySlot = true;\n try {\n await inContext();\n } finally {\n this._inSerializedDetachedDeliverySlot = false;\n }\n }\n )\n );\n }\n\n /**\n * Inject a synthetic chat message for a detached-run notification, idempotent\n * on its deterministic `id` (a re-delivery from the warm tail + cold backbone\n * collapses to one — `persistMessages` is skipped when the id already exists).\n * When `react` is set the model then takes a turn over the new message.\n *\n * `@cloudflare/ai-chat` has no durable-submission layer (unlike Think's\n * `submitMessages`), so the turn cannot be enqueued-and-awaited from inside the\n * serialized delivery slot — `TurnQueue` has no re-entrancy bypass, so that\n * would self-deadlock. Instead: when we are already inside a turn slot (the\n * `serialize: true` finish delivery runs as its own enqueued turn) we run the\n * programmatic turn INLINE, reusing that slot — so the whole notify completes\n * before the ledger marks the slot delivered (eviction-safe). When we are not\n * inside a slot (a milestone fired from the `waitUntil` fast path or the\n * reconcile alarm) we enqueue a fresh turn normally.\n */\n private async _injectDetachedNotification(\n id: string,\n role: \"user\" | \"assistant\",\n text: string,\n metadata: Record<string, unknown>,\n options: { react: boolean }\n ): Promise<void> {\n // `messages.some` covers re-delivery against persisted history (survives\n // eviction); the in-flight set closes the check-then-persist race when the\n // warm tail and cold backbone deliver the SAME milestone concurrently in one\n // isolate (milestones have no ledger claim, unlike finish).\n if (\n this._inFlightDetachedNotifications.has(id) ||\n this.messages.some((message) => message.id === id)\n ) {\n return;\n }\n this._inFlightDetachedNotifications.add(id);\n try {\n await this.persistMessages([\n ...this.messages,\n { id, role, parts: [{ type: \"text\", text }], metadata } as UIMessage\n ]);\n if (!options.react) return;\n const runReply = (requestId: string) =>\n this._runProgrammaticChatTurn(\n requestId,\n this._lastClientTools,\n this._lastBody,\n undefined\n );\n if (this._inSerializedDetachedDeliverySlot) {\n // We own the active turn slot (a `serialize: true` finish delivery), so\n // run inline + awaited, reusing the slot's request id (keeps the\n // `activeRequestId === turn requestId` invariant `saveMessages` relies\n // on). The ledger marks the slot delivered only after the reaction\n // completes, making the react turn eviction-safe too.\n await runReply(this._turnQueue.activeRequestId ?? nanoid());\n } else if (this._turnQueue.isActive) {\n // Inside a FOREIGN turn (e.g. `cancelAgentTool` called mid-turn).\n // Enqueue-and-await would deadlock; inline would interleave with that\n // turn. Fire-and-forget a turn that runs once the slot frees — the\n // message is already persisted, so the reaction is best-effort.\n const requestId = nanoid();\n void this.keepAliveWhile(() =>\n this._runExclusiveChatTurn(requestId, () => runReply(requestId))\n );\n } else {\n const requestId = nanoid();\n await this._runExclusiveChatTurn(requestId, () => runReply(requestId));\n }\n } finally {\n this._inFlightDetachedNotifications.delete(id);\n }\n }\n\n /**\n * Format the message injected by `detached: { notify }` when a background run\n * finishes. Override to customize the prose, or return an empty string to\n * suppress the notification for a given outcome.\n */\n protected formatDetachedCompletion(\n run: AgentToolRunInfo,\n result: AgentToolLifecycleResult\n ): string {\n const label = `Background task \"${run.agentType}\" (run ${run.runId})`;\n switch (result.status) {\n case \"completed\":\n return result.summary\n ? `${label} finished:\\n\\n${result.summary}`\n : `${label} finished successfully.`;\n case \"error\":\n return `${label} failed${result.error ? `: ${result.error}` : \".\"}`;\n case \"aborted\":\n return `${label} was cancelled.`;\n case \"interrupted\":\n return result.reason === \"budget-exceeded\"\n ? `${label} ran out of time before completing and was stopped.`\n : `${label} was interrupted before completing${result.error ? `: ${result.error}` : \".\"}`;\n default:\n return `${label} ended (${result.status}).`;\n }\n }\n\n /**\n * Targeted completion hook for `detached: { notify }`. Auto-wired by\n * `runAgentTool` (resolved by name so the base `Agent` stays decoupled from the\n * chat layer). Injects the formatted completion as a user turn so the model\n * reacts to the background result. Idempotent per run + status (deterministic\n * message id), so an exactly-once finish — or a soft give-up followed by a real\n * completion — never injects a duplicate, while a give-up and a later real\n * completion surface as two distinct messages.\n */\n async _cfDetachedNotifyFinish(\n run: AgentToolRunInfo,\n result: AgentToolLifecycleResult\n ): Promise<void> {\n const text = this.formatDetachedCompletion(run, result);\n if (!text) return;\n await this._injectDetachedNotification(\n `detached-finish:${run.runId}:${result.status}`,\n \"user\",\n text,\n {\n source: run.notifySource ?? \"detached-agent-tool\",\n runId: run.runId,\n agentType: run.agentType,\n status: result.status\n },\n { react: true }\n );\n }\n\n /**\n * Format the message injected when a `detached: { onMilestones }` milestone is\n * reached. Override to customize the prose (or return an empty string to\n * suppress a given milestone).\n */\n protected formatDetachedMilestone(\n run: AgentToolRunInfo,\n milestone: AgentToolMilestone\n ): string {\n const label = `Background task \"${run.agentType}\" (run ${run.runId})`;\n const detail =\n milestone.data !== undefined\n ? `\\n\\n${JSON.stringify(milestone.data, null, 2)}`\n : \"\";\n return `${label} reached milestone \"${milestone.name}\".${detail}`;\n }\n\n /**\n * Targeted milestone hook for `detached: { onMilestones }`. Idempotent per run\n * + milestone NAME (deterministic message id), so the warm tail and the cold\n * backbone reconcile converge to at most one message.\n *\n * - `\"narrate\"` (default): a synthetic **assistant** message injected directly\n * — no model turn.\n * - `\"react\"`: a **user** message followed by a model turn so the agent\n * responds to the milestone.\n */\n protected override async _deliverDetachedMilestone(\n run: AgentToolRunInfo,\n milestone: AgentToolMilestone,\n mode: \"react\" | \"narrate\"\n ): Promise<void> {\n const text = this.formatDetachedMilestone(run, milestone);\n if (!text) return;\n await this._injectDetachedNotification(\n `detached-ms:${run.runId}:${milestone.name}`,\n mode === \"narrate\" ? \"assistant\" : \"user\",\n text,\n {\n source: run.notifySource ?? \"detached-agent-tool\",\n runId: run.runId,\n agentType: run.agentType,\n milestone: milestone.name\n },\n { react: mode === \"react\" }\n );\n }\n\n /**\n * Bind the child turn that is about to stream to its agent-tool run, at\n * the moment the turn's request id is first knowable (inside the turn,\n * before any frame is broadcast). The in-memory mapping drives frame\n * attribution in {@link broadcast}; the run row's `request_id` is\n * persisted here rather than at terminal so attribution also survives a\n * DO restart mid-run (#1575).\n */\n private _registerAgentToolTurn(runId: string): void {\n const requestId = this._turnQueue.activeRequestId;\n if (requestId === null) {\n // Invariant: this runs inside the turn's enqueued fn, so the turn\n // queue's active request id is set. If it ever isn't, the run can't be\n // bound to its frames and its error/progress capture silently degrades\n // (#1575) — surface it rather than fail quietly.\n console.warn(\n `[AIChatAgent] agent-tool run ${runId} has no active request id at turn start; frame attribution will be skipped`\n );\n return;\n }\n this._agentToolRunsByRequestId.set(requestId, runId);\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set request_id = ${requestId}\n where run_id = ${runId}\n `;\n }\n\n async startAgentToolRun(\n input: unknown,\n options: { runId: string; signal?: AbortSignal }\n ): Promise<AgentToolRunInspection> {\n const existing = await this.inspectAgentToolRun(options.runId);\n if (existing) return existing;\n\n const startedAt = Date.now();\n const controller = new AbortController();\n const assistantIdsBeforeStart = new Set(\n this.messages\n .filter((message) => message.role === \"assistant\")\n .map((message) => message.id)\n );\n\n this.sql`\n insert into cf_ai_chat_agent_tool_runs\n (run_id, request_id, status, input_json, started_at)\n values (${options.runId}, null, 'running', ${AIChatAgent._stringifyAgentToolValue(input)}, ${startedAt})\n `;\n this._agentToolAbortControllers.set(options.runId, controller);\n this._agentToolPreTurnAssistantIds.set(\n options.runId,\n assistantIdsBeforeStart\n );\n this._agentToolLiveSequences.set(options.runId, 0);\n\n const abortFromParent = () => controller.abort(options.signal?.reason);\n if (options.signal?.aborted) {\n abortFromParent();\n } else {\n options.signal?.addEventListener(\"abort\", abortFromParent, {\n once: true\n });\n }\n\n const lifecycle = async () => {\n let requestId: string | undefined;\n try {\n const previousClientTools = this._lastClientTools;\n const previousBody = this._lastBody;\n this._setRequestContext(undefined, { agentToolInput: input });\n const result = await this.saveMessages(\n async (messages) => {\n this._registerAgentToolTurn(options.runId);\n return [\n ...messages,\n this.formatAgentToolInput(input, { runId: options.runId })\n ];\n },\n { signal: controller.signal }\n ).finally(() => {\n this._setRequestContext(previousClientTools, previousBody);\n });\n requestId = result.requestId;\n\n if (result.status === \"aborted\") {\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set request_id = ${requestId}, status = 'aborted',\n completed_at = ${Date.now()}\n where run_id = ${options.runId}\n `;\n return;\n }\n\n if (result.status === \"skipped\") {\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set request_id = ${requestId}, status = 'error',\n error_message = 'Agent tool run was skipped because the chat was cleared.',\n completed_at = ${Date.now()}\n where run_id = ${options.runId}\n `;\n return;\n }\n\n const streamError =\n result.error ?? this._agentToolLastErrors.get(options.runId);\n if (result.status === \"error\" || streamError) {\n const errorMessage =\n streamError ?? \"Agent tool run failed during streaming.\";\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set request_id = ${requestId}, status = 'error',\n error_message = ${errorMessage}, completed_at = ${Date.now()}\n where run_id = ${options.runId}\n `;\n return;\n }\n\n const messagesAfterStart = this._getAgentToolMessagesAfterStart(\n options.runId\n );\n const output = this.getAgentToolOutput(\n { runId: options.runId, input },\n messagesAfterStart\n );\n const summary = this.getAgentToolSummary(\n { runId: options.runId, input },\n output,\n messagesAfterStart\n );\n\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set request_id = ${requestId}, status = 'completed',\n output_json = ${AIChatAgent._stringifyAgentToolValue(output)},\n summary = ${summary}, error_message = null,\n completed_at = ${Date.now()}\n where run_id = ${options.runId}\n `;\n } catch (error) {\n if (controller.signal.aborted) {\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set request_id = ${requestId ?? null}, status = 'aborted',\n completed_at = ${Date.now()}\n where run_id = ${options.runId}\n `;\n return;\n }\n const message = error instanceof Error ? error.message : String(error);\n this._agentToolLastErrors.set(options.runId, message);\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set request_id = ${requestId ?? null}, status = 'error',\n error_message = ${message}, completed_at = ${Date.now()}\n where run_id = ${options.runId}\n `;\n } finally {\n options.signal?.removeEventListener(\"abort\", abortFromParent);\n this._agentToolAbortControllers.delete(options.runId);\n this._agentToolLiveSequences.delete(options.runId);\n // Drop the progress emitter's per-run coalescing state.\n this._agentToolProgressEmitterInstance?.forget(options.runId);\n // Drop this run's request-id mappings. When no runs remain in flight\n // clear the whole map, so negatively-cached (null) entries for\n // unrelated turns can't accumulate for the DO's lifetime — the map is\n // only consulted while a run is active (#1575).\n if (this._agentToolAbortControllers.size === 0) {\n this._agentToolRunsByRequestId.clear();\n } else {\n for (const [reqId, runId] of this._agentToolRunsByRequestId) {\n if (runId === options.runId) {\n this._agentToolRunsByRequestId.delete(reqId);\n }\n }\n }\n this._agentToolLastErrors.delete(options.runId);\n this._agentToolPreTurnAssistantIds.delete(options.runId);\n this._closeAgentToolTailers(options.runId);\n }\n };\n\n void this.keepAliveWhile(lifecycle);\n\n return {\n runId: options.runId,\n status: \"running\",\n startedAt\n };\n }\n\n async cancelAgentToolRun(runId: string, reason?: unknown): Promise<void> {\n // Stop the original in-isolate run if it's still live...\n this._agentToolAbortControllers.get(runId)?.abort(reason);\n // ...and any in-flight chat-recovery turn driving this child facet after an\n // eviction. A recovered turn re-runs via `_chatRecoveryContinue` /\n // `_chatRecoveryRetry` outside `startAgentToolRun`, so it has no entry in\n // `_agentToolAbortControllers`; a child facet is dedicated to a single\n // agent-tool run, so cancelling whatever turn is running tears the recovery\n // down instead of letting it keep grinding (and holding a keep-alive) after\n // the parent gave up and sealed `interrupted` (#1630 follow-up). Mirrors\n // Think's `_submissionAbortControllers` sweep.\n this.abortAllRequests(reason);\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set status = 'aborted', completed_at = coalesce(completed_at, ${Date.now()})\n where run_id = ${runId} and status = 'running'\n `;\n this._closeAgentToolTailers(runId);\n }\n\n /**\n * Classify any in-flight chat-recovery on this child facet (#1630 / N6). A\n * child facet is dedicated to a single agent-tool run, so any recovery\n * incident is that run's. Incidents in `detected`/`scheduled`/`attempting`\n * mean recovery is still resolving the interrupted turn; `exhausted`/`failed`\n * mean recovery gave up; a completed recovery deletes its incident.\n */\n private _classifyAgentToolChildRecovery(): Promise<\n \"in-progress\" | \"failed\" | \"none\"\n > {\n return classifyAgentToolChildRecovery(this.ctx.storage);\n }\n\n /**\n * Reconcile a stale (post-eviction) child run row from the child's own\n * durable recovery (#1630). The child facet self-heals its interrupted turn\n * via `chatRecovery`, but that path never writes the run row, so without this\n * the row strands `running` and the parent can only collect `interrupted`.\n *\n * Persisting the terminal here (rather than only computing it) is intentional:\n * it's a lazy materialization of the run's true terminal that also lets a\n * tailing parent's stream close promptly and makes subsequent inspects cheap.\n * While recovery is still resolving (active stream or in-progress incident)\n * the row is left `running` so the parent's bounded re-attach keeps waiting.\n * Mutates `row` in place when it settles so the caller can report it.\n */\n private async _reconcileStaleAgentToolChildRun(\n runId: string,\n row: AIChatAgentToolRunRow\n ): Promise<void> {\n const recovery = await this._classifyAgentToolChildRecovery();\n if (recovery === \"in-progress\" || this._resumableStream.hasActiveStream()) {\n return;\n }\n const messagesAfterStart = this._getAgentToolMessagesAfterStart(runId);\n // A settled recovery that produced an assistant turn is `completed`, even if\n // it ended on a tool result with no final text — keying off text alone would\n // mis-seal a legitimately-finished (but text-less) run as `error`.\n // `getAgentToolSummary` falls back when there is no text.\n const recoveredTurn =\n recovery !== \"failed\" &&\n messagesAfterStart.some((message) => message.role === \"assistant\");\n if (recoveredTurn) {\n const input = AIChatAgent._parseAgentToolValue(row.input_json);\n const output = this.getAgentToolOutput(\n { runId, input },\n messagesAfterStart\n );\n const summary = this.getAgentToolSummary(\n { runId, input },\n output,\n messagesAfterStart\n );\n const completedAt = Date.now();\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set status = 'completed',\n output_json = ${AIChatAgent._stringifyAgentToolValue(output)},\n summary = ${summary}, error_message = null,\n completed_at = ${completedAt}\n where run_id = ${runId} and status = 'running'\n `;\n row.status = \"completed\";\n row.output_json = AIChatAgent._stringifyAgentToolValue(output);\n row.summary = summary;\n row.error_message = null;\n row.completed_at = completedAt;\n this._closeAgentToolTailers(runId);\n } else {\n const error =\n \"Agent tool run was interrupted before the child could finish.\";\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set status = 'error', error_message = ${error}, completed_at = ${Date.now()}\n where run_id = ${runId}\n `;\n row.status = \"error\";\n row.error_message = error;\n row.completed_at = Date.now();\n this._closeAgentToolTailers(runId);\n }\n }\n\n /**\n * Eagerly terminalize this child facet's OWN agent-tool run row(s) once a\n * recovered turn has settled. A recovered turn re-runs via either\n * `_chatRecoveryContinue` → `continueLastTurn` or, for a pre-stream eviction,\n * `_chatRecoveryRetry` → `_retryLastUserTurn` — neither flows through\n * `startAgentToolRun`'s finalizer, so without this the row strands `running`\n * and its tailers stay open until a parent inspect lazily reconciles it —\n * forcing a re-attached parent to wait out a full no-progress window before\n * collecting an already-finished result (#1630 follow-up). Reconciling here\n * closes the tail promptly so the parent collects the terminal immediately.\n * No-op on non-child facets (their `cf_ai_chat_agent_tool_runs` table is\n * empty) and on rows whose in-memory run is still live; the underlying\n * reconcile leaves a row `running` while its recovery is still in progress.\n * Mirrors `@cloudflare/think`.\n */\n private async _reconcileOwnStaleAgentToolChildRuns(): Promise<void> {\n let rows: Array<{ run_id: string }>;\n try {\n rows = this.sql<{ run_id: string }>`\n select run_id from cf_ai_chat_agent_tool_runs\n where status = 'running'\n `;\n } catch {\n // No child-run table on this facet (it never ran as a child).\n return;\n }\n for (const { run_id } of rows) {\n if (this._agentToolAbortControllers.has(run_id)) continue;\n const row = this._getAgentToolRunRow(run_id);\n if (!row || row.status !== \"running\") continue;\n try {\n await this._reconcileStaleAgentToolChildRun(run_id, row);\n } catch {\n // Best-effort: a parent inspect still reconciles lazily.\n }\n }\n }\n\n async inspectAgentToolRun(\n runId: string\n ): Promise<AgentToolRunInspection | null> {\n const row = this._getAgentToolRunRow(runId);\n if (!row) return null;\n\n // A `running` row with no live abort controller means the original\n // in-isolate run is gone (e.g. the parent was evicted while this child run\n // was in flight, #1630) — lazily reconcile it from the child's own durable\n // recovery before reporting (mutates `row` in place when it settles).\n if (\n row.status === \"running\" &&\n !this._agentToolAbortControllers.has(runId)\n ) {\n await this._reconcileStaleAgentToolChildRun(runId, row);\n }\n\n const streamId = row.request_id\n ? this._getAgentToolStreamId(row.request_id)\n : undefined;\n const messagesAfterStart = this._getAgentToolMessagesAfterStart(runId);\n const input = AIChatAgent._parseAgentToolValue(row.input_json);\n const output =\n row.status === \"completed\"\n ? (AIChatAgent._parseAgentToolValue(row.output_json) ??\n this.getAgentToolOutput({ runId, input }, messagesAfterStart))\n : undefined;\n\n const progress = AIChatAgent._progressSnapshotFromRow(row);\n const milestones = this._readAgentToolMilestones(runId);\n return {\n runId,\n status: row.status,\n requestId: row.request_id ?? undefined,\n streamId,\n output,\n summary: row.status === \"completed\" ? (row.summary ?? \"\") : undefined,\n error:\n row.status === \"error\" ? (row.error_message ?? undefined) : undefined,\n startedAt: row.started_at,\n completedAt: row.completed_at ?? undefined,\n ...(progress ? { progress } : {}),\n ...(milestones.length > 0 ? { milestones } : {})\n };\n }\n\n private static _progressSnapshotFromRow(\n row: AIChatAgentToolRunRow\n ): AgentToolProgressSnapshot | undefined {\n if (row.progress_json == null || row.last_signal_at == null) {\n return undefined;\n }\n try {\n const parsed = JSON.parse(row.progress_json) as Partial<\n Omit<AgentToolProgressSnapshot, \"at\">\n >;\n return { ...parsed, at: row.last_signal_at };\n } catch {\n return { at: row.last_signal_at };\n }\n }\n\n async getAgentToolChunks(\n runId: string,\n options?: { afterSequence?: number }\n ): Promise<AgentToolStoredChunk[]> {\n this._flushChunkBuffer();\n const row = this._getAgentToolRunRow(runId);\n if (!row?.request_id) return [];\n\n return this._getAgentToolStoredChunks(\n row.request_id,\n options?.afterSequence\n );\n }\n\n async tailAgentToolRun(\n runId: string,\n options?: { afterSequence?: number; signal?: AbortSignal }\n ): Promise<ReadableStream<AgentToolStoredChunk>> {\n // Hoisted out of `start` so the `cancel` callback (a sibling of `start` on\n // the underlying source) can reach them — an in-scope-only `closed`/`forward`\n // is exactly why a cancelled consumer used to leave a zombie forwarder.\n let closed = false;\n let forward: ((chunk: AgentToolStoredChunk) => void) | undefined;\n const detach = () => {\n // Remove our forwarder and drop the now-empty set so the broadcast\n // idle-guard (`_agentToolForwarders.size`) goes cold again. Otherwise a\n // run that was already terminal at attach (its `_closeAgentToolTailers`\n // already ran and won't run again) leaves an empty set keyed by runId, and\n // every subsequent broadcast on this DO keeps paying the\n // `interceptAgentToolBroadcast` cost forever.\n if (forward) {\n const set = this._agentToolForwarders.get(runId);\n set?.delete(forward);\n if (set && set.size === 0) this._agentToolForwarders.delete(runId);\n forward = undefined;\n }\n };\n const stream = new ReadableStream<Uint8Array>({\n start: async (controller) => {\n // Highest sequence already enqueued into this view. Stored chunk_index\n // and the live forwarder sequence share one monotonic numbering (see\n // `_getAgentToolStoredChunks`), so a single high-water mark dedupes the\n // stored-replay → live-forwarding handoff: a chunk that lands in both\n // the drained backlog AND the live buffer (because it was stored and\n // broadcast during the drain) is emitted exactly once, in order.\n let lastEmitted = options?.afterSequence ?? -1;\n const emit = (chunk: AgentToolStoredChunk) => {\n if (closed) return;\n // Drop out-of-order / duplicate sequences. Guarantees in-order,\n // exactly-once delivery so the parent can rebuild tool-call state\n // (input-available → output-available) without gaps.\n if (chunk.sequence <= lastEmitted) return;\n lastEmitted = chunk.sequence;\n try {\n controller.enqueue(\n agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\\n`)\n );\n } catch {\n // The consumer detached (e.g. a parent's bounded re-attach budget\n // expired) between the read view closing and our handling here.\n // Just mark dead and detach — do NOT call `controller.close()` on an\n // already-cancelled stream, which throws and would propagate out of\n // `interceptAgentToolBroadcast`'s forward loop, starving the run's\n // sibling tailers of this chunk. The child run is unaffected.\n closed = true;\n detach();\n }\n };\n\n // While draining the stored backlog, live chunks are parked here rather\n // than emitted directly, so they keep arriving (the forwarder is\n // registered FIRST, below) but never race ahead of / interleave with\n // the ordered backlog.\n let draining = true;\n const pending: AgentToolStoredChunk[] = [];\n forward = (chunk: AgentToolStoredChunk) => {\n if (closed) return;\n if (draining) {\n pending.push(chunk);\n return;\n }\n emit(chunk);\n };\n\n const close = () => {\n if (closed) return;\n closed = true;\n detach();\n try {\n controller.close();\n } catch {\n // Already closed (e.g. the consumer cancelled the reader first).\n }\n };\n const onAbort = () => close();\n\n try {\n if (options?.signal?.aborted) {\n close();\n return;\n }\n options?.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n // Register the live forwarder BEFORE draining the stored backlog.\n // Previously the forwarder was attached only AFTER `getAgentToolChunks`\n // + `inspectAgentToolRun` resolved; any chunk the child stored AND\n // broadcast during those `await` boundaries advanced the live sequence\n // with no forwarder attached, so it was neither in the drained\n // snapshot nor live-forwarded — silently dropped from the parent's\n // forward stream. A network-paced proxied remote stream (a sub-agent\n // returning a remote `toUIMessageStreamResponse()` from\n // `onChatMessage`) hits this window constantly, leaving tool parts\n // stuck at `input-available` on the client (#1589).\n const forwarders =\n this._agentToolForwarders.get(runId) ??\n new Set<(chunk: AgentToolStoredChunk) => void>();\n forwarders.add(forward);\n this._agentToolForwarders.set(runId, forwarders);\n\n const closers =\n this._agentToolClosers.get(runId) ?? new Set<() => void>();\n closers.add(close);\n this._agentToolClosers.set(runId, closers);\n\n for (const chunk of await this.getAgentToolChunks(runId, options)) {\n if (closed) return;\n emit(chunk);\n }\n\n // Flush anything that arrived live during the drain, then switch the\n // forwarder to direct emit. No `await` between here and the loop above\n // means no live chunk can slip past this handoff.\n draining = false;\n for (const chunk of pending) emit(chunk);\n pending.length = 0;\n\n const inspection = await this.inspectAgentToolRun(runId);\n if (!inspection || inspection.status !== \"running\") {\n close();\n return;\n }\n\n // Run is still live: realign the live sequence to continue right\n // after the highest emitted chunk (the stored high-water plus\n // anything captured during the drain). On a normal warm attach the\n // in-memory counter is already in lockstep with the stored\n // chunk_index, so this is a no-op. But after the CHILD's Durable\n // Object restarts/wakes from hibernation, `_agentToolLiveSequences`\n // is cold (empty) while the stored backlog sits at N, and a\n // chat-recovery resume re-attaches via `tailAgentToolRun` WITHOUT\n // re-running `startAgentToolRun` (which is what seeds the counter).\n // Without this realign the broadcast snoop would hand the recovered\n // turn's new chunks sequences from 0 — all <= N — and `emit`'s\n // high-water dedupe would silently drop every one, leaving the parent\n // stuck with no post-restart chunks. Gating on the still-running check\n // also avoids re-heating the broadcast idle-guard for a terminal run.\n // Mirrors @cloudflare/think's tail.\n if (lastEmitted > (options?.afterSequence ?? -1)) {\n this._agentToolLiveSequences.set(runId, lastEmitted + 1);\n }\n } catch (error) {\n // Detach the up-front-registered forwarder before surfacing the\n // failure so it doesn't linger on this run, then guard\n // `controller.error` — the stream may already be torn down (e.g. the\n // consumer cancelled during the drain await), in which case\n // `controller.error` throws.\n closed = true;\n detach();\n try {\n controller.error(error);\n } catch {\n // Stream already torn down.\n }\n }\n },\n cancel: () => {\n // A consumer detaching from the tail (e.g. a parent's bounded re-attach\n // budget expiring via reader.cancel()) is read-only — it must NOT cancel\n // the child run. Mark dead and detach the forwarder so no later broadcast\n // reaches this torn-down controller (a lingering forwarder would throw on\n // the next enqueue). Mirrors @cloudflare/think's read-only tail.\n closed = true;\n detach();\n }\n });\n return stream as unknown as ReadableStream<AgentToolStoredChunk>;\n }\n\n private _getAgentToolRunRow(runId: string): AIChatAgentToolRunRow | null {\n const rows = this.sql<AIChatAgentToolRunRow>`\n select run_id, request_id, status, input_json, output_json, summary,\n error_message, started_at, completed_at, progress_json,\n last_signal_at\n from cf_ai_chat_agent_tool_runs\n where run_id = ${runId}\n `;\n return rows[0] ?? null;\n }\n\n private _getAgentToolStreamId(requestId: string): string | undefined {\n const rows = this.sql<AIChatStreamMetadataRow>`\n select id, status, request_id\n from cf_ai_chat_stream_metadata\n where request_id = ${requestId}\n order by rowid desc\n limit 1\n `;\n return rows[0]?.id;\n }\n\n private _getAgentToolStoredChunks(\n requestId: string,\n afterSequence = -1\n ): AgentToolStoredChunk[] {\n const streamId = this._getAgentToolStreamId(requestId);\n if (!streamId) return [];\n\n // Read through ResumableStream so packed segment rows are unpacked into\n // individual chunk bodies with a running per-chunk index. That per-chunk\n // sequence matches the in-memory live counter (`_agentToolLiveSequences`),\n // so a tailing parent can switch from stored replay to live forwarding\n // without gaps or duplicates.\n return this._resumableStream\n .getStreamChunks(streamId)\n .filter((chunk) => chunk.chunk_index > afterSequence)\n .map((chunk) => ({ sequence: chunk.chunk_index, body: chunk.body }));\n }\n\n private _getAgentToolMessagesAfterStart(runId: string): UIMessage[] {\n const previousAssistantIds =\n this._agentToolPreTurnAssistantIds.get(runId) ?? new Set<string>();\n return this.messages.filter(\n (message) =>\n message.role !== \"assistant\" || !previousAssistantIds.has(message.id)\n );\n }\n\n private _closeAgentToolTailers(runId: string) {\n const closers = this._agentToolClosers.get(runId);\n if (closers) {\n for (const close of closers) close();\n this._agentToolClosers.delete(runId);\n }\n this._agentToolForwarders.delete(runId);\n }\n\n private static _stringifyAgentToolValue(value: unknown): string | null {\n if (value === undefined) return null;\n const json = JSON.stringify(value);\n return json === undefined ? null : json;\n }\n\n private static _parseAgentToolValue(value: string | null): unknown {\n if (value === null) return undefined;\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n }\n\n private static _extractLatestAssistantText(\n messages: readonly UIMessage[]\n ): string | undefined {\n const message = [...messages]\n .reverse()\n .find((candidate) => candidate.role === \"assistant\");\n if (!message) return undefined;\n\n const text = message.parts\n .filter((part): part is TextUIPart => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\");\n return text.length > 0 ? text : undefined;\n }\n\n /**\n * Persist messages and trigger `onChatMessage()` for a new response.\n *\n * Waits for any active chat turn to finish before starting, so scheduled\n * or programmatic messages never overlap an in-flight stream.\n *\n * Pass a function to derive the next message list from the latest\n * persisted `this.messages` when the turn actually starts. This avoids\n * stale baselines when multiple `saveMessages()` calls queue up behind\n * active work:\n *\n * ```ts\n * await this.saveMessages((messages) => [...messages, syntheticMessage]);\n * ```\n *\n * Pass `options.signal` to cancel the turn from outside without knowing\n * the internally-generated request id. The signal is linked to the\n * registry's controller for this turn — when it aborts, the inference\n * loop's signal aborts and the result reports `status: \"aborted\"`.\n * Pre-aborted signals short-circuit before any model work runs.\n *\n * Returns `{ requestId, status, error? }` where `status` is `\"completed\"`\n * when the turn ran, `\"error\"` when the stream reported an error,\n * `\"skipped\"` when the chat was cleared, or `\"aborted\"` when an external\n * signal cancelled it mid-stream.\n */\n async saveMessages(\n messages:\n | UIMessage[]\n | ((\n currentMessages: readonly UIMessage[]\n ) => UIMessage[] | Promise<UIMessage[]>),\n options?: SaveMessagesOptions\n ): Promise<SaveMessagesResult> {\n const requestId = nanoid();\n const clientTools = this._lastClientTools;\n const body = this._lastBody;\n const epoch = this._turnQueue.generation;\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n let error: string | undefined;\n\n await this._runExclusiveChatTurn(\n requestId,\n async () => {\n const resolvedMessages =\n typeof messages === \"function\"\n ? await messages(this.messages)\n : messages;\n\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n await this.persistMessages(resolvedMessages);\n\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n const turnResult = await this._runProgrammaticChatTurn(\n requestId,\n clientTools,\n body,\n options?.signal\n );\n status = turnResult.status;\n error = turnResult.error;\n },\n { epoch }\n );\n\n if (this._turnQueue.generation !== epoch && status === \"completed\") {\n status = \"skipped\";\n }\n\n return { requestId, status, ...(error !== undefined && { error }) };\n }\n\n /**\n * Trigger a continuation of the last assistant message without inserting\n * a new user message. The LLM sees the full conversation (including the\n * partial assistant response) and generates a continuation that appends\n * to the same message.\n *\n * This uses `continuation: true` in `_reply`, which clones the last\n * assistant message and appends new parts to it — the same mechanism\n * used by tool auto-continuation.\n *\n * Returns early if there is no assistant message to continue from.\n *\n * Pass `options.signal` to cancel the continuation from outside —\n * matches the {@link saveMessages} contract.\n */\n protected async continueLastTurn(\n body?: Record<string, unknown>,\n options?: SaveMessagesOptions\n ): Promise<SaveMessagesResult> {\n if (!this._findLastAssistantMessage()) {\n return { requestId: \"\", status: \"skipped\" };\n }\n\n const requestId = nanoid();\n // If this facet is an agent-tool child being recovered, re-bind its run row\n // to this turn's request id so the parent's re-attach tail keeps attributing\n // the continued turn's frames (no-op otherwise).\n this._rebindAgentToolChildRunRequestId(requestId);\n const clientTools = this._lastClientTools;\n const resolvedBody = body ?? this._lastBody;\n const epoch = this._turnQueue.generation;\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n let error: string | undefined;\n let wasAborted = false;\n\n await this._runExclusiveChatTurn(\n requestId,\n async () => {\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n this._setRequestContext(clientTools, resolvedBody);\n\n const turnBody = async () => {\n await this._tryCatchChat(async () => {\n return agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n async () => {\n const abortSignal = this._abortRegistry.getSignal(requestId);\n const detachExternal = this._abortRegistry.linkExternal(\n requestId,\n options?.signal\n );\n try {\n await this._repairInterruptedToolsBeforeTurn();\n const response = await this.onChatMessage(() => {}, {\n requestId,\n abortSignal,\n clientTools,\n body: resolvedBody,\n continuation: true\n });\n\n if (response) {\n const replyResult = await this._reply(\n requestId,\n response,\n [],\n {\n continuation: true,\n chatMessageId: requestId\n }\n );\n status = replyResult.status;\n error = replyResult.error;\n }\n } finally {\n if (abortSignal?.aborted) wasAborted = true;\n detachExternal();\n this._abortRegistry.remove(requestId);\n }\n }\n );\n });\n };\n\n await this._runChatRecoveryFiber(requestId, true, turnBody);\n },\n { epoch }\n );\n\n if (this._turnQueue.generation !== epoch && status === \"completed\") {\n status = \"skipped\";\n } else if (wasAborted && status === \"completed\") {\n status = \"aborted\";\n }\n\n return { requestId, status, ...(error !== undefined && { error }) };\n }\n\n private async _retryLastUserTurn(\n clientTools?: ClientToolSchema[],\n body?: Record<string, unknown>,\n options?: SaveMessagesOptions\n ): Promise<SaveMessagesResult> {\n const lastMessage =\n this.messages.length > 0 ? this.messages[this.messages.length - 1] : null;\n if (!lastMessage || lastMessage.role !== \"user\") {\n return { requestId: \"\", status: \"skipped\" };\n }\n\n const requestId = nanoid();\n // If this facet is an agent-tool child being recovered, re-bind its run row\n // to this turn's request id so the parent's re-attach tail keeps attributing\n // the retried turn's frames (no-op otherwise).\n this._rebindAgentToolChildRunRequestId(requestId);\n const epoch = this._turnQueue.generation;\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n let error: string | undefined;\n\n await this._runExclusiveChatTurn(\n requestId,\n async () => {\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n const turnResult = await this._runProgrammaticChatTurn(\n requestId,\n clientTools,\n body,\n options?.signal\n );\n status = turnResult.status;\n error = turnResult.error;\n },\n { epoch }\n );\n\n if (this._turnQueue.generation !== epoch && status === \"completed\") {\n status = \"skipped\";\n }\n\n return { requestId, status, ...(error !== undefined && { error }) };\n }\n\n // ── Chat recovery via fibers ──────────────────────────────────────\n\n /**\n * Context passed to `onChatRecovery` when an interrupted chat stream\n * is detected after DO restart.\n */\n static readonly CHAT_FIBER_NAME = \"__cf_internal_chat_turn\";\n\n /**\n * Intercept internal chat fibers before they reach the user's\n * `onFiberRecovered` hook. Maps to `onChatRecovery`.\n * @internal\n */\n private _resolveChatRecoveryConfig(): ResolvedChatRecoveryConfig {\n // Delegates to the shared incident engine (agents/chat) so AIChatAgent and\n // Think resolve recovery config identically. See\n // design/rfc-chat-recovery-foundation.md.\n return resolveChatRecoveryConfig(this.chatRecovery);\n }\n\n /**\n * Monotonic forward-progress signal for recovery budget resets.\n *\n * This used to count assistant messages in `this.messages`, but that is\n * recomputed from the live, mutable transcript. Compaction collapses older\n * assistant messages into a summary, lowering the count — so a turn that had\n * genuinely advanced could read as \"no progress\" between attempts and exhaust\n * its budget prematurely (#1628). Instead we read a durably-persisted counter\n * that only ever increments — bumped at production time when new content is\n * streamed (see `_storeStreamChunk` / `_maybeBumpRecoveryProgress`), which is\n * genuine forward progress and is immune to client reconnects / recovery\n * re-persists — so compaction can never lower it and a reconnect can't fake\n * it (#1637).\n */\n private async _chatRecoveryProgressMarker(): Promise<number> {\n // Storage read lives in the shared engine (agents/chat); this is the\n // package binding, symmetric with `Think`.\n return readChatRecoveryProgress(this.ctx.storage);\n }\n\n /** Advance the durable recovery-progress counter. Called from\n * `_maybeBumpRecoveryProgress` when new content is streamed (real,\n * reconnect-immune forward progress). The increment lives in the shared\n * engine (agents/chat); this is the package binding. */\n private async _bumpChatRecoveryProgress(): Promise<void> {\n return bumpChatRecoveryProgress(this.ctx.storage);\n }\n\n /** Per-isolate N9 throttle gate (shared `agents/chat` helper); reset per\n * isolate so the first forwarded chunk after a restart always credits. */\n private _agentToolStreamProgress = new AgentToolStreamProgressThrottle();\n\n /**\n * N9: forwarding a sub-agent's chunks IS forward progress for this parent\n * turn, so credit the parent's recovery progress marker — otherwise a parent\n * whose turn merely `await`s a child banks no progress of its own and its\n * no-progress window exhausts while the child is healthily streaming. Only\n * invoked after a child actually produced output (see\n * `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.\n * Throttled (and reset per isolate) so we never write storage per token.\n */\n protected override async _onAgentToolStreamProgress(): Promise<void> {\n if (this._agentToolStreamProgress.shouldCredit(Date.now())) {\n await this._bumpChatRecoveryProgress();\n }\n }\n\n /**\n * Lazily-built shared recovery engine. The adapter arrows capture `this`, so a\n * single cached instance is correct across calls (and across future engine\n * methods). `AIChatAgent` has no interaction state to rehydrate, so it omits\n * the optional `ensureInteractionStateLoaded` hook.\n */\n private _chatRecoveryEngineInstance?: ChatRecoveryEngine;\n private _chatRecoveryEngine(): ChatRecoveryEngine {\n return (this._chatRecoveryEngineInstance ??= new ChatRecoveryEngine({\n resolveConfig: () => this._resolveChatRecoveryConfig(),\n now: () => Date.now(),\n sweepStaleIncidents: (now) =>\n sweepStaleChatRecoveryIncidents(this.ctx.storage, now),\n getIncident: async (key) =>\n (await this.ctx.storage.get<ChatRecoveryIncident>(key)) ?? null,\n readProgress: () => this._chatRecoveryProgressMarker(),\n // A turn parked on a pending CLIENT interaction is waiting on the human,\n // not stuck, so the engine keeps it budget-free.\n isAwaitingClientInteraction: () => this.hasPendingClientInteraction(),\n putIncident: (key, incident) => this.ctx.storage.put(key, incident),\n deleteIncident: async (key) => {\n await this.ctx.storage.delete(key);\n },\n emitRecoveryEvent: (event) =>\n this._emit(event.type, {\n incidentId: event.incidentId,\n requestId: event.requestId,\n attempt: event.attempt,\n maxAttempts: event.maxAttempts,\n recoveryKind: event.recoveryKind,\n ...(event.reason ? { reason: event.reason } : {})\n }),\n scheduleRecovery: async (callback, data, reason, delaySeconds) => {\n await this.schedule(\n delaySeconds,\n callback,\n data,\n chatRecoverySchedulePolicy(reason)\n );\n },\n setRecovering: (active, requestId) =>\n this._setChatRecovering(active, requestId),\n onShouldKeepRecoveringError: (error) =>\n console.error(\n \"[AIChatAgent] chatRecovery shouldKeepRecovering hook threw\",\n error\n ),\n exhaustChatRecovery: (incident, config, partial, streamId, createdAt) =>\n this._exhaustChatRecovery(\n incident,\n config,\n partial,\n streamId,\n createdAt\n ),\n resolveRecoveryStream: (requestId) =>\n this._resolveAIChatRecoveryStream(requestId),\n getPartialStreamText: (streamId) => this._getPartialStreamText(streamId),\n activeChatRecoveryRootRequestId: () =>\n this._activeChatRecoveryRootRequestId,\n onGiveUpBookkeepingError: (phase, error) =>\n console.error(\n phase === \"read\"\n ? \"[AIChatAgent] failed to read recovery incident during give-up; synthesizing\"\n : \"[AIChatAgent] failed to persist sealed recovery incident during give-up\",\n error\n )\n } satisfies ChatRecoveryAdapter));\n }\n\n private async _beginChatRecoveryIncident(input: {\n requestId: string;\n recoveryRootRequestId?: string | null;\n latestUserMessageId?: string | null;\n recoveryKind: ChatRecoveryKind;\n /** Test-only clock injection for deterministic debounce/window timing. */\n nowMs?: number;\n }): Promise<{\n incident: ChatRecoveryIncident;\n config: ResolvedChatRecoveryConfig;\n exhausted: boolean;\n }> {\n // Incident orchestration (sweep -> read -> budget eval -> persist -> emit,\n // with its ordering invariants) lives in the shared ChatRecoveryEngine; this\n // method is the package's adapter binding. See\n // design/rfc-chat-recovery-foundation.md.\n return this._chatRecoveryEngine().beginIncident(input);\n }\n\n private async _updateChatRecoveryIncident(\n incidentId: string | undefined,\n status: ChatRecoveryIncident[\"status\"],\n reason?: string\n ): Promise<void> {\n // Incident state-machine transitions (delete-on-completed vs persist, the\n // completed/skipped/failed event emit, and the #1620 recovering-flag) live\n // in the shared ChatRecoveryEngine; this method is the package's adapter\n // binding. See design/rfc-chat-recovery-foundation.md.\n return this._chatRecoveryEngine().updateIncident(\n incidentId,\n status,\n reason\n );\n }\n\n private async _exhaustChatRecovery(\n incident: ChatRecoveryIncident,\n config: ResolvedChatRecoveryConfig,\n // `parts` is the engine's vocabulary-agnostic `unknown[]`; ai-chat owns the\n // AI SDK `UIMessage` vocabulary, so it re-asserts `MessagePart[]` at the\n // user-facing exhausted-context edge below.\n partial: { text: string; parts: unknown[] },\n streamId: string,\n createdAt: number\n ): Promise<void> {\n // Build + notification (event + onExhausted-swallow) and the\n // notify-before-terminalize invariant live in the engine helper; the\n // terminal/broadcast ordering inside `terminalize` is broadcast-first,\n // converged onto `Think`'s ordering (see the note below).\n // See design/rfc-chat-recovery-foundation.md.\n await runChatRecoveryExhaustion(\n {\n incident,\n config,\n partialText: partial.text,\n partialParts: partial.parts as MessagePart[],\n streamId,\n createdAt\n },\n {\n emit: (event) => this._emit(\"chat:recovery:exhausted\", event),\n onExhausted: config.onExhausted,\n onError: (error) =>\n console.error(\n \"[AIChatAgent] chatRecovery onExhausted hook threw\",\n error\n ),\n terminalize: async (ctx) => {\n // Deliver the user-visible terminal banner BEFORE the durable terminal\n // write. The write can reject in the deploy/storage window a give-up\n // runs in (#1730); ordering the broadcast first keeps the banner\n // resilient to that, the throw then propagates, and the whole give-up\n // re-runs on a healthy isolate — which persists the record\n // (idempotently) and re-delivers the banner (the documented\n // at-least-once edge). Persisting first gains no durability (the\n // re-run persists either way) while dropping the live banner on the\n // failing pass — so ai-chat matches `Think`'s broadcast-first.\n this._broadcastChatMessage({\n body: ctx.terminalMessage,\n done: true,\n error: true,\n id: ctx.requestId,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE\n });\n // The durable terminal record (#1645) is replayed to a client that\n // (re)connects after the turn ended (shared\n // `ResumeHandshake._replayTerminalOnResume`).\n await this._recordChatTerminal(ctx.requestId, ctx.terminalMessage);\n // Exhaustion resolves recovery — clear the \"recovering…\" status (#1620).\n await this._setChatRecovering(false);\n }\n }\n );\n // The exhausted record is retained for inspection and reclaimed later by\n // the TTL sweep; only successful (completed) incidents are deleted eagerly.\n }\n\n /**\n * Persist a durable record of the last terminal turn so a client that\n * (re)connects after the turn ended still learns its outcome (#1645). Kept\n * until a later turn supersedes it (`_clearChatTerminal`); a single record is\n * sufficient because only the most recent terminal is relevant.\n */\n private async _recordChatTerminal(\n requestId: string,\n body: string\n ): Promise<void> {\n await recordChatTerminal(this.ctx.storage, requestId, body);\n }\n\n /** Clear the durable terminal record once a later turn supersedes it (#1645). */\n private async _clearChatTerminal(): Promise<void> {\n await clearChatTerminal(this.ctx.storage);\n }\n\n private async _pendingChatTerminal(): Promise<{\n requestId: string;\n body: string;\n } | null> {\n return pendingChatTerminal(this.ctx.storage);\n }\n\n /**\n * Build the on-connect \"recovering…\" replay frame (#1620), or `null` when no\n * (non-stale) recovery is in progress. A client that connects between recovery\n * attempts (no active stream) reads the turn as working rather than frozen.\n * A record older than the flag TTL is treated as abandoned (its terminal-clear\n * never ran) and skipped, so a dead recovery can't show \"recovering…\" forever.\n * Mirrors `@cloudflare/think`'s `_buildIdleConnectMessages` recovering replay.\n */\n private async _buildRecoveringConnectFrame(): Promise<Record<\n string,\n unknown\n > | null> {\n return buildChatRecoveringFrame(\n this.ctx.storage,\n MessageType.CF_AGENT_CHAT_RECOVERING,\n Date.now()\n );\n }\n\n /**\n * Set or clear the live \"recovering…\" status (#1620). Persists a durable\n * record (so set/clear stay consistent across the isolates a recovery spans)\n * and broadcasts a `CF_AGENT_CHAT_RECOVERING` frame on a genuine transition.\n * The status is also replayed on connect (`_buildRecoveringConnectFrame`) so a\n * client connecting mid-recovery isn't left looking frozen; the terminal\n * outcome is surfaced separately over the resume handshake (#1645).\n */\n private async _setChatRecovering(\n active: boolean,\n requestId?: string\n ): Promise<void> {\n await setChatRecovering(active, requestId, {\n storage: this.ctx.storage,\n messageType: MessageType.CF_AGENT_CHAT_RECOVERING,\n broadcast: (frame) =>\n this._broadcastChatMessage(frame as OutgoingMessage),\n now: Date.now()\n });\n }\n\n protected override async _handleInternalFiberRecovery(\n ctx: FiberRecoveryContext\n ): Promise<boolean> {\n // The wake-recovery lifecycle (non-chat dispatch → chat gate → unwrap →\n // stream/partial → classify → begin-incident → exhausted-branch →\n // onChatRecovery → persist → complete → dispatch → catch→failed) lives in the\n // shared ChatRecoveryEngine; this binds the divergent organs as wake hooks,\n // symmetric with `Think`. `AIChatAgent` tracks no terminal stream status\n // (`streamStatus: undefined`, so every terminal-stream branch is dead) and\n // has no submission layer, so its dispatch is a leaf-only retry/continue/skip.\n // See design/rfc-chat-recovery-foundation.md.\n return this._chatRecoveryEngine().handleChatFiberRecovery(ctx, {\n chatFiberPrefix: () =>\n (this.constructor as typeof AIChatAgent).CHAT_FIBER_NAME + \":\",\n unwrapRecoverySnapshot: (fiber) => {\n const { snapshot, user } = unwrapChatFiberSnapshot<\"ai-chat-turn\">(\n \"__cfAIChatFiberSnapshot\",\n fiber.snapshot,\n \"ai-chat-turn\"\n );\n return { snapshot, recoveryData: user };\n },\n classifyRecoveredTurn: (input) => this._classifyRecoveredChatTurn(input),\n invokeOnChatRecovery: (input) =>\n this.onChatRecovery({\n incidentId: input.incident.incidentId,\n recoveryRootRequestId: input.recoveryRootRequestId,\n attempt: input.incident.attempt,\n maxAttempts: input.incident.maxAttempts,\n recoveryKind: input.recoveryKind,\n streamId: input.streamId,\n requestId: input.requestId,\n partialText: input.partial.text,\n // The engine seam is vocabulary-agnostic (`unknown[]`); ai-chat owns\n // the AI SDK parts vocabulary, so re-assert it for the user context.\n partialParts: input.partial.parts as MessagePart[],\n recoveryData: input.recoveryData,\n messages: [...this.messages],\n lastBody: input.snapshot?.lastBody ?? this._lastBody,\n lastClientTools:\n input.snapshot?.lastClientTools ?? this._lastClientTools,\n createdAt: input.createdAt\n }),\n // Only persist while the stream is still active. The ACK handler (client\n // reconnect → replayChunks) may have already persisted + completed the\n // orphaned stream before fiber recovery runs; persisting again on the same\n // chunks would double the assistant message's parts. (The engine ANDs this\n // with the shared never-drop-settled-work clause.)\n shouldPersistOrphanedPartial: (input) => input.streamStillActive,\n persistOrphanedStream: (streamId) =>\n this._persistOrphanedStream(streamId),\n completeRecoveredStream: (streamId) => {\n this._resumableStream.complete(streamId);\n void this._ensureStreamCleanupScheduled();\n },\n dispatchRecoveredTurn: (input) => this._dispatchRecoveredChatTurn(input)\n } satisfies ChatFiberWakeHooks<AIChatRecoveryClassification>);\n }\n\n /**\n * Resolve the orphaned stream for a recovered chat turn — drives BOTH the wake\n * path (full result) and the give-up terminalization (which reads only\n * `.streamId`). Prefers the newest durable stream row keyed by the recovery-\n * root request id; falls back to the live active stream; `streamId` is `\"\"`\n * when neither survives. `AIChatAgent` does not model terminal stream status,\n * so `streamStatus` is left `undefined` (keeping the engine's terminal-stream\n * branches dead here) — see the \"substrate capabilities are optional\" decision\n * in the RFC.\n */\n private _resolveAIChatRecoveryStream(\n requestId: string\n ): ResolvedRecoveryStream {\n let streamId = \"\";\n if (requestId) {\n const rows = this.sql<{ id: string }>`\n SELECT id FROM cf_ai_chat_stream_metadata\n WHERE request_id = ${requestId}\n ORDER BY created_at DESC LIMIT 1\n `;\n if (rows.length > 0) {\n streamId = rows[0].id;\n }\n }\n if (!streamId && this._resumableStream.hasActiveStream()) {\n streamId = this._resumableStream.activeStreamId ?? \"\";\n }\n const streamStillActive = Boolean(\n streamId &&\n this._resumableStream.hasActiveStream() &&\n this._resumableStream.activeStreamId === streamId\n );\n return { streamId, streamStillActive };\n }\n\n /**\n * Classify a recovered turn as `retry` or `continue`. The `shouldRetryPreStream`\n * detail is threaded to the dispatch decision; `emptyPartialNewTurn` only\n * influences the reported kind (an empty partial persists nothing, so a new turn\n * is re-run fresh rather than merged into the previous assistant — #1691). The\n * `persist: false` discard case stays \"continue\" here and only surfaces as\n * \"retry\" on the `chat:recovery:scheduled` event, decided in dispatch.\n */\n private _classifyRecoveredChatTurn(input: ClassifyRecoveredTurnInput): {\n recoveryKind: ChatRecoveryKind;\n detail: AIChatRecoveryClassification;\n } {\n const shouldRetryPreStream = this._shouldRetryRecoveredPreStreamTurn(\n input.snapshot,\n input.streamId,\n input.partial\n );\n const preStreamLeaf =\n this.messages.length > 0\n ? this.messages[this.messages.length - 1]\n : undefined;\n const emptyPartialNewTurn =\n !!input.streamId &&\n input.snapshot?.continuation === false &&\n !!input.snapshot.latestUserMessageId &&\n input.partial.text === \"\" &&\n input.partial.parts.length === 0 &&\n preStreamLeaf?.role === \"user\" &&\n preStreamLeaf.id === input.snapshot.latestUserMessageId;\n const recoveryKind: ChatRecoveryKind =\n shouldRetryPreStream || emptyPartialNewTurn ? \"retry\" : \"continue\";\n return { recoveryKind, detail: { shouldRetryPreStream } };\n }\n\n /**\n * The retry/continue/skip decision for a recovered chat turn, run after the\n * partial is persisted and the stream completed. A NEW turn that left no\n * persisted assistant partial (the leaf is still the user message) is re-run\n * fresh instead of continued (which would clone + merge into the previous\n * assistant turn — #1691); this lost-partial check is re-derived here from the\n * now-updated leaf rather than carried from classify.\n */\n private async _dispatchRecoveredChatTurn(\n input: DispatchRecoveredTurnInput<AIChatRecoveryClassification>\n ): Promise<void> {\n const { incident, options, snapshot, recoveryRootRequestId } = input;\n const leaf =\n this.messages.length > 0\n ? this.messages[this.messages.length - 1]\n : undefined;\n const lostPartialUserId =\n snapshot?.continuation === false &&\n snapshot.latestUserMessageId &&\n leaf?.role === \"user\" &&\n leaf.id === snapshot.latestUserMessageId\n ? snapshot.latestUserMessageId\n : undefined;\n\n const targetId =\n input.detail.shouldRetryPreStream || lostPartialUserId !== undefined\n ? undefined\n : this._findLastAssistantMessage()?.id;\n\n if (input.detail.shouldRetryPreStream && options.continue !== false) {\n await this._chatRecoveryEngine().scheduleRecovery({\n incident,\n recoveryKind: input.recoveryKind,\n callback: \"_chatRecoveryRetry\",\n data: {\n targetUserId: snapshot?.latestUserMessageId,\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n lastBody: snapshot?.lastBody ?? null,\n lastClientTools: snapshot?.lastClientTools ?? null\n }\n });\n } else if (lostPartialUserId !== undefined && options.continue !== false) {\n // Re-run the orphaned new turn fresh instead of continuing (and merging\n // into) the previous assistant message. The incident may have opened as\n // `continue`, but the action (and the reported kind) is a `retry`.\n await this._chatRecoveryEngine().scheduleRecovery({\n incident,\n recoveryKind: \"retry\",\n callback: \"_chatRecoveryRetry\",\n data: {\n targetUserId: lostPartialUserId,\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n lastBody: snapshot?.lastBody ?? null,\n lastClientTools: snapshot?.lastClientTools ?? null\n }\n });\n } else if (options.continue !== false) {\n await this._chatRecoveryEngine().scheduleRecovery({\n incident,\n recoveryKind: input.recoveryKind,\n callback: \"_chatRecoveryContinue\",\n data: {\n ...(targetId ? { targetAssistantId: targetId } : {}),\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n ...(snapshot\n ? {\n lastBody: snapshot.lastBody ?? null,\n lastClientTools: snapshot.lastClientTools ?? null\n }\n : {})\n }\n });\n } else {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"skipped\",\n \"continue_disabled\"\n );\n }\n }\n\n /**\n * Called when an interrupted chat stream is detected after restart.\n * Return options to control recovery:\n *\n * - `{}` (default): persist partial response + schedule continuation\n * - `{ continue: false }`: persist but don't continue\n * - `{ persist: false, continue: false }`: handle everything yourself\n *\n * `ctx.recoveryData` contains any data checkpointed via `this.stash()`\n * during the turn (e.g., OpenAI `responseId`). If recovery happens before\n * any stream chunks exist and the latest message is still the unanswered\n * user message from the interrupted turn, the framework retries that turn\n * automatically unless continuation is disabled.\n */\n protected async onChatRecovery(\n // oxlint-disable-next-line @typescript-eslint/no-unused-vars -- overridable hook\n _ctx: ChatRecoveryContext\n ): Promise<ChatRecoveryOptions | void> {\n return {};\n }\n\n async _chatRecoveryContinue(data?: ChatRecoveryContinueData): Promise<void> {\n const previousRootRequestId = this._activeChatRecoveryRootRequestId;\n this._activeChatRecoveryRootRequestId =\n data?.originalRequestId ?? previousRootRequestId;\n try {\n const recoveryConfig = this._resolveChatRecoveryConfig();\n const ready = await this.waitUntilStable({\n timeout: recoveryConfig.stableTimeoutMs,\n // Recovery-scoped: a DEAD server-tool `input-available` orphan must not\n // block stability (A.2 repairs it below), so gate on the client-\n // resolvable predicate. A genuinely-pending CLIENT interaction still\n // keeps it unstable and parks via the `!ready` branch.\n pendingInteraction: () => this.hasPendingClientInteraction()\n });\n if (!ready) {\n // PARK, don't burn the budget: a stable-state timeout while a CLIENT\n // interaction is pending is not churn — the turn is correctly waiting\n // for the client to replay an interrupted tool-result / approval after\n // reconnect, which drives a fresh continuation independently of this\n // retry loop. Retrying here would just time out again (the human hasn't\n // answered) and eventually seal a healthy turn on `stable_timeout`. So\n // stop the loop, resolve the live \"recovering…\" indicator, and let the\n // client's replay resume the turn.\n if (await this._parkRecoveryForPendingInteraction(data)) {\n return;\n }\n console.warn(\n \"[AIChatAgent] _chatRecoveryContinue timed out waiting for stable state\"\n );\n // A stable-state timeout under deploy churn is usually transient (the\n // isolate is still settling / another deploy is in flight). Reschedule\n // within the attempt budget instead of permanently abandoning a\n // recoverable turn; only give up once the budget is exhausted.\n if (\n await this._rescheduleRecoveryAfterStableTimeout(\n \"_chatRecoveryContinue\",\n data,\n recoveryConfig.maxAttempts\n )\n ) {\n return;\n }\n // Budget spent: terminalize through the SAME exhaustion path as deploy\n // recovery (fires `onExhausted`, delivers the `terminalMessage` banner)\n // instead of silently dropping the turn — otherwise an app relying on\n // `onExhausted` sees an eternal spinner.\n await this._exhaustRecoveryAfterStableTimeout(\n \"_chatRecoveryContinue\",\n data\n );\n return;\n }\n\n const targetId = data?.targetAssistantId;\n if (targetId && this._findLastAssistantMessage()?.id !== targetId) {\n // The leaf moved, so this continuation is superseded — skip it.\n // NOTE: unlike `@cloudflare/think`, AIChatAgent does NOT distinguish an\n // assistant leaf (recovery's own forward progress) from a newer user\n // turn here, because AIChatAgent has no durable-submission layer to\n // protect — there is nothing to mark `skipped` vs leave `running`. If\n // AIChatAgent ever gains submissions, mirror Think's split in\n // `_chatRecoveryContinue` or this skip will silently clobber them.\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n \"skipped\",\n \"conversation_changed\"\n );\n return;\n }\n\n this._applyRecoveredRequestContext(data);\n // `continueLastTurn` repairs interrupted server-tool orphans before it\n // re-enters inference (`_repairInterruptedToolsBeforeTurn`), so the\n // recovered transcript is settled and the next `convertToModelMessages`\n // doesn't 400 with `AI_MissingToolResultsError`.\n const result = await this.continueLastTurn();\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n result.status === \"completed\"\n ? \"completed\"\n : result.status === \"skipped\"\n ? \"skipped\"\n : \"failed\",\n result.error\n );\n } catch (error) {\n // AIChatAgent otherwise has no continuation `catch` (a thrown error\n // propagates to `Agent._executeScheduleCallback`). The ONLY case we\n // intercept is an OOM thrown out of the turn (#1825): route it through the\n // tight OOM-retry budget, and rethrow everything else so the existing\n // behavior is byte-identical for non-OOM errors.\n if (await this._handleRecoveryOom(\"_chatRecoveryContinue\", data, error)) {\n return;\n }\n throw error;\n } finally {\n this._activeChatRecoveryRootRequestId = previousRootRequestId;\n // If this facet is an agent-tool child, its recovered turn just settled\n // outside `startAgentToolRun`'s finalizer — eagerly close the run so a\n // re-attached parent collects the terminal immediately rather than\n // waiting out a no-progress window.\n await this._reconcileOwnStaleAgentToolChildRuns();\n }\n }\n\n private _applyRecoveredRequestContext(\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined\n ): void {\n if (!data) return;\n if (\"lastClientTools\" in data) {\n this._lastClientTools = data.lastClientTools ?? undefined;\n }\n if (\"lastBody\" in data) {\n this._lastBody = data.lastBody ?? undefined;\n }\n if (\"lastClientTools\" in data || \"lastBody\" in data) {\n this._persistRequestContext();\n }\n }\n\n /**\n * Route a live stream stall (the {@link chatStreamStallTimeoutMs} watchdog\n * fired) into the same bounded-recovery machinery a deploy/eviction\n * interruption uses (#1626). Mirrors `@cloudflare/think`'s stall path: open or\n * reuse the incident under the turn's recovery identity, deliver terminal UX\n * if the budget is spent, otherwise schedule a `_chatRecoveryContinue`.\n *\n * Unlike Think there is no durable-submission layer to complete here, so the\n * schedule payload carries no `recoveredRequestId`.\n *\n * Returns `\"exhausted\"` when the budget was spent (terminal UX already\n * delivered), or `\"scheduled\"` when a continuation was queued.\n */\n private async _routeStallToBoundedRecovery(input: {\n requestId: string;\n streamId: string;\n partialParts: MessagePart[];\n targetAssistantId?: string;\n }): Promise<\"scheduled\" | \"exhausted\"> {\n const recoveryRootRequestId =\n this._activeChatRecoveryRootRequestId ?? input.requestId;\n const latestUserMessageId =\n [...this.messages].reverse().find((m) => m.role === \"user\")?.id ?? null;\n const { incident, config, exhausted } =\n await this._beginChatRecoveryIncident({\n requestId: input.requestId,\n recoveryRootRequestId,\n latestUserMessageId,\n recoveryKind: \"continue\"\n });\n if (exhausted) {\n // Budget spent: deliver the SAME terminal UX as deploy-recovery\n // exhaustion (terminalMessage + onExhausted + chat:recovery:exhausted)\n // instead of letting the raw stall error leak out. `firstSeenAt` is the\n // closest available turn-start proxy here.\n const partialText = input.partialParts\n .filter(\n (p): p is { type: \"text\"; text: string } =>\n (p as { type?: string }).type === \"text\"\n )\n .map((p) => p.text)\n .join(\"\");\n await this._exhaustChatRecovery(\n incident,\n config,\n { text: partialText, parts: input.partialParts },\n input.streamId,\n incident.firstSeenAt\n );\n return \"exhausted\";\n }\n await this._chatRecoveryEngine().scheduleRecovery({\n incident,\n recoveryKind: \"continue\",\n callback: \"_chatRecoveryContinue\",\n data: {\n ...(input.targetAssistantId\n ? { targetAssistantId: input.targetAssistantId }\n : {}),\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n lastBody: this._lastBody ?? null,\n lastClientTools: this._lastClientTools ?? null\n }\n });\n return \"scheduled\";\n }\n\n /**\n * Reschedule a recovery callback that timed out waiting for stable state,\n * consuming one attempt. Returns `true` if rescheduled, `false` if the\n * attempt budget is exhausted (caller should then fail terminally).\n */\n private async _rescheduleRecoveryAfterStableTimeout(\n callback: ChatRecoveryScheduleCallback,\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined,\n maxAttempts: number\n ): Promise<boolean> {\n // The attempt-bump + scheduled/stable_timeout_retry persist + delayed\n // non-idempotent reschedule live in the shared ChatRecoveryEngine; this\n // method is the package's adapter binding, symmetric with `Think`. See\n // design/rfc-chat-recovery-foundation.md.\n return this._chatRecoveryEngine().rescheduleAfterStableTimeout({\n incidentId: data?.incidentId,\n callback,\n data,\n fallbackMaxAttempts: maxAttempts\n });\n }\n\n /**\n * Park a recovery continuation that timed out waiting for stable state\n * because the turn is holding a pending CLIENT interaction (an\n * `input-available` client-tool part or an `approval-requested` part — see\n * `hasPendingClientInteraction`). Such a turn is WAITING ON THE HUMAN, not\n * stuck: the client replays the interrupted tool-result / approval after\n * reconnect, which drives a fresh continuation independently of the recovery\n * retry loop. Burning the attempt budget on that wait (each `waitUntilStable`\n * times out because the human hasn't answered) would seal a perfectly healthy\n * turn on `stable_timeout` — the symptom behind HITL \"session recovery errors\"\n * under deploy churn.\n *\n * So instead of rescheduling or exhausting, we stop the loop and mark the\n * incident `skipped` (reason `awaiting_client_interaction`). That retains the\n * incident record (a later genuine interruption re-evaluates it) while\n * resolving the live \"recovering…\" indicator via `_updateChatRecoveryIncident`\n * so the client sees the parked tool-call UI rather than an eternal spinner.\n * A client that never returns is reclaimed by the incident TTL sweep and DO\n * idle-eviction. SERVER-tool orphans are excluded by `hasPendingClientInteraction`\n * (their `execute` died with the isolate), so they still reschedule / exhaust\n * via the normal path. Mirrors the same helper in `@cloudflare/think`.\n *\n * Returns `true` when the recovery was parked (caller must return), `false`\n * when there is no pending client interaction (caller proceeds to the normal\n * reschedule / exhaustion path).\n */\n private async _parkRecoveryForPendingInteraction(\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined\n ): Promise<boolean> {\n if (!this.hasPendingClientInteraction()) return false;\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n \"skipped\",\n \"awaiting_client_interaction\"\n );\n return true;\n }\n\n /**\n * Terminalize a recovery turn that has run out of stable-state-timeout retry\n * budget — or whose incident record has vanished — by routing through the\n * SAME `_exhaustChatRecovery` path as deploy-recovery exhaustion. It fires\n * `onExhausted`, emits `chat:recovery:exhausted`, and delivers the configured\n * `terminalMessage`.\n *\n * This replaces the older give-up that only set the incident to `failed`,\n * which bypassed `_exhaustChatRecovery` entirely — so an app relying on\n * `onExhausted` for the terminal banner regressed to an eternal spinner when\n * recovery gave up under extreme churn. Shared by `_chatRecoveryRetry` and\n * `_chatRecoveryContinue`; mirrors the same helper in `@cloudflare/think`.\n *\n * Exactly-once terminalization here rests SOLELY on the\n * `stored?.status === \"exhausted\"` re-entry guard below — unlike\n * `@cloudflare/think`, `@cloudflare/ai-chat` has no durable-submission layer\n * to short-circuit a duplicate alarm earlier. The incident read/write are\n * best-effort because they back only that guard, not the terminal UX: a\n * failed read synthesizes the incident and a failed seal write costs at most\n * a re-delivered banner on a duplicate alarm.\n *\n * Two residual at-least-once edges, both deliberately accepted as \"deliver a\n * second banner\" ≫ \"silently drop the turn\":\n * • No `incidentId` at all in the payload (only reachable via a direct/test\n * invocation — every production scheduler carries one): the synthesized\n * incident can't be persisted (no key), so the guard can't arm.\n * • The record is swept AGAIN between two alarms (the guard re-persists on\n * the first, so this needs a second independent sweep) — vanishingly\n * unlikely.\n */\n /**\n * Recovery continuation callbacks the alarm-boundary OOM circuit breaker may\n * back off / purge (#1825). See `Agent._cf_handleAlarmMemoryLimitReset`.\n */\n protected override _cf_recoveryAlarmCallbacks(): string[] {\n return [\"_chatRecoveryContinue\", \"_chatRecoveryRetry\"];\n }\n\n /**\n * Seal any still-live recovery incident as an out-of-memory exhaustion when\n * the alarm circuit breaker trips at its strike budget (#1825). Runs at the\n * outermost alarm frame (post-unwind), so the terminal banner / `onExhausted`\n * and the sealed-incident write can land where mid-turn writes OOMed. Reuses\n * the shared give-up spine via the recovery engine.\n */\n protected override async _cf_sealMemoryLimitedRecovery(): Promise<void> {\n const active = await listActiveChatRecoveryIncidents(this.ctx.storage);\n for (const { incident } of active) {\n const callback: ChatRecoveryScheduleCallback =\n incident.recoveryKind === \"retry\"\n ? \"_chatRecoveryRetry\"\n : \"_chatRecoveryContinue\";\n await this._chatRecoveryEngine().exhaustRecoveryGiveUp({\n callback,\n data: { incidentId: incident.incidentId },\n reason: \"out_of_memory\"\n });\n }\n }\n\n private _exhaustRecoveryAfterStableTimeout(\n callback: ChatRecoveryScheduleCallback,\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined\n ): Promise<void> {\n // The give-up spine (read → re-entry-guard → build-exhausted-incident →\n // terminalize-before-seal → best-effort seal) lives in the shared\n // ChatRecoveryEngine; this is the package binding, symmetric with `Think`.\n // `AIChatAgent` always gives up with `stable_timeout` (its only give-up\n // trigger) and never sets `recoveredRequestId`, so the engine's unified\n // root-id chain collapses to `originalRequestId ?? activeRoot ?? stored…`\n // exactly as before. The terminalize + stream/partial hooks are wired on\n // the adapter above. See design/rfc-chat-recovery-foundation.md.\n return this._chatRecoveryEngine().exhaustRecoveryGiveUp({\n callback,\n data,\n reason: \"stable_timeout\"\n });\n }\n\n /**\n * Apply the tight OOM-retry budget to a recovery error (#1825). Symmetric with\n * `@cloudflare/think`'s `_handleRecoveryOom`: invoked from the narrow OOM-only\n * `catch` in `_chatRecoveryContinue` / `_chatRecoveryRetry`, i.e. for an OOM\n * that is *thrown* out of a recovery turn (e.g. storage/SQL ops rejecting with\n * the memory-limit-reset message after an isolate reset). An OOM caught inside\n * `continueLastTurn` that surfaces as a returned `error` result is NOT routed\n * here — that turn was already terminalized, so re-driving it would be wasteful\n * and risk a second terminal signal.\n *\n * The reliable terminator is the begin-path (`evaluateChatRecoveryIncident`),\n * which seals once `oomAttempts` exceeds the budget, running before the\n * memory-heavy turn in the low-memory window where writes succeed. This method\n * persists `oomAttempts` (small writes) for the begin path to act on, and\n * schedules a delayed re-run while under budget.\n *\n * Returns `true` when the error was an OOM and this method owns the outcome\n * (rescheduled a delayed re-run while under budget, or terminalized with\n * `reason=\"out_of_memory\"` once over budget / untrackable / bookkeeping\n * failed), `false` for non-OOM errors so the caller proceeds normally.\n */\n private async _handleRecoveryOom(\n callback: ChatRecoveryScheduleCallback,\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined,\n error: unknown\n ): Promise<boolean> {\n if (!isDurableObjectMemoryLimitReset(error)) return false;\n let decision: \"rescheduled\" | \"exhausted\" = \"exhausted\";\n try {\n decision = await this._chatRecoveryEngine().recordOomAndDecide({\n incidentId: data?.incidentId,\n callback,\n data,\n maxOomRetries: this._resolveChatRecoveryConfig().maxOomRetries\n });\n } catch (bookkeepingError) {\n // The bump/reschedule writes can themselves reject in the degraded isolate\n // that just OOMed. Fail closed (seal) rather than risk a silent wedge; the\n // finite `maxRecoveryWork` backstop covers anything that slips past.\n console.error(\n \"[AIChatAgent] failed to record OOM recovery attempt; terminalizing\",\n bookkeepingError\n );\n decision = \"exhausted\";\n }\n if (decision === \"exhausted\") {\n await this._chatRecoveryEngine().exhaustRecoveryGiveUp({\n callback,\n data,\n reason: \"out_of_memory\"\n });\n }\n return true;\n }\n\n private _shouldRetryRecoveredPreStreamTurn(\n snapshot: ChatFiberSnapshot | null,\n streamId: string,\n partial: { text: string; parts: unknown[] }\n ): snapshot is ChatFiberSnapshot & {\n latestUserMessageId: string;\n } {\n if (\n !snapshot ||\n snapshot.continuation ||\n !snapshot.latestUserMessageId ||\n streamId ||\n partial.text ||\n partial.parts.length > 0\n ) {\n return false;\n }\n\n const lastMessage =\n this.messages.length > 0 ? this.messages[this.messages.length - 1] : null;\n return (\n lastMessage?.role === \"user\" &&\n lastMessage.id === snapshot.latestUserMessageId\n );\n }\n\n async _chatRecoveryRetry(data?: ChatRecoveryRetryData): Promise<void> {\n const previousRootRequestId = this._activeChatRecoveryRootRequestId;\n this._activeChatRecoveryRootRequestId =\n data?.originalRequestId ?? previousRootRequestId;\n try {\n const recoveryConfig = this._resolveChatRecoveryConfig();\n const ready = await this.waitUntilStable({\n timeout: recoveryConfig.stableTimeoutMs,\n // Recovery-scoped narrow predicate (see `_chatRecoveryContinue`): a dead\n // server-tool orphan must not block stability; a real client\n // interaction still parks via the `!ready` branch.\n pendingInteraction: () => this.hasPendingClientInteraction()\n });\n if (!ready) {\n // PARK while a CLIENT interaction is pending — the turn is waiting for\n // the human, not churning; see `_chatRecoveryContinue` for the full\n // rationale.\n if (await this._parkRecoveryForPendingInteraction(data)) {\n return;\n }\n console.warn(\n \"[AIChatAgent] _chatRecoveryRetry timed out waiting for stable state\"\n );\n if (\n await this._rescheduleRecoveryAfterStableTimeout(\n \"_chatRecoveryRetry\",\n data,\n recoveryConfig.maxAttempts\n )\n ) {\n return;\n }\n // Budget spent: terminalize through the SAME exhaustion path as deploy\n // recovery (fires `onExhausted`, delivers the `terminalMessage` banner)\n // instead of silently dropping the turn — otherwise an app relying on\n // `onExhausted` sees an eternal spinner.\n await this._exhaustRecoveryAfterStableTimeout(\n \"_chatRecoveryRetry\",\n data\n );\n return;\n }\n\n const lastMessage =\n this.messages.length > 0\n ? this.messages[this.messages.length - 1]\n : null;\n if (!lastMessage || lastMessage.role !== \"user\") {\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n \"skipped\",\n \"no_unanswered_user_message\"\n );\n return;\n }\n\n if (data?.targetUserId && lastMessage.id !== data.targetUserId) {\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n \"skipped\",\n \"conversation_changed\"\n );\n return;\n }\n\n this._applyRecoveredRequestContext(data);\n // The retry runs through `_runProgrammaticChatTurn`, which repairs any\n // interrupted tool orphan before re-entering inference\n // (`_repairInterruptedToolsBeforeTurn`). The retry path normally re-runs\n // an unanswered user-message tail (no assistant orphan to repair), so that\n // is a defensive no-op here, but keeps both recovery entrypoints converged.\n const result = await this._retryLastUserTurn(\n this._lastClientTools,\n this._lastBody\n );\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n result.status === \"completed\"\n ? \"completed\"\n : result.status === \"skipped\"\n ? \"skipped\"\n : \"failed\",\n result.error\n );\n } catch (error) {\n // OOM-only intercept, rethrowing everything else (see\n // `_chatRecoveryContinue`, #1825).\n if (await this._handleRecoveryOom(\"_chatRecoveryRetry\", data, error)) {\n return;\n }\n throw error;\n } finally {\n this._activeChatRecoveryRootRequestId = previousRootRequestId;\n // If this facet is an agent-tool child, its recovered turn just settled\n // outside `startAgentToolRun`'s finalizer — eagerly close the run so a\n // re-attached parent collects the terminal immediately rather than\n // waiting out a no-progress window. The pre-stream retry path settles via\n // `_retryLastUserTurn`, which (like `continueLastTurn`) never hits the\n // finalizer, so it needs the same reconcile as `_chatRecoveryContinue`.\n await this._reconcileOwnStaleAgentToolChildRuns();\n }\n }\n\n /**\n * Extract partial text and parts from stored stream chunks.\n */\n private _getPartialStreamText(streamId: string): {\n text: string;\n parts: MessagePart[];\n hasSettledToolResults: boolean;\n } {\n return aiSdkRecoveryCodec.toRecoveryPartial(\n this._resumableStream.getStreamChunks(streamId).map((chunk) => chunk.body)\n );\n }\n\n async persistMessages(\n messages: UIMessage[],\n excludeBroadcastIds: string[] = [],\n /** @internal */\n options?: { _deleteStaleRows?: boolean }\n ) {\n const mergedMessages = reconcileMessages(messages, this.messages, (msg) =>\n this._sanitizeMessageForPersistence(msg)\n );\n\n // Persist only new or changed messages (incremental persistence).\n // Compares serialized JSON against a cache of last-persisted versions.\n for (const message of mergedMessages) {\n const sanitizedMessage = this._sanitizeMessageForPersistence(message);\n const resolved = resolveToolMergeId(sanitizedMessage, this.messages);\n const safe = this._enforceRowSizeLimit(resolved);\n const json = JSON.stringify(safe);\n\n // Skip SQL write if the message is identical to what's already persisted\n if (this._persistedMessageCache.get(safe.id) === json) {\n continue;\n }\n\n this.sql`\n insert into cf_ai_chat_agent_messages (id, message)\n values (${safe.id}, ${json})\n on conflict(id) do update set message = excluded.message\n `;\n this._persistedMessageCache.set(safe.id, json);\n }\n\n // Reconcile: delete DB rows not present in the incoming message set.\n // Only safe when the incoming set is a subset of the server state\n // (e.g. regenerate() trims the last assistant message). When the\n // client appends new messages (IDs unknown to the server), it may\n // not have the full history, so deleting \"missing\" rows would\n // destroy server-generated assistant messages the client hasn't\n // seen yet.\n // This MUST use mergedMessages (post-merge IDs) because\n // reconcileMessages can remap client IDs to server IDs.\n if (options?._deleteStaleRows) {\n const serverIds = new Set(this.messages.map((m) => m.id));\n const isSubsetOfServer = mergedMessages.every((m) => serverIds.has(m.id));\n\n if (isSubsetOfServer) {\n const keepIds = new Set(mergedMessages.map((m) => m.id));\n const allDbRows =\n this.sql<{ id: string }>`\n select id from cf_ai_chat_agent_messages\n ` || [];\n const staleIds = allDbRows\n .map((row) => row.id)\n .filter((id) => !keepIds.has(id));\n this._deleteMessagesByIds(staleIds);\n }\n }\n\n // Enforce maxPersistedMessages: delete oldest messages if over the limit\n if (this.maxPersistedMessages != null) {\n this._enforceMaxPersistedMessages();\n }\n\n // refresh in-memory messages\n const persisted = this._loadMessagesFromDb();\n this.messages = autoTransformMessages(persisted);\n this._broadcastChatMessage(\n {\n messages: mergedMessages,\n type: MessageType.CF_AGENT_CHAT_MESSAGES\n },\n excludeBroadcastIds\n );\n }\n\n /**\n * Finds an existing assistant message that contains a tool part with the given toolCallId.\n * Used to detect when a tool result should update an existing message rather than\n * creating a new one.\n *\n * @param toolCallId - The tool call ID to search for\n * @returns The existing message if found, undefined otherwise\n */\n private _findMessageByToolCallId(toolCallId: string): UIMessage | undefined {\n for (const msg of this.messages) {\n if (msg.role !== \"assistant\") continue;\n\n for (const part of msg.parts) {\n if (\"toolCallId\" in part && part.toolCallId === toolCallId) {\n return msg;\n }\n }\n }\n return undefined;\n }\n\n private _findLastAssistantMessage(): UIMessage | undefined {\n for (let i = this.messages.length - 1; i >= 0; i--) {\n if (this.messages[i].role === \"assistant\") {\n return this.messages[i];\n }\n }\n\n return undefined;\n }\n\n private _createStreamingAssistantMessage(continuation: boolean): UIMessage {\n if (continuation) {\n const lastAssistant = this._findLastAssistantMessage();\n if (lastAssistant) {\n return structuredClone(lastAssistant);\n }\n }\n\n return {\n id: `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`,\n role: \"assistant\",\n parts: []\n };\n }\n\n /**\n * Sanitizes a message for persistence by removing ephemeral provider-specific\n * data that should not be stored or sent back in subsequent requests.\n *\n * Pipeline:\n *\n * 1. **Strip OpenAI ephemeral fields**: The AI SDK's @ai-sdk/openai provider\n * (v2.0.x+) defaults to using OpenAI's Responses API which assigns unique\n * itemIds and reasoningEncryptedContent to message parts. When persisted\n * and sent back, OpenAI rejects duplicate itemIds.\n *\n * 2. **Truncate provider-executed tool payloads**: Server-side tool\n * executions (e.g. Anthropic code_execution, text_editor) can produce\n * 200KB+ payloads in `input` and `output`. These are truncated since the\n * model has already consumed the results.\n *\n * 3. **Filter truly empty reasoning parts**: After stripping, reasoning parts\n * with no text and no remaining providerMetadata are removed. Parts that\n * still carry providerMetadata (e.g. Anthropic's redacted_thinking blocks\n * with providerMetadata.anthropic.redactedData) are preserved, as they\n * contain data required for round-tripping with the provider API.\n *\n * 4. **User hook**: Calls the overridable `sanitizeMessageForPersistence()`\n * method, allowing subclasses to apply custom transformations.\n *\n * @param message - The message to sanitize\n * @returns A new message with ephemeral provider data removed\n */\n private _sanitizeMessageForPersistence(message: UIMessage): UIMessage {\n // Base sanitization: strip OpenAI ephemeral fields + filter empty reasoning parts\n const baseSanitized = sanitizeMessage(message);\n\n // ai-chat-specific: truncate large payloads in provider-executed tool parts\n const parts = baseSanitized.parts.map((part) =>\n AIChatAgent._truncateProviderExecutedToolPayloads(part)\n ) as UIMessage[\"parts\"];\n\n // Run user-overridable hook last\n return this.sanitizeMessageForPersistence({\n ...baseSanitized,\n parts\n });\n }\n\n /**\n * Truncates large string values in `input` and `output` of tool parts that\n * were executed server-side by the provider (e.g. Anthropic code_execution,\n * text_editor). These payloads can be 200KB+ and are dead weight once the\n * model has consumed the result.\n *\n * Anthropic web tools are excluded because their outputs are replayed on\n * subsequent turns. Within other tool payloads, opaque encrypted fields are\n * always preserved verbatim.\n */\n private static _truncateProviderExecutedToolPayloads<\n T extends UIMessage[\"parts\"][number]\n >(part: T): T {\n const record = part as Record<string, unknown>;\n if (!record.providerExecuted) return part;\n if (AIChatAgent._shouldPreserveProviderToolPayload(record)) return part;\n\n const result = { ...record };\n\n if (result.input !== undefined) {\n result.input = AIChatAgent._truncateLargeStrings(result.input);\n }\n if (result.output !== undefined) {\n result.output = AIChatAgent._truncateLargeStrings(result.output);\n }\n\n return result as T;\n }\n\n /**\n * Recursively walks a value and truncates any string exceeding\n * `PROVIDER_TOOL_MAX_STRING_LENGTH`, appending a size marker.\n *\n * The total output (content + marker) is kept within the threshold so\n * re-running this function on already-truncated data is a no-op. Strings\n * under opaque encrypted keys are preserved verbatim.\n */\n private static _truncateLargeStrings(\n value: unknown,\n preserveOpaqueStrings = false\n ): unknown {\n if (typeof value === \"string\") {\n if (preserveOpaqueStrings) return value;\n if (value.length > PROVIDER_TOOL_MAX_STRING_LENGTH) {\n const marker = `… [truncated, original length: ${value.length}]`;\n const contentLength = Math.max(\n 0,\n PROVIDER_TOOL_MAX_STRING_LENGTH - marker.length\n );\n return value.slice(0, contentLength) + marker;\n }\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((v) =>\n AIChatAgent._truncateLargeStrings(v, preserveOpaqueStrings)\n );\n }\n if (value !== null && typeof value === \"object\") {\n const result: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n result[k] = AIChatAgent._truncateLargeStrings(\n v,\n preserveOpaqueStrings || AIChatAgent._isOpaqueReplayFieldKey(k)\n );\n }\n return result;\n }\n return value;\n }\n\n private static _shouldPreserveProviderToolPayload(\n part: Record<string, unknown>\n ): boolean {\n const toolName = AIChatAgent._getToolNameFromPart(part);\n return toolName === \"web_search\" || toolName === \"web_fetch\";\n }\n\n private static _getToolNameFromPart(\n part: Record<string, unknown>\n ): string | undefined {\n if (typeof part.toolName === \"string\") {\n return part.toolName;\n }\n\n if (typeof part.type === \"string\" && part.type.startsWith(\"tool-\")) {\n return part.type.slice(\"tool-\".length);\n }\n\n return undefined;\n }\n\n private static _isOpaqueReplayFieldKey(key: string): boolean {\n return key.startsWith(PROVIDER_TOOL_OPAQUE_STRING_KEY_PREFIX);\n }\n\n /**\n * Delete the given message rows from SQLite in batched `IN (...)` queries\n * and evict them from the persistence cache. Batches stay within the SQLite\n * 100 bound-parameter limit. No-op for an empty list.\n * @internal\n */\n private _deleteMessagesByIds(ids: string[]) {\n for (let i = 0; i < ids.length; i += MAX_BOUND_PARAMS) {\n const batch = ids.slice(i, i + MAX_BOUND_PARAMS);\n const strings = buildInClauseStrings(\n \"delete from cf_ai_chat_agent_messages where id in \",\n batch.length\n );\n this.sql(strings, ...batch);\n for (const id of batch) {\n this._persistedMessageCache.delete(id);\n }\n }\n }\n\n /**\n * Deletes oldest messages from SQLite when the count exceeds maxPersistedMessages.\n * Called after each persist to keep storage bounded.\n */\n private _enforceMaxPersistedMessages() {\n if (this.maxPersistedMessages == null) return;\n\n const countResult = this.sql<{ cnt: number }>`\n select count(*) as cnt from cf_ai_chat_agent_messages\n `;\n const count = countResult?.[0]?.cnt ?? 0;\n\n if (count <= this.maxPersistedMessages) return;\n\n const excess = count - this.maxPersistedMessages;\n\n // Delete the oldest messages (by created_at)\n // Also remove them from the persistence cache\n const toDelete = this.sql<{ id: string }>`\n select id from cf_ai_chat_agent_messages \n order by created_at asc \n limit ${excess}\n `;\n\n if (toDelete && toDelete.length > 0) {\n this._deleteMessagesByIds(toDelete.map((row) => row.id));\n }\n }\n\n /**\n * Enforces SQLite row size limits by compacting tool outputs and text parts\n * when a serialized message exceeds the safety threshold (1.8MB).\n *\n * Only fires in pathological cases (extremely large tool outputs or text).\n * Returns the message unchanged if it fits within limits.\n *\n * Compaction strategy:\n * 1. Compact tool outputs over 1KB (replace with LLM-friendly summary)\n * 2. If still too big, truncate text parts from oldest to newest\n * 3. Add metadata so clients can detect compaction\n *\n * @param message - The message to check\n * @returns The message, compacted if necessary\n */\n private _enforceRowSizeLimit(message: UIMessage): UIMessage {\n return enforceRowSizeLimit(message, {\n warn: (m) => console.warn(`[AIChatAgent] ${m}`)\n });\n }\n\n /**\n * Shared helper for finding a tool part by toolCallId and applying an update.\n * Handles both streaming (in-memory) and persisted (SQLite) messages.\n *\n * Checks _streamingMessage first (tool results/approvals can arrive while\n * the AI is still streaming), then retries persisted messages with backoff\n * in case streaming completes between attempts.\n *\n * `applyUpdate` may return its argument by reference (or `{ ...part }`\n * with no semantic changes) to signal an idempotent no-op — this is\n * detected via `_isToolPartUnchanged` and short-circuits the SQLite\n * write and `MESSAGE_UPDATED` broadcast.\n *\n * @param toolCallId - The tool call ID to find\n * @param callerName - Name for log messages (e.g. \"_applyToolResult\")\n * @param matchStates - Which tool part states to match\n * @param applyUpdate - Mutation to apply to the matched part (streaming: in-place, persisted: spread)\n * @returns true if the update was applied (or matched as an idempotent\n * no-op), false if no matching part was found\n */\n private async _findAndUpdateToolPart(\n toolCallId: string,\n callerName: string,\n matchStates: string[],\n applyUpdate: (part: Record<string, unknown>) => Record<string, unknown>\n ): Promise<boolean> {\n // Find the message containing this tool call.\n // Check streaming message first (in-memory, not yet persisted), then\n // retry persisted messages with backoff.\n let message: UIMessage | undefined;\n\n if (this._streamingMessage) {\n for (const part of this._streamingMessage.parts) {\n if (\"toolCallId\" in part && part.toolCallId === toolCallId) {\n message = this._streamingMessage;\n break;\n }\n }\n }\n\n if (!message) {\n for (let attempt = 0; attempt < 10; attempt++) {\n message = this._findMessageByToolCallId(toolCallId);\n if (message) break;\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n }\n\n if (!message) {\n console.warn(\n `[AIChatAgent] ${callerName}: Could not find message with toolCallId ${toolCallId} after retries`\n );\n return false;\n }\n\n const isStreamingMessage = message === this._streamingMessage;\n // `wasFound` tracks whether any matching part was processed (real\n // change OR idempotent no-op). `hasRealChange` tracks whether any\n // apply actually mutated state. Tracking both separately matters\n // when a (legacy) message somehow contains duplicate tool parts for\n // the same toolCallId — we must still persist if any of them\n // produced a real change, even if another was an idempotent no-op.\n let wasFound = false;\n let hasRealChange = false;\n\n if (isStreamingMessage) {\n // Update in place -- the message will be persisted when streaming completes\n for (const part of message.parts) {\n if (\n \"toolCallId\" in part &&\n part.toolCallId === toolCallId &&\n \"state\" in part &&\n matchStates.includes(part.state as string)\n ) {\n wasFound = true;\n const applied = applyUpdate(part as Record<string, unknown>);\n if (\n !AIChatAgent._isToolPartUnchanged(\n part as Record<string, unknown>,\n applied\n )\n ) {\n Object.assign(part, applied);\n hasRealChange = true;\n }\n break;\n }\n }\n } else {\n // For persisted messages, create updated parts immutably\n const updatedParts = message.parts.map((part) => {\n if (\n \"toolCallId\" in part &&\n part.toolCallId === toolCallId &&\n \"state\" in part &&\n matchStates.includes(part.state as string)\n ) {\n wasFound = true;\n const applied = applyUpdate(part as Record<string, unknown>);\n if (\n AIChatAgent._isToolPartUnchanged(\n part as Record<string, unknown>,\n applied\n )\n ) {\n return part;\n }\n hasRealChange = true;\n return applied;\n }\n return part;\n }) as UIMessage[\"parts\"];\n\n if (hasRealChange) {\n const updatedMessage: UIMessage = this._sanitizeMessageForPersistence({\n ...message,\n parts: updatedParts\n });\n const safe = this._enforceRowSizeLimit(updatedMessage);\n const json = JSON.stringify(safe);\n\n this.sql`\n update cf_ai_chat_agent_messages \n set message = ${json}\n where id = ${message.id}\n `;\n this._persistedMessageCache.set(message.id, json);\n\n const persisted = this._loadMessagesFromDb();\n this.messages = autoTransformMessages(persisted);\n }\n }\n\n if (!wasFound) {\n console.warn(\n `[AIChatAgent] ${callerName}: Tool part with toolCallId ${toolCallId} not in expected state (expected: ${matchStates.join(\"|\")})`\n );\n return false;\n }\n\n // Idempotent no-op: caller asked us to apply something we'd already\n // applied (e.g. a duplicate cf_agent_tool_result, or a cross-tab\n // re-delivery). Skip the broadcast — clients are already in the\n // correct state and a redundant MESSAGE_UPDATED would just churn UI.\n if (!hasRealChange) {\n return true;\n }\n\n // Broadcast the update to all clients.\n // For persisted messages, re-fetch the latest state from this.messages.\n // For streaming messages, broadcast the in-memory snapshot so clients\n // get immediate confirmation that the tool result/approval was applied.\n if (isStreamingMessage) {\n this._broadcastChatMessage({\n type: MessageType.CF_AGENT_MESSAGE_UPDATED,\n message\n });\n } else {\n const broadcastMessage = this._findMessageByToolCallId(toolCallId);\n if (broadcastMessage) {\n this._broadcastChatMessage({\n type: MessageType.CF_AGENT_MESSAGE_UPDATED,\n message: broadcastMessage\n });\n }\n }\n\n return true;\n }\n\n /**\n * Returns true if `applied` is the same reference as `original`, or if\n * the two have identical state-relevant fields. Used by\n * `_findAndUpdateToolPart` to detect idempotent re-applies and skip\n * SQLite writes plus `MESSAGE_UPDATED` broadcasts.\n */\n private static _isToolPartUnchanged(\n original: Record<string, unknown>,\n applied: Record<string, unknown>\n ): boolean {\n if (applied === original) return true;\n if (applied.state !== original.state) return false;\n // For terminal output states, the only fields the apply functions\n // touch are output / errorText / preliminary. Compare via JSON so\n // structurally equal outputs (the common idempotent case) compare\n // equal regardless of reference identity.\n if (\n applied.state === \"output-available\" ||\n applied.state === \"output-error\"\n ) {\n return (\n JSON.stringify(applied.output) === JSON.stringify(original.output) &&\n applied.errorText === original.errorText &&\n applied.preliminary === original.preliminary\n );\n }\n if (applied.state === \"output-denied\") {\n return true;\n }\n if (\n applied.state === \"approval-responded\" ||\n applied.state === \"approval-requested\"\n ) {\n return (\n JSON.stringify(applied.approval) === JSON.stringify(original.approval)\n );\n }\n return false;\n }\n\n /**\n * Serialize a client-tool result/approval apply behind any in-flight apply\n * (#1649, defensive). Each apply is a read-modify-write of the message and\n * parallel tool results arrive as independent WebSocket messages. Today\n * `_findAndUpdateToolPart` performs that read-modify-write synchronously (no\n * await between reading `this.messages` and the SQLite write), so concurrent\n * applies can't actually interleave — unlike Think, ai-chat does not exhibit\n * the #1649 clobber. This queue is a guard so the invariant survives if the\n * apply ever gains an await between read and write (e.g. async storage): each\n * apply commits atomically in arrival order.\n *\n * `_pendingInteractionPromise` is set to the newest link so the barrier's\n * single-slot wake-up observes the latest apply; because the chain is serial,\n * awaiting it transitively waits for every predecessor.\n *\n * @internal\n */\n protected _enqueueInteractionApply(\n apply: () => Promise<boolean>\n ): Promise<boolean> {\n // `.then(apply, apply)` runs regardless of a predecessor's outcome so one\n // rejected apply can't poison the rest of the batch.\n const resultPromise = this._interactionApplyTail.then(apply, apply);\n this._interactionApplyTail = resultPromise.then(\n () => undefined,\n () => undefined\n );\n this._pendingInteractionPromise = resultPromise;\n resultPromise\n .finally(() => {\n if (this._pendingInteractionPromise === resultPromise) {\n this._pendingInteractionPromise = null;\n }\n })\n .catch(() => {});\n return resultPromise;\n }\n\n /**\n * Applies a tool result to an existing assistant message.\n * This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.\n * The server is the source of truth, so we update the message here and broadcast\n * the update to all clients.\n *\n * `output-available` and `output-error` are accepted as valid starting\n * states for *idempotent* re-application — duplicate WS frames, second\n * tabs re-running the same tool, and provider-replay round-trips all\n * become silent no-ops rather than a warn + skipped update. The first\n * applied terminal result wins; subsequent results carrying *different*\n * data are also dropped (preserving the existing \"first write wins\"\n * contract — see `client-tool-duplicate-message.test.ts`). See issue\n * #1404.\n *\n * @param toolCallId - The tool call ID this result is for\n * @param _toolName - The name of the tool (unused, kept for API compat)\n * @param output - The output from the tool execution\n * @param overrideState - Optional state override (\"output-error\" to signal denial/failure)\n * @param errorText - Error message when overrideState is \"output-error\"\n * @returns true if the result was applied, false if the message was not found\n */\n private async _applyToolResult(\n toolCallId: string,\n _toolName: string,\n output: unknown,\n overrideState?: \"output-error\",\n errorText?: string\n ): Promise<boolean> {\n return this._findAndUpdateToolPart(\n toolCallId,\n \"_applyToolResult\",\n [\n \"input-available\",\n \"approval-requested\",\n \"approval-responded\",\n // Idempotent re-apply: if the part is already terminal, the apply\n // function below returns the part by reference. _findAndUpdateToolPart\n // detects that and skips the persist + broadcast (and the warn).\n \"output-available\",\n \"output-error\",\n \"output-denied\"\n ],\n (part) => {\n // Once a tool part has reached a terminal state, the first applied\n // result wins. Don't overwrite with conflicting data, and don't\n // emit a redundant MESSAGE_UPDATED for a matching re-apply.\n if (\n part.state === \"output-available\" ||\n part.state === \"output-error\" ||\n part.state === \"output-denied\"\n ) {\n return part;\n }\n if (overrideState === \"output-error\") {\n return {\n ...part,\n state: \"output-error\",\n errorText: errorText ?? \"Tool execution denied by user\"\n };\n }\n return {\n ...part,\n state: \"output-available\",\n output,\n preliminary: false\n };\n }\n );\n }\n\n private async _streamSSEReply(\n id: string,\n streamId: string,\n reader: ReadableStreamDefaultReader<Uint8Array>,\n message: UIMessage,\n streamCompleted: { value: boolean },\n continuation = false,\n abortSignal?: AbortSignal\n ): Promise<StreamResultStatus> {\n streamCompleted.value = false;\n\n // During continuation, the first text-start and reasoning-start from the\n // model should merge into existing parts (from the cloned message) rather\n // than creating new blocks. Track whether we've already resumed each type.\n let continuationTextResumed = false;\n let continuationReasoningResumed = false;\n\n // Cancel the reader when the abort signal fires (e.g. client pressed stop).\n // This ensures we stop broadcasting chunks even if the underlying stream\n // hasn't been connected to the abort signal (e.g. user forgot to pass it\n // to streamText).\n if (abortSignal && !abortSignal.aborted) {\n abortSignal.addEventListener(\n \"abort\",\n () => {\n reader.cancel().catch(() => {});\n },\n { once: true }\n );\n }\n\n // Route reads through the shared inactivity watchdog when a stall timeout is\n // configured. The watchdog aborts a stream that parks between chunks (a hung\n // provider/transport) by cancelling the reader and throwing\n // `ChatStreamStalledError`, which the read-loop catch propagates so `_reply`\n // can route the stall into bounded recovery (#1626). A `0` timeout (the\n // default) keeps the raw `reader.read()` path untouched.\n const stallTimeoutMs = this.chatStreamStallTimeoutMs;\n let pull: () => Promise<ReadableStreamReadResult<Uint8Array>>;\n if (stallTimeoutMs > 0) {\n const byteSource: AsyncIterable<Uint8Array> = {\n [Symbol.asyncIterator]() {\n return {\n async next(): Promise<IteratorResult<Uint8Array>> {\n const { done, value } = await reader.read();\n return done || value === undefined\n ? { done: true, value: undefined }\n : { done: false, value };\n },\n async return(): Promise<IteratorResult<Uint8Array>> {\n await reader.cancel().catch(() => {});\n return { done: true, value: undefined };\n }\n };\n }\n };\n const guarded = iterateWithStallWatchdog(\n byteSource,\n stallTimeoutMs,\n () => {\n // Unblock the abandoned `reader.read()` so the pipeline unwinds; the\n // thrown `ChatStreamStalledError` carries the recovery decision.\n reader.cancel().catch(() => {});\n }\n )[Symbol.asyncIterator]();\n pull = async () => {\n const next = await guarded.next();\n return next.done\n ? { done: true, value: undefined }\n : { done: false, value: next.value };\n };\n } else {\n pull = () => reader.read();\n }\n\n while (true) {\n if (abortSignal?.aborted) break;\n let readResult: ReadableStreamReadResult<Uint8Array>;\n try {\n readResult = await pull();\n } catch (readError) {\n if (abortSignal?.aborted) break;\n throw readError;\n }\n const { done, value } = readResult;\n if (done) {\n // reader.cancel() resolves read() with { done: true } — check abort\n if (abortSignal?.aborted) break;\n this._completeStream(streamId);\n streamCompleted.value = true;\n this._broadcastChatMessage({\n body: \"\",\n done: true,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n ...(continuation && { continuation: true })\n });\n return { status: \"completed\" };\n }\n\n const chunk = decoder.decode(value);\n const lines = chunk.split(\"\\n\");\n\n for (const line of lines) {\n if (line.startsWith(\"data: \") && line !== \"data: [DONE]\") {\n try {\n const data: UIMessageChunk = JSON.parse(line.slice(6));\n\n // During continuation, merge into existing parts rather than\n // creating new blocks:\n // - text-start: suppressed only when the last text part has\n // state \"streaming\" (interrupted mid-generation). Parts with\n // state \"done\" or no state create new blocks as usual (e.g.\n // tool auto-continuation).\n // - reasoning-start: suppressed when resuming an interrupted\n // assistant turn (an existing reasoning part is still streaming,\n // or the message has progressed to a still-streaming text part).\n // Completed reasoning blocks from earlier tool-continuation steps\n // must not swallow new continuation reasoning, otherwise the\n // streamed reasoning block disappears when the final persisted\n // message replaces the live stream.\n let skipServerApply = false;\n if (continuation) {\n if (!continuationTextResumed && data.type === \"text-start\") {\n for (let k = message.parts.length - 1; k >= 0; k--) {\n const part = message.parts[k];\n if (part.type === \"text\") {\n if (\n \"state\" in part &&\n (part as { state: string }).state === \"streaming\"\n ) {\n continuationTextResumed = true;\n }\n break;\n }\n }\n if (continuationTextResumed) continue;\n }\n if (\n !continuationReasoningResumed &&\n data.type === \"reasoning-start\"\n ) {\n for (let k = message.parts.length - 1; k >= 0; k--) {\n const part = message.parts[k];\n if (part.type === \"text\") {\n if (\n \"state\" in part &&\n (part as { state: string }).state === \"streaming\"\n ) {\n continuationReasoningResumed = true;\n }\n break;\n }\n if (part.type === \"reasoning\") {\n if (\n \"state\" in part &&\n (part as { state: string }).state === \"streaming\"\n ) {\n continuationReasoningResumed = true;\n }\n break;\n }\n }\n // For interrupted continuations, keep appending to the cloned\n // reasoning part but still forward reasoning-start to the\n // client. AI SDK v6 requires reasoning-start before any\n // reasoning-delta in the stream processor's active-part\n // registry.\n skipServerApply = continuationReasoningResumed;\n }\n }\n\n // Drop replay chunks before applying or broadcasting them.\n //\n // Some providers (notably the OpenAI Responses API) re-emit\n // prior tool calls as a fresh `tool-input-start` →\n // `tool-input-delta` → `tool-input-available` sequence\n // carrying the *same* `toolCallId` during continuation\n // streams. AI SDK v6's `updateToolPart` finds an existing\n // part by toolCallId and mutates it in place, which\n // visibly regresses an `output-available` part back to\n // `input-streaming`/`input-available` on the client\n // (issue #1404).\n //\n // `applyChunkToParts` handles the server-side cloned\n // streaming message safely (it's idempotent for these\n // chunk types), but we must also stop these chunks from\n // reaching the client-side AI SDK, where the in-place\n // mutation would corrupt a resolved tool part.\n //\n // `tool-output-available` is not filtered: its in-place\n // update sets state and output to the values the part\n // already has when the replay matches, so it's\n // semantically a no-op on the client too.\n if (isReplayChunk(message.parts, data as StreamChunkData)) {\n continue;\n }\n\n // Delegate message building to the shared parser.\n // It handles: text, reasoning, file, source, tool lifecycle,\n // step boundaries — all the part types needed for UIMessage.\n const handled = skipServerApply\n ? true\n : applyChunkToParts(message.parts, data);\n\n // When a tool enters approval-requested state, the stream is\n // paused waiting for user approval. Persist the streaming message\n // immediately so the approval UI survives page refresh. Without\n // this, a refresh would reload from SQLite where the tool part\n // is still in input-available state, showing \"Running...\" instead\n // of the Approve/Reject buttons.\n if (\n data.type === \"tool-approval-request\" &&\n this._streamingMessage\n ) {\n // Persist directly to SQLite without broadcasting.\n // The client already has this data from the SSE stream —\n // broadcasting would cause the approval UI to render twice.\n // We only need the SQL write so the state survives page refresh.\n const snapshot: UIMessage = {\n ...this._streamingMessage,\n parts: [...this._streamingMessage.parts]\n };\n const sanitized = this._sanitizeMessageForPersistence(snapshot);\n const json = JSON.stringify(sanitized);\n this.sql`\n INSERT INTO cf_ai_chat_agent_messages (id, message)\n VALUES (${sanitized.id}, ${json})\n ON CONFLICT(id) DO UPDATE SET message = excluded.message\n `;\n // Track that we persisted early so stream completion can update\n // in place rather than appending a duplicate.\n this._approvalPersistedMessageId = sanitized.id;\n }\n\n // Cross-message tool output fallback:\n // When a tool with needsApproval is approved, the continuation\n // stream emits tool-output-available/tool-output-error for a\n // tool call that lives in a *previous* assistant message.\n // applyChunkToParts only searches the current message's parts,\n // so the update is silently skipped. Fall back to searching\n // this.messages and update the persisted message directly.\n // Note: checked independently of `handled` — applyChunkToParts\n // returns true for recognized chunk types even when it cannot\n // find the target part, so `handled` is not a reliable signal.\n //\n // `output-available` and `output-error` are accepted as\n // starting states for idempotent re-application. Some\n // providers (notably the OpenAI Responses API) replay the\n // entire prior tool round-trip during continuations — the\n // replay's tool-output-available carries the same output the\n // part already has, so the apply functions below short-circuit\n // to a no-op via reference equality (issue #1404).\n if (\n (data.type === \"tool-output-available\" ||\n data.type === \"tool-output-error\") &&\n data.toolCallId\n ) {\n const foundInCurrentMessage = message.parts.some(\n (p) => \"toolCallId\" in p && p.toolCallId === data.toolCallId\n );\n if (!foundInCurrentMessage) {\n if (data.type === \"tool-output-available\") {\n this._findAndUpdateToolPart(\n data.toolCallId,\n \"_streamSSEReply\",\n [\n \"input-available\",\n \"input-streaming\",\n \"approval-responded\",\n \"approval-requested\",\n \"output-available\",\n \"output-error\",\n \"output-denied\"\n ],\n (part) => {\n // First-write-wins: a chunk arriving for a tool\n // that's already terminal is a provider replay.\n // Never overwrite a resolved tool's output.\n if (\n part.state === \"output-available\" ||\n part.state === \"output-error\" ||\n part.state === \"output-denied\"\n ) {\n return part;\n }\n return {\n ...part,\n state: \"output-available\",\n output: data.output,\n ...(data.preliminary !== undefined && {\n preliminary: data.preliminary\n })\n };\n }\n );\n } else {\n this._findAndUpdateToolPart(\n data.toolCallId,\n \"_streamSSEReply\",\n [\n \"input-available\",\n \"input-streaming\",\n \"approval-responded\",\n \"approval-requested\",\n \"output-available\",\n \"output-error\",\n \"output-denied\"\n ],\n (part) => {\n if (\n part.state === \"output-available\" ||\n part.state === \"output-error\" ||\n part.state === \"output-denied\"\n ) {\n return part;\n }\n return {\n ...part,\n state: \"output-error\",\n errorText: data.errorText\n };\n }\n );\n }\n }\n }\n\n // Handle server-specific chunk types not covered by the shared parser\n if (!handled) {\n switch (data.type) {\n case \"start\": {\n if (data.messageId != null && !continuation) {\n message.id = data.messageId;\n }\n if (data.messageMetadata != null) {\n message.metadata = message.metadata\n ? { ...message.metadata, ...data.messageMetadata }\n : data.messageMetadata;\n }\n break;\n }\n case \"finish\":\n case \"message-metadata\": {\n if (data.messageMetadata != null) {\n message.metadata = message.metadata\n ? { ...message.metadata, ...data.messageMetadata }\n : data.messageMetadata;\n }\n break;\n }\n case \"finish-step\": {\n // No-op for message building (shared parser handles step-start)\n break;\n }\n case \"error\": {\n const error =\n data.errorText ?? JSON.stringify({ type: data.type });\n this._broadcastChatMessage({\n error: true,\n body: error,\n done: false,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n ...(continuation && { continuation: true })\n });\n this._markStreamError(streamId);\n this._emit(\"message:error\", { error });\n await reader.cancel().catch(() => {});\n streamCompleted.value = true;\n this._broadcastChatMessage({\n body: \"\",\n done: true,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n ...(continuation && { continuation: true })\n });\n return { status: \"error\", error };\n }\n }\n }\n\n // Rewrite chunks before storing and broadcasting:\n // 1. Strip messageId from continuation start chunks so clients\n // reuse the existing assistant message (#1229).\n // 2. Stamp the allocated assistant id onto a new turn's start chunk\n // so the client builds the live message under the SAME id the\n // server persists under (see below).\n // 3. Convert the internal \"finish\" event's finishReason into the\n // UIMessageStreamPart messageMetadata format (#677).\n let eventToSend: unknown = data;\n if (data.type === \"start\") {\n if (continuation && \"messageId\" in data) {\n const { messageId: _, ...rest } = data as {\n messageId: unknown;\n [key: string]: unknown;\n };\n eventToSend = rest;\n } else if (!continuation) {\n // Most providers (e.g. Workers AI) emit no `start.messageId`,\n // so the client's AI SDK would build the streaming assistant\n // under its own generated id while the server persists under\n // `message.id`. The two then can't be reconciled by id, and the\n // originating tab briefly renders the turn twice — the live copy\n // plus the `CF_AGENT_CHAT_MESSAGES` broadcast — before\n // collapsing. Stamping the allocated id here makes the common\n // case behave like the provider-id case the client already\n // relies on (react.tsx records `start.messageId` to map the\n // local stream to the persisted message).\n const startData = data as {\n messageId?: unknown;\n [key: string]: unknown;\n };\n if (startData.messageId == null) {\n eventToSend = { ...startData, messageId: message.id };\n }\n }\n }\n if (data.type === \"finish\" && \"finishReason\" in data) {\n const { finishReason, ...rest } = data as {\n finishReason: string;\n [key: string]: unknown;\n };\n eventToSend = {\n ...rest,\n type: \"finish\",\n messageMetadata: { finishReason }\n };\n }\n\n // Store chunk for replay and broadcast to clients\n const chunkBody = JSON.stringify(eventToSend);\n await this._storeStreamChunk(streamId, chunkBody);\n this._broadcastChatMessage({\n body: chunkBody,\n done: false,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n ...(continuation && { continuation: true })\n });\n } catch (_error) {\n // Skip malformed JSON lines silently\n }\n }\n }\n }\n\n // If we exited due to abort, send a done signal so clients know the stream ended\n if (!streamCompleted.value) {\n this._completeStream(streamId);\n streamCompleted.value = true;\n this._broadcastChatMessage({\n body: \"\",\n done: true,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n ...(continuation && { continuation: true })\n });\n return { status: \"aborted\" };\n }\n\n return { status: \"completed\" };\n }\n\n // Handle plain text responses (e.g., from generateText)\n private async _sendPlaintextReply(\n id: string,\n streamId: string,\n reader: ReadableStreamDefaultReader<Uint8Array>,\n message: UIMessage,\n streamCompleted: { value: boolean },\n continuation = false,\n abortSignal?: AbortSignal\n ): Promise<StreamResultStatus> {\n // During continuation, if the last text part was still streaming\n // (interrupted mid-generation), reuse it so the resumed content\n // stays in the same block.\n let textPart: TextUIPart | undefined;\n if (continuation) {\n for (let k = message.parts.length - 1; k >= 0; k--) {\n const part = message.parts[k];\n if (part.type === \"text\") {\n if (\n \"state\" in part &&\n (part as { state: string }).state === \"streaming\"\n ) {\n textPart = part as TextUIPart;\n }\n break;\n }\n }\n }\n\n if (textPart) {\n // Skip broadcasting text-start — the client already has this part\n } else {\n // if not AI SDK SSE format, we need to inject text-start and text-end events ourselves\n await this._broadcastTextEvent(\n streamId,\n { type: \"text-start\", id },\n continuation\n );\n\n // Use a single text part and accumulate into it, so the persisted message\n // has one text part regardless of how many network chunks the response spans.\n textPart = { type: \"text\", text: \"\", state: \"streaming\" };\n message.parts.push(textPart);\n }\n\n // Cancel the reader when the abort signal fires\n if (abortSignal && !abortSignal.aborted) {\n abortSignal.addEventListener(\n \"abort\",\n () => {\n reader.cancel().catch(() => {});\n },\n { once: true }\n );\n }\n\n while (true) {\n if (abortSignal?.aborted) break;\n let readResult: ReadableStreamReadResult<Uint8Array>;\n try {\n readResult = await reader.read();\n } catch (readError) {\n if (abortSignal?.aborted) break;\n throw readError;\n }\n const { done, value } = readResult;\n if (done) {\n // reader.cancel() resolves read() with { done: true } — check abort\n if (abortSignal?.aborted) break;\n textPart.state = \"done\";\n\n await this._broadcastTextEvent(\n streamId,\n { type: \"text-end\", id },\n continuation\n );\n\n // Mark the stream as completed\n this._completeStream(streamId);\n streamCompleted.value = true;\n // Send final completion signal\n this._broadcastChatMessage({\n body: \"\",\n done: true,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n ...(continuation && { continuation: true })\n });\n return { status: \"completed\" };\n }\n\n const chunk = decoder.decode(value);\n\n // Accumulate into the single text part to preserve exact formatting\n if (chunk.length > 0) {\n textPart.text += chunk;\n await this._broadcastTextEvent(\n streamId,\n { type: \"text-delta\", id, delta: chunk },\n continuation\n );\n }\n }\n\n // If we exited due to abort, send a done signal so clients know the stream ended\n if (!streamCompleted.value) {\n textPart.state = \"done\";\n await this._broadcastTextEvent(\n streamId,\n { type: \"text-end\", id },\n continuation\n );\n this._completeStream(streamId);\n streamCompleted.value = true;\n this._broadcastChatMessage({\n body: \"\",\n done: true,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n ...(continuation && { continuation: true })\n });\n return { status: \"aborted\" };\n }\n\n return { status: \"completed\" };\n }\n\n /**\n * Applies a tool approval response from the client, updating the persisted message.\n * This is called when the client sends CF_AGENT_TOOL_APPROVAL for tools with needsApproval.\n *\n * - approved=true transitions to approval-responded\n * - approved=false transitions to output-denied so convertToModelMessages\n * emits a tool_result for providers (e.g. Anthropic) that require it.\n *\n * @param toolCallId - The tool call ID this approval is for\n * @param approved - Whether the tool execution was approved\n * @returns true if the approval was applied, false if the message was not found\n */\n private async _applyToolApproval(\n toolCallId: string,\n approved: boolean\n ): Promise<boolean> {\n // Use the shared `agents/chat` builder so the approval merge — including\n // the fallback that synthesizes `approval.id` from `toolCallId` when an\n // older / hand-seeded transcript lacks one — stays identical to Think.\n // convertToModelMessages needs `approval.id` to produce a valid\n // tool-approval-request content part with `approvalId`.\n const update = toolApprovalUpdate(toolCallId, approved);\n return this._findAndUpdateToolPart(\n toolCallId,\n \"_applyToolApproval\",\n update.matchStates,\n update.apply\n );\n }\n\n private async _reply(\n id: string,\n response: Response,\n excludeBroadcastIds: string[] = [],\n options: { continuation?: boolean; chatMessageId?: string } = {}\n ): Promise<StreamResultStatus> {\n const { continuation = false, chatMessageId } = options;\n // Look up the abort signal for this request so we can cancel the reader\n // loop if the client sends a cancel message. This is a safety net —\n // users should also pass abortSignal to streamText for proper cancellation.\n const abortSignal = chatMessageId\n ? this._abortRegistry.getExistingSignal(chatMessageId)\n : undefined;\n\n // Keep the DO alive during streaming to prevent idle eviction\n return this.keepAliveWhile(() =>\n this._tryCatchChat(async () => {\n if (!response.body) {\n // Send empty response if no body\n this._clearPendingAutoContinuation(true);\n this._broadcastChatMessage({\n body: \"\",\n done: true,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n ...(continuation && { continuation: true })\n });\n this._activateDeferredAutoContinuation();\n return { status: \"completed\" };\n }\n\n // Parsing state adapted from:\n // https://github.com/vercel/ai/blob/main/packages/ai/src/ui-message-stream/ui-message-chunks.ts#L295\n const message = this._createStreamingAssistantMessage(continuation);\n\n // Start tracking this stream for resumability. The allocated message id\n // is persisted in stream metadata so orphan recovery (#1691) can\n // re-associate reconstructed chunks with the right assistant message —\n // even when the provider stream carries no `start.messageId`. For a\n // continuation this is the cloned last-assistant id, so recovery merges\n // into it; for a new turn it is a fresh id, so recovery keeps it\n // distinct.\n // The continuation flag is persisted in stream metadata so replayed\n // frames carry `continuation: true` exactly like the live broadcast\n // frames below (#1733) — a reconnecting client needs it to append to\n // the existing assistant message instead of rebuilding it from\n // scratch and dropping the pre-continuation parts.\n const streamId = this._startStream(id, {\n messageId: message.id,\n continuation\n });\n\n const reader = response.body.getReader();\n\n // Track the streaming message so tool results can be applied before persistence\n this._streamingMessage = message;\n\n // Determine response format based on content-type\n const contentType = response.headers.get(\"content-type\") || \"\";\n const isSSE = contentType.includes(\"text/event-stream\"); // AI SDK v5 SSE format\n const streamCompleted = { value: false };\n let streamResult: StreamResultStatus = { status: \"completed\" };\n // Capture before try so it's available after finally.\n // _approvalPersistedMessageId is set inside _streamSSEReply when a\n // tool enters approval-requested state and the message is persisted early.\n let earlyPersistedId: string | null = null;\n // Set when a stall watchdog abort was routed into bounded recovery\n // (#1626): the orphan partial was already persisted and a continuation\n // (or terminal exhaustion) now owns the turn, so the post-stream\n // persistence + the success `message:response` emit below are skipped.\n let stallRouted = false;\n\n // Stream-active gate for the auto-continuation barrier (#1650): while\n // this assistant turn is streaming the parallel tool batch can still\n // grow, so no completeness check is meaningful. The gate clears only in\n // the outer `finally` below — AFTER the streamed message (with all its\n // tool parts) is persisted to `this.messages` — so the re-armed barrier\n // check sees the fully-materialized batch.\n this._streamingTurnActive = true;\n try {\n try {\n if (isSSE) {\n // AI SDK v5 SSE format\n streamResult = await this._streamSSEReply(\n id,\n streamId,\n reader,\n message,\n streamCompleted,\n continuation,\n abortSignal\n );\n } else {\n streamResult = await this._sendPlaintextReply(\n id,\n streamId,\n reader,\n message,\n streamCompleted,\n continuation,\n abortSignal\n );\n }\n } catch (error) {\n // A stall watchdog abort (#1626) is a recoverable interruption, not a\n // terminal error. Persist the settled partial (so the continuation\n // re-anchors without re-running completed tool calls, and the user\n // keeps generated content), then route into bounded recovery.\n if (\n error instanceof ChatStreamStalledError &&\n !streamCompleted.value\n ) {\n // The partial generated so far lives on the in-memory `message`; the\n // unconditional post-stream persistence block below writes it under\n // `message.id` (the same path a normal turn uses), so the scheduled\n // continuation re-anchors onto it via `targetAssistantId`. (Unlike a\n // cold deploy recovery, there is no need to reconstruct from stored\n // chunks here — the live `message` is authoritative.)\n const targetAssistantId =\n message.parts.length > 0 ? message.id : undefined;\n const outcome = await this._routeStallToBoundedRecovery({\n requestId: id,\n streamId,\n partialParts: message.parts,\n targetAssistantId\n });\n if (outcome === \"scheduled\") {\n // Recovering: close the stream cleanly (no terminal error frame);\n // the scheduled continuation drives the turn to completion. Report\n // `aborted` so this attempt does not terminalize the turn.\n this._completeStream(streamId);\n this._broadcastChatMessage({\n body: \"\",\n done: true,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n ...(continuation && { continuation: true })\n });\n streamResult = { status: \"aborted\" };\n streamCompleted.value = true;\n stallRouted = true;\n } else if (outcome === \"exhausted\") {\n // `_routeStallToBoundedRecovery` already delivered terminal UX\n // (terminalMessage + done/error frame + onExhausted), identical to\n // deploy-recovery exhaustion. Finalize the resumable stream and\n // report `aborted` so the generic terminal path is not re-run.\n this._markStreamError(streamId);\n streamResult = { status: \"aborted\" };\n streamCompleted.value = true;\n stallRouted = true;\n }\n }\n if (!stallRouted) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n streamResult = { status: \"error\", error: errorMessage };\n // Mark stream as error if not already completed\n if (!streamCompleted.value) {\n this._markStreamError(streamId);\n // Notify clients of the error\n this._broadcastChatMessage({\n body: errorMessage,\n done: true,\n error: true,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n ...(continuation && { continuation: true })\n });\n this._emit(\"message:error\", { error: errorMessage });\n streamCompleted.value = true;\n }\n }\n } finally {\n reader.releaseLock();\n\n // Always clear the streaming message reference, even on error.\n this._streamingMessage = null;\n // Capture and clear early-persist tracking. The persistence block\n // after the finally uses the local to update in place.\n earlyPersistedId = this._approvalPersistedMessageId;\n this._approvalPersistedMessageId = null;\n\n // Framework-level cleanup: always remove abort controller.\n // Only emit observability on success (not on error path).\n if (chatMessageId) {\n this._abortRegistry.remove(chatMessageId);\n if (\n streamCompleted.value &&\n streamResult.status !== \"error\" &&\n !stallRouted\n ) {\n this._emit(\"message:response\");\n }\n }\n }\n\n if (message.parts.length > 0) {\n if (earlyPersistedId) {\n // Message already exists in this.messages from the early persist.\n // Update it in place with the final streaming state.\n const persistedMessage: UIMessage = {\n ...message,\n id: earlyPersistedId\n };\n const existingIdx = this.messages.findIndex(\n (msg) => msg.id === earlyPersistedId\n );\n const updatedMessages = [...this.messages];\n\n if (existingIdx >= 0) {\n updatedMessages[existingIdx] = persistedMessage;\n } else {\n updatedMessages.push(persistedMessage);\n }\n\n await this.persistMessages(updatedMessages, excludeBroadcastIds);\n } else if (continuation) {\n const existingIdx = this.messages.findIndex(\n (msg) => msg.id === message.id\n );\n if (existingIdx >= 0) {\n const updatedMessages = [...this.messages];\n updatedMessages[existingIdx] = message;\n await this.persistMessages(\n updatedMessages,\n excludeBroadcastIds\n );\n } else {\n // No assistant message to append to, create new one\n await this.persistMessages(\n [...this.messages, message],\n excludeBroadcastIds\n );\n }\n } else {\n await this.persistMessages(\n [...this.messages, message],\n excludeBroadcastIds\n );\n }\n }\n\n this._pendingChatResponseResults.push({\n message,\n requestId: id,\n continuation,\n status: streamResult.status,\n ...(streamResult.error !== undefined && {\n error: streamResult.error\n })\n });\n return streamResult;\n } finally {\n // The streamed assistant message (with all tool parts) is now\n // persisted: clear the stream-active gate and re-run the\n // auto-continuation barrier for a continuation it held (#1650). This\n // package-local hook is the SSE-loop equivalent of Think's\n // `_onStreamingTurnFinalized` in its `toUIMessageStream()` loop.\n // TODO(phase-5): the Tier-2 streaming-codec extraction touches this\n // same region — fold this finalize hook into the extracted codec\n // rather than leaving a second seam here.\n this._onStreamingTurnFinalized();\n }\n })\n );\n }\n\n /**\n * When the DO is destroyed, cancel all pending requests and clean up resources\n */\n async destroy() {\n this._abortRegistry.destroyAll();\n this._resumableStream.destroy();\n await super.destroy();\n }\n}\n"],"mappings":";;;;;;AAoKA,SAAS,cACP,MACA,WACA,cACA,YACA,KACgB;CACh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AAG;MACH,IAAI;KACN;KACA,MAAM,cAAc,KAAK,SAAS,WAC/B,QAAQ,IAAI,OAAO,gBACtB;KACA,MAAM,kBAAkB,CAAC,GAAG,KAAK,QAAQ;KAEzC,IAAI,eAAe,GACjB,gBAAgB,eAAe;UAE/B,gBAAgB,KAAK,gBAAgB;KAGvC,MAAM,KAAK,gBAAgB,iBAAiB,mBAAmB;IACjE,OAAO,IAAI,cAAc;KACvB,MAAM,cAAc,KAAK,SAAS,WAC/B,QAAQ,IAAI,OAAO,QAAQ,EAC9B;KACA,IAAI,eAAe,GAAG;MACpB,MAAM,kBAAkB,CAAC,GAAG,KAAK,QAAQ;MACzC,gBAAgB,eAAe;MAC/B,MAAM,KAAK,gBACT,iBACA,mBACF;KACF,OAEE,MAAM,KAAK,gBACT,CAAC,GAAG,KAAK,UAAU,OAAO,GAC1B,mBACF;IAEJ,OACE,MAAM,KAAK,gBACT,CAAC,GAAG,KAAK,UAAU,OAAO,GAC1B,mBACF;IAIJ,KAAK,4BAA4B,KAAK;KACpC;KACA,WAAW;KACX;KACA,QAAQ,aAAa;KACrB,GAAI,aAAa,UAAU,KAAA,KAAa,EACtC,OAAO,aAAa,MACtB;IACF,CAAC;IACD,OAAO;GACT,UAAU;IASR,KAAK,0BAA0B;GACjC;EACF,CAAC,CACH;CACF;;;;CAKA,MAAM,UAAU;EACd,KAAK,eAAe,WAAW;EAC/B,KAAK,iBAAiB,QAAQ;EAC9B,MAAM,MAAM,QAAQ;CACtB;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["#session","agentContext","#subscribeToSessionChanges","#streamMessagesAsJson","#messageForCache","withInvocationScope","#pendingCutover"],"sources":["../src/index.ts"],"sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type {\n UIMessage,\n GenerateTextOnFinishCallback,\n TextUIPart,\n ToolSet,\n UIMessageChunk\n} from \"ai\";\nimport {\n Agent,\n isDurableObjectMemoryLimitReset,\n isPlatformTransientError,\n __DO_NOT_USE_WILL_BREAK__agentContext as agentContext,\n __DO_NOT_USE_WILL_BREAK__withInvocationScope as withInvocationScope,\n type AgentToolEventDelivery,\n type AgentToolLifecycleResult,\n type AgentToolMilestone,\n type AgentToolProgress,\n type AgentToolProgressSnapshot,\n type AgentToolRunInfo,\n type AgentToolRunInspection,\n type AgentToolStoredChunk,\n type AgentContext,\n type Connection,\n type ConnectionContext,\n type FiberRecoveryContext,\n type WSMessage\n} from \"agents\";\n\nimport { MessageType, type OutgoingMessage } from \"./types\";\nimport { autoTransformMessages } from \"./ai-chat-v5-migration\";\nimport {\n reconcileMessages,\n reconcileOrphanPartial,\n repairInterruptedToolParts,\n persistReconstructedOrphan,\n createChatFiberSnapshot,\n unwrapChatFiberSnapshot,\n wrapChatFiberSnapshot,\n type OrphanPersistStore\n} from \"agents/chat\";\nimport {\n applyChunkToParts,\n applyLateToolInput,\n lateToolInputForwardChunks,\n AgentToolProgressEmitter,\n aiSdkRecoveryCodec,\n ResumeHandshake,\n isReplayChunk,\n parseProtocolMessage,\n sendIfOpen,\n TurnQueue,\n SubmitConcurrencyController,\n hasIncompleteToolBatch,\n partAwaitsClientInteraction,\n clientResolvableToolNames,\n toolApprovalUpdate,\n type TurnResult,\n type MessagePart,\n type StreamChunkData,\n type SubmitConcurrencyDecision,\n type ChatFiberSnapshot,\n type ChatTurnOutcome\n} from \"agents/chat\";\nimport { ResumableStream, createChatStreams } from \"agents/chat\";\nimport type { Streams } from \"agents/streams\";\nimport { Sessions, type Session, type SessionMessage } from \"agents/sessions\";\nimport {\n CHAT_RECOVERY_TASK_NAME,\n chatRecoveryTaskRunOptions,\n createChatRecoveryTaskDefinition,\n createChatTurnTaskDefinition,\n dispatchChatRecoveryToHandoff,\n type ChatRecoveryTaskReason\n} from \"agents/chat\";\nimport { CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS } from \"agents/chat\";\nimport {\n ContinuationState,\n PreStreamTurns,\n AutoContinuationController,\n AbortRegistry,\n TIMED_OUT,\n awaitWithDeadline,\n drainInteractionApplies,\n interceptAgentToolBroadcast,\n isPositionlessAgentToolChunk,\n type ClientToolSchema\n} from \"agents/chat\";\nimport {\n resolveChatRecoveryConfig,\n ChatRecoveryEngine,\n runChatRecoveryExhaustion,\n ChatStreamStalledError,\n iterateWithStallWatchdog,\n sweepStaleChatRecoveryIncidents,\n listActiveChatRecoveryIncidents,\n classifyAgentToolChildRecovery,\n readChatRecoveryProgress,\n CHAT_RECOVERY_PROGRESS_KEY,\n recordChatTerminal,\n clearChatTerminal,\n pendingChatTerminal,\n originMessageIds,\n withOriginMessageIds,\n buildChatRecoveringFrame,\n setChatRecovering,\n AgentToolStreamProgressThrottle,\n chatRecoveryBackoffSeconds,\n isDurableObjectResetError,\n partialHasSettledToolResults,\n type ChatRecoveryAdapter,\n type ChatFiberWakeHooks,\n type ResolvedRecoveryStream,\n type ClassifyRecoveredTurnInput,\n type DispatchRecoveredTurnInput,\n type ChatRecoveryScheduleCallback,\n type ChatRecoveryIncident,\n type ChatRecoveryKind\n} from \"agents/chat\";\nimport type {\n ChatResponseResult,\n ChatRecoveryConfig,\n ChatRecoveryContext,\n ChatRecoveryOptions,\n MessageConcurrency,\n ResolvedChatRecoveryConfig,\n SaveMessagesOptions,\n SaveMessagesResult\n} from \"agents/chat\";\nimport { nanoid } from \"nanoid\";\n\n// Re-export lifecycle types from the shared chat toolkit so existing\n// consumers (`import type { ChatResponseResult } from \"@cloudflare/ai-chat\"`)\n// continue to work.\nexport type {\n ChatResponseResult,\n ChatRecoveryConfig,\n ChatRecoveryContext,\n ChatRecoveryExhaustedContext,\n ChatRecoveryProgressContext,\n ChatRecoveryOptions,\n MessageConcurrency,\n ResolvedChatRecoveryConfig,\n SaveMessagesOptions,\n SaveMessagesResult\n} from \"agents/chat\";\n\ntype AgentSpanAttributes = Readonly<\n Record<string, string | number | boolean | undefined>\n>;\n\ntype UpdateAgentSpan = (attributes: AgentSpanAttributes) => void;\n\ntype AgentSpanHost = {\n _withAgentSpan<T>(\n operation: string,\n storagePhase: string,\n attributes: AgentSpanAttributes,\n run: (update: UpdateAgentSpan) => T | Promise<T>\n ): T | Promise<T>;\n};\n\nfunction withAgentSpan<T>(\n host: object,\n operation: string,\n storagePhase: string,\n attributes: AgentSpanAttributes,\n run: (update: UpdateAgentSpan) => Promise<T>\n): Promise<T>;\nfunction withAgentSpan<T>(\n host: object,\n operation: string,\n storagePhase: string,\n attributes: AgentSpanAttributes,\n run: (update: UpdateAgentSpan) => T\n): T;\nfunction withAgentSpan<T>(\n host: object,\n operation: string,\n storagePhase: string,\n attributes: AgentSpanAttributes,\n run: (update: UpdateAgentSpan) => T | Promise<T>\n): T | Promise<T> {\n return (host as AgentSpanHost)._withAgentSpan(\n operation,\n storagePhase,\n attributes,\n run\n );\n}\n\ntype ChatRecoveryRetryData = {\n targetUserId?: string;\n originalRequestId?: string;\n originMessageIds?: string[];\n incidentId?: string;\n lastBody?: Record<string, unknown> | null;\n lastClientTools?: ClientToolSchema[] | null;\n};\n\ntype ChatRecoveryContinueData = {\n targetAssistantId?: string;\n originalRequestId?: string;\n originMessageIds?: string[];\n incidentId?: string;\n lastBody?: Record<string, unknown> | null;\n lastClientTools?: ClientToolSchema[] | null;\n};\n\n/**\n * `AIChatAgent`'s `classifyRecoveredTurn` detail (the {@link ChatFiberWakeHooks}\n * generic). `shouldRetryPreStream` is the only classification bit the dispatch\n * decision needs that it cannot cheaply recompute post-persist; the lost-partial\n * branch is re-derived in `_dispatchRecoveredChatTurn` from the (now-updated) leaf.\n */\ntype AIChatRecoveryClassification = { shouldRetryPreStream: boolean };\n\n// `ChatRecoveryIncident` / `ChatRecoveryKind` / `CHAT_RECOVERY_INCIDENT_KEY_PREFIX`\n// are the canonical shared symbols from `agents/chat` (imported above); the\n// persisted incident shape and key prefix are owned by the engine package so\n// both consumers round-trip the same record across the deploy that ships them.\n\n// The monotonic forward-progress marker the recovery budget keys off is\n// derived from the stream log (`ResumableStream.progressMarker`): durably\n// flushed segments, folded into a retired total as their rows are deleted.\n// Nothing is written per chunk. The pre-derivation KV counter\n// (`CHAT_RECOVERY_PROGRESS_KEY`) is read once per isolate and seeded into the\n// marker, so it is never read lower than an in-flight incident recorded.\n// Recovery budget defaults (maxAttempts, maxRecoveryWork, stableTimeoutMs,\n// terminalMessage, noProgressTimeoutMs, alarm debounce) now live in the shared\n// incident engine (agents/chat) and are applied by `resolveChatRecoveryConfig`\n// / `evaluateChatRecoveryIncident`. See design/rfc-chat-recovery-foundation.md.\n// Auto-continuation barrier (#1649/#1650): when the model emits parallel tool\n// calls, the client answers each one independently and sends a tool result with\n// `autoContinue` per result. A fast tool's result must NOT trigger inference\n// while a slower sibling is still `input-available` — that feeds the provider\n// an incomplete tool-result set. The barrier is event-driven (converged onto\n// `@cloudflare/think`'s model): we only fire the continuation once the leaf\n// step's batch is fully answered, re-arming on each applied result and on stream\n// finalize, with NO orphan timeout — an incomplete batch simply never\n// auto-continues until it completes (a later user turn / chat recovery repairs\n// the transcript). See design/rfc-chat-recovery-foundation.md.\n// (Stable-state retry delay `CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS` now lives\n// in agents/chat; the reschedule that consumes it is owned by the shared engine.\n// The recovering-flag key/TTL and the terminal-record key now live in agents/chat\n// too — the durable recovery UX is driven via the shared `setChatRecovering` /\n// `buildChatRecoveringFrame` / `recordChatTerminal` helpers — and the incident\n// sweep via the shared `sweepStaleChatRecoveryIncidents` helper.)\n// (N9 throttle now lives in the shared engine as `AgentToolStreamProgressThrottle`\n// / `AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS`; the stream-cleanup delay and\n// The `sendIfOpen` / `isWebSocketClosedSendError` WS send\n// guard is shared via agents/chat.)\n\ntype StreamResultStatus = {\n status: Exclude<SaveMessagesResult[\"status\"], \"skipped\">;\n error?: string;\n finishReason?: string;\n};\n\nexport type ChatMessage = UIMessage;\n\n/**\n * Provider-executed tool fields that contain opaque replay tokens and must be\n * persisted exactly as returned by the provider.\n */\nconst PROVIDER_TOOL_OPAQUE_STRING_KEY_PREFIX = \"encrypted\";\n\n/**\n * Max string length preserved in `input`/`output` of provider-executed tool\n * parts (e.g. Anthropic code_execution / text_editor). Strings exceeding this\n * limit are truncated with a marker so persisted messages stay small.\n */\nconst PROVIDER_TOOL_MAX_STRING_LENGTH = 500;\n\n/**\n * Whether a response-reader error is a platform transient that bounded chat\n * recovery can retry. A deploy or storage reset is excluded: the isolate is\n * going away, and the restart's own recovery owns the turn.\n */\nfunction isRecoverableStreamReadError(error: unknown): boolean {\n return isPlatformTransientError(error) && !isDurableObjectResetError(error);\n}\n\n/** A live stream interruption (stall or transient error) to route to recovery. */\ntype StreamInterruptionRoute = {\n requestId: string;\n streamId: string;\n partialParts: MessagePart[];\n targetAssistantId?: string;\n continuation: boolean;\n /** Delay the recovery with exponential backoff (transient errors). */\n backoff?: boolean;\n /** Skip persisting the partial (`onChatRecovery` returned `persist: false`). */\n discardPartial: () => Promise<void>;\n};\n\n/**\n * Validates that a parsed message has the minimum required structure.\n * Returns false for messages that would cause runtime errors downstream\n * (e.g. in convertToModelMessages or the UI layer).\n *\n * Checks:\n * - `id` is a non-empty string\n * - `role` is one of the valid roles\n * - `parts` is an array (may be empty — the AI SDK enforces nonempty\n * on incoming messages, but we are lenient on persisted data)\n */\nfunction isValidMessageStructure(msg: unknown): msg is UIMessage {\n if (typeof msg !== \"object\" || msg === null) return false;\n const m = msg as Record<string, unknown>;\n\n if (typeof m.id !== \"string\" || m.id.length === 0) return false;\n\n if (m.role !== \"user\" && m.role !== \"assistant\" && m.role !== \"system\") {\n return false;\n }\n\n if (!Array.isArray(m.parts)) return false;\n\n return true;\n}\n\n/**\n * Schema for a client-defined tool sent from the browser.\n * These tools are executed on the client, not the server.\n *\n * **For most apps**, define tools on the server with `tool()` from `\"ai\"` —\n * you get schema-derived type safety, server-side execution, and simpler code.\n * Use `onToolCall` in `useAgentChat` for tools that need client-side execution.\n *\n * **For SDKs and platforms** where the tool surface is determined dynamically\n * by the embedding application at runtime, client tool schemas let the\n * client register tools the server does not know about at deploy time.\n *\n * Note: Uses `parameters` (JSONSchema7) rather than AI SDK's `inputSchema`\n * because this is the wire format. Runtime validation schemas cannot be\n * serialized.\n */\nexport type { ClientToolSchema } from \"agents/chat\";\n\ntype ChatRequestTrigger = \"submit-message\" | \"regenerate-message\";\ntype AIChatAgentToolRunStatus = \"running\" | \"completed\" | \"error\" | \"aborted\";\ntype AIChatAgentToolRunRow = {\n run_id: string;\n request_id: string | null;\n status: AIChatAgentToolRunStatus;\n input_json: string | null;\n output_json: string | null;\n summary: string | null;\n error_message: string | null;\n started_at: number;\n completed_at: number | null;\n progress_json?: string | null;\n last_signal_at?: number | null;\n};\n/**\n * Options passed to the onChatMessage handler.\n */\nexport type OnChatMessageOptions = {\n /**\n * Unique ID for this chat message exchange.\n *\n * For initial user messages this is the client-generated ID from the\n * `CF_AGENT_USE_CHAT_REQUEST` WebSocket frame. For tool continuations\n * (auto-continue after client tool results or approvals) this is a\n * server-generated ID.\n */\n requestId: string;\n /** AbortSignal for cancelling the request */\n abortSignal?: AbortSignal;\n /**\n * Tool schemas sent from the client for dynamic tool registration.\n * These represent tools that will be executed on the client side.\n * Use `createToolsFromClientSchemas()` to convert these to AI SDK tool format.\n *\n * **For most apps**, you do not need this — define tools on the server with\n * `tool()` from `\"ai\"` and use `onToolCall` for client-side execution.\n *\n * **For SDKs and platforms** where tools are defined dynamically by the\n * client at runtime and the server does not know the tool surface ahead\n * of time, this field carries the client-provided tool schemas.\n */\n clientTools?: ClientToolSchema[];\n /**\n * Custom body data sent from the client via `prepareSendMessagesRequest`\n * or the AI SDK's `body` option in `sendMessage`.\n *\n * Contains all fields from the request body except `messages` and `clientTools`,\n * which are handled separately.\n *\n * During tool continuations (auto-continue after client tool results), this\n * contains the body from the most recent chat request. The value is persisted\n * to SQLite so it survives Durable Object hibernation. It is cleared when the\n * chat is cleared via `CF_AGENT_CHAT_CLEAR`.\n */\n body?: Record<string, unknown>;\n /**\n * Whether this turn is a continuation of a previous assistant message\n * (auto-continue after tool result, `continueLastTurn`, or recovery).\n *\n * Use this to adjust system prompts, select different models, skip\n * expensive context assembly, or log differently for continuations.\n */\n continuation?: boolean;\n};\n\nexport { createToolsFromClientSchemas } from \"agents/chat\";\n\nconst decoder = new TextDecoder();\nconst agentToolChunkEncoder = new TextEncoder();\n\n/**\n * Extension of Agent with built-in chat capabilities\n * @template Env Environment type containing bindings\n */\n/** Bounds for one window of the legacy lift: rows and their summed bytes. */\nconst LEGACY_LIFT_WINDOW_ROWS = 25;\nconst LEGACY_LIFT_WINDOW_BYTES = 4 * 1024 * 1024;\n\nexport class AIChatAgent<\n Env extends Cloudflare.Env = Cloudflare.Env,\n State = unknown,\n Props extends object = object\n> extends Agent<Env, State, Props> {\n private _activeChatRecoveryRootRequestId: string | undefined;\n /**\n * The originating user message ids of the active recovery chain (#2280),\n * carried in the recovery payload because the successor turn runs under a\n * fresh request id. Scoped to the recovery callback's async context, so a\n * concurrent client request never inherits them.\n */\n private _chatRecoveryOriginIdsScope = new AsyncLocalStorage<\n string[] | undefined\n >();\n\n private get _activeChatRecoveryOriginIds(): string[] | undefined {\n return this._chatRecoveryOriginIdsScope.getStore();\n }\n\n /**\n * Registry of per-request AbortControllers.\n * Used to propagate cancellation signals for any external calls made by the agent.\n */\n private _abortRegistry: AbortRegistry;\n\n /** Durable chat history for this Agent. */\n readonly sessions = new Sessions();\n\n /**\n * Byte budget for wake-time transcript hydration into {@link messages}.\n *\n * `onStart` hydrates through `session.getRecentHistory(budget, …)`. The\n * budget counts each stored row plus the continuation rows it was split\n * across, so it bounds isolate memory: an oversized transcript hydrates\n * as a bounded recent window\n * instead of exhausting the isolate. Durable storage is never truncated by\n * this — `sessions.session().getHistory()` still reads the full path, and\n * the streamed `get-messages` route still serves every message.\n *\n * Set to `Number.POSITIVE_INFINITY` (or any non-positive value) to disable\n * windowing and always hydrate the whole transcript.\n *\n * @default 32 * 1024 * 1024\n */\n hydrationByteBudget: number = 32 * 1024 * 1024;\n\n /** The default linear conversation handle. */\n readonly #session: Session = this.sessions.session();\n\n /**\n * The Streams capability backing `_resumableStream`: chat's in-flight\n * output lives in the shared durable chunk log, readable by any\n * `streams.read()` consumer on this Durable Object.\n */\n readonly streams: Streams = createChatStreams();\n\n /**\n * Resumable stream manager -- handles chunk buffering, persistence, and replay.\n * @internal Protected for testing purposes.\n */\n protected _resumableStream!: ResumableStream;\n\n /**\n * The message currently being streamed. Used to apply tool results\n * before the message is persisted.\n * @internal\n */\n private _streamingMessage: UIMessage | null = null;\n\n /**\n * Queued by `_reply` so the hook can fire after the turn lock releases.\n * Uses an array to avoid losing results when multiple turns complete\n * during a single `onChatResponse` call.\n * @internal\n */\n private _pendingChatResponseResults: ChatResponseResult[] = [];\n\n /**\n * Re-entrancy guard: true while `onChatResponse` is executing.\n * Prevents recursive hook calls when the hook triggers `saveMessages`.\n * @internal\n */\n private _insideResponseHook = false;\n\n /**\n * Resolves when the current pending client-tool interaction (tool result or\n * approval) has been written to state. Set when an apply promise is created,\n * cleared when it settles. Used by waitUntilStable to avoid polling.\n */\n private _pendingInteractionPromise: Promise<boolean> | null = null;\n\n /**\n * Serialization tail for client-tool result/approval applies (#1649). Each\n * apply is a read-modify-write of the full message; running siblings from a\n * parallel tool batch concurrently lets last-write-wins clobber the others\n * back to `input-available`. Chaining every apply off this tail makes them\n * commit atomically in arrival order.\n */\n private _interactionApplyTail: Promise<void> = Promise.resolve();\n\n /**\n * Tracks the ID of a streaming message that was persisted early due to\n * a tool entering approval-requested state. When set, stream completion\n * updates the existing persisted message instead of appending a new one.\n * @internal\n */\n private _approvalPersistedMessageId: string | null = null;\n\n /**\n * Serial queue for chat turns. Handles promise-chain serialization,\n * generation-based invalidation on clear, and active-request tracking.\n */\n private _turnQueue = new TurnQueue();\n\n /**\n * Durable chat recovery configuration. Every chat turn runs in `runFiber`,\n * enabling `onChatRecovery` and `this.stash()` during streaming. Assign an\n * object to tune recovery budgets and terminal behavior.\n *\n * Assign this as a class field or in the constructor — NOT in `onStart()`.\n * On every wake the SDK evaluates recovery budgets (and may seal an\n * interrupted turn, firing `onExhausted`) before `onStart()` runs, so a config\n * set in `onStart()` is applied too late and the built-in defaults are used\n * for the recovery that matters. See {@link ChatRecoveryConfig}.\n */\n chatRecovery: ChatRecoveryConfig = true;\n\n /**\n * Inactivity watchdog for the live model/transport stream, in milliseconds.\n * If more than this many ms elapse between stream chunks, the turn is aborted\n * and routed into bounded recovery (the same continuation machinery as a\n * deploy or eviction interruption, #1626) rather than parking forever on a\n * hung provider.\n *\n * Default `0` disables the watchdog (opt-in), matching `@cloudflare/think`.\n * A value such as `60_000` (60s) is a reasonable starting point; tune it\n * above your slowest legitimate inter-chunk gap (slow reasoning models, long\n * tool calls) to avoid aborting healthy turns. Because the watchdog measures\n * the gap between chunks — not total turn duration — a steadily streaming\n * turn never trips it regardless of overall length.\n *\n * Assign as a class field or in the constructor, like {@link chatRecovery}.\n */\n chatStreamStallTimeoutMs = 0;\n\n /** First queued overlap message index for merge strategy, keyed by epoch. */\n private _mergeQueuedUserStartIndexByEpoch = new Map<number, number>();\n\n /** Shared admission policy state for overlapping submit-message requests. */\n private _submitConcurrency = new SubmitConcurrencyController({\n defaultDebounceMs: AIChatAgent.MESSAGE_DEBOUNCE_MS\n });\n\n /**\n * Set of connection IDs that are pending stream resume.\n * These connections have received CF_AGENT_STREAM_RESUMING but haven't sent ACK yet.\n * They should be excluded from live stream broadcasts until they ACK.\n * @internal\n */\n private _pendingResumeConnections: Set<string> = new Set();\n\n /** Lazily-built shared resume-handshake driver (Tier-2). */\n private _resumeHandshakeInstance: ResumeHandshake | null = null;\n\n /**\n * Continuation lifecycle state: pending, deferred, active, and\n * connections awaiting a continuation stream to start.\n */\n private _continuation = new ContinuationState<Connection>();\n\n /**\n * Accepted-but-not-yet-streamed turns and the connections parked waiting for\n * one (#1784). Lets a client that reconnects/re-mounts during a turn's\n * pre-stream window (queue, MCP wait, model latency) keep waiting instead of\n * giving up — see the {@link ResumeHandshake} `preStream` seam.\n *\n * HIBERNATION INVARIANT: this is in-memory only and is NOT persisted. It is\n * safe precisely because the pre-stream window cannot overlap hibernation: a\n * turn between `begin()` and `_startStream()` is an unresolved `onMessage`\n * handler promise (queue/debounce/MCP/model awaits) that pins the DO in\n * memory, so the DO is only evicted once the turn either recorded a durable\n * stream (resumed via `ResumableStream` on wake) or finished. This breaks if a\n * pre-stream wait is ever moved onto a durable alarm that releases the DO; if\n * that changes, this state must become durable.\n */\n private _preStream = new PreStreamTurns<Connection>();\n private _agentToolForwarders = new Map<\n string,\n Set<(chunk: AgentToolStoredChunk) => void>\n >();\n private _agentToolClosers = new Map<string, Set<() => void>>();\n private _agentToolAbortControllers = new Map<string, AbortController>();\n private _agentToolLastErrors = new Map<string, string>();\n private _agentToolPreTurnAssistantIds = new Map<string, Set<string>>();\n private _agentToolLiveSequences = new Map<string, number>();\n /** Runs started with `eventDelivery: \"terminal\"`: their chunks are not broadcast. */\n private _agentToolTerminalOnlyRuns = new Set<string>();\n /**\n * Request id → run id for in-flight agent-tool turns (null = resolved as\n * not an agent-tool turn, cached so unrelated turns don't re-query SQLite\n * per frame). Drives frame attribution in {@link broadcast}: a frame\n * belongs to a run iff it carries that run's turn request id, so an error\n * in a user-driven turn or a concurrent run can never leak into another\n * run's state (#1575).\n */\n private _agentToolRunsByRequestId = new Map<string, string | null>();\n\n /**\n * Client tool schemas from the most recent chat request.\n * Stored so they can be passed to onChatMessage during tool continuations.\n * @internal\n */\n protected _lastClientTools: ClientToolSchema[] | undefined;\n\n /**\n * Custom body data from the most recent chat request.\n * Stored so it can be passed to onChatMessage during tool continuations.\n * @internal\n */\n protected _lastBody: Record<string, unknown> | undefined;\n\n /**\n * Shared auto-continuation barrier (#1649 / #1650): owns the coalesce timer\n * and the double-fire guard. Parameterized by this agent's stream-active\n * signal, apply-drain, and continuation-turn pipeline (`_fireAutoContinuation`).\n */\n private _autoContinuation = new AutoContinuationController<Connection>({\n continuation: this._continuation,\n generateRequestId: () => nanoid(),\n isStreamActive: () => this._streamingTurnActive,\n hasPendingInteraction: () => this._pendingInteractionPromise !== null,\n hasIncompleteToolBatch: () => this._hasIncompleteToolBatch(),\n drainInteractionApplies: () => this._drainInteractionApplies(),\n keepAliveWhile: <T>(fn: () => Promise<T>) => this.keepAliveWhile(fn),\n fire: () => this._fireAutoContinuation()\n });\n\n /**\n * Stream-active gate for the auto-continuation barrier (#1650). True while an\n * assistant turn is streaming in `_reply`: the parallel tool batch can still\n * grow with tool calls the model hasn't emitted yet, so no completeness check\n * is meaningful until the stream finalizes. `_onStreamingTurnFinalized`\n * clears it and re-runs the barrier once the batch is fully materialized.\n */\n private _streamingTurnActive = false;\n\n /** Default wait for trailing-edge debounced overlapping submits. */\n private static MESSAGE_DEBOUNCE_MS = 750;\n\n /**\n * Maximum number of messages to keep in SQLite storage.\n * When the conversation exceeds this limit, oldest messages are deleted\n * after each persist. Set to `undefined` (default) for no limit.\n *\n * This controls storage only — it does not affect what's sent to the LLM.\n * Use `pruneMessages()` from the AI SDK in your `onChatMessage` to control\n * LLM context separately.\n *\n * @example\n * ```typescript\n * class MyAgent extends AIChatAgent<Env> {\n * maxPersistedMessages = 100; // Keep last 100 messages in storage\n * }\n * ```\n */\n maxPersistedMessages: number | undefined = undefined;\n\n /**\n * Controls how overlapping user submit requests behave while another chat\n * turn is already active or queued.\n *\n * - `\"queue\"` (default) — queue every submit and process them in order.\n * - `\"latest\"` — keep only the latest overlapping submit; superseded submits\n * still persist their user messages, but do not start their own model turn.\n * - `\"merge\"` — queue overlapping submits, then collapse their trailing user\n * messages into one combined user turn before the latest queued turn runs.\n * - `\"drop\"` — ignore overlapping submits entirely.\n * - `{ strategy: \"debounce\" }` — trailing-edge latest with a quiet window.\n *\n * This setting only applies to `sendMessage()` / `trigger: \"submit-message\"`\n * requests. Regenerations, tool continuations, approvals, clears, and\n * programmatic `saveMessages()` calls keep their existing serialized\n * behavior.\n */\n messageConcurrency: MessageConcurrency = \"queue\";\n\n /**\n * When enabled, waits for all MCP server connections to be ready before\n * calling `onChatMessage`. This prevents the race condition where\n * `getAITools()` returns an incomplete set because connections are still\n * restoring after Durable Object hibernation.\n *\n * - `false` (default) — non-blocking; `onChatMessage` runs immediately.\n * - `true` — waits indefinitely for all connections to settle.\n * - `{ timeout: number }` — waits up to `timeout` milliseconds.\n *\n * For lower-level control, call `this.mcp.waitForConnections()` directly\n * inside your `onChatMessage` instead.\n *\n * @example\n * ```typescript\n * class MyAgent extends AIChatAgent<Env> {\n * waitForMcpConnections = true;\n * }\n * ```\n *\n * @example\n * ```typescript\n * class MyAgent extends AIChatAgent<Env> {\n * waitForMcpConnections = { timeout: 10_000 };\n * }\n * ```\n */\n waitForMcpConnections: boolean | { timeout: number } = { timeout: 10_000 };\n\n /**\n * Live chat-turn closures keyed by run nonce. A closure exists only in the\n * isolate that accepted the turn; recovery after interruption never re-runs\n * it — the definition's `recover` callback hands the interruption to the\n * shared ChatRecoveryEngine instead.\n */\n private readonly _liveChatTurnClosures = new Map<\n string,\n {\n initial: unknown;\n wrap: (data: unknown) => unknown;\n run: () => Promise<unknown>;\n settle: {\n resolve: (value: unknown) => void;\n reject: (error: unknown) => void;\n };\n }\n >();\n\n /**\n * Register the shared chat-turn Task definition (see\n * `agents/chat` `createChatTurnTaskDefinition` for the turn logic): the\n * host wires its protected internals through the hooks.\n */\n private _registerChatTurnTaskDefinition(): void {\n const chatFiberName = (this.constructor as typeof AIChatAgent)\n .CHAT_FIBER_NAME;\n this.tasks.register(\n chatFiberName,\n createChatTurnTaskDefinition({\n definitionName: chatFiberName,\n storage: this.ctx.storage,\n getRunCreatedAt: async (runId) =>\n (await this.tasks.get(runId))?.createdAt ?? null,\n getLiveClosure: (nonce) => this._liveChatTurnClosures.get(nonce),\n keepAliveWhile: (fn) => this.keepAliveWhile(fn),\n withStash: (context, fn) => this._withFiberStash(context, fn),\n handleRecovery: (ctx) => this._handleInternalFiberRecovery(ctx)\n })\n );\n }\n\n /** Register the shared Tasks transport for recovery continuations. */\n private _registerChatRecoveryTaskDefinition(): void {\n // SAFETY: the recovery engine is the sole producer of each callback's\n // payload and the Task persists it verbatim, so the callback name selects\n // the matching host input type.\n this.tasks.register(\n CHAT_RECOVERY_TASK_NAME,\n createChatRecoveryTaskDefinition({\n _chatRecoveryContinue: (data) =>\n this._chatRecoveryContinue(data as ChatRecoveryContinueData),\n _chatRecoveryRetry: (data) =>\n this._chatRecoveryRetry(data as ChatRecoveryRetryData)\n })\n );\n }\n\n /**\n * Run a queue-driven recovery callback to its model handoff and return;\n * the turn continues as tracked alarm work, and a detached platform\n * failure enqueues one replacement attempt through the same transport.\n */\n private _dispatchChatRecovery(\n callback: ChatRecoveryScheduleCallback,\n data: Record<string, unknown> | undefined,\n detached: (onTurnStarted: () => void) => Promise<void>\n ): Promise<void> {\n return dispatchChatRecoveryToHandoff({\n detached,\n track: (turn) => this.lifecycle.trackAlarmWork(turn),\n redefer: (dedupeKey) =>\n this._enqueueChatRecovery(\n callback,\n data ?? {},\n \"redefer\",\n CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS,\n dedupeKey\n ),\n onDetachedError: (error) =>\n console.error(`[AIChatAgent] ${callback} dispatch failed`, error)\n });\n }\n\n /**\n * Enqueue one recovery attempt on the shared Tasks transport. Tasks\n * mirrors a routed dynamic agent's wake to the root's alarm; the run\n * itself, and this continuation's replay, still execute here. `dedupeKey`\n * keys a retried enqueue so it joins its own prior attempt instead of\n * duplicating it — see {@link chatRecoveryTaskRunOptions}.\n */\n private async _enqueueChatRecovery(\n callback: ChatRecoveryScheduleCallback,\n data: Record<string, unknown>,\n reason: ChatRecoveryTaskReason,\n delaySeconds: number,\n dedupeKey?: string\n ): Promise<void> {\n const input = { callback, data, delaySeconds };\n await this.tasks.__DO_NOT_USE_WILL_BREAK__enqueue(\n CHAT_RECOVERY_TASK_NAME,\n input,\n chatRecoveryTaskRunOptions(input, reason, dedupeKey)\n );\n }\n\n /**\n * Start time and latest `stash()` data of each chat turn running in this\n * isolate, keyed by request id. A live stream failure is recovered while the\n * turn is still running, so `onChatRecovery` reads these instead of a fiber\n * snapshot.\n */\n private readonly _liveChatRecoveryTurns = new Map<\n string,\n { createdAt: number; recoveryData: unknown }\n >();\n\n private async _runChatRecoveryFiber<T>(\n requestId: string,\n continuation: boolean,\n fn: () => Promise<T>\n ): Promise<T> {\n const snapshot = createChatFiberSnapshot({\n kind: \"ai-chat-turn\",\n requestId,\n recoveryRootRequestId: this._activeChatRecoveryRootRequestId ?? requestId,\n continuation,\n messages: this.messages,\n lastBody: this._lastBody,\n lastClientTools: this._lastClientTools,\n originMessageIds: this._originMessageIdsFor(requestId)\n });\n const liveTurn = { createdAt: Date.now(), recoveryData: null as unknown };\n const wrap = (data: unknown) => {\n liveTurn.recoveryData = data;\n return wrapChatFiberSnapshot(\"__cfAIChatFiberSnapshot\", snapshot, data);\n };\n this._liveChatRecoveryTurns.set(requestId, liveTurn);\n try {\n return await this._runWrappedChatRecoveryFiber(\n requestId,\n continuation,\n wrap,\n fn\n );\n } finally {\n if (this._liveChatRecoveryTurns.get(requestId) === liveTurn) {\n this._liveChatRecoveryTurns.delete(requestId);\n }\n }\n }\n\n private async _runWrappedChatRecoveryFiber<T>(\n requestId: string,\n continuation: boolean,\n wrap: (data: unknown) => Record<string, unknown>,\n fn: () => Promise<T>\n ): Promise<T> {\n // Facet-hosted turns stay on the legacy fiber engine: the Tasks\n // capability does not accept runs on routed sub-agents yet, and facet\n // recovery routes through the root's facet-run index.\n if (this.parentPath.length > 0) {\n return this._runFiberWithStashWrapper(\n `${(this.constructor as typeof AIChatAgent).CHAT_FIBER_NAME}:${requestId}`,\n async () => fn(),\n { initialSnapshot: wrap(null), wrapStash: wrap }\n );\n }\n\n const nonce = nanoid();\n let resolveOutcome!: (value: unknown) => void;\n let rejectOutcome!: (error: unknown) => void;\n const outcome = new Promise<unknown>((resolve, reject) => {\n resolveOutcome = resolve;\n rejectOutcome = reject;\n });\n // Rejections can land while `runAttached` is still being awaited (before\n // the outcome listener attaches); mark them handled so workerd does not\n // report an unhandled rejection the wrapper is about to consume.\n outcome.catch(() => {});\n // The turn closure re-enters the caller's invocation context (live\n // connection/request), exactly as legacy inline fiber execution did: the\n // capability's host boundary intentionally carries no connection.\n const ambient = agentContext.getStore();\n this._liveChatTurnClosures.set(nonce, {\n initial: wrap(null),\n wrap,\n run: ambient ? () => agentContext.run(ambient, fn) : fn,\n settle: { resolve: resolveOutcome, reject: rejectOutcome }\n });\n try {\n await this.tasks.__DO_NOT_USE_WILL_BREAK__runAttached(\n (this.constructor as typeof AIChatAgent).CHAT_FIBER_NAME,\n { requestId, continuation, nonce },\n { runId: `chat_${nonce}`, retain: false, metadata: { requestId } }\n );\n return (await outcome) as T;\n } finally {\n this._liveChatTurnClosures.delete(nonce);\n }\n }\n\n /**\n * Array of chat messages for the current conversation.\n *\n * Public and mutable for backwards compatibility. Framework code\n * generally writes through `saveMessages` / `persistMessages`, but\n * existing subclasses may still assign `this.messages = [...]` or\n * mutate the array directly.\n */\n messages: UIMessage[] = [];\n\n override broadcast(\n msg: string | ArrayBuffer | ArrayBufferView,\n without?: string[]\n ): void {\n // Cheap idle guard so the common (no agent-tool child) broadcast path stays\n // allocation-free — only build the snoop hooks while a run is in flight.\n if (\n this._agentToolForwarders.size > 0 ||\n this._agentToolLiveSequences.size > 0 ||\n this._agentToolTerminalOnlyRuns.size > 0\n ) {\n const chunkRunId = interceptAgentToolBroadcast(msg, {\n forwarders: this._agentToolForwarders,\n liveSequences: this._agentToolLiveSequences,\n lastErrors: this._agentToolLastErrors,\n onError: (runId, body) => this._recordAgentToolStreamError(runId, body),\n responseType: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n runForRequest: (requestId) => this._agentToolRunForRequest(requestId),\n terminalOnlyRuns: this._agentToolTerminalOnlyRuns\n });\n if (\n chunkRunId !== null &&\n this._agentToolTerminalOnlyRuns.has(chunkRunId)\n ) {\n return;\n }\n }\n super.broadcast(msg, without);\n }\n\n /**\n * Durably record a run's stream error on its still-open row, so a stale-row\n * reconcile after an eviction (before the finalizer seals `error`) still\n * sees the failure. Leaves `status` to the finalizer / reconcile.\n */\n private _recordAgentToolStreamError(runId: string, body: string): void {\n try {\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set error_message = ${body}\n where run_id = ${runId} and status = 'running'\n `;\n } catch {\n // Best-effort: broadcast must never throw; the in-memory capture remains.\n }\n }\n\n /**\n * Resolve the agent-tool run whose turn owns a request id, or null when the\n * request is not an agent-tool turn. Falls back to the persisted run row\n * (written when the turn starts, see `_registerAgentToolTurn`) so\n * attribution survives a DO restart mid-run; either outcome is cached.\n */\n private _agentToolRunForRequest(requestId: string): string | null {\n const cached = this._agentToolRunsByRequestId.get(requestId);\n if (cached !== undefined) return cached;\n // Active-run predicate: a child run is in flight while `status` is\n // `starting`/`running`. ai-chat inserts rows directly as `running` (no\n // `starting` phase), but we match on both for parity with\n // `@cloudflare/think` and to stay correct if a `starting` phase is ever\n // added. Terminal rows set `status` AND `completed_at` together.\n const rows = this.sql<{ run_id: string; event_delivery: string | null }>`\n select run_id, event_delivery from cf_ai_chat_agent_tool_runs\n where request_id = ${requestId} and status in ('starting', 'running')\n limit 1\n `;\n const runId = rows?.[0]?.run_id ?? null;\n if (runId && rows?.[0]?.event_delivery === \"terminal\") {\n this._agentToolTerminalOnlyRuns.add(runId);\n }\n this._agentToolRunsByRequestId.set(requestId, runId);\n return runId;\n }\n\n /**\n * Re-bind this facet's in-flight agent-tool child run to the CURRENT turn's\n * request id. Parity with `@cloudflare/think`'s\n * `_rebindAgentToolChildRunRequestId`.\n *\n * When this facet runs as an agent-tool child and its turn is interrupted, the\n * recovery continuation (`continueLastTurn` / `_retryLastUserTurn`) mints a NEW\n * request id but never flows through `startAgentToolRun`'s\n * `_registerAgentToolTurn`. So `cf_ai_chat_agent_tool_runs.request_id` (and the\n * in-memory attribution map) still point at the pre-eviction turn, and\n * `broadcast` can no longer attribute the recovered turn's frames to the run.\n * A long-running child then forwards nothing to the parent's re-attach tail,\n * its no-progress budget elapses, and a healthy child is abandoned as\n * `interrupted`. Re-binding keeps attribution alive across recovery.\n *\n * Safe to call on EVERY recovery continuation:\n * - Facets that never ran as an agent-tool child have no\n * `cf_ai_chat_agent_tool_runs` table → the guarded SELECT throws → no-op.\n * - A facet whose run already settled has no active row → no-op.\n * - A child DO is addressed by its `runId` (`subAgent(cls, runId)`), so it\n * owns AT MOST ONE child-run row for its whole lifetime and is never reused\n * as a top-level chat agent — the single active row is unambiguously this\n * recovery's run. The `order by started_at desc limit 1` is defensive\n * belt-and-suspenders for that invariant.\n *\n * Uses the same `status in ('starting','running')` active-run predicate as\n * `_agentToolRunForRequest` and the `@cloudflare/think` counterpart.\n */\n private _rebindAgentToolChildRunRequestId(requestId: string): void {\n let runId: string | undefined;\n let terminalOnly = false;\n try {\n const rows = this.sql<{ run_id: string; event_delivery: string | null }>`\n select run_id, event_delivery from cf_ai_chat_agent_tool_runs\n where status in ('starting', 'running')\n order by started_at desc\n limit 1\n `;\n runId = rows?.[0]?.run_id;\n terminalOnly = rows?.[0]?.event_delivery === \"terminal\";\n } catch {\n // No child-run table on this facet (it never ran as a child).\n return;\n }\n if (!runId) return;\n if (terminalOnly) this._agentToolTerminalOnlyRuns.add(runId);\n this._agentToolRunsByRequestId.set(requestId, runId);\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set request_id = ${requestId}\n where run_id = ${runId}\n `;\n }\n\n constructor(ctx: AgentContext, env: Env) {\n super(ctx, env);\n this.lifecycle.use(this.sessions);\n this.lifecycle.use(this.streams);\n this._registerChatTurnTaskDefinition();\n this._registerChatRecoveryTaskDefinition();\n withAgentSpan(\n this,\n \"chat_initialization\",\n \"initialization\",\n { \"cloudflare.agents.component\": \"ai_chat\" },\n (update) => {\n withAgentSpan(\n this,\n \"initialize_chat_storage\",\n \"initialization\",\n { \"cloudflare.agents.component\": \"ai_chat\" },\n () => {\n // Session storage is Sessions' business and is initialized by its\n // capability `onStart`; the constructor never reads or writes the\n // transcript. Legacy lift and hydration happen in `onStart`.\n\n // Key-value table for request context that must survive hibernation\n // (e.g., custom body fields, client tools from the last chat request).\n this.sql`create table if not exists cf_ai_chat_request_context (\n key text primary key,\n value text not null\n )`;\n\n this._ensureAgentToolTables();\n }\n );\n\n // Restore request context from SQLite (survives hibernation)\n withAgentSpan(\n this,\n \"restore_chat_request_context\",\n \"initialization\",\n { \"cloudflare.agents.component\": \"ai_chat\" },\n () => this._restoreRequestContext()\n );\n\n // Initialize resumable stream manager (creates its own tables + restores state)\n withAgentSpan(\n this,\n \"initialize_resumable_stream\",\n \"initialization\",\n { \"cloudflare.agents.component\": \"ai_chat\" },\n () => {\n this._resumableStream = new ResumableStream(\n this.streams,\n this.sql.bind(this),\n {\n // Rollback insurance: a build still on the KV counter reads\n // a marker no lower than one recorded under the derived\n // marker. One put per stream retired, none per chunk.\n onProgress: (durable) => {\n void this.ctx.storage\n .put(CHAT_RECOVERY_PROGRESS_KEY, durable)\n .catch(() => {});\n }\n }\n );\n }\n );\n\n update({\n \"cloudflare.agents.chat.active_stream.restored\":\n this._resumableStream.hasActiveStream()\n });\n }\n );\n\n // `this.messages` mirrors durable storage through the Sessions change\n // feed rather than being hand-patched at each write site.\n this.#subscribeToSessionChanges();\n\n const _onStart = this.onStart.bind(this);\n this.onStart = async (props?: Props) => {\n await withAgentSpan(\n this,\n \"load_chat_messages\",\n \"startup\",\n { \"cloudflare.agents.component\": \"ai_chat\" },\n async (update) => {\n await this._migrateLegacyMessages();\n await this._hydrateMessages();\n update({\n \"cloudflare.agents.chat.messages.loaded\": this.messages.length\n });\n }\n );\n return _onStart(props);\n };\n\n this._abortRegistry = new AbortRegistry();\n const _onConnect = this.onConnect.bind(this);\n this.onConnect = async (connection: Connection, ctx: ConnectionContext) => {\n if (this._cf_requestTargetsSubAgent(ctx.request)) {\n return _onConnect(connection, ctx);\n }\n\n // Notify client about active streams that can be resumed\n if (this._resumableStream.hasActiveStream()) {\n this._notifyStreamResuming(connection);\n } else if (this._preStream.park(connection)) {\n // A turn is accepted but its stream hasn't started yet (#1784): park\n // this connection and tell it to keep waiting. `park` sent the\n // keep-waiting frame; the turn flushes it into STREAM_RESUMING on\n // _startStream or releases it with STREAM_RESUME_NONE on settle.\n } else {\n // No active stream to resume: if a recovery is in progress (between\n // attempts — the interrupted stream ended and the continuation hasn't\n // started yet), replay the live \"recovering…\" status so a client that\n // connects mid-recovery reads the turn as working rather than frozen\n // (#1620). This converges `AIChatAgent` onto `@cloudflare/think`'s\n // behavior. Unlike the terminal outcome (which must go through the\n // resume handshake to reach the client's stream reader), the recovering\n // frame is a plain status the client reflects directly into state.\n const recoveringFrame = await this._buildRecoveringConnectFrame();\n if (recoveringFrame) {\n sendIfOpen(connection, JSON.stringify(recoveringFrame));\n }\n }\n // Call consumer's onConnect\n return _onConnect(connection, ctx);\n };\n\n // Wrap onClose to clean up pending resume connections\n const _onClose = this.onClose.bind(this);\n this.onClose = async (\n connection: Connection,\n code: number,\n reason: string,\n wasClean: boolean\n ) => {\n // Clean up pending resume state for this connection\n this._pendingResumeConnections.delete(connection.id);\n this._continuation.releaseConnection(connection.id);\n this._preStream.release(connection.id);\n // Call consumer's onClose\n return _onClose(connection, code, reason, wasClean);\n };\n\n // Wrap onMessage\n const _onMessage = this.onMessage.bind(this);\n const handleMessage = async (\n connection: Connection,\n message: WSMessage\n ) => {\n if (this._cf_connectionTargetsSubAgent(connection)) {\n return _onMessage(connection, message);\n }\n\n // Handle AIChatAgent's internal messages first. Classification is shared\n // with `@cloudflare/think` via `parseProtocolMessage`; the handler bodies\n // below stay AIChatAgent-specific (e.g. the `messages` event persists the\n // client snapshot, where Think no-ops it).\n if (typeof message === \"string\") {\n const event = parseProtocolMessage(message);\n if (!event) {\n // Not JSON, or not a recognized chat protocol message — forward to\n // the consumer's onMessage.\n return _onMessage(connection, message);\n }\n\n // Handle chat request\n if (event.type === \"chat-request\" && event.init.method === \"POST\") {\n const { body } = event.init;\n if (!body) {\n console.warn(\n \"[AIChatAgent] Received chat request with empty body, ignoring\"\n );\n return;\n }\n\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(body as string);\n } catch (_parseError) {\n console.warn(\n \"[AIChatAgent] Received chat request with invalid JSON body, ignoring\"\n );\n return;\n }\n\n const {\n messages,\n clientTools,\n trigger: _trigger,\n ...customBody\n } = parsed as {\n messages: UIMessage[];\n clientTools?: ClientToolSchema[];\n trigger?: string;\n [key: string]: unknown;\n };\n const chatMessageId = event.id;\n const transformedMessages = autoTransformMessages(messages);\n const requestTrigger: ChatRequestTrigger =\n _trigger === \"regenerate-message\"\n ? \"regenerate-message\"\n : \"submit-message\";\n const requestClientTools = clientTools?.length\n ? clientTools\n : undefined;\n const requestBody =\n Object.keys(customBody).length > 0 ? customBody : undefined;\n const epoch = this._turnQueue.generation;\n const requestOriginIds = originMessageIds(messages);\n if (requestOriginIds) {\n this._requestOriginMessageIds.set(chatMessageId, requestOriginIds);\n }\n const concurrencyDecision =\n this._getSubmitConcurrencyDecision(requestTrigger);\n\n if (concurrencyDecision.action === \"drop\") {\n this._rollbackDroppedSubmit(connection);\n this._completeSkippedRequest(connection, chatMessageId);\n this._requestOriginMessageIds.delete(chatMessageId);\n return;\n }\n\n // A genuinely-new turn supersedes any pending terminal record (#1645)\n // so a stale exhaustion can't replay on a later reconnect once the\n // user has moved on.\n await withAgentSpan(\n this,\n \"clear_previous_chat_state\",\n \"interaction\",\n {\n \"cloudflare.agents.component\": \"ai_chat\",\n \"cloudflare.agents.turn.request_id\": chatMessageId,\n \"cloudflare.agents.turn.trigger\": requestTrigger\n },\n () => this._clearChatTerminal()\n );\n\n // Mark this turn as accepted-but-not-yet-streamed (#1784) so a client\n // that reconnects/re-mounts before the stream starts is parked and\n // told to keep waiting (see _resumeHandshake / onConnect), then\n // flushed into STREAM_RESUMING on _startStream or released on settle.\n this._preStream.begin(chatMessageId);\n\n // Outer finally so the accepted pre-stream turn ALWAYS settles\n // (#1784). begin() runs before the pre-turn-body steps below\n // (persistMessages, _mergeQueuedUserMessages, and inside the queued\n // execute callback mcp.waitForConnections / _setRequestContext); if\n // any of those throws, chatTurnBody's own finally never runs. Without\n // this backstop the request id would stay stuck in _preStream —\n // hasInFlight() true forever — so every future client would be parked\n // on STREAM_PENDING (60s) instead of getting an immediate\n // STREAM_RESUME_NONE, until chat clear or DO eviction. Mirrors\n // @cloudflare/think's _handleChatRequest.\n try {\n // Track that this request is past the concurrency decision but\n // not yet enqueued in _turnQueue. Decremented synchronously\n // before _runExclusiveChatTurn (which increments queuedCount).\n const releasePendingEnqueue =\n this._submitConcurrency.beginEnqueue();\n try {\n // Persist and broadcast user messages before entering the turn\n // queue so other tabs see the new message immediately and so\n // overlapping submits under latest/merge/debounce can inspect\n // the full message list when their turn starts.\n await withAgentSpan(\n this,\n \"persist_incoming_messages\",\n \"interaction\",\n {\n \"cloudflare.agents.component\": \"ai_chat\",\n \"cloudflare.agents.turn.request_id\": chatMessageId,\n \"cloudflare.agents.turn.trigger\": requestTrigger\n },\n async () => {\n this._broadcastChatMessage(\n {\n messages: transformedMessages,\n type: MessageType.CF_AGENT_CHAT_MESSAGES\n },\n [connection.id]\n );\n\n await this.persistMessages(\n transformedMessages,\n [connection.id],\n { _deleteStaleRows: true }\n );\n\n if (concurrencyDecision.strategy === \"merge\") {\n await this._mergeQueuedUserMessages(epoch);\n }\n }\n );\n } finally {\n releasePendingEnqueue();\n }\n await this._runExclusiveChatTurn(\n chatMessageId,\n async () => {\n if (\n this._submitConcurrency.isSuperseded(\n concurrencyDecision.submitSequence\n )\n ) {\n this._completeSkippedRequest(connection, chatMessageId);\n return;\n }\n\n if (concurrencyDecision.debounceUntilMs !== null) {\n await this._submitConcurrency.waitForTimestamp(\n concurrencyDecision.debounceUntilMs\n );\n\n if (this._turnQueue.generation !== epoch) {\n this._completeSkippedRequest(connection, chatMessageId);\n return;\n }\n\n if (\n this._submitConcurrency.isSuperseded(\n concurrencyDecision.submitSequence\n )\n ) {\n this._completeSkippedRequest(connection, chatMessageId);\n return;\n }\n }\n\n // Re-merge inside the lock: more overlapping submits may have\n // persisted additional user messages while this turn was queued.\n if (concurrencyDecision.strategy === \"merge\") {\n await withAgentSpan(\n this,\n \"merge_queued_messages\",\n \"turn\",\n {\n \"cloudflare.agents.component\": \"ai_chat\",\n \"cloudflare.agents.turn.request_id\": chatMessageId,\n \"cloudflare.agents.turn.trigger\": requestTrigger,\n \"cloudflare.agents.turn.admission\": \"queue\",\n \"cloudflare.agents.turn.generation\": epoch\n },\n () => this._mergeQueuedUserMessages(epoch)\n );\n\n if (this._turnQueue.generation !== epoch) {\n this._completeSkippedRequest(connection, chatMessageId);\n return;\n }\n\n if (\n this._submitConcurrency.isSuperseded(\n concurrencyDecision.submitSequence\n )\n ) {\n this._completeSkippedRequest(connection, chatMessageId);\n return;\n }\n }\n\n await withAgentSpan(\n this,\n \"prepare_chat_context\",\n \"turn\",\n {\n \"cloudflare.agents.component\": \"ai_chat\",\n \"cloudflare.agents.turn.request_id\": chatMessageId,\n \"cloudflare.agents.turn.trigger\": requestTrigger,\n \"cloudflare.agents.turn.admission\": \"queue\",\n \"cloudflare.agents.turn.generation\": epoch\n },\n async () => {\n // Optionally wait for in-flight MCP connections to settle (e.g. after hibernation restore)\n // so that getAITools() returns the full set of tools in onChatMessage\n if (this.waitForMcpConnections) {\n const timeout =\n typeof this.waitForMcpConnections === \"object\"\n ? this.waitForMcpConnections.timeout\n : undefined;\n await this.mcp.waitForConnections(\n timeout != null ? { timeout } : undefined\n );\n }\n\n this._setRequestContext(requestClientTools, requestBody);\n }\n );\n\n this._emit(\"message:request\");\n\n const abortSignal =\n this._abortRegistry.getSignal(chatMessageId);\n\n return this._tryCatchChat(async () => {\n // Wrap in agentContext.run() to propagate connection context to onChatMessage\n // This ensures getCurrentAgent() returns the connection inside tool execute functions\n return agentContext.run(\n {\n agent: this,\n connection,\n request: undefined,\n email: undefined\n },\n async () => {\n const chatTurnBody = async () => {\n try {\n await withAgentSpan(\n this,\n \"repair_interrupted_tools\",\n \"turn\",\n {\n \"cloudflare.agents.component\": \"ai_chat\",\n \"cloudflare.agents.turn.request_id\":\n chatMessageId,\n \"cloudflare.agents.turn.trigger\": requestTrigger,\n \"cloudflare.agents.turn.admission\": \"queue\",\n \"cloudflare.agents.turn.generation\": epoch\n },\n () =>\n this._repairInterruptedToolsBeforeTurn({\n continuation: false\n })\n );\n const response = await this.onChatMessage(\n async (_finishResult) => {\n // User-provided hook. Cleanup is now handled by _reply,\n // so this is optional for the user to pass to streamText.\n },\n {\n requestId: chatMessageId,\n abortSignal,\n clientTools: requestClientTools,\n body: requestBody,\n continuation: false\n }\n );\n\n if (response) {\n await withAgentSpan(\n this,\n \"persist_chat_result\",\n \"turn\",\n {\n \"cloudflare.agents.component\": \"ai_chat\",\n \"cloudflare.agents.turn.request_id\":\n chatMessageId,\n \"cloudflare.agents.turn.trigger\":\n requestTrigger,\n \"cloudflare.agents.turn.admission\": \"queue\",\n \"cloudflare.agents.turn.generation\": epoch\n },\n () =>\n this._reply(\n chatMessageId,\n response,\n [connection.id],\n { chatMessageId }\n )\n );\n } else {\n console.warn(\n `[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`\n );\n this._broadcastChatMessage({\n body: \"No response was generated by the agent.\",\n done: true,\n id: chatMessageId,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n outcome: \"completed\"\n });\n }\n } finally {\n this._abortRegistry.remove(chatMessageId);\n // Settle the pre-stream turn on the normal path (#1784):\n // a no-op release when the turn streamed (already flushed\n // into STREAM_RESUMING on _startStream) or a release on\n // the no-response path. A throw BEFORE chatTurnBody runs\n // is caught by the outer finally instead.\n this._settlePreStreamTurn(chatMessageId);\n }\n };\n\n await this._runChatRecoveryFiber(\n chatMessageId,\n false,\n chatTurnBody\n );\n }\n );\n });\n },\n {\n epoch,\n onStale: () =>\n this._completeSkippedRequest(connection, chatMessageId)\n }\n );\n } finally {\n // Guaranteed settle (#1784): on the happy path chatTurnBody /\n // _completeSkippedRequest already settled (idempotent here); this\n // covers a throw in a pre-turn-body step before chatTurnBody's\n // finally could run.\n this._settlePreStreamTurn(chatMessageId);\n this._requestOriginMessageIds.delete(chatMessageId);\n }\n return;\n }\n\n // Handle clear chat\n if (event.type === \"clear\") {\n this.resetTurnState();\n await this.#session.clearMessages();\n // Drop any pending terminal record (#1645) so a stale exhaustion\n // can't replay onto a freshly-cleared (empty) conversation when a\n // client reconnects and runs the resume probe.\n await this._clearChatTerminal();\n this._resumableStream.clearAll();\n this._pendingResumeConnections.clear();\n this._preStream.releaseAwaiting();\n this._preStream.reset();\n this._lastClientTools = undefined;\n this._lastBody = undefined;\n this._persistRequestContext();\n // `clearMessages()` above emptied `this.messages` through the\n // change feed.\n this._broadcastChatMessage(\n { type: MessageType.CF_AGENT_CHAT_CLEAR },\n [connection.id]\n );\n this._emit(\"message:clear\");\n return;\n }\n\n // Handle message replacement\n if (event.type === \"messages\") {\n const transformedMessages = autoTransformMessages(event.messages);\n await this.persistMessages(transformedMessages, [connection.id]);\n return;\n }\n\n // Handle request cancellation\n if (event.type === \"cancel\") {\n this._abortRegistry.cancel(event.id);\n await this._cancelScheduledRecovery(event.id);\n this._emit(\"message:cancel\", { requestId: event.id });\n return;\n }\n\n // Handle client-initiated stream resume request.\n // The client sends this after its message handler is registered,\n // avoiding the race condition where CF_AGENT_STREAM_RESUMING sent\n // in onConnect arrives before the client's handler is ready.\n if (event.type === \"stream-resume-request\") {\n await this._resumeHandshake().handleResumeRequest(\n connection,\n event.probeId\n );\n return;\n }\n\n // Handle stream resume acknowledgment\n if (event.type === \"stream-resume-ack\") {\n await this._resumeHandshake().handleResumeAck(connection, event.id);\n return;\n }\n\n // Handle client-side tool result\n if (event.type === \"tool-result\") {\n const {\n toolCallId,\n toolName,\n output,\n state,\n errorText,\n autoContinue,\n clientTools\n } = event;\n\n // Update cached client tools so subsequent continuations use the latest schemas\n if (clientTools?.length) {\n this._lastClientTools = clientTools as ClientToolSchema[];\n this._persistRequestContext();\n }\n\n const overrideState =\n state === \"output-error\" ? \"output-error\" : undefined;\n\n this._emit(\"tool:result\", { toolCallId, toolName });\n\n this._enqueueInteractionApply(() =>\n this._applyToolResult(\n toolCallId,\n toolName,\n output,\n overrideState,\n errorText\n )\n );\n\n if (autoContinue) {\n this._scheduleAutoContinuation(\n connection,\n (clientTools as ClientToolSchema[] | undefined) ??\n this._lastClientTools,\n this._lastBody,\n \"[AIChatAgent] Tool continuation failed:\"\n );\n } else {\n // A result that arrived WITHOUT autoContinue (e.g. a standalone\n // errored tool) can still be the one that completes a parallel batch\n // a sibling already opted to continue — re-arm the barrier so that\n // continuation fires once the batch is whole (#1650). Never CREATES\n // a pending continuation.\n this._rearmPendingAutoContinuationForBatch();\n }\n return;\n }\n\n // Handle client-side tool approval response\n if (event.type === \"tool-approval\") {\n const { toolCallId, approved, autoContinue } = event;\n this._emit(\"tool:approval\", { toolCallId, approved });\n this._enqueueInteractionApply(() =>\n this._applyToolApproval(toolCallId, approved)\n );\n\n if (autoContinue) {\n this._scheduleAutoContinuation(\n connection,\n this._lastClientTools,\n this._lastBody,\n \"[AIChatAgent] Tool approval continuation failed:\"\n );\n } else {\n this._rearmPendingAutoContinuationForBatch();\n }\n return;\n }\n }\n\n // Forward unhandled messages to consumer's onMessage\n return _onMessage(connection, message);\n };\n this.onMessage = (connection: Connection, message: WSMessage) => {\n const event =\n typeof message === \"string\" ? parseProtocolMessage(message) : null;\n if (event?.type === \"chat-request\") {\n return withAgentSpan(\n this,\n \"chat_interaction\",\n \"interaction\",\n {\n \"cloudflare.agents.component\": \"ai_chat\",\n \"cloudflare.agents.turn.request_id\": event.id\n },\n () => handleMessage(connection, message)\n );\n }\n return handleMessage(connection, message);\n };\n\n const _onRequest = this.onRequest.bind(this);\n this.onRequest = async (request: Request) => {\n return this._tryCatchChat(async () => {\n const url = new URL(request.url);\n if (url.pathname.split(\"/\").pop() === \"get-messages\") {\n return new Response(this.#streamMessagesAsJson(), {\n headers: { \"content-type\": \"application/json\" }\n });\n }\n return _onRequest(request);\n });\n };\n }\n\n private _ensureAgentToolTables() {\n this.sql`create table if not exists cf_ai_chat_agent_tool_runs (\n run_id text primary key,\n request_id text,\n status text not null,\n input_json text,\n output_json text,\n summary text,\n error_message text,\n started_at integer not null,\n completed_at integer\n )`;\n const addColumnIfNotExists = (sql: string) => {\n try {\n this.ctx.storage.sql.exec(sql);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (!message.toLowerCase().includes(\"duplicate column\")) {\n throw error;\n }\n }\n };\n addColumnIfNotExists(\n \"alter table cf_ai_chat_agent_tool_runs add column input_json text\"\n );\n addColumnIfNotExists(\n \"alter table cf_ai_chat_agent_tool_runs add column output_json text\"\n );\n addColumnIfNotExists(\n \"alter table cf_ai_chat_agent_tool_runs add column summary text\"\n );\n // Latest progress snapshot (rfc-detached-agent-tools §progress); only the\n // most recent `reportProgress` is retained. `last_signal_at` drives the\n // parent's resetting no-progress budget across eviction.\n addColumnIfNotExists(\n \"alter table cf_ai_chat_agent_tool_runs add column progress_json text\"\n );\n addColumnIfNotExists(\n \"alter table cf_ai_chat_agent_tool_runs add column last_signal_at integer\"\n );\n addColumnIfNotExists(\n \"alter table cf_ai_chat_agent_tool_runs add column event_delivery text\"\n );\n this.sql`create index if not exists idx_ai_chat_agent_tool_request_id\n on cf_ai_chat_agent_tool_runs(request_id)`;\n // Durable milestones (rfc-detached-agent-tools §progress, 4b). One row per\n // milestone; `sequence` is monotonic per run so replay/live races dedupe.\n this.sql`create table if not exists cf_ai_chat_agent_tool_milestones (\n run_id text not null,\n sequence integer not null,\n name text not null,\n data_json text,\n at integer not null,\n primary key (run_id, sequence)\n )`;\n }\n\n private _persistAgentToolMilestone(\n runId: string,\n name: string,\n data: unknown,\n at: number\n ): number {\n this._ensureAgentToolTables();\n const rows = this.sql<{ next: number }>`\n select coalesce(max(sequence), -1) + 1 as next\n from cf_ai_chat_agent_tool_milestones where run_id = ${runId}\n `;\n const sequence = rows[0]?.next ?? 0;\n this.sql`\n insert or ignore into cf_ai_chat_agent_tool_milestones\n (run_id, sequence, name, data_json, at)\n values (\n ${runId}, ${sequence}, ${name},\n ${data !== undefined ? JSON.stringify(data) : null}, ${at}\n )\n `;\n // A milestone is a progress signal too: advance the no-progress clock.\n this.sql`update cf_ai_chat_agent_tool_runs set last_signal_at = ${at}\n where run_id = ${runId}`;\n return sequence;\n }\n\n private _readAgentToolMilestones(runId: string): AgentToolMilestone[] {\n this._ensureAgentToolTables();\n return this.sql<{\n sequence: number;\n name: string;\n data_json: string | null;\n at: number;\n }>`\n select sequence, name, data_json, at\n from cf_ai_chat_agent_tool_milestones\n where run_id = ${runId} order by sequence asc\n `.map((row) => ({\n name: row.name,\n sequence: row.sequence,\n at: row.at,\n ...(row.data_json != null\n ? { data: JSON.parse(row.data_json) as unknown }\n : {})\n }));\n }\n\n private _flushAwaitingStreamStartConnections() {\n if (!this._resumableStream.hasActiveStream()) {\n return;\n }\n\n this._continuation.flushAwaitingConnections((c) =>\n this._notifyStreamResuming(c)\n );\n }\n\n private _activateDeferredAutoContinuation() {\n // Run the freshly-activated continuation through the event-driven barrier\n // (#1650) rather than enqueuing it directly — its batch may still be\n // incomplete (or a stream may be active), in which case it parks and\n // re-arms instead of firing inference against a half-complete transcript.\n this._autoContinuation.activateDeferredAndReschedule();\n }\n\n private _clearAllAutoContinuationState(sendNone = false) {\n this._clearPendingAutoContinuation(sendNone);\n this._continuation.clearDeferred();\n }\n\n private _clearPendingAutoContinuation(sendNone = false) {\n if (sendNone) {\n this._continuation.sendResumeNone();\n }\n this._continuation.clearPending();\n }\n\n /**\n * The shared resume-handshake driver (Tier-2). Lazily built; the\n * `ResumableStream` / `ContinuationState` / pending set are stable after the\n * constructor, so a single instance threads them for the agent's lifetime.\n */\n private _resumeHandshake(): ResumeHandshake {\n return (this._resumeHandshakeInstance ??= new ResumeHandshake({\n responseMessageType: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n resumableStream: this._resumableStream,\n continuation: this._continuation,\n preStream: this._preStream,\n pendingResumeConnections: this._pendingResumeConnections,\n pendingChatTerminal: () => this._pendingChatTerminal(),\n persistOrphanedStream: (streamId) =>\n this._persistOrphanedStream(streamId),\n isConnectionPresent: (connectionId) =>\n this._isConnectionPresent(connectionId),\n holdsTerminalFrames: (requestId) =>\n this._heldTerminalFrames.has(requestId)\n }));\n }\n\n /**\n * Notify a connection about an active stream that can be resumed — delegates\n * to the shared {@link ResumeHandshake}. Kept as a thin method because it is\n * also called proactively from onConnect and the broadcast loop. See the\n * driver for the #1733 double-send contract.\n * @param connection - The WebSocket connection to notify\n */\n private _notifyStreamResuming(connection: Connection) {\n this._resumeHandshake().notifyStreamResuming(connection);\n }\n\n // ── Delegate methods for backward compatibility with tests ─────────\n // These protected methods delegate to _resumableStream so existing\n // test workers that call them directly continue to work.\n\n /** @internal Delegate to _resumableStream */\n protected get _activeStreamId(): string | null {\n return this._resumableStream?.activeStreamId ?? null;\n }\n\n /** @internal Delegate to _resumableStream */\n protected get _activeRequestId(): string | null {\n return this._resumableStream?.activeRequestId ?? null;\n }\n\n /** @internal Delegate to _resumableStream */\n protected _startStream(\n requestId: string,\n options: { messageId?: string; continuation?: boolean } = {}\n ): string {\n const originIds =\n this._requestOriginMessageIds.get(requestId) ??\n this._activeChatRecoveryOriginIds;\n const streamId = this._resumableStream.start(requestId, {\n ...options,\n ...(originIds && { originMessageIds: originIds })\n });\n // Flush connections parked during this turn's pre-stream window (#1784)\n // into the normal STREAM_RESUMING path now that a stream exists. Safe for\n // every turn — the awaiting set is empty unless a client reconnected before\n // the first chunk. (Continuation-turn parks live in `_continuation` and are\n // flushed below.)\n this._preStream.flushOnStreamStart((c) => this._notifyStreamResuming(c));\n if (this._continuation.pending?.requestId === requestId) {\n this._continuation.activatePending();\n this._flushAwaitingStreamStartConnections();\n this._activateDeferredAutoContinuation();\n }\n // Arm on START as well as finish so cleanup still has a belt-and-suspenders\n // wake if fiber recovery cannot finalize a stream. The last-activity sweep\n // threshold keeps an actively streaming run from being reclaimed before it\n // goes quiet (#1706).\n return streamId;\n }\n\n /** @internal Delegate to _resumableStream */\n protected _completeStream(streamId: string, outcome?: ChatTurnOutcome) {\n const completedRequestId = this._resumableStream.activeRequestId;\n this._resumableStream.complete(streamId, outcome);\n this._afterStreamFinished(completedRequestId);\n }\n\n /**\n * @internal The producer finished; leave the row for the cutover that\n * persists the message (`persistMessages` via `#pendingCutover`). `_reply`'s\n * finally settles it if no persist follows.\n */\n protected _finishStream(streamId: string, outcome?: ChatTurnOutcome) {\n const finishedRequestId = this._resumableStream.activeRequestId;\n this._resumableStream.finish(streamId, outcome);\n this._afterStreamFinished(finishedRequestId);\n }\n\n private _afterStreamFinished(requestId: string | null) {\n this._pendingResumeConnections.clear();\n if (requestId === this._continuation.activeRequestId) {\n this._continuation.activeRequestId = null;\n this._continuation.activeConnectionId = null;\n }\n }\n\n /**\n * @deprecated Streams are reclaimed at cutover and on the next stream\n * start; no alarm is armed any more. Kept so a cleanup alarm persisted\n * by an earlier version still resolves to a callback when it fires.\n * @internal\n */\n async _cleanupStreamBuffers(): Promise<void> {\n this._resumableStream.reclaim();\n }\n\n /**\n * @internal Delegate to _resumableStream.\n *\n * A settled tool result (`tool-output-available` / `-error` / `-denied`)\n * is flushed to SQLite immediately rather than waiting for the packed\n * segment to fill: it captures a completed, often non-idempotent side\n * effect (or a user's denial), and an isolate eviction before the next\n * batch flush would lose it — recovery would re-anchor without it and\n * re-run the tool. The flush is also what the recovery progress marker is\n * derived from (`_chatRecoveryProgressMarker`), so a settled result counts\n * as forward progress the moment it lands, as it did under the old\n * per-chunk counter. Streaming deltas keep the buffer's own packing.\n */\n protected async _storeStreamChunk(\n streamId: string,\n body: string\n ): Promise<number | undefined> {\n const seq = this._resumableStream.storeChunk(streamId, body);\n let type: string | undefined;\n try {\n type = (JSON.parse(body) as { type?: string }).type;\n } catch {\n // non-JSON chunk body — packed with the rest\n }\n if (\n type === \"tool-output-available\" ||\n type === \"tool-output-error\" ||\n type === \"tool-output-denied\"\n ) {\n this._resumableStream.flushBuffer();\n }\n return seq;\n }\n\n /** @internal Delegate to _resumableStream */\n protected _flushChunkBuffer() {\n this._resumableStream.flushBuffer();\n }\n\n /** @internal Delegate to _resumableStream */\n protected _restoreActiveStream() {\n this._resumableStream.restore();\n }\n\n /** @internal Delegate to _resumableStream */\n protected _markStreamError(streamId: string) {\n const erroredRequestId = this._resumableStream.activeRequestId;\n this._resumableStream.markError(streamId);\n this._pendingResumeConnections.clear();\n if (erroredRequestId === this._continuation.activeRequestId) {\n this._continuation.activeRequestId = null;\n this._continuation.activeConnectionId = null;\n }\n }\n\n /**\n * Reconstruct and persist a partial assistant message from an orphaned\n * stream's stored chunks. Called when the DO wakes from hibernation and\n * discovers an active stream with no live LLM reader.\n *\n * Built from the three orphan-persist seams the chat-recovery RFC factored\n * out — all three are ai-chat's substrate-specific realizations of a shape\n * `Think` shares:\n * - (a) reconstruct via the shared `StreamAccumulator` (the same primitive\n * `Think` and the client reducer use), replacing a hand-rolled chunk\n * switch; it owns the `start` / `finish` / `message-metadata` handling;\n * - (b) {@link _resolveOrphanTargetId} — the id to persist under (#1691);\n * - (c)+(d) upsert-by-id through the shared `OrphanPersistStore` shape\n * (`getMessage` → `updateMessage` / `appendMessage`).\n * When a row already owns the id, the shared `reconcileOrphanPartial`\n * merge preserves an in-place tool result rather than letting a replayed\n * chunk re-advance it (ai-chat has an early tool-approval persist; hosts\n * without one append straight through).\n * @internal\n */\n protected async _persistOrphanedStream(streamId: string): Promise<void> {\n const chunks = this._resumableStream.getStreamChunks(streamId);\n if (!chunks.length) return;\n\n // The accumulate loop and the `getMessage → update(merge) XOR append` upsert\n // are the shared `persistReconstructedOrphan` core. ai-chat supplies the two\n // host-specific hooks:\n // - prepare: resolve the persist-target id (#1691) — the one per-package\n // step (a flat array can't express the tree a Session uses). A provider\n // `start.messageId` is adopted by the accumulator (the live path adopts\n // it for new turns too); continuations have it stripped before storage\n // (#1229), so the unconditional adopt matches the live path.\n // - merge: a row may already own this id (an early persist during tool\n // approval, or a continuation resuming the last assistant message) —\n // reconcile onto it via the shared `reconcileOrphanPartial` so an\n // in-place tool result isn't re-advanced by a replayed chunk.\n // The store routes each write through `persistMessages` (exactly one write →\n // one `persistMessages` → one broadcast), so no explicit broadcast here.\n // NOTE: progress is bumped at production/flush time in `_storeStreamChunk`\n // (#1637), NOT here — persisting on recovery or a client reconnect must not\n // be miscounted as new forward progress.\n const fallbackId = `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;\n await persistReconstructedOrphan(chunks, {\n store: this._orphanStore(),\n fallbackId,\n prepare: (message) => {\n message.id = this._resolveOrphanTargetId(\n streamId,\n message.id,\n fallbackId\n );\n return message;\n },\n merge: (existing, incoming) => reconcileOrphanPartial(existing, incoming)\n });\n }\n\n /**\n * Resolve the id an orphaned partial should persist under — orphan-persist\n * step **(b)**, and the one legitimately per-package piece of the path: a\n * flat `UIMessage[]` can't express the parent/child a Session tree uses to\n * resolve this structurally, so ai-chat reads it from stream metadata.\n *\n * When the reconstructed message already adopted a provider `start.messageId`\n * (kept as-is — the live path adopts it for new turns too) `reconstructedId`\n * differs from `fallbackId` and is returned unchanged. Otherwise resolve to:\n * - the id allocated when the stream started, recorded in stream metadata\n * (#1691) — the SAME id the live path persists under (it only adopts a\n * provider id, never invents one). A new turn stored its own fresh id, so\n * it becomes its own message; a continuation stored the cloned\n * last-assistant id, so it merges. This is what stops a new turn after a\n * later user message from being folded into the previous assistant\n * message (the #1691 corruption); or\n * - (legacy rows written before the metadata column existed) the last\n * assistant message, matching pre-#1691 behavior.\n * @internal\n */\n protected _resolveOrphanTargetId(\n streamId: string,\n reconstructedId: string,\n fallbackId: string\n ): string {\n if (reconstructedId !== fallbackId) return reconstructedId;\n const storedId = this._resumableStream.getStreamMessageId(streamId);\n if (storedId != null) return storedId;\n for (let i = this.messages.length - 1; i >= 0; i--) {\n if (this.messages[i].role === \"assistant\") return this.messages[i].id;\n }\n return reconstructedId;\n }\n\n /**\n * The orphan-persist store adapter. Orphan-persist steps **(c)/(d)** route\n * through the shared `OrphanPersistStore` seam, backed by ai-chat's\n * `this.messages`\n * array + the existing `persistMessages` whole-array write path, so\n * reconcile/sanitize/row-size/broadcast all stay intact. Each mutating call\n * is exactly one `persistMessages` invocation; `parentId` is unused (a flat\n * array has no tree to attach to).\n * @internal\n */\n protected _orphanStore(): OrphanPersistStore {\n return {\n getMessage: (id) => this.messages.find((m) => m.id === id) ?? null,\n appendMessage: (message) =>\n this.persistMessages([...this.messages, message]),\n updateMessage: (message) =>\n this.persistMessages(\n this.messages.map((m) => (m.id === message.id ? message : m))\n )\n };\n }\n\n /**\n * Repair a single interrupted tool call — a tool part with no settled result,\n * left behind when a stream was cut off mid-flight (e.g. a SERVER tool whose\n * `execute()` died with an evicted isolate, leaving an `input-available`\n * orphan that nothing will ever resolve). Returns the replacement part that\n * takes its place in the transcript; `input` has already been normalized to a\n * valid object.\n *\n * The default flips it to an errored tool result so the record survives (no\n * \"disappearing\" tool call) and `convertToModelMessages` still gets a\n * tool-result for it, avoiding `AI_MissingToolResultsError` on the next\n * provider call. This mirrors `@cloudflare/think` so ai-chat RECOVERS an\n * interrupted server tool (repairs, then continues) instead of waiting on a\n * dead orphan until its budget is spent.\n *\n * Override to customize the repaired shape for client-resolved tools — e.g.\n * convert an interrupted question tool (no server `execute`, normally answered\n * by the user's next message) into a plain text part so the model sees it as\n * ordinary conversation rather than a tool error. A returned tool part MUST\n * carry a settled result (`output-available` / `output-error` /\n * `output-denied` or an `output` / `result` field); returning a non-tool part\n * (e.g. text) is fine.\n */\n protected repairInterruptedToolPart(\n part: UIMessage[\"parts\"][number]\n ): UIMessage[\"parts\"][number] {\n return {\n ...part,\n state: \"output-error\",\n errorText:\n (part as { state?: string }).state === \"approval-responded\"\n ? \"The tool call was approved but did not run before the next turn started.\"\n : \"The tool call was interrupted before a result was recorded.\"\n } as UIMessage[\"parts\"][number];\n }\n\n /**\n * Transcript repair, run before EVERY inference chokepoint (live submit, tool\n * auto-continuation, `continueLastTurn`, `saveMessages`/retry, and the chat\n * recovery callbacks). An interrupted server-tool orphan is flipped to a\n * settled (errored) result — via the shared `agents/chat`\n * `repairInterruptedToolParts` primitive, the SAME logic `@cloudflare/think`\n * runs before its own inference (`_assembleModelMessages`) — so the app's next\n * `convertToModelMessages(this.messages)` doesn't 400 with\n * `AI_MissingToolResultsError`. Because the app owns the inference call, the\n * framework can't repair \"inside\" it the way Think does; it repairs\n * `this.messages` at each point right before handing control to\n * `onChatMessage` instead. This reaches the cases the recovery-only repair\n * missed, including a mixed client+server orphan whose client replay drives\n * an auto-continuation.\n *\n * Scope: repair only ever flips a DEAD SERVER orphan (an interrupted tool with\n * no settled result whose `execute()` died with the evicted isolate). A part\n * still legitimately awaiting a CLIENT interaction — an `input-available`\n * client tool the SPA replays, or an `approval-requested` part the user may\n * still answer — is left verbatim via the shared `shouldRepair` skip, so it is\n * never clobbered with an error. This is per-part (not a whole-transcript\n * guard), so a fresh dead-server orphan at the leaf is still repaired even if\n * an unrelated abandoned client orphan sits earlier in history.\n *\n * Repair only ever reshapes ASSISTANT tool parts; it never touches user\n * messages, so per-channel policy carried on the user message's\n * `metadata.channel` (re-resolved on wake) is structurally untouched. It is a\n * no-op (no write, no broadcast) when nothing needs repair — the common case\n * for a healthy transcript. When anything changes, the corrected transcript is\n * persisted and broadcast through the normal `persistMessages` write path (one\n * write, one broadcast), which also refreshes `this.messages`.\n * @internal\n */\n private async _repairInterruptedToolsBeforeTurn(options: {\n continuation: boolean;\n }): Promise<void> {\n const clientResolvable = this._clientResolvableToolNames();\n const repaired = repairInterruptedToolParts(this.messages, {\n repairPart: (part) => this.repairInterruptedToolPart(part),\n shouldRepair: (part) =>\n !this._partAwaitsClientInteraction(part, clientResolvable),\n // An approval a continuation will still execute must survive; one the\n // conversation moved past without running would 400 at the provider.\n repairApprovalResponded:\n !options.continuation &&\n !this._continuation.pending &&\n !this._continuation.deferred\n });\n if (repaired.removedToolCalls === 0 && repaired.normalizedInputs === 0) {\n return;\n }\n await this.persistMessages(repaired.messages);\n }\n\n /**\n * Restore _lastBody and _lastClientTools from SQLite.\n * Called in the constructor so these values survive DO hibernation.\n * @internal\n */\n private _restoreRequestContext() {\n const rows =\n this.sql<{ key: string; value: string }>`\n select key, value from cf_ai_chat_request_context\n ` || [];\n\n for (const row of rows) {\n try {\n if (row.key === \"lastBody\") {\n this._lastBody = JSON.parse(row.value);\n } else if (row.key === \"lastClientTools\") {\n this._lastClientTools = JSON.parse(row.value);\n }\n } catch {\n // Corrupted row — ignore and let the next request overwrite it\n }\n }\n }\n\n /**\n * Persist _lastBody and _lastClientTools to SQLite so they survive hibernation.\n * Uses upsert (INSERT OR REPLACE) so repeated calls are safe.\n * @internal\n */\n private _persistRequestContext() {\n // Persist or delete body\n if (this._lastBody) {\n this.sql`\n insert or replace into cf_ai_chat_request_context (key, value)\n values ('lastBody', ${JSON.stringify(this._lastBody)})\n `;\n } else {\n this.sql`delete from cf_ai_chat_request_context where key = 'lastBody'`;\n }\n // Persist or delete client tools\n if (this._lastClientTools) {\n this.sql`\n insert or replace into cf_ai_chat_request_context (key, value)\n values ('lastClientTools', ${JSON.stringify(this._lastClientTools)})\n `;\n } else {\n this\n .sql`delete from cf_ai_chat_request_context where key = 'lastClientTools'`;\n }\n }\n\n /**\n * User message ids a WebSocket chat request originated from (#2280), keyed\n * by request id while the request is handled. After that (or after a\n * restart) the request's stream metadata is the fallback.\n */\n private _requestOriginMessageIds = new Map<string, string[]>();\n\n private _originMessageIdsFor(requestId: string): string[] | undefined {\n return (\n this._requestOriginMessageIds.get(requestId) ??\n this._resumableStream.getOriginMessageIds(requestId) ??\n this._activeChatRecoveryOriginIds\n );\n }\n\n private _withOriginMessageIds(message: OutgoingMessage): OutgoingMessage {\n if (\n message.type !== MessageType.CF_AGENT_USE_CHAT_RESPONSE ||\n !(message.done || message.error)\n ) {\n return message;\n }\n return withOriginMessageIds(message, this._originMessageIdsFor(message.id));\n }\n\n private _broadcastChatMessage(message: OutgoingMessage, exclude?: string[]) {\n message = this._withOriginMessageIds(message);\n if (\n message.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE &&\n (message.done || message.error)\n ) {\n const held = this._heldTerminalFrames.get(message.id);\n if (held) {\n held.push({ message, exclude });\n return;\n }\n }\n // Combine explicit exclusions with connections pending stream resume.\n // Pending connections should not receive live stream chunks until they ACK,\n // at which point they'll receive the full replay via _sendStreamChunks.\n const allExclusions = [\n ...(exclude || []),\n ...this._pendingResumeConnections\n ];\n this.broadcast(JSON.stringify(message), allExclusions);\n }\n\n /**\n * `useAgentChat` flips to ready on the terminal `done` frame, and a message\n * the user sends after that is replaced by any transcript broadcast that\n * arrives later. So while `_reply` owns a request, its terminal frames (the\n * `done` frame, and an in-band `error` frame, which clients also treat as\n * terminal) are held here in order and sent only after the assistant message\n * is persisted and broadcast.\n */\n private _heldTerminalFrames = new Map<\n string,\n Array<{ message: OutgoingMessage; exclude?: string[] }>\n >();\n\n private _releaseTerminalFrames(id: string, errorText?: string): void {\n const held = this._heldTerminalFrames.get(id);\n this._heldTerminalFrames.delete(id);\n if (!held) return;\n const failed =\n errorText !== undefined &&\n !held.some(\n ({ message }) =>\n message.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE &&\n message.error\n );\n for (const { message, exclude } of held) {\n this._broadcastChatMessage(\n failed && message.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE\n ? {\n ...message,\n body: errorText,\n error: true,\n ...(message.done && { outcome: \"error\" as const })\n }\n : message,\n exclude\n );\n }\n }\n\n /**\n * Broadcasts a text event for non-SSE responses.\n * This ensures plain text responses follow the AI SDK v5 stream protocol.\n *\n * @param streamId - The stream identifier for chunk storage\n * @param event - The text event payload (text-start, text-delta with delta, or text-end)\n * @param continuation - Whether this is a continuation of a previous stream\n */\n private async _broadcastTextEvent(\n streamId: string,\n event:\n | { type: \"text-start\"; id: string }\n | { type: \"text-delta\"; id: string; delta: string }\n | { type: \"text-end\"; id: string },\n continuation: boolean\n ) {\n const body = JSON.stringify(event);\n const seq = await this._storeStreamChunk(streamId, body);\n this._broadcastChatMessage({\n body,\n done: false,\n id: event.id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n ...(seq !== undefined && { seq }),\n ...(continuation && { continuation: true })\n });\n }\n\n /**\n * Lift ai-chat's legacy flat table into the default Sessions chain.\n *\n * Runs in `onStart` (before hydration), not in the constructor: the lift is\n * an async import through Sessions, and the constructor does no session\n * storage work at all.\n *\n * Order is read first as ids alone, then message bodies are fetched in\n * windows bounded by row count and bytes, so a large transcript never sits\n * in the isolate at once. Once every readable row has a copy the legacy\n * table is DROPPED rather than renamed: keeping it would leave the object\n * holding its history twice.\n */\n private async _migrateLegacyMessages(): Promise<void> {\n const present =\n this.ctx.storage.sql\n .exec(\n `SELECT name FROM sqlite_master\n WHERE type = 'table' AND name = 'cf_ai_chat_agent_messages'`\n )\n .toArray().length > 0;\n if (!present) return;\n\n // Ids and sizes only: the ordering pass must not carry message bodies.\n const order = this.sql<{\n id: string;\n bytes: number;\n created_at: string | number | null;\n }>`\n SELECT id, LENGTH(CAST(message AS BLOB)) AS bytes, created_at\n FROM cf_ai_chat_agent_messages\n ORDER BY created_at ASC, rowid ASC\n `;\n\n let parentId: string | null = null;\n let imported = 0;\n let skipped = 0;\n let index = 0;\n while (index < order.length) {\n const window: typeof order = [];\n let bytes = 0;\n while (\n index < order.length &&\n window.length < LEGACY_LIFT_WINDOW_ROWS &&\n (window.length === 0 ||\n bytes + order[index].bytes <= LEGACY_LIFT_WINDOW_BYTES)\n ) {\n bytes += order[index].bytes;\n window.push(order[index]);\n index++;\n }\n const ids = JSON.stringify(window.map((row) => row.id));\n const bodies = new Map(\n this.sql<{ id: string; message: string }>`\n SELECT id, message FROM cf_ai_chat_agent_messages\n WHERE id IN (SELECT value FROM json_each(${ids}))\n `.map((row) => [row.id, row.message] as const)\n );\n\n for (const row of window) {\n const body = bodies.get(row.id);\n if (body === undefined) {\n skipped++;\n continue;\n }\n try {\n const parsed: unknown = JSON.parse(body);\n const message = autoTransformMessages([parsed])[0];\n if (!message || !isValidMessageStructure(message)) {\n console.warn(\n `[AIChatAgent] Skipping invalid legacy message ${row.id}: ` +\n \"missing or malformed id, role, or parts\"\n );\n skipped++;\n continue;\n }\n const parsedTime =\n typeof row.created_at === \"number\"\n ? row.created_at\n : Date.parse(String(row.created_at ?? \"\"));\n await this.#session.importMessage(message, {\n parentId,\n createdAt: Number.isFinite(parsedTime) ? parsedTime : imported\n });\n parentId = message.id;\n imported++;\n } catch (error) {\n console.error(`Failed to migrate message ${row.id}:`, error);\n skipped++;\n }\n }\n }\n\n // Drop the source ONLY when every row actually landed. A skipped row is\n // one that could not be parsed or imported, and dropping the table then\n // would delete it permanently — accounting for a row is not the same as\n // migrating it. The lift is idempotent (`importMessage` ignores ids it\n // already has), so leaving the table means a later start retries the rows\n // that failed rather than losing them.\n if (skipped === 0 && imported === order.length) {\n this.ctx.storage.sql.exec(\"DROP TABLE cf_ai_chat_agent_messages\");\n return;\n }\n console.error(\n `[AIChatAgent] Legacy lift imported ${imported} of ${order.length} rows ` +\n `(${skipped} skipped); leaving cf_ai_chat_agent_messages in place so ` +\n \"they remain recoverable.\"\n );\n }\n\n /**\n * Hydrate `this.messages` once per wake, bounded by\n * {@link hydrationByteBudget}. This is the only transcript read on the\n * startup path; every later change arrives through the Sessions change\n * feed.\n */\n private async _hydrateMessages(): Promise<void> {\n const budget = this.hydrationByteBudget;\n const stored =\n Number.isFinite(budget) && budget > 0\n ? (await this.#session.getRecentHistory(budget)).messages\n : await this.#session.getHistory();\n\n const messages: UIMessage[] = [];\n for (const message of stored as unknown[]) {\n if (!isValidMessageStructure(message)) {\n console.warn(\n `[AIChatAgent] Skipping invalid message ${(message as { id?: unknown } | null)?.id}: ` +\n \"missing or malformed id, role, or parts\"\n );\n continue;\n }\n messages.push(message);\n }\n // Automatic migration following https://jhak.im/blog/ai-sdk-migration-handling-previously-saved-messages\n this.messages = autoTransformMessages(messages);\n }\n\n /**\n * Mirror `this.messages` from the Sessions change feed. Every durable write\n * dispatches here synchronously, so write sites never hand-patch the\n * cache.\n */\n #subscribeToSessionChanges(): void {\n this.#session.mirror<UIMessage>({\n get: () => this.messages,\n set: (messages) => {\n this.messages = messages;\n },\n transform: (message) => this.#messageForCache(message)\n });\n }\n\n /**\n * Turn a stored row into its in-memory form. A stored row is exactly what\n * the write returned, so this never costs a re-read.\n */\n #messageForCache(message: SessionMessage): UIMessage {\n const stored = message as UIMessage;\n return autoTransformMessages([stored])[0] ?? stored;\n }\n\n /**\n * Serialize the whole transcript as a JSON array of messages without ever\n * holding it in one string: `historyBatches()` yields bounded batches and\n * each batch is encoded straight into the response body.\n */\n #streamMessagesAsJson(): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n const batches = this.#session.historyBatches();\n let opened = false;\n let first = true;\n return new ReadableStream<Uint8Array>({\n pull: async (controller) => {\n if (!opened) {\n opened = true;\n controller.enqueue(encoder.encode(\"[\"));\n return;\n }\n const next = await batches.next();\n if (next.done) {\n controller.enqueue(encoder.encode(\"]\"));\n controller.close();\n return;\n }\n let chunk = \"\";\n for (const message of autoTransformMessages(\n next.value as UIMessage[]\n )) {\n chunk += `${first ? \"\" : \",\"}${JSON.stringify(message)}`;\n first = false;\n }\n if (chunk.length > 0) controller.enqueue(encoder.encode(chunk));\n },\n cancel: async () => {\n await batches.return?.(undefined);\n }\n });\n }\n\n private async _tryCatchChat<T>(fn: () => T | Promise<T>) {\n try {\n return await fn();\n } catch (e) {\n throw this.onError(e);\n }\n }\n\n private isChatTurnActive(): boolean {\n return this._turnQueue.isActive;\n }\n\n /**\n * Wait until the agent is fully idle — both the turn queue is drained\n * AND no submits are in flight between the concurrency decision and\n * `_runExclusiveChatTurn` (mid-`persistMessages` etc.).\n *\n * Just awaiting `_turnQueue.waitForIdle()` would miss submits whose\n * handlers have bumped `_latestOverlappingSubmitSequence` and\n * incremented `_pendingEnqueueCount` but haven't yet reached\n * `_runExclusiveChatTurn` — those would race with anything calling\n * `waitForIdle()` (tests, `waitUntilStable`, recovery code).\n */\n private async waitForIdle(): Promise<void> {\n for (;;) {\n await this._submitConcurrency.waitForIdle(() =>\n this._turnQueue.waitForIdle()\n );\n // An armed coalesce timer / in-flight barrier drain means an\n // auto-continuation decision is imminent (#1650): it will either enqueue\n // a continuation turn (re-busying the queue) or park on an incomplete\n // batch. Wait for that decision to resolve before reporting idle so a\n // debounced continuation isn't missed by idle observers (tests,\n // recovery).\n if (!this._hasArmedContinuation()) return;\n await new Promise<void>((resolve) =>\n setTimeout(resolve, AutoContinuationController.COALESCE_MS)\n );\n }\n }\n\n /**\n * `true` when an auto-continuation is armed and going to fire on its own —\n * its coalesce timer is still pending or its completeness barrier is\n * mid-drain (#1650). Such an agent is NOT idle/stable: a continuation turn is\n * imminent, so idle observers (recovery, idle-eviction, tests) must keep\n * waiting until it either enqueues a turn or parks on an incomplete batch.\n * A continuation that has already entered its turn (`pastCoalesce`) is\n * covered by the turn queue, and a parked one (waiting on an unanswered\n * sibling) is covered by `hasPendingInteraction()`, so neither is reported\n * here.\n */\n private _hasArmedContinuation(): boolean {\n return (\n this._continuation.pending !== null &&\n !this._continuation.pending.pastCoalesce &&\n this._autoContinuation.isArmed()\n );\n }\n\n private _getSubmitConcurrencyDecision(\n trigger: ChatRequestTrigger\n ): SubmitConcurrencyDecision {\n const decision = this._submitConcurrency.decide({\n concurrency: this.messageConcurrency,\n isSubmitMessage: trigger === \"submit-message\",\n queuedTurns: this._turnQueue.queuedCount()\n });\n\n if (decision.strategy === \"merge\") {\n if (\n !this._mergeQueuedUserStartIndexByEpoch.has(this._turnQueue.generation)\n ) {\n this._mergeQueuedUserStartIndexByEpoch.set(\n this._turnQueue.generation,\n this.messages.length\n );\n }\n }\n\n return decision;\n }\n\n private async _mergeQueuedUserMessages(\n epoch = this._turnQueue.generation\n ): Promise<void> {\n const mergedMessages = this._getMergedQueuedUserMessages(epoch);\n if (!mergedMessages) {\n return;\n }\n\n await this.persistMessages(mergedMessages, [], {\n _deleteStaleRows: true\n });\n }\n\n private _getMergedQueuedUserMessages(epoch: number): UIMessage[] | null {\n const queuedUserStart = this._mergeQueuedUserStartIndexByEpoch.get(epoch);\n if (queuedUserStart === undefined) {\n return null;\n }\n\n let queuedUserEnd = queuedUserStart;\n while (this.messages[queuedUserEnd]?.role === \"user\") {\n queuedUserEnd++;\n }\n\n if (\n queuedUserEnd === queuedUserStart &&\n queuedUserStart < this.messages.length\n ) {\n console.warn(\n `[AIChatAgent] merge: expected user messages at index ${queuedUserStart} ` +\n `but found role=\"${this.messages[queuedUserStart]?.role}\"; skipping merge`\n );\n }\n\n const queuedUserMessages = this.messages.slice(\n queuedUserStart,\n queuedUserEnd\n );\n if (queuedUserMessages.length < 2) {\n return null;\n }\n\n return [\n ...this.messages.slice(0, queuedUserStart),\n AIChatAgent._mergeUserMessages(queuedUserMessages),\n ...this.messages.slice(queuedUserEnd)\n ];\n }\n\n private static _mergeUserMessages(messages: UIMessage[]): UIMessage {\n const [firstMessage, ...remainingMessages] = messages;\n if (!firstMessage) {\n throw new Error(\"cannot merge an empty message list\");\n }\n\n let mergedParts = AIChatAgent._cloneMessageParts(firstMessage.parts);\n for (const message of remainingMessages) {\n AIChatAgent._appendMergedText(mergedParts, \"\\n\\n\");\n mergedParts = AIChatAgent._mergeMessageParts(mergedParts, message.parts);\n }\n\n const lastMessage = messages[messages.length - 1] ?? firstMessage;\n return {\n ...lastMessage,\n parts: mergedParts\n };\n }\n\n private static _mergeMessageParts(\n currentParts: UIMessage[\"parts\"],\n nextParts: UIMessage[\"parts\"]\n ): UIMessage[\"parts\"] {\n const mergedParts = AIChatAgent._cloneMessageParts(currentParts);\n\n for (const part of nextParts) {\n if (part.type === \"text\") {\n AIChatAgent._appendMergedText(mergedParts, part.text);\n continue;\n }\n\n mergedParts.push(part);\n }\n\n return mergedParts;\n }\n\n private static _cloneMessageParts(\n parts: UIMessage[\"parts\"]\n ): UIMessage[\"parts\"] {\n return [...parts];\n }\n\n private static _appendMergedText(\n parts: UIMessage[\"parts\"],\n text: string\n ): void {\n if (text.length === 0) {\n return;\n }\n\n const lastPart = parts[parts.length - 1];\n if (lastPart?.type === \"text\") {\n parts[parts.length - 1] = {\n ...lastPart,\n text: lastPart.text + text\n };\n return;\n }\n\n const textPart: TextUIPart = {\n type: \"text\",\n text\n };\n parts.push(textPart);\n }\n\n private _setRequestContext(\n clientTools?: ClientToolSchema[],\n body?: Record<string, unknown>\n ) {\n this._lastClientTools = clientTools?.length ? clientTools : undefined;\n this._lastBody = body && Object.keys(body).length > 0 ? body : undefined;\n this._persistRequestContext();\n }\n\n private _messagesForClientSync(): readonly UIMessage[] {\n if (!this._streamingMessage || this._streamingMessage.parts.length === 0) {\n return this.messages;\n }\n\n const existingIdx = this.messages.findIndex(\n (message) => message.id === this._streamingMessage?.id\n );\n\n if (existingIdx >= 0) {\n return this.messages.map((message, idx) =>\n idx === existingIdx && this._streamingMessage\n ? this._streamingMessage\n : message\n );\n }\n\n return [...this.messages, this._streamingMessage];\n }\n\n private _sendDirectMessage(\n connection: Connection,\n message: OutgoingMessage\n ): void {\n try {\n connection.send(JSON.stringify(message));\n } catch {\n // Connection closed before the server could reply.\n }\n }\n\n private _completeSkippedRequest(connection: Connection, requestId: string) {\n this._sendDirectMessage(\n connection,\n this._withOriginMessageIds({\n body: \"\",\n done: true,\n id: requestId,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n outcome: \"skipped\"\n })\n );\n // A skipped turn settles out of the pre-stream set, but must NOT release\n // parked connections (#1784): a skip happens because a NEWER turn was\n // admitted (latest/merge supersede) or the queue generation advanced. The\n // earliest \"successor exists\" signal (`SubmitConcurrencyController.decide`)\n // fires before the successor's `_preStream.begin()`, so releasing here would\n // race a `begin()` that hasn't run yet and cut a parked client loose right\n // before the successor streams. Leave it parked: the successor flushes it on\n // `_startStream`, or the final surviving turn's settle releases it. (Chat\n // clear releases parked connections explicitly via `resetTurnState`.)\n this._settlePreStreamTurn(requestId, { releaseParked: false });\n }\n\n /** Whether a connection with this id is still attached. */\n private _isConnectionPresent(connectionId: string): boolean {\n return this.getConnection(connectionId) !== undefined;\n }\n\n /**\n * Mark an accepted turn (#1784) as settled. When `releaseParked` (the default)\n * and no accepted turn remains in flight and no stream is active, release every\n * parked connection with STREAM_RESUME_NONE so a client that reconnected during\n * the pre-stream window stops waiting. A no-op when the parked set was already\n * flushed on stream start. Skip paths pass `releaseParked: false` so a parked\n * client survives onto the successor turn (see `_completeSkippedRequest`).\n */\n private _settlePreStreamTurn(\n requestId: string,\n options: { releaseParked?: boolean } = {}\n ): void {\n const idle = this._preStream.settle(requestId);\n const releaseParked = options.releaseParked ?? true;\n if (releaseParked && idle && !this._resumableStream.hasActiveStream()) {\n this._preStream.releaseAwaiting();\n }\n }\n\n private _rollbackDroppedSubmit(connection: Connection) {\n this._sendDirectMessage(connection, {\n messages: this._messagesForClientSync(),\n type: MessageType.CF_AGENT_CHAT_MESSAGES\n });\n }\n\n /** `true` when an assistant message is waiting on a client tool result or approval. */\n protected hasPendingInteraction(): boolean {\n if (\n this._streamingMessage &&\n this._messageHasPendingInteraction(this._streamingMessage)\n ) {\n return true;\n }\n\n return this.messages.some(\n (message) =>\n message.role === \"assistant\" &&\n this._messageHasPendingInteraction(message)\n );\n }\n\n /**\n * Waits until the conversation is fully stable — no active stream, no\n * pending client-tool interactions, and no queued continuation turns.\n *\n * Returns `true` when stable. Returns `false` if `timeout` expires before\n * a pending interaction resolves. Safe to call at any time; if there is\n * nothing pending it returns immediately.\n *\n * `pendingInteraction` overrides which \"still waiting\" predicate gates\n * stability. It defaults to the broad {@link hasPendingInteraction} (any\n * `input-available` / `approval-requested` part) to preserve the documented\n * semantics for app overrides. The recovery paths pass the narrower\n * {@link hasPendingClientInteraction} so a DEAD server-tool `input-available`\n * orphan (its `execute()` died with the evicted isolate; nothing will resolve\n * it) does NOT block stability — recovery then repairs it to an errored\n * result and continues, instead of waiting until the budget is spent. This\n * mirrors `@cloudflare/think`, whose single pending predicate is already\n * client-only by construction.\n */\n protected async waitUntilStable(options?: {\n timeout?: number;\n pendingInteraction?: () => boolean;\n }): Promise<boolean> {\n const deadline =\n options?.timeout != null ? Date.now() + options.timeout : null;\n const hasPendingInteraction =\n options?.pendingInteraction ?? (() => this.hasPendingInteraction());\n\n while (true) {\n // Drain active turns AND any in-flight submits past the concurrency\n // decision (mid-`persistMessages`) so `hasPendingInteraction()`\n // reflects settled message state rather than in-flight streaming\n // state. Just `_turnQueue.waitForIdle()` would miss submits whose\n // handlers have bumped `_latestOverlappingSubmitSequence` and\n // incremented `_pendingEnqueueCount` but haven't yet enqueued.\n while (true) {\n if (\n (await this._awaitWithDeadline(\n this._turnQueue.waitForIdle(),\n deadline\n )) === TIMED_OUT\n ) {\n return false;\n }\n if (this._submitConcurrency.pendingEnqueueCount === 0) break;\n if (\n (await this._awaitWithDeadline(\n new Promise<void>((resolve) => setTimeout(resolve, 5)),\n deadline\n )) === TIMED_OUT\n ) {\n return false;\n }\n }\n\n if (!hasPendingInteraction()) {\n if (!this._hasArmedContinuation()) {\n return true;\n }\n // An auto-continuation is armed (#1650) — not stable yet. Wait for it\n // to fire (enqueuing a turn the outer loop then drains) or park, then\n // re-check.\n if (\n (await this._awaitWithDeadline(\n new Promise<void>((resolve) =>\n setTimeout(resolve, AutoContinuationController.COALESCE_MS)\n ),\n deadline\n )) === TIMED_OUT\n ) {\n return false;\n }\n continue;\n }\n\n const pending = this._pendingInteractionPromise;\n if (pending) {\n let result: boolean | typeof TIMED_OUT;\n try {\n result = await this._awaitWithDeadline(pending, deadline);\n } catch {\n continue;\n }\n\n if (result === TIMED_OUT) {\n return false;\n }\n } else {\n // No tool result/approval apply is currently in flight; we are still\n // waiting for the user to resolve the interaction.\n if (\n (await this._awaitWithDeadline(\n new Promise<void>((resolve) => setTimeout(resolve, 100)),\n deadline\n )) === TIMED_OUT\n ) {\n return false;\n }\n }\n }\n }\n\n private abortActiveTurn(): boolean {\n if (!this._turnQueue.activeRequestId) {\n return false;\n }\n\n this._abortRegistry.cancel(this._turnQueue.activeRequestId);\n return true;\n }\n\n /**\n * Aborts the active turn and invalidates queued continuations. Call this\n * when intercepting `CF_AGENT_CHAT_CLEAR` before the SDK sees the message —\n * the built-in handler calls it automatically.\n */\n protected resetTurnState(): void {\n this._mergeQueuedUserStartIndexByEpoch.delete(this._turnQueue.generation);\n this._turnQueue.reset();\n this._abortRegistry.destroyAll();\n this._submitConcurrency.reset();\n this._pendingInteractionPromise = null;\n // Drop the apply chain so new interactions don't serialize behind a stale\n // (possibly hung) apply from the turn we just reset (#1649).\n this._interactionApplyTail = Promise.resolve();\n // Tear down the event-driven auto-continuation barrier (#1650): cancel the\n // coalesce timer and clear the double-fire / stream-active gates so a reset\n // mid-park can't leave a stale flag pinning future continuations.\n this._autoContinuation.reset();\n this._streamingTurnActive = false;\n this._continuation.sendResumeNone();\n this._continuation.clearAll();\n this._preStream.releaseAwaiting();\n this._preStream.reset();\n this._pendingChatResponseResults.length = 0;\n }\n\n /**\n * Abort a single in-flight chat turn by request id.\n *\n * Equivalent to the cancel path that fires when a client sends a\n * `chat-request-cancel` WebSocket message — the inference loop's\n * signal aborts and the turn's `ChatResponseResult` reports\n * `status: \"aborted\"`. No-op if no controller exists for `requestId`.\n *\n * Most callers don't have the request id and want\n * {@link abortAllRequests} instead. Prefer\n * {@link SaveMessagesOptions.signal} when driving a turn\n * programmatically — it threads the abort intent in from the start\n * without requiring the caller to know the id.\n */\n protected abortRequest(requestId: string, reason?: unknown): void {\n this._abortRegistry.cancel(requestId, reason);\n }\n\n /**\n * A cancel can land while the turn's recovery is waiting out its backoff,\n * with nothing in flight to abort: cancel the scheduled recovery instead,\n * so the queued callback bails when it fires.\n */\n private async _cancelScheduledRecovery(requestId: string): Promise<void> {\n try {\n await this._chatRecoveryEngine().cancelScheduledRecovery(requestId);\n } catch (error) {\n console.error(\n \"[AIChatAgent] failed to cancel a scheduled chat recovery\",\n error\n );\n }\n }\n\n /**\n * Abort every in-flight chat turn on this agent.\n *\n * Aborts all controllers in the registry and clears it. Used by\n * subclasses that drive single-purpose turns (e.g. an RPC-driven\n * sub-agent helper that runs one turn at a time) and want a coarse\n * \"cancel whatever is running\" handle without tracking request ids.\n *\n * Does NOT reset queued turns, continuation timers, or submit\n * concurrency state — use {@link resetTurnState} for the full\n * teardown that runs on `chat-clear`.\n */\n protected abortAllRequests(reason?: unknown): void {\n this._abortRegistry.destroyAll(reason);\n }\n\n private _awaitWithDeadline<T>(\n promise: Promise<T>,\n deadline: number | null\n ): Promise<T | typeof TIMED_OUT> {\n return awaitWithDeadline(promise, deadline);\n }\n\n private _messageHasPendingInteraction(message: UIMessage): boolean {\n return message.parts.some(\n (part) =>\n \"state\" in part &&\n (part.state === \"input-available\" ||\n part.state === \"approval-requested\")\n );\n }\n\n /**\n * `true` when the turn is parked on a pending interaction that the CLIENT can\n * still resolve after a restart — an `approval-requested` part, or an\n * `input-available` part for a CLIENT tool (no server `execute`) whose\n * `tool-result` the SPA replays over the WebSocket on reconnect.\n *\n * This is intentionally NARROWER than `hasPendingInteraction()` (which\n * `waitUntilStable` uses): a SERVER tool's `input-available` orphan is\n * excluded, because its `execute()` promise died with the evicted isolate and\n * nothing will ever post its result — so it must NOT be treated as a healthy\n * \"waiting on the human\" wait. Used to make a HITL turn budget-free during\n * recovery so a slow human can't trip the no-progress / attempt / stable-\n * timeout budgets; see `_beginChatRecoveryIncident` and\n * `_parkRecoveryForPendingInteraction`. Mirrors `@cloudflare/think`'s\n * `hasPendingInteraction`, which is already client-only by construction.\n */\n protected hasPendingClientInteraction(): boolean {\n const clientResolvable = this._clientResolvableToolNames();\n if (\n this._streamingMessage &&\n this._messageAwaitsClientInteraction(\n this._streamingMessage,\n clientResolvable\n )\n ) {\n return true;\n }\n return this.messages.some(\n (message) =>\n message.role === \"assistant\" &&\n this._messageAwaitsClientInteraction(message, clientResolvable)\n );\n }\n\n private _messageAwaitsClientInteraction(\n message: UIMessage,\n clientResolvable: Set<string>\n ): boolean {\n return message.parts.some((part) =>\n this._partAwaitsClientInteraction(part, clientResolvable)\n );\n }\n\n /**\n * Whether a part is still awaiting a CLIENT interaction that can genuinely\n * arrive after a restart: an `approval-requested` part (a reconnecting client\n * replays the approval) or an `input-available` part for a CLIENT tool (the\n * SPA replays the `tool-result`). A SERVER tool's `input-available` is NOT\n * pending — its `execute()` died with the isolate. Mirrors `@cloudflare/think`.\n */\n private _partAwaitsClientInteraction(\n part: UIMessage[\"parts\"][number],\n clientResolvable: Set<string>\n ): boolean {\n return partAwaitsClientInteraction(part, clientResolvable);\n }\n\n /**\n * Names of the CLIENT-resolvable tools (the client-provided schemas from the\n * last request, which have no server `execute`). Mirrors `@cloudflare/think`.\n */\n private _clientResolvableToolNames(): Set<string> {\n return clientResolvableToolNames(this._lastClientTools);\n }\n\n /**\n * Run a chat turn exclusively so `_reply()` never overlaps with another\n * streaming turn.\n */\n private async _runExclusiveChatTurn<T>(\n requestId: string,\n fn: () => Promise<T>,\n options?: { epoch?: number; onStale?: () => void }\n ): Promise<T> {\n const generation = options?.epoch;\n let result: TurnResult<T>;\n try {\n result = await this._turnQueue.enqueue(\n requestId,\n () =>\n // A turn owns its own traced boundary, never that of whatever\n // admitted it: an auto-continuation fires from a coalescing timer\n // long after the handler that armed it returned, and a turn started\n // without being awaited outlives its caller. Either way the caller's\n // boundary would close every span in a turn that is still running.\n withInvocationScope(\n () =>\n withAgentSpan(\n this,\n \"chat_turn\",\n \"turn\",\n {\n \"cloudflare.agents.component\": \"ai_chat\",\n \"cloudflare.agents.turn.request_id\": requestId,\n \"cloudflare.agents.turn.admission\": \"queue\",\n \"cloudflare.agents.turn.generation\": generation\n },\n fn\n ),\n { detached: true }\n ),\n { generation }\n );\n } finally {\n // Clean merge map when all turns for a generation complete\n const gen = generation ?? this._turnQueue.generation;\n if (this._turnQueue.queuedCount(gen) === 0) {\n this._mergeQueuedUserStartIndexByEpoch.delete(gen);\n }\n\n if (\n this._pendingChatResponseResults.length > 0 &&\n !this._insideResponseHook\n ) {\n this._insideResponseHook = true;\n try {\n await this.keepAliveWhile(async () => {\n while (this._pendingChatResponseResults.length > 0) {\n const chatResult = this._pendingChatResponseResults.shift()!;\n // A later turn that ends in a non-error outcome supersedes any\n // pending terminal record (#1645) — both a successful turn and an\n // aborted one (the conversation has moved on either way; only a\n // fresh error should leave a terminal to replay). The\n // client-request handler already clears on a new submit; this\n // covers turns driven purely server-side (`saveMessages`,\n // auto-continuation) with no client request in between, so a\n // stale exhaustion can't replay on a later reconnect. Mirrors\n // Think's `_recordTerminalChatStatus`, which clears on any\n // non-error/non-interrupted status.\n if (\n chatResult.status === \"completed\" ||\n chatResult.status === \"aborted\"\n ) {\n await this._clearChatTerminal();\n } else if (chatResult.status === \"error\") {\n // A terminal (non-recovered) error — e.g. a provider 500 surfaced\n // as a stream `error` part — has no durable trace otherwise, so a\n // client disconnected at this moment never learns the turn failed\n // and stays frozen on reconnect (#1645). Record it so it replays\n // over the resume handshake (shared\n // `ResumeHandshake._replayTerminalOnResume`). Mirrors\n // Think's `_fireResponseHook`, which records on `error` too.\n // Recoverable failures (deploy/eviction/stall) don't arrive here\n // as `error` — they reach the drain loop as `aborted`, or not at\n // all (the isolate is gone), and exhaustion records its own\n // terminal — so this can't pre-empt recovery.\n await this._recordChatTerminal(\n chatResult.requestId,\n chatResult.error ?? \"The assistant encountered an error.\"\n );\n }\n try {\n await this.onChatResponse(chatResult);\n } catch (hookError) {\n console.error(\"[AIChatAgent] onChatResponse threw:\", hookError);\n }\n }\n });\n } finally {\n this._insideResponseHook = false;\n }\n }\n }\n\n if (result!.status === \"stale\") {\n options?.onStale?.();\n return undefined as T;\n }\n return result!.value;\n }\n\n /**\n * Schedule an auto-continuation for a tool result/approval that opted in with\n * `autoContinue: true` (#1650). Thin host wrapper that builds the\n * {@link ContinuationSpec} and delegates to the shared\n * {@link AutoContinuationController}, which owns the coalesce timer and the\n * completeness-gated fire (shared with `@cloudflare/think`).\n */\n private _scheduleAutoContinuation(\n connection: Connection,\n clientTools: ClientToolSchema[] | undefined,\n body: Record<string, unknown> | undefined,\n errorPrefix: string\n ) {\n this._autoContinuation.schedule({\n connection,\n clientTools,\n body,\n errorPrefix\n });\n }\n\n /**\n * Re-arm the barrier for a result/approval that arrived WITHOUT `autoContinue`\n * (#1650). A standalone errored result declines to continue on its own, but in\n * a parallel batch a SIBLING may already have opted in — and this result can be\n * the one that completes the batch, so we must re-run the barrier check. Unlike\n * `_scheduleAutoContinuation` this NEVER creates a pending continuation (a\n * standalone errored tool with no opted-in sibling must not auto-continue), and\n * it no-ops once the continuation is running (`pastCoalesce`).\n */\n private _rearmPendingAutoContinuationForBatch(): void {\n this._autoContinuation.rearmForBatch();\n }\n\n /**\n * Called when a streaming assistant turn finalizes (its message, with ALL tool\n * parts, is now persisted). Clears the stream-active gate and re-runs the\n * barrier for a continuation the gate held (#1650). Essential for an all-fast\n * parallel batch whose every result landed mid-stream: once the stream ends\n * there is no further tool-result event to re-arm, so without this the held\n * continuation would never fire. A slow batch is re-checked here and simply\n * keeps holding (event-driven) until its remaining siblings answer.\n */\n private _onStreamingTurnFinalized(finishReason?: string): void {\n this._streamingTurnActive = false;\n\n // A tool result or approval can leave an auto-continuation pending while the\n // original AI SDK stream is still active. If that stream then finishes with\n // a normal assistant response, the continuation is stale: firing it would\n // replay a transcript ending in assistant text. Modern Anthropic models\n // reject that request as an unsupported assistant prefill (#1618, #2171).\n // A sibling tool call still awaiting its result keeps the continuation:\n // the stream's text did not answer it, and the continuation is the only\n // record of the batch's opt-in.\n if (\n finishReason === \"stop\" &&\n this._continuation.pending &&\n !this._hasIncompleteToolBatch()\n ) {\n this._clearPendingAutoContinuation(true);\n return;\n }\n\n this._autoContinuation.rearmForBatch();\n }\n\n /**\n * Drain every in-flight tool-result/approval apply, including any enqueued\n * while we wait, so the subsequent `_hasIncompleteToolBatch()` re-check sees\n * every result that has ALREADY arrived. Bounded by real apply activity (a\n * storage write each), never by a fixed timer: the loop re-reads\n * `_interactionApplyTail` after each await because a sibling can extend the\n * tail mid-drain, and stops once the tail stops advancing. Mirrors\n * `@cloudflare/think`'s `_drainInteractionApplies`.\n */\n private _drainInteractionApplies(): Promise<void> {\n return drainInteractionApplies(\n () => this._continuation.pending !== null,\n () => this._interactionApplyTail\n );\n }\n\n /**\n * `true` when the latest assistant message is mid-batch: it carries at least\n * one settled tool result AND at least one tool call/approval still awaiting a\n * client result. That is the #1649 signature — the model fanned out parallel\n * tool calls and only some have been answered. Scoped to the leaf (the step\n * the continuation answers) so an unrelated dangling tool in an earlier\n * message doesn't block a legitimate follow-up continuation.\n */\n private _hasIncompleteToolBatch(): boolean {\n return hasIncompleteToolBatch(this.messages);\n }\n\n private _fireAutoContinuation() {\n const pending = this._continuation.pending;\n if (!pending) return;\n const requestId = pending.requestId;\n\n const epoch = this._turnQueue.generation;\n // _runExclusiveChatTurn must be called synchronously so the chat turn\n // queue is set up immediately — otherwise waitForIdle() can resolve\n // before the continuation starts. keepAlive() is called inside the\n // turn to prevent hibernation while streaming, without deferring the queue\n // registration.\n this._runExclusiveChatTurn(\n requestId,\n async () => {\n const dispose = await this.keepAlive();\n try {\n const connection = this._continuation.pending?.connection;\n if (!connection) {\n this._clearAllAutoContinuationState(true);\n return;\n }\n\n const clientTools = this._continuation.pending?.clientTools;\n const body = this._continuation.pending?.body;\n if (this._continuation.pending) {\n this._continuation.pending.pastCoalesce = true;\n }\n\n const abortSignal = this._abortRegistry.getSignal(requestId);\n\n return this._tryCatchChat(async () => {\n return agentContext.run(\n {\n agent: this,\n connection,\n request: undefined,\n email: undefined\n },\n async () => {\n const autoContinuationBody = async () => {\n let replying = false;\n try {\n await this._repairInterruptedToolsBeforeTurn({\n continuation: true\n });\n const response = await this.onChatMessage(\n async (_finishResult) => {},\n {\n requestId,\n abortSignal,\n clientTools,\n body,\n continuation: true\n }\n );\n\n if (response) {\n const replyResult = await this._reply(\n requestId,\n response,\n [],\n {\n continuation: true,\n chatMessageId: requestId,\n onStreamStart: () => {\n replying = true;\n }\n }\n );\n if (replyResult.status === \"error\") {\n this._clearAllAutoContinuationState(true);\n return;\n }\n this._activateDeferredAutoContinuation();\n } else {\n this._clearPendingAutoContinuation(true);\n this._activateDeferredAutoContinuation();\n }\n } catch (error) {\n if (\n !replying &&\n !abortSignal?.aborted &&\n !isDurableObjectResetError(error)\n ) {\n await this._reportContinuationFailure(requestId, error);\n }\n throw error;\n } finally {\n this._abortRegistry.remove(requestId);\n }\n };\n\n await this._runChatRecoveryFiber(\n requestId,\n true,\n autoContinuationBody\n );\n }\n );\n });\n } finally {\n dispose();\n }\n },\n {\n epoch,\n onStale: () => this._clearAllAutoContinuationState(true)\n }\n ).catch((error) => {\n const errorPrefix =\n this._continuation.pending?.errorPrefix ??\n \"[AIChatAgent] Auto-continuation failed:\";\n this._clearAllAutoContinuationState(true);\n console.error(errorPrefix, error);\n });\n }\n\n /**\n * Report an auto-continuation that failed before it produced a response,\n * the way a stream error is reported: an error frame, a durable terminal\n * record, and `onChatResponse` with `status: \"error\"` for the assistant\n * message the continuation would have extended. Called inside the turn so\n * the response hook drains when the turn settles.\n */\n private async _reportContinuationFailure(\n requestId: string,\n error: unknown\n ): Promise<void> {\n const errorMessage = error instanceof Error ? error.message : String(error);\n this._broadcastChatMessage({\n body: errorMessage,\n done: true,\n error: true,\n id: requestId,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n continuation: true\n });\n const message = [...this.messages]\n .reverse()\n .find((candidate) => candidate.role === \"assistant\");\n if (message) {\n this._pendingChatResponseResults.push({\n message,\n requestId,\n continuation: true,\n status: \"error\",\n error: errorMessage\n });\n } else {\n await this._recordChatTerminal(requestId, errorMessage);\n }\n }\n\n /**\n * @returns Terminal status for the turn.\n */\n private async _runProgrammaticChatTurn(\n requestId: string,\n clientTools?: ClientToolSchema[],\n body?: Record<string, unknown>,\n externalSignal?: AbortSignal\n ): Promise<StreamResultStatus> {\n this._setRequestContext(clientTools, body);\n let wasAborted = false;\n let status: StreamResultStatus = { status: \"completed\" };\n\n await this._tryCatchChat(async () => {\n return agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n async () => {\n const abortSignal = this._abortRegistry.getSignal(requestId);\n // Wire the optional external signal to the registry's\n // controller. Detacher MUST run in `finally` to avoid leaking\n // listeners on long-lived parent signals — including the case\n // where `runFiber` itself throws (e.g. SQLite error inserting\n // the fiber row) before `programmaticBody` is ever invoked.\n const detachExternal = this._abortRegistry.linkExternal(\n requestId,\n externalSignal\n );\n try {\n const programmaticBody = async () => {\n await this._repairInterruptedToolsBeforeTurn({\n continuation: false\n });\n const response = await this.onChatMessage(() => {}, {\n requestId,\n abortSignal,\n clientTools,\n body,\n continuation: false\n });\n\n if (response) {\n status = await this._reply(requestId, response, [], {\n chatMessageId: requestId\n });\n }\n };\n\n await this._runChatRecoveryFiber(\n requestId,\n false,\n programmaticBody\n );\n } finally {\n if (abortSignal?.aborted) wasAborted = true;\n detachExternal();\n this._abortRegistry.remove(requestId);\n }\n }\n );\n });\n\n if (status.status === \"completed\" && wasAborted) {\n return { status: \"aborted\" };\n }\n return status;\n }\n\n /**\n * Handle incoming chat messages and generate a response\n * @param onFinish Callback to be called when the response is finished\n * @param options Options including abort signal and client-defined tools\n * @returns Response to send to the client or undefined\n */\n async onChatMessage(\n // oxlint-disable-next-line eslint(no-unused-vars) -- params used by subclass overrides\n _onFinish: GenerateTextOnFinishCallback<ToolSet>,\n // oxlint-disable-next-line eslint(no-unused-vars) -- params used by subclass overrides\n _options?: OnChatMessageOptions\n ): Promise<Response | undefined> {\n throw new Error(\n \"received a chat message, override onChatMessage and return a Response to send to the client\"\n );\n }\n\n /**\n * Called after a chat turn completes and the assistant message has been\n * persisted. The turn lock is released before this hook runs, so it is\n * safe to call `saveMessages` from inside.\n *\n * Fires for all turn completion paths: WebSocket chat requests,\n * `saveMessages`, and auto-continuation.\n *\n * Responses triggered from inside `onChatResponse` (e.g. via `saveMessages`)\n * do not fire `onChatResponse` recursively.\n *\n * The default implementation is a no-op.\n *\n * @param result - Information about the completed turn\n *\n * @example\n * ```ts\n * class MyAgent extends AIChatAgent<Env> {\n * protected async onChatResponse(result: ChatResponseResult) {\n * if (result.status === \"completed\") {\n * this.broadcast(JSON.stringify({ streaming: false }));\n * }\n * }\n * }\n * ```\n */\n protected onChatResponse(\n // oxlint-disable-next-line eslint(no-unused-vars) -- params used by subclass overrides\n _result: ChatResponseResult\n ): void | Promise<void> {}\n\n /**\n * Override this method to apply custom transformations to messages before\n * they are persisted to storage. This hook runs **after** the built-in\n * sanitization (OpenAI metadata stripping, Anthropic provider-executed tool\n * payload truncation, empty reasoning part filtering).\n *\n * The default implementation returns the message unchanged.\n *\n * @param message - The pre-sanitized message about to be persisted\n * @returns The transformed message to persist\n *\n * @example\n * ```ts\n * class MyAgent extends AIChatAgent<Env> {\n * protected sanitizeMessageForPersistence(\n * message: UIMessage\n * ): UIMessage {\n * return {\n * ...message,\n * parts: message.parts.map(part => {\n * if (\"output\" in part && typeof part.output === \"string\"\n * && part.output.length > 1000) {\n * return { ...part, output: \"[redacted]\" };\n * }\n * return part;\n * })\n * };\n * }\n * }\n * ```\n */\n protected sanitizeMessageForPersistence(\n // oxlint-disable-next-line eslint(no-unused-vars) -- params used by subclass overrides\n message: UIMessage\n ): UIMessage {\n return message;\n }\n\n /**\n * Convert an agent-tool input payload into the synthetic user message that\n * starts a headless `AIChatAgent` turn.\n */\n protected formatAgentToolInput(\n input: unknown,\n request: { runId: string }\n ): UIMessage {\n let text: string;\n try {\n text = typeof input === \"string\" ? input : JSON.stringify(input, null, 2);\n } catch {\n text = String(input);\n }\n\n return {\n id: `agent-tool-${request.runId}-input`,\n role: \"user\",\n parts: [{ type: \"text\", text }]\n };\n }\n\n private _agentToolProgressEmitterInstance: AgentToolProgressEmitter | null =\n null;\n\n private get _agentToolProgressEmitter(): AgentToolProgressEmitter {\n if (!this._agentToolProgressEmitterInstance) {\n this._agentToolProgressEmitterInstance = new AgentToolProgressEmitter({\n resolveActiveRun: () => {\n const requestId = this._activeRequestId;\n if (!requestId) return null;\n const runId = this._agentToolRunsByRequestId.get(requestId);\n return runId ? { runId, requestId } : null;\n },\n broadcast: (requestId, chunkBody) => {\n this._broadcastChatMessage({\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n id: requestId,\n body: chunkBody,\n done: false\n });\n },\n persistSnapshot: (runId, snapshot, at) => {\n this._ensureAgentToolTables();\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set progress_json = ${JSON.stringify(snapshot)},\n last_signal_at = ${at}\n where run_id = ${runId}\n `;\n },\n persistMilestone: (runId, name, data, at) =>\n this._persistAgentToolMilestone(runId, name, data, at)\n });\n }\n return this._agentToolProgressEmitterInstance;\n }\n\n override async reportProgress<T = unknown>(\n progress: AgentToolProgress<T>,\n options?: { persist?: boolean }\n ): Promise<void> {\n const result = this._agentToolProgressEmitter.report(progress, options);\n if (result === \"inactive\") {\n console.warn(\n \"[ai-chat] reportProgress() was called outside of an active agent-tool run; ignoring. Call it from within an onChatMessage turn that is running as a sub-agent.\"\n );\n }\n }\n\n /**\n * Override to return structured agent-tool output instead of the default\n * final assistant text.\n */\n protected getAgentToolOutput(\n _request: { runId: string; input: unknown },\n messagesAfterStart: readonly UIMessage[]\n ): unknown {\n return AIChatAgent._extractLatestAssistantText(messagesAfterStart);\n }\n\n /**\n * Override to customize the concise summary stored on the parent run.\n */\n protected getAgentToolSummary(\n _request: { runId: string; input: unknown },\n output: unknown,\n messagesAfterStart: readonly UIMessage[]\n ): string {\n if (typeof output === \"string\") return output;\n if (output === undefined) {\n return AIChatAgent._extractLatestAssistantText(messagesAfterStart) ?? \"\";\n }\n try {\n return JSON.stringify(output);\n } catch {\n return String(output);\n }\n }\n\n /** True while running inside this agent's own serialized detached-delivery\n * turn slot (set by {@link _runDetachedDelivery}); lets a `react` notify run\n * its reply inline rather than enqueuing (which would deadlock) or interleaving\n * with a foreign turn. */\n private _inSerializedDetachedDeliverySlot = false;\n\n /** Notification ids (`detached-finish:*` / `detached-ms:*`) currently being\n * injected, to dedupe a concurrent warm-tail + backbone delivery of the same\n * milestone within one isolate before the persisted message exists. */\n private _inFlightDetachedNotifications = new Set<string>();\n\n /**\n * Serialize detached terminal delivery against the chat turn queue. A\n * fast-path push or backbone tick can land mid-turn, and an `onFinish` that\n * mutates chat state (`saveMessages`, `setState`, a follow-up\n * `runAgentTool`) running concurrently with an active LLM turn is a data\n * race. Those paths never run synchronously inside a turn body (they fire\n * from `waitUntil` / a scheduled alarm), so enqueuing on the turn queue runs\n * the delivery strictly between turns without risk of self-deadlock.\n *\n * An explicit `cancelAgentTool` (`serialize` unset) may be invoked from\n * inside the very turn that triggers it, where enqueuing WOULD self-deadlock,\n * so it runs inline in the caller's (or a fresh) `agentContext`.\n */\n protected override async _runDetachedDelivery(\n invoke: () => Promise<void>,\n options?: { serialize?: boolean }\n ): Promise<void> {\n const inContext = () =>\n agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n invoke\n );\n if (!options?.serialize) {\n if (agentContext.getStore()?.agent === this) {\n await invoke();\n return;\n }\n await inContext();\n return;\n }\n await this.keepAliveWhile(() =>\n this._turnQueue.enqueue(\n `detached-delivery:${crypto.randomUUID()}`,\n // Mark the slot so `_injectDetachedNotification` knows it owns the active\n // turn and can run a `react` reply INLINE (vs a foreign active turn,\n // where inline would interleave and enqueue-await would deadlock).\n async () => {\n this._inSerializedDetachedDeliverySlot = true;\n try {\n await inContext();\n } finally {\n this._inSerializedDetachedDeliverySlot = false;\n }\n }\n )\n );\n }\n\n /**\n * Inject a synthetic chat message for a detached-run notification, idempotent\n * on its deterministic `id` (a re-delivery from the warm tail + cold backbone\n * collapses to one — `persistMessages` is skipped when the id already exists).\n * When `react` is set the model then takes a turn over the new message.\n *\n * `@cloudflare/ai-chat` has no durable-submission layer (unlike Think's\n * `submitMessages`), so the turn cannot be enqueued-and-awaited from inside the\n * serialized delivery slot — `TurnQueue` has no re-entrancy bypass, so that\n * would self-deadlock. Instead: when we are already inside a turn slot (the\n * `serialize: true` finish delivery runs as its own enqueued turn) we run the\n * programmatic turn INLINE, reusing that slot — so the whole notify completes\n * before the ledger marks the slot delivered (eviction-safe). When we are not\n * inside a slot (a milestone fired from the `waitUntil` fast path or the\n * reconcile alarm) we enqueue a fresh turn normally.\n */\n private async _injectDetachedNotification(\n id: string,\n role: \"user\" | \"assistant\",\n text: string,\n metadata: Record<string, unknown>,\n options: { react: boolean }\n ): Promise<void> {\n // `messages.some` covers re-delivery against persisted history (survives\n // eviction); the in-flight set closes the check-then-persist race when the\n // warm tail and cold backbone deliver the SAME milestone concurrently in one\n // isolate (milestones have no ledger claim, unlike finish).\n if (\n this._inFlightDetachedNotifications.has(id) ||\n this.messages.some((message) => message.id === id)\n ) {\n return;\n }\n this._inFlightDetachedNotifications.add(id);\n try {\n await this.persistMessages([\n ...this.messages,\n { id, role, parts: [{ type: \"text\", text }], metadata } as UIMessage\n ]);\n if (!options.react) return;\n const runReply = (requestId: string) =>\n this._runProgrammaticChatTurn(\n requestId,\n this._lastClientTools,\n this._lastBody,\n undefined\n );\n if (this._inSerializedDetachedDeliverySlot) {\n // We own the active turn slot (a `serialize: true` finish delivery), so\n // run inline + awaited, reusing the slot's request id (keeps the\n // `activeRequestId === turn requestId` invariant `saveMessages` relies\n // on). The ledger marks the slot delivered only after the reaction\n // completes, making the react turn eviction-safe too.\n await runReply(this._turnQueue.activeRequestId ?? nanoid());\n } else if (this._turnQueue.isActive) {\n // Inside a FOREIGN turn (e.g. `cancelAgentTool` called mid-turn).\n // Enqueue-and-await would deadlock; inline would interleave with that\n // turn. Fire-and-forget a turn that runs once the slot frees — the\n // message is already persisted, so the reaction is best-effort.\n const requestId = nanoid();\n void this.keepAliveWhile(() =>\n this._runExclusiveChatTurn(requestId, () => runReply(requestId))\n );\n } else {\n const requestId = nanoid();\n await this._runExclusiveChatTurn(requestId, () => runReply(requestId));\n }\n } finally {\n this._inFlightDetachedNotifications.delete(id);\n }\n }\n\n /**\n * Format the message injected by `detached: { notify }` when a background run\n * finishes. Override to customize the prose, or return an empty string to\n * suppress the notification for a given outcome.\n */\n protected formatDetachedCompletion(\n run: AgentToolRunInfo,\n result: AgentToolLifecycleResult\n ): string {\n const label = `Background task \"${run.agentType}\" (run ${run.runId})`;\n switch (result.status) {\n case \"completed\":\n return result.summary\n ? `${label} finished:\\n\\n${result.summary}`\n : `${label} finished successfully.`;\n case \"error\":\n return `${label} failed${result.error ? `: ${result.error}` : \".\"}`;\n case \"aborted\":\n return `${label} was cancelled.`;\n case \"interrupted\":\n return result.reason === \"budget-exceeded\"\n ? `${label} ran out of time before completing and was stopped.`\n : `${label} was interrupted before completing${result.error ? `: ${result.error}` : \".\"}`;\n default:\n return `${label} ended (${result.status}).`;\n }\n }\n\n /**\n * Targeted completion hook for `detached: { notify }`. Auto-wired by\n * `runAgentTool` (resolved by name so the base `Agent` stays decoupled from the\n * chat layer). Injects the formatted completion as a user turn so the model\n * reacts to the background result. Idempotent per run + status (deterministic\n * message id), so an exactly-once finish — or a soft give-up followed by a real\n * completion — never injects a duplicate, while a give-up and a later real\n * completion surface as two distinct messages.\n */\n async _cfDetachedNotifyFinish(\n run: AgentToolRunInfo,\n result: AgentToolLifecycleResult\n ): Promise<void> {\n const text = this.formatDetachedCompletion(run, result);\n if (!text) return;\n await this._injectDetachedNotification(\n `detached-finish:${run.runId}:${result.status}`,\n \"user\",\n text,\n {\n source: run.notifySource ?? \"detached-agent-tool\",\n runId: run.runId,\n agentType: run.agentType,\n status: result.status\n },\n { react: true }\n );\n }\n\n /**\n * Format the message injected when a `detached: { onMilestones }` milestone is\n * reached. Override to customize the prose (or return an empty string to\n * suppress a given milestone).\n */\n protected formatDetachedMilestone(\n run: AgentToolRunInfo,\n milestone: AgentToolMilestone\n ): string {\n const label = `Background task \"${run.agentType}\" (run ${run.runId})`;\n const detail =\n milestone.data !== undefined\n ? `\\n\\n${JSON.stringify(milestone.data, null, 2)}`\n : \"\";\n return `${label} reached milestone \"${milestone.name}\".${detail}`;\n }\n\n /**\n * Targeted milestone hook for `detached: { onMilestones }`. Idempotent per run\n * + milestone NAME (deterministic message id), so the warm tail and the cold\n * backbone reconcile converge to at most one message.\n *\n * - `\"narrate\"` (default): a synthetic **assistant** message injected directly\n * — no model turn.\n * - `\"react\"`: a **user** message followed by a model turn so the agent\n * responds to the milestone.\n */\n protected override async _deliverDetachedMilestone(\n run: AgentToolRunInfo,\n milestone: AgentToolMilestone,\n mode: \"react\" | \"narrate\"\n ): Promise<void> {\n const text = this.formatDetachedMilestone(run, milestone);\n if (!text) return;\n await this._injectDetachedNotification(\n `detached-ms:${run.runId}:${milestone.name}`,\n mode === \"narrate\" ? \"assistant\" : \"user\",\n text,\n {\n source: run.notifySource ?? \"detached-agent-tool\",\n runId: run.runId,\n agentType: run.agentType,\n milestone: milestone.name\n },\n { react: mode === \"react\" }\n );\n }\n\n /**\n * Bind the child turn that is about to stream to its agent-tool run, at\n * the moment the turn's request id is first knowable (inside the turn,\n * before any frame is broadcast). The in-memory mapping drives frame\n * attribution in {@link broadcast}; the run row's `request_id` is\n * persisted here rather than at terminal so attribution also survives a\n * DO restart mid-run (#1575).\n */\n private _registerAgentToolTurn(runId: string): void {\n const requestId = this._turnQueue.activeRequestId;\n if (requestId === null) {\n // Invariant: this runs inside the turn's enqueued fn, so the turn\n // queue's active request id is set. If it ever isn't, the run can't be\n // bound to its frames and its error/progress capture silently degrades\n // (#1575) — surface it rather than fail quietly.\n console.warn(\n `[AIChatAgent] agent-tool run ${runId} has no active request id at turn start; frame attribution will be skipped`\n );\n return;\n }\n this._agentToolRunsByRequestId.set(requestId, runId);\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set request_id = ${requestId}\n where run_id = ${runId}\n `;\n }\n\n async startAgentToolRun(\n input: unknown,\n options: {\n runId: string;\n signal?: AbortSignal;\n eventDelivery?: AgentToolEventDelivery;\n }\n ): Promise<AgentToolRunInspection> {\n const existing = await this.inspectAgentToolRun(options.runId);\n if (existing) return existing;\n\n const startedAt = Date.now();\n const controller = new AbortController();\n const assistantIdsBeforeStart = new Set(\n this.messages\n .filter((message) => message.role === \"assistant\")\n .map((message) => message.id)\n );\n\n this.sql`\n insert into cf_ai_chat_agent_tool_runs\n (run_id, request_id, status, input_json, started_at, event_delivery)\n values (${options.runId}, null, 'running', ${AIChatAgent._stringifyAgentToolValue(input)}, ${startedAt}, ${options.eventDelivery === \"terminal\" ? \"terminal\" : null})\n `;\n this._agentToolAbortControllers.set(options.runId, controller);\n this._agentToolPreTurnAssistantIds.set(\n options.runId,\n assistantIdsBeforeStart\n );\n this._agentToolLiveSequences.set(options.runId, 0);\n if (options.eventDelivery === \"terminal\") {\n this._agentToolTerminalOnlyRuns.add(options.runId);\n }\n\n const abortFromParent = () => controller.abort(options.signal?.reason);\n if (options.signal?.aborted) {\n abortFromParent();\n } else {\n options.signal?.addEventListener(\"abort\", abortFromParent, {\n once: true\n });\n }\n\n const lifecycle = async () => {\n let requestId: string | undefined;\n try {\n const previousClientTools = this._lastClientTools;\n const previousBody = this._lastBody;\n this._setRequestContext(undefined, { agentToolInput: input });\n const result = await this.saveMessages(\n async (messages) => {\n this._registerAgentToolTurn(options.runId);\n return [\n ...messages,\n this.formatAgentToolInput(input, { runId: options.runId })\n ];\n },\n { signal: controller.signal }\n ).finally(() => {\n this._setRequestContext(previousClientTools, previousBody);\n });\n requestId = result.requestId;\n\n if (result.status === \"aborted\") {\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set request_id = ${requestId}, status = 'aborted',\n completed_at = ${Date.now()}\n where run_id = ${options.runId}\n `;\n return;\n }\n\n if (result.status === \"skipped\") {\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set request_id = ${requestId}, status = 'error',\n error_message = 'Agent tool run was skipped because the chat was cleared.',\n completed_at = ${Date.now()}\n where run_id = ${options.runId}\n `;\n return;\n }\n\n const streamError =\n result.error ?? this._agentToolLastErrors.get(options.runId);\n if (result.status === \"error\" || streamError) {\n const errorMessage =\n streamError ?? \"Agent tool run failed during streaming.\";\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set request_id = ${requestId}, status = 'error',\n error_message = ${errorMessage}, completed_at = ${Date.now()}\n where run_id = ${options.runId}\n `;\n return;\n }\n\n const messagesAfterStart = this._getAgentToolMessagesAfterStart(\n options.runId\n );\n const output = this.getAgentToolOutput(\n { runId: options.runId, input },\n messagesAfterStart\n );\n const summary = this.getAgentToolSummary(\n { runId: options.runId, input },\n output,\n messagesAfterStart\n );\n\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set request_id = ${requestId}, status = 'completed',\n output_json = ${AIChatAgent._stringifyAgentToolValue(output)},\n summary = ${summary}, error_message = null,\n completed_at = ${Date.now()}\n where run_id = ${options.runId}\n `;\n } catch (error) {\n if (controller.signal.aborted) {\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set request_id = ${requestId ?? null}, status = 'aborted',\n completed_at = ${Date.now()}\n where run_id = ${options.runId}\n `;\n return;\n }\n const message = error instanceof Error ? error.message : String(error);\n this._agentToolLastErrors.set(options.runId, message);\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set request_id = ${requestId ?? null}, status = 'error',\n error_message = ${message}, completed_at = ${Date.now()}\n where run_id = ${options.runId}\n `;\n } finally {\n options.signal?.removeEventListener(\"abort\", abortFromParent);\n this._agentToolAbortControllers.delete(options.runId);\n this._agentToolLiveSequences.delete(options.runId);\n this._agentToolTerminalOnlyRuns.delete(options.runId);\n // Drop the progress emitter's per-run coalescing state.\n this._agentToolProgressEmitterInstance?.forget(options.runId);\n // Drop this run's request-id mappings. When no runs remain in flight\n // clear the whole map, so negatively-cached (null) entries for\n // unrelated turns can't accumulate for the DO's lifetime — the map is\n // only consulted while a run is active (#1575).\n if (this._agentToolAbortControllers.size === 0) {\n this._agentToolRunsByRequestId.clear();\n } else {\n for (const [reqId, runId] of this._agentToolRunsByRequestId) {\n if (runId === options.runId) {\n this._agentToolRunsByRequestId.delete(reqId);\n }\n }\n }\n this._agentToolLastErrors.delete(options.runId);\n this._agentToolPreTurnAssistantIds.delete(options.runId);\n this._closeAgentToolTailers(options.runId);\n }\n };\n\n void this.keepAliveWhile(lifecycle);\n\n return {\n runId: options.runId,\n status: \"running\",\n startedAt\n };\n }\n\n async cancelAgentToolRun(runId: string, reason?: unknown): Promise<void> {\n // Stop the original in-isolate run if it's still live...\n this._agentToolAbortControllers.get(runId)?.abort(reason);\n // ...and any in-flight chat-recovery turn driving this child facet after an\n // eviction. A recovered turn re-runs via `_chatRecoveryContinue` /\n // `_chatRecoveryRetry` outside `startAgentToolRun`, so it has no entry in\n // `_agentToolAbortControllers`; a child facet is dedicated to a single\n // agent-tool run, so cancelling whatever turn is running tears the recovery\n // down instead of letting it keep grinding (and holding a keep-alive) after\n // the parent gave up and sealed `interrupted` (#1630 follow-up). Mirrors\n // Think's `_submissionAbortControllers` sweep.\n this.abortAllRequests(reason);\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set status = 'aborted', completed_at = coalesce(completed_at, ${Date.now()})\n where run_id = ${runId} and status = 'running'\n `;\n this._closeAgentToolTailers(runId);\n }\n\n /**\n * Classify any in-flight chat-recovery on this child facet (#1630 / N6). A\n * child facet is dedicated to a single agent-tool run, so any recovery\n * incident is that run's. Incidents in `detected`/`scheduled`/`attempting`\n * mean recovery is still resolving the interrupted turn; `exhausted`/`failed`\n * mean recovery gave up; a completed recovery deletes its incident.\n */\n private _classifyAgentToolChildRecovery(): Promise<\n \"in-progress\" | \"failed\" | \"none\"\n > {\n return classifyAgentToolChildRecovery(this.ctx.storage);\n }\n\n /**\n * Reconcile a stale (post-eviction) child run row from the child's own\n * durable recovery (#1630). The child facet self-heals its interrupted turn\n * via `chatRecovery`, but that path never writes the run row, so without this\n * the row strands `running` and the parent can only collect `interrupted`.\n *\n * Persisting the terminal here (rather than only computing it) is intentional:\n * it's a lazy materialization of the run's true terminal that also lets a\n * tailing parent's stream close promptly and makes subsequent inspects cheap.\n * While recovery is still resolving (active stream or in-progress incident)\n * the row is left `running` so the parent's bounded re-attach keeps waiting.\n * Mutates `row` in place when it settles so the caller can report it.\n */\n private async _reconcileStaleAgentToolChildRun(\n runId: string,\n row: AIChatAgentToolRunRow\n ): Promise<void> {\n const recovery = await this._classifyAgentToolChildRecovery();\n if (recovery === \"in-progress\" || this._resumableStream.hasActiveStream()) {\n return;\n }\n // A stream error recorded on the open row means the turn failed even if it\n // persisted an assistant reply — matching the live finalizer, which fails a\n // run whenever a stream error was captured.\n if (row.error_message !== null) {\n const completedAt = Date.now();\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set status = 'error', error_message = ${row.error_message},\n completed_at = ${completedAt}\n where run_id = ${runId}\n `;\n row.status = \"error\";\n row.completed_at = completedAt;\n this._closeAgentToolTailers(runId);\n return;\n }\n const messagesAfterStart = this._getAgentToolMessagesAfterStart(runId);\n // A settled recovery that produced an assistant turn is `completed`, even if\n // it ended on a tool result with no final text — keying off text alone would\n // mis-seal a legitimately-finished (but text-less) run as `error`.\n // `getAgentToolSummary` falls back when there is no text.\n const recoveredTurn =\n recovery !== \"failed\" &&\n messagesAfterStart.some((message) => message.role === \"assistant\");\n if (recoveredTurn) {\n const input = AIChatAgent._parseAgentToolValue(row.input_json);\n const output = this.getAgentToolOutput(\n { runId, input },\n messagesAfterStart\n );\n const summary = this.getAgentToolSummary(\n { runId, input },\n output,\n messagesAfterStart\n );\n const completedAt = Date.now();\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set status = 'completed',\n output_json = ${AIChatAgent._stringifyAgentToolValue(output)},\n summary = ${summary}, error_message = null,\n completed_at = ${completedAt}\n where run_id = ${runId} and status = 'running'\n `;\n row.status = \"completed\";\n row.output_json = AIChatAgent._stringifyAgentToolValue(output);\n row.summary = summary;\n row.error_message = null;\n row.completed_at = completedAt;\n this._closeAgentToolTailers(runId);\n } else {\n const error =\n \"Agent tool run was interrupted before the child could finish.\";\n this.sql`\n update cf_ai_chat_agent_tool_runs\n set status = 'error', error_message = ${error}, completed_at = ${Date.now()}\n where run_id = ${runId}\n `;\n row.status = \"error\";\n row.error_message = error;\n row.completed_at = Date.now();\n this._closeAgentToolTailers(runId);\n }\n }\n\n /**\n * Eagerly terminalize this child facet's OWN agent-tool run row(s) once a\n * recovered turn has settled. A recovered turn re-runs via either\n * `_chatRecoveryContinue` → `continueLastTurn` or, for a pre-stream eviction,\n * `_chatRecoveryRetry` → `_retryLastUserTurn` — neither flows through\n * `startAgentToolRun`'s finalizer, so without this the row strands `running`\n * and its tailers stay open until a parent inspect lazily reconciles it —\n * forcing a re-attached parent to wait out a full no-progress window before\n * collecting an already-finished result (#1630 follow-up). Reconciling here\n * closes the tail promptly so the parent collects the terminal immediately.\n * No-op on non-child facets (their `cf_ai_chat_agent_tool_runs` table is\n * empty) and on rows whose in-memory run is still live; the underlying\n * reconcile leaves a row `running` while its recovery is still in progress.\n * Mirrors `@cloudflare/think`.\n */\n private async _reconcileOwnStaleAgentToolChildRuns(): Promise<void> {\n let rows: Array<{ run_id: string }>;\n try {\n rows = this.sql<{ run_id: string }>`\n select run_id from cf_ai_chat_agent_tool_runs\n where status = 'running'\n `;\n } catch {\n // No child-run table on this facet (it never ran as a child).\n return;\n }\n for (const { run_id } of rows) {\n if (this._agentToolAbortControllers.has(run_id)) continue;\n const row = this._getAgentToolRunRow(run_id);\n if (!row || row.status !== \"running\") continue;\n try {\n await this._reconcileStaleAgentToolChildRun(run_id, row);\n } catch {\n // Best-effort: a parent inspect still reconciles lazily.\n }\n }\n }\n\n async inspectAgentToolRun(\n runId: string,\n options?: { reconcile?: boolean }\n ): Promise<AgentToolRunInspection | null> {\n const row = this._getAgentToolRunRow(runId);\n if (!row) return null;\n\n // A `running` row with no live abort controller means the original\n // in-isolate run is gone (e.g. the parent was evicted while this child run\n // was in flight, #1630) — lazily reconcile it from the child's own durable\n // recovery before reporting (mutates `row` in place when it settles).\n if (\n options?.reconcile !== false &&\n row.status === \"running\" &&\n !this._agentToolAbortControllers.has(runId)\n ) {\n await this._reconcileStaleAgentToolChildRun(runId, row);\n }\n\n const streamId = row.request_id\n ? this._getAgentToolStreamId(row.request_id)\n : undefined;\n const messagesAfterStart = this._getAgentToolMessagesAfterStart(runId);\n const input = AIChatAgent._parseAgentToolValue(row.input_json);\n const output =\n row.status === \"completed\"\n ? (AIChatAgent._parseAgentToolValue(row.output_json) ??\n this.getAgentToolOutput({ runId, input }, messagesAfterStart))\n : undefined;\n\n const progress = AIChatAgent._progressSnapshotFromRow(row);\n const milestones = this._readAgentToolMilestones(runId);\n return {\n runId,\n status: row.status,\n requestId: row.request_id ?? undefined,\n streamId,\n output,\n summary: row.status === \"completed\" ? (row.summary ?? \"\") : undefined,\n error:\n row.status === \"error\" ? (row.error_message ?? undefined) : undefined,\n startedAt: row.started_at,\n completedAt: row.completed_at ?? undefined,\n ...(progress ? { progress } : {}),\n ...(milestones.length > 0 ? { milestones } : {})\n };\n }\n\n private static _progressSnapshotFromRow(\n row: AIChatAgentToolRunRow\n ): AgentToolProgressSnapshot | undefined {\n if (row.progress_json == null || row.last_signal_at == null) {\n return undefined;\n }\n try {\n const parsed = JSON.parse(row.progress_json) as Partial<\n Omit<AgentToolProgressSnapshot, \"at\">\n >;\n return { ...parsed, at: row.last_signal_at };\n } catch {\n return { at: row.last_signal_at };\n }\n }\n\n async getAgentToolChunks(\n runId: string,\n options?: { afterSequence?: number }\n ): Promise<AgentToolStoredChunk[]> {\n this._flushChunkBuffer();\n const row = this._getAgentToolRunRow(runId);\n if (!row?.request_id) return [];\n\n return this._getAgentToolStoredChunks(\n row.request_id,\n options?.afterSequence\n );\n }\n\n async tailAgentToolRun(\n runId: string,\n options?: { afterSequence?: number; signal?: AbortSignal }\n ): Promise<ReadableStream<AgentToolStoredChunk>> {\n // Hoisted out of `start` so the `cancel` callback (a sibling of `start` on\n // the underlying source) can reach them — an in-scope-only `closed`/`forward`\n // is exactly why a cancelled consumer used to leave a zombie forwarder.\n let closed = false;\n let forward: ((chunk: AgentToolStoredChunk) => void) | undefined;\n const detach = () => {\n // Remove our forwarder and drop the now-empty set so the broadcast\n // idle-guard (`_agentToolForwarders.size`) goes cold again. Otherwise a\n // run that was already terminal at attach (its `_closeAgentToolTailers`\n // already ran and won't run again) leaves an empty set keyed by runId, and\n // every subsequent broadcast on this DO keeps paying the\n // `interceptAgentToolBroadcast` cost forever.\n if (forward) {\n const set = this._agentToolForwarders.get(runId);\n set?.delete(forward);\n if (set && set.size === 0) this._agentToolForwarders.delete(runId);\n forward = undefined;\n }\n };\n const stream = new ReadableStream<Uint8Array>({\n start: async (controller) => {\n // Highest sequence already enqueued into this view. Stored chunk_index\n // and the live forwarder sequence share one monotonic numbering (see\n // `_getAgentToolStoredChunks`), so a single high-water mark dedupes the\n // stored-replay → live-forwarding handoff: a chunk that lands in both\n // the drained backlog AND the live buffer (because it was stored and\n // broadcast during the drain) is emitted exactly once, in order.\n // Progress/milestone frames and unstored chunks have no stored\n // position (they reuse the next one), so they bypass the high-water\n // mark instead of moving it.\n let lastEmitted = options?.afterSequence ?? -1;\n const emit = (chunk: AgentToolStoredChunk) => {\n if (closed) return;\n // Drop out-of-order / duplicate sequences. Guarantees in-order,\n // exactly-once delivery so the parent can rebuild tool-call state\n // (input-available → output-available) without gaps.\n if (!isPositionlessAgentToolChunk(chunk)) {\n if (chunk.sequence <= lastEmitted) return;\n lastEmitted = chunk.sequence;\n }\n try {\n controller.enqueue(\n agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\\n`)\n );\n } catch {\n // The consumer detached (e.g. a parent's bounded re-attach budget\n // expired) between the read view closing and our handling here.\n // Just mark dead and detach — do NOT call `controller.close()` on an\n // already-cancelled stream, which throws and would propagate out of\n // `interceptAgentToolBroadcast`'s forward loop, starving the run's\n // sibling tailers of this chunk. The child run is unaffected.\n closed = true;\n detach();\n }\n };\n\n // While draining the stored backlog, live chunks are parked here rather\n // than emitted directly, so they keep arriving (the forwarder is\n // registered FIRST, below) but never race ahead of / interleave with\n // the ordered backlog.\n let draining = true;\n const pending: AgentToolStoredChunk[] = [];\n forward = (chunk: AgentToolStoredChunk) => {\n if (closed) return;\n if (draining) {\n pending.push(chunk);\n return;\n }\n emit(chunk);\n };\n\n const close = () => {\n if (closed) return;\n closed = true;\n detach();\n try {\n controller.close();\n } catch {\n // Already closed (e.g. the consumer cancelled the reader first).\n }\n };\n const onAbort = () => close();\n\n try {\n if (options?.signal?.aborted) {\n close();\n return;\n }\n options?.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n // Register the live forwarder BEFORE draining the stored backlog.\n // Previously the forwarder was attached only AFTER `getAgentToolChunks`\n // + `inspectAgentToolRun` resolved; any chunk the child stored AND\n // broadcast during those `await` boundaries advanced the live sequence\n // with no forwarder attached, so it was neither in the drained\n // snapshot nor live-forwarded — silently dropped from the parent's\n // forward stream. A network-paced proxied remote stream (a sub-agent\n // returning a remote `toUIMessageStreamResponse()` from\n // `onChatMessage`) hits this window constantly, leaving tool parts\n // stuck at `input-available` on the client (#1589).\n //\n // Seed a cold live counter first, so a chunk broadcast while this\n // tail drains or inspects continues the stored numbering.\n const seeded = this._seedAgentToolLiveSequence(runId);\n const forwarders =\n this._agentToolForwarders.get(runId) ??\n new Set<(chunk: AgentToolStoredChunk) => void>();\n forwarders.add(forward);\n this._agentToolForwarders.set(runId, forwarders);\n\n const closers =\n this._agentToolClosers.get(runId) ?? new Set<() => void>();\n closers.add(close);\n this._agentToolClosers.set(runId, closers);\n\n for (const chunk of await this.getAgentToolChunks(runId, options)) {\n if (closed) return;\n emit(chunk);\n }\n\n // Flush anything that arrived live during the drain, then switch the\n // forwarder to direct emit. No `await` between here and the loop above\n // means no live chunk can slip past this handoff.\n draining = false;\n for (const chunk of pending) emit(chunk);\n pending.length = 0;\n\n const inspection = await this.inspectAgentToolRun(runId);\n if (!inspection || inspection.status !== \"running\") {\n // Don't leave a seeded counter re-heating the broadcast idle-guard\n // for a terminal run.\n if (seeded) this._agentToolLiveSequences.delete(runId);\n close();\n return;\n }\n } catch (error) {\n // Detach the up-front-registered forwarder before surfacing the\n // failure so it doesn't linger on this run, then guard\n // `controller.error` — the stream may already be torn down (e.g. the\n // consumer cancelled during the drain await), in which case\n // `controller.error` throws.\n closed = true;\n detach();\n try {\n controller.error(error);\n } catch {\n // Stream already torn down.\n }\n }\n },\n cancel: () => {\n // A consumer detaching from the tail (e.g. a parent's bounded re-attach\n // budget expiring via reader.cancel()) is read-only — it must NOT cancel\n // the child run. Mark dead and detach the forwarder so no later broadcast\n // reaches this torn-down controller (a lingering forwarder would throw on\n // the next enqueue). Mirrors @cloudflare/think's read-only tail.\n closed = true;\n detach();\n }\n });\n return stream as unknown as ReadableStream<AgentToolStoredChunk>;\n }\n\n private _getAgentToolRunRow(runId: string): AIChatAgentToolRunRow | null {\n const rows = this.sql<AIChatAgentToolRunRow>`\n select run_id, request_id, status, input_json, output_json, summary,\n error_message, started_at, completed_at, progress_json,\n last_signal_at\n from cf_ai_chat_agent_tool_runs\n where run_id = ${runId}\n `;\n return rows[0] ?? null;\n }\n\n private _getAgentToolStreamId(requestId: string): string | undefined {\n return this._resumableStream.latestStreamInfoForRequest(requestId)?.id;\n }\n\n /**\n * After this DO restarts, `_agentToolLiveSequences` is cold while the stored\n * backlog sits at N, and a chat-recovery resume re-attaches via\n * `tailAgentToolRun` without re-running `startAgentToolRun` (which seeds the\n * counter). Unseeded, the broadcast snoop numbers the recovered turn's chunks\n * from 0 and the tail's high-water dedupe drops them. Seeds only a running\n * run, so a terminal one doesn't re-heat the broadcast idle-guard; a warm\n * counter is authoritative. Returns whether it seeded.\n */\n private _seedAgentToolLiveSequence(runId: string): boolean {\n if (this._agentToolLiveSequences.has(runId)) return false;\n this._flushChunkBuffer();\n const row = this._getAgentToolRunRow(runId);\n if (!row?.request_id || row.status !== \"running\") return false;\n this._agentToolLiveSequences.set(\n runId,\n this._getAgentToolStoredChunks(row.request_id).length\n );\n return true;\n }\n\n private _getAgentToolStoredChunks(\n requestId: string,\n afterSequence = -1\n ): AgentToolStoredChunk[] {\n const streamId = this._getAgentToolStreamId(requestId);\n if (!streamId) return [];\n\n // Read through ResumableStream so packed segment rows are unpacked into\n // individual chunk bodies with a running per-chunk index. That per-chunk\n // sequence matches the in-memory live counter (`_agentToolLiveSequences`),\n // so a tailing parent can switch from stored replay to live forwarding\n // without gaps or duplicates.\n return this._resumableStream\n .getStreamChunks(streamId)\n .filter((chunk) => chunk.chunk_index > afterSequence)\n .map((chunk) => ({ sequence: chunk.chunk_index, body: chunk.body }));\n }\n\n private _getAgentToolMessagesAfterStart(runId: string): UIMessage[] {\n const previousAssistantIds =\n this._agentToolPreTurnAssistantIds.get(runId) ?? new Set<string>();\n return this.messages.filter(\n (message) =>\n message.role !== \"assistant\" || !previousAssistantIds.has(message.id)\n );\n }\n\n private _closeAgentToolTailers(runId: string) {\n const closers = this._agentToolClosers.get(runId);\n if (closers) {\n for (const close of closers) close();\n this._agentToolClosers.delete(runId);\n }\n this._agentToolForwarders.delete(runId);\n // A live in-isolate run keeps suppressing until `startAgentToolRun`'s\n // finally; a recovered turn never reaches that finally.\n if (!this._agentToolAbortControllers.has(runId)) {\n this._agentToolTerminalOnlyRuns.delete(runId);\n }\n }\n\n private static _stringifyAgentToolValue(value: unknown): string | null {\n if (value === undefined) return null;\n const json = JSON.stringify(value);\n return json === undefined ? null : json;\n }\n\n private static _parseAgentToolValue(value: string | null): unknown {\n if (value === null) return undefined;\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n }\n\n private static _extractLatestAssistantText(\n messages: readonly UIMessage[]\n ): string | undefined {\n const message = [...messages]\n .reverse()\n .find((candidate) => candidate.role === \"assistant\");\n if (!message) return undefined;\n\n const text = message.parts\n .filter((part): part is TextUIPart => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\");\n return text.length > 0 ? text : undefined;\n }\n\n /**\n * Persist messages and trigger `onChatMessage()` for a new response.\n *\n * Waits for any active chat turn to finish before starting, so scheduled\n * or programmatic messages never overlap an in-flight stream.\n *\n * Pass a function to derive the next message list from the latest\n * persisted `this.messages` when the turn actually starts. This avoids\n * stale baselines when multiple `saveMessages()` calls queue up behind\n * active work:\n *\n * ```ts\n * await this.saveMessages((messages) => [...messages, syntheticMessage]);\n * ```\n *\n * Pass `options.signal` to cancel the turn from outside without knowing\n * the internally-generated request id. The signal is linked to the\n * registry's controller for this turn — when it aborts, the inference\n * loop's signal aborts and the result reports `status: \"aborted\"`.\n * Pre-aborted signals short-circuit before any model work runs.\n *\n * Returns `{ requestId, status, error? }` where `status` is `\"completed\"`\n * when the turn ran, `\"error\"` when the stream reported an error,\n * `\"skipped\"` when the chat was cleared, or `\"aborted\"` when an external\n * signal cancelled it mid-stream.\n */\n async saveMessages(\n messages:\n | UIMessage[]\n | ((\n currentMessages: readonly UIMessage[]\n ) => UIMessage[] | Promise<UIMessage[]>),\n options?: SaveMessagesOptions\n ): Promise<SaveMessagesResult> {\n const requestId = nanoid();\n const clientTools = this._lastClientTools;\n const body = this._lastBody;\n const epoch = this._turnQueue.generation;\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n let error: string | undefined;\n\n await this._runExclusiveChatTurn(\n requestId,\n async () => {\n const resolvedMessages =\n typeof messages === \"function\"\n ? await messages(this.messages)\n : messages;\n\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n await this.persistMessages(resolvedMessages);\n\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n const turnResult = await this._runProgrammaticChatTurn(\n requestId,\n clientTools,\n body,\n options?.signal\n );\n status = turnResult.status;\n error = turnResult.error;\n },\n { epoch }\n );\n\n if (this._turnQueue.generation !== epoch && status === \"completed\") {\n status = \"skipped\";\n }\n\n return { requestId, status, ...(error !== undefined && { error }) };\n }\n\n /**\n * Trigger a continuation of the last assistant message without inserting\n * a new user message. The LLM sees the full conversation (including the\n * partial assistant response) and generates a continuation that appends\n * to the same message.\n *\n * This uses `continuation: true` in `_reply`, which clones the last\n * assistant message and appends new parts to it — the same mechanism\n * used by tool auto-continuation.\n *\n * Returns early if there is no assistant message to continue from.\n *\n * Pass `options.signal` to cancel the continuation from outside —\n * matches the {@link saveMessages} contract.\n */\n protected async continueLastTurn(\n body?: Record<string, unknown>,\n options?: SaveMessagesOptions\n ): Promise<SaveMessagesResult> {\n if (!this._findLastAssistantMessage()) {\n return { requestId: \"\", status: \"skipped\" };\n }\n\n const requestId = nanoid();\n // If this facet is an agent-tool child being recovered, re-bind its run row\n // to this turn's request id so the parent's re-attach tail keeps attributing\n // the continued turn's frames (no-op otherwise).\n this._rebindAgentToolChildRunRequestId(requestId);\n const clientTools = this._lastClientTools;\n const resolvedBody = body ?? this._lastBody;\n const epoch = this._turnQueue.generation;\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n let error: string | undefined;\n let wasAborted = false;\n\n await this._runExclusiveChatTurn(\n requestId,\n async () => {\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n this._setRequestContext(clientTools, resolvedBody);\n\n const turnBody = async () => {\n await this._tryCatchChat(async () => {\n return agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n async () => {\n const abortSignal = this._abortRegistry.getSignal(requestId);\n const detachExternal = this._abortRegistry.linkExternal(\n requestId,\n options?.signal\n );\n try {\n await this._repairInterruptedToolsBeforeTurn({\n continuation: true\n });\n const response = await this.onChatMessage(() => {}, {\n requestId,\n abortSignal,\n clientTools,\n body: resolvedBody,\n continuation: true\n });\n\n if (response) {\n const replyResult = await this._reply(\n requestId,\n response,\n [],\n {\n continuation: true,\n chatMessageId: requestId\n }\n );\n status = replyResult.status;\n error = replyResult.error;\n }\n } finally {\n if (abortSignal?.aborted) wasAborted = true;\n detachExternal();\n this._abortRegistry.remove(requestId);\n }\n }\n );\n });\n };\n\n await this._runChatRecoveryFiber(requestId, true, turnBody);\n },\n { epoch }\n );\n\n if (this._turnQueue.generation !== epoch && status === \"completed\") {\n status = \"skipped\";\n } else if (wasAborted && status === \"completed\") {\n status = \"aborted\";\n }\n\n return { requestId, status, ...(error !== undefined && { error }) };\n }\n\n private async _retryLastUserTurn(\n clientTools?: ClientToolSchema[],\n body?: Record<string, unknown>,\n options?: SaveMessagesOptions\n ): Promise<SaveMessagesResult> {\n const lastMessage =\n this.messages.length > 0 ? this.messages[this.messages.length - 1] : null;\n if (!lastMessage || lastMessage.role !== \"user\") {\n return { requestId: \"\", status: \"skipped\" };\n }\n\n const requestId = nanoid();\n // If this facet is an agent-tool child being recovered, re-bind its run row\n // to this turn's request id so the parent's re-attach tail keeps attributing\n // the retried turn's frames (no-op otherwise).\n this._rebindAgentToolChildRunRequestId(requestId);\n const epoch = this._turnQueue.generation;\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n let error: string | undefined;\n\n await this._runExclusiveChatTurn(\n requestId,\n async () => {\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n const turnResult = await this._runProgrammaticChatTurn(\n requestId,\n clientTools,\n body,\n options?.signal\n );\n status = turnResult.status;\n error = turnResult.error;\n },\n { epoch }\n );\n\n if (this._turnQueue.generation !== epoch && status === \"completed\") {\n status = \"skipped\";\n }\n\n return { requestId, status, ...(error !== undefined && { error }) };\n }\n\n // ── Chat recovery via fibers ──────────────────────────────────────\n\n /**\n * Context passed to `onChatRecovery` when an interrupted chat stream\n * is detected after DO restart.\n */\n static readonly CHAT_FIBER_NAME = \"__cf_internal_chat_turn\";\n\n /**\n * Intercept internal chat fibers before they reach the user's\n * `onFiberRecovered` hook. Maps to `onChatRecovery`.\n * @internal\n */\n private _resolveChatRecoveryConfig(): ResolvedChatRecoveryConfig {\n // Delegates to the shared incident engine (agents/chat) so AIChatAgent and\n // Think resolve recovery config identically. See\n // design/rfc-chat-recovery-foundation.md.\n return resolveChatRecoveryConfig(this.chatRecovery);\n }\n\n /**\n * Monotonic forward-progress signal for recovery budget resets.\n *\n * This used to count assistant messages in `this.messages`, but that is\n * recomputed from the live, mutable transcript. Compaction collapses older\n * assistant messages into a summary, lowering the count — so a turn that had\n * genuinely advanced could read as \"no progress\" between attempts and exhaust\n * its budget prematurely (#1628). It then became a KV counter bumped per\n * credited chunk. It is now derived from the stream log the chunks were\n * already flushed to (`ResumableStream.progressMarker`): the log only grows\n * when new content lands durably, a reconnect replay or a recovery\n * re-persist reads it without appending (#1637), and compaction rewrites\n * the transcript, not the log. Nothing is written per chunk.\n *\n * The pre-derivation KV counter is folded in once per isolate, so a marker\n * an in-flight incident already recorded is never read lower after the\n * upgrade.\n */\n private async _chatRecoveryProgressMarker(): Promise<number> {\n // Memoized as the promise, not a flag: two concurrent readers both wait\n // for the seed to land, so neither can hand the engine an unseeded\n // marker as an incident's work baseline. A failed read is not cached:\n // the next evaluation retries it instead of failing for the isolate's\n // life on a transient storage error.\n this._progressSeed ??= readChatRecoveryProgress(this.ctx.storage).then(\n (legacy) => this._resumableStream.seedProgress(legacy),\n (error: unknown) => {\n this._progressSeed = null;\n throw error;\n }\n );\n await this._progressSeed;\n return this._resumableStream.progressMarker();\n }\n\n private _progressSeed: Promise<void> | null = null;\n\n /** Per-isolate N9 throttle gate (shared `agents/chat` helper); reset per\n * isolate so the first forwarded chunk after a restart always credits. */\n private _agentToolStreamProgress = new AgentToolStreamProgressThrottle();\n\n /**\n * N9: forwarding a sub-agent's chunks IS forward progress for this parent\n * turn, so credit the parent's recovery progress marker — otherwise a parent\n * whose turn merely `await`s a child banks no progress of its own and its\n * no-progress window exhausts while the child is healthily streaming. The\n * child's output goes to clients, not to this object's stream log, so the\n * derived marker cannot see it; this is the one explicit credit left. Only\n * invoked after a child actually produced output (see\n * `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.\n * Throttled (and reset per isolate) so we never write storage per token.\n */\n protected override async _onAgentToolStreamProgress(): Promise<void> {\n if (this._agentToolStreamProgress.shouldCredit(Date.now())) {\n this._resumableStream.creditProgress();\n }\n }\n\n /**\n * Lazily-built shared recovery engine. The adapter arrows capture `this`, so a\n * single cached instance is correct across calls (and across future engine\n * methods). `AIChatAgent` has no interaction state to rehydrate, so it omits\n * the optional `ensureInteractionStateLoaded` hook.\n */\n private _chatRecoveryEngineInstance?: ChatRecoveryEngine;\n private _chatRecoveryEngine(): ChatRecoveryEngine {\n return (this._chatRecoveryEngineInstance ??= new ChatRecoveryEngine({\n resolveConfig: () => this._resolveChatRecoveryConfig(),\n now: () => Date.now(),\n sweepStaleIncidents: (now) =>\n sweepStaleChatRecoveryIncidents(this.ctx.storage, now),\n getIncident: async (key) =>\n (await this.ctx.storage.get<ChatRecoveryIncident>(key)) ?? null,\n listActiveIncidents: async () =>\n (await listActiveChatRecoveryIncidents(this.ctx.storage)).map(\n ({ incident }) => incident\n ),\n readProgress: () => this._chatRecoveryProgressMarker(),\n // A turn parked on a pending CLIENT interaction is waiting on the human,\n // not stuck, so the engine keeps it budget-free.\n isAwaitingClientInteraction: () => this.hasPendingClientInteraction(),\n putIncident: (key, incident) => this.ctx.storage.put(key, incident),\n deleteIncident: async (key) => {\n await this.ctx.storage.delete(key);\n },\n emitRecoveryEvent: (event) =>\n this._emit(event.type, {\n incidentId: event.incidentId,\n requestId: event.requestId,\n attempt: event.attempt,\n maxAttempts: event.maxAttempts,\n recoveryKind: event.recoveryKind,\n ...(event.reason ? { reason: event.reason } : {})\n }),\n scheduleRecovery: (callback, data, reason, delaySeconds) =>\n this._enqueueChatRecovery(callback, data, reason, delaySeconds),\n setRecovering: (active, requestId) =>\n this._setChatRecovering(active, requestId),\n onShouldKeepRecoveringError: (error) =>\n console.error(\n \"[AIChatAgent] chatRecovery shouldKeepRecovering hook threw\",\n error\n ),\n exhaustChatRecovery: (\n incident,\n config,\n partial,\n streamId,\n createdAt,\n originMessageIds\n ) =>\n this._exhaustChatRecovery(\n incident,\n config,\n partial,\n streamId,\n createdAt,\n originMessageIds\n ),\n resolveRecoveryStream: (requestId) =>\n this._resolveAIChatRecoveryStream(requestId),\n getPartialStreamText: (streamId) => this._getPartialStreamText(streamId),\n activeChatRecoveryRootRequestId: () =>\n this._activeChatRecoveryRootRequestId,\n onGiveUpBookkeepingError: (phase, error) =>\n console.error(\n phase === \"read\"\n ? \"[AIChatAgent] failed to read recovery incident during give-up; synthesizing\"\n : \"[AIChatAgent] failed to persist sealed recovery incident during give-up\",\n error\n )\n } satisfies ChatRecoveryAdapter));\n }\n\n private async _beginChatRecoveryIncident(input: {\n requestId: string;\n recoveryRootRequestId?: string | null;\n latestUserMessageId?: string | null;\n recoveryKind: ChatRecoveryKind;\n /** Test-only clock injection for deterministic debounce/window timing. */\n nowMs?: number;\n }): Promise<{\n incident: ChatRecoveryIncident;\n config: ResolvedChatRecoveryConfig;\n exhausted: boolean;\n }> {\n // Incident orchestration (sweep -> read -> budget eval -> persist -> emit,\n // with its ordering invariants) lives in the shared ChatRecoveryEngine; this\n // method is the package's adapter binding. See\n // design/rfc-chat-recovery-foundation.md.\n return this._chatRecoveryEngine().beginIncident(input);\n }\n\n private async _updateChatRecoveryIncident(\n incidentId: string | undefined,\n status: ChatRecoveryIncident[\"status\"],\n reason?: string\n ): Promise<void> {\n // Incident state-machine transitions (delete-on-completed vs persist, the\n // completed/skipped/failed event emit, and the #1620 recovering-flag) live\n // in the shared ChatRecoveryEngine; this method is the package's adapter\n // binding. See design/rfc-chat-recovery-foundation.md.\n return this._chatRecoveryEngine().updateIncident(\n incidentId,\n status,\n reason\n );\n }\n\n private async _exhaustChatRecovery(\n incident: ChatRecoveryIncident,\n config: ResolvedChatRecoveryConfig,\n // `parts` is the engine's vocabulary-agnostic `unknown[]`; ai-chat owns the\n // AI SDK `UIMessage` vocabulary, so it re-asserts `MessagePart[]` at the\n // user-facing exhausted-context edge below.\n partial: { text: string; parts: unknown[] },\n streamId: string,\n createdAt: number,\n originMessageIds?: string[]\n ): Promise<void> {\n // Build + notification (event + onExhausted-swallow) and the\n // notify-before-terminalize invariant live in the engine helper; the\n // terminal/broadcast ordering inside `terminalize` is broadcast-first,\n // converged onto `Think`'s ordering (see the note below).\n // See design/rfc-chat-recovery-foundation.md.\n await runChatRecoveryExhaustion(\n {\n incident,\n config,\n partialText: partial.text,\n partialParts: partial.parts as MessagePart[],\n streamId,\n createdAt\n },\n {\n emit: (event) => this._emit(\"chat:recovery:exhausted\", event),\n onExhausted: config.onExhausted,\n onError: (error) =>\n console.error(\n \"[AIChatAgent] chatRecovery onExhausted hook threw\",\n error\n ),\n terminalize: async (ctx) => {\n // Deliver the user-visible terminal banner BEFORE the durable terminal\n // write. The write can reject in the deploy/storage window a give-up\n // runs in (#1730); ordering the broadcast first keeps the banner\n // resilient to that, the throw then propagates, and the whole give-up\n // re-runs on a healthy isolate — which persists the record\n // (idempotently) and re-delivers the banner (the documented\n // at-least-once edge). Persisting first gains no durability (the\n // re-run persists either way) while dropping the live banner on the\n // failing pass — so ai-chat matches `Think`'s broadcast-first.\n const messageIds =\n this._originMessageIdsFor(ctx.requestId) ?? originMessageIds;\n this._broadcastChatMessage({\n body: ctx.terminalMessage,\n done: true,\n error: true,\n id: ctx.requestId,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n ...(messageIds ? { messageIds } : {})\n });\n // The durable terminal record (#1645) is replayed to a client that\n // (re)connects after the turn ended (shared\n // `ResumeHandshake._replayTerminalOnResume`).\n await this._recordChatTerminal(\n ctx.requestId,\n ctx.terminalMessage,\n messageIds\n );\n // Exhaustion resolves recovery — clear the \"recovering…\" status (#1620).\n await this._setChatRecovering(false);\n }\n }\n );\n // The exhausted record is retained for inspection and reclaimed later by\n // the TTL sweep; only successful (completed) incidents are deleted eagerly.\n }\n\n /**\n * Persist a durable record of the last terminal turn so a client that\n * (re)connects after the turn ended still learns its outcome (#1645). Kept\n * until a later turn supersedes it (`_clearChatTerminal`); a single record is\n * sufficient because only the most recent terminal is relevant.\n */\n private async _recordChatTerminal(\n requestId: string,\n body: string,\n messageIds = this._originMessageIdsFor(requestId)\n ): Promise<void> {\n await recordChatTerminal(this.ctx.storage, requestId, body, messageIds);\n }\n\n /** Clear the durable terminal record once a later turn supersedes it (#1645). */\n private async _clearChatTerminal(): Promise<void> {\n await clearChatTerminal(this.ctx.storage);\n }\n\n private async _pendingChatTerminal(): Promise<{\n requestId: string;\n body: string;\n messageIds?: string[];\n } | null> {\n return pendingChatTerminal(this.ctx.storage);\n }\n\n /**\n * Build the on-connect \"recovering…\" replay frame (#1620), or `null` when no\n * (non-stale) recovery is in progress. A client that connects between recovery\n * attempts (no active stream) reads the turn as working rather than frozen.\n * A record older than the flag TTL is treated as abandoned (its terminal-clear\n * never ran) and skipped, so a dead recovery can't show \"recovering…\" forever.\n * Mirrors `@cloudflare/think`'s `_buildIdleConnectMessages` recovering replay.\n */\n private async _buildRecoveringConnectFrame(): Promise<Record<\n string,\n unknown\n > | null> {\n return buildChatRecoveringFrame(\n this.ctx.storage,\n MessageType.CF_AGENT_CHAT_RECOVERING,\n Date.now()\n );\n }\n\n /**\n * Set or clear the live \"recovering…\" status (#1620). Persists a durable\n * record (so set/clear stay consistent across the isolates a recovery spans)\n * and broadcasts a `CF_AGENT_CHAT_RECOVERING` frame on a genuine transition.\n * The status is also replayed on connect (`_buildRecoveringConnectFrame`) so a\n * client connecting mid-recovery isn't left looking frozen; the terminal\n * outcome is surfaced separately over the resume handshake (#1645).\n */\n private async _setChatRecovering(\n active: boolean,\n requestId?: string\n ): Promise<void> {\n await setChatRecovering(active, requestId, {\n storage: this.ctx.storage,\n messageType: MessageType.CF_AGENT_CHAT_RECOVERING,\n broadcast: (frame) =>\n this._broadcastChatMessage(frame as OutgoingMessage),\n now: Date.now()\n });\n }\n\n protected override async _handleInternalFiberRecovery(\n ctx: FiberRecoveryContext\n ): Promise<boolean> {\n // The wake-recovery lifecycle (non-chat dispatch → chat gate → unwrap →\n // stream/partial → classify → begin-incident → exhausted-branch →\n // onChatRecovery → persist → complete → dispatch → catch→failed) lives in the\n // shared ChatRecoveryEngine; this binds the divergent organs as wake hooks,\n // symmetric with `Think`. `AIChatAgent` tracks no terminal stream status\n // (`streamStatus: undefined`, so every terminal-stream branch is dead) and\n // has no submission layer, so its dispatch is a leaf-only retry/continue/skip.\n // See design/rfc-chat-recovery-foundation.md.\n return this._chatRecoveryEngine().handleChatFiberRecovery(ctx, {\n chatFiberPrefix: () =>\n (this.constructor as typeof AIChatAgent).CHAT_FIBER_NAME + \":\",\n unwrapRecoverySnapshot: (fiber) => {\n const { snapshot, user } = unwrapChatFiberSnapshot<\"ai-chat-turn\">(\n \"__cfAIChatFiberSnapshot\",\n fiber.snapshot,\n \"ai-chat-turn\"\n );\n return { snapshot, recoveryData: user };\n },\n classifyRecoveredTurn: (input) => this._classifyRecoveredChatTurn(input),\n invokeOnChatRecovery: (input) =>\n this.onChatRecovery({\n incidentId: input.incident.incidentId,\n recoveryRootRequestId: input.recoveryRootRequestId,\n attempt: input.incident.attempt,\n maxAttempts: input.incident.maxAttempts,\n recoveryKind: input.recoveryKind,\n streamId: input.streamId,\n requestId: input.requestId,\n partialText: input.partial.text,\n // The engine seam is vocabulary-agnostic (`unknown[]`); ai-chat owns\n // the AI SDK parts vocabulary, so re-assert it for the user context.\n partialParts: input.partial.parts as MessagePart[],\n recoveryData: input.recoveryData,\n messages: [...this.messages],\n lastBody: input.snapshot?.lastBody ?? this._lastBody,\n lastClientTools:\n input.snapshot?.lastClientTools ?? this._lastClientTools,\n createdAt: input.createdAt\n }),\n // Only persist while the stream is still active. The ACK handler (client\n // reconnect → replayChunks) may have already persisted + completed the\n // orphaned stream before fiber recovery runs; persisting again on the same\n // chunks would double the assistant message's parts. (The engine ANDs this\n // with the shared never-drop-settled-work clause.)\n shouldPersistOrphanedPartial: (input) => input.streamStillActive,\n persistOrphanedStream: (streamId) =>\n this._persistOrphanedStream(streamId),\n completeRecoveredStream: (streamId) => {\n this._resumableStream.complete(streamId);\n },\n dispatchRecoveredTurn: (input) => this._dispatchRecoveredChatTurn(input)\n } satisfies ChatFiberWakeHooks<AIChatRecoveryClassification>);\n }\n\n /**\n * Resolve the orphaned stream for a recovered chat turn — drives BOTH the wake\n * path (full result) and the give-up terminalization (which reads only\n * `.streamId`). Prefers the newest durable stream row keyed by the recovery-\n * root request id; falls back to the live active stream; `streamId` is `\"\"`\n * when neither survives. `AIChatAgent` does not model terminal stream status,\n * so `streamStatus` is left `undefined` (keeping the engine's terminal-stream\n * branches dead here) — see the \"substrate capabilities are optional\" decision\n * in the RFC.\n */\n private _resolveAIChatRecoveryStream(\n requestId: string\n ): ResolvedRecoveryStream {\n let streamId = \"\";\n if (requestId) {\n streamId =\n this._resumableStream.latestStreamInfoForRequest(requestId)?.id ?? \"\";\n }\n if (!streamId && this._resumableStream.hasActiveStream()) {\n streamId = this._resumableStream.activeStreamId ?? \"\";\n }\n const streamStillActive = Boolean(\n streamId &&\n this._resumableStream.hasActiveStream() &&\n this._resumableStream.activeStreamId === streamId\n );\n return { streamId, streamStillActive };\n }\n\n /**\n * Classify a recovered turn as `retry` or `continue`. The `shouldRetryPreStream`\n * detail is threaded to the dispatch decision; `emptyPartialNewTurn` only\n * influences the reported kind (an empty partial persists nothing, so a new turn\n * is re-run fresh rather than merged into the previous assistant — #1691). The\n * `persist: false` discard case stays \"continue\" here and only surfaces as\n * \"retry\" on the `chat:recovery:scheduled` event, decided in dispatch.\n */\n private _classifyRecoveredChatTurn(input: ClassifyRecoveredTurnInput): {\n recoveryKind: ChatRecoveryKind;\n detail: AIChatRecoveryClassification;\n } {\n const shouldRetryPreStream = this._shouldRetryRecoveredPreStreamTurn(\n input.snapshot,\n input.streamId,\n input.partial\n );\n const preStreamLeaf =\n this.messages.length > 0\n ? this.messages[this.messages.length - 1]\n : undefined;\n const emptyPartialNewTurn =\n !!input.streamId &&\n input.snapshot?.continuation === false &&\n !!input.snapshot.latestUserMessageId &&\n input.partial.text === \"\" &&\n input.partial.parts.length === 0 &&\n preStreamLeaf?.role === \"user\" &&\n preStreamLeaf.id === input.snapshot.latestUserMessageId;\n const recoveryKind: ChatRecoveryKind =\n shouldRetryPreStream || emptyPartialNewTurn ? \"retry\" : \"continue\";\n return { recoveryKind, detail: { shouldRetryPreStream } };\n }\n\n /**\n * The retry/continue/skip decision for a recovered chat turn, run after the\n * partial is persisted and the stream completed. A NEW turn that left no\n * persisted assistant partial (the leaf is still the user message) is re-run\n * fresh instead of continued (which would clone + merge into the previous\n * assistant turn — #1691); this lost-partial check is re-derived here from the\n * now-updated leaf rather than carried from classify.\n */\n private async _dispatchRecoveredChatTurn(\n input: DispatchRecoveredTurnInput<AIChatRecoveryClassification>\n ): Promise<void> {\n const { incident, options, snapshot, recoveryRootRequestId } = input;\n const originIds =\n this._originMessageIdsFor(input.requestId) ?? snapshot?.originMessageIds;\n const leaf =\n this.messages.length > 0\n ? this.messages[this.messages.length - 1]\n : undefined;\n const lostPartialUserId =\n snapshot?.continuation === false &&\n snapshot.latestUserMessageId &&\n leaf?.role === \"user\" &&\n leaf.id === snapshot.latestUserMessageId\n ? snapshot.latestUserMessageId\n : undefined;\n\n const targetId =\n input.detail.shouldRetryPreStream || lostPartialUserId !== undefined\n ? undefined\n : this._findLastAssistantMessage()?.id;\n\n if (input.detail.shouldRetryPreStream && options.continue !== false) {\n await this._chatRecoveryEngine().scheduleRecovery({\n incident,\n recoveryKind: input.recoveryKind,\n callback: \"_chatRecoveryRetry\",\n data: {\n targetUserId: snapshot?.latestUserMessageId,\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n lastBody: snapshot?.lastBody ?? null,\n lastClientTools: snapshot?.lastClientTools ?? null,\n ...(originIds ? { originMessageIds: originIds } : {})\n }\n });\n } else if (lostPartialUserId !== undefined && options.continue !== false) {\n // Re-run the orphaned new turn fresh instead of continuing (and merging\n // into) the previous assistant message. The incident may have opened as\n // `continue`, but the action (and the reported kind) is a `retry`.\n await this._chatRecoveryEngine().scheduleRecovery({\n incident,\n recoveryKind: \"retry\",\n callback: \"_chatRecoveryRetry\",\n data: {\n targetUserId: lostPartialUserId,\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n lastBody: snapshot?.lastBody ?? null,\n lastClientTools: snapshot?.lastClientTools ?? null,\n ...(originIds ? { originMessageIds: originIds } : {})\n }\n });\n } else if (options.continue !== false) {\n await this._chatRecoveryEngine().scheduleRecovery({\n incident,\n recoveryKind: input.recoveryKind,\n callback: \"_chatRecoveryContinue\",\n data: {\n ...(targetId ? { targetAssistantId: targetId } : {}),\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n ...(snapshot\n ? {\n lastBody: snapshot.lastBody ?? null,\n lastClientTools: snapshot.lastClientTools ?? null\n }\n : {}),\n ...(originIds ? { originMessageIds: originIds } : {})\n }\n });\n } else {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"skipped\",\n \"continue_disabled\"\n );\n }\n }\n\n /**\n * Called when an interrupted chat stream is detected after restart.\n * Return options to control recovery:\n *\n * - `{}` (default): persist partial response + schedule continuation\n * - `{ continue: false }`: persist but don't continue\n * - `{ persist: false, continue: false }`: handle everything yourself\n *\n * `ctx.recoveryData` contains any data checkpointed via `this.stash()`\n * during the turn (e.g., OpenAI `responseId`). If recovery happens before\n * any stream chunks exist and the latest message is still the unanswered\n * user message from the interrupted turn, the framework retries that turn\n * automatically unless continuation is disabled.\n */\n protected async onChatRecovery(\n // oxlint-disable-next-line @typescript-eslint/no-unused-vars -- overridable hook\n _ctx: ChatRecoveryContext\n ): Promise<ChatRecoveryOptions | void> {\n return {};\n }\n\n async _chatRecoveryContinue(data?: ChatRecoveryContinueData): Promise<void> {\n await this._dispatchChatRecovery(\n \"_chatRecoveryContinue\",\n data,\n (onTurnStarted) =>\n this._chatRecoveryOriginIdsScope.run(data?.originMessageIds, () =>\n this._chatRecoveryContinueDetached(data, onTurnStarted)\n )\n );\n }\n\n protected async _chatRecoveryContinueDetached(\n data?: ChatRecoveryContinueData,\n onTurnStarted?: () => void\n ): Promise<void> {\n if (\n await this._chatRecoveryEngine().isRecoveryCancelled(data?.incidentId)\n ) {\n return;\n }\n const previousRootRequestId = this._activeChatRecoveryRootRequestId;\n this._activeChatRecoveryRootRequestId =\n data?.originalRequestId ?? previousRootRequestId;\n try {\n const recoveryConfig = this._resolveChatRecoveryConfig();\n const ready = await this.waitUntilStable({\n timeout: recoveryConfig.stableTimeoutMs,\n // Recovery-scoped: a DEAD server-tool `input-available` orphan must not\n // block stability (A.2 repairs it below), so gate on the client-\n // resolvable predicate. A genuinely-pending CLIENT interaction still\n // keeps it unstable and parks via the `!ready` branch.\n pendingInteraction: () => this.hasPendingClientInteraction()\n });\n if (!ready) {\n // PARK, don't burn the budget: a stable-state timeout while a CLIENT\n // interaction is pending is not churn — the turn is correctly waiting\n // for the client to replay an interrupted tool-result / approval after\n // reconnect, which drives a fresh continuation independently of this\n // retry loop. Retrying here would just time out again (the human hasn't\n // answered) and eventually seal a healthy turn on `stable_timeout`. So\n // stop the loop, resolve the live \"recovering…\" indicator, and let the\n // client's replay resume the turn.\n if (await this._parkRecoveryForPendingInteraction(data)) {\n return;\n }\n console.warn(\n \"[AIChatAgent] _chatRecoveryContinue timed out waiting for stable state\"\n );\n // A stable-state timeout under deploy churn is usually transient (the\n // isolate is still settling / another deploy is in flight). Reschedule\n // within the attempt budget instead of permanently abandoning a\n // recoverable turn; only give up once the budget is exhausted.\n if (\n await this._rescheduleRecoveryAfterStableTimeout(\n \"_chatRecoveryContinue\",\n data,\n recoveryConfig.maxAttempts\n )\n ) {\n return;\n }\n // Budget spent: terminalize through the SAME exhaustion path as deploy\n // recovery (fires `onExhausted`, delivers the `terminalMessage` banner)\n // instead of silently dropping the turn — otherwise an app relying on\n // `onExhausted` sees an eternal spinner.\n await this._exhaustRecoveryAfterStableTimeout(\n \"_chatRecoveryContinue\",\n data\n );\n return;\n }\n\n const targetId = data?.targetAssistantId;\n if (targetId && this._findLastAssistantMessage()?.id !== targetId) {\n // The leaf moved, so this continuation is superseded — skip it.\n // NOTE: unlike `@cloudflare/think`, AIChatAgent does NOT distinguish an\n // assistant leaf (recovery's own forward progress) from a newer user\n // turn here, because AIChatAgent has no durable-submission layer to\n // protect — there is nothing to mark `skipped` vs leave `running`. If\n // AIChatAgent ever gains submissions, mirror Think's split in\n // `_chatRecoveryContinue` or this skip will silently clobber them.\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n \"skipped\",\n \"conversation_changed\"\n );\n return;\n }\n\n this._applyRecoveredRequestContext(data);\n // `continueLastTurn` repairs interrupted server-tool orphans before it\n // re-enters inference (`_repairInterruptedToolsBeforeTurn`), so the\n // recovered transcript is settled and the next `convertToModelMessages`\n // doesn't 400 with `AI_MissingToolResultsError`.\n onTurnStarted?.();\n this._takeRecoveryReschedule(data?.incidentId);\n const result = await this.continueLastTurn();\n if (\n result.status !== \"completed\" &&\n this._takeRecoveryReschedule(data?.incidentId)\n ) {\n // Interrupted again: the attempt it scheduled owns the outcome.\n return;\n }\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n result.status === \"completed\"\n ? \"completed\"\n : result.status === \"skipped\"\n ? \"skipped\"\n : \"failed\",\n result.error\n );\n } catch (error) {\n // AIChatAgent otherwise has no continuation `catch` (a thrown error\n // propagates to the driving Task attempt, or the routed one-shot\n // schedule row). The ONLY case we intercept is an OOM thrown out of\n // the turn (#1825): route it through the\n // tight OOM-retry budget, and rethrow everything else so the existing\n // behavior is byte-identical for non-OOM errors.\n if (await this._handleRecoveryOom(\"_chatRecoveryContinue\", data, error)) {\n return;\n }\n throw error;\n } finally {\n this._activeChatRecoveryRootRequestId = previousRootRequestId;\n // If this facet is an agent-tool child, its recovered turn just settled\n // outside `startAgentToolRun`'s finalizer — eagerly close the run so a\n // re-attached parent collects the terminal immediately rather than\n // waiting out a no-progress window.\n await this._reconcileOwnStaleAgentToolChildRuns();\n }\n }\n\n private _applyRecoveredRequestContext(\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined\n ): void {\n if (!data) return;\n if (\"lastClientTools\" in data) {\n this._lastClientTools = data.lastClientTools ?? undefined;\n }\n if (\"lastBody\" in data) {\n this._lastBody = data.lastBody ?? undefined;\n }\n if (\"lastClientTools\" in data || \"lastBody\" in data) {\n this._persistRequestContext();\n }\n }\n\n /**\n * Route a live stream stall (the {@link chatStreamStallTimeoutMs} watchdog\n * fired) into the same bounded-recovery machinery a deploy/eviction\n * interruption uses (#1626). Mirrors `@cloudflare/think`'s stall path: open or\n * reuse the incident under the turn's recovery identity, deliver terminal UX\n * if the budget is spent, otherwise schedule a `_chatRecoveryContinue`.\n *\n * Unlike Think there is no durable-submission layer to complete here, so the\n * schedule payload carries no `recoveredRequestId`.\n *\n * Returns `\"exhausted\"` when the budget was spent (terminal UX already\n * delivered), `\"scheduled\"` when a continuation was queued, or `\"declined\"`\n * / `\"failed\"` when `onChatRecovery` opted out or threw — the caller then\n * delivers the ordinary terminal error.\n */\n private async _routeStallToBoundedRecovery(\n input: StreamInterruptionRoute\n ): Promise<\"scheduled\" | \"exhausted\" | \"declined\" | \"failed\"> {\n const recoveryRootRequestId =\n this._activeChatRecoveryRootRequestId ?? input.requestId;\n const originIds = this._originMessageIdsFor(input.requestId);\n const latestUserMessageId =\n [...this.messages].reverse().find((m) => m.role === \"user\")?.id ?? null;\n // A new turn that failed before producing any part has nothing to continue:\n // continuing would clone and merge into the previous assistant (#1691), so\n // re-run it fresh like `_dispatchRecoveredChatTurn` does after a restart.\n const leaf = this.messages[this.messages.length - 1];\n const lostPartialUserId =\n !input.continuation &&\n input.partialParts.length === 0 &&\n leaf?.role === \"user\" &&\n leaf.id === latestUserMessageId\n ? latestUserMessageId\n : undefined;\n const recoveryKind = lostPartialUserId ? \"retry\" : \"continue\";\n const { incident, config, exhausted } =\n await this._beginChatRecoveryIncident({\n requestId: input.requestId,\n recoveryRootRequestId,\n latestUserMessageId,\n recoveryKind\n });\n const partialText = input.partialParts\n .filter(\n (p): p is { type: \"text\"; text: string } =>\n (p as { type?: string }).type === \"text\"\n )\n .map((p) => p.text)\n .join(\"\");\n if (exhausted) {\n // Budget spent: deliver the SAME terminal UX as deploy-recovery\n // exhaustion (terminalMessage + onExhausted + chat:recovery:exhausted)\n // instead of letting the raw stall error leak out. `firstSeenAt` is the\n // closest available turn-start proxy here.\n await this._exhaustChatRecovery(\n incident,\n config,\n { text: partialText, parts: input.partialParts },\n input.streamId,\n incident.firstSeenAt\n );\n return \"exhausted\";\n }\n\n const liveTurn = this._liveChatRecoveryTurns.get(input.requestId);\n let options: ChatRecoveryOptions;\n try {\n options =\n (await this.onChatRecovery({\n incidentId: incident.incidentId,\n recoveryRootRequestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind,\n streamId: input.streamId,\n requestId: input.requestId,\n partialText,\n partialParts: input.partialParts,\n recoveryData: liveTurn?.recoveryData ?? null,\n messages: [...this.messages],\n lastBody: this._lastBody,\n lastClientTools: this._lastClientTools,\n createdAt: liveTurn?.createdAt ?? incident.firstSeenAt\n })) ?? {};\n } catch (error) {\n console.error(\n \"[AIChatAgent] onChatRecovery threw during stream recovery:\",\n error\n );\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"failed\",\n error instanceof Error ? error.message : String(error)\n );\n return \"failed\";\n }\n // `persist: false` drops the partial unless it holds settled tool results\n // (non-idempotent work that must not re-run), same as Think.\n const discardPartial =\n options.persist === false &&\n !partialHasSettledToolResults(input.partialParts);\n if (discardPartial) await input.discardPartial();\n if (options.continue === false) {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"skipped\",\n \"continue_disabled\"\n );\n return \"declined\";\n }\n\n // A dropped partial on a new turn leaves the user's message as the leaf,\n // so there is nothing to continue: retry the turn instead.\n const leafAfterDiscard = this.messages[this.messages.length - 1];\n const retryUserId =\n lostPartialUserId ??\n (discardPartial &&\n !input.continuation &&\n leafAfterDiscard?.role === \"user\"\n ? leafAfterDiscard.id\n : undefined);\n // Stalls count too: a turn that streams a little and then stalls resets\n // the progress-keyed attempt cap every time, so this is its only bound.\n const retries = await this._chatRecoveryEngine().recordTransientRetry(\n incident.incidentId\n );\n const delaySeconds = input.backoff\n ? chatRecoveryBackoffSeconds(retries)\n : undefined;\n // Inside a recovery attempt, the next attempt must not join the run that\n // is scheduling it (see `ChatRecoveryScheduleReason`).\n const reason =\n this._activeChatRecoveryRootRequestId !== undefined\n ? \"chained_retry\"\n : undefined;\n if (retryUserId) {\n await this._chatRecoveryEngine().scheduleRecovery({\n incident,\n delaySeconds,\n reason,\n recoveryKind: \"retry\",\n callback: \"_chatRecoveryRetry\",\n data: {\n targetUserId: retryUserId,\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n lastBody: this._lastBody ?? null,\n lastClientTools: this._lastClientTools ?? null,\n ...(originIds ? { originMessageIds: originIds } : {})\n }\n });\n this._rescheduledRecoveryIncidents.add(incident.incidentId);\n return \"scheduled\";\n }\n await this._chatRecoveryEngine().scheduleRecovery({\n incident,\n delaySeconds,\n reason,\n recoveryKind: \"continue\",\n callback: \"_chatRecoveryContinue\",\n data: {\n ...(input.targetAssistantId\n ? { targetAssistantId: input.targetAssistantId }\n : {}),\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n lastBody: this._lastBody ?? null,\n lastClientTools: this._lastClientTools ?? null,\n ...(originIds ? { originMessageIds: originIds } : {})\n }\n });\n this._rescheduledRecoveryIncidents.add(incident.incidentId);\n return \"scheduled\";\n }\n\n /** Incidents whose running recovery attempt scheduled the next attempt. */\n private _rescheduledRecoveryIncidents = new Set<string>();\n\n private _takeRecoveryReschedule(incidentId: string | undefined): boolean {\n return (\n incidentId !== undefined &&\n this._rescheduledRecoveryIncidents.delete(incidentId)\n );\n }\n\n /**\n * {@link _routeStallToBoundedRecovery} for the stream `catch`: a routing\n * failure (e.g. a rejected incident write) degrades to `\"failed\"`, so the\n * caller still delivers its terminal error frame.\n */\n private async _routeStreamInterruption(\n input: StreamInterruptionRoute\n ): Promise<\"scheduled\" | \"exhausted\" | \"declined\" | \"failed\"> {\n try {\n return await this._routeStallToBoundedRecovery(input);\n } catch (error) {\n console.error(\n \"[AIChatAgent] routing a stream interruption into recovery failed; delivering the terminal error\",\n error\n );\n return \"failed\";\n }\n }\n\n /**\n * Reschedule a recovery callback that timed out waiting for stable state,\n * consuming one attempt. Returns `true` if rescheduled, `false` if the\n * attempt budget is exhausted (caller should then fail terminally).\n */\n private async _rescheduleRecoveryAfterStableTimeout(\n callback: ChatRecoveryScheduleCallback,\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined,\n maxAttempts: number\n ): Promise<boolean> {\n // The attempt-bump + scheduled/stable_timeout_retry persist + delayed\n // non-idempotent reschedule live in the shared ChatRecoveryEngine; this\n // method is the package's adapter binding, symmetric with `Think`. See\n // design/rfc-chat-recovery-foundation.md.\n return this._chatRecoveryEngine().rescheduleAfterStableTimeout({\n incidentId: data?.incidentId,\n callback,\n data,\n fallbackMaxAttempts: maxAttempts\n });\n }\n\n /**\n * Park a recovery continuation that timed out waiting for stable state\n * because the turn is holding a pending CLIENT interaction (an\n * `input-available` client-tool part or an `approval-requested` part — see\n * `hasPendingClientInteraction`). Such a turn is WAITING ON THE HUMAN, not\n * stuck: the client replays the interrupted tool-result / approval after\n * reconnect, which drives a fresh continuation independently of the recovery\n * retry loop. Burning the attempt budget on that wait (each `waitUntilStable`\n * times out because the human hasn't answered) would seal a perfectly healthy\n * turn on `stable_timeout` — the symptom behind HITL \"session recovery errors\"\n * under deploy churn.\n *\n * So instead of rescheduling or exhausting, we stop the loop and mark the\n * incident `skipped` (reason `awaiting_client_interaction`). That retains the\n * incident record (a later genuine interruption re-evaluates it) while\n * resolving the live \"recovering…\" indicator via `_updateChatRecoveryIncident`\n * so the client sees the parked tool-call UI rather than an eternal spinner.\n * A client that never returns is reclaimed by the incident TTL sweep and DO\n * idle-eviction. SERVER-tool orphans are excluded by `hasPendingClientInteraction`\n * (their `execute` died with the isolate), so they still reschedule / exhaust\n * via the normal path. Mirrors the same helper in `@cloudflare/think`.\n *\n * Returns `true` when the recovery was parked (caller must return), `false`\n * when there is no pending client interaction (caller proceeds to the normal\n * reschedule / exhaustion path).\n */\n private async _parkRecoveryForPendingInteraction(\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined\n ): Promise<boolean> {\n if (!this.hasPendingClientInteraction()) return false;\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n \"skipped\",\n \"awaiting_client_interaction\"\n );\n return true;\n }\n\n /**\n * Terminalize a recovery turn that has run out of stable-state-timeout retry\n * budget — or whose incident record has vanished — by routing through the\n * SAME `_exhaustChatRecovery` path as deploy-recovery exhaustion. It fires\n * `onExhausted`, emits `chat:recovery:exhausted`, and delivers the configured\n * `terminalMessage`.\n *\n * This replaces the older give-up that only set the incident to `failed`,\n * which bypassed `_exhaustChatRecovery` entirely — so an app relying on\n * `onExhausted` for the terminal banner regressed to an eternal spinner when\n * recovery gave up under extreme churn. Shared by `_chatRecoveryRetry` and\n * `_chatRecoveryContinue`; mirrors the same helper in `@cloudflare/think`.\n *\n * Exactly-once terminalization here rests SOLELY on the\n * `stored?.status === \"exhausted\"` re-entry guard below — unlike\n * `@cloudflare/think`, `@cloudflare/ai-chat` has no durable-submission layer\n * to short-circuit a duplicate alarm earlier. The incident read/write are\n * best-effort because they back only that guard, not the terminal UX: a\n * failed read synthesizes the incident and a failed seal write costs at most\n * a re-delivered banner on a duplicate alarm.\n *\n * Two residual at-least-once edges, both deliberately accepted as \"deliver a\n * second banner\" ≫ \"silently drop the turn\":\n * • No `incidentId` at all in the payload (only reachable via a direct/test\n * invocation — every production recovery enqueue carries one): the\n * synthesized incident can't be persisted (no key), so the guard can't\n * arm.\n * • The record is swept AGAIN between two alarms (the guard re-persists on\n * the first, so this needs a second independent sweep) — vanishingly\n * unlikely.\n */\n /**\n * Host memory-limit policy hook (#1825), dispatched structurally by\n * Lifecycle's circuit breaker — protected because it is framework\n * machinery, not part of the public chat API. Tasks applies the breaker to\n * root recovery runs; the routed dynamic-agent fallback applies it to\n * `recoveryLoop` schedule rows (see `RecoveryLoopScheduleOptions`). At the\n * strike budget this hook seals active incidents via\n * {@link _cf_sealMemoryLimitedRecovery}.\n */\n protected async onAlarmMemoryLimit(context: { readonly sealed: boolean }) {\n if (!context.sealed) return;\n await this._cf_sealMemoryLimitedRecovery();\n }\n\n /**\n * Seal any still-live recovery incident as an out-of-memory exhaustion\n * when the alarm circuit breaker trips at its strike budget (#1825). Runs\n * at the outermost alarm frame (post-unwind), so the terminal banner /\n * `onExhausted` and the sealed-incident write can land where mid-turn\n * writes OOMed. Reuses the shared give-up spine via the recovery engine.\n */\n private async _cf_sealMemoryLimitedRecovery(): Promise<void> {\n const active = await listActiveChatRecoveryIncidents(this.ctx.storage);\n for (const { incident } of active) {\n const callback: ChatRecoveryScheduleCallback =\n incident.recoveryKind === \"retry\"\n ? \"_chatRecoveryRetry\"\n : \"_chatRecoveryContinue\";\n await this._chatRecoveryEngine().exhaustRecoveryGiveUp({\n callback,\n data: { incidentId: incident.incidentId },\n reason: \"out_of_memory\"\n });\n }\n }\n\n private _exhaustRecoveryAfterStableTimeout(\n callback: ChatRecoveryScheduleCallback,\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined\n ): Promise<void> {\n // The give-up spine (read → re-entry-guard → build-exhausted-incident →\n // terminalize-before-seal → best-effort seal) lives in the shared\n // ChatRecoveryEngine; this is the package binding, symmetric with `Think`.\n // `AIChatAgent` always gives up with `stable_timeout` (its only give-up\n // trigger) and never sets `recoveredRequestId`, so the engine's unified\n // root-id chain collapses to `originalRequestId ?? activeRoot ?? stored…`\n // exactly as before. The terminalize + stream/partial hooks are wired on\n // the adapter above. See design/rfc-chat-recovery-foundation.md.\n return this._chatRecoveryEngine().exhaustRecoveryGiveUp({\n callback,\n data,\n reason: \"stable_timeout\"\n });\n }\n\n /**\n * Apply the tight OOM-retry budget to a recovery error (#1825). Symmetric with\n * `@cloudflare/think`'s `_handleRecoveryOom`: invoked from the narrow OOM-only\n * `catch` in `_chatRecoveryContinue` / `_chatRecoveryRetry`, i.e. for an OOM\n * that is *thrown* out of a recovery turn (e.g. storage/SQL ops rejecting with\n * the memory-limit-reset message after an isolate reset). An OOM caught inside\n * `continueLastTurn` that surfaces as a returned `error` result is NOT routed\n * here — that turn was already terminalized, so re-driving it would be wasteful\n * and risk a second terminal signal.\n *\n * The reliable terminator is the begin-path (`evaluateChatRecoveryIncident`),\n * which seals once `oomAttempts` exceeds the budget, running before the\n * memory-heavy turn in the low-memory window where writes succeed. This method\n * persists `oomAttempts` (small writes) for the begin path to act on, and\n * schedules a delayed re-run while under budget.\n *\n * Returns `true` when the error was an OOM and this method owns the outcome\n * (rescheduled a delayed re-run while under budget, or terminalized with\n * `reason=\"out_of_memory\"` once over budget / untrackable / bookkeeping\n * failed), `false` for non-OOM errors so the caller proceeds normally.\n */\n private async _handleRecoveryOom(\n callback: ChatRecoveryScheduleCallback,\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined,\n error: unknown\n ): Promise<boolean> {\n if (!isDurableObjectMemoryLimitReset(error)) return false;\n let decision: \"rescheduled\" | \"exhausted\" = \"exhausted\";\n try {\n decision = await this._chatRecoveryEngine().recordOomAndDecide({\n incidentId: data?.incidentId,\n callback,\n data,\n maxOomRetries: this._resolveChatRecoveryConfig().maxOomRetries\n });\n } catch (bookkeepingError) {\n // The bump/reschedule writes can themselves reject in the degraded isolate\n // that just OOMed. Fail closed (seal) rather than risk a silent wedge; the\n // finite `maxRecoveryWork` backstop covers anything that slips past.\n console.error(\n \"[AIChatAgent] failed to record OOM recovery attempt; terminalizing\",\n bookkeepingError\n );\n decision = \"exhausted\";\n }\n if (decision === \"exhausted\") {\n await this._chatRecoveryEngine().exhaustRecoveryGiveUp({\n callback,\n data,\n reason: \"out_of_memory\"\n });\n }\n return true;\n }\n\n private _shouldRetryRecoveredPreStreamTurn(\n snapshot: ChatFiberSnapshot | null,\n streamId: string,\n partial: { text: string; parts: unknown[] }\n ): snapshot is ChatFiberSnapshot & {\n latestUserMessageId: string;\n } {\n if (\n !snapshot ||\n snapshot.continuation ||\n !snapshot.latestUserMessageId ||\n streamId ||\n partial.text ||\n partial.parts.length > 0\n ) {\n return false;\n }\n\n const lastMessage =\n this.messages.length > 0 ? this.messages[this.messages.length - 1] : null;\n return (\n lastMessage?.role === \"user\" &&\n lastMessage.id === snapshot.latestUserMessageId\n );\n }\n\n async _chatRecoveryRetry(data?: ChatRecoveryRetryData): Promise<void> {\n await this._dispatchChatRecovery(\n \"_chatRecoveryRetry\",\n data,\n (onTurnStarted) =>\n this._chatRecoveryOriginIdsScope.run(data?.originMessageIds, () =>\n this._chatRecoveryRetryDetached(data, onTurnStarted)\n )\n );\n }\n\n protected async _chatRecoveryRetryDetached(\n data?: ChatRecoveryRetryData,\n onTurnStarted?: () => void\n ): Promise<void> {\n if (\n await this._chatRecoveryEngine().isRecoveryCancelled(data?.incidentId)\n ) {\n return;\n }\n const previousRootRequestId = this._activeChatRecoveryRootRequestId;\n this._activeChatRecoveryRootRequestId =\n data?.originalRequestId ?? previousRootRequestId;\n try {\n const recoveryConfig = this._resolveChatRecoveryConfig();\n const ready = await this.waitUntilStable({\n timeout: recoveryConfig.stableTimeoutMs,\n // Recovery-scoped narrow predicate (see `_chatRecoveryContinue`): a dead\n // server-tool orphan must not block stability; a real client\n // interaction still parks via the `!ready` branch.\n pendingInteraction: () => this.hasPendingClientInteraction()\n });\n if (!ready) {\n // PARK while a CLIENT interaction is pending — the turn is waiting for\n // the human, not churning; see `_chatRecoveryContinue` for the full\n // rationale.\n if (await this._parkRecoveryForPendingInteraction(data)) {\n return;\n }\n console.warn(\n \"[AIChatAgent] _chatRecoveryRetry timed out waiting for stable state\"\n );\n if (\n await this._rescheduleRecoveryAfterStableTimeout(\n \"_chatRecoveryRetry\",\n data,\n recoveryConfig.maxAttempts\n )\n ) {\n return;\n }\n // Budget spent: terminalize through the SAME exhaustion path as deploy\n // recovery (fires `onExhausted`, delivers the `terminalMessage` banner)\n // instead of silently dropping the turn — otherwise an app relying on\n // `onExhausted` sees an eternal spinner.\n await this._exhaustRecoveryAfterStableTimeout(\n \"_chatRecoveryRetry\",\n data\n );\n return;\n }\n\n const lastMessage =\n this.messages.length > 0\n ? this.messages[this.messages.length - 1]\n : null;\n if (!lastMessage || lastMessage.role !== \"user\") {\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n \"skipped\",\n \"no_unanswered_user_message\"\n );\n return;\n }\n\n if (data?.targetUserId && lastMessage.id !== data.targetUserId) {\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n \"skipped\",\n \"conversation_changed\"\n );\n return;\n }\n\n this._applyRecoveredRequestContext(data);\n // The retry runs through `_runProgrammaticChatTurn`, which repairs any\n // interrupted tool orphan before re-entering inference\n // (`_repairInterruptedToolsBeforeTurn`). The retry path normally re-runs\n // an unanswered user-message tail (no assistant orphan to repair), so that\n // is a defensive no-op here, but keeps both recovery entrypoints converged.\n onTurnStarted?.();\n this._takeRecoveryReschedule(data?.incidentId);\n const result = await this._retryLastUserTurn(\n this._lastClientTools,\n this._lastBody\n );\n if (\n result.status !== \"completed\" &&\n this._takeRecoveryReschedule(data?.incidentId)\n ) {\n // Interrupted again: the attempt it scheduled owns the outcome.\n return;\n }\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n result.status === \"completed\"\n ? \"completed\"\n : result.status === \"skipped\"\n ? \"skipped\"\n : \"failed\",\n result.error\n );\n } catch (error) {\n // OOM-only intercept, rethrowing everything else (see\n // `_chatRecoveryContinue`, #1825).\n if (await this._handleRecoveryOom(\"_chatRecoveryRetry\", data, error)) {\n return;\n }\n throw error;\n } finally {\n this._activeChatRecoveryRootRequestId = previousRootRequestId;\n // If this facet is an agent-tool child, its recovered turn just settled\n // outside `startAgentToolRun`'s finalizer — eagerly close the run so a\n // re-attached parent collects the terminal immediately rather than\n // waiting out a no-progress window. The pre-stream retry path settles via\n // `_retryLastUserTurn`, which (like `continueLastTurn`) never hits the\n // finalizer, so it needs the same reconcile as `_chatRecoveryContinue`.\n await this._reconcileOwnStaleAgentToolChildRuns();\n }\n }\n\n /**\n * Extract partial text and parts from stored stream chunks.\n */\n private _getPartialStreamText(streamId: string): {\n text: string;\n parts: MessagePart[];\n hasSettledToolResults: boolean;\n } {\n return aiSdkRecoveryCodec.toRecoveryPartial(\n this._resumableStream.getStreamChunks(streamId).map((chunk) => chunk.body)\n );\n }\n\n /**\n * The turn whose finished stream is waiting for its message write: the\n * cutover rides on the instance, not on an argument, so a subclass that\n * overrides {@link persistMessages} and calls `super` with only the\n * messages still lands the message, the stream's settlement and the\n * deletion of its rows in one transaction. Consumed by the first persist\n * that carries the turn's message; cleared when the turn ends.\n */\n #pendingCutover: {\n streamId: string;\n messageId: string;\n discard: boolean;\n } | null = null;\n\n async persistMessages(\n messages: UIMessage[],\n excludeBroadcastIds: string[] = [],\n /** @internal */\n options?: { _deleteStaleRows?: boolean }\n ) {\n // Snapshot the pre-write transcript: `this.messages` is mirrored from the\n // change feed and therefore mutates as the loop below writes.\n const priorMessages = [...this.messages];\n const priorById = new Map(priorMessages.map((m) => [m.id, m]));\n const mergedMessages = reconcileMessages(messages, priorMessages, (msg) =>\n this._sanitizeMessageForPersistence(msg)\n );\n\n const toWrite: UIMessage[] = [];\n for (const message of mergedMessages) {\n const resolved = this._sanitizeMessageForPersistence(message);\n // The live array mirrors storage, so a message serializing to what it\n // already holds is already stored. Comparing here is a string compare;\n // letting Sessions discover it would cost a row read and, for media, a\n // decode and hash of every payload on every turn.\n const prior = priorById.get(resolved.id);\n if (prior && JSON.stringify(prior) === JSON.stringify(resolved)) continue;\n toWrite.push(resolved);\n }\n // The cutover: a persist that carries the finished turn's message\n // lands every changed message in the same transaction that settles the\n // stream and drops its rows. A persist of other messages (an override\n // writing its own first) takes the plain path and leaves the cutover\n // pending. The change feed (and auto-compaction) run once the\n // transaction has committed.\n const cutover = this.#pendingCutover;\n if (\n cutover &&\n mergedMessages.some((message) => message.id === cutover.messageId)\n ) {\n this.#pendingCutover = null;\n const sync = this.#session.__DO_NOT_USE_WILL_BREAK__sync();\n const afters: Array<() => Promise<void>> = [];\n try {\n this._resumableStream.cutover(\n cutover.streamId,\n () => {\n for (const message of toWrite)\n afters.push(sync.upsert(message).after);\n },\n { discard: cutover.discard }\n );\n } catch (error) {\n // The settle transaction rolled back: no row landed, but the\n // session's in-memory caches already counted the writes.\n sync.abandon();\n throw error;\n }\n for (const after of afters) await after();\n } else {\n for (const message of toWrite) await this.#session.upsertMessage(message);\n }\n\n // Regeneration can submit a strict subset of the server transcript. Keep\n // the old subset guard, but delete through Sessions so descendants splice\n // to their grandparent instead of breaking the active path.\n if (options?._deleteStaleRows) {\n const serverIds = new Set(priorMessages.map((message) => message.id));\n const isSubsetOfServer = mergedMessages.every((message) =>\n serverIds.has(message.id)\n );\n if (isSubsetOfServer) {\n const keepIds = new Set(mergedMessages.map((message) => message.id));\n await this._deleteMessagesByIds(\n this.messages\n .map((message) => message.id)\n .filter((id) => !keepIds.has(id))\n );\n }\n }\n\n // Retention counts STORED rows, not the hydrated window: a transcript\n // larger than the hydration budget holds rows this.messages never saw.\n if (this.maxPersistedMessages != null) {\n const stored = await this.#session.getHistoryRowStats();\n const excess = stored.length - this.maxPersistedMessages;\n if (excess > 0) {\n await this._deleteMessagesByIds(\n stored.slice(0, excess).map((row) => row.id)\n );\n }\n }\n\n this._broadcastChatMessage(\n {\n messages: mergedMessages,\n type: MessageType.CF_AGENT_CHAT_MESSAGES\n },\n excludeBroadcastIds\n );\n }\n\n /**\n * Finds an existing assistant message that contains a tool part with the given toolCallId.\n * Used to detect when a tool result should update an existing message rather than\n * creating a new one.\n *\n * @param toolCallId - The tool call ID to search for\n * @returns The existing message if found, undefined otherwise\n */\n private _findMessageByToolCallId(toolCallId: string): UIMessage | undefined {\n for (const msg of this.messages) {\n if (msg.role !== \"assistant\") continue;\n\n for (const part of msg.parts) {\n if (\"toolCallId\" in part && part.toolCallId === toolCallId) {\n return msg;\n }\n }\n }\n return undefined;\n }\n\n private _findLastAssistantMessage(): UIMessage | undefined {\n for (let i = this.messages.length - 1; i >= 0; i--) {\n if (this.messages[i].role === \"assistant\") {\n return this.messages[i];\n }\n }\n\n return undefined;\n }\n\n private _createStreamingAssistantMessage(continuation: boolean): UIMessage {\n if (continuation) {\n const lastAssistant = this._findLastAssistantMessage();\n if (lastAssistant) {\n return structuredClone(lastAssistant);\n }\n }\n\n return {\n id: `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`,\n role: \"assistant\",\n parts: []\n };\n }\n\n /**\n * Applies the ai-chat-specific normalization Sessions does not do.\n *\n * Sessions already strips OpenAI ephemeral fields (itemId,\n * reasoningEncryptedContent) and drops truly empty reasoning parts on every\n * write, so those steps are not repeated here.\n *\n * Pipeline:\n *\n * 1. **Truncate provider-executed tool payloads**: Server-side tool\n * executions (e.g. Anthropic code_execution, text_editor) can produce\n * 200KB+ payloads in `input` and `output`. These are truncated since the\n * model has already consumed the results.\n *\n * 2. **User hook**: Calls the overridable `sanitizeMessageForPersistence()`\n * method, allowing subclasses to apply custom transformations.\n *\n * @param message - The message to sanitize\n * @returns A new message with ai-chat's normalization applied\n */\n private _sanitizeMessageForPersistence(message: UIMessage): UIMessage {\n // ai-chat-specific: truncate large payloads in provider-executed tool parts\n const parts = message.parts.map((part) =>\n AIChatAgent._truncateProviderExecutedToolPayloads(part)\n ) as UIMessage[\"parts\"];\n\n // Run user-overridable hook last\n return this.sanitizeMessageForPersistence({\n ...message,\n parts\n });\n }\n\n /**\n * Truncates large string values in `input` and `output` of tool parts that\n * were executed server-side by the provider (e.g. Anthropic code_execution,\n * text_editor). These payloads can be 200KB+ and are dead weight once the\n * model has consumed the result.\n *\n * Anthropic web tools are excluded because their outputs are replayed on\n * subsequent turns. Within other tool payloads, opaque encrypted fields are\n * always preserved verbatim.\n */\n private static _truncateProviderExecutedToolPayloads<\n T extends UIMessage[\"parts\"][number]\n >(part: T): T {\n const record = part as Record<string, unknown>;\n if (!record.providerExecuted) return part;\n if (AIChatAgent._shouldPreserveProviderToolPayload(record)) return part;\n\n const result = { ...record };\n\n if (result.input !== undefined) {\n result.input = AIChatAgent._truncateLargeStrings(result.input);\n }\n if (result.output !== undefined) {\n result.output = AIChatAgent._truncateLargeStrings(result.output);\n }\n\n return result as T;\n }\n\n /**\n * Recursively walks a value and truncates any string exceeding\n * `PROVIDER_TOOL_MAX_STRING_LENGTH`, appending a size marker.\n *\n * The total output (content + marker) is kept within the threshold so\n * re-running this function on already-truncated data is a no-op. Strings\n * under opaque encrypted keys are preserved verbatim.\n */\n private static _truncateLargeStrings(\n value: unknown,\n preserveOpaqueStrings = false\n ): unknown {\n if (typeof value === \"string\") {\n if (preserveOpaqueStrings) return value;\n if (value.length > PROVIDER_TOOL_MAX_STRING_LENGTH) {\n const marker = `… [truncated, original length: ${value.length}]`;\n const contentLength = Math.max(\n 0,\n PROVIDER_TOOL_MAX_STRING_LENGTH - marker.length\n );\n return value.slice(0, contentLength) + marker;\n }\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((v) =>\n AIChatAgent._truncateLargeStrings(v, preserveOpaqueStrings)\n );\n }\n if (value !== null && typeof value === \"object\") {\n const result: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n result[k] = AIChatAgent._truncateLargeStrings(\n v,\n preserveOpaqueStrings || AIChatAgent._isOpaqueReplayFieldKey(k)\n );\n }\n return result;\n }\n return value;\n }\n\n private static _shouldPreserveProviderToolPayload(\n part: Record<string, unknown>\n ): boolean {\n const toolName = AIChatAgent._getToolNameFromPart(part);\n return toolName === \"web_search\" || toolName === \"web_fetch\";\n }\n\n private static _getToolNameFromPart(\n part: Record<string, unknown>\n ): string | undefined {\n if (typeof part.toolName === \"string\") {\n return part.toolName;\n }\n\n if (typeof part.type === \"string\" && part.type.startsWith(\"tool-\")) {\n return part.type.slice(\"tool-\".length);\n }\n\n return undefined;\n }\n\n private static _isOpaqueReplayFieldKey(key: string): boolean {\n return key.startsWith(PROVIDER_TOOL_OPAQUE_STRING_KEY_PREFIX);\n }\n\n /**\n * Delete message rows through Sessions. The change feed removes them from\n * `this.messages`.\n */\n private async _deleteMessagesByIds(ids: string[]): Promise<void> {\n if (ids.length === 0) return;\n await this.#session.deleteMessages(ids);\n }\n\n /**\n * Shared helper for finding a tool part by toolCallId and applying an update.\n * Handles both streaming (in-memory) and persisted (SQLite) messages.\n *\n * Checks _streamingMessage first (tool results/approvals can arrive while\n * the AI is still streaming), then retries persisted messages with backoff\n * in case streaming completes between attempts.\n *\n * `applyUpdate` may return its argument by reference (or `{ ...part }`\n * with no semantic changes) to signal an idempotent no-op — this is\n * detected via `_isToolPartUnchanged` and short-circuits the SQLite\n * write and `MESSAGE_UPDATED` broadcast.\n *\n * @param toolCallId - The tool call ID to find\n * @param callerName - Name for log messages (e.g. \"_applyToolResult\")\n * @param matchStates - Which tool part states to match\n * @param applyUpdate - Mutation to apply to the matched part (streaming: in-place, persisted: spread)\n * @returns true if the update was applied (or matched as an idempotent\n * no-op), false if no matching part was found\n */\n private async _findAndUpdateToolPart(\n toolCallId: string,\n callerName: string,\n matchStates: string[],\n applyUpdate: (part: Record<string, unknown>) => Record<string, unknown>\n ): Promise<boolean> {\n // Find the message containing this tool call.\n // Check streaming message first (in-memory, not yet persisted), then\n // retry persisted messages with backoff.\n let message: UIMessage | undefined;\n\n if (this._streamingMessage) {\n for (const part of this._streamingMessage.parts) {\n if (\"toolCallId\" in part && part.toolCallId === toolCallId) {\n message = this._streamingMessage;\n break;\n }\n }\n }\n\n if (!message) {\n for (let attempt = 0; attempt < 10; attempt++) {\n message = this._findMessageByToolCallId(toolCallId);\n if (message) break;\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n }\n\n if (!message) {\n console.warn(\n `[AIChatAgent] ${callerName}: Could not find message with toolCallId ${toolCallId} after retries`\n );\n return false;\n }\n\n const isStreamingMessage = message === this._streamingMessage;\n // `wasFound` tracks whether any matching part was processed (real\n // change OR idempotent no-op). `hasRealChange` tracks whether any\n // apply actually mutated state. Tracking both separately matters\n // when a (legacy) message somehow contains duplicate tool parts for\n // the same toolCallId — we must still persist if any of them\n // produced a real change, even if another was an idempotent no-op.\n let wasFound = false;\n let hasRealChange = false;\n\n if (isStreamingMessage) {\n // Update in place -- the message will be persisted when streaming completes\n for (const part of message.parts) {\n if (\n \"toolCallId\" in part &&\n part.toolCallId === toolCallId &&\n \"state\" in part &&\n matchStates.includes(part.state as string)\n ) {\n wasFound = true;\n const applied = applyUpdate(part as Record<string, unknown>);\n if (\n !AIChatAgent._isToolPartUnchanged(\n part as Record<string, unknown>,\n applied\n )\n ) {\n Object.assign(part, applied);\n hasRealChange = true;\n }\n break;\n }\n }\n } else {\n // For persisted messages, create updated parts immutably\n const updatedParts = message.parts.map((part) => {\n if (\n \"toolCallId\" in part &&\n part.toolCallId === toolCallId &&\n \"state\" in part &&\n matchStates.includes(part.state as string)\n ) {\n wasFound = true;\n const applied = applyUpdate(part as Record<string, unknown>);\n if (\n AIChatAgent._isToolPartUnchanged(\n part as Record<string, unknown>,\n applied\n )\n ) {\n return part;\n }\n hasRealChange = true;\n return applied;\n }\n return part;\n }) as UIMessage[\"parts\"];\n\n if (hasRealChange) {\n const updatedMessage: UIMessage = this._sanitizeMessageForPersistence({\n ...message,\n parts: updatedParts\n });\n // The change feed patches `this.messages`. A `null` result means the\n // row is not in storage (nothing to mirror), so patch the live view\n // directly to keep the in-memory transcript consistent.\n const stored = await this.#session.updateMessage(updatedMessage);\n if (!stored) {\n const index = this.messages.findIndex(\n (candidate) => candidate.id === updatedMessage.id\n );\n if (index !== -1) {\n this.messages[index] = autoTransformMessages([updatedMessage])[0];\n }\n }\n }\n }\n\n if (!wasFound) {\n console.warn(\n `[AIChatAgent] ${callerName}: Tool part with toolCallId ${toolCallId} not in expected state (expected: ${matchStates.join(\"|\")})`\n );\n return false;\n }\n\n // Idempotent no-op: caller asked us to apply something we'd already\n // applied (e.g. a duplicate cf_agent_tool_result, or a cross-tab\n // re-delivery). Skip the broadcast — clients are already in the\n // correct state and a redundant MESSAGE_UPDATED would just churn UI.\n if (!hasRealChange) {\n return true;\n }\n\n // Broadcast the update to all clients.\n // For persisted messages, re-fetch the latest state from this.messages.\n // For streaming messages, broadcast the in-memory snapshot so clients\n // get immediate confirmation that the tool result/approval was applied.\n if (isStreamingMessage) {\n this._broadcastChatMessage({\n type: MessageType.CF_AGENT_MESSAGE_UPDATED,\n message\n });\n } else {\n const broadcastMessage = this._findMessageByToolCallId(toolCallId);\n if (broadcastMessage) {\n this._broadcastChatMessage({\n type: MessageType.CF_AGENT_MESSAGE_UPDATED,\n message: broadcastMessage\n });\n }\n }\n\n return true;\n }\n\n /**\n * Returns true if `applied` is the same reference as `original`, or if\n * the two have identical state-relevant fields. Used by\n * `_findAndUpdateToolPart` to detect idempotent re-applies and skip\n * SQLite writes plus `MESSAGE_UPDATED` broadcasts.\n */\n private static _isToolPartUnchanged(\n original: Record<string, unknown>,\n applied: Record<string, unknown>\n ): boolean {\n if (applied === original) return true;\n if (applied.state !== original.state) return false;\n // For terminal output states, the only fields the apply functions\n // touch are output / errorText / preliminary. Compare via JSON so\n // structurally equal outputs (the common idempotent case) compare\n // equal regardless of reference identity.\n if (\n applied.state === \"output-available\" ||\n applied.state === \"output-error\"\n ) {\n return (\n JSON.stringify(applied.output) === JSON.stringify(original.output) &&\n applied.errorText === original.errorText &&\n applied.preliminary === original.preliminary\n );\n }\n if (applied.state === \"output-denied\") {\n return true;\n }\n if (\n applied.state === \"approval-responded\" ||\n applied.state === \"approval-requested\"\n ) {\n return (\n JSON.stringify(applied.approval) === JSON.stringify(original.approval)\n );\n }\n return false;\n }\n\n /**\n * Serialize a client-tool result/approval apply behind any in-flight apply\n * (#1649, defensive). Each apply is a read-modify-write of the message and\n * parallel tool results arrive as independent WebSocket messages. Today\n * `_findAndUpdateToolPart` performs that read-modify-write synchronously (no\n * await between reading `this.messages` and the SQLite write), so concurrent\n * applies can't actually interleave — unlike Think, ai-chat does not exhibit\n * the #1649 clobber. This queue is a guard so the invariant survives if the\n * apply ever gains an await between read and write (e.g. async storage): each\n * apply commits atomically in arrival order.\n *\n * `_pendingInteractionPromise` is set to the newest link so the barrier's\n * single-slot wake-up observes the latest apply; because the chain is serial,\n * awaiting it transitively waits for every predecessor.\n *\n * @internal\n */\n protected _enqueueInteractionApply(\n apply: () => Promise<boolean>\n ): Promise<boolean> {\n // `.then(apply, apply)` runs regardless of a predecessor's outcome so one\n // rejected apply can't poison the rest of the batch.\n const resultPromise = this._interactionApplyTail.then(apply, apply);\n this._interactionApplyTail = resultPromise.then(\n () => undefined,\n () => undefined\n );\n this._pendingInteractionPromise = resultPromise;\n resultPromise\n .finally(() => {\n if (this._pendingInteractionPromise === resultPromise) {\n this._pendingInteractionPromise = null;\n }\n })\n .catch(() => {});\n return resultPromise;\n }\n\n /**\n * Applies a tool result to an existing assistant message.\n * This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.\n * The server is the source of truth, so we update the message here and broadcast\n * the update to all clients.\n *\n * `output-available` and `output-error` are accepted as valid starting\n * states for *idempotent* re-application — duplicate WS frames, second\n * tabs re-running the same tool, and provider-replay round-trips all\n * become silent no-ops rather than a warn + skipped update. The first\n * applied terminal result wins; subsequent results carrying *different*\n * data are also dropped (preserving the existing \"first write wins\"\n * contract — see `client-tool-duplicate-message.test.ts`). See issue\n * #1404.\n *\n * @param toolCallId - The tool call ID this result is for\n * @param _toolName - The name of the tool (unused, kept for API compat)\n * @param output - The output from the tool execution\n * @param overrideState - Optional state override (\"output-error\" to signal denial/failure)\n * @param errorText - Error message when overrideState is \"output-error\"\n * @returns true if the result was applied, false if the message was not found\n */\n private async _applyToolResult(\n toolCallId: string,\n _toolName: string,\n output: unknown,\n overrideState?: \"output-error\",\n errorText?: string\n ): Promise<boolean> {\n return this._findAndUpdateToolPart(\n toolCallId,\n \"_applyToolResult\",\n [\n \"input-available\",\n \"approval-requested\",\n \"approval-responded\",\n // Idempotent re-apply: if the part is already terminal, the apply\n // function below returns the part by reference. _findAndUpdateToolPart\n // detects that and skips the persist + broadcast (and the warn).\n \"output-available\",\n \"output-error\",\n \"output-denied\"\n ],\n (part) => {\n // Once a tool part has reached a terminal state, the first applied\n // result wins. Don't overwrite with conflicting data, and don't\n // emit a redundant MESSAGE_UPDATED for a matching re-apply.\n if (\n part.state === \"output-available\" ||\n part.state === \"output-error\" ||\n part.state === \"output-denied\"\n ) {\n return part;\n }\n if (overrideState === \"output-error\") {\n return {\n ...part,\n state: \"output-error\",\n errorText: errorText ?? \"Tool execution denied by user\"\n };\n }\n return {\n ...part,\n state: \"output-available\",\n output,\n preliminary: false\n };\n }\n );\n }\n\n private async _streamSSEReply(\n id: string,\n streamId: string,\n reader: ReadableStreamDefaultReader<Uint8Array>,\n message: UIMessage,\n streamCompleted: { value: boolean },\n continuation = false,\n abortSignal?: AbortSignal\n ): Promise<StreamResultStatus> {\n streamCompleted.value = false;\n\n // During continuation, the first text-start and reasoning-start from the\n // model should merge into existing parts (from the cloned message) rather\n // than creating new blocks. Track whether we've already resumed each type.\n let continuationTextResumed = false;\n let continuationReasoningResumed = false;\n let finishReason: string | undefined;\n\n // Cancel the reader when the abort signal fires (e.g. client pressed stop).\n // This ensures we stop broadcasting chunks even if the underlying stream\n // hasn't been connected to the abort signal (e.g. user forgot to pass it\n // to streamText).\n if (abortSignal && !abortSignal.aborted) {\n abortSignal.addEventListener(\n \"abort\",\n () => {\n reader.cancel().catch(() => {});\n },\n { once: true }\n );\n }\n\n // Route reads through the shared inactivity watchdog when a stall timeout is\n // configured. The watchdog aborts a stream that parks between chunks (a hung\n // provider/transport) by cancelling the reader and throwing\n // `ChatStreamStalledError`, which the read-loop catch propagates so `_reply`\n // can route the stall into bounded recovery (#1626). A `0` timeout (the\n // default) keeps the raw `reader.read()` path untouched.\n const stallTimeoutMs = this.chatStreamStallTimeoutMs;\n let pull: () => Promise<ReadableStreamReadResult<Uint8Array>>;\n if (stallTimeoutMs > 0) {\n const byteSource: AsyncIterable<Uint8Array> = {\n [Symbol.asyncIterator]() {\n return {\n async next(): Promise<IteratorResult<Uint8Array>> {\n const { done, value } = await reader.read();\n return done || value === undefined\n ? { done: true, value: undefined }\n : { done: false, value };\n },\n async return(): Promise<IteratorResult<Uint8Array>> {\n await reader.cancel().catch(() => {});\n return { done: true, value: undefined };\n }\n };\n }\n };\n const guarded = iterateWithStallWatchdog(\n byteSource,\n stallTimeoutMs,\n () => {\n // Unblock the abandoned `reader.read()` so the pipeline unwinds; the\n // thrown `ChatStreamStalledError` carries the recovery decision.\n reader.cancel().catch(() => {});\n }\n )[Symbol.asyncIterator]();\n pull = async () => {\n const next = await guarded.next();\n return next.done\n ? { done: true, value: undefined }\n : { done: false, value: next.value };\n };\n } else {\n pull = () => reader.read();\n }\n\n while (true) {\n if (abortSignal?.aborted) break;\n let readResult: ReadableStreamReadResult<Uint8Array>;\n try {\n readResult = await pull();\n } catch (readError) {\n if (abortSignal?.aborted) break;\n throw readError;\n }\n const { done, value } = readResult;\n if (done) {\n // reader.cancel() resolves read() with { done: true } — check abort\n if (abortSignal?.aborted) break;\n this._finishStream(streamId);\n streamCompleted.value = true;\n this._broadcastChatMessage({\n body: \"\",\n done: true,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n ...(continuation && { continuation: true })\n });\n return { status: \"completed\", finishReason };\n }\n\n const chunk = decoder.decode(value);\n const lines = chunk.split(\"\\n\");\n\n for (const line of lines) {\n if (line.startsWith(\"data: \") && line !== \"data: [DONE]\") {\n try {\n const data: UIMessageChunk = JSON.parse(line.slice(6));\n\n // During continuation, merge into existing parts rather than\n // creating new blocks:\n // - text-start: suppressed only when the last text part has\n // state \"streaming\" (interrupted mid-generation). Parts with\n // state \"done\" or no state create new blocks as usual (e.g.\n // tool auto-continuation).\n // - reasoning-start: suppressed when resuming an interrupted\n // assistant turn (an existing reasoning part is still streaming,\n // or the message has progressed to a still-streaming text part).\n // Completed reasoning blocks from earlier tool-continuation steps\n // must not swallow new continuation reasoning, otherwise the\n // streamed reasoning block disappears when the final persisted\n // message replaces the live stream.\n let skipServerApply = false;\n if (continuation) {\n if (!continuationTextResumed && data.type === \"text-start\") {\n for (let k = message.parts.length - 1; k >= 0; k--) {\n const part = message.parts[k];\n if (part.type === \"text\") {\n if (\n \"state\" in part &&\n (part as { state: string }).state === \"streaming\"\n ) {\n continuationTextResumed = true;\n }\n break;\n }\n }\n if (continuationTextResumed) continue;\n }\n if (\n !continuationReasoningResumed &&\n data.type === \"reasoning-start\"\n ) {\n for (let k = message.parts.length - 1; k >= 0; k--) {\n const part = message.parts[k];\n if (part.type === \"text\") {\n if (\n \"state\" in part &&\n (part as { state: string }).state === \"streaming\"\n ) {\n continuationReasoningResumed = true;\n }\n break;\n }\n if (part.type === \"reasoning\") {\n if (\n \"state\" in part &&\n (part as { state: string }).state === \"streaming\"\n ) {\n continuationReasoningResumed = true;\n }\n break;\n }\n }\n // For interrupted continuations, keep appending to the cloned\n // reasoning part but still forward reasoning-start to the\n // client. AI SDK v6 requires reasoning-start before any\n // reasoning-delta in the stream processor's active-part\n // registry.\n skipServerApply = continuationReasoningResumed;\n }\n }\n\n // Drop replay chunks before applying or broadcasting them.\n //\n // Some providers (notably the OpenAI Responses API) re-emit\n // prior tool calls as a fresh `tool-input-start` →\n // `tool-input-delta` → `tool-input-available` sequence\n // carrying the *same* `toolCallId` during continuation\n // streams. AI SDK v6's `updateToolPart` finds an existing\n // part by toolCallId and mutates it in place, which\n // visibly regresses an `output-available` part back to\n // `input-streaming`/`input-available` on the client\n // (issue #1404).\n //\n // `applyChunkToParts` handles the server-side cloned\n // streaming message safely (it's idempotent for these\n // chunk types), but we must also stop these chunks from\n // reaching the client-side AI SDK, where the in-place\n // mutation would corrupt a resolved tool part.\n //\n // `tool-output-available` is not filtered: its in-place\n // update sets state and output to the values the part\n // already has when the replay matches, so it's\n // semantically a no-op on the client too.\n if (isReplayChunk(message.parts, data as StreamChunkData)) {\n // A `tool-input-available` that lands after its approval\n // request still carries the canonical input the approved\n // call executes with. Refresh the approval snapshot persisted\n // without it, and forward it followed by the approval request\n // again so clients show the input on the approval card.\n if (\n applyLateToolInput(message.parts, data as StreamChunkData) &&\n this._approvalPersistedMessageId !== null &&\n this._streamingMessage\n ) {\n await this.#session.upsertMessage(\n this._sanitizeMessageForPersistence({\n ...this._streamingMessage,\n parts: [...this._streamingMessage.parts]\n })\n );\n }\n for (const forwarded of lateToolInputForwardChunks(\n message.parts,\n data as StreamChunkData\n )) {\n const chunkBody = JSON.stringify(forwarded);\n const seq = await this._storeStreamChunk(streamId, chunkBody);\n this._broadcastChatMessage({\n body: chunkBody,\n done: false,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n ...(seq !== undefined && { seq }),\n ...(continuation && { continuation: true })\n });\n }\n continue;\n }\n\n // Delegate message building to the shared parser.\n // It handles: text, reasoning, file, source, tool lifecycle,\n // step boundaries — all the part types needed for UIMessage.\n const handled = skipServerApply\n ? true\n : applyChunkToParts(message.parts, data);\n\n // When a tool enters approval-requested state, the stream is\n // paused waiting for user approval. Persist the streaming message\n // immediately so the approval UI survives page refresh. Without\n // this, a refresh would reload from SQLite where the tool part\n // is still in input-available state, showing \"Running...\" instead\n // of the Approve/Reject buttons.\n if (\n data.type === \"tool-approval-request\" &&\n this._streamingMessage\n ) {\n // Persist directly to SQLite without broadcasting.\n // The client already has this data from the SSE stream —\n // broadcasting would cause the approval UI to render twice.\n // We only need the SQL write so the state survives page refresh.\n const snapshot: UIMessage = {\n ...this._streamingMessage,\n parts: [...this._streamingMessage.parts]\n };\n const sanitized = this._sanitizeMessageForPersistence(snapshot);\n const stored = await this.#session.upsertMessage(sanitized);\n // Track that we persisted early so stream completion can update\n // in place rather than appending a duplicate.\n this._approvalPersistedMessageId = stored.message.id;\n }\n\n // Cross-message tool output fallback:\n // When a tool with needsApproval is approved, the continuation\n // stream emits tool-output-available/tool-output-error for a\n // tool call that lives in a *previous* assistant message.\n // applyChunkToParts only searches the current message's parts,\n // so the update is silently skipped. Fall back to searching\n // this.messages and update the persisted message directly.\n // Note: checked independently of `handled` — applyChunkToParts\n // returns true for recognized chunk types even when it cannot\n // find the target part, so `handled` is not a reliable signal.\n //\n // `output-available` and `output-error` are accepted as\n // starting states for idempotent re-application. Some\n // providers (notably the OpenAI Responses API) replay the\n // entire prior tool round-trip during continuations — the\n // replay's tool-output-available carries the same output the\n // part already has, so the apply functions below short-circuit\n // to a no-op via reference equality (issue #1404).\n if (\n (data.type === \"tool-output-available\" ||\n data.type === \"tool-output-error\") &&\n data.toolCallId\n ) {\n const foundInCurrentMessage = message.parts.some(\n (p) => \"toolCallId\" in p && p.toolCallId === data.toolCallId\n );\n if (!foundInCurrentMessage) {\n if (data.type === \"tool-output-available\") {\n this._findAndUpdateToolPart(\n data.toolCallId,\n \"_streamSSEReply\",\n [\n \"input-available\",\n \"input-streaming\",\n \"approval-responded\",\n \"approval-requested\",\n \"output-available\",\n \"output-error\",\n \"output-denied\"\n ],\n (part) => {\n // First-write-wins: a chunk arriving for a tool\n // that's already terminal is a provider replay.\n // Never overwrite a resolved tool's output.\n if (\n part.state === \"output-available\" ||\n part.state === \"output-error\" ||\n part.state === \"output-denied\"\n ) {\n return part;\n }\n return {\n ...part,\n state: \"output-available\",\n output: data.output,\n ...(data.preliminary !== undefined && {\n preliminary: data.preliminary\n })\n };\n }\n );\n } else {\n this._findAndUpdateToolPart(\n data.toolCallId,\n \"_streamSSEReply\",\n [\n \"input-available\",\n \"input-streaming\",\n \"approval-responded\",\n \"approval-requested\",\n \"output-available\",\n \"output-error\",\n \"output-denied\"\n ],\n (part) => {\n if (\n part.state === \"output-available\" ||\n part.state === \"output-error\" ||\n part.state === \"output-denied\"\n ) {\n return part;\n }\n return {\n ...part,\n state: \"output-error\",\n errorText: data.errorText\n };\n }\n );\n }\n }\n }\n\n // Handle server-specific chunk types not covered by the shared parser\n if (!handled) {\n switch (data.type) {\n case \"start\": {\n if (data.messageId != null && !continuation) {\n message.id = data.messageId;\n }\n if (data.messageMetadata != null) {\n message.metadata = message.metadata\n ? { ...message.metadata, ...data.messageMetadata }\n : data.messageMetadata;\n }\n break;\n }\n case \"finish\":\n case \"message-metadata\": {\n if (data.messageMetadata != null) {\n message.metadata = message.metadata\n ? { ...message.metadata, ...data.messageMetadata }\n : data.messageMetadata;\n }\n break;\n }\n case \"finish-step\": {\n // No-op for message building (shared parser handles step-start)\n break;\n }\n case \"error\": {\n const error =\n data.errorText ?? JSON.stringify({ type: data.type });\n this._broadcastChatMessage({\n error: true,\n body: error,\n done: false,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n ...(continuation && { continuation: true })\n });\n this._markStreamError(streamId);\n this._emit(\"message:error\", { error });\n await reader.cancel().catch(() => {});\n streamCompleted.value = true;\n this._broadcastChatMessage({\n body: \"\",\n done: true,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n outcome: \"error\",\n ...(continuation && { continuation: true })\n });\n return { status: \"error\", error };\n }\n }\n }\n\n // Rewrite chunks before storing and broadcasting:\n // 1. Strip messageId from continuation start chunks so clients\n // reuse the existing assistant message (#1229).\n // 2. Stamp the allocated assistant id onto a new turn's start chunk\n // so the client builds the live message under the SAME id the\n // server persists under (see below).\n // 3. Convert the internal \"finish\" event's finishReason into the\n // UIMessageStreamPart messageMetadata format (#677).\n let eventToSend: unknown = data;\n if (data.type === \"start\") {\n if (continuation && \"messageId\" in data) {\n const { messageId: _, ...rest } = data as {\n messageId: unknown;\n [key: string]: unknown;\n };\n eventToSend = rest;\n } else if (!continuation) {\n // Most providers (e.g. Workers AI) emit no `start.messageId`,\n // so the client's AI SDK would build the streaming assistant\n // under its own generated id while the server persists under\n // `message.id`. The two then can't be reconciled by id, and the\n // originating tab briefly renders the turn twice — the live copy\n // plus the `CF_AGENT_CHAT_MESSAGES` broadcast — before\n // collapsing. Stamping the allocated id here makes the common\n // case behave like the provider-id case the client already\n // relies on (react.tsx records `start.messageId` to map the\n // local stream to the persisted message).\n const startData = data as {\n messageId?: unknown;\n [key: string]: unknown;\n };\n if (startData.messageId == null) {\n eventToSend = { ...startData, messageId: message.id };\n }\n }\n }\n if (data.type === \"finish\" && \"finishReason\" in data) {\n const { finishReason: chunkFinishReason, ...rest } = data as {\n finishReason: string;\n [key: string]: unknown;\n };\n finishReason = chunkFinishReason;\n eventToSend = {\n ...rest,\n type: \"finish\",\n messageMetadata: { finishReason: chunkFinishReason }\n };\n }\n\n // Store chunk for replay and broadcast to clients\n const chunkBody = JSON.stringify(eventToSend);\n const seq = await this._storeStreamChunk(streamId, chunkBody);\n this._broadcastChatMessage({\n body: chunkBody,\n done: false,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n ...(seq !== undefined && { seq }),\n ...(continuation && { continuation: true })\n });\n } catch (_error) {\n // Skip malformed JSON lines silently\n }\n }\n }\n }\n\n // If we exited due to abort, send a done signal so clients know the stream ended\n if (!streamCompleted.value) {\n this._finishStream(streamId, \"aborted\");\n streamCompleted.value = true;\n this._broadcastChatMessage({\n body: \"\",\n done: true,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n outcome: \"aborted\",\n ...(continuation && { continuation: true })\n });\n return { status: \"aborted\" };\n }\n\n return { status: \"completed\", finishReason };\n }\n\n // Handle plain text responses (e.g., from generateText)\n private async _sendPlaintextReply(\n id: string,\n streamId: string,\n reader: ReadableStreamDefaultReader<Uint8Array>,\n message: UIMessage,\n streamCompleted: { value: boolean },\n continuation = false,\n abortSignal?: AbortSignal\n ): Promise<StreamResultStatus> {\n // During continuation, if the last text part was still streaming\n // (interrupted mid-generation), reuse it so the resumed content\n // stays in the same block.\n let textPart: TextUIPart | undefined;\n if (continuation) {\n for (let k = message.parts.length - 1; k >= 0; k--) {\n const part = message.parts[k];\n if (part.type === \"text\") {\n if (\n \"state\" in part &&\n (part as { state: string }).state === \"streaming\"\n ) {\n textPart = part as TextUIPart;\n }\n break;\n }\n }\n }\n\n if (textPart) {\n // Skip broadcasting text-start — the client already has this part\n } else {\n // if not AI SDK SSE format, we need to inject text-start and text-end events ourselves\n await this._broadcastTextEvent(\n streamId,\n { type: \"text-start\", id },\n continuation\n );\n\n // Use a single text part and accumulate into it, so the persisted message\n // has one text part regardless of how many network chunks the response spans.\n textPart = { type: \"text\", text: \"\", state: \"streaming\" };\n message.parts.push(textPart);\n }\n\n // Cancel the reader when the abort signal fires\n if (abortSignal && !abortSignal.aborted) {\n abortSignal.addEventListener(\n \"abort\",\n () => {\n reader.cancel().catch(() => {});\n },\n { once: true }\n );\n }\n\n while (true) {\n if (abortSignal?.aborted) break;\n let readResult: ReadableStreamReadResult<Uint8Array>;\n try {\n readResult = await reader.read();\n } catch (readError) {\n if (abortSignal?.aborted) break;\n throw readError;\n }\n const { done, value } = readResult;\n if (done) {\n // reader.cancel() resolves read() with { done: true } — check abort\n if (abortSignal?.aborted) break;\n textPart.state = \"done\";\n\n await this._broadcastTextEvent(\n streamId,\n { type: \"text-end\", id },\n continuation\n );\n\n // Mark the stream as completed\n this._finishStream(streamId);\n streamCompleted.value = true;\n // Send final completion signal\n this._broadcastChatMessage({\n body: \"\",\n done: true,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n ...(continuation && { continuation: true })\n });\n return { status: \"completed\" };\n }\n\n const chunk = decoder.decode(value);\n\n // Accumulate into the single text part to preserve exact formatting\n if (chunk.length > 0) {\n textPart.text += chunk;\n await this._broadcastTextEvent(\n streamId,\n { type: \"text-delta\", id, delta: chunk },\n continuation\n );\n }\n }\n\n // If we exited due to abort, send a done signal so clients know the stream ended\n if (!streamCompleted.value) {\n textPart.state = \"done\";\n await this._broadcastTextEvent(\n streamId,\n { type: \"text-end\", id },\n continuation\n );\n this._finishStream(streamId, \"aborted\");\n streamCompleted.value = true;\n this._broadcastChatMessage({\n body: \"\",\n done: true,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n outcome: \"aborted\",\n ...(continuation && { continuation: true })\n });\n return { status: \"aborted\" };\n }\n\n return { status: \"completed\" };\n }\n\n /**\n * Applies a tool approval response from the client, updating the persisted message.\n * This is called when the client sends CF_AGENT_TOOL_APPROVAL for tools with needsApproval.\n *\n * - approved=true transitions to approval-responded\n * - approved=false transitions to output-denied so convertToModelMessages\n * emits a tool_result for providers (e.g. Anthropic) that require it.\n *\n * @param toolCallId - The tool call ID this approval is for\n * @param approved - Whether the tool execution was approved\n * @returns true if the approval was applied, false if the message was not found\n */\n private async _applyToolApproval(\n toolCallId: string,\n approved: boolean\n ): Promise<boolean> {\n // Use the shared `agents/chat` builder so the approval merge — including\n // the fallback that synthesizes `approval.id` from `toolCallId` when an\n // older / hand-seeded transcript lacks one — stays identical to Think.\n // convertToModelMessages needs `approval.id` to produce a valid\n // tool-approval-request content part with `approvalId`.\n const update = toolApprovalUpdate(toolCallId, approved);\n return this._findAndUpdateToolPart(\n toolCallId,\n \"_applyToolApproval\",\n update.matchStates,\n update.apply\n );\n }\n\n private async _reply(\n id: string,\n response: Response,\n excludeBroadcastIds: string[] = [],\n options: {\n continuation?: boolean;\n chatMessageId?: string;\n /**\n * Called once the stream is set up. From then on `_reply` reports its\n * own failures to clients; a throw before it is the caller's to report.\n */\n onStreamStart?: () => void;\n } = {}\n ): Promise<StreamResultStatus> {\n const { continuation = false, chatMessageId, onStreamStart } = options;\n // Look up the abort signal for this request so we can cancel the reader\n // loop if the client sends a cancel message. This is a safety net —\n // users should also pass abortSignal to streamText for proper cancellation.\n const abortSignal = chatMessageId\n ? this._abortRegistry.getExistingSignal(chatMessageId)\n : undefined;\n\n // Keep the DO alive during streaming to prevent idle eviction\n return this.keepAliveWhile(() =>\n this._tryCatchChat(async () => {\n if (!response.body) {\n // Send empty response if no body\n this._clearPendingAutoContinuation(true);\n this._broadcastChatMessage({\n body: \"\",\n done: true,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n ...(continuation && { continuation: true })\n });\n this._activateDeferredAutoContinuation();\n return { status: \"completed\" };\n }\n\n // Take the reader before the stream starts: an unreadable body must\n // fail while nothing has been sent, not leave a started stream behind.\n const reader = response.body.getReader();\n let message: UIMessage;\n let streamId: string;\n try {\n // Parsing state adapted from:\n // https://github.com/vercel/ai/blob/main/packages/ai/src/ui-message-stream/ui-message-chunks.ts#L295\n message = this._createStreamingAssistantMessage(continuation);\n\n // Start tracking this stream for resumability. The allocated message id\n // is persisted in stream metadata so orphan recovery (#1691) can\n // re-associate reconstructed chunks with the right assistant message —\n // even when the provider stream carries no `start.messageId`. For a\n // continuation this is the cloned last-assistant id, so recovery merges\n // into it; for a new turn it is a fresh id, so recovery keeps it\n // distinct.\n // The continuation flag is persisted in stream metadata so replayed\n // frames carry `continuation: true` exactly like the live broadcast\n // frames below (#1733) — a reconnecting client needs it to append to\n // the existing assistant message instead of rebuilding it from\n // scratch and dropping the pre-continuation parts.\n streamId = this._startStream(id, {\n messageId: message.id,\n continuation\n });\n } catch (error) {\n // The streaming `finally` that releases the reader is not entered yet.\n reader.cancel(error).catch(() => {});\n throw error;\n }\n\n // Track the streaming message so tool results can be applied before persistence\n this._streamingMessage = message;\n\n // Determine response format based on content-type\n const contentType = response.headers.get(\"content-type\") || \"\";\n const isSSE = contentType.includes(\"text/event-stream\"); // AI SDK v5 SSE format\n const streamCompleted = { value: false };\n let streamResult: StreamResultStatus = { status: \"completed\" };\n // Capture before try so it's available after finally.\n // _approvalPersistedMessageId is set inside _streamSSEReply when a\n // tool enters approval-requested state and the message is persisted early.\n let earlyPersistedId: string | null = null;\n // Set when a stall watchdog abort was routed into bounded recovery\n // (#1626): the orphan partial was already persisted and a continuation\n // (or terminal exhaustion) now owns the turn, so the post-stream\n // persistence + the success `message:response` emit below are skipped.\n let stallRouted = false;\n // Set when `onChatRecovery` returned `persist: false` for the routed\n // interruption: the partial is dropped instead of persisted.\n let discardPartial = false;\n\n // Stream-active gate for the auto-continuation barrier (#1650): while\n // this assistant turn is streaming the parallel tool batch can still\n // grow, so no completeness check is meaningful. The gate clears only in\n // the outer `finally` below — AFTER the streamed message (with all its\n // tool parts) is persisted to `this.messages` — so the re-armed barrier\n // check sees the fully-materialized batch.\n this._streamingTurnActive = true;\n this._heldTerminalFrames.set(id, []);\n let persisted = false;\n onStreamStart?.();\n try {\n try {\n if (isSSE) {\n // AI SDK v5 SSE format\n streamResult = await this._streamSSEReply(\n id,\n streamId,\n reader,\n message,\n streamCompleted,\n continuation,\n abortSignal\n );\n } else {\n streamResult = await this._sendPlaintextReply(\n id,\n streamId,\n reader,\n message,\n streamCompleted,\n continuation,\n abortSignal\n );\n }\n } catch (error) {\n // A stall watchdog abort (#1626) or a platform transient such as a\n // dropped connection (#1964) is a recoverable interruption, not a\n // terminal error. Persist the settled partial (so the continuation\n // re-anchors without re-running completed tool calls, and the user\n // keeps generated content), then route into bounded recovery.\n if (\n !streamCompleted.value &&\n (error instanceof ChatStreamStalledError ||\n (!abortSignal?.aborted && isRecoverableStreamReadError(error)))\n ) {\n // The partial generated so far lives on the in-memory `message`; the\n // unconditional post-stream persistence block below writes it under\n // `message.id` (the same path a normal turn uses), so the scheduled\n // continuation re-anchors onto it via `targetAssistantId`. (Unlike a\n // cold deploy recovery, there is no need to reconstruct from stored\n // chunks here — the live `message` is authoritative.)\n const targetAssistantId =\n message.parts.length > 0 ? message.id : undefined;\n const outcome = await this._routeStreamInterruption({\n requestId: id,\n streamId,\n partialParts: message.parts,\n targetAssistantId,\n continuation,\n backoff: !(error instanceof ChatStreamStalledError),\n discardPartial: async () => {\n discardPartial = true;\n // An approval request already persisted this turn's\n // message; drop it too. A continuation's early persist\n // overwrote the message it continues, which stays.\n const earlyId = this._approvalPersistedMessageId;\n if (!earlyId || continuation) return;\n this._approvalPersistedMessageId = null;\n await this._deleteMessagesByIds([earlyId]);\n this._broadcastChatMessage({\n messages: this._messagesForClientSync(),\n type: MessageType.CF_AGENT_CHAT_MESSAGES\n });\n }\n });\n if (outcome === \"scheduled\") {\n // Recovering: close the stream cleanly (no terminal error frame);\n // the scheduled continuation drives the turn to completion. Report\n // `aborted` so this attempt does not terminalize the turn.\n this._completeStream(streamId, \"recovering\");\n this._broadcastChatMessage({\n body: \"\",\n done: true,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n outcome: \"recovering\",\n ...(continuation && { continuation: true })\n });\n streamResult = { status: \"aborted\" };\n streamCompleted.value = true;\n stallRouted = true;\n } else if (outcome === \"exhausted\") {\n // `_routeStallToBoundedRecovery` already delivered terminal UX\n // (terminalMessage + done/error frame + onExhausted), identical to\n // deploy-recovery exhaustion. Finalize the resumable stream and\n // report `aborted` so the generic terminal path is not re-run.\n this._markStreamError(streamId);\n streamResult = { status: \"aborted\" };\n streamCompleted.value = true;\n stallRouted = true;\n }\n }\n if (!stallRouted) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n streamResult = { status: \"error\", error: errorMessage };\n // Mark stream as error if not already completed\n if (!streamCompleted.value) {\n this._markStreamError(streamId);\n // Notify clients of the error\n this._broadcastChatMessage({\n body: errorMessage,\n done: true,\n error: true,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n ...(continuation && { continuation: true })\n });\n this._emit(\"message:error\", { error: errorMessage });\n streamCompleted.value = true;\n }\n }\n } finally {\n reader.releaseLock();\n\n // Always clear the streaming message reference, even on error.\n this._streamingMessage = null;\n // Capture and clear early-persist tracking. The persistence block\n // after the finally uses the local to update in place.\n earlyPersistedId = this._approvalPersistedMessageId;\n this._approvalPersistedMessageId = null;\n\n // Framework-level cleanup: always remove abort controller.\n // Only emit observability on success (not on error path).\n if (chatMessageId) {\n this._abortRegistry.remove(chatMessageId);\n if (\n streamCompleted.value &&\n streamResult.status !== \"error\" &&\n !stallRouted\n ) {\n this._emit(\"message:response\");\n }\n }\n }\n\n // The cutover: when this turn's stream is awaiting settlement, the\n // persist that carries this turn's message settles it and drops\n // its rows in one transaction (see `#pendingCutover`). Agent-tool\n // child turns keep their rows (the parent tails the stored chunks\n // after completion); the next start() reclaims them.\n this.#pendingCutover =\n this._resumableStream.pendingCutoverId === streamId\n ? {\n streamId,\n messageId: earlyPersistedId ?? message.id,\n discard: !this._agentToolRunsByRequestId.get(id)\n }\n : null;\n if (message.parts.length > 0 && !discardPartial) {\n if (earlyPersistedId) {\n // Message already exists in this.messages from the early persist.\n // Update it in place with the final streaming state.\n const persistedMessage: UIMessage = {\n ...message,\n id: earlyPersistedId\n };\n const existingIdx = this.messages.findIndex(\n (msg) => msg.id === earlyPersistedId\n );\n const updatedMessages = [...this.messages];\n\n if (existingIdx >= 0) {\n updatedMessages[existingIdx] = persistedMessage;\n } else {\n updatedMessages.push(persistedMessage);\n }\n\n await this.persistMessages(updatedMessages, excludeBroadcastIds);\n } else if (continuation) {\n const existingIdx = this.messages.findIndex(\n (msg) => msg.id === message.id\n );\n if (existingIdx >= 0) {\n const updatedMessages = [...this.messages];\n updatedMessages[existingIdx] = message;\n await this.persistMessages(\n updatedMessages,\n excludeBroadcastIds\n );\n } else {\n // No assistant message to append to, create new one\n await this.persistMessages(\n [...this.messages, message],\n excludeBroadcastIds\n );\n }\n } else {\n await this.persistMessages(\n [...this.messages, message],\n excludeBroadcastIds\n );\n }\n }\n // Nothing to persist (or the persist threw, or an override never\n // reached the session write): settle the stream so it is not\n // mistaken for an interrupted turn.\n this.#pendingCutover = null;\n this._resumableStream.finalizePending();\n persisted = true;\n this._releaseTerminalFrames(id);\n\n this._pendingChatResponseResults.push({\n message,\n requestId: id,\n continuation,\n status: streamResult.status,\n ...(streamResult.error !== undefined && {\n error: streamResult.error\n })\n });\n return streamResult;\n } finally {\n this.#pendingCutover = null;\n this._resumableStream.finalizePending();\n this._releaseTerminalFrames(\n id,\n persisted ? undefined : \"Failed to save the response.\"\n );\n // The streamed assistant message (with all tool parts) is now\n // persisted: clear the stream-active gate and re-run the\n // auto-continuation barrier for a continuation it held (#1650). This\n // package-local hook is the SSE-loop equivalent of Think's\n // `_onStreamingTurnFinalized` in its `toUIMessageStream()` loop.\n // TODO(phase-5): the Tier-2 streaming-codec extraction touches this\n // same region — fold this finalize hook into the extracted codec\n // rather than leaving a second seam here.\n this._onStreamingTurnFinalized(streamResult.finishReason);\n }\n })\n );\n }\n\n /**\n * When the DO is destroyed, cancel all pending requests and clean up resources\n */\n async destroy() {\n this._abortRegistry.destroyAll();\n this._resumableStream.destroy();\n await super.destroy();\n }\n}\n"],"mappings":";;;;;;;;AAgLA,SAAS,cACP,MACA,WAC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