@cloudflare/ai-chat 0.4.5 → 0.5.0
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/README.md +12 -12
- package/dist/index.d.ts +48 -75
- package/dist/index.js +57 -34
- package/dist/index.js.map +1 -1
- package/dist/react.d.ts +1 -1
- package/dist/react.js +69 -33
- package/dist/react.js.map +1 -1
- package/dist/types.d.ts +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["agentContext","chatByteLength"],"sources":["../src/message-reconciler.ts","../src/index.ts"],"sourcesContent":["/**\n * Message reconciliation — pure functions for aligning client messages\n * with server state during persistence.\n *\n * Three strategies applied in order:\n * 1. Merge server-known tool outputs into stale client messages\n * 2. Reconcile assistant IDs (exact match → content-key → toolCallId)\n * 3. Per-message toolCallId dedup for persistence\n */\n\nimport type { UIMessage } from \"ai\";\n\ntype ChatMessage = UIMessage;\n\n/**\n * Reconcile incoming client messages against server state.\n *\n * 1. Merges server-known tool outputs into incoming messages that still\n * show stale states (input-available, approval-requested, approval-responded)\n * 2. Reconciles assistant IDs: exact match → content-key match → toolCallId match\n *\n * @param incoming - Messages from the client\n * @param serverMessages - Current server-side messages (source of truth)\n * @param sanitizeForContentKey - Function to sanitize a message before computing\n * its content key (typically strips ephemeral provider metadata)\n * @returns Reconciled messages ready for persistence\n */\nexport function reconcileMessages(\n incoming: ChatMessage[],\n serverMessages: ChatMessage[],\n sanitizeForContentKey?: (message: ChatMessage) => ChatMessage\n): ChatMessage[] {\n const withMergedToolOutputs = mergeServerToolOutputs(\n incoming,\n serverMessages\n );\n return reconcileAssistantIds(\n withMergedToolOutputs,\n serverMessages,\n sanitizeForContentKey\n );\n}\n\n/**\n * For a single message, resolve its ID by matching toolCallId against server state.\n * Prevents duplicate DB rows when client IDs differ from server IDs.\n * Tool call IDs are unique per conversation, so matching is safe regardless of state.\n */\nexport function resolveToolMergeId(\n message: ChatMessage,\n serverMessages: ChatMessage[]\n): ChatMessage {\n if (message.role !== \"assistant\") {\n return message;\n }\n\n for (const part of message.parts) {\n if (\"toolCallId\" in part && part.toolCallId) {\n const toolCallId = part.toolCallId as string;\n const existing = findMessageByToolCallId(serverMessages, toolCallId);\n if (existing && existing.id !== message.id) {\n return { ...message, id: existing.id };\n }\n }\n }\n\n return message;\n}\n\n/**\n * Content key for assistant messages used for dedup of identical short replies.\n * Returns JSON of sanitized parts, or undefined for non-assistant messages.\n */\nexport function assistantContentKey(\n message: ChatMessage,\n sanitize?: (message: ChatMessage) => ChatMessage\n): string | undefined {\n if (message.role !== \"assistant\") {\n return undefined;\n }\n const sanitized = sanitize ? sanitize(message) : message;\n return JSON.stringify(sanitized.parts);\n}\n\nfunction mergeServerToolOutputs(\n incoming: ChatMessage[],\n serverMessages: ChatMessage[]\n): ChatMessage[] {\n const serverToolOutputs = new Map<string, unknown>();\n for (const msg of serverMessages) {\n if (msg.role !== \"assistant\") continue;\n for (const part of msg.parts) {\n if (\n \"toolCallId\" in part &&\n \"state\" in part &&\n part.state === \"output-available\" &&\n \"output\" in part\n ) {\n serverToolOutputs.set(\n part.toolCallId as string,\n (part as { output: unknown }).output\n );\n }\n }\n }\n\n if (serverToolOutputs.size === 0) return incoming;\n\n return incoming.map((msg) => {\n if (msg.role !== \"assistant\") return msg;\n\n let hasChanges = false;\n const updatedParts = msg.parts.map((part) => {\n if (\n \"toolCallId\" in part &&\n \"state\" in part &&\n (part.state === \"input-available\" ||\n part.state === \"approval-requested\" ||\n part.state === \"approval-responded\") &&\n serverToolOutputs.has(part.toolCallId as string)\n ) {\n hasChanges = true;\n return {\n ...part,\n state: \"output-available\" as const,\n output: serverToolOutputs.get(part.toolCallId as string)\n };\n }\n return part;\n }) as ChatMessage[\"parts\"];\n\n return hasChanges ? { ...msg, parts: updatedParts } : msg;\n });\n}\n\nfunction reconcileAssistantIds(\n incoming: ChatMessage[],\n serverMessages: ChatMessage[],\n sanitize?: (message: ChatMessage) => ChatMessage\n): ChatMessage[] {\n if (serverMessages.length === 0) return incoming;\n\n const claimedServerIndices = new Set<number>();\n const exactMatchMap = new Map<number, number>();\n\n for (let i = 0; i < incoming.length; i++) {\n const serverIdx = serverMessages.findIndex(\n (sm, si) => !claimedServerIndices.has(si) && sm.id === incoming[i].id\n );\n if (serverIdx !== -1) {\n claimedServerIndices.add(serverIdx);\n exactMatchMap.set(i, serverIdx);\n }\n }\n\n return incoming.map((incomingMessage, incomingIdx) => {\n if (exactMatchMap.has(incomingIdx)) {\n return incomingMessage;\n }\n\n if (\n incomingMessage.role !== \"assistant\" ||\n hasToolCallPart(incomingMessage)\n ) {\n return incomingMessage;\n }\n\n const incomingKey = assistantContentKey(incomingMessage, sanitize);\n if (!incomingKey) {\n return incomingMessage;\n }\n\n for (let i = 0; i < serverMessages.length; i++) {\n if (claimedServerIndices.has(i)) continue;\n\n const serverMessage = serverMessages[i];\n if (\n serverMessage.role !== \"assistant\" ||\n hasToolCallPart(serverMessage)\n ) {\n continue;\n }\n\n if (assistantContentKey(serverMessage, sanitize) === incomingKey) {\n claimedServerIndices.add(i);\n return { ...incomingMessage, id: serverMessage.id };\n }\n }\n\n return incomingMessage;\n });\n}\n\nfunction hasToolCallPart(message: ChatMessage): boolean {\n return message.parts.some((part) => \"toolCallId\" in part);\n}\n\nfunction findMessageByToolCallId(\n messages: ChatMessage[],\n toolCallId: string\n): ChatMessage | undefined {\n for (const msg of messages) {\n if (msg.role !== \"assistant\") continue;\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","import type {\n UIMessage as ChatMessage,\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 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 { reconcileMessages, resolveToolMergeId } from \"./message-reconciler\";\nimport {\n applyChunkToParts,\n sanitizeMessage,\n byteLength as chatByteLength,\n ROW_MAX_BYTES,\n TurnQueue,\n type TurnResult,\n type MessagePart\n} from \"agents/chat\";\nimport { ResumableStream } from \"agents/chat\";\nimport {\n createToolsFromClientSchemas,\n ContinuationState,\n AbortRegistry,\n type ContinuationConnection,\n type ClientToolSchema\n} from \"agents/chat\";\nimport { nanoid } from \"nanoid\";\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 ChatMessage {\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\n/**\n * Context passed to `onChatRecovery` when an interrupted chat stream\n * is detected after DO restart.\n */\nexport type ChatRecoveryContext = {\n /** Stream ID from the interrupted stream. */\n streamId: string;\n /** Request ID from the interrupted stream. */\n requestId: string;\n /** Partial text extracted from stored chunks. */\n partialText: string;\n /** Partial message parts reconstructed from chunks. */\n partialParts: MessagePart[];\n /** Checkpoint data from `this.stash()` during the interrupted stream. */\n recoveryData: unknown | null;\n /** Current persisted messages. */\n messages: ChatMessage[];\n /** Custom body from the last chat request. */\n lastBody?: Record<string, unknown>;\n /** Client tool schemas from the last chat request. */\n lastClientTools?: ClientToolSchema[];\n /**\n * Epoch milliseconds when the underlying fiber was started. Compare against\n * `Date.now()` to suppress continuations for turns that have been orphaned\n * too long to safely replay.\n */\n createdAt: number;\n};\n\n/**\n * Options returned from `onChatRecovery` to control recovery behavior.\n */\nexport type ChatRecoveryOptions = {\n /** Save the partial response from stored chunks. Default: true. */\n persist?: boolean;\n /** Schedule a continuation via continueLastTurn(). Default: true. */\n continue?: boolean;\n};\n\nexport type MessageConcurrency =\n | \"queue\"\n | \"latest\"\n | \"merge\"\n | \"drop\"\n | {\n strategy: \"debounce\";\n debounceMs?: number;\n };\n\ntype ChatRequestTrigger = \"submit-message\" | \"regenerate-message\";\n\ntype NormalizedMessageConcurrency =\n | \"queue\"\n | \"latest\"\n | \"merge\"\n | \"drop\"\n | {\n strategy: \"debounce\";\n debounceMs: number;\n };\n\ntype SubmitConcurrencyDecision = {\n action: \"execute\" | \"drop\";\n submitSequence: number | null;\n debounceUntilMs: number | null;\n mergeQueuedMessages: boolean;\n};\n\n/**\n * Result passed to the `onChatResponse` lifecycle hook after a chat turn completes.\n */\nexport type ChatResponseResult = {\n /** The finalized assistant message from this turn. */\n message: ChatMessage;\n /** The request ID associated with this turn. */\n requestId: string;\n /** Whether this turn was a continuation of a previous assistant turn. */\n continuation: boolean;\n /** How the turn ended. */\n status: \"completed\" | \"error\" | \"aborted\";\n /** Error message when `status` is `\"error\"`. */\n error?: 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\n/**\n * Result returned by `saveMessages()`.\n */\nexport type SaveMessagesResult = {\n /** Server-generated request ID for the chat turn. */\n requestId: string;\n /** Whether the turn ran or was skipped (e.g. because the chat was cleared). */\n status: \"completed\" | \"skipped\";\n};\n\nexport { createToolsFromClientSchemas } from \"agents/chat\";\n\nconst decoder = new TextDecoder();\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> extends Agent<Env, State> {\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: ChatMessage | 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 * 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 chatRecovery = false;\n\n /** First queued overlap message index for merge strategy, keyed by epoch. */\n private _mergeQueuedUserStartIndexByEpoch = new Map<number, number>();\n\n /** Monotonic sequence for overlapping submit-message requests. */\n private _submitSequence = 0;\n\n /** Latest overlapping submit-message sequence kept for latest/debounce. */\n private _latestOverlappingSubmitSequence = 0;\n\n /**\n * Tracks requests that have passed concurrency decision but haven't\n * yet been enqueued into `_turnQueue`. Bridges the gap caused by\n * `await persistMessages()` between the decision and the enqueue,\n * preventing a race where a subsequent message sees `queuedCount()=0`\n * and skips concurrency handling.\n */\n private _pendingEnqueueCount = 0;\n\n /** Active debounce timer handle, cleared on resetTurnState. */\n private _activeDebounceTimer: ReturnType<typeof setTimeout> | null = null;\n\n /** Resolve callback for the active debounce promise. */\n private _activeDebounceResolve: (() => void) | null = null;\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();\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 /** Array of chat messages for the current conversation */\n messages: ChatMessage[];\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 // 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 // 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.awaitingConnections.delete(connection.id);\n if (this._continuation.pending?.connectionId === connection.id) {\n this._continuation.pending = null;\n }\n if (this._continuation.activeConnectionId === connection.id) {\n this._continuation.activeConnectionId = null;\n }\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 // 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: ChatMessage[];\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 // 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 this._pendingEnqueueCount++;\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.mergeQueuedMessages) {\n await this._mergeQueuedUserMessages(epoch);\n }\n } finally {\n this._pendingEnqueueCount = Math.max(\n 0,\n this._pendingEnqueueCount - 1\n );\n }\n return this._runExclusiveChatTurn(\n chatMessageId,\n async () => {\n if (\n this._isSupersededSubmit(concurrencyDecision.submitSequence)\n ) {\n this._completeSkippedRequest(connection, chatMessageId);\n return;\n }\n\n if (concurrencyDecision.debounceUntilMs !== null) {\n await this._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._isSupersededSubmit(concurrencyDecision.submitSequence)\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.mergeQueuedMessages) {\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._isSupersededSubmit(concurrencyDecision.submitSequence)\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.runFiber(\n `${(this.constructor as typeof AIChatAgent).CHAT_FIBER_NAME}:${chatMessageId}`,\n async () => {\n await chatTurnBody();\n }\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 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 connection.send(\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 === connection.id\n ) {\n this._continuation.awaitingConnections.set(\n connection.id,\n connection\n );\n } else {\n connection.send(\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 this._persistOrphanedStream(orphanedStreamId);\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._applyToolResult(\n toolCallId,\n toolName,\n output,\n overrideState,\n errorText\n );\n this._pendingInteractionPromise = applyPromise;\n applyPromise\n .finally(() => {\n if (this._pendingInteractionPromise === applyPromise) {\n this._pendingInteractionPromise = null;\n }\n })\n .catch(() => {});\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._applyToolApproval(toolCallId, approved);\n this._pendingInteractionPromise = approvalPromise;\n approvalPromise\n .finally(() => {\n if (this._pendingInteractionPromise === approvalPromise) {\n this._pendingInteractionPromise = null;\n }\n })\n .catch(() => {});\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 _flushAwaitingStreamStartConnections() {\n if (!this._resumableStream.hasActiveStream()) {\n return;\n }\n\n this._continuation.flushAwaitingConnections((c: ContinuationConnection) =>\n this._notifyStreamResuming(c as Connection)\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 * @param connection - The WebSocket connection to notify\n */\n private _notifyStreamResuming(connection: Connection) {\n if (!this._resumableStream.hasActiveStream()) {\n return;\n }\n\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 // Notify client - they will send ACK when ready\n connection.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_STREAM_RESUMING,\n id: this._resumableStream.activeRequestId\n })\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(requestId: string): string {\n const streamId = this._resumableStream.start(requestId);\n if (this._continuation.pending?.requestId === requestId) {\n this._continuation.activatePending();\n this._flushAwaitingStreamStartConnections();\n this._activateDeferredAutoContinuation();\n }\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 }\n\n /** @internal Delegate to _resumableStream */\n protected _storeStreamChunk(streamId: string, body: string) {\n this._resumableStream.storeChunk(streamId, body);\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 this._resumableStream.markError(streamId);\n this._pendingResumeConnections.clear();\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 _persistOrphanedStream(streamId: string) {\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: ChatMessage = {\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 message ID from the \"start\" event if present\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 // Continuation streams have their messageId stripped (#1229) so the\n // start chunk won't contain one. Fall back to the last assistant\n // message — continuations always append to it.\n if (message.id === fallbackId) {\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 // 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 const existing = this.messages[existingIdx];\n message.parts = [...existing.parts, ...message.parts];\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 this.persistMessages(updatedMessages);\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 _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 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(): ChatMessage[] {\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 ChatMessage;\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 ChatMessage => 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 private async waitForIdle(): Promise<void> {\n await this._turnQueue.waitForIdle();\n }\n\n private _normalizeMessageConcurrency(): NormalizedMessageConcurrency {\n if (typeof this.messageConcurrency === \"string\") {\n return this.messageConcurrency;\n }\n\n const debounceMs = this.messageConcurrency.debounceMs;\n\n return {\n strategy: \"debounce\",\n debounceMs:\n typeof debounceMs === \"number\" &&\n Number.isFinite(debounceMs) &&\n debounceMs >= 0\n ? debounceMs\n : AIChatAgent.MESSAGE_DEBOUNCE_MS\n };\n }\n\n private _getSubmitConcurrencyDecision(\n trigger: ChatRequestTrigger\n ): SubmitConcurrencyDecision {\n const queuedTurnsInCurrentEpoch =\n this._turnQueue.queuedCount() + this._pendingEnqueueCount;\n\n if (trigger !== \"submit-message\" || queuedTurnsInCurrentEpoch === 0) {\n return {\n action: \"execute\",\n submitSequence: null,\n debounceUntilMs: null,\n mergeQueuedMessages: false\n };\n }\n\n const concurrency = this._normalizeMessageConcurrency();\n if (concurrency === \"drop\") {\n return {\n action: \"drop\",\n submitSequence: null,\n debounceUntilMs: null,\n mergeQueuedMessages: false\n };\n }\n\n if (concurrency === \"queue\") {\n return {\n action: \"execute\",\n submitSequence: null,\n debounceUntilMs: null,\n mergeQueuedMessages: false\n };\n }\n\n const submitSequence = ++this._submitSequence;\n this._latestOverlappingSubmitSequence = submitSequence;\n\n if (concurrency === \"latest\") {\n return {\n action: \"execute\",\n submitSequence,\n debounceUntilMs: null,\n mergeQueuedMessages: false\n };\n }\n\n if (concurrency === \"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 return {\n action: \"execute\",\n submitSequence,\n debounceUntilMs: null,\n mergeQueuedMessages: true\n };\n }\n\n return {\n action: \"execute\",\n submitSequence,\n debounceUntilMs: Date.now() + concurrency.debounceMs,\n mergeQueuedMessages: false\n };\n }\n\n private _isSupersededSubmit(submitSequence: number | null): boolean {\n return (\n submitSequence !== null &&\n submitSequence < this._latestOverlappingSubmitSequence\n );\n }\n\n private async _waitForTimestamp(timestampMs: number): Promise<void> {\n const remainingMs = timestampMs - Date.now();\n if (remainingMs <= 0) {\n return;\n }\n\n await new Promise<void>((resolve) => {\n this._activeDebounceResolve = resolve;\n this._activeDebounceTimer = setTimeout(() => {\n this._activeDebounceTimer = null;\n this._activeDebounceResolve = null;\n resolve();\n }, remainingMs);\n });\n }\n\n private _cancelActiveDebounce(): void {\n if (this._activeDebounceTimer !== null) {\n clearTimeout(this._activeDebounceTimer);\n this._activeDebounceTimer = null;\n }\n if (this._activeDebounceResolve !== null) {\n this._activeDebounceResolve();\n this._activeDebounceResolve = null;\n }\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): ChatMessage[] | 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: ChatMessage[]): ChatMessage {\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: ChatMessage[\"parts\"],\n nextParts: ChatMessage[\"parts\"]\n ): ChatMessage[\"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: ChatMessage[\"parts\"]\n ): ChatMessage[\"parts\"] {\n return [...parts];\n }\n\n private static _appendMergedText(\n parts: ChatMessage[\"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(): ChatMessage[] {\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 first so hasPendingInteraction() reflects settled\n // message state rather than in-flight streaming state.\n if (\n (await this._awaitWithDeadline(\n this._turnQueue.waitForIdle(),\n deadline\n )) === TIMED_OUT\n ) {\n return false;\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._cancelActiveDebounce();\n this._pendingEnqueueCount = 0;\n this._pendingInteractionPromise = null;\n this._continuation.sendResumeNone();\n this._continuation.clearAll();\n this._pendingChatResponseResults.length = 0;\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: ChatMessage): 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 * 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 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 return true;\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 return true;\n }\n }\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\n ?.connection as Connection | null;\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 await this._reply(requestId, response, [], {\n continuation: true,\n chatMessageId: requestId\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.runFiber(\n `${(this.constructor as typeof AIChatAgent).CHAT_FIBER_NAME}:${requestId}`,\n async () => {\n await autoContinuationBody();\n }\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 private async _runProgrammaticChatTurn(\n requestId: string,\n clientTools?: ClientToolSchema[],\n body?: Record<string, unknown>\n ): Promise<void> {\n this._setRequestContext(clientTools, body);\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 const programmaticBody = async () => {\n try {\n const response = await this.onChatMessage(() => {}, {\n requestId,\n abortSignal,\n clientTools,\n body,\n continuation: false\n });\n\n if (response) {\n await this._reply(requestId, response, [], {\n chatMessageId: requestId\n });\n }\n } finally {\n this._abortRegistry.remove(requestId);\n }\n };\n\n if (this.chatRecovery) {\n await this.runFiber(\n `${(this.constructor as typeof AIChatAgent).CHAT_FIBER_NAME}:${requestId}`,\n async () => {\n await programmaticBody();\n }\n );\n } else {\n await programmaticBody();\n }\n }\n );\n });\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: ChatMessage\n ): ChatMessage {\n return message;\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 * Returns `{ requestId, status }` so callers can detect whether the turn\n * ran (`\"completed\"`) or was skipped because the chat was cleared\n * (`\"skipped\"`).\n */\n async saveMessages(\n messages:\n | ChatMessage[]\n | ((\n currentMessages: ChatMessage[]\n ) => ChatMessage[] | Promise<ChatMessage[]>)\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\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 await this._runProgrammaticChatTurn(requestId, clientTools, body);\n },\n { epoch }\n );\n\n if (this._turnQueue.generation !== epoch && status === \"completed\") {\n status = \"skipped\";\n }\n\n return { requestId, status };\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 protected async continueLastTurn(\n body?: Record<string, unknown>\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\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 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 await this._reply(requestId, response, [], {\n continuation: true,\n chatMessageId: requestId\n });\n }\n } finally {\n this._abortRegistry.remove(requestId);\n }\n }\n );\n });\n };\n\n if (this.chatRecovery) {\n await this.runFiber(\n `${(this.constructor as typeof AIChatAgent).CHAT_FIBER_NAME}:${requestId}`,\n async () => {\n await turnBody();\n }\n );\n } else {\n await turnBody();\n }\n },\n { epoch }\n );\n\n if (this._turnQueue.generation !== epoch && status === \"completed\") {\n status = \"skipped\";\n }\n\n return { requestId, status };\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 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\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 const options = await this.onChatRecovery({\n streamId: streamId ?? \"\",\n requestId,\n partialText: partial.text,\n partialParts: partial.parts,\n recoveryData: ctx.snapshot,\n messages: [...this.messages],\n lastBody: this._lastBody,\n lastClientTools: this._lastClientTools,\n createdAt: ctx.createdAt\n });\n\n // Only persist and complete if the stream is still active. The ACK\n // handler (client reconnect → replayChunks) may have already persisted\n // the orphaned stream and completed it before fiber recovery runs.\n // Without this guard, _persistOrphanedStream runs twice on the same\n // chunks, doubling the assistant message's parts.\n const streamStillActive =\n streamId &&\n this._resumableStream.hasActiveStream() &&\n this._resumableStream.activeStreamId === streamId;\n\n if (options.persist !== false && streamStillActive) {\n this._persistOrphanedStream(streamId);\n }\n\n if (streamStillActive) {\n this._resumableStream.complete(streamId);\n }\n\n if (options.continue !== false) {\n const targetId = this._findLastAssistantMessage()?.id;\n await this.schedule(\n 0,\n \"_chatRecoveryContinue\",\n targetId ? { targetAssistantId: targetId } : undefined,\n { idempotent: true }\n );\n }\n\n return true;\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 streaming (e.g., OpenAI `responseId`).\n */\n protected async onChatRecovery(\n // oxlint-disable-next-line @typescript-eslint/no-unused-vars -- overridable hook\n _ctx: ChatRecoveryContext\n ): Promise<ChatRecoveryOptions> {\n return {};\n }\n\n async _chatRecoveryContinue(data?: {\n targetAssistantId?: string;\n }): Promise<void> {\n const ready = await this.waitUntilStable({ timeout: 10_000 });\n if (!ready) {\n console.warn(\n \"[AIChatAgent] _chatRecoveryContinue timed out waiting for stable state, skipping continuation\"\n );\n return;\n }\n\n const targetId = data?.targetAssistantId;\n if (targetId && this._findLastAssistantMessage()?.id !== targetId) {\n return;\n }\n\n await this.continueLastTurn();\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: ChatMessage[],\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 for (const row of allDbRows) {\n if (!keepIds.has(row.id)) {\n this.sql`\n delete from cf_ai_chat_agent_messages where id = ${row.id}\n `;\n this._persistedMessageCache.delete(row.id);\n }\n }\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(\n toolCallId: string\n ): ChatMessage | 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(): ChatMessage | 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): ChatMessage {\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: ChatMessage): ChatMessage {\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 ChatMessage[\"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 ChatMessage[\"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 * 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 for (const row of toDelete) {\n this.sql`delete from cf_ai_chat_agent_messages where id = ${row.id}`;\n this._persistedMessageCache.delete(row.id);\n }\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: ChatMessage): ChatMessage {\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 ChatMessage[\"parts\"];\n\n let result: ChatMessage = {\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: ChatMessage): ChatMessage {\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 ChatMessage[\"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: ChatMessage = { ...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 * @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, false if not found or state didn't match\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: ChatMessage | 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 let updated = 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 const applied = applyUpdate(part as Record<string, unknown>);\n Object.assign(part, applied);\n updated = true;\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 updated = true;\n return applyUpdate(part as Record<string, unknown>);\n }\n return part;\n }) as ChatMessage[\"parts\"];\n\n if (updated) {\n const updatedMessage: ChatMessage = this._sanitizeMessageForPersistence(\n { ...message, 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 (!updated) {\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 // 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 * 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 * @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 [\"input-available\", \"approval-requested\", \"approval-responded\"],\n (part) => ({\n ...part,\n ...(overrideState === \"output-error\"\n ? {\n state: \"output-error\",\n errorText: errorText ?? \"Tool execution denied by user\"\n }\n : { state: \"output-available\", output, preliminary: false })\n })\n );\n }\n\n private async _streamSSEReply(\n id: string,\n streamId: string,\n reader: ReadableStreamDefaultReader<Uint8Array>,\n message: ChatMessage,\n streamCompleted: { value: boolean },\n continuation = false,\n abortSignal?: AbortSignal\n ): Promise<\"completed\" | \"aborted\"> {\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 \"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: always suppressed when an existing\n // reasoning part exists — re-reasoning during continuation\n // appends to the same block rather than creating a new one.\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 if (message.parts[k].type === \"reasoning\") {\n continuationReasoningResumed = true;\n break;\n }\n }\n if (continuationReasoningResumed) continue;\n }\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 = 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: ChatMessage = {\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 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 ],\n (part) => ({\n ...part,\n state: \"output-available\",\n output: data.output,\n ...(data.preliminary !== undefined && {\n preliminary: data.preliminary\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 ],\n (part) => ({\n ...part,\n state: \"output-error\",\n errorText: data.errorText\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 this._broadcastChatMessage({\n error: true,\n body: data.errorText ?? JSON.stringify(data),\n done: false,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE\n });\n break;\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 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 \"aborted\";\n }\n\n return \"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: ChatMessage,\n streamCompleted: { value: boolean },\n continuation = false,\n abortSignal?: AbortSignal\n ): Promise<\"completed\" | \"aborted\"> {\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 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 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 \"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 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 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 \"aborted\";\n }\n\n return \"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 ) {\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;\n }\n\n // Start tracking this stream for resumability\n const streamId = this._startStream(id);\n\n const reader = response.body.getReader();\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 // 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 streamEndStatus: \"completed\" | \"aborted\" | \"error\" = \"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 streamEndStatus = await this._streamSSEReply(\n id,\n streamId,\n reader,\n message,\n streamCompleted,\n continuation,\n abortSignal\n );\n } else {\n streamEndStatus = await this._sendPlaintextReply(\n id,\n streamId,\n reader,\n message,\n streamCompleted,\n continuation,\n abortSignal\n );\n }\n } catch (error) {\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: error instanceof Error ? error.message : \"Stream error\",\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\", {\n error: error instanceof Error ? error.message : String(error)\n });\n\n this._pendingChatResponseResults.push({\n message,\n requestId: id,\n continuation,\n status: \"error\",\n error: error instanceof Error ? error.message : String(error)\n });\n }\n throw error;\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) {\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: ChatMessage = {\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: streamEndStatus\n });\n })\n );\n }\n\n /**\n * When the DO is destroyed, cancel all pending requests and clean up resources\n */\n async destroy() {\n this._abortRegistry.destroyAll();\n this._resumableStream.destroy();\n await super.destroy();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,kBACd,UACA,gBACA,uBACe;AAKf,QAAO,sBAJuB,uBAC5B,UACA,eACD,EAGC,gBACA,sBACD;;;;;;;AAQH,SAAgB,mBACd,SACA,gBACa;AACb,KAAI,QAAQ,SAAS,YACnB,QAAO;AAGT,MAAK,MAAM,QAAQ,QAAQ,MACzB,KAAI,gBAAgB,QAAQ,KAAK,YAAY;EAC3C,MAAM,aAAa,KAAK;EACxB,MAAM,WAAW,wBAAwB,gBAAgB,WAAW;AACpE,MAAI,YAAY,SAAS,OAAO,QAAQ,GACtC,QAAO;GAAE,GAAG;GAAS,IAAI,SAAS;GAAI;;AAK5C,QAAO;;;;;;AAOT,SAAgB,oBACd,SACA,UACoB;AACpB,KAAI,QAAQ,SAAS,YACnB;CAEF,MAAM,YAAY,WAAW,SAAS,QAAQ,GAAG;AACjD,QAAO,KAAK,UAAU,UAAU,MAAM;;AAGxC,SAAS,uBACP,UACA,gBACe;CACf,MAAM,oCAAoB,IAAI,KAAsB;AACpD,MAAK,MAA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,EACjB,iBAAgB,eAAe;QAE/B,iBAAgB,KAAK,iBAAiB;AAGxC,UAAM,KAAK,gBAAgB,iBAAiB,oBAAoB;cACvD,cAAc;IACvB,MAAM,cAAc,KAAK,SAAS,WAC/B,QAAQ,IAAI,OAAO,QAAQ,GAC7B;AACD,QAAI,eAAe,GAAG;KACpB,MAAM,kBAAkB,CAAC,GAAG,KAAK,SAAS;AAC1C,qBAAgB,eAAe;AAC/B,WAAM,KAAK,gBAAgB,iBAAiB,oBAAoB;UAGhE,OAAM,KAAK,gBACT,CAAC,GAAG,KAAK,UAAU,QAAQ,EAC3B,oBACD;SAGH,OAAM,KAAK,gBACT,CAAC,GAAG,KAAK,UAAU,QAAQ,EAC3B,oBACD;AAIL,QAAK,4BAA4B,KAAK;IACpC;IACA,WAAW;IACX;IACA,QAAQ;IACT,CAAC;IACF,CACH;;;;;CAMH,MAAM,UAAU;AACd,OAAK,eAAe,YAAY;AAChC,OAAK,iBAAiB,SAAS;AAC/B,QAAM,MAAM,SAAS"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["agentContext","chatByteLength"],"sources":["../src/message-reconciler.ts","../src/index.ts"],"sourcesContent":["/**\n * Message reconciliation — pure functions for aligning client messages\n * with server state during persistence.\n *\n * Three strategies applied in order:\n * 1. Merge server-known tool outputs into stale client messages\n * 2. Reconcile assistant IDs (exact match → content-key → toolCallId)\n * 3. Per-message toolCallId dedup for persistence\n */\n\nimport type { UIMessage } from \"ai\";\n\n/**\n * Reconcile incoming client messages against server state.\n *\n * 1. Merges server-known tool outputs into incoming messages that still\n * show stale states (input-available, approval-requested, approval-responded)\n * 2. Reconciles assistant IDs: exact match → content-key match → toolCallId match\n *\n * @param incoming - Messages from the client\n * @param serverMessages - Current server-side messages (source of truth)\n * @param sanitizeForContentKey - Function to sanitize a message before computing\n * its content key (typically strips ephemeral provider metadata)\n * @returns Reconciled messages ready for persistence\n */\nexport function reconcileMessages(\n incoming: UIMessage[],\n serverMessages: readonly UIMessage[],\n sanitizeForContentKey?: (message: UIMessage) => UIMessage\n): UIMessage[] {\n const withMergedToolOutputs = mergeServerToolOutputs(\n incoming,\n serverMessages\n );\n return reconcileAssistantIds(\n withMergedToolOutputs,\n serverMessages,\n sanitizeForContentKey\n );\n}\n\n/**\n * For a single message, resolve its ID by matching toolCallId against server state.\n * Prevents duplicate DB rows when client IDs differ from server IDs.\n * Tool call IDs are unique per conversation, so matching is safe regardless of state.\n */\nexport function resolveToolMergeId(\n message: UIMessage,\n serverMessages: readonly UIMessage[]\n): UIMessage {\n if (message.role !== \"assistant\") {\n return message;\n }\n\n for (const part of message.parts) {\n if (\"toolCallId\" in part && part.toolCallId) {\n const toolCallId = part.toolCallId as string;\n const existing = findMessageByToolCallId(serverMessages, toolCallId);\n if (existing && existing.id !== message.id) {\n return { ...message, id: existing.id };\n }\n }\n }\n\n return message;\n}\n\n/**\n * Content key for assistant messages used for dedup of identical short replies.\n * Returns JSON of sanitized parts, or undefined for non-assistant messages.\n */\nexport function assistantContentKey(\n message: UIMessage,\n sanitize?: (message: UIMessage) => UIMessage\n): string | undefined {\n if (message.role !== \"assistant\") {\n return undefined;\n }\n const sanitized = sanitize ? sanitize(message) : message;\n return JSON.stringify(sanitized.parts);\n}\n\nfunction mergeServerToolOutputs(\n incoming: UIMessage[],\n serverMessages: readonly UIMessage[]\n): UIMessage[] {\n const serverToolOutputs = new Map<string, unknown>();\n for (const msg of serverMessages) {\n if (msg.role !== \"assistant\") continue;\n for (const part of msg.parts) {\n if (\n \"toolCallId\" in part &&\n \"state\" in part &&\n part.state === \"output-available\" &&\n \"output\" in part\n ) {\n serverToolOutputs.set(\n part.toolCallId as string,\n (part as { output: unknown }).output\n );\n }\n }\n }\n\n if (serverToolOutputs.size === 0) return incoming;\n\n return incoming.map((msg) => {\n if (msg.role !== \"assistant\") return msg;\n\n let hasChanges = false;\n const updatedParts = msg.parts.map((part) => {\n if (\n \"toolCallId\" in part &&\n \"state\" in part &&\n (part.state === \"input-available\" ||\n part.state === \"approval-requested\" ||\n part.state === \"approval-responded\") &&\n serverToolOutputs.has(part.toolCallId as string)\n ) {\n hasChanges = true;\n return {\n ...part,\n state: \"output-available\" as const,\n output: serverToolOutputs.get(part.toolCallId as string)\n };\n }\n return part;\n }) as UIMessage[\"parts\"];\n\n return hasChanges ? { ...msg, parts: updatedParts } : msg;\n });\n}\n\nfunction reconcileAssistantIds(\n incoming: UIMessage[],\n serverMessages: readonly UIMessage[],\n sanitize?: (message: UIMessage) => UIMessage\n): UIMessage[] {\n if (serverMessages.length === 0) return incoming;\n\n const claimedServerIndices = new Set<number>();\n const exactMatchMap = new Map<number, number>();\n\n for (let i = 0; i < incoming.length; i++) {\n const serverIdx = serverMessages.findIndex(\n (sm, si) => !claimedServerIndices.has(si) && sm.id === incoming[i].id\n );\n if (serverIdx !== -1) {\n claimedServerIndices.add(serverIdx);\n exactMatchMap.set(i, serverIdx);\n }\n }\n\n return incoming.map((incomingMessage, incomingIdx) => {\n if (exactMatchMap.has(incomingIdx)) {\n return incomingMessage;\n }\n\n if (\n incomingMessage.role !== \"assistant\" ||\n hasToolCallPart(incomingMessage)\n ) {\n return incomingMessage;\n }\n\n const incomingKey = assistantContentKey(incomingMessage, sanitize);\n if (!incomingKey) {\n return incomingMessage;\n }\n\n for (let i = 0; i < serverMessages.length; i++) {\n if (claimedServerIndices.has(i)) continue;\n\n const serverMessage = serverMessages[i];\n if (\n serverMessage.role !== \"assistant\" ||\n hasToolCallPart(serverMessage)\n ) {\n continue;\n }\n\n if (assistantContentKey(serverMessage, sanitize) === incomingKey) {\n claimedServerIndices.add(i);\n return { ...incomingMessage, id: serverMessage.id };\n }\n }\n\n return incomingMessage;\n });\n}\n\nfunction hasToolCallPart(message: UIMessage): boolean {\n return message.parts.some((part) => \"toolCallId\" in part);\n}\n\nfunction findMessageByToolCallId(\n messages: readonly UIMessage[],\n toolCallId: string\n): UIMessage | undefined {\n for (const msg of messages) {\n if (msg.role !== \"assistant\") continue;\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","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 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 { reconcileMessages, resolveToolMergeId } from \"./message-reconciler\";\nimport {\n applyChunkToParts,\n sanitizeMessage,\n byteLength as chatByteLength,\n ROW_MAX_BYTES,\n TurnQueue,\n type TurnResult,\n type MessagePart\n} from \"agents/chat\";\nimport { ResumableStream } from \"agents/chat\";\nimport {\n createToolsFromClientSchemas,\n ContinuationState,\n AbortRegistry,\n type ContinuationConnection,\n type ClientToolSchema\n} from \"agents/chat\";\nimport type {\n ChatResponseResult,\n ChatRecoveryContext,\n ChatRecoveryOptions,\n MessageConcurrency,\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 ChatRecoveryContext,\n ChatRecoveryOptions,\n MessageConcurrency,\n SaveMessagesResult\n} from \"agents/chat\";\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\";\n\ntype NormalizedMessageConcurrency =\n | \"queue\"\n | \"latest\"\n | \"merge\"\n | \"drop\"\n | {\n strategy: \"debounce\";\n debounceMs: number;\n };\n\ntype SubmitConcurrencyDecision = {\n action: \"execute\" | \"drop\";\n submitSequence: number | null;\n debounceUntilMs: number | null;\n mergeQueuedMessages: boolean;\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();\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 /**\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 * 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 chatRecovery = false;\n\n /** First queued overlap message index for merge strategy, keyed by epoch. */\n private _mergeQueuedUserStartIndexByEpoch = new Map<number, number>();\n\n /** Monotonic sequence for overlapping submit-message requests. */\n private _submitSequence = 0;\n\n /** Latest overlapping submit-message sequence kept for latest/debounce. */\n private _latestOverlappingSubmitSequence = 0;\n\n /**\n * Tracks requests that have passed concurrency decision but haven't\n * yet been enqueued into `_turnQueue`. Bridges the gap caused by\n * `await persistMessages()` between the decision and the enqueue,\n * preventing a race where a subsequent message sees `queuedCount()=0`\n * and skips concurrency handling.\n */\n private _pendingEnqueueCount = 0;\n\n /** Active debounce timer handle, cleared on resetTurnState. */\n private _activeDebounceTimer: ReturnType<typeof setTimeout> | null = null;\n\n /** Resolve callback for the active debounce promise. */\n private _activeDebounceResolve: (() => void) | null = null;\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();\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 /**\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 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 // 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 // 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.awaitingConnections.delete(connection.id);\n if (this._continuation.pending?.connectionId === connection.id) {\n this._continuation.pending = null;\n }\n if (this._continuation.activeConnectionId === connection.id) {\n this._continuation.activeConnectionId = null;\n }\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 // 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 // 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 this._pendingEnqueueCount++;\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.mergeQueuedMessages) {\n await this._mergeQueuedUserMessages(epoch);\n }\n } finally {\n this._pendingEnqueueCount = Math.max(\n 0,\n this._pendingEnqueueCount - 1\n );\n }\n return this._runExclusiveChatTurn(\n chatMessageId,\n async () => {\n if (\n this._isSupersededSubmit(concurrencyDecision.submitSequence)\n ) {\n this._completeSkippedRequest(connection, chatMessageId);\n return;\n }\n\n if (concurrencyDecision.debounceUntilMs !== null) {\n await this._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._isSupersededSubmit(concurrencyDecision.submitSequence)\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.mergeQueuedMessages) {\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._isSupersededSubmit(concurrencyDecision.submitSequence)\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.runFiber(\n `${(this.constructor as typeof AIChatAgent).CHAT_FIBER_NAME}:${chatMessageId}`,\n async () => {\n await chatTurnBody();\n }\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 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 connection.send(\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 === connection.id\n ) {\n this._continuation.awaitingConnections.set(\n connection.id,\n connection\n );\n } else {\n connection.send(\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 this._persistOrphanedStream(orphanedStreamId);\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._applyToolResult(\n toolCallId,\n toolName,\n output,\n overrideState,\n errorText\n );\n this._pendingInteractionPromise = applyPromise;\n applyPromise\n .finally(() => {\n if (this._pendingInteractionPromise === applyPromise) {\n this._pendingInteractionPromise = null;\n }\n })\n .catch(() => {});\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._applyToolApproval(toolCallId, approved);\n this._pendingInteractionPromise = approvalPromise;\n approvalPromise\n .finally(() => {\n if (this._pendingInteractionPromise === approvalPromise) {\n this._pendingInteractionPromise = null;\n }\n })\n .catch(() => {});\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 _flushAwaitingStreamStartConnections() {\n if (!this._resumableStream.hasActiveStream()) {\n return;\n }\n\n this._continuation.flushAwaitingConnections((c: ContinuationConnection) =>\n this._notifyStreamResuming(c as Connection)\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 * @param connection - The WebSocket connection to notify\n */\n private _notifyStreamResuming(connection: Connection) {\n if (!this._resumableStream.hasActiveStream()) {\n return;\n }\n\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 // Notify client - they will send ACK when ready\n connection.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_STREAM_RESUMING,\n id: this._resumableStream.activeRequestId\n })\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(requestId: string): string {\n const streamId = this._resumableStream.start(requestId);\n if (this._continuation.pending?.requestId === requestId) {\n this._continuation.activatePending();\n this._flushAwaitingStreamStartConnections();\n this._activateDeferredAutoContinuation();\n }\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 }\n\n /** @internal Delegate to _resumableStream */\n protected _storeStreamChunk(streamId: string, body: string) {\n this._resumableStream.storeChunk(streamId, body);\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 this._resumableStream.markError(streamId);\n this._pendingResumeConnections.clear();\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 _persistOrphanedStream(streamId: string) {\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 message ID from the \"start\" event if present\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 // Continuation streams have their messageId stripped (#1229) so the\n // start chunk won't contain one. Fall back to the last assistant\n // message — continuations always append to it.\n if (message.id === fallbackId) {\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 // 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 const existing = this.messages[existingIdx];\n message.parts = [...existing.parts, ...message.parts];\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 this.persistMessages(updatedMessages);\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 _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 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 while (true) {\n await this._turnQueue.waitForIdle();\n if (this._pendingEnqueueCount === 0) return;\n // Brief yield so in-flight submits can reach `_runExclusiveChatTurn`,\n // which transfers their bookkeeping from `_pendingEnqueueCount` into\n // the turn queue. Bounded by inbound WS messages — drains quickly.\n await new Promise<void>((resolve) => setTimeout(resolve, 5));\n }\n }\n\n private _normalizeMessageConcurrency(): NormalizedMessageConcurrency {\n if (typeof this.messageConcurrency === \"string\") {\n return this.messageConcurrency;\n }\n\n const debounceMs = this.messageConcurrency.debounceMs;\n\n return {\n strategy: \"debounce\",\n debounceMs:\n typeof debounceMs === \"number\" &&\n Number.isFinite(debounceMs) &&\n debounceMs >= 0\n ? debounceMs\n : AIChatAgent.MESSAGE_DEBOUNCE_MS\n };\n }\n\n private _getSubmitConcurrencyDecision(\n trigger: ChatRequestTrigger\n ): SubmitConcurrencyDecision {\n const queuedTurnsInCurrentEpoch =\n this._turnQueue.queuedCount() + this._pendingEnqueueCount;\n\n if (trigger !== \"submit-message\" || queuedTurnsInCurrentEpoch === 0) {\n return {\n action: \"execute\",\n submitSequence: null,\n debounceUntilMs: null,\n mergeQueuedMessages: false\n };\n }\n\n const concurrency = this._normalizeMessageConcurrency();\n if (concurrency === \"drop\") {\n return {\n action: \"drop\",\n submitSequence: null,\n debounceUntilMs: null,\n mergeQueuedMessages: false\n };\n }\n\n if (concurrency === \"queue\") {\n return {\n action: \"execute\",\n submitSequence: null,\n debounceUntilMs: null,\n mergeQueuedMessages: false\n };\n }\n\n const submitSequence = ++this._submitSequence;\n this._latestOverlappingSubmitSequence = submitSequence;\n\n if (concurrency === \"latest\") {\n return {\n action: \"execute\",\n submitSequence,\n debounceUntilMs: null,\n mergeQueuedMessages: false\n };\n }\n\n if (concurrency === \"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 return {\n action: \"execute\",\n submitSequence,\n debounceUntilMs: null,\n mergeQueuedMessages: true\n };\n }\n\n return {\n action: \"execute\",\n submitSequence,\n debounceUntilMs: Date.now() + concurrency.debounceMs,\n mergeQueuedMessages: false\n };\n }\n\n private _isSupersededSubmit(submitSequence: number | null): boolean {\n return (\n submitSequence !== null &&\n submitSequence < this._latestOverlappingSubmitSequence\n );\n }\n\n private async _waitForTimestamp(timestampMs: number): Promise<void> {\n const remainingMs = timestampMs - Date.now();\n if (remainingMs <= 0) {\n return;\n }\n\n await new Promise<void>((resolve) => {\n this._activeDebounceResolve = resolve;\n this._activeDebounceTimer = setTimeout(() => {\n this._activeDebounceTimer = null;\n this._activeDebounceResolve = null;\n resolve();\n }, remainingMs);\n });\n }\n\n private _cancelActiveDebounce(): void {\n if (this._activeDebounceTimer !== null) {\n clearTimeout(this._activeDebounceTimer);\n this._activeDebounceTimer = null;\n }\n if (this._activeDebounceResolve !== null) {\n this._activeDebounceResolve();\n this._activeDebounceResolve = null;\n }\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._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._cancelActiveDebounce();\n this._pendingEnqueueCount = 0;\n this._pendingInteractionPromise = null;\n this._continuation.sendResumeNone();\n this._continuation.clearAll();\n this._pendingChatResponseResults.length = 0;\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 * 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 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 return true;\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 return true;\n }\n }\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\n ?.connection as Connection | null;\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 await this._reply(requestId, response, [], {\n continuation: true,\n chatMessageId: requestId\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.runFiber(\n `${(this.constructor as typeof AIChatAgent).CHAT_FIBER_NAME}:${requestId}`,\n async () => {\n await autoContinuationBody();\n }\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 private async _runProgrammaticChatTurn(\n requestId: string,\n clientTools?: ClientToolSchema[],\n body?: Record<string, unknown>\n ): Promise<void> {\n this._setRequestContext(clientTools, body);\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 const programmaticBody = async () => {\n try {\n const response = await this.onChatMessage(() => {}, {\n requestId,\n abortSignal,\n clientTools,\n body,\n continuation: false\n });\n\n if (response) {\n await this._reply(requestId, response, [], {\n chatMessageId: requestId\n });\n }\n } finally {\n this._abortRegistry.remove(requestId);\n }\n };\n\n if (this.chatRecovery) {\n await this.runFiber(\n `${(this.constructor as typeof AIChatAgent).CHAT_FIBER_NAME}:${requestId}`,\n async () => {\n await programmaticBody();\n }\n );\n } else {\n await programmaticBody();\n }\n }\n );\n });\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 * 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 * Returns `{ requestId, status }` so callers can detect whether the turn\n * ran (`\"completed\"`) or was skipped because the chat was cleared\n * (`\"skipped\"`).\n */\n async saveMessages(\n messages:\n | UIMessage[]\n | ((\n currentMessages: readonly UIMessage[]\n ) => UIMessage[] | Promise<UIMessage[]>)\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\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 await this._runProgrammaticChatTurn(requestId, clientTools, body);\n },\n { epoch }\n );\n\n if (this._turnQueue.generation !== epoch && status === \"completed\") {\n status = \"skipped\";\n }\n\n return { requestId, status };\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 protected async continueLastTurn(\n body?: Record<string, unknown>\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\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 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 await this._reply(requestId, response, [], {\n continuation: true,\n chatMessageId: requestId\n });\n }\n } finally {\n this._abortRegistry.remove(requestId);\n }\n }\n );\n });\n };\n\n if (this.chatRecovery) {\n await this.runFiber(\n `${(this.constructor as typeof AIChatAgent).CHAT_FIBER_NAME}:${requestId}`,\n async () => {\n await turnBody();\n }\n );\n } else {\n await turnBody();\n }\n },\n { epoch }\n );\n\n if (this._turnQueue.generation !== epoch && status === \"completed\") {\n status = \"skipped\";\n }\n\n return { requestId, status };\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 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\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 const options = await this.onChatRecovery({\n streamId: streamId ?? \"\",\n requestId,\n partialText: partial.text,\n partialParts: partial.parts,\n recoveryData: ctx.snapshot,\n messages: [...this.messages],\n lastBody: this._lastBody,\n lastClientTools: this._lastClientTools,\n createdAt: ctx.createdAt\n });\n\n // Only persist and complete if the stream is still active. The ACK\n // handler (client reconnect → replayChunks) may have already persisted\n // the orphaned stream and completed it before fiber recovery runs.\n // Without this guard, _persistOrphanedStream runs twice on the same\n // chunks, doubling the assistant message's parts.\n const streamStillActive =\n streamId &&\n this._resumableStream.hasActiveStream() &&\n this._resumableStream.activeStreamId === streamId;\n\n if (options.persist !== false && streamStillActive) {\n this._persistOrphanedStream(streamId);\n }\n\n if (streamStillActive) {\n this._resumableStream.complete(streamId);\n }\n\n if (options.continue !== false) {\n const targetId = this._findLastAssistantMessage()?.id;\n await this.schedule(\n 0,\n \"_chatRecoveryContinue\",\n targetId ? { targetAssistantId: targetId } : undefined,\n { idempotent: true }\n );\n }\n\n return true;\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 streaming (e.g., OpenAI `responseId`).\n */\n protected async onChatRecovery(\n // oxlint-disable-next-line @typescript-eslint/no-unused-vars -- overridable hook\n _ctx: ChatRecoveryContext\n ): Promise<ChatRecoveryOptions> {\n return {};\n }\n\n async _chatRecoveryContinue(data?: {\n targetAssistantId?: string;\n }): Promise<void> {\n const ready = await this.waitUntilStable({ timeout: 10_000 });\n if (!ready) {\n console.warn(\n \"[AIChatAgent] _chatRecoveryContinue timed out waiting for stable state, skipping continuation\"\n );\n return;\n }\n\n const targetId = data?.targetAssistantId;\n if (targetId && this._findLastAssistantMessage()?.id !== targetId) {\n return;\n }\n\n await this.continueLastTurn();\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 for (const row of allDbRows) {\n if (!keepIds.has(row.id)) {\n this.sql`\n delete from cf_ai_chat_agent_messages where id = ${row.id}\n `;\n this._persistedMessageCache.delete(row.id);\n }\n }\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 * 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 for (const row of toDelete) {\n this.sql`delete from cf_ai_chat_agent_messages where id = ${row.id}`;\n this._persistedMessageCache.delete(row.id);\n }\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 * @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, false if not found or state didn't match\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 let updated = 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 const applied = applyUpdate(part as Record<string, unknown>);\n Object.assign(part, applied);\n updated = true;\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 updated = true;\n return applyUpdate(part as Record<string, unknown>);\n }\n return part;\n }) as UIMessage[\"parts\"];\n\n if (updated) {\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 (!updated) {\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 // 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 * 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 * @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 [\"input-available\", \"approval-requested\", \"approval-responded\"],\n (part) => ({\n ...part,\n ...(overrideState === \"output-error\"\n ? {\n state: \"output-error\",\n errorText: errorText ?? \"Tool execution denied by user\"\n }\n : { state: \"output-available\", output, preliminary: false })\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<\"completed\" | \"aborted\"> {\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 \"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: always suppressed when an existing\n // reasoning part exists — re-reasoning during continuation\n // appends to the same block rather than creating a new one.\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 if (message.parts[k].type === \"reasoning\") {\n continuationReasoningResumed = true;\n break;\n }\n }\n if (continuationReasoningResumed) continue;\n }\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 = 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 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 ],\n (part) => ({\n ...part,\n state: \"output-available\",\n output: data.output,\n ...(data.preliminary !== undefined && {\n preliminary: data.preliminary\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 ],\n (part) => ({\n ...part,\n state: \"output-error\",\n errorText: data.errorText\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 this._broadcastChatMessage({\n error: true,\n body: data.errorText ?? JSON.stringify(data),\n done: false,\n id,\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE\n });\n break;\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 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 \"aborted\";\n }\n\n return \"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<\"completed\" | \"aborted\"> {\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 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 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 \"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 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 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 \"aborted\";\n }\n\n return \"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 ) {\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;\n }\n\n // Start tracking this stream for resumability\n const streamId = this._startStream(id);\n\n const reader = response.body.getReader();\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 // 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 streamEndStatus: \"completed\" | \"aborted\" | \"error\" = \"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 streamEndStatus = await this._streamSSEReply(\n id,\n streamId,\n reader,\n message,\n streamCompleted,\n continuation,\n abortSignal\n );\n } else {\n streamEndStatus = await this._sendPlaintextReply(\n id,\n streamId,\n reader,\n message,\n streamCompleted,\n continuation,\n abortSignal\n );\n }\n } catch (error) {\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: error instanceof Error ? error.message : \"Stream error\",\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\", {\n error: error instanceof Error ? error.message : String(error)\n });\n\n this._pendingChatResponseResults.push({\n message,\n requestId: id,\n continuation,\n status: \"error\",\n error: error instanceof Error ? error.message : String(error)\n });\n }\n throw error;\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) {\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: streamEndStatus\n });\n })\n );\n }\n\n /**\n * When the DO is destroyed, cancel all pending requests and clean up resources\n */\n async destroy() {\n this._abortRegistry.destroyAll();\n this._resumableStream.destroy();\n await super.destroy();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,kBACd,UACA,gBACA,uBACa;AAKb,QAAO,sBAJuB,uBAC5B,UACA,eACD,EAGC,gBACA,sBACD;;;;;;;AAQH,SAAgB,mBACd,SACA,gBACW;AACX,KAAI,QAAQ,SAAS,YACnB,QAAO;AAGT,MAAK,MAAM,QAAQ,QAAQ,MACzB,KAAI,gBAAgB,QAAQ,KAAK,YAAY;EAC3C,MAAM,aAAa,KAAK;EACxB,MAAM,WAAW,wBAAwB,gBAAgB,WAAW;AACpE,MAAI,YAAY,SAAS,OAAO,QAAQ,GACtC,QAAO;GAAE,GAAG;GAAS,IAAI,SAAS;GAAI;;AAK5C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