@cloudflare/ai-chat 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,22 @@
1
1
  import "./types.js";
2
2
  import { autoTransformMessages } from "./ai-chat-v5-migration.js";
3
3
  import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
4
- import { AbortRegistry, ContinuationState, ROW_MAX_BYTES, ResumableStream, SubmitConcurrencyController, TurnQueue, applyChunkToParts, byteLength, createToolsFromClientSchemas, isReplayChunk, reconcileMessages, resolveToolMergeId, sanitizeMessage } from "agents/chat";
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);
@@ -60,6 +73,21 @@ var AIChatAgent = class AIChatAgent extends Agent {
60
73
  static {
61
74
  this.MESSAGE_DEBOUNCE_MS = 750;
62
75
  }
76
+ async _runChatRecoveryFiber(requestId, continuation, fn) {
77
+ const snapshot = createChatFiberSnapshot({
78
+ kind: "ai-chat-turn",
79
+ requestId,
80
+ recoveryRootRequestId: this._activeChatRecoveryRootRequestId ?? requestId,
81
+ continuation,
82
+ messages: this.messages,
83
+ lastBody: this._lastBody,
84
+ lastClientTools: this._lastClientTools
85
+ });
86
+ return this._runFiberWithStashWrapper(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => fn(), {
87
+ initialSnapshot: wrapChatFiberSnapshot("__cfAIChatFiberSnapshot", snapshot, null),
88
+ wrapStash: (data) => wrapChatFiberSnapshot("__cfAIChatFiberSnapshot", snapshot, data)
89
+ });
90
+ }
63
91
  broadcast(msg, without) {
64
92
  if (this._agentToolForwarders.size > 0 && typeof msg === "string") try {
65
93
  const parsed = JSON.parse(msg);
@@ -108,6 +136,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
108
136
  this.messageConcurrency = "queue";
109
137
  this.waitForMcpConnections = { timeout: 1e4 };
110
138
  this.messages = [];
139
+ this._lastAgentToolStreamProgressAt = 0;
111
140
  this.sql`create table if not exists cf_ai_chat_agent_messages (
112
141
  id text primary key,
113
142
  message text not null,
@@ -132,9 +161,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
132
161
  const _onClose = this.onClose.bind(this);
133
162
  this.onClose = async (connection, code, reason, wasClean) => {
134
163
  this._pendingResumeConnections.delete(connection.id);
135
- this._continuation.awaitingConnections.delete(connection.id);
136
- if (this._continuation.pending?.connectionId === connection.id) this._continuation.pending = null;
137
- if (this._continuation.activeConnectionId === connection.id) this._continuation.activeConnectionId = null;
164
+ this._continuation.releaseConnection(connection.id);
138
165
  return _onClose(connection, code, reason, wasClean);
139
166
  };
140
167
  const _onMessage = this.onMessage.bind(this);
@@ -248,9 +275,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
248
275
  this._abortRegistry.remove(chatMessageId);
249
276
  }
250
277
  };
251
- if (this.chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${chatMessageId}`, async () => {
252
- await chatTurnBody();
253
- });
278
+ if (this.chatRecovery) await this._runChatRecoveryFiber(chatMessageId, false, chatTurnBody);
254
279
  else await chatTurnBody();
255
280
  });
256
281
  });
@@ -286,7 +311,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
286
311
  if (data.type === "cf_agent_stream_resume_request") {
287
312
  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" }));
288
313
  else this._notifyStreamResuming(connection);
289
- else if (this._continuation.pending !== null && this._continuation.pending.connectionId === connection.id) this._continuation.awaitingConnections.set(connection.id, connection);
314
+ else if (this._continuation.pending !== null && (this._continuation.pending.connectionId === null || this._continuation.pending.connectionId === connection.id)) this._continuation.awaitingConnections.set(connection.id, connection);
290
315
  else sendIfOpen(connection, JSON.stringify({ type: "cf_agent_stream_resume_none" }));
291
316
  return;
292
317
  }
@@ -294,7 +319,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
294
319
  this._pendingResumeConnections.delete(connection.id);
