agents 0.0.0-feef082 → 0.0.0-ff45307
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.
- package/README.md +130 -6
- package/dist/ai-chat-agent.d.ts +99 -19
- package/dist/ai-chat-agent.js +804 -329
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-chat-v5-migration-BSiGZmYU.js +155 -0
- package/dist/ai-chat-v5-migration-BSiGZmYU.js.map +1 -0
- package/dist/ai-chat-v5-migration.d.ts +7 -4
- package/dist/ai-chat-v5-migration.js +3 -19
- package/dist/ai-react.d.ts +25 -23
- package/dist/ai-react.js +409 -304
- package/dist/ai-react.js.map +1 -1
- package/dist/ai-types-81H_-Uxh.d.ts +103 -0
- package/dist/ai-types-CrMqkwc_.js +24 -0
- package/dist/ai-types-CrMqkwc_.js.map +1 -0
- package/dist/ai-types.d.ts +6 -91
- package/dist/ai-types.js +3 -7
- package/dist/cli/index.d.ts +1 -0
- package/dist/cli/index.js +28 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/client-B3SR12TQ.js +117 -0
- package/dist/client-B3SR12TQ.js.map +1 -0
- package/dist/client-BAQA84dr.d.ts +104 -0
- package/dist/client-CFhjXCiO.js +1093 -0
- package/dist/client-CFhjXCiO.js.map +1 -0
- package/dist/client-CwqTTb-B.d.ts +833 -0
- package/dist/client.d.ts +11 -92
- package/dist/client.js +4 -12
- package/dist/codemode/ai.d.ts +27 -0
- package/dist/codemode/ai.js +151 -0
- package/dist/codemode/ai.js.map +1 -0
- package/dist/do-oauth-client-provider-C2CHH5x-.d.ts +55 -0
- package/dist/do-oauth-client-provider-CwqK5SXm.js +94 -0
- package/dist/do-oauth-client-provider-CwqK5SXm.js.map +1 -0
- package/dist/index-BUle9RiP.d.ts +58 -0
- package/dist/index-DJ4vV2-x.d.ts +587 -0
- package/dist/index.d.ts +56 -541
- package/dist/index.js +7 -31
- package/dist/mcp/client.d.ts +4 -11
- package/dist/mcp/client.js +4 -9
- package/dist/mcp/do-oauth-client-provider.d.ts +2 -42
- package/dist/mcp/do-oauth-client-provider.js +3 -7
- package/dist/mcp/index.d.ts +190 -109
- package/dist/mcp/index.js +1434 -943
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/x402.d.ts +34 -0
- package/dist/mcp/x402.js +198 -0
- package/dist/mcp/x402.js.map +1 -0
- package/dist/mcp-BwPscEiF.d.ts +61 -0
- package/dist/observability/index.d.ts +3 -46
- package/dist/observability/index.js +7 -11
- package/dist/react-w4GT20p4.d.ts +113 -0
- package/dist/react.d.ts +10 -123
- package/dist/react.js +183 -112
- package/dist/react.js.map +1 -1
- package/dist/schedule.d.ts +13 -10
- package/dist/schedule.js +43 -31
- package/dist/schedule.js.map +1 -1
- package/dist/serializable-faDkMCai.d.ts +39 -0
- package/dist/serializable.d.ts +7 -32
- package/dist/serializable.js +1 -1
- package/dist/src-tXpYCgas.js +1184 -0
- package/dist/src-tXpYCgas.js.map +1 -0
- package/package.json +72 -31
- package/dist/ai-chat-v5-migration.js.map +0 -1
- package/dist/ai-types.js.map +0 -1
- package/dist/chunk-AVYJQSLW.js +0 -17
- package/dist/chunk-AVYJQSLW.js.map +0 -1
- package/dist/chunk-LL2AFX7V.js +0 -109
- package/dist/chunk-LL2AFX7V.js.map +0 -1
- package/dist/chunk-PNF6ZMUA.js +0 -1296
- package/dist/chunk-PNF6ZMUA.js.map +0 -1
- package/dist/chunk-QEVM4BVL.js +0 -116
- package/dist/chunk-QEVM4BVL.js.map +0 -1
- package/dist/chunk-UJVEAURM.js +0 -150
- package/dist/chunk-UJVEAURM.js.map +0 -1
- package/dist/chunk-VYENMKFS.js +0 -612
- package/dist/chunk-VYENMKFS.js.map +0 -1
- package/dist/client-B9tFv5gX.d.ts +0 -4607
- package/dist/client.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/mcp/client.js.map +0 -1
- package/dist/mcp/do-oauth-client-provider.js.map +0 -1
- package/dist/observability/index.js.map +0 -1
- package/dist/serializable.js.map +0 -1
- package/src/index.ts +0 -1938
package/dist/ai-chat-agent.js
CHANGED
|
@@ -1,337 +1,812 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import
|
|
5
|
-
|
|
6
|
-
} from "./
|
|
7
|
-
import "
|
|
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-tXpYCgas.js";
|
|
6
|
+
import { r as autoTransformMessages } from "./ai-chat-v5-migration-BSiGZmYU.js";
|
|
7
|
+
import { nanoid } from "nanoid";
|
|
11
8
|
|
|
12
|
-
|
|
13
|
-
|
|
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
|
-
|
|
16
|
-
|
|
17
|
-
|
|
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
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
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
|
+
}
|
|
336
808
|
};
|
|
809
|
+
|
|
810
|
+
//#endregion
|
|
811
|
+
export { AIChatAgent };
|
|
337
812
|
//# sourceMappingURL=ai-chat-agent.js.map
|