agents 0.0.0-d72c6a2 → 0.0.0-d7b2f14

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 (85) hide show
  1. package/README.md +5 -3
  2. package/dist/ai-chat-agent.d.ts +99 -19
  3. package/dist/ai-chat-agent.js +804 -351
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration-BSiGZmYU.js +155 -0
  6. package/dist/ai-chat-v5-migration-BSiGZmYU.js.map +1 -0
  7. package/dist/ai-chat-v5-migration.d.ts +7 -4
  8. package/dist/ai-chat-v5-migration.js +3 -19
  9. package/dist/ai-react.d.ts +25 -23
  10. package/dist/ai-react.js +409 -304
  11. package/dist/ai-react.js.map +1 -1
  12. package/dist/ai-types-81H_-Uxh.d.ts +103 -0
  13. package/dist/ai-types-CrMqkwc_.js +24 -0
  14. package/dist/ai-types-CrMqkwc_.js.map +1 -0
  15. package/dist/ai-types.d.ts +6 -91
  16. package/dist/ai-types.js +3 -7
  17. package/dist/cli/index.d.ts +1 -0
  18. package/dist/cli/index.js +28 -0
  19. package/dist/cli/index.js.map +1 -0
  20. package/dist/client-B3SR12TQ.js +117 -0
  21. package/dist/client-B3SR12TQ.js.map +1 -0
  22. package/dist/client-BAQA84dr.d.ts +104 -0
  23. package/dist/client-CFhjXCiO.js +1093 -0
  24. package/dist/client-CFhjXCiO.js.map +1 -0
  25. package/dist/client-z9RQJDtK.d.ts +833 -0
  26. package/dist/client.d.ts +11 -92
  27. package/dist/client.js +4 -12
  28. package/dist/codemode/ai.d.ts +27 -0
  29. package/dist/codemode/ai.js +151 -0
  30. package/dist/codemode/ai.js.map +1 -0
  31. package/dist/do-oauth-client-provider-C2CHH5x-.d.ts +55 -0
  32. package/dist/do-oauth-client-provider-CwqK5SXm.js +94 -0
  33. package/dist/do-oauth-client-provider-CwqK5SXm.js.map +1 -0
  34. package/dist/index-BUle9RiP.d.ts +58 -0
  35. package/dist/index-D3s0zwxa.d.ts +587 -0
  36. package/dist/index.d.ts +56 -550
  37. package/dist/index.js +7 -31
  38. package/dist/mcp/client.d.ts +4 -11
  39. package/dist/mcp/client.js +4 -9
  40. package/dist/mcp/do-oauth-client-provider.d.ts +2 -42
  41. package/dist/mcp/do-oauth-client-provider.js +3 -7
  42. package/dist/mcp/index.d.ts +188 -92
  43. package/dist/mcp/index.js +1430 -1012
  44. package/dist/mcp/index.js.map +1 -1
  45. package/dist/mcp/x402.d.ts +34 -0
  46. package/dist/mcp/x402.js +198 -0
  47. package/dist/mcp/x402.js.map +1 -0
  48. package/dist/mcp-BwPscEiF.d.ts +61 -0
  49. package/dist/observability/index.d.ts +3 -46
  50. package/dist/observability/index.js +7 -11
  51. package/dist/react-D9Ou_tyQ.d.ts +113 -0
  52. package/dist/react.d.ts +10 -123
  53. package/dist/react.js +183 -112
  54. package/dist/react.js.map +1 -1
  55. package/dist/schedule.d.ts +13 -10
  56. package/dist/schedule.js +43 -31
  57. package/dist/schedule.js.map +1 -1
  58. package/dist/serializable-faDkMCai.d.ts +39 -0
  59. package/dist/serializable.d.ts +7 -32
  60. package/dist/serializable.js +1 -1
  61. package/dist/src-CNAXL7wY.js +1182 -0
  62. package/dist/src-CNAXL7wY.js.map +1 -0
  63. package/package.json +71 -32
  64. package/dist/ai-chat-v5-migration.js.map +0 -1
  65. package/dist/ai-types.js.map +0 -1
  66. package/dist/chunk-AVYJQSLW.js +0 -17
  67. package/dist/chunk-AVYJQSLW.js.map +0 -1
  68. package/dist/chunk-LL2AFX7V.js +0 -109
  69. package/dist/chunk-LL2AFX7V.js.map +0 -1
  70. package/dist/chunk-MH46VMM4.js +0 -612
  71. package/dist/chunk-MH46VMM4.js.map +0 -1
  72. package/dist/chunk-QEVM4BVL.js +0 -116
  73. package/dist/chunk-QEVM4BVL.js.map +0 -1
  74. package/dist/chunk-UJVEAURM.js +0 -150
  75. package/dist/chunk-UJVEAURM.js.map +0 -1
  76. package/dist/chunk-YDUDMOL6.js +0 -1296
  77. package/dist/chunk-YDUDMOL6.js.map +0 -1
  78. package/dist/client-CvaJdLQA.d.ts +0 -5015
  79. package/dist/client.js.map +0 -1
  80. package/dist/index.js.map +0 -1
  81. package/dist/mcp/client.js.map +0 -1
  82. package/dist/mcp/do-oauth-client-provider.js.map +0 -1
  83. package/dist/observability/index.js.map +0 -1
  84. package/dist/serializable.js.map +0 -1
  85. package/src/index.ts +0 -1947
