agents 0.0.0-d72c6a2 → 0.0.0-d7b2f14

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 +5 -3
  2. package/dist/ai-chat-agent.d.ts +99 -19
  3. package/dist/ai-chat-agent.js +804 -351
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration-BSiGZmYU.js +155 -0
  6. package/dist/ai-chat-v5-migration-BSiGZmYU.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 +25 -23
  10. package/dist/ai-react.js +409 -304
  11. package/dist/ai-react.js.map +1 -1
  12. package/dist/ai-types-81H_-Uxh.d.ts +103 -0
  13. package/dist/ai-types-CrMqkwc_.js +24 -0
  14. package/dist/ai-types-CrMqkwc_.js.map +1 -0
  15. package/dist/ai-types.d.ts +6 -91
  16. package/dist/ai-types.js +3 -7
  17. package/dist/cli/index.d.ts +1 -0
  18. package/dist/cli/index.js +28 -0
  19. package/dist/cli/index.js.map +1 -0
  20. package/dist/client-B3SR12TQ.js +117 -0
  21. package/dist/client-B3SR12TQ.js.map +1 -0
  22. package/dist/client-BAQA84dr.d.ts +104 -0
  23. package/dist/client-CFhjXCiO.js +1093 -0
  24. package/dist/client-CFhjXCiO.js.map +1 -0
  25. package/dist/client-z9RQJDtK.d.ts +833 -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-C2CHH5x-.d.ts +55 -0
  32. package/dist/do-oauth-client-provider-CwqK5SXm.js +94 -0
  33. package/dist/do-oauth-client-provider-CwqK5SXm.js.map +1 -0
  34. package/dist/index-BUle9RiP.d.ts +58 -0
  35. package/dist/index-D3s0zwxa.d.ts +587 -0
  36. package/dist/index.d.ts +56 -550
  37. package/dist/index.js +7 -31
  38. package/dist/mcp/client.d.ts +4 -11
  39. package/dist/mcp/client.js +4 -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 +188 -92
  43. package/dist/mcp/index.js +1430 -1012
  44. package/dist/mcp/index.js.map +1 -1
  45. package/dist/mcp/x402.d.ts +34 -0
  46. package/dist/mcp/x402.js +198 -0
  47. package/dist/mcp/x402.js.map +1 -0
  48. package/dist/mcp-BwPscEiF.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-D9Ou_tyQ.d.ts +113 -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-faDkMCai.d.ts +39 -0
  59. package/dist/serializable.d.ts +7 -32
  60. package/dist/serializable.js +1 -1
  61. package/dist/src-CNAXL7wY.js +1182 -0
  62. package/dist/src-CNAXL7wY.js.map +1 -0
  63. package/package.json +71 -32
  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-MH46VMM4.js +0 -612
  71. package/dist/chunk-MH46VMM4.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-YDUDMOL6.js +0 -1296
  77. package/dist/chunk-YDUDMOL6.js.map +0 -1
  78. package/dist/client-CvaJdLQA.d.ts +0 -5015
  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 -1947
@@ -1,359 +1,812 @@
1
- import {
2
- autoTransformMessages
3
- } from "./chunk-UJVEAURM.js";
4
- import {
5
- Agent
6
- } from "./chunk-YDUDMOL6.js";
7
- import "./chunk-MH46VMM4.js";
8
- import "./chunk-LL2AFX7V.js";
9
- import "./chunk-QEVM4BVL.js";
10
- import "./chunk-AVYJQSLW.js";
1
+ import { t as MessageType } from "./ai-types-CrMqkwc_.js";
2
+ import "./client-B3SR12TQ.js";
3
+ import "./client-CFhjXCiO.js";
4
+ import "./do-oauth-client-provider-CwqK5SXm.js";
5
+ import { t as Agent } from "./src-CNAXL7wY.js";
6
+ import { r as autoTransformMessages } from "./ai-chat-v5-migration-BSiGZmYU.js";
7
+ import { nanoid } from "nanoid";
11
8
 
