agents 0.0.0-fe9e8d3 → 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 (75) hide show
  1. package/README.md +255 -27
  2. package/dist/ai-chat-agent.d.ts +47 -18
  3. package/dist/ai-chat-agent.js +532 -226
  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 +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 -200
  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 -74
  16. package/dist/ai-types.js +3 -1
  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 +12 -79
  27. package/dist/client.js +3 -130
  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 +62 -306
  37. package/dist/index.js +7 -21
  38. package/dist/mcp/client.d.ts +4 -777
  39. package/dist/mcp/client.js +3 -10
  40. package/dist/mcp/do-oauth-client-provider.d.ts +2 -41
  41. package/dist/mcp/do-oauth-client-provider.js +2 -106
  42. package/dist/mcp/index.d.ts +151 -71
  43. package/dist/mcp/index.js +1359 -797
  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 -0
  50. package/dist/observability/index.js +7 -0
  51. package/dist/react-BIh615qN.d.ts +115 -0
  52. package/dist/react.d.ts +10 -39
  53. package/dist/react.js +183 -98
  54. package/dist/react.js.map +1 -1
  55. package/dist/schedule.d.ts +89 -12
  56. package/dist/schedule.js +46 -23
  57. package/dist/schedule.js.map +1 -1
  58. package/dist/serializable-CymX8ovI.d.ts +39 -0
  59. package/dist/serializable.d.ts +7 -0
  60. package/dist/serializable.js +1 -0
  61. package/dist/src-nFNV3Ttx.js +1216 -0
  62. package/dist/src-nFNV3Ttx.js.map +1 -0
  63. package/package.json +115 -66
  64. package/dist/ai-types.js.map +0 -1
  65. package/dist/chunk-HD4VEHBA.js +0 -608
  66. package/dist/chunk-HD4VEHBA.js.map +0 -1
  67. package/dist/chunk-HMLY7DHA.js +0 -16
  68. package/dist/chunk-HMLY7DHA.js.map +0 -1
  69. package/dist/chunk-Q5ZBHY4Z.js +0 -456
  70. package/dist/chunk-Q5ZBHY4Z.js.map +0 -1
  71. package/dist/client.js.map +0 -1
  72. package/dist/index.js.map +0 -1
  73. package/dist/mcp/client.js.map +0 -1
  74. package/dist/mcp/do-oauth-client-provider.js.map +0 -1
  75. package/src/index.ts +0 -942