package/dist/ai-react.js CHANGED
@@ -1,310 +1,415 @@
1
- import "./chunk-AVYJQSLW.js";
2
-
3
- // src/ai-react.tsx
4
- import { useChat } from "@ai-sdk/react";
5
- import { getToolName, isToolUIPart } from "ai";
6
- import { DefaultChatTransport } from "ai";
1
+ import { t as MessageType } from "./ai-types-CrMqkwc_.js";
7
2
  import { nanoid } from "nanoid";
8
- import { use, useEffect, useRef } from "react";
9
- var requestCache = /* @__PURE__ */ new Map();
3
+ import { useChat } from "@ai-sdk/react";
4
+ import { DefaultChatTransport, getToolName, isToolUIPart } from "ai";
5
+ import { use, useCallback, useEffect, useMemo, useRef } from "react";
6
+
7
+ //#region src/ai-react.tsx
8
+ const requestCache = /* @__PURE__ */ new Map();
9
+ /**
10
+ * React hook for building AI chat interfaces using an Agent
11
+ * @param options Chat options including the agent connection
12
+ * @returns Chat interface controls and state with added clearHistory method
13
+ */
14
+ /**
15
+ * Automatically detects which tools require confirmation based on their configuration.
16
+ * Tools require confirmation if they have no execute function AND are not server-executed.
17
+ * @param tools - Record of tool name to tool definition
18
+ * @returns Array of tool names that require confirmation
19
+ */
10
20
  function detectToolsRequiringConfirmation(tools) {
11
- if (!tools) return [];
12
- return Object.entries(tools).filter(([_name, tool]) => !tool.execute).map(([name]) => name);
21
+ if (!tools) return [];
22
+ return Object.entries(tools).filter(([_name, tool$1]) => !tool$1.execute).map(([name]) => name);
13
23
  }
