@cloudflare/ai-chat 0.12.0 → 0.12.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { MessageType } from "./types.js";
2
2
  import { autoTransformMessages } from "./ai-chat-v5-migration.js";
3
- import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext, __DO_NOT_USE_WILL_BREAK__withInvocationScope, isDurableObjectMemoryLimitReset } from "agents";
4
- import { AbortRegistry, AgentToolProgressEmitter, AgentToolStreamProgressThrottle, AutoContinuationController, CHAT_RECOVERY_PROGRESS_KEY, CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS, CHAT_RECOVERY_TASK_NAME, ChatRecoveryEngine, ChatStreamStalledError, ContinuationState, PreStreamTurns, ResumableStream, ResumeHandshake, SubmitConcurrencyController, TIMED_OUT, TurnQueue, aiSdkRecoveryCodec, applyChunkToParts, awaitWithDeadline, buildChatRecoveringFrame, chatRecoveryTaskRunOptions, classifyAgentToolChildRecovery, clearChatTerminal, clientResolvableToolNames, createChatFiberSnapshot, createChatRecoveryTaskDefinition, createChatStreams, createChatTurnTaskDefinition, createToolsFromClientSchemas, dispatchChatRecoveryToHandoff, drainInteractionApplies, hasIncompleteToolBatch, interceptAgentToolBroadcast, isReplayChunk, iterateWithStallWatchdog, listActiveChatRecoveryIncidents, parseProtocolMessage, partAwaitsClientInteraction, pendingChatTerminal, persistReconstructedOrphan, readChatRecoveryProgress, reconcileMessages, reconcileOrphanPartial, recordChatTerminal, repairInterruptedToolParts, resolveChatRecoveryConfig, resolveToolMergeId, runChatRecoveryExhaustion, sendIfOpen, setChatRecovering, sweepStaleChatRecoveryIncidents, toolApprovalUpdate, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
3
+ import { AsyncLocalStorage } from "node:async_hooks";
4
+ import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext, __DO_NOT_USE_WILL_BREAK__withInvocationScope, isPlatformTransientError } from "agents";
5
+ import { AbortRegistry, AgentToolProgressEmitter, AgentToolStreamProgressThrottle, AutoContinuationController, CHAT_RECOVERY_PROGRESS_KEY, CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS, CHAT_RECOVERY_TASK_NAME, ChatRecoveryEngine, ChatStreamStalledError, ContinuationState, PreStreamTurns, ResumableStream, ResumeHandshake, SubmitConcurrencyController, TIMED_OUT, TurnQueue, aiSdkRecoveryCodec, applyChunkToParts, applyLateToolInput, awaitWithDeadline, buildChatRecoveringFrame, chatRecoveryBackoffSeconds, chatRecoveryTaskRunOptions, classifyAgentToolChildRecovery, clearChatTerminal, clientResolvableToolNames, createChatFiberSnapshot, createChatRecoveryTaskDefinition, createChatStreams, createChatTurnTaskDefinition, createToolsFromClientSchemas, dispatchChatRecoveryToHandoff, drainInteractionApplies, hasIncompleteToolBatch, interceptAgentToolBroadcast, isDurableObjectResetError, isPositionlessAgentToolChunk, isReplayChunk, iterateWithStallWatchdog, lateToolInputForwardChunks, listActiveChatRecoveryIncidents, originMessageIds, parseProtocolMessage, partAwaitsClientInteraction, partialHasSettledToolResults, pendingChatTerminal, persistReconstructedOrphan, readChatRecoveryProgress, reconcileMessages, reconcileOrphanPartial, recordChatTerminal, repairInterruptedToolParts, resolveChatRecoveryConfig, runChatRecoveryExhaustion, sendIfOpen, setChatRecovering, sweepStaleChatRecoveryIncidents, toolApprovalUpdate, unwrapChatFiberSnapshot, withOriginMessageIds, wrapChatFiberSnapshot } from "agents/chat";
5
6
  import { Sessions } from "agents/sessions";
6
7
  import { nanoid } from "nanoid";
7
8
  //#region src/index.ts
@@ -20,6 +21,14 @@ const PROVIDER_TOOL_OPAQUE_STRING_KEY_PREFIX = "encrypted";
20
21
  */
21
22
  const PROVIDER_TOOL_MAX_STRING_LENGTH = 500;
22
23
  /**
24
+ * Whether a response-reader error is a platform transient that bounded chat
25
+ * recovery can retry. A deploy or storage reset is excluded: the isolate is
26
+ * going away, and the restart's own recovery owns the turn.
27
+ */
28
+ function isRecoverableStreamReadError(error) {
29
+ return isPlatformTransientError(error) && !isDurableObjectResetError(error);
30
+ }
31
+ /**
23
32
  * Validates that a parsed message has the minimum required structure.
24
33
  * Returns false for messages that would cause runtime errors downstream
25
34
  * (e.g. in convertToModelMessages or the UI layer).
@@ -48,6 +57,9 @@ const agentToolChunkEncoder = new TextEncoder();
48
57
  const LEGACY_LIFT_WINDOW_ROWS = 25;
49
58
  const LEGACY_LIFT_WINDOW_BYTES = 4 * 1024 * 1024;
50
59
  var AIChatAgent = class AIChatAgent extends Agent {
60
+ get _activeChatRecoveryOriginIds() {
61
+ return this._chatRecoveryOriginIdsScope.getStore();
62
+ }
51
63
  /** The default linear conversation handle. */
52
64
  #session;
