agents 0.0.0-f5b5854 → 0.0.0-f64700e

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