@cloudflare/ai-chat 0.3.0 → 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 */
@@ -807,8 +496,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
807
496
  _persistOrphanedStream(streamId) {
808
497
  const chunks = this._resumableStream.getStreamChunks(streamId);
809
498
  if (!chunks.length) return;
499
+ const fallbackId = `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
810
500
  const message = {
811
- id: `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`,
501
+ id: fallbackId,
812
502
  role: "assistant",
813
503
  parts: []
814
504
  };
@@ -822,7 +512,21 @@ var AIChatAgent = class AIChatAgent extends Agent {
822
512
  applyChunkToParts(message.parts, data);
823
513
  } catch {}
824
514
  if (message.parts.length > 0) {
515
+ if (message.id === fallbackId) {
516
+ for (let i = this.messages.length - 1; i >= 0; i--) if (this.messages[i].role === "assistant") {
517
+ message.id = this.messages[i].id;
518
+ break;
519
+ }
520
+ }
825
521
  const existingIdx = this.messages.findIndex((m) => m.id === message.id);
522
+ if (existingIdx >= 0) {
523
+ const existing = this.messages[existingIdx];
524
+ message.parts = [...existing.parts, ...message.parts];
525
+ if (existing.metadata) message.metadata = message.metadata ? {
526
+ ...existing.metadata,
527
+ ...message.metadata
528
+ } : existing.metadata;
529
+ }
826
530
  const updatedMessages = existingIdx >= 0 ? this.messages.map((m, i) => i === existingIdx ? message : m) : [...this.messages, message];
827
531
  this.persistMessages(updatedMessages);
828
532
  }
@@ -908,14 +612,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
908
612
  }
909
613
  }
910
614
  isChatTurnActive() {
911
- return this._activeChatTurnRequestId !== null;
615
+ return this._turnQueue.isActive;
912
616
  }
913
617
  async waitForIdle() {
914
- let queue;
915
- do {
916
- queue = this._chatTurnQueue;
917
- await queue;
918
- } while (this._chatTurnQueue !== queue);
618
+ await this._turnQueue.waitForIdle();
919
619
  }
920
620
  _normalizeMessageConcurrency() {
921
621
  if (typeof this.messageConcurrency === "string") return this.messageConcurrency;
@@ -926,7 +626,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
926
626
  };
927
627
  }
928
628
  _getSubmitConcurrencyDecision(trigger) {
929
- const queuedTurnsInCurrentEpoch = this._queuedChatTurnCountsByEpoch.get(this._chatEpoch) ?? 0;
629
+ const queuedTurnsInCurrentEpoch = this._turnQueue.queuedCount();
930
630
  if (trigger !== "submit-message" || queuedTurnsInCurrentEpoch === 0) return {
931
631
  action: "execute",
932
632
  submitSequence: null,
@@ -955,7 +655,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
955
655
  mergeQueuedMessages: false
956
656
  };
957
657
  if (concurrency === "merge") {
958
- 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);
959
659
  return {
960
660
  action: "execute",
961
661
  submitSequence,
@@ -995,7 +695,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
995
695
  this._activeDebounceResolve = null;
996
696
  }
997
697
  }
998
- async _mergeQueuedUserMessages(epoch = this._chatEpoch) {
698
+ async _mergeQueuedUserMessages(epoch = this._turnQueue.generation) {
999
699
  const mergedMessages = this._getMergedQueuedUserMessages(epoch);
1000
700
  if (!mergedMessages) return;
1001
701
  await this.persistMessages(mergedMessages, [], { _deleteStaleRows: true });
@@ -1103,7 +803,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1103
803
  async waitUntilStable(options) {
1104
804
  const deadline = options?.timeout != null ? Date.now() + options.timeout : null;
1105
805
  while (true) {
1106
- if (await this._awaitWithDeadline(this._chatTurnQueue, deadline) === TIMED_OUT) return false;
806
+ if (await this._awaitWithDeadline(this._turnQueue.waitForIdle(), deadline) === TIMED_OUT) return false;
1107
807
  if (!this.hasPendingInteraction()) return true;
1108
808
  const pending = this._pendingInteractionPromise;
1109
809
  if (pending) {
@@ -1118,8 +818,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
1118
818
  }
1119
819
  }
1120
820
  abortActiveTurn() {
1121
- if (!this._activeChatTurnRequestId) return false;
1122
- this._cancelChatRequest(this._activeChatTurnRequestId);
821
+ if (!this._turnQueue.activeRequestId) return false;
822
+ this._cancelChatRequest(this._turnQueue.activeRequestId);
1123
823
  return true;
1124
824
  }
1125
825
  /**
@@ -1128,14 +828,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
1128
828
  * the built-in handler calls it automatically.
1129
829
  */
1130
830
  resetTurnState() {
1131
- this._mergeQueuedUserStartIndexByEpoch.delete(this._chatEpoch);
1132
- this._chatEpoch++;
831
+ this._mergeQueuedUserStartIndexByEpoch.delete(this._turnQueue.generation);
832
+ this._turnQueue.reset();
1133
833
  this._destroyAbortControllers();
1134
834
  this._cancelActiveDebounce();
1135
835
  this._pendingInteractionPromise = null;
1136
- this._activeAutoContinuationRequestId = null;
1137
- this._activeAutoContinuationConnectionId = null;
1138
- this._clearAllAutoContinuationState(true);
836
+ this._continuation.sendResumeNone();
837
+ this._continuation.clearAll();
1139
838
  this._pendingChatResponseResults.length = 0;
1140
839
  }
1141
840
  async _awaitWithDeadline(promise, deadline) {
@@ -1156,33 +855,21 @@ var AIChatAgent = class AIChatAgent extends Agent {
1156
855
  * streaming turn.
1157
856
  */
1158
857
  async _runExclusiveChatTurn(requestId, fn, options) {
1159
- const previousTurn = this._chatTurnQueue;
1160
- let releaseTurn = () => {};
1161
- const epoch = options?.epoch ?? this._chatEpoch;
1162
- this._queuedChatTurnCountsByEpoch.set(epoch, (this._queuedChatTurnCountsByEpoch.get(epoch) ?? 0) + 1);
1163
- this._chatTurnQueue = new Promise((resolve) => {
1164
- releaseTurn = resolve;
1165
- });
1166
- await previousTurn;
1167
- this._activeChatTurnRequestId = requestId;
858
+ const generation = options?.epoch;
859
+ let result;
1168
860
  try {
1169
- return await fn();
861
+ result = await this._turnQueue.enqueue(requestId, fn, { generation });
1170
862
  } finally {
1171
- this._activeChatTurnRequestId = null;
1172
- const nextCount = (this._queuedChatTurnCountsByEpoch.get(epoch) ?? 1) - 1;
1173
- if (nextCount <= 0) {
1174
- this._queuedChatTurnCountsByEpoch.delete(epoch);
1175
- this._mergeQueuedUserStartIndexByEpoch.delete(epoch);
1176
- } else this._queuedChatTurnCountsByEpoch.set(epoch, nextCount);
1177
- releaseTurn();
863
+ const gen = generation ?? this._turnQueue.generation;
864
+ if (this._turnQueue.queuedCount(gen) === 0) this._mergeQueuedUserStartIndexByEpoch.delete(gen);
1178
865
  if (this._pendingChatResponseResults.length > 0 && !this._insideResponseHook) {
1179
866
  this._insideResponseHook = true;
1180
867
  try {
1181
868
  await this.keepAliveWhile(async () => {
1182
869
  while (this._pendingChatResponseResults.length > 0) {
1183
- const result = this._pendingChatResponseResults.shift();
870
+ const chatResult = this._pendingChatResponseResults.shift();
1184
871
  try {
1185
- await this.onChatResponse(result);
872
+ await this.onChatResponse(chatResult);
1186
873
  } catch (hookError) {
1187
874
  console.error("[AIChatAgent] onChatResponse threw:", hookError);
1188
875
  }
@@ -1193,65 +880,67 @@ var AIChatAgent = class AIChatAgent extends Agent {
1193
880
  }
1194
881
  }
1195
882
  }
883
+ if (result.status === "stale") {
884
+ options?.onStale?.();
885
+ return;
886
+ }
887
+ return result.value;
1196
888
  }
1197
889
  _enqueueAutoContinuation(connection, clientTools, body, errorPrefix, prerequisite) {
1198
- if (this._pendingAutoContinuation) {
1199
- if (this._pendingAutoContinuationPastCoalesce) {
890
+ if (this._continuation.pending) {
891
+ if (this._continuation.pending.pastCoalesce) {
1200
892
  this._storeDeferredAutoContinuation(connection, clientTools, body, errorPrefix, prerequisite);
1201
893
  return;
1202
894
  }
1203
- this._pendingAutoContinuationConnection = connection;
1204
- this._pendingAutoContinuationConnectionId = connection.id;
1205
- this._awaitingStreamStartConnections.set(connection.id, connection);
1206
- this._pendingAutoContinuationClientTools = clientTools;
1207
- this._pendingAutoContinuationBody = body;
1208
- this._pendingAutoContinuationErrorPrefix = errorPrefix;
1209
- 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);
1210
902
  return;
1211
903
  }
1212
- this._pendingAutoContinuationConnection = connection;
1213
- this._pendingAutoContinuationConnectionId = connection.id;
1214
- this._awaitingStreamStartConnections.set(connection.id, connection);
1215
- this._pendingAutoContinuationClientTools = clientTools;
1216
- this._pendingAutoContinuationBody = body;
1217
- this._pendingAutoContinuationErrorPrefix = errorPrefix;
1218
- this._pendingAutoContinuationPrerequisite = this._mergeAutoContinuationPrerequisite(this._pendingAutoContinuationPrerequisite, prerequisite);
1219
- this._pendingAutoContinuationPastCoalesce = false;
1220
904
  const requestId = nanoid();
1221
- this._pendingAutoContinuation = true;
1222
- 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);
1223
916
  this._queueAutoContinuation(requestId);
1224
917
  }
1225
918
  async _awaitPendingAutoContinuationPrerequisite() {
1226
919
  while (true) {
1227
- const prerequisite = this._pendingAutoContinuationPrerequisite;
920
+ const prerequisite = this._continuation.pending?.prerequisite;
1228
921
  if (!prerequisite) return true;
1229
922
  if (!await prerequisite) return false;
1230
923
  await new Promise((resolve) => setTimeout(resolve, AIChatAgent.AUTO_CONTINUATION_COALESCE_MS));
1231
- if (this._pendingAutoContinuationPrerequisite === prerequisite) return true;
924
+ if (this._continuation.pending?.prerequisite === prerequisite) return true;
1232
925
  }
1233
926
  }
1234
927
  _queueAutoContinuation(requestId) {
1235
- const epoch = this._chatEpoch;
928
+ const epoch = this._turnQueue.generation;
1236
929
  this._runExclusiveChatTurn(requestId, async () => {
1237
930
  const dispose = await this.keepAlive();
1238
931
  try {
1239
- if (this._chatEpoch !== epoch) {
1240
- this._clearAllAutoContinuationState(true);
1241
- return;
1242
- }
1243
932
  if (!await this._awaitPendingAutoContinuationPrerequisite()) {
1244
933
  this._clearAllAutoContinuationState(true);
1245
934
  return;
1246
935
  }
1247
- const connection = this._pendingAutoContinuationConnection;
936
+ const connection = this._continuation.pending?.connection;
1248
937
  if (!connection) {
1249
938
  this._clearAllAutoContinuationState(true);
1250
939
  return;
1251
940
  }
1252
- const clientTools = this._pendingAutoContinuationClientTools;
1253
- const body = this._pendingAutoContinuationBody;
1254
- 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;
1255
944
  const abortSignal = this._getAbortSignal(requestId);
1256
945
  return this._tryCatchChat(async () => {
1257
946
  return __DO_NOT_USE_WILL_BREAK__agentContext.run({
@@ -1281,8 +970,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
1281
970
  } finally {
1282
971
  dispose();
1283
972
  }
1284
- }, { epoch }).catch((error) => {
1285
- 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:";
1286
978
  this._clearAllAutoContinuationState(true);
1287
979
  console.error(errorPrefix, error);
1288
980
  });
@@ -1400,35 +1092,31 @@ var AIChatAgent = class AIChatAgent extends Agent {
1400
1092
  const requestId = nanoid();
1401
1093
  const clientTools = this._lastClientTools;
1402
1094
  const body = this._lastBody;
1403
- const epoch = this._chatEpoch;
1095
+ const epoch = this._turnQueue.generation;
1404
1096
  let status = "completed";
1405
1097
  await this._runExclusiveChatTurn(requestId, async () => {
1406
- if (this._chatEpoch !== epoch) {
1407
- status = "skipped";
1408
- return;
1409
- }
1410
1098
  const resolvedMessages = typeof messages === "function" ? await messages(this.messages) : messages;
1411
- if (this._chatEpoch !== epoch) {
1099
+ if (this._turnQueue.generation !== epoch) {
1412
1100
  status = "skipped";
1413
1101
  return;
1414
1102
  }
1415
1103
  await this.persistMessages(resolvedMessages);
1416
- if (this._chatEpoch !== epoch) {
1104
+ if (this._turnQueue.generation !== epoch) {
1417
1105
  status = "skipped";
1418
1106
  return;
1419
1107
  }
1420
1108
  await this._runProgrammaticChatTurn(requestId, clientTools, body);
1421
1109
  }, { epoch });
1110
+ if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
1422
1111
  return {
1423
1112
  requestId,
1424
1113
  status
1425
1114
  };
1426
1115
  }
1427
1116
  async persistMessages(messages, excludeBroadcastIds = [], options) {
1428
- const mergedMessages = this._mergeIncomingWithServerState(messages);
1117
+ const mergedMessages = reconcileMessages(messages, this.messages, (msg) => this._sanitizeMessageForPersistence(msg));
1429
1118
  for (const message of mergedMessages) {
1430
- const sanitizedMessage = this._sanitizeMessageForPersistence(message);
1431
- const resolved = this._resolveMessageForToolMerge(sanitizedMessage);
1119
+ const resolved = resolveToolMergeId(this._sanitizeMessageForPersistence(message), this.messages);
1432
1120
  const safe = this._enforceRowSizeLimit(resolved);
1433
1121
  const json = JSON.stringify(safe);
1434
1122
  if (this._persistedMessageCache.get(safe.id) === json) continue;
@@ -1462,123 +1150,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
1462
1150
  }, excludeBroadcastIds);
1463
1151
  }
1464
1152
  /**
1465
- * Merges incoming messages with existing server state.
1466
- * This preserves tool outputs that the server has (via _applyToolResult)
1467
- * but the client doesn't have yet.
1468
- *
1469
- * @param incomingMessages - Messages from the client
1470
- * @returns Messages with server's tool outputs preserved
1471
- */
1472
- _mergeIncomingWithServerState(incomingMessages) {
1473
- const serverToolOutputs = /* @__PURE__ */ new Map();
1474
- for (const msg of this.messages) {
1475
- if (msg.role !== "assistant") continue;
1476
- 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);
1477
- }
1478
- const withMergedToolOutputs = serverToolOutputs.size === 0 ? incomingMessages : incomingMessages.map((msg) => {
1479
- if (msg.role !== "assistant") return msg;
1480
- let hasChanges = false;
1481
- const updatedParts = msg.parts.map((part) => {
1482
- if ("toolCallId" in part && "state" in part && (part.state === "input-available" || part.state === "approval-requested" || part.state === "approval-responded") && serverToolOutputs.has(part.toolCallId)) {
1483
- hasChanges = true;
1484
- return {
1485
- ...part,
1486
- state: "output-available",
1487
- output: serverToolOutputs.get(part.toolCallId)
1488
- };
1489
- }
1490
- return part;
1491
- });
1492
- return hasChanges ? {
1493
- ...msg,
1494
- parts: updatedParts
1495
- } : msg;
1496
- });
1497
- return this._reconcileAssistantIdsWithServerState(withMergedToolOutputs);
1498
- }
1499
- /**
1500
- * Reconciles assistant message IDs between incoming client state and server state.
1501
- *
1502
- * The client can keep a different local ID for an assistant message than the one
1503
- * persisted on the server (e.g. optimistic/local IDs). When that full history is
1504
- * sent back, persisting by ID alone creates duplicate assistant rows. To prevent
1505
- * this, we reuse the server ID for assistant messages that match by content,
1506
- * while leaving tool-call messages to _resolveMessageForToolMerge.
1507
- *
1508
- * Uses a two-pass approach:
1509
- * - Pass 1: resolve all exact-ID matches, claiming server indices.
1510
- * - Pass 2: content-based matching for remaining non-tool assistant messages,
1511
- * scanning only unclaimed server indices left-to-right.
1512
- *
1513
- * The two-pass design prevents exact-ID matches from advancing a cursor past
1514
- * server messages that a later incoming message needs for content matching.
1515
- * This fixes mismatches when two assistant messages have identical text
1516
- * (e.g. "Sure", "I understand") — see #1008.
1517
- */
1518
- _reconcileAssistantIdsWithServerState(incomingMessages) {
1519
- if (this.messages.length === 0) return incomingMessages;
1520
- const claimedServerIndices = /* @__PURE__ */ new Set();
1521
- const exactMatchMap = /* @__PURE__ */ new Map();
1522
- for (let i = 0; i < incomingMessages.length; i++) {
1523
- const serverIdx = this.messages.findIndex((sm, si) => !claimedServerIndices.has(si) && sm.id === incomingMessages[i].id);
1524
- if (serverIdx !== -1) {
1525
- claimedServerIndices.add(serverIdx);
1526
- exactMatchMap.set(i, serverIdx);
1527
- }
1528
- }
1529
- return incomingMessages.map((incomingMessage, incomingIdx) => {
1530
- if (exactMatchMap.has(incomingIdx)) return incomingMessage;
1531
- if (incomingMessage.role !== "assistant" || this._hasToolCallPart(incomingMessage)) return incomingMessage;
1532
- const incomingKey = this._assistantMessageContentKey(incomingMessage);
1533
- if (!incomingKey) return incomingMessage;
1534
- for (let i = 0; i < this.messages.length; i++) {
1535
- if (claimedServerIndices.has(i)) continue;
1536
- const serverMessage = this.messages[i];
1537
- if (serverMessage.role !== "assistant" || this._hasToolCallPart(serverMessage)) continue;
1538
- if (this._assistantMessageContentKey(serverMessage) === incomingKey) {
1539
- claimedServerIndices.add(i);
1540
- return {
1541
- ...incomingMessage,
1542
- id: serverMessage.id
1543
- };
1544
- }
1545
- }
1546
- return incomingMessage;
1547
- });
1548
- }
1549
- _hasToolCallPart(message) {
1550
- return message.parts.some((part) => "toolCallId" in part);
1551
- }
1552
- _assistantMessageContentKey(message) {
1553
- if (message.role !== "assistant") return;
1554
- const sanitized = this._sanitizeMessageForPersistence(message);
1555
- return JSON.stringify(sanitized.parts);
1556
- }
1557
- /**
1558
- * Resolves a message for persistence, handling tool result merging.
1559
- * If the message contains tool parts with a toolCallId that already exists
1560
- * in a server-side message with a different ID, adopts the server's ID.
1561
- * This prevents duplicate rows when the client sends messages with
1562
- * client-generated IDs (e.g. nanoid from the AI SDK) that differ from
1563
- * the server-stamped IDs. Tool call IDs are unique per conversation,
1564
- * so matching by toolCallId is safe regardless of tool state (#1094).
1565
- *
1566
- * @param message - The message to potentially merge
1567
- * @returns The message with the correct ID (either original or merged)
1568
- */
1569
- _resolveMessageForToolMerge(message) {
1570
- if (message.role !== "assistant") return message;
1571
- for (const part of message.parts) if ("toolCallId" in part && part.toolCallId) {
1572
- const toolCallId = part.toolCallId;
1573
- const existingMessage = this._findMessageByToolCallId(toolCallId);
1574
- if (existingMessage && existingMessage.id !== message.id) return {
1575
- ...message,
1576
- id: existingMessage.id
1577
- };
1578
- }
1579
- return message;
1580
- }
1581
- /**
1582
1153
  * Finds an existing assistant message that contains a tool part with the given toolCallId.
1583
1154
  * Used to detect when a tool result should update an existing message rather than
1584
1155
  * creating a new one.
@@ -1635,51 +1206,14 @@ var AIChatAgent = class AIChatAgent extends Agent {
1635
1206
  * @returns A new message with ephemeral provider data removed
1636
1207
  */
1637
1208
  _sanitizeMessageForPersistence(message) {
1638
- const sanitizedParts = message.parts.map((part) => {
1639
- let sanitizedPart = part;
1640
- if ("providerMetadata" in sanitizedPart && sanitizedPart.providerMetadata && typeof sanitizedPart.providerMetadata === "object" && "openai" in sanitizedPart.providerMetadata) sanitizedPart = this._stripOpenAIMetadata(sanitizedPart, "providerMetadata");
1641
- if ("callProviderMetadata" in sanitizedPart && sanitizedPart.callProviderMetadata && typeof sanitizedPart.callProviderMetadata === "object" && "openai" in sanitizedPart.callProviderMetadata) sanitizedPart = this._stripOpenAIMetadata(sanitizedPart, "callProviderMetadata");
1642
- sanitizedPart = AIChatAgent._truncateProviderExecutedToolPayloads(sanitizedPart);
1643
- return sanitizedPart;
1644
- }).filter((part) => {
1645
- if (part.type === "reasoning") {
1646
- const reasoningPart = part;
1647
- if (!reasoningPart.text || reasoningPart.text.trim() === "") {
1648
- if ("providerMetadata" in reasoningPart && reasoningPart.providerMetadata && typeof reasoningPart.providerMetadata === "object" && Object.keys(reasoningPart.providerMetadata).length > 0) return true;
1649
- return false;
1650
- }
1651
- }
1652
- return true;
1653
- });
1209
+ const baseSanitized = sanitizeMessage(message);
1210
+ const parts = baseSanitized.parts.map((part) => AIChatAgent._truncateProviderExecutedToolPayloads(part));
1654
1211
  return this.sanitizeMessageForPersistence({
1655
- ...message,
1656
- parts: sanitizedParts
1212
+ ...baseSanitized,
1213
+ parts
1657
1214
  });
1658
1215
  }
1659
1216
  /**
1660
- * Helper to strip OpenAI-specific ephemeral fields from a metadata object.
1661
- * Removes itemId and reasoningEncryptedContent while preserving other fields.
1662
- */
1663
- _stripOpenAIMetadata(part, metadataKey) {
1664
- const metadata = part[metadataKey];
1665
- if (!metadata?.openai) return part;
1666
- const { itemId: _itemId, reasoningEncryptedContent: _rec, ...restOpenai } = metadata.openai;
1667
- const hasOtherOpenaiFields = Object.keys(restOpenai).length > 0;
1668
- const { openai: _openai, ...restMetadata } = metadata;
1669
- let newMetadata;
1670
- if (hasOtherOpenaiFields) newMetadata = {
1671
- ...restMetadata,
1672
- openai: restOpenai
1673
- };
1674
- else if (Object.keys(restMetadata).length > 0) newMetadata = restMetadata;
1675
- const { [metadataKey]: _oldMeta, ...restPart } = part;
1676
- if (newMetadata) return {
1677
- ...restPart,
1678
- [metadataKey]: newMetadata
1679
- };
1680
- return restPart;
1681
- }
1682
- /**
1683
1217
  * Truncates large string values in `input` and `output` of tool parts that
1684
1218
  * were executed server-side by the provider (e.g. Anthropic code_execution,
1685
1219
  * text_editor). These payloads can be 200KB+ and are dead weight once the
@@ -1773,8 +1307,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
1773
1307
  */
1774
1308
  _enforceRowSizeLimit(message) {
1775
1309
  let json = JSON.stringify(message);
1776
- let size = AIChatAgent._byteLength(json);
1777
- if (size <= AIChatAgent.ROW_MAX_BYTES) return message;
1310
+ let size = byteLength(json);
1311
+ if (size <= ROW_MAX_BYTES) return message;
1778
1312
  if (message.role !== "assistant") {
1779
1313
  console.warn(`[AIChatAgent] Non-assistant message ${message.id} is ${size} bytes, exceeds row limit. Truncating text parts.`);
1780
1314
  return this._truncateTextParts(message);
@@ -1803,8 +1337,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
1803
1337
  compactedToolOutputs: compactedToolCallIds
1804
1338
  };
1805
1339
  json = JSON.stringify(result);
1806
- size = AIChatAgent._byteLength(json);
1807
- if (size <= AIChatAgent.ROW_MAX_BYTES) return result;
1340
+ size = byteLength(json);
1341
+ if (size <= ROW_MAX_BYTES) return result;
1808
1342
  console.warn(`[AIChatAgent] Message ${message.id} still ${size} bytes after tool compaction, truncating text parts`);
1809
1343
  return this._truncateTextParts(result);
1810
1344
  }
@@ -1830,7 +1364,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1830
1364
  ...message,
1831
1365
  parts
1832
1366
  };
1833
- if (AIChatAgent._byteLength(JSON.stringify(candidate)) <= AIChatAgent.ROW_MAX_BYTES) break;
1367
+ if (byteLength(JSON.stringify(candidate)) <= ROW_MAX_BYTES) break;
1834
1368
  }
1835
1369
  }
1836
1370
  }
@@ -2051,6 +1585,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
2051
1585
  break;
2052
1586
  }
2053
1587
  let eventToSend = data;
1588
+ if (continuation && data.type === "start" && "messageId" in data) {
1589
+ const { messageId: _, ...rest } = data;
1590
+ eventToSend = rest;
1591
+ }
2054
1592
  if (data.type === "finish" && "finishReason" in data) {
2055
1593
  const { finishReason, ...rest } = data;
2056
1594
  eventToSend = {