@cloudflare/ai-chat 0.0.7 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +105 -0
  2. package/README.md +225 -459
  3. package/dist/ai-chat-v5-migration.d.ts +9 -9
  4. package/dist/ai-chat-v5-migration.js +25 -4
  5. package/dist/ai-chat-v5-migration.js.map +1 -1
  6. package/dist/experimental/forever.d.ts +29 -0
  7. package/dist/experimental/forever.js +55 -0
  8. package/dist/experimental/forever.js.map +1 -0
  9. package/dist/index.d.ts +126 -74
  10. package/dist/index.js +753 -632
  11. package/dist/index.js.map +1 -1
  12. package/dist/message-builder-Bwc_Umye.js +231 -0
  13. package/dist/message-builder-Bwc_Umye.js.map +1 -0
  14. package/dist/react.d.ts +27 -9
  15. package/dist/react.js +248 -259
  16. package/dist/react.js.map +1 -1
  17. package/dist/resumable-stream-DqXxQVjf.d.ts +103 -0
  18. package/dist/types.d.ts +16 -4
  19. package/dist/types.js +2 -0
  20. package/dist/types.js.map +1 -1
  21. package/e2e/chat.spec.ts +1703 -0
  22. package/e2e/client-tools.spec.ts +504 -0
  23. package/e2e/llm.spec.ts +637 -0
  24. package/e2e/playwright.config.ts +24 -0
  25. package/e2e/worker.ts +176 -0
  26. package/e2e/wrangler.jsonc +23 -0
  27. package/package.json +12 -5
  28. package/scripts/build.ts +2 -1
  29. package/src/ai-chat-v5-migration.ts +32 -5
  30. package/src/experimental/forever.ts +66 -0
  31. package/src/index.ts +850 -1132
  32. package/src/message-builder.ts +384 -0
  33. package/src/react-tests/use-agent-chat.test.tsx +738 -2
  34. package/src/react.tsx +396 -462
  35. package/src/resumable-stream.ts +441 -0
  36. package/src/tests/chat-context.test.ts +1 -1
  37. package/src/tests/chat-persistence.test.ts +5 -5
  38. package/src/tests/clear-history.test.ts +132 -0
  39. package/src/tests/client-tool-duplicate-message.test.ts +457 -14
  40. package/src/tests/client-tools-broadcast.test.ts +2 -2
  41. package/src/tests/client-tools-continuation.test.ts +314 -0
  42. package/src/tests/client-tools-reconnect.test.ts +143 -0
  43. package/src/tests/custom-body-continuation.test.ts +309 -0
  44. package/src/tests/custom-body.test.ts +186 -0
  45. package/src/tests/destroy.test.ts +57 -0
  46. package/src/tests/get-messages-endpoint.test.ts +79 -0
  47. package/src/tests/max-persisted-messages.test.ts +201 -0
  48. package/src/tests/merge-server-state.test.ts +106 -0
  49. package/src/tests/message-builder.test.ts +808 -0
  50. package/src/tests/migration.test.ts +282 -0
  51. package/src/tests/non-sse-response.test.ts +2 -2
  52. package/src/tests/onfinish-cleanup.test.ts +362 -0
  53. package/src/tests/plaintext-response.test.ts +87 -0
  54. package/src/tests/resumable-streaming.test.ts +220 -14
  55. package/src/tests/row-size-guard.test.ts +374 -0
  56. package/src/tests/sanitize-messages.test.ts +215 -0
  57. package/src/tests/validate-messages.test.ts +269 -0
  58. package/src/tests/worker.ts +85 -23
  59. package/src/types.ts +17 -1
  60. package/src/ws-chat-transport.ts +203 -0
package/dist/react.js CHANGED
@@ -1,11 +1,114 @@
1
1
  import { MessageType } from "./types.js";
2
- import { DefaultChatTransport, getToolName, isToolUIPart } from "ai";
2
+ import { t as applyChunkToParts } from "./message-builder-Bwc_Umye.js";
3
+ import { getToolName, isToolUIPart } from "ai";
3
4
  import { nanoid } from "nanoid";
4
5
  import { useChat } from "@ai-sdk/react";
5
6
  import { use, useCallback, useEffect, useMemo, useRef, useState } from "react";
6
7
 
