agents 0.0.0-eeb70e2 → 0.0.0-ef38e84

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 (78) hide show
  1. package/README.md +255 -27
  2. package/dist/ai-chat-agent.d.ts +20 -17
  3. package/dist/ai-chat-agent.js +532 -222
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration-DBHGW4Hv.js +155 -0
  6. package/dist/ai-chat-v5-migration-DBHGW4Hv.js.map +1 -0
  7. package/dist/ai-chat-v5-migration.d.ts +155 -0
  8. package/dist/ai-chat-v5-migration.js +3 -0
  9. package/dist/ai-react.d.ts +73 -85
  10. package/dist/ai-react.js +266 -199
  11. package/dist/ai-react.js.map +1 -1
  12. package/dist/ai-types-B3aQaFv3.js +20 -0
  13. package/dist/ai-types-B3aQaFv3.js.map +1 -0
  14. package/dist/ai-types-D5YoPrBZ.d.ts +95 -0
  15. package/dist/ai-types.d.ts +6 -74
  16. package/dist/ai-types.js +3 -1
  17. package/dist/cli.d.ts +8 -0
  18. package/dist/cli.js +27 -0
  19. package/dist/cli.js.map +1 -0
  20. package/dist/client-BfiZ3HQd.js +117 -0
  21. package/dist/client-BfiZ3HQd.js.map +1 -0
  22. package/dist/client-Bws9q38u.d.ts +5427 -0
  23. package/dist/client-CbWe9FBd.d.ts +104 -0
  24. package/dist/client-DvK0u9vD.js +898 -0
  25. package/dist/client-DvK0u9vD.js.map +1 -0
  26. package/dist/client.d.ts +12 -93
  27. package/dist/client.js +4 -11
  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-CcTno-25.d.ts +142 -0
  32. package/dist/do-oauth-client-provider-D2P1lSft.js +93 -0
  33. package/dist/do-oauth-client-provider-D2P1lSft.js.map +1 -0
  34. package/dist/index-Bdzb2feZ.d.ts +572 -0
  35. package/dist/index-DhJCaDWd.d.ts +58 -0
  36. package/dist/index.d.ts +61 -402
  37. package/dist/index.js +7 -22
  38. package/dist/mcp/client.d.ts +4 -783
  39. package/dist/mcp/client.js +4 -9
  40. package/dist/mcp/do-oauth-client-provider.d.ts +2 -41
  41. package/dist/mcp/do-oauth-client-provider.js +3 -7
  42. package/dist/mcp/index.d.ts +190 -81
  43. package/dist/mcp/index.js +1428 -770
  44. package/dist/mcp/index.js.map +1 -1
  45. package/dist/mcp/x402.d.ts +34 -0
  46. package/dist/mcp/x402.js +194 -0
  47. package/dist/mcp/x402.js.map +1 -0
  48. package/dist/mcp-Dw5vDrY8.d.ts +61 -0
  49. package/dist/observability/index.d.ts +3 -0
  50. package/dist/observability/index.js +7 -0
  51. package/dist/react-DFNXTQzy.d.ts +113 -0
  52. package/dist/react.d.ts +10 -119
  53. package/dist/react.js +183 -110
  54. package/dist/react.js.map +1 -1
  55. package/dist/schedule.d.ts +89 -12
  56. package/dist/schedule.js +46 -21
  57. package/dist/schedule.js.map +1 -1
  58. package/dist/serializable-CymX8ovI.d.ts +39 -0
  59. package/dist/serializable.d.ts +7 -32
  60. package/dist/serializable.js +1 -1
  61. package/dist/src-C1WWpbRo.js +1247 -0
  62. package/dist/src-C1WWpbRo.js.map +1 -0
  63. package/package.json +125 -71
  64. package/dist/ai-types.js.map +0 -1
  65. package/dist/chunk-BZXOAZUX.js +0 -106
  66. package/dist/chunk-BZXOAZUX.js.map +0 -1
  67. package/dist/chunk-OYJXQRRH.js +0 -465
  68. package/dist/chunk-OYJXQRRH.js.map +0 -1
  69. package/dist/chunk-P3RZJ72N.js +0 -783
  70. package/dist/chunk-P3RZJ72N.js.map +0 -1
  71. package/dist/chunk-VCSB47AK.js +0 -116
  72. package/dist/chunk-VCSB47AK.js.map +0 -1
  73. package/dist/client.js.map +0 -1
  74. package/dist/index.js.map +0 -1
  75. package/dist/mcp/client.js.map +0 -1
  76. package/dist/mcp/do-oauth-client-provider.js.map +0 -1
  77. package/dist/serializable.js.map +0 -1
  78. package/src/index.ts +0 -1252
