agents 0.0.0-e48e5f9 → 0.0.0-e777fdd

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 (67) hide show
  1. package/README.md +234 -6
  2. package/dist/_esm-LV5FJ3HK.js +3922 -0
  3. package/dist/_esm-LV5FJ3HK.js.map +1 -0
  4. package/dist/ai-chat-agent.d.ts +12 -9
  5. package/dist/ai-chat-agent.js +151 -59
  6. package/dist/ai-chat-agent.js.map +1 -1
  7. package/dist/ai-chat-v5-migration.d.ts +152 -0
  8. package/dist/ai-chat-v5-migration.js +20 -0
  9. package/dist/ai-chat-v5-migration.js.map +1 -0
  10. package/dist/ai-react.d.ts +68 -71
  11. package/dist/ai-react.js +252 -99
  12. package/dist/ai-react.js.map +1 -1
  13. package/dist/ai-types.d.ts +37 -19
  14. package/dist/ai-types.js +7 -0
  15. package/dist/ccip-CMBYN64O.js +15 -0
  16. package/dist/ccip-CMBYN64O.js.map +1 -0
  17. package/dist/chunk-5Y6BEZDY.js +276 -0
  18. package/dist/chunk-5Y6BEZDY.js.map +1 -0
  19. package/dist/chunk-BER7KXUJ.js +18 -0
  20. package/dist/chunk-BER7KXUJ.js.map +1 -0
  21. package/dist/chunk-JJBFIGUC.js +5202 -0
  22. package/dist/chunk-JJBFIGUC.js.map +1 -0
  23. package/dist/chunk-PR4QN5HX.js +43 -0
  24. package/dist/chunk-PR4QN5HX.js.map +1 -0
  25. package/dist/{chunk-MW5BQ2FW.js → chunk-QEPGNUG6.js} +213 -32
  26. package/dist/chunk-QEPGNUG6.js.map +1 -0
  27. package/dist/{chunk-KUH345EY.js → chunk-QEVM4BVL.js} +5 -5
  28. package/dist/chunk-QEVM4BVL.js.map +1 -0
  29. package/dist/{chunk-5YIRLLUX.js → chunk-RS5OCNEQ.js} +169 -110
  30. package/dist/chunk-RS5OCNEQ.js.map +1 -0
  31. package/dist/chunk-TYAY6AU6.js +159 -0
  32. package/dist/chunk-TYAY6AU6.js.map +1 -0
  33. package/dist/chunk-UJVEAURM.js +150 -0
  34. package/dist/chunk-UJVEAURM.js.map +1 -0
  35. package/dist/{chunk-PVQZBKN7.js → chunk-XFS5ERG3.js} +24 -3
  36. package/dist/chunk-XFS5ERG3.js.map +1 -0
  37. package/dist/client-BohGLma8.d.ts +5041 -0
  38. package/dist/client.js +3 -1
  39. package/dist/index.d.ts +564 -32
  40. package/dist/index.js +8 -4
  41. package/dist/mcp/client.d.ts +9 -1053
  42. package/dist/mcp/client.js +2 -1
  43. package/dist/mcp/do-oauth-client-provider.d.ts +9 -0
  44. package/dist/mcp/do-oauth-client-provider.js +2 -1
  45. package/dist/mcp/index.d.ts +57 -63
  46. package/dist/mcp/index.js +954 -638
  47. package/dist/mcp/index.js.map +1 -1
  48. package/dist/mcp/x402.d.ts +39 -0
  49. package/dist/mcp/x402.js +3195 -0
  50. package/dist/mcp/x402.js.map +1 -0
  51. package/dist/observability/index.d.ts +46 -12
  52. package/dist/observability/index.js +6 -4
  53. package/dist/react.d.ts +7 -3
  54. package/dist/react.js +8 -5
  55. package/dist/react.js.map +1 -1
  56. package/dist/schedule.d.ts +83 -9
  57. package/dist/schedule.js +17 -2
  58. package/dist/schedule.js.map +1 -1
  59. package/dist/secp256k1-M22GZP2U.js +2193 -0
  60. package/dist/secp256k1-M22GZP2U.js.map +1 -0
  61. package/package.json +25 -9
  62. package/src/index.ts +240 -131
  63. package/dist/chunk-5YIRLLUX.js.map +0 -1
  64. package/dist/chunk-KUH345EY.js.map +0 -1
  65. package/dist/chunk-MW5BQ2FW.js.map +0 -1
  66. package/dist/chunk-PVQZBKN7.js.map +0 -1
  67. package/dist/index-BIJvkfYt.d.ts +0 -614
