agents 0.0.0-f5b5854 → 0.0.0-f5ccde3

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