@@ -1,101 +1,89 @@
1
- import * as ai from "ai";
2
- import { Message } from "ai";
3
- import { useChat } from "@ai-sdk/react";
4
- import { useAgent } from "./react.js";
5
- import "partysocket";
6
- import "partysocket/react";
7
- import "./index.js";
8
- import "partyserver";
9
- import "@modelcontextprotocol/sdk/types.js";
10
- import "./mcp/client.js";
11
- import "zod";
12
- import "@modelcontextprotocol/sdk/client/index.js";
13
- import "@modelcontextprotocol/sdk/client/sse.js";
14
- import "./mcp/do-oauth-client-provider.js";
15
- import "@modelcontextprotocol/sdk/client/auth.js";
16
- import "@modelcontextprotocol/sdk/shared/auth.js";
17
- import "@modelcontextprotocol/sdk/shared/protocol.js";
18
- import "./client.js";
19
- import "./serializable.js";
1
+ import "./client-Bws9q38u.js";
2
+ import "./mcp-Dw5vDrY8.js";
3
+ import "./do-oauth-client-provider-CcTno-25.js";
4
+ import "./index-DhJCaDWd.js";
5
+ import "./ai-types-D5YoPrBZ.js";
6
+ import "./index-Bdzb2feZ.js";
7
+ import "./serializable-CymX8ovI.js";
8
+ import "./client-CbWe9FBd.js";
9
+ import { n as useAgent } from "./react-DFNXTQzy.js";
10
+ import { UseChatOptions, useChat } from "@ai-sdk/react";
11
+ import { ChatInit, UIMessage } from "ai";
20
12
 
13
+ //#region src/ai-react.d.ts
14
+ type AITool<Input = unknown, Output = unknown> = {
15
+ description?: string;
16
+ inputSchema?: unknown;
17
+ execute?: (input: Input) => Output | Promise<Output>;
18
+ };
21
19
  type GetInitialMessagesOptions = {
22
20
  agent: string;
23
21
  name: string;
24
22
  url: string;
25
23
  };
24
+ type UseChatParams<M extends UIMessage = UIMessage> = ChatInit<M> &
25
+ UseChatOptions<M>;
26
26
  /**
27
27
  * Options for the useAgentChat hook
28
28
  */
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
- >;
29
+ type UseAgentChatOptions<
30
+ State,
31
+ ChatMessage extends UIMessage = UIMessage
32
+ > = Omit<UseChatParams<ChatMessage>, "fetch"> & {
33
+ /** Agent connection from useAgent */
34
+ agent: ReturnType<typeof useAgent<State>>;
35
+ getInitialMessages?:
36
+ | undefined
37
+ | null
38
+ | ((options: GetInitialMessagesOptions) => Promise<ChatMessage[]>);
39
+ /** Request credentials */
40
+ credentials?: RequestCredentials;
41
+ /** Request headers */
42
+ headers?: HeadersInit;
43
+ /**
44
+ * @description Whether to automatically resolve tool calls that do not require human interaction.
45
+ * @experimental
46
+ */
47
+ experimental_automaticToolResolution?: boolean;
48
+ /**
49
+ * @description Tools object for automatic detection of confirmation requirements.
50
+ * Tools without execute function will require confirmation.
51
+ */
52
+ tools?: Record<string, AITool<unknown, unknown>>;
53
+ /**
54
+ * @description Manual override for tools requiring confirmation.
55
+ * If not provided, will auto-detect from tools object.
56
+ */
57
+ toolsRequiringConfirmation?: string[];
58
+ /**
59
+ * When true (default), automatically sends the next message only after
60
+ * all pending confirmation-required tool calls have been resolved.
61
+ * @default true
62
+ */
63
+ autoSendAfterAllConfirmationsResolved?: boolean;
64
+ };
40
65
  /**
41
66
  * React hook for building AI chat interfaces using an Agent
42
67
  * @param options Chat options including the agent connection
43
68
  * @returns Chat interface controls and state with added clearHistory method
44
69
  */
