agents 0.0.0-352d62c → 0.0.0-3667584

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 (79) hide show
  1. package/README.md +126 -4
  2. package/dist/ai-chat-agent.d.ts +20 -22
  3. package/dist/ai-chat-agent.js +532 -256
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration-gdyLiTd8.js +155 -0
  6. package/dist/ai-chat-v5-migration-gdyLiTd8.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 -89
  10. package/dist/ai-react.js +260 -201
  11. package/dist/ai-react.js.map +1 -1
  12. package/dist/ai-types-BWW4umHY.d.ts +95 -0
  13. package/dist/ai-types-UZlfLOYP.js +20 -0
  14. package/dist/ai-types-UZlfLOYP.js.map +1 -0
  15. package/dist/ai-types.d.ts +6 -92
  16. package/dist/ai-types.js +3 -7
  17. package/dist/client-C-nwz-3N.d.ts +5313 -0
  18. package/dist/client-CZBVDDoO.js +786 -0
  19. package/dist/client-CZBVDDoO.js.map +1 -0
  20. package/dist/client-CmMi85Sj.d.ts +104 -0
  21. package/dist/client-DjR-lC16.js +117 -0
  22. package/dist/client-DjR-lC16.js.map +1 -0
  23. package/dist/client.d.ts +11 -92
  24. package/dist/client.js +4 -12
  25. package/dist/codemode/ai.d.ts +27 -0
  26. package/dist/codemode/ai.js +151 -0
  27. package/dist/codemode/ai.js.map +1 -0
  28. package/dist/do-oauth-client-provider-B2jr6UNq.js +93 -0
  29. package/dist/do-oauth-client-provider-B2jr6UNq.js.map +1 -0
  30. package/dist/do-oauth-client-provider-CCwGwnrA.d.ts +55 -0
  31. package/dist/index-CkQU40oY.d.ts +558 -0
  32. package/dist/index-W4JUkafc.d.ts +54 -0
  33. package/dist/index.d.ts +57 -535
  34. package/dist/index.js +7 -29
  35. package/dist/mcp/client.d.ts +4 -11
  36. package/dist/mcp/client.js +3 -9
  37. package/dist/mcp/do-oauth-client-provider.d.ts +2 -41
  38. package/dist/mcp/do-oauth-client-provider.js +3 -7
  39. package/dist/mcp/index.d.ts +73 -110
  40. package/dist/mcp/index.js +836 -945
  41. package/dist/mcp/index.js.map +1 -1
  42. package/dist/mcp/x402.d.ts +34 -0
  43. package/dist/mcp/x402.js +194 -0
  44. package/dist/mcp/x402.js.map +1 -0
  45. package/dist/mcp-BEwaCsxO.d.ts +61 -0
  46. package/dist/observability/index.d.ts +3 -46
  47. package/dist/observability/index.js +7 -11
  48. package/dist/react-B4e1rDid.d.ts +113 -0
  49. package/dist/react.d.ts +10 -123
  50. package/dist/react.js +183 -112
  51. package/dist/react.js.map +1 -1
  52. package/dist/schedule.d.ts +84 -7
  53. package/dist/schedule.js +46 -21
  54. package/dist/schedule.js.map +1 -1
  55. package/dist/serializable-gtr9YMhp.d.ts +34 -0
  56. package/dist/serializable.d.ts +7 -32
  57. package/dist/serializable.js +1 -1
  58. package/dist/src-COfG--3R.js +1179 -0
  59. package/dist/src-COfG--3R.js.map +1 -0
  60. package/package.json +40 -9
  61. package/src/index.ts +226 -116
  62. package/dist/ai-types.js.map +0 -1
  63. package/dist/chunk-EEKLJYON.js +0 -17
  64. package/dist/chunk-EEKLJYON.js.map +0 -1
  65. package/dist/chunk-EM3J4KV7.js +0 -598
  66. package/dist/chunk-EM3J4KV7.js.map +0 -1
  67. package/dist/chunk-ID62XSAS.js +0 -1290
  68. package/dist/chunk-ID62XSAS.js.map +0 -1
  69. package/dist/chunk-PVQZBKN7.js +0 -106
  70. package/dist/chunk-PVQZBKN7.js.map +0 -1
  71. package/dist/chunk-QEVM4BVL.js +0 -116
  72. package/dist/chunk-QEVM4BVL.js.map +0 -1
  73. package/dist/client-DgyzBU_8.d.ts +0 -4601
  74. package/dist/client.js.map +0 -1
  75. package/dist/index.js.map +0 -1
  76. package/dist/mcp/client.js.map +0 -1
  77. package/dist/mcp/do-oauth-client-provider.js.map +0 -1
  78. package/dist/observability/index.js.map +0 -1
  79. package/dist/serializable.js.map +0 -1