295
320
  if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === data.id) {
296
321
  const orphanedStreamId = this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
297
- if (orphanedStreamId) this._persistOrphanedStream(orphanedStreamId);
322
+ if (orphanedStreamId) await this._persistOrphanedStream(orphanedStreamId);
298
323
  } else if (this._resumableStream.hasActiveStream()) {} else if (!this._resumableStream.replayCompletedChunksByRequestId(connection, data.id)) sendIfOpen(connection, JSON.stringify({
299
324
  body: "",
300
325
  done: true,
@@ -448,9 +473,25 @@ var AIChatAgent = class AIChatAgent extends Agent {
448
473
  this._continuation.activeConnectionId = null;
449
474
  }
450
475
  }
451
- /** @internal Delegate to _resumableStream */
452
- _storeStreamChunk(streamId, body) {
476
+ /** @internal Delegate to _resumableStream. Also advances the recovery
477
+ * progress counter at production time (see `_maybeBumpRecoveryProgress`). */
478
+ async _storeStreamChunk(streamId, body) {
453
479
  this._resumableStream.storeChunk(streamId, body);
480
+ let type;
481
+ try {
482
+ type = JSON.parse(body).type;
483
+ } catch {}
484
+ await this._maybeBumpRecoveryProgress(type);
485
+ }
486
+ /** Advance the recovery-progress counter when a chunk represents genuinely
487
+ * new produced content — a started text/reasoning segment or a settled tool
488
+ * input/output. Bumped at production time (the streaming path), so it
489
+ * reflects real forward progress and is immune to client reconnects /
490
+ * recovery re-persists (which replay or re-materialize stored chunks rather
491
+ * than flow through here). This is what the recovery no-progress window keys
492
+ * off (#1637), and stays compaction-proof (#1628). */
493
+ async _maybeBumpRecoveryProgress(type) {
494
+ 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();
454
495
  }
455
496
  /** @internal Delegate to _resumableStream */
456
497
  _flushChunkBuffer() {
@@ -462,8 +503,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
462
503
  }
463
504
  /** @internal Delegate to _resumableStream */
464
505
  _markStreamError(streamId) {
506
+ const erroredRequestId = this._resumableStream.activeRequestId;
465
507
  this._resumableStream.markError(streamId);
466
508
  this._pendingResumeConnections.clear();
509
+ if (erroredRequestId === this._continuation.activeRequestId) {
510
+ this._continuation.activeRequestId = null;
511
+ this._continuation.activeConnectionId = null;
512
+ }
467
513
  }
468
514
  /**
469
515
  * Reconstruct and persist a partial assistant message from an orphaned
@@ -474,7 +520,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
474
520
  * message parts, then persists the result so it survives further refreshes.
475
521
  * @internal
476
522
  */
477
- _persistOrphanedStream(streamId) {
523
+ async _persistOrphanedStream(streamId) {
478
524
  const chunks = this._resumableStream.getStreamChunks(streamId);
479
525
  if (!chunks.length) return;
480
526
  const fallbackId = `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
@@ -509,7 +555,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
509
555
  } : existing.metadata;
510
556
  }
511
557
  const updatedMessages = existingIdx >= 0 ? this.messages.map((m, i) => i === existingIdx ? message : m) : [...this.messages, message];
512
- this.persistMessages(updatedMessages);
558
+ await this.persistMessages(updatedMessages);
513
559
  }
514
560
  }
515
561
  /**
@@ -555,9 +601,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
555
601
  * @param event - The text event payload (text-start, text-delta with delta, or text-end)
556
602
  * @param continuation - Whether this is a continuation of a previous stream
557
603
  */
558
- _broadcastTextEvent(streamId, event, continuation) {
604
+ async _broadcastTextEvent(streamId, event, continuation) {
559
605
  const body = JSON.stringify(event);
560
- this._storeStreamChunk(streamId, body);
606
+ await this._storeStreamChunk(streamId, body);
561
607
  this._broadcastChatMessage({
562
608
  body,
563
609
  done: false,
@@ -879,11 +925,70 @@ var AIChatAgent = class AIChatAgent extends Agent {
879
925
  async _awaitPendingAutoContinuationPrerequisite() {
880
926
  while (true) {
881
927
  const prerequisite = this._continuation.pending?.prerequisite;
882
- if (!prerequisite) return true;
928
+ if (!prerequisite) break;
883
929
  if (!await prerequisite) return false;
884
930
  await new Promise((resolve) => setTimeout(resolve, AIChatAgent.AUTO_CONTINUATION_COALESCE_MS));
885
- if (this._continuation.pending?.prerequisite === prerequisite) return true;
931
+ if (this._continuation.pending?.prerequisite === prerequisite) break;
932
+ }
933
+ await this._awaitPendingInteractionBarrier();
934
+ return true;
935
+ }
936
+ /**
937
+ * Block until the latest assistant step's parallel tool batch is fully
938
+ * answered, or `AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS` elapses. Awaits the
939
+ * in-flight tool-result apply when one exists (so a sibling that lands
940
+ * mid-wait is observed promptly) and polls otherwise. Runs inside the
941
+ * continuation turn, so — unlike `waitUntilStable` — it must not wait on the
942
+ * turn queue (that would deadlock).
943
+ *
944
+ * No concurrent-entry guard is needed (unlike Think's `_continuationBarrier
945
+ * Active`): this runs inside the exclusive continuation turn, and a sibling
946
+ * result arriving while it waits hits the merge branch of
947
+ * `_enqueueAutoContinuation` (it updates `pending.prerequisite`) rather than
948
+ * enqueuing a second turn — so the turn queue serializes barrier waits.
949
+ */
950
+ async _awaitPendingInteractionBarrier() {
951
+ const deadline = Date.now() + AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS;
952
+ while (Date.now() < deadline) {
953
+ if (!this._continuation.pending) return;
954
+ const pending = this._pendingInteractionPromise;
955
+ if (pending) {
956
+ try {
957
+ await pending;
958
+ } catch {}
959
+ continue;
960
+ }
961
+ if (!this._hasIncompleteToolBatch()) return;
962
+ await new Promise((resolve) => setTimeout(resolve, 100));
963
+ }
964
+ console.warn(`[AIChatAgent] Auto-continuation proceeding after waiting ${AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS}ms for unanswered parallel tool result(s) (#1649).`);
965
+ }
966
+ /**
967
+ * `true` when the latest assistant message is mid-batch: it carries at least
968
+ * one settled tool result AND at least one tool call/approval still awaiting a
969
+ * client result. That is the #1649 signature — the model fanned out parallel
970
+ * tool calls and only some have been answered. Scoped to the leaf (the step
971
+ * the continuation answers) so an unrelated dangling tool in an earlier
972
+ * message doesn't block a legitimate follow-up continuation.
973
+ */
974
+ _hasIncompleteToolBatch() {
975
+ const messages = this.messages;
976
+ let leaf;
977
+ for (let i = messages.length - 1; i >= 0; i--) if (messages[i].role === "assistant") {
978
+ leaf = messages[i];
979
+ break;
980
+ }
981
+ if (!leaf) return false;
982
+ let hasPending = false;
983
+ let hasSettled = false;
984
+ for (const part of leaf.parts) {
985
+ const record = part;
986
+ const state = record.state;
987
+ if (state === "input-available" || state === "approval-requested") hasPending = true;
988
+ 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;
989
+ if (hasPending && hasSettled) return true;
886
990
  }
991
+ return false;
887
992
  }
888
993
  _queueAutoContinuation(requestId) {
889
994
  const epoch = this._turnQueue.generation;
@@ -920,10 +1025,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
920
1025
  continuation: true
921
1026
  });
922
1027
  if (response) {
923
- await this._reply(requestId, response, [], {
1028
+ if ((await this._reply(requestId, response, [], {
924
1029
  continuation: true,
925
1030
  chatMessageId: requestId
926
- });
1031
+ })).status === "error") {
1032
+ this._clearAllAutoContinuationState(true);
1033
+ return;
1034
+ }
927
1035
  this._activateDeferredAutoContinuation();
928
1036
  } else {
929
1037
  this._clearPendingAutoContinuation(true);
@@ -933,9 +1041,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
933
1041
  this._abortRegistry.remove(requestId);
934
1042
  }
935
1043
  };
936
- if (this.chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
937
- await autoContinuationBody();
938
- });
1044
+ if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, true, autoContinuationBody);
939
1045
  else await autoContinuationBody();
940
1046
  });
941
1047
  });
@@ -952,14 +1058,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
952
1058
  });
953
1059
  }
954
1060
  /**
955
- * @returns `true` if the registry's controller for `requestId` was
956
- * aborted during the turn (so the caller can surface
957
- * `status: "aborted"` to the public API). Returns `false` for
958
- * successful or errored completion.
1061
+ * @returns Terminal status for the turn.
959
1062
  */
960
1063
  async _runProgrammaticChatTurn(requestId, clientTools, body, externalSignal) {
961
1064
  this._setRequestContext(clientTools, body);
962
1065
  let wasAborted = false;
1066
+ let status = { status: "completed" };
963
1067
  await this._tryCatchChat(async () => {
964
1068
  return __DO_NOT_USE_WILL_BREAK__agentContext.run({
965
1069
  agent: this,
@@ -978,11 +1082,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
978
1082
  body,
979
1083
  continuation: false
980
1084
  });
981
- if (response) await this._reply(requestId, response, [], { chatMessageId: requestId });
1085
+ if (response) status = await this._reply(requestId, response, [], { chatMessageId: requestId });
982
1086
  };
983
- if (this.chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
984
- await programmaticBody();
985
- });
1087
+ if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, false, programmaticBody);
986
1088
  else await programmaticBody();
987
1089
  } finally {
988
1090
  if (abortSignal?.aborted) wasAborted = true;
@@ -991,7 +1093,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
991
1093
  }
992
1094
  });
993
1095
  });
994
- return wasAborted;
1096
+ if (status.status === "completed" && wasAborted) return { status: "aborted" };
1097
+ return status;
995
1098
  }
