agents 0.0.0-ad0054b → 0.0.0-afd9efd

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +255 -27
  2. package/dist/_esm-LV5FJ3HK.js +3922 -0
  3. package/dist/_esm-LV5FJ3HK.js.map +1 -0
  4. package/dist/ai-chat-agent.d.ts +42 -10
  5. package/dist/ai-chat-agent.js +603 -150
  6. package/dist/ai-chat-agent.js.map +1 -1
  7. package/dist/ai-chat-v5-migration.d.ts +152 -0
  8. package/dist/ai-chat-v5-migration.js +20 -0
  9. package/dist/ai-react.d.ts +78 -67
  10. package/dist/ai-react.js +254 -108
  11. package/dist/ai-react.js.map +1 -1
  12. package/dist/ai-types.d.ts +37 -19
  13. package/dist/ai-types.js +7 -0
  14. package/dist/ccip-CMBYN64O.js +15 -0
  15. package/dist/ccip-CMBYN64O.js.map +1 -0
  16. package/dist/chunk-2Y6KNRNP.js +1343 -0
  17. package/dist/chunk-2Y6KNRNP.js.map +1 -0
  18. package/dist/chunk-5Y6BEZDY.js +276 -0
  19. package/dist/chunk-5Y6BEZDY.js.map +1 -0
  20. package/dist/chunk-BER7KXUJ.js +18 -0
  21. package/dist/chunk-BER7KXUJ.js.map +1 -0
  22. package/dist/chunk-C2OEBJZ2.js +113 -0
  23. package/dist/chunk-C2OEBJZ2.js.map +1 -0
  24. package/dist/chunk-JJBFIGUC.js +5202 -0
  25. package/dist/chunk-JJBFIGUC.js.map +1 -0
  26. package/dist/chunk-PR4QN5HX.js +43 -0
  27. package/dist/chunk-PR4QN5HX.js.map +1 -0
  28. package/dist/chunk-QEVM4BVL.js +116 -0
  29. package/dist/chunk-QEVM4BVL.js.map +1 -0
  30. package/dist/chunk-QUOGV3WN.js +949 -0
  31. package/dist/chunk-QUOGV3WN.js.map +1 -0
  32. package/dist/chunk-TYAY6AU6.js +159 -0
  33. package/dist/chunk-TYAY6AU6.js.map +1 -0
  34. package/dist/chunk-UJVEAURM.js +150 -0
  35. package/dist/chunk-UJVEAURM.js.map +1 -0
  36. package/dist/client-C8tswVoM.d.ts +5248 -0
  37. package/dist/client.d.ts +16 -2
  38. package/dist/client.js +8 -126
  39. package/dist/client.js.map +1 -1
  40. package/dist/codemode/ai.d.ts +25 -0
  41. package/dist/codemode/ai.js +5200 -0
  42. package/dist/codemode/ai.js.map +1 -0
  43. package/dist/index.d.ts +269 -26
  44. package/dist/index.js +14 -3
  45. package/dist/mcp/client.d.ts +10 -775
  46. package/dist/mcp/client.js +2 -2
  47. package/dist/mcp/do-oauth-client-provider.d.ts +4 -3
  48. package/dist/mcp/do-oauth-client-provider.js +4 -103
  49. package/dist/mcp/do-oauth-client-provider.js.map +1 -1
  50. package/dist/mcp/index.d.ts +64 -59
  51. package/dist/mcp/index.js +992 -685
  52. package/dist/mcp/index.js.map +1 -1
  53. package/dist/mcp/x402.d.ts +39 -0
  54. package/dist/mcp/x402.js +3195 -0
  55. package/dist/mcp/x402.js.map +1 -0
  56. package/dist/mcp-BH1fJeiU.d.ts +58 -0
  57. package/dist/observability/index.d.ts +34 -0
  58. package/dist/observability/index.js +12 -0
  59. package/dist/observability/index.js.map +1 -0
  60. package/dist/react.d.ts +97 -9
  61. package/dist/react.js +123 -11
  62. package/dist/react.js.map +1 -1
  63. package/dist/schedule.d.ts +81 -7
  64. package/dist/schedule.js +20 -7
  65. package/dist/schedule.js.map +1 -1
  66. package/dist/secp256k1-M22GZP2U.js +2193 -0
  67. package/dist/secp256k1-M22GZP2U.js.map +1 -0
  68. package/dist/serializable.d.ts +32 -0
  69. package/dist/serializable.js +1 -0
  70. package/dist/serializable.js.map +1 -0
  71. package/package.json +103 -67
  72. package/src/index.ts +1245 -156
  73. package/dist/chunk-A65CRW2D.js +0 -609
  74. package/dist/chunk-A65CRW2D.js.map +0 -1
  75. package/dist/chunk-HMLY7DHA.js +0 -16
  76. package/dist/chunk-Q5ZBHY4Z.js +0 -456
  77. package/dist/chunk-Q5ZBHY4Z.js.map +0 -1
  78. /package/dist/{chunk-HMLY7DHA.js.map → ai-chat-v5-migration.js.map} +0 -0