8
+ //#region src/ws-chat-transport.ts
9
+ /**
10
+ * ChatTransport that sends messages over WebSocket and returns a
11
+ * ReadableStream<UIMessageChunk> that the AI SDK's useChat consumes directly.
12
+ * No fake fetch, no Response reconstruction, no double SSE parsing.
13
+ */
14
+ var WebSocketChatTransport = class {
15
+ constructor(options) {
16
+ this.agent = options.agent;
17
+ this.prepareBody = options.prepareBody;
18
+ this.activeRequestIds = options.activeRequestIds;
19
+ }
20
+ async sendMessages(options) {
21
+ const requestId = nanoid(8);
22
+ const abortController = new AbortController();
23
+ let completed = false;
24
+ let extraBody = {};
25
+ if (this.prepareBody) extraBody = await this.prepareBody({
26
+ messages: options.messages,
27
+ trigger: options.trigger,
28
+ messageId: options.messageId
29
+ });
30
+ if (options.body) extraBody = {
31
+ ...extraBody,
32
+ ...options.body
33
+ };
34
+ const bodyPayload = JSON.stringify({
35
+ messages: options.messages,
36
+ ...extraBody
37
+ });
38
+ this.activeRequestIds?.add(requestId);
39
+ options.abortSignal?.addEventListener("abort", () => {
40
+ if (completed) return;
41
+ this.agent.send(JSON.stringify({
42
+ id: requestId,
43
+ type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL
44
+ }));
45
+ this.activeRequestIds?.delete(requestId);
46
+ abortController.abort();
47
+ });
48
+ const agent = this.agent;
49
+ const activeIds = this.activeRequestIds;
50
+ const stream = new ReadableStream({
51
+ start(controller) {
52
+ const onMessage = (event) => {
53
+ try {
54
+ const data = JSON.parse(event.data);
55
+ if (data.type !== MessageType.CF_AGENT_USE_CHAT_RESPONSE) return;
56
+ if (data.id !== requestId) return;
57
+ if (data.error) {
58
+ completed = true;
59
+ controller.error(new Error(data.body));
60
+ activeIds?.delete(requestId);
61
+ abortController.abort();
62
+ return;
63
+ }
64
+ if (data.body?.trim()) try {
65
+ const chunk = JSON.parse(data.body);
66
+ controller.enqueue(chunk);
67
+ } catch {}
68
+ if (data.done) {
69
+ completed = true;
70
+ try {
71
+ controller.close();
72
+ } catch {}
73
+ activeIds?.delete(requestId);
74
+ abortController.abort();
75
+ }
76
+ } catch {}
77
+ };
78
+ agent.addEventListener("message", onMessage, { signal: abortController.signal });
79
+ },
80
+ cancel() {
81
+ abortController.abort();
82
+ }
83
+ });
84
+ agent.send(JSON.stringify({
85
+ id: requestId,
86
+ init: {
87
+ method: "POST",
88
+ body: bodyPayload
89
+ },
90
+ type: MessageType.CF_AGENT_USE_CHAT_REQUEST
91
+ }));
92
+ return stream;
93
+ }
94
+ async reconnectToStream(_options) {
95
+ return null;
96
+ }
97
+ };
98
+
99
+ //#endregion
7
100
  //#region src/react.tsx
8
101
  /**
102
+ * One-shot deprecation warnings (warns once per key per session).
103
+ */
104
+ const _deprecationWarnings = /* @__PURE__ */ new Set();
105
+ function warnDeprecated(id, message) {
106
+ if (!_deprecationWarnings.has(id)) {
107
+ _deprecationWarnings.add(id);
108
+ console.warn(`[@cloudflare/ai-chat] Deprecated: ${message}`);
109
+ }
110
+ }
111
+ /**
9
112
  * Extracts tool schemas from tools that have client-side execute functions.
10
113
  * These schemas are automatically sent to the server with each request.
11
114
  * @param tools - Record of tool name to tool definition
@@ -15,6 +118,7 @@ import { use, useCallback, useEffect, useMemo, useRef, useState } from "react";
15
118
  * and use `onToolCall` callback for client-side execution.
16
119
  */