996
1099
  /**
997
1100
  * Handle incoming chat messages and generate a response
@@ -1151,12 +1254,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
1151
1254
  `;
1152
1255
  return;
1153
1256
  }
1154
- const streamError = this._agentToolLastErrors.get(options.runId);
1155
- if (streamError) {
1257
+ const streamError = result.error ?? this._agentToolLastErrors.get(options.runId);
1258
+ if (result.status === "error" || streamError) {
1259
+ const errorMessage = streamError ?? "Agent tool run failed during streaming.";
1156
1260
  this.sql`
1157
1261
  update cf_ai_chat_agent_tool_runs
1158
1262
  set request_id = ${requestId}, status = 'error',
1159
- error_message = ${streamError}, completed_at = ${Date.now()}
1263
+ error_message = ${errorMessage}, completed_at = ${Date.now()}
1160
1264
  where run_id = ${options.runId}
1161
1265
  `;
1162
1266
  return;
@@ -1222,10 +1326,65 @@ var AIChatAgent = class AIChatAgent extends Agent {
1222
1326
  `;
1223
1327
  this._closeAgentToolTailers(runId);
1224
1328
  }
1225
- async inspectAgentToolRun(runId) {
1226
- const row = this._getAgentToolRunRow(runId);
1227
- if (!row) return null;
1228
- if (row.status === "running" && !this._agentToolAbortControllers.has(runId)) {
1329
+ /**
1330
+ * Classify any in-flight chat-recovery on this child facet (#1630 / N6). A
1331
+ * child facet is dedicated to a single agent-tool run, so any recovery
1332
+ * incident is that run's. Incidents in `detected`/`scheduled`/`attempting`
1333
+ * mean recovery is still resolving the interrupted turn; `exhausted`/`failed`
1334
+ * mean recovery gave up; a completed recovery deletes its incident.
1335
+ */
1336
+ async _classifyAgentToolChildRecovery() {
1337
+ const entries = await this.ctx.storage.list({ prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX });
1338
+ let failed = false;
1339
+ for (const incident of entries.values()) {
1340
+ if (incident.status === "detected" || incident.status === "scheduled" || incident.status === "attempting") return "in-progress";
1341
+ if (incident.status === "exhausted" || incident.status === "failed") failed = true;
1342
+ }
1343
+ return failed ? "failed" : "none";
1344
+ }
1345
+ /**
1346
+ * Reconcile a stale (post-eviction) child run row from the child's own
1347
+ * durable recovery (#1630). The child facet self-heals its interrupted turn
1348
+ * via `chatRecovery`, but that path never writes the run row, so without this
1349
+ * the row strands `running` and the parent can only collect `interrupted`.
1350
+ *
1351
+ * Persisting the terminal here (rather than only computing it) is intentional:
1352
+ * it's a lazy materialization of the run's true terminal that also lets a
1353
+ * tailing parent's stream close promptly and makes subsequent inspects cheap.
1354
+ * While recovery is still resolving (active stream or in-progress incident)
1355
+ * the row is left `running` so the parent's bounded re-attach keeps waiting.
1356
+ * Mutates `row` in place when it settles so the caller can report it.
1357
+ */
1358
+ async _reconcileStaleAgentToolChildRun(runId, row) {
1359
+ const recovery = await this._classifyAgentToolChildRecovery();
1360
+ if (recovery === "in-progress" || this._resumableStream.hasActiveStream()) return;
1361
+ const messagesAfterStart = this._getAgentToolMessagesAfterStart(runId);
1362
+ if (recovery !== "failed" && messagesAfterStart.some((message) => message.role === "assistant")) {
1363
+ const input = AIChatAgent._parseAgentToolValue(row.input_json);
1364
+ const output = this.getAgentToolOutput({
1365
+ runId,
1366
+ input
1367
+ }, messagesAfterStart);
1368
+ const summary = this.getAgentToolSummary({
1369
+ runId,
1370
+ input
1371
+ }, output, messagesAfterStart);
1372
+ const completedAt = Date.now();
1373
+ this.sql`
1374
+ update cf_ai_chat_agent_tool_runs
1375
+ set status = 'completed',
1376
+ output_json = ${AIChatAgent._stringifyAgentToolValue(output)},
1377
+ summary = ${summary}, error_message = null,
1378
+ completed_at = ${completedAt}
1379
+ where run_id = ${runId} and status = 'running'
1380
+ `;
1381
+ row.status = "completed";
1382
+ row.output_json = AIChatAgent._stringifyAgentToolValue(output);
1383
+ row.summary = summary;
1384
+ row.error_message = null;
1385
+ row.completed_at = completedAt;
1386
+ this._closeAgentToolTailers(runId);
1387
+ } else {
1229
1388
  const error = "Agent tool run was interrupted before the child could finish.";
1230
1389
  this.sql`
1231
1390
  update cf_ai_chat_agent_tool_runs
@@ -1235,7 +1394,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
1235
1394
  row.status = "error";
1236
1395
  row.error_message = error;
1237
1396
  row.completed_at = Date.now();
1397
+ this._closeAgentToolTailers(runId);
1238
1398
  }
1399
+ }
1400
+ async inspectAgentToolRun(runId) {
1401
+ const row = this._getAgentToolRunRow(runId);
1402
+ if (!row) return null;
1403
+ if (row.status === "running" && !this._agentToolAbortControllers.has(runId)) await this._reconcileStaleAgentToolChildRun(runId, row);
1239
1404
  const streamId = row.request_id ? this._getAgentToolStreamId(row.request_id) : void 0;
1240
1405
  const messagesAfterStart = this._getAgentToolMessagesAfterStart(runId);
1241
1406
  const input = AIChatAgent._parseAgentToolValue(row.input_json);
@@ -1288,7 +1453,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
1288
1453
  }
1289
1454
  const forwarders = this._agentToolForwarders.get(runId) ?? /* @__PURE__ */ new Set();
1290
1455
  const forward = (chunk) => {
1291
- if (!closed) controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
1456
+ if (closed) return;
1457
+ try {
1458
+ controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
1459
+ } catch {
1460
+ close();
1461
+ }
1292
1462
  };
1293
1463
  forwarders.add(forward);
1294
1464
  this._agentToolForwarders.set(runId, forwarders);
@@ -1384,9 +1554,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
1384
1554
  * loop's signal aborts and the result reports `status: "aborted"`.
1385
1555
  * Pre-aborted signals short-circuit before any model work runs.
1386
1556
  *
1387
- * Returns `{ requestId, status }` where `status` is `"completed"` when
1388
- * the turn ran, `"skipped"` when the chat was cleared, or `"aborted"`
1389
- * when an external signal cancelled it mid-stream.
1557
+ * Returns `{ requestId, status, error? }` where `status` is `"completed"`
1558
+ * when the turn ran, `"error"` when the stream reported an error,
1559
+ * `"skipped"` when the chat was cleared, or `"aborted"` when an external
1560
+ * signal cancelled it mid-stream.
1390
1561
  */
1391
1562
  async saveMessages(messages, options) {
1392
1563
  const requestId = nanoid();
@@ -1394,7 +1565,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1394
1565
  const body = this._lastBody;
1395
1566
  const epoch = this._turnQueue.generation;
1396
1567
  let status = "completed";
1397
- let wasAborted = false;
1568
+ let error;
1398
1569
  await this._runExclusiveChatTurn(requestId, async () => {
1399
1570
  const resolvedMessages = typeof messages === "function" ? await messages(this.messages) : messages;
1400
1571
  if (this._turnQueue.generation !== epoch) {
@@ -1406,13 +1577,15 @@ var AIChatAgent = class AIChatAgent extends Agent {
1406
1577
  status = "skipped";
1407
1578
  return;
1408
1579
  }
1409
- wasAborted = await this._runProgrammaticChatTurn(requestId, clientTools, body, options?.signal);
1580
+ const turnResult = await this._runProgrammaticChatTurn(requestId, clientTools, body, options?.signal);
1581
+ status = turnResult.status;
1582
+ error = turnResult.error;
1410
1583
  }, { epoch });
1411
1584
  if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
1412
- else if (wasAborted && status === "completed") status = "aborted";
1413
1585
  return {
1414
1586
  requestId,
1415
- status
1587
+ status,
1588
+ ...error !== void 0 && { error }
1416
1589
  };
1417
1590
  }
1418
1591
  /**
@@ -1440,6 +1613,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1440
1613
  const resolvedBody = body ?? this._lastBody;
1441
1614
  const epoch = this._turnQueue.generation;
1442
1615
  let status = "completed";
1616
+ let error;
1443
1617
  let wasAborted = false;
1444
1618
  await this._runExclusiveChatTurn(requestId, async () => {
1445
1619
  if (this._turnQueue.generation !== epoch) {
@@ -1465,10 +1639,14 @@ var AIChatAgent = class AIChatAgent extends Agent {
1465
1639
  body: resolvedBody,
1466
1640
  continuation: true
1467
1641
  });
1468
- if (response) await this._reply(requestId, response, [], {
1469
- continuation: true,
1470
- chatMessageId: requestId
1471
- });
1642
+ if (response) {
1643
+ const replyResult = await this._reply(requestId, response, [], {
1644
+ continuation: true,
1645
+ chatMessageId: requestId
1646
+ });
1647
+ status = replyResult.status;
1648
+ error = replyResult.error;
1649
+ }
1472
1650
  } finally {
1473
1651
  if (abortSignal?.aborted) wasAborted = true;
1474
1652
  detachExternal();
@@ -1477,16 +1655,41 @@ var AIChatAgent = class AIChatAgent extends Agent {
1477
1655
  });
1478
1656
  });
1479
1657
  };
1480
- if (this.chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
1481
- await turnBody();
1482
- });
1658
+ if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, true, turnBody);
1483
1659
  else await turnBody();
1484
1660
  }, { epoch });
1485
1661
  if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
1486
1662
  else if (wasAborted && status === "completed") status = "aborted";
1487
1663
  return {
1488
1664
  requestId,
1489
- status
1665
+ status,
1666
+ ...error !== void 0 && { error }
1667
+ };
1668
+ }
1669
+ async _retryLastUserTurn(clientTools, body, options) {
1670
+ const lastMessage = this.messages.length > 0 ? this.messages[this.messages.length - 1] : null;
1671
+ if (!lastMessage || lastMessage.role !== "user") return {
1672
+ requestId: "",
1673
+ status: "skipped"
1674
+ };
1675
+ const requestId = nanoid();
1676
+ const epoch = this._turnQueue.generation;
1677
+ let status = "completed";
1678
+ let error;
1679
+ await this._runExclusiveChatTurn(requestId, async () => {
1680
+ if (this._turnQueue.generation !== epoch) {
1681
+ status = "skipped";
1682
+ return;
1683
+ }
1684
+ const turnResult = await this._runProgrammaticChatTurn(requestId, clientTools, body, options?.signal);
1685
+ status = turnResult.status;
1686
+ error = turnResult.error;
1687
+ }, { epoch });
1688
+ if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
1689
+ return {
1690
+ requestId,
1691
+ status,
1692
+ ...error !== void 0 && { error }
1490
1693
  };
1491
1694
  }
1492
1695
  static {
@@ -1497,10 +1700,223 @@ var AIChatAgent = class AIChatAgent extends Agent {
1497
1700
  * `onFiberRecovered` hook. Maps to `onChatRecovery`.
1498
1701
  * @internal
1499
1702
  */
1703
+ _resolveChatRecoveryConfig() {
1704
+ const raw = this.chatRecovery;
1705
+ const custom = typeof raw === "object" ? raw : void 0;
1706
+ return {
1707
+ enabled: raw !== false,
1708
+ maxAttempts: Math.max(1, Math.floor(custom?.maxAttempts ?? DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS)),
1709
+ stableTimeoutMs: Math.max(0, Math.floor(custom?.stableTimeoutMs ?? DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS)),
1710
+ terminalMessage: custom?.terminalMessage ?? DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE,
1711
+ ...custom?.onExhausted ? { onExhausted: custom.onExhausted } : {}
1712
+ };
1713
+ }
1714
+ _chatRecoveryIncidentId(input) {
1715
+ return [input.recoveryRootRequestId ?? input.requestId, input.latestUserMessageId ?? ""].join(":");
1716
+ }
1717
+ _chatRecoveryIncidentKey(incidentId) {
1718
+ return `${CHAT_RECOVERY_INCIDENT_KEY_PREFIX}${encodeURIComponent(incidentId)}`;
1719
+ }
1720
+ /**
1721
+ * Monotonic forward-progress signal for recovery budget resets.
1722
+ *
1723
+ * This used to count assistant messages in `this.messages`, but that is
1724
+ * recomputed from the live, mutable transcript. Compaction collapses older
1725
+ * assistant messages into a summary, lowering the count — so a turn that had
1726
+ * genuinely advanced could read as "no progress" between attempts and exhaust
1727
+ * its budget prematurely (#1628). Instead we read a durably-persisted counter
1728
+ * that only ever increments — bumped at production time when new content is
1729
+ * streamed (see `_storeStreamChunk` / `_maybeBumpRecoveryProgress`), which is
1730
+ * genuine forward progress and is immune to client reconnects / recovery
1731
+ * re-persists — so compaction can never lower it and a reconnect can't fake
1732
+ * it (#1637).
1733
+ */
1734
+ async _chatRecoveryProgressMarker() {
1735
+ return await this.ctx.storage.get(CHAT_RECOVERY_PROGRESS_KEY) ?? 0;
1736
+ }
1737
+ /** Advance the durable recovery-progress counter. Called from
1738
+ * `_maybeBumpRecoveryProgress` when new content is streamed (real,
1739
+ * reconnect-immune forward progress). */
1740
+ async _bumpChatRecoveryProgress() {
1741
+ const current = await this.ctx.storage.get(CHAT_RECOVERY_PROGRESS_KEY) ?? 0;
1742
+ await this.ctx.storage.put(CHAT_RECOVERY_PROGRESS_KEY, current + 1);
1743
+ }
1744
+ /**
1745
+ * N9: forwarding a sub-agent's chunks IS forward progress for this parent
1746
+ * turn, so credit the parent's recovery progress marker — otherwise a parent
1747
+ * whose turn merely `await`s a child banks no progress of its own and its
1748
+ * no-progress window exhausts while the child is healthily streaming. Only
1749
+ * invoked after a child actually produced output (see
1750
+ * `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.
1751
+ * Throttled (and reset per isolate) so we never write storage per token.
1752
+ */
1753
+ async _onAgentToolStreamProgress() {
1754
+ const now = Date.now();
1755
+ if (now - this._lastAgentToolStreamProgressAt < AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS) return;
1756
+ this._lastAgentToolStreamProgressAt = now;
1757
+ await this._bumpChatRecoveryProgress();
1758
+ }
1759
+ /** Whether a reconstructed partial carries any settled (provider-accepted)
1760
+ * tool result — the completed, often non-idempotent work that a
1761
+ * `{ persist: false }` recovery return would silently discard.
1762
+ * `convertToModelMessages` treats `output-available` / `output-error` /
1763
+ * `output-denied` (or a part carrying `output`/`result`) as settled. */
1764
+ _partialHasSettledToolResults(parts) {
1765
+ return parts.some((part) => {
1766
+ const record = part;
1767
+ const type = typeof record.type === "string" ? record.type : "";
1768
+ if (!(type.startsWith("tool-") || type === "dynamic-tool")) return false;
1769
+ if ("output" in record || "result" in record) return true;
1770
+ const state = typeof record.state === "string" ? record.state : "";
1771
+ return state === "output-available" || state === "output-error" || state === "output-denied";
1772
+ });
1773
+ }
1774
+ /** Sweep recovery incidents that have been inactive past the TTL. */
1775
+ async _sweepStaleChatRecoveryIncidents(now) {
1776
+ const entries = await this.ctx.storage.list({ prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX });
1777
+ const staleKeys = [];
1778
+ for (const [key, incident] of entries) if (now - (incident?.lastAttemptAt ?? incident?.firstSeenAt ?? 0) > CHAT_RECOVERY_INCIDENT_TTL_MS) staleKeys.push(key);
1779
+ for (const key of staleKeys) await this.ctx.storage.delete(key);
1780
+ }
1781
+ async _beginChatRecoveryIncident(input) {
1782
+ const config = this._resolveChatRecoveryConfig();
1783
+ const incidentId = this._chatRecoveryIncidentId(input);
1784
+ const key = this._chatRecoveryIncidentKey(incidentId);
1785
+ const now = input.nowMs ?? Date.now();
1786
+ await this._sweepStaleChatRecoveryIncidents(now);
1787
+ const existing = await this.ctx.storage.get(key);
1788
+ const prevProgress = existing?.progress ?? 0;
1789
+ const currentProgress = await this._chatRecoveryProgressMarker();
1790
+ const madeProgress = existing != null && currentProgress > prevProgress;
1791
+ const lastProgressAt = madeProgress ? now : existing?.lastProgressAt ?? existing?.firstSeenAt ?? now;
1792
+ const noProgressExceeded = existing != null && now - lastProgressAt > CHAT_RECOVERY_NO_PROGRESS_WINDOW_MS;
1793
+ const incidentAgeExceeded = existing != null && now - existing.firstSeenAt > CHAT_RECOVERY_MAX_WINDOW_MS;
1794
+ const debounced = existing != null && !madeProgress && now - existing.lastAttemptAt < CHAT_RECOVERY_ALARM_DEBOUNCE_MS;
1795
+ const attempt = madeProgress ? 1 : debounced ? existing?.attempt ?? 1 : (existing?.attempt ?? 0) + 1;
1796
+ const exhausted = noProgressExceeded || incidentAgeExceeded || attempt > config.maxAttempts;
1797
+ const incident = {
1798
+ incidentId,
1799
+ requestId: input.requestId,
1800
+ recoveryRootRequestId: input.recoveryRootRequestId ?? input.requestId,
1801
+ recoveryKind: input.recoveryKind,
1802
+ attempt,
1803
+ maxAttempts: config.maxAttempts,
1804
+ status: exhausted ? "exhausted" : "attempting",
1805
+ firstSeenAt: existing?.firstSeenAt ?? now,
1806
+ lastAttemptAt: now,
1807
+ lastProgressAt,
1808
+ progress: Math.max(prevProgress, currentProgress),
1809
+ ...exhausted ? { reason: incidentAgeExceeded ? "max_recovery_window_exceeded" : noProgressExceeded ? "no_progress_timeout" : "max_attempts_exceeded" } : {}
1810
+ };
1811
+ await this.ctx.storage.put(key, incident);
1812
+ if (!existing) this._emit("chat:recovery:detected", {
1813
+ incidentId,
1814
+ requestId: input.requestId,
1815
+ attempt,
1816
+ maxAttempts: config.maxAttempts,
1817
+ recoveryKind: input.recoveryKind
1818
+ });
1819
+ this._emit("chat:recovery:attempt", {
1820
+ incidentId,
1821
+ requestId: input.requestId,
1822
+ attempt,
1823
+ maxAttempts: config.maxAttempts,
1824
+ recoveryKind: input.recoveryKind
1825
+ });
1826
+ return {
1827
+ incident,
1828
+ config,
1829
+ exhausted
1830
+ };
1831
+ }
1832
+ async _updateChatRecoveryIncident(incidentId, status, reason) {
1833
+ if (!incidentId) return;
1834
+ const key = this._chatRecoveryIncidentKey(incidentId);
1835
+ const incident = await this.ctx.storage.get(key);
1836
+ if (!incident) return;
1837
+ if (status === "completed") await this.ctx.storage.delete(key);
1838
+ else {
1839
+ const updated = {
1840
+ ...incident,
1841
+ status,
1842
+ ...reason ? { reason } : {}
1843
+ };
1844
+ await this.ctx.storage.put(key, updated);
1845
+ }
1846
+ const eventType = status === "completed" ? "chat:recovery:completed" : status === "skipped" ? "chat:recovery:skipped" : status === "failed" ? "chat:recovery:failed" : void 0;
1847
+ if (eventType) this._emit(eventType, {
1848
+ incidentId,
1849
+ requestId: incident.requestId,
1850
+ attempt: incident.attempt,
1851
+ maxAttempts: incident.maxAttempts,
1852
+ recoveryKind: incident.recoveryKind,
1853
+ ...reason ? { reason } : {}
1854
+ });
1855
+ if (status === "scheduled") await this._setChatRecovering(true, incident.recoveryRootRequestId ?? incident.requestId);
1856
+ else if (status === "completed" || status === "skipped" || status === "failed") await this._setChatRecovering(false);
1857
+ }
1858
+ async _exhaustChatRecovery(incident, config, partial, streamId, createdAt) {
1859
+ const ctx = {
1860
+ incidentId: incident.incidentId,
1861
+ requestId: incident.requestId,
1862
+ recoveryRootRequestId: incident.recoveryRootRequestId ?? incident.requestId,
1863
+ attempt: incident.attempt,
1864
+ maxAttempts: incident.maxAttempts,
1865
+ recoveryKind: incident.recoveryKind,
1866
+ streamId,
1867
+ createdAt,
1868
+ partialText: partial.text,
1869
+ partialParts: partial.parts,
1870
+ reason: incident.reason ?? "max_attempts_exceeded",
1871
+ terminalMessage: config.terminalMessage
1872
+ };
1873
+ this._emit("chat:recovery:exhausted", ctx);
1874
+ try {
1875
+ await config.onExhausted?.(ctx);
1876
+ } catch (error) {
1877
+ console.error("[AIChatAgent] chatRecovery onExhausted hook threw", error);
1878
+ }
1879
+ this._broadcastChatMessage({
1880
+ body: config.terminalMessage,
1881
+ done: true,
1882
+ error: true,
1883
+ id: incident.requestId,
1884
+ type: "cf_agent_use_chat_response"
1885
+ });
1886
+ await this._setChatRecovering(false);
1887
+ }
1888
+ /**
1889
+ * Set or clear the live "recovering…" status (#1620). Persists a durable
1890
+ * record (so set/clear stay consistent across the isolates a recovery spans)
1891
+ * and broadcasts a `CF_AGENT_CHAT_RECOVERING` frame on a genuine transition.
1892
+ * NOTE: AIChatAgent does not yet replay this on connect (no idle-connect
1893
+ * hydration; tracked in #1645) — this is the live signal only.
1894
+ */
1895
+ async _setChatRecovering(active, requestId) {
1896
+ const existing = await this.ctx.storage.get(CHAT_RECOVERING_KEY);
1897
+ const activeExisting = existing && Date.now() - (existing.at ?? 0) < CHAT_RECOVERY_MAX_WINDOW_MS;
1898
+ if (active) {
1899
+ if (activeExisting) return;
1900
+ await this.ctx.storage.put(CHAT_RECOVERING_KEY, {
1901
+ ...requestId ? { requestId } : {},
1902
+ at: Date.now()
1903
+ });
1904
+ } else {
1905
+ if (!existing) return;
1906
+ await this.ctx.storage.delete(CHAT_RECOVERING_KEY);
1907
+ requestId = requestId ?? existing.requestId;
1908
+ }
1909
+ this._broadcastChatMessage({
1910
+ type: "cf_agent_chat_recovering",
1911
+ recovering: active,
1912
+ ...requestId ? { id: requestId } : {}
1913
+ });
1914
+ }
1500
1915
  async _handleInternalFiberRecovery(ctx) {
1501
1916
  const chatPrefix = this.constructor.CHAT_FIBER_NAME + ":";
1502
1917
  if (!ctx.name.startsWith(chatPrefix)) return false;
1503
1918
  const requestId = ctx.name.slice(chatPrefix.length);
1919
+ const { snapshot: recoverySnapshot, user: recoveryData } = unwrapChatFiberSnapshot("__cfAIChatFiberSnapshot", ctx.snapshot, "ai-chat-turn");
1504
1920
  let streamId = "";
1505
1921
  if (requestId) {
1506
1922
  const rows = this.sql`
@@ -1515,25 +1931,81 @@ var AIChatAgent = class AIChatAgent extends Agent {
1515
1931
  text: "",
1516
1932
  parts: []
1517
1933
  };
1518
- const options = await this.onChatRecovery({
1519
- streamId: streamId ?? "",
1934
+ const streamStillActive = streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId;
1935
+ const shouldRetryPreStream = this._shouldRetryRecoveredPreStreamTurn(recoverySnapshot, streamId ?? "", partial);
1936
+ const recoveryKind = shouldRetryPreStream ? "retry" : "continue";
1937
+ const recoveryRootRequestId = recoverySnapshot?.recoveryRootRequestId ?? requestId;
1938
+ const { incident, config, exhausted } = await this._beginChatRecoveryIncident({
1520
1939
  requestId,
1521
- partialText: partial.text,
1522
- partialParts: partial.parts,
1523
- recoveryData: ctx.snapshot,
1524
- messages: [...this.messages],
1525
- lastBody: this._lastBody,
1526
- lastClientTools: this._lastClientTools,
1527
- createdAt: ctx.createdAt
1940
+ recoveryRootRequestId,
1941
+ latestUserMessageId: recoverySnapshot?.latestUserMessageId,
1942
+ recoveryKind
1528
1943
  });
1529
- const streamStillActive = streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId;
1530
- if (options.persist !== false && streamStillActive) this._persistOrphanedStream(streamId);
1531
- if (streamStillActive) this._resumableStream.complete(streamId);
1532
- if (options.continue !== false) {
1533
- const targetId = this._findLastAssistantMessage()?.id;
1534
- await this.schedule(0, "_chatRecoveryContinue", targetId ? { targetAssistantId: targetId } : void 0, { idempotent: true });
1944
+ if (exhausted) {
1945
+ if (streamStillActive) await this._persistOrphanedStream(streamId);
1946
+ await this._exhaustChatRecovery(incident, config, partial, streamId, ctx.createdAt);
1947
+ return true;
1948
+ }
1949
+ try {
1950
+ const options = await this.onChatRecovery({
1951
+ incidentId: incident.incidentId,
1952
+ recoveryRootRequestId,
1953
+ attempt: incident.attempt,
1954
+ maxAttempts: incident.maxAttempts,
1955
+ recoveryKind,
1956
+ streamId: streamId ?? "",
1957
+ requestId,
1958
+ partialText: partial.text,
1959
+ partialParts: partial.parts,
1960
+ recoveryData,
1961
+ messages: [...this.messages],
1962
+ lastBody: recoverySnapshot?.lastBody ?? this._lastBody,
1963
+ lastClientTools: recoverySnapshot?.lastClientTools ?? this._lastClientTools,
1964
+ createdAt: ctx.createdAt
1965
+ }) ?? {};
1966
+ if (streamStillActive && (options.persist !== false || this._partialHasSettledToolResults(partial.parts))) await this._persistOrphanedStream(streamId);
1967
+ if (streamStillActive) this._resumableStream.complete(streamId);
1968
+ const targetId = shouldRetryPreStream ? void 0 : this._findLastAssistantMessage()?.id;
1969
+ if (shouldRetryPreStream && options.continue !== false) {
1970
+ await this._updateChatRecoveryIncident(incident.incidentId, "scheduled");
1971
+ this._emit("chat:recovery:scheduled", {
1972
+ incidentId: incident.incidentId,
1973
+ requestId,
1974
+ attempt: incident.attempt,
1975
+ maxAttempts: incident.maxAttempts,
1976
+ recoveryKind
1977
+ });
1978
+ await this.schedule(0, "_chatRecoveryRetry", {
1979
+ targetUserId: recoverySnapshot.latestUserMessageId,
1980
+ originalRequestId: recoveryRootRequestId,
1981
+ incidentId: incident.incidentId,
1982
+ lastBody: recoverySnapshot.lastBody ?? null,
1983
+ lastClientTools: recoverySnapshot.lastClientTools ?? null
1984
+ }, { idempotent: true });
1985
+ } else if (options.continue !== false) {
1986
+ await this._updateChatRecoveryIncident(incident.incidentId, "scheduled");
1987
+ this._emit("chat:recovery:scheduled", {
1988
+ incidentId: incident.incidentId,
1989
+ requestId,
1990
+ attempt: incident.attempt,
1991
+ maxAttempts: incident.maxAttempts,
1992
+ recoveryKind
1993
+ });
1994
+ await this.schedule(0, "_chatRecoveryContinue", {
1995
+ ...targetId ? { targetAssistantId: targetId } : {},
1996
+ originalRequestId: recoveryRootRequestId,
1997
+ incidentId: incident.incidentId,
1998
+ ...recoverySnapshot ? {
1999
+ lastBody: recoverySnapshot.lastBody ?? null,
2000
+ lastClientTools: recoverySnapshot.lastClientTools ?? null
2001
+ } : {}
2002
+ }, { idempotent: true });
2003
+ } else await this._updateChatRecoveryIncident(incident.incidentId, "skipped", "continue_disabled");
2004
+ return true;
2005
+ } catch (error) {
2006
+ await this._updateChatRecoveryIncident(incident.incidentId, "failed", error instanceof Error ? error.message : String(error));
2007
+ throw error;
1535
2008
  }
1536
- return true;
1537
2009
  }
1538
2010
  /**
1539
2011
  * Called when an interrupted chat stream is detected after restart.
@@ -1544,19 +2016,167 @@ var AIChatAgent = class AIChatAgent extends Agent {
1544
2016
  * - `{ persist: false, continue: false }`: handle everything yourself
1545
2017
  *
1546
2018
  * `ctx.recoveryData` contains any data checkpointed via `this.stash()`
1547
- * during streaming (e.g., OpenAI `responseId`).
2019
+ * during the turn (e.g., OpenAI `responseId`). If recovery happens before
2020
+ * any stream chunks exist and the latest message is still the unanswered
2021
+ * user message from the interrupted turn, the framework retries that turn
2022
+ * automatically unless continuation is disabled.
1548
2023
  */
1549
2024
  async onChatRecovery(_ctx) {
1550
2025
  return {};
1551
2026
  }
1552
2027
  async _chatRecoveryContinue(data) {
1553
- if (!await this.waitUntilStable({ timeout: 1e4 })) {
1554
- console.warn("[AIChatAgent] _chatRecoveryContinue timed out waiting for stable state, skipping continuation");
1555
- return;
2028
+ const previousRootRequestId = this._activeChatRecoveryRootRequestId;
2029
+ this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
2030
+ try {
2031
+ const recoveryConfig = this._resolveChatRecoveryConfig();
2032
+ if (!await this.waitUntilStable({ timeout: recoveryConfig.stableTimeoutMs })) {
2033
+ console.warn("[AIChatAgent] _chatRecoveryContinue timed out waiting for stable state");
2034
+ if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryContinue", data, recoveryConfig.maxAttempts)) return;
2035
+ await this._exhaustRecoveryAfterStableTimeout("_chatRecoveryContinue", data);
2036
+ return;
2037
+ }
2038
+ const targetId = data?.targetAssistantId;
2039
+ if (targetId && this._findLastAssistantMessage()?.id !== targetId) {
2040
+ await this._updateChatRecoveryIncident(data?.incidentId, "skipped", "conversation_changed");
2041
+ return;
2042
+ }
2043
+ this._applyRecoveredRequestContext(data);
2044
+ const result = await this.continueLastTurn();
2045
+ await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
2046
+ } finally {
2047
+ this._activeChatRecoveryRootRequestId = previousRootRequestId;
2048
+ }
2049
+ }
2050
+ _applyRecoveredRequestContext(data) {
2051
+ if (!data) return;
2052
+ if ("lastClientTools" in data) this._lastClientTools = data.lastClientTools ?? void 0;
2053
+ if ("lastBody" in data) this._lastBody = data.lastBody ?? void 0;
2054
+ if ("lastClientTools" in data || "lastBody" in data) this._persistRequestContext();
2055
+ }
2056
+ /**
2057
+ * Reschedule a recovery callback that timed out waiting for stable state,
2058
+ * consuming one attempt. Returns `true` if rescheduled, `false` if the
2059
+ * attempt budget is exhausted (caller should then fail terminally).
2060
+ */
2061
+ async _rescheduleRecoveryAfterStableTimeout(callback, data, maxAttempts) {
2062
+ const incidentKey = data?.incidentId ? this._chatRecoveryIncidentKey(data.incidentId) : null;
2063
+ const incident = incidentKey ? await this.ctx.storage.get(incidentKey) : null;
2064
+ if (!incident || !incidentKey) return false;
2065
+ const attempt = incident.attempt ?? 0;
2066
+ if (attempt >= (incident.maxAttempts ?? maxAttempts)) return false;
2067
+ await this.ctx.storage.put(incidentKey, {
2068
+ ...incident,
2069
+ attempt: attempt + 1,
2070
+ status: "scheduled",
2071
+ lastAttemptAt: Date.now(),
2072
+ reason: "stable_timeout_retry"
2073
+ });
2074
+ await this.schedule(CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS, callback, data ?? {}, { idempotent: false });
2075
+ return true;
2076
+ }
2077
+ /**
2078
+ * Resolve the stream id for a recovery turn so the give-up terminalization
2079
+ * can surface whatever partial the turn produced. Prefers the durable stream
2080
+ * row keyed by the recovery-root request id; falls back to the live active
2081
+ * stream. Returns `""` when neither is available.
2082
+ */
2083
+ _resolveRecoveryStreamId(requestId) {
2084
+ if (requestId) {
2085
+ const fromMetadata = this._resumableStream.getAllStreamMetadata().find((metadata) => metadata.request_id === requestId)?.id;
2086
+ if (fromMetadata) return fromMetadata;
2087
+ }
2088
+ return this._resumableStream.hasActiveStream() ? this._resumableStream.activeStreamId ?? "" : "";
2089
+ }
2090
+ /**
2091
+ * Terminalize a recovery turn that has run out of stable-state-timeout retry
2092
+ * budget — or whose incident record has vanished — by routing through the
2093
+ * SAME `_exhaustChatRecovery` path as deploy-recovery exhaustion. It fires
2094
+ * `onExhausted`, emits `chat:recovery:exhausted`, and delivers the configured
2095
+ * `terminalMessage`.
2096
+ *
2097
+ * This replaces the older give-up that only set the incident to `failed`,
2098
+ * which bypassed `_exhaustChatRecovery` entirely — so an app relying on
2099
+ * `onExhausted` for the terminal banner regressed to an eternal spinner when
2100
+ * recovery gave up under extreme churn. Shared by `_chatRecoveryRetry` and
2101
+ * `_chatRecoveryContinue`; mirrors the same helper in `@cloudflare/think`.
2102
+ *
2103
+ * Exactly-once terminalization here rests SOLELY on the
2104
+ * `stored?.status === "exhausted"` re-entry guard below — unlike
2105
+ * `@cloudflare/think`, `@cloudflare/ai-chat` has no durable-submission layer
2106
+ * to short-circuit a duplicate alarm earlier. The sealed incident is
2107
+ * re-persisted even when the record was found missing, so a swept record is
2108
+ * re-armed for the guard on the next alarm.
2109
+ *
2110
+ * Two residual at-least-once edges, both deliberately accepted as "deliver a
2111
+ * second banner" ≫ "silently drop the turn":
2112
+ * • No `incidentId` at all in the payload (only reachable via a direct/test
2113
+ * invocation — every production scheduler carries one): the synthesized
2114
+ * incident can't be persisted (no key), so the guard can't arm.
2115
+ * • The record is swept AGAIN between two alarms (the guard re-persists on
2116
+ * the first, so this needs a second independent sweep) — vanishingly
2117
+ * unlikely.
2118
+ */
2119
+ async _exhaustRecoveryAfterStableTimeout(callback, data) {
2120
+ const config = this._resolveChatRecoveryConfig();
2121
+ const incidentKey = data?.incidentId ? this._chatRecoveryIncidentKey(data.incidentId) : null;
2122
+ const stored = incidentKey ? await this.ctx.storage.get(incidentKey) : null;
2123
+ if (stored?.status === "exhausted") return;
2124
+ const rootRequestId = data?.originalRequestId ?? this._activeChatRecoveryRootRequestId ?? stored?.recoveryRootRequestId ?? stored?.requestId ?? "";
2125
+ const incident = stored ? {
2126
+ ...stored,
2127
+ status: "exhausted",
2128
+ reason: "stable_timeout"
2129
+ } : {
2130
+ incidentId: data?.incidentId ?? crypto.randomUUID(),
2131
+ requestId: rootRequestId,
2132
+ recoveryRootRequestId: rootRequestId,
2133
+ recoveryKind: callback === "_chatRecoveryRetry" ? "retry" : "continue",
2134
+ attempt: config.maxAttempts,
2135
+ maxAttempts: config.maxAttempts,
2136
+ status: "exhausted",
2137
+ firstSeenAt: Date.now(),
2138
+ lastAttemptAt: Date.now(),
2139
+ reason: "stable_timeout"
2140
+ };
2141
+ if (incidentKey) await this.ctx.storage.put(incidentKey, incident);
2142
+ const streamId = this._resolveRecoveryStreamId(incident.recoveryRootRequestId ?? incident.requestId);
2143
+ const partial = streamId ? this._getPartialStreamText(streamId) : {
2144
+ text: "",
2145
+ parts: []
2146
+ };
2147
+ await this._exhaustChatRecovery(incident, config, partial, streamId, incident.firstSeenAt);
2148
+ }
2149
+ _shouldRetryRecoveredPreStreamTurn(snapshot, streamId, partial) {
2150
+ if (!snapshot || snapshot.continuation || !snapshot.latestUserMessageId || streamId || partial.text || partial.parts.length > 0) return false;
2151
+ const lastMessage = this.messages.length > 0 ? this.messages[this.messages.length - 1] : null;
2152
+ return lastMessage?.role === "user" && lastMessage.id === snapshot.latestUserMessageId;
2153
+ }
2154
+ async _chatRecoveryRetry(data) {
2155
+ const previousRootRequestId = this._activeChatRecoveryRootRequestId;
2156
+ this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
2157
+ try {
2158
+ const recoveryConfig = this._resolveChatRecoveryConfig();
2159
+ if (!await this.waitUntilStable({ timeout: recoveryConfig.stableTimeoutMs })) {
2160
+ console.warn("[AIChatAgent] _chatRecoveryRetry timed out waiting for stable state");
2161
+ if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryRetry", data, recoveryConfig.maxAttempts)) return;
2162
+ await this._exhaustRecoveryAfterStableTimeout("_chatRecoveryRetry", data);
2163
+ return;
2164
+ }
2165
+ const lastMessage = this.messages.length > 0 ? this.messages[this.messages.length - 1] : null;
2166
+ if (!lastMessage || lastMessage.role !== "user") {
2167
+ await this._updateChatRecoveryIncident(data?.incidentId, "skipped", "no_unanswered_user_message");
2168
+ return;
2169
+ }
2170
+ if (data?.targetUserId && lastMessage.id !== data.targetUserId) {
2171
+ await this._updateChatRecoveryIncident(data?.incidentId, "skipped", "conversation_changed");
2172
+ return;
2173
+ }
2174
+ this._applyRecoveredRequestContext(data);
2175
+ const result = await this._retryLastUserTurn(this._lastClientTools, this._lastBody);
2176
+ await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
2177
+ } finally {
2178
+ this._activeChatRecoveryRootRequestId = previousRootRequestId;
1556
2179
  }
1557
- const targetId = data?.targetAssistantId;
1558
- if (targetId && this._findLastAssistantMessage()?.id !== targetId) return;
1559
- await this.continueLastTurn();
1560
2180
  }
1561
2181
  /**
1562
2182
  * Extract partial text and parts from stored stream chunks.
@@ -2021,7 +2641,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2021
2641
  type: "cf_agent_use_chat_response",
2022
2642
  ...continuation && { continuation: true }
2023
2643
  });
2024
- return "completed";
2644
+ return { status: "completed" };
2025
2645
  }
2026
2646
  const lines = decoder.decode(value).split("\n");
2027
2647
  for (const line of lines) if (line.startsWith("data: ") && line !== "data: [DONE]") try {
@@ -2120,15 +2740,32 @@ var AIChatAgent = class AIChatAgent extends Agent {
2120
2740
  } : data.messageMetadata;
2121
2741
  break;
2122
2742
  case "finish-step": break;
2123
- case "error":
2743
+ case "error": {
2744
+ const error = data.errorText ?? JSON.stringify({ type: data.type });
2124
2745
  this._broadcastChatMessage({
2125
2746
  error: true,
2126
- body: data.errorText ?? JSON.stringify(data),
2747
+ body: error,
2127
2748
  done: false,
2128
2749
  id,
2129
- type: "cf_agent_use_chat_response"
2750
+ type: "cf_agent_use_chat_response",
2751
+ ...continuation && { continuation: true }
2130
2752
  });
2131
- break;
2753
+ this._markStreamError(streamId);
2754
+ this._emit("message:error", { error });
2755
+ await reader.cancel().catch(() => {});
2756
+ streamCompleted.value = true;
2757
+ this._broadcastChatMessage({
2758
+ body: "",
2759
+ done: true,
2760
+ id,
2761
+ type: "cf_agent_use_chat_response",
2762
+ ...continuation && { continuation: true }
2763
+ });
2764
+ return {
2765
+ status: "error",
2766
+ error
2767
+ };
2768
+ }
2132
2769
  }
2133
2770
  let eventToSend = data;
2134
2771
  if (continuation && data.type === "start" && "messageId" in data) {
@@ -2144,7 +2781,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2144
2781
  };
2145
2782
  }
2146
2783
  const chunkBody = JSON.stringify(eventToSend);
2147
- this._storeStreamChunk(streamId, chunkBody);
2784
+ await this._storeStreamChunk(streamId, chunkBody);
2148
2785
  this._broadcastChatMessage({
2149
2786
  body: chunkBody,
2150
2787
  done: false,
@@ -2164,9 +2801,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
2164
2801
  type: "cf_agent_use_chat_response",
2165
2802
  ...continuation && { continuation: true }
2166
2803
  });
2167
- return "aborted";
2804
+ return { status: "aborted" };
2168
2805
  }
2169
- return "completed";
2806
+ return { status: "completed" };
2170
2807
  }
2171
2808
  async _sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation = false, abortSignal) {
2172
2809
  let textPart;
@@ -2178,7 +2815,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2178
2815
  }
2179
2816
  }
2180
2817
  if (textPart) {} else {
2181
- this._broadcastTextEvent(streamId, {
2818
+ await this._broadcastTextEvent(streamId, {
2182
2819
  type: "text-start",
2183
2820
  id
2184
2821
  }, continuation);
@@ -2205,7 +2842,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2205
2842
  if (done) {
2206
2843
  if (abortSignal?.aborted) break;
2207
2844
  textPart.state = "done";
2208
- this._broadcastTextEvent(streamId, {
2845
+ await this._broadcastTextEvent(streamId, {
2209
2846
  type: "text-end",
2210
2847
  id
2211
2848
  }, continuation);
@@ -2218,12 +2855,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
2218
2855
  type: "cf_agent_use_chat_response",
2219
2856
  ...continuation && { continuation: true }
2220
2857
  });
2221
- return "completed";
2858
+ return { status: "completed" };
2222
2859
  }
2223
2860
  const chunk = decoder.decode(value);
2224
2861
  if (chunk.length > 0) {
2225
2862
  textPart.text += chunk;
2226
- this._broadcastTextEvent(streamId, {
2863
+ await this._broadcastTextEvent(streamId, {
2227
2864
  type: "text-delta",
2228
2865
  id,
2229
2866
  delta: chunk
@@ -2232,7 +2869,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2232
2869
  }
2233
2870
  if (!streamCompleted.value) {
2234
2871
  textPart.state = "done";
2235
- this._broadcastTextEvent(streamId, {
2872
+ await this._broadcastTextEvent(streamId, {
2236
2873
  type: "text-end",
2237
2874
  id
2238
2875
  }, continuation);
@@ -2245,9 +2882,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
2245
2882
  type: "cf_agent_use_chat_response",
2246
2883
  ...continuation && { continuation: true }
2247
2884
  });
2248
- return "aborted";
2885
+ return { status: "aborted" };
2249
2886
  }
2250
- return "completed";
2887
+ return { status: "completed" };
2251
2888
  }
2252
2889
  /**
2253
2890
  * Applies a tool approval response from the client, updating the persisted message.
@@ -2285,7 +2922,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2285
2922
  ...continuation && { continuation: true }
2286
2923
  });
2287
2924
  this._activateDeferredAutoContinuation();
2288
- return;
2925
+ return { status: "completed" };
2289
2926
  }
2290
2927
  const streamId = this._startStream(id);
2291
2928
  const reader = response.body.getReader();
@@ -2293,32 +2930,30 @@ var AIChatAgent = class AIChatAgent extends Agent {
2293
2930
  this._streamingMessage = message;
2294
2931
  const isSSE = (response.headers.get("content-type") || "").includes("text/event-stream");
2295
2932
  const streamCompleted = { value: false };
2296
- let streamEndStatus = "completed";
2933
+ let streamResult = { status: "completed" };
2297
2934
  let earlyPersistedId = null;
2298
2935
  try {
2299
- if (isSSE) streamEndStatus = await this._streamSSEReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
2300
- else streamEndStatus = await this._sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
2936
+ if (isSSE) streamResult = await this._streamSSEReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
2937
+ else streamResult = await this._sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
2301
2938
  } catch (error) {
2939
+ const errorMessage = error instanceof Error ? error.message : String(error);
2940
+ streamResult = {
2941
+ status: "error",
2942
+ error: errorMessage
2943
+ };
2302
2944
  if (!streamCompleted.value) {
2303
2945
  this._markStreamError(streamId);
2304
2946
  this._broadcastChatMessage({
2305
- body: error instanceof Error ? error.message : "Stream error",
2947
+ body: errorMessage,
2306
2948
  done: true,
2307
2949
  error: true,
2308
2950
  id,
2309
2951
  type: "cf_agent_use_chat_response",
2310
2952
  ...continuation && { continuation: true }
2311
2953
  });
2312
- this._emit("message:error", { error: error instanceof Error ? error.message : String(error) });
2313
- this._pendingChatResponseResults.push({
2314
- message,
2315
- requestId: id,
2316
- continuation,
2317
- status: "error",
2318
- error: error instanceof Error ? error.message : String(error)
2319
- });
2954
+ this._emit("message:error", { error: errorMessage });
2955
+ streamCompleted.value = true;
2320
2956
  }
2321
- throw error;
2322
2957
  } finally {
2323
2958
  reader.releaseLock();
2324
2959
  this._streamingMessage = null;
@@ -2326,7 +2961,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2326
2961
  this._approvalPersistedMessageId = null;
2327
2962
  if (chatMessageId) {
2328
2963
  this._abortRegistry.remove(chatMessageId);
2329
- if (streamCompleted.value) this._emit("message:response");
2964
+ if (streamCompleted.value && streamResult.status !== "error") this._emit("message:response");
2330
2965
  }
2331
2966
  }
2332
2967
  if (message.parts.length > 0) if (earlyPersistedId) {
@@ -2351,8 +2986,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
2351
2986
  message,
2352
2987
  requestId: id,
2353
2988
  continuation,
2354
- status: streamEndStatus
2989
+ status: streamResult.status,
2990
+ ...streamResult.error !== void 0 && { error: streamResult.error }
2355
2991
  });
2992
+ return streamResult;
2356
2993
  }));
2357
2994
  }
2358
2995
  /**