45
- declare function useAgentChat<State = unknown>(
46
- options: UseAgentChatOptions<State>
47
- ): {
48
- /**
49
- * Set the chat messages and synchronize with the Agent
50
- * @param messages New messages to set
51
- */
52
- setMessages: (messages: Message[]) => void;
53
- /**
54
- * Clear chat history on both client and Agent
55
- */
70
+ /**
71
+ * Automatically detects which tools require confirmation based on their configuration.
72
+ * Tools require confirmation if they have no execute function AND are not server-executed.
73
+ * @param tools - Record of tool name to tool definition
74
+ * @returns Array of tool names that require confirmation
75
+ */
76
+ declare function detectToolsRequiringConfirmation(
77
+ tools?: Record<string, AITool<unknown, unknown>>
78
+ ): string[];
79
+ declare function useAgentChat<
80
+ State = unknown,
81
+ ChatMessage extends UIMessage = UIMessage
82
+ >(
83
+ options: UseAgentChatOptions<State, ChatMessage>
84
+ ): ReturnType<typeof useChat<ChatMessage>> & {
56
85
  clearHistory: () => 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
86
  };
100
-
101
- export { useAgentChat };
87
+ //#endregion
88
+ export { AITool, detectToolsRequiringConfirmation, useAgentChat };
89
+ //# sourceMappingURL=ai-react.d.ts.map
package/dist/ai-react.js CHANGED
@@ -1,203 +1,270 @@
1
- // src/ai-react.tsx
2
- import { useChat } from "@ai-sdk/react";
3
- import { use, useEffect } from "react";
1
+ import { t as MessageType } from "./ai-types-B3aQaFv3.js";
4
2
  import { nanoid } from "nanoid";
5
- 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
+ */
20
+ function detectToolsRequiringConfirmation(tools) {
21
+ if (!tools) return [];
22
+ return Object.entries(tools).filter(([_name, tool$1]) => !tool$1.execute).map(([name]) => name);
23
+ }
6
24
  function useAgentChat(options) {
7
- const { agent, getInitialMessages, ...rest } = options;
8
- const agentUrl = new URL(
9
- `${// @ts-expect-error we're using a protected _url property that includes query params
10
- (agent._url || agent._pkurl)?.replace("ws://", "http://").replace("wss://", "https://")}`
11
- );
12
- agentUrl.searchParams.delete("_pk");
13
- const agentUrlString = agentUrl.toString();
14
- async function defaultGetInitialMessagesFetch({
15
- url
16
- }) {
17
- const getMessagesUrl = new URL(url);
18
- getMessagesUrl.pathname += "/get-messages";
19
- const response = await fetch(getMessagesUrl.toString(), {
20
- headers: options.headers,
21
- credentials: options.credentials
22
- });
23
- return response.json();
24
- }
25
- const getInitialMessagesFetch = getInitialMessages || defaultGetInitialMessagesFetch;
26
- function doGetInitialMessages(getInitialMessagesOptions) {
27
- if (requestCache.has(agentUrlString)) {
28
- return requestCache.get(agentUrlString);
29
- }
30
- const promise = getInitialMessagesFetch(getInitialMessagesOptions);
31
- requestCache.set(agentUrlString, promise);
32
- return promise;
33
- }
34
- const initialMessagesPromise = getInitialMessages === null ? null : doGetInitialMessages({
35
- agent: agent.agent,
36
- name: agent.name,
37
- url: agentUrlString
38
- });
39
- const initialMessages = initialMessagesPromise ? use(initialMessagesPromise) : rest.initialMessages ?? [];
40
- useEffect(() => {
41
- if (!initialMessagesPromise) {
42
- return;
43
- }
44
- requestCache.set(agentUrlString, initialMessagesPromise);
45
- return () => {
46
- if (requestCache.get(agentUrlString) === initialMessagesPromise) {
47
- requestCache.delete(agentUrlString);
48
- }
49
- };
50
- }, [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
- type: "cf_agent_chat_request_cancel",
73
- id
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;
87
- }
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();
94
- }
95
- }
96
- }
97
- },
98
- { signal: abortController.signal }
99
- );
100
- let controller;
101
- const stream = new ReadableStream({
102
- start(c) {
103
- controller = c;
104
- }
105
- });
106
- agent.send(
107
- JSON.stringify({
108
- type: "cf_agent_use_chat_request",
109
- id,
110
- url: request.toString(),
111
- init: {
112
- method,
113
- keepalive,
114
- headers,
115
- body,
116
- redirect,
117
- integrity,
118
- credentials,
119
- mode,
120
- referrer,
121
- referrerPolicy,
122
- window
123
- // dispatcher,
124
- // duplex
125
- }
126
- })
127
- );
128
- return new Response(stream);
129
- }
130
- const useChatHelpers = useChat({
131
- initialMessages,
132
- sendExtraMessageFields: true,
133
- fetch: aiFetch,
134
- ...rest
135
- });
136
- useEffect(() => {
137
- function onClearHistory(event) {
138
- if (typeof event.data !== "string") {
139
- return;
140
- }
141
- let data;
142
- try {
143
- data = JSON.parse(event.data);
144
- } catch (error) {
145
- return;
146
- }
147
- if (data.type === "cf_agent_chat_clear") {
148
- useChatHelpers.setMessages([]);
149
- }
150
- }
151
- function onMessages(event) {
152
- if (typeof event.data !== "string") {
153
- return;
154
- }
155
- let data;
156
- try {
157
- data = JSON.parse(event.data);
158
- } catch (error) {
159
- return;
160
- }
161
- if (data.type === "cf_agent_chat_messages") {
162
- useChatHelpers.setMessages(data.messages);
163
- }
164
- }
165
- agent.addEventListener("message", onClearHistory);
166
- agent.addEventListener("message", onMessages);
167
- return () => {
168
- agent.removeEventListener("message", onClearHistory);
169
- agent.removeEventListener("message", onMessages);
170
- };
171
- }, [agent, useChatHelpers.setMessages]);
172
- return {
173
- ...useChatHelpers,
174
- /**
175
- * Set the chat messages and synchronize with the Agent
176
- * @param messages New messages to set
177
- */
178
- setMessages: (messages) => {
179
- useChatHelpers.setMessages(messages);
180
- agent.send(
181
- JSON.stringify({
182
- type: "cf_agent_chat_messages",
183
- messages
184
- })
185
- );
186
- },
187
- /**
188
- * Clear chat history on both client and Agent
189
- */
190
- clearHistory: () => {
191
- useChatHelpers.setMessages([]);
192
- agent.send(
193
- JSON.stringify({
194
- type: "cf_agent_chat_clear"
195
- })
196
- );
197
- }
198
- };
25
+ const { agent, getInitialMessages, messages: optionsInitialMessages, experimental_automaticToolResolution, tools, toolsRequiringConfirmation: manualToolsRequiringConfirmation, autoSendAfterAllConfirmationsResolved = 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
+ signal?.addEventListener("abort", () => {
82
+ currentAgent.send(JSON.stringify({
83
+ id,
84
+ type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL
85
+ }));
86
+ abortController.abort();
87
+ controller.close();
88
+ });
89
+ currentAgent.addEventListener("message", (event) => {
90
+ let data;
91
+ try {
92
+ data = JSON.parse(event.data);
93
+ } catch (_error) {
94
+ return;
95
+ }
96
+ if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE) {
97
+ if (data.id === id) if (data.error) {
98
+ controller.error(new Error(data.body));
99
+ abortController.abort();
100
+ } else {
101
+ if (data.body?.trim()) controller.enqueue(new TextEncoder().encode(`data: ${data.body}\n\n`));
102
+ if (data.done) {
103
+ controller.close();
104
+ abortController.abort();
105
+ }
106
+ }
107
+ }
108
+ }, { signal: abortController.signal });
109
+ const stream = new ReadableStream({
110
+ start(c) {
111
+ controller = c;
112
+ },
113
+ cancel(reason) {
114
+ console.warn("[agents/ai-react] cancelling stream", id, reason || "no reason");
115
+ }
116
+ });
117
+ currentAgent.send(JSON.stringify({
118
+ id,
119
+ init: {
120
+ body,
121
+ credentials,
122
+ headers,
123
+ integrity,
124
+ keepalive,
125
+ method,
126
+ mode,
127
+ redirect,
128
+ referrer,
129
+ referrerPolicy,
130
+ window
131
+ },
132
+ type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
133
+ url: request.toString()
134
+ }));
135
+ return new Response(stream);
136
+ }, []);
137
+ const customTransport = useMemo(() => ({
138
+ sendMessages: async (options$1) => {
139
+ return new DefaultChatTransport({
140
+ api: agentUrlString,
141
+ fetch: aiFetch
142
+ }).sendMessages(options$1);
143
+ },
144
+ reconnectToStream: async (options$1) => {
145
+ return new DefaultChatTransport({
146
+ api: agentUrlString,
147
+ fetch: aiFetch
148
+ }).reconnectToStream(options$1);
149
+ }
150
+ }), [agentUrlString, aiFetch]);
151
+ const useChatHelpers = useChat({
152
+ ...rest,
153
+ messages: initialMessages,
154
+ transport: customTransport,
155
+ id: agent._pk
156
+ });
157
+ const processedToolCalls = useRef(/* @__PURE__ */ new Set());
158
+ const lastMessage = useChatHelpers.messages[useChatHelpers.messages.length - 1];
159
+ const pendingConfirmations = (() => {
160
+ if (!lastMessage || lastMessage.role !== "assistant") return {
161
+ messageId: void 0,
162
+ toolCallIds: /* @__PURE__ */ new Set()
163
+ };
164
+ const pendingIds = /* @__PURE__ */ new Set();
165
+ for (const part of lastMessage.parts ?? []) if (isToolUIPart(part) && part.state === "input-available" && toolsRequiringConfirmation.includes(getToolName(part))) pendingIds.add(part.toolCallId);
166
+ return {
167
+ messageId: lastMessage.id,
168
+ toolCallIds: pendingIds
169
+ };
170
+ })();
171
+ const pendingConfirmationsRef = useRef(pendingConfirmations);
172
+ pendingConfirmationsRef.current = pendingConfirmations;
173
+ useEffect(() => {
174
+ if (!experimental_automaticToolResolution) return;
175
+ const lastMessage$1 = useChatHelpers.messages[useChatHelpers.messages.length - 1];
176
+ if (!lastMessage$1 || lastMessage$1.role !== "assistant") return;
177
+ const toolCalls = lastMessage$1.parts.filter((part) => isToolUIPart(part) && part.state === "input-available" && !processedToolCalls.current.has(part.toolCallId));
178
+ if (toolCalls.length > 0) (async () => {
179
+ const toolCallsToResolve = toolCalls.filter((part) => isToolUIPart(part) && !toolsRequiringConfirmation.includes(getToolName(part)) && tools?.[getToolName(part)]?.execute);
180
+ if (toolCallsToResolve.length > 0) {
181
+ for (const part of toolCallsToResolve) if (isToolUIPart(part)) {
182
+ processedToolCalls.current.add(part.toolCallId);
183
+ let toolOutput = null;
184
+ const toolName = getToolName(part);
185
+ const tool$1 = tools?.[toolName];
186
+ if (tool$1?.execute && part.input) try {
187
+ toolOutput = await tool$1.execute(part.input);
188
+ } catch (error) {
189
+ toolOutput = `Error executing tool: ${error instanceof Error ? error.message : String(error)}`;
190
+ }
191
+ await useChatHelpers.addToolResult({
192
+ toolCallId: part.toolCallId,
193
+ tool: toolName,
194
+ output: toolOutput
195
+ });
196
+ }
197
+ if (pendingConfirmationsRef.current.toolCallIds.size === 0) useChatHelpers.sendMessage();
198
+ }
199
+ })();
200
+ }, [
201
+ useChatHelpers.messages,
202
+ experimental_automaticToolResolution,
203
+ useChatHelpers.addToolResult,
204
+ useChatHelpers.sendMessage,
205
+ toolsRequiringConfirmation
206
+ ]);
207
+ useEffect(() => {
208
+ function onClearHistory(event) {
209
+ if (typeof event.data !== "string") return;
210
+ let data;
211
+ try {
212
+ data = JSON.parse(event.data);
213
+ } catch (_error) {
214
+ return;
215
+ }
216
+ if (data.type === MessageType.CF_AGENT_CHAT_CLEAR) useChatHelpers.setMessages([]);
217
+ }
218
+ function onMessages(event) {
219
+ if (typeof event.data !== "string") return;
220
+ let data;
221
+ try {
222
+ data = JSON.parse(event.data);
223
+ } catch (_error) {
224
+ return;
225
+ }
226
+ if (data.type === MessageType.CF_AGENT_CHAT_MESSAGES) useChatHelpers.setMessages(data.messages);
227
+ }
228
+ agent.addEventListener("message", onClearHistory);
229
+ agent.addEventListener("message", onMessages);
230
+ return () => {
231
+ agent.removeEventListener("message", onClearHistory);
232
+ agent.removeEventListener("message", onMessages);
233
+ };
234
+ }, [agent, useChatHelpers.setMessages]);
235
+ const addToolResultAndSendMessage = async (args) => {
236
+ const { toolCallId } = args;
237
+ await useChatHelpers.addToolResult(args);
238
+ if (!autoSendAfterAllConfirmationsResolved) {
239
+ useChatHelpers.sendMessage();
240
+ return;
241
+ }
242
+ const pending = pendingConfirmationsRef.current?.toolCallIds;
243
+ if (!pending) {
244
+ useChatHelpers.sendMessage();
245
+ return;
246
+ }
247
+ const wasLast = pending.size === 1 && pending.has(toolCallId);
248
+ if (pending.has(toolCallId)) pending.delete(toolCallId);
249
+ if (wasLast || pending.size === 0) useChatHelpers.sendMessage();
250
+ };
251
+ return {
252
+ ...useChatHelpers,
253
+ addToolResult: addToolResultAndSendMessage,
254
+ clearHistory: () => {
255
+ useChatHelpers.setMessages([]);
256
+ agent.send(JSON.stringify({ type: MessageType.CF_AGENT_CHAT_CLEAR }));
257
+ },
258
+ setMessages: (messages) => {
259
+ useChatHelpers.setMessages(messages);
260
+ agent.send(JSON.stringify({
261
+ messages: Array.isArray(messages) ? messages : [],
262
+ type: MessageType.CF_AGENT_CHAT_MESSAGES
263
+ }));
264
+ }
265
+ };
199
266
  }
200
- export {
201
- useAgentChat
202
- };
267
+
268
+ //#endregion
269
+ export { detectToolsRequiringConfirmation, useAgentChat };
203
270
  //# sourceMappingURL=ai-react.js.map