@cloudflare/ai-chat 0.3.1 → 0.4.0
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/dist/index.d.ts +692 -9
- package/dist/index.js +469 -767
- package/dist/index.js.map +1 -1
- package/dist/react.d.ts +94 -16
- package/dist/react.js +126 -88
- package/dist/react.js.map +1 -1
- package/package.json +6 -11
- package/dist/experimental/forever.d.ts +0 -7
- package/dist/experimental/forever.js +0 -10
- package/dist/experimental/forever.js.map +0 -1
- package/dist/index-BZiT3pOq.d.ts +0 -901
- package/dist/message-builder-BAgcFJMf.js +0 -244
- package/dist/message-builder-BAgcFJMf.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,340 +1,120 @@
|
|
|
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-BAgcFJMf.js";
|
|
4
|
-
import { jsonSchema, tool } from "ai";
|
|
5
3
|
import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
|
|
4
|
+
import { AbortRegistry, ContinuationState, ROW_MAX_BYTES, ResumableStream, TurnQueue, applyChunkToParts, byteLength, createToolsFromClientSchemas, sanitizeMessage } from "agents/chat";
|
|
6
5
|
import { nanoid } from "nanoid";
|
|
7
|
-
//#region src/
|
|
6
|
+
//#region src/message-reconciler.ts
|
|
8
7
|
/**
|
|
9
|
-
*
|
|
10
|
-
* stream chunks in SQLite. Extracted from AIChatAgent to separate concerns.
|
|
8
|
+
* Reconcile incoming client messages against server state.
|
|
11
9
|
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
* -
|
|
15
|
-
*
|
|
16
|
-
* -
|
|
17
|
-
* -
|
|
10
|
+
* 1. Merges server-known tool outputs into incoming messages that still
|
|
11
|
+
* show stale states (input-available, approval-requested, approval-responded)
|
|
12
|
+
* 2. Reconciles assistant IDs: exact match → content-key match → toolCallId match
|
|
13
|
+
*
|
|
14
|
+
* @param incoming - Messages from the client
|
|
15
|
+
* @param serverMessages - Current server-side messages (source of truth)
|
|
16
|
+
* @param sanitizeForContentKey - Function to sanitize a message before computing
|
|
17
|
+
* its content key (typically strips ephemeral provider metadata)
|
|
18
|
+
* @returns Reconciled messages ready for persistence
|
|
18
19
|
*/
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
const
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
this._streamChunkIndex = 0;
|
|
37
|
-
this._isLive = false;
|
|
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
|
-
* Whether the active stream has a live LLM reader (started in this
|
|
70
|
-
* instance) vs being restored from SQLite after hibernation (orphaned).
|
|
71
|
-
*/
|
|
72
|
-
get isLive() {
|
|
73
|
-
return this._isLive;
|
|
74
|
-
}
|
|
75
|
-
/**
|
|
76
|
-
* Start tracking a new stream for resumable streaming.
|
|
77
|
-
* Creates metadata entry in SQLite and sets up tracking state.
|
|
78
|
-
* @param requestId - The unique ID of the chat request
|
|
79
|
-
* @returns The generated stream ID
|
|
80
|
-
*/
|
|
81
|
-
start(requestId) {
|
|
82
|
-
this.flushBuffer();
|
|
83
|
-
const streamId = nanoid();
|
|
84
|
-
this._activeStreamId = streamId;
|
|
85
|
-
this._activeRequestId = requestId;
|
|
86
|
-
this._streamChunkIndex = 0;
|
|
87
|
-
this._isLive = true;
|
|
88
|
-
this.sql`
|
|
89
|
-
insert into cf_ai_chat_stream_metadata (id, request_id, status, created_at)
|
|
90
|
-
values (${streamId}, ${requestId}, 'streaming', ${Date.now()})
|
|
91
|
-
`;
|
|
92
|
-
return streamId;
|
|
93
|
-
}
|
|
94
|
-
/**
|
|
95
|
-
* Mark a stream as completed and flush any pending chunks.
|
|
96
|
-
* @param streamId - The stream to mark as completed
|
|
97
|
-
*/
|
|
98
|
-
complete(streamId) {
|
|
99
|
-
this.flushBuffer();
|
|
100
|
-
this.sql`
|
|
101
|
-
update cf_ai_chat_stream_metadata
|
|
102
|
-
set status = 'completed', completed_at = ${Date.now()}
|
|
103
|
-
where id = ${streamId}
|
|
104
|
-
`;
|
|
105
|
-
this._activeStreamId = null;
|
|
106
|
-
this._activeRequestId = null;
|
|
107
|
-
this._streamChunkIndex = 0;
|
|
108
|
-
this._isLive = false;
|
|
109
|
-
this._maybeCleanupOldStreams();
|
|
110
|
-
}
|
|
111
|
-
/**
|
|
112
|
-
* Mark a stream as errored and clean up state.
|
|
113
|
-
* @param streamId - The stream to mark as errored
|
|
114
|
-
*/
|
|
115
|
-
markError(streamId) {
|
|
116
|
-
this.flushBuffer();
|
|
117
|
-
this.sql`
|
|
118
|
-
update cf_ai_chat_stream_metadata
|
|
119
|
-
set status = 'error', completed_at = ${Date.now()}
|
|
120
|
-
where id = ${streamId}
|
|
121
|
-
`;
|
|
122
|
-
this._activeStreamId = null;
|
|
123
|
-
this._activeRequestId = null;
|
|
124
|
-
this._streamChunkIndex = 0;
|
|
125
|
-
this._isLive = false;
|
|
126
|
-
}
|
|
127
|
-
static {
|
|
128
|
-
this.CHUNK_MAX_BYTES = 18e5;
|
|
20
|
+
function reconcileMessages(incoming, serverMessages, sanitizeForContentKey) {
|
|
21
|
+
return reconcileAssistantIds(mergeServerToolOutputs(incoming, serverMessages), serverMessages, sanitizeForContentKey);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* For a single message, resolve its ID by matching toolCallId against server state.
|
|
25
|
+
* Prevents duplicate DB rows when client IDs differ from server IDs.
|
|
26
|
+
* Tool call IDs are unique per conversation, so matching is safe regardless of state.
|
|
27
|
+
*/
|
|
28
|
+
function resolveToolMergeId(message, serverMessages) {
|
|
29
|
+
if (message.role !== "assistant") return message;
|
|
30
|
+
for (const part of message.parts) if ("toolCallId" in part && part.toolCallId) {
|
|
31
|
+
const toolCallId = part.toolCallId;
|
|
32
|
+
const existing = findMessageByToolCallId(serverMessages, toolCallId);
|
|
33
|
+
if (existing && existing.id !== message.id) return {
|
|
34
|
+
...message,
|
|
35
|
+
id: existing.id
|
|
36
|
+
};
|
|
129
37
|
}
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
if (
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
38
|
+
return message;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Content key for assistant messages used for dedup of identical short replies.
|
|
42
|
+
* Returns JSON of sanitized parts, or undefined for non-assistant messages.
|
|
43
|
+
*/
|
|
44
|
+
function assistantContentKey(message, sanitize) {
|
|
45
|
+
if (message.role !== "assistant") return;
|
|
46
|
+
const sanitized = sanitize ? sanitize(message) : message;
|
|
47
|
+
return JSON.stringify(sanitized.parts);
|
|
48
|
+
}
|
|
49
|
+
function mergeServerToolOutputs(incoming, serverMessages) {
|
|
50
|
+
const serverToolOutputs = /* @__PURE__ */ new Map();
|
|
51
|
+
for (const msg of serverMessages) {
|
|
52
|
+
if (msg.role !== "assistant") continue;
|
|
53
|
+
for (const part of msg.parts) if ("toolCallId" in part && "state" in part && part.state === "output-available" && "output" in part) serverToolOutputs.set(part.toolCallId, part.output);
|
|
54
|
+
}
|
|
55
|
+
if (serverToolOutputs.size === 0) return incoming;
|
|
56
|
+
return incoming.map((msg) => {
|
|
57
|
+
if (msg.role !== "assistant") return msg;
|
|
58
|
+
let hasChanges = false;
|
|
59
|
+
const updatedParts = msg.parts.map((part) => {
|
|
60
|
+
if ("toolCallId" in part && "state" in part && (part.state === "input-available" || part.state === "approval-requested" || part.state === "approval-responded") && serverToolOutputs.has(part.toolCallId)) {
|
|
61
|
+
hasChanges = true;
|
|
62
|
+
return {
|
|
63
|
+
...part,
|
|
64
|
+
state: "output-available",
|
|
65
|
+
output: serverToolOutputs.get(part.toolCallId)
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
return part;
|
|
150
69
|
});
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
insert into cf_ai_chat_stream_chunks (id, stream_id, body, chunk_index, created_at)
|
|
167
|
-
values (${chunk.id}, ${chunk.streamId}, ${chunk.body}, ${chunk.index}, ${now})
|
|
168
|
-
`;
|
|
169
|
-
} finally {
|
|
170
|
-
this._isFlushingChunks = false;
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
/**
|
|
174
|
-
* Send stored stream chunks to a connection for replay.
|
|
175
|
-
* Chunks are marked with replay: true so the client can batch-apply them.
|
|
176
|
-
*
|
|
177
|
-
* Three outcomes:
|
|
178
|
-
* - **Live stream**: sends chunks + `replayComplete` — client flushes and
|
|
179
|
-
* continues receiving live chunks from the LLM reader.
|
|
180
|
-
* - **Orphaned stream** (restored from SQLite after hibernation, no reader):
|
|
181
|
-
* sends chunks + `done` and completes the stream. The caller should
|
|
182
|
-
* reconstruct and persist the partial message from the stored chunks.
|
|
183
|
-
* - **Completed during replay** (defensive): sends chunks + `done`.
|
|
184
|
-
*
|
|
185
|
-
* @param connection - The WebSocket connection
|
|
186
|
-
* @param requestId - The original request ID
|
|
187
|
-
* @returns The stream ID if the stream was orphaned and finalized, null otherwise.
|
|
188
|
-
* When non-null the caller should reconstruct the message from chunks.
|
|
189
|
-
*/
|
|
190
|
-
replayChunks(connection, requestId) {
|
|
191
|
-
const streamId = this._activeStreamId;
|
|
192
|
-
if (!streamId) return null;
|
|
193
|
-
this.flushBuffer();
|
|
194
|
-
const chunks = this.sql`
|
|
195
|
-
select * from cf_ai_chat_stream_chunks
|
|
196
|
-
where stream_id = ${streamId}
|
|
197
|
-
order by chunk_index asc
|
|
198
|
-
`;
|
|
199
|
-
for (const chunk of chunks || []) connection.send(JSON.stringify({
|
|
200
|
-
body: chunk.body,
|
|
201
|
-
done: false,
|
|
202
|
-
id: requestId,
|
|
203
|
-
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
|
|
204
|
-
replay: true
|
|
205
|
-
}));
|
|
206
|
-
if (this._activeStreamId !== streamId) {
|
|
207
|
-
connection.send(JSON.stringify({
|
|
208
|
-
body: "",
|
|
209
|
-
done: true,
|
|
210
|
-
id: requestId,
|
|
211
|
-
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
|
|
212
|
-
replay: true
|
|
213
|
-
}));
|
|
214
|
-
return null;
|
|
215
|
-
}
|
|
216
|
-
if (!this._isLive) {
|
|
217
|
-
connection.send(JSON.stringify({
|
|
218
|
-
body: "",
|
|
219
|
-
done: true,
|
|
220
|
-
id: requestId,
|
|
221
|
-
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
|
|
222
|
-
replay: true
|
|
223
|
-
}));
|
|
224
|
-
this.complete(streamId);
|
|
225
|
-
return streamId;
|
|
70
|
+
return hasChanges ? {
|
|
71
|
+
...msg,
|
|
72
|
+
parts: updatedParts
|
|
73
|
+
} : msg;
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
function reconcileAssistantIds(incoming, serverMessages, sanitize) {
|
|
77
|
+
if (serverMessages.length === 0) return incoming;
|
|
78
|
+
const claimedServerIndices = /* @__PURE__ */ new Set();
|
|
79
|
+
const exactMatchMap = /* @__PURE__ */ new Map();
|
|
80
|
+
for (let i = 0; i < incoming.length; i++) {
|
|
81
|
+
const serverIdx = serverMessages.findIndex((sm, si) => !claimedServerIndices.has(si) && sm.id === incoming[i].id);
|
|
82
|
+
if (serverIdx !== -1) {
|
|
83
|
+
claimedServerIndices.add(serverIdx);
|
|
84
|
+
exactMatchMap.set(i, serverIdx);
|
|
226
85
|
}
|
|
227
|
-
connection.send(JSON.stringify({
|
|
228
|
-
body: "",
|
|
229
|
-
done: false,
|
|
230
|
-
id: requestId,
|
|
231
|
-
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
|
|
232
|
-
replay: true,
|
|
233
|
-
replayComplete: true
|
|
234
|
-
}));
|
|
235
|
-
return null;
|
|
236
86
|
}
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
this.sql`delete from cf_ai_chat_stream_chunks where stream_id = ${stream.id}`;
|
|
253
|
-
this.sql`delete from cf_ai_chat_stream_metadata where id = ${stream.id}`;
|
|
254
|
-
console.warn(`[ResumableStream] Deleted stale stream ${stream.id} (age: ${Math.round(streamAge / 1e3)}s)`);
|
|
255
|
-
return;
|
|
87
|
+
return incoming.map((incomingMessage, incomingIdx) => {
|
|
88
|
+
if (exactMatchMap.has(incomingIdx)) return incomingMessage;
|
|
89
|
+
if (incomingMessage.role !== "assistant" || hasToolCallPart(incomingMessage)) return incomingMessage;
|
|
90
|
+
const incomingKey = assistantContentKey(incomingMessage, sanitize);
|
|
91
|
+
if (!incomingKey) return incomingMessage;
|
|
92
|
+
for (let i = 0; i < serverMessages.length; i++) {
|
|
93
|
+
if (claimedServerIndices.has(i)) continue;
|
|
94
|
+
const serverMessage = serverMessages[i];
|
|
95
|
+
if (serverMessage.role !== "assistant" || hasToolCallPart(serverMessage)) continue;
|
|
96
|
+
if (assistantContentKey(serverMessage, sanitize) === incomingKey) {
|
|
97
|
+
claimedServerIndices.add(i);
|
|
98
|
+
return {
|
|
99
|
+
...incomingMessage,
|
|
100
|
+
id: serverMessage.id
|
|
101
|
+
};
|
|
256
102
|
}
|
|
257
|
-
this._activeStreamId = stream.id;
|
|
258
|
-
this._activeRequestId = stream.request_id;
|
|
259
|
-
const lastChunk = this.sql`
|
|
260
|
-
select max(chunk_index) as max_index
|
|
261
|
-
from cf_ai_chat_stream_chunks
|
|
262
|
-
where stream_id = ${this._activeStreamId}
|
|
263
|
-
`;
|
|
264
|
-
this._streamChunkIndex = lastChunk && lastChunk[0]?.max_index != null ? lastChunk[0].max_index + 1 : 0;
|
|
265
103
|
}
|
|
104
|
+
return incomingMessage;
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
function hasToolCallPart(message) {
|
|
108
|
+
return message.parts.some((part) => "toolCallId" in part);
|
|
109
|
+
}
|
|
110
|
+
function findMessageByToolCallId(messages, toolCallId) {
|
|
111
|
+
for (const msg of messages) {
|
|
112
|
+
if (msg.role !== "assistant") continue;
|
|
113
|
+
for (const part of msg.parts) if ("toolCallId" in part && part.toolCallId === toolCallId) return msg;
|
|
266
114
|
}
|
|
267
|
-
|
|
268
|
-
* Clear all stream data (called on chat history clear).
|
|
269
|
-
*/
|
|
270
|
-
clearAll() {
|
|
271
|
-
this._chunkBuffer = [];
|
|
272
|
-
this.sql`delete from cf_ai_chat_stream_chunks`;
|
|
273
|
-
this.sql`delete from cf_ai_chat_stream_metadata`;
|
|
274
|
-
this._activeStreamId = null;
|
|
275
|
-
this._activeRequestId = null;
|
|
276
|
-
this._streamChunkIndex = 0;
|
|
277
|
-
}
|
|
278
|
-
/**
|
|
279
|
-
* Drop all stream tables (called on destroy).
|
|
280
|
-
*/
|
|
281
|
-
destroy() {
|
|
282
|
-
this.flushBuffer();
|
|
283
|
-
this.sql`drop table if exists cf_ai_chat_stream_chunks`;
|
|
284
|
-
this.sql`drop table if exists cf_ai_chat_stream_metadata`;
|
|
285
|
-
this._activeStreamId = null;
|
|
286
|
-
this._activeRequestId = null;
|
|
287
|
-
}
|
|
288
|
-
_maybeCleanupOldStreams() {
|
|
289
|
-
const now = Date.now();
|
|
290
|
-
if (now - this._lastCleanupTime < CLEANUP_INTERVAL_MS) return;
|
|
291
|
-
this._lastCleanupTime = now;
|
|
292
|
-
const cutoff = now - CLEANUP_AGE_THRESHOLD_MS;
|
|
293
|
-
this.sql`
|
|
294
|
-
delete from cf_ai_chat_stream_chunks
|
|
295
|
-
where stream_id in (
|
|
296
|
-
select id from cf_ai_chat_stream_metadata
|
|
297
|
-
where status in ('completed', 'error') and completed_at < ${cutoff}
|
|
298
|
-
)
|
|
299
|
-
`;
|
|
300
|
-
this.sql`
|
|
301
|
-
delete from cf_ai_chat_stream_metadata
|
|
302
|
-
where status in ('completed', 'error') and completed_at < ${cutoff}
|
|
303
|
-
`;
|
|
304
|
-
}
|
|
305
|
-
/** @internal For testing only */
|
|
306
|
-
getStreamChunks(streamId) {
|
|
307
|
-
return this.sql`
|
|
308
|
-
select body, chunk_index from cf_ai_chat_stream_chunks
|
|
309
|
-
where stream_id = ${streamId}
|
|
310
|
-
order by chunk_index asc
|
|
311
|
-
` || [];
|
|
312
|
-
}
|
|
313
|
-
/** @internal For testing only */
|
|
314
|
-
getStreamMetadata(streamId) {
|
|
315
|
-
const result = this.sql`
|
|
316
|
-
select status, request_id from cf_ai_chat_stream_metadata
|
|
317
|
-
where id = ${streamId}
|
|
318
|
-
`;
|
|
319
|
-
return result && result.length > 0 ? result[0] : null;
|
|
320
|
-
}
|
|
321
|
-
/** @internal For testing only */
|
|
322
|
-
getAllStreamMetadata() {
|
|
323
|
-
return this.sql`select id, status, request_id, created_at from cf_ai_chat_stream_metadata` || [];
|
|
324
|
-
}
|
|
325
|
-
/** @internal For testing only */
|
|
326
|
-
insertStaleStream(streamId, requestId, ageMs) {
|
|
327
|
-
const createdAt = Date.now() - ageMs;
|
|
328
|
-
this.sql`
|
|
329
|
-
insert into cf_ai_chat_stream_metadata (id, request_id, status, created_at)
|
|
330
|
-
values (${streamId}, ${requestId}, 'streaming', ${createdAt})
|
|
331
|
-
`;
|
|
332
|
-
}
|
|
333
|
-
};
|
|
115
|
+
}
|
|
334
116
|
//#endregion
|
|
335
117
|
//#region src/index.ts
|
|
336
|
-
/** Shared encoder for UTF-8 byte length measurement */
|
|
337
|
-
const textEncoder = new TextEncoder();
|
|
338
118
|
const TIMED_OUT = Symbol("timed-out");
|
|
339
119
|
/**
|
|
340
120
|
* Provider-executed tool fields that contain opaque replay tokens and must be
|
|
@@ -366,60 +146,18 @@ function isValidMessageStructure(msg) {
|
|
|
366
146
|
if (!Array.isArray(m.parts)) return false;
|
|
367
147
|
return true;
|
|
368
148
|
}
|
|
369
|
-
/**
|
|
370
|
-
* Converts client tool schemas to AI SDK tool format.
|
|
371
|
-
*
|
|
372
|
-
* These tools have no `execute` function — when the AI model calls them,
|
|
373
|
-
* the tool call is sent back to the client for execution.
|
|
374
|
-
*
|
|
375
|
-
* **For most apps**, define tools on the server with `tool()` from `"ai"`
|
|
376
|
-
* for full Zod type safety. This helper is intended for SDK/platform use
|
|
377
|
-
* cases where the tool surface is determined dynamically by the client.
|
|
378
|
-
*
|
|
379
|
-
* @param clientTools - Array of tool schemas from the client
|
|
380
|
-
* @returns Record of AI SDK tools that can be spread into your tools object
|
|
381
|
-
*
|
|
382
|
-
* @example
|
|
383
|
-
* ```typescript
|
|
384
|
-
* // In onChatMessage:
|
|
385
|
-
* const tools = {
|
|
386
|
-
* ...createToolsFromClientSchemas(options.clientTools),
|
|
387
|
-
* // server-defined tools with execute:
|
|
388
|
-
* myServerTool: tool({ ... }),
|
|
389
|
-
* };
|
|
390
|
-
* ```
|
|
391
|
-
*/
|
|
392
|
-
function createToolsFromClientSchemas(clientTools) {
|
|
393
|
-
if (!clientTools || clientTools.length === 0) return {};
|
|
394
|
-
const seenNames = /* @__PURE__ */ new Set();
|
|
395
|
-
for (const t of clientTools) {
|
|
396
|
-
if (seenNames.has(t.name)) console.warn(`[createToolsFromClientSchemas] Duplicate tool name "${t.name}" found. Later definitions will override earlier ones.`);
|
|
397
|
-
seenNames.add(t.name);
|
|
398
|
-
}
|
|
399
|
-
return Object.fromEntries(clientTools.map((t) => [t.name, tool({
|
|
400
|
-
description: t.description ?? "",
|
|
401
|
-
inputSchema: jsonSchema(t.parameters ?? { type: "object" })
|
|
402
|
-
})]));
|
|
403
|
-
}
|
|
404
149
|
const decoder = new TextDecoder();
|
|
405
150
|
/**
|
|
406
151
|
* Extension of Agent with built-in chat capabilities
|
|
407
152
|
* @template Env Environment type containing bindings
|
|
408
153
|
*/
|
|
409
154
|
var AIChatAgent = class AIChatAgent extends Agent {
|
|
410
|
-
static {
|
|
411
|
-
this.ROW_MAX_BYTES = 18e5;
|
|
412
|
-
}
|
|
413
155
|
static {
|
|
414
156
|
this.AUTO_CONTINUATION_COALESCE_MS = 10;
|
|
415
157
|
}
|
|
416
158
|
static {
|
|
417
159
|
this.MESSAGE_DEBOUNCE_MS = 750;
|
|
418
160
|
}
|
|
419
|
-
/** Measure UTF-8 byte length of a string (accurate for SQLite row limits). */
|
|
420
|
-
static _byteLength(s) {
|
|
421
|
-
return textEncoder.encode(s).byteLength;
|
|
422
|
-
}
|
|
423
161
|
constructor(ctx, env) {
|
|
424
162
|
super(ctx, env);
|
|
425
163
|
this._streamingMessage = null;
|
|
@@ -427,27 +165,15 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
427
165
|
this._insideResponseHook = false;
|
|
428
166
|
this._pendingInteractionPromise = null;
|
|
429
167
|
this._approvalPersistedMessageId = null;
|
|
430
|
-
this.
|
|
431
|
-
this.
|
|
432
|
-
this._chatEpoch = 0;
|
|
433
|
-
this._queuedChatTurnCountsByEpoch = /* @__PURE__ */ new Map();
|
|
168
|
+
this._turnQueue = new TurnQueue();
|
|
169
|
+
this.unstable_chatRecovery = false;
|
|
434
170
|
this._mergeQueuedUserStartIndexByEpoch = /* @__PURE__ */ new Map();
|
|
435
171
|
this._submitSequence = 0;
|
|
436
172
|
this._latestOverlappingSubmitSequence = 0;
|
|
437
173
|
this._activeDebounceTimer = null;
|
|
438
174
|
this._activeDebounceResolve = null;
|
|
439
175
|
this._pendingResumeConnections = /* @__PURE__ */ new Set();
|
|
440
|
-
this.
|
|
441
|
-
this._pendingAutoContinuation = false;
|
|
442
|
-
this._pendingAutoContinuationConnection = null;
|
|
443
|
-
this._pendingAutoContinuationConnectionId = null;
|
|
444
|
-
this._activeAutoContinuationConnectionId = null;
|
|
445
|
-
this._activeAutoContinuationRequestId = null;
|
|
446
|
-
this._pendingAutoContinuationPastCoalesce = false;
|
|
447
|
-
this._pendingAutoContinuationErrorPrefix = null;
|
|
448
|
-
this._pendingAutoContinuationRequestId = null;
|
|
449
|
-
this._pendingAutoContinuationPrerequisite = null;
|
|
450
|
-
this._deferredAutoContinuation = null;
|
|
176
|
+
this._continuation = new ContinuationState();
|
|
451
177
|
this._persistedMessageCache = /* @__PURE__ */ new Map();
|
|
452
178
|
this.maxPersistedMessages = void 0;
|
|
453
179
|
this.messageConcurrency = "queue";
|
|
@@ -464,7 +190,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
464
190
|
this._restoreRequestContext();
|
|
465
191
|
this._resumableStream = new ResumableStream(this.sql.bind(this));
|
|
466
192
|
this.messages = autoTransformMessages(this._loadMessagesFromDb());
|
|
467
|
-
this.
|
|
193
|
+
this._abortRegistry = new AbortRegistry();
|
|
468
194
|
const _onConnect = this.onConnect.bind(this);
|
|
469
195
|
this.onConnect = async (connection, ctx) => {
|
|
470
196
|
if (this._resumableStream.hasActiveStream()) this._notifyStreamResuming(connection);
|
|
@@ -473,9 +199,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
473
199
|
const _onClose = this.onClose.bind(this);
|
|
474
200
|
this.onClose = async (connection, code, reason, wasClean) => {
|
|
475
201
|
this._pendingResumeConnections.delete(connection.id);
|
|
476
|
-
this.
|
|
477
|
-
if (this.
|
|
478
|
-
if (this.
|
|
202
|
+
this._continuation.awaitingConnections.delete(connection.id);
|
|
203
|
+
if (this._continuation.pending?.connectionId === connection.id) this._continuation.pending = null;
|
|
204
|
+
if (this._continuation.activeConnectionId === connection.id) this._continuation.activeConnectionId = null;
|
|
479
205
|
return _onClose(connection, code, reason, wasClean);
|
|
480
206
|
};
|
|
481
207
|
const _onMessage = this.onMessage.bind(this);
|
|
@@ -506,7 +232,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
506
232
|
const requestTrigger = _trigger === "regenerate-message" ? "regenerate-message" : "submit-message";
|
|
507
233
|
const requestClientTools = clientTools?.length ? clientTools : void 0;
|
|
508
234
|
const requestBody = Object.keys(customBody).length > 0 ? customBody : void 0;
|
|
509
|
-
const epoch = this.
|
|
235
|
+
const epoch = this._turnQueue.generation;
|
|
510
236
|
const concurrencyDecision = this._getSubmitConcurrencyDecision(requestTrigger);
|
|
511
237
|
if (concurrencyDecision.action === "drop") {
|
|
512
238
|
this._rollbackDroppedSubmit(connection);
|
|
@@ -520,17 +246,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
520
246
|
await this.persistMessages(transformedMessages, [connection.id], { _deleteStaleRows: true });
|
|
521
247
|
if (concurrencyDecision.mergeQueuedMessages) await this._mergeQueuedUserMessages(epoch);
|
|
522
248
|
return this._runExclusiveChatTurn(chatMessageId, async () => {
|
|
523
|
-
if (this._chatEpoch !== epoch) {
|
|
524
|
-
this._completeSkippedRequest(connection, chatMessageId);
|
|
525
|
-
return;
|
|
526
|
-
}
|
|
527
249
|
if (this._isSupersededSubmit(concurrencyDecision.submitSequence)) {
|
|
528
250
|
this._completeSkippedRequest(connection, chatMessageId);
|
|
529
251
|
return;
|
|
530
252
|
}
|
|
531
253
|
if (concurrencyDecision.debounceUntilMs !== null) {
|
|
532
254
|
await this._waitForTimestamp(concurrencyDecision.debounceUntilMs);
|
|
533
|
-
if (this.
|
|
255
|
+
if (this._turnQueue.generation !== epoch) {
|
|
534
256
|
this._completeSkippedRequest(connection, chatMessageId);
|
|
535
257
|
return;
|
|
536
258
|
}
|
|
@@ -541,7 +263,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
541
263
|
}
|
|
542
264
|
if (concurrencyDecision.mergeQueuedMessages) {
|
|
543
265
|
await this._mergeQueuedUserMessages(epoch);
|
|
544
|
-
if (this.
|
|
266
|
+
if (this._turnQueue.generation !== epoch) {
|
|
545
267
|
this._completeSkippedRequest(connection, chatMessageId);
|
|
546
268
|
return;
|
|
547
269
|
}
|
|
@@ -556,7 +278,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
556
278
|
}
|
|
557
279
|
this._setRequestContext(requestClientTools, requestBody);
|
|
558
280
|
this._emit("message:request");
|
|
559
|
-
const abortSignal = this.
|
|
281
|
+
const abortSignal = this._abortRegistry.getSignal(chatMessageId);
|
|
560
282
|
return this._tryCatchChat(async () => {
|
|
561
283
|
return __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
562
284
|
agent: this,
|
|
@@ -564,25 +286,39 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
564
286
|
request: void 0,
|
|
565
287
|
email: void 0
|
|
566
288
|
}, async () => {
|
|
567
|
-
const
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
289
|
+
const chatTurnBody = async () => {
|
|
290
|
+
try {
|
|
291
|
+
const response = await this.onChatMessage(async (_finishResult) => {}, {
|
|
292
|
+
requestId: chatMessageId,
|
|
293
|
+
abortSignal,
|
|
294
|
+
clientTools: requestClientTools,
|
|
295
|
+
body: requestBody,
|
|
296
|
+
continuation: false
|
|
297
|
+
});
|
|
298
|
+
if (response) await this._reply(chatMessageId, response, [connection.id], { chatMessageId });
|
|
299
|
+
else {
|
|
300
|
+
console.warn(`[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`);
|
|
301
|
+
this._broadcastChatMessage({
|
|
302
|
+
body: "No response was generated by the agent.",
|
|
303
|
+
done: true,
|
|
304
|
+
id: chatMessageId,
|
|
305
|
+
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
|
|
306
|
+
}, [connection.id]);
|
|
307
|
+
}
|
|
308
|
+
} finally {
|
|
309
|
+
this._abortRegistry.remove(chatMessageId);
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
if (this.unstable_chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${chatMessageId}`, async () => {
|
|
313
|
+
await chatTurnBody();
|
|
572
314
|
});
|
|
573
|
-
|
|
574
|
-
else {
|
|
575
|
-
console.warn(`[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`);
|
|
576
|
-
this._broadcastChatMessage({
|
|
577
|
-
body: "No response was generated by the agent.",
|
|
578
|
-
done: true,
|
|
579
|
-
id: chatMessageId,
|
|
580
|
-
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
|
|
581
|
-
}, [connection.id]);
|
|
582
|
-
}
|
|
315
|
+
else await chatTurnBody();
|
|
583
316
|
});
|
|
584
317
|
});
|
|
585
|
-
}, {
|
|
318
|
+
}, {
|
|
319
|
+
epoch,
|
|
320
|
+
onStale: () => this._completeSkippedRequest(connection, chatMessageId)
|
|
321
|
+
});
|
|
586
322
|
}
|
|
587
323
|
if (data.type === MessageType.CF_AGENT_CHAT_CLEAR) {
|
|
588
324
|
this.resetTurnState();
|
|
@@ -604,14 +340,14 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
604
340
|
return;
|
|
605
341
|
}
|
|
606
342
|
if (data.type === MessageType.CF_AGENT_CHAT_REQUEST_CANCEL) {
|
|
607
|
-
this.
|
|
343
|
+
this._abortRegistry.cancel(data.id);
|
|
608
344
|
this._emit("message:cancel", { requestId: data.id });
|
|
609
345
|
return;
|
|
610
346
|
}
|
|
611
347
|
if (data.type === MessageType.CF_AGENT_STREAM_RESUME_REQUEST) {
|
|
612
|
-
if (this._resumableStream.hasActiveStream()) if (this.
|
|
348
|
+
if (this._resumableStream.hasActiveStream()) if (this._continuation.activeRequestId === this._resumableStream.activeRequestId && this._continuation.activeConnectionId !== null && this._continuation.activeConnectionId !== connection.id) connection.send(JSON.stringify({ type: MessageType.CF_AGENT_STREAM_RESUME_NONE }));
|
|
613
349
|
else this._notifyStreamResuming(connection);
|
|
614
|
-
else if (this.
|
|
350
|
+
else if (this._continuation.pending !== null && this._continuation.pending.connectionId === connection.id) this._continuation.awaitingConnections.set(connection.id, connection);
|
|
615
351
|
else connection.send(JSON.stringify({ type: MessageType.CF_AGENT_STREAM_RESUME_NONE }));
|
|
616
352
|
return;
|
|
617
353
|
}
|
|
@@ -669,8 +405,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
669
405
|
}
|
|
670
406
|
_flushAwaitingStreamStartConnections() {
|
|
671
407
|
if (!this._resumableStream.hasActiveStream()) return;
|
|
672
|
-
|
|
673
|
-
this._awaitingStreamStartConnections.clear();
|
|
408
|
+
this._continuation.flushAwaitingConnections((c) => this._notifyStreamResuming(c));
|
|
674
409
|
}
|
|
675
410
|
_mergeAutoContinuationPrerequisite(current, next) {
|
|
676
411
|
if (!next) return current;
|
|
@@ -680,52 +415,28 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
680
415
|
});
|
|
681
416
|
}
|
|
682
417
|
_storeDeferredAutoContinuation(connection, clientTools, body, errorPrefix, prerequisite) {
|
|
683
|
-
const
|
|
684
|
-
this.
|
|
418
|
+
const existing = this._continuation.deferred;
|
|
419
|
+
this._continuation.deferred = {
|
|
685
420
|
connection,
|
|
686
421
|
connectionId: connection.id,
|
|
687
422
|
clientTools,
|
|
688
423
|
body,
|
|
689
424
|
errorPrefix,
|
|
690
|
-
prerequisite: this._mergeAutoContinuationPrerequisite(
|
|
425
|
+
prerequisite: this._mergeAutoContinuationPrerequisite(existing?.prerequisite ?? null, prerequisite)
|
|
691
426
|
};
|
|
692
427
|
}
|
|
693
428
|
_activateDeferredAutoContinuation() {
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
this.
|
|
697
|
-
this._pendingAutoContinuationConnection = deferred.connection;
|
|
698
|
-
this._pendingAutoContinuationConnectionId = deferred.connectionId;
|
|
699
|
-
this._awaitingStreamStartConnections.set(deferred.connectionId, deferred.connection);
|
|
700
|
-
this._pendingAutoContinuationClientTools = deferred.clientTools;
|
|
701
|
-
this._pendingAutoContinuationBody = deferred.body;
|
|
702
|
-
this._pendingAutoContinuationErrorPrefix = deferred.errorPrefix;
|
|
703
|
-
this._pendingAutoContinuationPrerequisite = deferred.prerequisite;
|
|
704
|
-
this._pendingAutoContinuationPastCoalesce = false;
|
|
705
|
-
const requestId = nanoid();
|
|
706
|
-
this._pendingAutoContinuation = true;
|
|
707
|
-
this._pendingAutoContinuationRequestId = requestId;
|
|
708
|
-
this._queueAutoContinuation(requestId);
|
|
709
|
-
}
|
|
710
|
-
_clearDeferredAutoContinuation() {
|
|
711
|
-
this._deferredAutoContinuation = null;
|
|
429
|
+
const pending = this._continuation.activateDeferred(() => nanoid());
|
|
430
|
+
if (!pending) return;
|
|
431
|
+
this._queueAutoContinuation(pending.requestId);
|
|
712
432
|
}
|
|
713
433
|
_clearAllAutoContinuationState(sendNone = false) {
|
|
714
434
|
this._clearPendingAutoContinuation(sendNone);
|
|
715
|
-
this.
|
|
435
|
+
this._continuation.clearDeferred();
|
|
716
436
|
}
|
|
717
437
|
_clearPendingAutoContinuation(sendNone = false) {
|
|
718
|
-
this.
|
|
719
|
-
this.
|
|
720
|
-
this._pendingAutoContinuationClientTools = void 0;
|
|
721
|
-
this._pendingAutoContinuationBody = void 0;
|
|
722
|
-
this._pendingAutoContinuationErrorPrefix = null;
|
|
723
|
-
this._pendingAutoContinuationRequestId = null;
|
|
724
|
-
this._pendingAutoContinuationPrerequisite = null;
|
|
725
|
-
this._pendingAutoContinuationConnectionId = null;
|
|
726
|
-
this._pendingAutoContinuationPastCoalesce = false;
|
|
727
|
-
if (sendNone) for (const connection of this._awaitingStreamStartConnections.values()) connection.send(JSON.stringify({ type: MessageType.CF_AGENT_STREAM_RESUME_NONE }));
|
|
728
|
-
this._awaitingStreamStartConnections.clear();
|
|
438
|
+
if (sendNone) this._continuation.sendResumeNone();
|
|
439
|
+
this._continuation.clearPending();
|
|
729
440
|
}
|
|
730
441
|
/**
|
|
731
442
|
* Notify a connection about an active stream that can be resumed.
|
|
@@ -751,19 +462,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
751
462
|
/** @internal Delegate to _resumableStream */
|
|
752
463
|
_startStream(requestId) {
|
|
753
464
|
const streamId = this._resumableStream.start(requestId);
|
|
754
|
-
if (this.
|
|
755
|
-
this.
|
|
756
|
-
this._activeAutoContinuationConnectionId = this._pendingAutoContinuationConnectionId;
|
|
757
|
-
this._pendingAutoContinuation = false;
|
|
758
|
-
this._pendingAutoContinuationConnection = null;
|
|
759
|
-
this._pendingAutoContinuationConnectionId = null;
|
|
760
|
-
this._pendingAutoContinuationClientTools = void 0;
|
|
761
|
-
this._pendingAutoContinuationBody = void 0;
|
|
762
|
-
this._pendingAutoContinuationErrorPrefix = null;
|
|
763
|
-
this._pendingAutoContinuationRequestId = null;
|
|
764
|
-
this._pendingAutoContinuationPrerequisite = null;
|
|
465
|
+
if (this._continuation.pending?.requestId === requestId) {
|
|
466
|
+
this._continuation.activatePending();
|
|
765
467
|
this._flushAwaitingStreamStartConnections();
|
|
766
|
-
this._pendingAutoContinuationPastCoalesce = false;
|
|
767
468
|
this._activateDeferredAutoContinuation();
|
|
768
469
|
}
|
|
769
470
|
return streamId;
|
|
@@ -773,9 +474,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
773
474
|
const completedRequestId = this._resumableStream.activeRequestId;
|
|
774
475
|
this._resumableStream.complete(streamId);
|
|
775
476
|
this._pendingResumeConnections.clear();
|
|
776
|
-
if (completedRequestId === this.
|
|
777
|
-
this.
|
|
778
|
-
this.
|
|
477
|
+
if (completedRequestId === this._continuation.activeRequestId) {
|
|
478
|
+
this._continuation.activeRequestId = null;
|
|
479
|
+
this._continuation.activeConnectionId = null;
|
|
779
480
|
}
|
|
780
481
|
}
|
|
781
482
|
/** @internal Delegate to _resumableStream */
|
|
@@ -923,14 +624,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
923
624
|
}
|
|
924
625
|
}
|
|
925
626
|
isChatTurnActive() {
|
|
926
|
-
return this.
|
|
627
|
+
return this._turnQueue.isActive;
|
|
927
628
|
}
|
|
928
629
|
async waitForIdle() {
|
|
929
|
-
|
|
930
|
-
do {
|
|
931
|
-
queue = this._chatTurnQueue;
|
|
932
|
-
await queue;
|
|
933
|
-
} while (this._chatTurnQueue !== queue);
|
|
630
|
+
await this._turnQueue.waitForIdle();
|
|
934
631
|
}
|
|
935
632
|
_normalizeMessageConcurrency() {
|
|
936
633
|
if (typeof this.messageConcurrency === "string") return this.messageConcurrency;
|
|
@@ -941,7 +638,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
941
638
|
};
|
|
942
639
|
}
|
|
943
640
|
_getSubmitConcurrencyDecision(trigger) {
|
|
944
|
-
const queuedTurnsInCurrentEpoch = this.
|
|
641
|
+
const queuedTurnsInCurrentEpoch = this._turnQueue.queuedCount();
|
|
945
642
|
if (trigger !== "submit-message" || queuedTurnsInCurrentEpoch === 0) return {
|
|
946
643
|
action: "execute",
|
|
947
644
|
submitSequence: null,
|
|
@@ -970,7 +667,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
970
667
|
mergeQueuedMessages: false
|
|
971
668
|
};
|
|
972
669
|
if (concurrency === "merge") {
|
|
973
|
-
if (!this._mergeQueuedUserStartIndexByEpoch.has(this.
|
|
670
|
+
if (!this._mergeQueuedUserStartIndexByEpoch.has(this._turnQueue.generation)) this._mergeQueuedUserStartIndexByEpoch.set(this._turnQueue.generation, this.messages.length);
|
|
974
671
|
return {
|
|
975
672
|
action: "execute",
|
|
976
673
|
submitSequence,
|
|
@@ -1010,7 +707,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1010
707
|
this._activeDebounceResolve = null;
|
|
1011
708
|
}
|
|
1012
709
|
}
|
|
1013
|
-
async _mergeQueuedUserMessages(epoch = this.
|
|
710
|
+
async _mergeQueuedUserMessages(epoch = this._turnQueue.generation) {
|
|
1014
711
|
const mergedMessages = this._getMergedQueuedUserMessages(epoch);
|
|
1015
712
|
if (!mergedMessages) return;
|
|
1016
713
|
await this.persistMessages(mergedMessages, [], { _deleteStaleRows: true });
|
|
@@ -1118,7 +815,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1118
815
|
async waitUntilStable(options) {
|
|
1119
816
|
const deadline = options?.timeout != null ? Date.now() + options.timeout : null;
|
|
1120
817
|
while (true) {
|
|
1121
|
-
if (await this._awaitWithDeadline(this.
|
|
818
|
+
if (await this._awaitWithDeadline(this._turnQueue.waitForIdle(), deadline) === TIMED_OUT) return false;
|
|
1122
819
|
if (!this.hasPendingInteraction()) return true;
|
|
1123
820
|
const pending = this._pendingInteractionPromise;
|
|
1124
821
|
if (pending) {
|
|
@@ -1133,8 +830,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1133
830
|
}
|
|
1134
831
|
}
|
|
1135
832
|
abortActiveTurn() {
|
|
1136
|
-
if (!this.
|
|
1137
|
-
this.
|
|
833
|
+
if (!this._turnQueue.activeRequestId) return false;
|
|
834
|
+
this._abortRegistry.cancel(this._turnQueue.activeRequestId);
|
|
1138
835
|
return true;
|
|
1139
836
|
}
|
|
1140
837
|
/**
|
|
@@ -1143,14 +840,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1143
840
|
* the built-in handler calls it automatically.
|
|
1144
841
|
*/
|
|
1145
842
|
resetTurnState() {
|
|
1146
|
-
this._mergeQueuedUserStartIndexByEpoch.delete(this.
|
|
1147
|
-
this.
|
|
1148
|
-
this.
|
|
843
|
+
this._mergeQueuedUserStartIndexByEpoch.delete(this._turnQueue.generation);
|
|
844
|
+
this._turnQueue.reset();
|
|
845
|
+
this._abortRegistry.destroyAll();
|
|
1149
846
|
this._cancelActiveDebounce();
|
|
1150
847
|
this._pendingInteractionPromise = null;
|
|
1151
|
-
this.
|
|
1152
|
-
this.
|
|
1153
|
-
this._clearAllAutoContinuationState(true);
|
|
848
|
+
this._continuation.sendResumeNone();
|
|
849
|
+
this._continuation.clearAll();
|
|
1154
850
|
this._pendingChatResponseResults.length = 0;
|
|
1155
851
|
}
|
|
1156
852
|
async _awaitWithDeadline(promise, deadline) {
|
|
@@ -1171,33 +867,21 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1171
867
|
* streaming turn.
|
|
1172
868
|
*/
|
|
1173
869
|
async _runExclusiveChatTurn(requestId, fn, options) {
|
|
1174
|
-
const
|
|
1175
|
-
let
|
|
1176
|
-
const epoch = options?.epoch ?? this._chatEpoch;
|
|
1177
|
-
this._queuedChatTurnCountsByEpoch.set(epoch, (this._queuedChatTurnCountsByEpoch.get(epoch) ?? 0) + 1);
|
|
1178
|
-
this._chatTurnQueue = new Promise((resolve) => {
|
|
1179
|
-
releaseTurn = resolve;
|
|
1180
|
-
});
|
|
1181
|
-
await previousTurn;
|
|
1182
|
-
this._activeChatTurnRequestId = requestId;
|
|
870
|
+
const generation = options?.epoch;
|
|
871
|
+
let result;
|
|
1183
872
|
try {
|
|
1184
|
-
|
|
873
|
+
result = await this._turnQueue.enqueue(requestId, fn, { generation });
|
|
1185
874
|
} finally {
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
if (nextCount <= 0) {
|
|
1189
|
-
this._queuedChatTurnCountsByEpoch.delete(epoch);
|
|
1190
|
-
this._mergeQueuedUserStartIndexByEpoch.delete(epoch);
|
|
1191
|
-
} else this._queuedChatTurnCountsByEpoch.set(epoch, nextCount);
|
|
1192
|
-
releaseTurn();
|
|
875
|
+
const gen = generation ?? this._turnQueue.generation;
|
|
876
|
+
if (this._turnQueue.queuedCount(gen) === 0) this._mergeQueuedUserStartIndexByEpoch.delete(gen);
|
|
1193
877
|
if (this._pendingChatResponseResults.length > 0 && !this._insideResponseHook) {
|
|
1194
878
|
this._insideResponseHook = true;
|
|
1195
879
|
try {
|
|
1196
880
|
await this.keepAliveWhile(async () => {
|
|
1197
881
|
while (this._pendingChatResponseResults.length > 0) {
|
|
1198
|
-
const
|
|
882
|
+
const chatResult = this._pendingChatResponseResults.shift();
|
|
1199
883
|
try {
|
|
1200
|
-
await this.onChatResponse(
|
|
884
|
+
await this.onChatResponse(chatResult);
|
|
1201
885
|
} catch (hookError) {
|
|
1202
886
|
console.error("[AIChatAgent] onChatResponse threw:", hookError);
|
|
1203
887
|
}
|
|
@@ -1208,66 +892,68 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1208
892
|
}
|
|
1209
893
|
}
|
|
1210
894
|
}
|
|
895
|
+
if (result.status === "stale") {
|
|
896
|
+
options?.onStale?.();
|
|
897
|
+
return;
|
|
898
|
+
}
|
|
899
|
+
return result.value;
|
|
1211
900
|
}
|
|
1212
901
|
_enqueueAutoContinuation(connection, clientTools, body, errorPrefix, prerequisite) {
|
|
1213
|
-
if (this.
|
|
1214
|
-
if (this.
|
|
902
|
+
if (this._continuation.pending) {
|
|
903
|
+
if (this._continuation.pending.pastCoalesce) {
|
|
1215
904
|
this._storeDeferredAutoContinuation(connection, clientTools, body, errorPrefix, prerequisite);
|
|
1216
905
|
return;
|
|
1217
906
|
}
|
|
1218
|
-
this.
|
|
1219
|
-
this.
|
|
1220
|
-
this.
|
|
1221
|
-
this.
|
|
1222
|
-
this.
|
|
1223
|
-
this.
|
|
1224
|
-
this.
|
|
907
|
+
this._continuation.pending.connection = connection;
|
|
908
|
+
this._continuation.pending.connectionId = connection.id;
|
|
909
|
+
this._continuation.awaitingConnections.set(connection.id, connection);
|
|
910
|
+
this._continuation.pending.clientTools = clientTools;
|
|
911
|
+
this._continuation.pending.body = body;
|
|
912
|
+
this._continuation.pending.errorPrefix = errorPrefix;
|
|
913
|
+
this._continuation.pending.prerequisite = this._mergeAutoContinuationPrerequisite(this._continuation.pending.prerequisite, prerequisite);
|
|
1225
914
|
return;
|
|
1226
915
|
}
|
|
1227
|
-
this._pendingAutoContinuationConnection = connection;
|
|
1228
|
-
this._pendingAutoContinuationConnectionId = connection.id;
|
|
1229
|
-
this._awaitingStreamStartConnections.set(connection.id, connection);
|
|
1230
|
-
this._pendingAutoContinuationClientTools = clientTools;
|
|
1231
|
-
this._pendingAutoContinuationBody = body;
|
|
1232
|
-
this._pendingAutoContinuationErrorPrefix = errorPrefix;
|
|
1233
|
-
this._pendingAutoContinuationPrerequisite = this._mergeAutoContinuationPrerequisite(this._pendingAutoContinuationPrerequisite, prerequisite);
|
|
1234
|
-
this._pendingAutoContinuationPastCoalesce = false;
|
|
1235
916
|
const requestId = nanoid();
|
|
1236
|
-
this.
|
|
1237
|
-
|
|
917
|
+
this._continuation.pending = {
|
|
918
|
+
connection,
|
|
919
|
+
connectionId: connection.id,
|
|
920
|
+
requestId,
|
|
921
|
+
clientTools,
|
|
922
|
+
body,
|
|
923
|
+
errorPrefix,
|
|
924
|
+
prerequisite: this._mergeAutoContinuationPrerequisite(null, prerequisite),
|
|
925
|
+
pastCoalesce: false
|
|
926
|
+
};
|
|
927
|
+
this._continuation.awaitingConnections.set(connection.id, connection);
|
|
1238
928
|
this._queueAutoContinuation(requestId);
|
|
1239
929
|
}
|
|
1240
930
|
async _awaitPendingAutoContinuationPrerequisite() {
|
|
1241
931
|
while (true) {
|
|
1242
|
-
const prerequisite = this.
|
|
932
|
+
const prerequisite = this._continuation.pending?.prerequisite;
|
|
1243
933
|
if (!prerequisite) return true;
|
|
1244
934
|
if (!await prerequisite) return false;
|
|
1245
935
|
await new Promise((resolve) => setTimeout(resolve, AIChatAgent.AUTO_CONTINUATION_COALESCE_MS));
|
|
1246
|
-
if (this.
|
|
936
|
+
if (this._continuation.pending?.prerequisite === prerequisite) return true;
|
|
1247
937
|
}
|
|
1248
938
|
}
|
|
1249
939
|
_queueAutoContinuation(requestId) {
|
|
1250
|
-
const epoch = this.
|
|
940
|
+
const epoch = this._turnQueue.generation;
|
|
1251
941
|
this._runExclusiveChatTurn(requestId, async () => {
|
|
1252
942
|
const dispose = await this.keepAlive();
|
|
1253
943
|
try {
|
|
1254
|
-
if (this._chatEpoch !== epoch) {
|
|
1255
|
-
this._clearAllAutoContinuationState(true);
|
|
1256
|
-
return;
|
|
1257
|
-
}
|
|
1258
944
|
if (!await this._awaitPendingAutoContinuationPrerequisite()) {
|
|
1259
945
|
this._clearAllAutoContinuationState(true);
|
|
1260
946
|
return;
|
|
1261
947
|
}
|
|
1262
|
-
const connection = this.
|
|
948
|
+
const connection = this._continuation.pending?.connection;
|
|
1263
949
|
if (!connection) {
|
|
1264
950
|
this._clearAllAutoContinuationState(true);
|
|
1265
951
|
return;
|
|
1266
952
|
}
|
|
1267
|
-
const clientTools = this.
|
|
1268
|
-
const body = this.
|
|
1269
|
-
this.
|
|
1270
|
-
const abortSignal = this.
|
|
953
|
+
const clientTools = this._continuation.pending?.clientTools;
|
|
954
|
+
const body = this._continuation.pending?.body;
|
|
955
|
+
if (this._continuation.pending) this._continuation.pending.pastCoalesce = true;
|
|
956
|
+
const abortSignal = this._abortRegistry.getSignal(requestId);
|
|
1271
957
|
return this._tryCatchChat(async () => {
|
|
1272
958
|
return __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
1273
959
|
agent: this,
|
|
@@ -1275,29 +961,43 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1275
961
|
request: void 0,
|
|
1276
962
|
email: void 0
|
|
1277
963
|
}, async () => {
|
|
1278
|
-
const
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
964
|
+
const autoContinuationBody = async () => {
|
|
965
|
+
try {
|
|
966
|
+
const response = await this.onChatMessage(async (_finishResult) => {}, {
|
|
967
|
+
requestId,
|
|
968
|
+
abortSignal,
|
|
969
|
+
clientTools,
|
|
970
|
+
body,
|
|
971
|
+
continuation: true
|
|
972
|
+
});
|
|
973
|
+
if (response) {
|
|
974
|
+
await this._reply(requestId, response, [], {
|
|
975
|
+
continuation: true,
|
|
976
|
+
chatMessageId: requestId
|
|
977
|
+
});
|
|
978
|
+
this._activateDeferredAutoContinuation();
|
|
979
|
+
} else {
|
|
980
|
+
this._clearPendingAutoContinuation(true);
|
|
981
|
+
this._activateDeferredAutoContinuation();
|
|
982
|
+
}
|
|
983
|
+
} finally {
|
|
984
|
+
this._abortRegistry.remove(requestId);
|
|
985
|
+
}
|
|
986
|
+
};
|
|
987
|
+
if (this.unstable_chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
|
|
988
|
+
await autoContinuationBody();
|
|
1283
989
|
});
|
|
1284
|
-
|
|
1285
|
-
await this._reply(requestId, response, [], {
|
|
1286
|
-
continuation: true,
|
|
1287
|
-
chatMessageId: requestId
|
|
1288
|
-
});
|
|
1289
|
-
this._activateDeferredAutoContinuation();
|
|
1290
|
-
} else {
|
|
1291
|
-
this._clearPendingAutoContinuation(true);
|
|
1292
|
-
this._activateDeferredAutoContinuation();
|
|
1293
|
-
}
|
|
990
|
+
else await autoContinuationBody();
|
|
1294
991
|
});
|
|
1295
992
|
});
|
|
1296
993
|
} finally {
|
|
1297
994
|
dispose();
|
|
1298
995
|
}
|
|
1299
|
-
}, {
|
|
1300
|
-
|
|
996
|
+
}, {
|
|
997
|
+
epoch,
|
|
998
|
+
onStale: () => this._clearAllAutoContinuationState(true)
|
|
999
|
+
}).catch((error) => {
|
|
1000
|
+
const errorPrefix = this._continuation.pending?.errorPrefix ?? "[AIChatAgent] Auto-continuation failed:";
|
|
1301
1001
|
this._clearAllAutoContinuationState(true);
|
|
1302
1002
|
console.error(errorPrefix, error);
|
|
1303
1003
|
});
|
|
@@ -1311,14 +1011,25 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1311
1011
|
request: void 0,
|
|
1312
1012
|
email: void 0
|
|
1313
1013
|
}, async () => {
|
|
1314
|
-
const abortSignal = this.
|
|
1315
|
-
const
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1014
|
+
const abortSignal = this._abortRegistry.getSignal(requestId);
|
|
1015
|
+
const programmaticBody = async () => {
|
|
1016
|
+
try {
|
|
1017
|
+
const response = await this.onChatMessage(() => {}, {
|
|
1018
|
+
requestId,
|
|
1019
|
+
abortSignal,
|
|
1020
|
+
clientTools,
|
|
1021
|
+
body,
|
|
1022
|
+
continuation: false
|
|
1023
|
+
});
|
|
1024
|
+
if (response) await this._reply(requestId, response, [], { chatMessageId: requestId });
|
|
1025
|
+
} finally {
|
|
1026
|
+
this._abortRegistry.remove(requestId);
|
|
1027
|
+
}
|
|
1028
|
+
};
|
|
1029
|
+
if (this.unstable_chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
|
|
1030
|
+
await programmaticBody();
|
|
1320
1031
|
});
|
|
1321
|
-
|
|
1032
|
+
else await programmaticBody();
|
|
1322
1033
|
});
|
|
1323
1034
|
});
|
|
1324
1035
|
}
|
|
@@ -1415,35 +1126,179 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1415
1126
|
const requestId = nanoid();
|
|
1416
1127
|
const clientTools = this._lastClientTools;
|
|
1417
1128
|
const body = this._lastBody;
|
|
1418
|
-
const epoch = this.
|
|
1129
|
+
const epoch = this._turnQueue.generation;
|
|
1419
1130
|
let status = "completed";
|
|
1420
1131
|
await this._runExclusiveChatTurn(requestId, async () => {
|
|
1421
|
-
if (this._chatEpoch !== epoch) {
|
|
1422
|
-
status = "skipped";
|
|
1423
|
-
return;
|
|
1424
|
-
}
|
|
1425
1132
|
const resolvedMessages = typeof messages === "function" ? await messages(this.messages) : messages;
|
|
1426
|
-
if (this.
|
|
1133
|
+
if (this._turnQueue.generation !== epoch) {
|
|
1427
1134
|
status = "skipped";
|
|
1428
1135
|
return;
|
|
1429
1136
|
}
|
|
1430
1137
|
await this.persistMessages(resolvedMessages);
|
|
1431
|
-
if (this.
|
|
1138
|
+
if (this._turnQueue.generation !== epoch) {
|
|
1432
1139
|
status = "skipped";
|
|
1433
1140
|
return;
|
|
1434
1141
|
}
|
|
1435
1142
|
await this._runProgrammaticChatTurn(requestId, clientTools, body);
|
|
1436
1143
|
}, { epoch });
|
|
1144
|
+
if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
|
|
1145
|
+
return {
|
|
1146
|
+
requestId,
|
|
1147
|
+
status
|
|
1148
|
+
};
|
|
1149
|
+
}
|
|
1150
|
+
/**
|
|
1151
|
+
* Trigger a continuation of the last assistant message without inserting
|
|
1152
|
+
* a new user message. The LLM sees the full conversation (including the
|
|
1153
|
+
* partial assistant response) and generates a continuation that appends
|
|
1154
|
+
* to the same message.
|
|
1155
|
+
*
|
|
1156
|
+
* This uses `continuation: true` in `_reply`, which clones the last
|
|
1157
|
+
* assistant message and appends new parts to it — the same mechanism
|
|
1158
|
+
* used by tool auto-continuation.
|
|
1159
|
+
*
|
|
1160
|
+
* Returns early if there is no assistant message to continue from.
|
|
1161
|
+
*/
|
|
1162
|
+
async continueLastTurn(body) {
|
|
1163
|
+
if (!this._findLastAssistantMessage()) return {
|
|
1164
|
+
requestId: "",
|
|
1165
|
+
status: "skipped"
|
|
1166
|
+
};
|
|
1167
|
+
const requestId = nanoid();
|
|
1168
|
+
const clientTools = this._lastClientTools;
|
|
1169
|
+
const resolvedBody = body ?? this._lastBody;
|
|
1170
|
+
const epoch = this._turnQueue.generation;
|
|
1171
|
+
let status = "completed";
|
|
1172
|
+
await this._runExclusiveChatTurn(requestId, async () => {
|
|
1173
|
+
if (this._turnQueue.generation !== epoch) {
|
|
1174
|
+
status = "skipped";
|
|
1175
|
+
return;
|
|
1176
|
+
}
|
|
1177
|
+
this._setRequestContext(clientTools, resolvedBody);
|
|
1178
|
+
const turnBody = async () => {
|
|
1179
|
+
await this._tryCatchChat(async () => {
|
|
1180
|
+
return __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
1181
|
+
agent: this,
|
|
1182
|
+
connection: void 0,
|
|
1183
|
+
request: void 0,
|
|
1184
|
+
email: void 0
|
|
1185
|
+
}, async () => {
|
|
1186
|
+
const abortSignal = this._abortRegistry.getSignal(requestId);
|
|
1187
|
+
try {
|
|
1188
|
+
const response = await this.onChatMessage(() => {}, {
|
|
1189
|
+
requestId,
|
|
1190
|
+
abortSignal,
|
|
1191
|
+
clientTools,
|
|
1192
|
+
body: resolvedBody,
|
|
1193
|
+
continuation: true
|
|
1194
|
+
});
|
|
1195
|
+
if (response) await this._reply(requestId, response, [], {
|
|
1196
|
+
continuation: true,
|
|
1197
|
+
chatMessageId: requestId
|
|
1198
|
+
});
|
|
1199
|
+
} finally {
|
|
1200
|
+
this._abortRegistry.remove(requestId);
|
|
1201
|
+
}
|
|
1202
|
+
});
|
|
1203
|
+
});
|
|
1204
|
+
};
|
|
1205
|
+
if (this.unstable_chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
|
|
1206
|
+
await turnBody();
|
|
1207
|
+
});
|
|
1208
|
+
else await turnBody();
|
|
1209
|
+
}, { epoch });
|
|
1210
|
+
if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
|
|
1437
1211
|
return {
|
|
1438
1212
|
requestId,
|
|
1439
1213
|
status
|
|
1440
1214
|
};
|
|
1441
1215
|
}
|
|
1216
|
+
static {
|
|
1217
|
+
this.CHAT_FIBER_NAME = "__cf_internal_chat_turn";
|
|
1218
|
+
}
|
|
1219
|
+
/**
|
|
1220
|
+
* Intercept internal chat fibers before they reach the user's
|
|
1221
|
+
* `onFiberRecovered` hook. Maps to `onChatRecovery`.
|
|
1222
|
+
* @internal
|
|
1223
|
+
*/
|
|
1224
|
+
async _handleInternalFiberRecovery(ctx) {
|
|
1225
|
+
const chatPrefix = this.constructor.CHAT_FIBER_NAME + ":";
|
|
1226
|
+
if (!ctx.name.startsWith(chatPrefix)) return false;
|
|
1227
|
+
const requestId = ctx.name.slice(chatPrefix.length);
|
|
1228
|
+
let streamId = "";
|
|
1229
|
+
if (requestId) {
|
|
1230
|
+
const rows = this.sql`
|
|
1231
|
+
SELECT id FROM cf_ai_chat_stream_metadata
|
|
1232
|
+
WHERE request_id = ${requestId}
|
|
1233
|
+
ORDER BY created_at DESC LIMIT 1
|
|
1234
|
+
`;
|
|
1235
|
+
if (rows.length > 0) streamId = rows[0].id;
|
|
1236
|
+
}
|
|
1237
|
+
if (!streamId && this._resumableStream.hasActiveStream()) streamId = this._resumableStream.activeStreamId ?? "";
|
|
1238
|
+
const partial = streamId ? this._getPartialStreamText(streamId) : {
|
|
1239
|
+
text: "",
|
|
1240
|
+
parts: []
|
|
1241
|
+
};
|
|
1242
|
+
const options = await this.onChatRecovery({
|
|
1243
|
+
streamId: streamId ?? "",
|
|
1244
|
+
requestId,
|
|
1245
|
+
partialText: partial.text,
|
|
1246
|
+
partialParts: partial.parts,
|
|
1247
|
+
recoveryData: ctx.snapshot,
|
|
1248
|
+
messages: [...this.messages],
|
|
1249
|
+
lastBody: this._lastBody,
|
|
1250
|
+
lastClientTools: this._lastClientTools
|
|
1251
|
+
});
|
|
1252
|
+
const streamStillActive = streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId;
|
|
1253
|
+
if (options.persist !== false && streamStillActive) this._persistOrphanedStream(streamId);
|
|
1254
|
+
if (streamStillActive) this._resumableStream.complete(streamId);
|
|
1255
|
+
if (options.continue !== false) {
|
|
1256
|
+
const targetId = this._findLastAssistantMessage()?.id;
|
|
1257
|
+
await this.schedule(0, "_chatRecoveryContinue", targetId ? { targetAssistantId: targetId } : void 0, { idempotent: true });
|
|
1258
|
+
}
|
|
1259
|
+
return true;
|
|
1260
|
+
}
|
|
1261
|
+
/**
|
|
1262
|
+
* Called when an interrupted chat stream is detected after restart.
|
|
1263
|
+
* Return options to control recovery:
|
|
1264
|
+
*
|
|
1265
|
+
* - `{}` (default): persist partial response + schedule continuation
|
|
1266
|
+
* - `{ continue: false }`: persist but don't continue
|
|
1267
|
+
* - `{ persist: false, continue: false }`: handle everything yourself
|
|
1268
|
+
*
|
|
1269
|
+
* `ctx.recoveryData` contains any data checkpointed via `this.stash()`
|
|
1270
|
+
* during streaming (e.g., OpenAI `responseId`).
|
|
1271
|
+
*/
|
|
1272
|
+
async onChatRecovery(_ctx) {
|
|
1273
|
+
return {};
|
|
1274
|
+
}
|
|
1275
|
+
async _chatRecoveryContinue(data) {
|
|
1276
|
+
if (!await this.waitUntilStable({ timeout: 1e4 })) {
|
|
1277
|
+
console.warn("[AIChatAgent] _chatRecoveryContinue timed out waiting for stable state, skipping continuation");
|
|
1278
|
+
return;
|
|
1279
|
+
}
|
|
1280
|
+
const targetId = data?.targetAssistantId;
|
|
1281
|
+
if (targetId && this._findLastAssistantMessage()?.id !== targetId) return;
|
|
1282
|
+
await this.continueLastTurn();
|
|
1283
|
+
}
|
|
1284
|
+
/**
|
|
1285
|
+
* Extract partial text and parts from stored stream chunks.
|
|
1286
|
+
*/
|
|
1287
|
+
_getPartialStreamText(streamId) {
|
|
1288
|
+
const chunks = this._resumableStream.getStreamChunks(streamId);
|
|
1289
|
+
const parts = [];
|
|
1290
|
+
for (const chunk of chunks) try {
|
|
1291
|
+
applyChunkToParts(parts, JSON.parse(chunk.body));
|
|
1292
|
+
} catch {}
|
|
1293
|
+
return {
|
|
1294
|
+
text: parts.filter((p) => p.type === "text" && "text" in p).map((p) => p.text).join(""),
|
|
1295
|
+
parts
|
|
1296
|
+
};
|
|
1297
|
+
}
|
|
1442
1298
|
async persistMessages(messages, excludeBroadcastIds = [], options) {
|
|
1443
|
-
const mergedMessages = this.
|
|
1299
|
+
const mergedMessages = reconcileMessages(messages, this.messages, (msg) => this._sanitizeMessageForPersistence(msg));
|
|
1444
1300
|
for (const message of mergedMessages) {
|
|
1445
|
-
const
|
|
1446
|
-
const resolved = this._resolveMessageForToolMerge(sanitizedMessage);
|
|
1301
|
+
const resolved = resolveToolMergeId(this._sanitizeMessageForPersistence(message), this.messages);
|
|
1447
1302
|
const safe = this._enforceRowSizeLimit(resolved);
|
|
1448
1303
|
const json = JSON.stringify(safe);
|
|
1449
1304
|
if (this._persistedMessageCache.get(safe.id) === json) continue;
|
|
@@ -1477,123 +1332,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1477
1332
|
}, excludeBroadcastIds);
|
|
1478
1333
|
}
|
|
1479
1334
|
/**
|
|
1480
|
-
* Merges incoming messages with existing server state.
|
|
1481
|
-
* This preserves tool outputs that the server has (via _applyToolResult)
|
|
1482
|
-
* but the client doesn't have yet.
|
|
1483
|
-
*
|
|
1484
|
-
* @param incomingMessages - Messages from the client
|
|
1485
|
-
* @returns Messages with server's tool outputs preserved
|
|
1486
|
-
*/
|
|
1487
|
-
_mergeIncomingWithServerState(incomingMessages) {
|
|
1488
|
-
const serverToolOutputs = /* @__PURE__ */ new Map();
|
|
1489
|
-
for (const msg of this.messages) {
|
|
1490
|
-
if (msg.role !== "assistant") continue;
|
|
1491
|
-
for (const part of msg.parts) if ("toolCallId" in part && "state" in part && part.state === "output-available" && "output" in part) serverToolOutputs.set(part.toolCallId, part.output);
|
|
1492
|
-
}
|
|
1493
|
-
const withMergedToolOutputs = serverToolOutputs.size === 0 ? incomingMessages : incomingMessages.map((msg) => {
|
|
1494
|
-
if (msg.role !== "assistant") return msg;
|
|
1495
|
-
let hasChanges = false;
|
|
1496
|
-
const updatedParts = msg.parts.map((part) => {
|
|
1497
|
-
if ("toolCallId" in part && "state" in part && (part.state === "input-available" || part.state === "approval-requested" || part.state === "approval-responded") && serverToolOutputs.has(part.toolCallId)) {
|
|
1498
|
-
hasChanges = true;
|
|
1499
|
-
return {
|
|
1500
|
-
...part,
|
|
1501
|
-
state: "output-available",
|
|
1502
|
-
output: serverToolOutputs.get(part.toolCallId)
|
|
1503
|
-
};
|
|
1504
|
-
}
|
|
1505
|
-
return part;
|
|
1506
|
-
});
|
|
1507
|
-
return hasChanges ? {
|
|
1508
|
-
...msg,
|
|
1509
|
-
parts: updatedParts
|
|
1510
|
-
} : msg;
|
|
1511
|
-
});
|
|
1512
|
-
return this._reconcileAssistantIdsWithServerState(withMergedToolOutputs);
|
|
1513
|
-
}
|
|
1514
|
-
/**
|
|
1515
|
-
* Reconciles assistant message IDs between incoming client state and server state.
|
|
1516
|
-
*
|
|
1517
|
-
* The client can keep a different local ID for an assistant message than the one
|
|
1518
|
-
* persisted on the server (e.g. optimistic/local IDs). When that full history is
|
|
1519
|
-
* sent back, persisting by ID alone creates duplicate assistant rows. To prevent
|
|
1520
|
-
* this, we reuse the server ID for assistant messages that match by content,
|
|
1521
|
-
* while leaving tool-call messages to _resolveMessageForToolMerge.
|
|
1522
|
-
*
|
|
1523
|
-
* Uses a two-pass approach:
|
|
1524
|
-
* - Pass 1: resolve all exact-ID matches, claiming server indices.
|
|
1525
|
-
* - Pass 2: content-based matching for remaining non-tool assistant messages,
|
|
1526
|
-
* scanning only unclaimed server indices left-to-right.
|
|
1527
|
-
*
|
|
1528
|
-
* The two-pass design prevents exact-ID matches from advancing a cursor past
|
|
1529
|
-
* server messages that a later incoming message needs for content matching.
|
|
1530
|
-
* This fixes mismatches when two assistant messages have identical text
|
|
1531
|
-
* (e.g. "Sure", "I understand") — see #1008.
|
|
1532
|
-
*/
|
|
1533
|
-
_reconcileAssistantIdsWithServerState(incomingMessages) {
|
|
1534
|
-
if (this.messages.length === 0) return incomingMessages;
|
|
1535
|
-
const claimedServerIndices = /* @__PURE__ */ new Set();
|
|
1536
|
-
const exactMatchMap = /* @__PURE__ */ new Map();
|
|
1537
|
-
for (let i = 0; i < incomingMessages.length; i++) {
|
|
1538
|
-
const serverIdx = this.messages.findIndex((sm, si) => !claimedServerIndices.has(si) && sm.id === incomingMessages[i].id);
|
|
1539
|
-
if (serverIdx !== -1) {
|
|
1540
|
-
claimedServerIndices.add(serverIdx);
|
|
1541
|
-
exactMatchMap.set(i, serverIdx);
|
|
1542
|
-
}
|
|
1543
|
-
}
|
|
1544
|
-
return incomingMessages.map((incomingMessage, incomingIdx) => {
|
|
1545
|
-
if (exactMatchMap.has(incomingIdx)) return incomingMessage;
|
|
1546
|
-
if (incomingMessage.role !== "assistant" || this._hasToolCallPart(incomingMessage)) return incomingMessage;
|
|
1547
|
-
const incomingKey = this._assistantMessageContentKey(incomingMessage);
|
|
1548
|
-
if (!incomingKey) return incomingMessage;
|
|
1549
|
-
for (let i = 0; i < this.messages.length; i++) {
|
|
1550
|
-
if (claimedServerIndices.has(i)) continue;
|
|
1551
|
-
const serverMessage = this.messages[i];
|
|
1552
|
-
if (serverMessage.role !== "assistant" || this._hasToolCallPart(serverMessage)) continue;
|
|
1553
|
-
if (this._assistantMessageContentKey(serverMessage) === incomingKey) {
|
|
1554
|
-
claimedServerIndices.add(i);
|
|
1555
|
-
return {
|
|
1556
|
-
...incomingMessage,
|
|
1557
|
-
id: serverMessage.id
|
|
1558
|
-
};
|
|
1559
|
-
}
|
|
1560
|
-
}
|
|
1561
|
-
return incomingMessage;
|
|
1562
|
-
});
|
|
1563
|
-
}
|
|
1564
|
-
_hasToolCallPart(message) {
|
|
1565
|
-
return message.parts.some((part) => "toolCallId" in part);
|
|
1566
|
-
}
|
|
1567
|
-
_assistantMessageContentKey(message) {
|
|
1568
|
-
if (message.role !== "assistant") return;
|
|
1569
|
-
const sanitized = this._sanitizeMessageForPersistence(message);
|
|
1570
|
-
return JSON.stringify(sanitized.parts);
|
|
1571
|
-
}
|
|
1572
|
-
/**
|
|
1573
|
-
* Resolves a message for persistence, handling tool result merging.
|
|
1574
|
-
* If the message contains tool parts with a toolCallId that already exists
|
|
1575
|
-
* in a server-side message with a different ID, adopts the server's ID.
|
|
1576
|
-
* This prevents duplicate rows when the client sends messages with
|
|
1577
|
-
* client-generated IDs (e.g. nanoid from the AI SDK) that differ from
|
|
1578
|
-
* the server-stamped IDs. Tool call IDs are unique per conversation,
|
|
1579
|
-
* so matching by toolCallId is safe regardless of tool state (#1094).
|
|
1580
|
-
*
|
|
1581
|
-
* @param message - The message to potentially merge
|
|
1582
|
-
* @returns The message with the correct ID (either original or merged)
|
|
1583
|
-
*/
|
|
1584
|
-
_resolveMessageForToolMerge(message) {
|
|
1585
|
-
if (message.role !== "assistant") return message;
|
|
1586
|
-
for (const part of message.parts) if ("toolCallId" in part && part.toolCallId) {
|
|
1587
|
-
const toolCallId = part.toolCallId;
|
|
1588
|
-
const existingMessage = this._findMessageByToolCallId(toolCallId);
|
|
1589
|
-
if (existingMessage && existingMessage.id !== message.id) return {
|
|
1590
|
-
...message,
|
|
1591
|
-
id: existingMessage.id
|
|
1592
|
-
};
|
|
1593
|
-
}
|
|
1594
|
-
return message;
|
|
1595
|
-
}
|
|
1596
|
-
/**
|
|
1597
1335
|
* Finds an existing assistant message that contains a tool part with the given toolCallId.
|
|
1598
1336
|
* Used to detect when a tool result should update an existing message rather than
|
|
1599
1337
|
* creating a new one.
|
|
@@ -1650,51 +1388,14 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1650
1388
|
* @returns A new message with ephemeral provider data removed
|
|
1651
1389
|
*/
|
|
1652
1390
|
_sanitizeMessageForPersistence(message) {
|
|
1653
|
-
const
|
|
1654
|
-
|
|
1655
|
-
if ("providerMetadata" in sanitizedPart && sanitizedPart.providerMetadata && typeof sanitizedPart.providerMetadata === "object" && "openai" in sanitizedPart.providerMetadata) sanitizedPart = this._stripOpenAIMetadata(sanitizedPart, "providerMetadata");
|
|
1656
|
-
if ("callProviderMetadata" in sanitizedPart && sanitizedPart.callProviderMetadata && typeof sanitizedPart.callProviderMetadata === "object" && "openai" in sanitizedPart.callProviderMetadata) sanitizedPart = this._stripOpenAIMetadata(sanitizedPart, "callProviderMetadata");
|
|
1657
|
-
sanitizedPart = AIChatAgent._truncateProviderExecutedToolPayloads(sanitizedPart);
|
|
1658
|
-
return sanitizedPart;
|
|
1659
|
-
}).filter((part) => {
|
|
1660
|
-
if (part.type === "reasoning") {
|
|
1661
|
-
const reasoningPart = part;
|
|
1662
|
-
if (!reasoningPart.text || reasoningPart.text.trim() === "") {
|
|
1663
|
-
if ("providerMetadata" in reasoningPart && reasoningPart.providerMetadata && typeof reasoningPart.providerMetadata === "object" && Object.keys(reasoningPart.providerMetadata).length > 0) return true;
|
|
1664
|
-
return false;
|
|
1665
|
-
}
|
|
1666
|
-
}
|
|
1667
|
-
return true;
|
|
1668
|
-
});
|
|
1391
|
+
const baseSanitized = sanitizeMessage(message);
|
|
1392
|
+
const parts = baseSanitized.parts.map((part) => AIChatAgent._truncateProviderExecutedToolPayloads(part));
|
|
1669
1393
|
return this.sanitizeMessageForPersistence({
|
|
1670
|
-
...
|
|
1671
|
-
parts
|
|
1394
|
+
...baseSanitized,
|
|
1395
|
+
parts
|
|
1672
1396
|
});
|
|
1673
1397
|
}
|
|
1674
1398
|
/**
|
|
1675
|
-
* Helper to strip OpenAI-specific ephemeral fields from a metadata object.
|
|
1676
|
-
* Removes itemId and reasoningEncryptedContent while preserving other fields.
|
|
1677
|
-
*/
|
|
1678
|
-
_stripOpenAIMetadata(part, metadataKey) {
|
|
1679
|
-
const metadata = part[metadataKey];
|
|
1680
|
-
if (!metadata?.openai) return part;
|
|
1681
|
-
const { itemId: _itemId, reasoningEncryptedContent: _rec, ...restOpenai } = metadata.openai;
|
|
1682
|
-
const hasOtherOpenaiFields = Object.keys(restOpenai).length > 0;
|
|
1683
|
-
const { openai: _openai, ...restMetadata } = metadata;
|
|
1684
|
-
let newMetadata;
|
|
1685
|
-
if (hasOtherOpenaiFields) newMetadata = {
|
|
1686
|
-
...restMetadata,
|
|
1687
|
-
openai: restOpenai
|
|
1688
|
-
};
|
|
1689
|
-
else if (Object.keys(restMetadata).length > 0) newMetadata = restMetadata;
|
|
1690
|
-
const { [metadataKey]: _oldMeta, ...restPart } = part;
|
|
1691
|
-
if (newMetadata) return {
|
|
1692
|
-
...restPart,
|
|
1693
|
-
[metadataKey]: newMetadata
|
|
1694
|
-
};
|
|
1695
|
-
return restPart;
|
|
1696
|
-
}
|
|
1697
|
-
/**
|
|
1698
1399
|
* Truncates large string values in `input` and `output` of tool parts that
|
|
1699
1400
|
* were executed server-side by the provider (e.g. Anthropic code_execution,
|
|
1700
1401
|
* text_editor). These payloads can be 200KB+ and are dead weight once the
|
|
@@ -1788,8 +1489,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1788
1489
|
*/
|
|
1789
1490
|
_enforceRowSizeLimit(message) {
|
|
1790
1491
|
let json = JSON.stringify(message);
|
|
1791
|
-
let size =
|
|
1792
|
-
if (size <=
|
|
1492
|
+
let size = byteLength(json);
|
|
1493
|
+
if (size <= ROW_MAX_BYTES) return message;
|
|
1793
1494
|
if (message.role !== "assistant") {
|
|
1794
1495
|
console.warn(`[AIChatAgent] Non-assistant message ${message.id} is ${size} bytes, exceeds row limit. Truncating text parts.`);
|
|
1795
1496
|
return this._truncateTextParts(message);
|
|
@@ -1818,8 +1519,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1818
1519
|
compactedToolOutputs: compactedToolCallIds
|
|
1819
1520
|
};
|
|
1820
1521
|
json = JSON.stringify(result);
|
|
1821
|
-
size =
|
|
1822
|
-
if (size <=
|
|
1522
|
+
size = byteLength(json);
|
|
1523
|
+
if (size <= ROW_MAX_BYTES) return result;
|
|
1823
1524
|
console.warn(`[AIChatAgent] Message ${message.id} still ${size} bytes after tool compaction, truncating text parts`);
|
|
1824
1525
|
return this._truncateTextParts(result);
|
|
1825
1526
|
}
|
|
@@ -1845,7 +1546,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1845
1546
|
...message,
|
|
1846
1547
|
parts
|
|
1847
1548
|
};
|
|
1848
|
-
if (
|
|
1549
|
+
if (byteLength(JSON.stringify(candidate)) <= ROW_MAX_BYTES) break;
|
|
1849
1550
|
}
|
|
1850
1551
|
}
|
|
1851
1552
|
}
|
|
@@ -1972,6 +1673,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1972
1673
|
}
|
|
1973
1674
|
async _streamSSEReply(id, streamId, reader, message, streamCompleted, continuation = false, abortSignal) {
|
|
1974
1675
|
streamCompleted.value = false;
|
|
1676
|
+
let continuationTextResumed = false;
|
|
1677
|
+
let continuationReasoningResumed = false;
|
|
1975
1678
|
if (abortSignal && !abortSignal.aborted) abortSignal.addEventListener("abort", () => {
|
|
1976
1679
|
reader.cancel().catch(() => {});
|
|
1977
1680
|
}, { once: true });
|
|
@@ -2001,6 +1704,25 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2001
1704
|
const lines = decoder.decode(value).split("\n");
|
|
2002
1705
|
for (const line of lines) if (line.startsWith("data: ") && line !== "data: [DONE]") try {
|
|
2003
1706
|
const data = JSON.parse(line.slice(6));
|
|
1707
|
+
if (continuation) {
|
|
1708
|
+
if (!continuationTextResumed && data.type === "text-start") {
|
|
1709
|
+
for (let k = message.parts.length - 1; k >= 0; k--) {
|
|
1710
|
+
const part = message.parts[k];
|
|
1711
|
+
if (part.type === "text") {
|
|
1712
|
+
if ("state" in part && part.state === "streaming") continuationTextResumed = true;
|
|
1713
|
+
break;
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1716
|
+
if (continuationTextResumed) continue;
|
|
1717
|
+
}
|
|
1718
|
+
if (!continuationReasoningResumed && data.type === "reasoning-start") {
|
|
1719
|
+
for (let k = message.parts.length - 1; k >= 0; k--) if (message.parts[k].type === "reasoning") {
|
|
1720
|
+
continuationReasoningResumed = true;
|
|
1721
|
+
break;
|
|
1722
|
+
}
|
|
1723
|
+
if (continuationReasoningResumed) continue;
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
2004
1726
|
const handled = applyChunkToParts(message.parts, data);
|
|
2005
1727
|
if (data.type === "tool-approval-request" && this._streamingMessage) {
|
|
2006
1728
|
const snapshot = {
|
|
@@ -2105,16 +1827,26 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2105
1827
|
return "completed";
|
|
2106
1828
|
}
|
|
2107
1829
|
async _sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation = false, abortSignal) {
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
}
|
|
2117
|
-
|
|
1830
|
+
let textPart;
|
|
1831
|
+
if (continuation) for (let k = message.parts.length - 1; k >= 0; k--) {
|
|
1832
|
+
const part = message.parts[k];
|
|
1833
|
+
if (part.type === "text") {
|
|
1834
|
+
if ("state" in part && part.state === "streaming") textPart = part;
|
|
1835
|
+
break;
|
|
1836
|
+
}
|
|
1837
|
+
}
|
|
1838
|
+
if (textPart) {} else {
|
|
1839
|
+
this._broadcastTextEvent(streamId, {
|
|
1840
|
+
type: "text-start",
|
|
1841
|
+
id
|
|
1842
|
+
}, continuation);
|
|
1843
|
+
textPart = {
|
|
1844
|
+
type: "text",
|
|
1845
|
+
text: "",
|
|
1846
|
+
state: "streaming"
|
|
1847
|
+
};
|
|
1848
|
+
message.parts.push(textPart);
|
|
1849
|
+
}
|
|
2118
1850
|
if (abortSignal && !abortSignal.aborted) abortSignal.addEventListener("abort", () => {
|
|
2119
1851
|
reader.cancel().catch(() => {});
|
|
2120
1852
|
}, { once: true });
|
|
@@ -2200,7 +1932,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2200
1932
|
}
|
|
2201
1933
|
async _reply(id, response, excludeBroadcastIds = [], options = {}) {
|
|
2202
1934
|
const { continuation = false, chatMessageId } = options;
|
|
2203
|
-
const abortSignal = chatMessageId ? this.
|
|
1935
|
+
const abortSignal = chatMessageId ? this._abortRegistry.getExistingSignal(chatMessageId) : void 0;
|
|
2204
1936
|
return this.keepAliveWhile(() => this._tryCatchChat(async () => {
|
|
2205
1937
|
if (!response.body) {
|
|
2206
1938
|
this._clearPendingAutoContinuation(true);
|
|
@@ -2252,7 +1984,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2252
1984
|
earlyPersistedId = this._approvalPersistedMessageId;
|
|
2253
1985
|
this._approvalPersistedMessageId = null;
|
|
2254
1986
|
if (chatMessageId) {
|
|
2255
|
-
this.
|
|
1987
|
+
this._abortRegistry.remove(chatMessageId);
|
|
2256
1988
|
if (streamCompleted.value) this._emit("message:response");
|
|
2257
1989
|
}
|
|
2258
1990
|
}
|
|
@@ -2283,40 +2015,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
2283
2015
|
}));
|
|
2284
2016
|
}
|
|
2285
2017
|
/**
|
|
2286
|
-
* For the given message id, look up its associated AbortController
|
|
2287
|
-
* If the AbortController does not exist, create and store one in memory
|
|
2288
|
-
*
|
|
2289
|
-
* returns the AbortSignal associated with the AbortController
|
|
2290
|
-
*/
|
|
2291
|
-
_getAbortSignal(id) {
|
|
2292
|
-
if (typeof id !== "string") return;
|
|
2293
|
-
if (!this._chatMessageAbortControllers.has(id)) this._chatMessageAbortControllers.set(id, new AbortController());
|
|
2294
|
-
return this._chatMessageAbortControllers.get(id)?.signal;
|
|
2295
|
-
}
|
|
2296
|
-
/**
|
|
2297
|
-
* Remove an abort controller from the cache of pending message responses
|
|
2298
|
-
*/
|
|
2299
|
-
_removeAbortController(id) {
|
|
2300
|
-
this._chatMessageAbortControllers.delete(id);
|
|
2301
|
-
}
|
|
2302
|
-
/**
|
|
2303
|
-
* Propagate an abort signal for any requests associated with the given message id
|
|
2304
|
-
*/
|
|
2305
|
-
_cancelChatRequest(id) {
|
|
2306
|
-
if (this._chatMessageAbortControllers.has(id)) this._chatMessageAbortControllers.get(id)?.abort();
|
|
2307
|
-
}
|
|
2308
|
-
/**
|
|
2309
|
-
* Abort all pending requests and clear the cache of AbortControllers
|
|
2310
|
-
*/
|
|
2311
|
-
_destroyAbortControllers() {
|
|
2312
|
-
for (const controller of this._chatMessageAbortControllers.values()) controller?.abort();
|
|
2313
|
-
this._chatMessageAbortControllers.clear();
|
|
2314
|
-
}
|
|
2315
|
-
/**
|
|
2316
2018
|
* When the DO is destroyed, cancel all pending requests and clean up resources
|
|
2317
2019
|
*/
|
|
2318
2020
|
async destroy() {
|
|
2319
|
-
this.
|
|
2021
|
+
this._abortRegistry.destroyAll();
|
|
2320
2022
|
this._resumableStream.destroy();
|
|
2321
2023
|
await super.destroy();
|
|
2322
2024
|
}
|