@@ -1,101 +1,98 @@
1
- import * as ai from "ai";
2
- import { Message } from "ai";
3
- import { useChat } from "@ai-sdk/react";
1
+ import { UseChatOptions, useChat } from "@ai-sdk/react";
2
+ import { UIMessage, ChatInit } from "ai";
4
3
  import { useAgent } from "./react.js";
5
4
  import "partysocket";
6
5
  import "partysocket/react";
7
- import "./index-BIJvkfYt.js";
6
+ import "./index.js";
7
+ import "cloudflare:workers";
8
8
  import "@modelcontextprotocol/sdk/client/index.js";
9
9
  import "@modelcontextprotocol/sdk/types.js";
10
10
  import "partyserver";
11
- import "./mcp/client.js";
11
+ import "./client-BohGLma8.js";
12
12
  import "zod";
13
- import "@modelcontextprotocol/sdk/client/sse.js";
14
13
  import "@modelcontextprotocol/sdk/shared/protocol.js";
14
+ import "@modelcontextprotocol/sdk/client/sse.js";
15
+ import "@modelcontextprotocol/sdk/client/streamableHttp.js";
15
16
  import "./mcp/do-oauth-client-provider.js";
16
17
  import "@modelcontextprotocol/sdk/client/auth.js";
17
18
  import "@modelcontextprotocol/sdk/shared/auth.js";
19
+ import "./observability/index.js";
20
+ import "./ai-types.js";
18
21
  import "./client.js";
19
22
  import "./serializable.js";
20
23
 
24
+ type AITool<Input = unknown, Output = unknown> = {
25
+ description?: string;
26
+ inputSchema?: unknown;
27
+ execute?: (input: Input) => Output | Promise<Output>;
28
+ };
21
29
  type GetInitialMessagesOptions = {
22
30
  agent: string;
23
31
  name: string;
24
32
  url: string;
25
33
  };
34
+ type UseChatParams<M extends UIMessage = UIMessage> = ChatInit<M> &
35
+ UseChatOptions<M>;
26
36
  /**
27
37
  * Options for the useAgentChat hook
28
38
  */
29
- type UseAgentChatOptions<State> = Omit<
30
- Parameters<typeof useChat>[0] & {
31
- /** Agent connection from useAgent */
32
- agent: ReturnType<typeof useAgent<State>>;
33
- getInitialMessages?:
34
- | undefined
35
- | null
36
- | ((options: GetInitialMessagesOptions) => Promise<Message[]>);
37
- },
38
- "fetch"
39
- >;
39
+ type UseAgentChatOptions<
40
+ State,
41
+ ChatMessage extends UIMessage = UIMessage
42
+ > = Omit<UseChatParams<ChatMessage>, "fetch"> & {
43
+ /** Agent connection from useAgent */
44
+ agent: ReturnType<typeof useAgent<State>>;
45
+ getInitialMessages?:
46
+ | undefined
47
+ | null
48
+ | ((options: GetInitialMessagesOptions) => Promise<ChatMessage[]>);
49
+ /** Request credentials */
50
+ credentials?: RequestCredentials;
51
+ /** Request headers */
52
+ headers?: HeadersInit;
53
+ /**
54
+ * @description Whether to automatically resolve tool calls that do not require human interaction.
55
+ * @experimental
56
+ */
57
+ experimental_automaticToolResolution?: boolean;
58
+ /**
59
+ * @description Tools object for automatic detection of confirmation requirements.
60
+ * Tools without execute function will require confirmation.
61
+ */
62
+ tools?: Record<string, AITool<unknown, unknown>>;
63
+ /**
64
+ * @description Manual override for tools requiring confirmation.
65
+ * If not provided, will auto-detect from tools object.
66
+ */
67
+ toolsRequiringConfirmation?: string[];
68
+ /**
69
+ * When true (default), automatically sends the next message only after
70
+ * all pending confirmation-required tool calls have been resolved.
71
+ * @default true
72
+ */
73
+ autoSendAfterAllConfirmationsResolved?: boolean;
74
+ };
40
75
  /**
41
76
  * React hook for building AI chat interfaces using an Agent
42
77
  * @param options Chat options including the agent connection
43
78
  * @returns Chat interface controls and state with added clearHistory method
44
79
  */
