agents 0.0.0-d045755 → 0.0.0-d08612f

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