17
120
  function extractClientToolSchemas(tools) {
121
+ warnDeprecated("extractClientToolSchemas", "extractClientToolSchemas() is deprecated. Define tools on the server and use onToolCall for client execution. Will be removed in the next major version.");
18
122
  if (!tools) return void 0;
19
123
  const schemas = Object.entries(tools).filter(([_, tool]) => tool.execute).map(([name, tool]) => {
20
124
  if (tool.inputSchema && !tool.parameters) console.warn(`[useAgentChat] Tool "${name}" uses deprecated 'inputSchema'. Please migrate to 'parameters'.`);
@@ -26,6 +130,12 @@ function extractClientToolSchemas(tools) {
26
130
  });
27
131
  return schemas.length > 0 ? schemas : void 0;
28
132
  }
133
+ /**
134
+ * Module-level cache for initial message fetches. Intentionally shared across
135
+ * all useAgentChat instances to deduplicate requests during React Strict Mode
136
+ * double-renders and re-renders. Cache keys include the agent URL, agent type,
137
+ * and thread name to prevent cross-agent collisions.
138
+ */
29
139
  const requestCache = /* @__PURE__ */ new Map();
30
140
  /**
31
141
  * React hook for building AI chat interfaces using an Agent
@@ -41,14 +151,21 @@ const requestCache = /* @__PURE__ */ new Map();
41
151
  * @deprecated Use `needsApproval` on server-side tools instead.
42
152
  */
43
153
  function detectToolsRequiringConfirmation(tools) {
154
+ warnDeprecated("detectToolsRequiringConfirmation", "detectToolsRequiringConfirmation() is deprecated. Use needsApproval on server-side tools instead. Will be removed in the next major version.");
44
155
  if (!tools) return [];
45
156
  return Object.entries(tools).filter(([_name, tool]) => !tool.execute).map(([name]) => name);
46
157
  }
47
158
  function useAgentChat(options) {
48
- const { agent, getInitialMessages, messages: optionsInitialMessages, onToolCall, experimental_automaticToolResolution, tools, toolsRequiringConfirmation: manualToolsRequiringConfirmation, autoContinueAfterToolResult = false, autoSendAfterAllConfirmationsResolved = true, resume = true, prepareSendMessagesRequest, ...rest } = options;
49
- const toolsRequiringConfirmation = manualToolsRequiringConfirmation ?? detectToolsRequiringConfirmation(tools);
159
+ const { agent, getInitialMessages, messages: optionsInitialMessages, onToolCall, onData, experimental_automaticToolResolution, tools, toolsRequiringConfirmation: manualToolsRequiringConfirmation, autoContinueAfterToolResult = true, autoSendAfterAllConfirmationsResolved = true, resume = true, body: bodyOption, prepareSendMessagesRequest, ...rest } = options;
160
+ if (tools) warnDeprecated("useAgentChat.tools", "The 'tools' option in useAgentChat is deprecated. Define tools on the server using tool() from 'ai' and handle client execution via the onToolCall callback. Will be removed in the next major version.");
161
+ if (manualToolsRequiringConfirmation) warnDeprecated("useAgentChat.toolsRequiringConfirmation", "The 'toolsRequiringConfirmation' option is deprecated. Use needsApproval on server-side tools instead. Will be removed in the next major version.");
162
+ if (experimental_automaticToolResolution) warnDeprecated("useAgentChat.experimental_automaticToolResolution", "The 'experimental_automaticToolResolution' option is deprecated. Use the onToolCall callback instead. Will be removed in the next major version.");
163
+ if (options.autoSendAfterAllConfirmationsResolved !== void 0) warnDeprecated("useAgentChat.autoSendAfterAllConfirmationsResolved", "The 'autoSendAfterAllConfirmationsResolved' option is deprecated. Use sendAutomaticallyWhen from AI SDK instead. Will be removed in the next major version.");
164
+ const toolsRequiringConfirmation = useMemo(() => manualToolsRequiringConfirmation ?? (tools ? detectToolsRequiringConfirmation(tools) : []), [manualToolsRequiringConfirmation, tools]);
50
165
  const onToolCallRef = useRef(onToolCall);
51
166
  onToolCallRef.current = onToolCall;
167
+ const onDataRef = useRef(onData);
168
+ onDataRef.current = onData;
52
169
  const agentUrl = new URL(`${(agent._url || agent._pkurl)?.replace("ws://", "http://").replace("wss://", "https://")}`);
53
170
  agentUrl.searchParams.delete("_pk");
54
171
  const agentUrlString = agentUrl.toString();
@@ -97,130 +214,55 @@ function useAgentChat(options) {
97
214
  if (requestCache.get(initialMessagesCacheKey) === initialMessagesPromise) requestCache.delete(initialMessagesCacheKey);
98
215
  };
99
216
  }, [initialMessagesCacheKey, initialMessagesPromise]);
100
- const aiFetch = useCallback(async (request, options = {}) => {
101
- const { method, keepalive, headers, body, redirect, integrity, signal, credentials, mode, referrer, referrerPolicy, window } = options;
102
- const id = nanoid(8);
103
- const abortController = new AbortController();
104
- let controller;
105
- const currentAgent = agentRef.current;
106
- localRequestIdsRef.current.add(id);
107
- signal?.addEventListener("abort", () => {
108
- currentAgent.send(JSON.stringify({
109
- id,
110
- type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL
111
- }));
112
- abortController.abort();
113
- try {
114
- controller.close();
115
- } catch {}
116
- localRequestIdsRef.current.delete(id);
117
- });
118
- currentAgent.addEventListener("message", (event) => {
119
- let data;
120
- try {
121
- data = JSON.parse(event.data);
122
- } catch (_error) {
123
- return;
124
- }
125
- if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE) {
126
- if (data.id === id) if (data.error) {
127
- controller.error(new Error(data.body));
128
- abortController.abort();
129
- localRequestIdsRef.current.delete(id);
130
- } else {
131
- if (data.body?.trim()) controller.enqueue(new TextEncoder().encode(`data: ${data.body}\n\n`));
132
- if (data.done) {
133
- try {
134
- controller.close();
135
- } catch {}
136
- abortController.abort();
137
- localRequestIdsRef.current.delete(id);
138
- }
139
- }
140
- }
141
- }, { signal: abortController.signal });
142
- const stream = new ReadableStream({
143
- start(c) {
144
- controller = c;
145
- },
146
- cancel(reason) {
147
- console.warn("[@cloudflare/ai-chat/react] cancelling stream", id, reason || "no reason");
148
- }
149
- });
150
- currentAgent.send(JSON.stringify({
151
- id,
152
- init: {
153
- body,
154
- credentials,
155
- headers,
156
- integrity,
157
- keepalive,
158
- method,
159
- mode,
160
- redirect,
161
- referrer,
162
- referrerPolicy,
163
- window
164
- },
165
- type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
166
- url: request.toString()
167
- }));
168
- return new Response(stream);
169
- }, []);
170
217
  const toolsRef = useRef(tools);
