@cloudflare/ai-chat 0.7.2 → 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
@@ -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,
@@ -122,6 +136,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
122
136
  this.messageConcurrency = "queue";
123
137
  this.waitForMcpConnections = { timeout: 1e4 };
124
138
  this.messages = [];
139
+ this._lastAgentToolStreamProgressAt = 0;
125
140
  this.sql`create table if not exists cf_ai_chat_agent_messages (
126
141
  id text primary key,
127
142
  message text not null,
@@ -146,9 +161,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
146
161
  const _onClose = this.onClose.bind(this);
147
162
  this.onClose = async (connection, code, reason, wasClean) => {
148
163
  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;
164
+ this._continuation.releaseConnection(connection.id);
152
165
  return _onClose(connection, code, reason, wasClean);
153
166
  };
154
167
  const _onMessage = this.onMessage.bind(this);
@@ -298,7 +311,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
298
311
  if (data.type === "cf_agent_stream_resume_request") {
299
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" }));
300
313
  else this._notifyStreamResuming(connection);
301
- 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);
302
315
  else sendIfOpen(connection, JSON.stringify({ type: "cf_agent_stream_resume_none" }));
303
316
  return;
304
317
  }
@@ -306,7 +319,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
306
319
  this._pendingResumeConnections.delete(connection.id);
307
320
  if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === data.id) {
308
321
  const orphanedStreamId = this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
309
- if (orphanedStreamId) this._persistOrphanedStream(orphanedStreamId);
322
+ if (orphanedStreamId) await this._persistOrphanedStream(orphanedStreamId);
310
323
  } else if (this._resumableStream.hasActiveStream()) {} else if (!this._resumableStream.replayCompletedChunksByRequestId(connection, data.id)) sendIfOpen(connection, JSON.stringify({
311
324
  body: "",
312
325
  done: true,
@@ -460,9 +473,25 @@ var AIChatAgent = class AIChatAgent extends Agent {
460
473
  this._continuation.activeConnectionId = null;
461
474
  }
462
475
  }
463
- /** @internal Delegate to _resumableStream */
464
- _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) {
465
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();
466
495
  }
467
496
  /** @internal Delegate to _resumableStream */
468
497
  _flushChunkBuffer() {
@@ -491,7 +520,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
491
520
  * message parts, then persists the result so it survives further refreshes.
492
521
  * @internal
493
522
  */
494
- _persistOrphanedStream(streamId) {
523
+ async _persistOrphanedStream(streamId) {
495
524
  const chunks = this._resumableStream.getStreamChunks(streamId);
496
525
  if (!chunks.length) return;
497
526
  const fallbackId = `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
@@ -526,7 +555,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
526
555
  } : existing.metadata;
527
556
  }
528
557
  const updatedMessages = existingIdx >= 0 ? this.messages.map((m, i) => i === existingIdx ? message : m) : [...this.messages, message];
529
- this.persistMessages(updatedMessages);
558
+ await this.persistMessages(updatedMessages);
530
559
  }
531
560
  }
532
561
  /**
@@ -572,9 +601,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
572
601
  * @param event - The text event payload (text-start, text-delta with delta, or text-end)
573
602
  * @param continuation - Whether this is a continuation of a previous stream
574
603
  */
