agents 0.0.0-7972da4 → 0.0.0-79843bd
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.
- package/README.md +378 -27
- package/dist/ai-chat-agent.d.ts +236 -24
- package/dist/ai-chat-agent.js +1118 -222
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-chat-v5-migration-DguhuLKF.js +155 -0
- package/dist/ai-chat-v5-migration-DguhuLKF.js.map +1 -0
- package/dist/ai-chat-v5-migration.d.ts +155 -0
- package/dist/ai-chat-v5-migration.js +3 -0
- package/dist/ai-react.d.ts +202 -85
- package/dist/ai-react.js +574 -199
- package/dist/ai-react.js.map +1 -1
- package/dist/ai-types-DEtF_8Km.js +28 -0
- package/dist/ai-types-DEtF_8Km.js.map +1 -0
- package/dist/ai-types-U8lYA0o8.d.ts +127 -0
- package/dist/ai-types.d.ts +6 -74
- package/dist/ai-types.js +3 -1
- package/dist/cli/index.d.ts +1 -0
- package/dist/cli/index.js +28 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/client-BZVYeBmf.d.ts +834 -0
- package/dist/client-ClORm6f0.d.ts +104 -0
- package/dist/client-DjTPRM8-.js +117 -0
- package/dist/client-DjTPRM8-.js.map +1 -0
- package/dist/client-QZa2Rq0l.js +1105 -0
- package/dist/client-QZa2Rq0l.js.map +1 -0
- package/dist/client.d.ts +12 -93
- package/dist/client.js +4 -11
- package/dist/codemode/ai.d.ts +27 -0
- package/dist/codemode/ai.js +152 -0
- package/dist/codemode/ai.js.map +1 -0
- package/dist/context-BkKbAa1R.js +8 -0
- package/dist/context-BkKbAa1R.js.map +1 -0
- package/dist/context-_sPQqJWv.d.ts +24 -0
- package/dist/context.d.ts +6 -0
- package/dist/context.js +3 -0
- package/dist/do-oauth-client-provider-B-ryFIPr.d.ts +70 -0
- package/dist/do-oauth-client-provider-B1fVIshX.js +155 -0
- package/dist/do-oauth-client-provider-B1fVIshX.js.map +1 -0
- package/dist/index-B6XHf8p0.d.ts +577 -0
- package/dist/index-CyDpAVHZ.d.ts +58 -0
- package/dist/index.d.ts +61 -402
- package/dist/index.js +8 -22
- package/dist/mcp/client.d.ts +4 -783
- package/dist/mcp/client.js +4 -9
- package/dist/mcp/do-oauth-client-provider.d.ts +2 -41
- package/dist/mcp/do-oauth-client-provider.js +3 -7
- package/dist/mcp/index.d.ts +200 -81
- package/dist/mcp/index.js +1430 -770
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/x402.d.ts +34 -0
- package/dist/mcp/x402.js +198 -0
- package/dist/mcp/x402.js.map +1 -0
- package/dist/mcp-CzbSsLfc.d.ts +61 -0
- package/dist/observability/index.d.ts +3 -0
- package/dist/observability/index.js +8 -0
- package/dist/react-DYwejKBr.d.ts +131 -0
- package/dist/react.d.ts +15 -119
- package/dist/react.js +183 -110
- package/dist/react.js.map +1 -1
- package/dist/schedule.d.ts +89 -12
- package/dist/schedule.js +46 -21
- package/dist/schedule.js.map +1 -1
- package/dist/serializable-C4GLimgv.d.ts +39 -0
- package/dist/serializable.d.ts +7 -32
- package/dist/serializable.js +1 -1
- package/dist/src-BZDh910Z.js +1181 -0
- package/dist/src-BZDh910Z.js.map +1 -0
- package/package.json +125 -71
- package/dist/ai-types.js.map +0 -1
- package/dist/chunk-BZXOAZUX.js +0 -106
- package/dist/chunk-BZXOAZUX.js.map +0 -1
- package/dist/chunk-CFTLYEEK.js +0 -783
- package/dist/chunk-CFTLYEEK.js.map +0 -1
- package/dist/chunk-IFXSRTKF.js +0 -465
- package/dist/chunk-IFXSRTKF.js.map +0 -1
- package/dist/chunk-VCSB47AK.js +0 -116
- package/dist/chunk-VCSB47AK.js.map +0 -1
- package/dist/client.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/mcp/client.js.map +0 -1
- package/dist/mcp/do-oauth-client-provider.js.map +0 -1
- package/dist/serializable.js.map +0 -1
- package/src/index.ts +0 -1250
package/dist/ai-react.js
CHANGED
|
@@ -1,203 +1,578 @@
|
|
|
1
|
-
|
|
2
|
-
import {
|
|
3
|
-
import { use, useEffect } from "react";
|
|
1
|
+
import { t as MessageType } from "./ai-types-DEtF_8Km.js";
|
|
2
|
+
import { DefaultChatTransport, getToolName, isToolUIPart } from "ai";
|
|
4
3
|
import { nanoid } from "nanoid";
|
|
5
|
-
|
|
4
|
+
import { useChat } from "@ai-sdk/react";
|
|
5
|
+
import { use, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
6
|
+
|
|
7
|
+
//#region src/ai-react.tsx
|
|
8
|
+
/**
|
|
9
|
+
* Extracts tool schemas from tools that have client-side execute functions.
|
|
10
|
+
* These schemas are automatically sent to the server with each request.
|
|
11
|
+
* @param tools - Record of tool name to tool definition
|
|
12
|
+
* @returns Array of tool schemas to send to server, or undefined if none
|
|
13
|
+
*/
|
|
14
|
+
function extractClientToolSchemas(tools) {
|
|
15
|
+
if (!tools) return void 0;
|
|
16
|
+
const schemas = Object.entries(tools).filter(([_, tool$1]) => tool$1.execute).map(([name, tool$1]) => {
|
|
17
|
+
if (tool$1.inputSchema && !tool$1.parameters) console.warn(`[useAgentChat] Tool "${name}" uses deprecated 'inputSchema'. Please migrate to 'parameters'.`);
|
|
18
|
+
return {
|
|
19
|
+
name,
|
|
20
|
+
description: tool$1.description,
|
|
21
|
+
parameters: tool$1.parameters ?? tool$1.inputSchema
|
|
22
|
+
};
|
|
23
|
+
});
|
|
24
|
+
return schemas.length > 0 ? schemas : void 0;
|
|
25
|
+
}
|
|
26
|
+
const requestCache = /* @__PURE__ */ new Map();
|
|
27
|
+
/**
|
|
28
|
+
* React hook for building AI chat interfaces using an Agent
|
|
29
|
+
* @param options Chat options including the agent connection
|
|
30
|
+
* @returns Chat interface controls and state with added clearHistory method
|
|
31
|
+
*/
|
|
32
|
+
/**
|
|
33
|
+
* Automatically detects which tools require confirmation based on their configuration.
|
|
34
|
+
* Tools require confirmation if they have no execute function AND are not server-executed.
|
|
35
|
+
* @param tools - Record of tool name to tool definition
|
|
36
|
+
* @returns Array of tool names that require confirmation
|
|
37
|
+
*/
|
|
38
|
+
function detectToolsRequiringConfirmation(tools) {
|
|
39
|
+
if (!tools) return [];
|
|
40
|
+
return Object.entries(tools).filter(([_name, tool$1]) => !tool$1.execute).map(([name]) => name);
|
|
41
|
+
}
|
|
6
42
|
function useAgentChat(options) {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
43
|
+
const { agent, getInitialMessages, messages: optionsInitialMessages, experimental_automaticToolResolution, tools, toolsRequiringConfirmation: manualToolsRequiringConfirmation, autoContinueAfterToolResult = false, autoSendAfterAllConfirmationsResolved = true, resume = true, prepareSendMessagesRequest, ...rest } = options;
|
|
44
|
+
const toolsRequiringConfirmation = manualToolsRequiringConfirmation ?? detectToolsRequiringConfirmation(tools);
|
|
45
|
+
const agentUrl = new URL(`${(agent._url || agent._pkurl)?.replace("ws://", "http://").replace("wss://", "https://")}`);
|
|
46
|
+
agentUrl.searchParams.delete("_pk");
|
|
47
|
+
const agentUrlString = agentUrl.toString();
|
|
48
|
+
const initialMessagesCacheKey = `${agentUrlString}|${agent.agent ?? ""}|${agent.name ?? ""}`;
|
|
49
|
+
const agentRef = useRef(agent);
|
|
50
|
+
useEffect(() => {
|
|
51
|
+
agentRef.current = agent;
|
|
52
|
+
}, [agent]);
|
|
53
|
+
async function defaultGetInitialMessagesFetch({ url }) {
|
|
54
|
+
const getMessagesUrl = new URL(url);
|
|
55
|
+
getMessagesUrl.pathname += "/get-messages";
|
|
56
|
+
const response = await fetch(getMessagesUrl.toString(), {
|
|
57
|
+
credentials: options.credentials,
|
|
58
|
+
headers: options.headers
|
|
59
|
+
});
|
|
60
|
+
if (!response.ok) {
|
|
61
|
+
console.warn(`Failed to fetch initial messages: ${response.status} ${response.statusText}`);
|
|
62
|
+
return [];
|
|
63
|
+
}
|
|
64
|
+
const text = await response.text();
|
|
65
|
+
if (!text.trim()) return [];
|
|
66
|
+
try {
|
|
67
|
+
return JSON.parse(text);
|
|
68
|
+
} catch (error) {
|
|
69
|
+
console.warn("Failed to parse initial messages JSON:", error);
|
|
70
|
+
return [];
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
const getInitialMessagesFetch = getInitialMessages || defaultGetInitialMessagesFetch;
|
|
74
|
+
function doGetInitialMessages(getInitialMessagesOptions, cacheKey) {
|
|
75
|
+
if (requestCache.has(cacheKey)) return requestCache.get(cacheKey);
|
|
76
|
+
const promise = getInitialMessagesFetch(getInitialMessagesOptions);
|
|
77
|
+
requestCache.set(cacheKey, promise);
|
|
78
|
+
return promise;
|
|
79
|
+
}
|
|
80
|
+
const initialMessagesPromise = getInitialMessages === null ? null : doGetInitialMessages({
|
|
81
|
+
agent: agent.agent,
|
|
82
|
+
name: agent.name,
|
|
83
|
+
url: agentUrlString
|
|
84
|
+
}, initialMessagesCacheKey);
|
|
85
|
+
const initialMessages = initialMessagesPromise ? use(initialMessagesPromise) : optionsInitialMessages ?? [];
|
|
86
|
+
useEffect(() => {
|
|
87
|
+
if (!initialMessagesPromise) return;
|
|
88
|
+
requestCache.set(initialMessagesCacheKey, initialMessagesPromise);
|
|
89
|
+
return () => {
|
|
90
|
+
if (requestCache.get(initialMessagesCacheKey) === initialMessagesPromise) requestCache.delete(initialMessagesCacheKey);
|
|
91
|
+
};
|
|
92
|
+
}, [initialMessagesCacheKey, initialMessagesPromise]);
|
|
93
|
+
const aiFetch = useCallback(async (request, options$1 = {}) => {
|
|
94
|
+
const { method, keepalive, headers, body, redirect, integrity, signal, credentials, mode, referrer, referrerPolicy, window } = options$1;
|
|
95
|
+
const id = nanoid(8);
|
|
96
|
+
const abortController = new AbortController();
|
|
97
|
+
let controller;
|
|
98
|
+
const currentAgent = agentRef.current;
|
|
99
|
+
localRequestIdsRef.current.add(id);
|
|
100
|
+
signal?.addEventListener("abort", () => {
|
|
101
|
+
currentAgent.send(JSON.stringify({
|
|
102
|
+
id,
|
|
103
|
+
type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL
|
|
104
|
+
}));
|
|
105
|
+
abortController.abort();
|
|
106
|
+
try {
|
|
107
|
+
controller.close();
|
|
108
|
+
} catch {}
|
|
109
|
+
localRequestIdsRef.current.delete(id);
|
|
110
|
+
});
|
|
111
|
+
currentAgent.addEventListener("message", (event) => {
|
|
112
|
+
let data;
|
|
113
|
+
try {
|
|
114
|
+
data = JSON.parse(event.data);
|
|
115
|
+
} catch (_error) {
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE) {
|
|
119
|
+
if (data.id === id) if (data.error) {
|
|
120
|
+
controller.error(new Error(data.body));
|
|
121
|
+
abortController.abort();
|
|
122
|
+
localRequestIdsRef.current.delete(id);
|
|
123
|
+
} else {
|
|
124
|
+
if (data.body?.trim()) controller.enqueue(new TextEncoder().encode(`data: ${data.body}\n\n`));
|
|
125
|
+
if (data.done) {
|
|
126
|
+
try {
|
|
127
|
+
controller.close();
|
|
128
|
+
} catch {}
|
|
129
|
+
abortController.abort();
|
|
130
|
+
localRequestIdsRef.current.delete(id);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}, { signal: abortController.signal });
|
|
135
|
+
const stream = new ReadableStream({
|
|
136
|
+
start(c) {
|
|
137
|
+
controller = c;
|
|
138
|
+
},
|
|
139
|
+
cancel(reason) {
|
|
140
|
+
console.warn("[agents/ai-react] cancelling stream", id, reason || "no reason");
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
currentAgent.send(JSON.stringify({
|
|
144
|
+
id,
|
|
145
|
+
init: {
|
|
146
|
+
body,
|
|
147
|
+
credentials,
|
|
148
|
+
headers,
|
|
149
|
+
integrity,
|
|
150
|
+
keepalive,
|
|
151
|
+
method,
|
|
152
|
+
mode,
|
|
153
|
+
redirect,
|
|
154
|
+
referrer,
|
|
155
|
+
referrerPolicy,
|
|
156
|
+
window
|
|
157
|
+
},
|
|
158
|
+
type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
|
|
159
|
+
url: request.toString()
|
|
160
|
+
}));
|
|
161
|
+
return new Response(stream);
|
|
162
|
+
}, []);
|
|
163
|
+
const toolsRef = useRef(tools);
|
|
164
|
+
toolsRef.current = tools;
|
|
165
|
+
const prepareSendMessagesRequestRef = useRef(prepareSendMessagesRequest);
|
|
166
|
+
prepareSendMessagesRequestRef.current = prepareSendMessagesRequest;
|
|
167
|
+
const customTransport = useMemo(() => ({
|
|
168
|
+
sendMessages: async (sendMessageOptions) => {
|
|
169
|
+
const clientToolSchemas = extractClientToolSchemas(toolsRef.current);
|
|
170
|
+
return new DefaultChatTransport({
|
|
171
|
+
api: agentUrlString,
|
|
172
|
+
fetch: aiFetch,
|
|
173
|
+
prepareSendMessagesRequest: clientToolSchemas || prepareSendMessagesRequestRef.current ? async (prepareOptions) => {
|
|
174
|
+
let body = {};
|
|
175
|
+
let headers;
|
|
176
|
+
let credentials;
|
|
177
|
+
let api;
|
|
178
|
+
if (clientToolSchemas) body = {
|
|
179
|
+
id: prepareOptions.id,
|
|
180
|
+
messages: prepareOptions.messages,
|
|
181
|
+
trigger: prepareOptions.trigger,
|
|
182
|
+
clientTools: clientToolSchemas
|
|
183
|
+
};
|
|
184
|
+
if (prepareSendMessagesRequestRef.current) {
|
|
185
|
+
const userResult = await prepareSendMessagesRequestRef.current(prepareOptions);
|
|
186
|
+
headers = userResult.headers;
|
|
187
|
+
credentials = userResult.credentials;
|
|
188
|
+
api = userResult.api;
|
|
189
|
+
body = {
|
|
190
|
+
...body,
|
|
191
|
+
...userResult.body ?? {}
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
return {
|
|
195
|
+
body,
|
|
196
|
+
headers,
|
|
197
|
+
credentials,
|
|
198
|
+
api
|
|
199
|
+
};
|
|
200
|
+
} : void 0
|
|
201
|
+
}).sendMessages(sendMessageOptions);
|
|
202
|
+
},
|
|
203
|
+
reconnectToStream: async () => null
|
|
204
|
+
}), [agentUrlString, aiFetch]);
|
|
205
|
+
const useChatHelpers = useChat({
|
|
206
|
+
...rest,
|
|
207
|
+
messages: initialMessages,
|
|
208
|
+
transport: customTransport,
|
|
209
|
+
id: agent._pk
|
|
210
|
+
});
|
|
211
|
+
const processedToolCalls = useRef(/* @__PURE__ */ new Set());
|
|
212
|
+
const isResolvingToolsRef = useRef(false);
|
|
213
|
+
const [clientToolResults, setClientToolResults] = useState(/* @__PURE__ */ new Map());
|
|
214
|
+
const messagesRef = useRef(useChatHelpers.messages);
|
|
215
|
+
messagesRef.current = useChatHelpers.messages;
|
|
216
|
+
const lastMessage = useChatHelpers.messages[useChatHelpers.messages.length - 1];
|
|
217
|
+
const pendingConfirmations = (() => {
|
|
218
|
+
if (!lastMessage || lastMessage.role !== "assistant") return {
|
|
219
|
+
messageId: void 0,
|
|
220
|
+
toolCallIds: /* @__PURE__ */ new Set()
|
|
221
|
+
};
|
|
222
|
+
const pendingIds = /* @__PURE__ */ new Set();
|
|
223
|
+
for (const part of lastMessage.parts ?? []) if (isToolUIPart(part) && part.state === "input-available" && toolsRequiringConfirmation.includes(getToolName(part))) pendingIds.add(part.toolCallId);
|
|
224
|
+
return {
|
|
225
|
+
messageId: lastMessage.id,
|
|
226
|
+
toolCallIds: pendingIds
|
|
227
|
+
};
|
|
228
|
+
})();
|
|
229
|
+
const pendingConfirmationsRef = useRef(pendingConfirmations);
|
|
230
|
+
pendingConfirmationsRef.current = pendingConfirmations;
|
|
231
|
+
useEffect(() => {
|
|
232
|
+
if (!experimental_automaticToolResolution) return;
|
|
233
|
+
if (isResolvingToolsRef.current) return;
|
|
234
|
+
const lastMessage$1 = useChatHelpers.messages[useChatHelpers.messages.length - 1];
|
|
235
|
+
if (!lastMessage$1 || lastMessage$1.role !== "assistant") return;
|
|
236
|
+
const toolCalls = lastMessage$1.parts.filter((part) => isToolUIPart(part) && part.state === "input-available" && !processedToolCalls.current.has(part.toolCallId));
|
|
237
|
+
if (toolCalls.length > 0) {
|
|
238
|
+
const currentTools = toolsRef.current;
|
|
239
|
+
const toolCallsToResolve = toolCalls.filter((part) => isToolUIPart(part) && !toolsRequiringConfirmation.includes(getToolName(part)) && currentTools?.[getToolName(part)]?.execute);
|
|
240
|
+
if (toolCallsToResolve.length > 0) {
|
|
241
|
+
isResolvingToolsRef.current = true;
|
|
242
|
+
(async () => {
|
|
243
|
+
try {
|
|
244
|
+
const toolResults = [];
|
|
245
|
+
for (const part of toolCallsToResolve) if (isToolUIPart(part)) {
|
|
246
|
+
let toolOutput = null;
|
|
247
|
+
const toolName = getToolName(part);
|
|
248
|
+
const tool$1 = currentTools?.[toolName];
|
|
249
|
+
if (tool$1?.execute && part.input !== void 0) try {
|
|
250
|
+
toolOutput = await tool$1.execute(part.input);
|
|
251
|
+
} catch (error) {
|
|
252
|
+
toolOutput = `Error executing tool: ${error instanceof Error ? error.message : String(error)}`;
|
|
253
|
+
}
|
|
254
|
+
processedToolCalls.current.add(part.toolCallId);
|
|
255
|
+
toolResults.push({
|
|
256
|
+
toolCallId: part.toolCallId,
|
|
257
|
+
toolName,
|
|
258
|
+
output: toolOutput
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
if (toolResults.length > 0) {
|
|
262
|
+
for (const result of toolResults) agentRef.current.send(JSON.stringify({
|
|
263
|
+
type: MessageType.CF_AGENT_TOOL_RESULT,
|
|
264
|
+
toolCallId: result.toolCallId,
|
|
265
|
+
toolName: result.toolName,
|
|
266
|
+
output: result.output,
|
|
267
|
+
autoContinue: autoContinueAfterToolResult
|
|
268
|
+
}));
|
|
269
|
+
await Promise.all(toolResults.map((result) => useChatHelpers.addToolResult({
|
|
270
|
+
tool: result.toolName,
|
|
271
|
+
toolCallId: result.toolCallId,
|
|
272
|
+
output: result.output
|
|
273
|
+
})));
|
|
274
|
+
setClientToolResults((prev) => {
|
|
275
|
+
const newMap = new Map(prev);
|
|
276
|
+
for (const result of toolResults) newMap.set(result.toolCallId, result.output);
|
|
277
|
+
return newMap;
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
} finally {
|
|
281
|
+
isResolvingToolsRef.current = false;
|
|
282
|
+
}
|
|
283
|
+
})();
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}, [
|
|
287
|
+
useChatHelpers.messages,
|
|
288
|
+
experimental_automaticToolResolution,
|
|
289
|
+
useChatHelpers.addToolResult,
|
|
290
|
+
toolsRequiringConfirmation,
|
|
291
|
+
autoContinueAfterToolResult
|
|
292
|
+
]);
|
|
293
|
+
/**
|
|
294
|
+
* Contains the request ID, accumulated message parts, and a unique message ID.
|
|
295
|
+
* Used for both resumed streams and real-time broadcasts from other tabs.
|
|
296
|
+
*/
|
|
297
|
+
const activeStreamRef = useRef(null);
|
|
298
|
+
/**
|
|
299
|
+
* Tracks request IDs initiated by this tab via aiFetch.
|
|
300
|
+
* Used to distinguish local requests from broadcasts.
|
|
301
|
+
*/
|
|
302
|
+
const localRequestIdsRef = useRef(/* @__PURE__ */ new Set());
|
|
303
|
+
useEffect(() => {
|
|
304
|
+
/**
|
|
305
|
+
* Unified message handler that parses JSON once and dispatches based on type.
|
|
306
|
+
* Avoids duplicate parsing overhead from separate listeners.
|
|
307
|
+
*/
|
|
308
|
+
function onAgentMessage(event) {
|
|
309
|
+
if (typeof event.data !== "string") return;
|
|
310
|
+
let data;
|
|
311
|
+
try {
|
|
312
|
+
data = JSON.parse(event.data);
|
|
313
|
+
} catch (_error) {
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
switch (data.type) {
|
|
317
|
+
case MessageType.CF_AGENT_CHAT_CLEAR:
|
|
318
|
+
useChatHelpers.setMessages([]);
|
|
319
|
+
break;
|
|
320
|
+
case MessageType.CF_AGENT_CHAT_MESSAGES:
|
|
321
|
+
useChatHelpers.setMessages(data.messages);
|
|
322
|
+
break;
|
|
323
|
+
case MessageType.CF_AGENT_MESSAGE_UPDATED:
|
|
324
|
+
useChatHelpers.setMessages((prevMessages) => {
|
|
325
|
+
const updatedMessage = data.message;
|
|
326
|
+
let idx = prevMessages.findIndex((m) => m.id === updatedMessage.id);
|
|
327
|
+
if (idx < 0) {
|
|
328
|
+
const updatedToolCallIds = new Set(updatedMessage.parts.filter((p) => "toolCallId" in p && p.toolCallId).map((p) => p.toolCallId));
|
|
329
|
+
if (updatedToolCallIds.size > 0) idx = prevMessages.findIndex((m) => m.parts.some((p) => "toolCallId" in p && updatedToolCallIds.has(p.toolCallId)));
|
|
330
|
+
}
|
|
331
|
+
if (idx >= 0) {
|
|
332
|
+
const updated = [...prevMessages];
|
|
333
|
+
updated[idx] = {
|
|
334
|
+
...updatedMessage,
|
|
335
|
+
id: prevMessages[idx].id
|
|
336
|
+
};
|
|
337
|
+
return updated;
|
|
338
|
+
}
|
|
339
|
+
return [...prevMessages, updatedMessage];
|
|
340
|
+
});
|
|
341
|
+
break;
|
|
342
|
+
case MessageType.CF_AGENT_STREAM_RESUMING:
|
|
343
|
+
if (!resume) return;
|
|
344
|
+
activeStreamRef.current = null;
|
|
345
|
+
activeStreamRef.current = {
|
|
346
|
+
id: data.id,
|
|
347
|
+
messageId: nanoid(),
|
|
348
|
+
parts: []
|
|
349
|
+
};
|
|
350
|
+
agentRef.current.send(JSON.stringify({
|
|
351
|
+
type: MessageType.CF_AGENT_STREAM_RESUME_ACK,
|
|
352
|
+
id: data.id
|
|
353
|
+
}));
|
|
354
|
+
break;
|
|
355
|
+
case MessageType.CF_AGENT_USE_CHAT_RESPONSE: {
|
|
356
|
+
if (localRequestIdsRef.current.has(data.id)) return;
|
|
357
|
+
const isContinuation = data.continuation === true;
|
|
358
|
+
if (!activeStreamRef.current || activeStreamRef.current.id !== data.id) {
|
|
359
|
+
let messageId = nanoid();
|
|
360
|
+
let existingParts = [];
|
|
361
|
+
if (isContinuation) {
|
|
362
|
+
const currentMessages = messagesRef.current;
|
|
363
|
+
for (let i = currentMessages.length - 1; i >= 0; i--) if (currentMessages[i].role === "assistant") {
|
|
364
|
+
messageId = currentMessages[i].id;
|
|
365
|
+
existingParts = [...currentMessages[i].parts];
|
|
366
|
+
break;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
activeStreamRef.current = {
|
|
370
|
+
id: data.id,
|
|
371
|
+
messageId,
|
|
372
|
+
parts: existingParts
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
const activeMsg = activeStreamRef.current;
|
|
376
|
+
if (data.body?.trim()) try {
|
|
377
|
+
const chunkData = JSON.parse(data.body);
|
|
378
|
+
switch (chunkData.type) {
|
|
379
|
+
case "text-start":
|
|
380
|
+
activeMsg.parts.push({
|
|
381
|
+
type: "text",
|
|
382
|
+
text: "",
|
|
383
|
+
state: "streaming"
|
|
384
|
+
});
|
|
385
|
+
break;
|
|
386
|
+
case "text-delta": {
|
|
387
|
+
const lastTextPart = [...activeMsg.parts].reverse().find((p) => p.type === "text");
|
|
388
|
+
if (lastTextPart && lastTextPart.type === "text") lastTextPart.text += chunkData.delta;
|
|
389
|
+
else activeMsg.parts.push({
|
|
390
|
+
type: "text",
|
|
391
|
+
text: chunkData.delta
|
|
392
|
+
});
|
|
393
|
+
break;
|
|
394
|
+
}
|
|
395
|
+
case "text-end": {
|
|
396
|
+
const lastTextPart = [...activeMsg.parts].reverse().find((p) => p.type === "text");
|
|
397
|
+
if (lastTextPart && "state" in lastTextPart) lastTextPart.state = "done";
|
|
398
|
+
break;
|
|
399
|
+
}
|
|
400
|
+
case "reasoning-start":
|
|
401
|
+
activeMsg.parts.push({
|
|
402
|
+
type: "reasoning",
|
|
403
|
+
text: "",
|
|
404
|
+
state: "streaming"
|
|
405
|
+
});
|
|
406
|
+
break;
|
|
407
|
+
case "reasoning-delta": {
|
|
408
|
+
const lastReasoningPart = [...activeMsg.parts].reverse().find((p) => p.type === "reasoning");
|
|
409
|
+
if (lastReasoningPart && lastReasoningPart.type === "reasoning") lastReasoningPart.text += chunkData.delta;
|
|
410
|
+
break;
|
|
411
|
+
}
|
|
412
|
+
case "reasoning-end": {
|
|
413
|
+
const lastReasoningPart = [...activeMsg.parts].reverse().find((p) => p.type === "reasoning");
|
|
414
|
+
if (lastReasoningPart && "state" in lastReasoningPart) lastReasoningPart.state = "done";
|
|
415
|
+
break;
|
|
416
|
+
}
|
|
417
|
+
case "file":
|
|
418
|
+
activeMsg.parts.push({
|
|
419
|
+
type: "file",
|
|
420
|
+
mediaType: chunkData.mediaType,
|
|
421
|
+
url: chunkData.url
|
|
422
|
+
});
|
|
423
|
+
break;
|
|
424
|
+
case "source-url":
|
|
425
|
+
activeMsg.parts.push({
|
|
426
|
+
type: "source-url",
|
|
427
|
+
sourceId: chunkData.sourceId,
|
|
428
|
+
url: chunkData.url,
|
|
429
|
+
title: chunkData.title
|
|
430
|
+
});
|
|
431
|
+
break;
|
|
432
|
+
case "source-document":
|
|
433
|
+
activeMsg.parts.push({
|
|
434
|
+
type: "source-document",
|
|
435
|
+
sourceId: chunkData.sourceId,
|
|
436
|
+
mediaType: chunkData.mediaType,
|
|
437
|
+
title: chunkData.title,
|
|
438
|
+
filename: chunkData.filename
|
|
439
|
+
});
|
|
440
|
+
break;
|
|
441
|
+
case "tool-input-available":
|
|
442
|
+
activeMsg.parts.push({
|
|
443
|
+
type: `tool-${chunkData.toolName}`,
|
|
444
|
+
toolCallId: chunkData.toolCallId,
|
|
445
|
+
toolName: chunkData.toolName,
|
|
446
|
+
state: "input-available",
|
|
447
|
+
input: chunkData.input
|
|
448
|
+
});
|
|
449
|
+
break;
|
|
450
|
+
case "tool-output-available":
|
|
451
|
+
activeMsg.parts = activeMsg.parts.map((p) => {
|
|
452
|
+
if ("toolCallId" in p && p.toolCallId === chunkData.toolCallId && "state" in p) return {
|
|
453
|
+
...p,
|
|
454
|
+
state: "output-available",
|
|
455
|
+
output: chunkData.output
|
|
456
|
+
};
|
|
457
|
+
return p;
|
|
458
|
+
});
|
|
459
|
+
break;
|
|
460
|
+
case "step-start":
|
|
461
|
+
activeMsg.parts.push({ type: "step-start" });
|
|
462
|
+
break;
|
|
463
|
+
}
|
|
464
|
+
useChatHelpers.setMessages((prevMessages) => {
|
|
465
|
+
if (!activeMsg) return prevMessages;
|
|
466
|
+
const existingIdx = prevMessages.findIndex((m) => m.id === activeMsg.messageId);
|
|
467
|
+
const partialMessage = {
|
|
468
|
+
id: activeMsg.messageId,
|
|
469
|
+
role: "assistant",
|
|
470
|
+
parts: [...activeMsg.parts]
|
|
471
|
+
};
|
|
472
|
+
if (existingIdx >= 0) {
|
|
473
|
+
const updated = [...prevMessages];
|
|
474
|
+
updated[existingIdx] = partialMessage;
|
|
475
|
+
return updated;
|
|
476
|
+
}
|
|
477
|
+
return [...prevMessages, partialMessage];
|
|
478
|
+
});
|
|
479
|
+
} catch (parseError) {
|
|
480
|
+
console.warn("[useAgentChat] Failed to parse stream chunk:", parseError instanceof Error ? parseError.message : parseError, "body:", data.body?.slice(0, 100));
|
|
481
|
+
}
|
|
482
|
+
if (data.done || data.error) activeStreamRef.current = null;
|
|
483
|
+
break;
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
agent.addEventListener("message", onAgentMessage);
|
|
488
|
+
return () => {
|
|
489
|
+
agent.removeEventListener("message", onAgentMessage);
|
|
490
|
+
activeStreamRef.current = null;
|
|
491
|
+
};
|
|
492
|
+
}, [
|
|
493
|
+
agent,
|
|
494
|
+
useChatHelpers.setMessages,
|
|
495
|
+
resume
|
|
496
|
+
]);
|
|
497
|
+
const addToolResultAndSendMessage = async (args) => {
|
|
498
|
+
const { toolCallId } = args;
|
|
499
|
+
const toolName = "tool" in args ? args.tool : "";
|
|
500
|
+
const output = "output" in args ? args.output : void 0;
|
|
501
|
+
agentRef.current.send(JSON.stringify({
|
|
502
|
+
type: MessageType.CF_AGENT_TOOL_RESULT,
|
|
503
|
+
toolCallId,
|
|
504
|
+
toolName,
|
|
505
|
+
output,
|
|
506
|
+
autoContinue: autoContinueAfterToolResult
|
|
507
|
+
}));
|
|
508
|
+
setClientToolResults((prev) => new Map(prev).set(toolCallId, output));
|
|
509
|
+
useChatHelpers.addToolResult(args);
|
|
510
|
+
if (!autoContinueAfterToolResult) {
|
|
511
|
+
if (!autoSendAfterAllConfirmationsResolved) {
|
|
512
|
+
useChatHelpers.sendMessage();
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
const pending = pendingConfirmationsRef.current?.toolCallIds;
|
|
516
|
+
if (!pending) {
|
|
517
|
+
useChatHelpers.sendMessage();
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
520
|
+
const wasLast = pending.size === 1 && pending.has(toolCallId);
|
|
521
|
+
if (pending.has(toolCallId)) pending.delete(toolCallId);
|
|
522
|
+
if (wasLast || pending.size === 0) useChatHelpers.sendMessage();
|
|
523
|
+
}
|
|
524
|
+
};
|
|
525
|
+
const messagesWithToolResults = useMemo(() => {
|
|
526
|
+
if (clientToolResults.size === 0) return useChatHelpers.messages;
|
|
527
|
+
return useChatHelpers.messages.map((msg) => ({
|
|
528
|
+
...msg,
|
|
529
|
+
parts: msg.parts.map((p) => {
|
|
530
|
+
if (!("toolCallId" in p) || !("state" in p) || p.state !== "input-available" || !clientToolResults.has(p.toolCallId)) return p;
|
|
531
|
+
return {
|
|
532
|
+
...p,
|
|
533
|
+
state: "output-available",
|
|
534
|
+
output: clientToolResults.get(p.toolCallId)
|
|
535
|
+
};
|
|
536
|
+
})
|
|
537
|
+
}));
|
|
538
|
+
}, [useChatHelpers.messages, clientToolResults]);
|
|
539
|
+
useEffect(() => {
|
|
540
|
+
const currentToolCallIds = /* @__PURE__ */ new Set();
|
|
541
|
+
for (const msg of useChatHelpers.messages) for (const part of msg.parts) if ("toolCallId" in part && part.toolCallId) currentToolCallIds.add(part.toolCallId);
|
|
542
|
+
setClientToolResults((prev) => {
|
|
543
|
+
if (prev.size === 0) return prev;
|
|
544
|
+
let hasStaleEntries = false;
|
|
545
|
+
for (const toolCallId of prev.keys()) if (!currentToolCallIds.has(toolCallId)) {
|
|
546
|
+
hasStaleEntries = true;
|
|
547
|
+
break;
|
|
548
|
+
}
|
|
549
|
+
if (!hasStaleEntries) return prev;
|
|
550
|
+
const newMap = /* @__PURE__ */ new Map();
|
|
551
|
+
for (const [id, output] of prev) if (currentToolCallIds.has(id)) newMap.set(id, output);
|
|
552
|
+
return newMap;
|
|
553
|
+
});
|
|
554
|
+
for (const toolCallId of processedToolCalls.current) if (!currentToolCallIds.has(toolCallId)) processedToolCalls.current.delete(toolCallId);
|
|
555
|
+
}, [useChatHelpers.messages]);
|
|
556
|
+
return {
|
|
557
|
+
...useChatHelpers,
|
|
558
|
+
messages: messagesWithToolResults,
|
|
559
|
+
addToolResult: addToolResultAndSendMessage,
|
|
560
|
+
clearHistory: () => {
|
|
561
|
+
useChatHelpers.setMessages([]);
|
|
562
|
+
setClientToolResults(/* @__PURE__ */ new Map());
|
|
563
|
+
processedToolCalls.current.clear();
|
|
564
|
+
agent.send(JSON.stringify({ type: MessageType.CF_AGENT_CHAT_CLEAR }));
|
|
565
|
+
},
|
|
566
|
+
setMessages: (messages) => {
|
|
567
|
+
useChatHelpers.setMessages(messages);
|
|
568
|
+
agent.send(JSON.stringify({
|
|
569
|
+
messages: Array.isArray(messages) ? messages : [],
|
|
570
|
+
type: MessageType.CF_AGENT_CHAT_MESSAGES
|
|
571
|
+
}));
|
|
572
|
+
}
|
|
573
|
+
};
|
|
199
574
|
}
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
};
|
|
575
|
+
|
|
576
|
+
//#endregion
|
|
577
|
+
export { detectToolsRequiringConfirmation, extractClientToolSchemas, useAgentChat };
|
|
203
578
|
//# sourceMappingURL=ai-react.js.map
|