14
24
  function useAgentChat(options) {
15
- const {
16
- agent,
17
- getInitialMessages,
18
- messages: optionsInitialMessages,
19
- experimental_automaticToolResolution,
20
- tools,
21
- toolsRequiringConfirmation: manualToolsRequiringConfirmation,
22
- ...rest
23
- } = options;
24
- const toolsRequiringConfirmation = manualToolsRequiringConfirmation ?? detectToolsRequiringConfirmation(tools);
25
- const agentUrl = new URL(
26
- `${// @ts-expect-error we're using a protected _url property that includes query params
27
- (agent._url || agent._pkurl)?.replace("ws://", "http://").replace("wss://", "https://")}`
28
- );
29
- agentUrl.searchParams.delete("_pk");
30
- const agentUrlString = agentUrl.toString();
31
- async function defaultGetInitialMessagesFetch({
32
- url
33
- }) {
34
- const getMessagesUrl = new URL(url);
35
- getMessagesUrl.pathname += "/get-messages";
36
- const response = await fetch(getMessagesUrl.toString(), {
37
- credentials: options.credentials,
38
- headers: options.headers
39
- });
40
- if (!response.ok) {
41
- console.warn(
42
- `Failed to fetch initial messages: ${response.status} ${response.statusText}`
43
- );
44
- return [];
45
- }
46
- const text = await response.text();
47
- if (!text.trim()) {
48
- return [];
49
- }
50
- try {
51
- return JSON.parse(text);
52
- } catch (error) {
53
- console.warn("Failed to parse initial messages JSON:", error);
54
- return [];
55
- }
56
- }
57
- const getInitialMessagesFetch = getInitialMessages || defaultGetInitialMessagesFetch;
58
- function doGetInitialMessages(getInitialMessagesOptions) {
59
- if (requestCache.has(agentUrlString)) {
60
- return requestCache.get(agentUrlString);
61
- }
62
- const promise = getInitialMessagesFetch(getInitialMessagesOptions);
63
- requestCache.set(agentUrlString, promise);
64
- return promise;
65
- }
66
- const initialMessagesPromise = getInitialMessages === null ? null : doGetInitialMessages({
67
- agent: agent.agent,
68
- name: agent.name,
69
- url: agentUrlString
70
- });
71
- const initialMessages = initialMessagesPromise ? use(initialMessagesPromise) : optionsInitialMessages ?? [];
72
- useEffect(() => {
73
- if (!initialMessagesPromise) {
74
- return;
75
- }
76
- requestCache.set(agentUrlString, initialMessagesPromise);
77
- return () => {
78
- if (requestCache.get(agentUrlString) === initialMessagesPromise) {
79
- requestCache.delete(agentUrlString);
80
- }
81
- };
82
- }, [agentUrlString, initialMessagesPromise]);
83
- async function aiFetch(request, options2 = {}) {
84
- const {
85
- method,
86
- keepalive,
87
- headers,
88
- body,
89
- redirect,
90
- integrity,
91
- signal,
92
- credentials,
93
- mode,
94
- referrer,
95
- referrerPolicy,
96
- window
97
- } = options2;
98
- const id = nanoid(8);
99
- const abortController = new AbortController();
100
- let controller;
101
- let isToolCallInProgress = false;
102
- signal?.addEventListener("abort", () => {
103
- agent.send(
104
- JSON.stringify({
105
- id,
106
- type: "cf_agent_chat_request_cancel" /* CF_AGENT_CHAT_REQUEST_CANCEL */
107
- })
108
- );
109
- abortController.abort();
110
- if (!isToolCallInProgress) {
111
- controller.close();
112
- }
113
- });
114
- agent.addEventListener(
115
- "message",
116
- (event) => {
117
- let data;
118
- try {
119
- data = JSON.parse(event.data);
120
- } catch (_error) {
121
- return;
122
- }
123
- if (data.type === "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */) {
124
- if (data.id === id) {
125
- if (data.error) {
126
- controller.error(new Error(data.body));
127
- abortController.abort();
128
- } else {
129
- if (data.body?.trim()) {
130
- if (data.body.includes('"tool_calls"')) {
131
- isToolCallInProgress = true;
132
- }
133
- controller.enqueue(
134
- new TextEncoder().encode(`data: ${data.body}
135
-
136
- `)
137
- );
138
- }
139
- if (data.done && !isToolCallInProgress) {
140
- controller.close();
141
- abortController.abort();
142
- }
143
- }
144
- }
145
- }
146
- },
147
- { signal: abortController.signal }
148
- );
149
- const stream = new ReadableStream({
150
- start(c) {
151
- controller = c;
152
- }
153
- });
154
- agent.send(
155
- JSON.stringify({
156
- id,
157
- init: {
158
- body,
159
- credentials,
160
- headers,
161
- integrity,
162
- keepalive,
163
- method,
164
- mode,
165
- redirect,
166
- referrer,
167
- referrerPolicy,
168
- window
169
- },
170
- type: "cf_agent_use_chat_request" /* CF_AGENT_USE_CHAT_REQUEST */,
171
- url: request.toString()
172
- })
173
- );
174
- return new Response(stream);
175
- }
176
- const customTransport = {
177
- sendMessages: async (options2) => {
178
- const transport = new DefaultChatTransport({
179
- api: agentUrlString,
180
- fetch: aiFetch
181
- });
182
- return transport.sendMessages(options2);
183
- },
184
- reconnectToStream: async (options2) => {
185
- const transport = new DefaultChatTransport({
186
- api: agentUrlString,
187
- fetch: aiFetch
188
- });
189
- return transport.reconnectToStream(options2);
190
- }
191
- };
192
- const useChatHelpers = useChat({
193
- ...rest,
194
- messages: initialMessages,
195
- transport: customTransport
196
- });
197
- const processedToolCalls = useRef(/* @__PURE__ */ new Set());
198
- useEffect(() => {
199
- if (!experimental_automaticToolResolution) {
200
- return;
201
- }
202
- const lastMessage = useChatHelpers.messages[useChatHelpers.messages.length - 1];
203
- if (!lastMessage || lastMessage.role !== "assistant") {
204
- return;
205
- }
206
- const toolCalls = lastMessage.parts.filter(
207
- (part) => isToolUIPart(part) && part.state === "input-available" && !processedToolCalls.current.has(part.toolCallId)
208
- );
209
- if (toolCalls.length > 0) {
210
- (async () => {
211
- const toolCallsToResolve = toolCalls.filter(
212
- (part) => isToolUIPart(part) && !toolsRequiringConfirmation.includes(getToolName(part)) && tools?.[getToolName(part)]?.execute
213
- // Only execute if client has execute function
214
- );
215
- if (toolCallsToResolve.length > 0) {
216
- for (const part of toolCallsToResolve) {
217
- if (isToolUIPart(part)) {
218
- processedToolCalls.current.add(part.toolCallId);
219
- let toolOutput = null;
220
- const toolName = getToolName(part);
221
- const tool = tools?.[toolName];
222
- if (tool?.execute && part.input) {
223
- try {
224
- toolOutput = await tool.execute(part.input);
225
- } catch (error) {
226
- toolOutput = `Error executing tool: ${error instanceof Error ? error.message : String(error)}`;
227
- }
228
- }
229
- await useChatHelpers.addToolResult({
230
- toolCallId: part.toolCallId,
231
- tool: toolName,
232
- output: toolOutput
233
- });
234
- }
235
- }
236
- useChatHelpers.sendMessage();
237
- }
238
- })();
239
- }
240
- }, [
241
- useChatHelpers.messages,
242
- experimental_automaticToolResolution,
243
- useChatHelpers.addToolResult,
244
- useChatHelpers.sendMessage,
245
- toolsRequiringConfirmation
246
- ]);
247
- useEffect(() => {
248
- function onClearHistory(event) {
249
- if (typeof event.data !== "string") return;
250
- let data;
251
- try {
252
- data = JSON.parse(event.data);
253
- } catch (_error) {
254
- return;
255
- }
256
- if (data.type === "cf_agent_chat_clear" /* CF_AGENT_CHAT_CLEAR */) {
257
- useChatHelpers.setMessages([]);
258
- }
259
- }
260
- function onMessages(event) {
261
- if (typeof event.data !== "string") return;
262
- let data;
263
- try {
264
- data = JSON.parse(event.data);
265
- } catch (_error) {
266
- return;
267
- }
268
- if (data.type === "cf_agent_chat_messages" /* CF_AGENT_CHAT_MESSAGES */) {
269
- useChatHelpers.setMessages(data.messages);
270
- }
271
- }
272
- agent.addEventListener("message", onClearHistory);
273
- agent.addEventListener("message", onMessages);
274
- return () => {
275
- agent.removeEventListener("message", onClearHistory);
276
- agent.removeEventListener("message", onMessages);
277
- };
278
- }, [agent, useChatHelpers.setMessages]);
279
- const { addToolResult } = useChatHelpers;
280
- const addToolResultAndSendMessage = async (...args) => {
281
- await addToolResult(...args);
282
- useChatHelpers.sendMessage();
283
- };
284
- return {
285
- ...useChatHelpers,
286
- addToolResult: addToolResultAndSendMessage,
287
- clearHistory: () => {
288
- useChatHelpers.setMessages([]);
289
- agent.send(
290
- JSON.stringify({
291
- type: "cf_agent_chat_clear" /* CF_AGENT_CHAT_CLEAR */
292
- })
293
- );
294
- },
295
- setMessages: (messages) => {
296
- useChatHelpers.setMessages(messages);
297
- agent.send(
298
- JSON.stringify({
299
- messages: Array.isArray(messages) ? messages : [],
300
- type: "cf_agent_chat_messages" /* CF_AGENT_CHAT_MESSAGES */
301
- })
302
- );
303
- }
304
- };
25
+ const { agent, getInitialMessages, messages: optionsInitialMessages, experimental_automaticToolResolution, tools, toolsRequiringConfirmation: manualToolsRequiringConfirmation, autoSendAfterAllConfirmationsResolved = true, resume = true, ...rest } = options;
26
+ const toolsRequiringConfirmation = manualToolsRequiringConfirmation ?? detectToolsRequiringConfirmation(tools);
27
+ const agentUrl = new URL(`${(agent._url || agent._pkurl)?.replace("ws://", "http://").replace("wss://", "https://")}`);
28
+ agentUrl.searchParams.delete("_pk");
29
+ const agentUrlString = agentUrl.toString();
30
+ const initialMessagesCacheKey = `${agentUrlString}|${agent.agent ?? ""}|${agent.name ?? ""}`;
31
+ const agentRef = useRef(agent);
32
+ useEffect(() => {
33
+ agentRef.current = agent;
34
+ }, [agent]);
35
+ async function defaultGetInitialMessagesFetch({ url }) {
36
+ const getMessagesUrl = new URL(url);
37
+ getMessagesUrl.pathname += "/get-messages";
38
+ const response = await fetch(getMessagesUrl.toString(), {
39
+ credentials: options.credentials,
40
+ headers: options.headers
41
+ });
42
+ if (!response.ok) {
43
+ console.warn(`Failed to fetch initial messages: ${response.status} ${response.statusText}`);
44
+ return [];
45
+ }
46
+ const text = await response.text();
47
+ if (!text.trim()) return [];
48
+ try {
49
+ return JSON.parse(text);
50
+ } catch (error) {
51
+ console.warn("Failed to parse initial messages JSON:", error);
52
+ return [];
53
+ }
54
+ }
55
+ const getInitialMessagesFetch = getInitialMessages || defaultGetInitialMessagesFetch;
56
+ function doGetInitialMessages(getInitialMessagesOptions, cacheKey) {
57
+ if (requestCache.has(cacheKey)) return requestCache.get(cacheKey);
58
+ const promise = getInitialMessagesFetch(getInitialMessagesOptions);
59
+ requestCache.set(cacheKey, promise);
60
+ return promise;
61
+ }
62
+ const initialMessagesPromise = getInitialMessages === null ? null : doGetInitialMessages({
63
+ agent: agent.agent,
64
+ name: agent.name,
65
+ url: agentUrlString
66
+ }, initialMessagesCacheKey);
67
+ const initialMessages = initialMessagesPromise ? use(initialMessagesPromise) : optionsInitialMessages ?? [];
68
+ useEffect(() => {
69
+ if (!initialMessagesPromise) return;
70
+ requestCache.set(initialMessagesCacheKey, initialMessagesPromise);
71
+ return () => {
72
+ if (requestCache.get(initialMessagesCacheKey) === initialMessagesPromise) requestCache.delete(initialMessagesCacheKey);
73
+ };
74
+ }, [initialMessagesCacheKey, initialMessagesPromise]);
75
+ const aiFetch = useCallback(async (request, options$1 = {}) => {
76
+ const { method, keepalive, headers, body, redirect, integrity, signal, credentials, mode, referrer, referrerPolicy, window } = options$1;
77
+ const id = nanoid(8);
78
+ const abortController = new AbortController();
79
+ let controller;
80
+ const currentAgent = agentRef.current;
81
+ localRequestIdsRef.current.add(id);
82
+ signal?.addEventListener("abort", () => {
83
+ currentAgent.send(JSON.stringify({
84
+ id,
85
+ type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL
86
+ }));
87
+ abortController.abort();
88
+ try {
89
+ controller.close();
90
+ } catch {}
91
+ localRequestIdsRef.current.delete(id);
92
+ });
93
+ currentAgent.addEventListener("message", (event) => {
94
+ let data;
95
+ try {
96
+ data = JSON.parse(event.data);
97
+ } catch (_error) {
98
+ return;
99
+ }
100
+ if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE) {
101
+ if (data.id === id) if (data.error) {
102
+ controller.error(new Error(data.body));
103
+ abortController.abort();
104
+ localRequestIdsRef.current.delete(id);
105
+ } else {
106
+ if (data.body?.trim()) controller.enqueue(new TextEncoder().encode(`data: ${data.body}\n\n`));
107
+ if (data.done) {
108
+ try {
109
+ controller.close();
110
+ } catch {}
111
+ abortController.abort();
112
+ localRequestIdsRef.current.delete(id);
113
+ }
114
+ }
115
+ }
116
+ }, { signal: abortController.signal });
117
+ const stream = new ReadableStream({
118
+ start(c) {
119
+ controller = c;
120
+ },
121
+ cancel(reason) {
122
+ console.warn("[agents/ai-react] cancelling stream", id, reason || "no reason");
123
+ }
124
+ });
125
+ currentAgent.send(JSON.stringify({
126
+ id,
127
+ init: {
128
+ body,
129
+ credentials,
130
+ headers,
131
+ integrity,
132
+ keepalive,
133
+ method,
134
+ mode,
135
+ redirect,
136
+ referrer,
137
+ referrerPolicy,
138
+ window
139
+ },
140
+ type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
141
+ url: request.toString()
142
+ }));
143
+ return new Response(stream);
144
+ }, []);
145
+ const customTransport = useMemo(() => ({
146
+ sendMessages: async (options$1) => {
147
+ return new DefaultChatTransport({
148
+ api: agentUrlString,
149
+ fetch: aiFetch
150
+ }).sendMessages(options$1);
151
+ },
152
+ reconnectToStream: async () => null
153
+ }), [agentUrlString, aiFetch]);
154
+ const useChatHelpers = useChat({
155
+ ...rest,
156
+ messages: initialMessages,
157
+ transport: customTransport,
158
+ id: agent._pk
159
+ });
160
+ const processedToolCalls = useRef(/* @__PURE__ */ new Set());
161
+ const lastMessage = useChatHelpers.messages[useChatHelpers.messages.length - 1];
162
+ const pendingConfirmations = (() => {
163
+ if (!lastMessage || lastMessage.role !== "assistant") return {
164
+ messageId: void 0,
165
+ toolCallIds: /* @__PURE__ */ new Set()
166
+ };
167
+ const pendingIds = /* @__PURE__ */ new Set();
168
+ for (const part of lastMessage.parts ?? []) if (isToolUIPart(part) && part.state === "input-available" && toolsRequiringConfirmation.includes(getToolName(part))) pendingIds.add(part.toolCallId);
169
+ return {
170
+ messageId: lastMessage.id,
171
+ toolCallIds: pendingIds
172
+ };
173
+ })();
174
+ const pendingConfirmationsRef = useRef(pendingConfirmations);
175
+ pendingConfirmationsRef.current = pendingConfirmations;
176
+ useEffect(() => {
177
+ if (!experimental_automaticToolResolution) return;
178
+ const lastMessage$1 = useChatHelpers.messages[useChatHelpers.messages.length - 1];
179
+ if (!lastMessage$1 || lastMessage$1.role !== "assistant") return;
180
+ const toolCalls = lastMessage$1.parts.filter((part) => isToolUIPart(part) && part.state === "input-available" && !processedToolCalls.current.has(part.toolCallId));
181
+ if (toolCalls.length > 0) (async () => {
182
+ const toolCallsToResolve = toolCalls.filter((part) => isToolUIPart(part) && !toolsRequiringConfirmation.includes(getToolName(part)) && tools?.[getToolName(part)]?.execute);
183
+ if (toolCallsToResolve.length > 0) {
184
+ for (const part of toolCallsToResolve) if (isToolUIPart(part)) {
185
+ processedToolCalls.current.add(part.toolCallId);
186
+ let toolOutput = null;
187
+ const toolName = getToolName(part);
188
+ const tool$1 = tools?.[toolName];
189
+ if (tool$1?.execute && part.input) try {
190
+ toolOutput = await tool$1.execute(part.input);
191
+ } catch (error) {
192
+ toolOutput = `Error executing tool: ${error instanceof Error ? error.message : String(error)}`;
193
+ }
194
+ await useChatHelpers.addToolResult({
195
+ toolCallId: part.toolCallId,
196
+ tool: toolName,
197
+ output: toolOutput
198
+ });
199
+ }
200
+ if (pendingConfirmationsRef.current.toolCallIds.size === 0) useChatHelpers.sendMessage();
201
+ }
202
+ })();
203
+ }, [
204
+ useChatHelpers.messages,
205
+ experimental_automaticToolResolution,
206
+ useChatHelpers.addToolResult,
207
+ useChatHelpers.sendMessage,
208
+ toolsRequiringConfirmation
209
+ ]);
210
+ /**
211
+ * Contains the request ID, accumulated message parts, and a unique message ID.
212
+ * Used for both resumed streams and real-time broadcasts from other tabs.
213
+ */
214
+ const activeStreamRef = useRef(null);
215
+ /**
216
+ * Tracks request IDs initiated by this tab via aiFetch.
217
+ * Used to distinguish local requests from broadcasts.
218
+ */
219
+ const localRequestIdsRef = useRef(/* @__PURE__ */ new Set());
220
+ useEffect(() => {
221
+ /**
222
+ * Unified message handler that parses JSON once and dispatches based on type.
223
+ * Avoids duplicate parsing overhead from separate listeners.
224
+ */
225
+ function onAgentMessage(event) {
226
+ if (typeof event.data !== "string") return;
227
+ let data;
228
+ try {
229
+ data = JSON.parse(event.data);
230
+ } catch (_error) {
231
+ return;
232
+ }
233
+ switch (data.type) {
234
+ case MessageType.CF_AGENT_CHAT_CLEAR:
235
+ useChatHelpers.setMessages([]);
236
+ break;
237
+ case MessageType.CF_AGENT_CHAT_MESSAGES:
238
+ useChatHelpers.setMessages(data.messages);
239
+ break;
240
+ case MessageType.CF_AGENT_STREAM_RESUMING:
241
+ if (!resume) return;
242
+ activeStreamRef.current = null;
243
+ activeStreamRef.current = {
244
+ id: data.id,
245
+ messageId: nanoid(),
246
+ parts: []
247
+ };
248
+ agentRef.current.send(JSON.stringify({
249
+ type: MessageType.CF_AGENT_STREAM_RESUME_ACK,
250
+ id: data.id
251
+ }));
252
+ break;
253
+ case MessageType.CF_AGENT_USE_CHAT_RESPONSE: {
254
+ if (localRequestIdsRef.current.has(data.id)) return;
255
+ if (!activeStreamRef.current || activeStreamRef.current.id !== data.id) activeStreamRef.current = {
256
+ id: data.id,
257
+ messageId: nanoid(),
258
+ parts: []
259
+ };
260
+ const activeMsg = activeStreamRef.current;
261
+ if (data.body?.trim()) try {
262
+ const chunkData = JSON.parse(data.body);
263
+ switch (chunkData.type) {
264
+ case "text-start":
265
+ activeMsg.parts.push({
266
+ type: "text",
267
+ text: "",
268
+ state: "streaming"
269
+ });
270
+ break;
271
+ case "text-delta": {
272
+ const lastTextPart = [...activeMsg.parts].reverse().find((p) => p.type === "text");
273
+ if (lastTextPart && lastTextPart.type === "text") lastTextPart.text += chunkData.delta;
274
+ else activeMsg.parts.push({
275
+ type: "text",
276
+ text: chunkData.delta
277
+ });
278
+ break;
279
+ }
280
+ case "text-end": {
281
+ const lastTextPart = [...activeMsg.parts].reverse().find((p) => p.type === "text");
282
+ if (lastTextPart && "state" in lastTextPart) lastTextPart.state = "done";
283
+ break;
284
+ }
285
+ case "reasoning-start":
286
+ activeMsg.parts.push({
287
+ type: "reasoning",
288
+ text: "",
289
+ state: "streaming"
290
+ });
291
+ break;
292
+ case "reasoning-delta": {
293
+ const lastReasoningPart = [...activeMsg.parts].reverse().find((p) => p.type === "reasoning");
294
+ if (lastReasoningPart && lastReasoningPart.type === "reasoning") lastReasoningPart.text += chunkData.delta;
295
+ break;
296
+ }
297
+ case "reasoning-end": {
298
+ const lastReasoningPart = [...activeMsg.parts].reverse().find((p) => p.type === "reasoning");
299
+ if (lastReasoningPart && "state" in lastReasoningPart) lastReasoningPart.state = "done";
300
+ break;
301
+ }
302
+ case "file":
303
+ activeMsg.parts.push({
304
+ type: "file",
305
+ mediaType: chunkData.mediaType,
306
+ url: chunkData.url
307
+ });
308
+ break;
309
+ case "source-url":
310
+ activeMsg.parts.push({
311
+ type: "source-url",
312
+ sourceId: chunkData.sourceId,
313
+ url: chunkData.url,
314
+ title: chunkData.title
315
+ });
316
+ break;
317
+ case "source-document":
318
+ activeMsg.parts.push({
319
+ type: "source-document",
320
+ sourceId: chunkData.sourceId,
321
+ mediaType: chunkData.mediaType,
322
+ title: chunkData.title,
323
+ filename: chunkData.filename
324
+ });
325
+ break;
326
+ case "tool-input-available":
327
+ activeMsg.parts.push({
328
+ type: `tool-${chunkData.toolName}`,
329
+ toolCallId: chunkData.toolCallId,
330
+ toolName: chunkData.toolName,
331
+ state: "input-available",
332
+ input: chunkData.input
333
+ });
334
+ break;
335
+ case "tool-output-available": {
336
+ const toolPart = activeMsg.parts.find((p) => "toolCallId" in p && p.toolCallId === chunkData.toolCallId);
337
+ if (toolPart && "state" in toolPart) {
338
+ toolPart.state = "output-available";
339
+ toolPart.output = chunkData.output;
340
+ }
341
+ break;
342
+ }
343
+ case "step-start":
344
+ activeMsg.parts.push({ type: "step-start" });
345
+ break;
346
+ }
347
+ useChatHelpers.setMessages((prevMessages) => {
348
+ if (!activeMsg) return prevMessages;
349
+ const existingIdx = prevMessages.findIndex((m) => m.id === activeMsg.messageId);
350
+ const partialMessage = {
351
+ id: activeMsg.messageId,
352
+ role: "assistant",
353
+ parts: [...activeMsg.parts]
354
+ };
355
+ if (existingIdx >= 0) {
356
+ const updated = [...prevMessages];
357
+ updated[existingIdx] = partialMessage;
358
+ return updated;
359
+ }
360
+ return [...prevMessages, partialMessage];
361
+ });
362
+ } catch (parseError) {
363
+ console.warn("[useAgentChat] Failed to parse stream chunk:", parseError instanceof Error ? parseError.message : parseError, "body:", data.body?.slice(0, 100));
364
+ }
365
+ if (data.done || data.error) activeStreamRef.current = null;
366
+ break;
367
+ }
368
+ }
369
+ }
370
+ agent.addEventListener("message", onAgentMessage);
371
+ return () => {
372
+ agent.removeEventListener("message", onAgentMessage);
373
+ activeStreamRef.current = null;
374
+ };
375
+ }, [
376
+ agent,
377
+ useChatHelpers.setMessages,
378
+ resume
379
+ ]);
380
+ const addToolResultAndSendMessage = async (args) => {
381
+ const { toolCallId } = args;
382
+ await useChatHelpers.addToolResult(args);
383
+ if (!autoSendAfterAllConfirmationsResolved) {
384
+ useChatHelpers.sendMessage();
385
+ return;
386
+ }
387
+ const pending = pendingConfirmationsRef.current?.toolCallIds;
388
+ if (!pending) {
389
+ useChatHelpers.sendMessage();
390
+ return;
391
+ }
392
+ const wasLast = pending.size === 1 && pending.has(toolCallId);
393
+ if (pending.has(toolCallId)) pending.delete(toolCallId);
394
+ if (wasLast || pending.size === 0) useChatHelpers.sendMessage();
395
+ };
396
+ return {
397
+ ...useChatHelpers,
398
+ addToolResult: addToolResultAndSendMessage,
399
+ clearHistory: () => {
400
+ useChatHelpers.setMessages([]);
401
+ agent.send(JSON.stringify({ type: MessageType.CF_AGENT_CHAT_CLEAR }));
402
+ },
403
+ setMessages: (messages) => {
404
+ useChatHelpers.setMessages(messages);
405
+ agent.send(JSON.stringify({
406
+ messages: Array.isArray(messages) ? messages : [],
407
+ type: MessageType.CF_AGENT_CHAT_MESSAGES
408
+ }));
409
+ }
410
+ };
305
411
  }
306
- export {
307
- detectToolsRequiringConfirmation,
308
- useAgentChat
309
- };
412
+
413
+ //#endregion
414
+ export { detectToolsRequiringConfirmation, useAgentChat };
310
415
  //# sourceMappingURL=ai-react.js.map