@cloudflare/ai-chat 0.7.2 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -4,6 +4,19 @@ import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
4
4
  import { AbortRegistry, ContinuationState, ROW_MAX_BYTES, ResumableStream, SubmitConcurrencyController, TurnQueue, applyChunkToParts, byteLength, createChatFiberSnapshot, createToolsFromClientSchemas, isReplayChunk, reconcileMessages, resolveToolMergeId, sanitizeMessage, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
5
5
  import { nanoid } from "nanoid";
6
6
  //#region src/index.ts
7
+ const CHAT_RECOVERY_INCIDENT_KEY_PREFIX = "cf:chat-recovery:incident:";
8
+ const CHAT_RECOVERY_PROGRESS_KEY = "cf:chat-recovery:progress";
9
+ const DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS = 10;
10
+ const DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS = 1e4;
11
+ const AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS = 6e4;
12
+ const CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS = 3;
13
+ const DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE = "The assistant was interrupted and could not recover. Please try again.";
14
+ const CHAT_RECOVERING_KEY = "cf:chat:recovering";
15
+ const CHAT_RECOVERY_INCIDENT_TTL_MS = 3600 * 1e3;
16
+ const CHAT_RECOVERY_NO_PROGRESS_WINDOW_MS = 300 * 1e3;
17
+ const CHAT_RECOVERY_ALARM_DEBOUNCE_MS = 30 * 1e3;
18
+ const CHAT_RECOVERY_MAX_WINDOW_MS = 900 * 1e3;
19
+ const AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS = 5e3;
7
20
  function sendIfOpen(connection, message) {
8
21
  try {
9
22
  connection.send(message);
@@ -64,6 +77,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
64
77
  const snapshot = createChatFiberSnapshot({
65
78
  kind: "ai-chat-turn",
66
79
  requestId,
80
+ recoveryRootRequestId: this._activeChatRecoveryRootRequestId ?? requestId,
67
81
  continuation,
68
82
  messages: this.messages,
69
83
  lastBody: this._lastBody,
@@ -103,6 +117,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
103
117
  this._pendingChatResponseResults = [];
104
118
  this._insideResponseHook = false;
105
119
  this._pendingInteractionPromise = null;
120
+ this._interactionApplyTail = Promise.resolve();
106
121
  this._approvalPersistedMessageId = null;
107
122
  this._turnQueue = new TurnQueue();
108
123
  this.chatRecovery = false;
@@ -122,6 +137,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
122
137
  this.messageConcurrency = "queue";
123
138
  this.waitForMcpConnections = { timeout: 1e4 };
124
139
  this.messages = [];
140
+ this._lastAgentToolStreamProgressAt = 0;
125
141
  this.sql`create table if not exists cf_ai_chat_agent_messages (
126
142
  id text primary key,
127
143
  message text not null,
@@ -146,9 +162,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
146
162
  const _onClose = this.onClose.bind(this);
147
163
  this.onClose = async (connection, code, reason, wasClean) => {
148
164
  this._pendingResumeConnections.delete(connection.id);
149
- this._continuation.awaitingConnections.delete(connection.id);
150
- if (this._continuation.pending?.connectionId === connection.id) this._continuation.pending = null;
151
- if (this._continuation.activeConnectionId === connection.id) this._continuation.activeConnectionId = null;
165
+ this._continuation.releaseConnection(connection.id);
152
166
  return _onClose(connection, code, reason, wasClean);
153
167
  };
154
168
  const _onMessage = this.onMessage.bind(this);
@@ -298,7 +312,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
298
312
  if (data.type === "cf_agent_stream_resume_request") {
299
313
  if (this._resumableStream.hasActiveStream()) if (this._continuation.activeRequestId === this._resumableStream.activeRequestId && this._continuation.activeConnectionId !== null && this._continuation.activeConnectionId !== connection.id) sendIfOpen(connection, JSON.stringify({ type: "cf_agent_stream_resume_none" }));
300
314
  else this._notifyStreamResuming(connection);
301
- else if (this._continuation.pending !== null && this._continuation.pending.connectionId === connection.id) this._continuation.awaitingConnections.set(connection.id, connection);
315
+ else if (this._continuation.pending !== null && (this._continuation.pending.connectionId === null || this._continuation.pending.connectionId === connection.id)) this._continuation.awaitingConnections.set(connection.id, connection);
302
316
  else sendIfOpen(connection, JSON.stringify({ type: "cf_agent_stream_resume_none" }));
303
317
  return;
304
318
  }
@@ -306,7 +320,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
306
320
  this._pendingResumeConnections.delete(connection.id);
307
321
  if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === data.id) {
308
322
  const orphanedStreamId = this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
309
- if (orphanedStreamId) this._persistOrphanedStream(orphanedStreamId);
323
+ if (orphanedStreamId) await this._persistOrphanedStream(orphanedStreamId);
310
324
  } else if (this._resumableStream.hasActiveStream()) {} else if (!this._resumableStream.replayCompletedChunksByRequestId(connection, data.id)) sendIfOpen(connection, JSON.stringify({
311
325
  body: "",
312
326
  done: true,
@@ -327,11 +341,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
327
341
  toolCallId,
328
342
  toolName
329
343
  });
330
- const applyPromise = this._applyToolResult(toolCallId, toolName, output, overrideState, errorText);
331
- this._pendingInteractionPromise = applyPromise;
332
- applyPromise.finally(() => {
333
- if (this._pendingInteractionPromise === applyPromise) this._pendingInteractionPromise = null;
334
- }).catch(() => {});
344
+ const applyPromise = this._enqueueInteractionApply(() => this._applyToolResult(toolCallId, toolName, output, overrideState, errorText));
335
345
  if (autoContinue) this._enqueueAutoContinuation(connection, clientTools ?? this._lastClientTools, this._lastBody, "[AIChatAgent] Tool continuation failed:", applyPromise);
336
346
  return;
337
347
  }
@@ -341,11 +351,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
341
351
  toolCallId,
342
352
  approved
343
353
  });
344
- const approvalPromise = this._applyToolApproval(toolCallId, approved);
345
- this._pendingInteractionPromise = approvalPromise;
346
- approvalPromise.finally(() => {
347
- if (this._pendingInteractionPromise === approvalPromise) this._pendingInteractionPromise = null;
348
- }).catch(() => {});
354
+ const approvalPromise = this._enqueueInteractionApply(() => this._applyToolApproval(toolCallId, approved));
349
355
  if (autoContinue) this._enqueueAutoContinuation(connection, this._lastClientTools, this._lastBody, "[AIChatAgent] Tool approval continuation failed:", approvalPromise);
350
356
  return;
351
357
  }
@@ -460,9 +466,25 @@ var AIChatAgent = class AIChatAgent extends Agent {
460
466
  this._continuation.activeConnectionId = null;
461
467
  }
462
468
  }
463
- /** @internal Delegate to _resumableStream */
464
- _storeStreamChunk(streamId, body) {
469
+ /** @internal Delegate to _resumableStream. Also advances the recovery
470
+ * progress counter at production time (see `_maybeBumpRecoveryProgress`). */
471
+ async _storeStreamChunk(streamId, body) {
465
472
  this._resumableStream.storeChunk(streamId, body);
473
+ let type;
474
+ try {
475
+ type = JSON.parse(body).type;
476
+ } catch {}
477
+ await this._maybeBumpRecoveryProgress(type);
478
+ }
479
+ /** Advance the recovery-progress counter when a chunk represents genuinely
480
+ * new produced content — a started text/reasoning segment or a settled tool
481
+ * input/output. Bumped at production time (the streaming path), so it
482
+ * reflects real forward progress and is immune to client reconnects /
483
+ * recovery re-persists (which replay or re-materialize stored chunks rather
484
+ * than flow through here). This is what the recovery no-progress window keys
485
+ * off (#1637), and stays compaction-proof (#1628). */
486
+ async _maybeBumpRecoveryProgress(type) {
487
+ if (type === "text-start" || type === "reasoning-start" || type === "tool-input-available" || type === "tool-output-available" || type === "tool-output-error" || type === "tool-output-denied") await this._bumpChatRecoveryProgress();
466
488
  }
467
489
  /** @internal Delegate to _resumableStream */
468
490
  _flushChunkBuffer() {
@@ -491,7 +513,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
491
513
  * message parts, then persists the result so it survives further refreshes.
492
514
  * @internal
493
515
  */
494
- _persistOrphanedStream(streamId) {
516
+ async _persistOrphanedStream(streamId) {
495
517
  const chunks = this._resumableStream.getStreamChunks(streamId);
496
518
  if (!chunks.length) return;
497
519
  const fallbackId = `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
@@ -526,7 +548,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
526
548
  } : existing.metadata;
527
549
  }
528
550
  const updatedMessages = existingIdx >= 0 ? this.messages.map((m, i) => i === existingIdx ? message : m) : [...this.messages, message];
529
- this.persistMessages(updatedMessages);
551
+ await this.persistMessages(updatedMessages);
530
552
  }
531
553
  }
532
554
  /**
@@ -572,9 +594,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
572
594
  * @param event - The text event payload (text-start, text-delta with delta, or text-end)
573
595
  * @param continuation - Whether this is a continuation of a previous stream
574
596
  */
575
- _broadcastTextEvent(streamId, event, continuation) {
597
+ async _broadcastTextEvent(streamId, event, continuation) {
576
598
  const body = JSON.stringify(event);
577
- this._storeStreamChunk(streamId, body);
599
+ await this._storeStreamChunk(streamId, body);
578
600
  this._broadcastChatMessage({
579
601
  body,
580
602
  done: false,
@@ -779,6 +801,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
779
801
  this._abortRegistry.destroyAll();
780
802
  this._submitConcurrency.reset();
781
803
  this._pendingInteractionPromise = null;
804
+ this._interactionApplyTail = Promise.resolve();
782
805
  this._continuation.sendResumeNone();
783
806
  this._continuation.clearAll();
784
807
  this._pendingChatResponseResults.length = 0;
@@ -896,11 +919,70 @@ var AIChatAgent = class AIChatAgent extends Agent {
896
919
  async _awaitPendingAutoContinuationPrerequisite() {
897
920
  while (true) {
898
921
  const prerequisite = this._continuation.pending?.prerequisite;
899
- if (!prerequisite) return true;
922
+ if (!prerequisite) break;
900
923
  if (!await prerequisite) return false;
901
924
  await new Promise((resolve) => setTimeout(resolve, AIChatAgent.AUTO_CONTINUATION_COALESCE_MS));
902
- if (this._continuation.pending?.prerequisite === prerequisite) return true;
925
+ if (this._continuation.pending?.prerequisite === prerequisite) break;
926
+ }
927
+ await this._awaitPendingInteractionBarrier();
928
+ return true;
929
+ }
930
+ /**
931
+ * Block until the latest assistant step's parallel tool batch is fully
932
+ * answered, or `AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS` elapses. Awaits the
933
+ * in-flight tool-result apply when one exists (so a sibling that lands
934
+ * mid-wait is observed promptly) and polls otherwise. Runs inside the
935
+ * continuation turn, so — unlike `waitUntilStable` — it must not wait on the
936
+ * turn queue (that would deadlock).
937
+ *
938
+ * No concurrent-entry guard is needed (unlike Think's `_continuationBarrier
939
+ * Active`): this runs inside the exclusive continuation turn, and a sibling
940
+ * result arriving while it waits hits the merge branch of
941
+ * `_enqueueAutoContinuation` (it updates `pending.prerequisite`) rather than
942
+ * enqueuing a second turn — so the turn queue serializes barrier waits.
943
+ */
944
+ async _awaitPendingInteractionBarrier() {
945
+ const deadline = Date.now() + AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS;
946
+ while (Date.now() < deadline) {
947
+ if (!this._continuation.pending) return;
948
+ const pending = this._pendingInteractionPromise;
949
+ if (pending) {
950
+ try {
951
+ await pending;
952
+ } catch {}
953
+ continue;
954
+ }
955
+ if (!this._hasIncompleteToolBatch()) return;
956
+ await new Promise((resolve) => setTimeout(resolve, 100));
957
+ }
958
+ console.warn(`[AIChatAgent] Auto-continuation proceeding after waiting ${AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS}ms for unanswered parallel tool result(s) (#1649).`);
959
+ }
960
+ /**
961
+ * `true` when the latest assistant message is mid-batch: it carries at least
962
+ * one settled tool result AND at least one tool call/approval still awaiting a
963
+ * client result. That is the #1649 signature — the model fanned out parallel
964
+ * tool calls and only some have been answered. Scoped to the leaf (the step
965
+ * the continuation answers) so an unrelated dangling tool in an earlier
966
+ * message doesn't block a legitimate follow-up continuation.
967
+ */
968
+ _hasIncompleteToolBatch() {
969
+ const messages = this.messages;
970
+ let leaf;
971
+ for (let i = messages.length - 1; i >= 0; i--) if (messages[i].role === "assistant") {
972
+ leaf = messages[i];
973
+ break;
974
+ }
975
+ if (!leaf) return false;
976
+ let hasPending = false;
977
+ let hasSettled = false;
978
+ for (const part of leaf.parts) {
979
+ const record = part;
980
+ const state = record.state;
981
+ if (state === "input-available" || state === "approval-requested") hasPending = true;
982
+ else if (typeof record.type === "string" && (record.type.startsWith("tool-") || record.type === "dynamic-tool") && (state === "output-available" || state === "output-error" || state === "output-denied" || state === "approval-responded")) hasSettled = true;
983
+ if (hasPending && hasSettled) return true;
903
984
  }
985
+ return false;
904
986
  }
905
987
  _queueAutoContinuation(requestId) {
906
988
  const epoch = this._turnQueue.generation;
@@ -1238,10 +1320,65 @@ var AIChatAgent = class AIChatAgent extends Agent {
1238
1320
  `;
1239
1321
  this._closeAgentToolTailers(runId);
1240
1322
  }
1241
- async inspectAgentToolRun(runId) {
1242
- const row = this._getAgentToolRunRow(runId);
1243
- if (!row) return null;
1244
- if (row.status === "running" && !this._agentToolAbortControllers.has(runId)) {
1323
+ /**
1324
+ * Classify any in-flight chat-recovery on this child facet (#1630 / N6). A
1325
+ * child facet is dedicated to a single agent-tool run, so any recovery
1326
+ * incident is that run's. Incidents in `detected`/`scheduled`/`attempting`
1327
+ * mean recovery is still resolving the interrupted turn; `exhausted`/`failed`
1328
+ * mean recovery gave up; a completed recovery deletes its incident.
1329
+ */
1330
+ async _classifyAgentToolChildRecovery() {
1331
+ const entries = await this.ctx.storage.list({ prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX });
1332
+ let failed = false;
1333
+ for (const incident of entries.values()) {
1334
+ if (incident.status === "detected" || incident.status === "scheduled" || incident.status === "attempting") return "in-progress";
1335
+ if (incident.status === "exhausted" || incident.status === "failed") failed = true;
1336
+ }
1337
+ return failed ? "failed" : "none";
1338
+ }
1339
+ /**
1340
+ * Reconcile a stale (post-eviction) child run row from the child's own
1341
+ * durable recovery (#1630). The child facet self-heals its interrupted turn
1342
+ * via `chatRecovery`, but that path never writes the run row, so without this
1343
+ * the row strands `running` and the parent can only collect `interrupted`.
1344
+ *
1345
+ * Persisting the terminal here (rather than only computing it) is intentional:
1346
+ * it's a lazy materialization of the run's true terminal that also lets a
1347
+ * tailing parent's stream close promptly and makes subsequent inspects cheap.
1348
+ * While recovery is still resolving (active stream or in-progress incident)
1349
+ * the row is left `running` so the parent's bounded re-attach keeps waiting.
1350
+ * Mutates `row` in place when it settles so the caller can report it.
1351
+ */
1352
+ async _reconcileStaleAgentToolChildRun(runId, row) {
1353
+ const recovery = await this._classifyAgentToolChildRecovery();
1354
+ if (recovery === "in-progress" || this._resumableStream.hasActiveStream()) return;
1355
+ const messagesAfterStart = this._getAgentToolMessagesAfterStart(runId);
1356
+ if (recovery !== "failed" && messagesAfterStart.some((message) => message.role === "assistant")) {
1357
+ const input = AIChatAgent._parseAgentToolValue(row.input_json);
1358
+ const output = this.getAgentToolOutput({
1359
+ runId,
1360
+ input
1361
+ }, messagesAfterStart);
1362
+ const summary = this.getAgentToolSummary({
1363
+ runId,
1364
+ input
1365
+ }, output, messagesAfterStart);
1366
+ const completedAt = Date.now();
1367
+ this.sql`
1368
+ update cf_ai_chat_agent_tool_runs
1369
+ set status = 'completed',
1370
+ output_json = ${AIChatAgent._stringifyAgentToolValue(output)},
1371
+ summary = ${summary}, error_message = null,
1372
+ completed_at = ${completedAt}
1373
+ where run_id = ${runId} and status = 'running'
1374
+ `;
1375
+ row.status = "completed";
1376
+ row.output_json = AIChatAgent._stringifyAgentToolValue(output);
1377
+ row.summary = summary;
1378
+ row.error_message = null;
1379
+ row.completed_at = completedAt;
1380
+ this._closeAgentToolTailers(runId);
1381
+ } else {
1245
1382
  const error = "Agent tool run was interrupted before the child could finish.";
1246
1383
  this.sql`
1247
1384
  update cf_ai_chat_agent_tool_runs
@@ -1251,7 +1388,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
1251
1388
  row.status = "error";
1252
1389
  row.error_message = error;
1253
1390
  row.completed_at = Date.now();
1391
+ this._closeAgentToolTailers(runId);
1254
1392
  }
1393
+ }
1394
+ async inspectAgentToolRun(runId) {
1395
+ const row = this._getAgentToolRunRow(runId);
1396
+ if (!row) return null;
1397
+ if (row.status === "running" && !this._agentToolAbortControllers.has(runId)) await this._reconcileStaleAgentToolChildRun(runId, row);
1255
1398
  const streamId = row.request_id ? this._getAgentToolStreamId(row.request_id) : void 0;
1256
1399
  const messagesAfterStart = this._getAgentToolMessagesAfterStart(runId);
1257
1400
  const input = AIChatAgent._parseAgentToolValue(row.input_json);
@@ -1304,7 +1447,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
1304
1447
  }
1305
1448
  const forwarders = this._agentToolForwarders.get(runId) ?? /* @__PURE__ */ new Set();
1306
1449
  const forward = (chunk) => {
1307
- if (!closed) controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
1450
+ if (closed) return;
1451
+ try {
1452
+ controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
1453
+ } catch {
1454
+ close();
1455
+ }
1308
1456
  };
1309
1457
  forwarders.add(forward);
1310
1458
  this._agentToolForwarders.set(runId, forwarders);
@@ -1546,6 +1694,218 @@ var AIChatAgent = class AIChatAgent extends Agent {
1546
1694
  * `onFiberRecovered` hook. Maps to `onChatRecovery`.
1547
1695
  * @internal
1548
1696
  */
1697
+ _resolveChatRecoveryConfig() {
1698
+ const raw = this.chatRecovery;
1699
+ const custom = typeof raw === "object" ? raw : void 0;
1700
+ return {
1701
+ enabled: raw !== false,
1702
+ maxAttempts: Math.max(1, Math.floor(custom?.maxAttempts ?? DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS)),
1703
+ stableTimeoutMs: Math.max(0, Math.floor(custom?.stableTimeoutMs ?? DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS)),
1704
+ terminalMessage: custom?.terminalMessage ?? DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE,
1705
+ ...custom?.onExhausted ? { onExhausted: custom.onExhausted } : {}
1706
+ };
1707
+ }
1708
+ _chatRecoveryIncidentId(input) {
1709
+ return [input.recoveryRootRequestId ?? input.requestId, input.latestUserMessageId ?? ""].join(":");
1710
+ }
1711
+ _chatRecoveryIncidentKey(incidentId) {
1712
+ return `${CHAT_RECOVERY_INCIDENT_KEY_PREFIX}${encodeURIComponent(incidentId)}`;
1713
+ }
1714
+ /**
1715
+ * Monotonic forward-progress signal for recovery budget resets.
1716
+ *
1717
+ * This used to count assistant messages in `this.messages`, but that is
1718
+ * recomputed from the live, mutable transcript. Compaction collapses older
1719
+ * assistant messages into a summary, lowering the count — so a turn that had
1720
+ * genuinely advanced could read as "no progress" between attempts and exhaust
1721
+ * its budget prematurely (#1628). Instead we read a durably-persisted counter
1722
+ * that only ever increments — bumped at production time when new content is
1723
+ * streamed (see `_storeStreamChunk` / `_maybeBumpRecoveryProgress`), which is
1724
+ * genuine forward progress and is immune to client reconnects / recovery
1725
+ * re-persists — so compaction can never lower it and a reconnect can't fake
1726
+ * it (#1637).
1727
+ */
1728
+ async _chatRecoveryProgressMarker() {
1729
+ return await this.ctx.storage.get(CHAT_RECOVERY_PROGRESS_KEY) ?? 0;
1730
+ }
1731
+ /** Advance the durable recovery-progress counter. Called from
1732
+ * `_maybeBumpRecoveryProgress` when new content is streamed (real,
1733
+ * reconnect-immune forward progress). */
1734
+ async _bumpChatRecoveryProgress() {
1735
+ const current = await this.ctx.storage.get(CHAT_RECOVERY_PROGRESS_KEY) ?? 0;
1736
+ await this.ctx.storage.put(CHAT_RECOVERY_PROGRESS_KEY, current + 1);
1737
+ }
1738
+ /**
1739
+ * N9: forwarding a sub-agent's chunks IS forward progress for this parent
1740
+ * turn, so credit the parent's recovery progress marker — otherwise a parent
1741
+ * whose turn merely `await`s a child banks no progress of its own and its
1742
+ * no-progress window exhausts while the child is healthily streaming. Only
1743
+ * invoked after a child actually produced output (see
1744
+ * `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.
1745
+ * Throttled (and reset per isolate) so we never write storage per token.
1746
+ */
1747
+ async _onAgentToolStreamProgress() {
1748
+ const now = Date.now();
1749
+ if (now - this._lastAgentToolStreamProgressAt < AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS) return;
1750
+ this._lastAgentToolStreamProgressAt = now;
1751
+ await this._bumpChatRecoveryProgress();
1752
+ }
1753
+ /** Whether a reconstructed partial carries any settled (provider-accepted)
1754
+ * tool result — the completed, often non-idempotent work that a
1755
+ * `{ persist: false }` recovery return would silently discard.
1756
+ * `convertToModelMessages` treats `output-available` / `output-error` /
1757
+ * `output-denied` (or a part carrying `output`/`result`) as settled. */
1758
+ _partialHasSettledToolResults(parts) {
1759
+ return parts.some((part) => {
1760
+ const record = part;
1761
+ const type = typeof record.type === "string" ? record.type : "";
1762
+ if (!(type.startsWith("tool-") || type === "dynamic-tool")) return false;
1763
+ if ("output" in record || "result" in record) return true;
1764
+ const state = typeof record.state === "string" ? record.state : "";
1765
+ return state === "output-available" || state === "output-error" || state === "output-denied";
1766
+ });
1767
+ }
1768
+ /** Sweep recovery incidents that have been inactive past the TTL. */
1769
+ async _sweepStaleChatRecoveryIncidents(now) {
1770
+ const entries = await this.ctx.storage.list({ prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX });
1771
+ const staleKeys = [];
1772
+ for (const [key, incident] of entries) if (now - (incident?.lastAttemptAt ?? incident?.firstSeenAt ?? 0) > CHAT_RECOVERY_INCIDENT_TTL_MS) staleKeys.push(key);
1773
+ for (const key of staleKeys) await this.ctx.storage.delete(key);
1774
+ }
1775
+ async _beginChatRecoveryIncident(input) {
1776
+ const config = this._resolveChatRecoveryConfig();
1777
+ const incidentId = this._chatRecoveryIncidentId(input);
1778
+ const key = this._chatRecoveryIncidentKey(incidentId);
1779
+ const now = input.nowMs ?? Date.now();
1780
+ await this._sweepStaleChatRecoveryIncidents(now);
1781
+ const existing = await this.ctx.storage.get(key);
1782
+ const prevProgress = existing?.progress ?? 0;
1783
+ const currentProgress = await this._chatRecoveryProgressMarker();
1784
+ const madeProgress = existing != null && currentProgress > prevProgress;
1785
+ const lastProgressAt = madeProgress ? now : existing?.lastProgressAt ?? existing?.firstSeenAt ?? now;
1786
+ const noProgressExceeded = existing != null && now - lastProgressAt > CHAT_RECOVERY_NO_PROGRESS_WINDOW_MS;
1787
+ const incidentAgeExceeded = existing != null && now - existing.firstSeenAt > CHAT_RECOVERY_MAX_WINDOW_MS;
1788
+ const debounced = existing != null && !madeProgress && now - existing.lastAttemptAt < CHAT_RECOVERY_ALARM_DEBOUNCE_MS;
1789
+ const attempt = madeProgress ? 1 : debounced ? existing?.attempt ?? 1 : (existing?.attempt ?? 0) + 1;
1790
+ const exhausted = noProgressExceeded || incidentAgeExceeded || attempt > config.maxAttempts;
1791
+ const incident = {
1792
+ incidentId,
1793
+ requestId: input.requestId,
1794
+ recoveryRootRequestId: input.recoveryRootRequestId ?? input.requestId,
1795
+ recoveryKind: input.recoveryKind,
1796
+ attempt,
1797
+ maxAttempts: config.maxAttempts,
1798
+ status: exhausted ? "exhausted" : "attempting",
1799
+ firstSeenAt: existing?.firstSeenAt ?? now,
1800
+ lastAttemptAt: now,
1801
+ lastProgressAt,
1802
+ progress: Math.max(prevProgress, currentProgress),
1803
+ ...exhausted ? { reason: incidentAgeExceeded ? "max_recovery_window_exceeded" : noProgressExceeded ? "no_progress_timeout" : "max_attempts_exceeded" } : {}
1804
+ };
1805
+ await this.ctx.storage.put(key, incident);
1806
+ if (!existing) this._emit("chat:recovery:detected", {
1807
+ incidentId,
1808
+ requestId: input.requestId,
1809
+ attempt,
1810
+ maxAttempts: config.maxAttempts,
1811
+ recoveryKind: input.recoveryKind
1812
+ });
1813
+ this._emit("chat:recovery:attempt", {
1814
+ incidentId,
1815
+ requestId: input.requestId,
1816
+ attempt,
1817
+ maxAttempts: config.maxAttempts,
1818
+ recoveryKind: input.recoveryKind
1819
+ });
1820
+ return {
1821
+ incident,
1822
+ config,
1823
+ exhausted
1824
+ };
1825
+ }
1826
+ async _updateChatRecoveryIncident(incidentId, status, reason) {
1827
+ if (!incidentId) return;
1828
+ const key = this._chatRecoveryIncidentKey(incidentId);
1829
+ const incident = await this.ctx.storage.get(key);
1830
+ if (!incident) return;
1831
+ if (status === "completed") await this.ctx.storage.delete(key);
1832
+ else {
1833
+ const updated = {
1834
+ ...incident,
1835
+ status,
1836
+ ...reason ? { reason } : {}
1837
+ };
1838
+ await this.ctx.storage.put(key, updated);
1839
+ }
1840
+ const eventType = status === "completed" ? "chat:recovery:completed" : status === "skipped" ? "chat:recovery:skipped" : status === "failed" ? "chat:recovery:failed" : void 0;
1841
+ if (eventType) this._emit(eventType, {
1842
+ incidentId,
1843
+ requestId: incident.requestId,
1844
+ attempt: incident.attempt,
1845
+ maxAttempts: incident.maxAttempts,
1846
+ recoveryKind: incident.recoveryKind,
1847
+ ...reason ? { reason } : {}
1848
+ });
1849
+ if (status === "scheduled") await this._setChatRecovering(true, incident.recoveryRootRequestId ?? incident.requestId);
1850
+ else if (status === "completed" || status === "skipped" || status === "failed") await this._setChatRecovering(false);
1851
+ }
1852
+ async _exhaustChatRecovery(incident, config, partial, streamId, createdAt) {
1853
+ const ctx = {
1854
+ incidentId: incident.incidentId,
1855
+ requestId: incident.requestId,
1856
+ recoveryRootRequestId: incident.recoveryRootRequestId ?? incident.requestId,
1857
+ attempt: incident.attempt,
1858
+ maxAttempts: incident.maxAttempts,
1859
+ recoveryKind: incident.recoveryKind,
1860
+ streamId,
1861
+ createdAt,
1862
+ partialText: partial.text,
1863
+ partialParts: partial.parts,
1864
+ reason: incident.reason ?? "max_attempts_exceeded",
1865
+ terminalMessage: config.terminalMessage
1866
+ };
1867
+ this._emit("chat:recovery:exhausted", ctx);
1868
+ try {
1869
+ await config.onExhausted?.(ctx);
1870
+ } catch (error) {
1871
+ console.error("[AIChatAgent] chatRecovery onExhausted hook threw", error);
1872
+ }
1873
+ this._broadcastChatMessage({
1874
+ body: config.terminalMessage,
1875
+ done: true,
1876
+ error: true,
1877
+ id: incident.requestId,
1878
+ type: "cf_agent_use_chat_response"
1879
+ });
1880
+ await this._setChatRecovering(false);
1881
+ }
1882
+ /**
1883
+ * Set or clear the live "recovering…" status (#1620). Persists a durable
1884
+ * record (so set/clear stay consistent across the isolates a recovery spans)
1885
+ * and broadcasts a `CF_AGENT_CHAT_RECOVERING` frame on a genuine transition.
1886
+ * NOTE: AIChatAgent does not yet replay this on connect (no idle-connect
1887
+ * hydration; tracked in #1645) — this is the live signal only.
1888
+ */
1889
+ async _setChatRecovering(active, requestId) {
1890
+ const existing = await this.ctx.storage.get(CHAT_RECOVERING_KEY);
1891
+ const activeExisting = existing && Date.now() - (existing.at ?? 0) < CHAT_RECOVERY_MAX_WINDOW_MS;
1892
+ if (active) {
1893
+ if (activeExisting) return;
1894
+ await this.ctx.storage.put(CHAT_RECOVERING_KEY, {
1895
+ ...requestId ? { requestId } : {},
1896
+ at: Date.now()
1897
+ });
1898
+ } else {
1899
+ if (!existing) return;
1900
+ await this.ctx.storage.delete(CHAT_RECOVERING_KEY);
1901
+ requestId = requestId ?? existing.requestId;
1902
+ }
1903
+ this._broadcastChatMessage({
1904
+ type: "cf_agent_chat_recovering",
1905
+ recovering: active,
1906
+ ...requestId ? { id: requestId } : {}
1907
+ });
1908
+ }
1549
1909
  async _handleInternalFiberRecovery(ctx) {
1550
1910
  const chatPrefix = this.constructor.CHAT_FIBER_NAME + ":";
1551
1911
  if (!ctx.name.startsWith(chatPrefix)) return false;
@@ -1565,39 +1925,81 @@ var AIChatAgent = class AIChatAgent extends Agent {
1565
1925
  text: "",
1566
1926
  parts: []
1567
1927
  };
1568
- const options = await this.onChatRecovery({
1569
- streamId: streamId ?? "",
1570
- requestId,
1571
- partialText: partial.text,
1572
- partialParts: partial.parts,
1573
- recoveryData,
1574
- messages: [...this.messages],
1575
- lastBody: recoverySnapshot?.lastBody ?? this._lastBody,
1576
- lastClientTools: recoverySnapshot?.lastClientTools ?? this._lastClientTools,
1577
- createdAt: ctx.createdAt
1578
- }) ?? {};
1579
- const shouldRetryPreStream = this._shouldRetryRecoveredPreStreamTurn(recoverySnapshot, streamId ?? "", partial);
1580
1928
  const streamStillActive = streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId;
1581
- if (options.persist !== false && streamStillActive) this._persistOrphanedStream(streamId);
1582
- if (streamStillActive) this._resumableStream.complete(streamId);
1583
- if (shouldRetryPreStream && options.continue !== false) await this.schedule(0, "_chatRecoveryRetry", {
1584
- targetUserId: recoverySnapshot.latestUserMessageId,
1585
- originalRequestId: requestId,
1586
- lastBody: recoverySnapshot.lastBody ?? null,
1587
- lastClientTools: recoverySnapshot.lastClientTools ?? null
1588
- }, { idempotent: true });
1589
- else if (options.continue !== false) {
1590
- const targetId = this._findLastAssistantMessage()?.id;
1591
- await this.schedule(0, "_chatRecoveryContinue", {
1592
- ...targetId ? { targetAssistantId: targetId } : {},
1593
- originalRequestId: requestId,
1594
- ...recoverySnapshot ? {
1929
+ const shouldRetryPreStream = this._shouldRetryRecoveredPreStreamTurn(recoverySnapshot, streamId ?? "", partial);
1930
+ const recoveryKind = shouldRetryPreStream ? "retry" : "continue";
1931
+ const recoveryRootRequestId = recoverySnapshot?.recoveryRootRequestId ?? requestId;
1932
+ const { incident, config, exhausted } = await this._beginChatRecoveryIncident({
1933
+ requestId,
1934
+ recoveryRootRequestId,
1935
+ latestUserMessageId: recoverySnapshot?.latestUserMessageId,
1936
+ recoveryKind
1937
+ });
1938
+ if (exhausted) {
1939
+ if (streamStillActive) await this._persistOrphanedStream(streamId);
1940
+ await this._exhaustChatRecovery(incident, config, partial, streamId, ctx.createdAt);
1941
+ return true;
1942
+ }
1943
+ try {
1944
+ const options = await this.onChatRecovery({
1945
+ incidentId: incident.incidentId,
1946
+ recoveryRootRequestId,
1947
+ attempt: incident.attempt,
1948
+ maxAttempts: incident.maxAttempts,
1949
+ recoveryKind,
1950
+ streamId: streamId ?? "",
1951
+ requestId,
1952
+ partialText: partial.text,
1953
+ partialParts: partial.parts,
1954
+ recoveryData,
1955
+ messages: [...this.messages],
1956
+ lastBody: recoverySnapshot?.lastBody ?? this._lastBody,
1957
+ lastClientTools: recoverySnapshot?.lastClientTools ?? this._lastClientTools,
1958
+ createdAt: ctx.createdAt
1959
+ }) ?? {};
1960
+ if (streamStillActive && (options.persist !== false || this._partialHasSettledToolResults(partial.parts))) await this._persistOrphanedStream(streamId);
1961
+ if (streamStillActive) this._resumableStream.complete(streamId);
1962
+ const targetId = shouldRetryPreStream ? void 0 : this._findLastAssistantMessage()?.id;
1963
+ if (shouldRetryPreStream && options.continue !== false) {
1964
+ await this._updateChatRecoveryIncident(incident.incidentId, "scheduled");
1965
+ this._emit("chat:recovery:scheduled", {
1966
+ incidentId: incident.incidentId,
1967
+ requestId,
1968
+ attempt: incident.attempt,
1969
+ maxAttempts: incident.maxAttempts,
1970
+ recoveryKind
1971
+ });
1972
+ await this.schedule(0, "_chatRecoveryRetry", {
1973
+ targetUserId: recoverySnapshot.latestUserMessageId,
1974
+ originalRequestId: recoveryRootRequestId,
1975
+ incidentId: incident.incidentId,
1595
1976
  lastBody: recoverySnapshot.lastBody ?? null,
1596
1977
  lastClientTools: recoverySnapshot.lastClientTools ?? null
1597
- } : {}
1598
- }, { idempotent: true });
1978
+ }, { idempotent: true });
1979
+ } else if (options.continue !== false) {
1980
+ await this._updateChatRecoveryIncident(incident.incidentId, "scheduled");
1981
+ this._emit("chat:recovery:scheduled", {
1982
+ incidentId: incident.incidentId,
1983
+ requestId,
1984
+ attempt: incident.attempt,
1985
+ maxAttempts: incident.maxAttempts,
1986
+ recoveryKind
1987
+ });
1988
+ await this.schedule(0, "_chatRecoveryContinue", {
1989
+ ...targetId ? { targetAssistantId: targetId } : {},
1990
+ originalRequestId: recoveryRootRequestId,
1991
+ incidentId: incident.incidentId,
1992
+ ...recoverySnapshot ? {
1993
+ lastBody: recoverySnapshot.lastBody ?? null,
1994
+ lastClientTools: recoverySnapshot.lastClientTools ?? null
1995
+ } : {}
1996
+ }, { idempotent: true });
1997
+ } else await this._updateChatRecoveryIncident(incident.incidentId, "skipped", "continue_disabled");
1998
+ return true;
1999
+ } catch (error) {
2000
+ await this._updateChatRecoveryIncident(incident.incidentId, "failed", error instanceof Error ? error.message : String(error));
2001
+ throw error;
1599
2002
  }
1600
- return true;
1601
2003
  }
1602
2004
  /**
1603
2005
  * Called when an interrupted chat stream is detected after restart.
@@ -1617,14 +2019,27 @@ var AIChatAgent = class AIChatAgent extends Agent {
1617
2019
  return {};
1618
2020
  }
1619
2021
  async _chatRecoveryContinue(data) {
1620
- if (!await this.waitUntilStable({ timeout: 1e4 })) {
1621
- console.warn("[AIChatAgent] _chatRecoveryContinue timed out waiting for stable state, skipping continuation");
1622
- return;
2022
+ const previousRootRequestId = this._activeChatRecoveryRootRequestId;
2023
+ this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
2024
+ try {
2025
+ const recoveryConfig = this._resolveChatRecoveryConfig();
2026
+ if (!await this.waitUntilStable({ timeout: recoveryConfig.stableTimeoutMs })) {
2027
+ console.warn("[AIChatAgent] _chatRecoveryContinue timed out waiting for stable state");
2028
+ if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryContinue", data, recoveryConfig.maxAttempts)) return;
2029
+ await this._exhaustRecoveryAfterStableTimeout("_chatRecoveryContinue", data);
2030
+ return;
2031
+ }
2032
+ const targetId = data?.targetAssistantId;
2033
+ if (targetId && this._findLastAssistantMessage()?.id !== targetId) {
2034
+ await this._updateChatRecoveryIncident(data?.incidentId, "skipped", "conversation_changed");
2035
+ return;
2036
+ }
2037
+ this._applyRecoveredRequestContext(data);
2038
+ const result = await this.continueLastTurn();
2039
+ await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
2040
+ } finally {
2041
+ this._activeChatRecoveryRootRequestId = previousRootRequestId;
1623
2042
  }
1624
- const targetId = data?.targetAssistantId;
1625
- if (targetId && this._findLastAssistantMessage()?.id !== targetId) return;
1626
- this._applyRecoveredRequestContext(data);
1627
- await this.continueLastTurn();
1628
2043
  }
1629
2044
  _applyRecoveredRequestContext(data) {
1630
2045
  if (!data) return;
@@ -1632,21 +2047,130 @@ var AIChatAgent = class AIChatAgent extends Agent {
1632
2047
  if ("lastBody" in data) this._lastBody = data.lastBody ?? void 0;
1633
2048
  if ("lastClientTools" in data || "lastBody" in data) this._persistRequestContext();
1634
2049
  }
2050
+ /**
2051
+ * Reschedule a recovery callback that timed out waiting for stable state,
2052
+ * consuming one attempt. Returns `true` if rescheduled, `false` if the
2053
+ * attempt budget is exhausted (caller should then fail terminally).
2054
+ */
2055
+ async _rescheduleRecoveryAfterStableTimeout(callback, data, maxAttempts) {
2056
+ const incidentKey = data?.incidentId ? this._chatRecoveryIncidentKey(data.incidentId) : null;
2057
+ const incident = incidentKey ? await this.ctx.storage.get(incidentKey) : null;
2058
+ if (!incident || !incidentKey) return false;
2059
+ const attempt = incident.attempt ?? 0;
2060
+ if (attempt >= (incident.maxAttempts ?? maxAttempts)) return false;
2061
+ await this.ctx.storage.put(incidentKey, {
2062
+ ...incident,
2063
+ attempt: attempt + 1,
2064
+ status: "scheduled",
2065
+ lastAttemptAt: Date.now(),
2066
+ reason: "stable_timeout_retry"
2067
+ });
2068
+ await this.schedule(CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS, callback, data ?? {}, { idempotent: false });
2069
+ return true;
2070
+ }
2071
+ /**
2072
+ * Resolve the stream id for a recovery turn so the give-up terminalization
2073
+ * can surface whatever partial the turn produced. Prefers the durable stream
2074
+ * row keyed by the recovery-root request id; falls back to the live active
2075
+ * stream. Returns `""` when neither is available.
2076
+ */
2077
+ _resolveRecoveryStreamId(requestId) {
2078
+ if (requestId) {
2079
+ const fromMetadata = this._resumableStream.getAllStreamMetadata().find((metadata) => metadata.request_id === requestId)?.id;
2080
+ if (fromMetadata) return fromMetadata;
2081
+ }
2082
+ return this._resumableStream.hasActiveStream() ? this._resumableStream.activeStreamId ?? "" : "";
2083
+ }
2084
+ /**
2085
+ * Terminalize a recovery turn that has run out of stable-state-timeout retry
2086
+ * budget — or whose incident record has vanished — by routing through the
2087
+ * SAME `_exhaustChatRecovery` path as deploy-recovery exhaustion. It fires
2088
+ * `onExhausted`, emits `chat:recovery:exhausted`, and delivers the configured
2089
+ * `terminalMessage`.
2090
+ *
2091
+ * This replaces the older give-up that only set the incident to `failed`,
2092
+ * which bypassed `_exhaustChatRecovery` entirely — so an app relying on
2093
+ * `onExhausted` for the terminal banner regressed to an eternal spinner when
2094
+ * recovery gave up under extreme churn. Shared by `_chatRecoveryRetry` and
2095
+ * `_chatRecoveryContinue`; mirrors the same helper in `@cloudflare/think`.
2096
+ *
2097
+ * Exactly-once terminalization here rests SOLELY on the
2098
+ * `stored?.status === "exhausted"` re-entry guard below — unlike
2099
+ * `@cloudflare/think`, `@cloudflare/ai-chat` has no durable-submission layer
2100
+ * to short-circuit a duplicate alarm earlier. The sealed incident is
2101
+ * re-persisted even when the record was found missing, so a swept record is
2102
+ * re-armed for the guard on the next alarm.
2103
+ *
2104
+ * Two residual at-least-once edges, both deliberately accepted as "deliver a
2105
+ * second banner" ≫ "silently drop the turn":
2106
+ * • No `incidentId` at all in the payload (only reachable via a direct/test
2107
+ * invocation — every production scheduler carries one): the synthesized
2108
+ * incident can't be persisted (no key), so the guard can't arm.
2109
+ * • The record is swept AGAIN between two alarms (the guard re-persists on
2110
+ * the first, so this needs a second independent sweep) — vanishingly
2111
+ * unlikely.
2112
+ */
2113
+ async _exhaustRecoveryAfterStableTimeout(callback, data) {
2114
+ const config = this._resolveChatRecoveryConfig();
2115
+ const incidentKey = data?.incidentId ? this._chatRecoveryIncidentKey(data.incidentId) : null;
2116
+ const stored = incidentKey ? await this.ctx.storage.get(incidentKey) : null;
2117
+ if (stored?.status === "exhausted") return;
2118
+ const rootRequestId = data?.originalRequestId ?? this._activeChatRecoveryRootRequestId ?? stored?.recoveryRootRequestId ?? stored?.requestId ?? "";
2119
+ const incident = stored ? {
2120
+ ...stored,
2121
+ status: "exhausted",
2122
+ reason: "stable_timeout"
2123
+ } : {
2124
+ incidentId: data?.incidentId ?? crypto.randomUUID(),
2125
+ requestId: rootRequestId,
2126
+ recoveryRootRequestId: rootRequestId,
2127
+ recoveryKind: callback === "_chatRecoveryRetry" ? "retry" : "continue",
2128
+ attempt: config.maxAttempts,
2129
+ maxAttempts: config.maxAttempts,
2130
+ status: "exhausted",
2131
+ firstSeenAt: Date.now(),
2132
+ lastAttemptAt: Date.now(),
2133
+ reason: "stable_timeout"
2134
+ };
2135
+ if (incidentKey) await this.ctx.storage.put(incidentKey, incident);
2136
+ const streamId = this._resolveRecoveryStreamId(incident.recoveryRootRequestId ?? incident.requestId);
2137
+ const partial = streamId ? this._getPartialStreamText(streamId) : {
2138
+ text: "",
2139
+ parts: []
2140
+ };
2141
+ await this._exhaustChatRecovery(incident, config, partial, streamId, incident.firstSeenAt);
2142
+ }
1635
2143
  _shouldRetryRecoveredPreStreamTurn(snapshot, streamId, partial) {
1636
2144
  if (!snapshot || snapshot.continuation || !snapshot.latestUserMessageId || streamId || partial.text || partial.parts.length > 0) return false;
1637
2145
  const lastMessage = this.messages.length > 0 ? this.messages[this.messages.length - 1] : null;
1638
2146
  return lastMessage?.role === "user" && lastMessage.id === snapshot.latestUserMessageId;
1639
2147
  }
1640
2148
  async _chatRecoveryRetry(data) {
1641
- if (!await this.waitUntilStable({ timeout: 1e4 })) {
1642
- console.warn("[AIChatAgent] _chatRecoveryRetry timed out waiting for stable state, skipping retry");
1643
- return;
2149
+ const previousRootRequestId = this._activeChatRecoveryRootRequestId;
2150
+ this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
2151
+ try {
2152
+ const recoveryConfig = this._resolveChatRecoveryConfig();
2153
+ if (!await this.waitUntilStable({ timeout: recoveryConfig.stableTimeoutMs })) {
2154
+ console.warn("[AIChatAgent] _chatRecoveryRetry timed out waiting for stable state");
2155
+ if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryRetry", data, recoveryConfig.maxAttempts)) return;
2156
+ await this._exhaustRecoveryAfterStableTimeout("_chatRecoveryRetry", data);
2157
+ return;
2158
+ }
2159
+ const lastMessage = this.messages.length > 0 ? this.messages[this.messages.length - 1] : null;
2160
+ if (!lastMessage || lastMessage.role !== "user") {
2161
+ await this._updateChatRecoveryIncident(data?.incidentId, "skipped", "no_unanswered_user_message");
2162
+ return;
2163
+ }
2164
+ if (data?.targetUserId && lastMessage.id !== data.targetUserId) {
2165
+ await this._updateChatRecoveryIncident(data?.incidentId, "skipped", "conversation_changed");
2166
+ return;
2167
+ }
2168
+ this._applyRecoveredRequestContext(data);
2169
+ const result = await this._retryLastUserTurn(this._lastClientTools, this._lastBody);
2170
+ await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
2171
+ } finally {
2172
+ this._activeChatRecoveryRootRequestId = previousRootRequestId;
1644
2173
  }
1645
- const lastMessage = this.messages.length > 0 ? this.messages[this.messages.length - 1] : null;
1646
- if (!lastMessage || lastMessage.role !== "user") return;
1647
- if (data?.targetUserId && lastMessage.id !== data.targetUserId) return;
1648
- this._applyRecoveredRequestContext(data);
1649
- await this._retryLastUserTurn(this._lastClientTools, this._lastBody);
1650
2174
  }
1651
2175
  /**
1652
2176
  * Extract partial text and parts from stored stream chunks.
@@ -2039,6 +2563,32 @@ var AIChatAgent = class AIChatAgent extends Agent {
2039
2563
  return false;
2040
2564
  }
2041
2565
  /**
2566
+ * Serialize a client-tool result/approval apply behind any in-flight apply
2567
+ * (#1649, defensive). Each apply is a read-modify-write of the message and
2568
+ * parallel tool results arrive as independent WebSocket messages. Today
2569
+ * `_findAndUpdateToolPart` performs that read-modify-write synchronously (no
2570
+ * await between reading `this.messages` and the SQLite write), so concurrent
2571
+ * applies can't actually interleave — unlike Think, ai-chat does not exhibit
2572
+ * the #1649 clobber. This queue is a guard so the invariant survives if the
2573
+ * apply ever gains an await between read and write (e.g. async storage): each
2574
+ * apply commits atomically in arrival order.
2575
+ *
2576
+ * `_pendingInteractionPromise` is set to the newest link so the barrier's
2577
+ * single-slot wake-up observes the latest apply; because the chain is serial,
2578
+ * awaiting it transitively waits for every predecessor.
2579
+ *
2580
+ * @internal
2581
+ */
2582
+ _enqueueInteractionApply(apply) {
2583
+ const resultPromise = this._interactionApplyTail.then(apply, apply);
2584
+ this._interactionApplyTail = resultPromise.then(() => void 0, () => void 0);
2585
+ this._pendingInteractionPromise = resultPromise;
2586
+ resultPromise.finally(() => {
2587
+ if (this._pendingInteractionPromise === resultPromise) this._pendingInteractionPromise = null;
2588
+ }).catch(() => {});
2589
+ return resultPromise;
2590
+ }
2591
+ /**
2042
2592
  * Applies a tool result to an existing assistant message.
2043
2593
  * This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.
2044
2594
  * The server is the source of truth, so we update the message here and broadcast
@@ -2251,7 +2801,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2251
2801
  };
2252
2802
  }
2253
2803
  const chunkBody = JSON.stringify(eventToSend);
2254
- this._storeStreamChunk(streamId, chunkBody);
2804
+ await this._storeStreamChunk(streamId, chunkBody);
2255
2805
  this._broadcastChatMessage({
2256
2806
  body: chunkBody,
2257
2807
  done: false,
@@ -2285,7 +2835,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2285
2835
  }
2286
2836
  }
2287
2837
  if (textPart) {} else {
2288
- this._broadcastTextEvent(streamId, {
2838
+ await this._broadcastTextEvent(streamId, {
2289
2839
  type: "text-start",
2290
2840
  id
2291
2841
  }, continuation);
@@ -2312,7 +2862,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2312
2862
  if (done) {
2313
2863
  if (abortSignal?.aborted) break;
2314
2864
  textPart.state = "done";
2315
- this._broadcastTextEvent(streamId, {
2865
+ await this._broadcastTextEvent(streamId, {
2316
2866
  type: "text-end",
2317
2867
  id
2318
2868
  }, continuation);
@@ -2330,7 +2880,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2330
2880
  const chunk = decoder.decode(value);
2331
2881
  if (chunk.length > 0) {
2332
2882
  textPart.text += chunk;
2333
- this._broadcastTextEvent(streamId, {
2883
+ await this._broadcastTextEvent(streamId, {
2334
2884
  type: "text-delta",
2335
2885
  id,
2336
2886
  delta: chunk
@@ -2339,7 +2889,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2339
2889
  }
2340
2890
  if (!streamCompleted.value) {
2341
2891
  textPart.state = "done";
2342
- this._broadcastTextEvent(streamId, {
2892
+ await this._broadcastTextEvent(streamId, {
2343
2893
  type: "text-end",
2344
2894
  id
2345
2895
  }, continuation);