agents 0.0.0-49fb428 → 0.0.0-4abd78a
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 +255 -27
- package/dist/ai-chat-agent.d.ts +57 -7
- package/dist/ai-chat-agent.js +284 -93
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-chat-v5-migration.d.ts +152 -0
- package/dist/ai-chat-v5-migration.js +19 -0
- package/dist/ai-react.d.ts +77 -67
- package/dist/ai-react.js +213 -66
- package/dist/ai-react.js.map +1 -1
- package/dist/ai-types.d.ts +40 -18
- package/dist/ai-types.js +6 -0
- package/dist/chunk-AVYJQSLW.js +17 -0
- package/dist/chunk-AVYJQSLW.js.map +1 -0
- package/dist/chunk-LL2AFX7V.js +109 -0
- package/dist/chunk-LL2AFX7V.js.map +1 -0
- package/dist/chunk-M5SZRJTA.js +1300 -0
- package/dist/chunk-M5SZRJTA.js.map +1 -0
- package/dist/chunk-MH46VMM4.js +612 -0
- package/dist/chunk-MH46VMM4.js.map +1 -0
- package/dist/chunk-QEVM4BVL.js +116 -0
- package/dist/chunk-QEVM4BVL.js.map +1 -0
- package/dist/chunk-UJVEAURM.js +150 -0
- package/dist/chunk-UJVEAURM.js.map +1 -0
- package/dist/client-CvaJdLQA.d.ts +5015 -0
- package/dist/client.d.ts +16 -2
- package/dist/client.js +7 -126
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +284 -22
- package/dist/index.js +17 -6
- package/dist/mcp/client.d.ts +9 -761
- package/dist/mcp/client.js +3 -402
- package/dist/mcp/client.js.map +1 -1
- package/dist/mcp/do-oauth-client-provider.d.ts +4 -3
- package/dist/mcp/do-oauth-client-provider.js +3 -103
- package/dist/mcp/do-oauth-client-provider.js.map +1 -1
- package/dist/mcp/index.d.ts +83 -31
- package/dist/mcp/index.js +947 -267
- package/dist/mcp/index.js.map +1 -1
- package/dist/observability/index.d.ts +46 -0
- package/dist/observability/index.js +11 -0
- package/dist/observability/index.js.map +1 -0
- package/dist/react.d.ts +89 -5
- package/dist/react.js +23 -9
- package/dist/react.js.map +1 -1
- package/dist/schedule.d.ts +81 -7
- package/dist/schedule.js +19 -8
- package/dist/schedule.js.map +1 -1
- package/dist/serializable.d.ts +32 -0
- package/dist/serializable.js +1 -0
- package/dist/serializable.js.map +1 -0
- package/package.json +87 -52
- package/src/index.ts +1193 -152
- package/dist/chunk-HMLY7DHA.js +0 -16
- package/dist/chunk-XG52S6YY.js +0 -591
- package/dist/chunk-XG52S6YY.js.map +0 -1
- /package/dist/{chunk-HMLY7DHA.js.map → ai-chat-v5-migration.js.map} +0 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import {
|
|
2
|
+
analyzeCorruption,
|
|
3
|
+
autoTransformMessage,
|
|
4
|
+
autoTransformMessages,
|
|
5
|
+
isUIMessage,
|
|
6
|
+
migrateMessagesToUIFormat,
|
|
7
|
+
migrateToUIMessage,
|
|
8
|
+
needsMigration
|
|
9
|
+
} from "./chunk-UJVEAURM.js";
|
|
10
|
+
export {
|
|
11
|
+
analyzeCorruption,
|
|
12
|
+
autoTransformMessage,
|
|
13
|
+
autoTransformMessages,
|
|
14
|
+
isUIMessage,
|
|
15
|
+
migrateMessagesToUIFormat,
|
|
16
|
+
migrateToUIMessage,
|
|
17
|
+
needsMigration
|
|
18
|
+
};
|
|
19
|
+
//# sourceMappingURL=ai-chat-v5-migration.js.map
|
package/dist/ai-react.d.ts
CHANGED
|
@@ -1,88 +1,98 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {
|
|
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";
|
|
6
|
+
import "./index.js";
|
|
7
|
+
import "cloudflare:workers";
|
|
8
|
+
import "@modelcontextprotocol/sdk/client/index.js";
|
|
9
|
+
import "@modelcontextprotocol/sdk/types.js";
|
|
10
|
+
import "partyserver";
|
|
11
|
+
import "./client-CvaJdLQA.js";
|
|
12
|
+
import "zod";
|
|
13
|
+
import "@modelcontextprotocol/sdk/shared/protocol.js";
|
|
14
|
+
import "@modelcontextprotocol/sdk/client/sse.js";
|
|
15
|
+
import "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
16
|
+
import "./mcp/do-oauth-client-provider.js";
|
|
17
|
+
import "@modelcontextprotocol/sdk/client/auth.js";
|
|
18
|
+
import "@modelcontextprotocol/sdk/shared/auth.js";
|
|
19
|
+
import "./observability/index.js";
|
|
20
|
+
import "./ai-types.js";
|
|
7
21
|
import "./client.js";
|
|
22
|
+
import "./serializable.js";
|
|
8
23
|
|
|
24
|
+
type AITool<Input = unknown, Output = unknown> = {
|
|
25
|
+
description?: string;
|
|
26
|
+
inputSchema?: unknown;
|
|
27
|
+
execute?: (input: Input) => Output | Promise<Output>;
|
|
28
|
+
};
|
|
9
29
|
type GetInitialMessagesOptions = {
|
|
10
30
|
agent: string;
|
|
11
31
|
name: string;
|
|
12
32
|
url: string;
|
|
13
33
|
};
|
|
34
|
+
type UseChatParams<M extends UIMessage = UIMessage> = ChatInit<M> &
|
|
35
|
+
UseChatOptions<M>;
|
|
14
36
|
/**
|
|
15
37
|
* Options for the useAgentChat hook
|
|
16
38
|
*/
|
|
17
|
-
type UseAgentChatOptions<
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
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
|
+
};
|
|
28
75
|
/**
|
|
29
76
|
* React hook for building AI chat interfaces using an Agent
|
|
30
77
|
* @param options Chat options including the agent connection
|
|
31
78
|
* @returns Chat interface controls and state with added clearHistory method
|
|
32
79
|
*/
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
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>> & {
|
|
44
95
|
clearHistory: () => void;
|
|
45
|
-
messages: ai.UIMessage[];
|
|
46
|
-
error: undefined | Error;
|
|
47
|
-
append: (
|
|
48
|
-
message: Message | ai.CreateMessage,
|
|
49
|
-
chatRequestOptions?: ai.ChatRequestOptions
|
|
50
|
-
) => Promise<string | null | undefined>;
|
|
51
|
-
reload: (
|
|
52
|
-
chatRequestOptions?: ai.ChatRequestOptions
|
|
53
|
-
) => Promise<string | null | undefined>;
|
|
54
|
-
stop: () => void;
|
|
55
|
-
input: string;
|
|
56
|
-
setInput: React.Dispatch<React.SetStateAction<string>>;
|
|
57
|
-
handleInputChange: (
|
|
58
|
-
e:
|
|
59
|
-
| React.ChangeEvent<HTMLInputElement>
|
|
60
|
-
| React.ChangeEvent<HTMLTextAreaElement>
|
|
61
|
-
) => void;
|
|
62
|
-
handleSubmit: (
|
|
63
|
-
event?: {
|
|
64
|
-
preventDefault?: () => void;
|
|
65
|
-
},
|
|
66
|
-
chatRequestOptions?: ai.ChatRequestOptions
|
|
67
|
-
) => void;
|
|
68
|
-
metadata?: Object;
|
|
69
|
-
isLoading: boolean;
|
|
70
|
-
status: "submitted" | "streaming" | "ready" | "error";
|
|
71
|
-
data?: ai.JSONValue[];
|
|
72
|
-
setData: (
|
|
73
|
-
data:
|
|
74
|
-
| ai.JSONValue[]
|
|
75
|
-
| undefined
|
|
76
|
-
| ((data: ai.JSONValue[] | undefined) => ai.JSONValue[] | undefined)
|
|
77
|
-
) => void;
|
|
78
|
-
id: string;
|
|
79
|
-
addToolResult: ({
|
|
80
|
-
toolCallId,
|
|
81
|
-
result,
|
|
82
|
-
}: {
|
|
83
|
-
toolCallId: string;
|
|
84
|
-
result: any;
|
|
85
|
-
}) => void;
|
|
86
96
|
};
|
|
87
97
|
|
|
88
|
-
export { useAgentChat };
|
|
98
|
+
export { type AITool, detectToolsRequiringConfirmation, useAgentChat };
|
package/dist/ai-react.js
CHANGED
|
@@ -1,11 +1,28 @@
|
|
|
1
|
-
import "./chunk-
|
|
1
|
+
import "./chunk-AVYJQSLW.js";
|
|
2
2
|
|
|
3
3
|
// src/ai-react.tsx
|
|
4
4
|
import { useChat } from "@ai-sdk/react";
|
|
5
|
-
import {
|
|
5
|
+
import { getToolName, isToolUIPart } from "ai";
|
|
6
|
+
import { DefaultChatTransport } from "ai";
|
|
7
|
+
import { nanoid } from "nanoid";
|
|
8
|
+
import { use, useEffect, useRef } from "react";
|
|
6
9
|
var requestCache = /* @__PURE__ */ new Map();
|
|
10
|
+
function detectToolsRequiringConfirmation(tools) {
|
|
11
|
+
if (!tools) return [];
|
|
12
|
+
return Object.entries(tools).filter(([_name, tool]) => !tool.execute).map(([name]) => name);
|
|
13
|
+
}
|
|
7
14
|
function useAgentChat(options) {
|
|
8
|
-
const {
|
|
15
|
+
const {
|
|
16
|
+
agent,
|
|
17
|
+
getInitialMessages,
|
|
18
|
+
messages: optionsInitialMessages,
|
|
19
|
+
experimental_automaticToolResolution,
|
|
20
|
+
tools,
|
|
21
|
+
toolsRequiringConfirmation: manualToolsRequiringConfirmation,
|
|
22
|
+
autoSendAfterAllConfirmationsResolved = true,
|
|
23
|
+
...rest
|
|
24
|
+
} = options;
|
|
25
|
+
const toolsRequiringConfirmation = manualToolsRequiringConfirmation ?? detectToolsRequiringConfirmation(tools);
|
|
9
26
|
const agentUrl = new URL(
|
|
10
27
|
`${// @ts-expect-error we're using a protected _url property that includes query params
|
|
11
28
|
(agent._url || agent._pkurl)?.replace("ws://", "http://").replace("wss://", "https://")}`
|
|
@@ -18,10 +35,25 @@ function useAgentChat(options) {
|
|
|
18
35
|
const getMessagesUrl = new URL(url);
|
|
19
36
|
getMessagesUrl.pathname += "/get-messages";
|
|
20
37
|
const response = await fetch(getMessagesUrl.toString(), {
|
|
21
|
-
|
|
22
|
-
|
|
38
|
+
credentials: options.credentials,
|
|
39
|
+
headers: options.headers
|
|
23
40
|
});
|
|
24
|
-
|
|
41
|
+
if (!response.ok) {
|
|
42
|
+
console.warn(
|
|
43
|
+
`Failed to fetch initial messages: ${response.status} ${response.statusText}`
|
|
44
|
+
);
|
|
45
|
+
return [];
|
|
46
|
+
}
|
|
47
|
+
const text = await response.text();
|
|
48
|
+
if (!text.trim()) {
|
|
49
|
+
return [];
|
|
50
|
+
}
|
|
51
|
+
try {
|
|
52
|
+
return JSON.parse(text);
|
|
53
|
+
} catch (error) {
|
|
54
|
+
console.warn("Failed to parse initial messages JSON:", error);
|
|
55
|
+
return [];
|
|
56
|
+
}
|
|
25
57
|
}
|
|
26
58
|
const getInitialMessagesFetch = getInitialMessages || defaultGetInitialMessagesFetch;
|
|
27
59
|
function doGetInitialMessages(getInitialMessagesOptions) {
|
|
@@ -32,18 +64,23 @@ function useAgentChat(options) {
|
|
|
32
64
|
requestCache.set(agentUrlString, promise);
|
|
33
65
|
return promise;
|
|
34
66
|
}
|
|
35
|
-
const
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
) : rest.initialMessages;
|
|
67
|
+
const initialMessagesPromise = getInitialMessages === null ? null : doGetInitialMessages({
|
|
68
|
+
agent: agent.agent,
|
|
69
|
+
name: agent.name,
|
|
70
|
+
url: agentUrlString
|
|
71
|
+
});
|
|
72
|
+
const initialMessages = initialMessagesPromise ? use(initialMessagesPromise) : optionsInitialMessages ?? [];
|
|
42
73
|
useEffect(() => {
|
|
74
|
+
if (!initialMessagesPromise) {
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
requestCache.set(agentUrlString, initialMessagesPromise);
|
|
43
78
|
return () => {
|
|
44
|
-
requestCache.
|
|
79
|
+
if (requestCache.get(agentUrlString) === initialMessagesPromise) {
|
|
80
|
+
requestCache.delete(agentUrlString);
|
|
81
|
+
}
|
|
45
82
|
};
|
|
46
|
-
}, [agentUrlString]);
|
|
83
|
+
}, [agentUrlString, initialMessagesPromise]);
|
|
47
84
|
async function aiFetch(request, options2 = {}) {
|
|
48
85
|
const {
|
|
49
86
|
method,
|
|
@@ -58,12 +95,22 @@ function useAgentChat(options) {
|
|
|
58
95
|
referrer,
|
|
59
96
|
referrerPolicy,
|
|
60
97
|
window
|
|
61
|
-
// dispatcher, duplex
|
|
62
98
|
} = options2;
|
|
63
|
-
const id =
|
|
99
|
+
const id = nanoid(8);
|
|
64
100
|
const abortController = new AbortController();
|
|
101
|
+
let controller;
|
|
102
|
+
let isToolCallInProgress = false;
|
|
65
103
|
signal?.addEventListener("abort", () => {
|
|
104
|
+
agent.send(
|
|
105
|
+
JSON.stringify({
|
|
106
|
+
id,
|
|
107
|
+
type: "cf_agent_chat_request_cancel" /* CF_AGENT_CHAT_REQUEST_CANCEL */
|
|
108
|
+
})
|
|
109
|
+
);
|
|
66
110
|
abortController.abort();
|
|
111
|
+
if (!isToolCallInProgress) {
|
|
112
|
+
controller.close();
|
|
113
|
+
}
|
|
67
114
|
});
|
|
68
115
|
agent.addEventListener(
|
|
69
116
|
"message",
|
|
@@ -71,22 +118,35 @@ function useAgentChat(options) {
|
|
|
71
118
|
let data;
|
|
72
119
|
try {
|
|
73
120
|
data = JSON.parse(event.data);
|
|
74
|
-
} catch (
|
|
121
|
+
} catch (_error) {
|
|
75
122
|
return;
|
|
76
123
|
}
|
|
77
|
-
if (data.type === "cf_agent_use_chat_response") {
|
|
124
|
+
if (data.type === "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */) {
|
|
78
125
|
if (data.id === id) {
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
controller.close();
|
|
126
|
+
if (data.error) {
|
|
127
|
+
controller.error(new Error(data.body));
|
|
82
128
|
abortController.abort();
|
|
129
|
+
} else {
|
|
130
|
+
if (data.body?.trim()) {
|
|
131
|
+
if (data.body.includes('"tool_calls"')) {
|
|
132
|
+
isToolCallInProgress = true;
|
|
133
|
+
}
|
|
134
|
+
controller.enqueue(
|
|
135
|
+
new TextEncoder().encode(`data: ${data.body}
|
|
136
|
+
|
|
137
|
+
`)
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
if (data.done && !isToolCallInProgress) {
|
|
141
|
+
controller.close();
|
|
142
|
+
abortController.abort();
|
|
143
|
+
}
|
|
83
144
|
}
|
|
84
145
|
}
|
|
85
146
|
}
|
|
86
147
|
},
|
|
87
148
|
{ signal: abortController.signal }
|
|
88
149
|
);
|
|
89
|
-
let controller;
|
|
90
150
|
const stream = new ReadableStream({
|
|
91
151
|
start(c) {
|
|
92
152
|
controller = c;
|
|
@@ -94,60 +154,136 @@ function useAgentChat(options) {
|
|
|
94
154
|
});
|
|
95
155
|
agent.send(
|
|
96
156
|
JSON.stringify({
|
|
97
|
-
type: "cf_agent_use_chat_request",
|
|
98
157
|
id,
|
|
99
|
-
url: request.toString(),
|
|
100
158
|
init: {
|
|
101
|
-
method,
|
|
102
|
-
keepalive,
|
|
103
|
-
headers,
|
|
104
159
|
body,
|
|
105
|
-
redirect,
|
|
106
|
-
integrity,
|
|
107
160
|
credentials,
|
|
161
|
+
headers,
|
|
162
|
+
integrity,
|
|
163
|
+
keepalive,
|
|
164
|
+
method,
|
|
108
165
|
mode,
|
|
166
|
+
redirect,
|
|
109
167
|
referrer,
|
|
110
168
|
referrerPolicy,
|
|
111
169
|
window
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
170
|
+
},
|
|
171
|
+
type: "cf_agent_use_chat_request" /* CF_AGENT_USE_CHAT_REQUEST */,
|
|
172
|
+
url: request.toString()
|
|
115
173
|
})
|
|
116
174
|
);
|
|
117
175
|
return new Response(stream);
|
|
118
176
|
}
|
|
177
|
+
const customTransport = {
|
|
178
|
+
sendMessages: async (options2) => {
|
|
179
|
+
const transport = new DefaultChatTransport({
|
|
180
|
+
api: agentUrlString,
|
|
181
|
+
fetch: aiFetch
|
|
182
|
+
});
|
|
183
|
+
return transport.sendMessages(options2);
|
|
184
|
+
},
|
|
185
|
+
reconnectToStream: async (options2) => {
|
|
186
|
+
const transport = new DefaultChatTransport({
|
|
187
|
+
api: agentUrlString,
|
|
188
|
+
fetch: aiFetch
|
|
189
|
+
});
|
|
190
|
+
return transport.reconnectToStream(options2);
|
|
191
|
+
}
|
|
192
|
+
};
|
|
119
193
|
const useChatHelpers = useChat({
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
...rest
|
|
194
|
+
...rest,
|
|
195
|
+
messages: initialMessages,
|
|
196
|
+
transport: customTransport
|
|
124
197
|
});
|
|
198
|
+
const processedToolCalls = useRef(/* @__PURE__ */ new Set());
|
|
199
|
+
const lastMessage = useChatHelpers.messages[useChatHelpers.messages.length - 1];
|
|
200
|
+
const pendingConfirmations = (() => {
|
|
201
|
+
if (!lastMessage || lastMessage.role !== "assistant") {
|
|
202
|
+
return { messageId: void 0, toolCallIds: /* @__PURE__ */ new Set() };
|
|
203
|
+
}
|
|
204
|
+
const pendingIds = /* @__PURE__ */ new Set();
|
|
205
|
+
for (const part of lastMessage.parts ?? []) {
|
|
206
|
+
if (isToolUIPart(part) && part.state === "input-available" && toolsRequiringConfirmation.includes(getToolName(part))) {
|
|
207
|
+
pendingIds.add(part.toolCallId);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
return { messageId: lastMessage.id, toolCallIds: pendingIds };
|
|
211
|
+
})();
|
|
212
|
+
const pendingConfirmationsRef = useRef(pendingConfirmations);
|
|
213
|
+
pendingConfirmationsRef.current = pendingConfirmations;
|
|
214
|
+
useEffect(() => {
|
|
215
|
+
if (!experimental_automaticToolResolution) {
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
const lastMessage2 = useChatHelpers.messages[useChatHelpers.messages.length - 1];
|
|
219
|
+
if (!lastMessage2 || lastMessage2.role !== "assistant") {
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
const toolCalls = lastMessage2.parts.filter(
|
|
223
|
+
(part) => isToolUIPart(part) && part.state === "input-available" && !processedToolCalls.current.has(part.toolCallId)
|
|
224
|
+
);
|
|
225
|
+
if (toolCalls.length > 0) {
|
|
226
|
+
(async () => {
|
|
227
|
+
const toolCallsToResolve = toolCalls.filter(
|
|
228
|
+
(part) => isToolUIPart(part) && !toolsRequiringConfirmation.includes(getToolName(part)) && tools?.[getToolName(part)]?.execute
|
|
229
|
+
// Only execute if client has execute function
|
|
230
|
+
);
|
|
231
|
+
if (toolCallsToResolve.length > 0) {
|
|
232
|
+
for (const part of toolCallsToResolve) {
|
|
233
|
+
if (isToolUIPart(part)) {
|
|
234
|
+
processedToolCalls.current.add(part.toolCallId);
|
|
235
|
+
let toolOutput = null;
|
|
236
|
+
const toolName = getToolName(part);
|
|
237
|
+
const tool = tools?.[toolName];
|
|
238
|
+
if (tool?.execute && part.input) {
|
|
239
|
+
try {
|
|
240
|
+
toolOutput = await tool.execute(part.input);
|
|
241
|
+
} catch (error) {
|
|
242
|
+
toolOutput = `Error executing tool: ${error instanceof Error ? error.message : String(error)}`;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
await useChatHelpers.addToolResult({
|
|
246
|
+
toolCallId: part.toolCallId,
|
|
247
|
+
tool: toolName,
|
|
248
|
+
output: toolOutput
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
if (pendingConfirmationsRef.current.toolCallIds.size === 0) {
|
|
253
|
+
useChatHelpers.sendMessage();
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
})();
|
|
257
|
+
}
|
|
258
|
+
}, [
|
|
259
|
+
useChatHelpers.messages,
|
|
260
|
+
experimental_automaticToolResolution,
|
|
261
|
+
useChatHelpers.addToolResult,
|
|
262
|
+
useChatHelpers.sendMessage,
|
|
263
|
+
toolsRequiringConfirmation
|
|
264
|
+
]);
|
|
125
265
|
useEffect(() => {
|
|
126
266
|
function onClearHistory(event) {
|
|
127
|
-
if (typeof event.data !== "string")
|
|
128
|
-
return;
|
|
129
|
-
}
|
|
267
|
+
if (typeof event.data !== "string") return;
|
|
130
268
|
let data;
|
|
131
269
|
try {
|
|
132
270
|
data = JSON.parse(event.data);
|
|
133
|
-
} catch (
|
|
271
|
+
} catch (_error) {
|
|
134
272
|
return;
|
|
135
273
|
}
|
|
136
|
-
if (data.type === "cf_agent_chat_clear") {
|
|
274
|
+
if (data.type === "cf_agent_chat_clear" /* CF_AGENT_CHAT_CLEAR */) {
|
|
137
275
|
useChatHelpers.setMessages([]);
|
|
138
276
|
}
|
|
139
277
|
}
|
|
140
278
|
function onMessages(event) {
|
|
141
|
-
if (typeof event.data !== "string")
|
|
142
|
-
return;
|
|
143
|
-
}
|
|
279
|
+
if (typeof event.data !== "string") return;
|
|
144
280
|
let data;
|
|
145
281
|
try {
|
|
146
282
|
data = JSON.parse(event.data);
|
|
147
|
-
} catch (
|
|
283
|
+
} catch (_error) {
|
|
148
284
|
return;
|
|
149
285
|
}
|
|
150
|
-
if (data.type === "cf_agent_chat_messages") {
|
|
286
|
+
if (data.type === "cf_agent_chat_messages" /* CF_AGENT_CHAT_MESSAGES */) {
|
|
151
287
|
useChatHelpers.setMessages(data.messages);
|
|
152
288
|
}
|
|
153
289
|
}
|
|
@@ -157,40 +293,51 @@ function useAgentChat(options) {
|
|
|
157
293
|
agent.removeEventListener("message", onClearHistory);
|
|
158
294
|
agent.removeEventListener("message", onMessages);
|
|
159
295
|
};
|
|
160
|
-
}, [
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
useChatHelpers.
|
|
164
|
-
|
|
296
|
+
}, [agent, useChatHelpers.setMessages]);
|
|
297
|
+
const addToolResultAndSendMessage = async (args) => {
|
|
298
|
+
const { toolCallId } = args;
|
|
299
|
+
await useChatHelpers.addToolResult(args);
|
|
300
|
+
if (!autoSendAfterAllConfirmationsResolved) {
|
|
301
|
+
useChatHelpers.sendMessage();
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
const pending = pendingConfirmationsRef.current?.toolCallIds;
|
|
305
|
+
if (!pending) {
|
|
306
|
+
useChatHelpers.sendMessage();
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
const wasLast = pending.size === 1 && pending.has(toolCallId);
|
|
310
|
+
if (pending.has(toolCallId)) {
|
|
311
|
+
pending.delete(toolCallId);
|
|
312
|
+
}
|
|
313
|
+
if (wasLast || pending.size === 0) {
|
|
314
|
+
useChatHelpers.sendMessage();
|
|
315
|
+
}
|
|
316
|
+
};
|
|
165
317
|
return {
|
|
166
318
|
...useChatHelpers,
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
*/
|
|
171
|
-
setMessages: (messages) => {
|
|
172
|
-
useChatHelpers.setMessages(messages);
|
|
319
|
+
addToolResult: addToolResultAndSendMessage,
|
|
320
|
+
clearHistory: () => {
|
|
321
|
+
useChatHelpers.setMessages([]);
|
|
173
322
|
agent.send(
|
|
174
323
|
JSON.stringify({
|
|
175
|
-
type: "
|
|
176
|
-
messages
|
|
324
|
+
type: "cf_agent_chat_clear" /* CF_AGENT_CHAT_CLEAR */
|
|
177
325
|
})
|
|
178
326
|
);
|
|
179
327
|
},
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
*/
|
|
183
|
-
clearHistory: () => {
|
|
184
|
-
useChatHelpers.setMessages([]);
|
|
328
|
+
setMessages: (messages) => {
|
|
329
|
+
useChatHelpers.setMessages(messages);
|
|
185
330
|
agent.send(
|
|
186
331
|
JSON.stringify({
|
|
187
|
-
|
|
332
|
+
messages: Array.isArray(messages) ? messages : [],
|
|
333
|
+
type: "cf_agent_chat_messages" /* CF_AGENT_CHAT_MESSAGES */
|
|
188
334
|
})
|
|
189
335
|
);
|
|
190
336
|
}
|
|
191
337
|
};
|
|
192
338
|
}
|
|
193
339
|
export {
|
|
340
|
+
detectToolsRequiringConfirmation,
|
|
194
341
|
useAgentChat
|
|
195
342
|
};
|
|
196
343
|
//# sourceMappingURL=ai-react.js.map
|
package/dist/ai-react.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/ai-react.tsx"],"sourcesContent":["import { useChat } from \"@ai-sdk/react\";\nimport type { Message } from \"ai\";\nimport type { useAgent } from \"./react\";\nimport { useEffect, use } from \"react\";\nimport type { OutgoingMessage } from \"./ai-types\";\n\ntype GetInitialMessagesOptions = {\n agent: string;\n name: string;\n url: string;\n};\n\n/**\n * Options for the useAgentChat hook\n */\ntype UseAgentChatOptions<State> = Omit<\n Parameters<typeof useChat>[0] & {\n /** Agent connection from useAgent */\n agent: ReturnType<typeof useAgent<State>>;\n getInitialMessages?:\n | undefined\n | null\n // | (() => Message[])\n | ((options: GetInitialMessagesOptions) => Promise<Message[]>);\n },\n \"fetch\"\n>;\n\n// TODO: clear cache when the agent is unmounted?\nconst requestCache = new Map<string, Promise<Message[]>>();\n\n/**\n * React hook for building AI chat interfaces using an Agent\n * @param options Chat options including the agent connection\n * @returns Chat interface controls and state with added clearHistory method\n */\nexport function useAgentChat<State = unknown>(\n options: UseAgentChatOptions<State>\n) {\n const { agent, getInitialMessages, ...rest } = options;\n\n const agentUrl = new URL(\n `${// @ts-expect-error we're using a protected _url property that includes query params\n ((agent._url as string | null) || agent._pkurl)\n ?.replace(\"ws://\", \"http://\")\n .replace(\"wss://\", \"https://\")}`\n );\n\n // delete the _pk query param\n agentUrl.searchParams.delete(\"_pk\");\n const agentUrlString = agentUrl.toString();\n\n async function defaultGetInitialMessagesFetch({\n url,\n }: GetInitialMessagesOptions) {\n const getMessagesUrl = new URL(url);\n getMessagesUrl.pathname += \"/get-messages\";\n const response = await fetch(getMessagesUrl.toString(), {\n headers: options.headers,\n credentials: options.credentials,\n });\n return response.json<Message[]>();\n }\n\n const getInitialMessagesFetch =\n getInitialMessages || defaultGetInitialMessagesFetch;\n\n function doGetInitialMessages(\n getInitialMessagesOptions: GetInitialMessagesOptions\n ) {\n if (requestCache.has(agentUrlString)) {\n return requestCache.get(agentUrlString)!;\n }\n const promise = getInitialMessagesFetch(getInitialMessagesOptions);\n requestCache.set(agentUrlString, promise);\n return promise;\n }\n\n const initialMessages =\n getInitialMessages !== null\n ? use(\n doGetInitialMessages({\n agent: agent.agent,\n name: agent.name,\n url: agentUrlString,\n })\n )\n : rest.initialMessages;\n\n useEffect(() => {\n return () => {\n requestCache.delete(agentUrlString);\n };\n }, [agentUrlString]);\n\n async function aiFetch(\n request: RequestInfo | URL,\n options: RequestInit = {}\n ) {\n // we're going to use a websocket to do the actual \"fetching\"\n // but still satisfy the type signature of the fetch function\n // so we'll return a promise that resolves to a response\n\n const {\n method,\n keepalive,\n headers,\n body,\n redirect,\n integrity,\n signal,\n credentials,\n mode,\n referrer,\n referrerPolicy,\n window,\n // dispatcher, duplex\n } = options;\n const id = crypto.randomUUID();\n const abortController = new AbortController();\n\n signal?.addEventListener(\"abort\", () => {\n abortController.abort();\n });\n\n agent.addEventListener(\n \"message\",\n (event) => {\n let data: OutgoingMessage;\n try {\n data = JSON.parse(event.data) as OutgoingMessage;\n } catch (error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (data.type === \"cf_agent_use_chat_response\") {\n if (data.id === id) {\n controller.enqueue(new TextEncoder().encode(data.body));\n if (data.done) {\n controller.close();\n abortController.abort();\n }\n }\n }\n },\n { signal: abortController.signal }\n );\n\n let controller: ReadableStreamDefaultController;\n\n const stream = new ReadableStream({\n start(c) {\n controller = c;\n },\n });\n\n agent.send(\n JSON.stringify({\n type: \"cf_agent_use_chat_request\",\n id,\n url: request.toString(),\n init: {\n method,\n keepalive,\n headers,\n body,\n redirect,\n integrity,\n credentials,\n mode,\n referrer,\n referrerPolicy,\n window,\n // dispatcher,\n // duplex\n },\n })\n );\n\n return new Response(stream);\n }\n const useChatHelpers = useChat({\n initialMessages,\n sendExtraMessageFields: true,\n fetch: aiFetch,\n ...rest,\n });\n\n useEffect(() => {\n function onClearHistory(event: MessageEvent) {\n if (typeof event.data !== \"string\") {\n return;\n }\n let data: OutgoingMessage;\n try {\n data = JSON.parse(event.data) as OutgoingMessage;\n } catch (error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (data.type === \"cf_agent_chat_clear\") {\n useChatHelpers.setMessages([]);\n }\n }\n\n function onMessages(event: MessageEvent) {\n if (typeof event.data !== \"string\") {\n return;\n }\n let data: OutgoingMessage;\n try {\n data = JSON.parse(event.data) as OutgoingMessage;\n } catch (error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (data.type === \"cf_agent_chat_messages\") {\n useChatHelpers.setMessages(data.messages);\n }\n }\n\n agent.addEventListener(\"message\", onClearHistory);\n agent.addEventListener(\"message\", onMessages);\n\n return () => {\n agent.removeEventListener(\"message\", onClearHistory);\n agent.removeEventListener(\"message\", onMessages);\n };\n }, [\n agent.addEventListener,\n agent.removeEventListener,\n useChatHelpers.setMessages,\n ]);\n\n return {\n ...useChatHelpers,\n /**\n * Set the chat messages and synchronize with the Agent\n * @param messages New messages to set\n */\n setMessages: (messages: Message[]) => {\n useChatHelpers.setMessages(messages);\n agent.send(\n JSON.stringify({\n type: \"cf_agent_chat_messages\",\n messages,\n })\n );\n },\n /**\n * Clear chat history on both client and Agent\n */\n clearHistory: () => {\n useChatHelpers.setMessages([]);\n agent.send(\n JSON.stringify({\n type: \"cf_agent_chat_clear\",\n })\n );\n },\n };\n}\n"],"mappings":";;;AAAA,SAAS,eAAe;AAGxB,SAAS,WAAW,WAAW;AA0B/B,IAAM,eAAe,oBAAI,IAAgC;AAOlD,SAAS,aACd,SACA;AACA,QAAM,EAAE,OAAO,oBAAoB,GAAG,KAAK,IAAI;AAE/C,QAAM,WAAW,IAAI;AAAA,IACnB;AAAA,KACE,MAAM,QAA0B,MAAM,SACpC,QAAQ,SAAS,SAAS,EAC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A,aAAS,WAAW,OAAqB;AACvC,UAAI,OAAO,MAAM,SAAS,UAAU;AAClC;AAAA,MACF;AACA,UAAI;AACJ,UAAI;AACF,eAAO,KAAK,MAAM,MAAM,IAAI;AAAA,MAC9B,SAAS,OAAO;AAGd;AAAA,MACF;AACA,UAAI,KAAK,SAAS,0BAA0B;AAC1C,uBAAe,YAAY,KAAK,QAAQ;AAAA,MAC1C;AAAA,IACF;AAEA,UAAM,iBAAiB,WAAW,cAAc;AAChD,UAAM,iBAAiB,WAAW,UAAU;AAE5C,WAAO,MAAM;AACX,YAAM,oBAAoB,WAAW,cAAc;AACnD,YAAM,oBAAoB,WAAW,UAAU;AAAA,IACjD;AAAA,EACF,GAAG;AAAA,IACD,MAAM;AAAA,IACN,MAAM;AAAA,IACN,eAAe;AAAA,EACjB,CAAC;AAED,SAAO;AAAA,IACL,GAAG;AAAA;AAAA;AAAA;AAAA;AAAA,IAKH,aAAa,CAAC,aAAwB;AACpC,qBAAe,YAAY,QAAQ;AACnC,YAAM;AAAA,QACJ,KAAK,UAAU;AAAA,UACb,MAAM;AAAA,UACN;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF;AAAA;AAAA;AAAA;AAAA,IAIA,cAAc,MAAM;AAClB,qBAAe,YAAY,CAAC,CAAC;AAC7B,YAAM;AAAA,QACJ,KAAK,UAAU;AAAA,UACb,MAAM;AAAA,QACR,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF;","names":["options"]}
|
|
1
|
+
{"version":3,"sources":["../src/ai-react.tsx"],"sourcesContent":["import { useChat, type UseChatOptions } from \"@ai-sdk/react\";\nimport { getToolName, isToolUIPart } from \"ai\";\nimport type {\n ChatInit,\n ChatTransport,\n UIMessage as Message,\n UIMessage\n} from \"ai\";\nimport { DefaultChatTransport } from \"ai\";\nimport { nanoid } from \"nanoid\";\nimport { use, useEffect, useRef } from \"react\";\nimport type { OutgoingMessage } from \"./ai-types\";\nimport { MessageType } from \"./ai-types\";\nimport type { useAgent } from \"./react\";\n\nexport type AITool<Input = unknown, Output = unknown> = {\n description?: string;\n inputSchema?: unknown;\n execute?: (input: Input) => Output | Promise<Output>;\n};\n\ntype GetInitialMessagesOptions = {\n agent: string;\n name: string;\n url: string;\n};\n\n// v5 useChat parameters\ntype UseChatParams<M extends UIMessage = UIMessage> = ChatInit<M> &\n UseChatOptions<M>;\n\n/**\n * Options for the useAgentChat hook\n */\ntype UseAgentChatOptions<\n State,\n ChatMessage extends UIMessage = UIMessage\n> = Omit<UseChatParams<ChatMessage>, \"fetch\"> & {\n /** Agent connection from useAgent */\n agent: ReturnType<typeof useAgent<State>>;\n getInitialMessages?:\n | undefined\n | null\n | ((options: GetInitialMessagesOptions) => Promise<ChatMessage[]>);\n /** Request credentials */\n credentials?: RequestCredentials;\n /** Request headers */\n headers?: HeadersInit;\n /**\n * @description Whether to automatically resolve tool calls that do not require human interaction.\n * @experimental\n */\n experimental_automaticToolResolution?: boolean;\n /**\n * @description Tools object for automatic detection of confirmation requirements.\n * Tools without execute function will require confirmation.\n */\n tools?: Record<string, AITool<unknown, unknown>>;\n /**\n * @description Manual override for tools requiring confirmation.\n * If not provided, will auto-detect from tools object.\n */\n toolsRequiringConfirmation?: string[];\n /**\n * When true (default), automatically sends the next message only after\n * all pending confirmation-required tool calls have been resolved.\n * @default true\n */\n autoSendAfterAllConfirmationsResolved?: boolean;\n};\n\nconst requestCache = new Map<string, Promise<Message[]>>();\n\n/**\n * React hook for building AI chat interfaces using an Agent\n * @param options Chat options including the agent connection\n * @returns Chat interface controls and state with added clearHistory method\n */\n/**\n * Automatically detects which tools require confirmation based on their configuration.\n * Tools require confirmation if they have no execute function AND are not server-executed.\n * @param tools - Record of tool name to tool definition\n * @returns Array of tool names that require confirmation\n */\nexport function detectToolsRequiringConfirmation(\n tools?: Record<string, AITool<unknown, unknown>>\n): string[] {\n if (!tools) return [];\n\n return Object.entries(tools)\n .filter(([_name, tool]) => !tool.execute)\n .map(([name]) => name);\n}\n\nexport function useAgentChat<\n State = unknown,\n ChatMessage extends UIMessage = UIMessage\n>(\n options: UseAgentChatOptions<State, ChatMessage>\n): ReturnType<typeof useChat<ChatMessage>> & {\n clearHistory: () => void;\n} {\n const {\n agent,\n getInitialMessages,\n messages: optionsInitialMessages,\n experimental_automaticToolResolution,\n tools,\n toolsRequiringConfirmation: manualToolsRequiringConfirmation,\n autoSendAfterAllConfirmationsResolved = true,\n ...rest\n } = options;\n\n // Auto-detect tools requiring confirmation, or use manual override\n const toolsRequiringConfirmation =\n manualToolsRequiringConfirmation ?? detectToolsRequiringConfirmation(tools);\n\n const agentUrl = new URL(\n `${// @ts-expect-error we're using a protected _url property that includes query params\n ((agent._url as string | null) || agent._pkurl)\n ?.replace(\"ws://\", \"http://\")\n .replace(\"wss://\", \"https://\")}`\n );\n\n agentUrl.searchParams.delete(\"_pk\");\n const agentUrlString = agentUrl.toString();\n\n async function defaultGetInitialMessagesFetch({\n url\n }: GetInitialMessagesOptions) {\n const getMessagesUrl = new URL(url);\n getMessagesUrl.pathname += \"/get-messages\";\n const response = await fetch(getMessagesUrl.toString(), {\n credentials: options.credentials,\n headers: options.headers\n });\n\n if (!response.ok) {\n console.warn(\n `Failed to fetch initial messages: ${response.status} ${response.statusText}`\n );\n return [];\n }\n\n const text = await response.text();\n if (!text.trim()) {\n return [];\n }\n\n try {\n return JSON.parse(text) as ChatMessage[];\n } catch (error) {\n console.warn(\"Failed to parse initial messages JSON:\", error);\n return [];\n }\n }\n\n const getInitialMessagesFetch =\n getInitialMessages || defaultGetInitialMessagesFetch;\n\n function doGetInitialMessages(\n getInitialMessagesOptions: GetInitialMessagesOptions\n ) {\n if (requestCache.has(agentUrlString)) {\n return requestCache.get(agentUrlString)! as Promise<ChatMessage[]>;\n }\n const promise = getInitialMessagesFetch(getInitialMessagesOptions);\n requestCache.set(agentUrlString, promise);\n return promise;\n }\n\n const initialMessagesPromise =\n getInitialMessages === null\n ? null\n : doGetInitialMessages({\n agent: agent.agent,\n name: agent.name,\n url: agentUrlString\n });\n const initialMessages = initialMessagesPromise\n ? use(initialMessagesPromise)\n : (optionsInitialMessages ?? []);\n\n useEffect(() => {\n if (!initialMessagesPromise) {\n return;\n }\n requestCache.set(agentUrlString, initialMessagesPromise!);\n return () => {\n if (requestCache.get(agentUrlString) === initialMessagesPromise) {\n requestCache.delete(agentUrlString);\n }\n };\n }, [agentUrlString, initialMessagesPromise]);\n\n async function aiFetch(\n request: RequestInfo | URL,\n options: RequestInit = {}\n ) {\n const {\n method,\n keepalive,\n headers,\n body,\n redirect,\n integrity,\n signal,\n credentials,\n mode,\n referrer,\n referrerPolicy,\n window\n } = options;\n const id = nanoid(8);\n const abortController = new AbortController();\n let controller: ReadableStreamDefaultController;\n let isToolCallInProgress = false;\n\n signal?.addEventListener(\"abort\", () => {\n agent.send(\n JSON.stringify({\n id,\n type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL\n })\n );\n\n // NOTE - If we wanted to, we could preserve the \"interrupted\" message here, with the code below\n // However, I think it might be the responsibility of the library user to implement that behavior manually?\n // Reasoning: This code could be subject to collisions, as it \"force saves\" the messages we have locally\n //\n // agent.send(JSON.stringify({\n // type: MessageType.CF_AGENT_CHAT_MESSAGES,\n // messages: ... /* some way of getting current messages ref? */\n // }))\n\n abortController.abort();\n // Make sure to also close the stream (cf. https://github.com/cloudflare/agents-starter/issues/69)\n if (!isToolCallInProgress) {\n controller.close();\n }\n });\n\n agent.addEventListener(\n \"message\",\n (event) => {\n let data: OutgoingMessage<ChatMessage>;\n try {\n data = JSON.parse(event.data) as OutgoingMessage<ChatMessage>;\n } catch (_error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE) {\n if (data.id === id) {\n if (data.error) {\n controller.error(new Error(data.body));\n abortController.abort();\n } else {\n // Only enqueue non-empty data to prevent JSON parsing errors\n if (data.body?.trim()) {\n if (data.body.includes('\"tool_calls\"')) {\n isToolCallInProgress = true;\n }\n controller.enqueue(\n new TextEncoder().encode(`data: ${data.body}\\n\\n`)\n );\n }\n if (data.done && !isToolCallInProgress) {\n controller.close();\n abortController.abort();\n }\n }\n }\n }\n },\n { signal: abortController.signal }\n );\n\n const stream = new ReadableStream({\n start(c) {\n controller = c;\n }\n });\n\n agent.send(\n JSON.stringify({\n id,\n init: {\n body,\n credentials,\n headers,\n integrity,\n keepalive,\n method,\n mode,\n redirect,\n referrer,\n referrerPolicy,\n window\n },\n type: MessageType.CF_AGENT_USE_CHAT_REQUEST,\n url: request.toString()\n })\n );\n\n return new Response(stream);\n }\n\n const customTransport: ChatTransport<ChatMessage> = {\n sendMessages: async (\n options: Parameters<typeof DefaultChatTransport.prototype.sendMessages>[0]\n ) => {\n const transport = new DefaultChatTransport<ChatMessage>({\n api: agentUrlString,\n fetch: aiFetch\n });\n return transport.sendMessages(options);\n },\n reconnectToStream: async (\n options: Parameters<\n typeof DefaultChatTransport.prototype.reconnectToStream\n >[0]\n ) => {\n const transport = new DefaultChatTransport<ChatMessage>({\n api: agentUrlString,\n fetch: aiFetch\n });\n return transport.reconnectToStream(options);\n }\n };\n\n const useChatHelpers = useChat<ChatMessage>({\n ...rest,\n messages: initialMessages,\n transport: customTransport\n });\n\n const processedToolCalls = useRef(new Set<string>());\n\n // Calculate pending confirmations for the latest assistant message\n const lastMessage =\n useChatHelpers.messages[useChatHelpers.messages.length - 1];\n\n const pendingConfirmations = (() => {\n if (!lastMessage || lastMessage.role !== \"assistant\") {\n return { messageId: undefined, toolCallIds: new Set<string>() };\n }\n\n const pendingIds = new Set<string>();\n for (const part of lastMessage.parts ?? []) {\n if (\n isToolUIPart(part) &&\n part.state === \"input-available\" &&\n toolsRequiringConfirmation.includes(getToolName(part))\n ) {\n pendingIds.add(part.toolCallId);\n }\n }\n return { messageId: lastMessage.id, toolCallIds: pendingIds };\n })();\n\n const pendingConfirmationsRef = useRef(pendingConfirmations);\n pendingConfirmationsRef.current = pendingConfirmations;\n\n // tools can be a different object everytime it's called,\n // which might lead to this effect being called multiple times with different tools objects.\n // we need to fix this, but that's a bigger refactor.\n // biome-ignore lint/correctness/useExhaustiveDependencies: we need to fix this\n useEffect(() => {\n if (!experimental_automaticToolResolution) {\n return;\n }\n\n const lastMessage =\n useChatHelpers.messages[useChatHelpers.messages.length - 1];\n if (!lastMessage || lastMessage.role !== \"assistant\") {\n return;\n }\n\n const toolCalls = lastMessage.parts.filter(\n (part) =>\n isToolUIPart(part) &&\n part.state === \"input-available\" &&\n !processedToolCalls.current.has(part.toolCallId)\n );\n\n if (toolCalls.length > 0) {\n (async () => {\n const toolCallsToResolve = toolCalls.filter(\n (part) =>\n isToolUIPart(part) &&\n !toolsRequiringConfirmation.includes(getToolName(part)) &&\n tools?.[getToolName(part)]?.execute // Only execute if client has execute function\n );\n\n if (toolCallsToResolve.length > 0) {\n for (const part of toolCallsToResolve) {\n if (isToolUIPart(part)) {\n processedToolCalls.current.add(part.toolCallId);\n let toolOutput = null;\n const toolName = getToolName(part);\n const tool = tools?.[toolName];\n\n if (tool?.execute && part.input) {\n try {\n toolOutput = await tool.execute(part.input);\n } catch (error) {\n toolOutput = `Error executing tool: ${error instanceof Error ? error.message : String(error)}`;\n }\n }\n\n await useChatHelpers.addToolResult({\n toolCallId: part.toolCallId,\n tool: toolName,\n output: toolOutput\n });\n }\n }\n // If there are NO pending confirmations for the latest assistant message,\n // we can continue the conversation. Otherwise, wait for the UI to resolve\n // those confirmations; the addToolResult wrapper will send when the last\n // pending confirmation is resolved.\n if (pendingConfirmationsRef.current.toolCallIds.size === 0) {\n useChatHelpers.sendMessage();\n }\n }\n })();\n }\n }, [\n useChatHelpers.messages,\n experimental_automaticToolResolution,\n useChatHelpers.addToolResult,\n useChatHelpers.sendMessage,\n toolsRequiringConfirmation\n ]);\n\n useEffect(() => {\n function onClearHistory(event: MessageEvent) {\n if (typeof event.data !== \"string\") return;\n let data: OutgoingMessage;\n try {\n data = JSON.parse(event.data) as OutgoingMessage;\n } catch (_error) {\n return;\n }\n if (data.type === MessageType.CF_AGENT_CHAT_CLEAR) {\n useChatHelpers.setMessages([]);\n }\n }\n\n function onMessages(event: MessageEvent) {\n if (typeof event.data !== \"string\") return;\n let data: OutgoingMessage<ChatMessage>;\n try {\n data = JSON.parse(event.data) as OutgoingMessage<ChatMessage>;\n } catch (_error) {\n return;\n }\n if (data.type === MessageType.CF_AGENT_CHAT_MESSAGES) {\n useChatHelpers.setMessages(data.messages);\n }\n }\n\n agent.addEventListener(\"message\", onClearHistory);\n agent.addEventListener(\"message\", onMessages);\n\n return () => {\n agent.removeEventListener(\"message\", onClearHistory);\n agent.removeEventListener(\"message\", onMessages);\n };\n }, [agent, useChatHelpers.setMessages]);\n\n // Wrapper that sends only when the last pending confirmation is resolved\n const addToolResultAndSendMessage: typeof useChatHelpers.addToolResult =\n async (args) => {\n const { toolCallId } = args;\n\n await useChatHelpers.addToolResult(args);\n\n if (!autoSendAfterAllConfirmationsResolved) {\n // always send immediately\n useChatHelpers.sendMessage();\n return;\n }\n\n // wait for all confirmations\n const pending = pendingConfirmationsRef.current?.toolCallIds;\n if (!pending) {\n useChatHelpers.sendMessage();\n return;\n }\n\n const wasLast = pending.size === 1 && pending.has(toolCallId);\n if (pending.has(toolCallId)) {\n pending.delete(toolCallId);\n }\n\n if (wasLast || pending.size === 0) {\n useChatHelpers.sendMessage();\n }\n };\n\n return {\n ...useChatHelpers,\n addToolResult: addToolResultAndSendMessage,\n clearHistory: () => {\n useChatHelpers.setMessages([]);\n agent.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_CHAT_CLEAR\n })\n );\n },\n setMessages: (\n messages: Parameters<typeof useChatHelpers.setMessages>[0]\n ) => {\n useChatHelpers.setMessages(messages);\n agent.send(\n JSON.stringify({\n messages: Array.isArray(messages) ? messages : [],\n type: MessageType.CF_AGENT_CHAT_MESSAGES\n })\n );\n }\n };\n}\n"],"mappings":";;;AAAA,SAAS,eAAoC;AAC7C,SAAS,aAAa,oBAAoB;AAO1C,SAAS,4B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