@@ -1,234 +1,540 @@
1
- import {
2
- Agent
3
- } from "./chunk-HD4VEHBA.js";
4
- import "./chunk-Q5ZBHY4Z.js";
5
- import {
6
- __privateAdd,
7
- __privateGet,
8
- __privateMethod,
9
- __privateSet
10
- } from "./chunk-HMLY7DHA.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
- import { appendResponseMessages } from "ai";
14
- var decoder = new TextDecoder();
15
- var _chatMessageAbortControllers, _AIChatAgent_instances, broadcastChatMessage_fn, tryCatch_fn, reply_fn, getAbortSignal_fn, removeAbortController_fn, cancelChatRequest_fn, destroyAbortControllers_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
+ */
16
14
  var AIChatAgent = class extends Agent {
17
- constructor(ctx, env) {
18
- super(ctx, env);
19
- __privateAdd(this, _AIChatAgent_instances);
20
- /**
21
- * Map of message `id`s to `AbortController`s
22
- * useful to propagate request cancellation signals for any external calls made by the agent
23
- */
24
- __privateAdd(this, _chatMessageAbortControllers);
25
- 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 (
26
18
  id text primary key,
27
19
  message text not null,
28
20
  created_at datetime default current_timestamp
29
21
  )`;
30
- this.messages = (this.sql`select * from cf_ai_chat_agent_messages` || []).map((row) => {
31
- return JSON.parse(row.message);
32
- });
33
- __privateSet(this, _chatMessageAbortControllers, /* @__PURE__ */ new Map());
34
- }
35
- async onMessage(connection, message) {
36
- if (typeof message === "string") {
37
- let data;
38
- try {
39
- data = JSON.parse(message);
40
- } catch (error) {
41
- return;
42
- }
43
- if (data.type === "cf_agent_use_chat_request" && data.init.method === "POST") {
44
- const {
45
- method,
46
- keepalive,
47
- headers,
48
- body,
49
- // we're reading this
50
- redirect,
51
- integrity,
52
- credentials,
53
- mode,
54
- referrer,
55
- referrerPolicy,
56
- window
57
- // dispatcher,
58
- // duplex
59
- } = data.init;
60
- const { messages } = JSON.parse(body);
61
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
62
- type: "cf_agent_chat_messages",
63
- messages
64
- }, [connection.id]);
65
- await this.persistMessages(messages, [connection.id]);
66
- const chatMessageId = data.id;
67
- const abortSignal = __privateMethod(this, _AIChatAgent_instances, getAbortSignal_fn).call(this, chatMessageId);
68
- return __privateMethod(this, _AIChatAgent_instances, tryCatch_fn).call(this, async () => {
69
- const response = await this.onChatMessage(
70
- async ({ response: response2 }) => {
71
- const finalMessages = appendResponseMessages({
72
- messages,
73
- responseMessages: response2.messages
74
- });
75
- await this.persistMessages(finalMessages, [connection.id]);
76
- __privateMethod(this, _AIChatAgent_instances, removeAbortController_fn).call(this, chatMessageId);
77
- },
78
- abortSignal ? { abortSignal } : void 0
79
- );
80
- if (response) {
81
- await __privateMethod(this, _AIChatAgent_instances, reply_fn).call(this, data.id, response);
82
- }
83
- });
84
- }
85
- if (data.type === "cf_agent_chat_clear") {
86
- __privateMethod(this, _AIChatAgent_instances, destroyAbortControllers_fn).call(this);
87
- this.sql`delete from cf_ai_chat_agent_messages`;
88
- this.messages = [];
89
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
90
- type: "cf_agent_chat_clear"
91
- }, [connection.id]);
92
- } else if (data.type === "cf_agent_chat_messages") {
93
- await this.persistMessages(data.messages, [connection.id]);
94
- } else if (data.type === "cf_agent_chat_request_cancel") {
95
- __privateMethod(this, _AIChatAgent_instances, cancelChatRequest_fn).call(this, data.id);
96
- }
97
- }
98
- }
99
- async onRequest(request) {
100
- return __privateMethod(this, _AIChatAgent_instances, tryCatch_fn).call(this, () => {
101
- const url = new URL(request.url);
102
- if (url.pathname.endsWith("/get-messages")) {
103
- const messages = (this.sql`select * from cf_ai_chat_agent_messages` || []).map((row) => {
104
- return JSON.parse(row.message);
105
- });
106
- return Response.json(messages);
107
- }
108
- return super.onRequest(request);
109
- });
110
- }
111
- /**
112
- * Handle incoming chat messages and generate a response
113
- * @param onFinish Callback to be called when the response is finished
114
- * @param options.signal A signal to pass to any child requests which can be used to cancel them
115
- * @returns Response to send to the client or undefined
116
- */
117
- async onChatMessage(onFinish, options) {
118
- throw new Error(
119
- "recieved a chat message, override onChatMessage and return a Response to send to the client"
120
- );
121
- }
122
- /**
123
- * Save messages on the server side and trigger AI response
124
- * @param messages Chat messages to save
125
- */
126
- async saveMessages(messages) {
127
- await this.persistMessages(messages);
128
- const response = await this.onChatMessage(async ({ response: response2 }) => {
129
- const finalMessages = appendResponseMessages({
130
- messages,
131
- responseMessages: response2.messages
132
- });
133
- await this.persistMessages(finalMessages, []);
134
- });
135
- if (response) {
136
- for await (const chunk of response.body) {
137
- decoder.decode(chunk);
138
- }
139
- response.body?.cancel();
140
- }
141
- }
142
- async persistMessages(messages, excludeBroadcastIds = []) {
143
- this.sql`delete from cf_ai_chat_agent_messages`;
144
- for (const message of messages) {
145
- this.sql`insert into cf_ai_chat_agent_messages (id, message) values (${message.id},${JSON.stringify(message)})`;
146
- }
147
- this.messages = messages;
148
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
149
- type: "cf_agent_chat_messages",
150
- messages
151
- }, excludeBroadcastIds);
152
- }
153
- /**
154
- * When the DO is destroyed, cancel all pending requests
155
- */
156
- async destroy() {
157
- __privateMethod(this, _AIChatAgent_instances, destroyAbortControllers_fn).call(this);
158
- await super.destroy();
159
- }
160
- };
161
- _chatMessageAbortControllers = new WeakMap();
162
- _AIChatAgent_instances = new WeakSet();
163
- broadcastChatMessage_fn = function(message, exclude) {
164
- this.broadcast(JSON.stringify(message), exclude);
165
- };
166
- tryCatch_fn = async function(fn) {
167
- try {
168
- return await fn();
169
- } catch (e) {
170
- throw this.onError(e);
171
- }
172
- };
173
- reply_fn = async function(id, response) {
174
- return __privateMethod(this, _AIChatAgent_instances, tryCatch_fn).call(this, async () => {
175
- for await (const chunk of response.body) {
176
- const body = decoder.decode(chunk);
177
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
178
- id,
179
- type: "cf_agent_use_chat_response",
180
- body,
181
- done: false
182
- });
183
- }
184
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
185
- id,
186
- type: "cf_agent_use_chat_response",
187
- body: "",
188
- done: true
189
- });
190
- });
191
- };
192
- /**
193
- * For the given message id, look up its associated AbortController
194
- * If the AbortController does not exist, create and store one in memory
195
- *
196
- * returns the AbortSignal associated with the AbortController
197
- */
198
- getAbortSignal_fn = function(id) {
199
- if (typeof id !== "string") {
200
- return void 0;
201
- }
202
- if (!__privateGet(this, _chatMessageAbortControllers).has(id)) {
203
- __privateGet(this, _chatMessageAbortControllers).set(id, new AbortController());
204
- }
205
- return __privateGet(this, _chatMessageAbortControllers).get(id)?.signal;
206
- };
207
- /**
208
- * Remove an abort controller from the cache of pending message responses
209
- */
210
- removeAbortController_fn = function(id) {
211
- __privateGet(this, _chatMessageAbortControllers).delete(id);
212
- };
213
- /**
214
- * Propagate an abort signal for any requests associated with the given message id
215
- */
216
- cancelChatRequest_fn = function(id) {
217
- if (__privateGet(this, _chatMessageAbortControllers).has(id)) {
218
- const abortController = __privateGet(this, _chatMessageAbortControllers).get(id);
219
- abortController?.abort();
220
- }
221
- };
222
- /**
223
- * Abort all pending requests and clear the cache of AbortControllers
224
- */
225
- destroyAbortControllers_fn = function() {
226
- for (const controller of __privateGet(this, _chatMessageAbortControllers).values()) {
227
- controller?.abort();
228
- }
229
- __privateGet(this, _chatMessageAbortControllers).clear();
230
- };
231
- export {
232
- 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
+ }
233
536
  };
537
+
538
+ //#endregion
539
+ export { AIChatAgent };
234
540
  //# sourceMappingURL=ai-chat-agent.js.map