575
- _broadcastTextEvent(streamId, event, continuation) {
604
+ async _broadcastTextEvent(streamId, event, continuation) {
576
605
  const body = JSON.stringify(event);
577
- this._storeStreamChunk(streamId, body);
606
+ await this._storeStreamChunk(streamId, body);
578
607
  this._broadcastChatMessage({
579
608
  body,
580
609
  done: false,
@@ -896,11 +925,70 @@ var AIChatAgent = class AIChatAgent extends Agent {
896
925
  async _awaitPendingAutoContinuationPrerequisite() {
897
926
  while (true) {
898
927
  const prerequisite = this._continuation.pending?.prerequisite;
899
- if (!prerequisite) return true;
928
+ if (!prerequisite) break;
900
929
  if (!await prerequisite) return false;
901
930
  await new Promise((resolve) => setTimeout(resolve, AIChatAgent.AUTO_CONTINUATION_COALESCE_MS));
902
- 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;
903
990
  }
991
+ return false;
904
992
  }
905
993
  _queueAutoContinuation(requestId) {
906
994
  const epoch = this._turnQueue.generation;
@@ -1238,10 +1326,65 @@ var AIChatAgent = class AIChatAgent extends Agent {
1238
1326
  `;
1239
1327
  this._closeAgentToolTailers(runId);
1240
1328
  }
1241
- async inspectAgentToolRun(runId) {
1242
- const row = this._getAgentToolRunRow(runId);
1243
- if (!row) return null;
1244
- 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 {
1245
1388
  const error = "Agent tool run was interrupted before the child could finish.";
1246
1389
  this.sql`
1247
1390
  update cf_ai_chat_agent_tool_runs
@@ -1251,7 +1394,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
1251
1394
  row.status = "error";
1252
1395
  row.error_message = error;
1253
1396
  row.completed_at = Date.now();
1397
+ this._closeAgentToolTailers(runId);
1254
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);
1255
1404
  const streamId = row.request_id ? this._getAgentToolStreamId(row.request_id) : void 0;
1256
1405
  const messagesAfterStart = this._getAgentToolMessagesAfterStart(runId);
1257
1406
  const input = AIChatAgent._parseAgentToolValue(row.input_json);
@@ -1304,7 +1453,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
1304
1453
  }
1305
1454
  const forwarders = this._agentToolForwarders.get(runId) ?? /* @__PURE__ */ new Set();
1306
1455
  const forward = (chunk) => {
1307
- 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
+ }
1308
1462
  };
1309
1463
  forwarders.add(forward);
1310
1464
  this._agentToolForwarders.set(runId, forwarders);
@@ -1546,6 +1700,218 @@ var AIChatAgent = class AIChatAgent extends Agent {
1546
1700
  * `onFiberRecovered` hook. Maps to `onChatRecovery`.
1547
1701
  * @internal
1548
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
+ }
1549
1915
  async _handleInternalFiberRecovery(ctx) {
1550
1916
  const chatPrefix = this.constructor.CHAT_FIBER_NAME + ":";
1551
1917
  if (!ctx.name.startsWith(chatPrefix)) return false;
@@ -1565,39 +1931,81 @@ var AIChatAgent = class AIChatAgent extends Agent {
1565
1931
  text: "",
1566
1932
  parts: []
1567
1933
  };
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
1934
  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 ? {
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({
1939
+ requestId,
1940
+ recoveryRootRequestId,
1941
+ latestUserMessageId: recoverySnapshot?.latestUserMessageId,
1942
+ recoveryKind
1943
+ });
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,
1595
1982
  lastBody: recoverySnapshot.lastBody ?? null,
1596
1983
  lastClientTools: recoverySnapshot.lastClientTools ?? null
1597
- } : {}
1598
- }, { idempotent: true });
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;
1599
2008
  }
1600
- return true;
1601
2009
  }
1602
2010
  /**
1603
2011
  * Called when an interrupted chat stream is detected after restart.
@@ -1617,14 +2025,27 @@ var AIChatAgent = class AIChatAgent extends Agent {
1617
2025
  return {};
1618
2026
  }
1619
2027
  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;
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;
1623
2048
  }
1624
- const targetId = data?.targetAssistantId;
1625
- if (targetId && this._findLastAssistantMessage()?.id !== targetId) return;
1626
- this._applyRecoveredRequestContext(data);
1627
- await this.continueLastTurn();
1628
2049
  }
1629
2050
  _applyRecoveredRequestContext(data) {
1630
2051
  if (!data) return;
@@ -1632,21 +2053,130 @@ var AIChatAgent = class AIChatAgent extends Agent {
1632
2053
  if ("lastBody" in data) this._lastBody = data.lastBody ?? void 0;
1633
2054
  if ("lastClientTools" in data || "lastBody" in data) this._persistRequestContext();
1634
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
+ }
1635
2149
  _shouldRetryRecoveredPreStreamTurn(snapshot, streamId, partial) {
1636
2150
  if (!snapshot || snapshot.continuation || !snapshot.latestUserMessageId || streamId || partial.text || partial.parts.length > 0) return false;
1637
2151
  const lastMessage = this.messages.length > 0 ? this.messages[this.messages.length - 1] : null;
1638
2152
  return lastMessage?.role === "user" && lastMessage.id === snapshot.latestUserMessageId;
1639
2153
  }
1640
2154
  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;
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;
1644
2179
  }
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
2180
  }
1651
2181
  /**
1652
2182
  * Extract partial text and parts from stored stream chunks.
@@ -2251,7 +2781,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2251
2781
  };
2252
2782
  }
2253
2783
  const chunkBody = JSON.stringify(eventToSend);
2254
- this._storeStreamChunk(streamId, chunkBody);
2784
+ await this._storeStreamChunk(streamId, chunkBody);
2255
2785
  this._broadcastChatMessage({
2256
2786
  body: chunkBody,
2257
2787
  done: false,
@@ -2285,7 +2815,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2285
2815
  }
2286
2816
  }
2287
2817
  if (textPart) {} else {
2288
- this._broadcastTextEvent(streamId, {
2818
+ await this._broadcastTextEvent(streamId, {
2289
2819
  type: "text-start",
2290
2820
  id
2291
2821
  }, continuation);
@@ -2312,7 +2842,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2312
2842
  if (done) {
2313
2843
  if (abortSignal?.aborted) break;
2314
2844
  textPart.state = "done";
2315
- this._broadcastTextEvent(streamId, {
2845
+ await this._broadcastTextEvent(streamId, {
2316
2846
  type: "text-end",
2317
2847
  id
2318
2848
  }, continuation);
@@ -2330,7 +2860,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2330
2860
  const chunk = decoder.decode(value);
2331
2861
  if (chunk.length > 0) {
2332
2862
  textPart.text += chunk;
2333
- this._broadcastTextEvent(streamId, {
2863
+ await this._broadcastTextEvent(streamId, {
2334
2864
  type: "text-delta",
2335
2865
  id,
2336
2866
  delta: chunk
@@ -2339,7 +2869,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2339
2869
  }
2340
2870
  if (!streamCompleted.value) {
2341
2871
  textPart.state = "done";
2342
- this._broadcastTextEvent(streamId, {
2872
+ await this._broadcastTextEvent(streamId, {
2343
2873
  type: "text-end",
2344
2874
  id
2345
2875
  }, continuation);