agents 0.0.0-6dc3b6a → 0.0.0-6e0420c

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 (71) hide show
  1. package/README.md +255 -27
  2. package/dist/ai-chat-agent.d.ts +59 -11
  3. package/dist/ai-chat-agent.js +548 -159
  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 -72
  10. package/dist/ai-react.js +260 -185
  11. package/dist/ai-react.js.map +1 -1
  12. package/dist/ai-types-B0GBFDwi.js +20 -0
  13. package/dist/ai-types-B0GBFDwi.js.map +1 -0
  14. package/dist/ai-types-BWW4umHY.d.ts +95 -0
  15. package/dist/ai-types.d.ts +6 -69
  16. package/dist/ai-types.js +3 -1
  17. package/dist/client-C-u-lCFT.d.ts +5311 -0
  18. package/dist/client-CmMi85Sj.d.ts +104 -0
  19. package/dist/client-WbaRgKYN.js +788 -0
  20. package/dist/client-WbaRgKYN.js.map +1 -0
  21. package/dist/client-zS-OCVJA.js +117 -0
  22. package/dist/client-zS-OCVJA.js.map +1 -0
  23. package/dist/client.d.ts +12 -79
  24. package/dist/client.js +3 -137
  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-DWcUTPtX.d.ts +558 -0
  32. package/dist/index-W4JUkafc.d.ts +54 -0
  33. package/dist/index.d.ts +63 -301
  34. package/dist/index.js +7 -22
  35. package/dist/mcp/client.d.ts +4 -0
  36. package/dist/mcp/client.js +3 -0
  37. package/dist/mcp/do-oauth-client-provider.d.ts +2 -0
  38. package/dist/mcp/do-oauth-client-provider.js +3 -0
  39. package/dist/mcp/index.d.ts +75 -0
  40. package/dist/mcp/index.js +847 -0
  41. package/dist/mcp/index.js.map +1 -0
  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 -0
  47. package/dist/observability/index.js +7 -0
  48. package/dist/react-B8BT6PYZ.d.ts +113 -0
  49. package/dist/react.d.ts +10 -39
  50. package/dist/react.js +185 -93
  51. package/dist/react.js.map +1 -1
  52. package/dist/schedule.d.ts +89 -12
  53. package/dist/schedule.js +46 -23
  54. package/dist/schedule.js.map +1 -1
  55. package/dist/serializable-gtr9YMhp.d.ts +34 -0
  56. package/dist/serializable.d.ts +7 -0
  57. package/dist/serializable.js +1 -0
  58. package/dist/src-C9xZ0CrH.js +1179 -0
  59. package/dist/src-C9xZ0CrH.js.map +1 -0
  60. package/package.json +117 -50
  61. package/src/index.ts +1268 -156
  62. package/dist/ai-types.js.map +0 -1
  63. package/dist/chunk-HMLY7DHA.js +0 -16
  64. package/dist/chunk-HMLY7DHA.js.map +0 -1
  65. package/dist/chunk-YMUU7QHV.js +0 -595
  66. package/dist/chunk-YMUU7QHV.js.map +0 -1
  67. package/dist/client.js.map +0 -1
  68. package/dist/index.js.map +0 -1
  69. package/dist/mcp.d.ts +0 -58
  70. package/dist/mcp.js +0 -945
  71. package/dist/mcp.js.map +0 -1
@@ -1,167 +1,556 @@
1
- import {
2
- Agent
3
- } from "./chunk-YMUU7QHV.js";
4
- import {
5
- __privateAdd,
6
- __privateMethod
7
- } from "./chunk-HMLY7DHA.js";
1
+ import { __require } from "./client-WbaRgKYN.js";
2
+ import { MessageType } from "./ai-types-B0GBFDwi.js";
3
+ import "./client-zS-OCVJA.js";
4
+ import "./do-oauth-client-provider-B2jr6UNq.js";
5
+ import { Agent } from "./src-C9xZ0CrH.js";
6
+ import { autoTransformMessages } from "./ai-chat-v5-migration-gdyLiTd8.js";
8
7
 
