@cloudflare/ai-chat 0.2.2 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/react.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"react.js","names":[],"sources":["../src/ws-chat-transport.ts","../src/react.tsx"],"sourcesContent":["/**\n * WebSocket-based ChatTransport for useAgentChat.\n *\n * Replaces the aiFetch + DefaultChatTransport indirection with a direct\n * WebSocket implementation that speaks the CF_AGENT protocol natively.\n *\n * Data flow (old): WS → aiFetch fake Response → DefaultChatTransport → useChat\n * Data flow (new): WS → WebSocketChatTransport → useChat\n */\n\nimport type { ChatTransport, UIMessage, UIMessageChunk } from \"ai\";\nimport { nanoid } from \"nanoid\";\nimport { MessageType, type OutgoingMessage } from \"./types\";\n\n/**\n * Agent-like interface for sending/receiving WebSocket messages.\n * Matches the shape returned by useAgent from agents/react.\n */\nexport interface AgentConnection {\n send: (data: string) => void;\n addEventListener: (\n type: string,\n listener: (event: MessageEvent) => void,\n options?: { signal?: AbortSignal }\n ) => void;\n removeEventListener: (\n type: string,\n listener: (event: MessageEvent) => void\n ) => void;\n}\n\nexport type WebSocketChatTransportOptions<\n ChatMessage extends UIMessage = UIMessage\n> = {\n /** The agent connection from useAgent */\n agent: AgentConnection;\n /**\n * Callback to prepare the request body before sending.\n * Can add custom headers, body fields, or credentials.\n */\n prepareBody?: (options: {\n messages: ChatMessage[];\n trigger: \"submit-message\" | \"regenerate-message\";\n messageId?: string;\n }) => Promise<Record<string, unknown>> | Record<string, unknown>;\n /**\n * Optional set to track active request IDs.\n * IDs are added when a request starts and removed when it completes.\n * Used by the onAgentMessage handler to skip messages already handled by the transport.\n */\n activeRequestIds?: Set<string>;\n};\n\n/**\n * ChatTransport that sends messages over WebSocket and returns a\n * ReadableStream<UIMessageChunk> that the AI SDK's useChat consumes directly.\n * No fake fetch, no Response reconstruction, no double SSE parsing.\n */\nexport class WebSocketChatTransport<\n ChatMessage extends UIMessage = UIMessage\n> implements ChatTransport<ChatMessage> {\n agent: AgentConnection;\n private prepareBody?: WebSocketChatTransportOptions<ChatMessage>[\"prepareBody\"];\n private activeRequestIds?: Set<string>;\n\n // Pending resume resolver — set by reconnectToStream, called by\n // handleStreamResuming when onAgentMessage sees CF_AGENT_STREAM_RESUMING.\n private _resumeResolver: ((data: { id: string }) => void) | null = null;\n // Pending \"no stream\" resolver — called by handleStreamResumeNone\n // when onAgentMessage sees CF_AGENT_STREAM_RESUME_NONE.\n private _resumeNoneResolver: (() => void) | null = null;\n // Set when a client-side tool result/approval is expected to trigger\n // a new continuation stream. In this mode reconnectToStream() returns\n // a deferred ReadableStream immediately so AI SDK status can transition\n // to \"submitted\" before the server starts streaming.\n private _expectToolContinuation = false;\n\n constructor(options: WebSocketChatTransportOptions<ChatMessage>) {\n this.agent = options.agent;\n this.prepareBody = options.prepareBody;\n this.activeRequestIds = options.activeRequestIds;\n }\n\n /**\n * Mark that the next reconnectToStream() call should attach to a\n * server-initiated tool continuation rather than a page-load resume.\n */\n expectToolContinuation() {\n this._expectToolContinuation = true;\n }\n\n /**\n * True when the transport is waiting for a resume handshake.\n */\n isAwaitingResume(): boolean {\n return this._resumeResolver !== null || this._resumeNoneResolver !== null;\n }\n\n /**\n * Called by onAgentMessage when it receives CF_AGENT_STREAM_RESUMING.\n * If reconnectToStream is waiting, this handles the resume handshake\n * (ACK + stream creation) and returns true. Otherwise returns false\n * so the caller can use its own fallback path.\n */\n handleStreamResuming(data: { id: string }): boolean {\n if (!this._resumeResolver) return false;\n this._resumeResolver(data);\n return true;\n }\n\n /**\n * Called by onAgentMessage when it receives CF_AGENT_STREAM_RESUME_NONE.\n * If reconnectToStream is waiting, resolves the promise with null\n * immediately (no 5-second timeout). Returns true if handled.\n */\n handleStreamResumeNone(): boolean {\n if (!this._resumeNoneResolver) return false;\n this._resumeNoneResolver();\n return true;\n }\n\n async sendMessages(options: {\n chatId: string;\n messages: ChatMessage[];\n abortSignal: AbortSignal | undefined;\n trigger: \"submit-message\" | \"regenerate-message\";\n messageId?: string;\n body?: object;\n headers?: Record<string, string> | Headers;\n metadata?: unknown;\n }): Promise<ReadableStream<UIMessageChunk>> {\n const requestId = nanoid(8);\n const abortController = new AbortController();\n let completed = false;\n\n // Build the request body\n let extraBody: Record<string, unknown> = {};\n if (this.prepareBody) {\n extraBody = await this.prepareBody({\n messages: options.messages,\n trigger: options.trigger,\n messageId: options.messageId\n });\n }\n if (options.body) {\n extraBody = {\n ...extraBody,\n ...(options.body as Record<string, unknown>)\n };\n }\n\n const bodyPayload = JSON.stringify({\n messages: options.messages,\n trigger: options.trigger,\n ...extraBody\n });\n\n // Track this request so the onAgentMessage handler skips it\n this.activeRequestIds?.add(requestId);\n\n // Create a ReadableStream<UIMessageChunk> that emits parsed chunks\n // as they arrive over the WebSocket\n const agent = this.agent;\n const activeIds = this.activeRequestIds;\n\n // Single cleanup helper — every terminal path (done, error, abort)\n // goes through here exactly once.\n // keepId: when true, do NOT remove requestId from activeIds. Used by\n // onAbort so that onAgentMessage continues to skip in-flight chunks\n // and the server's final done:true broadcast until cleanup happens there.\n const finish = (action: () => void, keepId = false) => {\n if (completed) return;\n completed = true;\n try {\n action();\n } catch {\n // Stream may already be closed\n }\n if (!keepId) {\n activeIds?.delete(requestId);\n }\n abortController.abort();\n };\n\n const abortError = new Error(\"Aborted\");\n abortError.name = \"AbortError\";\n\n // Abort handler: send cancel to server, then terminate the stream.\n // Used by both the caller's abortSignal and stream.cancel().\n // keepId=true: keep requestId in activeIds so onAgentMessage skips any\n // in-flight chunks the server broadcasts before its done:true signal.\n // The ID is removed by onAgentMessage when done:true is received.\n const onAbort = () => {\n if (completed) return;\n try {\n agent.send(\n JSON.stringify({\n id: requestId,\n type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL\n })\n );\n } catch {\n // Ignore failures (e.g. agent already disconnected)\n }\n finish(() => streamController.error(abortError), true);\n };\n\n // streamController is assigned synchronously by start(), so it is\n // always available by the time onAbort or onMessage can fire.\n let streamController!: ReadableStreamDefaultController<UIMessageChunk>;\n\n const stream = new ReadableStream<UIMessageChunk>({\n start(controller) {\n streamController = controller;\n\n const onMessage = (event: MessageEvent) => {\n try {\n const data = JSON.parse(\n event.data as string\n ) as OutgoingMessage<ChatMessage>;\n\n if (data.type !== MessageType.CF_AGENT_USE_CHAT_RESPONSE) return;\n if (data.id !== requestId) return;\n\n if (data.error) {\n finish(() =>\n controller.error(new Error(data.body || \"Stream error\"))\n );\n return;\n }\n\n // Parse the body as UIMessageChunk and enqueue\n if (data.body?.trim()) {\n try {\n const chunk = JSON.parse(data.body) as UIMessageChunk;\n controller.enqueue(chunk);\n } catch {\n // Skip malformed chunk bodies\n }\n }\n\n if (data.done) {\n finish(() => controller.close());\n }\n } catch {\n // Ignore non-JSON messages\n }\n };\n\n agent.addEventListener(\"message\", onMessage, {\n signal: abortController.signal\n });\n },\n cancel() {\n onAbort();\n }\n });\n\n // Handle abort from the caller\n if (options.abortSignal) {\n options.abortSignal.addEventListener(\"abort\", onAbort, { once: true });\n if (options.abortSignal.aborted) onAbort();\n }\n\n // Send the request over WebSocket\n agent.send(\n JSON.stringify({\n id: requestId,\n init: {\n method: \"POST\",\n body: bodyPayload\n },\n type: MessageType.CF_AGENT_USE_CHAT_REQUEST\n })\n );\n\n return stream;\n }\n\n async reconnectToStream(_options: {\n chatId: string;\n }): Promise<ReadableStream<UIMessageChunk> | null> {\n if (this._expectToolContinuation) {\n this._expectToolContinuation = false;\n return this._createToolContinuationStream();\n }\n\n // Detect whether the server has an active stream for this chat.\n // Instead of registering our own addEventListener listener (which\n // races with onAgentMessage), we set _resumeResolver so that\n // onAgentMessage can call handleStreamResuming() synchronously\n // when it sees CF_AGENT_STREAM_RESUMING — eliminating the race.\n const activeIds = this.activeRequestIds;\n\n return new Promise<ReadableStream<UIMessageChunk> | null>((resolve) => {\n let resolved = false;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n\n const done = (value: ReadableStream<UIMessageChunk> | null) => {\n if (resolved) return;\n resolved = true;\n this._resumeResolver = null;\n this._resumeNoneResolver = null;\n if (timeout) clearTimeout(timeout);\n resolve(value);\n };\n\n // Set the \"no stream\" resolver that handleStreamResumeNone() will call.\n // When onAgentMessage sees CF_AGENT_STREAM_RESUME_NONE, it calls\n // handleStreamResumeNone() which resolves immediately with null.\n this._resumeNoneResolver = () => done(null);\n\n // Set the resolver that handleStreamResuming() will call.\n // When onAgentMessage sees CF_AGENT_STREAM_RESUMING, it calls\n // handleStreamResuming() which invokes this callback.\n this._resumeResolver = (data: { id: string }) => {\n const requestId = data.id;\n\n // Track this request so onAgentMessage skips subsequent chunks\n activeIds?.add(requestId);\n\n // Send ACK to server via the latest agent (the socket may\n // have been replaced since reconnectToStream was called).\n this.agent.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_STREAM_RESUME_ACK,\n id: requestId\n })\n );\n\n // Return a ReadableStream fed by the replayed + live chunks\n done(this._createResumeStream(requestId));\n };\n\n // Send the resume request. PartySocket queues sends when\n // the socket isn't open yet and flushes on connect, so\n // this works regardless of current readyState.\n try {\n this.agent.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_STREAM_RESUME_REQUEST\n })\n );\n } catch {\n // WebSocket may already be closed\n }\n\n // Safety-net timeout: if the WebSocket never connects or the\n // server is unreachable, resolve null. Under normal operation\n // the server responds with STREAM_RESUMING or STREAM_RESUME_NONE\n // well before this fires.\n timeout = setTimeout(() => done(null), 5000);\n });\n }\n\n /**\n * Creates a deferred ReadableStream for client-side tool continuations.\n * The stream is returned immediately so AI SDK status becomes \"submitted\"\n * right after addToolOutput()/addToolApprovalResponse(), then it waits for\n * the server to announce the continuation via STREAM_RESUMING.\n */\n private _createToolContinuationStream(): ReadableStream<UIMessageChunk> {\n const agent = this.agent;\n const activeIds = this.activeRequestIds;\n const streamController = new AbortController();\n let completed = false;\n let requestId: string | null = null;\n\n const clearHandshakeResolvers = (\n resumeResolver?: ((data: { id: string }) => void) | null,\n resumeNoneResolver?: (() => void) | null\n ) => {\n if (resumeResolver === undefined && resumeNoneResolver === undefined) {\n this._resumeResolver = null;\n this._resumeNoneResolver = null;\n return;\n }\n\n if (resumeResolver && this._resumeResolver === resumeResolver) {\n this._resumeResolver = null;\n }\n if (\n resumeNoneResolver &&\n this._resumeNoneResolver === resumeNoneResolver\n ) {\n this._resumeNoneResolver = null;\n }\n };\n\n const finish = (\n action: () => void,\n resumeResolver?: ((data: { id: string }) => void) | null,\n resumeNoneResolver?: (() => void) | null\n ) => {\n if (completed) return;\n completed = true;\n clearHandshakeResolvers(resumeResolver, resumeNoneResolver);\n try {\n action();\n } catch {\n // Stream may already be closed\n }\n if (requestId) {\n activeIds?.delete(requestId);\n }\n streamController.abort();\n };\n\n const transport = this;\n\n return new ReadableStream<UIMessageChunk>({\n start(controller) {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n\n const onResumeNone = () => {\n if (timeout) clearTimeout(timeout);\n finish(() => controller.close(), onResume, onResumeNone);\n };\n\n const onResume = (data: { id: string }) => {\n if (requestId) return;\n\n requestId = data.id;\n activeIds?.add(requestId);\n clearHandshakeResolvers(onResume, onResumeNone);\n if (timeout) clearTimeout(timeout);\n\n agent.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_STREAM_RESUME_ACK,\n id: requestId\n })\n );\n };\n\n timeout = setTimeout(\n () => finish(() => controller.close(), onResume, onResumeNone),\n 5000\n );\n\n transport._resumeResolver = onResume;\n transport._resumeNoneResolver = onResumeNone;\n\n const onMessage = (event: MessageEvent) => {\n try {\n const data = JSON.parse(\n event.data as string\n ) as OutgoingMessage<UIMessage>;\n\n if (\n data.type !== MessageType.CF_AGENT_USE_CHAT_RESPONSE ||\n requestId == null ||\n data.id !== requestId\n ) {\n return;\n }\n\n if (data.error) {\n finish(\n () => controller.error(new Error(data.body || \"Stream error\")),\n onResume,\n onResumeNone\n );\n return;\n }\n\n if (data.body?.trim()) {\n try {\n const chunk = JSON.parse(data.body) as UIMessageChunk;\n controller.enqueue(chunk);\n } catch {\n // Skip malformed chunk bodies\n }\n }\n\n if (data.done) {\n finish(() => controller.close(), onResume, onResumeNone);\n }\n } catch {\n // Ignore non-JSON messages\n }\n };\n\n agent.addEventListener(\"message\", onMessage, {\n signal: streamController.signal\n });\n\n try {\n agent.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_STREAM_RESUME_REQUEST\n })\n );\n } catch {\n finish(() => controller.close());\n }\n },\n cancel() {\n finish(() => {});\n }\n });\n }\n\n /**\n * Creates a ReadableStream that receives resumed stream chunks\n * and forwards them to useChat as UIMessageChunk objects.\n */\n private _createResumeStream(\n requestId: string\n ): ReadableStream<UIMessageChunk> {\n // Read agent at resolve time (not when reconnectToStream was called)\n // so chunk listener attaches to the latest socket after _pk changes.\n const agent = this.agent;\n const activeIds = this.activeRequestIds;\n const chunkController = new AbortController();\n let completed = false;\n\n const finish = (action: () => void) => {\n if (completed) return;\n completed = true;\n try {\n action();\n } catch {\n // Stream may already be closed\n }\n activeIds?.delete(requestId);\n chunkController.abort();\n };\n\n return new ReadableStream<UIMessageChunk>({\n start(controller) {\n const onMessage = (event: MessageEvent) => {\n try {\n const data = JSON.parse(\n event.data as string\n ) as OutgoingMessage<UIMessage>;\n\n if (data.type !== MessageType.CF_AGENT_USE_CHAT_RESPONSE) return;\n if (data.id !== requestId) return;\n\n if (data.error) {\n finish(() =>\n controller.error(new Error(data.body || \"Stream error\"))\n );\n return;\n }\n\n // Parse and enqueue the chunk\n if (data.body?.trim()) {\n try {\n const chunk = JSON.parse(data.body) as UIMessageChunk;\n controller.enqueue(chunk);\n } catch {\n // Skip malformed chunk bodies\n }\n }\n\n if (data.done) {\n finish(() => controller.close());\n }\n } catch {\n // Ignore non-JSON messages\n }\n };\n\n agent.addEventListener(\"message\", onMessage, {\n signal: chunkController.signal\n });\n },\n cancel() {\n finish(() => {});\n }\n });\n }\n}\n","import { useChat, type UseChatOptions } from \"@ai-sdk/react\";\nimport { getToolName, isToolUIPart } from \"ai\";\nimport type {\n ChatInit,\n JSONSchema7,\n Tool,\n UIMessage as Message,\n UIMessage\n} from \"ai\";\nimport { nanoid } from \"nanoid\";\nimport { use, useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { OutgoingMessage } from \"./types\";\nimport { MessageType } from \"./types\";\nimport { applyChunkToParts, type MessageParts } from \"./message-builder\";\nimport { WebSocketChatTransport } from \"./ws-chat-transport\";\nimport type { useAgent } from \"agents/react\";\n\n/**\n * One-shot deprecation warnings (warns once per key per session).\n */\nconst _deprecationWarnings = new Set<string>();\nfunction warnDeprecated(id: string, message: string) {\n if (!_deprecationWarnings.has(id)) {\n _deprecationWarnings.add(id);\n console.warn(`[@cloudflare/ai-chat] Deprecated: ${message}`);\n }\n}\n\n// ── DEPRECATED TYPES AND FUNCTIONS ──────────────────────────────────\n// Everything in this section is deprecated and will be removed in the\n// next major version. Use server-side tools with tool() from \"ai\" and\n// the onToolCall callback in useAgentChat instead.\n\n/**\n * JSON Schema type for tool parameters.\n * Re-exported from the AI SDK for convenience.\n * @deprecated Import JSONSchema7 directly from \"ai\" instead. Will be removed in the next major version.\n */\nexport type JSONSchemaType = JSONSchema7;\n\n/**\n * Definition for a tool that can be executed on the client.\n * Tools with an `execute` function are automatically registered with the server.\n *\n * **For most apps**, define tools on the server with `tool()` from `\"ai\"` —\n * you get full Zod type safety and simpler code. Use `onToolCall` in\n * `useAgentChat` for tools that need browser-side execution.\n *\n * **For SDKs and platforms** where the tool surface is determined dynamically\n * by the embedding application at runtime, this type lets the client register\n * tools the server does not know about at deploy time.\n *\n * Note: Uses `parameters` (JSONSchema7) because client tools must be\n * serializable for the wire format. Zod schemas cannot be serialized.\n */\nexport type AITool<Input = unknown, Output = unknown> = {\n /** Human-readable description of what the tool does */\n description?: Tool[\"description\"];\n /** JSON Schema defining the tool's input parameters */\n parameters?: JSONSchema7;\n /**\n * @deprecated Use `parameters` instead. Will be removed in a future version.\n */\n inputSchema?: JSONSchema7;\n /**\n * Function to execute the tool on the client.\n * If provided, the tool schema is automatically sent to the server.\n */\n execute?: (input: Input) => Output | Promise<Output>;\n};\n\n/**\n * Schema for a client tool sent to the server.\n * This is the wire format — what gets sent in the request body.\n * Must match the server-side ClientToolSchema type.\n *\n * Most apps do not need this directly — it is used internally when the\n * `tools` option on `useAgentChat` contains tools with `execute` functions.\n */\nexport type ClientToolSchema = {\n /** Unique name for the tool */\n name: string;\n /** Human-readable description of what the tool does */\n description?: Tool[\"description\"];\n /** JSON Schema defining the tool's input parameters */\n parameters?: JSONSchema7;\n};\n\n/**\n * Extracts tool schemas from tools that have client-side execute functions.\n * These schemas are automatically sent to the server with each request.\n *\n * Called internally by `useAgentChat` when `tools` are provided.\n * Most apps do not need to call this directly.\n *\n * @param tools - Record of tool name to tool definition\n * @returns Array of tool schemas to send to server, or undefined if none\n */\nexport function extractClientToolSchemas(\n tools?: Record<string, AITool<unknown, unknown>>\n): ClientToolSchema[] | undefined {\n if (!tools) return undefined;\n\n const schemas: ClientToolSchema[] = Object.entries(tools)\n .filter(([_, tool]) => tool.execute) // Only tools with client-side execute\n .map(([name, tool]) => {\n if (tool.inputSchema && !tool.parameters) {\n console.warn(\n `[useAgentChat] Tool \"${name}\" uses deprecated 'inputSchema'. Please migrate to 'parameters'.`\n );\n }\n return {\n name,\n description: tool.description,\n parameters: tool.parameters ?? tool.inputSchema\n };\n });\n\n return schemas.length > 0 ? schemas : undefined;\n}\n\n// ── END DEPRECATED TYPES AND FUNCTIONS ─────────────────────────────\n\ntype GetInitialMessagesOptions = {\n agent: string;\n name: string;\n url: string;\n};\n\n// v5 useChat parameters\ntype UseChatParams<M extends UIMessage = UIMessage> = ChatInit<M> &\n UseChatOptions<M>;\n\n/**\n * Options for preparing the send messages request.\n * Used by prepareSendMessagesRequest callback.\n */\nexport type PrepareSendMessagesRequestOptions<\n ChatMessage extends UIMessage = UIMessage\n> = {\n /** The chat ID */\n id: string;\n /** Messages to send */\n messages: ChatMessage[];\n /** What triggered this request */\n trigger: \"submit-message\" | \"regenerate-message\";\n /** ID of the message being sent (if applicable) */\n messageId?: string;\n /** Request metadata */\n requestMetadata?: unknown;\n /** Current body (if any) */\n body?: Record<string, unknown>;\n /** Current credentials (if any) */\n credentials?: RequestCredentials;\n /** Current headers (if any) */\n headers?: HeadersInit;\n /** API endpoint */\n api?: string;\n};\n\n/**\n * Return type for prepareSendMessagesRequest callback.\n * Allows customizing headers, body, and credentials for each request.\n * All fields are optional; only specify what you need to customize.\n */\nexport type PrepareSendMessagesRequestResult = {\n /** Custom headers to send with the request */\n headers?: HeadersInit;\n /** Custom body data to merge with the request */\n body?: Record<string, unknown>;\n /** Custom credentials option */\n credentials?: RequestCredentials;\n /** Custom API endpoint */\n api?: string;\n};\n\n/**\n * Options for addToolOutput function\n */\ntype AddToolOutputOptions = {\n /** The ID of the tool call to provide output for */\n toolCallId: string;\n /** The name of the tool (optional, for type safety) */\n toolName?: string;\n /** The output to provide */\n output?: unknown;\n /** Override the tool part state (e.g. \"output-error\" for custom denial) */\n state?: \"output-available\" | \"output-error\";\n /** Error message when state is \"output-error\" */\n errorText?: string;\n};\n\n/**\n * Callback for handling client-side tool execution.\n * Called when a tool without server-side execute is invoked.\n */\nexport type OnToolCallCallback = (options: {\n /** The tool call that needs to be handled */\n toolCall: {\n toolCallId: string;\n toolName: string;\n input: unknown;\n };\n /** Function to provide the tool output (or signal an error/denial) */\n addToolOutput: (options: Omit<AddToolOutputOptions, \"toolName\">) => void;\n}) => void | Promise<void>;\n\n/**\n * Options for the useAgentChat hook\n */\ntype UseAgentChatOptions<\n State,\n ChatMessage extends UIMessage = UIMessage\n> = Omit<UseChatParams<ChatMessage>, \"fetch\" | \"onToolCall\"> & {\n /** Agent connection from useAgent */\n agent: ReturnType<typeof useAgent<State>>;\n getInitialMessages?:\n | undefined\n | null\n | ((options: GetInitialMessagesOptions) => Promise<ChatMessage[]>);\n /** Request credentials */\n credentials?: RequestCredentials;\n /** Request headers */\n headers?: HeadersInit;\n /**\n * Callback for handling client-side tool execution.\n * Called when a tool without server-side `execute` is invoked by the LLM.\n *\n * Use this for:\n * - Tools that need browser APIs (geolocation, camera, etc.)\n * - Tools that need user interaction before providing a result\n * - Tools requiring approval before execution\n *\n * @example\n * ```typescript\n * onToolCall: async ({ toolCall, addToolOutput }) => {\n * if (toolCall.toolName === 'getLocation') {\n * const position = await navigator.geolocation.getCurrentPosition();\n * addToolOutput({\n * toolCallId: toolCall.toolCallId,\n * output: { lat: position.coords.latitude, lng: position.coords.longitude }\n * });\n * }\n * }\n * ```\n */\n onToolCall?: OnToolCallCallback;\n /**\n * @deprecated Use `onToolCall` callback instead for automatic tool execution.\n * @description Whether to automatically resolve tool calls that do not require human interaction.\n * @experimental\n */\n experimental_automaticToolResolution?: boolean;\n /**\n * Tools that can be executed on the client. Tool schemas are automatically\n * sent to the server and tool calls are routed back for client execution.\n *\n * **For most apps**, define tools on the server with `tool()` from `\"ai\"`\n * and handle client-side execution via `onToolCall`. This gives you full\n * Zod type safety and keeps tool definitions in one place.\n *\n * **For SDKs and platforms** where tools are defined dynamically by the\n * embedding application at runtime, this option lets the client register\n * tools the server does not know about at deploy time.\n */\n tools?: Record<string, AITool<unknown, unknown>>;\n /**\n * @deprecated Use `needsApproval` on server-side tools instead.\n * @description Manual override for tools requiring confirmation.\n * If not provided, will auto-detect from tools object (tools without execute require confirmation).\n */\n toolsRequiringConfirmation?: string[];\n /**\n * When true (default), the server automatically continues the conversation\n * after receiving client-side tool results or approvals, similar to how\n * server-executed tools work with maxSteps in streamText. The continuation\n * is merged into the same assistant message.\n *\n * When false, the client must call sendMessage() after tool results\n * to continue the conversation, which creates a new assistant message.\n *\n * @default true\n */\n autoContinueAfterToolResult?: boolean;\n /**\n * @deprecated Use `sendAutomaticallyWhen` from AI SDK instead.\n *\n * When true (default), automatically sends the next message only after\n * all pending confirmation-required tool calls have been resolved.\n * When false, sends immediately after each tool result.\n *\n * Only applies when `autoContinueAfterToolResult` is false.\n *\n * @default true\n */\n autoSendAfterAllConfirmationsResolved?: boolean;\n /**\n * Set to false to disable automatic stream resumption.\n * @default true\n */\n resume?: boolean;\n /**\n * Custom data to include in every chat request body.\n * Accepts a static object or a function that returns one (for dynamic values).\n * These fields are available in `onChatMessage` via `options.body`.\n *\n * @example\n * ```typescript\n * // Static\n * body: { timezone: \"America/New_York\", userId: \"abc\" }\n *\n * // Dynamic (called on each send)\n * body: () => ({ token: getAuthToken(), timestamp: Date.now() })\n * ```\n */\n body?:\n | Record<string, unknown>\n | (() => Record<string, unknown> | Promise<Record<string, unknown>>);\n /**\n * Callback to customize the request before sending messages.\n * For most cases, use the `body` option instead.\n * Use this for advanced scenarios that need access to the messages or trigger type.\n *\n * Note: Client tool schemas are automatically sent when tools have `execute` functions.\n * This callback can add additional data alongside the auto-extracted schemas.\n */\n prepareSendMessagesRequest?: (\n options: PrepareSendMessagesRequestOptions<ChatMessage>\n ) =>\n | PrepareSendMessagesRequestResult\n | Promise<PrepareSendMessagesRequestResult>;\n};\n\n/**\n * Module-level cache for initial message fetches. Intentionally shared across\n * all useAgentChat instances to deduplicate requests during React Strict Mode\n * double-renders and re-renders. Cache keys include the agent URL, agent type,\n * and thread name to prevent cross-agent collisions.\n */\nconst requestCache = new Map<string, Promise<Message[]>>();\n\n/**\n * React hook for building AI chat interfaces using an Agent\n * @param options Chat options including the agent connection\n * @returns Chat interface controls and state with added clearHistory method\n */\n/**\n * Automatically detects which tools require confirmation based on their configuration.\n * Tools require confirmation if they have no execute function AND are not server-executed.\n * @param tools - Record of tool name to tool definition\n * @returns Array of tool names that require confirmation\n *\n * @deprecated Use `needsApproval` on server-side tools instead.\n */\nexport function detectToolsRequiringConfirmation(\n tools?: Record<string, AITool<unknown, unknown>>\n): string[] {\n warnDeprecated(\n \"detectToolsRequiringConfirmation\",\n \"detectToolsRequiringConfirmation() is deprecated. Use needsApproval on server-side tools instead. Will be removed in the next major version.\"\n );\n if (!tools) return [];\n\n return Object.entries(tools)\n .filter(([_name, tool]) => !tool.execute)\n .map(([name]) => name);\n}\n\nexport function useAgentChat<\n State = unknown,\n ChatMessage extends UIMessage = UIMessage\n>(\n options: UseAgentChatOptions<State, ChatMessage>\n): Omit<ReturnType<typeof useChat<ChatMessage>>, \"addToolOutput\"> & {\n clearHistory: () => void;\n /**\n * Provide output for a tool call. Use this for tools that require user interaction\n * or client-side execution.\n */\n addToolOutput: (opts: AddToolOutputOptions) => void;\n} {\n const {\n agent,\n getInitialMessages,\n messages: optionsInitialMessages,\n onToolCall,\n onData,\n experimental_automaticToolResolution,\n tools,\n toolsRequiringConfirmation: manualToolsRequiringConfirmation,\n autoContinueAfterToolResult = true, // Server auto-continues after tool results/approvals\n autoSendAfterAllConfirmationsResolved = true, // Legacy option for client-side batching\n resume = true, // Enable stream resumption by default\n body: bodyOption,\n prepareSendMessagesRequest,\n ...rest\n } = options;\n\n // Emit deprecation warnings for deprecated options (once per session)\n if (manualToolsRequiringConfirmation) {\n warnDeprecated(\n \"useAgentChat.toolsRequiringConfirmation\",\n \"The 'toolsRequiringConfirmation' option is deprecated. Use needsApproval on server-side tools instead. Will be removed in the next major version.\"\n );\n }\n if (experimental_automaticToolResolution) {\n warnDeprecated(\n \"useAgentChat.experimental_automaticToolResolution\",\n \"The 'experimental_automaticToolResolution' option is deprecated. Use the onToolCall callback instead. Will be removed in the next major version.\"\n );\n }\n if (options.autoSendAfterAllConfirmationsResolved !== undefined) {\n warnDeprecated(\n \"useAgentChat.autoSendAfterAllConfirmationsResolved\",\n \"The 'autoSendAfterAllConfirmationsResolved' option is deprecated. Use sendAutomaticallyWhen from AI SDK instead. Will be removed in the next major version.\"\n );\n }\n\n // ── DEPRECATED: client-side tool confirmation ──────────────────────\n // This block will be removed when toolsRequiringConfirmation is removed.\n // Only call the deprecated function when deprecated options are actually used.\n const toolsRequiringConfirmation = useMemo(() => {\n if (manualToolsRequiringConfirmation) {\n return manualToolsRequiringConfirmation;\n }\n // Inline the logic from detectToolsRequiringConfirmation to avoid\n // emitting a deprecation warning when tools are provided via the\n // non-deprecated `tools` option.\n if (!tools) return [];\n return Object.entries(tools)\n .filter(([_name, tool]) => !tool.execute)\n .map(([name]) => name);\n }, [manualToolsRequiringConfirmation, tools]);\n\n // Keep refs to always point to the latest callbacks\n const onToolCallRef = useRef(onToolCall);\n onToolCallRef.current = onToolCall;\n const onDataRef = useRef(onData);\n onDataRef.current = onData;\n\n const agentUrl = new URL(\n `${\n // @ts-expect-error we're using a protected _url property that includes query params\n ((agent._url as string | null) || agent._pkurl)\n ?.replace(\"ws://\", \"http://\")\n .replace(\"wss://\", \"https://\")\n }`\n );\n\n agentUrl.searchParams.delete(\"_pk\");\n const agentUrlString = agentUrl.toString();\n\n // we need to include agent.name in cache key to prevent collisions during agent switching.\n // The URL may be stale between updateProperties() and reconnect(), but agent.name\n // is updated synchronously, so each thread gets its own cache entry\n const initialMessagesCacheKey = `${agentUrlString}|${agent.agent ?? \"\"}|${agent.name ?? \"\"}`;\n\n // Keep a ref to always point to the latest agent instance.\n // Updated synchronously during render (not in useEffect) so the\n // transport's agent ref is always current. The transport is a\n // singleton whose .agent is reassigned every render — if we used\n // useEffect the assignment would lag behind, causing the transport\n // to send through a stale/closed socket (issue #929).\n const agentRef = useRef(agent);\n agentRef.current = agent;\n\n async function defaultGetInitialMessagesFetch({\n url\n }: GetInitialMessagesOptions) {\n const getMessagesUrl = new URL(url);\n getMessagesUrl.pathname += \"/get-messages\";\n const response = await fetch(getMessagesUrl.toString(), {\n credentials: options.credentials,\n headers: options.headers\n });\n\n if (!response.ok) {\n console.warn(\n `Failed to fetch initial messages: ${response.status} ${response.statusText}`\n );\n return [];\n }\n\n const text = await response.text();\n if (!text.trim()) {\n return [];\n }\n\n try {\n return JSON.parse(text) as ChatMessage[];\n } catch (error) {\n console.warn(\"Failed to parse initial messages JSON:\", error);\n return [];\n }\n }\n\n const getInitialMessagesFetch =\n getInitialMessages || defaultGetInitialMessagesFetch;\n\n function doGetInitialMessages(\n getInitialMessagesOptions: GetInitialMessagesOptions,\n cacheKey: string\n ) {\n if (requestCache.has(cacheKey)) {\n return requestCache.get(cacheKey)! as Promise<ChatMessage[]>;\n }\n const promise = getInitialMessagesFetch(getInitialMessagesOptions);\n requestCache.set(cacheKey, promise);\n return promise;\n }\n\n const initialMessagesPromise =\n getInitialMessages === null\n ? null\n : doGetInitialMessages(\n {\n agent: agent.agent,\n name: agent.name,\n url: agentUrlString\n },\n initialMessagesCacheKey\n );\n const initialMessages = initialMessagesPromise\n ? use(initialMessagesPromise)\n : (optionsInitialMessages ?? []);\n\n useEffect(() => {\n if (!initialMessagesPromise) {\n return;\n }\n requestCache.set(initialMessagesCacheKey, initialMessagesPromise!);\n return () => {\n if (\n requestCache.get(initialMessagesCacheKey) === initialMessagesPromise\n ) {\n requestCache.delete(initialMessagesCacheKey);\n }\n };\n }, [initialMessagesCacheKey, initialMessagesPromise]);\n\n // Use synchronous ref updates to avoid race conditions between effect runs.\n // This ensures the ref always has the latest value before any effect reads it.\n const toolsRef = useRef(tools);\n toolsRef.current = tools;\n\n const prepareSendMessagesRequestRef = useRef(prepareSendMessagesRequest);\n prepareSendMessagesRequestRef.current = prepareSendMessagesRequest;\n\n const bodyOptionRef = useRef(bodyOption);\n bodyOptionRef.current = bodyOption;\n\n /**\n * Tracks request IDs initiated by this tab via the transport.\n * Used by onAgentMessage to skip messages already handled by the transport.\n */\n const localRequestIdsRef = useRef<Set<string>>(new Set());\n\n // WebSocket-based transport that speaks the CF_AGENT protocol natively.\n // Replaces the old aiFetch + DefaultChatTransport indirection.\n //\n // The transport is a true singleton (created once, never recreated) so\n // that the resolver set by reconnectToStream and the handleStreamResuming\n // call from onAgentMessage always operate on the SAME instance — even\n // when _pk changes (async queries, socket recreation) or React Strict\n // Mode double-mounts. The agent reference is updated every render so\n // sends always go through the latest socket.\n const customTransportRef = useRef<WebSocketChatTransport<ChatMessage> | null>(\n null\n );\n\n if (customTransportRef.current === null) {\n customTransportRef.current = new WebSocketChatTransport<ChatMessage>({\n agent: agentRef.current,\n activeRequestIds: localRequestIdsRef.current,\n prepareBody: async ({ messages: msgs, trigger, messageId }) => {\n // Start with the top-level body option (static or dynamic)\n let extraBody: Record<string, unknown> = {};\n const currentBody = bodyOptionRef.current;\n if (currentBody) {\n const resolved =\n typeof currentBody === \"function\"\n ? await currentBody()\n : currentBody;\n extraBody = { ...resolved };\n }\n\n // Extract schemas from deprecated client tools (if any)\n // Only extract client tool schemas when deprecated tools option is used\n if (toolsRef.current) {\n const clientToolSchemas = extractClientToolSchemas(toolsRef.current);\n if (clientToolSchemas) {\n extraBody.clientTools = clientToolSchemas;\n }\n }\n\n // Apply user's prepareSendMessagesRequest callback (overrides body option)\n if (prepareSendMessagesRequestRef.current) {\n const userResult = await prepareSendMessagesRequestRef.current({\n id: agentRef.current._pk,\n messages: msgs,\n trigger,\n messageId\n });\n if (userResult.body) {\n Object.assign(extraBody, userResult.body);\n }\n }\n\n return extraBody;\n }\n });\n }\n // Always point the transport at the latest socket so sends/listeners\n // go through the current connection after _pk changes.\n customTransportRef.current.agent = agentRef.current;\n const customTransport = customTransportRef.current;\n\n // Use a stable Chat ID that doesn't change when _pk changes.\n // The AI SDK recreates the Chat when `id` changes, which would\n // abandon any in-flight makeRequest (including resume) and the\n // resume effect wouldn't re-fire (deps are [resume, chatRef]).\n // Using the initial messages cache key (URL + agent + name) keeps\n // the Chat stable across socket recreations.\n const useChatHelpers = useChat<ChatMessage>({\n ...rest,\n onData,\n messages: initialMessages,\n transport: customTransport,\n id: initialMessagesCacheKey,\n // Pass resume so useChat calls transport.reconnectToStream().\n // This lets the AI SDK track status (\"streaming\") during resume.\n resume\n });\n\n // Destructure stable method references from useChatHelpers.\n // These are individually memoized by the AI SDK (via useCallback), so they're\n // safe to use in dependency arrays without causing re-renders. Using them\n // directly instead of `useChatHelpers.method` avoids the exhaustive-deps\n // warning about the unstable `useChatHelpers` object.\n const {\n messages: chatMessages,\n setMessages,\n addToolResult,\n addToolApprovalResponse,\n sendMessage,\n resumeStream\n } = useChatHelpers;\n\n const resumingToolContinuationRef = useRef(false);\n const startToolContinuation = useCallback(() => {\n if (!autoContinueAfterToolResult || resumingToolContinuationRef.current) {\n return;\n }\n\n resumingToolContinuationRef.current = true;\n customTransport.expectToolContinuation();\n\n void resumeStream().finally(() => {\n resumingToolContinuationRef.current = false;\n });\n }, [autoContinueAfterToolResult, customTransport, resumeStream]);\n\n const processedToolCalls = useRef(new Set<string>());\n const isResolvingToolsRef = useRef(false);\n // Counter to force the tool resolution effect to re-run after completing\n // a batch of tool calls. Without this, if new tool calls arrive while\n // isResolvingToolsRef is true (e.g. server auto-continuation), the effect\n // exits early and never retriggers because the ref reset doesn't cause\n // a re-render.\n const [toolResolutionTrigger, setToolResolutionTrigger] = useState(0);\n\n // Fix for issue #728: Track client-side tool results in local state\n // to ensure tool parts show output-available immediately after execution.\n const [clientToolResults, setClientToolResults] = useState<\n Map<string, unknown>\n >(new Map());\n\n // Ref to access current messages in callbacks without stale closures\n const messagesRef = useRef(chatMessages);\n messagesRef.current = chatMessages;\n\n // Calculate pending confirmations for the latest assistant message\n const lastMessage = chatMessages[chatMessages.length - 1];\n\n const pendingConfirmations = (() => {\n if (!lastMessage || lastMessage.role !== \"assistant\") {\n return { messageId: undefined, toolCallIds: new Set<string>() };\n }\n\n const pendingIds = new Set<string>();\n for (const part of lastMessage.parts ?? []) {\n if (\n isToolUIPart(part) &&\n part.state === \"input-available\" &&\n toolsRequiringConfirmation.includes(getToolName(part))\n ) {\n pendingIds.add(part.toolCallId);\n }\n }\n return { messageId: lastMessage.id, toolCallIds: pendingIds };\n })();\n\n const pendingConfirmationsRef = useRef(pendingConfirmations);\n pendingConfirmationsRef.current = pendingConfirmations;\n\n // ── DEPRECATED: automatic tool resolution effect ────────────────────\n // This entire useEffect is deprecated. Use onToolCall instead.\n useEffect(() => {\n if (!experimental_automaticToolResolution) {\n return;\n }\n\n // Prevent re-entry while async operations are in progress\n if (isResolvingToolsRef.current) {\n return;\n }\n\n const lastMsg = chatMessages[chatMessages.length - 1];\n if (!lastMsg || lastMsg.role !== \"assistant\") {\n return;\n }\n\n const toolCalls = lastMsg.parts.filter(\n (part) =>\n isToolUIPart(part) &&\n part.state === \"input-available\" &&\n !processedToolCalls.current.has(part.toolCallId)\n );\n\n if (toolCalls.length > 0) {\n // Capture tools synchronously before async work\n const currentTools = toolsRef.current;\n const toolCallsToResolve = toolCalls.filter(\n (part) =>\n isToolUIPart(part) &&\n !toolsRequiringConfirmation.includes(getToolName(part)) &&\n currentTools?.[getToolName(part)]?.execute\n );\n\n if (toolCallsToResolve.length > 0) {\n isResolvingToolsRef.current = true;\n\n (async () => {\n try {\n const toolResults: Array<{\n toolCallId: string;\n toolName: string;\n output: unknown;\n }> = [];\n\n for (const part of toolCallsToResolve) {\n if (isToolUIPart(part)) {\n let toolOutput: unknown = null;\n const toolName = getToolName(part);\n const tool = currentTools?.[toolName];\n\n if (tool?.execute && part.input !== undefined) {\n try {\n toolOutput = await tool.execute(part.input);\n } catch (error) {\n toolOutput = `Error executing tool: ${error instanceof Error ? error.message : String(error)}`;\n }\n }\n\n processedToolCalls.current.add(part.toolCallId);\n\n toolResults.push({\n toolCallId: part.toolCallId,\n toolName,\n output: toolOutput\n });\n }\n }\n\n if (toolResults.length > 0) {\n // Send tool results to server first (server is source of truth)\n const clientToolSchemas = extractClientToolSchemas(currentTools);\n for (const result of toolResults) {\n agentRef.current.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_TOOL_RESULT,\n toolCallId: result.toolCallId,\n toolName: result.toolName,\n output: result.output,\n autoContinue: autoContinueAfterToolResult,\n clientTools: clientToolSchemas\n })\n );\n }\n\n // Also update local state via AI SDK for immediate UI feedback\n await Promise.all(\n toolResults.map((result) =>\n addToolResult({\n tool: result.toolName,\n toolCallId: result.toolCallId,\n output: result.output\n })\n )\n );\n\n setClientToolResults((prev) => {\n const newMap = new Map(prev);\n for (const result of toolResults) {\n newMap.set(result.toolCallId, result.output);\n }\n return newMap;\n });\n\n startToolContinuation();\n }\n\n // Note: We don't call sendMessage() here anymore.\n // The server will continue the conversation after applying tool results.\n } finally {\n isResolvingToolsRef.current = false;\n // Trigger a re-run so any tool calls that arrived while we were\n // busy (e.g. from server auto-continuation) get picked up.\n setToolResolutionTrigger((c) => c + 1);\n }\n })();\n }\n }\n }, [\n chatMessages,\n experimental_automaticToolResolution,\n addToolResult,\n toolsRequiringConfirmation,\n autoContinueAfterToolResult,\n startToolContinuation,\n toolResolutionTrigger\n ]);\n\n // Helper function to send tool output to server\n const sendToolOutputToServer = useCallback(\n (\n toolCallId: string,\n toolName: string,\n output: unknown,\n state?: \"output-available\" | \"output-error\",\n errorText?: string\n ) => {\n const shouldAutoContinue =\n state === \"output-error\" ? false : autoContinueAfterToolResult;\n\n agentRef.current.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_TOOL_RESULT,\n toolCallId,\n toolName,\n output,\n ...(state ? { state } : {}),\n ...(errorText !== undefined ? { errorText } : {}),\n // output-error is a deliberate client action — don't auto-continue.\n // This differs from addToolApprovalResponse (which auto-continues for\n // both approvals and rejections). To have the LLM respond to the error,\n // call sendMessage() after addToolOutput.\n autoContinue: shouldAutoContinue,\n clientTools: toolsRef.current\n ? extractClientToolSchemas(toolsRef.current)\n : undefined\n })\n );\n\n if (state !== \"output-error\") {\n setClientToolResults((prev) => new Map(prev).set(toolCallId, output));\n }\n\n if (shouldAutoContinue) {\n startToolContinuation();\n }\n },\n [autoContinueAfterToolResult, startToolContinuation]\n );\n\n // Helper function to send tool approval to server\n const sendToolApprovalToServer = useCallback(\n (toolCallId: string, approved: boolean) => {\n agentRef.current.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_TOOL_APPROVAL,\n toolCallId,\n approved,\n autoContinue: autoContinueAfterToolResult\n })\n );\n\n if (autoContinueAfterToolResult) {\n startToolContinuation();\n }\n },\n [autoContinueAfterToolResult, startToolContinuation]\n );\n\n // Effect for new onToolCall callback pattern (v6 style)\n // This fires when there are tool calls that need client-side handling\n useEffect(() => {\n const currentOnToolCall = onToolCallRef.current;\n if (!currentOnToolCall) {\n return;\n }\n\n const lastMsg = chatMessages[chatMessages.length - 1];\n if (!lastMsg || lastMsg.role !== \"assistant\") {\n return;\n }\n\n // Find tool calls in input-available state that haven't been processed\n const pendingToolCalls = lastMsg.parts.filter(\n (part) =>\n isToolUIPart(part) &&\n part.state === \"input-available\" &&\n !processedToolCalls.current.has(part.toolCallId)\n );\n\n for (const part of pendingToolCalls) {\n if (isToolUIPart(part)) {\n const toolCallId = part.toolCallId;\n const toolName = getToolName(part);\n\n // Mark as processed to prevent re-triggering\n processedToolCalls.current.add(toolCallId);\n\n // Create addToolOutput function for this specific tool call\n const addToolOutput = (opts: AddToolOutputOptions) => {\n sendToolOutputToServer(\n opts.toolCallId,\n toolName,\n opts.output,\n opts.state,\n opts.errorText\n );\n\n // Update local state via AI SDK\n addToolResult({\n tool: toolName,\n toolCallId: opts.toolCallId,\n output:\n opts.state === \"output-error\"\n ? (opts.errorText ?? \"Tool execution denied by user\")\n : opts.output\n });\n };\n\n // Call the onToolCall callback\n // The callback is responsible for calling addToolOutput when ready\n currentOnToolCall({\n toolCall: {\n toolCallId,\n toolName,\n input: part.input\n },\n addToolOutput\n });\n }\n }\n }, [chatMessages, sendToolOutputToServer, addToolResult]);\n\n /**\n * Contains the request ID, accumulated message parts, metadata, and a unique message ID.\n * Used for both resumed streams and real-time broadcasts from other tabs.\n * Metadata is captured from start/finish/message-metadata stream chunks\n * so that it's included when the partial message is flushed to React state.\n */\n const activeStreamRef = useRef<{\n id: string;\n messageId: string;\n continuation: boolean;\n parts: ChatMessage[\"parts\"];\n metadata?: Record<string, unknown>;\n } | null>(null);\n\n /**\n * Flush the active stream's accumulated parts into React state.\n * Extracted as a helper so it can be called both during live streaming\n * (per-chunk) and after replay completes (once, at done).\n */\n const flushActiveStreamToMessages = useCallback(\n (activeMsg: {\n id: string;\n messageId: string;\n continuation: boolean;\n parts: ChatMessage[\"parts\"];\n metadata?: Record<string, unknown>;\n }) => {\n setMessages((prevMessages: ChatMessage[]) => {\n let existingIdx = prevMessages.findIndex(\n (m) => m.id === activeMsg.messageId\n );\n\n if (existingIdx < 0 && activeMsg.continuation) {\n for (let i = prevMessages.length - 1; i >= 0; i--) {\n if (prevMessages[i].role === \"assistant\") {\n existingIdx = i;\n break;\n }\n }\n }\n\n const messageId =\n existingIdx >= 0 ? prevMessages[existingIdx].id : activeMsg.messageId;\n\n const partialMessage = {\n id: messageId,\n role: \"assistant\" as const,\n parts: [...activeMsg.parts],\n ...(activeMsg.metadata != null && { metadata: activeMsg.metadata })\n } as unknown as ChatMessage;\n\n if (existingIdx >= 0) {\n const updated = [...prevMessages];\n updated[existingIdx] = partialMessage;\n return updated;\n }\n return [...prevMessages, partialMessage];\n });\n },\n [setMessages]\n );\n\n useEffect(() => {\n /**\n * Unified message handler that parses JSON once and dispatches based on type.\n * Avoids duplicate parsing overhead from separate listeners.\n */\n function onAgentMessage(event: MessageEvent) {\n if (typeof event.data !== \"string\") return;\n\n let data: OutgoingMessage<ChatMessage>;\n try {\n data = JSON.parse(event.data) as OutgoingMessage<ChatMessage>;\n } catch (_error) {\n return;\n }\n\n switch (data.type) {\n case MessageType.CF_AGENT_CHAT_CLEAR:\n setMessages([]);\n break;\n\n case MessageType.CF_AGENT_CHAT_MESSAGES:\n setMessages(data.messages);\n break;\n\n case MessageType.CF_AGENT_MESSAGE_UPDATED:\n // Server updated a message (e.g., applied tool result)\n // Update the specific message in local state\n setMessages((prevMessages: ChatMessage[]) => {\n const updatedMessage = data.message;\n\n // First try to find by message ID\n let idx = prevMessages.findIndex((m) => m.id === updatedMessage.id);\n\n // If not found by ID, try to find by toolCallId\n // This handles the case where client has AI SDK-generated IDs\n // but server has server-generated IDs\n if (idx < 0) {\n const updatedToolCallIds = new Set(\n updatedMessage.parts\n .filter(\n (p: ChatMessage[\"parts\"][number]) =>\n \"toolCallId\" in p && p.toolCallId\n )\n .map(\n (p: ChatMessage[\"parts\"][number]) =>\n (p as { toolCallId: string }).toolCallId\n )\n );\n\n if (updatedToolCallIds.size > 0) {\n idx = prevMessages.findIndex((m) =>\n m.parts.some(\n (p) =>\n \"toolCallId\" in p &&\n updatedToolCallIds.has(\n (p as { toolCallId: string }).toolCallId\n )\n )\n );\n }\n }\n\n if (idx >= 0) {\n const updated = [...prevMessages];\n // Preserve the client's message ID but update the content\n updated[idx] = {\n ...updatedMessage,\n id: prevMessages[idx].id\n };\n return updated;\n }\n // Message not found — don't append. CF_AGENT_MESSAGE_UPDATED is\n // for updating existing messages (e.g. tool result/approval state\n // changes), not for adding new ones. If the message isn't in\n // client state yet, it will arrive via the transport stream\n // (same tab) or CF_AGENT_CHAT_MESSAGES (cross-tab).\n // Appending here causes temporary duplicates (#1094).\n return prevMessages;\n });\n break;\n\n case MessageType.CF_AGENT_STREAM_RESUME_NONE:\n // Server confirmed no active stream — let the transport\n // resolve reconnectToStream immediately with null.\n customTransport.handleStreamResumeNone();\n break;\n\n case MessageType.CF_AGENT_STREAM_RESUMING:\n if (!resume && !customTransport.isAwaitingResume()) return;\n // Let the transport handle it if reconnectToStream is waiting.\n // This is called synchronously — no addEventListener race.\n // The transport sends ACK, adds to activeRequestIds, and\n // creates the ReadableStream that feeds into useChat's pipeline\n // (which correctly sets status to \"streaming\").\n if (customTransport.handleStreamResuming(data)) return;\n // Skip if the transport already handled this stream's resume\n // (server sends STREAM_RESUMING from both onConnect and the\n // RESUME_REQUEST handler — the second one must not trigger\n // a duplicate ACK / replay).\n if (localRequestIdsRef.current.has(data.id)) return;\n // Fallback for cross-tab broadcasts or cases where the\n // transport isn't expecting a resume.\n activeStreamRef.current = null;\n activeStreamRef.current = {\n id: data.id,\n messageId: nanoid(),\n continuation: false,\n parts: []\n };\n agentRef.current.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_STREAM_RESUME_ACK,\n id: data.id\n })\n );\n break;\n\n case MessageType.CF_AGENT_USE_CHAT_RESPONSE: {\n // Skip if this is a response to a request this tab initiated\n // (handled by the transport listener instead).\n // On done:true, also clean up the ID — it may have been kept in the\n // set after an abort to prevent in-flight chunks from creating a\n // duplicate message (see ws-chat-transport.ts onAbort).\n if (localRequestIdsRef.current.has(data.id)) {\n if (data.done) {\n localRequestIdsRef.current.delete(data.id);\n }\n return;\n }\n\n // For continuations, find the last assistant message ID to append to\n const isContinuation = data.continuation === true;\n\n // Initialize stream state for broadcasts from other tabs\n if (\n !activeStreamRef.current ||\n activeStreamRef.current.id !== data.id\n ) {\n let messageId = nanoid();\n let existingParts: ChatMessage[\"parts\"] = [];\n let existingMetadata: Record<string, unknown> | undefined;\n\n // For continuations, use the last assistant message's ID, parts, and metadata\n if (isContinuation) {\n const currentMessages = messagesRef.current;\n for (let i = currentMessages.length - 1; i >= 0; i--) {\n if (currentMessages[i].role === \"assistant\") {\n messageId = currentMessages[i].id;\n existingParts = [...currentMessages[i].parts];\n if (currentMessages[i].metadata != null) {\n existingMetadata = {\n ...(currentMessages[i].metadata as Record<\n string,\n unknown\n >)\n };\n }\n break;\n }\n }\n }\n\n activeStreamRef.current = {\n id: data.id,\n messageId,\n continuation: isContinuation,\n parts: existingParts,\n metadata: existingMetadata\n };\n }\n\n const activeMsg = activeStreamRef.current;\n const isReplay = data.replay === true;\n\n if (data.body?.trim()) {\n try {\n const chunkData = JSON.parse(data.body);\n\n // Apply chunk to parts using shared parser.\n // Handles text, reasoning, file, source, tool lifecycle\n // (including streaming: tool-input-start, tool-input-delta,\n // tool-input-available, tool-output-available), step, and\n // data-* chunks.\n const handled = applyChunkToParts(\n activeMsg.parts as MessageParts,\n chunkData\n );\n\n // Fire onData callback for data-* parts (stream resumption\n // and cross-tab broadcasts). For the transport path (new\n // messages from this tab), the AI SDK's pipeline invokes\n // onData internally.\n if (\n typeof chunkData.type === \"string\" &&\n chunkData.type.startsWith(\"data-\") &&\n onDataRef.current\n ) {\n onDataRef.current(chunkData);\n }\n\n // Capture message metadata from start/finish/message-metadata\n // chunks. These carry metadata like timestamps, model info, and\n // token usage that should be attached at the message level.\n if (\n !handled &&\n (chunkData.type === \"start\" ||\n chunkData.type === \"finish\" ||\n chunkData.type === \"message-metadata\")\n ) {\n if (\n chunkData.messageId != null &&\n chunkData.type === \"start\" &&\n !isContinuation\n ) {\n activeMsg.messageId = chunkData.messageId;\n }\n if (chunkData.messageMetadata != null) {\n activeMsg.metadata = activeMsg.metadata\n ? { ...activeMsg.metadata, ...chunkData.messageMetadata }\n : { ...chunkData.messageMetadata };\n }\n }\n\n // For replayed chunks, skip intermediate setMessages calls.\n // Replayed chunks arrive synchronously in a tight loop, so React\n // would batch all state updates into a single render anyway —\n // causing intermediate states (like \"Thinking...\") to be lost.\n // We defer the render until replay is complete (done signal).\n if (!isReplay) {\n flushActiveStreamToMessages(activeMsg);\n }\n } catch (parseError) {\n console.warn(\n \"[useAgentChat] Failed to parse stream chunk:\",\n parseError instanceof Error ? parseError.message : parseError,\n \"body:\",\n data.body?.slice(0, 100)\n );\n }\n }\n\n // On completion or error, flush final state to messages\n if (data.done || data.error) {\n // For replayed streams, this is the single render point —\n // all parts have been accumulated, now render them at once.\n if (isReplay && activeMsg) {\n flushActiveStreamToMessages(activeMsg);\n }\n activeStreamRef.current = null;\n } else if (data.replayComplete && activeMsg) {\n // Replay of stored chunks is complete but the stream is still\n // active (e.g. model is still thinking). Flush the accumulated\n // parts to React state so the UI shows progress. Without this,\n // replayed chunks sit in activeStreamRef unflushed until the\n // next live chunk arrives.\n flushActiveStreamToMessages(activeMsg);\n }\n break;\n }\n }\n }\n\n agent.addEventListener(\"message\", onAgentMessage);\n\n // Stream resume is now primarily handled by the transport's\n // reconnectToStream (which sends CF_AGENT_STREAM_RESUME_REQUEST).\n // The onAgentMessage handler above serves as fallback for cross-tab\n // broadcasts and cases where the transport didn't handle the resume.\n\n return () => {\n agent.removeEventListener(\"message\", onAgentMessage);\n // Clear active stream state on cleanup to prevent memory leak\n activeStreamRef.current = null;\n };\n }, [\n agent,\n setMessages,\n resume,\n flushActiveStreamToMessages,\n customTransport\n ]);\n\n // ── DEPRECATED: addToolResult wrapper with confirmation batching ────\n // This wrapper is deprecated. Use addToolOutput or addToolApprovalResponse instead.\n const addToolResultAndSendMessage: typeof addToolResult = async (args) => {\n const { toolCallId } = args;\n const toolName = \"tool\" in args ? args.tool : \"\";\n const output = \"output\" in args ? args.output : undefined;\n\n // Send tool result to server (server is source of truth)\n // Include flag to tell server whether to auto-continue\n agentRef.current.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_TOOL_RESULT,\n toolCallId,\n toolName,\n output,\n autoContinue: autoContinueAfterToolResult,\n clientTools: toolsRef.current\n ? extractClientToolSchemas(toolsRef.current)\n : undefined\n })\n );\n\n setClientToolResults((prev) => new Map(prev).set(toolCallId, output));\n\n // Call AI SDK's addToolResult for local state update (non-blocking)\n // We don't await this since clientToolResults provides immediate UI feedback\n addToolResult(args);\n\n if (autoContinueAfterToolResult) {\n startToolContinuation();\n }\n\n // If server auto-continuation is disabled, client needs to trigger continuation\n if (!autoContinueAfterToolResult) {\n // Use legacy behavior: batch confirmations or send immediately\n if (!autoSendAfterAllConfirmationsResolved) {\n // Always send immediately\n sendMessage();\n return;\n }\n\n // Wait for all confirmations before sending\n const pending = pendingConfirmationsRef.current?.toolCallIds;\n if (!pending) {\n sendMessage();\n return;\n }\n\n const wasLast = pending.size === 1 && pending.has(toolCallId);\n if (pending.has(toolCallId)) {\n pending.delete(toolCallId);\n }\n\n if (wasLast || pending.size === 0) {\n sendMessage();\n }\n }\n // If autoContinueAfterToolResult is true, server handles continuation\n };\n\n // Wrapper that sends tool approval to server before updating local state.\n // This prevents duplicate messages by ensuring server updates the message\n // in place with the existing ID, rather than relying on ID resolution\n // when sendMessage() is called later.\n const addToolApprovalResponseAndNotifyServer: typeof addToolApprovalResponse =\n (args) => {\n const { id: approvalId, approved } = args;\n\n // Find the toolCallId from the approval ID\n // The approval ID is stored on the tool part's approval.id field\n let toolCallId: string | undefined;\n for (const msg of messagesRef.current) {\n for (const part of msg.parts) {\n if (\n \"toolCallId\" in part &&\n \"approval\" in part &&\n (part.approval as { id?: string })?.id === approvalId\n ) {\n toolCallId = part.toolCallId as string;\n break;\n }\n }\n if (toolCallId) break;\n }\n\n if (toolCallId) {\n // Send approval to server first (server updates message in place)\n sendToolApprovalToServer(toolCallId, approved);\n } else {\n console.warn(\n `[useAgentChat] addToolApprovalResponse: Could not find toolCallId for approval ID \"${approvalId}\". ` +\n \"Server will not be notified, which may cause duplicate messages.\"\n );\n }\n\n // Call AI SDK's addToolApprovalResponse for local state update\n addToolApprovalResponse(args);\n };\n\n // Fix for issue #728: Merge client-side tool results with messages\n // so tool parts show output-available immediately after execution\n const messagesWithToolResults = useMemo(() => {\n if (clientToolResults.size === 0) {\n return chatMessages;\n }\n return chatMessages.map((msg) => ({\n ...msg,\n parts: msg.parts.map((p) => {\n if (\n !(\"toolCallId\" in p) ||\n !(\"state\" in p) ||\n p.state !== \"input-available\" ||\n !clientToolResults.has(p.toolCallId)\n ) {\n return p;\n }\n return {\n ...p,\n state: \"output-available\" as const,\n output: clientToolResults.get(p.toolCallId)\n };\n })\n })) as ChatMessage[];\n }, [chatMessages, clientToolResults]);\n\n // Cleanup stale entries from clientToolResults when messages change\n // to prevent memory leak in long conversations.\n // Note: We intentionally exclude clientToolResults from deps to avoid infinite loops.\n // The functional update form gives us access to the previous state.\n useEffect(() => {\n // Collect all current toolCallIds from messages\n const currentToolCallIds = new Set<string>();\n for (const msg of chatMessages) {\n for (const part of msg.parts) {\n if (\"toolCallId\" in part && part.toolCallId) {\n currentToolCallIds.add(part.toolCallId);\n }\n }\n }\n\n // Use functional update to check and clean stale entries atomically\n setClientToolResults((prev) => {\n if (prev.size === 0) return prev;\n\n // Check if any entries are stale\n let hasStaleEntries = false;\n for (const toolCallId of prev.keys()) {\n if (!currentToolCallIds.has(toolCallId)) {\n hasStaleEntries = true;\n break;\n }\n }\n\n // Only create new Map if there are stale entries to remove\n if (!hasStaleEntries) return prev;\n\n const newMap = new Map<string, unknown>();\n for (const [id, output] of prev) {\n if (currentToolCallIds.has(id)) {\n newMap.set(id, output);\n }\n }\n return newMap;\n });\n\n // Also cleanup processedToolCalls to prevent issues in long conversations\n for (const toolCallId of processedToolCalls.current) {\n if (!currentToolCallIds.has(toolCallId)) {\n processedToolCalls.current.delete(toolCallId);\n }\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [chatMessages]);\n\n // Create addToolOutput function for external use\n const addToolOutput = useCallback(\n (opts: AddToolOutputOptions) => {\n const toolName = opts.toolName ?? \"\";\n sendToolOutputToServer(\n opts.toolCallId,\n toolName,\n opts.output,\n opts.state,\n opts.errorText\n );\n\n // Update local state via AI SDK\n addToolResult({\n tool: toolName,\n toolCallId: opts.toolCallId,\n output:\n opts.state === \"output-error\"\n ? (opts.errorText ?? \"Tool execution denied by user\")\n : opts.output\n });\n },\n [sendToolOutputToServer, addToolResult]\n );\n\n return {\n ...useChatHelpers,\n messages: messagesWithToolResults,\n /**\n * Provide output for a tool call. Use this for tools that require user interaction\n * or client-side execution.\n */\n addToolOutput,\n /**\n * @deprecated Use `addToolOutput` instead.\n */\n addToolResult: addToolResultAndSendMessage,\n /**\n * Respond to a tool approval request. Use this for tools with `needsApproval`.\n * This wrapper notifies the server before updating local state, preventing\n * duplicate messages when sendMessage() is called afterward.\n */\n addToolApprovalResponse: addToolApprovalResponseAndNotifyServer,\n clearHistory: () => {\n setMessages([]);\n setClientToolResults(new Map());\n resumingToolContinuationRef.current = false;\n processedToolCalls.current.clear();\n agent.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_CHAT_CLEAR\n })\n );\n },\n setMessages: (messagesOrUpdater: Parameters<typeof setMessages>[0]) => {\n // Resolve functional updaters to get the actual messages array\n // before syncing to server. Without this, updater functions would\n // send an empty array and wipe server-side messages.\n let resolvedMessages: ChatMessage[];\n if (typeof messagesOrUpdater === \"function\") {\n resolvedMessages = messagesOrUpdater(messagesRef.current);\n } else {\n resolvedMessages = messagesOrUpdater;\n }\n\n setMessages(resolvedMessages);\n agent.send(\n JSON.stringify({\n messages: resolvedM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,OAAO,sBAAsB,WAC/B,oBAAmB,kBAAkB,YAAY,QAAQ;OAEzD,oBAAmB;AAGrB,eAAY,iBAAiB;AAC7B,SAAM,KACJ,KAAK,UAAU;IACb,UAAU;IACV,MAAM,YAAY;IACnB,CAAC,CACH;;EAEJ"}
1
+ {"version":3,"file":"react.js","names":[],"sources":["../src/ws-chat-transport.ts","../src/react.tsx"],"sourcesContent":["/**\n * WebSocket-based ChatTransport for useAgentChat.\n *\n * Replaces the aiFetch + DefaultChatTransport indirection with a direct\n * WebSocket implementation that speaks the CF_AGENT protocol natively.\n *\n * Data flow (old): WS → aiFetch fake Response → DefaultChatTransport → useChat\n * Data flow (new): WS → WebSocketChatTransport → useChat\n */\n\nimport type { ChatTransport, UIMessage, UIMessageChunk } from \"ai\";\nimport { nanoid } from \"nanoid\";\nimport { MessageType, type OutgoingMessage } from \"./types\";\n\n/**\n * Agent-like interface for sending/receiving WebSocket messages.\n * Matches the shape returned by useAgent from agents/react.\n */\nexport interface AgentConnection {\n send: (data: string) => void;\n addEventListener: (\n type: string,\n listener: (event: MessageEvent) => void,\n options?: { signal?: AbortSignal }\n ) => void;\n removeEventListener: (\n type: string,\n listener: (event: MessageEvent) => void\n ) => void;\n}\n\nexport type WebSocketChatTransportOptions<\n ChatMessage extends UIMessage = UIMessage\n> = {\n /** The agent connection from useAgent */\n agent: AgentConnection;\n /**\n * Callback to prepare the request body before sending.\n * Can add custom headers, body fields, or credentials.\n */\n prepareBody?: (options: {\n messages: ChatMessage[];\n trigger: \"submit-message\" | \"regenerate-message\";\n messageId?: string;\n }) => Promise<Record<string, unknown>> | Record<string, unknown>;\n /**\n * Optional set to track active request IDs.\n * IDs are added when a request starts and removed when it completes.\n * Used by the onAgentMessage handler to skip messages already handled by the transport.\n */\n activeRequestIds?: Set<string>;\n};\n\n/**\n * ChatTransport that sends messages over WebSocket and returns a\n * ReadableStream<UIMessageChunk> that the AI SDK's useChat consumes directly.\n * No fake fetch, no Response reconstruction, no double SSE parsing.\n */\nexport class WebSocketChatTransport<\n ChatMessage extends UIMessage = UIMessage\n> implements ChatTransport<ChatMessage> {\n agent: AgentConnection;\n private prepareBody?: WebSocketChatTransportOptions<ChatMessage>[\"prepareBody\"];\n private activeRequestIds?: Set<string>;\n\n // Pending resume resolver — set by reconnectToStream, called by\n // handleStreamResuming when onAgentMessage sees CF_AGENT_STREAM_RESUMING.\n private _resumeResolver: ((data: { id: string }) => void) | null = null;\n // Pending \"no stream\" resolver — called by handleStreamResumeNone\n // when onAgentMessage sees CF_AGENT_STREAM_RESUME_NONE.\n private _resumeNoneResolver: (() => void) | null = null;\n // Set when a client-side tool result/approval is expected to trigger\n // a new continuation stream. In this mode reconnectToStream() returns\n // a deferred ReadableStream immediately so AI SDK status can transition\n // to \"submitted\" before the server starts streaming.\n private _expectToolContinuation = false;\n\n constructor(options: WebSocketChatTransportOptions<ChatMessage>) {\n this.agent = options.agent;\n this.prepareBody = options.prepareBody;\n this.activeRequestIds = options.activeRequestIds;\n }\n\n /**\n * Mark that the next reconnectToStream() call should attach to a\n * server-initiated tool continuation rather than a page-load resume.\n */\n expectToolContinuation() {\n this._expectToolContinuation = true;\n }\n\n /**\n * True when the transport is waiting for a resume handshake.\n */\n isAwaitingResume(): boolean {\n return this._resumeResolver !== null || this._resumeNoneResolver !== null;\n }\n\n /**\n * Called by onAgentMessage when it receives CF_AGENT_STREAM_RESUMING.\n * If reconnectToStream is waiting, this handles the resume handshake\n * (ACK + stream creation) and returns true. Otherwise returns false\n * so the caller can use its own fallback path.\n */\n handleStreamResuming(data: { id: string }): boolean {\n if (!this._resumeResolver) return false;\n this._resumeResolver(data);\n return true;\n }\n\n /**\n * Called by onAgentMessage when it receives CF_AGENT_STREAM_RESUME_NONE.\n * If reconnectToStream is waiting, resolves the promise with null\n * immediately (no 5-second timeout). Returns true if handled.\n */\n handleStreamResumeNone(): boolean {\n if (!this._resumeNoneResolver) return false;\n this._resumeNoneResolver();\n return true;\n }\n\n async sendMessages(options: {\n chatId: string;\n messages: ChatMessage[];\n abortSignal: AbortSignal | undefined;\n trigger: \"submit-message\" | \"regenerate-message\";\n messageId?: string;\n body?: object;\n headers?: Record<string, string> | Headers;\n metadata?: unknown;\n }): Promise<ReadableStream<UIMessageChunk>> {\n const requestId = nanoid(8);\n const abortController = new AbortController();\n let completed = false;\n\n // Build the request body\n let extraBody: Record<string, unknown> = {};\n if (this.prepareBody) {\n extraBody = await this.prepareBody({\n messages: options.messages,\n trigger: options.trigger,\n messageId: options.messageId\n });\n }\n if (options.body) {\n extraBody = {\n ...extraBody,\n ...(options.body as Record<string, unknown>)\n };\n }\n\n const bodyPayload = JSON.stringify({\n messages: options.messages,\n trigger: options.trigger,\n ...extraBody\n });\n\n // Track this request so the onAgentMessage handler skips it\n this.activeRequestIds?.add(requestId);\n\n // Create a ReadableStream<UIMessageChunk> that emits parsed chunks\n // as they arrive over the WebSocket\n const agent = this.agent;\n const activeIds = this.activeRequestIds;\n\n // Single cleanup helper — every terminal path (done, error, abort)\n // goes through here exactly once.\n // keepId: when true, do NOT remove requestId from activeIds. Used by\n // onAbort so that onAgentMessage continues to skip in-flight chunks\n // and the server's final done:true broadcast until cleanup happens there.\n const finish = (action: () => void, keepId = false) => {\n if (completed) return;\n completed = true;\n try {\n action();\n } catch {\n // Stream may already be closed\n }\n if (!keepId) {\n activeIds?.delete(requestId);\n }\n abortController.abort();\n };\n\n const abortError = new Error(\"Aborted\");\n abortError.name = \"AbortError\";\n\n // Abort handler: send cancel to server, then terminate the stream.\n // Used by both the caller's abortSignal and stream.cancel().\n // keepId=true: keep requestId in activeIds so onAgentMessage skips any\n // in-flight chunks the server broadcasts before its done:true signal.\n // The ID is removed by onAgentMessage when done:true is received.\n const onAbort = () => {\n if (completed) return;\n try {\n agent.send(\n JSON.stringify({\n id: requestId,\n type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL\n })\n );\n } catch {\n // Ignore failures (e.g. agent already disconnected)\n }\n finish(() => streamController.error(abortError), true);\n };\n\n // streamController is assigned synchronously by start(), so it is\n // always available by the time onAbort or onMessage can fire.\n let streamController!: ReadableStreamDefaultController<UIMessageChunk>;\n\n const stream = new ReadableStream<UIMessageChunk>({\n start(controller) {\n streamController = controller;\n\n const onMessage = (event: MessageEvent) => {\n try {\n const data = JSON.parse(\n event.data as string\n ) as OutgoingMessage<ChatMessage>;\n\n if (data.type !== MessageType.CF_AGENT_USE_CHAT_RESPONSE) return;\n if (data.id !== requestId) return;\n\n if (data.error) {\n finish(() =>\n controller.error(new Error(data.body || \"Stream error\"))\n );\n return;\n }\n\n // Parse the body as UIMessageChunk and enqueue\n if (data.body?.trim()) {\n try {\n const chunk = JSON.parse(data.body) as UIMessageChunk;\n controller.enqueue(chunk);\n } catch {\n // Skip malformed chunk bodies\n }\n }\n\n if (data.done) {\n finish(() => controller.close());\n }\n } catch {\n // Ignore non-JSON messages\n }\n };\n\n agent.addEventListener(\"message\", onMessage, {\n signal: abortController.signal\n });\n },\n cancel() {\n onAbort();\n }\n });\n\n // Handle abort from the caller\n if (options.abortSignal) {\n options.abortSignal.addEventListener(\"abort\", onAbort, { once: true });\n if (options.abortSignal.aborted) onAbort();\n }\n\n // Send the request over WebSocket\n agent.send(\n JSON.stringify({\n id: requestId,\n init: {\n method: \"POST\",\n body: bodyPayload\n },\n type: MessageType.CF_AGENT_USE_CHAT_REQUEST\n })\n );\n\n return stream;\n }\n\n async reconnectToStream(_options: {\n chatId: string;\n }): Promise<ReadableStream<UIMessageChunk> | null> {\n if (this._expectToolContinuation) {\n this._expectToolContinuation = false;\n return this._createToolContinuationStream();\n }\n\n // Detect whether the server has an active stream for this chat.\n // Instead of registering our own addEventListener listener (which\n // races with onAgentMessage), we set _resumeResolver so that\n // onAgentMessage can call handleStreamResuming() synchronously\n // when it sees CF_AGENT_STREAM_RESUMING — eliminating the race.\n const activeIds = this.activeRequestIds;\n\n return new Promise<ReadableStream<UIMessageChunk> | null>((resolve) => {\n let resolved = false;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n\n const done = (value: ReadableStream<UIMessageChunk> | null) => {\n if (resolved) return;\n resolved = true;\n this._resumeResolver = null;\n this._resumeNoneResolver = null;\n if (timeout) clearTimeout(timeout);\n resolve(value);\n };\n\n // Set the \"no stream\" resolver that handleStreamResumeNone() will call.\n // When onAgentMessage sees CF_AGENT_STREAM_RESUME_NONE, it calls\n // handleStreamResumeNone() which resolves immediately with null.\n this._resumeNoneResolver = () => done(null);\n\n // Set the resolver that handleStreamResuming() will call.\n // When onAgentMessage sees CF_AGENT_STREAM_RESUMING, it calls\n // handleStreamResuming() which invokes this callback.\n this._resumeResolver = (data: { id: string }) => {\n const requestId = data.id;\n\n // Track this request so onAgentMessage skips subsequent chunks\n activeIds?.add(requestId);\n\n // Send ACK to server via the latest agent (the socket may\n // have been replaced since reconnectToStream was called).\n this.agent.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_STREAM_RESUME_ACK,\n id: requestId\n })\n );\n\n // Return a ReadableStream fed by the replayed + live chunks\n done(this._createResumeStream(requestId));\n };\n\n // Send the resume request. PartySocket queues sends when\n // the socket isn't open yet and flushes on connect, so\n // this works regardless of current readyState.\n try {\n this.agent.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_STREAM_RESUME_REQUEST\n })\n );\n } catch {\n // WebSocket may already be closed\n }\n\n // Safety-net timeout: if the WebSocket never connects or the\n // server is unreachable, resolve null. Under normal operation\n // the server responds with STREAM_RESUMING or STREAM_RESUME_NONE\n // well before this fires.\n timeout = setTimeout(() => done(null), 5000);\n });\n }\n\n /**\n * Creates a deferred ReadableStream for client-side tool continuations.\n * The stream is returned immediately so AI SDK status becomes \"submitted\"\n * right after addToolOutput()/addToolApprovalResponse(), then it waits for\n * the server to announce the continuation via STREAM_RESUMING.\n */\n private _createToolContinuationStream(): ReadableStream<UIMessageChunk> {\n const agent = this.agent;\n const activeIds = this.activeRequestIds;\n const streamController = new AbortController();\n let completed = false;\n let requestId: string | null = null;\n\n const clearHandshakeResolvers = (\n resumeResolver?: ((data: { id: string }) => void) | null,\n resumeNoneResolver?: (() => void) | null\n ) => {\n if (resumeResolver === undefined && resumeNoneResolver === undefined) {\n this._resumeResolver = null;\n this._resumeNoneResolver = null;\n return;\n }\n\n if (resumeResolver && this._resumeResolver === resumeResolver) {\n this._resumeResolver = null;\n }\n if (\n resumeNoneResolver &&\n this._resumeNoneResolver === resumeNoneResolver\n ) {\n this._resumeNoneResolver = null;\n }\n };\n\n const finish = (\n action: () => void,\n resumeResolver?: ((data: { id: string }) => void) | null,\n resumeNoneResolver?: (() => void) | null\n ) => {\n if (completed) return;\n completed = true;\n clearHandshakeResolvers(resumeResolver, resumeNoneResolver);\n try {\n action();\n } catch {\n // Stream may already be closed\n }\n if (requestId) {\n activeIds?.delete(requestId);\n }\n streamController.abort();\n };\n\n const transport = this;\n\n return new ReadableStream<UIMessageChunk>({\n start(controller) {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n\n const onResumeNone = () => {\n if (timeout) clearTimeout(timeout);\n finish(() => controller.close(), onResume, onResumeNone);\n };\n\n const onResume = (data: { id: string }) => {\n if (requestId) return;\n\n requestId = data.id;\n activeIds?.add(requestId);\n clearHandshakeResolvers(onResume, onResumeNone);\n if (timeout) clearTimeout(timeout);\n\n agent.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_STREAM_RESUME_ACK,\n id: requestId\n })\n );\n };\n\n timeout = setTimeout(\n () => finish(() => controller.close(), onResume, onResumeNone),\n 5000\n );\n\n transport._resumeResolver = onResume;\n transport._resumeNoneResolver = onResumeNone;\n const onMessage = (event: MessageEvent) => {\n try {\n const data = JSON.parse(\n event.data as string\n ) as OutgoingMessage<UIMessage>;\n\n if (\n data.type !== MessageType.CF_AGENT_USE_CHAT_RESPONSE ||\n requestId == null ||\n data.id !== requestId\n ) {\n return;\n }\n\n if (data.error) {\n finish(\n () => controller.error(new Error(data.body || \"Stream error\")),\n onResume,\n onResumeNone\n );\n return;\n }\n\n if (data.body?.trim()) {\n try {\n const chunk = JSON.parse(data.body) as UIMessageChunk;\n controller.enqueue(chunk);\n } catch {\n // Skip malformed chunk bodies\n }\n }\n\n if (data.done) {\n finish(() => controller.close(), onResume, onResumeNone);\n }\n } catch {\n // Ignore non-JSON messages\n }\n };\n\n agent.addEventListener(\"message\", onMessage, {\n signal: streamController.signal\n });\n\n try {\n agent.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_STREAM_RESUME_REQUEST\n })\n );\n } catch {\n finish(() => controller.close());\n }\n },\n cancel() {\n finish(() => {});\n }\n });\n }\n\n /**\n * Creates a ReadableStream that receives resumed stream chunks\n * and forwards them to useChat as UIMessageChunk objects.\n */\n private _createResumeStream(\n requestId: string\n ): ReadableStream<UIMessageChunk> {\n // Read agent at resolve time (not when reconnectToStream was called)\n // so chunk listener attaches to the latest socket after _pk changes.\n const agent = this.agent;\n const activeIds = this.activeRequestIds;\n const chunkController = new AbortController();\n let completed = false;\n\n const finish = (action: () => void) => {\n if (completed) return;\n completed = true;\n try {\n action();\n } catch {\n // Stream may already be closed\n }\n activeIds?.delete(requestId);\n chunkController.abort();\n };\n\n return new ReadableStream<UIMessageChunk>({\n start(controller) {\n const onMessage = (event: MessageEvent) => {\n try {\n const data = JSON.parse(\n event.data as string\n ) as OutgoingMessage<UIMessage>;\n\n if (data.type !== MessageType.CF_AGENT_USE_CHAT_RESPONSE) return;\n if (data.id !== requestId) return;\n\n if (data.error) {\n finish(() =>\n controller.error(new Error(data.body || \"Stream error\"))\n );\n return;\n }\n\n // Parse and enqueue the chunk\n if (data.body?.trim()) {\n try {\n const chunk = JSON.parse(data.body) as UIMessageChunk;\n controller.enqueue(chunk);\n } catch {\n // Skip malformed chunk bodies\n }\n }\n\n if (data.done) {\n finish(() => controller.close());\n }\n } catch {\n // Ignore non-JSON messages\n }\n };\n\n agent.addEventListener(\"message\", onMessage, {\n signal: chunkController.signal\n });\n },\n cancel() {\n finish(() => {});\n }\n });\n }\n}\n","import { useChat, type UseChatOptions } from \"@ai-sdk/react\";\nimport { getToolName, isToolUIPart } from \"ai\";\nimport type {\n ChatInit,\n JSONSchema7,\n Tool,\n UIMessage as Message,\n UIMessage\n} from \"ai\";\nimport { nanoid } from \"nanoid\";\nimport { use, useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { OutgoingMessage } from \"./types\";\nimport { MessageType } from \"./types\";\nimport { applyChunkToParts, type MessageParts } from \"./message-builder\";\nimport { WebSocketChatTransport } from \"./ws-chat-transport\";\nimport type { useAgent } from \"agents/react\";\n\n/**\n * One-shot deprecation warnings (warns once per key per session).\n */\nconst _deprecationWarnings = new Set<string>();\nfunction warnDeprecated(id: string, message: string) {\n if (!_deprecationWarnings.has(id)) {\n _deprecationWarnings.add(id);\n console.warn(`[@cloudflare/ai-chat] Deprecated: ${message}`);\n }\n}\n\n// ── DEPRECATED TYPES AND FUNCTIONS ──────────────────────────────────\n// Everything in this section is deprecated and will be removed in the\n// next major version. Use server-side tools with tool() from \"ai\" and\n// the onToolCall callback in useAgentChat instead.\n\n/**\n * JSON Schema type for tool parameters.\n * Re-exported from the AI SDK for convenience.\n * @deprecated Import JSONSchema7 directly from \"ai\" instead. Will be removed in the next major version.\n */\nexport type JSONSchemaType = JSONSchema7;\n\n/**\n * Definition for a tool that can be executed on the client.\n * Tools with an `execute` function are automatically registered with the server.\n *\n * **For most apps**, define tools on the server with `tool()` from `\"ai\"` —\n * you get full Zod type safety and simpler code. Use `onToolCall` in\n * `useAgentChat` for tools that need browser-side execution.\n *\n * **For SDKs and platforms** where the tool surface is determined dynamically\n * by the embedding application at runtime, this type lets the client register\n * tools the server does not know about at deploy time.\n *\n * Note: Uses `parameters` (JSONSchema7) because client tools must be\n * serializable for the wire format. Zod schemas cannot be serialized.\n */\nexport type AITool<Input = unknown, Output = unknown> = {\n /** Human-readable description of what the tool does */\n description?: Tool[\"description\"];\n /** JSON Schema defining the tool's input parameters */\n parameters?: JSONSchema7;\n /**\n * @deprecated Use `parameters` instead. Will be removed in a future version.\n */\n inputSchema?: JSONSchema7;\n /**\n * Function to execute the tool on the client.\n * If provided, the tool schema is automatically sent to the server.\n */\n execute?: (input: Input) => Output | Promise<Output>;\n};\n\n/**\n * Schema for a client tool sent to the server.\n * This is the wire format — what gets sent in the request body.\n * Must match the server-side ClientToolSchema type.\n *\n * Most apps do not need this directly — it is used internally when the\n * `tools` option on `useAgentChat` contains tools with `execute` functions.\n */\nexport type ClientToolSchema = {\n /** Unique name for the tool */\n name: string;\n /** Human-readable description of what the tool does */\n description?: Tool[\"description\"];\n /** JSON Schema defining the tool's input parameters */\n parameters?: JSONSchema7;\n};\n\n/**\n * Extracts tool schemas from tools that have client-side execute functions.\n * These schemas are automatically sent to the server with each request.\n *\n * Called internally by `useAgentChat` when `tools` are provided.\n * Most apps do not need to call this directly.\n *\n * @param tools - Record of tool name to tool definition\n * @returns Array of tool schemas to send to server, or undefined if none\n */\nexport function extractClientToolSchemas(\n tools?: Record<string, AITool<unknown, unknown>>\n): ClientToolSchema[] | undefined {\n if (!tools) return undefined;\n\n const schemas: ClientToolSchema[] = Object.entries(tools)\n .filter(([_, tool]) => tool.execute) // Only tools with client-side execute\n .map(([name, tool]) => {\n if (tool.inputSchema && !tool.parameters) {\n console.warn(\n `[useAgentChat] Tool \"${name}\" uses deprecated 'inputSchema'. Please migrate to 'parameters'.`\n );\n }\n return {\n name,\n description: tool.description,\n parameters: tool.parameters ?? tool.inputSchema\n };\n });\n\n return schemas.length > 0 ? schemas : undefined;\n}\n\n// ── END DEPRECATED TYPES AND FUNCTIONS ─────────────────────────────\n\ntype GetInitialMessagesOptions = {\n agent: string;\n name: string;\n url: string;\n};\n\n// v5 useChat parameters\ntype UseChatParams<M extends UIMessage = UIMessage> = ChatInit<M> &\n UseChatOptions<M>;\n\n/**\n * Options for preparing the send messages request.\n * Used by prepareSendMessagesRequest callback.\n */\nexport type PrepareSendMessagesRequestOptions<\n ChatMessage extends UIMessage = UIMessage\n> = {\n /** The chat ID */\n id: string;\n /** Messages to send */\n messages: ChatMessage[];\n /** What triggered this request */\n trigger: \"submit-message\" | \"regenerate-message\";\n /** ID of the message being sent (if applicable) */\n messageId?: string;\n /** Request metadata */\n requestMetadata?: unknown;\n /** Current body (if any) */\n body?: Record<string, unknown>;\n /** Current credentials (if any) */\n credentials?: RequestCredentials;\n /** Current headers (if any) */\n headers?: HeadersInit;\n /** API endpoint */\n api?: string;\n};\n\n/**\n * Return type for prepareSendMessagesRequest callback.\n * Allows customizing headers, body, and credentials for each request.\n * All fields are optional; only specify what you need to customize.\n */\nexport type PrepareSendMessagesRequestResult = {\n /** Custom headers to send with the request */\n headers?: HeadersInit;\n /** Custom body data to merge with the request */\n body?: Record<string, unknown>;\n /** Custom credentials option */\n credentials?: RequestCredentials;\n /** Custom API endpoint */\n api?: string;\n};\n\n/**\n * Options for addToolOutput function\n */\ntype AddToolOutputOptions = {\n /** The ID of the tool call to provide output for */\n toolCallId: string;\n /** The name of the tool (optional, for type safety) */\n toolName?: string;\n /** The output to provide */\n output?: unknown;\n /** Override the tool part state (e.g. \"output-error\" for custom denial) */\n state?: \"output-available\" | \"output-error\";\n /** Error message when state is \"output-error\" */\n errorText?: string;\n};\n\n/**\n * Callback for handling client-side tool execution.\n * Called when a tool without server-side execute is invoked.\n */\nexport type OnToolCallCallback = (options: {\n /** The tool call that needs to be handled */\n toolCall: {\n toolCallId: string;\n toolName: string;\n input: unknown;\n };\n /** Function to provide the tool output (or signal an error/denial) */\n addToolOutput: (options: Omit<AddToolOutputOptions, \"toolName\">) => void;\n}) => void | Promise<void>;\n\n/**\n * Options for the useAgentChat hook\n */\ntype UseAgentChatOptions<\n State,\n ChatMessage extends UIMessage = UIMessage\n> = Omit<UseChatParams<ChatMessage>, \"fetch\" | \"onToolCall\"> & {\n /** Agent connection from useAgent */\n agent: ReturnType<typeof useAgent<State>>;\n getInitialMessages?:\n | undefined\n | null\n | ((options: GetInitialMessagesOptions) => Promise<ChatMessage[]>);\n /** Request credentials */\n credentials?: RequestCredentials;\n /** Request headers */\n headers?: HeadersInit;\n /**\n * Callback for handling client-side tool execution.\n * Called when a tool without server-side `execute` is invoked by the LLM.\n *\n * Use this for:\n * - Tools that need browser APIs (geolocation, camera, etc.)\n * - Tools that need user interaction before providing a result\n * - Tools requiring approval before execution\n *\n * @example\n * ```typescript\n * onToolCall: async ({ toolCall, addToolOutput }) => {\n * if (toolCall.toolName === 'getLocation') {\n * const position = await navigator.geolocation.getCurrentPosition();\n * addToolOutput({\n * toolCallId: toolCall.toolCallId,\n * output: { lat: position.coords.latitude, lng: position.coords.longitude }\n * });\n * }\n * }\n * ```\n */\n onToolCall?: OnToolCallCallback;\n /**\n * @deprecated Use `onToolCall` callback instead for automatic tool execution.\n * @description Whether to automatically resolve tool calls that do not require human interaction.\n * @experimental\n */\n experimental_automaticToolResolution?: boolean;\n /**\n * Tools that can be executed on the client. Tool schemas are automatically\n * sent to the server and tool calls are routed back for client execution.\n *\n * **For most apps**, define tools on the server with `tool()` from `\"ai\"`\n * and handle client-side execution via `onToolCall`. This gives you full\n * Zod type safety and keeps tool definitions in one place.\n *\n * **For SDKs and platforms** where tools are defined dynamically by the\n * embedding application at runtime, this option lets the client register\n * tools the server does not know about at deploy time.\n */\n tools?: Record<string, AITool<unknown, unknown>>;\n /**\n * @deprecated Use `needsApproval` on server-side tools instead.\n * @description Manual override for tools requiring confirmation.\n * If not provided, will auto-detect from tools object (tools without execute require confirmation).\n */\n toolsRequiringConfirmation?: string[];\n /**\n * When true (default), the server automatically continues the conversation\n * after receiving client-side tool results or approvals, similar to how\n * server-executed tools work with maxSteps in streamText. The continuation\n * is merged into the same assistant message.\n *\n * When false, the client must call sendMessage() after tool results\n * to continue the conversation, which creates a new assistant message.\n *\n * @default true\n */\n autoContinueAfterToolResult?: boolean;\n /**\n * @deprecated Use `sendAutomaticallyWhen` from AI SDK instead.\n *\n * When true (default), automatically sends the next message only after\n * all pending confirmation-required tool calls have been resolved.\n * When false, sends immediately after each tool result.\n *\n * Only applies when `autoContinueAfterToolResult` is false.\n *\n * @default true\n */\n autoSendAfterAllConfirmationsResolved?: boolean;\n /**\n * Set to false to disable automatic stream resumption.\n * @default true\n */\n resume?: boolean;\n /**\n * Custom data to include in every chat request body.\n * Accepts a static object or a function that returns one (for dynamic values).\n * These fields are available in `onChatMessage` via `options.body`.\n *\n * @example\n * ```typescript\n * // Static\n * body: { timezone: \"America/New_York\", userId: \"abc\" }\n *\n * // Dynamic (called on each send)\n * body: () => ({ token: getAuthToken(), timestamp: Date.now() })\n * ```\n */\n body?:\n | Record<string, unknown>\n | (() => Record<string, unknown> | Promise<Record<string, unknown>>);\n /**\n * Callback to customize the request before sending messages.\n * For most cases, use the `body` option instead.\n * Use this for advanced scenarios that need access to the messages or trigger type.\n *\n * Note: Client tool schemas are automatically sent when tools have `execute` functions.\n * This callback can add additional data alongside the auto-extracted schemas.\n */\n prepareSendMessagesRequest?: (\n options: PrepareSendMessagesRequestOptions<ChatMessage>\n ) =>\n | PrepareSendMessagesRequestResult\n | Promise<PrepareSendMessagesRequestResult>;\n};\n\n/**\n * Module-level cache for initial message fetches. Intentionally shared across\n * all useAgentChat instances to deduplicate requests during React Strict Mode\n * double-renders and re-renders. Cache keys include the agent URL, agent type,\n * and thread name to prevent cross-agent collisions.\n */\nconst requestCache = new Map<string, Promise<Message[]>>();\n\n/**\n * React hook for building AI chat interfaces using an Agent\n * @param options Chat options including the agent connection\n * @returns Chat interface controls and state with added clearHistory method\n */\n/**\n * Automatically detects which tools require confirmation based on their configuration.\n * Tools require confirmation if they have no execute function AND are not server-executed.\n * @param tools - Record of tool name to tool definition\n * @returns Array of tool names that require confirmation\n *\n * @deprecated Use `needsApproval` on server-side tools instead.\n */\nexport function detectToolsRequiringConfirmation(\n tools?: Record<string, AITool<unknown, unknown>>\n): string[] {\n warnDeprecated(\n \"detectToolsRequiringConfirmation\",\n \"detectToolsRequiringConfirmation() is deprecated. Use needsApproval on server-side tools instead. Will be removed in the next major version.\"\n );\n if (!tools) return [];\n\n return Object.entries(tools)\n .filter(([_name, tool]) => !tool.execute)\n .map(([name]) => name);\n}\n\nexport function useAgentChat<\n State = unknown,\n ChatMessage extends UIMessage = UIMessage\n>(\n options: UseAgentChatOptions<State, ChatMessage>\n): Omit<ReturnType<typeof useChat<ChatMessage>>, \"addToolOutput\"> & {\n clearHistory: () => void;\n /**\n * Provide output for a tool call. Use this for tools that require user interaction\n * or client-side execution.\n */\n addToolOutput: (opts: AddToolOutputOptions) => void;\n} {\n const {\n agent,\n getInitialMessages,\n messages: optionsInitialMessages,\n onToolCall,\n onData,\n experimental_automaticToolResolution,\n tools,\n toolsRequiringConfirmation: manualToolsRequiringConfirmation,\n autoContinueAfterToolResult = true, // Server auto-continues after tool results/approvals\n autoSendAfterAllConfirmationsResolved = true, // Legacy option for client-side batching\n resume = true, // Enable stream resumption by default\n body: bodyOption,\n prepareSendMessagesRequest,\n ...rest\n } = options;\n\n // Emit deprecation warnings for deprecated options (once per session)\n if (manualToolsRequiringConfirmation) {\n warnDeprecated(\n \"useAgentChat.toolsRequiringConfirmation\",\n \"The 'toolsRequiringConfirmation' option is deprecated. Use needsApproval on server-side tools instead. Will be removed in the next major version.\"\n );\n }\n if (experimental_automaticToolResolution) {\n warnDeprecated(\n \"useAgentChat.experimental_automaticToolResolution\",\n \"The 'experimental_automaticToolResolution' option is deprecated. Use the onToolCall callback instead. Will be removed in the next major version.\"\n );\n }\n if (options.autoSendAfterAllConfirmationsResolved !== undefined) {\n warnDeprecated(\n \"useAgentChat.autoSendAfterAllConfirmationsResolved\",\n \"The 'autoSendAfterAllConfirmationsResolved' option is deprecated. Use sendAutomaticallyWhen from AI SDK instead. Will be removed in the next major version.\"\n );\n }\n\n // ── DEPRECATED: client-side tool confirmation ──────────────────────\n // This block will be removed when toolsRequiringConfirmation is removed.\n // Only call the deprecated function when deprecated options are actually used.\n const toolsRequiringConfirmation = useMemo(() => {\n if (manualToolsRequiringConfirmation) {\n return manualToolsRequiringConfirmation;\n }\n // Inline the logic from detectToolsRequiringConfirmation to avoid\n // emitting a deprecation warning when tools are provided via the\n // non-deprecated `tools` option.\n if (!tools) return [];\n return Object.entries(tools)\n .filter(([_name, tool]) => !tool.execute)\n .map(([name]) => name);\n }, [manualToolsRequiringConfirmation, tools]);\n\n // Keep refs to always point to the latest callbacks\n const onToolCallRef = useRef(onToolCall);\n onToolCallRef.current = onToolCall;\n const onDataRef = useRef(onData);\n onDataRef.current = onData;\n\n const agentUrl = new URL(\n `${\n // @ts-expect-error we're using a protected _url property that includes query params\n ((agent._url as string | null) || agent._pkurl)\n ?.replace(\"ws://\", \"http://\")\n .replace(\"wss://\", \"https://\")\n }`\n );\n\n agentUrl.searchParams.delete(\"_pk\");\n const agentUrlString = agentUrl.toString();\n\n // we need to include agent.name in cache key to prevent collisions during agent switching.\n // The URL may be stale between updateProperties() and reconnect(), but agent.name\n // is updated synchronously, so each thread gets its own cache entry\n const initialMessagesCacheKey = `${agentUrlString}|${agent.agent ?? \"\"}|${agent.name ?? \"\"}`;\n\n // Keep a ref to always point to the latest agent instance.\n // Updated synchronously during render (not in useEffect) so the\n // transport's agent ref is always current. The transport is a\n // singleton whose .agent is reassigned every render — if we used\n // useEffect the assignment would lag behind, causing the transport\n // to send through a stale/closed socket (issue #929).\n const agentRef = useRef(agent);\n agentRef.current = agent;\n\n async function defaultGetInitialMessagesFetch({\n url\n }: GetInitialMessagesOptions) {\n const getMessagesUrl = new URL(url);\n getMessagesUrl.pathname += \"/get-messages\";\n const response = await fetch(getMessagesUrl.toString(), {\n credentials: options.credentials,\n headers: options.headers\n });\n\n if (!response.ok) {\n console.warn(\n `Failed to fetch initial messages: ${response.status} ${response.statusText}`\n );\n return [];\n }\n\n const text = await response.text();\n if (!text.trim()) {\n return [];\n }\n\n try {\n return JSON.parse(text) as ChatMessage[];\n } catch (error) {\n console.warn(\"Failed to parse initial messages JSON:\", error);\n return [];\n }\n }\n\n const getInitialMessagesFetch =\n getInitialMessages || defaultGetInitialMessagesFetch;\n\n function doGetInitialMessages(\n getInitialMessagesOptions: GetInitialMessagesOptions,\n cacheKey: string\n ) {\n if (requestCache.has(cacheKey)) {\n return requestCache.get(cacheKey)! as Promise<ChatMessage[]>;\n }\n const promise = getInitialMessagesFetch(getInitialMessagesOptions);\n requestCache.set(cacheKey, promise);\n return promise;\n }\n\n const initialMessagesPromise =\n getInitialMessages === null\n ? null\n : doGetInitialMessages(\n {\n agent: agent.agent,\n name: agent.name,\n url: agentUrlString\n },\n initialMessagesCacheKey\n );\n const initialMessages = initialMessagesPromise\n ? use(initialMessagesPromise)\n : (optionsInitialMessages ?? []);\n\n useEffect(() => {\n if (!initialMessagesPromise) {\n return;\n }\n requestCache.set(initialMessagesCacheKey, initialMessagesPromise!);\n return () => {\n if (\n requestCache.get(initialMessagesCacheKey) === initialMessagesPromise\n ) {\n requestCache.delete(initialMessagesCacheKey);\n }\n };\n }, [initialMessagesCacheKey, initialMessagesPromise]);\n\n // Use synchronous ref updates to avoid race conditions between effect runs.\n // This ensures the ref always has the latest value before any effect reads it.\n const toolsRef = useRef(tools);\n toolsRef.current = tools;\n\n const prepareSendMessagesRequestRef = useRef(prepareSendMessagesRequest);\n prepareSendMessagesRequestRef.current = prepareSendMessagesRequest;\n\n const bodyOptionRef = useRef(bodyOption);\n bodyOptionRef.current = bodyOption;\n\n /**\n * Tracks request IDs initiated by this tab via the transport.\n * Used by onAgentMessage to skip messages already handled by the transport.\n */\n const localRequestIdsRef = useRef<Set<string>>(new Set());\n\n // WebSocket-based transport that speaks the CF_AGENT protocol natively.\n // Replaces the old aiFetch + DefaultChatTransport indirection.\n //\n // The transport is a true singleton (created once, never recreated) so\n // that the resolver set by reconnectToStream and the handleStreamResuming\n // call from onAgentMessage always operate on the SAME instance — even\n // when _pk changes (async queries, socket recreation) or React Strict\n // Mode double-mounts. The agent reference is updated every render so\n // sends always go through the latest socket.\n const customTransportRef = useRef<WebSocketChatTransport<ChatMessage> | null>(\n null\n );\n\n if (customTransportRef.current === null) {\n customTransportRef.current = new WebSocketChatTransport<ChatMessage>({\n agent: agentRef.current,\n activeRequestIds: localRequestIdsRef.current,\n prepareBody: async ({ messages: msgs, trigger, messageId }) => {\n // Start with the top-level body option (static or dynamic)\n let extraBody: Record<string, unknown> = {};\n const currentBody = bodyOptionRef.current;\n if (currentBody) {\n const resolved =\n typeof currentBody === \"function\"\n ? await currentBody()\n : currentBody;\n extraBody = { ...resolved };\n }\n\n // Extract schemas from deprecated client tools (if any)\n // Only extract client tool schemas when deprecated tools option is used\n if (toolsRef.current) {\n const clientToolSchemas = extractClientToolSchemas(toolsRef.current);\n if (clientToolSchemas) {\n extraBody.clientTools = clientToolSchemas;\n }\n }\n\n // Apply user's prepareSendMessagesRequest callback (overrides body option)\n if (prepareSendMessagesRequestRef.current) {\n const userResult = await prepareSendMessagesRequestRef.current({\n id: agentRef.current._pk,\n messages: msgs,\n trigger,\n messageId\n });\n if (userResult.body) {\n Object.assign(extraBody, userResult.body);\n }\n }\n\n return extraBody;\n }\n });\n }\n // Always point the transport at the latest socket so sends/listeners\n // go through the current connection after _pk changes.\n customTransportRef.current.agent = agentRef.current;\n const customTransport = customTransportRef.current;\n\n // Use a stable Chat ID that doesn't change when _pk changes.\n // The AI SDK recreates the Chat when `id` changes, which would\n // abandon any in-flight makeRequest (including resume) and the\n // resume effect wouldn't re-fire (deps are [resume, chatRef]).\n // Using the initial messages cache key (URL + agent + name) keeps\n // the Chat stable across socket recreations.\n const useChatHelpers = useChat<ChatMessage>({\n ...rest,\n onData,\n messages: initialMessages,\n transport: customTransport,\n id: initialMessagesCacheKey,\n // Pass resume so useChat calls transport.reconnectToStream().\n // This lets the AI SDK track status (\"streaming\") during resume.\n resume\n });\n\n // Destructure stable method references from useChatHelpers.\n // These are individually memoized by the AI SDK (via useCallback), so they're\n // safe to use in dependency arrays without causing re-renders. Using them\n // directly instead of `useChatHelpers.method` avoids the exhaustive-deps\n // warning about the unstable `useChatHelpers` object.\n const {\n messages: chatMessages,\n setMessages,\n addToolResult,\n addToolApprovalResponse,\n sendMessage,\n resumeStream\n } = useChatHelpers;\n\n const resumingToolContinuationRef = useRef(false);\n const startToolContinuation = useCallback(() => {\n if (!autoContinueAfterToolResult || resumingToolContinuationRef.current) {\n return;\n }\n\n resumingToolContinuationRef.current = true;\n customTransport.expectToolContinuation();\n\n void resumeStream().finally(() => {\n resumingToolContinuationRef.current = false;\n });\n }, [autoContinueAfterToolResult, customTransport, resumeStream]);\n\n const processedToolCalls = useRef(new Set<string>());\n const isResolvingToolsRef = useRef(false);\n // Counter to force the tool resolution effect to re-run after completing\n // a batch of tool calls. Without this, if new tool calls arrive while\n // isResolvingToolsRef is true (e.g. server auto-continuation), the effect\n // exits early and never retriggers because the ref reset doesn't cause\n // a re-render.\n const [toolResolutionTrigger, setToolResolutionTrigger] = useState(0);\n\n // Fix for issue #728: Track client-side tool results in local state\n // to ensure tool parts show output-available immediately after execution.\n const [clientToolResults, setClientToolResults] = useState<\n Map<string, unknown>\n >(new Map());\n\n // Ref to access current messages in callbacks without stale closures\n const messagesRef = useRef(chatMessages);\n messagesRef.current = chatMessages;\n\n // Calculate pending confirmations for the latest assistant message\n const lastMessage = chatMessages[chatMessages.length - 1];\n\n const pendingConfirmations = (() => {\n if (!lastMessage || lastMessage.role !== \"assistant\") {\n return { messageId: undefined, toolCallIds: new Set<string>() };\n }\n\n const pendingIds = new Set<string>();\n for (const part of lastMessage.parts ?? []) {\n if (\n isToolUIPart(part) &&\n part.state === \"input-available\" &&\n toolsRequiringConfirmation.includes(getToolName(part))\n ) {\n pendingIds.add(part.toolCallId);\n }\n }\n return { messageId: lastMessage.id, toolCallIds: pendingIds };\n })();\n\n const pendingConfirmationsRef = useRef(pendingConfirmations);\n pendingConfirmationsRef.current = pendingConfirmations;\n\n // ── DEPRECATED: automatic tool resolution effect ────────────────────\n // This entire useEffect is deprecated. Use onToolCall instead.\n useEffect(() => {\n if (!experimental_automaticToolResolution) {\n return;\n }\n\n // Prevent re-entry while async operations are in progress\n if (isResolvingToolsRef.current) {\n return;\n }\n\n const lastMsg = chatMessages[chatMessages.length - 1];\n if (!lastMsg || lastMsg.role !== \"assistant\") {\n return;\n }\n\n const toolCalls = lastMsg.parts.filter(\n (part) =>\n isToolUIPart(part) &&\n part.state === \"input-available\" &&\n !processedToolCalls.current.has(part.toolCallId)\n );\n\n if (toolCalls.length > 0) {\n // Capture tools synchronously before async work\n const currentTools = toolsRef.current;\n const toolCallsToResolve = toolCalls.filter(\n (part) =>\n isToolUIPart(part) &&\n !toolsRequiringConfirmation.includes(getToolName(part)) &&\n currentTools?.[getToolName(part)]?.execute\n );\n\n if (toolCallsToResolve.length > 0) {\n isResolvingToolsRef.current = true;\n\n (async () => {\n try {\n const toolResults: Array<{\n toolCallId: string;\n toolName: string;\n output: unknown;\n }> = [];\n\n for (const part of toolCallsToResolve) {\n if (isToolUIPart(part)) {\n let toolOutput: unknown = null;\n const toolName = getToolName(part);\n const tool = currentTools?.[toolName];\n\n if (tool?.execute && part.input !== undefined) {\n try {\n toolOutput = await tool.execute(part.input);\n } catch (error) {\n toolOutput = `Error executing tool: ${error instanceof Error ? error.message : String(error)}`;\n }\n }\n\n processedToolCalls.current.add(part.toolCallId);\n\n toolResults.push({\n toolCallId: part.toolCallId,\n toolName,\n output: toolOutput\n });\n }\n }\n\n if (toolResults.length > 0) {\n // Send tool results to server first (server is source of truth)\n const clientToolSchemas = extractClientToolSchemas(currentTools);\n for (const result of toolResults) {\n agentRef.current.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_TOOL_RESULT,\n toolCallId: result.toolCallId,\n toolName: result.toolName,\n output: result.output,\n autoContinue: autoContinueAfterToolResult,\n clientTools: clientToolSchemas\n })\n );\n }\n\n // Also update local state via AI SDK for immediate UI feedback\n await Promise.all(\n toolResults.map((result) =>\n addToolResult({\n tool: result.toolName,\n toolCallId: result.toolCallId,\n output: result.output\n })\n )\n );\n\n setClientToolResults((prev) => {\n const newMap = new Map(prev);\n for (const result of toolResults) {\n newMap.set(result.toolCallId, result.output);\n }\n return newMap;\n });\n\n startToolContinuation();\n }\n\n // Note: We don't call sendMessage() here anymore.\n // The server will continue the conversation after applying tool results.\n } finally {\n isResolvingToolsRef.current = false;\n // Trigger a re-run so any tool calls that arrived while we were\n // busy (e.g. from server auto-continuation) get picked up.\n setToolResolutionTrigger((c) => c + 1);\n }\n })();\n }\n }\n }, [\n chatMessages,\n experimental_automaticToolResolution,\n addToolResult,\n toolsRequiringConfirmation,\n autoContinueAfterToolResult,\n startToolContinuation,\n toolResolutionTrigger\n ]);\n\n // Helper function to send tool output to server\n const sendToolOutputToServer = useCallback(\n (\n toolCallId: string,\n toolName: string,\n output: unknown,\n state?: \"output-available\" | \"output-error\",\n errorText?: string\n ) => {\n const shouldAutoContinue =\n state === \"output-error\" ? false : autoContinueAfterToolResult;\n\n agentRef.current.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_TOOL_RESULT,\n toolCallId,\n toolName,\n output,\n ...(state ? { state } : {}),\n ...(errorText !== undefined ? { errorText } : {}),\n // output-error is a deliberate client action — don't auto-continue.\n // This differs from addToolApprovalResponse (which auto-continues for\n // both approvals and rejections). To have the LLM respond to the error,\n // call sendMessage() after addToolOutput.\n autoContinue: shouldAutoContinue,\n clientTools: toolsRef.current\n ? extractClientToolSchemas(toolsRef.current)\n : undefined\n })\n );\n\n if (state !== \"output-error\") {\n setClientToolResults((prev) => new Map(prev).set(toolCallId, output));\n }\n\n if (shouldAutoContinue) {\n startToolContinuation();\n }\n },\n [autoContinueAfterToolResult, startToolContinuation]\n );\n\n // Helper function to send tool approval to server\n const sendToolApprovalToServer = useCallback(\n (toolCallId: string, approved: boolean) => {\n agentRef.current.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_TOOL_APPROVAL,\n toolCallId,\n approved,\n autoContinue: autoContinueAfterToolResult\n })\n );\n\n if (autoContinueAfterToolResult) {\n startToolContinuation();\n }\n },\n [autoContinueAfterToolResult, startToolContinuation]\n );\n\n // Effect for new onToolCall callback pattern (v6 style)\n // This fires when there are tool calls that need client-side handling\n useEffect(() => {\n const currentOnToolCall = onToolCallRef.current;\n if (!currentOnToolCall) {\n return;\n }\n\n const lastMsg = chatMessages[chatMessages.length - 1];\n if (!lastMsg || lastMsg.role !== \"assistant\") {\n return;\n }\n\n // Find tool calls in input-available state that haven't been processed\n const pendingToolCalls = lastMsg.parts.filter(\n (part) =>\n isToolUIPart(part) &&\n part.state === \"input-available\" &&\n !processedToolCalls.current.has(part.toolCallId)\n );\n\n for (const part of pendingToolCalls) {\n if (isToolUIPart(part)) {\n const toolCallId = part.toolCallId;\n const toolName = getToolName(part);\n\n // Mark as processed to prevent re-triggering\n processedToolCalls.current.add(toolCallId);\n\n // Create addToolOutput function for this specific tool call\n const addToolOutput = (opts: AddToolOutputOptions) => {\n sendToolOutputToServer(\n opts.toolCallId,\n toolName,\n opts.output,\n opts.state,\n opts.errorText\n );\n\n // Update local state via AI SDK\n addToolResult({\n tool: toolName,\n toolCallId: opts.toolCallId,\n output:\n opts.state === \"output-error\"\n ? (opts.errorText ?? \"Tool execution denied by user\")\n : opts.output\n });\n };\n\n // Call the onToolCall callback\n // The callback is responsible for calling addToolOutput when ready\n currentOnToolCall({\n toolCall: {\n toolCallId,\n toolName,\n input: part.input\n },\n addToolOutput\n });\n }\n }\n }, [chatMessages, sendToolOutputToServer, addToolResult]);\n\n /**\n * Contains the request ID, accumulated message parts, metadata, and a unique message ID.\n * Used for both resumed streams and real-time broadcasts from other tabs.\n * Metadata is captured from start/finish/message-metadata stream chunks\n * so that it's included when the partial message is flushed to React state.\n */\n const activeStreamRef = useRef<{\n id: string;\n messageId: string;\n continuation: boolean;\n parts: ChatMessage[\"parts\"];\n metadata?: Record<string, unknown>;\n } | null>(null);\n\n /**\n * Flush the active stream's accumulated parts into React state.\n * Extracted as a helper so it can be called both during live streaming\n * (per-chunk) and after replay completes (once, at done).\n */\n const flushActiveStreamToMessages = useCallback(\n (activeMsg: {\n id: string;\n messageId: string;\n continuation: boolean;\n parts: ChatMessage[\"parts\"];\n metadata?: Record<string, unknown>;\n }) => {\n setMessages((prevMessages: ChatMessage[]) => {\n let existingIdx = prevMessages.findIndex(\n (m) => m.id === activeMsg.messageId\n );\n\n if (existingIdx < 0 && activeMsg.continuation) {\n for (let i = prevMessages.length - 1; i >= 0; i--) {\n if (prevMessages[i].role === \"assistant\") {\n existingIdx = i;\n break;\n }\n }\n }\n\n const messageId =\n existingIdx >= 0 ? prevMessages[existingIdx].id : activeMsg.messageId;\n\n const partialMessage = {\n id: messageId,\n role: \"assistant\" as const,\n parts: [...activeMsg.parts],\n ...(activeMsg.metadata != null && { metadata: activeMsg.metadata })\n } as unknown as ChatMessage;\n\n if (existingIdx >= 0) {\n const updated = [...prevMessages];\n updated[existingIdx] = partialMessage;\n return updated;\n }\n return [...prevMessages, partialMessage];\n });\n },\n [setMessages]\n );\n\n useEffect(() => {\n /**\n * Unified message handler that parses JSON once and dispatches based on type.\n * Avoids duplicate parsing overhead from separate listeners.\n */\n function onAgentMessage(event: MessageEvent) {\n if (typeof event.data !== \"string\") return;\n\n let data: OutgoingMessage<ChatMessage>;\n try {\n data = JSON.parse(event.data) as OutgoingMessage<ChatMessage>;\n } catch (_error) {\n return;\n }\n\n switch (data.type) {\n case MessageType.CF_AGENT_CHAT_CLEAR:\n setMessages([]);\n break;\n\n case MessageType.CF_AGENT_CHAT_MESSAGES:\n setMessages(data.messages);\n break;\n\n case MessageType.CF_AGENT_MESSAGE_UPDATED:\n // Server updated a message (e.g., applied tool result)\n // Update the specific message in local state\n setMessages((prevMessages: ChatMessage[]) => {\n const updatedMessage = data.message;\n\n // First try to find by message ID\n let idx = prevMessages.findIndex((m) => m.id === updatedMessage.id);\n\n // If not found by ID, try to find by toolCallId\n // This handles the case where client has AI SDK-generated IDs\n // but server has server-generated IDs\n if (idx < 0) {\n const updatedToolCallIds = new Set(\n updatedMessage.parts\n .filter(\n (p: ChatMessage[\"parts\"][number]) =>\n \"toolCallId\" in p && p.toolCallId\n )\n .map(\n (p: ChatMessage[\"parts\"][number]) =>\n (p as { toolCallId: string }).toolCallId\n )\n );\n\n if (updatedToolCallIds.size > 0) {\n idx = prevMessages.findIndex((m) =>\n m.parts.some(\n (p) =>\n \"toolCallId\" in p &&\n updatedToolCallIds.has(\n (p as { toolCallId: string }).toolCallId\n )\n )\n );\n }\n }\n\n if (idx >= 0) {\n const updated = [...prevMessages];\n // Preserve the client's message ID but update the content\n updated[idx] = {\n ...updatedMessage,\n id: prevMessages[idx].id\n };\n return updated;\n }\n // Message not found — don't append. CF_AGENT_MESSAGE_UPDATED is\n // for updating existing messages (e.g. tool result/approval state\n // changes), not for adding new ones. If the message isn't in\n // client state yet, it will arrive via the transport stream\n // (same tab) or CF_AGENT_CHAT_MESSAGES (cross-tab).\n // Appending here causes temporary duplicates (#1094).\n return prevMessages;\n });\n break;\n\n case MessageType.CF_AGENT_STREAM_RESUME_NONE:\n // Server confirmed no active stream — let the transport\n // resolve reconnectToStream immediately with null.\n customTransport.handleStreamResumeNone();\n break;\n\n case MessageType.CF_AGENT_STREAM_RESUMING:\n if (!resume && !customTransport.isAwaitingResume()) return;\n // Let the transport handle it if reconnectToStream is waiting.\n // This is called synchronously — no addEventListener race.\n // The transport sends ACK, adds to activeRequestIds, and\n // creates the ReadableStream that feeds into useChat's pipeline\n // (which correctly sets status to \"streaming\").\n if (customTransport.handleStreamResuming(data)) return;\n // Skip if the transport already handled this stream's resume\n // (server sends STREAM_RESUMING from both onConnect and the\n // RESUME_REQUEST handler — the second one must not trigger\n // a duplicate ACK / replay).\n if (localRequestIdsRef.current.has(data.id)) return;\n // Fallback for cross-tab broadcasts or cases where the\n // transport isn't expecting a resume.\n activeStreamRef.current = null;\n activeStreamRef.current = {\n id: data.id,\n messageId: nanoid(),\n continuation: false,\n parts: []\n };\n agentRef.current.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_STREAM_RESUME_ACK,\n id: data.id\n })\n );\n break;\n\n case MessageType.CF_AGENT_USE_CHAT_RESPONSE: {\n // Skip if this is a response to a request this tab initiated\n // (handled by the transport listener instead).\n // On done:true, also clean up the ID — it may have been kept in the\n // set after an abort to prevent in-flight chunks from creating a\n // duplicate message (see ws-chat-transport.ts onAbort).\n if (localRequestIdsRef.current.has(data.id)) {\n if (data.done) {\n localRequestIdsRef.current.delete(data.id);\n }\n return;\n }\n\n // For continuations, find the last assistant message ID to append to\n const isContinuation = data.continuation === true;\n\n // Initialize stream state for broadcasts from other tabs\n if (\n !activeStreamRef.current ||\n activeStreamRef.current.id !== data.id\n ) {\n let messageId = nanoid();\n let existingParts: ChatMessage[\"parts\"] = [];\n let existingMetadata: Record<string, unknown> | undefined;\n\n // For continuations, use the last assistant message's ID, parts, and metadata\n if (isContinuation) {\n const currentMessages = messagesRef.current;\n for (let i = currentMessages.length - 1; i >= 0; i--) {\n if (currentMessages[i].role === \"assistant\") {\n messageId = currentMessages[i].id;\n existingParts = [...currentMessages[i].parts];\n if (currentMessages[i].metadata != null) {\n existingMetadata = {\n ...(currentMessages[i].metadata as Record<\n string,\n unknown\n >)\n };\n }\n break;\n }\n }\n }\n\n activeStreamRef.current = {\n id: data.id,\n messageId,\n continuation: isContinuation,\n parts: existingParts,\n metadata: existingMetadata\n };\n }\n\n const activeMsg = activeStreamRef.current;\n const isReplay = data.replay === true;\n\n if (data.body?.trim()) {\n try {\n const chunkData = JSON.parse(data.body);\n\n // Apply chunk to parts using shared parser.\n // Handles text, reasoning, file, source, tool lifecycle\n // (including streaming: tool-input-start, tool-input-delta,\n // tool-input-available, tool-output-available), step, and\n // data-* chunks.\n const handled = applyChunkToParts(\n activeMsg.parts as MessageParts,\n chunkData\n );\n\n // Fire onData callback for data-* parts (stream resumption\n // and cross-tab broadcasts). For the transport path (new\n // messages from this tab), the AI SDK's pipeline invokes\n // onData internally.\n if (\n typeof chunkData.type === \"string\" &&\n chunkData.type.startsWith(\"data-\") &&\n onDataRef.current\n ) {\n onDataRef.current(chunkData);\n }\n\n // Capture message metadata from start/finish/message-metadata\n // chunks. These carry metadata like timestamps, model info, and\n // token usage that should be attached at the message level.\n if (\n !handled &&\n (chunkData.type === \"start\" ||\n chunkData.type === \"finish\" ||\n chunkData.type === \"message-metadata\")\n ) {\n if (\n chunkData.messageId != null &&\n chunkData.type === \"start\" &&\n !isContinuation\n ) {\n activeMsg.messageId = chunkData.messageId;\n }\n if (chunkData.messageMetadata != null) {\n activeMsg.metadata = activeMsg.metadata\n ? { ...activeMsg.metadata, ...chunkData.messageMetadata }\n : { ...chunkData.messageMetadata };\n }\n }\n\n // For replayed chunks, skip intermediate setMessages calls.\n // Replayed chunks arrive synchronously in a tight loop, so React\n // would batch all state updates into a single render anyway —\n // causing intermediate states (like \"Thinking...\") to be lost.\n // We defer the render until replay is complete (done signal).\n if (!isReplay) {\n flushActiveStreamToMessages(activeMsg);\n }\n } catch (parseError) {\n console.warn(\n \"[useAgentChat] Failed to parse stream chunk:\",\n parseError instanceof Error ? parseError.message : parseError,\n \"body:\",\n data.body?.slice(0, 100)\n );\n }\n }\n\n // On completion or error, flush final state to messages\n if (data.done || data.error) {\n // For replayed streams, this is the single render point —\n // all parts have been accumulated, now render them at once.\n if (isReplay && activeMsg) {\n flushActiveStreamToMessages(activeMsg);\n }\n activeStreamRef.current = null;\n } else if (data.replayComplete && activeMsg) {\n // Replay of stored chunks is complete but the stream is still\n // active (e.g. model is still thinking). Flush the accumulated\n // parts to React state so the UI shows progress. Without this,\n // replayed chunks sit in activeStreamRef unflushed until the\n // next live chunk arrives.\n flushActiveStreamToMessages(activeMsg);\n }\n break;\n }\n }\n }\n\n agent.addEventListener(\"message\", onAgentMessage);\n\n // Stream resume is now primarily handled by the transport's\n // reconnectToStream (which sends CF_AGENT_STREAM_RESUME_REQUEST).\n // The onAgentMessage handler above serves as fallback for cross-tab\n // broadcasts and cases where the transport didn't handle the resume.\n\n return () => {\n agent.removeEventListener(\"message\", onAgentMessage);\n // Clear active stream state on cleanup to prevent memory leak\n activeStreamRef.current = null;\n };\n }, [\n agent,\n setMessages,\n resume,\n flushActiveStreamToMessages,\n customTransport\n ]);\n\n // ── DEPRECATED: addToolResult wrapper with confirmation batching ────\n // This wrapper is deprecated. Use addToolOutput or addToolApprovalResponse instead.\n const addToolResultAndSendMessage: typeof addToolResult = async (args) => {\n const { toolCallId } = args;\n const toolName = \"tool\" in args ? args.tool : \"\";\n const output = \"output\" in args ? args.output : undefined;\n\n // Send tool result to server (server is source of truth)\n // Include flag to tell server whether to auto-continue\n agentRef.current.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_TOOL_RESULT,\n toolCallId,\n toolName,\n output,\n autoContinue: autoContinueAfterToolResult,\n clientTools: toolsRef.current\n ? extractClientToolSchemas(toolsRef.current)\n : undefined\n })\n );\n\n setClientToolResults((prev) => new Map(prev).set(toolCallId, output));\n\n // Call AI SDK's addToolResult for local state update (non-blocking)\n // We don't await this since clientToolResults provides immediate UI feedback\n addToolResult(args);\n\n if (autoContinueAfterToolResult) {\n startToolContinuation();\n }\n\n // If server auto-continuation is disabled, client needs to trigger continuation\n if (!autoContinueAfterToolResult) {\n // Use legacy behavior: batch confirmations or send immediately\n if (!autoSendAfterAllConfirmationsResolved) {\n // Always send immediately\n sendMessage();\n return;\n }\n\n // Wait for all confirmations before sending\n const pending = pendingConfirmationsRef.current?.toolCallIds;\n if (!pending) {\n sendMessage();\n return;\n }\n\n const wasLast = pending.size === 1 && pending.has(toolCallId);\n if (pending.has(toolCallId)) {\n pending.delete(toolCallId);\n }\n\n if (wasLast || pending.size === 0) {\n sendMessage();\n }\n }\n // If autoContinueAfterToolResult is true, server handles continuation\n };\n\n // Wrapper that sends tool approval to server before updating local state.\n // This prevents duplicate messages by ensuring server updates the message\n // in place with the existing ID, rather than relying on ID resolution\n // when sendMessage() is called later.\n const addToolApprovalResponseAndNotifyServer: typeof addToolApprovalResponse =\n (args) => {\n const { id: approvalId, approved } = args;\n\n // Find the toolCallId from the approval ID\n // The approval ID is stored on the tool part's approval.id field\n let toolCallId: string | undefined;\n for (const msg of messagesRef.current) {\n for (const part of msg.parts) {\n if (\n \"toolCallId\" in part &&\n \"approval\" in part &&\n (part.approval as { id?: string })?.id === approvalId\n ) {\n toolCallId = part.toolCallId as string;\n break;\n }\n }\n if (toolCallId) break;\n }\n\n if (toolCallId) {\n // Send approval to server first (server updates message in place)\n sendToolApprovalToServer(toolCallId, approved);\n } else {\n console.warn(\n `[useAgentChat] addToolApprovalResponse: Could not find toolCallId for approval ID \"${approvalId}\". ` +\n \"Server will not be notified, which may cause duplicate messages.\"\n );\n }\n\n // Call AI SDK's addToolApprovalResponse for local state update\n addToolApprovalResponse(args);\n };\n\n // Fix for issue #728: Merge client-side tool results with messages\n // so tool parts show output-available immediately after execution\n const messagesWithToolResults = useMemo(() => {\n if (clientToolResults.size === 0) {\n return chatMessages;\n }\n return chatMessages.map((msg) => ({\n ...msg,\n parts: msg.parts.map((p) => {\n if (\n !(\"toolCallId\" in p) ||\n !(\"state\" in p) ||\n p.state !== \"input-available\" ||\n !clientToolResults.has(p.toolCallId)\n ) {\n return p;\n }\n return {\n ...p,\n state: \"output-available\" as const,\n output: clientToolResults.get(p.toolCallId)\n };\n })\n })) as ChatMessage[];\n }, [chatMessages, clientToolResults]);\n\n // Cleanup stale entries from clientToolResults when messages change\n // to prevent memory leak in long conversations.\n // Note: We intentionally exclude clientToolResults from deps to avoid infinite loops.\n // The functional update form gives us access to the previous state.\n useEffect(() => {\n // Collect all current toolCallIds from messages\n const currentToolCallIds = new Set<string>();\n for (const msg of chatMessages) {\n for (const part of msg.parts) {\n if (\"toolCallId\" in part && part.toolCallId) {\n currentToolCallIds.add(part.toolCallId);\n }\n }\n }\n\n // Use functional update to check and clean stale entries atomically\n setClientToolResults((prev) => {\n if (prev.size === 0) return prev;\n\n // Check if any entries are stale\n let hasStaleEntries = false;\n for (const toolCallId of prev.keys()) {\n if (!currentToolCallIds.has(toolCallId)) {\n hasStaleEntries = true;\n break;\n }\n }\n\n // Only create new Map if there are stale entries to remove\n if (!hasStaleEntries) return prev;\n\n const newMap = new Map<string, unknown>();\n for (const [id, output] of prev) {\n if (currentToolCallIds.has(id)) {\n newMap.set(id, output);\n }\n }\n return newMap;\n });\n\n // Also cleanup processedToolCalls to prevent issues in long conversations\n for (const toolCallId of processedToolCalls.current) {\n if (!currentToolCallIds.has(toolCallId)) {\n processedToolCalls.current.delete(toolCallId);\n }\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [chatMessages]);\n\n // Create addToolOutput function for external use\n const addToolOutput = useCallback(\n (opts: AddToolOutputOptions) => {\n const toolName = opts.toolName ?? \"\";\n sendToolOutputToServer(\n opts.toolCallId,\n toolName,\n opts.output,\n opts.state,\n opts.errorText\n );\n\n // Update local state via AI SDK\n addToolResult({\n tool: toolName,\n toolCallId: opts.toolCallId,\n output:\n opts.state === \"output-error\"\n ? (opts.errorText ?? \"Tool execution denied by user\")\n : opts.output\n });\n },\n [sendToolOutputToServer, addToolResult]\n );\n\n return {\n ...useChatHelpers,\n messages: messagesWithToolResults,\n /**\n * Provide output for a tool call. Use this for tools that require user interaction\n * or client-side execution.\n */\n addToolOutput,\n /**\n * @deprecated Use `addToolOutput` instead.\n */\n addToolResult: addToolResultAndSendMessage,\n /**\n * Respond to a tool approval request. Use this for tools with `needsApproval`.\n * This wrapper notifies the server before updating local state, preventing\n * duplicate messages when sendMessage() is called afterward.\n */\n addToolApprovalResponse: addToolApprovalResponseAndNotifyServer,\n clearHistory: () => {\n setMessages([]);\n setClientToolResults(new Map());\n resumingToolContinuationRef.current = false;\n processedToolCalls.current.clear();\n agent.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_CHAT_CLEAR\n })\n );\n },\n setMessages: (messagesOrUpdater: Parameters<typeof setMessages>[0]) => {\n // Resolve functional updaters to get the actual messages array\n // before syncing to server. Without this, updater functions would\n // send an empty array and wipe server-side messages.\n let resolvedMessages: ChatMessage[];\n if (typeof messagesOrUpdater === \"function\") {\n resolvedMessages = messagesOrUpdater(messagesRef.current);\n } else {\n resolvedMessages = messagesOrUpdater;\n }\n\n setMessages(resolvedMessages);\n agent.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GAIrE,IAAI;AACJ,OAAI,OAAO,sBAAsB,WAC/B,oBAAmB,kBAAkB,YAAY,QAAQ;OAEzD,oBAAmB;AAGrB,eAAY,iBAAiB;AAC7B,SAAM,KACJ,KAAK,UAAU;IACb,UAAU;IACV,MAAM,YAAY;IACnB,CAAC,CACH;;EAEJ"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/ai-chat",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "description": "Cloudflare Agents (x) AI SDK Chat",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -28,7 +28,7 @@
28
28
  },
29
29
  "peerDependencies": {
30
30
  "@ai-sdk/react": "^3.0.0",
31
- "agents": "^0.8.1",
31
+ "agents": "^0.8.2",
32
32
  "ai": "^6.0.0",
33
33
  "react": "^19.0.0",
34
34
  "zod": "^4.0.0"