agents 0.0.0-e777fdd → 0.0.0-e7d0d4d

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 (95) hide show
  1. package/dist/ai-chat-agent.d.ts +16 -17
  2. package/dist/ai-chat-agent.js +532 -352
  3. package/dist/ai-chat-agent.js.map +1 -1
  4. package/dist/ai-chat-v5-migration-DBHGW4Hv.js +155 -0
  5. package/dist/ai-chat-v5-migration-DBHGW4Hv.js.map +1 -0
  6. package/dist/ai-chat-v5-migration.d.ts +7 -4
  7. package/dist/ai-chat-v5-migration.js +3 -20
  8. package/dist/ai-react.d.ts +14 -23
  9. package/dist/ai-react.js +258 -349
  10. package/dist/ai-react.js.map +1 -1
  11. package/dist/ai-types-B3aQaFv3.js +20 -0
  12. package/dist/ai-types-B3aQaFv3.js.map +1 -0
  13. package/dist/ai-types-D5YoPrBZ.d.ts +95 -0
  14. package/dist/ai-types.d.ts +6 -92
  15. package/dist/ai-types.js +3 -8
  16. package/dist/client-9Ld2_lnt.js +786 -0
  17. package/dist/client-9Ld2_lnt.js.map +1 -0
  18. package/dist/client-BfiZ3HQd.js +117 -0
  19. package/dist/client-BfiZ3HQd.js.map +1 -0
  20. package/dist/client-CbWe9FBd.d.ts +104 -0
  21. package/dist/client-Csp_m13H.d.ts +5315 -0
  22. package/dist/client.d.ts +11 -92
  23. package/dist/client.js +4 -13
  24. package/dist/codemode/ai.d.ts +27 -0
  25. package/dist/codemode/ai.js +151 -0
  26. package/dist/codemode/ai.js.map +1 -0
  27. package/dist/do-oauth-client-provider-CswoD5Lu.js +93 -0
  28. package/dist/do-oauth-client-provider-CswoD5Lu.js.map +1 -0
  29. package/dist/do-oauth-client-provider-DGc5pP0l.d.ts +55 -0
  30. package/dist/index-DFqsR7mb.d.ts +560 -0
  31. package/dist/index-DhJCaDWd.d.ts +58 -0
  32. package/dist/index.d.ts +55 -556
  33. package/dist/index.js +7 -32
  34. package/dist/mcp/client.d.ts +4 -11
  35. package/dist/mcp/client.js +3 -10
  36. package/dist/mcp/do-oauth-client-provider.d.ts +2 -50
  37. package/dist/mcp/do-oauth-client-provider.js +3 -8
  38. package/dist/mcp/index.d.ts +151 -75
  39. package/dist/mcp/index.js +1355 -1081
  40. package/dist/mcp/index.js.map +1 -1
  41. package/dist/mcp/x402.d.ts +22 -27
  42. package/dist/mcp/x402.js +186 -3187
  43. package/dist/mcp/x402.js.map +1 -1
  44. package/dist/mcp-Dw5vDrY8.d.ts +61 -0
  45. package/dist/observability/index.d.ts +3 -46
  46. package/dist/observability/index.js +7 -12
  47. package/dist/react-NCPvtyCY.d.ts +115 -0
  48. package/dist/react.d.ts +10 -123
  49. package/dist/react.js +183 -113
  50. package/dist/react.js.map +1 -1
  51. package/dist/schedule.d.ts +13 -10
  52. package/dist/schedule.js +43 -33
  53. package/dist/schedule.js.map +1 -1
  54. package/dist/serializable-CymX8ovI.d.ts +39 -0
  55. package/dist/serializable.d.ts +7 -32
  56. package/dist/serializable.js +1 -1
  57. package/dist/src-Dz0H9hSU.js +1200 -0
  58. package/dist/src-Dz0H9hSU.js.map +1 -0
  59. package/package.json +30 -12
  60. package/dist/_esm-LV5FJ3HK.js +0 -3922
  61. package/dist/_esm-LV5FJ3HK.js.map +0 -1
  62. package/dist/ai-chat-v5-migration.js.map +0 -1
  63. package/dist/ai-types.js.map +0 -1
  64. package/dist/ccip-CMBYN64O.js +0 -15
  65. package/dist/ccip-CMBYN64O.js.map +0 -1
  66. package/dist/chunk-5Y6BEZDY.js +0 -276
  67. package/dist/chunk-5Y6BEZDY.js.map +0 -1
  68. package/dist/chunk-BER7KXUJ.js +0 -18
  69. package/dist/chunk-BER7KXUJ.js.map +0 -1
  70. package/dist/chunk-JJBFIGUC.js +0 -5202
  71. package/dist/chunk-JJBFIGUC.js.map +0 -1
  72. package/dist/chunk-PR4QN5HX.js +0 -43
  73. package/dist/chunk-PR4QN5HX.js.map +0 -1
  74. package/dist/chunk-QEPGNUG6.js +0 -650
  75. package/dist/chunk-QEPGNUG6.js.map +0 -1
  76. package/dist/chunk-QEVM4BVL.js +0 -116
  77. package/dist/chunk-QEVM4BVL.js.map +0 -1
  78. package/dist/chunk-RS5OCNEQ.js +0 -1323
  79. package/dist/chunk-RS5OCNEQ.js.map +0 -1
  80. package/dist/chunk-TYAY6AU6.js +0 -159
  81. package/dist/chunk-TYAY6AU6.js.map +0 -1
  82. package/dist/chunk-UJVEAURM.js +0 -150
  83. package/dist/chunk-UJVEAURM.js.map +0 -1
  84. package/dist/chunk-XFS5ERG3.js +0 -127
  85. package/dist/chunk-XFS5ERG3.js.map +0 -1
  86. package/dist/client-BohGLma8.d.ts +0 -5041
  87. package/dist/client.js.map +0 -1
  88. package/dist/index.js.map +0 -1
  89. package/dist/mcp/client.js.map +0 -1
  90. package/dist/mcp/do-oauth-client-provider.js.map +0 -1
  91. package/dist/observability/index.js.map +0 -1
  92. package/dist/secp256k1-M22GZP2U.js +0 -2193
  93. package/dist/secp256k1-M22GZP2U.js.map +0 -1
  94. package/dist/serializable.js.map +0 -1
  95. package/src/index.ts +0 -1987