9
- // src/ai-chat-agent.ts
10
- import { appendResponseMessages } from "ai";
11
- var decoder = new TextDecoder();
12
- var _AIChatAgent_instances, broadcastChatMessage_fn, tryCatch_fn, persistMessages_fn, reply_fn;
8
+ //#region src/ai-chat-agent.ts
9
+ const decoder = new TextDecoder();
10
+ let aiSDK;
11
+ function getAISDK() {
12
+ if (!aiSDK) {
13
+ const { getToolName, isToolUIPart, parsePartialJson } = __require("ai");
14
+ aiSDK = {
15
+ getToolName,
16
+ isToolUIPart,
17
+ parsePartialJson
18
+ };
19
+ }
20
+ return aiSDK;
21
+ }
22
+ /**
23
+ * Extension of Agent with built-in chat capabilities
24
+ * @template Env Environment type containing bindings
25
+ */
13
26
  var AIChatAgent = class extends Agent {
14
- constructor(ctx, env) {
15
- super(ctx, env);
16
- __privateAdd(this, _AIChatAgent_instances);
17
- this.sql`create table if not exists cf_ai_chat_agent_messages (
27
+ constructor(ctx, env) {
28
+ super(ctx, env);
29
+ this.sql`create table if not exists cf_ai_chat_agent_messages (
18
30
  id text primary key,
19
31
  message text not null,
20
32
  created_at datetime default current_timestamp
21
33
  )`;
22
- this.messages = (this.sql`select * from cf_ai_chat_agent_messages` || []).map((row) => {
23
- return JSON.parse(row.message);
24
- });
25
- }
26
- async onMessage(connection, message) {
27
- if (typeof message === "string") {
28
- let data;
29
- try {
30
- data = JSON.parse(message);
31
- } catch (error) {
32
- return;
33
- }
34
- if (data.type === "cf_agent_use_chat_request" && data.init.method === "POST") {
35
- const {
36
- method,
37
- keepalive,
38
- headers,
39
- body,
40
- // we're reading this
41
- redirect,
42
- integrity,
43
- credentials,
44
- mode,
45
- referrer,
46
- referrerPolicy,
47
- window
48
- // dispatcher,
49
- // duplex
50
- } = data.init;
51
- const { messages } = JSON.parse(body);
52
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
53
- type: "cf_agent_chat_messages",
54
- messages
55
- }, [connection.id]);
56
- await __privateMethod(this, _AIChatAgent_instances, persistMessages_fn).call(this, messages, [connection.id]);
57
- return __privateMethod(this, _AIChatAgent_instances, tryCatch_fn).call(this, async () => {
58
- const response = await this.onChatMessage(async ({ response: response2 }) => {
59
- const finalMessages = appendResponseMessages({
60
- messages,
61
- responseMessages: response2.messages
62
- });
63
- await __privateMethod(this, _AIChatAgent_instances, persistMessages_fn).call(this, finalMessages, [connection.id]);
64
- });
65
- if (response) {
66
- await __privateMethod(this, _AIChatAgent_instances, reply_fn).call(this, data.id, response);
67
- }
68
- });
69
- }
70
- if (data.type === "cf_agent_chat_clear") {
71
- this.sql`delete from cf_ai_chat_agent_messages`;
72
- this.messages = [];
73
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
74
- type: "cf_agent_chat_clear"
75
- }, [connection.id]);
76
- } else if (data.type === "cf_agent_chat_messages") {
77
- await __privateMethod(this, _AIChatAgent_instances, persistMessages_fn).call(this, data.messages, [connection.id]);
78
- }
79
- }
80
- }
81
- async onRequest(request) {
82
- return __privateMethod(this, _AIChatAgent_instances, tryCatch_fn).call(this, () => {
83
- if (request.url.endsWith("/get-messages")) {
84
- const messages = (this.sql`select * from cf_ai_chat_agent_messages` || []).map((row) => {
85
- return JSON.parse(row.message);
86
- });
87
- return Response.json(messages);
88
- }
89
- return super.onRequest(request);
90
- });
91
- }
92
- /**
93
- * Handle incoming chat messages and generate a response
94
- * @param onFinish Callback to be called when the response is finished
95
- * @returns Response to send to the client or undefined
96
- */
97
- async onChatMessage(onFinish) {
98
- throw new Error(
99
- "recieved a chat message, override onChatMessage and return a Response to send to the client"
100
- );
101
- }
102
- /**
103
- * Save messages on the server side and trigger AI response
104
- * @param messages Chat messages to save
105
- */
106
- async saveMessages(messages) {
107
- await __privateMethod(this, _AIChatAgent_instances, persistMessages_fn).call(this, messages);
108
- const response = await this.onChatMessage(async ({ response: response2 }) => {
109
- const finalMessages = appendResponseMessages({
110
- messages,
111
- responseMessages: response2.messages
112
- });
113
- await __privateMethod(this, _AIChatAgent_instances, persistMessages_fn).call(this, finalMessages, []);
114
- });
115
- if (response) {
116
- for await (const chunk of response.body) {
117
- decoder.decode(chunk);
118
- }
119
- response.body?.cancel();
120
- }
121
- }
122
- };
123
- _AIChatAgent_instances = new WeakSet();
124
- broadcastChatMessage_fn = function(message, exclude) {
125
- this.broadcast(JSON.stringify(message), exclude);
126
- };
127
- tryCatch_fn = async function(fn) {
128
- try {
129
- return await fn();
130
- } catch (e) {
131
- throw this.onError(e);
132
- }
133
- };
134
- persistMessages_fn = async function(messages, excludeBroadcastIds = []) {
135
- this.sql`delete from cf_ai_chat_agent_messages`;
136
- for (const message of messages) {
137
- this.sql`insert into cf_ai_chat_agent_messages (id, message) values (${message.id},${JSON.stringify(message)})`;
138
- }
139
- this.messages = messages;
140
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
141
- type: "cf_agent_chat_messages",
142
- messages
143
- }, excludeBroadcastIds);
144
- };
145
- reply_fn = async function(id, response) {
146
- return __privateMethod(this, _AIChatAgent_instances, tryCatch_fn).call(this, async () => {
147
- for await (const chunk of response.body) {
148
- const body = decoder.decode(chunk);
149
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
150
- id,
151
- type: "cf_agent_use_chat_response",
152
- body,
153
- done: false
154
- });
155
- }
156
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
157
- id,
158
- type: "cf_agent_use_chat_response",
159
- body: "",
160
- done: true
161
- });
162
- });
163
- };
164
- export {
165
- AIChatAgent
34
+ this.messages = autoTransformMessages(this._loadMessagesFromDb());
35
+ this._chatMessageAbortControllers = /* @__PURE__ */ new Map();
36
+ }
37
+ _broadcastChatMessage(message, exclude) {
38
+ this.broadcast(JSON.stringify(message), exclude);
39
+ }
40
+ _loadMessagesFromDb() {
41
+ return (this.sql`select * from cf_ai_chat_agent_messages order by created_at` || []).map((row) => {
42
+ try {
43
+ return JSON.parse(row.message);
44
+ } catch (error) {
45
+ console.error(`Failed to parse message ${row.id}:`, error);
46
+ return null;
47
+ }
48
+ }).filter((msg) => msg !== null);
49
+ }
50
+ async onMessage(connection, message) {
51
+ if (typeof message === "string") {
52
+ let data;
53
+ try {
54
+ data = JSON.parse(message);
55
+ } catch (_error) {
56
+ return;
57
+ }
58
+ if (data.type === MessageType.CF_AGENT_USE_CHAT_REQUEST && data.init.method === "POST") {
59
+ const { body } = data.init;
60
+ const { messages } = JSON.parse(body);
61
+ const transformedMessages = autoTransformMessages(messages);
62
+ this._broadcastChatMessage({
63
+ messages: transformedMessages,
64
+ type: MessageType.CF_AGENT_CHAT_MESSAGES
65
+ }, [connection.id]);
66
+ await this.persistMessages(transformedMessages, [connection.id]);
67
+ this.observability?.emit({
68
+ displayMessage: "Chat message request",
69
+ id: data.id,
70
+ payload: {},
71
+ timestamp: Date.now(),
72
+ type: "message:request"
73
+ }, this.ctx);
74
+ const chatMessageId = data.id;
75
+ const abortSignal = this._getAbortSignal(chatMessageId);
76
+ return this._tryCatchChat(async () => {
77
+ const response = await this.onChatMessage(async (_finishResult) => {
78
+ this._removeAbortController(chatMessageId);
79
+ this.observability?.emit({
80
+ displayMessage: "Chat message response",
81
+ id: data.id,
82
+ payload: {},
83
+ timestamp: Date.now(),
84
+ type: "message:response"
85
+ }, this.ctx);
86
+ }, abortSignal ? { abortSignal } : void 0);
87
+ if (response) await this._reply(data.id, response);
88
+ else {
89
+ console.warn(`[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`);
90
+ this._broadcastChatMessage({
91
+ body: "No response was generated by the agent.",
92
+ done: true,
93
+ id: data.id,
94
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
95
+ }, [connection.id]);
96
+ }
97
+ });
98
+ }
99
+ if (data.type === MessageType.CF_AGENT_CHAT_CLEAR) {
100
+ this._destroyAbortControllers();
101
+ this.sql`delete from cf_ai_chat_agent_messages`;
102
+ this.messages = [];
103
+ this._broadcastChatMessage({ type: MessageType.CF_AGENT_CHAT_CLEAR }, [connection.id]);
104
+ } else if (data.type === MessageType.CF_AGENT_CHAT_MESSAGES) {
105
+ const transformedMessages = autoTransformMessages(data.messages);
106
+ await this.persistMessages(transformedMessages, [connection.id]);
107
+ } else if (data.type === MessageType.CF_AGENT_CHAT_REQUEST_CANCEL) this._cancelChatRequest(data.id);
108
+ }
109
+ }
110
+ async onRequest(request) {
111
+ return this._tryCatchChat(() => {
112
+ if (new URL(request.url).pathname.endsWith("/get-messages")) {
113
+ const messages = this._loadMessagesFromDb();
114
+ return Response.json(messages);
115
+ }
116
+ return super.onRequest(request);
117
+ });
118
+ }
119
+ async _tryCatchChat(fn) {
120
+ try {
121
+ return await fn();
122
+ } catch (e) {
123
+ throw this.onError(e);
124
+ }
125
+ }
126
+ /**
127
+ * Handle incoming chat messages and generate a response
128
+ * @param onFinish Callback to be called when the response is finished
129
+ * @param options.signal A signal to pass to any child requests which can be used to cancel them
130
+ * @returns Response to send to the client or undefined
131
+ */
132
+ async onChatMessage(onFinish, options) {
133
+ throw new Error("recieved a chat message, override onChatMessage and return a Response to send to the client");
134
+ }
135
+ /**
136
+ * Save messages on the server side
137
+ * @param messages Chat messages to save
138
+ */
139
+ async saveMessages(messages) {
140
+ await this.persistMessages(messages);
141
+ await this._tryCatchChat(async () => {
142
+ const response = await this.onChatMessage(() => {});
143
+ if (response) this._reply(crypto.randomUUID(), response);
144
+ });
145
+ }
146
+ async persistMessages(messages, excludeBroadcastIds = []) {
147
+ for (const message of messages) this.sql`
148
+ insert into cf_ai_chat_agent_messages (id, message)
149
+ values (${message.id}, ${JSON.stringify(message)})
150
+ on conflict(id) do update set message = excluded.message
151
+ `;
152
+ this.messages = autoTransformMessages(this._loadMessagesFromDb());
153
+ this._broadcastChatMessage({
154
+ messages,
155
+ type: MessageType.CF_AGENT_CHAT_MESSAGES
156
+ }, excludeBroadcastIds);
157
+ }
158
+ async _reply(id, response) {
159
+ return this._tryCatchChat(async () => {
160
+ if (!response.body) {
161
+ this._broadcastChatMessage({
162
+ body: "",
163
+ done: true,
164
+ id,
165
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
166
+ });
167
+ return;
168
+ }
169
+ const reader = response.body.getReader();
170
+ const message = {
171
+ id: `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`,
172
+ role: "assistant",
173
+ parts: []
174
+ };
175
+ let activeTextParts = {};
176
+ let activeReasoningParts = {};
177
+ const partialToolCalls = {};
178
+ function updateDynamicToolPart(options) {
179
+ const part = message.parts.find((part$1) => part$1.type === "dynamic-tool" && part$1.toolCallId === options.toolCallId);
180
+ const anyOptions = options;
181
+ const anyPart = part;
182
+ if (part != null) {
183
+ part.state = options.state;
184
+ anyPart.toolName = options.toolName;
185
+ anyPart.input = anyOptions.input;
186
+ anyPart.output = anyOptions.output;
187
+ anyPart.errorText = anyOptions.errorText;
188
+ anyPart.rawInput = anyOptions.rawInput ?? anyPart.rawInput;
189
+ anyPart.preliminary = anyOptions.preliminary;
190
+ if (anyOptions.providerMetadata != null && part.state === "input-available") part.callProviderMetadata = anyOptions.providerMetadata;
191
+ } else message.parts.push({
192
+ type: "dynamic-tool",
193
+ toolName: options.toolName,
194
+ toolCallId: options.toolCallId,
195
+ state: options.state,
196
+ input: anyOptions.input,
197
+ output: anyOptions.output,
198
+ errorText: anyOptions.errorText,
199
+ preliminary: anyOptions.preliminary,
200
+ ...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}
201
+ });
202
+ }
203
+ function updateToolPart(options) {
204
+ const { isToolUIPart } = getAISDK();
205
+ const part = message.parts.find((part$1) => isToolUIPart(part$1) && part$1.toolCallId === options.toolCallId);
206
+ const anyOptions = options;
207
+ const anyPart = part;
208
+ if (part != null) {
209
+ part.state = options.state;
210
+ anyPart.input = anyOptions.input;
211
+ anyPart.output = anyOptions.output;
212
+ anyPart.errorText = anyOptions.errorText;
213
+ anyPart.rawInput = anyOptions.rawInput;
214
+ anyPart.preliminary = anyOptions.preliminary;
215
+ anyPart.providerExecuted = anyOptions.providerExecuted ?? part.providerExecuted;
216
+ if (anyOptions.providerMetadata != null && part.state === "input-available") part.callProviderMetadata = anyOptions.providerMetadata;
217
+ } else message.parts.push({
218
+ type: `tool-${options.toolName}`,
219
+ toolCallId: options.toolCallId,
220
+ state: options.state,
221
+ input: anyOptions.input,
222
+ output: anyOptions.output,
223
+ rawInput: anyOptions.rawInput,
224
+ errorText: anyOptions.errorText,
225
+ providerExecuted: anyOptions.providerExecuted,
226
+ preliminary: anyOptions.preliminary,
227
+ ...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}
228
+ });
229
+ }
230
+ async function updateMessageMetadata(metadata) {
231
+ if (metadata != null) message.metadata = message.metadata != null ? {
232
+ ...message.metadata,
233
+ ...metadata
234
+ } : metadata;
235
+ }
236
+ try {
237
+ while (true) {
238
+ const { done, value } = await reader.read();
239
+ if (done) {
240
+ this._broadcastChatMessage({
241
+ body: "",
242
+ done: true,
243
+ id,
244
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
245
+ });
246
+ break;
247
+ }
248
+ const chunk = decoder.decode(value);
249
+ if ((response.headers.get("content-type") || "").includes("text/event-stream")) {
250
+ const lines = chunk.split("\n");
251
+ for (const line of lines) if (line.startsWith("data: ") && line !== "data: [DONE]") try {
252
+ const data = JSON.parse(line.slice(6));
253
+ switch (data.type) {
254
+ case "text-start": {
255
+ const textPart = {
256
+ type: "text",
257
+ text: "",
258
+ providerMetadata: data.providerMetadata,
259
+ state: "streaming"
260
+ };
261
+ activeTextParts[data.id] = textPart;
262
+ message.parts.push(textPart);
263
+ break;
264
+ }
265
+ case "text-delta": {
266
+ const textPart = activeTextParts[data.id];
267
+ textPart.text += data.delta;
268
+ textPart.providerMetadata = data.providerMetadata ?? textPart.providerMetadata;
269
+ break;
270
+ }
271
+ case "text-end": {
272
+ const textPart = activeTextParts[data.id];
273
+ textPart.state = "done";
274
+ textPart.providerMetadata = data.providerMetadata ?? textPart.providerMetadata;
275
+ delete activeTextParts[data.id];
276
+ break;
277
+ }
278
+ case "reasoning-start": {
279
+ const reasoningPart = {
280
+ type: "reasoning",
281
+ text: "",
282
+ providerMetadata: data.providerMetadata,
283
+ state: "streaming"
284
+ };
285
+ activeReasoningParts[data.id] = reasoningPart;
286
+ message.parts.push(reasoningPart);
287
+ break;
288
+ }
289
+ case "reasoning-delta": {
290
+ const reasoningPart = activeReasoningParts[data.id];
291
+ reasoningPart.text += data.delta;
292
+ reasoningPart.providerMetadata = data.providerMetadata ?? reasoningPart.providerMetadata;
293
+ break;
294
+ }
295
+ case "reasoning-end": {
296
+ const reasoningPart = activeReasoningParts[data.id];
297
+ reasoningPart.providerMetadata = data.providerMetadata ?? reasoningPart.providerMetadata;
298
+ reasoningPart.state = "done";
299
+ delete activeReasoningParts[data.id];
300
+ break;
301
+ }
302
+ case "file":
303
+ message.parts.push({
304
+ type: "file",
305
+ mediaType: data.mediaType,
306
+ url: data.url
307
+ });
308
+ break;
309
+ case "source-url":
310
+ message.parts.push({
311
+ type: "source-url",
312
+ sourceId: data.sourceId,
313
+ url: data.url,
314
+ title: data.title,
315
+ providerMetadata: data.providerMetadata
316
+ });
317
+ break;
318
+ case "source-document":
319
+ message.parts.push({
320
+ type: "source-document",
321
+ sourceId: data.sourceId,
322
+ mediaType: data.mediaType,
323
+ title: data.title,
324
+ filename: data.filename,
325
+ providerMetadata: data.providerMetadata
326
+ });
327
+ break;
328
+ case "tool-input-start": {
329
+ const { isToolUIPart } = getAISDK();
330
+ const toolInvocations = message.parts.filter(isToolUIPart);
331
+ partialToolCalls[data.toolCallId] = {
332
+ text: "",
333
+ toolName: data.toolName,
334
+ index: toolInvocations.length,
335
+ dynamic: data.dynamic
336
+ };
337
+ if (data.dynamic) updateDynamicToolPart({
338
+ toolCallId: data.toolCallId,
339
+ toolName: data.toolName,
340
+ state: "input-streaming",
341
+ input: void 0
342
+ });
343
+ else updateToolPart({
344
+ toolCallId: data.toolCallId,
345
+ toolName: data.toolName,
346
+ state: "input-streaming",
347
+ input: void 0
348
+ });
349
+ break;
350
+ }
351
+ case "tool-input-delta": {
352
+ const partialToolCall = partialToolCalls[data.toolCallId];
353
+ partialToolCall.text += data.inputTextDelta;
354
+ const { parsePartialJson } = getAISDK();
355
+ const partialArgs = (await parsePartialJson(partialToolCall.text)).value;
356
+ if (partialToolCall.dynamic) updateDynamicToolPart({
357
+ toolCallId: data.toolCallId,
358
+ toolName: partialToolCall.toolName,
359
+ state: "input-streaming",
360
+ input: partialArgs
361
+ });
362
+ else updateToolPart({
363
+ toolCallId: data.toolCallId,
364
+ toolName: partialToolCall.toolName,
365
+ state: "input-streaming",
366
+ input: partialArgs
367
+ });
368
+ break;
369
+ }
370
+ case "tool-input-available":
371
+ if (data.dynamic) updateDynamicToolPart({
372
+ toolCallId: data.toolCallId,
373
+ toolName: data.toolName,
374
+ state: "input-available",
375
+ input: data.input,
376
+ providerMetadata: data.providerMetadata
377
+ });
378
+ else updateToolPart({
379
+ toolCallId: data.toolCallId,
380
+ toolName: data.toolName,
381
+ state: "input-available",
382
+ input: data.input,
383
+ providerExecuted: data.providerExecuted,
384
+ providerMetadata: data.providerMetadata
385
+ });
386
+ break;
387
+ case "tool-input-error":
388
+ if (data.dynamic) updateDynamicToolPart({
389
+ toolCallId: data.toolCallId,
390
+ toolName: data.toolName,
391
+ state: "output-error",
392
+ input: data.input,
393
+ errorText: data.errorText,
394
+ providerMetadata: data.providerMetadata
395
+ });
396
+ else updateToolPart({
397
+ toolCallId: data.toolCallId,
398
+ toolName: data.toolName,
399
+ state: "output-error",
400
+ input: void 0,
401
+ rawInput: data.input,
402
+ errorText: data.errorText,
403
+ providerExecuted: data.providerExecuted,
404
+ providerMetadata: data.providerMetadata
405
+ });
406
+ break;
407
+ case "tool-output-available":
408
+ if (data.dynamic) {
409
+ const toolInvocation = message.parts.filter((part) => part.type === "dynamic-tool").find((invocation) => invocation.toolCallId === data.toolCallId);
410
+ if (!toolInvocation) throw new Error("Tool invocation not found");
411
+ updateDynamicToolPart({
412
+ toolCallId: data.toolCallId,
413
+ toolName: toolInvocation.toolName,
414
+ state: "output-available",
415
+ input: toolInvocation.input,
416
+ output: data.output,
417
+ preliminary: data.preliminary
418
+ });
419
+ } else {
420
+ const { isToolUIPart, getToolName } = getAISDK();
421
+ const toolInvocation = message.parts.filter(isToolUIPart).find((invocation) => invocation.toolCallId === data.toolCallId);
422
+ if (!toolInvocation) throw new Error("Tool invocation not found");
423
+ updateToolPart({
424
+ toolCallId: data.toolCallId,
425
+ toolName: getToolName(toolInvocation),
426
+ state: "output-available",
427
+ input: toolInvocation.input,
428
+ output: data.output,
429
+ providerExecuted: data.providerExecuted,
430
+ preliminary: data.preliminary
431
+ });
432
+ }
433
+ break;
434
+ case "tool-output-error":
435
+ if (data.dynamic) {
436
+ const toolInvocation = message.parts.filter((part) => part.type === "dynamic-tool").find((invocation) => invocation.toolCallId === data.toolCallId);
437
+ if (!toolInvocation) throw new Error("Tool invocation not found");
438
+ updateDynamicToolPart({
439
+ toolCallId: data.toolCallId,
440
+ toolName: toolInvocation.toolName,
441
+ state: "output-error",
442
+ input: toolInvocation.input,
443
+ errorText: data.errorText
444
+ });
445
+ } else {
446
+ const { isToolUIPart, getToolName } = getAISDK();
447
+ const toolInvocation = message.parts.filter(isToolUIPart).find((invocation) => invocation.toolCallId === data.toolCallId);
448
+ if (!toolInvocation) throw new Error("Tool invocation not found");
449
+ updateToolPart({
450
+ toolCallId: data.toolCallId,
451
+ toolName: getToolName(toolInvocation),
452
+ state: "output-error",
453
+ input: toolInvocation.input,
454
+ rawInput: "rawInput" in toolInvocation ? toolInvocation.rawInput : void 0,
455
+ errorText: data.errorText
456
+ });
457
+ }
458
+ break;
459
+ case "start-step":
460
+ message.parts.push({ type: "step-start" });
461
+ break;
462
+ case "finish-step":
463
+ activeTextParts = {};
464
+ activeReasoningParts = {};
465
+ break;
466
+ case "start":
467
+ if (data.messageId != null) message.id = data.messageId;
468
+ await updateMessageMetadata(data.messageMetadata);
469
+ break;
470
+ case "finish":
471
+ await updateMessageMetadata(data.messageMetadata);
472
+ break;
473
+ case "message-metadata":
474
+ await updateMessageMetadata(data.messageMetadata);
475
+ break;
476
+ case "error":
477
+ this._broadcastChatMessage({
478
+ error: true,
479
+ body: data.errorText ?? JSON.stringify(data),
480
+ done: false,
481
+ id,
482
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
483
+ });
484
+ break;
485
+ }
486
+ this._broadcastChatMessage({
487
+ body: JSON.stringify(data),
488
+ done: false,
489
+ id,
490
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
491
+ });
492
+ } catch (_e) {}
493
+ } else if (chunk.length > 0) {
494
+ message.parts.push({
495
+ type: "text",
496
+ text: chunk
497
+ });
498
+ this._broadcastChatMessage({
499
+ body: JSON.stringify({
500
+ type: "text-delta",
501
+ delta: chunk
502
+ }),
503
+ done: false,
504
+ id,
505
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
506
+ });
507
+ }
508
+ }
509
+ } finally {
510
+ reader.releaseLock();
511
+ }
512
+ if (message.parts.length > 0) await this.persistMessages([...this.messages, message]);
513
+ });
514
+ }
515
+ /**
516
+ * For the given message id, look up its associated AbortController
517
+ * If the AbortController does not exist, create and store one in memory
518
+ *
519
+ * returns the AbortSignal associated with the AbortController
520
+ */
521
+ _getAbortSignal(id) {
522
+ if (typeof id !== "string") return;
523
+ if (!this._chatMessageAbortControllers.has(id)) this._chatMessageAbortControllers.set(id, new AbortController());
524
+ return this._chatMessageAbortControllers.get(id)?.signal;
525
+ }
526
+ /**
527
+ * Remove an abort controller from the cache of pending message responses
528
+ */
529
+ _removeAbortController(id) {
530
+ this._chatMessageAbortControllers.delete(id);
531
+ }
532
+ /**
533
+ * Propagate an abort signal for any requests associated with the given message id
534
+ */
535
+ _cancelChatRequest(id) {
536
+ if (this._chatMessageAbortControllers.has(id)) this._chatMessageAbortControllers.get(id)?.abort();
537
+ }
538
+ /**
539
+ * Abort all pending requests and clear the cache of AbortControllers
540
+ */
541
+ _destroyAbortControllers() {
542
+ for (const controller of this._chatMessageAbortControllers.values()) controller?.abort();
543
+ this._chatMessageAbortControllers.clear();
544
+ }
545
+ /**
546
+ * When the DO is destroyed, cancel all pending requests
547
+ */
548
+ async destroy() {
549
+ this._destroyAbortControllers();
550
+ await super.destroy();
551
+ }
166
552
  };
553
+
554
+ //#endregion
555
+ export { AIChatAgent };
167
556
  //# sourceMappingURL=ai-chat-agent.js.map