53
65
  static {
@@ -84,7 +96,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
84
96
  */
85
97
  _dispatchChatRecovery(callback, data, detached) {
86
98
  return dispatchChatRecoveryToHandoff({
87
- detached,
99
+ detached: (onTurnStarted) => this._chatRecoveryEngine().runRecoveryAttempt({
100
+ callback,
101
+ data,
102
+ run: () => detached(onTurnStarted)
103
+ }),
88
104
  track: (turn) => this.lifecycle.trackAlarmWork(turn),
89
105
  redefer: (dedupeKey) => this._enqueueChatRecovery(callback, data ?? {}, "redefer", CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS, dedupeKey),
90
106
  onDetachedError: (error) => console.error(`[AIChatAgent] ${callback} dispatch failed`, error)
@@ -113,9 +129,25 @@ var AIChatAgent = class AIChatAgent extends Agent {
113
129
  continuation,
114
130
  messages: this.messages,
115
131
  lastBody: this._lastBody,
116
- lastClientTools: this._lastClientTools
132
+ lastClientTools: this._lastClientTools,
133
+ originMessageIds: this._originMessageIdsFor(requestId)
117
134
  });
118
- const wrap = (data) => wrapChatFiberSnapshot("__cfAIChatFiberSnapshot", snapshot, data);
135
+ const liveTurn = {
136
+ createdAt: Date.now(),
137
+ recoveryData: null
138
+ };
139
+ const wrap = (data) => {
140
+ liveTurn.recoveryData = data;
141
+ return wrapChatFiberSnapshot("__cfAIChatFiberSnapshot", snapshot, data);
142
+ };
143
+ this._liveChatRecoveryTurns.set(requestId, liveTurn);
144
+ try {
145
+ return await this._runWrappedChatRecoveryFiber(requestId, continuation, wrap, fn);
146
+ } finally {
147
+ if (this._liveChatRecoveryTurns.get(requestId) === liveTurn) this._liveChatRecoveryTurns.delete(requestId);
148
+ }
149
+ }
150
+ async _runWrappedChatRecoveryFiber(requestId, continuation, wrap, fn) {
119
151
  if (this.parentPath.length > 0) return this._runFiberWithStashWrapper(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => fn(), {
120
152
  initialSnapshot: wrap(null),
121
153
  wrapStash: wrap
@@ -154,16 +186,35 @@ var AIChatAgent = class AIChatAgent extends Agent {
154
186
  }
155
187
  }
156
188
  broadcast(msg, without) {
157
- if (this._agentToolForwarders.size > 0 || this._agentToolLiveSequences.size > 0) interceptAgentToolBroadcast(msg, {
158
- forwarders: this._agentToolForwarders,
159
- liveSequences: this._agentToolLiveSequences,
160
- lastErrors: this._agentToolLastErrors,
161
- responseType: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
162
- runForRequest: (requestId) => this._agentToolRunForRequest(requestId)
163
- });
189
+ if (this._agentToolForwarders.size > 0 || this._agentToolLiveSequences.size > 0 || this._agentToolTerminalOnlyRuns.size > 0) {
190
+ const chunkRunId = interceptAgentToolBroadcast(msg, {
191
+ forwarders: this._agentToolForwarders,
192
+ liveSequences: this._agentToolLiveSequences,
193
+ lastErrors: this._agentToolLastErrors,
194
+ onError: (runId, body) => this._recordAgentToolStreamError(runId, body),
195
+ responseType: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
196
+ runForRequest: (requestId) => this._agentToolRunForRequest(requestId),
197
+ terminalOnlyRuns: this._agentToolTerminalOnlyRuns
198
+ });
199
+ if (chunkRunId !== null && this._agentToolTerminalOnlyRuns.has(chunkRunId)) return;
200
+ }
164
201
  super.broadcast(msg, without);
165
202
  }
166
203
  /**
204
+ * Durably record a run's stream error on its still-open row, so a stale-row
205
+ * reconcile after an eviction (before the finalizer seals `error`) still
206
+ * sees the failure. Leaves `status` to the finalizer / reconcile.
207
+ */
208
+ _recordAgentToolStreamError(runId, body) {
209
+ try {
210
+ this.sql`
211
+ update cf_ai_chat_agent_tool_runs
212
+ set error_message = ${body}
213
+ where run_id = ${runId} and status = 'running'
214
+ `;
215
+ } catch {}
216
+ }
217
+ /**
167
218
  * Resolve the agent-tool run whose turn owns a request id, or null when the
168
219
  * request is not an agent-tool turn. Falls back to the persisted run row
169
220
  * (written when the turn starts, see `_registerAgentToolTurn`) so
@@ -172,11 +223,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
172
223
  _agentToolRunForRequest(requestId) {
173
224
  const cached = this._agentToolRunsByRequestId.get(requestId);
174
225
  if (cached !== void 0) return cached;
175
- const runId = this.sql`
176
- select run_id from cf_ai_chat_agent_tool_runs
226
+ const rows = this.sql`
227
+ select run_id, event_delivery from cf_ai_chat_agent_tool_runs
177
228
  where request_id = ${requestId} and status in ('starting', 'running')
178
229
  limit 1
179
- `?.[0]?.run_id ?? null;
230
+ `;
231
+ const runId = rows?.[0]?.run_id ?? null;
232
+ if (runId && rows?.[0]?.event_delivery === "terminal") this._agentToolTerminalOnlyRuns.add(runId);
180
233
  this._agentToolRunsByRequestId.set(requestId, runId);
181
234
  return runId;
182
235
  }
@@ -210,17 +263,21 @@ var AIChatAgent = class AIChatAgent extends Agent {
210
263
  */
211
264
  _rebindAgentToolChildRunRequestId(requestId) {
212
265
  let runId;
266
+ let terminalOnly = false;
213
267
  try {
214
- runId = this.sql`
215
- select run_id from cf_ai_chat_agent_tool_runs
268
+ const rows = this.sql`
269
+ select run_id, event_delivery from cf_ai_chat_agent_tool_runs
216
270
  where status in ('starting', 'running')
217
271
  order by started_at desc
218
272
  limit 1
219
- `?.[0]?.run_id;
273
+ `;
274
+ runId = rows?.[0]?.run_id;
275
+ terminalOnly = rows?.[0]?.event_delivery === "terminal";
220
276
  } catch {
221
277
  return;
222
278
  }
223
279
  if (!runId) return;
280
+ if (terminalOnly) this._agentToolTerminalOnlyRuns.add(runId);
224
281
  this._agentToolRunsByRequestId.set(requestId, runId);
225
282
  this.sql`
226
283
  update cf_ai_chat_agent_tool_runs
@@ -230,6 +287,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
230
287
  }
231
288
  constructor(ctx, env) {
232
289
  super(ctx, env);
290
+ this._chatRecoveryOriginIdsScope = new AsyncLocalStorage();
233
291
  this.sessions = new Sessions();
234
292
  this.hydrationByteBudget = 32 * 1024 * 1024;
235
293
  this.#session = this.sessions.session();
@@ -255,6 +313,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
255
313
  this._agentToolLastErrors = /* @__PURE__ */ new Map();
256
314
  this._agentToolPreTurnAssistantIds = /* @__PURE__ */ new Map();
257
315
  this._agentToolLiveSequences = /* @__PURE__ */ new Map();
316
+ this._agentToolTerminalOnlyRuns = /* @__PURE__ */ new Set();
258
317
  this._agentToolRunsByRequestId = /* @__PURE__ */ new Map();
259
318
  this._autoContinuation = new AutoContinuationController({
260
319
  continuation: this._continuation,
@@ -271,12 +330,16 @@ var AIChatAgent = class AIChatAgent extends Agent {
271
330
  this.messageConcurrency = "queue";
272
331
  this.waitForMcpConnections = { timeout: 1e4 };
273
332
  this._liveChatTurnClosures = /* @__PURE__ */ new Map();
333
+ this._liveChatRecoveryTurns = /* @__PURE__ */ new Map();
274
334
  this.messages = [];
335
+ this._requestOriginMessageIds = /* @__PURE__ */ new Map();
336
+ this._heldTerminalFrames = /* @__PURE__ */ new Map();
275
337
  this._agentToolProgressEmitterInstance = null;
276
338
  this._inSerializedDetachedDeliverySlot = false;
277
339
  this._inFlightDetachedNotifications = /* @__PURE__ */ new Set();
278
340
  this._progressSeed = null;
279
341
  this._agentToolStreamProgress = new AgentToolStreamProgressThrottle();
342
+ this._rescheduledRecoveryIncidents = /* @__PURE__ */ new Set();
280
343
  this.#pendingCutover = null;
281
344
  this.lifecycle.use(this.sessions);
282
345
  this.lifecycle.use(this.streams);
@@ -352,10 +415,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
352
415
  const requestClientTools = clientTools?.length ? clientTools : void 0;
353
416
  const requestBody = Object.keys(customBody).length > 0 ? customBody : void 0;
354
417
  const epoch = this._turnQueue.generation;
418
+ const requestOriginIds = originMessageIds(messages);
419
+ if (requestOriginIds) this._requestOriginMessageIds.set(chatMessageId, requestOriginIds);
355
420
  const concurrencyDecision = this._getSubmitConcurrencyDecision(requestTrigger);
356
421
  if (concurrencyDecision.action === "drop") {
357
422
  this._rollbackDroppedSubmit(connection);
358
423
  this._completeSkippedRequest(connection, chatMessageId);
424
+ this._requestOriginMessageIds.delete(chatMessageId);
359
425
  return;
360
426
  }
361
427
  await withAgentSpan(this, "clear_previous_chat_state", "interaction", {
@@ -445,7 +511,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
445
511
  "cloudflare.agents.turn.trigger": requestTrigger,
446
512
  "cloudflare.agents.turn.admission": "queue",
447
513
  "cloudflare.agents.turn.generation": epoch
448
- }, () => this._repairInterruptedToolsBeforeTurn());
514
+ }, () => this._repairInterruptedToolsBeforeTurn({ continuation: false }));
449
515
  const response = await this.onChatMessage(async (_finishResult) => {}, {
450
516
  requestId: chatMessageId,
451
517
  abortSignal,
@@ -466,8 +532,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
466
532
  body: "No response was generated by the agent.",
467
533
  done: true,
468
534
  id: chatMessageId,
469
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
470
- }, [connection.id]);
535
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
536
+ outcome: "completed"
537
+ });
471
538
  }
472
539
  } finally {
473
540
  this._abortRegistry.remove(chatMessageId);
@@ -483,6 +550,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
483
550
  });
484
551
  } finally {
485
552
  this._settlePreStreamTurn(chatMessageId);
553
+ this._requestOriginMessageIds.delete(chatMessageId);
486
554
  }
487
555
  return;
488
556
  }
@@ -508,6 +576,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
508
576
  }
509
577
  if (event.type === "cancel") {
510
578
  this._abortRegistry.cancel(event.id);
579
+ await this._cancelScheduledRecovery(event.id);
511
580
  this._emit("message:cancel", { requestId: event.id });
512
581
  return;
513
582
  }
@@ -589,6 +658,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
589
658
  addColumnIfNotExists("alter table cf_ai_chat_agent_tool_runs add column summary text");
590
659
  addColumnIfNotExists("alter table cf_ai_chat_agent_tool_runs add column progress_json text");
591
660
  addColumnIfNotExists("alter table cf_ai_chat_agent_tool_runs add column last_signal_at integer");
661
+ addColumnIfNotExists("alter table cf_ai_chat_agent_tool_runs add column event_delivery text");
592
662
  this.sql`create index if not exists idx_ai_chat_agent_tool_request_id
593
663
  on cf_ai_chat_agent_tool_runs(request_id)`;
594
664
  this.sql`create table if not exists cf_ai_chat_agent_tool_milestones (
@@ -660,7 +730,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
660
730
  pendingResumeConnections: this._pendingResumeConnections,
661
731
  pendingChatTerminal: () => this._pendingChatTerminal(),
662
732
  persistOrphanedStream: (streamId) => this._persistOrphanedStream(streamId),
663
- isConnectionPresent: (connectionId) => this._isConnectionPresent(connectionId)
733
+ isConnectionPresent: (connectionId) => this._isConnectionPresent(connectionId),
734
+ holdsTerminalFrames: (requestId) => this._heldTerminalFrames.has(requestId)
664
735
  });
665
736
  }
666
737
  /**
@@ -683,7 +754,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
683
754
  }
684
755
  /** @internal Delegate to _resumableStream */
685
756
  _startStream(requestId, options = {}) {
686
- const streamId = this._resumableStream.start(requestId, options);
757
+ const originIds = this._requestOriginMessageIds.get(requestId) ?? this._activeChatRecoveryOriginIds;
758
+ const streamId = this._resumableStream.start(requestId, {
759
+ ...options,
760
+ ...originIds && { originMessageIds: originIds }
761
+ });
687
762
  this._preStream.flushOnStreamStart((c) => this._notifyStreamResuming(c));
688
763
  if (this._continuation.pending?.requestId === requestId) {
689
764
  this._continuation.activatePending();
@@ -693,9 +768,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
693
768
  return streamId;
694
769
  }
695
770
  /** @internal Delegate to _resumableStream */
696
- _completeStream(streamId) {
771
+ _completeStream(streamId, outcome) {
697
772
  const completedRequestId = this._resumableStream.activeRequestId;
698
- this._resumableStream.complete(streamId);
773
+ this._resumableStream.complete(streamId, outcome);
699
774
  this._afterStreamFinished(completedRequestId);
700
775
  }
701
776
  /**
@@ -703,9 +778,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
703
778
  * persists the message (`persistMessages` via `#pendingCutover`). `_reply`'s
704
779
  * finally settles it if no persist follows.
705
780
  */
706
- _finishStream(streamId) {
781
+ _finishStream(streamId, outcome) {
707
782
  const finishedRequestId = this._resumableStream.activeRequestId;
708
- this._resumableStream.finish(streamId);
783
+ this._resumableStream.finish(streamId, outcome);
709
784
  this._afterStreamFinished(finishedRequestId);
710
785
  }
711
786
  _afterStreamFinished(requestId) {
@@ -738,12 +813,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
738
813
  * per-chunk counter. Streaming deltas keep the buffer's own packing.
739
814
  */
740
815
  async _storeStreamChunk(streamId, body) {
741
- this._resumableStream.storeChunk(streamId, body);
816
+ const seq = this._resumableStream.storeChunk(streamId, body);
742
817
  let type;
743
818
  try {
744
819
  type = JSON.parse(body).type;
745
820
  } catch {}
746
821
  if (type === "tool-output-available" || type === "tool-output-error" || type === "tool-output-denied") this._resumableStream.flushBuffer();
822
+ return seq;
747
823
  }
748
824
  /** @internal Delegate to _resumableStream */
749
825
  _flushChunkBuffer() {
@@ -868,7 +944,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
868
944
  return {
869
945
  ...part,
870
946
  state: "output-error",
871
- errorText: "The tool call was interrupted before a result was recorded."
947
+ errorText: part.state === "approval-responded" ? "The tool call was approved but did not run before the next turn started." : "The tool call was interrupted before a result was recorded."
872
948
  };
873
949
  }
874
950
  /**
@@ -904,11 +980,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
904
980
  * write, one broadcast), which also refreshes `this.messages`.
905
981
  * @internal
906
982
  */
907
- async _repairInterruptedToolsBeforeTurn() {
983
+ async _repairInterruptedToolsBeforeTurn(options) {
908
984
  const clientResolvable = this._clientResolvableToolNames();
909
985
  const repaired = repairInterruptedToolParts(this.messages, {
910
986
  repairPart: (part) => this.repairInterruptedToolPart(part),
911
- shouldRepair: (part) => !this._partAwaitsClientInteraction(part, clientResolvable)
987
+ shouldRepair: (part) => !this._partAwaitsClientInteraction(part, clientResolvable),
988
+ repairApprovalResponded: !options.continuation && !this._continuation.pending && !this._continuation.deferred
912
989
  });
913
990
  if (repaired.removedToolCalls === 0 && repaired.normalizedInputs === 0) return;
914
991
  await this.persistMessages(repaired.messages);
@@ -944,10 +1021,40 @@ var AIChatAgent = class AIChatAgent extends Agent {
944
1021
  `;
945
1022
  else this.sql`delete from cf_ai_chat_request_context where key = 'lastClientTools'`;
946
1023
  }
1024
+ _originMessageIdsFor(requestId) {
1025
+ return this._requestOriginMessageIds.get(requestId) ?? this._resumableStream.getOriginMessageIds(requestId) ?? this._activeChatRecoveryOriginIds;
1026
+ }
1027
+ _withOriginMessageIds(message) {
1028
+ if (message.type !== MessageType.CF_AGENT_USE_CHAT_RESPONSE || !(message.done || message.error)) return message;
1029
+ return withOriginMessageIds(message, this._originMessageIdsFor(message.id));
1030
+ }
947
1031
  _broadcastChatMessage(message, exclude) {
1032
+ message = this._withOriginMessageIds(message);
1033
+ if (message.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && (message.done || message.error)) {
1034
+ const held = this._heldTerminalFrames.get(message.id);
1035
+ if (held) {
1036
+ held.push({
1037
+ message,
1038
+ exclude
1039
+ });
1040
+ return;
1041
+ }
1042
+ }
948
1043
  const allExclusions = [...exclude || [], ...this._pendingResumeConnections];
949
1044
  this.broadcast(JSON.stringify(message), allExclusions);
950
1045
  }
1046
+ _releaseTerminalFrames(id, errorText) {
1047
+ const held = this._heldTerminalFrames.get(id);
1048
+ this._heldTerminalFrames.delete(id);
1049
+ if (!held) return;
1050
+ const failed = errorText !== void 0 && !held.some(({ message }) => message.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && message.error);
1051
+ for (const { message, exclude } of held) this._broadcastChatMessage(failed && message.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE ? {
1052
+ ...message,
1053
+ body: errorText,
1054
+ error: true,
1055
+ ...message.done && { outcome: "error" }
1056
+ } : message, exclude);
1057
+ }
951
1058
  /**
952
1059
  * Broadcasts a text event for non-SSE responses.
953
1060
  * This ensures plain text responses follow the AI SDK v5 stream protocol.
@@ -958,12 +1065,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
958
1065
  */
959
1066
  async _broadcastTextEvent(streamId, event, continuation) {
960
1067
  const body = JSON.stringify(event);
961
- await this._storeStreamChunk(streamId, body);
1068
+ const seq = await this._storeStreamChunk(streamId, body);
962
1069
  this._broadcastChatMessage({
963
1070
  body,
964
1071
  done: false,
965
1072
  id: event.id,
966
1073
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1074
+ ...seq !== void 0 && { seq },
967
1075
  ...continuation && { continuation: true }
968
1076
  });
969
1077
  }
@@ -1062,33 +1170,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
1062
1170
  * cache.
1063
1171
  */
1064
1172
  #subscribeToSessionChanges() {
1065
- this.sessions.subscribe(async (event) => {
1066
- if (event.sessionId !== this.#session.sessionId) return;
1067
- switch (event.type) {
1068
- case "append": {
1069
- if (!event.inserted) return;
1070
- const message = this.#messageForCache(event.message);
1071
- const index = this.messages.findIndex((m) => m.id === message.id);
1072
- if (index === -1) this.messages.push(message);
1073
- else this.messages[index] = message;
1074
- return;
1075
- }
1076
- case "update": {
1077
- const index = this.messages.findIndex((m) => m.id === event.message.id);
1078
- if (index === -1) return;
1079
- this.messages[index] = this.#messageForCache(event.message);
1080
- return;
1081
- }
1082
- case "delete": {
1083
- const removed = new Set(event.messageIds);
1084
- this.messages = this.messages.filter((m) => !removed.has(m.id));
1085
- return;
1086
- }
1087
- case "clear":
1088
- this.messages = [];
1089
- return;
1090
- default: return;
1091
- }
1173
+ this.#session.mirror({
1174
+ get: () => this.messages,
1175
+ set: (messages) => {
1176
+ this.messages = messages;
1177
+ },
1178
+ transform: (message) => this.#messageForCache(message)
1092
1179
  });
1093
1180
  }
1094
1181
  /**
@@ -1266,12 +1353,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
1266
1353
  } catch {}
1267
1354
  }
1268
1355
  _completeSkippedRequest(connection, requestId) {
1269
- this._sendDirectMessage(connection, {
1356
+ this._sendDirectMessage(connection, this._withOriginMessageIds({
1270
1357
  body: "",
1271
1358
  done: true,
1272
1359
  id: requestId,
1273
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
1274
- });
1360
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1361
+ outcome: "skipped"
1362
+ }));
1275
1363
  this._settlePreStreamTurn(requestId, { releaseParked: false });
1276
1364
  }
1277
1365
  /** Whether a connection with this id is still attached. */
@@ -1389,6 +1477,18 @@ var AIChatAgent = class AIChatAgent extends Agent {
1389
1477
  this._abortRegistry.cancel(requestId, reason);
1390
1478
  }
1391
1479
  /**
1480
+ * A cancel can land while the turn's recovery is waiting out its backoff,
1481
+ * with nothing in flight to abort: cancel the scheduled recovery instead,
1482
+ * so the queued callback bails when it fires.
1483
+ */
1484
+ async _cancelScheduledRecovery(requestId) {
1485
+ try {
1486
+ await this._chatRecoveryEngine().cancelScheduledRecovery(requestId);
1487
+ } catch (error) {
1488
+ console.error("[AIChatAgent] failed to cancel a scheduled chat recovery", error);
1489
+ }
1490
+ }
1491
+ /**
1392
1492
  * Abort every in-flight chat turn on this agent.
1393
1493
  *
1394
1494
  * Aborts all controllers in the registry and clears it. Used by
@@ -1529,8 +1629,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
1529
1629
  * continuation would never fire. A slow batch is re-checked here and simply
1530
1630
  * keeps holding (event-driven) until its remaining siblings answer.
1531
1631
  */
1532
- _onStreamingTurnFinalized() {
1632
+ _onStreamingTurnFinalized(finishReason) {
1533
1633
  this._streamingTurnActive = false;
1634
+ if (finishReason === "stop" && this._continuation.pending && !this._hasIncompleteToolBatch()) {
1635
+ this._clearPendingAutoContinuation(true);
1636
+ return;
1637
+ }
1534
1638
  this._autoContinuation.rearmForBatch();
1535
1639
  }
1536
1640
  /**
@@ -1581,8 +1685,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
1581
1685
  email: void 0
1582
1686
  }, async () => {
1583
1687
  const autoContinuationBody = async () => {
1688
+ let replying = false;
1584
1689
  try {
1585
- await this._repairInterruptedToolsBeforeTurn();
1690
+ await this._repairInterruptedToolsBeforeTurn({ continuation: true });
1586
1691
  const response = await this.onChatMessage(async (_finishResult) => {}, {
1587
1692
  requestId,
1588
1693
  abortSignal,
@@ -1593,7 +1698,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
1593
1698
  if (response) {
1594
1699
  if ((await this._reply(requestId, response, [], {
1595
1700
  continuation: true,
1596
- chatMessageId: requestId
1701
+ chatMessageId: requestId,
1702
+ onStreamStart: () => {
1703
+ replying = true;
1704
+ }
1597
1705
  })).status === "error") {
1598
1706
  this._clearAllAutoContinuationState(true);
1599
1707
  return;
@@ -1603,6 +1711,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
1603
1711
  this._clearPendingAutoContinuation(true);
1604
1712
  this._activateDeferredAutoContinuation();
1605
1713
  }
1714
+ } catch (error) {
1715
+ if (!replying && !abortSignal?.aborted && !isDurableObjectResetError(error)) await this._reportContinuationFailure(requestId, error);
1716
+ throw error;
1606
1717
  } finally {
1607
1718
  this._abortRegistry.remove(requestId);
1608
1719
  }
@@ -1623,6 +1734,33 @@ var AIChatAgent = class AIChatAgent extends Agent {
1623
1734
  });
1624
1735
  }
1625
1736
  /**
1737
+ * Report an auto-continuation that failed before it produced a response,
1738
+ * the way a stream error is reported: an error frame, a durable terminal
1739
+ * record, and `onChatResponse` with `status: "error"` for the assistant
1740
+ * message the continuation would have extended. Called inside the turn so
1741
+ * the response hook drains when the turn settles.
1742
+ */
1743
+ async _reportContinuationFailure(requestId, error) {
1744
+ const errorMessage = error instanceof Error ? error.message : String(error);
1745
+ this._broadcastChatMessage({
1746
+ body: errorMessage,
1747
+ done: true,
1748
+ error: true,
1749
+ id: requestId,
1750
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1751
+ continuation: true
1752
+ });
1753
+ const message = [...this.messages].reverse().find((candidate) => candidate.role === "assistant");
1754
+ if (message) this._pendingChatResponseResults.push({
1755
+ message,
1756
+ requestId,
1757
+ continuation: true,
1758
+ status: "error",
1759
+ error: errorMessage
1760
+ });
1761
+ else await this._recordChatTerminal(requestId, errorMessage);
1762
+ }
1763
+ /**
1626
1764
  * @returns Terminal status for the turn.
1627
1765
  */
1628
1766
  async _runProgrammaticChatTurn(requestId, clientTools, body, externalSignal) {
@@ -1640,7 +1778,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1640
1778
  const detachExternal = this._abortRegistry.linkExternal(requestId, externalSignal);
1641
1779
  try {
1642
1780
  const programmaticBody = async () => {
1643
- await this._repairInterruptedToolsBeforeTurn();
1781
+ await this._repairInterruptedToolsBeforeTurn({ continuation: false });
1644
1782
  const response = await this.onChatMessage(() => {}, {
1645
1783
  requestId,
1646
1784
  abortSignal,
@@ -1978,12 +2116,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
1978
2116
  const assistantIdsBeforeStart = new Set(this.messages.filter((message) => message.role === "assistant").map((message) => message.id));
1979
2117
  this.sql`
1980
2118
  insert into cf_ai_chat_agent_tool_runs
1981
- (run_id, request_id, status, input_json, started_at)
1982
- values (${options.runId}, null, 'running', ${AIChatAgent._stringifyAgentToolValue(input)}, ${startedAt})
2119
+ (run_id, request_id, status, input_json, started_at, event_delivery)
2120
+ values (${options.runId}, null, 'running', ${AIChatAgent._stringifyAgentToolValue(input)}, ${startedAt}, ${options.eventDelivery === "terminal" ? "terminal" : null})
1983
2121
  `;
1984
2122
  this._agentToolAbortControllers.set(options.runId, controller);
1985
2123
  this._agentToolPreTurnAssistantIds.set(options.runId, assistantIdsBeforeStart);
1986
2124
  this._agentToolLiveSequences.set(options.runId, 0);
2125
+ if (options.eventDelivery === "terminal") this._agentToolTerminalOnlyRuns.add(options.runId);
1987
2126
  const abortFromParent = () => controller.abort(options.signal?.reason);
1988
2127
  if (options.signal?.aborted) abortFromParent();
1989
2128
  else options.signal?.addEventListener("abort", abortFromParent, { once: true });
@@ -2069,6 +2208,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2069
2208
  options.signal?.removeEventListener("abort", abortFromParent);
2070
2209
  this._agentToolAbortControllers.delete(options.runId);
2071
2210
  this._agentToolLiveSequences.delete(options.runId);
2211
+ this._agentToolTerminalOnlyRuns.delete(options.runId);
2072
2212
  this._agentToolProgressEmitterInstance?.forget(options.runId);
2073
2213
  if (this._agentToolAbortControllers.size === 0) this._agentToolRunsByRequestId.clear();
2074
2214
  else for (const [reqId, runId] of this._agentToolRunsByRequestId) if (runId === options.runId) this._agentToolRunsByRequestId.delete(reqId);
@@ -2120,6 +2260,19 @@ var AIChatAgent = class AIChatAgent extends Agent {
2120
2260
  async _reconcileStaleAgentToolChildRun(runId, row) {
2121
2261
  const recovery = await this._classifyAgentToolChildRecovery();
2122
2262
  if (recovery === "in-progress" || this._resumableStream.hasActiveStream()) return;
2263
+ if (row.error_message !== null) {
2264
+ const completedAt = Date.now();
2265
+ this.sql`
2266
+ update cf_ai_chat_agent_tool_runs
2267
+ set status = 'error', error_message = ${row.error_message},
2268
+ completed_at = ${completedAt}
2269
+ where run_id = ${runId}
2270
+ `;
2271
+ row.status = "error";
2272
+ row.completed_at = completedAt;
2273
+ this._closeAgentToolTailers(runId);
2274
+ return;
2275
+ }
2123
2276
  const messagesAfterStart = this._getAgentToolMessagesAfterStart(runId);
2124
2277
  if (recovery !== "failed" && messagesAfterStart.some((message) => message.role === "assistant")) {
2125
2278
  const input = AIChatAgent._parseAgentToolValue(row.input_json);
@@ -2193,10 +2346,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
2193
2346
  } catch {}
2194
2347
  }
2195
2348
  }
2196
- async inspectAgentToolRun(runId) {
2349
+ async inspectAgentToolRun(runId, options) {
2197
2350
  const row = this._getAgentToolRunRow(runId);
2198
2351
  if (!row) return null;
2199
- if (row.status === "running" && !this._agentToolAbortControllers.has(runId)) await this._reconcileStaleAgentToolChildRun(runId, row);
2352
+ if (options?.reconcile !== false && row.status === "running" && !this._agentToolAbortControllers.has(runId)) await this._reconcileStaleAgentToolChildRun(runId, row);
2200
2353
  const streamId = row.request_id ? this._getAgentToolStreamId(row.request_id) : void 0;
2201
2354
  const messagesAfterStart = this._getAgentToolMessagesAfterStart(runId);
2202
2355
  const input = AIChatAgent._parseAgentToolValue(row.input_json);
@@ -2253,8 +2406,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
2253
2406
  let lastEmitted = options?.afterSequence ?? -1;
2254
2407
  const emit = (chunk) => {
2255
2408
  if (closed) return;
2256
- if (chunk.sequence <= lastEmitted) return;
2257
- lastEmitted = chunk.sequence;
2409
+ if (!isPositionlessAgentToolChunk(chunk)) {
2410
+ if (chunk.sequence <= lastEmitted) return;
2411
+ lastEmitted = chunk.sequence;
2412
+ }
2258
2413
  try {
2259
2414
  controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
2260
2415
  } catch {
@@ -2287,6 +2442,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2287
2442
  return;
2288
2443
  }
2289
2444
  options?.signal?.addEventListener("abort", onAbort, { once: true });
2445
+ const seeded = this._seedAgentToolLiveSequence(runId);
2290
2446
  const forwarders = this._agentToolForwarders.get(runId) ?? /* @__PURE__ */ new Set();
2291
2447
  forwarders.add(forward);
2292
2448
  this._agentToolForwarders.set(runId, forwarders);
@@ -2302,10 +2458,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
2302
2458
  pending.length = 0;
2303
2459
  const inspection = await this.inspectAgentToolRun(runId);
2304
2460
  if (!inspection || inspection.status !== "running") {
2461
+ if (seeded) this._agentToolLiveSequences.delete(runId);
2305
2462
  close();
2306
2463
  return;
2307
2464
  }
2308
- if (lastEmitted > (options?.afterSequence ?? -1)) this._agentToolLiveSequences.set(runId, lastEmitted + 1);
2309
2465
  } catch (error) {
2310
2466
  closed = true;
2311
2467
  detach();
@@ -2332,6 +2488,23 @@ var AIChatAgent = class AIChatAgent extends Agent {
2332
2488
  _getAgentToolStreamId(requestId) {
2333
2489
  return this._resumableStream.latestStreamInfoForRequest(requestId)?.id;
2334
2490
  }
2491
+ /**
2492
+ * After this DO restarts, `_agentToolLiveSequences` is cold while the stored
2493
+ * backlog sits at N, and a chat-recovery resume re-attaches via
2494
+ * `tailAgentToolRun` without re-running `startAgentToolRun` (which seeds the
2495
+ * counter). Unseeded, the broadcast snoop numbers the recovered turn's chunks
2496
+ * from 0 and the tail's high-water dedupe drops them. Seeds only a running
2497
+ * run, so a terminal one doesn't re-heat the broadcast idle-guard; a warm
2498
+ * counter is authoritative. Returns whether it seeded.
2499
+ */
2500
+ _seedAgentToolLiveSequence(runId) {
2501
+ if (this._agentToolLiveSequences.has(runId)) return false;
2502
+ this._flushChunkBuffer();
2503
+ const row = this._getAgentToolRunRow(runId);
2504
+ if (!row?.request_id || row.status !== "running") return false;
2505
+ this._agentToolLiveSequences.set(runId, this._getAgentToolStoredChunks(row.request_id).length);
2506
+ return true;
2507
+ }
2335
2508
  _getAgentToolStoredChunks(requestId, afterSequence = -1) {
2336
2509
  const streamId = this._getAgentToolStreamId(requestId);
2337
2510
  if (!streamId) return [];
@@ -2351,6 +2524,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2351
2524
  this._agentToolClosers.delete(runId);
2352
2525
  }
2353
2526
  this._agentToolForwarders.delete(runId);
2527
+ if (!this._agentToolAbortControllers.has(runId)) this._agentToolTerminalOnlyRuns.delete(runId);
2354
2528
  }
2355
2529
  static _stringifyAgentToolValue(value) {
2356
2530
  if (value === void 0) return null;
@@ -2471,7 +2645,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2471
2645
  const abortSignal = this._abortRegistry.getSignal(requestId);
2472
2646
  const detachExternal = this._abortRegistry.linkExternal(requestId, options?.signal);
2473
2647
  try {
2474
- await this._repairInterruptedToolsBeforeTurn();
2648
+ await this._repairInterruptedToolsBeforeTurn({ continuation: true });
2475
2649
  const response = await this.onChatMessage(() => {}, {
2476
2650
  requestId,
2477
2651
  abortSignal,
@@ -2589,9 +2763,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
2589
2763
  now: () => Date.now(),
2590
2764
  sweepStaleIncidents: (now) => sweepStaleChatRecoveryIncidents(this.ctx.storage, now),
2591
2765
  getIncident: async (key) => await this.ctx.storage.get(key) ?? null,
2766
+ listActiveIncidents: async () => (await listActiveChatRecoveryIncidents(this.ctx.storage)).map(({ incident }) => incident),
2592
2767
  readProgress: () => this._chatRecoveryProgressMarker(),
2593
2768
  isAwaitingClientInteraction: () => this.hasPendingClientInteraction(),
2594
2769
  putIncident: (key, incident) => this.ctx.storage.put(key, incident),
2770
+ syncStorage: () => this.ctx.storage.sync(),
2595
2771
  deleteIncident: async (key) => {
2596
2772
  await this.ctx.storage.delete(key);
2597
2773
  },
@@ -2606,7 +2782,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2606
2782
  scheduleRecovery: (callback, data, reason, delaySeconds) => this._enqueueChatRecovery(callback, data, reason, delaySeconds),
2607
2783
  setRecovering: (active, requestId) => this._setChatRecovering(active, requestId),
2608
2784
  onShouldKeepRecoveringError: (error) => console.error("[AIChatAgent] chatRecovery shouldKeepRecovering hook threw", error),
2609
- exhaustChatRecovery: (incident, config, partial, streamId, createdAt) => this._exhaustChatRecovery(incident, config, partial, streamId, createdAt),
2785
+ exhaustChatRecovery: (incident, config, partial, streamId, createdAt, originMessageIds) => this._exhaustChatRecovery(incident, config, partial, streamId, createdAt, originMessageIds),
2610
2786
  resolveRecoveryStream: (requestId) => this._resolveAIChatRecoveryStream(requestId),
2611
2787
  getPartialStreamText: (streamId) => this._getPartialStreamText(streamId),
2612
2788
  activeChatRecoveryRootRequestId: () => this._activeChatRecoveryRootRequestId,
@@ -2619,7 +2795,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2619
2795
  async _updateChatRecoveryIncident(incidentId, status, reason) {
2620
2796
  return this._chatRecoveryEngine().updateIncident(incidentId, status, reason);
2621
2797
  }
2622
- async _exhaustChatRecovery(incident, config, partial, streamId, createdAt) {
2798
+ async _exhaustChatRecovery(incident, config, partial, streamId, createdAt, originMessageIds) {
2623
2799
  await runChatRecoveryExhaustion({
2624
2800
  incident,
2625
2801
  config,
@@ -2632,14 +2808,16 @@ var AIChatAgent = class AIChatAgent extends Agent {
2632
2808
  onExhausted: config.onExhausted,
2633
2809
  onError: (error) => console.error("[AIChatAgent] chatRecovery onExhausted hook threw", error),
2634
2810
  terminalize: async (ctx) => {
2811
+ const messageIds = this._originMessageIdsFor(ctx.requestId) ?? originMessageIds;
2635
2812
  this._broadcastChatMessage({
2636
2813
  body: ctx.terminalMessage,
2637
2814
  done: true,
2638
2815
  error: true,
2639
2816
  id: ctx.requestId,
2640
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
2817
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
2818
+ ...messageIds ? { messageIds } : {}
2641
2819
  });
2642
- await this._recordChatTerminal(ctx.requestId, ctx.terminalMessage);
2820
+ await this._recordChatTerminal(ctx.requestId, ctx.terminalMessage, messageIds);
2643
2821
  await this._setChatRecovering(false);
2644
2822
  }
2645
2823
  });
@@ -2650,8 +2828,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
2650
2828
  * until a later turn supersedes it (`_clearChatTerminal`); a single record is
2651
2829
  * sufficient because only the most recent terminal is relevant.
2652
2830
  */
2653
- async _recordChatTerminal(requestId, body) {
2654
- await recordChatTerminal(this.ctx.storage, requestId, body);
2831
+ async _recordChatTerminal(requestId, body, messageIds = this._originMessageIdsFor(requestId)) {
2832
+ await recordChatTerminal(this.ctx.storage, requestId, body, messageIds);
2655
2833
  }
2656
2834
  /** Clear the durable terminal record once a later turn supersedes it (#1645). */
2657
2835
  async _clearChatTerminal() {
@@ -2769,6 +2947,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2769
2947
  */
2770
2948
  async _dispatchRecoveredChatTurn(input) {
2771
2949
  const { incident, options, snapshot, recoveryRootRequestId } = input;
2950
+ const originIds = this._originMessageIdsFor(input.requestId) ?? snapshot?.originMessageIds;
2772
2951
  const leaf = this.messages.length > 0 ? this.messages[this.messages.length - 1] : void 0;
2773
2952
  const lostPartialUserId = snapshot?.continuation === false && snapshot.latestUserMessageId && leaf?.role === "user" && leaf.id === snapshot.latestUserMessageId ? snapshot.latestUserMessageId : void 0;
2774
2953
  const targetId = input.detail.shouldRetryPreStream || lostPartialUserId !== void 0 ? void 0 : this._findLastAssistantMessage()?.id;
@@ -2781,7 +2960,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
2781
2960
  originalRequestId: recoveryRootRequestId,
2782
2961
  incidentId: incident.incidentId,
2783
2962
  lastBody: snapshot?.lastBody ?? null,
2784
- lastClientTools: snapshot?.lastClientTools ?? null
2963
+ lastClientTools: snapshot?.lastClientTools ?? null,
2964
+ ...originIds ? { originMessageIds: originIds } : {}
2785
2965
  }
2786
2966
  });
2787
2967
  else if (lostPartialUserId !== void 0 && options.continue !== false) await this._chatRecoveryEngine().scheduleRecovery({
@@ -2793,7 +2973,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
2793
2973
  originalRequestId: recoveryRootRequestId,
2794
2974
  incidentId: incident.incidentId,
2795
2975
  lastBody: snapshot?.lastBody ?? null,
2796
- lastClientTools: snapshot?.lastClientTools ?? null
2976
+ lastClientTools: snapshot?.lastClientTools ?? null,
2977
+ ...originIds ? { originMessageIds: originIds } : {}
2797
2978
  }
2798
2979
  });
2799
2980
  else if (options.continue !== false) await this._chatRecoveryEngine().scheduleRecovery({
@@ -2807,7 +2988,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
2807
2988
  ...snapshot ? {
2808
2989
  lastBody: snapshot.lastBody ?? null,
2809
2990
  lastClientTools: snapshot.lastClientTools ?? null
2810
- } : {}
2991
+ } : {},
2992
+ ...originIds ? { originMessageIds: originIds } : {}
2811
2993
  }
2812
2994
  });
2813
2995
  else await this._updateChatRecoveryIncident(incident.incidentId, "skipped", "continue_disabled");
@@ -2830,9 +3012,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
2830
3012
  return {};
2831
3013
  }
2832
3014
  async _chatRecoveryContinue(data) {
2833
- await this._dispatchChatRecovery("_chatRecoveryContinue", data, (onTurnStarted) => this._chatRecoveryContinueDetached(data, onTurnStarted));
3015
+ await this._dispatchChatRecovery("_chatRecoveryContinue", data, (onTurnStarted) => this._chatRecoveryOriginIdsScope.run(data?.originMessageIds, () => this._chatRecoveryContinueDetached(data, onTurnStarted)));
2834
3016
  }
2835
3017
  async _chatRecoveryContinueDetached(data, onTurnStarted) {
3018
+ if (await this._chatRecoveryEngine().isRecoveryCancelled(data?.incidentId)) return;
2836
3019
  const previousRootRequestId = this._activeChatRecoveryRootRequestId;
2837
3020
  this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
2838
3021
  try {
@@ -2854,11 +3037,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
2854
3037
  }
2855
3038
  this._applyRecoveredRequestContext(data);
2856
3039
  onTurnStarted?.();
3040
+ this._takeRecoveryReschedule(data?.incidentId);
2857
3041
  const result = await this.continueLastTurn();
3042
+ if (result.status !== "completed" && this._takeRecoveryReschedule(data?.incidentId)) return;
2858
3043
  await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
2859
- } catch (error) {
2860
- if (await this._handleRecoveryOom("_chatRecoveryContinue", data, error)) return;
2861
- throw error;
2862
3044
  } finally {
2863
3045
  this._activeChatRecoveryRootRequestId = previousRootRequestId;
2864
3046
  await this._reconcileOwnStaleAgentToolChildRuns();
@@ -2881,27 +3063,90 @@ var AIChatAgent = class AIChatAgent extends Agent {
2881
3063
  * schedule payload carries no `recoveredRequestId`.
2882
3064
  *
2883
3065
  * Returns `"exhausted"` when the budget was spent (terminal UX already
2884
- * delivered), or `"scheduled"` when a continuation was queued.
3066
+ * delivered), `"scheduled"` when a continuation was queued, or `"declined"`
3067
+ * / `"failed"` when `onChatRecovery` opted out or threw — the caller then
3068
+ * delivers the ordinary terminal error.
2885
3069
  */
2886
3070
  async _routeStallToBoundedRecovery(input) {
2887
3071
  const recoveryRootRequestId = this._activeChatRecoveryRootRequestId ?? input.requestId;
3072
+ const originIds = this._originMessageIdsFor(input.requestId);
2888
3073
  const latestUserMessageId = [...this.messages].reverse().find((m) => m.role === "user")?.id ?? null;
3074
+ const leaf = this.messages[this.messages.length - 1];
3075
+ const lostPartialUserId = !input.continuation && input.partialParts.length === 0 && leaf?.role === "user" && leaf.id === latestUserMessageId ? latestUserMessageId : void 0;
3076
+ const recoveryKind = lostPartialUserId ? "retry" : "continue";
2889
3077
  const { incident, config, exhausted } = await this._beginChatRecoveryIncident({
2890
3078
  requestId: input.requestId,
2891
3079
  recoveryRootRequestId,
2892
3080
  latestUserMessageId,
2893
- recoveryKind: "continue"
3081
+ recoveryKind,
3082
+ trigger: "stalled"
2894
3083
  });
3084
+ const partialText = input.partialParts.filter((p) => p.type === "text").map((p) => p.text).join("");
2895
3085
  if (exhausted) {
2896
- const partialText = input.partialParts.filter((p) => p.type === "text").map((p) => p.text).join("");
2897
3086
  await this._exhaustChatRecovery(incident, config, {
2898
3087
  text: partialText,
2899
3088
  parts: input.partialParts
2900
3089
  }, input.streamId, incident.firstSeenAt);
2901
3090
  return "exhausted";
2902
3091
  }
3092
+ const liveTurn = this._liveChatRecoveryTurns.get(input.requestId);
3093
+ let options;
3094
+ try {
3095
+ options = await this.onChatRecovery({
3096
+ incidentId: incident.incidentId,
3097
+ recoveryRootRequestId,
3098
+ attempt: incident.attempt,
3099
+ maxAttempts: incident.maxAttempts,
3100
+ recoveryKind,
3101
+ streamId: input.streamId,
3102
+ requestId: input.requestId,
3103
+ partialText,
3104
+ partialParts: input.partialParts,
3105
+ recoveryData: liveTurn?.recoveryData ?? null,
3106
+ messages: [...this.messages],
3107
+ lastBody: this._lastBody,
3108
+ lastClientTools: this._lastClientTools,
3109
+ createdAt: liveTurn?.createdAt ?? incident.firstSeenAt
3110
+ }) ?? {};
3111
+ } catch (error) {
3112
+ console.error("[AIChatAgent] onChatRecovery threw during stream recovery:", error);
3113
+ await this._updateChatRecoveryIncident(incident.incidentId, "failed", error instanceof Error ? error.message : String(error));
3114
+ return "failed";
3115
+ }
3116
+ const discardPartial = options.persist === false && !partialHasSettledToolResults(input.partialParts);
3117
+ if (discardPartial) await input.discardPartial();
3118
+ if (options.continue === false) {
3119
+ await this._updateChatRecoveryIncident(incident.incidentId, "skipped", "continue_disabled");
3120
+ return "declined";
3121
+ }
3122
+ const leafAfterDiscard = this.messages[this.messages.length - 1];
3123
+ const retryUserId = lostPartialUserId ?? (discardPartial && !input.continuation && leafAfterDiscard?.role === "user" ? leafAfterDiscard.id : void 0);
3124
+ const retries = await this._chatRecoveryEngine().recordTransientRetry(incident.incidentId);
3125
+ const delaySeconds = input.backoff ? chatRecoveryBackoffSeconds(retries) : void 0;
3126
+ const reason = this._activeChatRecoveryRootRequestId !== void 0 ? "chained_retry" : void 0;
3127
+ if (retryUserId) {
3128
+ await this._chatRecoveryEngine().scheduleRecovery({
3129
+ incident,
3130
+ delaySeconds,
3131
+ reason,
3132
+ recoveryKind: "retry",
3133
+ callback: "_chatRecoveryRetry",
3134
+ data: {
3135
+ targetUserId: retryUserId,
3136
+ originalRequestId: recoveryRootRequestId,
3137
+ incidentId: incident.incidentId,
3138
+ lastBody: this._lastBody ?? null,
3139
+ lastClientTools: this._lastClientTools ?? null,
3140
+ ...originIds ? { originMessageIds: originIds } : {}
3141
+ }
3142
+ });
3143
+ this._rescheduledRecoveryIncidents.add(incident.incidentId);
3144
+ return "scheduled";
3145
+ }
2903
3146
  await this._chatRecoveryEngine().scheduleRecovery({
2904
3147
  incident,
3148
+ delaySeconds,
3149
+ reason,
2905
3150
  recoveryKind: "continue",
2906
3151
  callback: "_chatRecoveryContinue",
2907
3152
  data: {
@@ -2909,11 +3154,29 @@ var AIChatAgent = class AIChatAgent extends Agent {
2909
3154
  originalRequestId: recoveryRootRequestId,
2910
3155
  incidentId: incident.incidentId,
2911
3156
  lastBody: this._lastBody ?? null,
2912
- lastClientTools: this._lastClientTools ?? null
3157
+ lastClientTools: this._lastClientTools ?? null,
3158
+ ...originIds ? { originMessageIds: originIds } : {}
2913
3159
  }
2914
3160
  });
3161
+ this._rescheduledRecoveryIncidents.add(incident.incidentId);
2915
3162
  return "scheduled";
2916
3163
  }
3164
+ _takeRecoveryReschedule(incidentId) {
3165
+ return incidentId !== void 0 && this._rescheduledRecoveryIncidents.delete(incidentId);
3166
+ }
3167
+ /**
3168
+ * {@link _routeStallToBoundedRecovery} for the stream `catch`: a routing
3169
+ * failure (e.g. a rejected incident write) degrades to `"failed"`, so the
3170
+ * caller still delivers its terminal error frame.
3171
+ */
3172
+ async _routeStreamInterruption(input) {
3173
+ try {
3174
+ return await this._routeStallToBoundedRecovery(input);
3175
+ } catch (error) {
3176
+ console.error("[AIChatAgent] routing a stream interruption into recovery failed; delivering the terminal error", error);
3177
+ return "failed";
3178
+ }
3179
+ }
2917
3180
  /**
2918
3181
  * Reschedule a recovery callback that timed out waiting for stable state,
2919
3182
  * consuming one attempt. Returns `true` if rescheduled, `false` if the
@@ -3027,57 +3290,16 @@ var AIChatAgent = class AIChatAgent extends Agent {
3027
3290
  reason: "stable_timeout"
3028
3291
  });
3029
3292
  }
3030
- /**
3031
- * Apply the tight OOM-retry budget to a recovery error (#1825). Symmetric with
3032
- * `@cloudflare/think`'s `_handleRecoveryOom`: invoked from the narrow OOM-only
3033
- * `catch` in `_chatRecoveryContinue` / `_chatRecoveryRetry`, i.e. for an OOM
3034
- * that is *thrown* out of a recovery turn (e.g. storage/SQL ops rejecting with
3035
- * the memory-limit-reset message after an isolate reset). An OOM caught inside
3036
- * `continueLastTurn` that surfaces as a returned `error` result is NOT routed
3037
- * here — that turn was already terminalized, so re-driving it would be wasteful
3038
- * and risk a second terminal signal.
3039
- *
3040
- * The reliable terminator is the begin-path (`evaluateChatRecoveryIncident`),
3041
- * which seals once `oomAttempts` exceeds the budget, running before the
3042
- * memory-heavy turn in the low-memory window where writes succeed. This method
3043
- * persists `oomAttempts` (small writes) for the begin path to act on, and
3044
- * schedules a delayed re-run while under budget.
3045
- *
3046
- * Returns `true` when the error was an OOM and this method owns the outcome
3047
- * (rescheduled a delayed re-run while under budget, or terminalized with
3048
- * `reason="out_of_memory"` once over budget / untrackable / bookkeeping
3049
- * failed), `false` for non-OOM errors so the caller proceeds normally.
3050
- */
3051
- async _handleRecoveryOom(callback, data, error) {
3052
- if (!isDurableObjectMemoryLimitReset(error)) return false;
3053
- let decision = "exhausted";
3054
- try {
3055
- decision = await this._chatRecoveryEngine().recordOomAndDecide({
3056
- incidentId: data?.incidentId,
3057
- callback,
3058
- data,
3059
- maxOomRetries: this._resolveChatRecoveryConfig().maxOomRetries
3060
- });
3061
- } catch (bookkeepingError) {
3062
- console.error("[AIChatAgent] failed to record OOM recovery attempt; terminalizing", bookkeepingError);
3063
- decision = "exhausted";
3064
- }
3065
- if (decision === "exhausted") await this._chatRecoveryEngine().exhaustRecoveryGiveUp({
3066
- callback,
3067
- data,
3068
- reason: "out_of_memory"
3069
- });
3070
- return true;
3071
- }
3072
3293
  _shouldRetryRecoveredPreStreamTurn(snapshot, streamId, partial) {
3073
3294
  if (!snapshot || snapshot.continuation || !snapshot.latestUserMessageId || streamId || partial.text || partial.parts.length > 0) return false;
3074
3295
  const lastMessage = this.messages.length > 0 ? this.messages[this.messages.length - 1] : null;
3075
3296
  return lastMessage?.role === "user" && lastMessage.id === snapshot.latestUserMessageId;
3076
3297
  }
3077
3298
  async _chatRecoveryRetry(data) {
3078
- await this._dispatchChatRecovery("_chatRecoveryRetry", data, (onTurnStarted) => this._chatRecoveryRetryDetached(data, onTurnStarted));
3299
+ await this._dispatchChatRecovery("_chatRecoveryRetry", data, (onTurnStarted) => this._chatRecoveryOriginIdsScope.run(data?.originMessageIds, () => this._chatRecoveryRetryDetached(data, onTurnStarted)));
3079
3300
  }
3080
3301
  async _chatRecoveryRetryDetached(data, onTurnStarted) {
3302
+ if (await this._chatRecoveryEngine().isRecoveryCancelled(data?.incidentId)) return;
3081
3303
  const previousRootRequestId = this._activeChatRecoveryRootRequestId;
3082
3304
  this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
3083
3305
  try {
@@ -3103,11 +3325,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
3103
3325
  }
3104
3326
  this._applyRecoveredRequestContext(data);
3105
3327
  onTurnStarted?.();
3328
+ this._takeRecoveryReschedule(data?.incidentId);
3106
3329
  const result = await this._retryLastUserTurn(this._lastClientTools, this._lastBody);
3330
+ if (result.status !== "completed" && this._takeRecoveryReschedule(data?.incidentId)) return;
3107
3331
  await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
3108
- } catch (error) {
3109
- if (await this._handleRecoveryOom("_chatRecoveryRetry", data, error)) return;
3110
- throw error;
3111
3332
  } finally {
3112
3333
  this._activeChatRecoveryRootRequestId = previousRootRequestId;
3113
3334
  await this._reconcileOwnStaleAgentToolChildRuns();
@@ -3134,7 +3355,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3134
3355
  const mergedMessages = reconcileMessages(messages, priorMessages, (msg) => this._sanitizeMessageForPersistence(msg));
3135
3356
  const toWrite = [];
3136
3357
  for (const message of mergedMessages) {
3137
- const resolved = resolveToolMergeId(this._sanitizeMessageForPersistence(message), priorMessages);
3358
+ const resolved = this._sanitizeMessageForPersistence(message);
3138
3359
  const prior = priorById.get(resolved.id);
3139
3360
  if (prior && JSON.stringify(prior) === JSON.stringify(resolved)) continue;
3140
3361
  toWrite.push(resolved);
@@ -3469,6 +3690,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3469
3690
  streamCompleted.value = false;
3470
3691
  let continuationTextResumed = false;
3471
3692
  let continuationReasoningResumed = false;
3693
+ let finishReason;
3472
3694
  if (abortSignal && !abortSignal.aborted) abortSignal.addEventListener("abort", () => {
3473
3695
  reader.cancel().catch(() => {});
3474
3696
  }, { once: true });
@@ -3530,7 +3752,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
3530
3752
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
3531
3753
  ...continuation && { continuation: true }
3532
3754
  });
3533
- return { status: "completed" };
3755
+ return {
3756
+ status: "completed",
3757
+ finishReason
3758
+ };
3534
3759
  }
3535
3760
  const lines = decoder.decode(value).split("\n");
3536
3761
  for (const line of lines) if (line.startsWith("data: ") && line !== "data: [DONE]") try {
@@ -3562,7 +3787,25 @@ var AIChatAgent = class AIChatAgent extends Agent {
3562
3787
  skipServerApply = continuationReasoningResumed;
3563
3788
  }
3564
3789
  }
3565
- if (isReplayChunk(message.parts, data)) continue;
3790
+ if (isReplayChunk(message.parts, data)) {
3791
+ if (applyLateToolInput(message.parts, data) && this._approvalPersistedMessageId !== null && this._streamingMessage) await this.#session.upsertMessage(this._sanitizeMessageForPersistence({
3792
+ ...this._streamingMessage,
3793
+ parts: [...this._streamingMessage.parts]
3794
+ }));
3795
+ for (const forwarded of lateToolInputForwardChunks(message.parts, data)) {
3796
+ const chunkBody = JSON.stringify(forwarded);
3797
+ const seq = await this._storeStreamChunk(streamId, chunkBody);
3798
+ this._broadcastChatMessage({
3799
+ body: chunkBody,
3800
+ done: false,
3801
+ id,
3802
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
3803
+ ...seq !== void 0 && { seq },
3804
+ ...continuation && { continuation: true }
3805
+ });
3806
+ }
3807
+ continue;
3808
+ }
3566
3809
  const handled = skipServerApply ? true : applyChunkToParts(message.parts, data);
3567
3810
  if (data.type === "tool-approval-request" && this._streamingMessage) {
3568
3811
  const snapshot = {
@@ -3643,6 +3886,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3643
3886
  done: true,
3644
3887
  id,
3645
3888
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
3889
+ outcome: "error",
3646
3890
  ...continuation && { continuation: true }
3647
3891
  });
3648
3892
  return {
@@ -3665,37 +3909,43 @@ var AIChatAgent = class AIChatAgent extends Agent {
3665
3909
  }
3666
3910
  }
3667
3911
  if (data.type === "finish" && "finishReason" in data) {
3668
- const { finishReason, ...rest } = data;
3912
+ const { finishReason: chunkFinishReason, ...rest } = data;
3913
+ finishReason = chunkFinishReason;
3669
3914
  eventToSend = {
3670
3915
  ...rest,
3671
3916
  type: "finish",
3672
- messageMetadata: { finishReason }
3917
+ messageMetadata: { finishReason: chunkFinishReason }
3673
3918
  };
3674
3919
  }
3675
3920
  const chunkBody = JSON.stringify(eventToSend);
3676
- await this._storeStreamChunk(streamId, chunkBody);
3921
+ const seq = await this._storeStreamChunk(streamId, chunkBody);
3677
3922
  this._broadcastChatMessage({
3678
3923
  body: chunkBody,
3679
3924
  done: false,
3680
3925
  id,
3681
3926
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
3927
+ ...seq !== void 0 && { seq },
3682
3928
  ...continuation && { continuation: true }
3683
3929
  });
3684
3930
  } catch (_error) {}
3685
3931
  }
3686
3932
  if (!streamCompleted.value) {
3687
- this._finishStream(streamId);
3933
+ this._finishStream(streamId, "aborted");
3688
3934
  streamCompleted.value = true;
3689
3935
  this._broadcastChatMessage({
3690
3936
  body: "",
3691
3937
  done: true,
3692
3938
  id,
3693
3939
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
3940
+ outcome: "aborted",
3694
3941
  ...continuation && { continuation: true }
3695
3942
  });
3696
3943
  return { status: "aborted" };
3697
3944
  }
3698
- return { status: "completed" };
3945
+ return {
3946
+ status: "completed",
3947
+ finishReason
3948
+ };
3699
3949
  }
3700
3950
  async _sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation = false, abortSignal) {
3701
3951
  let textPart;
@@ -3765,13 +4015,14 @@ var AIChatAgent = class AIChatAgent extends Agent {
3765
4015
  type: "text-end",
3766
4016
  id
3767
4017
  }, continuation);
3768
- this._finishStream(streamId);
4018
+ this._finishStream(streamId, "aborted");
3769
4019
  streamCompleted.value = true;
3770
4020
  this._broadcastChatMessage({
3771
4021
  body: "",
3772
4022
  done: true,
3773
4023
  id,
3774
4024
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
4025
+ outcome: "aborted",
3775
4026
  ...continuation && { continuation: true }
3776
4027
  });
3777
4028
  return { status: "aborted" };
@@ -3795,7 +4046,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3795
4046
  return this._findAndUpdateToolPart(toolCallId, "_applyToolApproval", update.matchStates, update.apply);
3796
4047
  }
3797
4048
  async _reply(id, response, excludeBroadcastIds = [], options = {}) {
3798
- const { continuation = false, chatMessageId } = options;
4049
+ const { continuation = false, chatMessageId, onStreamStart } = options;
3799
4050
  const abortSignal = chatMessageId ? this._abortRegistry.getExistingSignal(chatMessageId) : void 0;
3800
4051
  return this.keepAliveWhile(() => this._tryCatchChat(async () => {
3801
4052
  if (!response.body) {
@@ -3810,39 +4061,64 @@ var AIChatAgent = class AIChatAgent extends Agent {
3810
4061
  this._activateDeferredAutoContinuation();
3811
4062
  return { status: "completed" };
3812
4063
  }
3813
- const message = this._createStreamingAssistantMessage(continuation);
3814
- const streamId = this._startStream(id, {
3815
- messageId: message.id,
3816
- continuation
3817
- });
3818
4064
  const reader = response.body.getReader();
4065
+ let message;
4066
+ let streamId;
4067
+ try {
4068
+ message = this._createStreamingAssistantMessage(continuation);
4069
+ streamId = this._startStream(id, {
4070
+ messageId: message.id,
4071
+ continuation
4072
+ });
4073
+ } catch (error) {
4074
+ reader.cancel(error).catch(() => {});
4075
+ throw error;
4076
+ }
3819
4077
  this._streamingMessage = message;
3820
4078
  const isSSE = (response.headers.get("content-type") || "").includes("text/event-stream");
3821
4079
  const streamCompleted = { value: false };
3822
4080
  let streamResult = { status: "completed" };
3823
4081
  let earlyPersistedId = null;
3824
4082
  let stallRouted = false;
4083
+ let discardPartial = false;
3825
4084
  this._streamingTurnActive = true;
4085
+ this._heldTerminalFrames.set(id, []);
4086
+ let persisted = false;
4087
+ onStreamStart?.();
3826
4088
  try {
3827
4089
  try {
3828
4090
  if (isSSE) streamResult = await this._streamSSEReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
3829
4091
  else streamResult = await this._sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
3830
4092
  } catch (error) {
3831
- if (error instanceof ChatStreamStalledError && !streamCompleted.value) {
4093
+ if (!streamCompleted.value && (error instanceof ChatStreamStalledError || !abortSignal?.aborted && isRecoverableStreamReadError(error))) {
3832
4094
  const targetAssistantId = message.parts.length > 0 ? message.id : void 0;
3833
- const outcome = await this._routeStallToBoundedRecovery({
4095
+ const outcome = await this._routeStreamInterruption({
3834
4096
  requestId: id,
3835
4097
  streamId,
3836
4098
  partialParts: message.parts,
3837
- targetAssistantId
4099
+ targetAssistantId,
4100
+ continuation,
4101
+ backoff: !(error instanceof ChatStreamStalledError),
4102
+ discardPartial: async () => {
4103
+ discardPartial = true;
4104
+ const earlyId = this._approvalPersistedMessageId;
4105
+ if (!earlyId || continuation) return;
4106
+ this._approvalPersistedMessageId = null;
4107
+ await this._deleteMessagesByIds([earlyId]);
4108
+ this._broadcastChatMessage({
4109
+ messages: this._messagesForClientSync(),
4110
+ type: MessageType.CF_AGENT_CHAT_MESSAGES
4111
+ });
4112
+ }
3838
4113
  });
3839
4114
  if (outcome === "scheduled") {
3840
- this._completeStream(streamId);
4115
+ this._completeStream(streamId, "recovering");
3841
4116
  this._broadcastChatMessage({
3842
4117
  body: "",
3843
4118
  done: true,
3844
4119
  id,
3845
4120
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
4121
+ outcome: "recovering",
3846
4122
  ...continuation && { continuation: true }
3847
4123
  });
3848
4124
  streamResult = { status: "aborted" };
@@ -3890,7 +4166,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3890
4166
  messageId: earlyPersistedId ?? message.id,
3891
4167
  discard: !this._agentToolRunsByRequestId.get(id)
3892
4168
  } : null;
3893
- if (message.parts.length > 0) if (earlyPersistedId) {
4169
+ if (message.parts.length > 0 && !discardPartial) if (earlyPersistedId) {
3894
4170
  const persistedMessage = {
3895
4171
  ...message,
3896
4172
  id: earlyPersistedId
@@ -3910,6 +4186,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
3910
4186
  } else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
3911
4187
  this.#pendingCutover = null;
3912
4188
  this._resumableStream.finalizePending();
4189
+ persisted = true;
4190
+ this._releaseTerminalFrames(id);
3913
4191
  this._pendingChatResponseResults.push({
3914
4192
  message,
3915
4193
  requestId: id,
@@ -3921,7 +4199,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
3921
4199
  } finally {
3922
4200
  this.#pendingCutover = null;
3923
4201
  this._resumableStream.finalizePending();
3924
- this._onStreamingTurnFinalized();
4202
+ this._releaseTerminalFrames(id, persisted ? void 0 : "Failed to save the response.");
4203
+ this._onStreamingTurnFinalized(streamResult.finishReason);
3925
4204
  }
3926
4205
  }));
3927
4206
  }