@@ -1,105 +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 "cloudflare:workers";
9
- import "@modelcontextprotocol/sdk/client/index.js";
10
- import "@modelcontextprotocol/sdk/types.js";
11
- import "partyserver";
12
- import "./client-DgyzBU_8.js";
13
- import "zod";
14
- import "@modelcontextprotocol/sdk/shared/protocol.js";
15
- import "@modelcontextprotocol/sdk/client/sse.js";
16
- import "@modelcontextprotocol/sdk/client/streamableHttp.js";
17
- import "./mcp/do-oauth-client-provider.js";
18
- import "@modelcontextprotocol/sdk/client/auth.js";
19
- import "@modelcontextprotocol/sdk/shared/auth.js";
20
- import "./observability/index.js";
21
- import "./ai-types.js";
22
- import "./client.js";
23
- import "./serializable.js";
1
+ import "./client-C-nwz-3N.js";
2
+ import "./mcp-BEwaCsxO.js";
3
+ import "./do-oauth-client-provider-CCwGwnrA.js";
4
+ import "./index-W4JUkafc.js";
5
+ import "./ai-types-BWW4umHY.js";
6
+ import "./index-CkQU40oY.js";
7
+ import "./serializable-gtr9YMhp.js";
8
+ import "./client-CmMi85Sj.js";
9
+ import { useAgent } from "./react-B4e1rDid.js";
10
+ import { UseChatOptions, useChat } from "@ai-sdk/react";
11
+ import { ChatInit, UIMessage } from "ai";
24
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
+ };
25
19
  type GetInitialMessagesOptions = {
26
20
  agent: string;
27
21
  name: string;
28
22
  url: string;
29
23
  };
24
+ type UseChatParams<M extends UIMessage = UIMessage> = ChatInit<M> &
25
+ UseChatOptions<M>;
30
26
  /**
31
27
  * Options for the useAgentChat hook
32
28
  */
33
- type UseAgentChatOptions<State> = Omit<
34
- Parameters<typeof useChat>[0] & {
35
- /** Agent connection from useAgent */
36
- agent: ReturnType<typeof useAgent<State>>;
37
- getInitialMessages?:
38
- | undefined
39
- | null
40
- | ((options: GetInitialMessagesOptions) => Promise<Message[]>);
41
- },
42
- "fetch"
43
- >;
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
+ };
44
65
  /**
45
66
  * React hook for building AI chat interfaces using an Agent
46
67
  * @param options Chat options including the agent connection
47
68
  * @returns Chat interface controls and state with added clearHistory method
48
69
  */