@@ -1,360 +1,540 @@
1
- import {
2
- autoTransformMessages
3
- } from "./chunk-UJVEAURM.js";
4
- import {
5
- Agent
6
- } from "./chunk-RS5OCNEQ.js";
7
- import "./chunk-QEPGNUG6.js";
8
- import "./chunk-XFS5ERG3.js";
9
- import "./chunk-QEVM4BVL.js";
10
- import "./chunk-BER7KXUJ.js";
11
- import "./chunk-PR4QN5HX.js";
1
+ import { t as MessageType } from "./ai-types-B3aQaFv3.js";
2
+ import "./client-BfiZ3HQd.js";
3
+ import "./client-9Ld2_lnt.js";
4
+ import "./do-oauth-client-provider-CswoD5Lu.js";
5
+ import { t as Agent } from "./src-Dz0H9hSU.js";
6
+ import { r as autoTransformMessages } from "./ai-chat-v5-migration-DBHGW4Hv.js";
12
7
 
13
- // src/ai-chat-agent.ts
14
- var decoder = new TextDecoder();
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
+ */
15
14
  var AIChatAgent = class extends Agent {
16
- constructor(ctx, env) {
17
- super(ctx, env);
18
- 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 (
19
18
  id text primary key,
20
19
  message text not null,
21
20
  created_at datetime default current_timestamp
22
21
  )`;
23
- const rawMessages = (this.sql`select * from cf_ai_chat_agent_messages` || []).map((row) => {
24
- return JSON.parse(row.message);
25
- });
26
- this.messages = autoTransformMessages(rawMessages);
27
- this._chatMessageAbortControllers = /* @__PURE__ */ new Map();
28
- }
29
- _broadcastChatMessage(message, exclude) {
30
- this.broadcast(JSON.stringify(message), exclude);
31
- }
32
- async onMessage(connection, message) {
33
- if (typeof message === "string") {
34
- let data;
35
- try {
36
- data = JSON.parse(message);
37
- } catch (_error) {
38
- return;
39
- }
40
- if (data.type === "cf_agent_use_chat_request" /* CF_AGENT_USE_CHAT_REQUEST */ && data.init.method === "POST") {
41
- const {
42
- // method,
43
- // keepalive,
44
- // headers,
45
- body
46
- // we're reading this
47
- //
48
- // // these might not exist?
49
- // dispatcher,
50
- // duplex
51
- } = data.init;
52
- const { messages } = JSON.parse(body);
53
- const transformedMessages = autoTransformMessages(messages);
54
- this._broadcastChatMessage(
55
- {
56
- messages: transformedMessages,
57
- type: "cf_agent_chat_messages" /* CF_AGENT_CHAT_MESSAGES */
58
- },
59
- [connection.id]
60
- );
61
- await this.persistMessages(transformedMessages, [connection.id]);
62
- this.observability?.emit(
63
- {
64
- displayMessage: "Chat message request",
65
- id: data.id,
66
- payload: {},
67
- timestamp: Date.now(),
68
- type: "message:request"
69
- },
70
- this.ctx
71
- );
72
- const chatMessageId = data.id;
73
- const abortSignal = this._getAbortSignal(chatMessageId);
74
- return this._tryCatchChat(async () => {
75
- const response = await this.onChatMessage(
76
- async (_finishResult) => {
77
- this._removeAbortController(chatMessageId);
78
- this.observability?.emit(
79
- {
80
- displayMessage: "Chat message response",
81
- id: data.id,
82
- payload: {},
83
- timestamp: Date.now(),
84
- type: "message:response"
85
- },
86
- this.ctx
87
- );
88
- },
89
- abortSignal ? { abortSignal } : void 0
90
- );
91
- if (response) {
92
- await this._reply(data.id, response);
93
- } else {
94
- console.warn(
95
- `[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`
96
- );
97
- this._broadcastChatMessage(
98
- {
99
- body: "No response was generated by the agent.",
100
- done: true,
101
- id: data.id,
102
- type: "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */
103
- },
104
- [connection.id]
105
- );
106
- }
107
- });
108
- }
109
- if (data.type === "cf_agent_chat_clear" /* CF_AGENT_CHAT_CLEAR */) {
110
- this._destroyAbortControllers();
111
- this.sql`delete from cf_ai_chat_agent_messages`;
112
- this.messages = [];
113
- this._broadcastChatMessage(
114
- {
115
- type: "cf_agent_chat_clear" /* CF_AGENT_CHAT_CLEAR */
116
- },
117
- [connection.id]
118
- );
119
- } else if (data.type === "cf_agent_chat_messages" /* CF_AGENT_CHAT_MESSAGES */) {
120
- const transformedMessages = autoTransformMessages(data.messages);
121
- await this.persistMessages(transformedMessages, [connection.id]);
122
- } else if (data.type === "cf_agent_chat_request_cancel" /* CF_AGENT_CHAT_REQUEST_CANCEL */) {
123
- this._cancelChatRequest(data.id);
124
- }
125
- }
126
- }
127
- async onRequest(request) {
128
- return this._tryCatchChat(() => {
129
- const url = new URL(request.url);
130
- if (url.pathname.endsWith("/get-messages")) {
131
- const messages = (this.sql`select * from cf_ai_chat_agent_messages` || []).map((row) => {
132
- return JSON.parse(row.message);
133
- });
134
- return Response.json(messages);
135
- }
136
- return super.onRequest(request);
137
- });
138
- }
139
- async _tryCatchChat(fn) {
140
- try {
141
- return await fn();
142
- } catch (e) {
143
- throw this.onError(e);
144
- }
145
- }
146
- /**
147
- * Handle incoming chat messages and generate a response
148
- * @param onFinish Callback to be called when the response is finished
149
- * @param options.signal A signal to pass to any child requests which can be used to cancel them
150
- * @returns Response to send to the client or undefined
151
- */
152
- async onChatMessage(onFinish, options) {
153
- throw new Error(
154
- "recieved a chat message, override onChatMessage and return a Response to send to the client"
155
- );
156
- }
157
- /**
158
- * Save messages on the server side
159
- * @param messages Chat messages to save
160
- */
161
- async saveMessages(messages) {
162
- await this.persistMessages(messages);
163
- }
164
- async persistMessages(messages, excludeBroadcastIds = []) {
165
- this.sql`delete from cf_ai_chat_agent_messages`;
166
- for (const message of messages) {
167
- this.sql`insert into cf_ai_chat_agent_messages (id, message) values (${message.id},${JSON.stringify(message)})`;
168
- }
169
- this.messages = messages;
170
- this._broadcastChatMessage(
171
- {
172
- messages,
173
- type: "cf_agent_chat_messages" /* CF_AGENT_CHAT_MESSAGES */
174
- },
175
- excludeBroadcastIds
176
- );
177
- }
178
- async _reply(id, response) {
179
- return this._tryCatchChat(async () => {
180
- if (!response.body) {
181
- this._broadcastChatMessage({
182
- body: "",
183
- done: true,
184
- id,
185
- type: "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */
186
- });
187
- return;
188
- }
189
- const reader = response.body.getReader();
190
- let fullResponseText = "";
191
- let fullReasoningText = "";
192
- const toolCalls = /* @__PURE__ */ new Map();
193
- try {
194
- while (true) {
195
- const { done, value } = await reader.read();
196
- if (done) {
197
- this._broadcastChatMessage({
198
- body: "",
199
- done: true,
200
- id,
201
- type: "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */
202
- });
203
- break;
204
- }
205
- const chunk = decoder.decode(value);
206
- const contentType = response.headers.get("content-type") || "";
207
- const isSSE = contentType.includes("text/event-stream");
208
- if (isSSE) {
209
- const lines = chunk.split("\n");
210
- for (const line of lines) {
211
- if (line.startsWith("data: ") && line !== "data: [DONE]") {
212
- try {
213
- const data = JSON.parse(line.slice(6));
214
- switch (data.type) {
215
- // SSE event signaling the tool input is ready. We track by
216
- // `toolCallId` so we can persist it as a tool part in the message.
217
- case "tool-input-available": {
218
- const { toolCallId, toolName, input } = data;
219
- toolCalls.set(toolCallId, {
220
- toolCallId,
221
- toolName,
222
- input,
223
- type: toolName ? `tool-${toolName}` : "dynamic-tool",
224
- state: "input-available"
225
- });
226
- break;
227
- }
228
- // SSE event signaling the tool output is ready. We should've
229
- // already received the input in a previous event so an entry
230
- // with `toolCallId` should already be present
231
- case "tool-output-available": {
232
- const { toolCallId, output, isError, errorText } = data;
233
- const toolPart = toolCalls.get(toolCallId);
234
- if (toolPart)
235
- toolCalls.set(toolCallId, {
236
- ...toolPart,
237
- output,
238
- isError,
239
- errorText,
240
- state: "output-available"
241
- });
242
- break;
243
- }
244
- case "error": {
245
- this._broadcastChatMessage({
246
- error: true,
247
- body: data.errorText ?? JSON.stringify(data),
248
- done: false,
249
- id,
250
- type: "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */
251
- });
252
- return;
253
- }
254
- case "reasoning-delta": {
255
- if (data.delta) fullReasoningText += data.delta;
256
- break;
257
- }
258
- case "text-delta": {
259
- if (data.delta) fullResponseText += data.delta;
260
- break;
261
- }
262
- }
263
- this._broadcastChatMessage({
264
- body: JSON.stringify(data),
265
- done: false,
266
- id,
267
- type: "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */
268
- });
269
- } catch (_e) {
270
- }
271
- }
272
- }
273
- } else {
274
- if (chunk.length > 0) {
275
- fullResponseText += chunk;
276
- this._broadcastChatMessage({
277
- body: JSON.stringify({ type: "text-delta", delta: chunk }),
278
- done: false,
279
- id,
280
- type: "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */
281
- });
282
- }
283
- }
284
- }
285
- } finally {
286
- reader.releaseLock();
287
- }
288
- const messageParts = [];
289
- Array.from(toolCalls.values()).forEach((t) => {
290
- messageParts.push(t);
291
- });
292
- if (fullReasoningText.trim()) {
293
- messageParts.push({ type: "reasoning", text: fullReasoningText });
294
- }
295
- if (fullResponseText.trim()) {
296
- messageParts.push({ type: "text", text: fullResponseText });
297
- }
298
- if (messageParts.length > 0) {
299
- await this.persistMessages([
300
- ...this.messages,
301
- {
302
- id: `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`,
303
- role: "assistant",
304
- parts: messageParts
305
- }
306
- ]);
307
- }
308
- });
309
- }
310
- /**
311
- * For the given message id, look up its associated AbortController
312
- * If the AbortController does not exist, create and store one in memory
313
- *
314
- * returns the AbortSignal associated with the AbortController
315
- */
316
- _getAbortSignal(id) {
317
- if (typeof id !== "string") {
318
- return void 0;
319
- }
320
- if (!this._chatMessageAbortControllers.has(id)) {
321
- this._chatMessageAbortControllers.set(id, new AbortController());
322
- }
323
- return this._chatMessageAbortControllers.get(id)?.signal;
324
- }
325
- /**
326
- * Remove an abort controller from the cache of pending message responses
327
- */
328
- _removeAbortController(id) {
329
- this._chatMessageAbortControllers.delete(id);
330
- }
331
- /**
332
- * Propagate an abort signal for any requests associated with the given message id
333
- */
334
- _cancelChatRequest(id) {
335
- if (this._chatMessageAbortControllers.has(id)) {
336
- const abortController = this._chatMessageAbortControllers.get(id);
337
- abortController?.abort();
338
- }
339
- }
340
- /**
341
- * Abort all pending requests and clear the cache of AbortControllers
342
- */
343
- _destroyAbortControllers() {
344
- for (const controller of this._chatMessageAbortControllers.values()) {
345
- controller?.abort();
346
- }
347
- this._chatMessageAbortControllers.clear();
348
- }
349
- /**
350
- * When the DO is destroyed, cancel all pending requests
351
- */
352
- async destroy() {
353
- this._destroyAbortControllers();
354
- await super.destroy();
355
- }
356
- };
357
- export {
358
- 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
+ }
359
536
  };
537
+
538
+ //#endregion
539
+ export { AIChatAgent };
360
540
  //# sourceMappingURL=ai-chat-agent.js.map