@cloudflare/ai-chat 0.8.5 → 0.8.6

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.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["agentContext","chatByteLength"],"sources":["../src/index.ts"],"sourcesContent":["import type {\n UIMessage,\n StreamTextOnFinishCallback,\n TextUIPart,\n ToolSet,\n UIMessageChunk\n} from \"ai\";\nimport {\n Agent,\n __DO_NOT_USE_WILL_BREAK__agentContext as agentContext,\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 {\n MessageType,\n type IncomingMessage,\n type OutgoingMessage\n} from \"./types\";\nimport { autoTransformMessages } from \"./ai-chat-v5-migration\";\nimport {\n reconcileMessages,\n resolveToolMergeId,\n createChatFiberSnapshot,\n unwrapChatFiberSnapshot,\n wrapChatFiberSnapshot\n} from \"agents/chat\";\nimport {\n applyChunkToParts,\n isReplayChunk,\n sanitizeMessage,\n byteLength as chatByteLength,\n ROW_MAX_BYTES,\n TurnQueue,\n SubmitConcurrencyController,\n type TurnResult,\n type MessagePart,\n type StreamChunkData,\n type SubmitConcurrencyDecision,\n type ChatFiberSnapshot\n} from \"agents/chat\";\nimport { ResumableStream } from \"agents/chat\";\nimport { MAX_BOUND_PARAMS, buildInClauseStrings } from \"agents/chat\";\nimport {\n ContinuationState,\n AbortRegistry,\n type ClientToolSchema\n} from \"agents/chat\";\nimport type {\n ChatResponseResult,\n ChatRecoveryConfig,\n ChatRecoveryContext,\n ChatRecoveryExhaustedContext,\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 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\ntype ChatRecoveryKind = \"retry\" | \"continue\";\n\ntype ChatRecoveryIncident = {\n incidentId: string;\n requestId: string;\n /** Stable request ID for the whole continuation chain (the recovery root). */\n recoveryRootRequestId?: string;\n recoveryKind: ChatRecoveryKind;\n attempt: number;\n maxAttempts: number;\n status:\n | \"detected\"\n | \"scheduled\"\n | \"attempting\"\n | \"completed\"\n | \"skipped\"\n | \"exhausted\"\n | \"failed\";\n firstSeenAt: number;\n lastAttemptAt: number;\n /**\n * Epoch ms of the last attempt that observed forward progress. The recovery\n * budget is keyed to this (`now - lastProgressAt > NO_PROGRESS_WINDOW`), so a\n * turn that keeps producing content survives churn indefinitely while a\n * genuinely stuck turn is sealed within the window (#1637). Optional for\n * backward-compat — falls back to `firstSeenAt`.\n */\n lastProgressAt?: number;\n reason?: string;\n /**\n * High-water mark of the durable, monotonic recovery-progress counter (see\n * `_chatRecoveryProgressMarker`) observed for this incident. Used to\n * distinguish a turn that is making forward progress but keeps getting\n * interrupted by isolate resets (deploys) — which should NOT exhaust the\n * budget — from one that genuinely fails to advance. Sourced from a persisted\n * counter rather than the live transcript so compaction cannot lower it\n * (#1628).\n */\n progress?: number;\n /**\n * Value of the durable progress counter when this incident first opened. The\n * runaway-loop work budget is `progress - workBaseline` (work produced since\n * the incident began); compared against `maxRecoveryWork`. Optional for\n * backward-compat with incidents persisted before this field existed — a\n * missing baseline is treated as the current marker (zero work so far), so an\n * in-flight incident from an older build is never falsely sealed.\n */\n workBaseline?: number;\n};\n\nconst CHAT_RECOVERY_INCIDENT_KEY_PREFIX = \"cf:chat-recovery:incident:\";\n// Durable, monotonic forward-progress counter for recovery budget resets.\n// Bumped at production time when new content is streamed (`_storeStreamChunk`),\n// so it reflects genuinely new content and is immune to reconnects/re-persists;\n// never recomputed from the (compactable) transcript. See\n// `_chatRecoveryProgressMarker`.\nconst CHAT_RECOVERY_PROGRESS_KEY = \"cf:chat-recovery:progress\";\n// Secondary backstop only. The primary recovery bound is the no-progress\n// wall clock below; with alarm debounce this cap rarely binds (it catches a\n// pathological tight alarm-loop). Kept high so the no-progress window seals\n// first under normal deploy cadence (#1637).\nconst DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS = 10;\n// Runaway-loop guard default. `Infinity` = no SDK-imposed work cap: a turn that\n// keeps making forward progress is never terminated by the framework on its own\n// (rfc-chat-recovery-work-budget). Integrators bound a content-emitting runaway\n// by setting `maxRecoveryWork` or a `shouldKeepRecovering` predicate.\nconst DEFAULT_CHAT_RECOVERY_MAX_WORK = Number.POSITIVE_INFINITY;\nconst DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS = 10_000;\n// Auto-continuation barrier (#1649): when the model emits parallel tool calls,\n// 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. So we wait until the transcript is stable (no\n// `input-available`/`approval-requested` parts) before continuing, bounded by\n// this timeout so a genuinely orphaned tool call (e.g. the client disconnected\n// mid-batch) still falls through instead of pinning the continuation open.\nconst AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS = 60_000;\n// Delay before retrying a recovery that timed out waiting for stable state.\n// Gives an actively-churning isolate (e.g. a deploy in flight) time to settle.\nconst CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS = 3;\nconst DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE =\n \"The assistant was interrupted and could not recover. Please try again.\";\n// Durable record of an in-progress recovery so a \"recovering…\" status (#1620)\n// can be broadcast live and survives the set/clear happening in different\n// isolates (a continuation runs in a later alarm invocation). NOTE: this live\n// \"recovering…\" status is NOT replayed on connect — only the terminal outcome\n// is (#1645, via the resume handshake; see `CHAT_LAST_TERMINAL_KEY`). A client\n// that connects mid-recovery isn't re-told it's recovering, but the live\n// broadcast + reliable clear work regardless, and any terminal outcome is\n// surfaced on reconnect.\nconst CHAT_RECOVERING_KEY = \"cf:chat:recovering\";\n// Durable record of the last turn that ended in a terminal error / abandoned\n// recovery (#1645). The terminal `CF_AGENT_USE_CHAT_RESPONSE` broadcast is\n// transient, so a client disconnected at the moment recovery exhausts would\n// otherwise never learn the turn failed and stay frozen. Replayed on the next\n// reconnect via the resume handshake (`_replayTerminalOnResume`); cleared when\n// a later turn supersedes it.\nconst CHAT_LAST_TERMINAL_KEY = \"cf:chat:last-terminal\";\n// Incidents that have not seen a new attempt within this window are assumed\n// abandoned and swept so durable storage does not grow without bound.\nconst CHAT_RECOVERY_INCIDENT_TTL_MS = 60 * 60 * 1000;\n// Max keys per Durable Object KV `delete([...])` call.\n// See https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/\nconst KV_DELETE_MAX_KEYS = 128;\n// PRIMARY recovery bound (#1637): seal an incident that has made no forward\n// progress for this long. Keyed to `lastProgressAt`, which resets on every\n// progress-bearing attempt — so a turn that keeps producing content survives\n// deploy churn indefinitely, while a genuinely stuck turn dies within 5 min.\n// Overridable per-agent via `chatRecovery.noProgressTimeoutMs`.\nconst DEFAULT_CHAT_RECOVERY_NO_PROGRESS_TIMEOUT_MS = 5 * 60 * 1000;\n// Alarm debounce: recovery alarms bunched within this window collapse into a\n// single attempt. A deploy rollout drops/reconnects the socket several times\n// over ~11–22s; without this, one logical deploy would burn several attempts.\nconst CHAT_RECOVERY_ALARM_DEBOUNCE_MS = 30 * 1000;\n// Staleness bound for the live \"recovering…\" flag (#1620). A flag older than\n// this is treated as abandoned (the owning incident died without a terminal,\n// e.g. the DO went idle) so it can neither pin the indicator on forever nor\n// suppress a genuinely-new recovering signal. This is NOT a recovery budget —\n// a progressing turn is bounded by work, not wall-clock\n// (rfc-chat-recovery-work-budget).\nconst CHAT_RECOVERING_FLAG_TTL_MS = 15 * 60 * 1000;\n// N9: while a parent re-attaches to and forwards a sub-agent's stream, credit\n// the parent's recovery progress at most this often. The marker only needs to\n// advance ≥once between recovery attempts (the no-progress window is minutes),\n// so this caps storage writes during high-rate child streaming. The throttle\n// state is in-memory (reset per isolate), so the first forwarded chunk after\n// ANY restart always bumps — guaranteeing every recovery attempt that observes\n// child output registers forward progress.\nconst AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS = 5_000;\n\n// How far ahead to schedule the resumable-stream buffer cleanup alarm. Set to\n// ResumableStream's short completion-grace window (COMPLETED_RETENTION_MS, 10m)\n// so a finished buffer is reclaimed promptly. The re-arm-while-reclaimable loop\n// (see _cleanupStreamBuffers) revisits any longer-lived rows — e.g. an\n// abandoned in-flight buffer on its 1h window — by waking again each interval\n// until they age out, then stops. Driving cleanup from an alarm (rather than\n// only piggybacking on the next stream completion) ensures idle/one-off chat\n// DOs still reclaim their buffers without waking forever (#1706).\nconst STREAM_CLEANUP_DELAY_SECONDS = 10 * 60;\n\ntype StreamResultStatus = {\n status: Exclude<SaveMessagesResult[\"status\"], \"skipped\">;\n error?: string;\n};\n\nfunction sendIfOpen(connection: Connection, message: string): boolean {\n try {\n connection.send(message);\n return true;\n } catch (error) {\n if (isWebSocketClosedSendError(error)) return false;\n throw error;\n }\n}\n\nfunction isWebSocketClosedSendError(error: unknown): boolean {\n return (\n error instanceof TypeError &&\n error.message.includes(\"WebSocket send() after close\")\n );\n}\n\nexport type ChatMessage = UIMessage;\n\nconst TIMED_OUT = Symbol(\"timed-out\");\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 full Zod 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. Zod schemas cannot be 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};\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 * When true, chat turns are wrapped in `runFiber` for durable execution.\n * Enables `onChatRecovery` hook and `this.stash()` during streaming.\n * Set to `true` in subclasses to enable durable streaming.\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 = false;\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 /**\n * Continuation lifecycle state: pending, deferred, active, and\n * connections awaiting a continuation stream to start.\n */\n private _continuation = new ContinuationState<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 * Small debounce window to batch adjacent client-side tool results/approvals\n * into a single server continuation turn.\n */\n private static AUTO_CONTINUATION_COALESCE_MS = 10;\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 // Inspect frames while any agent-tool run is in flight (live sequences\n // exist for the run's whole lifecycle), not only while a tailer is\n // attached — error capture must not depend on tailer timing (#1575).\n if (\n (this._agentToolForwarders.size > 0 ||\n this._agentToolLiveSequences.size > 0) &&\n typeof msg === \"string\"\n ) {\n try {\n const parsed = JSON.parse(msg) as {\n type?: unknown;\n body?: unknown;\n error?: unknown;\n id?: unknown;\n };\n if (\n parsed.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE &&\n typeof parsed.id === \"string\"\n ) {\n // A frame belongs to a run iff it carries that run's turn request\n // id. Frames from unrelated turns (a user-driven turn on this\n // agent, or another run's turn) resolve to a different — or no —\n // run and are left alone, so concurrent runs cannot\n // cross-contaminate each other's progress or error state (#1575).\n const runId = this._agentToolRunForRequest(parsed.id);\n if (runId !== null) {\n if (parsed.error === true && typeof parsed.body === \"string\") {\n this._agentToolLastErrors.set(runId, parsed.body);\n } else if (\n typeof parsed.body === \"string\" &&\n parsed.body.length > 0\n ) {\n // Advance the live sequence even with no tailer attached so a\n // tailer registering mid-run resumes at the right offset.\n const sequence = this._agentToolLiveSequences.get(runId) ?? 0;\n this._agentToolLiveSequences.set(runId, sequence + 1);\n const chunk = { sequence, body: parsed.body };\n const forwarders = this._agentToolForwarders.get(runId);\n if (forwarders) {\n for (const forward of forwarders) forward(chunk);\n }\n }\n }\n }\n } catch {\n // Non-chat frames pass through unchanged.\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 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 = '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 constructor(ctx: AgentContext, env: Env) {\n super(ctx, env);\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 // Restore request context from SQLite (survives hibernation)\n this._restoreRequestContext();\n\n // Initialize resumable stream manager (creates its own tables + restores state)\n this._resumableStream = new ResumableStream(this.sql.bind(this));\n\n // Load messages and automatically transform them to v5 format.\n // Note: _loadMessagesFromDb() runs structural validation which requires\n // `parts` to be an array. Legacy v4 messages (with `content` instead of\n // `parts`) would fail this check — but that's fine because autoTransformMessages\n // already migrated them on a previous load, and persistMessages wrote them back.\n // Any message still without `parts` at this point is genuinely corrupt.\n const rawMessages = this._loadMessagesFromDb();\n\n // Automatic migration following https://jhak.im/blog/ai-sdk-migration-handling-previously-saved-messages\n this.messages = autoTransformMessages(rawMessages);\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 }\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 // Call consumer's onClose\n return _onClose(connection, code, reason, wasClean);\n };\n\n // Wrap onMessage\n const _onMessage = this.onMessage.bind(this);\n this.onMessage = async (connection: Connection, message: WSMessage) => {\n if (this._cf_connectionTargetsSubAgent(connection)) {\n return _onMessage(connection, message);\n }\n\n // Handle AIChatAgent's internal messages first\n if (typeof message === \"string\") {\n let data: IncomingMessage;\n try {\n data = JSON.parse(message) as IncomingMessage;\n } catch (_error) {\n // Not JSON, forward to consumer\n return _onMessage(connection, message);\n }\n\n // Handle chat request\n if (\n data.type === MessageType.CF_AGENT_USE_CHAT_REQUEST &&\n data.init.method === \"POST\"\n ) {\n const { body } = data.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 = data.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 this._clearChatTerminal();\n\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 = 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 this._broadcastChatMessage(\n {\n messages: transformedMessages,\n type: MessageType.CF_AGENT_CHAT_MESSAGES\n },\n [connection.id]\n );\n\n await this.persistMessages(transformedMessages, [connection.id], {\n _deleteStaleRows: true\n });\n\n if (concurrencyDecision.strategy === \"merge\") {\n await this._mergeQueuedUserMessages(epoch);\n }\n } finally {\n releasePendingEnqueue();\n }\n return 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 this._mergeQueuedUserMessages(epoch);\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 // 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 this._emit(\"message:request\");\n\n const abortSignal = 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 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 this._reply(\n chatMessageId,\n response,\n [connection.id],\n {\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 }\n };\n\n if (this.chatRecovery) {\n await this._runChatRecoveryFiber(\n chatMessageId,\n false,\n chatTurnBody\n );\n } else {\n await chatTurnBody();\n }\n }\n );\n });\n },\n {\n epoch,\n onStale: () =>\n this._completeSkippedRequest(connection, chatMessageId)\n }\n );\n }\n\n // Handle clear chat\n if (data.type === MessageType.CF_AGENT_CHAT_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._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 (data.type === MessageType.CF_AGENT_CHAT_MESSAGES) {\n const transformedMessages = autoTransformMessages(data.messages);\n await this.persistMessages(transformedMessages, [connection.id]);\n return;\n }\n\n // Handle request cancellation\n if (data.type === MessageType.CF_AGENT_CHAT_REQUEST_CANCEL) {\n this._abortRegistry.cancel(data.id);\n this._emit(\"message:cancel\", { requestId: data.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 (data.type === MessageType.CF_AGENT_STREAM_RESUME_REQUEST) {\n if (this._resumableStream.hasActiveStream()) {\n if (\n this._continuation.activeRequestId ===\n this._resumableStream.activeRequestId &&\n this._continuation.activeConnectionId !== null &&\n this._continuation.activeConnectionId !== connection.id\n ) {\n sendIfOpen(\n connection,\n JSON.stringify({\n type: MessageType.CF_AGENT_STREAM_RESUME_NONE\n })\n );\n } else {\n this._notifyStreamResuming(connection);\n }\n } else if (\n this._continuation.pending !== null &&\n (this._continuation.pending.connectionId === null ||\n this._continuation.pending.connectionId === connection.id)\n ) {\n this._continuation.awaitingConnections.set(\n connection.id,\n connection\n );\n } else if (await this._replayTerminalOnResume(connection)) {\n // A turn terminalized while no client was connected (#1645): drive\n // the resume handshake so the terminal error frame can be delivered\n // on the resumed stream (the only path that surfaces as an error on\n // the client) once this connection ACKs — see `_replayTerminalOnAck`.\n } else {\n sendIfOpen(\n connection,\n JSON.stringify({\n type: MessageType.CF_AGENT_STREAM_RESUME_NONE\n })\n );\n }\n return;\n }\n\n // Handle stream resume acknowledgment\n if (data.type === MessageType.CF_AGENT_STREAM_RESUME_ACK) {\n this._pendingResumeConnections.delete(connection.id);\n\n if (\n this._resumableStream.hasActiveStream() &&\n this._resumableStream.activeRequestId === data.id\n ) {\n const orphanedStreamId = this._resumableStream.replayChunks(\n connection,\n this._resumableStream.activeRequestId\n );\n\n // If the stream was orphaned (restored from SQLite after\n // hibernation with no live reader), reconstruct the partial\n // assistant message from stored chunks and persist it so it\n // survives further page refreshes.\n if (orphanedStreamId) {\n await this._persistOrphanedStream(orphanedStreamId);\n }\n } else if (this._resumableStream.hasActiveStream()) {\n // Ignore ACKs for a different active stream request id.\n } else if (await this._replayTerminalOnAck(connection, data.id)) {\n // Delivered the pending terminal error frame on the resumed stream\n // the client just ACKed (#1645).\n } else if (\n !this._resumableStream.replayCompletedChunksByRequestId(\n connection,\n data.id\n )\n ) {\n sendIfOpen(\n connection,\n JSON.stringify({\n body: \"\",\n done: true,\n id: data.id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n replay: true\n })\n );\n }\n return;\n }\n\n // Handle client-side tool result\n if (data.type === MessageType.CF_AGENT_TOOL_RESULT) {\n const {\n toolCallId,\n toolName,\n output,\n state,\n errorText,\n autoContinue,\n clientTools\n } = data;\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 const applyPromise = this._enqueueInteractionApply(() =>\n this._applyToolResult(\n toolCallId,\n toolName,\n output,\n overrideState,\n errorText\n )\n );\n\n if (autoContinue) {\n this._enqueueAutoContinuation(\n connection,\n clientTools ?? this._lastClientTools,\n this._lastBody,\n \"[AIChatAgent] Tool continuation failed:\",\n applyPromise\n );\n }\n return;\n }\n\n // Handle client-side tool approval response\n if (data.type === MessageType.CF_AGENT_TOOL_APPROVAL) {\n const { toolCallId, approved, autoContinue } = data;\n this._emit(\"tool:approval\", { toolCallId, approved });\n const approvalPromise = this._enqueueInteractionApply(() =>\n this._applyToolApproval(toolCallId, approved)\n );\n\n if (autoContinue) {\n this._enqueueAutoContinuation(\n connection,\n this._lastClientTools,\n this._lastBody,\n \"[AIChatAgent] Tool approval continuation failed:\",\n approvalPromise\n );\n }\n return;\n }\n }\n\n // Forward unhandled messages to consumer's onMessage\n return _onMessage(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 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 }\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 _mergeAutoContinuationPrerequisite(\n current: Promise<boolean> | null,\n next?: Promise<boolean>\n ): Promise<boolean> | null {\n if (!next) {\n return current;\n }\n\n if (!current) {\n return next;\n }\n\n return Promise.all([current, next]).then(\n ([currentApplied, nextApplied]) => {\n return currentApplied && nextApplied;\n }\n );\n }\n\n private _storeDeferredAutoContinuation(\n connection: Connection,\n clientTools: ClientToolSchema[] | undefined,\n body: Record<string, unknown> | undefined,\n errorPrefix: string,\n prerequisite?: Promise<boolean>\n ) {\n const existing = this._continuation.deferred;\n this._continuation.deferred = {\n connection,\n connectionId: connection.id,\n clientTools,\n body,\n errorPrefix,\n prerequisite: this._mergeAutoContinuationPrerequisite(\n existing?.prerequisite ?? null,\n prerequisite\n )\n };\n }\n\n private _activateDeferredAutoContinuation() {\n const pending = this._continuation.activateDeferred(() => nanoid());\n if (!pending) return;\n this._queueAutoContinuation(pending.requestId);\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 * Notify a connection about an active stream that can be resumed.\n * The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.\n *\n * A connection can legitimately be notified more than once for the same\n * request — proactively from onConnect AND in response to its\n * CF_AGENT_STREAM_RESUME_REQUEST (#1733). This is intentional and must NOT\n * be deduped here: an explicit resume request always deserves a response\n * (the client's reconnectToStream would otherwise hang until its safety\n * timeout, with no replay), and the proactive notify is required for\n * clients that never send a resume request. The notify itself is a single\n * tiny frame; clients are responsible for deduping the ACK so the full\n * chunk buffer is not replayed twice.\n * @param connection - The WebSocket connection to notify\n */\n private _notifyStreamResuming(connection: Connection) {\n if (!this._resumableStream.hasActiveStream()) {\n return;\n }\n\n // Notify client - they will send ACK when ready\n const sent = sendIfOpen(\n connection,\n JSON.stringify({\n type: MessageType.CF_AGENT_STREAM_RESUMING,\n id: this._resumableStream.activeRequestId\n })\n );\n if (sent) {\n // Add connection to pending set - they'll be excluded from live broadcasts\n // until they send ACK to receive the full stream replay\n this._pendingResumeConnections.add(connection.id);\n }\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 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 a stream whose DO is evicted mid-flight\n // and never reaches a finish still gets a future sweep instead of leaking.\n // This matters for `chatRecovery: false` (the default): those turns don't\n // run inside `runFiber`, so there is no durable keepAlive alarm and no\n // fiber-recovery scan — if the client never reconnects, nothing else ever\n // wakes the DO to finalize the orphan. (With `chatRecovery: true` the\n // leftover keepAlive alarm wakes the DO within ~keepAliveIntervalMs and\n // recovery finalizes the stream, which arms cleanup anyway — so this is\n // belt-and-suspenders there.) The last-activity sweep threshold keeps an\n // actively streaming run from being reclaimed before it 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, then re-arm only while rows\n * remain so a fully-swept DO stops waking itself. Public so it is reachable\n * as a schedule callback.\n * @internal\n */\n async _cleanupStreamBuffers(): Promise<void> {\n this._resumableStream.cleanup();\n if (this._resumableStream.hasReclaimableStreams()) {\n // Must NOT be idempotent: this runs INSIDE the currently-executing\n // one-shot schedule row, which `alarm()` deletes only after we return. An\n // idempotent reschedule would dedup onto that row and then be deleted with\n // it — the re-arm would silently never fire, leaving buffers that survived\n // this sweep (e.g. a younger turn) uncollected. A fresh delayed row\n // survives the deletion.\n await 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 /** Advance the recovery-progress counter when a chunk represents genuinely\n * new produced content — a started text/reasoning segment or a settled tool\n * input/output. Bumped at production time (the streaming path), so it\n * reflects real forward progress and is immune to client reconnects /\n * recovery re-persists (which replay or re-materialize stored chunks rather\n * than flow through here). This is what the recovery no-progress window keys\n * off (#1637), and stays compaction-proof (#1628). */\n private async _maybeBumpRecoveryProgress(\n type: string | undefined\n ): Promise<void> {\n if (\n type === \"text-start\" ||\n type === \"reasoning-start\" ||\n type === \"tool-input-available\" ||\n type === \"tool-output-available\" ||\n type === \"tool-output-error\" ||\n type === \"tool-output-denied\"\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 * Replays each chunk body through `applyChunkToParts` to rebuild the\n * message parts, then persists the result so it survives further refreshes.\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 const fallbackId = `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;\n const message: UIMessage = {\n id: fallbackId,\n role: \"assistant\",\n parts: []\n };\n\n for (const chunk of chunks) {\n try {\n const data = JSON.parse(chunk.body);\n\n // Capture a provider `start.messageId` if present. The live path adopts\n // it for new turns (see `_streamSSEReply`'s \"start\" handling), so\n // recovery must reuse it to land under the same id a completed live\n // turn would. Continuations have it stripped before storage (#1229).\n if (data.type === \"start\" && data.messageId != null) {\n message.id = data.messageId;\n }\n if (\n (data.type === \"start\" ||\n data.type === \"finish\" ||\n data.type === \"message-metadata\") &&\n data.messageMetadata != null\n ) {\n message.metadata = message.metadata\n ? { ...message.metadata, ...data.messageMetadata }\n : data.messageMetadata;\n }\n\n applyChunkToParts(message.parts, data);\n } catch {\n // Skip malformed chunk bodies\n }\n }\n\n if (message.parts.length > 0) {\n // Resolve the id to persist under when the chunks carried no provider\n // `start.messageId` (the common case — most providers don't emit one, and\n // continuations have it stripped, #1229). When a provider id WAS present\n // it was applied above and is kept, since the live path adopts it too.\n if (message.id === fallbackId) {\n // Preferred: the id allocated when the stream started, recorded in\n // stream metadata (#1691) — the SAME id the live path persists under\n // (it only adopts a provider id, never invents one). A new turn stored\n // its own fresh id, so it becomes its own message; a continuation\n // stored the cloned last-assistant id, so it merges (via the\n // existing-index check below). 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).\n const storedId = this._resumableStream.getStreamMessageId(streamId);\n if (storedId != null) {\n message.id = storedId;\n } else {\n // Legacy row written before the metadata column existed: fall back to\n // the last assistant message, matching pre-#1691 behavior.\n for (let i = this.messages.length - 1; i >= 0; i--) {\n if (this.messages[i].role === \"assistant\") {\n message.id = this.messages[i].id;\n break;\n }\n }\n }\n }\n\n // Check if a message with this ID already exists (e.g., from an\n // early persist during tool approval, or a continuation resuming\n // the last assistant message). Update in place if so.\n const existingIdx = this.messages.findIndex((m) => m.id === message.id);\n if (existingIdx >= 0) {\n // Merge: keep existing parts and append new ones from the stream.\n // A tool part is identified by its toolCallId, so a reconstructed part\n // whose toolCallId already exists is NOT re-appended — otherwise an\n // early persist (at tool approval) followed by recovery, which replays\n // the SAME chunks, would leave two parts for one tool call. The kept\n // (persisted) part is also the one that may have received a tool result\n // applied in place, so preserving it avoids regressing settled state.\n const existing = this.messages[existingIdx];\n const existingToolCallIds = new Set(\n existing.parts\n .filter(\n (p): p is typeof p & { toolCallId: string } => \"toolCallId\" in p\n )\n .map((p) => p.toolCallId)\n );\n const newParts = message.parts.filter(\n (p) => !(\"toolCallId\" in p && existingToolCallIds.has(p.toolCallId))\n );\n message.parts = [...existing.parts, ...newParts];\n if (existing.metadata) {\n message.metadata = message.metadata\n ? { ...existing.metadata, ...message.metadata }\n : existing.metadata;\n }\n }\n const updatedMessages =\n existingIdx >= 0\n ? this.messages.map((m, i) => (i === existingIdx ? message : m))\n : [...this.messages, message];\n await this.persistMessages(updatedMessages);\n // NOTE: progress is bumped at production/flush time in `_storeStreamChunk`\n // (#1637), NOT here — persisting on recovery or a client reconnect must\n // not be miscounted as new forward progress.\n }\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 await this._submitConcurrency.waitForIdle(() =>\n this._turnQueue.waitForIdle()\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 }\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 protected async waitUntilStable(options?: {\n timeout?: number;\n }): Promise<boolean> {\n const deadline =\n options?.timeout != null ? Date.now() + options.timeout : null;\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 (!this.hasPendingInteraction()) {\n return true;\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 this._continuation.sendResumeNone();\n this._continuation.clearAll();\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 async _awaitWithDeadline<T>(\n promise: Promise<T>,\n deadline: number | null\n ): Promise<T | typeof TIMED_OUT> {\n if (deadline == null) {\n return promise;\n }\n\n const remainingMs = Math.max(0, deadline - Date.now());\n let timer: ReturnType<typeof setTimeout>;\n const result = await Promise.race([\n promise,\n new Promise<typeof TIMED_OUT>((resolve) => {\n timer = setTimeout(() => resolve(TIMED_OUT), remainingMs);\n })\n ]);\n clearTimeout(timer!);\n return result;\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 if (!(\"state\" in part)) return false;\n const record = part as Record<string, unknown>;\n const state = record.state;\n if (state === \"approval-requested\") return true;\n if (state !== \"input-available\") return false;\n const toolName = this._toolPartName(record);\n return toolName != null && clientResolvable.has(toolName);\n }\n\n /** Extract a tool part's name from its `tool-<name>` / `dynamic-tool` shape. */\n private _toolPartName(record: Record<string, unknown>): string | undefined {\n const type = typeof record.type === \"string\" ? record.type : \"\";\n if (type === \"dynamic-tool\") {\n return typeof record.toolName === \"string\" ? record.toolName : undefined;\n }\n if (type.startsWith(\"tool-\")) {\n return type.slice(\"tool-\".length);\n }\n return undefined;\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 const names = new Set<string>();\n for (const tool of this._lastClientTools ?? []) {\n if (tool?.name) names.add(tool.name);\n }\n return names;\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(requestId, fn, {\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 (`_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 private _enqueueAutoContinuation(\n connection: Connection,\n clientTools: ClientToolSchema[] | undefined,\n body: Record<string, unknown> | undefined,\n errorPrefix: string,\n prerequisite?: Promise<boolean>\n ) {\n if (this._continuation.pending) {\n if (this._continuation.pending.pastCoalesce) {\n this._storeDeferredAutoContinuation(\n connection,\n clientTools,\n body,\n errorPrefix,\n prerequisite\n );\n return;\n }\n\n this._continuation.pending.connection = connection;\n this._continuation.pending.connectionId = connection.id;\n this._continuation.awaitingConnections.set(connection.id, connection);\n this._continuation.pending.clientTools = clientTools;\n this._continuation.pending.body = body;\n this._continuation.pending.errorPrefix = errorPrefix;\n this._continuation.pending.prerequisite =\n this._mergeAutoContinuationPrerequisite(\n this._continuation.pending.prerequisite,\n prerequisite\n );\n return;\n }\n\n const requestId = nanoid();\n this._continuation.pending = {\n connection,\n connectionId: connection.id,\n requestId,\n clientTools,\n body,\n errorPrefix,\n prerequisite: this._mergeAutoContinuationPrerequisite(null, prerequisite),\n pastCoalesce: false\n };\n this._continuation.awaitingConnections.set(connection.id, connection);\n this._queueAutoContinuation(requestId);\n }\n\n private async _awaitPendingAutoContinuationPrerequisite(): Promise<boolean> {\n while (true) {\n const prerequisite = this._continuation.pending?.prerequisite;\n if (!prerequisite) {\n break;\n }\n\n const applied = await prerequisite;\n if (!applied) {\n return false;\n }\n\n await new Promise((resolve) =>\n setTimeout(resolve, AIChatAgent.AUTO_CONTINUATION_COALESCE_MS)\n );\n\n if (this._continuation.pending?.prerequisite === prerequisite) {\n break;\n }\n }\n\n // #1649 barrier: the prior step may have emitted parallel tool calls. The\n // client answers each one independently, so the result that triggered this\n // continuation can arrive while slower siblings are still `input-available`\n // (or `approval-requested`). Continuing now would send the provider an\n // incomplete tool-result set. Hold until the batch settles, bounded so a\n // genuinely orphaned tool call (client disconnected mid-batch) still falls\n // through rather than pinning the continuation open forever.\n await this._awaitPendingInteractionBarrier();\n return true;\n }\n\n /**\n * Block until the latest assistant step's parallel tool batch is fully\n * answered, or `AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS` elapses. Awaits the\n * in-flight tool-result apply when one exists (so a sibling that lands\n * mid-wait is observed promptly) and polls otherwise. Runs inside the\n * continuation turn, so — unlike `waitUntilStable` — it must not wait on the\n * turn queue (that would deadlock).\n *\n * No concurrent-entry guard is needed (unlike Think's `_continuationBarrier\n * Active`): this runs inside the exclusive continuation turn, and a sibling\n * result arriving while it waits hits the merge branch of\n * `_enqueueAutoContinuation` (it updates `pending.prerequisite`) rather than\n * enqueuing a second turn — so the turn queue serializes barrier waits.\n */\n private async _awaitPendingInteractionBarrier(): Promise<void> {\n const deadline = Date.now() + AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS;\n while (Date.now() < deadline) {\n // The pending continuation was cleared (chat clear / turn reset) — nothing\n // to wait for; bail so the turn isn't held by a stale wait.\n if (!this._continuation.pending) return;\n const pending = this._pendingInteractionPromise;\n if (pending) {\n // `_pendingInteractionPromise` is a single slot — awaiting it is only a\n // \"wake up as soon as an apply lands\" optimization, NOT the correctness\n // gate (that is `_hasIncompleteToolBatch()`, re-checked each loop). If\n // sibling results overwrite the slot, each apply still patches the cache.\n try {\n await pending;\n } catch {\n // Ignore — re-evaluate the batch below.\n }\n continue;\n }\n if (!this._hasIncompleteToolBatch()) return;\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n // Timed out with the batch still incomplete: a sibling tool result never\n // arrived (e.g. the client disconnected mid-batch). Proceed anyway rather\n // than pinning the continuation turn open forever.\n console.warn(\n `[AIChatAgent] Auto-continuation proceeding after waiting ${AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS}ms for unanswered parallel tool result(s) (#1649).`\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 // Zero-allocation backward scan for the latest assistant message — this\n // runs on every barrier poll tick, and `this.messages` can be large.\n const messages = this.messages;\n let leaf: (typeof messages)[number] | undefined;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === \"assistant\") {\n leaf = messages[i];\n break;\n }\n }\n if (!leaf) return false;\n let hasPending = false;\n let hasSettled = false;\n for (const part of leaf.parts) {\n const record = part as Record<string, unknown>;\n const state = record.state;\n if (state === \"input-available\" || state === \"approval-requested\") {\n hasPending = true;\n } else if (\n typeof record.type === \"string\" &&\n (record.type.startsWith(\"tool-\") || record.type === \"dynamic-tool\") &&\n (state === \"output-available\" ||\n state === \"output-error\" ||\n state === \"output-denied\" ||\n state === \"approval-responded\")\n ) {\n hasSettled = true;\n }\n if (hasPending && hasSettled) return true;\n }\n return false;\n }\n\n private _queueAutoContinuation(requestId: string) {\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 waiting for prerequisites /\n // streaming, without deferring the queue registration.\n this._runExclusiveChatTurn(\n requestId,\n async () => {\n const dispose = await this.keepAlive();\n try {\n const applied =\n await this._awaitPendingAutoContinuationPrerequisite();\n if (!applied) {\n this._clearAllAutoContinuationState(true);\n return;\n }\n\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 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 if (this.chatRecovery) {\n await this._runChatRecoveryFiber(\n requestId,\n true,\n autoContinuationBody\n );\n } else {\n await 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 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 if (this.chatRecovery) {\n await this._runChatRecoveryFiber(\n requestId,\n false,\n programmaticBody\n );\n } else {\n await 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: StreamTextOnFinishCallback<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 /**\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 /**\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 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 async _classifyAgentToolChildRecovery(): Promise<\n \"in-progress\" | \"failed\" | \"none\"\n > {\n const entries = await this.ctx.storage.list<ChatRecoveryIncident>({\n prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX\n });\n let failed = false;\n for (const incident of entries.values()) {\n if (\n incident.status === \"detected\" ||\n incident.status === \"scheduled\" ||\n incident.status === \"attempting\"\n ) {\n return \"in-progress\";\n }\n if (incident.status === \"exhausted\" || incident.status === \"failed\") {\n failed = true;\n }\n }\n return failed ? \"failed\" : \"none\";\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 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 };\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 const stream = new ReadableStream<Uint8Array>({\n start: async (controller) => {\n let closed = false;\n const close = () => {\n if (closed) return;\n closed = true;\n controller.close();\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 for (const chunk of await this.getAgentToolChunks(runId, options)) {\n if (closed) return;\n controller.enqueue(\n agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\\n`)\n );\n }\n\n const inspection = await this.inspectAgentToolRun(runId);\n if (!inspection || inspection.status !== \"running\") {\n close();\n return;\n }\n\n const forwarders =\n this._agentToolForwarders.get(runId) ??\n new Set<(chunk: AgentToolStoredChunk) => void>();\n const forward = (chunk: AgentToolStoredChunk) => {\n if (closed) return;\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 close() running.\n // Drop the chunk instead of surfacing a stream rejection; the\n // child run is unaffected.\n close();\n }\n };\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 } catch (error) {\n controller.error(error);\n }\n },\n cancel: () => {}\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\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 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 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 if (this.chatRecovery) {\n await this._runChatRecoveryFiber(requestId, true, turnBody);\n } else {\n await turnBody();\n }\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 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 const raw = this.chatRecovery;\n const custom = typeof raw === \"object\" ? raw : undefined;\n return {\n enabled: raw !== false,\n maxAttempts: Math.max(\n 1,\n Math.floor(custom?.maxAttempts ?? DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS)\n ),\n stableTimeoutMs: Math.max(\n 0,\n Math.floor(\n custom?.stableTimeoutMs ?? DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS\n )\n ),\n terminalMessage:\n custom?.terminalMessage ?? DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE,\n noProgressTimeoutMs: Math.max(\n 0,\n Math.floor(\n custom?.noProgressTimeoutMs ??\n DEFAULT_CHAT_RECOVERY_NO_PROGRESS_TIMEOUT_MS\n )\n ),\n maxRecoveryWork:\n typeof custom?.maxRecoveryWork === \"number\" &&\n custom.maxRecoveryWork >= 0\n ? custom.maxRecoveryWork\n : DEFAULT_CHAT_RECOVERY_MAX_WORK,\n ...(custom?.shouldKeepRecovering\n ? { shouldKeepRecovering: custom.shouldKeepRecovering }\n : {}),\n ...(custom?.onExhausted ? { onExhausted: custom.onExhausted } : {})\n };\n }\n\n private _chatRecoveryIncidentId(input: {\n requestId: string;\n recoveryRootRequestId?: string | null;\n latestUserMessageId?: string | null;\n targetAssistantId?: string | null;\n recoveryKind: ChatRecoveryKind;\n }): string {\n // `recoveryKind` is intentionally NOT part of the identity: a single\n // interrupted turn can flip between \"retry\" (no chunks persisted) and\n // \"continue\" (partial chunks exist) across restarts, and the attempt\n // budget must be shared so recovery stays bounded by `maxAttempts`.\n return [\n input.recoveryRootRequestId ?? input.requestId,\n input.latestUserMessageId ?? \"\"\n ].join(\":\");\n }\n\n private _chatRecoveryIncidentKey(incidentId: string): string {\n return `${CHAT_RECOVERY_INCIDENT_KEY_PREFIX}${encodeURIComponent(incidentId)}`;\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 return (\n (await this.ctx.storage.get<number>(CHAT_RECOVERY_PROGRESS_KEY)) ?? 0\n );\n }\n\n /** Advance the durable recovery-progress counter. Called from\n * `_maybeBumpRecoveryProgress` when new content is streamed (real,\n * reconnect-immune forward progress). */\n private async _bumpChatRecoveryProgress(): Promise<void> {\n const current =\n (await this.ctx.storage.get<number>(CHAT_RECOVERY_PROGRESS_KEY)) ?? 0;\n await this.ctx.storage.put(CHAT_RECOVERY_PROGRESS_KEY, current + 1);\n }\n\n /** In-memory wall-clock of the last N9 child-stream progress bump (reset per\n * isolate so the first forwarded chunk after a restart always credits). */\n private _lastAgentToolStreamProgressAt = 0;\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 const now = Date.now();\n if (\n now - this._lastAgentToolStreamProgressAt <\n AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS\n ) {\n return;\n }\n this._lastAgentToolStreamProgressAt = now;\n await this._bumpChatRecoveryProgress();\n }\n\n /** Whether a reconstructed partial carries any settled (provider-accepted)\n * tool result — the completed, often non-idempotent work that a\n * `{ persist: false }` recovery return would silently discard.\n * `convertToModelMessages` treats `output-available` / `output-error` /\n * `output-denied` (or a part carrying `output`/`result`) as settled. */\n private _partialHasSettledToolResults(parts: MessagePart[]): boolean {\n return parts.some((part) => {\n const record = part as Record<string, unknown>;\n const type = typeof record.type === \"string\" ? record.type : \"\";\n if (!(type.startsWith(\"tool-\") || type === \"dynamic-tool\")) return false;\n if (\"output\" in record || \"result\" in record) return true;\n const state = typeof record.state === \"string\" ? record.state : \"\";\n return (\n state === \"output-available\" ||\n state === \"output-error\" ||\n state === \"output-denied\"\n );\n });\n }\n\n /** Sweep recovery incidents that have been inactive past the TTL. */\n private async _sweepStaleChatRecoveryIncidents(now: number): Promise<void> {\n const entries = await this.ctx.storage.list<ChatRecoveryIncident>({\n prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX\n });\n const staleKeys: string[] = [];\n for (const [key, incident] of entries) {\n const lastActive = incident?.lastAttemptAt ?? incident?.firstSeenAt ?? 0;\n if (now - lastActive > CHAT_RECOVERY_INCIDENT_TTL_MS) {\n staleKeys.push(key);\n }\n }\n // Batch deletes — the DO storage KV delete accepts up to 128 keys per call,\n // collapsing N awaited round-trips into ceil(N / 128).\n for (let i = 0; i < staleKeys.length; i += KV_DELETE_MAX_KEYS) {\n await this.ctx.storage.delete(staleKeys.slice(i, i + KV_DELETE_MAX_KEYS));\n }\n }\n\n private async _beginChatRecoveryIncident(input: {\n requestId: string;\n recoveryRootRequestId?: string | null;\n latestUserMessageId?: string | null;\n targetAssistantId?: 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 const config = this._resolveChatRecoveryConfig();\n const incidentId = this._chatRecoveryIncidentId(input);\n const key = this._chatRecoveryIncidentKey(incidentId);\n const now = input.nowMs ?? Date.now();\n await this._sweepStaleChatRecoveryIncidents(now);\n const existing = await this.ctx.storage.get<ChatRecoveryIncident>(key);\n\n // Forward-progress detection. A mid-turn deploy resets the Durable Object\n // (\"code was updated\"); the interrupted continuation is re-detected on the\n // next wake. A turn that followed real progress (more durably-produced\n // content than the last attempt saw) is environmental churn, not a poison\n // turn.\n const prevProgress = existing?.progress ?? 0;\n const currentProgress = await this._chatRecoveryProgressMarker();\n const madeProgress = existing != null && currentProgress > prevProgress;\n\n // A turn parked on a pending CLIENT interaction (an `input-available`\n // client-tool part or an `approval-requested` part — see\n // `hasPendingClientInteraction`) is WAITING ON THE HUMAN, not stuck. It\n // produces no forward progress by design until the client replays the\n // tool-result / approval after reconnect, which drives a fresh continuation\n // independently of recovery. Spending the recovery budget on that wait would\n // seal a perfectly healthy turn whose human is simply slow (e.g. a mid-turn\n // deploy during a confirmation prompt the user takes longer than\n // `noProgressTimeoutMs` to answer). So while a client interaction is pending\n // the turn is budget-free: the no-progress window, attempt cap, work budget,\n // and caller predicate are all suppressed, and the no-progress clock is kept\n // fresh so the turn has a full window once the human finally answers.\n // SERVER-tool orphans are excluded (their `execute` died with the isolate),\n // so they still recover normally. The recovery continuation additionally\n // PARKS (skips, no reschedule) on a stable-state timeout while this holds;\n // see `_chatRecoveryContinue`/`_chatRecoveryRetry`.\n const awaitingClientInteraction = this.hasPendingClientInteraction();\n\n // Recovery budget (#1637, rfc-chat-recovery-work-budget). A turn making\n // genuine forward progress survives unbounded deploy churn — duration is\n // never a bound. The instruments are decoupled by what they catch:\n // • STUCK — no-progress window: `lastProgressAt` resets on every\n // progress-bearing attempt, so a turn that keeps producing content\n // survives churn indefinitely; a stuck turn is sealed after 5 min.\n // • DEBOUNCE — alarms bunched within `ALARM_DEBOUNCE_MS` collapse into one\n // attempt, so a single rollout's reconnect storm isn't N attempts.\n // • ALARM-LOOP — the attempt cap (resets on progress) catches a tight\n // no-progress alarm loop.\n // • RUNAWAY — the work budget seals a loop that keeps emitting content but\n // never converges. Keyed to WORK done (produced content/tool units since\n // the incident opened), not wall-clock, because a healthy long turn and a\n // runaway differ by bounded work, not duration. Defaults to no cap.\n // • CALLER — `shouldKeepRecovering` lets the integrator express a\n // token/cost/step budget the SDK should not hardcode.\n const lastProgressAt =\n madeProgress || awaitingClientInteraction\n ? now\n : (existing?.lastProgressAt ?? existing?.firstSeenAt ?? now);\n const noProgressExceeded =\n existing != null &&\n !awaitingClientInteraction &&\n now - lastProgressAt > config.noProgressTimeoutMs;\n // Reuse the durable progress counter as a work meter. Baseline is captured\n // when the incident opens; `work` is what the turn produced since.\n const workBaseline = existing?.workBaseline ?? currentProgress;\n const progress = Math.max(prevProgress, currentProgress);\n const work = progress - workBaseline;\n const workBudgetExceeded =\n existing != null &&\n Number.isFinite(config.maxRecoveryWork) &&\n work > config.maxRecoveryWork;\n const debounced =\n existing != null &&\n !madeProgress &&\n now - existing.lastAttemptAt < CHAT_RECOVERY_ALARM_DEBOUNCE_MS;\n\n const attempt = madeProgress\n ? 1\n : debounced\n ? (existing?.attempt ?? 1)\n : (existing?.attempt ?? 0) + 1;\n\n // Consult the caller predicate only when no hard bound has already sealed\n // the incident — a buggy/expensive hook must not run after we've decided,\n // and a throwing hook must not wedge the turn (log and treat as \"continue\").\n let abortedByCaller = false;\n if (\n existing != null &&\n !awaitingClientInteraction &&\n config.shouldKeepRecovering &&\n !noProgressExceeded &&\n !workBudgetExceeded &&\n attempt <= config.maxAttempts\n ) {\n try {\n const decision = await config.shouldKeepRecovering({\n incidentId,\n requestId: input.requestId,\n recoveryRootRequestId: input.recoveryRootRequestId ?? input.requestId,\n attempt,\n maxAttempts: config.maxAttempts,\n recoveryKind: input.recoveryKind,\n work,\n ageMs: now - (existing.firstSeenAt ?? now)\n });\n abortedByCaller = decision === false;\n } catch (error) {\n console.error(\n \"[AIChatAgent] chatRecovery shouldKeepRecovering hook threw\",\n error\n );\n }\n }\n\n const exhausted =\n !awaitingClientInteraction &&\n (noProgressExceeded ||\n workBudgetExceeded ||\n abortedByCaller ||\n attempt > config.maxAttempts);\n const incident: ChatRecoveryIncident = {\n incidentId,\n requestId: input.requestId,\n recoveryRootRequestId: input.recoveryRootRequestId ?? input.requestId,\n recoveryKind: input.recoveryKind,\n attempt,\n maxAttempts: config.maxAttempts,\n status: exhausted ? \"exhausted\" : \"attempting\",\n firstSeenAt: existing?.firstSeenAt ?? now,\n lastAttemptAt: now,\n lastProgressAt,\n progress,\n workBaseline,\n ...(exhausted\n ? {\n reason: workBudgetExceeded\n ? \"work_budget_exceeded\"\n : noProgressExceeded\n ? \"no_progress_timeout\"\n : abortedByCaller\n ? \"recovery_aborted\"\n : \"max_attempts_exceeded\"\n }\n : {})\n };\n await this.ctx.storage.put(key, incident);\n\n if (!existing) {\n this._emit(\"chat:recovery:detected\", {\n incidentId,\n requestId: input.requestId,\n attempt,\n maxAttempts: config.maxAttempts,\n recoveryKind: input.recoveryKind\n });\n }\n this._emit(\"chat:recovery:attempt\", {\n incidentId,\n requestId: input.requestId,\n attempt,\n maxAttempts: config.maxAttempts,\n recoveryKind: input.recoveryKind\n });\n\n return { incident, config, exhausted };\n }\n\n private async _updateChatRecoveryIncident(\n incidentId: string | undefined,\n status: ChatRecoveryIncident[\"status\"],\n reason?: string\n ): Promise<void> {\n if (!incidentId) return;\n const key = this._chatRecoveryIncidentKey(incidentId);\n const incident = await this.ctx.storage.get<ChatRecoveryIncident>(key);\n if (!incident) return;\n // A completed recovery is terminal and will not be retried, so drop the\n // record instead of leaving it in storage forever. Non-completed states\n // (scheduled/skipped/failed) are retained so the attempt budget survives\n // across restarts; the TTL sweep eventually reclaims abandoned ones.\n if (status === \"completed\") {\n await this.ctx.storage.delete(key);\n } else {\n const updated: ChatRecoveryIncident = {\n ...incident,\n status,\n ...(reason ? { reason } : {})\n };\n await this.ctx.storage.put(key, updated);\n }\n const eventType =\n status === \"completed\"\n ? \"chat:recovery:completed\"\n : status === \"skipped\"\n ? \"chat:recovery:skipped\"\n : status === \"failed\"\n ? \"chat:recovery:failed\"\n : undefined;\n if (eventType) {\n this._emit(eventType, {\n incidentId,\n requestId: incident.requestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind: incident.recoveryKind,\n ...(reason ? { reason } : {})\n });\n }\n\n // Live \"recovering…\" status (#1620): a scheduled continuation/retry means\n // recovery is in progress; a terminal incident state resolves it.\n if (status === \"scheduled\") {\n await this._setChatRecovering(\n true,\n incident.recoveryRootRequestId ?? incident.requestId\n );\n } else if (\n status === \"completed\" ||\n status === \"skipped\" ||\n status === \"failed\"\n ) {\n await this._setChatRecovering(false);\n }\n }\n\n private async _exhaustChatRecovery(\n incident: ChatRecoveryIncident,\n config: ResolvedChatRecoveryConfig,\n partial: { text: string; parts: MessagePart[] },\n streamId: string,\n createdAt: number\n ): Promise<void> {\n const ctx: ChatRecoveryExhaustedContext = {\n incidentId: incident.incidentId,\n requestId: incident.requestId,\n recoveryRootRequestId:\n incident.recoveryRootRequestId ?? incident.requestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind: incident.recoveryKind,\n streamId,\n createdAt,\n partialText: partial.text,\n partialParts: partial.parts,\n reason: incident.reason ?? \"max_attempts_exceeded\",\n terminalMessage: config.terminalMessage\n };\n this._emit(\"chat:recovery:exhausted\", ctx);\n // A throwing onExhausted hook must not prevent the terminal UX from being\n // delivered, otherwise the turn wedges with no user-visible resolution.\n try {\n await config.onExhausted?.(ctx);\n } catch (error) {\n console.error(\"[AIChatAgent] chatRecovery onExhausted hook threw\", error);\n }\n // Persist the terminal outcome BEFORE broadcasting it (#1645): the\n // broadcast is transient, so a client disconnected at this moment (a\n // deploy/reconnect storm exhausting recovery) would otherwise never learn\n // the turn failed. The record is replayed on the next reconnect via the\n // resume handshake (`_replayTerminalOnResume`).\n await this._recordChatTerminal(incident.requestId, config.terminalMessage);\n this._broadcastChatMessage({\n body: config.terminalMessage,\n done: true,\n error: true,\n id: incident.requestId,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE\n });\n // Exhaustion resolves recovery — clear the \"recovering…\" status (#1620).\n await this._setChatRecovering(false);\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 this.ctx.storage.put(CHAT_LAST_TERMINAL_KEY, { 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 this.ctx.storage.delete(CHAT_LAST_TERMINAL_KEY);\n }\n\n private async _pendingChatTerminal(): Promise<{\n requestId: string;\n body: string;\n } | null> {\n return (\n (await this.ctx.storage.get<{ requestId: string; body: string }>(\n CHAT_LAST_TERMINAL_KEY\n )) ?? null\n );\n }\n\n /**\n * Replay a pending terminal outcome (#1645) over the resume handshake so a\n * reconnecting client surfaces it exactly like a live exhaustion. The bare\n * terminal frame is dropped by the client unless it arrives on a resumed\n * stream — the only path that reaches the transport's stream reader and\n * becomes `useChat.error` — so we drive `STREAM_RESUMING` here and deliver\n * the error frame once the client ACKs (see `_replayTerminalOnAck`).\n * Returns true if a terminal was pending (and `STREAM_RESUMING` was sent).\n */\n private async _replayTerminalOnResume(\n connection: Connection\n ): Promise<boolean> {\n const pending = await this._pendingChatTerminal();\n if (!pending) return false;\n sendIfOpen(\n connection,\n JSON.stringify({\n type: MessageType.CF_AGENT_STREAM_RESUMING,\n id: pending.requestId\n })\n );\n return true;\n }\n\n /**\n * Deliver the pending terminal error frame on the resumed stream the client\n * ACKed (#1645). The record is retained (not cleared) so concurrent\n * reconnects (e.g. multiple tabs) each learn the outcome; it is cleared when\n * a later turn supersedes it.\n */\n private async _replayTerminalOnAck(\n connection: Connection,\n requestId: string\n ): Promise<boolean> {\n const pending = await this._pendingChatTerminal();\n if (!pending || pending.requestId !== requestId) return false;\n // Replay any partial content the errored stream produced before the\n // error, so the reconnecting client observes the same sequence a live\n // client did — content chunks, then the terminal error (#1575). If the\n // connection drops mid-replay, skip the terminal frame; the record is\n // retained, so the next reconnect retries the whole sequence.\n if (\n !this._resumableStream.replayErroredChunksByRequestId(\n connection,\n pending.requestId\n )\n ) {\n return true;\n }\n sendIfOpen(\n connection,\n JSON.stringify({\n body: pending.body,\n done: true,\n error: true,\n id: pending.requestId,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE\n })\n );\n return true;\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 * NOTE: the live \"recovering…\" signal is still not replayed on connect — only\n * the terminal outcome is (#1645, via the resume handshake).\n */\n private async _setChatRecovering(\n active: boolean,\n requestId?: string\n ): Promise<void> {\n const existing = await this.ctx.storage.get<{\n requestId?: string;\n at?: number;\n }>(CHAT_RECOVERING_KEY);\n // A flag older than the TTL is stale: the owning incident was abandoned\n // without a terminal (e.g. the DO went idle before recovery could resolve).\n // Treat it as not-recovering so it can't suppress a genuinely-new recovering\n // signal.\n const activeExisting =\n existing && Date.now() - (existing.at ?? 0) < CHAT_RECOVERING_FLAG_TTL_MS;\n if (active) {\n if (activeExisting) return; // already recovering — idempotent, no re-broadcast\n await this.ctx.storage.put(CHAT_RECOVERING_KEY, {\n ...(requestId ? { requestId } : {}),\n at: Date.now()\n });\n } else {\n if (!existing) return; // not recovering — nothing to clear\n await this.ctx.storage.delete(CHAT_RECOVERING_KEY);\n requestId = requestId ?? existing.requestId;\n }\n this._broadcastChatMessage({\n type: MessageType.CF_AGENT_CHAT_RECOVERING,\n recovering: active,\n ...(requestId ? { id: requestId } : {})\n });\n }\n\n protected override async _handleInternalFiberRecovery(\n ctx: FiberRecoveryContext\n ): Promise<boolean> {\n const chatPrefix =\n (this.constructor as typeof AIChatAgent).CHAT_FIBER_NAME + \":\";\n if (!ctx.name.startsWith(chatPrefix)) {\n return false;\n }\n\n const requestId = ctx.name.slice(chatPrefix.length);\n const { snapshot: recoverySnapshot, user: recoveryData } =\n unwrapChatFiberSnapshot<\"ai-chat-turn\">(\n \"__cfAIChatFiberSnapshot\",\n ctx.snapshot,\n \"ai-chat-turn\"\n );\n\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\n const partial = streamId\n ? this._getPartialStreamText(streamId)\n : { text: \"\", parts: [] as MessagePart[] };\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.\n const streamStillActive =\n streamId &&\n this._resumableStream.hasActiveStream() &&\n this._resumableStream.activeStreamId === streamId;\n\n const shouldRetryPreStream = this._shouldRetryRecoveredPreStreamTurn(\n recoverySnapshot,\n streamId ?? \"\",\n partial\n );\n // A new turn whose stream produced no assistant partial at all (interrupted\n // before the first chunk materialized) will be re-run fresh rather than\n // continued (#1691) — and that is knowable *before* `onChatRecovery`,\n // because an empty partial persists nothing and leaves the conversation\n // leaf at the user message regardless of what the hook returns. Report it\n // as \"retry\" so the hook and the incident match the action that follows.\n // The sibling `persist: false` case (a NON-empty partial the hook chooses\n // to discard) only becomes a retry based on the hook's own return value, so\n // it cannot be pre-detected here — the hook still sees \"continue\" there and\n // only the `chat:recovery:scheduled` event reflects the final \"retry\".\n const preStreamLeaf =\n this.messages.length > 0\n ? this.messages[this.messages.length - 1]\n : undefined;\n const emptyPartialNewTurn =\n !!streamId &&\n recoverySnapshot?.continuation === false &&\n !!recoverySnapshot.latestUserMessageId &&\n partial.text === \"\" &&\n partial.parts.length === 0 &&\n preStreamLeaf?.role === \"user\" &&\n preStreamLeaf.id === recoverySnapshot.latestUserMessageId;\n const recoveryKind: ChatRecoveryKind =\n shouldRetryPreStream || emptyPartialNewTurn ? \"retry\" : \"continue\";\n const recoveryRootRequestId =\n recoverySnapshot?.recoveryRootRequestId ?? requestId;\n const { incident, config, exhausted } =\n await this._beginChatRecoveryIncident({\n requestId,\n recoveryRootRequestId,\n latestUserMessageId: recoverySnapshot?.latestUserMessageId,\n recoveryKind\n });\n\n if (exhausted) {\n // Preserve the settled partial before sealing the turn. Exhaustion is\n // decided BEFORE `onChatRecovery` is consulted, so without this the\n // settled (often non-idempotent) tool results the turn already produced\n // are discarded and the model re-runs them on the next message (#1631).\n if (streamStillActive) {\n await this._persistOrphanedStream(streamId);\n }\n await this._exhaustChatRecovery(\n incident,\n config,\n partial,\n streamId,\n ctx.createdAt\n );\n return true;\n }\n\n // Any throw after the incident is opened (user `onChatRecovery`, orphan\n // persistence, scheduling) must flip the incident to a terminal `failed`\n // state and emit, otherwise it leaks in `attempting` and is never\n // observable as a stuck turn.\n try {\n const options =\n (await this.onChatRecovery({\n incidentId: incident.incidentId,\n recoveryRootRequestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind,\n streamId: streamId ?? \"\",\n requestId,\n partialText: partial.text,\n partialParts: partial.parts,\n recoveryData,\n messages: [...this.messages],\n lastBody: recoverySnapshot?.lastBody ?? this._lastBody,\n lastClientTools:\n recoverySnapshot?.lastClientTools ?? this._lastClientTools,\n createdAt: ctx.createdAt\n })) ?? {};\n\n // Settled work — completed, often non-idempotent tool results — is NEVER\n // dropped by recovery. `persist: false` only suppresses persistence of a\n // partial that has nothing settled to lose; a partial carrying settled\n // tool results is persisted regardless, so an app can never accidentally\n // discard completed work (and never needs `{ persist: true }` just to be\n // safe). A safe default beats a warning about an unsafe one (#1631).\n if (\n streamStillActive &&\n (options.persist !== false ||\n this._partialHasSettledToolResults(partial.parts))\n ) {\n await this._persistOrphanedStream(streamId);\n }\n\n if (streamStillActive) {\n this._resumableStream.complete(streamId);\n void this._ensureStreamCleanupScheduled();\n }\n\n // A NEW turn (not a continuation) that produced no persisted assistant\n // partial — interrupted before any part materialized, or `persist: false`\n // discarded it — leaves the conversation leaf at the user message.\n // Continuing here would clone the PREVIOUS assistant turn (the most recent\n // assistant message, found by walking back past the trailing user\n // message) and merge this turn into it (#1691). Re-run the user turn fresh\n // instead, so it becomes its own message. Checked AFTER the persist step,\n // so a partial that WAS persisted (now the assistant leaf) still continues.\n const leaf =\n this.messages.length > 0\n ? this.messages[this.messages.length - 1]\n : undefined;\n const lostPartialUserId =\n recoverySnapshot?.continuation === false &&\n recoverySnapshot.latestUserMessageId &&\n leaf?.role === \"user\" &&\n leaf.id === recoverySnapshot.latestUserMessageId\n ? recoverySnapshot.latestUserMessageId\n : undefined;\n\n const targetId =\n shouldRetryPreStream || lostPartialUserId !== undefined\n ? undefined\n : this._findLastAssistantMessage()?.id;\n\n if (shouldRetryPreStream && options.continue !== false) {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"scheduled\"\n );\n this._emit(\"chat:recovery:scheduled\", {\n incidentId: incident.incidentId,\n requestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind\n });\n await this.schedule(\n 0,\n \"_chatRecoveryRetry\",\n {\n targetUserId: recoverySnapshot.latestUserMessageId,\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n lastBody: recoverySnapshot.lastBody ?? null,\n lastClientTools: recoverySnapshot.lastClientTools ?? null\n },\n { idempotent: true }\n );\n } else if (\n lostPartialUserId !== undefined &&\n options.continue !== false\n ) {\n // Re-run the orphaned new turn fresh instead of continuing (and\n // merging into) the previous assistant message.\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"scheduled\"\n );\n this._emit(\"chat:recovery:scheduled\", {\n incidentId: incident.incidentId,\n requestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind: \"retry\"\n });\n await this.schedule(\n 0,\n \"_chatRecoveryRetry\",\n {\n targetUserId: lostPartialUserId,\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n lastBody: recoverySnapshot?.lastBody ?? null,\n lastClientTools: recoverySnapshot?.lastClientTools ?? null\n },\n { idempotent: true }\n );\n } else if (options.continue !== false) {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"scheduled\"\n );\n this._emit(\"chat:recovery:scheduled\", {\n incidentId: incident.incidentId,\n requestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind\n });\n await this.schedule(\n 0,\n \"_chatRecoveryContinue\",\n {\n ...(targetId ? { targetAssistantId: targetId } : {}),\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n ...(recoverySnapshot\n ? {\n lastBody: recoverySnapshot.lastBody ?? null,\n lastClientTools: recoverySnapshot.lastClientTools ?? null\n }\n : {})\n },\n { idempotent: true }\n );\n } else {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"skipped\",\n \"continue_disabled\"\n );\n }\n\n return true;\n } catch (error) {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"failed\",\n error instanceof Error ? error.message : String(error)\n );\n throw error;\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 });\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 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 } 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 * 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: \"_chatRecoveryContinue\" | \"_chatRecoveryRetry\",\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined,\n maxAttempts: number\n ): Promise<boolean> {\n const incidentKey = data?.incidentId\n ? this._chatRecoveryIncidentKey(data.incidentId)\n : null;\n const incident = incidentKey\n ? await this.ctx.storage.get<ChatRecoveryIncident>(incidentKey)\n : null;\n if (!incident || !incidentKey) return false;\n const attempt = incident.attempt ?? 0;\n if (attempt >= (incident.maxAttempts ?? maxAttempts)) return false;\n await this.ctx.storage.put(incidentKey, {\n ...incident,\n attempt: attempt + 1,\n status: \"scheduled\",\n lastAttemptAt: Date.now(),\n reason: \"stable_timeout_retry\"\n });\n // Must NOT be idempotent: this runs inside the currently-executing one-shot\n // schedule row (deleted by `alarm()` only after we return). An idempotent\n // reschedule would dedup onto that row and be deleted with it — the retry\n // would never fire. A fresh delayed row survives.\n await this.schedule(\n CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS,\n callback,\n data ?? {},\n { idempotent: false }\n );\n return true;\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 * Resolve the stream id for a recovery turn so the give-up terminalization\n * can surface whatever partial the turn produced. Prefers the durable stream\n * row keyed by the recovery-root request id; falls back to the live active\n * stream. Returns `\"\"` when neither is available.\n */\n private _resolveRecoveryStreamId(requestId: string): string {\n if (requestId) {\n const fromMetadata = this._resumableStream\n .getAllStreamMetadata()\n .find((metadata) => metadata.request_id === requestId)?.id;\n if (fromMetadata) return fromMetadata;\n }\n return this._resumableStream.hasActiveStream()\n ? (this._resumableStream.activeStreamId ?? \"\")\n : \"\";\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 private async _exhaustRecoveryAfterStableTimeout(\n callback: \"_chatRecoveryContinue\" | \"_chatRecoveryRetry\",\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined\n ): Promise<void> {\n const config = this._resolveChatRecoveryConfig();\n const incidentKey = data?.incidentId\n ? this._chatRecoveryIncidentKey(data.incidentId)\n : null;\n let stored: ChatRecoveryIncident | null = null;\n if (incidentKey) {\n try {\n stored =\n (await this.ctx.storage.get<ChatRecoveryIncident>(incidentKey)) ??\n null;\n } catch (readError) {\n console.error(\n \"[AIChatAgent] failed to read recovery incident during give-up; synthesizing\",\n readError\n );\n }\n }\n\n // Re-entry guard (see method doc): a sealed incident means terminalization\n // already happened, so a duplicate stale alarm must not re-fire\n // `onExhausted` / re-broadcast the banner. This is ai-chat's ONLY guard.\n if (stored?.status === \"exhausted\") return;\n\n const rootRequestId =\n data?.originalRequestId ??\n this._activeChatRecoveryRootRequestId ??\n stored?.recoveryRootRequestId ??\n stored?.requestId ??\n \"\";\n\n // `stable_timeout` distinguishes a give-up driven by repeated stable-state\n // timeouts from the generic max-attempts / no-progress exhaustion reasons.\n const incident: ChatRecoveryIncident = stored\n ? { ...stored, status: \"exhausted\", reason: \"stable_timeout\" }\n : {\n // Silent-drop guard: the incident record is gone (no `incidentId`, or\n // it was swept/deleted before this stale alarm fired). Synthesize a\n // minimal incident so the turn STILL terminalizes through\n // `onExhausted` instead of being dropped with no terminal UX.\n incidentId: data?.incidentId ?? crypto.randomUUID(),\n requestId: rootRequestId,\n recoveryRootRequestId: rootRequestId,\n recoveryKind:\n callback === \"_chatRecoveryRetry\" ? \"retry\" : \"continue\",\n attempt: config.maxAttempts,\n maxAttempts: config.maxAttempts,\n status: \"exhausted\",\n firstSeenAt: Date.now(),\n lastAttemptAt: Date.now(),\n reason: \"stable_timeout\"\n };\n\n const streamId = this._resolveRecoveryStreamId(\n incident.recoveryRootRequestId ?? incident.requestId\n );\n const partial = streamId\n ? this._getPartialStreamText(streamId)\n : { text: \"\", parts: [] as MessagePart[] };\n\n // Terminalize BEFORE sealing the incident. The terminal write inside\n // `_exhaustChatRecovery` (`_recordChatTerminal`) hits storage and can\n // reject with a platform transient in exactly the window a give-up tends\n // to run in (#1730: deploy reset / storage outage). Letting that throw\n // propagate is deliberate: `Agent._executeScheduleCallback` defers the\n // one-shot row on a platform transient, so the WHOLE give-up re-runs on a\n // healthy isolate instead of half-sealing. Sealing first would arm the\n // re-entry guard above and turn that re-run into a no-op — dropping the\n // durable terminal record (#1645). The re-run is idempotent\n // (`_recordChatTerminal` overwrites the same key); `onExhausted` + the\n // banner may fire again — the documented at-least-once edge.\n await this._exhaustChatRecovery(\n incident,\n config,\n partial,\n streamId,\n incident.firstSeenAt\n );\n\n // Persist the sealed incident (retained for inspection / TTL sweep) so the\n // re-entry guard above sees `exhausted` if a duplicate stale alarm fires.\n // Best-effort: terminalization already fully succeeded, so a failed seal\n // write costs at most a re-delivered banner on a duplicate alarm.\n if (incidentKey) {\n try {\n await this.ctx.storage.put(incidentKey, incident);\n } catch (writeError) {\n console.error(\n \"[AIChatAgent] failed to persist sealed recovery incident during give-up\",\n writeError\n );\n }\n }\n }\n\n private _shouldRetryRecoveredPreStreamTurn(\n snapshot: ChatFiberSnapshot<\"ai-chat-turn\"> | null,\n streamId: string,\n partial: { text: string; parts: MessagePart[] }\n ): snapshot is ChatFiberSnapshot<\"ai-chat-turn\"> & {\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 });\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 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 } 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 } {\n const chunks = this._resumableStream.getStreamChunks(streamId);\n const parts: MessagePart[] = [];\n\n for (const chunk of chunks) {\n try {\n const data = JSON.parse(chunk.body);\n applyChunkToParts(parts, data);\n } catch {\n // Skip malformed chunk bodies\n }\n }\n\n const text = parts\n .filter(\n (p): p is MessagePart & { type: \"text\"; text: string } =>\n p.type === \"text\" && \"text\" in p\n )\n .map((p) => p.text)\n .join(\"\");\n\n return { text, parts };\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 let json = JSON.stringify(message);\n let size = chatByteLength(json);\n if (size <= ROW_MAX_BYTES) return message;\n\n if (message.role !== \"assistant\") {\n // Non-assistant messages (user/system) are harder to compact safely.\n // Truncate the entire message JSON as a last resort.\n console.warn(\n `[AIChatAgent] Non-assistant message ${message.id} is ${size} bytes, ` +\n `exceeds row limit. Truncating text parts.`\n );\n return this._truncateTextParts(message);\n }\n\n console.warn(\n `[AIChatAgent] Message ${message.id} is ${size} bytes, ` +\n `compacting tool outputs to fit SQLite row limit`\n );\n\n // Pass 1: compact tool outputs\n const compactedToolCallIds: string[] = [];\n const compactedParts = message.parts.map((part) => {\n if (\n \"output\" in part &&\n \"toolCallId\" in part &&\n \"state\" in part &&\n part.state === \"output-available\"\n ) {\n const outputJson = JSON.stringify((part as { output: unknown }).output);\n if (outputJson.length > 1000) {\n compactedToolCallIds.push(part.toolCallId as string);\n return {\n ...part,\n output:\n \"This tool output was too large to persist in storage \" +\n `(${outputJson.length} bytes). ` +\n \"If the user asks about this data, suggest re-running the tool. \" +\n `Preview: ${outputJson.slice(0, 500)}...`\n };\n }\n }\n return part;\n }) as UIMessage[\"parts\"];\n\n let result: UIMessage = {\n ...message,\n parts: compactedParts\n };\n\n if (compactedToolCallIds.length > 0) {\n result.metadata = {\n ...(result.metadata ?? {}),\n compactedToolOutputs: compactedToolCallIds\n };\n }\n\n // Check if tool compaction was enough\n json = JSON.stringify(result);\n size = chatByteLength(json);\n if (size <= ROW_MAX_BYTES) return result;\n\n // Pass 2: truncate text parts\n console.warn(\n `[AIChatAgent] Message ${message.id} still ${size} bytes after tool compaction, truncating text parts`\n );\n return this._truncateTextParts(result);\n }\n\n /**\n * Truncates text parts in a message to fit within the row size limit.\n * Truncates from the first text part forward, keeping the last text part\n * as intact as possible (it is usually the most relevant).\n */\n private _truncateTextParts(message: UIMessage): UIMessage {\n const compactedTextPartIndices: number[] = [];\n const parts = [...message.parts];\n\n // Truncate text parts from oldest to newest until we fit\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n if (part.type === \"text\" && \"text\" in part) {\n const text = (part as { text: string }).text;\n if (text.length > 1000) {\n compactedTextPartIndices.push(i);\n parts[i] = {\n ...part,\n text:\n `[Text truncated for storage (${text.length} chars). ` +\n `First 500 chars: ${text.slice(0, 500)}...]`\n } as UIMessage[\"parts\"][number];\n\n // Check if we fit now\n const candidate = { ...message, parts };\n if (chatByteLength(JSON.stringify(candidate)) <= ROW_MAX_BYTES) {\n break;\n }\n }\n }\n }\n\n const result: UIMessage = { ...message, parts };\n if (compactedTextPartIndices.length > 0) {\n result.metadata = {\n ...(result.metadata ?? {}),\n compactedTextParts: compactedTextPartIndices\n };\n }\n return result;\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 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 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. Convert the internal \"finish\" event's finishReason into the\n // UIMessageStreamPart messageMetadata format (#677).\n let eventToSend: unknown = data;\n if (continuation && data.type === \"start\" && \"messageId\" in data) {\n const { messageId: _, ...rest } = data as {\n messageId: unknown;\n [key: string]: unknown;\n };\n eventToSend = rest;\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 return this._findAndUpdateToolPart(\n toolCallId,\n \"_applyToolApproval\",\n [\"input-available\", \"approval-requested\"],\n (part) => ({\n ...part,\n state: approved ? \"approval-responded\" : \"output-denied\",\n // Merge with existing approval data to preserve the id field.\n // convertToModelMessages needs approval.id to produce a valid\n // tool-approval-request content part with approvalId.\n approval: {\n ...(part.approval as Record<string, unknown> | undefined),\n approved\n }\n })\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\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 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 } 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 (streamCompleted.value && streamResult.status !== \"error\") {\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(updatedMessages, excludeBroadcastIds);\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 && { error: streamResult.error })\n });\n return streamResult;\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":";;;;;;AAoJA,MAAM,oCAAoC;AAM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IACjE,OAEE,MAAM,KAAK,gBACT,CAAC,GAAG,KAAK,UAAU,OAAO,GAC1B,mBACF;GAEJ,OACE,MAAM,KAAK,gBACT,CAAC,GAAG,KAAK,UAAU,OAAO,GAC1B,mBACF;GAIJ,KAAK,4BAA4B,KAAK;IACpC;IACA,WAAW;IACX;IACA,QAAQ,aAAa;IACrB,GAAI,aAAa,UAAU,KAAA,KAAa,EAAE,OAAO,aAAa,MAAM;GACtE,CAAC;GACD,OAAO;EACT,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":["agentContext","chatByteLength"],"sources":["../src/index.ts"],"sourcesContent":["import type {\n UIMessage,\n StreamTextOnFinishCallback,\n TextUIPart,\n ToolSet,\n UIMessageChunk\n} from \"ai\";\nimport {\n Agent,\n __DO_NOT_USE_WILL_BREAK__agentContext as agentContext,\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 {\n MessageType,\n type IncomingMessage,\n type OutgoingMessage\n} from \"./types\";\nimport { autoTransformMessages } from \"./ai-chat-v5-migration\";\nimport {\n reconcileMessages,\n resolveToolMergeId,\n createChatFiberSnapshot,\n unwrapChatFiberSnapshot,\n wrapChatFiberSnapshot\n} from \"agents/chat\";\nimport {\n applyChunkToParts,\n isReplayChunk,\n sanitizeMessage,\n byteLength as chatByteLength,\n ROW_MAX_BYTES,\n TurnQueue,\n SubmitConcurrencyController,\n type TurnResult,\n type MessagePart,\n type StreamChunkData,\n type SubmitConcurrencyDecision,\n type ChatFiberSnapshot\n} from \"agents/chat\";\nimport { ResumableStream } from \"agents/chat\";\nimport { MAX_BOUND_PARAMS, buildInClauseStrings } from \"agents/chat\";\nimport {\n ContinuationState,\n AbortRegistry,\n type ClientToolSchema\n} from \"agents/chat\";\nimport type {\n ChatResponseResult,\n ChatRecoveryConfig,\n ChatRecoveryContext,\n ChatRecoveryExhaustedContext,\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 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\ntype ChatRecoveryKind = \"retry\" | \"continue\";\n\ntype ChatRecoveryIncident = {\n incidentId: string;\n requestId: string;\n /** Stable request ID for the whole continuation chain (the recovery root). */\n recoveryRootRequestId?: string;\n recoveryKind: ChatRecoveryKind;\n attempt: number;\n maxAttempts: number;\n status:\n | \"detected\"\n | \"scheduled\"\n | \"attempting\"\n | \"completed\"\n | \"skipped\"\n | \"exhausted\"\n | \"failed\";\n firstSeenAt: number;\n lastAttemptAt: number;\n /**\n * Epoch ms of the last attempt that observed forward progress. The recovery\n * budget is keyed to this (`now - lastProgressAt > NO_PROGRESS_WINDOW`), so a\n * turn that keeps producing content survives churn indefinitely while a\n * genuinely stuck turn is sealed within the window (#1637). Optional for\n * backward-compat — falls back to `firstSeenAt`.\n */\n lastProgressAt?: number;\n reason?: string;\n /**\n * High-water mark of the durable, monotonic recovery-progress counter (see\n * `_chatRecoveryProgressMarker`) observed for this incident. Used to\n * distinguish a turn that is making forward progress but keeps getting\n * interrupted by isolate resets (deploys) — which should NOT exhaust the\n * budget — from one that genuinely fails to advance. Sourced from a persisted\n * counter rather than the live transcript so compaction cannot lower it\n * (#1628).\n */\n progress?: number;\n /**\n * Value of the durable progress counter when this incident first opened. The\n * runaway-loop work budget is `progress - workBaseline` (work produced since\n * the incident began); compared against `maxRecoveryWork`. Optional for\n * backward-compat with incidents persisted before this field existed — a\n * missing baseline is treated as the current marker (zero work so far), so an\n * in-flight incident from an older build is never falsely sealed.\n */\n workBaseline?: number;\n};\n\nconst CHAT_RECOVERY_INCIDENT_KEY_PREFIX = \"cf:chat-recovery:incident:\";\n// Durable, monotonic forward-progress counter for recovery budget resets.\n// Bumped at production time when new content is streamed (`_storeStreamChunk`),\n// so it reflects genuinely new content and is immune to reconnects/re-persists;\n// never recomputed from the (compactable) transcript. See\n// `_chatRecoveryProgressMarker`.\nconst CHAT_RECOVERY_PROGRESS_KEY = \"cf:chat-recovery:progress\";\n// Secondary backstop only. The primary recovery bound is the no-progress\n// wall clock below; with alarm debounce this cap rarely binds (it catches a\n// pathological tight alarm-loop). Kept high so the no-progress window seals\n// first under normal deploy cadence (#1637).\nconst DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS = 10;\n// Runaway-loop guard default. `Infinity` = no SDK-imposed work cap: a turn that\n// keeps making forward progress is never terminated by the framework on its own\n// (rfc-chat-recovery-work-budget). Integrators bound a content-emitting runaway\n// by setting `maxRecoveryWork` or a `shouldKeepRecovering` predicate.\nconst DEFAULT_CHAT_RECOVERY_MAX_WORK = Number.POSITIVE_INFINITY;\nconst DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS = 10_000;\n// Auto-continuation barrier (#1649): when the model emits parallel tool calls,\n// 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. So we wait until the transcript is stable (no\n// `input-available`/`approval-requested` parts) before continuing, bounded by\n// this timeout so a genuinely orphaned tool call (e.g. the client disconnected\n// mid-batch) still falls through instead of pinning the continuation open.\nconst AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS = 60_000;\n// Delay before retrying a recovery that timed out waiting for stable state.\n// Gives an actively-churning isolate (e.g. a deploy in flight) time to settle.\nconst CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS = 3;\nconst DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE =\n \"The assistant was interrupted and could not recover. Please try again.\";\n// Durable record of an in-progress recovery so a \"recovering…\" status (#1620)\n// can be broadcast live and survives the set/clear happening in different\n// isolates (a continuation runs in a later alarm invocation). NOTE: this live\n// \"recovering…\" status is NOT replayed on connect — only the terminal outcome\n// is (#1645, via the resume handshake; see `CHAT_LAST_TERMINAL_KEY`). A client\n// that connects mid-recovery isn't re-told it's recovering, but the live\n// broadcast + reliable clear work regardless, and any terminal outcome is\n// surfaced on reconnect.\nconst CHAT_RECOVERING_KEY = \"cf:chat:recovering\";\n// Durable record of the last turn that ended in a terminal error / abandoned\n// recovery (#1645). The terminal `CF_AGENT_USE_CHAT_RESPONSE` broadcast is\n// transient, so a client disconnected at the moment recovery exhausts would\n// otherwise never learn the turn failed and stay frozen. Replayed on the next\n// reconnect via the resume handshake (`_replayTerminalOnResume`); cleared when\n// a later turn supersedes it.\nconst CHAT_LAST_TERMINAL_KEY = \"cf:chat:last-terminal\";\n// Incidents that have not seen a new attempt within this window are assumed\n// abandoned and swept so durable storage does not grow without bound.\nconst CHAT_RECOVERY_INCIDENT_TTL_MS = 60 * 60 * 1000;\n// Max keys per Durable Object KV `delete([...])` call.\n// See https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/\nconst KV_DELETE_MAX_KEYS = 128;\n// PRIMARY recovery bound (#1637): seal an incident that has made no forward\n// progress for this long. Keyed to `lastProgressAt`, which resets on every\n// progress-bearing attempt — so a turn that keeps producing content survives\n// deploy churn indefinitely, while a genuinely stuck turn dies within 5 min.\n// Overridable per-agent via `chatRecovery.noProgressTimeoutMs`.\nconst DEFAULT_CHAT_RECOVERY_NO_PROGRESS_TIMEOUT_MS = 5 * 60 * 1000;\n// Alarm debounce: recovery alarms bunched within this window collapse into a\n// single attempt. A deploy rollout drops/reconnects the socket several times\n// over ~11–22s; without this, one logical deploy would burn several attempts.\nconst CHAT_RECOVERY_ALARM_DEBOUNCE_MS = 30 * 1000;\n// Staleness bound for the live \"recovering…\" flag (#1620). A flag older than\n// this is treated as abandoned (the owning incident died without a terminal,\n// e.g. the DO went idle) so it can neither pin the indicator on forever nor\n// suppress a genuinely-new recovering signal. This is NOT a recovery budget —\n// a progressing turn is bounded by work, not wall-clock\n// (rfc-chat-recovery-work-budget).\nconst CHAT_RECOVERING_FLAG_TTL_MS = 15 * 60 * 1000;\n// N9: while a parent re-attaches to and forwards a sub-agent's stream, credit\n// the parent's recovery progress at most this often. The marker only needs to\n// advance ≥once between recovery attempts (the no-progress window is minutes),\n// so this caps storage writes during high-rate child streaming. The throttle\n// state is in-memory (reset per isolate), so the first forwarded chunk after\n// ANY restart always bumps — guaranteeing every recovery attempt that observes\n// child output registers forward progress.\nconst AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS = 5_000;\n\n// How far ahead to schedule the resumable-stream buffer cleanup alarm. Set to\n// ResumableStream's short completion-grace window (COMPLETED_RETENTION_MS, 10m)\n// so a finished buffer is reclaimed promptly. The re-arm-while-reclaimable loop\n// (see _cleanupStreamBuffers) revisits any longer-lived rows — e.g. an\n// abandoned in-flight buffer on its 1h window — by waking again each interval\n// until they age out, then stops. Driving cleanup from an alarm (rather than\n// only piggybacking on the next stream completion) ensures idle/one-off chat\n// DOs still reclaim their buffers without waking forever (#1706).\nconst STREAM_CLEANUP_DELAY_SECONDS = 10 * 60;\n\ntype StreamResultStatus = {\n status: Exclude<SaveMessagesResult[\"status\"], \"skipped\">;\n error?: string;\n};\n\nfunction sendIfOpen(connection: Connection, message: string): boolean {\n try {\n connection.send(message);\n return true;\n } catch (error) {\n if (isWebSocketClosedSendError(error)) return false;\n throw error;\n }\n}\n\nfunction isWebSocketClosedSendError(error: unknown): boolean {\n return (\n error instanceof TypeError &&\n error.message.includes(\"WebSocket send() after close\")\n );\n}\n\nexport type ChatMessage = UIMessage;\n\nconst TIMED_OUT = Symbol(\"timed-out\");\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 full Zod 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. Zod schemas cannot be 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};\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 * When true, chat turns are wrapped in `runFiber` for durable execution.\n * Enables `onChatRecovery` hook and `this.stash()` during streaming.\n * Set to `true` in subclasses to enable durable streaming.\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 = false;\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 /**\n * Continuation lifecycle state: pending, deferred, active, and\n * connections awaiting a continuation stream to start.\n */\n private _continuation = new ContinuationState<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 * Small debounce window to batch adjacent client-side tool results/approvals\n * into a single server continuation turn.\n */\n private static AUTO_CONTINUATION_COALESCE_MS = 10;\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 // Inspect frames while any agent-tool run is in flight (live sequences\n // exist for the run's whole lifecycle), not only while a tailer is\n // attached — error capture must not depend on tailer timing (#1575).\n if (\n (this._agentToolForwarders.size > 0 ||\n this._agentToolLiveSequences.size > 0) &&\n typeof msg === \"string\"\n ) {\n try {\n const parsed = JSON.parse(msg) as {\n type?: unknown;\n body?: unknown;\n error?: unknown;\n id?: unknown;\n };\n if (\n parsed.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE &&\n typeof parsed.id === \"string\"\n ) {\n // A frame belongs to a run iff it carries that run's turn request\n // id. Frames from unrelated turns (a user-driven turn on this\n // agent, or another run's turn) resolve to a different — or no —\n // run and are left alone, so concurrent runs cannot\n // cross-contaminate each other's progress or error state (#1575).\n const runId = this._agentToolRunForRequest(parsed.id);\n if (runId !== null) {\n if (parsed.error === true && typeof parsed.body === \"string\") {\n this._agentToolLastErrors.set(runId, parsed.body);\n } else if (\n typeof parsed.body === \"string\" &&\n parsed.body.length > 0\n ) {\n // Advance the live sequence even with no tailer attached so a\n // tailer registering mid-run resumes at the right offset.\n const sequence = this._agentToolLiveSequences.get(runId) ?? 0;\n this._agentToolLiveSequences.set(runId, sequence + 1);\n const chunk = { sequence, body: parsed.body };\n const forwarders = this._agentToolForwarders.get(runId);\n if (forwarders) {\n for (const forward of forwarders) forward(chunk);\n }\n }\n }\n }\n } catch {\n // Non-chat frames pass through unchanged.\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 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 = '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 constructor(ctx: AgentContext, env: Env) {\n super(ctx, env);\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 // Restore request context from SQLite (survives hibernation)\n this._restoreRequestContext();\n\n // Initialize resumable stream manager (creates its own tables + restores state)\n this._resumableStream = new ResumableStream(this.sql.bind(this));\n\n // Load messages and automatically transform them to v5 format.\n // Note: _loadMessagesFromDb() runs structural validation which requires\n // `parts` to be an array. Legacy v4 messages (with `content` instead of\n // `parts`) would fail this check — but that's fine because autoTransformMessages\n // already migrated them on a previous load, and persistMessages wrote them back.\n // Any message still without `parts` at this point is genuinely corrupt.\n const rawMessages = this._loadMessagesFromDb();\n\n // Automatic migration following https://jhak.im/blog/ai-sdk-migration-handling-previously-saved-messages\n this.messages = autoTransformMessages(rawMessages);\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 }\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 // Call consumer's onClose\n return _onClose(connection, code, reason, wasClean);\n };\n\n // Wrap onMessage\n const _onMessage = this.onMessage.bind(this);\n this.onMessage = async (connection: Connection, message: WSMessage) => {\n if (this._cf_connectionTargetsSubAgent(connection)) {\n return _onMessage(connection, message);\n }\n\n // Handle AIChatAgent's internal messages first\n if (typeof message === \"string\") {\n let data: IncomingMessage;\n try {\n data = JSON.parse(message) as IncomingMessage;\n } catch (_error) {\n // Not JSON, forward to consumer\n return _onMessage(connection, message);\n }\n\n // Handle chat request\n if (\n data.type === MessageType.CF_AGENT_USE_CHAT_REQUEST &&\n data.init.method === \"POST\"\n ) {\n const { body } = data.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 = data.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 this._clearChatTerminal();\n\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 = 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 this._broadcastChatMessage(\n {\n messages: transformedMessages,\n type: MessageType.CF_AGENT_CHAT_MESSAGES\n },\n [connection.id]\n );\n\n await this.persistMessages(transformedMessages, [connection.id], {\n _deleteStaleRows: true\n });\n\n if (concurrencyDecision.strategy === \"merge\") {\n await this._mergeQueuedUserMessages(epoch);\n }\n } finally {\n releasePendingEnqueue();\n }\n return 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 this._mergeQueuedUserMessages(epoch);\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 // 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 this._emit(\"message:request\");\n\n const abortSignal = 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 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 this._reply(\n chatMessageId,\n response,\n [connection.id],\n {\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 }\n };\n\n if (this.chatRecovery) {\n await this._runChatRecoveryFiber(\n chatMessageId,\n false,\n chatTurnBody\n );\n } else {\n await chatTurnBody();\n }\n }\n );\n });\n },\n {\n epoch,\n onStale: () =>\n this._completeSkippedRequest(connection, chatMessageId)\n }\n );\n }\n\n // Handle clear chat\n if (data.type === MessageType.CF_AGENT_CHAT_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._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 (data.type === MessageType.CF_AGENT_CHAT_MESSAGES) {\n const transformedMessages = autoTransformMessages(data.messages);\n await this.persistMessages(transformedMessages, [connection.id]);\n return;\n }\n\n // Handle request cancellation\n if (data.type === MessageType.CF_AGENT_CHAT_REQUEST_CANCEL) {\n this._abortRegistry.cancel(data.id);\n this._emit(\"message:cancel\", { requestId: data.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 (data.type === MessageType.CF_AGENT_STREAM_RESUME_REQUEST) {\n if (this._resumableStream.hasActiveStream()) {\n if (\n this._continuation.activeRequestId ===\n this._resumableStream.activeRequestId &&\n this._continuation.activeConnectionId !== null &&\n this._continuation.activeConnectionId !== connection.id\n ) {\n sendIfOpen(\n connection,\n JSON.stringify({\n type: MessageType.CF_AGENT_STREAM_RESUME_NONE\n })\n );\n } else {\n this._notifyStreamResuming(connection);\n }\n } else if (\n this._continuation.pending !== null &&\n (this._continuation.pending.connectionId === null ||\n this._continuation.pending.connectionId === connection.id)\n ) {\n this._continuation.awaitingConnections.set(\n connection.id,\n connection\n );\n } else if (await this._replayTerminalOnResume(connection)) {\n // A turn terminalized while no client was connected (#1645): drive\n // the resume handshake so the terminal error frame can be delivered\n // on the resumed stream (the only path that surfaces as an error on\n // the client) once this connection ACKs — see `_replayTerminalOnAck`.\n } else {\n sendIfOpen(\n connection,\n JSON.stringify({\n type: MessageType.CF_AGENT_STREAM_RESUME_NONE\n })\n );\n }\n return;\n }\n\n // Handle stream resume acknowledgment\n if (data.type === MessageType.CF_AGENT_STREAM_RESUME_ACK) {\n this._pendingResumeConnections.delete(connection.id);\n\n if (\n this._resumableStream.hasActiveStream() &&\n this._resumableStream.activeRequestId === data.id\n ) {\n const orphanedStreamId = this._resumableStream.replayChunks(\n connection,\n this._resumableStream.activeRequestId\n );\n\n // If the stream was orphaned (restored from SQLite after\n // hibernation with no live reader), reconstruct the partial\n // assistant message from stored chunks and persist it so it\n // survives further page refreshes.\n if (orphanedStreamId) {\n await this._persistOrphanedStream(orphanedStreamId);\n }\n } else if (this._resumableStream.hasActiveStream()) {\n // Ignore ACKs for a different active stream request id.\n } else if (await this._replayTerminalOnAck(connection, data.id)) {\n // Delivered the pending terminal error frame on the resumed stream\n // the client just ACKed (#1645).\n } else if (\n !this._resumableStream.replayCompletedChunksByRequestId(\n connection,\n data.id\n )\n ) {\n sendIfOpen(\n connection,\n JSON.stringify({\n body: \"\",\n done: true,\n id: data.id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,\n replay: true\n })\n );\n }\n return;\n }\n\n // Handle client-side tool result\n if (data.type === MessageType.CF_AGENT_TOOL_RESULT) {\n const {\n toolCallId,\n toolName,\n output,\n state,\n errorText,\n autoContinue,\n clientTools\n } = data;\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 const applyPromise = this._enqueueInteractionApply(() =>\n this._applyToolResult(\n toolCallId,\n toolName,\n output,\n overrideState,\n errorText\n )\n );\n\n if (autoContinue) {\n this._enqueueAutoContinuation(\n connection,\n clientTools ?? this._lastClientTools,\n this._lastBody,\n \"[AIChatAgent] Tool continuation failed:\",\n applyPromise\n );\n }\n return;\n }\n\n // Handle client-side tool approval response\n if (data.type === MessageType.CF_AGENT_TOOL_APPROVAL) {\n const { toolCallId, approved, autoContinue } = data;\n this._emit(\"tool:approval\", { toolCallId, approved });\n const approvalPromise = this._enqueueInteractionApply(() =>\n this._applyToolApproval(toolCallId, approved)\n );\n\n if (autoContinue) {\n this._enqueueAutoContinuation(\n connection,\n this._lastClientTools,\n this._lastBody,\n \"[AIChatAgent] Tool approval continuation failed:\",\n approvalPromise\n );\n }\n return;\n }\n }\n\n // Forward unhandled messages to consumer's onMessage\n return _onMessage(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 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 }\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 _mergeAutoContinuationPrerequisite(\n current: Promise<boolean> | null,\n next?: Promise<boolean>\n ): Promise<boolean> | null {\n if (!next) {\n return current;\n }\n\n if (!current) {\n return next;\n }\n\n return Promise.all([current, next]).then(\n ([currentApplied, nextApplied]) => {\n return currentApplied && nextApplied;\n }\n );\n }\n\n private _storeDeferredAutoContinuation(\n connection: Connection,\n clientTools: ClientToolSchema[] | undefined,\n body: Record<string, unknown> | undefined,\n errorPrefix: string,\n prerequisite?: Promise<boolean>\n ) {\n const existing = this._continuation.deferred;\n this._continuation.deferred = {\n connection,\n connectionId: connection.id,\n clientTools,\n body,\n errorPrefix,\n prerequisite: this._mergeAutoContinuationPrerequisite(\n existing?.prerequisite ?? null,\n prerequisite\n )\n };\n }\n\n private _activateDeferredAutoContinuation() {\n const pending = this._continuation.activateDeferred(() => nanoid());\n if (!pending) return;\n this._queueAutoContinuation(pending.requestId);\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 * Notify a connection about an active stream that can be resumed.\n * The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.\n *\n * A connection can legitimately be notified more than once for the same\n * request — proactively from onConnect AND in response to its\n * CF_AGENT_STREAM_RESUME_REQUEST (#1733). This is intentional and must NOT\n * be deduped here: an explicit resume request always deserves a response\n * (the client's reconnectToStream would otherwise hang until its safety\n * timeout, with no replay), and the proactive notify is required for\n * clients that never send a resume request. The notify itself is a single\n * tiny frame; clients are responsible for deduping the ACK so the full\n * chunk buffer is not replayed twice.\n * @param connection - The WebSocket connection to notify\n */\n private _notifyStreamResuming(connection: Connection) {\n if (!this._resumableStream.hasActiveStream()) {\n return;\n }\n\n // Notify client - they will send ACK when ready\n const sent = sendIfOpen(\n connection,\n JSON.stringify({\n type: MessageType.CF_AGENT_STREAM_RESUMING,\n id: this._resumableStream.activeRequestId\n })\n );\n if (sent) {\n // Add connection to pending set - they'll be excluded from live broadcasts\n // until they send ACK to receive the full stream replay\n this._pendingResumeConnections.add(connection.id);\n }\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 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 a stream whose DO is evicted mid-flight\n // and never reaches a finish still gets a future sweep instead of leaking.\n // This matters for `chatRecovery: false` (the default): those turns don't\n // run inside `runFiber`, so there is no durable keepAlive alarm and no\n // fiber-recovery scan — if the client never reconnects, nothing else ever\n // wakes the DO to finalize the orphan. (With `chatRecovery: true` the\n // leftover keepAlive alarm wakes the DO within ~keepAliveIntervalMs and\n // recovery finalizes the stream, which arms cleanup anyway — so this is\n // belt-and-suspenders there.) The last-activity sweep threshold keeps an\n // actively streaming run from being reclaimed before it 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, then re-arm only while rows\n * remain so a fully-swept DO stops waking itself. Public so it is reachable\n * as a schedule callback.\n * @internal\n */\n async _cleanupStreamBuffers(): Promise<void> {\n this._resumableStream.cleanup();\n if (this._resumableStream.hasReclaimableStreams()) {\n // Must NOT be idempotent: this runs INSIDE the currently-executing\n // one-shot schedule row, which `alarm()` deletes only after we return. An\n // idempotent reschedule would dedup onto that row and then be deleted with\n // it — the re-arm would silently never fire, leaving buffers that survived\n // this sweep (e.g. a younger turn) uncollected. A fresh delayed row\n // survives the deletion.\n await 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 /** Advance the recovery-progress counter when a chunk represents genuinely\n * new produced content — a started text/reasoning segment or a settled tool\n * input/output. Bumped at production time (the streaming path), so it\n * reflects real forward progress and is immune to client reconnects /\n * recovery re-persists (which replay or re-materialize stored chunks rather\n * than flow through here). This is what the recovery no-progress window keys\n * off (#1637), and stays compaction-proof (#1628). */\n private async _maybeBumpRecoveryProgress(\n type: string | undefined\n ): Promise<void> {\n if (\n type === \"text-start\" ||\n type === \"reasoning-start\" ||\n type === \"tool-input-available\" ||\n type === \"tool-output-available\" ||\n type === \"tool-output-error\" ||\n type === \"tool-output-denied\"\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 * Replays each chunk body through `applyChunkToParts` to rebuild the\n * message parts, then persists the result so it survives further refreshes.\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 const fallbackId = `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;\n const message: UIMessage = {\n id: fallbackId,\n role: \"assistant\",\n parts: []\n };\n\n for (const chunk of chunks) {\n try {\n const data = JSON.parse(chunk.body);\n\n // Capture a provider `start.messageId` if present. The live path adopts\n // it for new turns (see `_streamSSEReply`'s \"start\" handling), so\n // recovery must reuse it to land under the same id a completed live\n // turn would. Continuations have it stripped before storage (#1229).\n if (data.type === \"start\" && data.messageId != null) {\n message.id = data.messageId;\n }\n if (\n (data.type === \"start\" ||\n data.type === \"finish\" ||\n data.type === \"message-metadata\") &&\n data.messageMetadata != null\n ) {\n message.metadata = message.metadata\n ? { ...message.metadata, ...data.messageMetadata }\n : data.messageMetadata;\n }\n\n applyChunkToParts(message.parts, data);\n } catch {\n // Skip malformed chunk bodies\n }\n }\n\n if (message.parts.length > 0) {\n // Resolve the id to persist under when the chunks carried no provider\n // `start.messageId` (the common case — most providers don't emit one, and\n // continuations have it stripped, #1229). When a provider id WAS present\n // it was applied above and is kept, since the live path adopts it too.\n if (message.id === fallbackId) {\n // Preferred: the id allocated when the stream started, recorded in\n // stream metadata (#1691) — the SAME id the live path persists under\n // (it only adopts a provider id, never invents one). A new turn stored\n // its own fresh id, so it becomes its own message; a continuation\n // stored the cloned last-assistant id, so it merges (via the\n // existing-index check below). 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).\n const storedId = this._resumableStream.getStreamMessageId(streamId);\n if (storedId != null) {\n message.id = storedId;\n } else {\n // Legacy row written before the metadata column existed: fall back to\n // the last assistant message, matching pre-#1691 behavior.\n for (let i = this.messages.length - 1; i >= 0; i--) {\n if (this.messages[i].role === \"assistant\") {\n message.id = this.messages[i].id;\n break;\n }\n }\n }\n }\n\n // Check if a message with this ID already exists (e.g., from an\n // early persist during tool approval, or a continuation resuming\n // the last assistant message). Update in place if so.\n const existingIdx = this.messages.findIndex((m) => m.id === message.id);\n if (existingIdx >= 0) {\n // Merge: keep existing parts and append new ones from the stream.\n // A tool part is identified by its toolCallId, so a reconstructed part\n // whose toolCallId already exists is NOT re-appended — otherwise an\n // early persist (at tool approval) followed by recovery, which replays\n // the SAME chunks, would leave two parts for one tool call. The kept\n // (persisted) part is also the one that may have received a tool result\n // applied in place, so preserving it avoids regressing settled state.\n const existing = this.messages[existingIdx];\n const existingToolCallIds = new Set(\n existing.parts\n .filter(\n (p): p is typeof p & { toolCallId: string } => \"toolCallId\" in p\n )\n .map((p) => p.toolCallId)\n );\n const newParts = message.parts.filter(\n (p) => !(\"toolCallId\" in p && existingToolCallIds.has(p.toolCallId))\n );\n message.parts = [...existing.parts, ...newParts];\n if (existing.metadata) {\n message.metadata = message.metadata\n ? { ...existing.metadata, ...message.metadata }\n : existing.metadata;\n }\n }\n const updatedMessages =\n existingIdx >= 0\n ? this.messages.map((m, i) => (i === existingIdx ? message : m))\n : [...this.messages, message];\n await this.persistMessages(updatedMessages);\n // NOTE: progress is bumped at production/flush time in `_storeStreamChunk`\n // (#1637), NOT here — persisting on recovery or a client reconnect must\n // not be miscounted as new forward progress.\n }\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 await this._submitConcurrency.waitForIdle(() =>\n this._turnQueue.waitForIdle()\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 }\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 protected async waitUntilStable(options?: {\n timeout?: number;\n }): Promise<boolean> {\n const deadline =\n options?.timeout != null ? Date.now() + options.timeout : null;\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 (!this.hasPendingInteraction()) {\n return true;\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 this._continuation.sendResumeNone();\n this._continuation.clearAll();\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 async _awaitWithDeadline<T>(\n promise: Promise<T>,\n deadline: number | null\n ): Promise<T | typeof TIMED_OUT> {\n if (deadline == null) {\n return promise;\n }\n\n const remainingMs = Math.max(0, deadline - Date.now());\n let timer: ReturnType<typeof setTimeout>;\n const result = await Promise.race([\n promise,\n new Promise<typeof TIMED_OUT>((resolve) => {\n timer = setTimeout(() => resolve(TIMED_OUT), remainingMs);\n })\n ]);\n clearTimeout(timer!);\n return result;\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 if (!(\"state\" in part)) return false;\n const record = part as Record<string, unknown>;\n const state = record.state;\n if (state === \"approval-requested\") return true;\n if (state !== \"input-available\") return false;\n const toolName = this._toolPartName(record);\n return toolName != null && clientResolvable.has(toolName);\n }\n\n /** Extract a tool part's name from its `tool-<name>` / `dynamic-tool` shape. */\n private _toolPartName(record: Record<string, unknown>): string | undefined {\n const type = typeof record.type === \"string\" ? record.type : \"\";\n if (type === \"dynamic-tool\") {\n return typeof record.toolName === \"string\" ? record.toolName : undefined;\n }\n if (type.startsWith(\"tool-\")) {\n return type.slice(\"tool-\".length);\n }\n return undefined;\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 const names = new Set<string>();\n for (const tool of this._lastClientTools ?? []) {\n if (tool?.name) names.add(tool.name);\n }\n return names;\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(requestId, fn, {\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 (`_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 private _enqueueAutoContinuation(\n connection: Connection,\n clientTools: ClientToolSchema[] | undefined,\n body: Record<string, unknown> | undefined,\n errorPrefix: string,\n prerequisite?: Promise<boolean>\n ) {\n if (this._continuation.pending) {\n if (this._continuation.pending.pastCoalesce) {\n this._storeDeferredAutoContinuation(\n connection,\n clientTools,\n body,\n errorPrefix,\n prerequisite\n );\n return;\n }\n\n this._continuation.pending.connection = connection;\n this._continuation.pending.connectionId = connection.id;\n this._continuation.awaitingConnections.set(connection.id, connection);\n this._continuation.pending.clientTools = clientTools;\n this._continuation.pending.body = body;\n this._continuation.pending.errorPrefix = errorPrefix;\n this._continuation.pending.prerequisite =\n this._mergeAutoContinuationPrerequisite(\n this._continuation.pending.prerequisite,\n prerequisite\n );\n return;\n }\n\n const requestId = nanoid();\n this._continuation.pending = {\n connection,\n connectionId: connection.id,\n requestId,\n clientTools,\n body,\n errorPrefix,\n prerequisite: this._mergeAutoContinuationPrerequisite(null, prerequisite),\n pastCoalesce: false\n };\n this._continuation.awaitingConnections.set(connection.id, connection);\n this._queueAutoContinuation(requestId);\n }\n\n private async _awaitPendingAutoContinuationPrerequisite(): Promise<boolean> {\n while (true) {\n const prerequisite = this._continuation.pending?.prerequisite;\n if (!prerequisite) {\n break;\n }\n\n const applied = await prerequisite;\n if (!applied) {\n return false;\n }\n\n await new Promise((resolve) =>\n setTimeout(resolve, AIChatAgent.AUTO_CONTINUATION_COALESCE_MS)\n );\n\n if (this._continuation.pending?.prerequisite === prerequisite) {\n break;\n }\n }\n\n // #1649 barrier: the prior step may have emitted parallel tool calls. The\n // client answers each one independently, so the result that triggered this\n // continuation can arrive while slower siblings are still `input-available`\n // (or `approval-requested`). Continuing now would send the provider an\n // incomplete tool-result set. Hold until the batch settles, bounded so a\n // genuinely orphaned tool call (client disconnected mid-batch) still falls\n // through rather than pinning the continuation open forever.\n await this._awaitPendingInteractionBarrier();\n return true;\n }\n\n /**\n * Block until the latest assistant step's parallel tool batch is fully\n * answered, or `AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS` elapses. Awaits the\n * in-flight tool-result apply when one exists (so a sibling that lands\n * mid-wait is observed promptly) and polls otherwise. Runs inside the\n * continuation turn, so — unlike `waitUntilStable` — it must not wait on the\n * turn queue (that would deadlock).\n *\n * No concurrent-entry guard is needed (unlike Think's `_continuationBarrier\n * Active`): this runs inside the exclusive continuation turn, and a sibling\n * result arriving while it waits hits the merge branch of\n * `_enqueueAutoContinuation` (it updates `pending.prerequisite`) rather than\n * enqueuing a second turn — so the turn queue serializes barrier waits.\n */\n private async _awaitPendingInteractionBarrier(): Promise<void> {\n const deadline = Date.now() + AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS;\n while (Date.now() < deadline) {\n // The pending continuation was cleared (chat clear / turn reset) — nothing\n // to wait for; bail so the turn isn't held by a stale wait.\n if (!this._continuation.pending) return;\n const pending = this._pendingInteractionPromise;\n if (pending) {\n // `_pendingInteractionPromise` is a single slot — awaiting it is only a\n // \"wake up as soon as an apply lands\" optimization, NOT the correctness\n // gate (that is `_hasIncompleteToolBatch()`, re-checked each loop). If\n // sibling results overwrite the slot, each apply still patches the cache.\n try {\n await pending;\n } catch {\n // Ignore — re-evaluate the batch below.\n }\n continue;\n }\n if (!this._hasIncompleteToolBatch()) return;\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n // Timed out with the batch still incomplete: a sibling tool result never\n // arrived (e.g. the client disconnected mid-batch). Proceed anyway rather\n // than pinning the continuation turn open forever.\n console.warn(\n `[AIChatAgent] Auto-continuation proceeding after waiting ${AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS}ms for unanswered parallel tool result(s) (#1649).`\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 // Zero-allocation backward scan for the latest assistant message — this\n // runs on every barrier poll tick, and `this.messages` can be large.\n const messages = this.messages;\n let leaf: (typeof messages)[number] | undefined;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === \"assistant\") {\n leaf = messages[i];\n break;\n }\n }\n if (!leaf) return false;\n let hasPending = false;\n let hasSettled = false;\n for (const part of leaf.parts) {\n const record = part as Record<string, unknown>;\n const state = record.state;\n if (state === \"input-available\" || state === \"approval-requested\") {\n hasPending = true;\n } else if (\n typeof record.type === \"string\" &&\n (record.type.startsWith(\"tool-\") || record.type === \"dynamic-tool\") &&\n (state === \"output-available\" ||\n state === \"output-error\" ||\n state === \"output-denied\" ||\n state === \"approval-responded\")\n ) {\n hasSettled = true;\n }\n if (hasPending && hasSettled) return true;\n }\n return false;\n }\n\n private _queueAutoContinuation(requestId: string) {\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 waiting for prerequisites /\n // streaming, without deferring the queue registration.\n this._runExclusiveChatTurn(\n requestId,\n async () => {\n const dispose = await this.keepAlive();\n try {\n const applied =\n await this._awaitPendingAutoContinuationPrerequisite();\n if (!applied) {\n this._clearAllAutoContinuationState(true);\n return;\n }\n\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 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 if (this.chatRecovery) {\n await this._runChatRecoveryFiber(\n requestId,\n true,\n autoContinuationBody\n );\n } else {\n await 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 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 if (this.chatRecovery) {\n await this._runChatRecoveryFiber(\n requestId,\n false,\n programmaticBody\n );\n } else {\n await 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: StreamTextOnFinishCallback<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 /**\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 /**\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 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 async _classifyAgentToolChildRecovery(): Promise<\n \"in-progress\" | \"failed\" | \"none\"\n > {\n const entries = await this.ctx.storage.list<ChatRecoveryIncident>({\n prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX\n });\n let failed = false;\n for (const incident of entries.values()) {\n if (\n incident.status === \"detected\" ||\n incident.status === \"scheduled\" ||\n incident.status === \"attempting\"\n ) {\n return \"in-progress\";\n }\n if (incident.status === \"exhausted\" || incident.status === \"failed\") {\n failed = true;\n }\n }\n return failed ? \"failed\" : \"none\";\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 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 };\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 const stream = new ReadableStream<Uint8Array>({\n start: async (controller) => {\n let closed = false;\n const close = () => {\n if (closed) return;\n closed = true;\n controller.close();\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 for (const chunk of await this.getAgentToolChunks(runId, options)) {\n if (closed) return;\n controller.enqueue(\n agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\\n`)\n );\n }\n\n const inspection = await this.inspectAgentToolRun(runId);\n if (!inspection || inspection.status !== \"running\") {\n close();\n return;\n }\n\n const forwarders =\n this._agentToolForwarders.get(runId) ??\n new Set<(chunk: AgentToolStoredChunk) => void>();\n const forward = (chunk: AgentToolStoredChunk) => {\n if (closed) return;\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 close() running.\n // Drop the chunk instead of surfacing a stream rejection; the\n // child run is unaffected.\n close();\n }\n };\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 } catch (error) {\n controller.error(error);\n }\n },\n cancel: () => {}\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\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 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 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 if (this.chatRecovery) {\n await this._runChatRecoveryFiber(requestId, true, turnBody);\n } else {\n await turnBody();\n }\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 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 const raw = this.chatRecovery;\n const custom = typeof raw === \"object\" ? raw : undefined;\n return {\n enabled: raw !== false,\n maxAttempts: Math.max(\n 1,\n Math.floor(custom?.maxAttempts ?? DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS)\n ),\n stableTimeoutMs: Math.max(\n 0,\n Math.floor(\n custom?.stableTimeoutMs ?? DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS\n )\n ),\n terminalMessage:\n custom?.terminalMessage ?? DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE,\n noProgressTimeoutMs: Math.max(\n 0,\n Math.floor(\n custom?.noProgressTimeoutMs ??\n DEFAULT_CHAT_RECOVERY_NO_PROGRESS_TIMEOUT_MS\n )\n ),\n maxRecoveryWork:\n typeof custom?.maxRecoveryWork === \"number\" &&\n custom.maxRecoveryWork >= 0\n ? custom.maxRecoveryWork\n : DEFAULT_CHAT_RECOVERY_MAX_WORK,\n ...(custom?.shouldKeepRecovering\n ? { shouldKeepRecovering: custom.shouldKeepRecovering }\n : {}),\n ...(custom?.onExhausted ? { onExhausted: custom.onExhausted } : {})\n };\n }\n\n private _chatRecoveryIncidentId(input: {\n requestId: string;\n recoveryRootRequestId?: string | null;\n latestUserMessageId?: string | null;\n targetAssistantId?: string | null;\n recoveryKind: ChatRecoveryKind;\n }): string {\n // `recoveryKind` is intentionally NOT part of the identity: a single\n // interrupted turn can flip between \"retry\" (no chunks persisted) and\n // \"continue\" (partial chunks exist) across restarts, and the attempt\n // budget must be shared so recovery stays bounded by `maxAttempts`.\n return [\n input.recoveryRootRequestId ?? input.requestId,\n input.latestUserMessageId ?? \"\"\n ].join(\":\");\n }\n\n private _chatRecoveryIncidentKey(incidentId: string): string {\n return `${CHAT_RECOVERY_INCIDENT_KEY_PREFIX}${encodeURIComponent(incidentId)}`;\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 return (\n (await this.ctx.storage.get<number>(CHAT_RECOVERY_PROGRESS_KEY)) ?? 0\n );\n }\n\n /** Advance the durable recovery-progress counter. Called from\n * `_maybeBumpRecoveryProgress` when new content is streamed (real,\n * reconnect-immune forward progress). */\n private async _bumpChatRecoveryProgress(): Promise<void> {\n const current =\n (await this.ctx.storage.get<number>(CHAT_RECOVERY_PROGRESS_KEY)) ?? 0;\n await this.ctx.storage.put(CHAT_RECOVERY_PROGRESS_KEY, current + 1);\n }\n\n /** In-memory wall-clock of the last N9 child-stream progress bump (reset per\n * isolate so the first forwarded chunk after a restart always credits). */\n private _lastAgentToolStreamProgressAt = 0;\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 const now = Date.now();\n if (\n now - this._lastAgentToolStreamProgressAt <\n AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS\n ) {\n return;\n }\n this._lastAgentToolStreamProgressAt = now;\n await this._bumpChatRecoveryProgress();\n }\n\n /** Whether a reconstructed partial carries any settled (provider-accepted)\n * tool result — the completed, often non-idempotent work that a\n * `{ persist: false }` recovery return would silently discard.\n * `convertToModelMessages` treats `output-available` / `output-error` /\n * `output-denied` (or a part carrying `output`/`result`) as settled. */\n private _partialHasSettledToolResults(parts: MessagePart[]): boolean {\n return parts.some((part) => {\n const record = part as Record<string, unknown>;\n const type = typeof record.type === \"string\" ? record.type : \"\";\n if (!(type.startsWith(\"tool-\") || type === \"dynamic-tool\")) return false;\n if (\"output\" in record || \"result\" in record) return true;\n const state = typeof record.state === \"string\" ? record.state : \"\";\n return (\n state === \"output-available\" ||\n state === \"output-error\" ||\n state === \"output-denied\"\n );\n });\n }\n\n /** Sweep recovery incidents that have been inactive past the TTL. */\n private async _sweepStaleChatRecoveryIncidents(now: number): Promise<void> {\n const entries = await this.ctx.storage.list<ChatRecoveryIncident>({\n prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX\n });\n const staleKeys: string[] = [];\n for (const [key, incident] of entries) {\n const lastActive = incident?.lastAttemptAt ?? incident?.firstSeenAt ?? 0;\n if (now - lastActive > CHAT_RECOVERY_INCIDENT_TTL_MS) {\n staleKeys.push(key);\n }\n }\n // Batch deletes — the DO storage KV delete accepts up to 128 keys per call,\n // collapsing N awaited round-trips into ceil(N / 128).\n for (let i = 0; i < staleKeys.length; i += KV_DELETE_MAX_KEYS) {\n await this.ctx.storage.delete(staleKeys.slice(i, i + KV_DELETE_MAX_KEYS));\n }\n }\n\n private async _beginChatRecoveryIncident(input: {\n requestId: string;\n recoveryRootRequestId?: string | null;\n latestUserMessageId?: string | null;\n targetAssistantId?: 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 const config = this._resolveChatRecoveryConfig();\n const incidentId = this._chatRecoveryIncidentId(input);\n const key = this._chatRecoveryIncidentKey(incidentId);\n const now = input.nowMs ?? Date.now();\n await this._sweepStaleChatRecoveryIncidents(now);\n const existing = await this.ctx.storage.get<ChatRecoveryIncident>(key);\n\n // Forward-progress detection. A mid-turn deploy resets the Durable Object\n // (\"code was updated\"); the interrupted continuation is re-detected on the\n // next wake. A turn that followed real progress (more durably-produced\n // content than the last attempt saw) is environmental churn, not a poison\n // turn.\n const prevProgress = existing?.progress ?? 0;\n const currentProgress = await this._chatRecoveryProgressMarker();\n const madeProgress = existing != null && currentProgress > prevProgress;\n\n // A turn parked on a pending CLIENT interaction (an `input-available`\n // client-tool part or an `approval-requested` part — see\n // `hasPendingClientInteraction`) is WAITING ON THE HUMAN, not stuck. It\n // produces no forward progress by design until the client replays the\n // tool-result / approval after reconnect, which drives a fresh continuation\n // independently of recovery. Spending the recovery budget on that wait would\n // seal a perfectly healthy turn whose human is simply slow (e.g. a mid-turn\n // deploy during a confirmation prompt the user takes longer than\n // `noProgressTimeoutMs` to answer). So while a client interaction is pending\n // the turn is budget-free: the no-progress window, attempt cap, work budget,\n // and caller predicate are all suppressed, and the no-progress clock is kept\n // fresh so the turn has a full window once the human finally answers.\n // SERVER-tool orphans are excluded (their `execute` died with the isolate),\n // so they still recover normally. The recovery continuation additionally\n // PARKS (skips, no reschedule) on a stable-state timeout while this holds;\n // see `_chatRecoveryContinue`/`_chatRecoveryRetry`.\n const awaitingClientInteraction = this.hasPendingClientInteraction();\n\n // Recovery budget (#1637, rfc-chat-recovery-work-budget). A turn making\n // genuine forward progress survives unbounded deploy churn — duration is\n // never a bound. The instruments are decoupled by what they catch:\n // • STUCK — no-progress window: `lastProgressAt` resets on every\n // progress-bearing attempt, so a turn that keeps producing content\n // survives churn indefinitely; a stuck turn is sealed after 5 min.\n // • DEBOUNCE — alarms bunched within `ALARM_DEBOUNCE_MS` collapse into one\n // attempt, so a single rollout's reconnect storm isn't N attempts.\n // • ALARM-LOOP — the attempt cap (resets on progress) catches a tight\n // no-progress alarm loop.\n // • RUNAWAY — the work budget seals a loop that keeps emitting content but\n // never converges. Keyed to WORK done (produced content/tool units since\n // the incident opened), not wall-clock, because a healthy long turn and a\n // runaway differ by bounded work, not duration. Defaults to no cap.\n // • CALLER — `shouldKeepRecovering` lets the integrator express a\n // token/cost/step budget the SDK should not hardcode.\n const lastProgressAt =\n madeProgress || awaitingClientInteraction\n ? now\n : (existing?.lastProgressAt ?? existing?.firstSeenAt ?? now);\n const noProgressExceeded =\n existing != null &&\n !awaitingClientInteraction &&\n now - lastProgressAt > config.noProgressTimeoutMs;\n // Reuse the durable progress counter as a work meter. Baseline is captured\n // when the incident opens; `work` is what the turn produced since.\n const workBaseline = existing?.workBaseline ?? currentProgress;\n const progress = Math.max(prevProgress, currentProgress);\n const work = progress - workBaseline;\n const workBudgetExceeded =\n existing != null &&\n Number.isFinite(config.maxRecoveryWork) &&\n work > config.maxRecoveryWork;\n const debounced =\n existing != null &&\n !madeProgress &&\n now - existing.lastAttemptAt < CHAT_RECOVERY_ALARM_DEBOUNCE_MS;\n\n const attempt = madeProgress\n ? 1\n : debounced\n ? (existing?.attempt ?? 1)\n : (existing?.attempt ?? 0) + 1;\n\n // Consult the caller predicate only when no hard bound has already sealed\n // the incident — a buggy/expensive hook must not run after we've decided,\n // and a throwing hook must not wedge the turn (log and treat as \"continue\").\n let abortedByCaller = false;\n if (\n existing != null &&\n !awaitingClientInteraction &&\n config.shouldKeepRecovering &&\n !noProgressExceeded &&\n !workBudgetExceeded &&\n attempt <= config.maxAttempts\n ) {\n try {\n const decision = await config.shouldKeepRecovering({\n incidentId,\n requestId: input.requestId,\n recoveryRootRequestId: input.recoveryRootRequestId ?? input.requestId,\n attempt,\n maxAttempts: config.maxAttempts,\n recoveryKind: input.recoveryKind,\n work,\n ageMs: now - (existing.firstSeenAt ?? now)\n });\n abortedByCaller = decision === false;\n } catch (error) {\n console.error(\n \"[AIChatAgent] chatRecovery shouldKeepRecovering hook threw\",\n error\n );\n }\n }\n\n const exhausted =\n !awaitingClientInteraction &&\n (noProgressExceeded ||\n workBudgetExceeded ||\n abortedByCaller ||\n attempt > config.maxAttempts);\n const incident: ChatRecoveryIncident = {\n incidentId,\n requestId: input.requestId,\n recoveryRootRequestId: input.recoveryRootRequestId ?? input.requestId,\n recoveryKind: input.recoveryKind,\n attempt,\n maxAttempts: config.maxAttempts,\n status: exhausted ? \"exhausted\" : \"attempting\",\n firstSeenAt: existing?.firstSeenAt ?? now,\n lastAttemptAt: now,\n lastProgressAt,\n progress,\n workBaseline,\n ...(exhausted\n ? {\n reason: workBudgetExceeded\n ? \"work_budget_exceeded\"\n : noProgressExceeded\n ? \"no_progress_timeout\"\n : abortedByCaller\n ? \"recovery_aborted\"\n : \"max_attempts_exceeded\"\n }\n : {})\n };\n await this.ctx.storage.put(key, incident);\n\n if (!existing) {\n this._emit(\"chat:recovery:detected\", {\n incidentId,\n requestId: input.requestId,\n attempt,\n maxAttempts: config.maxAttempts,\n recoveryKind: input.recoveryKind\n });\n }\n this._emit(\"chat:recovery:attempt\", {\n incidentId,\n requestId: input.requestId,\n attempt,\n maxAttempts: config.maxAttempts,\n recoveryKind: input.recoveryKind\n });\n\n return { incident, config, exhausted };\n }\n\n private async _updateChatRecoveryIncident(\n incidentId: string | undefined,\n status: ChatRecoveryIncident[\"status\"],\n reason?: string\n ): Promise<void> {\n if (!incidentId) return;\n const key = this._chatRecoveryIncidentKey(incidentId);\n const incident = await this.ctx.storage.get<ChatRecoveryIncident>(key);\n if (!incident) return;\n // A completed recovery is terminal and will not be retried, so drop the\n // record instead of leaving it in storage forever. Non-completed states\n // (scheduled/skipped/failed) are retained so the attempt budget survives\n // across restarts; the TTL sweep eventually reclaims abandoned ones.\n if (status === \"completed\") {\n await this.ctx.storage.delete(key);\n } else {\n const updated: ChatRecoveryIncident = {\n ...incident,\n status,\n ...(reason ? { reason } : {})\n };\n await this.ctx.storage.put(key, updated);\n }\n const eventType =\n status === \"completed\"\n ? \"chat:recovery:completed\"\n : status === \"skipped\"\n ? \"chat:recovery:skipped\"\n : status === \"failed\"\n ? \"chat:recovery:failed\"\n : undefined;\n if (eventType) {\n this._emit(eventType, {\n incidentId,\n requestId: incident.requestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind: incident.recoveryKind,\n ...(reason ? { reason } : {})\n });\n }\n\n // Live \"recovering…\" status (#1620): a scheduled continuation/retry means\n // recovery is in progress; a terminal incident state resolves it.\n if (status === \"scheduled\") {\n await this._setChatRecovering(\n true,\n incident.recoveryRootRequestId ?? incident.requestId\n );\n } else if (\n status === \"completed\" ||\n status === \"skipped\" ||\n status === \"failed\"\n ) {\n await this._setChatRecovering(false);\n }\n }\n\n private async _exhaustChatRecovery(\n incident: ChatRecoveryIncident,\n config: ResolvedChatRecoveryConfig,\n partial: { text: string; parts: MessagePart[] },\n streamId: string,\n createdAt: number\n ): Promise<void> {\n const ctx: ChatRecoveryExhaustedContext = {\n incidentId: incident.incidentId,\n requestId: incident.requestId,\n recoveryRootRequestId:\n incident.recoveryRootRequestId ?? incident.requestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind: incident.recoveryKind,\n streamId,\n createdAt,\n partialText: partial.text,\n partialParts: partial.parts,\n reason: incident.reason ?? \"max_attempts_exceeded\",\n terminalMessage: config.terminalMessage\n };\n this._emit(\"chat:recovery:exhausted\", ctx);\n // A throwing onExhausted hook must not prevent the terminal UX from being\n // delivered, otherwise the turn wedges with no user-visible resolution.\n try {\n await config.onExhausted?.(ctx);\n } catch (error) {\n console.error(\"[AIChatAgent] chatRecovery onExhausted hook threw\", error);\n }\n // Persist the terminal outcome BEFORE broadcasting it (#1645): the\n // broadcast is transient, so a client disconnected at this moment (a\n // deploy/reconnect storm exhausting recovery) would otherwise never learn\n // the turn failed. The record is replayed on the next reconnect via the\n // resume handshake (`_replayTerminalOnResume`).\n await this._recordChatTerminal(incident.requestId, config.terminalMessage);\n this._broadcastChatMessage({\n body: config.terminalMessage,\n done: true,\n error: true,\n id: incident.requestId,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE\n });\n // Exhaustion resolves recovery — clear the \"recovering…\" status (#1620).\n await this._setChatRecovering(false);\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 this.ctx.storage.put(CHAT_LAST_TERMINAL_KEY, { 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 this.ctx.storage.delete(CHAT_LAST_TERMINAL_KEY);\n }\n\n private async _pendingChatTerminal(): Promise<{\n requestId: string;\n body: string;\n } | null> {\n return (\n (await this.ctx.storage.get<{ requestId: string; body: string }>(\n CHAT_LAST_TERMINAL_KEY\n )) ?? null\n );\n }\n\n /**\n * Replay a pending terminal outcome (#1645) over the resume handshake so a\n * reconnecting client surfaces it exactly like a live exhaustion. The bare\n * terminal frame is dropped by the client unless it arrives on a resumed\n * stream — the only path that reaches the transport's stream reader and\n * becomes `useChat.error` — so we drive `STREAM_RESUMING` here and deliver\n * the error frame once the client ACKs (see `_replayTerminalOnAck`).\n * Returns true if a terminal was pending (and `STREAM_RESUMING` was sent).\n */\n private async _replayTerminalOnResume(\n connection: Connection\n ): Promise<boolean> {\n const pending = await this._pendingChatTerminal();\n if (!pending) return false;\n sendIfOpen(\n connection,\n JSON.stringify({\n type: MessageType.CF_AGENT_STREAM_RESUMING,\n id: pending.requestId\n })\n );\n return true;\n }\n\n /**\n * Deliver the pending terminal error frame on the resumed stream the client\n * ACKed (#1645). The record is retained (not cleared) so concurrent\n * reconnects (e.g. multiple tabs) each learn the outcome; it is cleared when\n * a later turn supersedes it.\n */\n private async _replayTerminalOnAck(\n connection: Connection,\n requestId: string\n ): Promise<boolean> {\n const pending = await this._pendingChatTerminal();\n if (!pending || pending.requestId !== requestId) return false;\n // Replay any partial content the errored stream produced before the\n // error, so the reconnecting client observes the same sequence a live\n // client did — content chunks, then the terminal error (#1575). If the\n // connection drops mid-replay, skip the terminal frame; the record is\n // retained, so the next reconnect retries the whole sequence.\n if (\n !this._resumableStream.replayErroredChunksByRequestId(\n connection,\n pending.requestId\n )\n ) {\n return true;\n }\n sendIfOpen(\n connection,\n JSON.stringify({\n body: pending.body,\n done: true,\n error: true,\n id: pending.requestId,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE\n })\n );\n return true;\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 * NOTE: the live \"recovering…\" signal is still not replayed on connect — only\n * the terminal outcome is (#1645, via the resume handshake).\n */\n private async _setChatRecovering(\n active: boolean,\n requestId?: string\n ): Promise<void> {\n const existing = await this.ctx.storage.get<{\n requestId?: string;\n at?: number;\n }>(CHAT_RECOVERING_KEY);\n // A flag older than the TTL is stale: the owning incident was abandoned\n // without a terminal (e.g. the DO went idle before recovery could resolve).\n // Treat it as not-recovering so it can't suppress a genuinely-new recovering\n // signal.\n const activeExisting =\n existing && Date.now() - (existing.at ?? 0) < CHAT_RECOVERING_FLAG_TTL_MS;\n if (active) {\n if (activeExisting) return; // already recovering — idempotent, no re-broadcast\n await this.ctx.storage.put(CHAT_RECOVERING_KEY, {\n ...(requestId ? { requestId } : {}),\n at: Date.now()\n });\n } else {\n if (!existing) return; // not recovering — nothing to clear\n await this.ctx.storage.delete(CHAT_RECOVERING_KEY);\n requestId = requestId ?? existing.requestId;\n }\n this._broadcastChatMessage({\n type: MessageType.CF_AGENT_CHAT_RECOVERING,\n recovering: active,\n ...(requestId ? { id: requestId } : {})\n });\n }\n\n protected override async _handleInternalFiberRecovery(\n ctx: FiberRecoveryContext\n ): Promise<boolean> {\n const chatPrefix =\n (this.constructor as typeof AIChatAgent).CHAT_FIBER_NAME + \":\";\n if (!ctx.name.startsWith(chatPrefix)) {\n return false;\n }\n\n const requestId = ctx.name.slice(chatPrefix.length);\n const { snapshot: recoverySnapshot, user: recoveryData } =\n unwrapChatFiberSnapshot<\"ai-chat-turn\">(\n \"__cfAIChatFiberSnapshot\",\n ctx.snapshot,\n \"ai-chat-turn\"\n );\n\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\n const partial = streamId\n ? this._getPartialStreamText(streamId)\n : { text: \"\", parts: [] as MessagePart[] };\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.\n const streamStillActive =\n streamId &&\n this._resumableStream.hasActiveStream() &&\n this._resumableStream.activeStreamId === streamId;\n\n const shouldRetryPreStream = this._shouldRetryRecoveredPreStreamTurn(\n recoverySnapshot,\n streamId ?? \"\",\n partial\n );\n // A new turn whose stream produced no assistant partial at all (interrupted\n // before the first chunk materialized) will be re-run fresh rather than\n // continued (#1691) — and that is knowable *before* `onChatRecovery`,\n // because an empty partial persists nothing and leaves the conversation\n // leaf at the user message regardless of what the hook returns. Report it\n // as \"retry\" so the hook and the incident match the action that follows.\n // The sibling `persist: false` case (a NON-empty partial the hook chooses\n // to discard) only becomes a retry based on the hook's own return value, so\n // it cannot be pre-detected here — the hook still sees \"continue\" there and\n // only the `chat:recovery:scheduled` event reflects the final \"retry\".\n const preStreamLeaf =\n this.messages.length > 0\n ? this.messages[this.messages.length - 1]\n : undefined;\n const emptyPartialNewTurn =\n !!streamId &&\n recoverySnapshot?.continuation === false &&\n !!recoverySnapshot.latestUserMessageId &&\n partial.text === \"\" &&\n partial.parts.length === 0 &&\n preStreamLeaf?.role === \"user\" &&\n preStreamLeaf.id === recoverySnapshot.latestUserMessageId;\n const recoveryKind: ChatRecoveryKind =\n shouldRetryPreStream || emptyPartialNewTurn ? \"retry\" : \"continue\";\n const recoveryRootRequestId =\n recoverySnapshot?.recoveryRootRequestId ?? requestId;\n const { incident, config, exhausted } =\n await this._beginChatRecoveryIncident({\n requestId,\n recoveryRootRequestId,\n latestUserMessageId: recoverySnapshot?.latestUserMessageId,\n recoveryKind\n });\n\n if (exhausted) {\n // Preserve the settled partial before sealing the turn. Exhaustion is\n // decided BEFORE `onChatRecovery` is consulted, so without this the\n // settled (often non-idempotent) tool results the turn already produced\n // are discarded and the model re-runs them on the next message (#1631).\n if (streamStillActive) {\n await this._persistOrphanedStream(streamId);\n }\n await this._exhaustChatRecovery(\n incident,\n config,\n partial,\n streamId,\n ctx.createdAt\n );\n return true;\n }\n\n // Any throw after the incident is opened (user `onChatRecovery`, orphan\n // persistence, scheduling) must flip the incident to a terminal `failed`\n // state and emit, otherwise it leaks in `attempting` and is never\n // observable as a stuck turn.\n try {\n const options =\n (await this.onChatRecovery({\n incidentId: incident.incidentId,\n recoveryRootRequestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind,\n streamId: streamId ?? \"\",\n requestId,\n partialText: partial.text,\n partialParts: partial.parts,\n recoveryData,\n messages: [...this.messages],\n lastBody: recoverySnapshot?.lastBody ?? this._lastBody,\n lastClientTools:\n recoverySnapshot?.lastClientTools ?? this._lastClientTools,\n createdAt: ctx.createdAt\n })) ?? {};\n\n // Settled work — completed, often non-idempotent tool results — is NEVER\n // dropped by recovery. `persist: false` only suppresses persistence of a\n // partial that has nothing settled to lose; a partial carrying settled\n // tool results is persisted regardless, so an app can never accidentally\n // discard completed work (and never needs `{ persist: true }` just to be\n // safe). A safe default beats a warning about an unsafe one (#1631).\n if (\n streamStillActive &&\n (options.persist !== false ||\n this._partialHasSettledToolResults(partial.parts))\n ) {\n await this._persistOrphanedStream(streamId);\n }\n\n if (streamStillActive) {\n this._resumableStream.complete(streamId);\n void this._ensureStreamCleanupScheduled();\n }\n\n // A NEW turn (not a continuation) that produced no persisted assistant\n // partial — interrupted before any part materialized, or `persist: false`\n // discarded it — leaves the conversation leaf at the user message.\n // Continuing here would clone the PREVIOUS assistant turn (the most recent\n // assistant message, found by walking back past the trailing user\n // message) and merge this turn into it (#1691). Re-run the user turn fresh\n // instead, so it becomes its own message. Checked AFTER the persist step,\n // so a partial that WAS persisted (now the assistant leaf) still continues.\n const leaf =\n this.messages.length > 0\n ? this.messages[this.messages.length - 1]\n : undefined;\n const lostPartialUserId =\n recoverySnapshot?.continuation === false &&\n recoverySnapshot.latestUserMessageId &&\n leaf?.role === \"user\" &&\n leaf.id === recoverySnapshot.latestUserMessageId\n ? recoverySnapshot.latestUserMessageId\n : undefined;\n\n const targetId =\n shouldRetryPreStream || lostPartialUserId !== undefined\n ? undefined\n : this._findLastAssistantMessage()?.id;\n\n if (shouldRetryPreStream && options.continue !== false) {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"scheduled\"\n );\n this._emit(\"chat:recovery:scheduled\", {\n incidentId: incident.incidentId,\n requestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind\n });\n await this.schedule(\n 0,\n \"_chatRecoveryRetry\",\n {\n targetUserId: recoverySnapshot.latestUserMessageId,\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n lastBody: recoverySnapshot.lastBody ?? null,\n lastClientTools: recoverySnapshot.lastClientTools ?? null\n },\n { idempotent: true }\n );\n } else if (\n lostPartialUserId !== undefined &&\n options.continue !== false\n ) {\n // Re-run the orphaned new turn fresh instead of continuing (and\n // merging into) the previous assistant message.\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"scheduled\"\n );\n this._emit(\"chat:recovery:scheduled\", {\n incidentId: incident.incidentId,\n requestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind: \"retry\"\n });\n await this.schedule(\n 0,\n \"_chatRecoveryRetry\",\n {\n targetUserId: lostPartialUserId,\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n lastBody: recoverySnapshot?.lastBody ?? null,\n lastClientTools: recoverySnapshot?.lastClientTools ?? null\n },\n { idempotent: true }\n );\n } else if (options.continue !== false) {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"scheduled\"\n );\n this._emit(\"chat:recovery:scheduled\", {\n incidentId: incident.incidentId,\n requestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind\n });\n await this.schedule(\n 0,\n \"_chatRecoveryContinue\",\n {\n ...(targetId ? { targetAssistantId: targetId } : {}),\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n ...(recoverySnapshot\n ? {\n lastBody: recoverySnapshot.lastBody ?? null,\n lastClientTools: recoverySnapshot.lastClientTools ?? null\n }\n : {})\n },\n { idempotent: true }\n );\n } else {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"skipped\",\n \"continue_disabled\"\n );\n }\n\n return true;\n } catch (error) {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"failed\",\n error instanceof Error ? error.message : String(error)\n );\n throw error;\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 });\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 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 } 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 * 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: \"_chatRecoveryContinue\" | \"_chatRecoveryRetry\",\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined,\n maxAttempts: number\n ): Promise<boolean> {\n const incidentKey = data?.incidentId\n ? this._chatRecoveryIncidentKey(data.incidentId)\n : null;\n const incident = incidentKey\n ? await this.ctx.storage.get<ChatRecoveryIncident>(incidentKey)\n : null;\n if (!incident || !incidentKey) return false;\n const attempt = incident.attempt ?? 0;\n if (attempt >= (incident.maxAttempts ?? maxAttempts)) return false;\n await this.ctx.storage.put(incidentKey, {\n ...incident,\n attempt: attempt + 1,\n status: \"scheduled\",\n lastAttemptAt: Date.now(),\n reason: \"stable_timeout_retry\"\n });\n // Must NOT be idempotent: this runs inside the currently-executing one-shot\n // schedule row (deleted by `alarm()` only after we return). An idempotent\n // reschedule would dedup onto that row and be deleted with it — the retry\n // would never fire. A fresh delayed row survives.\n await this.schedule(\n CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS,\n callback,\n data ?? {},\n { idempotent: false }\n );\n return true;\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 * Resolve the stream id for a recovery turn so the give-up terminalization\n * can surface whatever partial the turn produced. Prefers the durable stream\n * row keyed by the recovery-root request id; falls back to the live active\n * stream. Returns `\"\"` when neither is available.\n */\n private _resolveRecoveryStreamId(requestId: string): string {\n if (requestId) {\n const fromMetadata = this._resumableStream\n .getAllStreamMetadata()\n .find((metadata) => metadata.request_id === requestId)?.id;\n if (fromMetadata) return fromMetadata;\n }\n return this._resumableStream.hasActiveStream()\n ? (this._resumableStream.activeStreamId ?? \"\")\n : \"\";\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 private async _exhaustRecoveryAfterStableTimeout(\n callback: \"_chatRecoveryContinue\" | \"_chatRecoveryRetry\",\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined\n ): Promise<void> {\n const config = this._resolveChatRecoveryConfig();\n const incidentKey = data?.incidentId\n ? this._chatRecoveryIncidentKey(data.incidentId)\n : null;\n let stored: ChatRecoveryIncident | null = null;\n if (incidentKey) {\n try {\n stored =\n (await this.ctx.storage.get<ChatRecoveryIncident>(incidentKey)) ??\n null;\n } catch (readError) {\n console.error(\n \"[AIChatAgent] failed to read recovery incident during give-up; synthesizing\",\n readError\n );\n }\n }\n\n // Re-entry guard (see method doc): a sealed incident means terminalization\n // already happened, so a duplicate stale alarm must not re-fire\n // `onExhausted` / re-broadcast the banner. This is ai-chat's ONLY guard.\n if (stored?.status === \"exhausted\") return;\n\n const rootRequestId =\n data?.originalRequestId ??\n this._activeChatRecoveryRootRequestId ??\n stored?.recoveryRootRequestId ??\n stored?.requestId ??\n \"\";\n\n // `stable_timeout` distinguishes a give-up driven by repeated stable-state\n // timeouts from the generic max-attempts / no-progress exhaustion reasons.\n const incident: ChatRecoveryIncident = stored\n ? { ...stored, status: \"exhausted\", reason: \"stable_timeout\" }\n : {\n // Silent-drop guard: the incident record is gone (no `incidentId`, or\n // it was swept/deleted before this stale alarm fired). Synthesize a\n // minimal incident so the turn STILL terminalizes through\n // `onExhausted` instead of being dropped with no terminal UX.\n incidentId: data?.incidentId ?? crypto.randomUUID(),\n requestId: rootRequestId,\n recoveryRootRequestId: rootRequestId,\n recoveryKind:\n callback === \"_chatRecoveryRetry\" ? \"retry\" : \"continue\",\n attempt: config.maxAttempts,\n maxAttempts: config.maxAttempts,\n status: \"exhausted\",\n firstSeenAt: Date.now(),\n lastAttemptAt: Date.now(),\n reason: \"stable_timeout\"\n };\n\n const streamId = this._resolveRecoveryStreamId(\n incident.recoveryRootRequestId ?? incident.requestId\n );\n const partial = streamId\n ? this._getPartialStreamText(streamId)\n : { text: \"\", parts: [] as MessagePart[] };\n\n // Terminalize BEFORE sealing the incident. The terminal write inside\n // `_exhaustChatRecovery` (`_recordChatTerminal`) hits storage and can\n // reject with a platform transient in exactly the window a give-up tends\n // to run in (#1730: deploy reset / storage outage). Letting that throw\n // propagate is deliberate: `Agent._executeScheduleCallback` defers the\n // one-shot row on a platform transient, so the WHOLE give-up re-runs on a\n // healthy isolate instead of half-sealing. Sealing first would arm the\n // re-entry guard above and turn that re-run into a no-op — dropping the\n // durable terminal record (#1645). The re-run is idempotent\n // (`_recordChatTerminal` overwrites the same key); `onExhausted` + the\n // banner may fire again — the documented at-least-once edge.\n await this._exhaustChatRecovery(\n incident,\n config,\n partial,\n streamId,\n incident.firstSeenAt\n );\n\n // Persist the sealed incident (retained for inspection / TTL sweep) so the\n // re-entry guard above sees `exhausted` if a duplicate stale alarm fires.\n // Best-effort: terminalization already fully succeeded, so a failed seal\n // write costs at most a re-delivered banner on a duplicate alarm.\n if (incidentKey) {\n try {\n await this.ctx.storage.put(incidentKey, incident);\n } catch (writeError) {\n console.error(\n \"[AIChatAgent] failed to persist sealed recovery incident during give-up\",\n writeError\n );\n }\n }\n }\n\n private _shouldRetryRecoveredPreStreamTurn(\n snapshot: ChatFiberSnapshot<\"ai-chat-turn\"> | null,\n streamId: string,\n partial: { text: string; parts: MessagePart[] }\n ): snapshot is ChatFiberSnapshot<\"ai-chat-turn\"> & {\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 });\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 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 } 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 } {\n const chunks = this._resumableStream.getStreamChunks(streamId);\n const parts: MessagePart[] = [];\n\n for (const chunk of chunks) {\n try {\n const data = JSON.parse(chunk.body);\n applyChunkToParts(parts, data);\n } catch {\n // Skip malformed chunk bodies\n }\n }\n\n const text = parts\n .filter(\n (p): p is MessagePart & { type: \"text\"; text: string } =>\n p.type === \"text\" && \"text\" in p\n )\n .map((p) => p.text)\n .join(\"\");\n\n return { text, parts };\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 let json = JSON.stringify(message);\n let size = chatByteLength(json);\n if (size <= ROW_MAX_BYTES) return message;\n\n if (message.role !== \"assistant\") {\n // Non-assistant messages (user/system) are harder to compact safely.\n // Truncate the entire message JSON as a last resort.\n console.warn(\n `[AIChatAgent] Non-assistant message ${message.id} is ${size} bytes, ` +\n `exceeds row limit. Truncating text parts.`\n );\n return this._truncateTextParts(message);\n }\n\n console.warn(\n `[AIChatAgent] Message ${message.id} is ${size} bytes, ` +\n `compacting tool outputs to fit SQLite row limit`\n );\n\n // Pass 1: compact tool outputs\n const compactedToolCallIds: string[] = [];\n const compactedParts = message.parts.map((part) => {\n if (\n \"output\" in part &&\n \"toolCallId\" in part &&\n \"state\" in part &&\n part.state === \"output-available\"\n ) {\n const outputJson = JSON.stringify((part as { output: unknown }).output);\n if (outputJson.length > 1000) {\n compactedToolCallIds.push(part.toolCallId as string);\n return {\n ...part,\n output:\n \"This tool output was too large to persist in storage \" +\n `(${outputJson.length} bytes). ` +\n \"If the user asks about this data, suggest re-running the tool. \" +\n `Preview: ${outputJson.slice(0, 500)}...`\n };\n }\n }\n return part;\n }) as UIMessage[\"parts\"];\n\n let result: UIMessage = {\n ...message,\n parts: compactedParts\n };\n\n if (compactedToolCallIds.length > 0) {\n result.metadata = {\n ...(result.metadata ?? {}),\n compactedToolOutputs: compactedToolCallIds\n };\n }\n\n // Check if tool compaction was enough\n json = JSON.stringify(result);\n size = chatByteLength(json);\n if (size <= ROW_MAX_BYTES) return result;\n\n // Pass 2: truncate text parts\n console.warn(\n `[AIChatAgent] Message ${message.id} still ${size} bytes after tool compaction, truncating text parts`\n );\n return this._truncateTextParts(result);\n }\n\n /**\n * Truncates text parts in a message to fit within the row size limit.\n * Truncates from the first text part forward, keeping the last text part\n * as intact as possible (it is usually the most relevant).\n */\n private _truncateTextParts(message: UIMessage): UIMessage {\n const compactedTextPartIndices: number[] = [];\n const parts = [...message.parts];\n\n // Truncate text parts from oldest to newest until we fit\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n if (part.type === \"text\" && \"text\" in part) {\n const text = (part as { text: string }).text;\n if (text.length > 1000) {\n compactedTextPartIndices.push(i);\n parts[i] = {\n ...part,\n text:\n `[Text truncated for storage (${text.length} chars). ` +\n `First 500 chars: ${text.slice(0, 500)}...]`\n } as UIMessage[\"parts\"][number];\n\n // Check if we fit now\n const candidate = { ...message, parts };\n if (chatByteLength(JSON.stringify(candidate)) <= ROW_MAX_BYTES) {\n break;\n }\n }\n }\n }\n\n const result: UIMessage = { ...message, parts };\n if (compactedTextPartIndices.length > 0) {\n result.metadata = {\n ...(result.metadata ?? {}),\n compactedTextParts: compactedTextPartIndices\n };\n }\n return result;\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 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 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 return this._findAndUpdateToolPart(\n toolCallId,\n \"_applyToolApproval\",\n [\"input-available\", \"approval-requested\"],\n (part) => ({\n ...part,\n state: approved ? \"approval-responded\" : \"output-denied\",\n // Merge with existing approval data to preserve the id field.\n // convertToModelMessages needs approval.id to produce a valid\n // tool-approval-request content part with approvalId.\n approval: {\n ...(part.approval as Record<string, unknown> | undefined),\n approved\n }\n })\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\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 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 } 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 (streamCompleted.value && streamResult.status !== \"error\") {\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(updatedMessages, excludeBroadcastIds);\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 && { error: streamResult.error })\n });\n return streamResult;\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":";;;;;;AAoJA,MAAM,oCAAoC;AAM1C,MAAM,6BAA6B;AAKnC,MAAM,qCAAqC;AAK3C,MAAM,iCAAiC,OAAO;AAC9C,MAAM,0CAA0C;AAShD,MAAM,4CAA4C;AAGlD,MAAM,2CAA2C;AACjD,MAAM,yCACJ;AASF,MAAM,sBAAsB;AAO5B,MAAM,yBAAyB;AAG/B,MAAM,gCAAgC,OAAU;AAGhD,MAAM,qBAAqB;AAM3B,MAAM,+CAA+C,MAAS;AAI9D,MAAM,kCAAkC,KAAK;AAO7C,MAAM,8BAA8B,MAAU;AAQ9C,MAAM,8CAA8C;AAUpD,MAAM,+BAA+B;AAOrC,SAAS,WAAW,YAAwB,SAA0B;CACpE,IAAI;EACF,WAAW,KAAK,OAAO;EACvB,OAAO;CACT,SAAS,OAAO;EACd,IAAI,2BAA2B,KAAK,GAAG,OAAO;EA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