49
- declare function useAgentChat<State = unknown>(
50
- options: UseAgentChatOptions<State>
51
- ): {
52
- /**
53
- * Clear chat history on both client and Agent
54
- */
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>> & {
55
85
  clearHistory: () => void;
56
- /**
57
- * Set the chat messages and synchronize with the Agent
58
- * @param messages New messages to set
59
- */
60
- setMessages: (messages: Message[]) => void;
61
- messages: ai.UIMessage[];
62
- error: undefined | Error;
63
- append: (
64
- message: Message | ai.CreateMessage,
65
- chatRequestOptions?: ai.ChatRequestOptions
66
- ) => Promise<string | null | undefined>;
67
- reload: (
68
- chatRequestOptions?: ai.ChatRequestOptions
69
- ) => Promise<string | null | undefined>;
70
- stop: () => void;
71
- experimental_resume: () => void;
72
- input: string;
73
- setInput: React.Dispatch<React.SetStateAction<string>>;
74
- handleInputChange: (
75
- e:
76
- | React.ChangeEvent<HTMLInputElement>
77
- | React.ChangeEvent<HTMLTextAreaElement>
78
- ) => void;
79
- handleSubmit: (
80
- event?: {
81
- preventDefault?: () => void;
82
- },
83
- chatRequestOptions?: ai.ChatRequestOptions
84
- ) => void;
85
- metadata?: Object;
86
- isLoading: boolean;
87
- status: "submitted" | "streaming" | "ready" | "error";
88
- data?: ai.JSONValue[];
89
- setData: (
90
- data:
91
- | ai.JSONValue[]
92
- | undefined
93
- | ((data: ai.JSONValue[] | undefined) => ai.JSONValue[] | undefined)
94
- ) => void;
95
- id: string;
96
- addToolResult: ({
97
- toolCallId,
98
- result
99
- }: {
100
- toolCallId: string;
101
- result: any;
102
- }) => void;
103
86
  };
104
-
105
- export { useAgentChat };
87
+ //#endregion
88
+ export { AITool, detectToolsRequiringConfirmation, useAgentChat };
89
+ //# sourceMappingURL=ai-react.d.ts.map
package/dist/ai-react.js CHANGED
@@ -1,205 +1,264 @@
1
- import "./chunk-EEKLJYON.js";
2
-
3
- // src/ai-react.tsx
4
- import { useChat } from "@ai-sdk/react";
1
+ import { MessageType } from "./ai-types-UZlfLOYP.js";
5
2
  import { nanoid } from "nanoid";
6
- import { use, useEffect } from "react";
7
- 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
+ }
8
24
  function useAgentChat(options) {
9
- const { agent, getInitialMessages, ...rest } = options;
10
- const agentUrl = new URL(
11
- `${// @ts-expect-error we're using a protected _url property that includes query params
12
- (agent._url || agent._pkurl)?.replace("ws://", "http://").replace("wss://", "https://")}`
13
- );
14
- agentUrl.searchParams.delete("_pk");
15
- const agentUrlString = agentUrl.toString();
16
- async function defaultGetInitialMessagesFetch({
17
- url
18
- }) {
19
- const getMessagesUrl = new URL(url);
20
- getMessagesUrl.pathname += "/get-messages";
21
- const response = await fetch(getMessagesUrl.toString(), {
22
- credentials: options.credentials,
23
- headers: options.headers
24
- });
25
- return response.json();
26
- }
27
- const getInitialMessagesFetch = getInitialMessages || defaultGetInitialMessagesFetch;
28
- function doGetInitialMessages(getInitialMessagesOptions) {
29
- if (requestCache.has(agentUrlString)) {
30
- return requestCache.get(agentUrlString);
31
- }
32
- const promise = getInitialMessagesFetch(getInitialMessagesOptions);
33
- requestCache.set(agentUrlString, promise);
34
- return promise;
35
- }
36
- const initialMessagesPromise = getInitialMessages === null ? null : doGetInitialMessages({
37
- agent: agent.agent,
38
- name: agent.name,
39
- url: agentUrlString
40
- });
41
- const initialMessages = initialMessagesPromise ? use(initialMessagesPromise) : rest.initialMessages ?? [];
42
- useEffect(() => {
43
- if (!initialMessagesPromise) {
44
- return;
45
- }
46
- requestCache.set(agentUrlString, initialMessagesPromise);
47
- return () => {
48
- if (requestCache.get(agentUrlString) === initialMessagesPromise) {
49
- requestCache.delete(agentUrlString);
50
- }
51
- };
52
- }, [agentUrlString, initialMessagesPromise]);
53
- async function aiFetch(request, options2 = {}) {
54
- const {
55
- method,
56
- keepalive,
57
- headers,
58
- body,
59
- redirect,
60
- integrity,
61
- signal,
62
- credentials,
63
- mode,
64
- referrer,
65
- referrerPolicy,
66
- window
67
- // dispatcher, duplex
68
- } = options2;
69
- const id = nanoid(8);
70
- const abortController = new AbortController();
71
- signal?.addEventListener("abort", () => {
72
- agent.send(
73
- JSON.stringify({
74
- id,
75
- type: "cf_agent_chat_request_cancel" /* CF_AGENT_CHAT_REQUEST_CANCEL */
76
- })
77
- );
78
- abortController.abort();
79
- controller.close();
80
- });
81
- agent.addEventListener(
82
- "message",
83
- (event) => {
84
- let data;
85
- try {
86
- data = JSON.parse(event.data);
87
- } catch (_error) {
88
- return;
89
- }
90
- if (data.type === "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */) {
91
- if (data.id === id) {
92
- controller.enqueue(new TextEncoder().encode(data.body));
93
- if (data.done) {
94
- controller.close();
95
- abortController.abort();
96
- }
97
- }
98
- }
99
- },
100
- { signal: abortController.signal }
101
- );
102
- let controller;
103
- const stream = new ReadableStream({
104
- start(c) {
105
- controller = c;
106
- }
107
- });
108
- agent.send(
109
- JSON.stringify({
110
- id,
111
- init: {
112
- body,
113
- credentials,
114
- headers,
115
- integrity,
116
- keepalive,
117
- method,
118
- mode,
119
- redirect,
120
- referrer,
121
- referrerPolicy,
122
- window
123
- // dispatcher,
124
- // duplex
125
- },
126
- type: "cf_agent_use_chat_request" /* CF_AGENT_USE_CHAT_REQUEST */,
127
- url: request.toString()
128
- })
129
- );
130
- return new Response(stream);
131
- }
132
- const useChatHelpers = useChat({
133
- fetch: aiFetch,
134
- initialMessages,
135
- sendExtraMessageFields: true,
136
- ...rest
137
- });
138
- useEffect(() => {
139
- function onClearHistory(event) {
140
- if (typeof event.data !== "string") {
141
- return;
142
- }
143
- let data;
144
- try {
145
- data = JSON.parse(event.data);
146
- } catch (_error) {
147
- return;
148
- }
149
- if (data.type === "cf_agent_chat_clear" /* CF_AGENT_CHAT_CLEAR */) {
150
- useChatHelpers.setMessages([]);
151
- }
152
- }
153
- function onMessages(event) {
154
- if (typeof event.data !== "string") {
155
- return;
156
- }
157
- let data;
158
- try {
159
- data = JSON.parse(event.data);
160
- } catch (_error) {
161
- return;
162
- }
163
- if (data.type === "cf_agent_chat_messages" /* CF_AGENT_CHAT_MESSAGES */) {
164
- useChatHelpers.setMessages(data.messages);
165
- }
166
- }
167
- agent.addEventListener("message", onClearHistory);
168
- agent.addEventListener("message", onMessages);
169
- return () => {
170
- agent.removeEventListener("message", onClearHistory);
171
- agent.removeEventListener("message", onMessages);
172
- };
173
- }, [agent, useChatHelpers.setMessages]);
174
- return {
175
- ...useChatHelpers,
176
- /**
177
- * Clear chat history on both client and Agent
178
- */
179
- clearHistory: () => {
180
- useChatHelpers.setMessages([]);
181
- agent.send(
182
- JSON.stringify({
183
- type: "cf_agent_chat_clear" /* CF_AGENT_CHAT_CLEAR */
184
- })
185
- );
186
- },
187
- /**
188
- * Set the chat messages and synchronize with the Agent
189
- * @param messages New messages to set
190
- */
191
- setMessages: (messages) => {
192
- useChatHelpers.setMessages(messages);
193
- agent.send(
194
- JSON.stringify({
195
- messages,
196
- type: "cf_agent_chat_messages" /* CF_AGENT_CHAT_MESSAGES */
197
- })
198
- );
199
- }
200
- };
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 agentRef = useRef(agent);
31
+ useEffect(() => {
32
+ agentRef.current = agent;
33
+ }, [agent]);
34
+ async function defaultGetInitialMessagesFetch({ url }) {
35
+ const getMessagesUrl = new URL(url);
36
+ getMessagesUrl.pathname += "/get-messages";
37
+ const response = await fetch(getMessagesUrl.toString(), {
38
+ credentials: options.credentials,
39
+ headers: options.headers
40
+ });
41
+ if (!response.ok) {
42
+ console.warn(`Failed to fetch initial messages: ${response.status} ${response.statusText}`);
43
+ return [];
44
+ }
45
+ const text = await response.text();
46
+ if (!text.trim()) return [];
47
+ try {
48
+ return JSON.parse(text);
49
+ } catch (error) {
50
+ console.warn("Failed to parse initial messages JSON:", error);
51
+ return [];
52
+ }
53
+ }
54
+ const getInitialMessagesFetch = getInitialMessages || defaultGetInitialMessagesFetch;
55
+ function doGetInitialMessages(getInitialMessagesOptions) {
56
+ if (requestCache.has(agentUrlString)) return requestCache.get(agentUrlString);
57
+ const promise = getInitialMessagesFetch(getInitialMessagesOptions);
58
+ requestCache.set(agentUrlString, promise);
59
+ return promise;
60
+ }
61
+ const initialMessagesPromise = getInitialMessages === null ? null : doGetInitialMessages({
62
+ agent: agent.agent,
63
+ name: agent.name,
64
+ url: agentUrlString
65
+ });
66
+ const initialMessages = initialMessagesPromise ? use(initialMessagesPromise) : optionsInitialMessages ?? [];
67
+ useEffect(() => {
68
+ if (!initialMessagesPromise) return;
69
+ requestCache.set(agentUrlString, initialMessagesPromise);
70
+ return () => {
71
+ if (requestCache.get(agentUrlString) === initialMessagesPromise) requestCache.delete(agentUrlString);
72
+ };
73
+ }, [agentUrlString, initialMessagesPromise]);
74
+ const aiFetch = useCallback(async (request, options$1 = {}) => {
75
+ const { method, keepalive, headers, body, redirect, integrity, signal, credentials, mode, referrer, referrerPolicy, window } = options$1;
76
+ const id = nanoid(8);
77
+ const abortController = new AbortController();
78
+ let controller;
79
+ const currentAgent = agentRef.current;
80
+ signal?.addEventListener("abort", () => {
81
+ currentAgent.send(JSON.stringify({
82
+ id,
83
+ type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL
84
+ }));
85
+ abortController.abort();
86
+ controller.close();
87
+ });
88
+ currentAgent.addEventListener("message", (event) => {
89
+ let data;
90
+ try {
91
+ data = JSON.parse(event.data);
92
+ } catch (_error) {
93
+ return;
94
+ }
95
+ if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE) {
96
+ if (data.id === id) if (data.error) {
97
+ controller.error(new Error(data.body));
98
+ abortController.abort();
99
+ } else {
100
+ if (data.body?.trim()) controller.enqueue(new TextEncoder().encode(`data: ${data.body}\n\n`));
101
+ if (data.done) {
102
+ controller.close();
103
+ abortController.abort();
104
+ }
105
+ }
106
+ }
107
+ }, { signal: abortController.signal });
108
+ const stream = new ReadableStream({ start(c) {
109
+ controller = c;
110
+ } });
111
+ currentAgent.send(JSON.stringify({
112
+ id,
113
+ init: {
114
+ body,
115
+ credentials,
116
+ headers,
117
+ integrity,
118
+ keepalive,
119
+ method,
120
+ mode,
121
+ redirect,
122
+ referrer,
123
+ referrerPolicy,
124
+ window
125
+ },
126
+ type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
127
+ url: request.toString()
128
+ }));
129
+ return new Response(stream);
130
+ }, []);
131
+ const customTransport = useMemo(() => ({
132
+ sendMessages: async (options$1) => {
133
+ return new DefaultChatTransport({
134
+ api: agentUrlString,
135
+ fetch: aiFetch
136
+ }).sendMessages(options$1);
137
+ },
138
+ reconnectToStream: async (options$1) => {
139
+ return new DefaultChatTransport({
140
+ api: agentUrlString,
141
+ fetch: aiFetch
142
+ }).reconnectToStream(options$1);
143
+ }
144
+ }), [agentUrlString, aiFetch]);
145
+ const useChatHelpers = useChat({
146
+ ...rest,
147
+ messages: initialMessages,
148
+ transport: customTransport,
149
+ id: agent._pk
150
+ });
151
+ const processedToolCalls = useRef(/* @__PURE__ */ new Set());
152
+ const lastMessage = useChatHelpers.messages[useChatHelpers.messages.length - 1];
153
+ const pendingConfirmations = (() => {
154
+ if (!lastMessage || lastMessage.role !== "assistant") return {
155
+ messageId: void 0,
156
+ toolCallIds: /* @__PURE__ */ new Set()
157
+ };
158
+ const pendingIds = /* @__PURE__ */ new Set();
159
+ for (const part of lastMessage.parts ?? []) if (isToolUIPart(part) && part.state === "input-available" && toolsRequiringConfirmation.includes(getToolName(part))) pendingIds.add(part.toolCallId);
160
+ return {
161
+ messageId: lastMessage.id,
162
+ toolCallIds: pendingIds
163
+ };
164
+ })();
165
+ const pendingConfirmationsRef = useRef(pendingConfirmations);
166
+ pendingConfirmationsRef.current = pendingConfirmations;
167
+ useEffect(() => {
168
+ if (!experimental_automaticToolResolution) return;
169
+ const lastMessage$1 = useChatHelpers.messages[useChatHelpers.messages.length - 1];
170
+ if (!lastMessage$1 || lastMessage$1.role !== "assistant") return;
171
+ const toolCalls = lastMessage$1.parts.filter((part) => isToolUIPart(part) && part.state === "input-available" && !processedToolCalls.current.has(part.toolCallId));
172
+ if (toolCalls.length > 0) (async () => {
173
+ const toolCallsToResolve = toolCalls.filter((part) => isToolUIPart(part) && !toolsRequiringConfirmation.includes(getToolName(part)) && tools?.[getToolName(part)]?.execute);
174
+ if (toolCallsToResolve.length > 0) {
175
+ for (const part of toolCallsToResolve) if (isToolUIPart(part)) {
176
+ processedToolCalls.current.add(part.toolCallId);
177
+ let toolOutput = null;
178
+ const toolName = getToolName(part);
179
+ const tool$1 = tools?.[toolName];
180
+ if (tool$1?.execute && part.input) try {
181
+ toolOutput = await tool$1.execute(part.input);
182
+ } catch (error) {
183
+ toolOutput = `Error executing tool: ${error instanceof Error ? error.message : String(error)}`;
184
+ }
185
+ await useChatHelpers.addToolResult({
186
+ toolCallId: part.toolCallId,
187
+ tool: toolName,
188
+ output: toolOutput
189
+ });
190
+ }
191
+ if (pendingConfirmationsRef.current.toolCallIds.size === 0) useChatHelpers.sendMessage();
192
+ }
193
+ })();
194
+ }, [
195
+ useChatHelpers.messages,
196
+ experimental_automaticToolResolution,
197
+ useChatHelpers.addToolResult,
198
+ useChatHelpers.sendMessage,
199
+ toolsRequiringConfirmation
200
+ ]);
201
+ useEffect(() => {
202
+ function onClearHistory(event) {
203
+ if (typeof event.data !== "string") return;
204
+ let data;
205
+ try {
206
+ data = JSON.parse(event.data);
207
+ } catch (_error) {
208
+ return;
209
+ }
210
+ if (data.type === MessageType.CF_AGENT_CHAT_CLEAR) useChatHelpers.setMessages([]);
211
+ }
212
+ function onMessages(event) {
213
+ if (typeof event.data !== "string") return;
214
+ let data;
215
+ try {
216
+ data = JSON.parse(event.data);
217
+ } catch (_error) {
218
+ return;
219
+ }
220
+ if (data.type === MessageType.CF_AGENT_CHAT_MESSAGES) useChatHelpers.setMessages(data.messages);
221
+ }
222
+ agent.addEventListener("message", onClearHistory);
223
+ agent.addEventListener("message", onMessages);
224
+ return () => {
225
+ agent.removeEventListener("message", onClearHistory);
226
+ agent.removeEventListener("message", onMessages);
227
+ };
228
+ }, [agent, useChatHelpers.setMessages]);
229
+ const addToolResultAndSendMessage = async (args) => {
230
+ const { toolCallId } = args;
231
+ await useChatHelpers.addToolResult(args);
232
+ if (!autoSendAfterAllConfirmationsResolved) {
233
+ useChatHelpers.sendMessage();
234
+ return;
235
+ }
236
+ const pending = pendingConfirmationsRef.current?.toolCallIds;
237
+ if (!pending) {
238
+ useChatHelpers.sendMessage();
239
+ return;
240
+ }
241
+ const wasLast = pending.size === 1 && pending.has(toolCallId);
242
+ if (pending.has(toolCallId)) pending.delete(toolCallId);
243
+ if (wasLast || pending.size === 0) useChatHelpers.sendMessage();
244
+ };
245
+ return {
246
+ ...useChatHelpers,
247
+ addToolResult: addToolResultAndSendMessage,
248
+ clearHistory: () => {
249
+ useChatHelpers.setMessages([]);
250
+ agent.send(JSON.stringify({ type: MessageType.CF_AGENT_CHAT_CLEAR }));
251
+ },
252
+ setMessages: (messages) => {
253
+ useChatHelpers.setMessages(messages);
254
+ agent.send(JSON.stringify({
255
+ messages: Array.isArray(messages) ? messages : [],
256
+ type: MessageType.CF_AGENT_CHAT_MESSAGES
257
+ }));
258
+ }
259
+ };
201
260
  }
202
- export {
203
- useAgentChat
204
- };
261
+
262
+ //#endregion
263
+ export { detectToolsRequiringConfirmation, useAgentChat };
205
264
  //# sourceMappingURL=ai-react.js.map