171
218
  toolsRef.current = tools;
172
219
  const prepareSendMessagesRequestRef = useRef(prepareSendMessagesRequest);
173
220
  prepareSendMessagesRequestRef.current = prepareSendMessagesRequest;
174
- const customTransport = useMemo(() => ({
175
- sendMessages: async (sendMessageOptions) => {
176
- const clientToolSchemas = extractClientToolSchemas(toolsRef.current);
177
- return new DefaultChatTransport({
178
- api: agentUrlString,
179
- fetch: aiFetch,
180
- prepareSendMessagesRequest: clientToolSchemas || prepareSendMessagesRequestRef.current ? async (prepareOptions) => {
181
- let body = {};
182
- let headers;
183
- let credentials;
184
- let api;
185
- if (clientToolSchemas) body = {
186
- id: prepareOptions.id,
187
- messages: prepareOptions.messages,
188
- trigger: prepareOptions.trigger,
189
- clientTools: clientToolSchemas
190
- };
191
- if (prepareSendMessagesRequestRef.current) {
192
- const userResult = await prepareSendMessagesRequestRef.current(prepareOptions);
193
- headers = userResult.headers;
194
- credentials = userResult.credentials;
195
- api = userResult.api;
196
- body = {
197
- ...body,
198
- ...userResult.body ?? {}
199
- };
200
- }
201
- return {
202
- body,
203
- headers,
204
- credentials,
205
- api
206
- };
207
- } : void 0
208
- }).sendMessages(sendMessageOptions);
209
- },
210
- reconnectToStream: async () => null
211
- }), [agentUrlString, aiFetch]);
221
+ const bodyOptionRef = useRef(bodyOption);
222
+ bodyOptionRef.current = bodyOption;
223
+ /**
224
+ * Tracks request IDs initiated by this tab via the transport.
225
+ * Used by onAgentMessage to skip messages already handled by the transport.
226
+ */
227
+ const localRequestIdsRef = useRef(/* @__PURE__ */ new Set());
228
+ const customTransport = useMemo(() => new WebSocketChatTransport({
229
+ agent: agentRef.current,
230
+ activeRequestIds: localRequestIdsRef.current,
231
+ prepareBody: async ({ messages: msgs, trigger, messageId }) => {
232
+ let extraBody = {};
233
+ const currentBody = bodyOptionRef.current;
234
+ if (currentBody) extraBody = { ...typeof currentBody === "function" ? await currentBody() : currentBody };
235
+ if (toolsRef.current) {
236
+ const clientToolSchemas = extractClientToolSchemas(toolsRef.current);
237
+ if (clientToolSchemas) extraBody.clientTools = clientToolSchemas;
238
+ }
239
+ if (prepareSendMessagesRequestRef.current) {
240
+ const userResult = await prepareSendMessagesRequestRef.current({
241
+ id: agent._pk,
242
+ messages: msgs,
243
+ trigger,
244
+ messageId
245
+ });
246
+ if (userResult.body) Object.assign(extraBody, userResult.body);
247
+ }
248
+ return extraBody;
249
+ }
250
+ }), [agent._pk]);
212
251
  const useChatHelpers = useChat({
213
252
  ...rest,
253
+ onData,
214
254
  messages: initialMessages,
215
255
  transport: customTransport,
216
256
  id: agent._pk
217
257
  });
258
+ const { messages: chatMessages, setMessages, addToolResult, addToolApprovalResponse, sendMessage } = useChatHelpers;
218
259
  const processedToolCalls = useRef(/* @__PURE__ */ new Set());
219
260
  const isResolvingToolsRef = useRef(false);
261
+ const [toolResolutionTrigger, setToolResolutionTrigger] = useState(0);
220
262
  const [clientToolResults, setClientToolResults] = useState(/* @__PURE__ */ new Map());
