@cloudflare/ai-chat 0.0.8 → 0.1.1
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/CHANGELOG.md +97 -0
- package/README.md +225 -459
- package/dist/ai-chat-v5-migration.d.ts +9 -9
- package/dist/ai-chat-v5-migration.js +25 -4
- package/dist/ai-chat-v5-migration.js.map +1 -1
- package/dist/experimental/forever.d.ts +29 -0
- package/dist/experimental/forever.js +55 -0
- package/dist/experimental/forever.js.map +1 -0
- package/dist/index.d.ts +114 -76
- package/dist/index.js +745 -629
- package/dist/index.js.map +1 -1
- package/dist/message-builder-Bwc_Umye.js +231 -0
- package/dist/message-builder-Bwc_Umye.js.map +1 -0
- package/dist/react.d.ts +27 -9
- package/dist/react.js +244 -258
- package/dist/react.js.map +1 -1
- package/dist/resumable-stream-DqXxQVjf.d.ts +103 -0
- package/dist/types.d.ts +16 -4
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -1
- package/e2e/chat.spec.ts +1703 -0
- package/e2e/client-tools.spec.ts +504 -0
- package/e2e/llm.spec.ts +637 -0
- package/e2e/playwright.config.ts +24 -0
- package/e2e/worker.ts +176 -0
- package/e2e/wrangler.jsonc +23 -0
- package/package.json +13 -5
- package/scripts/build.ts +2 -1
- package/src/ai-chat-v5-migration.ts +32 -5
- package/src/experimental/forever.ts +66 -0
- package/src/index.ts +831 -1137
- package/src/message-builder.ts +384 -0
- package/src/react-tests/use-agent-chat.test.tsx +738 -2
- package/src/react.tsx +385 -461
- package/src/resumable-stream.ts +441 -0
- package/src/tests/chat-context.test.ts +1 -1
- package/src/tests/chat-persistence.test.ts +5 -5
- package/src/tests/clear-history.test.ts +132 -0
- package/src/tests/client-tool-duplicate-message.test.ts +457 -14
- package/src/tests/client-tools-broadcast.test.ts +2 -2
- package/src/tests/client-tools-continuation.test.ts +3 -3
- package/src/tests/client-tools-reconnect.test.ts +143 -0
- package/src/tests/custom-body-continuation.test.ts +309 -0
- package/src/tests/custom-body.test.ts +3 -3
- package/src/tests/destroy.test.ts +57 -0
- package/src/tests/get-messages-endpoint.test.ts +79 -0
- package/src/tests/max-persisted-messages.test.ts +201 -0
- package/src/tests/merge-server-state.test.ts +106 -0
- package/src/tests/message-builder.test.ts +808 -0
- package/src/tests/migration.test.ts +282 -0
- package/src/tests/non-sse-response.test.ts +2 -2
- package/src/tests/onfinish-cleanup.test.ts +362 -0
- package/src/tests/plaintext-response.test.ts +87 -0
- package/src/tests/resumable-streaming.test.ts +220 -14
- package/src/tests/row-size-guard.test.ts +374 -0
- package/src/tests/sanitize-messages.test.ts +215 -0
- package/src/tests/validate-messages.test.ts +269 -0
- package/src/tests/worker.ts +59 -24
- package/src/types.ts +17 -1
- package/src/ws-chat-transport.ts +203 -0
package/dist/index.js
CHANGED
|
@@ -1,10 +1,326 @@
|
|
|
1
1
|
import { MessageType } from "./types.js";
|
|
2
2
|
import { autoTransformMessages } from "./ai-chat-v5-migration.js";
|
|
3
|
+
import { t as applyChunkToParts } from "./message-builder-Bwc_Umye.js";
|
|
3
4
|
import { jsonSchema, tool } from "ai";
|
|
4
5
|
import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
|
|
5
6
|
import { nanoid } from "nanoid";
|
|
6
7
|
|
|
8
|
+
//#region src/resumable-stream.ts
|
|
9
|
+
/**
|
|
10
|
+
* ResumableStream: Standalone class for buffering, persisting, and replaying
|
|
11
|
+
* stream chunks in SQLite. Extracted from AIChatAgent to separate concerns.
|
|
12
|
+
*
|
|
13
|
+
* Handles:
|
|
14
|
+
* - Chunk buffering (batched writes to SQLite for performance)
|
|
15
|
+
* - Stream lifecycle (start, complete, error)
|
|
16
|
+
* - Chunk replay for reconnecting clients
|
|
17
|
+
* - Stale stream cleanup
|
|
18
|
+
* - Active stream restoration after agent restart
|
|
19
|
+
*/
|
|
20
|
+
/** Number of chunks to buffer before flushing to SQLite */
|
|
21
|
+
const CHUNK_BUFFER_SIZE = 10;
|
|
22
|
+
/** Maximum buffer size to prevent memory issues on rapid reconnections */
|
|
23
|
+
const CHUNK_BUFFER_MAX_SIZE = 100;
|
|
24
|
+
/** Maximum age for a "streaming" stream before considering it stale (ms) - 5 minutes */
|
|
25
|
+
const STREAM_STALE_THRESHOLD_MS = 300 * 1e3;
|
|
26
|
+
/** Default cleanup interval for old streams (ms) - every 10 minutes */
|
|
27
|
+
const CLEANUP_INTERVAL_MS = 600 * 1e3;
|
|
28
|
+
/** Default age threshold for cleaning up completed streams (ms) - 24 hours */
|
|
29
|
+
const CLEANUP_AGE_THRESHOLD_MS = 1440 * 60 * 1e3;
|
|
30
|
+
/** Shared encoder for UTF-8 byte length measurement */
|
|
31
|
+
const textEncoder$1 = new TextEncoder();
|
|
32
|
+
var ResumableStream = class ResumableStream {
|
|
33
|
+
constructor(sql) {
|
|
34
|
+
this.sql = sql;
|
|
35
|
+
this._activeStreamId = null;
|
|
36
|
+
this._activeRequestId = null;
|
|
37
|
+
this._streamChunkIndex = 0;
|
|
38
|
+
this._chunkBuffer = [];
|
|
39
|
+
this._isFlushingChunks = false;
|
|
40
|
+
this._lastCleanupTime = 0;
|
|
41
|
+
this.sql`create table if not exists cf_ai_chat_stream_chunks (
|
|
42
|
+
id text primary key,
|
|
43
|
+
stream_id text not null,
|
|
44
|
+
body text not null,
|
|
45
|
+
chunk_index integer not null,
|
|
46
|
+
created_at integer not null
|
|
47
|
+
)`;
|
|
48
|
+
this.sql`create table if not exists cf_ai_chat_stream_metadata (
|
|
49
|
+
id text primary key,
|
|
50
|
+
request_id text not null,
|
|
51
|
+
status text not null,
|
|
52
|
+
created_at integer not null,
|
|
53
|
+
completed_at integer
|
|
54
|
+
)`;
|
|
55
|
+
this.sql`create index if not exists idx_stream_chunks_stream_id
|
|
56
|
+
on cf_ai_chat_stream_chunks(stream_id, chunk_index)`;
|
|
57
|
+
this.restore();
|
|
58
|
+
}
|
|
59
|
+
get activeStreamId() {
|
|
60
|
+
return this._activeStreamId;
|
|
61
|
+
}
|
|
62
|
+
get activeRequestId() {
|
|
63
|
+
return this._activeRequestId;
|
|
64
|
+
}
|
|
65
|
+
hasActiveStream() {
|
|
66
|
+
return this._activeStreamId !== null;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Start tracking a new stream for resumable streaming.
|
|
70
|
+
* Creates metadata entry in SQLite and sets up tracking state.
|
|
71
|
+
* @param requestId - The unique ID of the chat request
|
|
72
|
+
* @returns The generated stream ID
|
|
73
|
+
*/
|
|
74
|
+
start(requestId) {
|
|
75
|
+
this.flushBuffer();
|
|
76
|
+
const streamId = nanoid();
|
|
77
|
+
this._activeStreamId = streamId;
|
|
78
|
+
this._activeRequestId = requestId;
|
|
79
|
+
this._streamChunkIndex = 0;
|
|
80
|
+
this.sql`
|
|
81
|
+
insert into cf_ai_chat_stream_metadata (id, request_id, status, created_at)
|
|
82
|
+
values (${streamId}, ${requestId}, 'streaming', ${Date.now()})
|
|
83
|
+
`;
|
|
84
|
+
return streamId;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Mark a stream as completed and flush any pending chunks.
|
|
88
|
+
* @param streamId - The stream to mark as completed
|
|
89
|
+
*/
|
|
90
|
+
complete(streamId) {
|
|
91
|
+
this.flushBuffer();
|
|
92
|
+
this.sql`
|
|
93
|
+
update cf_ai_chat_stream_metadata
|
|
94
|
+
set status = 'completed', completed_at = ${Date.now()}
|
|
95
|
+
where id = ${streamId}
|
|
96
|
+
`;
|
|
97
|
+
this._activeStreamId = null;
|
|
98
|
+
this._activeRequestId = null;
|
|
99
|
+
this._streamChunkIndex = 0;
|
|
100
|
+
this._maybeCleanupOldStreams();
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Mark a stream as errored and clean up state.
|
|
104
|
+
* @param streamId - The stream to mark as errored
|
|
105
|
+
*/
|
|
106
|
+
markError(streamId) {
|
|
107
|
+
this.flushBuffer();
|
|
108
|
+
this.sql`
|
|
109
|
+
update cf_ai_chat_stream_metadata
|
|
110
|
+
set status = 'error', completed_at = ${Date.now()}
|
|
111
|
+
where id = ${streamId}
|
|
112
|
+
`;
|
|
113
|
+
this._activeStreamId = null;
|
|
114
|
+
this._activeRequestId = null;
|
|
115
|
+
this._streamChunkIndex = 0;
|
|
116
|
+
}
|
|
117
|
+
static {
|
|
118
|
+
this.CHUNK_MAX_BYTES = 18e5;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Buffer a stream chunk for batch write to SQLite.
|
|
122
|
+
* Chunks exceeding the row size limit are skipped to prevent crashes.
|
|
123
|
+
* The chunk is still broadcast to live clients (caller handles that),
|
|
124
|
+
* but will be missing from replay on reconnection.
|
|
125
|
+
* @param streamId - The stream this chunk belongs to
|
|
126
|
+
* @param body - The serialized chunk body
|
|
127
|
+
*/
|
|
128
|
+
storeChunk(streamId, body) {
|
|
129
|
+
const bodyBytes = textEncoder$1.encode(body).byteLength;
|
|
130
|
+
if (bodyBytes > ResumableStream.CHUNK_MAX_BYTES) {
|
|
131
|
+
console.warn(`[ResumableStream] Skipping oversized chunk (${bodyBytes} bytes) to prevent SQLite row limit crash. Live clients still receive it.`);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
if (this._chunkBuffer.length >= CHUNK_BUFFER_MAX_SIZE) this.flushBuffer();
|
|
135
|
+
this._chunkBuffer.push({
|
|
136
|
+
id: nanoid(),
|
|
137
|
+
streamId,
|
|
138
|
+
body,
|
|
139
|
+
index: this._streamChunkIndex
|
|
140
|
+
});
|
|
141
|
+
this._streamChunkIndex++;
|
|
142
|
+
if (this._chunkBuffer.length >= CHUNK_BUFFER_SIZE) this.flushBuffer();
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Flush buffered chunks to SQLite in a single batch.
|
|
146
|
+
* Uses a lock to prevent concurrent flush operations.
|
|
147
|
+
*/
|
|
148
|
+
flushBuffer() {
|
|
149
|
+
if (this._isFlushingChunks || this._chunkBuffer.length === 0) return;
|
|
150
|
+
this._isFlushingChunks = true;
|
|
151
|
+
try {
|
|
152
|
+
const chunks = this._chunkBuffer;
|
|
153
|
+
this._chunkBuffer = [];
|
|
154
|
+
const now = Date.now();
|
|
155
|
+
for (const chunk of chunks) this.sql`
|
|
156
|
+
insert into cf_ai_chat_stream_chunks (id, stream_id, body, chunk_index, created_at)
|
|
157
|
+
values (${chunk.id}, ${chunk.streamId}, ${chunk.body}, ${chunk.index}, ${now})
|
|
158
|
+
`;
|
|
159
|
+
} finally {
|
|
160
|
+
this._isFlushingChunks = false;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Send stored stream chunks to a connection for replay.
|
|
165
|
+
* Chunks are marked with replay: true so the client can batch-apply them.
|
|
166
|
+
* @param connection - The WebSocket connection
|
|
167
|
+
* @param requestId - The original request ID
|
|
168
|
+
*/
|
|
169
|
+
replayChunks(connection, requestId) {
|
|
170
|
+
const streamId = this._activeStreamId;
|
|
171
|
+
if (!streamId) return;
|
|
172
|
+
this.flushBuffer();
|
|
173
|
+
const chunks = this.sql`
|
|
174
|
+
select * from cf_ai_chat_stream_chunks
|
|
175
|
+
where stream_id = ${streamId}
|
|
176
|
+
order by chunk_index asc
|
|
177
|
+
`;
|
|
178
|
+
for (const chunk of chunks || []) connection.send(JSON.stringify({
|
|
179
|
+
body: chunk.body,
|
|
180
|
+
done: false,
|
|
181
|
+
id: requestId,
|
|
182
|
+
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
|
|
183
|
+
replay: true
|
|
184
|
+
}));
|
|
185
|
+
if (this._activeStreamId !== streamId) connection.send(JSON.stringify({
|
|
186
|
+
body: "",
|
|
187
|
+
done: true,
|
|
188
|
+
id: requestId,
|
|
189
|
+
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
|
|
190
|
+
replay: true
|
|
191
|
+
}));
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Restore active stream state if the agent was restarted during streaming.
|
|
195
|
+
* Validates stream freshness to avoid sending stale resume notifications.
|
|
196
|
+
*/
|
|
197
|
+
restore() {
|
|
198
|
+
const activeStreams = this.sql`
|
|
199
|
+
select * from cf_ai_chat_stream_metadata
|
|
200
|
+
where status = 'streaming'
|
|
201
|
+
order by created_at desc
|
|
202
|
+
limit 1
|
|
203
|
+
`;
|
|
204
|
+
if (activeStreams && activeStreams.length > 0) {
|
|
205
|
+
const stream = activeStreams[0];
|
|
206
|
+
const streamAge = Date.now() - stream.created_at;
|
|
207
|
+
if (streamAge > STREAM_STALE_THRESHOLD_MS) {
|
|
208
|
+
this.sql`delete from cf_ai_chat_stream_chunks where stream_id = ${stream.id}`;
|
|
209
|
+
this.sql`delete from cf_ai_chat_stream_metadata where id = ${stream.id}`;
|
|
210
|
+
console.warn(`[ResumableStream] Deleted stale stream ${stream.id} (age: ${Math.round(streamAge / 1e3)}s)`);
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
this._activeStreamId = stream.id;
|
|
214
|
+
this._activeRequestId = stream.request_id;
|
|
215
|
+
const lastChunk = this.sql`
|
|
216
|
+
select max(chunk_index) as max_index
|
|
217
|
+
from cf_ai_chat_stream_chunks
|
|
218
|
+
where stream_id = ${this._activeStreamId}
|
|
219
|
+
`;
|
|
220
|
+
this._streamChunkIndex = lastChunk && lastChunk[0]?.max_index != null ? lastChunk[0].max_index + 1 : 0;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Clear all stream data (called on chat history clear).
|
|
225
|
+
*/
|
|
226
|
+
clearAll() {
|
|
227
|
+
this._chunkBuffer = [];
|
|
228
|
+
this.sql`delete from cf_ai_chat_stream_chunks`;
|
|
229
|
+
this.sql`delete from cf_ai_chat_stream_metadata`;
|
|
230
|
+
this._activeStreamId = null;
|
|
231
|
+
this._activeRequestId = null;
|
|
232
|
+
this._streamChunkIndex = 0;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Drop all stream tables (called on destroy).
|
|
236
|
+
*/
|
|
237
|
+
destroy() {
|
|
238
|
+
this.flushBuffer();
|
|
239
|
+
this.sql`drop table if exists cf_ai_chat_stream_chunks`;
|
|
240
|
+
this.sql`drop table if exists cf_ai_chat_stream_metadata`;
|
|
241
|
+
this._activeStreamId = null;
|
|
242
|
+
this._activeRequestId = null;
|
|
243
|
+
}
|
|
244
|
+
_maybeCleanupOldStreams() {
|
|
245
|
+
const now = Date.now();
|
|
246
|
+
if (now - this._lastCleanupTime < CLEANUP_INTERVAL_MS) return;
|
|
247
|
+
this._lastCleanupTime = now;
|
|
248
|
+
const cutoff = now - CLEANUP_AGE_THRESHOLD_MS;
|
|
249
|
+
this.sql`
|
|
250
|
+
delete from cf_ai_chat_stream_chunks
|
|
251
|
+
where stream_id in (
|
|
252
|
+
select id from cf_ai_chat_stream_metadata
|
|
253
|
+
where status in ('completed', 'error') and completed_at < ${cutoff}
|
|
254
|
+
)
|
|
255
|
+
`;
|
|
256
|
+
this.sql`
|
|
257
|
+
delete from cf_ai_chat_stream_metadata
|
|
258
|
+
where status in ('completed', 'error') and completed_at < ${cutoff}
|
|
259
|
+
`;
|
|
260
|
+
}
|
|
261
|
+
/** @internal For testing only */
|
|
262
|
+
getStreamChunks(streamId) {
|
|
263
|
+
return this.sql`
|
|
264
|
+
select body, chunk_index from cf_ai_chat_stream_chunks
|
|
265
|
+
where stream_id = ${streamId}
|
|
266
|
+
order by chunk_index asc
|
|
267
|
+
` || [];
|
|
268
|
+
}
|
|
269
|
+
/** @internal For testing only */
|
|
270
|
+
getStreamMetadata(streamId) {
|
|
271
|
+
const result = this.sql`
|
|
272
|
+
select status, request_id from cf_ai_chat_stream_metadata
|
|
273
|
+
where id = ${streamId}
|
|
274
|
+
`;
|
|
275
|
+
return result && result.length > 0 ? result[0] : null;
|
|
276
|
+
}
|
|
277
|
+
/** @internal For testing only */
|
|
278
|
+
getAllStreamMetadata() {
|
|
279
|
+
return this.sql`select id, status, request_id, created_at from cf_ai_chat_stream_metadata` || [];
|
|
280
|
+
}
|
|
281
|
+
/** @internal For testing only */
|
|
282
|
+
insertStaleStream(streamId, requestId, ageMs) {
|
|
283
|
+
const createdAt = Date.now() - ageMs;
|
|
284
|
+
this.sql`
|
|
285
|
+
insert into cf_ai_chat_stream_metadata (id, request_id, status, created_at)
|
|
286
|
+
values (${streamId}, ${requestId}, 'streaming', ${createdAt})
|
|
287
|
+
`;
|
|
288
|
+
}
|
|
289
|
+
};
|
|
290
|
+
|
|
291
|
+
//#endregion
|
|
7
292
|
//#region src/index.ts
|
|
293
|
+
/** Shared encoder for UTF-8 byte length measurement */
|
|
294
|
+
const textEncoder = new TextEncoder();
|
|
295
|
+
/**
|
|
296
|
+
* Validates that a parsed message has the minimum required structure.
|
|
297
|
+
* Returns false for messages that would cause runtime errors downstream
|
|
298
|
+
* (e.g. in convertToModelMessages or the UI layer).
|
|
299
|
+
*
|
|
300
|
+
* Checks:
|
|
301
|
+
* - `id` is a non-empty string
|
|
302
|
+
* - `role` is one of the valid roles
|
|
303
|
+
* - `parts` is an array (may be empty — the AI SDK enforces nonempty
|
|
304
|
+
* on incoming messages, but we are lenient on persisted data)
|
|
305
|
+
*/
|
|
306
|
+
function isValidMessageStructure(msg) {
|
|
307
|
+
if (typeof msg !== "object" || msg === null) return false;
|
|
308
|
+
const m = msg;
|
|
309
|
+
if (typeof m.id !== "string" || m.id.length === 0) return false;
|
|
310
|
+
if (m.role !== "user" && m.role !== "assistant" && m.role !== "system") return false;
|
|
311
|
+
if (!Array.isArray(m.parts)) return false;
|
|
312
|
+
return true;
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* One-shot deprecation warnings (warns once per key per session).
|
|
316
|
+
*/
|
|
317
|
+
const _deprecationWarnings = /* @__PURE__ */ new Set();
|
|
318
|
+
function warnDeprecated(id, message) {
|
|
319
|
+
if (!_deprecationWarnings.has(id)) {
|
|
320
|
+
_deprecationWarnings.add(id);
|
|
321
|
+
console.warn(`[@cloudflare/ai-chat] Deprecated: ${message}`);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
8
324
|
/**
|
|
9
325
|
* Converts client tool schemas to AI SDK tool format.
|
|
10
326
|
*
|
|
@@ -41,6 +357,7 @@ import { nanoid } from "nanoid";
|
|
|
41
357
|
* ```
|
|
42
358
|
*/
|
|
43
359
|
function createToolsFromClientSchemas(clientTools) {
|
|
360
|
+
warnDeprecated("createToolsFromClientSchemas", "createToolsFromClientSchemas() is deprecated. Define tools on the server using tool() from 'ai' and handle client execution via onToolCall in useAgentChat. Will be removed in the next major version.");
|
|
44
361
|
if (!clientTools || clientTools.length === 0) return {};
|
|
45
362
|
const seenNames = /* @__PURE__ */ new Set();
|
|
46
363
|
for (const t of clientTools) {
|
|
@@ -52,61 +369,44 @@ function createToolsFromClientSchemas(clientTools) {
|
|
|
52
369
|
inputSchema: jsonSchema(t.parameters ?? { type: "object" })
|
|
53
370
|
})]));
|
|
54
371
|
}
|
|
55
|
-
/** Number of chunks to buffer before flushing to SQLite */
|
|
56
|
-
const CHUNK_BUFFER_SIZE = 10;
|
|
57
|
-
/** Maximum buffer size to prevent memory issues on rapid reconnections */
|
|
58
|
-
const CHUNK_BUFFER_MAX_SIZE = 100;
|
|
59
|
-
/** Maximum age for a "streaming" stream before considering it stale (ms) - 5 minutes */
|
|
60
|
-
const STREAM_STALE_THRESHOLD_MS = 300 * 1e3;
|
|
61
|
-
/** Default cleanup interval for old streams (ms) - every 10 minutes */
|
|
62
|
-
const CLEANUP_INTERVAL_MS = 600 * 1e3;
|
|
63
|
-
/** Default age threshold for cleaning up completed streams (ms) - 24 hours */
|
|
64
|
-
const CLEANUP_AGE_THRESHOLD_MS = 1440 * 60 * 1e3;
|
|
65
372
|
const decoder = new TextDecoder();
|
|
66
373
|
/**
|
|
67
374
|
* Extension of Agent with built-in chat capabilities
|
|
68
375
|
* @template Env Environment type containing bindings
|
|
69
376
|
*/
|
|
70
|
-
var AIChatAgent = class extends Agent {
|
|
377
|
+
var AIChatAgent = class AIChatAgent extends Agent {
|
|
378
|
+
static {
|
|
379
|
+
this.ROW_MAX_BYTES = 18e5;
|
|
380
|
+
}
|
|
381
|
+
/** Measure UTF-8 byte length of a string (accurate for SQLite row limits). */
|
|
382
|
+
static _byteLength(s) {
|
|
383
|
+
return textEncoder.encode(s).byteLength;
|
|
384
|
+
}
|
|
71
385
|
constructor(ctx, env) {
|
|
72
386
|
super(ctx, env);
|
|
73
|
-
this._activeStreamId = null;
|
|
74
|
-
this._activeRequestId = null;
|
|
75
387
|
this._streamingMessage = null;
|
|
388
|
+
this._approvalPersistedMessageId = null;
|
|
76
389
|
this._streamCompletionPromise = null;
|
|
77
390
|
this._streamCompletionResolve = null;
|
|
78
|
-
this._streamChunkIndex = 0;
|
|
79
|
-
this._chunkBuffer = [];
|
|
80
|
-
this._isFlushingChunks = false;
|
|
81
|
-
this._lastCleanupTime = 0;
|
|
82
391
|
this._pendingResumeConnections = /* @__PURE__ */ new Set();
|
|
392
|
+
this._persistedMessageCache = /* @__PURE__ */ new Map();
|
|
393
|
+
this.maxPersistedMessages = void 0;
|
|
83
394
|
this.sql`create table if not exists cf_ai_chat_agent_messages (
|
|
84
395
|
id text primary key,
|
|
85
396
|
message text not null,
|
|
86
397
|
created_at datetime default current_timestamp
|
|
87
398
|
)`;
|
|
88
|
-
this.sql`create table if not exists
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
body text not null,
|
|
92
|
-
chunk_index integer not null,
|
|
93
|
-
created_at integer not null
|
|
94
|
-
)`;
|
|
95
|
-
this.sql`create table if not exists cf_ai_chat_stream_metadata (
|
|
96
|
-
id text primary key,
|
|
97
|
-
request_id text not null,
|
|
98
|
-
status text not null,
|
|
99
|
-
created_at integer not null,
|
|
100
|
-
completed_at integer
|
|
399
|
+
this.sql`create table if not exists cf_ai_chat_request_context (
|
|
400
|
+
key text primary key,
|
|
401
|
+
value text not null
|
|
101
402
|
)`;
|
|
102
|
-
this.
|
|
103
|
-
|
|
403
|
+
this._restoreRequestContext();
|
|
404
|
+
this._resumableStream = new ResumableStream(this.sql.bind(this));
|
|
104
405
|
this.messages = autoTransformMessages(this._loadMessagesFromDb());
|
|
105
406
|
this._chatMessageAbortControllers = /* @__PURE__ */ new Map();
|
|
106
|
-
this._restoreActiveStream();
|
|
107
407
|
const _onConnect = this.onConnect.bind(this);
|
|
108
408
|
this.onConnect = async (connection, ctx) => {
|
|
109
|
-
if (this.
|
|
409
|
+
if (this._resumableStream.hasActiveStream()) this._notifyStreamResuming(connection);
|
|
110
410
|
return _onConnect(connection, ctx);
|
|
111
411
|
};
|
|
112
412
|
const _onClose = this.onClose.bind(this);
|
|
@@ -125,8 +425,21 @@ var AIChatAgent = class extends Agent {
|
|
|
125
425
|
}
|
|
126
426
|
if (data.type === MessageType.CF_AGENT_USE_CHAT_REQUEST && data.init.method === "POST") {
|
|
127
427
|
const { body } = data.init;
|
|
128
|
-
|
|
428
|
+
if (!body) {
|
|
429
|
+
console.warn("[AIChatAgent] Received chat request with empty body, ignoring");
|
|
430
|
+
return;
|
|
431
|
+
}
|
|
432
|
+
let parsed;
|
|
433
|
+
try {
|
|
434
|
+
parsed = JSON.parse(body);
|
|
435
|
+
} catch (_parseError) {
|
|
436
|
+
console.warn("[AIChatAgent] Received chat request with invalid JSON body, ignoring");
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
const { messages, clientTools, ...customBody } = parsed;
|
|
129
440
|
this._lastClientTools = clientTools?.length ? clientTools : void 0;
|
|
441
|
+
this._lastBody = Object.keys(customBody).length > 0 ? customBody : void 0;
|
|
442
|
+
this._persistRequestContext();
|
|
130
443
|
const transformedMessages = autoTransformMessages(messages);
|
|
131
444
|
this._broadcastChatMessage({
|
|
132
445
|
messages: transformedMessages,
|
|
@@ -149,21 +462,12 @@ var AIChatAgent = class extends Agent {
|
|
|
149
462
|
request: void 0,
|
|
150
463
|
email: void 0
|
|
151
464
|
}, async () => {
|
|
152
|
-
const response = await this.onChatMessage(async (_finishResult) => {
|
|
153
|
-
this._removeAbortController(chatMessageId);
|
|
154
|
-
this.observability?.emit({
|
|
155
|
-
displayMessage: "Chat message response",
|
|
156
|
-
id: data.id,
|
|
157
|
-
payload: {},
|
|
158
|
-
timestamp: Date.now(),
|
|
159
|
-
type: "message:response"
|
|
160
|
-
}, this.ctx);
|
|
161
|
-
}, {
|
|
465
|
+
const response = await this.onChatMessage(async (_finishResult) => {}, {
|
|
162
466
|
abortSignal,
|
|
163
467
|
clientTools,
|
|
164
|
-
body:
|
|
468
|
+
body: this._lastBody
|
|
165
469
|
});
|
|
166
|
-
if (response) await this._reply(data.id, response, [connection.id]);
|
|
470
|
+
if (response) await this._reply(data.id, response, [connection.id], { chatMessageId });
|
|
167
471
|
else {
|
|
168
472
|
console.warn(`[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`);
|
|
169
473
|
this._broadcastChatMessage({
|
|
@@ -179,13 +483,12 @@ var AIChatAgent = class extends Agent {
|
|
|
179
483
|
if (data.type === MessageType.CF_AGENT_CHAT_CLEAR) {
|
|
180
484
|
this._destroyAbortControllers();
|
|
181
485
|
this.sql`delete from cf_ai_chat_agent_messages`;
|
|
182
|
-
this.
|
|
183
|
-
this.sql`delete from cf_ai_chat_stream_metadata`;
|
|
184
|
-
this._activeStreamId = null;
|
|
185
|
-
this._activeRequestId = null;
|
|
186
|
-
this._streamChunkIndex = 0;
|
|
486
|
+
this._resumableStream.clearAll();
|
|
187
487
|
this._pendingResumeConnections.clear();
|
|
188
488
|
this._lastClientTools = void 0;
|
|
489
|
+
this._lastBody = void 0;
|
|
490
|
+
this._persistRequestContext();
|
|
491
|
+
this._persistedMessageCache.clear();
|
|
189
492
|
this.messages = [];
|
|
190
493
|
this._broadcastChatMessage({ type: MessageType.CF_AGENT_CHAT_CLEAR }, [connection.id]);
|
|
191
494
|
return;
|
|
@@ -199,13 +502,21 @@ var AIChatAgent = class extends Agent {
|
|
|
199
502
|
this._cancelChatRequest(data.id);
|
|
200
503
|
return;
|
|
201
504
|
}
|
|
505
|
+
if (data.type === MessageType.CF_AGENT_STREAM_RESUME_REQUEST) {
|
|
506
|
+
if (this._resumableStream.hasActiveStream()) this._notifyStreamResuming(connection);
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
202
509
|
if (data.type === MessageType.CF_AGENT_STREAM_RESUME_ACK) {
|
|
203
510
|
this._pendingResumeConnections.delete(connection.id);
|
|
204
|
-
if (this.
|
|
511
|
+
if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === data.id) this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
|
|
205
512
|
return;
|
|
206
513
|
}
|
|
207
514
|
if (data.type === MessageType.CF_AGENT_TOOL_RESULT) {
|
|
208
|
-
const { toolCallId, toolName, output, autoContinue } = data;
|
|
515
|
+
const { toolCallId, toolName, output, autoContinue, clientTools } = data;
|
|
516
|
+
if (clientTools?.length) {
|
|
517
|
+
this._lastClientTools = clientTools;
|
|
518
|
+
this._persistRequestContext();
|
|
519
|
+
}
|
|
209
520
|
this._applyToolResult(toolCallId, toolName, output).then((applied) => {
|
|
210
521
|
if (applied && autoContinue) {
|
|
211
522
|
const waitForStream = async () => {
|
|
@@ -215,209 +526,147 @@ var AIChatAgent = class extends Agent {
|
|
|
215
526
|
waitForStream().then(() => {
|
|
216
527
|
const continuationId = nanoid();
|
|
217
528
|
const abortSignal = this._getAbortSignal(continuationId);
|
|
218
|
-
this._tryCatchChat(async () => {
|
|
529
|
+
return this._tryCatchChat(async () => {
|
|
219
530
|
return __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
220
531
|
agent: this,
|
|
221
532
|
connection,
|
|
222
533
|
request: void 0,
|
|
223
534
|
email: void 0
|
|
224
535
|
}, async () => {
|
|
225
|
-
const response = await this.onChatMessage(async (_finishResult) => {
|
|
226
|
-
this._removeAbortController(continuationId);
|
|
227
|
-
this.observability?.emit({
|
|
228
|
-
displayMessage: "Chat message response (tool continuation)",
|
|
229
|
-
id: continuationId,
|
|
230
|
-
payload: {},
|
|
231
|
-
timestamp: Date.now(),
|
|
232
|
-
type: "message:response"
|
|
233
|
-
}, this.ctx);
|
|
234
|
-
}, {
|
|
536
|
+
const response = await this.onChatMessage(async (_finishResult) => {}, {
|
|
235
537
|
abortSignal,
|
|
236
|
-
clientTools: this._lastClientTools
|
|
538
|
+
clientTools: clientTools ?? this._lastClientTools,
|
|
539
|
+
body: this._lastBody
|
|
540
|
+
});
|
|
541
|
+
if (response) await this._reply(continuationId, response, [], {
|
|
542
|
+
continuation: true,
|
|
543
|
+
chatMessageId: continuationId
|
|
237
544
|
});
|
|
238
|
-
if (response) await this._reply(continuationId, response, [], { continuation: true });
|
|
239
545
|
});
|
|
240
546
|
});
|
|
547
|
+
}).catch((error) => {
|
|
548
|
+
console.error("[AIChatAgent] Tool continuation failed:", error);
|
|
241
549
|
});
|
|
242
550
|
}
|
|
243
551
|
});
|
|
244
552
|
return;
|
|
245
553
|
}
|
|
246
554
|
if (data.type === MessageType.CF_AGENT_TOOL_APPROVAL) {
|
|
247
|
-
const { toolCallId, approved } = data;
|
|
248
|
-
this._applyToolApproval(toolCallId, approved)
|
|
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
|
-
* Notify a connection about an active stream that can be resumed.
|
|
289
|
-
* The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
|
|
290
|
-
* Uses in-memory state for request ID - no extra DB lookup needed.
|
|
291
|
-
* @param connection - The WebSocket connection to notify
|
|
292
|
-
*/
|
|
293
|
-
_notifyStreamResuming(connection) {
|
|
294
|
-
if (!this._activeStreamId || !this._activeRequestId) return;
|
|
295
|
-
this._pendingResumeConnections.add(connection.id);
|
|
296
|
-
connection.send(JSON.stringify({
|
|
297
|
-
type: MessageType.CF_AGENT_STREAM_RESUMING,
|
|
298
|
-
id: this._activeRequestId
|
|
299
|
-
}));
|
|
300
|
-
}
|
|
301
|
-
/**
|
|
302
|
-
* Send stream chunks to a connection after receiving ACK.
|
|
303
|
-
* @param connection - The WebSocket connection
|
|
304
|
-
* @param streamId - The stream to replay
|
|
305
|
-
* @param requestId - The original request ID
|
|
306
|
-
*/
|
|
307
|
-
_sendStreamChunks(connection, streamId, requestId) {
|
|
308
|
-
this._flushChunkBuffer();
|
|
309
|
-
const chunks = this.sql`
|
|
310
|
-
select * from cf_ai_chat_stream_chunks
|
|
311
|
-
where stream_id = ${streamId}
|
|
312
|
-
order by chunk_index asc
|
|
313
|
-
`;
|
|
314
|
-
for (const chunk of chunks || []) connection.send(JSON.stringify({
|
|
315
|
-
body: chunk.body,
|
|
316
|
-
done: false,
|
|
317
|
-
id: requestId,
|
|
318
|
-
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
|
|
319
|
-
}));
|
|
320
|
-
if (this._activeStreamId !== streamId) connection.send(JSON.stringify({
|
|
321
|
-
body: "",
|
|
322
|
-
done: true,
|
|
323
|
-
id: requestId,
|
|
324
|
-
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
|
|
325
|
-
}));
|
|
326
|
-
}
|
|
327
|
-
/**
|
|
328
|
-
* Buffer a stream chunk for batch write to SQLite.
|
|
329
|
-
* @param streamId - The stream this chunk belongs to
|
|
330
|
-
* @param body - The serialized chunk body
|
|
331
|
-
* @internal Protected for testing purposes.
|
|
332
|
-
*/
|
|
333
|
-
_storeStreamChunk(streamId, body) {
|
|
334
|
-
if (this._chunkBuffer.length >= CHUNK_BUFFER_MAX_SIZE) this._flushChunkBuffer();
|
|
335
|
-
this._chunkBuffer.push({
|
|
336
|
-
id: nanoid(),
|
|
337
|
-
streamId,
|
|
338
|
-
body,
|
|
339
|
-
index: this._streamChunkIndex
|
|
340
|
-
});
|
|
341
|
-
this._streamChunkIndex++;
|
|
342
|
-
if (this._chunkBuffer.length >= CHUNK_BUFFER_SIZE) this._flushChunkBuffer();
|
|
343
|
-
}
|
|
344
|
-
/**
|
|
345
|
-
* Flush buffered chunks to SQLite in a single batch.
|
|
346
|
-
* Uses a lock to prevent concurrent flush operations.
|
|
347
|
-
* @internal Protected for testing purposes.
|
|
348
|
-
*/
|
|
349
|
-
_flushChunkBuffer() {
|
|
350
|
-
if (this._isFlushingChunks || this._chunkBuffer.length === 0) return;
|
|
351
|
-
this._isFlushingChunks = true;
|
|
352
|
-
try {
|
|
353
|
-
const chunks = this._chunkBuffer;
|
|
354
|
-
this._chunkBuffer = [];
|
|
355
|
-
const now = Date.now();
|
|
356
|
-
for (const chunk of chunks) this.sql`
|
|
357
|
-
insert into cf_ai_chat_stream_chunks (id, stream_id, body, chunk_index, created_at)
|
|
358
|
-
values (${chunk.id}, ${chunk.streamId}, ${chunk.body}, ${chunk.index}, ${now})
|
|
359
|
-
`;
|
|
360
|
-
} finally {
|
|
361
|
-
this._isFlushingChunks = false;
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
/**
|
|
365
|
-
* Start tracking a new stream for resumable streaming.
|
|
366
|
-
* Creates metadata entry in SQLite and sets up tracking state.
|
|
367
|
-
* @param requestId - The unique ID of the chat request
|
|
368
|
-
* @returns The generated stream ID
|
|
369
|
-
* @internal Protected for testing purposes.
|
|
370
|
-
*/
|
|
371
|
-
_startStream(requestId) {
|
|
372
|
-
this._flushChunkBuffer();
|
|
373
|
-
const streamId = nanoid();
|
|
374
|
-
this._activeStreamId = streamId;
|
|
375
|
-
this._activeRequestId = requestId;
|
|
376
|
-
this._streamChunkIndex = 0;
|
|
377
|
-
this.sql`
|
|
378
|
-
insert into cf_ai_chat_stream_metadata (id, request_id, status, created_at)
|
|
379
|
-
values (${streamId}, ${requestId}, 'streaming', ${Date.now()})
|
|
380
|
-
`;
|
|
381
|
-
return streamId;
|
|
555
|
+
const { toolCallId, approved, autoContinue } = data;
|
|
556
|
+
this._applyToolApproval(toolCallId, approved).then((applied) => {
|
|
557
|
+
if (applied && approved && autoContinue) {
|
|
558
|
+
const waitForStream = async () => {
|
|
559
|
+
if (this._streamCompletionPromise) await this._streamCompletionPromise;
|
|
560
|
+
else await new Promise((resolve) => setTimeout(resolve, 500));
|
|
561
|
+
};
|
|
562
|
+
waitForStream().then(() => {
|
|
563
|
+
const continuationId = nanoid();
|
|
564
|
+
const abortSignal = this._getAbortSignal(continuationId);
|
|
565
|
+
return this._tryCatchChat(async () => {
|
|
566
|
+
return __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
567
|
+
agent: this,
|
|
568
|
+
connection,
|
|
569
|
+
request: void 0,
|
|
570
|
+
email: void 0
|
|
571
|
+
}, async () => {
|
|
572
|
+
const response = await this.onChatMessage(async (_finishResult) => {}, {
|
|
573
|
+
abortSignal,
|
|
574
|
+
clientTools: this._lastClientTools,
|
|
575
|
+
body: this._lastBody
|
|
576
|
+
});
|
|
577
|
+
if (response) await this._reply(continuationId, response, [], {
|
|
578
|
+
continuation: true,
|
|
579
|
+
chatMessageId: continuationId
|
|
580
|
+
});
|
|
581
|
+
});
|
|
582
|
+
});
|
|
583
|
+
}).catch((error) => {
|
|
584
|
+
console.error("[AIChatAgent] Tool approval continuation failed:", error);
|
|
585
|
+
});
|
|
586
|
+
}
|
|
587
|
+
});
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
return _onMessage(connection, message);
|
|
592
|
+
};
|
|
382
593
|
}
|
|
383
594
|
/**
|
|
384
|
-
*
|
|
385
|
-
*
|
|
386
|
-
* @
|
|
595
|
+
* Notify a connection about an active stream that can be resumed.
|
|
596
|
+
* The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
|
|
597
|
+
* @param connection - The WebSocket connection to notify
|
|
387
598
|
*/
|
|
599
|
+
_notifyStreamResuming(connection) {
|
|
600
|
+
if (!this._resumableStream.hasActiveStream()) return;
|
|
601
|
+
this._pendingResumeConnections.add(connection.id);
|
|
602
|
+
connection.send(JSON.stringify({
|
|
603
|
+
type: MessageType.CF_AGENT_STREAM_RESUMING,
|
|
604
|
+
id: this._resumableStream.activeRequestId
|
|
605
|
+
}));
|
|
606
|
+
}
|
|
607
|
+
/** @internal Delegate to _resumableStream */
|
|
608
|
+
get _activeStreamId() {
|
|
609
|
+
return this._resumableStream?.activeStreamId ?? null;
|
|
610
|
+
}
|
|
611
|
+
/** @internal Delegate to _resumableStream */
|
|
612
|
+
get _activeRequestId() {
|
|
613
|
+
return this._resumableStream?.activeRequestId ?? null;
|
|
614
|
+
}
|
|
615
|
+
/** @internal Delegate to _resumableStream */
|
|
616
|
+
_startStream(requestId) {
|
|
617
|
+
return this._resumableStream.start(requestId);
|
|
618
|
+
}
|
|
619
|
+
/** @internal Delegate to _resumableStream */
|
|
388
620
|
_completeStream(streamId) {
|
|
389
|
-
this.
|
|
390
|
-
this.sql`
|
|
391
|
-
update cf_ai_chat_stream_metadata
|
|
392
|
-
set status = 'completed', completed_at = ${Date.now()}
|
|
393
|
-
where id = ${streamId}
|
|
394
|
-
`;
|
|
395
|
-
this._activeStreamId = null;
|
|
396
|
-
this._activeRequestId = null;
|
|
397
|
-
this._streamChunkIndex = 0;
|
|
621
|
+
this._resumableStream.complete(streamId);
|
|
398
622
|
this._pendingResumeConnections.clear();
|
|
399
|
-
|
|
623
|
+
}
|
|
624
|
+
/** @internal Delegate to _resumableStream */
|
|
625
|
+
_storeStreamChunk(streamId, body) {
|
|
626
|
+
this._resumableStream.storeChunk(streamId, body);
|
|
627
|
+
}
|
|
628
|
+
/** @internal Delegate to _resumableStream */
|
|
629
|
+
_flushChunkBuffer() {
|
|
630
|
+
this._resumableStream.flushBuffer();
|
|
631
|
+
}
|
|
632
|
+
/** @internal Delegate to _resumableStream */
|
|
633
|
+
_restoreActiveStream() {
|
|
634
|
+
this._resumableStream.restore();
|
|
635
|
+
}
|
|
636
|
+
/** @internal Delegate to _resumableStream */
|
|
637
|
+
_markStreamError(streamId) {
|
|
638
|
+
this._resumableStream.markError(streamId);
|
|
400
639
|
}
|
|
401
640
|
/**
|
|
402
|
-
*
|
|
403
|
-
*
|
|
641
|
+
* Restore _lastBody and _lastClientTools from SQLite.
|
|
642
|
+
* Called in the constructor so these values survive DO hibernation.
|
|
643
|
+
* @internal
|
|
404
644
|
*/
|
|
405
|
-
|
|
406
|
-
const
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
const
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
645
|
+
_restoreRequestContext() {
|
|
646
|
+
const rows = this.sql`
|
|
647
|
+
select key, value from cf_ai_chat_request_context
|
|
648
|
+
` || [];
|
|
649
|
+
for (const row of rows) try {
|
|
650
|
+
if (row.key === "lastBody") this._lastBody = JSON.parse(row.value);
|
|
651
|
+
else if (row.key === "lastClientTools") this._lastClientTools = JSON.parse(row.value);
|
|
652
|
+
} catch {}
|
|
653
|
+
}
|
|
654
|
+
/**
|
|
655
|
+
* Persist _lastBody and _lastClientTools to SQLite so they survive hibernation.
|
|
656
|
+
* Uses upsert (INSERT OR REPLACE) so repeated calls are safe.
|
|
657
|
+
* @internal
|
|
658
|
+
*/
|
|
659
|
+
_persistRequestContext() {
|
|
660
|
+
if (this._lastBody) this.sql`
|
|
661
|
+
insert or replace into cf_ai_chat_request_context (key, value)
|
|
662
|
+
values ('lastBody', ${JSON.stringify(this._lastBody)})
|
|
663
|
+
`;
|
|
664
|
+
else this.sql`delete from cf_ai_chat_request_context where key = 'lastBody'`;
|
|
665
|
+
if (this._lastClientTools) this.sql`
|
|
666
|
+
insert or replace into cf_ai_chat_request_context (key, value)
|
|
667
|
+
values ('lastClientTools', ${JSON.stringify(this._lastClientTools)})
|
|
668
|
+
`;
|
|
669
|
+
else this.sql`delete from cf_ai_chat_request_context where key = 'lastClientTools'`;
|
|
421
670
|
}
|
|
422
671
|
_broadcastChatMessage(message, exclude) {
|
|
423
672
|
const allExclusions = [...exclude || [], ...this._pendingResumeConnections];
|
|
@@ -443,9 +692,18 @@ var AIChatAgent = class extends Agent {
|
|
|
443
692
|
});
|
|
444
693
|
}
|
|
445
694
|
_loadMessagesFromDb() {
|
|
446
|
-
|
|
695
|
+
const rows = this.sql`select * from cf_ai_chat_agent_messages order by created_at` || [];
|
|
696
|
+
this._persistedMessageCache.clear();
|
|
697
|
+
return rows.map((row) => {
|
|
447
698
|
try {
|
|
448
|
-
|
|
699
|
+
const messageStr = row.message;
|
|
700
|
+
const parsed = JSON.parse(messageStr);
|
|
701
|
+
if (!isValidMessageStructure(parsed)) {
|
|
702
|
+
console.warn(`[AIChatAgent] Skipping invalid message ${row.id}: missing or malformed id, role, or parts`);
|
|
703
|
+
return null;
|
|
704
|
+
}
|
|
705
|
+
this._persistedMessageCache.set(parsed.id, messageStr);
|
|
706
|
+
return parsed;
|
|
449
707
|
} catch (error) {
|
|
450
708
|
console.error(`Failed to parse message ${row.id}:`, error);
|
|
451
709
|
return null;
|
|
@@ -475,7 +733,7 @@ var AIChatAgent = class extends Agent {
|
|
|
475
733
|
* @returns Response to send to the client or undefined
|
|
476
734
|
*/
|
|
477
735
|
async onChatMessage(onFinish, options) {
|
|
478
|
-
throw new Error("
|
|
736
|
+
throw new Error("received a chat message, override onChatMessage and return a Response to send to the client");
|
|
479
737
|
}
|
|
480
738
|
/**
|
|
481
739
|
* Save messages on the server side
|
|
@@ -492,13 +750,18 @@ var AIChatAgent = class extends Agent {
|
|
|
492
750
|
const mergedMessages = this._mergeIncomingWithServerState(messages);
|
|
493
751
|
for (const message of mergedMessages) {
|
|
494
752
|
const sanitizedMessage = this._sanitizeMessageForPersistence(message);
|
|
495
|
-
const
|
|
753
|
+
const resolved = this._resolveMessageForToolMerge(sanitizedMessage);
|
|
754
|
+
const safe = this._enforceRowSizeLimit(resolved);
|
|
755
|
+
const json = JSON.stringify(safe);
|
|
756
|
+
if (this._persistedMessageCache.get(safe.id) === json) continue;
|
|
496
757
|
this.sql`
|
|
497
758
|
insert into cf_ai_chat_agent_messages (id, message)
|
|
498
|
-
values (${
|
|
759
|
+
values (${safe.id}, ${json})
|
|
499
760
|
on conflict(id) do update set message = excluded.message
|
|
500
761
|
`;
|
|
762
|
+
this._persistedMessageCache.set(safe.id, json);
|
|
501
763
|
}
|
|
764
|
+
if (this.maxPersistedMessages != null) this._enforceMaxPersistedMessages();
|
|
502
765
|
this.messages = autoTransformMessages(this._loadMessagesFromDb());
|
|
503
766
|
this._broadcastChatMessage({
|
|
504
767
|
messages: mergedMessages,
|
|
@@ -636,17 +899,129 @@ var AIChatAgent = class extends Agent {
|
|
|
636
899
|
return restPart;
|
|
637
900
|
}
|
|
638
901
|
/**
|
|
639
|
-
*
|
|
640
|
-
*
|
|
641
|
-
|
|
642
|
-
|
|
902
|
+
* Deletes oldest messages from SQLite when the count exceeds maxPersistedMessages.
|
|
903
|
+
* Called after each persist to keep storage bounded.
|
|
904
|
+
*/
|
|
905
|
+
_enforceMaxPersistedMessages() {
|
|
906
|
+
if (this.maxPersistedMessages == null) return;
|
|
907
|
+
const count = this.sql`
|
|
908
|
+
select count(*) as cnt from cf_ai_chat_agent_messages
|
|
909
|
+
`?.[0]?.cnt ?? 0;
|
|
910
|
+
if (count <= this.maxPersistedMessages) return;
|
|
911
|
+
const excess = count - this.maxPersistedMessages;
|
|
912
|
+
const toDelete = this.sql`
|
|
913
|
+
select id from cf_ai_chat_agent_messages
|
|
914
|
+
order by created_at asc
|
|
915
|
+
limit ${excess}
|
|
916
|
+
`;
|
|
917
|
+
if (toDelete && toDelete.length > 0) for (const row of toDelete) {
|
|
918
|
+
this.sql`delete from cf_ai_chat_agent_messages where id = ${row.id}`;
|
|
919
|
+
this._persistedMessageCache.delete(row.id);
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
/**
|
|
923
|
+
* Enforces SQLite row size limits by compacting tool outputs and text parts
|
|
924
|
+
* when a serialized message exceeds the safety threshold (1.8MB).
|
|
643
925
|
*
|
|
644
|
-
*
|
|
645
|
-
*
|
|
646
|
-
*
|
|
647
|
-
*
|
|
926
|
+
* Only fires in pathological cases (extremely large tool outputs or text).
|
|
927
|
+
* Returns the message unchanged if it fits within limits.
|
|
928
|
+
*
|
|
929
|
+
* Compaction strategy:
|
|
930
|
+
* 1. Compact tool outputs over 1KB (replace with LLM-friendly summary)
|
|
931
|
+
* 2. If still too big, truncate text parts from oldest to newest
|
|
932
|
+
* 3. Add metadata so clients can detect compaction
|
|
933
|
+
*
|
|
934
|
+
* @param message - The message to check
|
|
935
|
+
* @returns The message, compacted if necessary
|
|
648
936
|
*/
|
|
649
|
-
|
|
937
|
+
_enforceRowSizeLimit(message) {
|
|
938
|
+
let json = JSON.stringify(message);
|
|
939
|
+
let size = AIChatAgent._byteLength(json);
|
|
940
|
+
if (size <= AIChatAgent.ROW_MAX_BYTES) return message;
|
|
941
|
+
if (message.role !== "assistant") {
|
|
942
|
+
console.warn(`[AIChatAgent] Non-assistant message ${message.id} is ${size} bytes, exceeds row limit. Truncating text parts.`);
|
|
943
|
+
return this._truncateTextParts(message);
|
|
944
|
+
}
|
|
945
|
+
console.warn(`[AIChatAgent] Message ${message.id} is ${size} bytes, compacting tool outputs to fit SQLite row limit`);
|
|
946
|
+
const compactedToolCallIds = [];
|
|
947
|
+
const compactedParts = message.parts.map((part) => {
|
|
948
|
+
if ("output" in part && "toolCallId" in part && "state" in part && part.state === "output-available") {
|
|
949
|
+
const outputJson = JSON.stringify(part.output);
|
|
950
|
+
if (outputJson.length > 1e3) {
|
|
951
|
+
compactedToolCallIds.push(part.toolCallId);
|
|
952
|
+
return {
|
|
953
|
+
...part,
|
|
954
|
+
output: `This tool output was too large to persist in storage (${outputJson.length} bytes). If the user asks about this data, suggest re-running the tool. Preview: ${outputJson.slice(0, 500)}...`
|
|
955
|
+
};
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
return part;
|
|
959
|
+
});
|
|
960
|
+
let result = {
|
|
961
|
+
...message,
|
|
962
|
+
parts: compactedParts
|
|
963
|
+
};
|
|
964
|
+
if (compactedToolCallIds.length > 0) result.metadata = {
|
|
965
|
+
...result.metadata ?? {},
|
|
966
|
+
compactedToolOutputs: compactedToolCallIds
|
|
967
|
+
};
|
|
968
|
+
json = JSON.stringify(result);
|
|
969
|
+
size = AIChatAgent._byteLength(json);
|
|
970
|
+
if (size <= AIChatAgent.ROW_MAX_BYTES) return result;
|
|
971
|
+
console.warn(`[AIChatAgent] Message ${message.id} still ${size} bytes after tool compaction, truncating text parts`);
|
|
972
|
+
return this._truncateTextParts(result);
|
|
973
|
+
}
|
|
974
|
+
/**
|
|
975
|
+
* Truncates text parts in a message to fit within the row size limit.
|
|
976
|
+
* Truncates from the first text part forward, keeping the last text part
|
|
977
|
+
* as intact as possible (it is usually the most relevant).
|
|
978
|
+
*/
|
|
979
|
+
_truncateTextParts(message) {
|
|
980
|
+
const compactedTextPartIndices = [];
|
|
981
|
+
const parts = [...message.parts];
|
|
982
|
+
for (let i = 0; i < parts.length; i++) {
|
|
983
|
+
const part = parts[i];
|
|
984
|
+
if (part.type === "text" && "text" in part) {
|
|
985
|
+
const text = part.text;
|
|
986
|
+
if (text.length > 1e3) {
|
|
987
|
+
compactedTextPartIndices.push(i);
|
|
988
|
+
parts[i] = {
|
|
989
|
+
...part,
|
|
990
|
+
text: `[Text truncated for storage (${text.length} chars). First 500 chars: ${text.slice(0, 500)}...]`
|
|
991
|
+
};
|
|
992
|
+
const candidate = {
|
|
993
|
+
...message,
|
|
994
|
+
parts
|
|
995
|
+
};
|
|
996
|
+
if (AIChatAgent._byteLength(JSON.stringify(candidate)) <= AIChatAgent.ROW_MAX_BYTES) break;
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
const result = {
|
|
1001
|
+
...message,
|
|
1002
|
+
parts
|
|
1003
|
+
};
|
|
1004
|
+
if (compactedTextPartIndices.length > 0) result.metadata = {
|
|
1005
|
+
...result.metadata ?? {},
|
|
1006
|
+
compactedTextParts: compactedTextPartIndices
|
|
1007
|
+
};
|
|
1008
|
+
return result;
|
|
1009
|
+
}
|
|
1010
|
+
/**
|
|
1011
|
+
* Shared helper for finding a tool part by toolCallId and applying an update.
|
|
1012
|
+
* Handles both streaming (in-memory) and persisted (SQLite) messages.
|
|
1013
|
+
*
|
|
1014
|
+
* Checks _streamingMessage first (tool results/approvals can arrive while
|
|
1015
|
+
* the AI is still streaming), then retries persisted messages with backoff
|
|
1016
|
+
* in case streaming completes between attempts.
|
|
1017
|
+
*
|
|
1018
|
+
* @param toolCallId - The tool call ID to find
|
|
1019
|
+
* @param callerName - Name for log messages (e.g. "_applyToolResult")
|
|
1020
|
+
* @param matchStates - Which tool part states to match
|
|
1021
|
+
* @param applyUpdate - Mutation to apply to the matched part (streaming: in-place, persisted: spread)
|
|
1022
|
+
* @returns true if the update was applied, false if not found or state didn't match
|
|
1023
|
+
*/
|
|
1024
|
+
async _findAndUpdateToolPart(toolCallId, callerName, matchStates, applyUpdate) {
|
|
650
1025
|
let message;
|
|
651
1026
|
if (this._streamingMessage) {
|
|
652
1027
|
for (const part of this._streamingMessage.parts) if ("toolCallId" in part && part.toolCallId === toolCallId) {
|
|
@@ -660,27 +1035,23 @@ var AIChatAgent = class extends Agent {
|
|
|
660
1035
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
661
1036
|
}
|
|
662
1037
|
if (!message) {
|
|
663
|
-
console.warn(`[AIChatAgent]
|
|
1038
|
+
console.warn(`[AIChatAgent] ${callerName}: Could not find message with toolCallId ${toolCallId} after retries`);
|
|
664
1039
|
return false;
|
|
665
1040
|
}
|
|
666
1041
|
const isStreamingMessage = message === this._streamingMessage;
|
|
667
1042
|
let updated = false;
|
|
668
1043
|
if (isStreamingMessage) {
|
|
669
|
-
for (const part of message.parts) if ("toolCallId" in part && part.toolCallId === toolCallId && "state" in part && part.state
|
|
670
|
-
|
|
671
|
-
part
|
|
1044
|
+
for (const part of message.parts) if ("toolCallId" in part && part.toolCallId === toolCallId && "state" in part && matchStates.includes(part.state)) {
|
|
1045
|
+
const applied = applyUpdate(part);
|
|
1046
|
+
Object.assign(part, applied);
|
|
672
1047
|
updated = true;
|
|
673
1048
|
break;
|
|
674
1049
|
}
|
|
675
1050
|
} else {
|
|
676
1051
|
const updatedParts = message.parts.map((part) => {
|
|
677
|
-
if ("toolCallId" in part && part.toolCallId === toolCallId && "state" in part && part.state
|
|
1052
|
+
if ("toolCallId" in part && part.toolCallId === toolCallId && "state" in part && matchStates.includes(part.state)) {
|
|
678
1053
|
updated = true;
|
|
679
|
-
return
|
|
680
|
-
...part,
|
|
681
|
-
state: "output-available",
|
|
682
|
-
output
|
|
683
|
-
};
|
|
1054
|
+
return applyUpdate(part);
|
|
684
1055
|
}
|
|
685
1056
|
return part;
|
|
686
1057
|
});
|
|
@@ -689,19 +1060,26 @@ var AIChatAgent = class extends Agent {
|
|
|
689
1060
|
...message,
|
|
690
1061
|
parts: updatedParts
|
|
691
1062
|
});
|
|
1063
|
+
const safe = this._enforceRowSizeLimit(updatedMessage);
|
|
1064
|
+
const json = JSON.stringify(safe);
|
|
692
1065
|
this.sql`
|
|
693
1066
|
update cf_ai_chat_agent_messages
|
|
694
|
-
set message = ${
|
|
1067
|
+
set message = ${json}
|
|
695
1068
|
where id = ${message.id}
|
|
696
1069
|
`;
|
|
1070
|
+
this._persistedMessageCache.set(message.id, json);
|
|
697
1071
|
this.messages = autoTransformMessages(this._loadMessagesFromDb());
|
|
698
1072
|
}
|
|
699
1073
|
}
|
|
700
1074
|
if (!updated) {
|
|
701
|
-
console.warn(`[AIChatAgent]
|
|
1075
|
+
console.warn(`[AIChatAgent] ${callerName}: Tool part with toolCallId ${toolCallId} not in expected state (expected: ${matchStates.join("|")})`);
|
|
702
1076
|
return false;
|
|
703
1077
|
}
|
|
704
|
-
if (
|
|
1078
|
+
if (isStreamingMessage) this._broadcastChatMessage({
|
|
1079
|
+
type: MessageType.CF_AGENT_MESSAGE_UPDATED,
|
|
1080
|
+
message
|
|
1081
|
+
});
|
|
1082
|
+
else {
|
|
705
1083
|
const broadcastMessage = this._findMessageByToolCallId(toolCallId);
|
|
706
1084
|
if (broadcastMessage) this._broadcastChatMessage({
|
|
707
1085
|
type: MessageType.CF_AGENT_MESSAGE_UPDATED,
|
|
@@ -710,11 +1088,26 @@ var AIChatAgent = class extends Agent {
|
|
|
710
1088
|
}
|
|
711
1089
|
return true;
|
|
712
1090
|
}
|
|
1091
|
+
/**
|
|
1092
|
+
* Applies a tool result to an existing assistant message.
|
|
1093
|
+
* This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.
|
|
1094
|
+
* The server is the source of truth, so we update the message here and broadcast
|
|
1095
|
+
* the update to all clients.
|
|
1096
|
+
*
|
|
1097
|
+
* @param toolCallId - The tool call ID this result is for
|
|
1098
|
+
* @param _toolName - The name of the tool (unused, kept for API compat)
|
|
1099
|
+
* @param output - The output from the tool execution
|
|
1100
|
+
* @returns true if the result was applied, false if the message was not found
|
|
1101
|
+
*/
|
|
1102
|
+
async _applyToolResult(toolCallId, _toolName, output) {
|
|
1103
|
+
return this._findAndUpdateToolPart(toolCallId, "_applyToolResult", ["input-available"], (part) => ({
|
|
1104
|
+
...part,
|
|
1105
|
+
state: "output-available",
|
|
1106
|
+
output,
|
|
1107
|
+
preliminary: false
|
|
1108
|
+
}));
|
|
1109
|
+
}
|
|
713
1110
|
async _streamSSEReply(id, streamId, reader, message, streamCompleted, continuation = false) {
|
|
714
|
-
let activeTextParts = {};
|
|
715
|
-
let activeReasoningParts = {};
|
|
716
|
-
const partialToolCalls = {};
|
|
717
|
-
const { getToolName, isToolUIPart, parsePartialJson } = await import("ai");
|
|
718
1111
|
streamCompleted.value = false;
|
|
719
1112
|
while (true) {
|
|
720
1113
|
const { done, value } = await reader.read();
|
|
@@ -733,225 +1126,60 @@ var AIChatAgent = class extends Agent {
|
|
|
733
1126
|
const lines = decoder.decode(value).split("\n");
|
|
734
1127
|
for (const line of lines) if (line.startsWith("data: ") && line !== "data: [DONE]") try {
|
|
735
1128
|
const data = JSON.parse(line.slice(6));
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
reasoningPart.providerMetadata = data.providerMetadata ?? reasoningPart.providerMetadata;
|
|
776
|
-
break;
|
|
777
|
-
}
|
|
778
|
-
case "reasoning-end": {
|
|
779
|
-
const reasoningPart = activeReasoningParts[data.id];
|
|
780
|
-
reasoningPart.providerMetadata = data.providerMetadata ?? reasoningPart.providerMetadata;
|
|
781
|
-
reasoningPart.state = "done";
|
|
782
|
-
delete activeReasoningParts[data.id];
|
|
783
|
-
break;
|
|
784
|
-
}
|
|
785
|
-
case "file":
|
|
786
|
-
message.parts.push({
|
|
787
|
-
type: "file",
|
|
788
|
-
mediaType: data.mediaType,
|
|
789
|
-
url: data.url
|
|
790
|
-
});
|
|
791
|
-
break;
|
|
792
|
-
case "source-url":
|
|
793
|
-
message.parts.push({
|
|
794
|
-
type: "source-url",
|
|
795
|
-
sourceId: data.sourceId,
|
|
796
|
-
url: data.url,
|
|
797
|
-
title: data.title,
|
|
798
|
-
providerMetadata: data.providerMetadata
|
|
799
|
-
});
|
|
800
|
-
break;
|
|
801
|
-
case "source-document":
|
|
802
|
-
message.parts.push({
|
|
803
|
-
type: "source-document",
|
|
804
|
-
sourceId: data.sourceId,
|
|
805
|
-
mediaType: data.mediaType,
|
|
806
|
-
title: data.title,
|
|
807
|
-
filename: data.filename,
|
|
808
|
-
providerMetadata: data.providerMetadata
|
|
809
|
-
});
|
|
810
|
-
break;
|
|
811
|
-
case "tool-input-start": {
|
|
812
|
-
const toolInvocations = message.parts.filter(isToolUIPart);
|
|
813
|
-
partialToolCalls[data.toolCallId] = {
|
|
814
|
-
text: "",
|
|
815
|
-
toolName: data.toolName,
|
|
816
|
-
index: toolInvocations.length,
|
|
817
|
-
dynamic: data.dynamic
|
|
818
|
-
};
|
|
819
|
-
if (data.dynamic) this.updateDynamicToolPart(message, {
|
|
820
|
-
toolCallId: data.toolCallId,
|
|
821
|
-
toolName: data.toolName,
|
|
822
|
-
state: "input-streaming",
|
|
823
|
-
input: void 0
|
|
824
|
-
});
|
|
825
|
-
else await this.updateToolPart(message, {
|
|
826
|
-
toolCallId: data.toolCallId,
|
|
827
|
-
toolName: data.toolName,
|
|
828
|
-
state: "input-streaming",
|
|
829
|
-
input: void 0
|
|
830
|
-
});
|
|
831
|
-
break;
|
|
832
|
-
}
|
|
833
|
-
case "tool-input-delta": {
|
|
834
|
-
const partialToolCall = partialToolCalls[data.toolCallId];
|
|
835
|
-
partialToolCall.text += data.inputTextDelta;
|
|
836
|
-
const partialArgs = (await parsePartialJson(partialToolCall.text)).value;
|
|
837
|
-
if (partialToolCall.dynamic) this.updateDynamicToolPart(message, {
|
|
838
|
-
toolCallId: data.toolCallId,
|
|
839
|
-
toolName: partialToolCall.toolName,
|
|
840
|
-
state: "input-streaming",
|
|
841
|
-
input: partialArgs
|
|
842
|
-
});
|
|
843
|
-
else await this.updateToolPart(message, {
|
|
844
|
-
toolCallId: data.toolCallId,
|
|
845
|
-
toolName: partialToolCall.toolName,
|
|
846
|
-
state: "input-streaming",
|
|
847
|
-
input: partialArgs
|
|
848
|
-
});
|
|
849
|
-
break;
|
|
850
|
-
}
|
|
851
|
-
case "tool-input-available":
|
|
852
|
-
if (data.dynamic) this.updateDynamicToolPart(message, {
|
|
853
|
-
toolCallId: data.toolCallId,
|
|
854
|
-
toolName: data.toolName,
|
|
855
|
-
state: "input-available",
|
|
856
|
-
input: data.input,
|
|
857
|
-
providerMetadata: data.providerMetadata
|
|
858
|
-
});
|
|
859
|
-
else await this.updateToolPart(message, {
|
|
860
|
-
toolCallId: data.toolCallId,
|
|
861
|
-
toolName: data.toolName,
|
|
862
|
-
state: "input-available",
|
|
863
|
-
input: data.input,
|
|
864
|
-
providerExecuted: data.providerExecuted,
|
|
865
|
-
providerMetadata: data.providerMetadata
|
|
866
|
-
});
|
|
867
|
-
break;
|
|
868
|
-
case "tool-input-error":
|
|
869
|
-
if (data.dynamic) this.updateDynamicToolPart(message, {
|
|
870
|
-
toolCallId: data.toolCallId,
|
|
871
|
-
toolName: data.toolName,
|
|
872
|
-
state: "output-error",
|
|
873
|
-
input: data.input,
|
|
874
|
-
errorText: data.errorText,
|
|
875
|
-
providerMetadata: data.providerMetadata
|
|
876
|
-
});
|
|
877
|
-
else await this.updateToolPart(message, {
|
|
878
|
-
toolCallId: data.toolCallId,
|
|
879
|
-
toolName: data.toolName,
|
|
880
|
-
state: "output-error",
|
|
881
|
-
input: void 0,
|
|
882
|
-
rawInput: data.input,
|
|
883
|
-
errorText: data.errorText,
|
|
884
|
-
providerExecuted: data.providerExecuted,
|
|
885
|
-
providerMetadata: data.providerMetadata
|
|
886
|
-
});
|
|
887
|
-
break;
|
|
888
|
-
case "tool-output-available":
|
|
889
|
-
if (data.dynamic) {
|
|
890
|
-
const toolInvocation = message.parts.filter((part) => part.type === "dynamic-tool").find((invocation) => invocation.toolCallId === data.toolCallId);
|
|
891
|
-
if (!toolInvocation) throw new Error("Tool invocation not found");
|
|
892
|
-
this.updateDynamicToolPart(message, {
|
|
893
|
-
toolCallId: data.toolCallId,
|
|
894
|
-
toolName: toolInvocation.toolName,
|
|
895
|
-
state: "output-available",
|
|
896
|
-
input: toolInvocation.input,
|
|
897
|
-
output: data.output,
|
|
898
|
-
preliminary: data.preliminary
|
|
899
|
-
});
|
|
900
|
-
} else {
|
|
901
|
-
const toolInvocation = message.parts.filter(isToolUIPart).find((invocation) => invocation.toolCallId === data.toolCallId);
|
|
902
|
-
if (!toolInvocation) throw new Error("Tool invocation not found");
|
|
903
|
-
await this.updateToolPart(message, {
|
|
904
|
-
toolCallId: data.toolCallId,
|
|
905
|
-
toolName: getToolName(toolInvocation),
|
|
906
|
-
state: "output-available",
|
|
907
|
-
input: toolInvocation.input,
|
|
908
|
-
output: data.output,
|
|
909
|
-
providerExecuted: data.providerExecuted,
|
|
910
|
-
preliminary: data.preliminary
|
|
911
|
-
});
|
|
912
|
-
}
|
|
913
|
-
break;
|
|
914
|
-
case "tool-output-error":
|
|
915
|
-
if (data.dynamic) {
|
|
916
|
-
const toolInvocation = message.parts.filter((part) => part.type === "dynamic-tool").find((invocation) => invocation.toolCallId === data.toolCallId);
|
|
917
|
-
if (!toolInvocation) throw new Error("Tool invocation not found");
|
|
918
|
-
this.updateDynamicToolPart(message, {
|
|
919
|
-
toolCallId: data.toolCallId,
|
|
920
|
-
toolName: toolInvocation.toolName,
|
|
921
|
-
state: "output-error",
|
|
922
|
-
input: toolInvocation.input,
|
|
923
|
-
errorText: data.errorText
|
|
924
|
-
});
|
|
925
|
-
} else {
|
|
926
|
-
const toolInvocation = message.parts.filter(isToolUIPart).find((invocation) => invocation.toolCallId === data.toolCallId);
|
|
927
|
-
if (!toolInvocation) throw new Error("Tool invocation not found");
|
|
928
|
-
await this.updateToolPart(message, {
|
|
929
|
-
toolCallId: data.toolCallId,
|
|
930
|
-
toolName: getToolName(toolInvocation),
|
|
931
|
-
state: "output-error",
|
|
932
|
-
input: toolInvocation.input,
|
|
933
|
-
rawInput: "rawInput" in toolInvocation ? toolInvocation.rawInput : void 0,
|
|
934
|
-
errorText: data.errorText
|
|
935
|
-
});
|
|
936
|
-
}
|
|
937
|
-
break;
|
|
938
|
-
case "start-step":
|
|
939
|
-
message.parts.push({ type: "step-start" });
|
|
940
|
-
break;
|
|
941
|
-
case "finish-step":
|
|
942
|
-
activeTextParts = {};
|
|
943
|
-
activeReasoningParts = {};
|
|
944
|
-
break;
|
|
1129
|
+
const handled = applyChunkToParts(message.parts, data);
|
|
1130
|
+
if (data.type === "tool-approval-request" && this._streamingMessage) {
|
|
1131
|
+
const snapshot = {
|
|
1132
|
+
...this._streamingMessage,
|
|
1133
|
+
parts: [...this._streamingMessage.parts]
|
|
1134
|
+
};
|
|
1135
|
+
const sanitized = this._sanitizeMessageForPersistence(snapshot);
|
|
1136
|
+
const json = JSON.stringify(sanitized);
|
|
1137
|
+
this.sql`
|
|
1138
|
+
INSERT INTO cf_ai_chat_agent_messages (id, message)
|
|
1139
|
+
VALUES (${sanitized.id}, ${json})
|
|
1140
|
+
ON CONFLICT(id) DO UPDATE SET message = excluded.message
|
|
1141
|
+
`;
|
|
1142
|
+
this._approvalPersistedMessageId = sanitized.id;
|
|
1143
|
+
}
|
|
1144
|
+
if ((data.type === "tool-output-available" || data.type === "tool-output-error") && data.toolCallId) {
|
|
1145
|
+
if (!message.parts.some((p) => "toolCallId" in p && p.toolCallId === data.toolCallId)) if (data.type === "tool-output-available") this._findAndUpdateToolPart(data.toolCallId, "_streamSSEReply", [
|
|
1146
|
+
"input-available",
|
|
1147
|
+
"input-streaming",
|
|
1148
|
+
"approval-responded",
|
|
1149
|
+
"approval-requested"
|
|
1150
|
+
], (part) => ({
|
|
1151
|
+
...part,
|
|
1152
|
+
state: "output-available",
|
|
1153
|
+
output: data.output,
|
|
1154
|
+
...data.preliminary !== void 0 && { preliminary: data.preliminary }
|
|
1155
|
+
}));
|
|
1156
|
+
else this._findAndUpdateToolPart(data.toolCallId, "_streamSSEReply", [
|
|
1157
|
+
"input-available",
|
|
1158
|
+
"input-streaming",
|
|
1159
|
+
"approval-responded",
|
|
1160
|
+
"approval-requested"
|
|
1161
|
+
], (part) => ({
|
|
1162
|
+
...part,
|
|
1163
|
+
state: "output-error",
|
|
1164
|
+
errorText: data.errorText
|
|
1165
|
+
}));
|
|
1166
|
+
}
|
|
1167
|
+
if (!handled) switch (data.type) {
|
|
945
1168
|
case "start":
|
|
946
1169
|
if (data.messageId != null) message.id = data.messageId;
|
|
947
|
-
|
|
1170
|
+
if (data.messageMetadata != null) message.metadata = message.metadata ? {
|
|
1171
|
+
...message.metadata,
|
|
1172
|
+
...data.messageMetadata
|
|
1173
|
+
} : data.messageMetadata;
|
|
948
1174
|
break;
|
|
949
1175
|
case "finish":
|
|
950
|
-
await this.updateMessageMetadata(message, data.messageMetadata);
|
|
951
|
-
break;
|
|
952
1176
|
case "message-metadata":
|
|
953
|
-
|
|
1177
|
+
if (data.messageMetadata != null) message.metadata = message.metadata ? {
|
|
1178
|
+
...message.metadata,
|
|
1179
|
+
...data.messageMetadata
|
|
1180
|
+
} : data.messageMetadata;
|
|
954
1181
|
break;
|
|
1182
|
+
case "finish-step": break;
|
|
955
1183
|
case "error":
|
|
956
1184
|
this._broadcastChatMessage({
|
|
957
1185
|
error: true,
|
|
@@ -988,9 +1216,16 @@ var AIChatAgent = class extends Agent {
|
|
|
988
1216
|
type: "text-start",
|
|
989
1217
|
id
|
|
990
1218
|
}, continuation);
|
|
1219
|
+
const textPart = {
|
|
1220
|
+
type: "text",
|
|
1221
|
+
text: "",
|
|
1222
|
+
state: "streaming"
|
|
1223
|
+
};
|
|
1224
|
+
message.parts.push(textPart);
|
|
991
1225
|
while (true) {
|
|
992
1226
|
const { done, value } = await reader.read();
|
|
993
1227
|
if (done) {
|
|
1228
|
+
textPart.state = "done";
|
|
994
1229
|
this._broadcastTextEvent(streamId, {
|
|
995
1230
|
type: "text-end",
|
|
996
1231
|
id
|
|
@@ -1008,10 +1243,7 @@ var AIChatAgent = class extends Agent {
|
|
|
1008
1243
|
}
|
|
1009
1244
|
const chunk = decoder.decode(value);
|
|
1010
1245
|
if (chunk.length > 0) {
|
|
1011
|
-
|
|
1012
|
-
type: "text",
|
|
1013
|
-
text: chunk
|
|
1014
|
-
});
|
|
1246
|
+
textPart.text += chunk;
|
|
1015
1247
|
this._broadcastTextEvent(streamId, {
|
|
1016
1248
|
type: "text-delta",
|
|
1017
1249
|
id,
|
|
@@ -1020,64 +1252,6 @@ var AIChatAgent = class extends Agent {
|
|
|
1020
1252
|
}
|
|
1021
1253
|
}
|
|
1022
1254
|
}
|
|
1023
|
-
updateDynamicToolPart(message, options) {
|
|
1024
|
-
const part = message.parts.find((part) => part.type === "dynamic-tool" && part.toolCallId === options.toolCallId);
|
|
1025
|
-
const anyOptions = options;
|
|
1026
|
-
const anyPart = part;
|
|
1027
|
-
if (part != null) {
|
|
1028
|
-
part.state = options.state;
|
|
1029
|
-
anyPart.toolName = options.toolName;
|
|
1030
|
-
anyPart.input = anyOptions.input;
|
|
1031
|
-
anyPart.output = anyOptions.output;
|
|
1032
|
-
anyPart.errorText = anyOptions.errorText;
|
|
1033
|
-
anyPart.rawInput = anyOptions.rawInput ?? anyPart.rawInput;
|
|
1034
|
-
anyPart.preliminary = anyOptions.preliminary;
|
|
1035
|
-
if (anyOptions.providerMetadata != null && part.state === "input-available") part.callProviderMetadata = anyOptions.providerMetadata;
|
|
1036
|
-
} else message.parts.push({
|
|
1037
|
-
type: "dynamic-tool",
|
|
1038
|
-
toolName: options.toolName,
|
|
1039
|
-
toolCallId: options.toolCallId,
|
|
1040
|
-
state: options.state,
|
|
1041
|
-
input: anyOptions.input,
|
|
1042
|
-
output: anyOptions.output,
|
|
1043
|
-
errorText: anyOptions.errorText,
|
|
1044
|
-
preliminary: anyOptions.preliminary,
|
|
1045
|
-
...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}
|
|
1046
|
-
});
|
|
1047
|
-
}
|
|
1048
|
-
async updateToolPart(message, options) {
|
|
1049
|
-
const { isToolUIPart } = await import("ai");
|
|
1050
|
-
const part = message.parts.find((part) => isToolUIPart(part) && part.toolCallId === options.toolCallId);
|
|
1051
|
-
const anyOptions = options;
|
|
1052
|
-
const anyPart = part;
|
|
1053
|
-
if (part != null) {
|
|
1054
|
-
part.state = options.state;
|
|
1055
|
-
anyPart.input = anyOptions.input;
|
|
1056
|
-
anyPart.output = anyOptions.output;
|
|
1057
|
-
anyPart.errorText = anyOptions.errorText;
|
|
1058
|
-
anyPart.rawInput = anyOptions.rawInput;
|
|
1059
|
-
anyPart.preliminary = anyOptions.preliminary;
|
|
1060
|
-
anyPart.providerExecuted = anyOptions.providerExecuted ?? part.providerExecuted;
|
|
1061
|
-
if (anyOptions.providerMetadata != null && part.state === "input-available") part.callProviderMetadata = anyOptions.providerMetadata;
|
|
1062
|
-
} else message.parts.push({
|
|
1063
|
-
type: `tool-${options.toolName}`,
|
|
1064
|
-
toolCallId: options.toolCallId,
|
|
1065
|
-
state: options.state,
|
|
1066
|
-
input: anyOptions.input,
|
|
1067
|
-
output: anyOptions.output,
|
|
1068
|
-
rawInput: anyOptions.rawInput,
|
|
1069
|
-
errorText: anyOptions.errorText,
|
|
1070
|
-
providerExecuted: anyOptions.providerExecuted,
|
|
1071
|
-
preliminary: anyOptions.preliminary,
|
|
1072
|
-
...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}
|
|
1073
|
-
});
|
|
1074
|
-
}
|
|
1075
|
-
async updateMessageMetadata(message, metadata) {
|
|
1076
|
-
if (metadata != null) message.metadata = message.metadata != null ? {
|
|
1077
|
-
...message.metadata,
|
|
1078
|
-
...metadata
|
|
1079
|
-
} : metadata;
|
|
1080
|
-
}
|
|
1081
1255
|
/**
|
|
1082
1256
|
* Applies a tool approval response from the client, updating the persisted message.
|
|
1083
1257
|
* This is called when the client sends CF_AGENT_TOOL_APPROVAL for tools with needsApproval.
|
|
@@ -1088,71 +1262,17 @@ var AIChatAgent = class extends Agent {
|
|
|
1088
1262
|
* @returns true if the approval was applied, false if the message was not found
|
|
1089
1263
|
*/
|
|
1090
1264
|
async _applyToolApproval(toolCallId, approved) {
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
}
|
|
1098
|
-
if (!message) for (let attempt = 0; attempt < 10; attempt++) {
|
|
1099
|
-
message = this._findMessageByToolCallId(toolCallId);
|
|
1100
|
-
if (message) break;
|
|
1101
|
-
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
1102
|
-
}
|
|
1103
|
-
if (!message) {
|
|
1104
|
-
console.warn(`[AIChatAgent] _applyToolApproval: Could not find message with toolCallId ${toolCallId} after retries`);
|
|
1105
|
-
return false;
|
|
1106
|
-
}
|
|
1107
|
-
const isStreamingMessage = message === this._streamingMessage;
|
|
1108
|
-
let updated = false;
|
|
1109
|
-
if (isStreamingMessage) {
|
|
1110
|
-
for (const part of message.parts) if ("toolCallId" in part && part.toolCallId === toolCallId && "state" in part && (part.state === "input-available" || part.state === "approval-requested")) {
|
|
1111
|
-
part.state = "approval-responded";
|
|
1112
|
-
part.approval = { approved };
|
|
1113
|
-
updated = true;
|
|
1114
|
-
break;
|
|
1115
|
-
}
|
|
1116
|
-
} else {
|
|
1117
|
-
const updatedParts = message.parts.map((part) => {
|
|
1118
|
-
if ("toolCallId" in part && part.toolCallId === toolCallId && "state" in part && (part.state === "input-available" || part.state === "approval-requested")) {
|
|
1119
|
-
updated = true;
|
|
1120
|
-
return {
|
|
1121
|
-
...part,
|
|
1122
|
-
state: "approval-responded",
|
|
1123
|
-
approval: { approved }
|
|
1124
|
-
};
|
|
1125
|
-
}
|
|
1126
|
-
return part;
|
|
1127
|
-
});
|
|
1128
|
-
if (updated) {
|
|
1129
|
-
const updatedMessage = this._sanitizeMessageForPersistence({
|
|
1130
|
-
...message,
|
|
1131
|
-
parts: updatedParts
|
|
1132
|
-
});
|
|
1133
|
-
this.sql`
|
|
1134
|
-
update cf_ai_chat_agent_messages
|
|
1135
|
-
set message = ${JSON.stringify(updatedMessage)}
|
|
1136
|
-
where id = ${message.id}
|
|
1137
|
-
`;
|
|
1138
|
-
this.messages = autoTransformMessages(this._loadMessagesFromDb());
|
|
1265
|
+
return this._findAndUpdateToolPart(toolCallId, "_applyToolApproval", ["input-available", "approval-requested"], (part) => ({
|
|
1266
|
+
...part,
|
|
1267
|
+
state: "approval-responded",
|
|
1268
|
+
approval: {
|
|
1269
|
+
...part.approval,
|
|
1270
|
+
approved
|
|
1139
1271
|
}
|
|
1140
|
-
}
|
|
1141
|
-
if (!updated) {
|
|
1142
|
-
console.warn(`[AIChatAgent] _applyToolApproval: Tool part with toolCallId ${toolCallId} not in input-available or approval-requested state`);
|
|
1143
|
-
return false;
|
|
1144
|
-
}
|
|
1145
|
-
if (!isStreamingMessage) {
|
|
1146
|
-
const broadcastMessage = this._findMessageByToolCallId(toolCallId);
|
|
1147
|
-
if (broadcastMessage) this._broadcastChatMessage({
|
|
1148
|
-
type: MessageType.CF_AGENT_MESSAGE_UPDATED,
|
|
1149
|
-
message: broadcastMessage
|
|
1150
|
-
});
|
|
1151
|
-
}
|
|
1152
|
-
return true;
|
|
1272
|
+
}));
|
|
1153
1273
|
}
|
|
1154
1274
|
async _reply(id, response, excludeBroadcastIds = [], options = {}) {
|
|
1155
|
-
const { continuation = false } = options;
|
|
1275
|
+
const { continuation = false, chatMessageId } = options;
|
|
1156
1276
|
return this._tryCatchChat(async () => {
|
|
1157
1277
|
if (!response.body) {
|
|
1158
1278
|
this._broadcastChatMessage({
|
|
@@ -1177,6 +1297,7 @@ var AIChatAgent = class extends Agent {
|
|
|
1177
1297
|
});
|
|
1178
1298
|
const isSSE = (response.headers.get("content-type") || "").includes("text/event-stream");
|
|
1179
1299
|
const streamCompleted = { value: false };
|
|
1300
|
+
let earlyPersistedId = null;
|
|
1180
1301
|
try {
|
|
1181
1302
|
if (isSSE) await this._streamSSEReply(id, streamId, reader, message, streamCompleted, continuation);
|
|
1182
1303
|
else await this._sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation);
|
|
@@ -1195,8 +1316,29 @@ var AIChatAgent = class extends Agent {
|
|
|
1195
1316
|
throw error;
|
|
1196
1317
|
} finally {
|
|
1197
1318
|
reader.releaseLock();
|
|
1319
|
+
this._streamingMessage = null;
|
|
1320
|
+
earlyPersistedId = this._approvalPersistedMessageId;
|
|
1321
|
+
this._approvalPersistedMessageId = null;
|
|
1322
|
+
if (this._streamCompletionResolve) {
|
|
1323
|
+
this._streamCompletionResolve();
|
|
1324
|
+
this._streamCompletionResolve = null;
|
|
1325
|
+
this._streamCompletionPromise = null;
|
|
1326
|
+
}
|
|
1327
|
+
if (chatMessageId) {
|
|
1328
|
+
this._removeAbortController(chatMessageId);
|
|
1329
|
+
if (streamCompleted.value) this.observability?.emit({
|
|
1330
|
+
displayMessage: continuation ? "Chat message response (tool continuation)" : "Chat message response",
|
|
1331
|
+
id: chatMessageId,
|
|
1332
|
+
payload: {},
|
|
1333
|
+
timestamp: Date.now(),
|
|
1334
|
+
type: "message:response"
|
|
1335
|
+
}, this.ctx);
|
|
1336
|
+
}
|
|
1198
1337
|
}
|
|
1199
|
-
if (message.parts.length > 0) if (
|
|
1338
|
+
if (message.parts.length > 0) if (earlyPersistedId) {
|
|
1339
|
+
const updatedMessages = this.messages.map((msg) => msg.id === earlyPersistedId ? message : msg);
|
|
1340
|
+
await this.persistMessages(updatedMessages, excludeBroadcastIds);
|
|
1341
|
+
} else if (continuation) {
|
|
1200
1342
|
let lastAssistantIdx = -1;
|
|
1201
1343
|
for (let i = this.messages.length - 1; i >= 0; i--) if (this.messages[i].role === "assistant") {
|
|
1202
1344
|
lastAssistantIdx = i;
|
|
@@ -1213,31 +1355,9 @@ var AIChatAgent = class extends Agent {
|
|
|
1213
1355
|
await this.persistMessages(updatedMessages, excludeBroadcastIds);
|
|
1214
1356
|
} else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
|
|
1215
1357
|
} else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
|
|
1216
|
-
this._streamingMessage = null;
|
|
1217
|
-
if (this._streamCompletionResolve) {
|
|
1218
|
-
this._streamCompletionResolve();
|
|
1219
|
-
this._streamCompletionResolve = null;
|
|
1220
|
-
this._streamCompletionPromise = null;
|
|
1221
|
-
}
|
|
1222
1358
|
});
|
|
1223
1359
|
}
|
|
1224
1360
|
/**
|
|
1225
|
-
* Mark a stream as errored and clean up state.
|
|
1226
|
-
* @param streamId - The stream to mark as errored
|
|
1227
|
-
* @internal Protected for testing purposes.
|
|
1228
|
-
*/
|
|
1229
|
-
_markStreamError(streamId) {
|
|
1230
|
-
this._flushChunkBuffer();
|
|
1231
|
-
this.sql`
|
|
1232
|
-
update cf_ai_chat_stream_metadata
|
|
1233
|
-
set status = 'error', completed_at = ${Date.now()}
|
|
1234
|
-
where id = ${streamId}
|
|
1235
|
-
`;
|
|
1236
|
-
this._activeStreamId = null;
|
|
1237
|
-
this._activeRequestId = null;
|
|
1238
|
-
this._streamChunkIndex = 0;
|
|
1239
|
-
}
|
|
1240
|
-
/**
|
|
1241
1361
|
* For the given message id, look up its associated AbortController
|
|
1242
1362
|
* If the AbortController does not exist, create and store one in memory
|
|
1243
1363
|
*
|
|
@@ -1272,11 +1392,7 @@ var AIChatAgent = class extends Agent {
|
|
|
1272
1392
|
*/
|
|
1273
1393
|
async destroy() {
|
|
1274
1394
|
this._destroyAbortControllers();
|
|
1275
|
-
this.
|
|
1276
|
-
this.sql`drop table if exists cf_ai_chat_stream_chunks`;
|
|
1277
|
-
this.sql`drop table if exists cf_ai_chat_stream_metadata`;
|
|
1278
|
-
this._activeStreamId = null;
|
|
1279
|
-
this._activeRequestId = null;
|
|
1395
|
+
this._resumableStream.destroy();
|
|
1280
1396
|
await super.destroy();
|
|
1281
1397
|
}
|
|
1282
1398
|
};
|