@@ -1,113 +1,169 @@
1
+ import {
2
+ autoTransformMessages
3
+ } from "./chunk-UJVEAURM.js";
1
4
  import {
2
5
  Agent
3
- } from "./chunk-A65CRW2D.js";
4
- import "./chunk-Q5ZBHY4Z.js";
6
+ } from "./chunk-2Y6KNRNP.js";
7
+ import "./chunk-QUOGV3WN.js";
8
+ import "./chunk-C2OEBJZ2.js";
9
+ import "./chunk-QEVM4BVL.js";
10
+ import "./chunk-BER7KXUJ.js";
5
11
  import {
6
- __privateAdd,
7
- __privateGet,
8
- __privateMethod,
9
- __privateSet
10
- } from "./chunk-HMLY7DHA.js";
12
+ __require
13
+ } from "./chunk-PR4QN5HX.js";
11
14
 
12
15
  // src/ai-chat-agent.ts
13
- import { appendResponseMessages } from "ai";
14
16
  var decoder = new TextDecoder();
15
- var _chatMessageAbortControllers, _AIChatAgent_instances, broadcastChatMessage_fn, tryCatch_fn, reply_fn, getAbortSignal_fn, removeAbortController_fn, cancelChatRequest_fn, destroyAbortControllers_fn;
17
+ var aiSDK;
18
+ function getAISDK() {
19
+ if (!aiSDK) {
20
+ const { getToolName, isToolUIPart, parsePartialJson } = __require("ai");
21
+ aiSDK = {
22
+ getToolName,
23
+ isToolUIPart,
24
+ parsePartialJson
25
+ };
26
+ }
27
+ return aiSDK;
28
+ }
16
29
  var AIChatAgent = class extends Agent {
17
30
  constructor(ctx, env) {
18
31
  super(ctx, env);
19
- __privateAdd(this, _AIChatAgent_instances);
20
- /**
21
- * Map of message `id`s to `AbortController`s
22
- * useful to propagate request cancellation signals for any external calls made by the agent
23
- */
24
- __privateAdd(this, _chatMessageAbortControllers);
25
32
  this.sql`create table if not exists cf_ai_chat_agent_messages (
26
33
  id text primary key,
27
34
  message text not null,
28
35
  created_at datetime default current_timestamp
29
36
  )`;
30
- this.messages = (this.sql`select * from cf_ai_chat_agent_messages` || []).map((row) => {
31
- return JSON.parse(row.message);
32
- });
33
- __privateSet(this, _chatMessageAbortControllers, /* @__PURE__ */ new Map());
37
+ const rawMessages = this._loadMessagesFromDb();
38
+ this.messages = autoTransformMessages(rawMessages);
39
+ this._chatMessageAbortControllers = /* @__PURE__ */ new Map();
40
+ }
41
+ _broadcastChatMessage(message, exclude) {
42
+ this.broadcast(JSON.stringify(message), exclude);
43
+ }
44
+ _loadMessagesFromDb() {
45
+ const rows = this.sql`select * from cf_ai_chat_agent_messages order by created_at` || [];
46
+ return rows.map((row) => {
47
+ try {
48
+ return JSON.parse(row.message);
49
+ } catch (error) {
50
+ console.error(`Failed to parse message ${row.id}:`, error);
51
+ return null;
52
+ }
53
+ }).filter((msg) => msg !== null);
34
54
  }
35
55
  async onMessage(connection, message) {
36
56
  if (typeof message === "string") {
37
57
  let data;
38
58
  try {
39
59
  data = JSON.parse(message);
40
- } catch (error) {
60
+ } catch (_error) {
41
61
  return;
42
62
  }
43
- if (data.type === "cf_agent_use_chat_request" && data.init.method === "POST") {
63
+ if (data.type === "cf_agent_use_chat_request" /* CF_AGENT_USE_CHAT_REQUEST */ && data.init.method === "POST") {
44
64
  const {
45
- method,
46
- keepalive,
47
- headers,
48
- body,
65
+ // method,
66
+ // keepalive,
67
+ // headers,
68
+ body
49
69
  // we're reading this
50
- redirect,
51
- integrity,
52
- credentials,
53
- mode,
54
- referrer,
55
- referrerPolicy,
56
- window
70
+ //
71
+ // // these might not exist?
57
72
  // dispatcher,
58
73
  // duplex
59
74
  } = data.init;
60
75
  const { messages } = JSON.parse(body);
61
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
62
- type: "cf_agent_chat_messages",
63
- messages
64
- }, [connection.id]);
65
- await this.persistMessages(messages, [connection.id]);
76
+ const transformedMessages = autoTransformMessages(messages);
77
+ this._broadcastChatMessage(
78
+ {
79
+ messages: transformedMessages,
80
+ type: "cf_agent_chat_messages" /* CF_AGENT_CHAT_MESSAGES */
81
+ },
82
+ [connection.id]
83
+ );
84
+ await this.persistMessages(transformedMessages, [connection.id]);
85
+ this.observability?.emit(
86
+ {
87
+ displayMessage: "Chat message request",
88
+ id: data.id,
89
+ payload: {},
90
+ timestamp: Date.now(),
91
+ type: "message:request"
92
+ },
93
+ this.ctx
94
+ );
66
95
  const chatMessageId = data.id;
67
- const abortSignal = __privateMethod(this, _AIChatAgent_instances, getAbortSignal_fn).call(this, chatMessageId);
68
- return __privateMethod(this, _AIChatAgent_instances, tryCatch_fn).call(this, async () => {
96
+ const abortSignal = this._getAbortSignal(chatMessageId);
97
+ return this._tryCatchChat(async () => {
69
98
  const response = await this.onChatMessage(
70
- async ({ response: response2 }) => {
71
- const finalMessages = appendResponseMessages({
72
- messages,
73
- responseMessages: response2.messages
74
- });
75
- await this.persistMessages(finalMessages, [connection.id]);
76
- __privateMethod(this, _AIChatAgent_instances, removeAbortController_fn).call(this, chatMessageId);
99
+ async (_finishResult) => {
100
+ this._removeAbortController(chatMessageId);
101
+ this.observability?.emit(
102
+ {
103
+ displayMessage: "Chat message response",
104
+ id: data.id,
105
+ payload: {},
106
+ timestamp: Date.now(),
107
+ type: "message:response"
108
+ },
109
+ this.ctx
110
+ );
77
111
  },
78
112
  abortSignal ? { abortSignal } : void 0
79
113
  );
80
114
  if (response) {
81
- await __privateMethod(this, _AIChatAgent_instances, reply_fn).call(this, data.id, response);
115
+ await this._reply(data.id, response);
116
+ } else {
117
+ console.warn(
118
+ `[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`
119
+ );
120
+ this._broadcastChatMessage(
121
+ {
122
+ body: "No response was generated by the agent.",
123
+ done: true,
124
+ id: data.id,
125
+ type: "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */
126
+ },
127
+ [connection.id]
128
+ );
82
129
  }
83
130
  });
84
131
  }
85
- if (data.type === "cf_agent_chat_clear") {
86
- __privateMethod(this, _AIChatAgent_instances, destroyAbortControllers_fn).call(this);
132
+ if (data.type === "cf_agent_chat_clear" /* CF_AGENT_CHAT_CLEAR */) {
133
+ this._destroyAbortControllers();
87
134
  this.sql`delete from cf_ai_chat_agent_messages`;
88
135
  this.messages = [];
89
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
90
- type: "cf_agent_chat_clear"
91
- }, [connection.id]);
92
- } else if (data.type === "cf_agent_chat_messages") {
93
- await this.persistMessages(data.messages, [connection.id]);
94
- } else if (data.type === "cf_agent_chat_request_cancel") {
95
- __privateMethod(this, _AIChatAgent_instances, cancelChatRequest_fn).call(this, data.id);
136
+ this._broadcastChatMessage(
137
+ {
138
+ type: "cf_agent_chat_clear" /* CF_AGENT_CHAT_CLEAR */
139
+ },
140
+ [connection.id]
141
+ );
142
+ } else if (data.type === "cf_agent_chat_messages" /* CF_AGENT_CHAT_MESSAGES */) {
143
+ const transformedMessages = autoTransformMessages(data.messages);
144
+ await this.persistMessages(transformedMessages, [connection.id]);
145
+ } else if (data.type === "cf_agent_chat_request_cancel" /* CF_AGENT_CHAT_REQUEST_CANCEL */) {
146
+ this._cancelChatRequest(data.id);
96
147
  }
97
148
  }
98
149
  }
99
150
  async onRequest(request) {
100
- return __privateMethod(this, _AIChatAgent_instances, tryCatch_fn).call(this, () => {
151
+ return this._tryCatchChat(() => {
101
152
  const url = new URL(request.url);
102
153
  if (url.pathname.endsWith("/get-messages")) {
103
- const messages = (this.sql`select * from cf_ai_chat_agent_messages` || []).map((row) => {
104
- return JSON.parse(row.message);
105
- });
154
+ const messages = this._loadMessagesFromDb();
106
155
  return Response.json(messages);
107
156
  }
108
157
  return super.onRequest(request);
109
158
  });
110
159
  }
160
+ async _tryCatchChat(fn) {
161
+ try {
162
+ return await fn();
163
+ } catch (e) {
164
+ throw this.onError(e);
165
+ }
166
+ }
111
167
  /**
112
168
  * Handle incoming chat messages and generate a response
113
169
  * @param onFinish Callback to be called when the response is finished
@@ -120,113 +176,510 @@ var AIChatAgent = class extends Agent {
120
176
  );
121
177
  }
122
178
  /**
123
- * Save messages on the server side and trigger AI response
179
+ * Save messages on the server side
124
180
  * @param messages Chat messages to save
125
181
  */
126
182
  async saveMessages(messages) {
127
183
  await this.persistMessages(messages);
128
- const response = await this.onChatMessage(async ({ response: response2 }) => {
129
- const finalMessages = appendResponseMessages({
130
- messages,
131
- responseMessages: response2.messages
184
+ await this._tryCatchChat(async () => {
185
+ const response = await this.onChatMessage(() => {
132
186
  });
133
- await this.persistMessages(finalMessages, []);
187
+ if (response) this._reply(crypto.randomUUID(), response);
134
188
  });
135
- if (response) {
136
- for await (const chunk of response.body) {
137
- decoder.decode(chunk);
138
- }
139
- response.body?.cancel();
140
- }
141
189
  }
142
190
  async persistMessages(messages, excludeBroadcastIds = []) {
143
- this.sql`delete from cf_ai_chat_agent_messages`;
144
191
  for (const message of messages) {
145
- this.sql`insert into cf_ai_chat_agent_messages (id, message) values (${message.id},${JSON.stringify(message)})`;
192
+ this.sql`
193
+ insert into cf_ai_chat_agent_messages (id, message)
194
+ values (${message.id}, ${JSON.stringify(message)})
195
+ on conflict(id) do update set message = excluded.message
196
+ `;
197
+ }
198
+ const persisted = this._loadMessagesFromDb();
199
+ this.messages = autoTransformMessages(persisted);
200
+ this._broadcastChatMessage(
201
+ {
202
+ messages,
203
+ type: "cf_agent_chat_messages" /* CF_AGENT_CHAT_MESSAGES */
204
+ },
205
+ excludeBroadcastIds
206
+ );
207
+ }
208
+ async _reply(id, response) {
209
+ return this._tryCatchChat(async () => {
210
+ if (!response.body) {
211
+ this._broadcastChatMessage({
212
+ body: "",
213
+ done: true,
214
+ id,
215
+ type: "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */
216
+ });
217
+ return;
218
+ }
219
+ const reader = response.body.getReader();
220
+ const message = {
221
+ id: `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`,
222
+ // default
223
+ role: "assistant",
224
+ parts: []
225
+ };
226
+ let activeTextParts = {};
227
+ let activeReasoningParts = {};
228
+ const partialToolCalls = {};
229
+ function updateDynamicToolPart(options) {
230
+ const part = message.parts.find(
231
+ (part2) => part2.type === "dynamic-tool" && part2.toolCallId === options.toolCallId
232
+ );
233
+ const anyOptions = options;
234
+ const anyPart = part;
235
+ if (part != null) {
236
+ part.state = options.state;
237
+ anyPart.toolName = options.toolName;
238
+ anyPart.input = anyOptions.input;
239
+ anyPart.output = anyOptions.output;
240
+ anyPart.errorText = anyOptions.errorText;
241
+ anyPart.rawInput = anyOptions.rawInput ?? anyPart.rawInput;
242
+ anyPart.preliminary = anyOptions.preliminary;
243
+ if (anyOptions.providerMetadata != null && part.state === "input-available") {
244
+ part.callProviderMetadata = anyOptions.providerMetadata;
245
+ }
246
+ } else {
247
+ message.parts.push({
248
+ type: "dynamic-tool",
249
+ toolName: options.toolName,
250
+ toolCallId: options.toolCallId,
251
+ state: options.state,
252
+ input: anyOptions.input,
253
+ output: anyOptions.output,
254
+ errorText: anyOptions.errorText,
255
+ preliminary: anyOptions.preliminary,
256
+ ...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}
257
+ });
258
+ }
259
+ }
260
+ function updateToolPart(options) {
261
+ const { isToolUIPart } = getAISDK();
262
+ const part = message.parts.find(
263
+ (part2) => isToolUIPart(part2) && part2.toolCallId === options.toolCallId
264
+ );
265
+ const anyOptions = options;
266
+ const anyPart = part;
267
+ if (part != null) {
268
+ part.state = options.state;
269
+ anyPart.input = anyOptions.input;
270
+ anyPart.output = anyOptions.output;
271
+ anyPart.errorText = anyOptions.errorText;
272
+ anyPart.rawInput = anyOptions.rawInput;
273
+ anyPart.preliminary = anyOptions.preliminary;
274
+ anyPart.providerExecuted = anyOptions.providerExecuted ?? part.providerExecuted;
275
+ if (anyOptions.providerMetadata != null && part.state === "input-available") {
276
+ part.callProviderMetadata = anyOptions.providerMetadata;
277
+ }
278
+ } else {
279
+ message.parts.push({
280
+ type: `tool-${options.toolName}`,
281
+ toolCallId: options.toolCallId,
282
+ state: options.state,
283
+ input: anyOptions.input,
284
+ output: anyOptions.output,
285
+ rawInput: anyOptions.rawInput,
286
+ errorText: anyOptions.errorText,
287
+ providerExecuted: anyOptions.providerExecuted,
288
+ preliminary: anyOptions.preliminary,
289
+ ...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}
290
+ });
291
+ }
292
+ }
293
+ async function updateMessageMetadata(metadata) {
294
+ if (metadata != null) {
295
+ const mergedMetadata = message.metadata != null ? { ...message.metadata, ...metadata } : metadata;
296
+ message.metadata = mergedMetadata;
297
+ }
298
+ }
299
+ try {
300
+ while (true) {
301
+ const { done, value } = await reader.read();
302
+ if (done) {
303
+ this._broadcastChatMessage({
304
+ body: "",
305
+ done: true,
306
+ id,
307
+ type: "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */
308
+ });
309
+ break;
310
+ }
311
+ const chunk = decoder.decode(value);
312
+ const contentType = response.headers.get("content-type") || "";
313
+ const isSSE = contentType.includes("text/event-stream");
314
+ if (isSSE) {
315
+ const lines = chunk.split("\n");
316
+ for (const line of lines) {
317
+ if (line.startsWith("data: ") && line !== "data: [DONE]") {
318
+ try {
319
+ const data = JSON.parse(line.slice(6));
320
+ switch (data.type) {
321
+ case "text-start": {
322
+ const textPart = {
323
+ type: "text",
324
+ text: "",
325
+ providerMetadata: data.providerMetadata,
326
+ state: "streaming"
327
+ };
328
+ activeTextParts[data.id] = textPart;
329
+ message.parts.push(textPart);
330
+ break;
331
+ }
332
+ case "text-delta": {
333
+ const textPart = activeTextParts[data.id];
334
+ textPart.text += data.delta;
335
+ textPart.providerMetadata = data.providerMetadata ?? textPart.providerMetadata;
336
+ break;
337
+ }
338
+ case "text-end": {
339
+ const textPart = activeTextParts[data.id];
340
+ textPart.state = "done";
341
+ textPart.providerMetadata = data.providerMetadata ?? textPart.providerMetadata;
342
+ delete activeTextParts[data.id];
343
+ break;
344
+ }
345
+ case "reasoning-start": {
346
+ const reasoningPart = {
347
+ type: "reasoning",
348
+ text: "",
349
+ providerMetadata: data.providerMetadata,
350
+ state: "streaming"
351
+ };
352
+ activeReasoningParts[data.id] = reasoningPart;
353
+ message.parts.push(reasoningPart);
354
+ break;
355
+ }
356
+ case "reasoning-delta": {
357
+ const reasoningPart = activeReasoningParts[data.id];
358
+ reasoningPart.text += data.delta;
359
+ reasoningPart.providerMetadata = data.providerMetadata ?? reasoningPart.providerMetadata;
360
+ break;
361
+ }
362
+ case "reasoning-end": {
363
+ const reasoningPart = activeReasoningParts[data.id];
364
+ reasoningPart.providerMetadata = data.providerMetadata ?? reasoningPart.providerMetadata;
365
+ reasoningPart.state = "done";
366
+ delete activeReasoningParts[data.id];
367
+ break;
368
+ }
369
+ case "file": {
370
+ message.parts.push({
371
+ type: "file",
372
+ mediaType: data.mediaType,
373
+ url: data.url
374
+ });
375
+ break;
376
+ }
377
+ case "source-url": {
378
+ message.parts.push({
379
+ type: "source-url",
380
+ sourceId: data.sourceId,
381
+ url: data.url,
382
+ title: data.title,
383
+ providerMetadata: data.providerMetadata
384
+ });
385
+ break;
386
+ }
387
+ case "source-document": {
388
+ message.parts.push({
389
+ type: "source-document",
390
+ sourceId: data.sourceId,
391
+ mediaType: data.mediaType,
392
+ title: data.title,
393
+ filename: data.filename,
394
+ providerMetadata: data.providerMetadata
395
+ });
396
+ break;
397
+ }
398
+ case "tool-input-start": {
399
+ const { isToolUIPart } = getAISDK();
400
+ const toolInvocations = message.parts.filter(isToolUIPart);
401
+ partialToolCalls[data.toolCallId] = {
402
+ text: "",
403
+ toolName: data.toolName,
404
+ index: toolInvocations.length,
405
+ dynamic: data.dynamic
406
+ };
407
+ if (data.dynamic) {
408
+ updateDynamicToolPart({
409
+ toolCallId: data.toolCallId,
410
+ toolName: data.toolName,
411
+ state: "input-streaming",
412
+ input: void 0
413
+ });
414
+ } else {
415
+ updateToolPart({
416
+ toolCallId: data.toolCallId,
417
+ toolName: data.toolName,
418
+ state: "input-streaming",
419
+ input: void 0
420
+ });
421
+ }
422
+ break;
423
+ }
424
+ case "tool-input-delta": {
425
+ const partialToolCall = partialToolCalls[data.toolCallId];
426
+ partialToolCall.text += data.inputTextDelta;
427
+ const { parsePartialJson } = getAISDK();
428
+ const partialArgsResult = await parsePartialJson(
429
+ partialToolCall.text
430
+ );
431
+ const partialArgs = partialArgsResult.value;
432
+ if (partialToolCall.dynamic) {
433
+ updateDynamicToolPart({
434
+ toolCallId: data.toolCallId,
435
+ toolName: partialToolCall.toolName,
436
+ state: "input-streaming",
437
+ input: partialArgs
438
+ });
439
+ } else {
440
+ updateToolPart({
441
+ toolCallId: data.toolCallId,
442
+ toolName: partialToolCall.toolName,
443
+ state: "input-streaming",
444
+ input: partialArgs
445
+ });
446
+ }
447
+ break;
448
+ }
449
+ case "tool-input-available": {
450
+ if (data.dynamic) {
451
+ updateDynamicToolPart({
452
+ toolCallId: data.toolCallId,
453
+ toolName: data.toolName,
454
+ state: "input-available",
455
+ input: data.input,
456
+ providerMetadata: data.providerMetadata
457
+ });
458
+ } else {
459
+ updateToolPart({
460
+ toolCallId: data.toolCallId,
461
+ toolName: data.toolName,
462
+ state: "input-available",
463
+ input: data.input,
464
+ providerExecuted: data.providerExecuted,
465
+ providerMetadata: data.providerMetadata
466
+ });
467
+ }
468
+ break;
469
+ }
470
+ case "tool-input-error": {
471
+ if (data.dynamic) {
472
+ updateDynamicToolPart({
473
+ toolCallId: data.toolCallId,
474
+ toolName: data.toolName,
475
+ state: "output-error",
476
+ input: data.input,
477
+ errorText: data.errorText,
478
+ providerMetadata: data.providerMetadata
479
+ });
480
+ } else {
481
+ updateToolPart({
482
+ toolCallId: data.toolCallId,
483
+ toolName: data.toolName,
484
+ state: "output-error",
485
+ input: void 0,
486
+ rawInput: data.input,
487
+ errorText: data.errorText,
488
+ providerExecuted: data.providerExecuted,
489
+ providerMetadata: data.providerMetadata
490
+ });
491
+ }
492
+ break;
493
+ }
494
+ case "tool-output-available": {
495
+ if (data.dynamic) {
496
+ const toolInvocations = message.parts.filter(
497
+ (part) => part.type === "dynamic-tool"
498
+ );
499
+ const toolInvocation = toolInvocations.find(
500
+ (invocation) => invocation.toolCallId === data.toolCallId
501
+ );
502
+ if (!toolInvocation)
503
+ throw new Error("Tool invocation not found");
504
+ updateDynamicToolPart({
505
+ toolCallId: data.toolCallId,
506
+ toolName: toolInvocation.toolName,
507
+ state: "output-available",
508
+ input: toolInvocation.input,
509
+ output: data.output,
510
+ preliminary: data.preliminary
511
+ });
512
+ } else {
513
+ const { isToolUIPart, getToolName } = getAISDK();
514
+ const toolInvocations = message.parts.filter(
515
+ isToolUIPart
516
+ );
517
+ const toolInvocation = toolInvocations.find(
518
+ (invocation) => invocation.toolCallId === data.toolCallId
519
+ );
520
+ if (!toolInvocation)
521
+ throw new Error("Tool invocation not found");
522
+ updateToolPart({
523
+ toolCallId: data.toolCallId,
524
+ toolName: getToolName(toolInvocation),
525
+ state: "output-available",
526
+ input: toolInvocation.input,
527
+ output: data.output,
528
+ providerExecuted: data.providerExecuted,
529
+ preliminary: data.preliminary
530
+ });
531
+ }
532
+ break;
533
+ }
534
+ case "tool-output-error": {
535
+ if (data.dynamic) {
536
+ const toolInvocations = message.parts.filter(
537
+ (part) => part.type === "dynamic-tool"
538
+ );
539
+ const toolInvocation = toolInvocations.find(
540
+ (invocation) => invocation.toolCallId === data.toolCallId
541
+ );
542
+ if (!toolInvocation)
543
+ throw new Error("Tool invocation not found");
544
+ updateDynamicToolPart({
545
+ toolCallId: data.toolCallId,
546
+ toolName: toolInvocation.toolName,
547
+ state: "output-error",
548
+ input: toolInvocation.input,
549
+ errorText: data.errorText
550
+ });
551
+ } else {
552
+ const { isToolUIPart, getToolName } = getAISDK();
553
+ const toolInvocations = message.parts.filter(
554
+ isToolUIPart
555
+ );
556
+ const toolInvocation = toolInvocations.find(
557
+ (invocation) => invocation.toolCallId === data.toolCallId
558
+ );
559
+ if (!toolInvocation)
560
+ throw new Error("Tool invocation not found");
561
+ updateToolPart({
562
+ toolCallId: data.toolCallId,
563
+ toolName: getToolName(toolInvocation),
564
+ state: "output-error",
565
+ input: toolInvocation.input,
566
+ rawInput: "rawInput" in toolInvocation ? toolInvocation.rawInput : void 0,
567
+ errorText: data.errorText
568
+ });
569
+ }
570
+ break;
571
+ }
572
+ case "start-step": {
573
+ message.parts.push({ type: "step-start" });
574
+ break;
575
+ }
576
+ case "finish-step": {
577
+ activeTextParts = {};
578
+ activeReasoningParts = {};
579
+ break;
580
+ }
581
+ case "start": {
582
+ if (data.messageId != null) {
583
+ message.id = data.messageId;
584
+ }
585
+ await updateMessageMetadata(data.messageMetadata);
586
+ break;
587
+ }
588
+ case "finish": {
589
+ await updateMessageMetadata(data.messageMetadata);
590
+ break;
591
+ }
592
+ case "message-metadata": {
593
+ await updateMessageMetadata(data.messageMetadata);
594
+ break;
595
+ }
596
+ case "error": {
597
+ this._broadcastChatMessage({
598
+ error: true,
599
+ body: data.errorText ?? JSON.stringify(data),
600
+ done: false,
601
+ id,
602
+ type: "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */
603
+ });
604
+ break;
605
+ }
606
+ }
607
+ this._broadcastChatMessage({
608
+ body: JSON.stringify(data),
609
+ done: false,
610
+ id,
611
+ type: "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */
612
+ });
613
+ } catch (_e) {
614
+ }
615
+ }
616
+ }
617
+ } else {
618
+ if (chunk.length > 0) {
619
+ message.parts.push({ type: "text", text: chunk });
620
+ this._broadcastChatMessage({
621
+ body: JSON.stringify({ type: "text-delta", delta: chunk }),
622
+ done: false,
623
+ id,
624
+ type: "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */
625
+ });
626
+ }
627
+ }
628
+ }
629
+ } finally {
630
+ reader.releaseLock();
631
+ }
632
+ if (message.parts.length > 0) {
633
+ await this.persistMessages([...this.messages, message]);
634
+ }
635
+ });
636
+ }
637
+ /**
638
+ * For the given message id, look up its associated AbortController
639
+ * If the AbortController does not exist, create and store one in memory
640
+ *
641
+ * returns the AbortSignal associated with the AbortController
642
+ */
643
+ _getAbortSignal(id) {
644
+ if (typeof id !== "string") {
645
+ return void 0;
646
+ }
647
+ if (!this._chatMessageAbortControllers.has(id)) {
648
+ this._chatMessageAbortControllers.set(id, new AbortController());
146
649
  }
147
- this.messages = messages;
148
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
149
- type: "cf_agent_chat_messages",
150
- messages
151
- }, excludeBroadcastIds);
650
+ return this._chatMessageAbortControllers.get(id)?.signal;
152
651
  }
153
652
  /**
154
- * When the DO is destroyed, cancel all pending requests
653
+ * Remove an abort controller from the cache of pending message responses
155
654
  */
156
- async destroy() {
157
- __privateMethod(this, _AIChatAgent_instances, destroyAbortControllers_fn).call(this);
158
- await super.destroy();
655
+ _removeAbortController(id) {
656
+ this._chatMessageAbortControllers.delete(id);
159
657
  }
160
- };
161
- _chatMessageAbortControllers = new WeakMap();
162
- _AIChatAgent_instances = new WeakSet();
163
- broadcastChatMessage_fn = function(message, exclude) {
164
- this.broadcast(JSON.stringify(message), exclude);
165
- };
166
- tryCatch_fn = async function(fn) {
167
- try {
168
- return await fn();
169
- } catch (e) {
170
- throw this.onError(e);
658
+ /**
659
+ * Propagate an abort signal for any requests associated with the given message id
660
+ */
661
+ _cancelChatRequest(id) {
662
+ if (this._chatMessageAbortControllers.has(id)) {
663
+ const abortController = this._chatMessageAbortControllers.get(id);
664
+ abortController?.abort();
665
+ }
171
666
  }
172
- };
173
- reply_fn = async function(id, response) {
174
- return __privateMethod(this, _AIChatAgent_instances, tryCatch_fn).call(this, async () => {
175
- for await (const chunk of response.body) {
176
- const body = decoder.decode(chunk);
177
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
178
- id,
179
- type: "cf_agent_use_chat_response",
180
- body,
181
- done: false
182
- });
667
+ /**
668
+ * Abort all pending requests and clear the cache of AbortControllers
669
+ */
670
+ _destroyAbortControllers() {
671
+ for (const controller of this._chatMessageAbortControllers.values()) {
672
+ controller?.abort();
183
673
  }
184
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
185
- id,
186
- type: "cf_agent_use_chat_response",
187
- body: "",
188
- done: true
189
- });
190
- });
191
- };
192
- /**
193
- * For the given message id, look up its associated AbortController
194
- * If the AbortController does not exist, create and store one in memory
195
- *
196
- * returns the AbortSignal associated with the AbortController
197
- */
198
- getAbortSignal_fn = function(id) {
199
- if (typeof id !== "string") {
200
- return void 0;
201
- }
202
- if (!__privateGet(this, _chatMessageAbortControllers).has(id)) {
203
- __privateGet(this, _chatMessageAbortControllers).set(id, new AbortController());
204
- }
205
- return __privateGet(this, _chatMessageAbortControllers).get(id)?.signal;
206
- };
207
- /**
208
- * Remove an abort controller from the cache of pending message responses
209
- */
210
- removeAbortController_fn = function(id) {
211
- __privateGet(this, _chatMessageAbortControllers).delete(id);
212
- };
213
- /**
214
- * Propagate an abort signal for any requests associated with the given message id
215
- */
216
- cancelChatRequest_fn = function(id) {
217
- if (__privateGet(this, _chatMessageAbortControllers).has(id)) {
218
- const abortController = __privateGet(this, _chatMessageAbortControllers).get(id);
219
- abortController?.abort();
674
+ this._chatMessageAbortControllers.clear();
675
+ }
676
+ /**
677
+ * When the DO is destroyed, cancel all pending requests
678
+ */
679
+ async destroy() {
680
+ this._destroyAbortControllers();
681
+ await super.destroy();
220
682
  }
221
- };
222
- /**
223
- * Abort all pending requests and clear the cache of AbortControllers
224
- */
225
- destroyAbortControllers_fn = function() {
226
- for (const controller of __privateGet(this, _chatMessageAbortControllers).values()) {
227
- controller?.abort();
228
- }
229
- __privateGet(this, _chatMessageAbortControllers).clear();
230
683
  };
231
684
  export {
232
685
  AIChatAgent