@cloudflare/ai-chat 0.3.1 → 0.3.2

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.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 { ContinuationState, ROW_MAX_BYTES, ResumableStream, TurnQueue, applyChunkToParts, byteLength, createToolsFromClientSchemas, sanitizeMessage } from "agents/chat";
6
5
  import { nanoid } from "nanoid";
7
- //#region src/resumable-stream.ts
6
+ //#region src/message-reconciler.ts
8
7
  /**
9
- * ResumableStream: Standalone class for buffering, persisting, and replaying
10
- * stream chunks in SQLite. Extracted from AIChatAgent to separate concerns.
8
+ * Reconcile incoming client messages against server state.
11
9
  *
12
- * Handles:
13
- * - Chunk buffering (batched writes to SQLite for performance)
14
- * - Stream lifecycle (start, complete, error)
15
- * - Chunk replay for reconnecting clients
16
- * - Stale stream cleanup
17
- * - Active stream restoration after agent restart
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
- /** Number of chunks to buffer before flushing to SQLite */
20
- const CHUNK_BUFFER_SIZE = 10;
21
- /** Maximum buffer size to prevent memory issues on rapid reconnections */
22
- const CHUNK_BUFFER_MAX_SIZE = 100;
23
- /** Maximum age for a "streaming" stream before considering it stale (ms) - 5 minutes */
24
- const STREAM_STALE_THRESHOLD_MS = 300 * 1e3;
25
- /** Default cleanup interval for old streams (ms) - every 10 minutes */
26
- const CLEANUP_INTERVAL_MS = 600 * 1e3;
27
- /** Default age threshold for cleaning up completed streams (ms) - 24 hours */
28
- const CLEANUP_AGE_THRESHOLD_MS = 1440 * 60 * 1e3;
29
- /** Shared encoder for UTF-8 byte length measurement */
30
- const textEncoder$1 = new TextEncoder();
31
- var ResumableStream = class ResumableStream {
32
- constructor(sql) {
33
- this.sql = sql;
34
- this._activeStreamId = null;
35
- this._activeRequestId = null;
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
- * Buffer a stream chunk for batch write to SQLite.
132
- * Chunks exceeding the row size limit are skipped to prevent crashes.
133
- * The chunk is still broadcast to live clients (caller handles that),
134
- * but will be missing from replay on reconnection.
135
- * @param streamId - The stream this chunk belongs to
136
- * @param body - The serialized chunk body
137
- */
138
- storeChunk(streamId, body) {
139
- const bodyBytes = textEncoder$1.encode(body).byteLength;
140
- if (bodyBytes > ResumableStream.CHUNK_MAX_BYTES) {
141
- console.warn(`[ResumableStream] Skipping oversized chunk (${bodyBytes} bytes) to prevent SQLite row limit crash. Live clients still receive it.`);
142
- return;
143
- }
144
- if (this._chunkBuffer.length >= CHUNK_BUFFER_MAX_SIZE) this.flushBuffer();
145
- this._chunkBuffer.push({
146
- id: nanoid(),
147
- streamId,
148
- body,
149
- index: this._streamChunkIndex
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
- this._streamChunkIndex++;
152
- if (this._chunkBuffer.length >= CHUNK_BUFFER_SIZE) this.flushBuffer();
153
- }
154
- /**
155
- * Flush buffered chunks to SQLite in a single batch.
156
- * Uses a lock to prevent concurrent flush operations.
157
- */
158
- flushBuffer() {
159
- if (this._isFlushingChunks || this._chunkBuffer.length === 0) return;
160
- this._isFlushingChunks = true;
161
- try {
162
- const chunks = this._chunkBuffer;
163
- this._chunkBuffer = [];
164
- const now = Date.now();
165
- for (const chunk of chunks) this.sql`
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
- * Restore active stream state if the agent was restarted during streaming.
239
- * Validates stream freshness to avoid sending stale resume notifications.
240
- */
241
- restore() {
242
- const activeStreams = this.sql`
243
- select * from cf_ai_chat_stream_metadata
244
- where status = 'streaming'
245
- order by created_at desc
246
- limit 1
247
- `;
248
- if (activeStreams && activeStreams.length > 0) {
249
- const stream = activeStreams[0];
250
- const streamAge = Date.now() - stream.created_at;
251
- if (streamAge > STREAM_STALE_THRESHOLD_MS) {
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,14 @@ var AIChatAgent = class AIChatAgent extends Agent {
427
165
  this._insideResponseHook = false;
428
166
  this._pendingInteractionPromise = null;
429
167
  this._approvalPersistedMessageId = null;
430
- this._chatTurnQueue = Promise.resolve();
431
- this._activeChatTurnRequestId = null;
432
- this._chatEpoch = 0;
433
- this._queuedChatTurnCountsByEpoch = /* @__PURE__ */ new Map();
168
+ this._turnQueue = new TurnQueue();
434
169
  this._mergeQueuedUserStartIndexByEpoch = /* @__PURE__ */ new Map();
435
170
  this._submitSequence = 0;
436
171
  this._latestOverlappingSubmitSequence = 0;
437
172
  this._activeDebounceTimer = null;
438
173
  this._activeDebounceResolve = null;
439
174
  this._pendingResumeConnections = /* @__PURE__ */ new Set();
440
- this._awaitingStreamStartConnections = /* @__PURE__ */ new Map();
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;
175
+ this._continuation = new ContinuationState();
451
176
  this._persistedMessageCache = /* @__PURE__ */ new Map();
452
177
  this.maxPersistedMessages = void 0;
453
178
  this.messageConcurrency = "queue";
@@ -473,9 +198,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
473
198
  const _onClose = this.onClose.bind(this);
474
199
  this.onClose = async (connection, code, reason, wasClean) => {
475
200
  this._pendingResumeConnections.delete(connection.id);
476
- this._awaitingStreamStartConnections.delete(connection.id);
477
- if (this._pendingAutoContinuationConnection?.id === connection.id) this._pendingAutoContinuationConnection = null;
478
- if (this._activeAutoContinuationConnectionId === connection.id) this._activeAutoContinuationConnectionId = null;
201
+ this._continuation.awaitingConnections.delete(connection.id);
202
+ if (this._continuation.pending?.connectionId === connection.id) this._continuation.pending = null;
203
+ if (this._continuation.activeConnectionId === connection.id) this._continuation.activeConnectionId = null;
479
204
  return _onClose(connection, code, reason, wasClean);
480
205
  };
481
206
  const _onMessage = this.onMessage.bind(this);
@@ -506,7 +231,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
506
231
  const requestTrigger = _trigger === "regenerate-message" ? "regenerate-message" : "submit-message";
507
232
  const requestClientTools = clientTools?.length ? clientTools : void 0;
508
233
  const requestBody = Object.keys(customBody).length > 0 ? customBody : void 0;
509
- const epoch = this._chatEpoch;
234
+ const epoch = this._turnQueue.generation;
510
235
  const concurrencyDecision = this._getSubmitConcurrencyDecision(requestTrigger);
511
236
  if (concurrencyDecision.action === "drop") {
512
237
  this._rollbackDroppedSubmit(connection);
@@ -520,17 +245,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
520
245
  await this.persistMessages(transformedMessages, [connection.id], { _deleteStaleRows: true });
521
246
  if (concurrencyDecision.mergeQueuedMessages) await this._mergeQueuedUserMessages(epoch);
522
247
  return this._runExclusiveChatTurn(chatMessageId, async () => {
523
- if (this._chatEpoch !== epoch) {
524
- this._completeSkippedRequest(connection, chatMessageId);
525
- return;
526
- }
527
248
  if (this._isSupersededSubmit(concurrencyDecision.submitSequence)) {
528
249
  this._completeSkippedRequest(connection, chatMessageId);
529
250
  return;
530
251
  }
531
252
  if (concurrencyDecision.debounceUntilMs !== null) {
532
253
  await this._waitForTimestamp(concurrencyDecision.debounceUntilMs);
533
- if (this._chatEpoch !== epoch) {
254
+ if (this._turnQueue.generation !== epoch) {
534
255
  this._completeSkippedRequest(connection, chatMessageId);
535
256
  return;
536
257
  }
@@ -541,7 +262,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
541
262
  }
542
263
  if (concurrencyDecision.mergeQueuedMessages) {
543
264
  await this._mergeQueuedUserMessages(epoch);
544
- if (this._chatEpoch !== epoch) {
265
+ if (this._turnQueue.generation !== epoch) {
545
266
  this._completeSkippedRequest(connection, chatMessageId);
546
267
  return;
547
268
  }
@@ -582,7 +303,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
582
303
  }
583
304
  });
584
305
  });
585
- }, { epoch });
306
+ }, {
307
+ epoch,
308
+ onStale: () => this._completeSkippedRequest(connection, chatMessageId)
309
+ });
586
310
  }
587
311
  if (data.type === MessageType.CF_AGENT_CHAT_CLEAR) {
588
312
  this.resetTurnState();
@@ -609,9 +333,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
609
333
  return;
610
334
  }
611
335
  if (data.type === MessageType.CF_AGENT_STREAM_RESUME_REQUEST) {
612
- if (this._resumableStream.hasActiveStream()) if (this._activeAutoContinuationRequestId === this._resumableStream.activeRequestId && this._activeAutoContinuationConnectionId !== null && this._activeAutoContinuationConnectionId !== connection.id) connection.send(JSON.stringify({ type: MessageType.CF_AGENT_STREAM_RESUME_NONE }));
336
+ 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
337
  else this._notifyStreamResuming(connection);
614
- else if (this._pendingAutoContinuation && this._pendingAutoContinuationConnectionId === connection.id) this._awaitingStreamStartConnections.set(connection.id, connection);
338
+ else if (this._continuation.pending !== null && this._continuation.pending.connectionId === connection.id) this._continuation.awaitingConnections.set(connection.id, connection);
615
339
  else connection.send(JSON.stringify({ type: MessageType.CF_AGENT_STREAM_RESUME_NONE }));
616
340
  return;
617
341
  }
@@ -669,8 +393,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
669
393
  }
670
394
  _flushAwaitingStreamStartConnections() {
671
395
  if (!this._resumableStream.hasActiveStream()) return;
672
- for (const connection of this._awaitingStreamStartConnections.values()) this._notifyStreamResuming(connection);
673
- this._awaitingStreamStartConnections.clear();
396
+ this._continuation.flushAwaitingConnections((c) => this._notifyStreamResuming(c));
674
397
  }
675
398
  _mergeAutoContinuationPrerequisite(current, next) {
676
399
  if (!next) return current;
@@ -680,52 +403,28 @@ var AIChatAgent = class AIChatAgent extends Agent {
680
403
  });
681
404
  }
682
405
  _storeDeferredAutoContinuation(connection, clientTools, body, errorPrefix, prerequisite) {
683
- const deferred = this._deferredAutoContinuation;
684
- this._deferredAutoContinuation = {
406
+ const existing = this._continuation.deferred;
407
+ this._continuation.deferred = {
685
408
  connection,
686
409
  connectionId: connection.id,
687
410
  clientTools,
688
411
  body,
689
412
  errorPrefix,
690
- prerequisite: this._mergeAutoContinuationPrerequisite(deferred?.prerequisite ?? null, prerequisite)
413
+ prerequisite: this._mergeAutoContinuationPrerequisite(existing?.prerequisite ?? null, prerequisite)
691
414
  };
692
415
  }
693
416
  _activateDeferredAutoContinuation() {
694
- if (this._pendingAutoContinuation || !this._deferredAutoContinuation) return;
695
- const deferred = this._deferredAutoContinuation;
696
- this._deferredAutoContinuation = null;
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;
417
+ const pending = this._continuation.activateDeferred(() => nanoid());
418
+ if (!pending) return;
419
+ this._queueAutoContinuation(pending.requestId);
712
420
  }
713
421
  _clearAllAutoContinuationState(sendNone = false) {
714
422
  this._clearPendingAutoContinuation(sendNone);
715
- this._clearDeferredAutoContinuation();
423
+ this._continuation.clearDeferred();
716
424
  }
717
425
  _clearPendingAutoContinuation(sendNone = false) {
718
- this._pendingAutoContinuation = false;
719
- this._pendingAutoContinuationConnection = null;
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();
426
+ if (sendNone) this._continuation.sendResumeNone();
427
+ this._continuation.clearPending();
729
428
  }
730
429
  /**
731
430
  * Notify a connection about an active stream that can be resumed.
@@ -751,19 +450,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
751
450
  /** @internal Delegate to _resumableStream */
752
451
  _startStream(requestId) {
753
452
  const streamId = this._resumableStream.start(requestId);
754
- if (this._pendingAutoContinuationRequestId === requestId) {
755
- this._activeAutoContinuationRequestId = requestId;
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;
453
+ if (this._continuation.pending?.requestId === requestId) {
454
+ this._continuation.activatePending();
765
455
  this._flushAwaitingStreamStartConnections();
766
- this._pendingAutoContinuationPastCoalesce = false;
767
456
  this._activateDeferredAutoContinuation();
768
457
  }
769
458
  return streamId;
@@ -773,9 +462,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
773
462
  const completedRequestId = this._resumableStream.activeRequestId;
774
463
  this._resumableStream.complete(streamId);
775
464
  this._pendingResumeConnections.clear();
776
- if (completedRequestId === this._activeAutoContinuationRequestId) {
777
- this._activeAutoContinuationRequestId = null;
778
- this._activeAutoContinuationConnectionId = null;
465
+ if (completedRequestId === this._continuation.activeRequestId) {
466
+ this._continuation.activeRequestId = null;
467
+ this._continuation.activeConnectionId = null;
779
468
  }
780
469
  }
781
470
  /** @internal Delegate to _resumableStream */
@@ -923,14 +612,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
923
612
  }
924
613
  }
925
614
  isChatTurnActive() {
926
- return this._activeChatTurnRequestId !== null;
615
+ return this._turnQueue.isActive;
927
616
  }
928
617
  async waitForIdle() {
929
- let queue;
930
- do {
931
- queue = this._chatTurnQueue;
932
- await queue;
933
- } while (this._chatTurnQueue !== queue);
618
+ await this._turnQueue.waitForIdle();
934
619
  }
935
620
  _normalizeMessageConcurrency() {
936
621
  if (typeof this.messageConcurrency === "string") return this.messageConcurrency;
@@ -941,7 +626,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
941
626
  };
942
627
  }
943
628
  _getSubmitConcurrencyDecision(trigger) {
944
- const queuedTurnsInCurrentEpoch = this._queuedChatTurnCountsByEpoch.get(this._chatEpoch) ?? 0;
629
+ const queuedTurnsInCurrentEpoch = this._turnQueue.queuedCount();
945
630
  if (trigger !== "submit-message" || queuedTurnsInCurrentEpoch === 0) return {
946
631
  action: "execute",
947
632
  submitSequence: null,
@@ -970,7 +655,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
970
655
  mergeQueuedMessages: false
971
656
  };
972
657
  if (concurrency === "merge") {
973
- if (!this._mergeQueuedUserStartIndexByEpoch.has(this._chatEpoch)) this._mergeQueuedUserStartIndexByEpoch.set(this._chatEpoch, this.messages.length);
658
+ if (!this._mergeQueuedUserStartIndexByEpoch.has(this._turnQueue.generation)) this._mergeQueuedUserStartIndexByEpoch.set(this._turnQueue.generation, this.messages.length);
974
659
  return {
975
660
  action: "execute",
976
661
  submitSequence,
@@ -1010,7 +695,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1010
695
  this._activeDebounceResolve = null;
1011
696
  }
1012
697
  }
1013
- async _mergeQueuedUserMessages(epoch = this._chatEpoch) {
698
+ async _mergeQueuedUserMessages(epoch = this._turnQueue.generation) {
1014
699
  const mergedMessages = this._getMergedQueuedUserMessages(epoch);
1015
700
  if (!mergedMessages) return;
1016
701
  await this.persistMessages(mergedMessages, [], { _deleteStaleRows: true });
@@ -1118,7 +803,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1118
803
  async waitUntilStable(options) {
1119
804
  const deadline = options?.timeout != null ? Date.now() + options.timeout : null;
1120
805
  while (true) {
1121
- if (await this._awaitWithDeadline(this._chatTurnQueue, deadline) === TIMED_OUT) return false;
806
+ if (await this._awaitWithDeadline(this._turnQueue.waitForIdle(), deadline) === TIMED_OUT) return false;
1122
807
  if (!this.hasPendingInteraction()) return true;
1123
808
  const pending = this._pendingInteractionPromise;
1124
809
  if (pending) {
@@ -1133,8 +818,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
1133
818
  }
1134
819
  }
1135
820
  abortActiveTurn() {
1136
- if (!this._activeChatTurnRequestId) return false;
1137
- this._cancelChatRequest(this._activeChatTurnRequestId);
821
+ if (!this._turnQueue.activeRequestId) return false;
822
+ this._cancelChatRequest(this._turnQueue.activeRequestId);
1138
823
  return true;
1139
824
  }
1140
825
  /**
@@ -1143,14 +828,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
1143
828
  * the built-in handler calls it automatically.
1144
829
  */
1145
830
  resetTurnState() {
1146
- this._mergeQueuedUserStartIndexByEpoch.delete(this._chatEpoch);
1147
- this._chatEpoch++;
831
+ this._mergeQueuedUserStartIndexByEpoch.delete(this._turnQueue.generation);
832
+ this._turnQueue.reset();
1148
833
  this._destroyAbortControllers();
1149
834
  this._cancelActiveDebounce();
1150
835
  this._pendingInteractionPromise = null;
1151
- this._activeAutoContinuationRequestId = null;
1152
- this._activeAutoContinuationConnectionId = null;
1153
- this._clearAllAutoContinuationState(true);
836
+ this._continuation.sendResumeNone();
837
+ this._continuation.clearAll();
1154
838
  this._pendingChatResponseResults.length = 0;
1155
839
  }
1156
840
  async _awaitWithDeadline(promise, deadline) {
@@ -1171,33 +855,21 @@ var AIChatAgent = class AIChatAgent extends Agent {
1171
855
  * streaming turn.
1172
856
  */
1173
857
  async _runExclusiveChatTurn(requestId, fn, options) {
1174
- const previousTurn = this._chatTurnQueue;
1175
- let releaseTurn = () => {};
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;
858
+ const generation = options?.epoch;
859
+ let result;
1183
860
  try {
1184
- return await fn();
861
+ result = await this._turnQueue.enqueue(requestId, fn, { generation });
1185
862
  } finally {
1186
- this._activeChatTurnRequestId = null;
1187
- const nextCount = (this._queuedChatTurnCountsByEpoch.get(epoch) ?? 1) - 1;
1188
- if (nextCount <= 0) {
1189
- this._queuedChatTurnCountsByEpoch.delete(epoch);
1190
- this._mergeQueuedUserStartIndexByEpoch.delete(epoch);
1191
- } else this._queuedChatTurnCountsByEpoch.set(epoch, nextCount);
1192
- releaseTurn();
863
+ const gen = generation ?? this._turnQueue.generation;
864
+ if (this._turnQueue.queuedCount(gen) === 0) this._mergeQueuedUserStartIndexByEpoch.delete(gen);
1193
865
  if (this._pendingChatResponseResults.length > 0 && !this._insideResponseHook) {
1194
866
  this._insideResponseHook = true;
1195
867
  try {
1196
868
  await this.keepAliveWhile(async () => {
1197
869
  while (this._pendingChatResponseResults.length > 0) {
1198
- const result = this._pendingChatResponseResults.shift();
870
+ const chatResult = this._pendingChatResponseResults.shift();
1199
871
  try {
1200
- await this.onChatResponse(result);
872
+ await this.onChatResponse(chatResult);
1201
873
  } catch (hookError) {
1202
874
  console.error("[AIChatAgent] onChatResponse threw:", hookError);
1203
875
  }
@@ -1208,65 +880,67 @@ var AIChatAgent = class AIChatAgent extends Agent {
1208
880
  }
1209
881
  }
1210
882
  }
883
+ if (result.status === "stale") {
884
+ options?.onStale?.();
885
+ return;
886
+ }
887
+ return result.value;
1211
888
  }
1212
889
  _enqueueAutoContinuation(connection, clientTools, body, errorPrefix, prerequisite) {
1213
- if (this._pendingAutoContinuation) {
1214
- if (this._pendingAutoContinuationPastCoalesce) {
890
+ if (this._continuation.pending) {
891
+ if (this._continuation.pending.pastCoalesce) {
1215
892
  this._storeDeferredAutoContinuation(connection, clientTools, body, errorPrefix, prerequisite);
1216
893
  return;
1217
894
  }
1218
- this._pendingAutoContinuationConnection = connection;
1219
- this._pendingAutoContinuationConnectionId = connection.id;
1220
- this._awaitingStreamStartConnections.set(connection.id, connection);
1221
- this._pendingAutoContinuationClientTools = clientTools;
1222
- this._pendingAutoContinuationBody = body;
1223
- this._pendingAutoContinuationErrorPrefix = errorPrefix;
1224
- this._pendingAutoContinuationPrerequisite = this._mergeAutoContinuationPrerequisite(this._pendingAutoContinuationPrerequisite, prerequisite);
895
+ this._continuation.pending.connection = connection;
896
+ this._continuation.pending.connectionId = connection.id;
897
+ this._continuation.awaitingConnections.set(connection.id, connection);
898
+ this._continuation.pending.clientTools = clientTools;
899
+ this._continuation.pending.body = body;
900
+ this._continuation.pending.errorPrefix = errorPrefix;
901
+ this._continuation.pending.prerequisite = this._mergeAutoContinuationPrerequisite(this._continuation.pending.prerequisite, prerequisite);
1225
902
  return;
1226
903
  }
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
904
  const requestId = nanoid();
1236
- this._pendingAutoContinuation = true;
1237
- this._pendingAutoContinuationRequestId = requestId;
905
+ this._continuation.pending = {
906
+ connection,
907
+ connectionId: connection.id,
908
+ requestId,
909
+ clientTools,
910
+ body,
911
+ errorPrefix,
912
+ prerequisite: this._mergeAutoContinuationPrerequisite(null, prerequisite),
913
+ pastCoalesce: false
914
+ };
915
+ this._continuation.awaitingConnections.set(connection.id, connection);
1238
916
  this._queueAutoContinuation(requestId);
1239
917
  }
1240
918
  async _awaitPendingAutoContinuationPrerequisite() {
1241
919
  while (true) {
1242
- const prerequisite = this._pendingAutoContinuationPrerequisite;
920
+ const prerequisite = this._continuation.pending?.prerequisite;
1243
921
  if (!prerequisite) return true;
1244
922
  if (!await prerequisite) return false;
1245
923
  await new Promise((resolve) => setTimeout(resolve, AIChatAgent.AUTO_CONTINUATION_COALESCE_MS));
1246
- if (this._pendingAutoContinuationPrerequisite === prerequisite) return true;
924
+ if (this._continuation.pending?.prerequisite === prerequisite) return true;
1247
925
  }
1248
926
  }
1249
927
  _queueAutoContinuation(requestId) {
1250
- const epoch = this._chatEpoch;
928
+ const epoch = this._turnQueue.generation;
1251
929
  this._runExclusiveChatTurn(requestId, async () => {
1252
930
  const dispose = await this.keepAlive();
1253
931
  try {
1254
- if (this._chatEpoch !== epoch) {
1255
- this._clearAllAutoContinuationState(true);
1256
- return;
1257
- }
1258
932
  if (!await this._awaitPendingAutoContinuationPrerequisite()) {
1259
933
  this._clearAllAutoContinuationState(true);
1260
934
  return;
1261
935
  }
1262
- const connection = this._pendingAutoContinuationConnection;
936
+ const connection = this._continuation.pending?.connection;
1263
937
  if (!connection) {
1264
938
  this._clearAllAutoContinuationState(true);
1265
939
  return;
1266
940
  }
1267
- const clientTools = this._pendingAutoContinuationClientTools;
1268
- const body = this._pendingAutoContinuationBody;
1269
- this._pendingAutoContinuationPastCoalesce = true;
941
+ const clientTools = this._continuation.pending?.clientTools;
942
+ const body = this._continuation.pending?.body;
943
+ if (this._continuation.pending) this._continuation.pending.pastCoalesce = true;
1270
944
  const abortSignal = this._getAbortSignal(requestId);
1271
945
  return this._tryCatchChat(async () => {
1272
946
  return __DO_NOT_USE_WILL_BREAK__agentContext.run({
@@ -1296,8 +970,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
1296
970
  } finally {
1297
971
  dispose();
1298
972
  }
1299
- }, { epoch }).catch((error) => {
1300
- const errorPrefix = this._pendingAutoContinuationErrorPrefix ?? "[AIChatAgent] Auto-continuation failed:";
973
+ }, {
974
+ epoch,
975
+ onStale: () => this._clearAllAutoContinuationState(true)
976
+ }).catch((error) => {
977
+ const errorPrefix = this._continuation.pending?.errorPrefix ?? "[AIChatAgent] Auto-continuation failed:";
1301
978
  this._clearAllAutoContinuationState(true);
1302
979
  console.error(errorPrefix, error);
1303
980
  });
@@ -1415,35 +1092,31 @@ var AIChatAgent = class AIChatAgent extends Agent {
1415
1092
  const requestId = nanoid();
1416
1093
  const clientTools = this._lastClientTools;
1417
1094
  const body = this._lastBody;
1418
- const epoch = this._chatEpoch;
1095
+ const epoch = this._turnQueue.generation;
1419
1096
  let status = "completed";
1420
1097
  await this._runExclusiveChatTurn(requestId, async () => {
1421
- if (this._chatEpoch !== epoch) {
1422
- status = "skipped";
1423
- return;
1424
- }
1425
1098
  const resolvedMessages = typeof messages === "function" ? await messages(this.messages) : messages;
1426
- if (this._chatEpoch !== epoch) {
1099
+ if (this._turnQueue.generation !== epoch) {
1427
1100
  status = "skipped";
1428
1101
  return;
1429
1102
  }
1430
1103
  await this.persistMessages(resolvedMessages);
1431
- if (this._chatEpoch !== epoch) {
1104
+ if (this._turnQueue.generation !== epoch) {
1432
1105
  status = "skipped";
1433
1106
  return;
1434
1107
  }
1435
1108
  await this._runProgrammaticChatTurn(requestId, clientTools, body);
1436
1109
  }, { epoch });
1110
+ if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
1437
1111
  return {
1438
1112
  requestId,
1439
1113
  status
1440
1114
  };
1441
1115
  }
1442
1116
  async persistMessages(messages, excludeBroadcastIds = [], options) {
1443
- const mergedMessages = this._mergeIncomingWithServerState(messages);
1117
+ const mergedMessages = reconcileMessages(messages, this.messages, (msg) => this._sanitizeMessageForPersistence(msg));
1444
1118
  for (const message of mergedMessages) {
1445
- const sanitizedMessage = this._sanitizeMessageForPersistence(message);
1446
- const resolved = this._resolveMessageForToolMerge(sanitizedMessage);
1119
+ const resolved = resolveToolMergeId(this._sanitizeMessageForPersistence(message), this.messages);
1447
1120
  const safe = this._enforceRowSizeLimit(resolved);
1448
1121
  const json = JSON.stringify(safe);
1449
1122
  if (this._persistedMessageCache.get(safe.id) === json) continue;
@@ -1477,123 +1150,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
1477
1150
  }, excludeBroadcastIds);
1478
1151
  }
1479
1152
  /**
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
1153
  * Finds an existing assistant message that contains a tool part with the given toolCallId.
1598
1154
  * Used to detect when a tool result should update an existing message rather than
1599
1155
  * creating a new one.
@@ -1650,51 +1206,14 @@ var AIChatAgent = class AIChatAgent extends Agent {
1650
1206
  * @returns A new message with ephemeral provider data removed
1651
1207
  */
1652
1208
  _sanitizeMessageForPersistence(message) {
1653
- const sanitizedParts = message.parts.map((part) => {
1654
- let sanitizedPart = part;
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
- });
1209
+ const baseSanitized = sanitizeMessage(message);
1210
+ const parts = baseSanitized.parts.map((part) => AIChatAgent._truncateProviderExecutedToolPayloads(part));
1669
1211
  return this.sanitizeMessageForPersistence({
1670
- ...message,
1671
- parts: sanitizedParts
1212
+ ...baseSanitized,
1213
+ parts
1672
1214
  });
1673
1215
  }
1674
1216
  /**
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
1217
  * Truncates large string values in `input` and `output` of tool parts that
1699
1218
  * were executed server-side by the provider (e.g. Anthropic code_execution,
1700
1219
  * text_editor). These payloads can be 200KB+ and are dead weight once the
@@ -1788,8 +1307,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
1788
1307
  */
1789
1308
  _enforceRowSizeLimit(message) {
1790
1309
  let json = JSON.stringify(message);
1791
- let size = AIChatAgent._byteLength(json);
1792
- if (size <= AIChatAgent.ROW_MAX_BYTES) return message;
1310
+ let size = byteLength(json);
1311
+ if (size <= ROW_MAX_BYTES) return message;
1793
1312
  if (message.role !== "assistant") {
1794
1313
  console.warn(`[AIChatAgent] Non-assistant message ${message.id} is ${size} bytes, exceeds row limit. Truncating text parts.`);
1795
1314
  return this._truncateTextParts(message);
@@ -1818,8 +1337,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
1818
1337
  compactedToolOutputs: compactedToolCallIds
1819
1338
  };
1820
1339
  json = JSON.stringify(result);
1821
- size = AIChatAgent._byteLength(json);
1822
- if (size <= AIChatAgent.ROW_MAX_BYTES) return result;
1340
+ size = byteLength(json);
1341
+ if (size <= ROW_MAX_BYTES) return result;
1823
1342
  console.warn(`[AIChatAgent] Message ${message.id} still ${size} bytes after tool compaction, truncating text parts`);
1824
1343
  return this._truncateTextParts(result);
1825
1344
  }
@@ -1845,7 +1364,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1845
1364
  ...message,
1846
1365
  parts
1847
1366
  };
1848
- if (AIChatAgent._byteLength(JSON.stringify(candidate)) <= AIChatAgent.ROW_MAX_BYTES) break;
1367
+ if (byteLength(JSON.stringify(candidate)) <= ROW_MAX_BYTES) break;
1849
1368
  }
1850
1369
  }
1851
1370
  }