12
- // src/ai-chat-agent.ts
13
- var decoder = new TextDecoder();
9
+ //#region src/ai-chat-agent.ts
10
+ /** Number of chunks to buffer before flushing to SQLite */
11
+ const CHUNK_BUFFER_SIZE = 10;
12
+ /** Maximum buffer size to prevent memory issues on rapid reconnections */
13
+ const CHUNK_BUFFER_MAX_SIZE = 100;
14
+ /** Maximum age for a "streaming" stream before considering it stale (ms) - 5 minutes */
15
+ const STREAM_STALE_THRESHOLD_MS = 300 * 1e3;
16
+ /** Default cleanup interval for old streams (ms) - every 10 minutes */
17
+ const CLEANUP_INTERVAL_MS = 600 * 1e3;
18
+ /** Default age threshold for cleaning up completed streams (ms) - 24 hours */
19
+ const CLEANUP_AGE_THRESHOLD_MS = 1440 * 60 * 1e3;
20
+ const decoder = new TextDecoder();
21
+ /**
22
+ * Extension of Agent with built-in chat capabilities
23
+ * @template Env Environment type containing bindings
24
+ */
14
25
  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 (
26
+ constructor(ctx, env) {
27
+ super(ctx, env);
28
+ this._activeStreamId = null;
29
+ this._activeRequestId = null;
30
+ this._streamChunkIndex = 0;
31
+ this._chunkBuffer = [];
32
+ this._isFlushingChunks = false;
33
+ this._lastCleanupTime = 0;
34
+ this.sql`create table if not exists cf_ai_chat_agent_messages (
18
35
  id text primary key,
19
36
  message text not null,
20
37
  created_at datetime default current_timestamp
21
38
  )`;
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
- let fullReasoningText = "";
191
- const toolCalls = /* @__PURE__ */ new Map();
192
- try {
193
- while (true) {
194
- const { done, value } = await reader.read();
195
- if (done) {
196
- this._broadcastChatMessage({
197
- body: "",
198
- done: true,
199
- id,
200
- type: "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */
201
- });
202
- break;
203
- }
204
- const chunk = decoder.decode(value);
205
- const contentType = response.headers.get("content-type") || "";
206
- const isSSE = contentType.includes("text/event-stream");
207
- if (isSSE) {
208
- const lines = chunk.split("\n");
209
- for (const line of lines) {
210
- if (line.startsWith("data: ") && line !== "data: [DONE]") {
211
- try {
212
- const data = JSON.parse(line.slice(6));
213
- switch (data.type) {
214
- // SSE event signaling the tool input is ready. We track by
215
- // `toolCallId` so we can persist it as a tool part in the message.
216
- case "tool-input-available": {
217
- const { toolCallId, toolName, input } = data;
218
- toolCalls.set(toolCallId, {
219
- toolCallId,
220
- toolName,
221
- input,
222
- type: toolName ? `tool-${toolName}` : "dynamic-tool",
223
- state: "input-available"
224
- });
225
- break;
226
- }
227
- // SSE event signaling the tool output is ready. We should've
228
- // already received the input in a previous event so an entry
229
- // with `toolCallId` should already be present
230
- case "tool-output-available": {
231
- const { toolCallId, output, isError, errorText } = data;
232
- const toolPart = toolCalls.get(toolCallId);
233
- if (toolPart)
234
- toolCalls.set(toolCallId, {
235
- ...toolPart,
236
- output,
237
- isError,
238
- errorText,
239
- state: "output-available"
240
- });
241
- break;
242
- }
243
- case "error": {
244
- this._broadcastChatMessage({
245
- error: true,
246
- body: data.errorText ?? JSON.stringify(data),
247
- done: false,
248
- id,
249
- type: "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */
250
- });
251
- return;
252
- }
253
- case "reasoning-delta": {
254
- if (data.delta) fullReasoningText += data.delta;
255
- break;
256
- }
257
- case "text-delta": {
258
- if (data.delta) fullResponseText += data.delta;
259
- break;
260
- }
261
- }
262
- this._broadcastChatMessage({
263
- body: JSON.stringify(data),
264
- done: false,
265
- id,
266
- type: "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */
267
- });
268
- } catch (_e) {
269
- }
270
- }
271
- }
272
- } else {
273
- if (chunk.length > 0) {
274
- fullResponseText += chunk;
275
- this._broadcastChatMessage({
276
- body: JSON.stringify({ type: "text-delta", delta: chunk }),
277
- done: false,
278
- id,
279
- type: "cf_agent_use_chat_response" /* CF_AGENT_USE_CHAT_RESPONSE */
280
- });
281
- }
282
- }
283
- }
284
- } finally {
285
- reader.releaseLock();
286
- }
287
- const messageParts = [];
288
- Array.from(toolCalls.values()).forEach((t) => {
289
- messageParts.push(t);
290
- });
291
- if (fullReasoningText.trim()) {
292
- messageParts.push({ type: "reasoning", text: fullReasoningText });
293
- }
294
- if (fullResponseText.trim()) {
295
- messageParts.push({ type: "text", text: fullResponseText });
296
- }
297
- if (messageParts.length > 0) {
298
- await this.persistMessages([
299
- ...this.messages,
300
- {
301
- id: `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`,
302
- role: "assistant",
303
- parts: messageParts
304
- }
305
- ]);
306
- }
307
- });
308
- }
309
- /**
310
- * For the given message id, look up its associated AbortController
311
- * If the AbortController does not exist, create and store one in memory
312
- *
313
- * returns the AbortSignal associated with the AbortController
314
- */
315
- _getAbortSignal(id) {
316
- if (typeof id !== "string") {
317
- return void 0;
318
- }
319
- if (!this._chatMessageAbortControllers.has(id)) {
320
- this._chatMessageAbortControllers.set(id, new AbortController());
321
- }
322
- return this._chatMessageAbortControllers.get(id)?.signal;
323
- }
324
- /**
325
- * Remove an abort controller from the cache of pending message responses
326
- */
327
- _removeAbortController(id) {
328
- this._chatMessageAbortControllers.delete(id);
329
- }
330
- /**
331
- * Propagate an abort signal for any requests associated with the given message id
332
- */
333
- _cancelChatRequest(id) {
334
- if (this._chatMessageAbortControllers.has(id)) {
335
- const abortController = this._chatMessageAbortControllers.get(id);
336
- abortController?.abort();
337
- }
338
- }
339
- /**
340
- * Abort all pending requests and clear the cache of AbortControllers
341
- */
342
- _destroyAbortControllers() {
343
- for (const controller of this._chatMessageAbortControllers.values()) {
344
- controller?.abort();
345
- }
346
- this._chatMessageAbortControllers.clear();
347
- }
348
- /**
349
- * When the DO is destroyed, cancel all pending requests
350
- */
351
- async destroy() {
352
- this._destroyAbortControllers();
353
- await super.destroy();
354
- }
355
- };
356
- export {
357
- AIChatAgent
39
+ this.sql`create table if not exists cf_ai_chat_stream_chunks (
40
+ id text primary key,
41
+ stream_id text not null,
42
+ body text not null,
43
+ chunk_index integer not null,
44
+ created_at integer not null
45
+ )`;
46
+ this.sql`create table if not exists cf_ai_chat_stream_metadata (
47
+ id text primary key,
48
+ request_id text not null,
49
+ status text not null,
50
+ created_at integer not null,
51
+ completed_at integer
52
+ )`;
53
+ this.sql`create index if not exists idx_stream_chunks_stream_id
54
+ on cf_ai_chat_stream_chunks(stream_id, chunk_index)`;
55
+ this.messages = autoTransformMessages(this._loadMessagesFromDb());
56
+ this._chatMessageAbortControllers = /* @__PURE__ */ new Map();
57
+ this._restoreActiveStream();
58
+ const _onConnect = this.onConnect.bind(this);
59
+ this.onConnect = async (connection, ctx$1) => {
60
+ if (this._activeStreamId) this._notifyStreamResuming(connection);
61
+ return _onConnect(connection, ctx$1);
62
+ };
63
+ const _onMessage = this.onMessage.bind(this);
64
+ this.onMessage = async (connection, message) => {
65
+ if (typeof message === "string") {
66
+ let data;
67
+ try {
68
+ data = JSON.parse(message);
69
+ } catch (_error) {
70
+ return _onMessage(connection, message);
71
+ }
72
+ if (data.type === MessageType.CF_AGENT_USE_CHAT_REQUEST && data.init.method === "POST") {
73
+ const { body } = data.init;
74
+ const { messages } = JSON.parse(body);
75
+ const transformedMessages = autoTransformMessages(messages);
76
+ this._broadcastChatMessage({
77
+ messages: transformedMessages,
78
+ type: MessageType.CF_AGENT_CHAT_MESSAGES
79
+ }, [connection.id]);
80
+ await this.persistMessages(transformedMessages, [connection.id]);
81
+ this.observability?.emit({
82
+ displayMessage: "Chat message request",
83
+ id: data.id,
84
+ payload: {},
85
+ timestamp: Date.now(),
86
+ type: "message:request"
87
+ }, this.ctx);
88
+ const chatMessageId = data.id;
89
+ const abortSignal = this._getAbortSignal(chatMessageId);
90
+ return this._tryCatchChat(async () => {
91
+ const response = await this.onChatMessage(async (_finishResult) => {
92
+ this._removeAbortController(chatMessageId);
93
+ this.observability?.emit({
94
+ displayMessage: "Chat message response",
95
+ id: data.id,
96
+ payload: {},
97
+ timestamp: Date.now(),
98
+ type: "message:response"
99
+ }, this.ctx);
100
+ }, abortSignal ? { abortSignal } : void 0);
101
+ if (response) await this._reply(data.id, response);
102
+ else {
103
+ console.warn(`[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`);
104
+ this._broadcastChatMessage({
105
+ body: "No response was generated by the agent.",
106
+ done: true,
107
+ id: data.id,
108
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
109
+ }, [connection.id]);
110
+ }
111
+ });
112
+ }
113
+ if (data.type === MessageType.CF_AGENT_CHAT_CLEAR) {
114
+ this._destroyAbortControllers();
115
+ this.sql`delete from cf_ai_chat_agent_messages`;
116
+ this.sql`delete from cf_ai_chat_stream_chunks`;
117
+ this.sql`delete from cf_ai_chat_stream_metadata`;
118
+ this._activeStreamId = null;
119
+ this._activeRequestId = null;
120
+ this._streamChunkIndex = 0;
121
+ this.messages = [];
122
+ this._broadcastChatMessage({ type: MessageType.CF_AGENT_CHAT_CLEAR }, [connection.id]);
123
+ return;
124
+ }
125
+ if (data.type === MessageType.CF_AGENT_CHAT_MESSAGES) {
126
+ const transformedMessages = autoTransformMessages(data.messages);
127
+ await this.persistMessages(transformedMessages, [connection.id]);
128
+ return;
129
+ }
130
+ if (data.type === MessageType.CF_AGENT_CHAT_REQUEST_CANCEL) {
131
+ this._cancelChatRequest(data.id);
132
+ return;
133
+ }
134
+ if (data.type === MessageType.CF_AGENT_STREAM_RESUME_ACK) {
135
+ if (this._activeStreamId && this._activeRequestId && this._activeRequestId === data.id) this._sendStreamChunks(connection, this._activeStreamId, this._activeRequestId);
136
+ return;
137
+ }
138
+ }
139
+ return _onMessage(connection, message);
140
+ };
141
+ }
142
+ /**
143
+ * Restore active stream state if the agent was restarted during streaming.
144
+ * Called during construction to recover any interrupted streams.
145
+ * Validates stream freshness to avoid sending stale resume notifications.
146
+ * @internal Protected for testing purposes.
147
+ */
148
+ _restoreActiveStream() {
149
+ const activeStreams = this.sql`
150
+ select * from cf_ai_chat_stream_metadata
151
+ where status = 'streaming'
152
+ order by created_at desc
153
+ limit 1
154
+ `;
155
+ if (activeStreams && activeStreams.length > 0) {
156
+ const stream = activeStreams[0];
157
+ const streamAge = Date.now() - stream.created_at;
158
+ if (streamAge > STREAM_STALE_THRESHOLD_MS) {
159
+ this.sql`delete from cf_ai_chat_stream_chunks where stream_id = ${stream.id}`;
160
+ this.sql`delete from cf_ai_chat_stream_metadata where id = ${stream.id}`;
161
+ console.warn(`[AIChatAgent] Deleted stale stream ${stream.id} (age: ${Math.round(streamAge / 1e3)}s)`);
162
+ return;
163
+ }
164
+ this._activeStreamId = stream.id;
165
+ this._activeRequestId = stream.request_id;
166
+ const lastChunk = this.sql`
167
+ select max(chunk_index) as max_index
168
+ from cf_ai_chat_stream_chunks
169
+ where stream_id = ${this._activeStreamId}
170
+ `;
171
+ this._streamChunkIndex = lastChunk && lastChunk[0]?.max_index != null ? lastChunk[0].max_index + 1 : 0;
172
+ }
173
+ }
174
+ /**
175
+ * Notify a connection about an active stream that can be resumed.
176
+ * The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
177
+ * Uses in-memory state for request ID - no extra DB lookup needed.
178
+ * @param connection - The WebSocket connection to notify
179
+ */
180
+ _notifyStreamResuming(connection) {
181
+ if (!this._activeStreamId || !this._activeRequestId) return;
182
+ connection.send(JSON.stringify({
183
+ type: MessageType.CF_AGENT_STREAM_RESUMING,
184
+ id: this._activeRequestId
185
+ }));
186
+ }
187
+ /**
188
+ * Send stream chunks to a connection after receiving ACK.
189
+ * @param connection - The WebSocket connection
190
+ * @param streamId - The stream to replay
191
+ * @param requestId - The original request ID
192
+ */
193
+ _sendStreamChunks(connection, streamId, requestId) {
194
+ this._flushChunkBuffer();
195
+ const chunks = this.sql`
196
+ select * from cf_ai_chat_stream_chunks
197
+ where stream_id = ${streamId}
198
+ order by chunk_index asc
199
+ `;
200
+ for (const chunk of chunks || []) connection.send(JSON.stringify({
201
+ body: chunk.body,
202
+ done: false,
203
+ id: requestId,
204
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
205
+ }));
206
+ if (this._activeStreamId !== streamId) connection.send(JSON.stringify({
207
+ body: "",
208
+ done: true,
209
+ id: requestId,
210
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
211
+ }));
212
+ }
213
+ /**
214
+ * Buffer a stream chunk for batch write to SQLite.
215
+ * @param streamId - The stream this chunk belongs to
216
+ * @param body - The serialized chunk body
217
+ * @internal Protected for testing purposes.
218
+ */
219
+ _storeStreamChunk(streamId, body) {
220
+ if (this._chunkBuffer.length >= CHUNK_BUFFER_MAX_SIZE) this._flushChunkBuffer();
221
+ this._chunkBuffer.push({
222
+ id: nanoid(),
223
+ streamId,
224
+ body,
225
+ index: this._streamChunkIndex
226
+ });
227
+ this._streamChunkIndex++;
228
+ if (this._chunkBuffer.length >= CHUNK_BUFFER_SIZE) this._flushChunkBuffer();
229
+ }
230
+ /**
231
+ * Flush buffered chunks to SQLite in a single batch.
232
+ * Uses a lock to prevent concurrent flush operations.
233
+ * @internal Protected for testing purposes.
234
+ */
235
+ _flushChunkBuffer() {
236
+ if (this._isFlushingChunks || this._chunkBuffer.length === 0) return;
237
+ this._isFlushingChunks = true;
238
+ try {
239
+ const chunks = this._chunkBuffer;
240
+ this._chunkBuffer = [];
241
+ const now = Date.now();
242
+ for (const chunk of chunks) this.sql`
243
+ insert into cf_ai_chat_stream_chunks (id, stream_id, body, chunk_index, created_at)
244
+ values (${chunk.id}, ${chunk.streamId}, ${chunk.body}, ${chunk.index}, ${now})
245
+ `;
246
+ } finally {
247
+ this._isFlushingChunks = false;
248
+ }
249
+ }
250
+ /**
251
+ * Start tracking a new stream for resumable streaming.
252
+ * Creates metadata entry in SQLite and sets up tracking state.
253
+ * @param requestId - The unique ID of the chat request
254
+ * @returns The generated stream ID
255
+ * @internal Protected for testing purposes.
256
+ */
257
+ _startStream(requestId) {
258
+ this._flushChunkBuffer();
259
+ const streamId = nanoid();
260
+ this._activeStreamId = streamId;
261
+ this._activeRequestId = requestId;
262
+ this._streamChunkIndex = 0;
263
+ this.sql`
264
+ insert into cf_ai_chat_stream_metadata (id, request_id, status, created_at)
265
+ values (${streamId}, ${requestId}, 'streaming', ${Date.now()})
266
+ `;
267
+ return streamId;
268
+ }
269
+ /**
270
+ * Mark a stream as completed and flush any pending chunks.
271
+ * @param streamId - The stream to mark as completed
272
+ * @internal Protected for testing purposes.
273
+ */
274
+ _completeStream(streamId) {
275
+ this._flushChunkBuffer();
276
+ this.sql`
277
+ update cf_ai_chat_stream_metadata
278
+ set status = 'completed', completed_at = ${Date.now()}
279
+ where id = ${streamId}
280
+ `;
281
+ this._activeStreamId = null;
282
+ this._activeRequestId = null;
283
+ this._streamChunkIndex = 0;
284
+ this._maybeCleanupOldStreams();
285
+ }
286
+ /**
287
+ * Clean up old completed streams if enough time has passed since last cleanup.
288
+ * This prevents database growth while avoiding cleanup overhead on every stream completion.
289
+ */
290
+ _maybeCleanupOldStreams() {
291
+ const now = Date.now();
292
+ if (now - this._lastCleanupTime < CLEANUP_INTERVAL_MS) return;
293
+ this._lastCleanupTime = now;
294
+ const cutoff = now - CLEANUP_AGE_THRESHOLD_MS;
295
+ this.sql`
296
+ delete from cf_ai_chat_stream_chunks
297
+ where stream_id in (
298
+ select id from cf_ai_chat_stream_metadata
299
+ where status = 'completed' and completed_at < ${cutoff}
300
+ )
301
+ `;
302
+ this.sql`
303
+ delete from cf_ai_chat_stream_metadata
304
+ where status = 'completed' and completed_at < ${cutoff}
305
+ `;
306
+ }
307
+ _broadcastChatMessage(message, exclude) {
308
+ this.broadcast(JSON.stringify(message), exclude);
309
+ }
310
+ _loadMessagesFromDb() {
311
+ return (this.sql`select * from cf_ai_chat_agent_messages order by created_at` || []).map((row) => {
312
+ try {
313
+ return JSON.parse(row.message);
314
+ } catch (error) {
315
+ console.error(`Failed to parse message ${row.id}:`, error);
316
+ return null;
317
+ }
318
+ }).filter((msg) => msg !== null);
319
+ }
320
+ async onRequest(request) {
321
+ return this._tryCatchChat(async () => {
322
+ if (new URL(request.url).pathname.endsWith("/get-messages")) {
323
+ const messages = this._loadMessagesFromDb();
324
+ return Response.json(messages);
325
+ }
326
+ return super.onRequest(request);
327
+ });
328
+ }
329
+ async _tryCatchChat(fn) {
330
+ try {
331
+ return await fn();
332
+ } catch (e) {
333
+ throw this.onError(e);
334
+ }
335
+ }
336
+ /**
337
+ * Handle incoming chat messages and generate a response
338
+ * @param onFinish Callback to be called when the response is finished
339
+ * @param options.signal A signal to pass to any child requests which can be used to cancel them
340
+ * @returns Response to send to the client or undefined
341
+ */
342
+ async onChatMessage(onFinish, options) {
343
+ throw new Error("recieved a chat message, override onChatMessage and return a Response to send to the client");
344
+ }
345
+ /**
346
+ * Save messages on the server side
347
+ * @param messages Chat messages to save
348
+ */
349
+ async saveMessages(messages) {
350
+ await this.persistMessages(messages);
351
+ await this._tryCatchChat(async () => {
352
+ const response = await this.onChatMessage(() => {});
353
+ if (response) this._reply(crypto.randomUUID(), response);
354
+ });
355
+ }
356
+ async persistMessages(messages, excludeBroadcastIds = []) {
357
+ for (const message of messages) this.sql`
358
+ insert into cf_ai_chat_agent_messages (id, message)
359
+ values (${message.id}, ${JSON.stringify(message)})
360
+ on conflict(id) do update set message = excluded.message
361
+ `;
362
+ this.messages = autoTransformMessages(this._loadMessagesFromDb());
363
+ this._broadcastChatMessage({
364
+ messages,
365
+ type: MessageType.CF_AGENT_CHAT_MESSAGES
366
+ }, excludeBroadcastIds);
367
+ }
368
+ async _reply(id, response) {
369
+ return this._tryCatchChat(async () => {
370
+ if (!response.body) {
371
+ this._broadcastChatMessage({
372
+ body: "",
373
+ done: true,
374
+ id,
375
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
376
+ });
377
+ return;
378
+ }
379
+ const streamId = this._startStream(id);
380
+ const { getToolName, isToolUIPart, parsePartialJson } = await import("ai");
381
+ const reader = response.body.getReader();
382
+ const message = {
383
+ id: `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`,
384
+ role: "assistant",
385
+ parts: []
386
+ };
387
+ let activeTextParts = {};
388
+ let activeReasoningParts = {};
389
+ const partialToolCalls = {};
390
+ function updateDynamicToolPart(options) {
391
+ const part = message.parts.find((part$1) => part$1.type === "dynamic-tool" && part$1.toolCallId === options.toolCallId);
392
+ const anyOptions = options;
393
+ const anyPart = part;
394
+ if (part != null) {
395
+ part.state = options.state;
396
+ anyPart.toolName = options.toolName;
397
+ anyPart.input = anyOptions.input;
398
+ anyPart.output = anyOptions.output;
399
+ anyPart.errorText = anyOptions.errorText;
400
+ anyPart.rawInput = anyOptions.rawInput ?? anyPart.rawInput;
401
+ anyPart.preliminary = anyOptions.preliminary;
402
+ if (anyOptions.providerMetadata != null && part.state === "input-available") part.callProviderMetadata = anyOptions.providerMetadata;
403
+ } else message.parts.push({
404
+ type: "dynamic-tool",
405
+ toolName: options.toolName,
406
+ toolCallId: options.toolCallId,
407
+ state: options.state,
408
+ input: anyOptions.input,
409
+ output: anyOptions.output,
410
+ errorText: anyOptions.errorText,
411
+ preliminary: anyOptions.preliminary,
412
+ ...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}
413
+ });
414
+ }
415
+ function updateToolPart(options) {
416
+ const part = message.parts.find((part$1) => isToolUIPart(part$1) && part$1.toolCallId === options.toolCallId);
417
+ const anyOptions = options;
418
+ const anyPart = part;
419
+ if (part != null) {
420
+ part.state = options.state;
421
+ anyPart.input = anyOptions.input;
422
+ anyPart.output = anyOptions.output;
423
+ anyPart.errorText = anyOptions.errorText;
424
+ anyPart.rawInput = anyOptions.rawInput;
425
+ anyPart.preliminary = anyOptions.preliminary;
426
+ anyPart.providerExecuted = anyOptions.providerExecuted ?? part.providerExecuted;
427
+ if (anyOptions.providerMetadata != null && part.state === "input-available") part.callProviderMetadata = anyOptions.providerMetadata;
428
+ } else message.parts.push({
429
+ type: `tool-${options.toolName}`,
430
+ toolCallId: options.toolCallId,
431
+ state: options.state,
432
+ input: anyOptions.input,
433
+ output: anyOptions.output,
434
+ rawInput: anyOptions.rawInput,
435
+ errorText: anyOptions.errorText,
436
+ providerExecuted: anyOptions.providerExecuted,
437
+ preliminary: anyOptions.preliminary,
438
+ ...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}
439
+ });
440
+ }
441
+ async function updateMessageMetadata(metadata) {
442
+ if (metadata != null) message.metadata = message.metadata != null ? {
443
+ ...message.metadata,
444
+ ...metadata
445
+ } : metadata;
446
+ }
447
+ let streamCompleted = false;
448
+ try {
449
+ while (true) {
450
+ const { done, value } = await reader.read();
451
+ if (done) {
452
+ this._completeStream(streamId);
453
+ streamCompleted = true;
454
+ this._broadcastChatMessage({
455
+ body: "",
456
+ done: true,
457
+ id,
458
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
459
+ });
460
+ break;
461
+ }
462
+ const chunk = decoder.decode(value);
463
+ if ((response.headers.get("content-type") || "").includes("text/event-stream")) {
464
+ const lines = chunk.split("\n");
465
+ for (const line of lines) if (line.startsWith("data: ") && line !== "data: [DONE]") try {
466
+ const data = JSON.parse(line.slice(6));
467
+ switch (data.type) {
468
+ case "text-start": {
469
+ const textPart = {
470
+ type: "text",
471
+ text: "",
472
+ providerMetadata: data.providerMetadata,
473
+ state: "streaming"
474
+ };
475
+ activeTextParts[data.id] = textPart;
476
+ message.parts.push(textPart);
477
+ break;
478
+ }
479
+ case "text-delta": {
480
+ const textPart = activeTextParts[data.id];
481
+ textPart.text += data.delta;
482
+ textPart.providerMetadata = data.providerMetadata ?? textPart.providerMetadata;
483
+ break;
484
+ }
485
+ case "text-end": {
486
+ const textPart = activeTextParts[data.id];
487
+ textPart.state = "done";
488
+ textPart.providerMetadata = data.providerMetadata ?? textPart.providerMetadata;
489
+ delete activeTextParts[data.id];
490
+ break;
491
+ }
492
+ case "reasoning-start": {
493
+ const reasoningPart = {
494
+ type: "reasoning",
495
+ text: "",
496
+ providerMetadata: data.providerMetadata,
497
+ state: "streaming"
498
+ };
499
+ activeReasoningParts[data.id] = reasoningPart;
500
+ message.parts.push(reasoningPart);
501
+ break;
502
+ }
503
+ case "reasoning-delta": {
504
+ const reasoningPart = activeReasoningParts[data.id];
505
+ reasoningPart.text += data.delta;
506
+ reasoningPart.providerMetadata = data.providerMetadata ?? reasoningPart.providerMetadata;
507
+ break;
508
+ }
509
+ case "reasoning-end": {
510
+ const reasoningPart = activeReasoningParts[data.id];
511
+ reasoningPart.providerMetadata = data.providerMetadata ?? reasoningPart.providerMetadata;
512
+ reasoningPart.state = "done";
513
+ delete activeReasoningParts[data.id];
514
+ break;
515
+ }
516
+ case "file":
517
+ message.parts.push({
518
+ type: "file",
519
+ mediaType: data.mediaType,
520
+ url: data.url
521
+ });
522
+ break;
523
+ case "source-url":
524
+ message.parts.push({
525
+ type: "source-url",
526
+ sourceId: data.sourceId,
527
+ url: data.url,
528
+ title: data.title,
529
+ providerMetadata: data.providerMetadata
530
+ });
531
+ break;
532
+ case "source-document":
533
+ message.parts.push({
534
+ type: "source-document",
535
+ sourceId: data.sourceId,
536
+ mediaType: data.mediaType,
537
+ title: data.title,
538
+ filename: data.filename,
539
+ providerMetadata: data.providerMetadata
540
+ });
541
+ break;
542
+ case "tool-input-start": {
543
+ const toolInvocations = message.parts.filter(isToolUIPart);
544
+ partialToolCalls[data.toolCallId] = {
545
+ text: "",
546
+ toolName: data.toolName,
547
+ index: toolInvocations.length,
548
+ dynamic: data.dynamic
549
+ };
550
+ if (data.dynamic) updateDynamicToolPart({
551
+ toolCallId: data.toolCallId,
552
+ toolName: data.toolName,
553
+ state: "input-streaming",
554
+ input: void 0
555
+ });
556
+ else updateToolPart({
557
+ toolCallId: data.toolCallId,
558
+ toolName: data.toolName,
559
+ state: "input-streaming",
560
+ input: void 0
561
+ });
562
+ break;
563
+ }
564
+ case "tool-input-delta": {
565
+ const partialToolCall = partialToolCalls[data.toolCallId];
566
+ partialToolCall.text += data.inputTextDelta;
567
+ const partialArgs = (await parsePartialJson(partialToolCall.text)).value;
568
+ if (partialToolCall.dynamic) updateDynamicToolPart({
569
+ toolCallId: data.toolCallId,
570
+ toolName: partialToolCall.toolName,
571
+ state: "input-streaming",
572
+ input: partialArgs
573
+ });
574
+ else updateToolPart({
575
+ toolCallId: data.toolCallId,
576
+ toolName: partialToolCall.toolName,
577
+ state: "input-streaming",
578
+ input: partialArgs
579
+ });
580
+ break;
581
+ }
582
+ case "tool-input-available":
583
+ if (data.dynamic) updateDynamicToolPart({
584
+ toolCallId: data.toolCallId,
585
+ toolName: data.toolName,
586
+ state: "input-available",
587
+ input: data.input,
588
+ providerMetadata: data.providerMetadata
589
+ });
590
+ else updateToolPart({
591
+ toolCallId: data.toolCallId,
592
+ toolName: data.toolName,
593
+ state: "input-available",
594
+ input: data.input,
595
+ providerExecuted: data.providerExecuted,
596
+ providerMetadata: data.providerMetadata
597
+ });
598
+ break;
599
+ case "tool-input-error":
600
+ if (data.dynamic) updateDynamicToolPart({
601
+ toolCallId: data.toolCallId,
602
+ toolName: data.toolName,
603
+ state: "output-error",
604
+ input: data.input,
605
+ errorText: data.errorText,
606
+ providerMetadata: data.providerMetadata
607
+ });
608
+ else updateToolPart({
609
+ toolCallId: data.toolCallId,
610
+ toolName: data.toolName,
611
+ state: "output-error",
612
+ input: void 0,
613
+ rawInput: data.input,
614
+ errorText: data.errorText,
615
+ providerExecuted: data.providerExecuted,
616
+ providerMetadata: data.providerMetadata
617
+ });
618
+ break;
619
+ case "tool-output-available":
620
+ if (data.dynamic) {
621
+ const toolInvocation = message.parts.filter((part) => part.type === "dynamic-tool").find((invocation) => invocation.toolCallId === data.toolCallId);
622
+ if (!toolInvocation) throw new Error("Tool invocation not found");
623
+ updateDynamicToolPart({
624
+ toolCallId: data.toolCallId,
625
+ toolName: toolInvocation.toolName,
626
+ state: "output-available",
627
+ input: toolInvocation.input,
628
+ output: data.output,
629
+ preliminary: data.preliminary
630
+ });
631
+ } else {
632
+ const toolInvocation = message.parts.filter(isToolUIPart).find((invocation) => invocation.toolCallId === data.toolCallId);
633
+ if (!toolInvocation) throw new Error("Tool invocation not found");
634
+ updateToolPart({
635
+ toolCallId: data.toolCallId,
636
+ toolName: getToolName(toolInvocation),
637
+ state: "output-available",
638
+ input: toolInvocation.input,
639
+ output: data.output,
640
+ providerExecuted: data.providerExecuted,
641
+ preliminary: data.preliminary
642
+ });
643
+ }
644
+ break;
645
+ case "tool-output-error":
646
+ if (data.dynamic) {
647
+ const toolInvocation = message.parts.filter((part) => part.type === "dynamic-tool").find((invocation) => invocation.toolCallId === data.toolCallId);
648
+ if (!toolInvocation) throw new Error("Tool invocation not found");
649
+ updateDynamicToolPart({
650
+ toolCallId: data.toolCallId,
651
+ toolName: toolInvocation.toolName,
652
+ state: "output-error",
653
+ input: toolInvocation.input,
654
+ errorText: data.errorText
655
+ });
656
+ } else {
657
+ const toolInvocation = message.parts.filter(isToolUIPart).find((invocation) => invocation.toolCallId === data.toolCallId);
658
+ if (!toolInvocation) throw new Error("Tool invocation not found");
659
+ updateToolPart({
660
+ toolCallId: data.toolCallId,
661
+ toolName: getToolName(toolInvocation),
662
+ state: "output-error",
663
+ input: toolInvocation.input,
664
+ rawInput: "rawInput" in toolInvocation ? toolInvocation.rawInput : void 0,
665
+ errorText: data.errorText
666
+ });
667
+ }
668
+ break;
669
+ case "start-step":
670
+ message.parts.push({ type: "step-start" });
671
+ break;
672
+ case "finish-step":
673
+ activeTextParts = {};
674
+ activeReasoningParts = {};
675
+ break;
676
+ case "start":
677
+ if (data.messageId != null) message.id = data.messageId;
678
+ await updateMessageMetadata(data.messageMetadata);
679
+ break;
680
+ case "finish":
681
+ await updateMessageMetadata(data.messageMetadata);
682
+ break;
683
+ case "message-metadata":
684
+ await updateMessageMetadata(data.messageMetadata);
685
+ break;
686
+ case "error":
687
+ this._broadcastChatMessage({
688
+ error: true,
689
+ body: data.errorText ?? JSON.stringify(data),
690
+ done: false,
691
+ id,
692
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
693
+ });
694
+ break;
695
+ }
696
+ let eventToSend = data;
697
+ if (data.type === "finish" && "finishReason" in data) {
698
+ const { finishReason, ...rest } = data;
699
+ eventToSend = {
700
+ ...rest,
701
+ type: "finish",
702
+ messageMetadata: { finishReason }
703
+ };
704
+ }
705
+ const chunkBody = JSON.stringify(eventToSend);
706
+ this._storeStreamChunk(streamId, chunkBody);
707
+ this._broadcastChatMessage({
708
+ body: chunkBody,
709
+ done: false,
710
+ id,
711
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
712
+ });
713
+ } catch (_error) {}
714
+ } else if (chunk.length > 0) {
715
+ message.parts.push({
716
+ type: "text",
717
+ text: chunk
718
+ });
719
+ const chunkBody = JSON.stringify({
720
+ type: "text-delta",
721
+ delta: chunk
722
+ });
723
+ this._storeStreamChunk(streamId, chunkBody);
724
+ this._broadcastChatMessage({
725
+ body: chunkBody,
726
+ done: false,
727
+ id,
728
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
729
+ });
730
+ }
731
+ }
732
+ } catch (error) {
733
+ if (!streamCompleted) {
734
+ this._markStreamError(streamId);
735
+ this._broadcastChatMessage({
736
+ body: error instanceof Error ? error.message : "Stream error",
737
+ done: true,
738
+ error: true,
739
+ id,
740
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
741
+ });
742
+ }
743
+ throw error;
744
+ } finally {
745
+ reader.releaseLock();
746
+ }
747
+ if (message.parts.length > 0) await this.persistMessages([...this.messages, message]);
748
+ });
749
+ }
750
+ /**
751
+ * Mark a stream as errored and clean up state.
752
+ * @param streamId - The stream to mark as errored
753
+ * @internal Protected for testing purposes.
754
+ */
755
+ _markStreamError(streamId) {
756
+ this._flushChunkBuffer();
757
+ this.sql`
758
+ update cf_ai_chat_stream_metadata
759
+ set status = 'error', completed_at = ${Date.now()}
760
+ where id = ${streamId}
761
+ `;
762
+ this._activeStreamId = null;
763
+ this._activeRequestId = null;
764
+ this._streamChunkIndex = 0;
765
+ }
766
+ /**
767
+ * For the given message id, look up its associated AbortController
768
+ * If the AbortController does not exist, create and store one in memory
769
+ *
770
+ * returns the AbortSignal associated with the AbortController
771
+ */
772
+ _getAbortSignal(id) {
773
+ if (typeof id !== "string") return;
774
+ if (!this._chatMessageAbortControllers.has(id)) this._chatMessageAbortControllers.set(id, new AbortController());
775
+ return this._chatMessageAbortControllers.get(id)?.signal;
776
+ }
777
+ /**
778
+ * Remove an abort controller from the cache of pending message responses
779
+ */
780
+ _removeAbortController(id) {
781
+ this._chatMessageAbortControllers.delete(id);
782
+ }
783
+ /**
784
+ * Propagate an abort signal for any requests associated with the given message id
785
+ */
786
+ _cancelChatRequest(id) {
787
+ if (this._chatMessageAbortControllers.has(id)) this._chatMessageAbortControllers.get(id)?.abort();
788
+ }
789
+ /**
790
+ * Abort all pending requests and clear the cache of AbortControllers
791
+ */
792
+ _destroyAbortControllers() {
793
+ for (const controller of this._chatMessageAbortControllers.values()) controller?.abort();
794
+ this._chatMessageAbortControllers.clear();
795
+ }
796
+ /**
797
+ * When the DO is destroyed, cancel all pending requests and clean up resources
798
+ */
799
+ async destroy() {
800
+ this._destroyAbortControllers();
801
+ this._flushChunkBuffer();
802
+ this.sql`drop table if exists cf_ai_chat_stream_chunks`;
803
+ this.sql`drop table if exists cf_ai_chat_stream_metadata`;
804
+ this._activeStreamId = null;
805
+ this._activeRequestId = null;
806
+ await super.destroy();
807
+ }
358
808
  };
809
+
810
+ //#endregion
811
+ export { AIChatAgent };
359
812
  //# sourceMappingURL=ai-chat-agent.js.map