221
- const messagesRef = useRef(useChatHelpers.messages);
222
- messagesRef.current = useChatHelpers.messages;
223
- const lastMessage = useChatHelpers.messages[useChatHelpers.messages.length - 1];
263
+ const messagesRef = useRef(chatMessages);
264
+ messagesRef.current = chatMessages;
265
+ const lastMessage = chatMessages[chatMessages.length - 1];
224
266
  const pendingConfirmations = (() => {
225
267
  if (!lastMessage || lastMessage.role !== "assistant") return {
226
268
  messageId: void 0,
@@ -238,9 +280,9 @@ function useAgentChat(options) {
238
280
  useEffect(() => {
239
281
  if (!experimental_automaticToolResolution) return;
240
282
  if (isResolvingToolsRef.current) return;
241
- const lastMessage = useChatHelpers.messages[useChatHelpers.messages.length - 1];
242
- if (!lastMessage || lastMessage.role !== "assistant") return;
243
- const toolCalls = lastMessage.parts.filter((part) => isToolUIPart(part) && part.state === "input-available" && !processedToolCalls.current.has(part.toolCallId));
283
+ const lastMsg = chatMessages[chatMessages.length - 1];
284
+ if (!lastMsg || lastMsg.role !== "assistant") return;
285
+ const toolCalls = lastMsg.parts.filter((part) => isToolUIPart(part) && part.state === "input-available" && !processedToolCalls.current.has(part.toolCallId));
244
286
  if (toolCalls.length > 0) {
245
287
  const currentTools = toolsRef.current;
246
288
  const toolCallsToResolve = toolCalls.filter((part) => isToolUIPart(part) && !toolsRequiringConfirmation.includes(getToolName(part)) && currentTools?.[getToolName(part)]?.execute);
@@ -266,14 +308,16 @@ function useAgentChat(options) {
266
308
  });
267
309
  }
268
310
  if (toolResults.length > 0) {
311
+ const clientToolSchemas = extractClientToolSchemas(currentTools);
269
312
  for (const result of toolResults) agentRef.current.send(JSON.stringify({
270
313
  type: MessageType.CF_AGENT_TOOL_RESULT,
271
314
  toolCallId: result.toolCallId,
272
315
  toolName: result.toolName,
273
316
  output: result.output,
274
- autoContinue: autoContinueAfterToolResult
317
+ autoContinue: autoContinueAfterToolResult,
318
+ clientTools: clientToolSchemas
275
319
  }));
276
- await Promise.all(toolResults.map((result) => useChatHelpers.addToolResult({
320
+ await Promise.all(toolResults.map((result) => addToolResult({
277
321
  tool: result.toolName,
278
322
  toolCallId: result.toolCallId,
279
323
  output: result.output
@@ -286,16 +330,18 @@ function useAgentChat(options) {
286
330
  }
287
331
  } finally {
288
332
  isResolvingToolsRef.current = false;
333
+ setToolResolutionTrigger((c) => c + 1);
289
334
  }
290
335
  })();
291
336
  }
292
337
  }
293
338
  }, [
294
- useChatHelpers.messages,
339
+ chatMessages,
295
340
  experimental_automaticToolResolution,
296
- useChatHelpers.addToolResult,
341
+ addToolResult,
297
342
  toolsRequiringConfirmation,
298
- autoContinueAfterToolResult
343
+ autoContinueAfterToolResult,
344
+ toolResolutionTrigger
299
345
  ]);
300
346
  const sendToolOutputToServer = useCallback((toolCallId, toolName, output) => {
301
347
  agentRef.current.send(JSON.stringify({
@@ -303,7 +349,8 @@ function useAgentChat(options) {
303
349
  toolCallId,
304
350
  toolName,
305
351
  output,
306
- autoContinue: autoContinueAfterToolResult
352
+ autoContinue: autoContinueAfterToolResult,
353
+ clientTools: toolsRef.current ? extractClientToolSchemas(toolsRef.current) : void 0
307
354
  }));
308
355
  setClientToolResults((prev) => new Map(prev).set(toolCallId, output));
309
356
  }, [autoContinueAfterToolResult]);
@@ -311,22 +358,23 @@ function useAgentChat(options) {
311
358
  agentRef.current.send(JSON.stringify({
312
359
  type: MessageType.CF_AGENT_TOOL_APPROVAL,
313
360
  toolCallId,
314
- approved
361
+ approved,
362
+ autoContinue: autoContinueAfterToolResult
315
363
  }));
316
- }, []);
364
+ }, [autoContinueAfterToolResult]);
317
365
  useEffect(() => {
318
366
  const currentOnToolCall = onToolCallRef.current;
319
367
  if (!currentOnToolCall) return;
320
- const lastMessage = useChatHelpers.messages[useChatHelpers.messages.length - 1];
321
- if (!lastMessage || lastMessage.role !== "assistant") return;
322
- const pendingToolCalls = lastMessage.parts.filter((part) => isToolUIPart(part) && part.state === "input-available" && !processedToolCalls.current.has(part.toolCallId));
368
+ const lastMsg = chatMessages[chatMessages.length - 1];
369
+ if (!lastMsg || lastMsg.role !== "assistant") return;
370
+ const pendingToolCalls = lastMsg.parts.filter((part) => isToolUIPart(part) && part.state === "input-available" && !processedToolCalls.current.has(part.toolCallId));
323
371
  for (const part of pendingToolCalls) if (isToolUIPart(part)) {
324
372
  const toolCallId = part.toolCallId;
325
373
  const toolName = getToolName(part);
326
374
  processedToolCalls.current.add(toolCallId);
327
375
  const addToolOutput = (opts) => {
328
376
  sendToolOutputToServer(opts.toolCallId, toolName, opts.output);
329
- useChatHelpers.addToolResult({
377
+ addToolResult({
330
378
  tool: toolName,
331
379
  toolCallId: opts.toolCallId,
332
380
  output: opts.output
@@ -342,20 +390,39 @@ function useAgentChat(options) {
342
390
  });
343
391
  }
344
392
  }, [
345
- useChatHelpers.messages,
393
+ chatMessages,
346
394
  sendToolOutputToServer,
347
- useChatHelpers.addToolResult
395
+ addToolResult
348
396
  ]);
349
397
  /**
350
- * Contains the request ID, accumulated message parts, and a unique message ID.
398
+ * Contains the request ID, accumulated message parts, metadata, and a unique message ID.
351
399
  * Used for both resumed streams and real-time broadcasts from other tabs.
400
+ * Metadata is captured from start/finish/message-metadata stream chunks
401
+ * so that it's included when the partial message is flushed to React state.
352
402
  */
353
403
  const activeStreamRef = useRef(null);
354
404
  /**
355
- * Tracks request IDs initiated by this tab via aiFetch.
356
- * Used to distinguish local requests from broadcasts.
405
+ * Flush the active stream's accumulated parts into React state.
406
+ * Extracted as a helper so it can be called both during live streaming
407
+ * (per-chunk) and after replay completes (once, at done).
357
408
  */
358
- const localRequestIdsRef = useRef(/* @__PURE__ */ new Set());
409
+ const flushActiveStreamToMessages = useCallback((activeMsg) => {
410
+ setMessages((prevMessages) => {
411
+ const existingIdx = prevMessages.findIndex((m) => m.id === activeMsg.messageId);
412
+ const partialMessage = {
413
+ id: activeMsg.messageId,
414
+ role: "assistant",
415
+ parts: [...activeMsg.parts],
416
+ ...activeMsg.metadata != null && { metadata: activeMsg.metadata }
417
+ };
418
+ if (existingIdx >= 0) {
419
+ const updated = [...prevMessages];
420
+ updated[existingIdx] = partialMessage;
421
+ return updated;
422
+ }
423
+ return [...prevMessages, partialMessage];
424
+ });
425
+ }, [setMessages]);
359
426
  useEffect(() => {
360
427
  /**
361
428
  * Unified message handler that parses JSON once and dispatches based on type.
@@ -371,13 +438,13 @@ function useAgentChat(options) {
371
438
  }
372
439
  switch (data.type) {
373
440
  case MessageType.CF_AGENT_CHAT_CLEAR:
374
- useChatHelpers.setMessages([]);
441
+ setMessages([]);
375
442
  break;
376
443
  case MessageType.CF_AGENT_CHAT_MESSAGES:
377
- useChatHelpers.setMessages(data.messages);
444
+ setMessages(data.messages);
378
445
  break;
379
446
  case MessageType.CF_AGENT_MESSAGE_UPDATED:
380
- useChatHelpers.setMessages((prevMessages) => {
447
+ setMessages((prevMessages) => {
381
448
  const updatedMessage = data.message;
382
449
  let idx = prevMessages.findIndex((m) => m.id === updatedMessage.id);
383
450
  if (idx < 0) {
@@ -414,141 +481,59 @@ function useAgentChat(options) {
414
481
  if (!activeStreamRef.current || activeStreamRef.current.id !== data.id) {
415
482
  let messageId = nanoid();
416
483
  let existingParts = [];
484
+ let existingMetadata;
417
485
  if (isContinuation) {
418
486
  const currentMessages = messagesRef.current;
419
487
  for (let i = currentMessages.length - 1; i >= 0; i--) if (currentMessages[i].role === "assistant") {
420
488
  messageId = currentMessages[i].id;
421
489
  existingParts = [...currentMessages[i].parts];
490
+ if (currentMessages[i].metadata != null) existingMetadata = { ...currentMessages[i].metadata };
422
491
  break;
423
492
  }
424
493
  }
425
494
  activeStreamRef.current = {
426
495
  id: data.id,
427
496
  messageId,
428
- parts: existingParts
497
+ parts: existingParts,
498
+ metadata: existingMetadata
429
499
  };
430
500
  }
431
501
  const activeMsg = activeStreamRef.current;
502
+ const isReplay = data.replay === true;
432
503
  if (data.body?.trim()) try {
433
504
  const chunkData = JSON.parse(data.body);
434
- switch (chunkData.type) {
435
- case "text-start":
436
- activeMsg.parts.push({
437
- type: "text",
438
- text: "",
439
- state: "streaming"
440
- });
441
- break;
442
- case "text-delta": {
443
- const lastTextPart = [...activeMsg.parts].reverse().find((p) => p.type === "text");
444
- if (lastTextPart && lastTextPart.type === "text") lastTextPart.text += chunkData.delta;
445
- else activeMsg.parts.push({
446
- type: "text",
447
- text: chunkData.delta
448
- });
449
- break;
450
- }
451
- case "text-end": {
452
- const lastTextPart = [...activeMsg.parts].reverse().find((p) => p.type === "text");
453
- if (lastTextPart && "state" in lastTextPart) lastTextPart.state = "done";
454
- break;
455
- }
456
- case "reasoning-start":
457
- activeMsg.parts.push({
458
- type: "reasoning",
459
- text: "",
460
- state: "streaming"
461
- });
462
- break;
463
- case "reasoning-delta": {
464
- const lastReasoningPart = [...activeMsg.parts].reverse().find((p) => p.type === "reasoning");
465
- if (lastReasoningPart && lastReasoningPart.type === "reasoning") lastReasoningPart.text += chunkData.delta;
466
- break;
467
- }
468
- case "reasoning-end": {
469
- const lastReasoningPart = [...activeMsg.parts].reverse().find((p) => p.type === "reasoning");
470
- if (lastReasoningPart && "state" in lastReasoningPart) lastReasoningPart.state = "done";
471
- break;
472
- }
473
- case "file":
474
- activeMsg.parts.push({
475
- type: "file",
476
- mediaType: chunkData.mediaType,
477
- url: chunkData.url
478
- });
479
- break;
480
- case "source-url":
481
- activeMsg.parts.push({
482
- type: "source-url",
483
- sourceId: chunkData.sourceId,
484
- url: chunkData.url,
485
- title: chunkData.title
486
- });
487
- break;
488
- case "source-document":
489
- activeMsg.parts.push({
490
- type: "source-document",
491
- sourceId: chunkData.sourceId,
492
- mediaType: chunkData.mediaType,
493
- title: chunkData.title,
494
- filename: chunkData.filename
495
- });
496
- break;
497
- case "tool-input-available":
498
- activeMsg.parts.push({
499
- type: `tool-${chunkData.toolName}`,
500
- toolCallId: chunkData.toolCallId,
501
- toolName: chunkData.toolName,
502
- state: "input-available",
503
- input: chunkData.input
504
- });
505
- break;
506
- case "tool-output-available":
507
- activeMsg.parts = activeMsg.parts.map((p) => {
508
- if ("toolCallId" in p && p.toolCallId === chunkData.toolCallId && "state" in p) return {
509
- ...p,
510
- state: "output-available",
511
- output: chunkData.output
512
- };
513
- return p;
514
- });
515
- break;
516
- case "step-start":
517
- activeMsg.parts.push({ type: "step-start" });
518
- break;
505
+ const handled = applyChunkToParts(activeMsg.parts, chunkData);
506
+ if (typeof chunkData.type === "string" && chunkData.type.startsWith("data-") && onDataRef.current) onDataRef.current(chunkData);
507
+ if (!handled && (chunkData.type === "start" || chunkData.type === "finish" || chunkData.type === "message-metadata")) {
508
+ if (chunkData.messageId != null && chunkData.type === "start") activeMsg.messageId = chunkData.messageId;
509
+ if (chunkData.messageMetadata != null) activeMsg.metadata = activeMsg.metadata ? {
510
+ ...activeMsg.metadata,
511
+ ...chunkData.messageMetadata
512
+ } : { ...chunkData.messageMetadata };
519
513
  }
520
- useChatHelpers.setMessages((prevMessages) => {
521
- if (!activeMsg) return prevMessages;
522
- const existingIdx = prevMessages.findIndex((m) => m.id === activeMsg.messageId);
523
- const partialMessage = {
524
- id: activeMsg.messageId,
525
- role: "assistant",
526
- parts: [...activeMsg.parts]
527
- };
528
- if (existingIdx >= 0) {
529
- const updated = [...prevMessages];
530
- updated[existingIdx] = partialMessage;
531
- return updated;
532
- }
533
- return [...prevMessages, partialMessage];
534
- });
514
+ if (!isReplay) flushActiveStreamToMessages(activeMsg);
535
515
  } catch (parseError) {
536
516
  console.warn("[useAgentChat] Failed to parse stream chunk:", parseError instanceof Error ? parseError.message : parseError, "body:", data.body?.slice(0, 100));
537
517
  }
538
- if (data.done || data.error) activeStreamRef.current = null;
518
+ if (data.done || data.error) {
519
+ if (isReplay && activeMsg) flushActiveStreamToMessages(activeMsg);
520
+ activeStreamRef.current = null;
521
+ }
539
522
  break;
540
523
  }
541
524
  }
542
525
  }
543
526
  agent.addEventListener("message", onAgentMessage);
527
+ if (resume) agent.send(JSON.stringify({ type: MessageType.CF_AGENT_STREAM_RESUME_REQUEST }));
544
528
  return () => {
545
529
  agent.removeEventListener("message", onAgentMessage);
546
530
  activeStreamRef.current = null;
547
531
  };
548
532
  }, [
549
533
  agent,
550
- useChatHelpers.setMessages,
551
- resume
534
+ setMessages,
535
+ resume,
536
+ flushActiveStreamToMessages
552
537
  ]);
553
538
  const addToolResultAndSendMessage = async (args) => {
554
539
  const { toolCallId } = args;
@@ -559,23 +544,24 @@ function useAgentChat(options) {
559
544
  toolCallId,
560
545
  toolName,
561
546
  output,
562
- autoContinue: autoContinueAfterToolResult
547
+ autoContinue: autoContinueAfterToolResult,
548
+ clientTools: toolsRef.current ? extractClientToolSchemas(toolsRef.current) : void 0
563
549
  }));
564
550
  setClientToolResults((prev) => new Map(prev).set(toolCallId, output));
565
- useChatHelpers.addToolResult(args);
551
+ addToolResult(args);
566
552
  if (!autoContinueAfterToolResult) {
567
553
  if (!autoSendAfterAllConfirmationsResolved) {
568
- useChatHelpers.sendMessage();
554
+ sendMessage();
569
555
  return;
570
556
  }
571
557
  const pending = pendingConfirmationsRef.current?.toolCallIds;
572
558
  if (!pending) {
573
- useChatHelpers.sendMessage();
559
+ sendMessage();
574
560
  return;
575
561
  }
576
562
  const wasLast = pending.size === 1 && pending.has(toolCallId);
577
563
  if (pending.has(toolCallId)) pending.delete(toolCallId);
578
- if (wasLast || pending.size === 0) useChatHelpers.sendMessage();
564
+ if (wasLast || pending.size === 0) sendMessage();
579
565
  }
580
566
  };
581
567
  const addToolApprovalResponseAndNotifyServer = (args) => {
@@ -590,11 +576,11 @@ function useAgentChat(options) {
590
576
  }
591
577
  if (toolCallId) sendToolApprovalToServer(toolCallId, approved);
592
578
  else console.warn(`[useAgentChat] addToolApprovalResponse: Could not find toolCallId for approval ID "${approvalId}". Server will not be notified, which may cause duplicate messages.`);
593
- useChatHelpers.addToolApprovalResponse(args);
579
+ addToolApprovalResponse(args);
594
580
  };
595
581
  const messagesWithToolResults = useMemo(() => {
596
- if (clientToolResults.size === 0) return useChatHelpers.messages;
597
- return useChatHelpers.messages.map((msg) => ({
582
+ if (clientToolResults.size === 0) return chatMessages;
583
+ return chatMessages.map((msg) => ({
598
584
  ...msg,
599
585
  parts: msg.parts.map((p) => {
600
586
  if (!("toolCallId" in p) || !("state" in p) || p.state !== "input-available" || !clientToolResults.has(p.toolCallId)) return p;
@@ -605,10 +591,10 @@ function useAgentChat(options) {
605
591
  };
606
592
  })
607
593
  }));
608
- }, [useChatHelpers.messages, clientToolResults]);
594
+ }, [chatMessages, clientToolResults]);
609
595
  useEffect(() => {
610
596
  const currentToolCallIds = /* @__PURE__ */ new Set();
611
- for (const msg of useChatHelpers.messages) for (const part of msg.parts) if ("toolCallId" in part && part.toolCallId) currentToolCallIds.add(part.toolCallId);
597
+ for (const msg of chatMessages) for (const part of msg.parts) if ("toolCallId" in part && part.toolCallId) currentToolCallIds.add(part.toolCallId);
612
598
  setClientToolResults((prev) => {
613
599
  if (prev.size === 0) return prev;
614
600
  let hasStaleEntries = false;
@@ -622,16 +608,16 @@ function useAgentChat(options) {
622
608
  return newMap;
623
609
  });
624
610
  for (const toolCallId of processedToolCalls.current) if (!currentToolCallIds.has(toolCallId)) processedToolCalls.current.delete(toolCallId);
625
- }, [useChatHelpers.messages]);
611
+ }, [chatMessages]);
626
612
  const addToolOutput = useCallback((opts) => {
627
613
  const toolName = opts.toolName ?? "";
628
614
  sendToolOutputToServer(opts.toolCallId, toolName, opts.output);
629
- useChatHelpers.addToolResult({
615
+ addToolResult({
630
616
  tool: toolName,
631
617
  toolCallId: opts.toolCallId,
632
618
  output: opts.output
633
619
  });
634
- }, [sendToolOutputToServer, useChatHelpers.addToolResult]);
620
+ }, [sendToolOutputToServer, addToolResult]);
635
621
  return {
636
622
  ...useChatHelpers,
637
623
  messages: messagesWithToolResults,
@@ -639,15 +625,18 @@ function useAgentChat(options) {
639
625
  addToolResult: addToolResultAndSendMessage,
640
626
  addToolApprovalResponse: addToolApprovalResponseAndNotifyServer,
641
627
  clearHistory: () => {
642
- useChatHelpers.setMessages([]);
628
+ setMessages([]);
643
629
  setClientToolResults(/* @__PURE__ */ new Map());
644
630
  processedToolCalls.current.clear();
645
631
  agent.send(JSON.stringify({ type: MessageType.CF_AGENT_CHAT_CLEAR }));
646
632
  },
647
- setMessages: (messages) => {
648
- useChatHelpers.setMessages(messages);
633
+ setMessages: (messagesOrUpdater) => {
634
+ let resolvedMessages;
635
+ if (typeof messagesOrUpdater === "function") resolvedMessages = messagesOrUpdater(messagesRef.current);
636
+ else resolvedMessages = messagesOrUpdater;
637
+ setMessages(resolvedMessages);
649
638
  agent.send(JSON.stringify({
650
- messages: Array.isArray(messages) ? messages : [],
639
+ messages: resolvedMessages,
651
640
  type: MessageType.CF_AGENT_CHAT_MESSAGES
652
641
  }));
653
642
  }