agents 0.0.0-feef082 → 0.0.0-ff431ff

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