45
- declare function useAgentChat<State = unknown>(
46
- options: UseAgentChatOptions<State>
47
- ): {
48
- /**
49
- * Clear chat history on both client and Agent
50
- */
80
+ /**
81
+ * Automatically detects which tools require confirmation based on their configuration.
82
+ * Tools require confirmation if they have no execute function AND are not server-executed.
83
+ * @param tools - Record of tool name to tool definition
84
+ * @returns Array of tool names that require confirmation
85
+ */
86
+ declare function detectToolsRequiringConfirmation(
87
+ tools?: Record<string, AITool<unknown, unknown>>
88
+ ): string[];
89
+ declare function useAgentChat<
90
+ State = unknown,
91
+ ChatMessage extends UIMessage = UIMessage
92
+ >(
93
+ options: UseAgentChatOptions<State, ChatMessage>
94
+ ): ReturnType<typeof useChat<ChatMessage>> & {
51
95
  clearHistory: () => void;
52
- /**
53
- * Set the chat messages and synchronize with the Agent
54
- * @param messages New messages to set
55
- */
56
- setMessages: (messages: Message[]) => void;
57
- messages: ai.UIMessage[];
58
- error: undefined | Error;
59
- append: (
60
- message: Message | ai.CreateMessage,
61
- chatRequestOptions?: ai.ChatRequestOptions
62
- ) => Promise<string | null | undefined>;
63
- reload: (
64
- chatRequestOptions?: ai.ChatRequestOptions
65
- ) => Promise<string | null | undefined>;
66
- stop: () => void;
67
- experimental_resume: () => void;
68
- input: string;
69
- setInput: React.Dispatch<React.SetStateAction<string>>;
70
- handleInputChange: (
71
- e:
72
- | React.ChangeEvent<HTMLInputElement>
73
- | React.ChangeEvent<HTMLTextAreaElement>
74
- ) => void;
75
- handleSubmit: (
76
- event?: {
77
- preventDefault?: () => void;
78
- },
79
- chatRequestOptions?: ai.ChatRequestOptions
80
- ) => void;
81
- metadata?: Object;
82
- isLoading: boolean;
83
- status: "submitted" | "streaming" | "ready" | "error";
84
- data?: ai.JSONValue[];
85
- setData: (
86
- data:
87
- | ai.JSONValue[]
88
- | undefined
89
- | ((data: ai.JSONValue[] | undefined) => ai.JSONValue[] | undefined)
90
- ) => void;
91
- id: string;
92
- addToolResult: ({
93
- toolCallId,
94
- result
95
- }: {
96
- toolCallId: string;
97
- result: any;
98
- }) => void;
99
96
  };
100
97
 
101
- export { useAgentChat };
98
+ export { type AITool, detectToolsRequiringConfirmation, useAgentChat };
package/dist/ai-react.js CHANGED
@@ -1,16 +1,39 @@
1
+ import "./chunk-BER7KXUJ.js";
2
+ import "./chunk-PR4QN5HX.js";
3
+
1
4
  // src/ai-react.tsx
2
5
  import { useChat } from "@ai-sdk/react";
6
+ import { getToolName, isToolUIPart } from "ai";
7
+ import { DefaultChatTransport } from "ai";
3
8
  import { nanoid } from "nanoid";
4
- import { use, useEffect } from "react";
9
+ import { use, useCallback, useEffect, useMemo, useRef } from "react";
5
10
  var requestCache = /* @__PURE__ */ new Map();
11
+ function detectToolsRequiringConfirmation(tools) {
12
+ if (!tools) return [];
13
+ return Object.entries(tools).filter(([_name, tool]) => !tool.execute).map(([name]) => name);
14
+ }
6
15
  function useAgentChat(options) {
7
- const { agent, getInitialMessages, ...rest } = options;
16
+ const {
17
+ agent,
18
+ getInitialMessages,
19
+ messages: optionsInitialMessages,
20
+ experimental_automaticToolResolution,
21
+ tools,
22
+ toolsRequiringConfirmation: manualToolsRequiringConfirmation,
23
+ autoSendAfterAllConfirmationsResolved = true,
24
+ ...rest
25
+ } = options;
26
+ const toolsRequiringConfirmation = manualToolsRequiringConfirmation ?? detectToolsRequiringConfirmation(tools);
8
27
  const agentUrl = new URL(
9
28
  `${// @ts-expect-error we're using a protected _url property that includes query params
10
29
  (agent._url || agent._pkurl)?.replace("ws://", "http://").replace("wss://", "https://")}`
11
30
  );
12
31
  agentUrl.searchParams.delete("_pk");
13
32
  const agentUrlString = agentUrl.toString();
33
+ const agentRef = useRef(agent);
34
+ useEffect(() => {
35
+ agentRef.current = agent;
36
+ }, [agent]);
14
37
  async function defaultGetInitialMessagesFetch({
15
38
  url
16
39
  }) {
@@ -20,7 +43,22 @@ function useAgentChat(options) {
20
43
  credentials: options.credentials,
21
44
  headers: options.headers
22
45
  });
23
- return response.json();
46
+ if (!response.ok) {
47
+ console.warn(
48
+ `Failed to fetch initial messages: ${response.status} ${response.statusText}`
49
+ );
50
+ return [];
51
+ }
52
+ const text = await response.text();
53
+ if (!text.trim()) {
54
+ return [];
55
+ }
56
+ try {
57
+ return JSON.parse(text);
58
+ } catch (error) {
59
+ console.warn("Failed to parse initial messages JSON:", error);
60
+ return [];
61
+ }
24
62
  }
25
63
  const getInitialMessagesFetch = getInitialMessages || defaultGetInitialMessagesFetch;
26
64
  function doGetInitialMessages(getInitialMessagesOptions) {
@@ -36,7 +74,7 @@ function useAgentChat(options) {
36
74
  name: agent.name,
37
75
  url: agentUrlString
38
76
  });
39
- const initialMessages = initialMessagesPromise ? use(initialMessagesPromise) : rest.initialMessages ?? [];
77
+ const initialMessages = initialMessagesPromise ? use(initialMessagesPromise) : optionsInitialMessages ?? [];
40
78
  useEffect(() => {
41
79
  if (!initialMessagesPromise) {
42
80
  return;
@@ -48,117 +86,217 @@ function useAgentChat(options) {
48
86
  }
49
87
  };
50
88
  }, [agentUrlString, initialMessagesPromise]);
51
- async function aiFetch(request, options2 = {}) {
52
- const {
53
- method,
54
- keepalive,
55
- headers,
56
- body,
57
- redirect,
58
- integrity,
59
- signal,
60
- credentials,
61
- mode,
62
- referrer,
63
- referrerPolicy,
64
- window
65
- // dispatcher, duplex
66
- } = options2;
67
- const id = nanoid(8);
68
- const abortController = new AbortController();
69
- signal?.addEventListener("abort", () => {
70
- agent.send(
71
- JSON.stringify({
72
- id,
73
- type: "cf_agent_chat_request_cancel"
74
- })
75
- );
76
- abortController.abort();
77
- controller.close();
78
- });
79
- agent.addEventListener(
80
- "message",
81
- (event) => {
82
- let data;
83
- try {
84
- data = JSON.parse(event.data);
85
- } catch (_error) {
86
- return;
89
+ const aiFetch = useCallback(
90
+ async (request, options2 = {}) => {
91
+ const {
92
+ method,
93
+ keepalive,
94
+ headers,
95
+ body,
96
+ redirect,
97
+ integrity,
98
+ signal,
99
+ credentials,
100
+ mode,
101
+ referrer,
102
+ referrerPolicy,
103
+ window
104
+ } = options2;
105
+ const id = nanoid(8);
106
+ const abortController = new AbortController();
107
+ let controller;
108
+ let isToolCallInProgress = false;
109
+ const currentAgent = agentRef.current;
110
+ signal?.addEventListener("abort", () => {
111
+ currentAgent.send(
112
+ JSON.stringify({
113
+ id,
114
+ type: "cf_agent_chat_request_cancel" /* CF_AGENT_CHAT_REQUEST_CANCEL */
115
+ })
116
+ );
117
+ abortController.abort();
118
+ if (!isToolCallInProgress) {
119
+ controller.close();
87
120
  }
88
- if (data.type === "cf_agent_use_chat_response") {
89
- if (data.id === id) {
90
- controller.enqueue(new TextEncoder().encode(data.body));
91
- if (data.done) {
92
- controller.close();
93
- abortController.abort();
121
+ });
122
+ currentAgent.addEventListener(
123
+ "message",
124
+ (event) => {
125
+ let data;
126
+ try {
127
+ data = JSON.parse(event.data);
128
+ } catch (_error) {
129
+ return;
130
+ }
131
+ if (data.type === "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */) {
132
+ if (data.id === id) {
133
+ if (data.error) {
134
+ controller.error(new Error(data.body));
135
+ abortController.abort();
136
+ } else {
137
+ if (data.body?.trim()) {
138
+ if (data.body.includes('"tool_calls"')) {
139
+ isToolCallInProgress = true;
140
+ }
141
+ controller.enqueue(
142
+ new TextEncoder().encode(`data: ${data.body}
143
+
144
+ `)
145
+ );
146
+ }
147
+ if (data.done && !isToolCallInProgress) {
148
+ controller.close();
149
+ abortController.abort();
150
+ }
151
+ }
94
152
  }
95
153
  }
154
+ },
155
+ { signal: abortController.signal }
156
+ );
157
+ const stream = new ReadableStream({
158
+ start(c) {
159
+ controller = c;
96
160
  }
161
+ });
162
+ currentAgent.send(
163
+ JSON.stringify({
164
+ id,
165
+ init: {
166
+ body,
167
+ credentials,
168
+ headers,
169
+ integrity,
170
+ keepalive,
171
+ method,
172
+ mode,
173
+ redirect,
174
+ referrer,
175
+ referrerPolicy,
176
+ window
177
+ },
178
+ type: "cf_agent_use_chat_request" /* CF_AGENT_USE_CHAT_REQUEST */,
179
+ url: request.toString()
180
+ })
181
+ );
182
+ return new Response(stream);
183
+ },
184
+ []
185
+ );
186
+ const customTransport = useMemo(
187
+ () => ({
188
+ sendMessages: async (options2) => {
189
+ const transport = new DefaultChatTransport({
190
+ api: agentUrlString,
191
+ fetch: aiFetch
192
+ });
193
+ return transport.sendMessages(options2);
97
194
  },
98
- { signal: abortController.signal }
99
- );
100
- let controller;
101
- const stream = new ReadableStream({
102
- start(c) {
103
- controller = c;
195
+ reconnectToStream: async (options2) => {
196
+ const transport = new DefaultChatTransport({
197
+ api: agentUrlString,
198
+ fetch: aiFetch
199
+ });
200
+ return transport.reconnectToStream(options2);
104
201
  }
105
- });
106
- agent.send(
107
- JSON.stringify({
108
- id,
109
- init: {
110
- body,
111
- credentials,
112
- headers,
113
- integrity,
114
- keepalive,
115
- method,
116
- mode,
117
- redirect,
118
- referrer,
119
- referrerPolicy,
120
- window
121
- // dispatcher,
122
- // duplex
123
- },
124
- type: "cf_agent_use_chat_request",
125
- url: request.toString()
126
- })
127
- );
128
- return new Response(stream);
129
- }
202
+ }),
203
+ [agentUrlString, aiFetch]
204
+ );
130
205
  const useChatHelpers = useChat({
131
- fetch: aiFetch,
132
- initialMessages,
133
- sendExtraMessageFields: true,
134
- ...rest
206
+ ...rest,
207
+ messages: initialMessages,
208
+ transport: customTransport,
209
+ id: agent._pk
135
210
  });
211
+ const processedToolCalls = useRef(/* @__PURE__ */ new Set());
212
+ const lastMessage = useChatHelpers.messages[useChatHelpers.messages.length - 1];
213
+ const pendingConfirmations = (() => {
214
+ if (!lastMessage || lastMessage.role !== "assistant") {
215
+ return { messageId: void 0, toolCallIds: /* @__PURE__ */ new Set() };
216
+ }
217
+ const pendingIds = /* @__PURE__ */ new Set();
218
+ for (const part of lastMessage.parts ?? []) {
219
+ if (isToolUIPart(part) && part.state === "input-available" && toolsRequiringConfirmation.includes(getToolName(part))) {
220
+ pendingIds.add(part.toolCallId);
221
+ }
222
+ }
223
+ return { messageId: lastMessage.id, toolCallIds: pendingIds };
224
+ })();
225
+ const pendingConfirmationsRef = useRef(pendingConfirmations);
226
+ pendingConfirmationsRef.current = pendingConfirmations;
227
+ useEffect(() => {
228
+ if (!experimental_automaticToolResolution) {
229
+ return;
230
+ }
231
+ const lastMessage2 = useChatHelpers.messages[useChatHelpers.messages.length - 1];
232
+ if (!lastMessage2 || lastMessage2.role !== "assistant") {
233
+ return;
234
+ }
235
+ const toolCalls = lastMessage2.parts.filter(
236
+ (part) => isToolUIPart(part) && part.state === "input-available" && !processedToolCalls.current.has(part.toolCallId)
237
+ );
238
+ if (toolCalls.length > 0) {
239
+ (async () => {
240
+ const toolCallsToResolve = toolCalls.filter(
241
+ (part) => isToolUIPart(part) && !toolsRequiringConfirmation.includes(getToolName(part)) && tools?.[getToolName(part)]?.execute
242
+ // Only execute if client has execute function
243
+ );
244
+ if (toolCallsToResolve.length > 0) {
245
+ for (const part of toolCallsToResolve) {
246
+ if (isToolUIPart(part)) {
247
+ processedToolCalls.current.add(part.toolCallId);
248
+ let toolOutput = null;
249
+ const toolName = getToolName(part);
250
+ const tool = tools?.[toolName];
251
+ if (tool?.execute && part.input) {
252
+ try {
253
+ toolOutput = await tool.execute(part.input);
254
+ } catch (error) {
255
+ toolOutput = `Error executing tool: ${error instanceof Error ? error.message : String(error)}`;
256
+ }
257
+ }
258
+ await useChatHelpers.addToolResult({
259
+ toolCallId: part.toolCallId,
260
+ tool: toolName,
261
+ output: toolOutput
262
+ });
263
+ }
264
+ }
265
+ if (pendingConfirmationsRef.current.toolCallIds.size === 0) {
266
+ useChatHelpers.sendMessage();
267
+ }
268
+ }
269
+ })();
270
+ }
271
+ }, [
272
+ useChatHelpers.messages,
273
+ experimental_automaticToolResolution,
274
+ useChatHelpers.addToolResult,
275
+ useChatHelpers.sendMessage,
276
+ toolsRequiringConfirmation
277
+ ]);
136
278
  useEffect(() => {
137
279
  function onClearHistory(event) {
138
- if (typeof event.data !== "string") {
139
- return;
140
- }
280
+ if (typeof event.data !== "string") return;
141
281
  let data;
142
282
  try {
143
283
  data = JSON.parse(event.data);
144
284
  } catch (_error) {
145
285
  return;
146
286
  }
147
- if (data.type === "cf_agent_chat_clear") {
287
+ if (data.type === "cf_agent_chat_clear" /* CF_AGENT_CHAT_CLEAR */) {
148
288
  useChatHelpers.setMessages([]);
149
289
  }
150
290
  }
151
291
  function onMessages(event) {
152
- if (typeof event.data !== "string") {
153
- return;
154
- }
292
+ if (typeof event.data !== "string") return;
155
293
  let data;
156
294
  try {
157
295
  data = JSON.parse(event.data);
158
296
  } catch (_error) {
159
297
  return;
160
298
  }
161
- if (data.type === "cf_agent_chat_messages") {
299
+ if (data.type === "cf_agent_chat_messages" /* CF_AGENT_CHAT_MESSAGES */) {
162
300
  useChatHelpers.setMessages(data.messages);
163
301
  }
164
302
  }
@@ -169,35 +307,50 @@ function useAgentChat(options) {
169
307
  agent.removeEventListener("message", onMessages);
170
308
  };
171
309
  }, [agent, useChatHelpers.setMessages]);
310
+ const addToolResultAndSendMessage = async (args) => {
311
+ const { toolCallId } = args;
312
+ await useChatHelpers.addToolResult(args);
313
+ if (!autoSendAfterAllConfirmationsResolved) {
314
+ useChatHelpers.sendMessage();
315
+ return;
316
+ }
317
+ const pending = pendingConfirmationsRef.current?.toolCallIds;
318
+ if (!pending) {
319
+ useChatHelpers.sendMessage();
320
+ return;
321
+ }
322
+ const wasLast = pending.size === 1 && pending.has(toolCallId);
323
+ if (pending.has(toolCallId)) {
324
+ pending.delete(toolCallId);
325
+ }
326
+ if (wasLast || pending.size === 0) {
327
+ useChatHelpers.sendMessage();
328
+ }
329
+ };
172
330
  return {
173
331
  ...useChatHelpers,
174
- /**
175
- * Clear chat history on both client and Agent
176
- */
332
+ addToolResult: addToolResultAndSendMessage,
177
333
  clearHistory: () => {
178
334
  useChatHelpers.setMessages([]);
179
335
  agent.send(
180
336
  JSON.stringify({
181
- type: "cf_agent_chat_clear"
337
+ type: "cf_agent_chat_clear" /* CF_AGENT_CHAT_CLEAR */
182
338
  })
183
339
  );
184
340
  },
185
- /**
186
- * Set the chat messages and synchronize with the Agent
187
- * @param messages New messages to set
188
- */
189
341
  setMessages: (messages) => {
190
342
  useChatHelpers.setMessages(messages);
191
343
  agent.send(
192
344
  JSON.stringify({
193
- messages,
194
- type: "cf_agent_chat_messages"
345
+ messages: Array.isArray(messages) ? messages : [],
346
+ type: "cf_agent_chat_messages" /* CF_AGENT_CHAT_MESSAGES */
195
347
  })
196
348
  );
197
349
  }
198
350
  };
199
351
  }
200
352
  export {
353
+ detectToolsRequiringConfirmation,
201
354
  useAgentChat
202
355
  };
203
356
  //# sourceMappingURL=ai-react.js.map