@cloudflare/ai-chat 0.12.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -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, isDurableObjectMemoryLimitReset, 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 {
@@ -113,9 +125,25 @@ var AIChatAgent = class AIChatAgent extends Agent {
113
125
  continuation,
114
126
  messages: this.messages,
115
127
  lastBody: this._lastBody,
116
- lastClientTools: this._lastClientTools
128
+ lastClientTools: this._lastClientTools,
129
+ originMessageIds: this._originMessageIdsFor(requestId)
117
130
  });
118
- const wrap = (data) => wrapChatFiberSnapshot("__cfAIChatFiberSnapshot", snapshot, data);
131
+ const liveTurn = {
132
+ createdAt: Date.now(),
133
+ recoveryData: null
134
+ };
135
+ const wrap = (data) => {
136
+ liveTurn.recoveryData = data;
137
+ return wrapChatFiberSnapshot("__cfAIChatFiberSnapshot", snapshot, data);
138
+ };
139
+ this._liveChatRecoveryTurns.set(requestId, liveTurn);
140
+ try {
141
+ return await this._runWrappedChatRecoveryFiber(requestId, continuation, wrap, fn);
142
+ } finally {
143
+ if (this._liveChatRecoveryTurns.get(requestId) === liveTurn) this._liveChatRecoveryTurns.delete(requestId);
144
+ }
145
+ }
146
+ async _runWrappedChatRecoveryFiber(requestId, continuation, wrap, fn) {
119
147
  if (this.parentPath.length > 0) return this._runFiberWithStashWrapper(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => fn(), {
120
148
  initialSnapshot: wrap(null),
121
149
  wrapStash: wrap
@@ -154,16 +182,35 @@ var AIChatAgent = class AIChatAgent extends Agent {
154
182
  }
155
183
  }
156
184
  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
- });
185
+ if (this._agentToolForwarders.size > 0 || this._agentToolLiveSequences.size > 0 || this._agentToolTerminalOnlyRuns.size > 0) {
186
+ const chunkRunId = interceptAgentToolBroadcast(msg, {
187
+ forwarders: this._agentToolForwarders,
188
+ liveSequences: this._agentToolLiveSequences,
189
+ lastErrors: this._agentToolLastErrors,
190
+ onError: (runId, body) => this._recordAgentToolStreamError(runId, body),
191
+ responseType: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
192
+ runForRequest: (requestId) => this._agentToolRunForRequest(requestId),
193
+ terminalOnlyRuns: this._agentToolTerminalOnlyRuns
194
+ });
195
+ if (chunkRunId !== null && this._agentToolTerminalOnlyRuns.has(chunkRunId)) return;
196
+ }
164
197
  super.broadcast(msg, without);
165
198
  }
166
199
  /**
200
+ * Durably record a run's stream error on its still-open row, so a stale-row
201
+ * reconcile after an eviction (before the finalizer seals `error`) still
202
+ * sees the failure. Leaves `status` to the finalizer / reconcile.
203
+ */
204
+ _recordAgentToolStreamError(runId, body) {
205
+ try {
206
+ this.sql`
207
+ update cf_ai_chat_agent_tool_runs
208
+ set error_message = ${body}
209
+ where run_id = ${runId} and status = 'running'
210
+ `;
211
+ } catch {}
212
+ }
213
+ /**
167
214
  * Resolve the agent-tool run whose turn owns a request id, or null when the
168
215
  * request is not an agent-tool turn. Falls back to the persisted run row
169
216
  * (written when the turn starts, see `_registerAgentToolTurn`) so
@@ -172,11 +219,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
172
219
  _agentToolRunForRequest(requestId) {
173
220
  const cached = this._agentToolRunsByRequestId.get(requestId);
174
221
  if (cached !== void 0) return cached;
175
- const runId = this.sql`
176
- select run_id from cf_ai_chat_agent_tool_runs
222
+ const rows = this.sql`
223
+ select run_id, event_delivery from cf_ai_chat_agent_tool_runs
177
224
  where request_id = ${requestId} and status in ('starting', 'running')
178
225
  limit 1
179
- `?.[0]?.run_id ?? null;
226
+ `;
227
+ const runId = rows?.[0]?.run_id ?? null;
228
+ if (runId && rows?.[0]?.event_delivery === "terminal") this._agentToolTerminalOnlyRuns.add(runId);
180
229
  this._agentToolRunsByRequestId.set(requestId, runId);
181
230
  return runId;
182
231
  }
@@ -210,17 +259,21 @@ var AIChatAgent = class AIChatAgent extends Agent {
210
259
  */
211
260
  _rebindAgentToolChildRunRequestId(requestId) {
212
261
  let runId;
262
+ let terminalOnly = false;
213
263
  try {
214
- runId = this.sql`
215
- select run_id from cf_ai_chat_agent_tool_runs
264
+ const rows = this.sql`
265
+ select run_id, event_delivery from cf_ai_chat_agent_tool_runs
216
266
  where status in ('starting', 'running')
217
267
  order by started_at desc
218
268
  limit 1
219
- `?.[0]?.run_id;
269
+ `;
270
+ runId = rows?.[0]?.run_id;
271
+ terminalOnly = rows?.[0]?.event_delivery === "terminal";
220
272
  } catch {
221
273
  return;
222
274
  }
223
275
  if (!runId) return;
276
+ if (terminalOnly) this._agentToolTerminalOnlyRuns.add(runId);
224
277
  this._agentToolRunsByRequestId.set(requestId, runId);
225
278
  this.sql`
226
279
  update cf_ai_chat_agent_tool_runs
@@ -230,6 +283,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
230
283
  }
231
284
  constructor(ctx, env) {
232
285
  super(ctx, env);
286
+ this._chatRecoveryOriginIdsScope = new AsyncLocalStorage();
233
287
  this.sessions = new Sessions();
234
288
  this.hydrationByteBudget = 32 * 1024 * 1024;
235
289
  this.#session = this.sessions.session();
@@ -255,6 +309,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
255
309
  this._agentToolLastErrors = /* @__PURE__ */ new Map();
256
310
  this._agentToolPreTurnAssistantIds = /* @__PURE__ */ new Map();
257
311
  this._agentToolLiveSequences = /* @__PURE__ */ new Map();
312
+ this._agentToolTerminalOnlyRuns = /* @__PURE__ */ new Set();
258
313
  this._agentToolRunsByRequestId = /* @__PURE__ */ new Map();
259
314
  this._autoContinuation = new AutoContinuationController({
260
315
  continuation: this._continuation,
@@ -271,12 +326,16 @@ var AIChatAgent = class AIChatAgent extends Agent {
271
326
  this.messageConcurrency = "queue";
272
327
  this.waitForMcpConnections = { timeout: 1e4 };
273
328
  this._liveChatTurnClosures = /* @__PURE__ */ new Map();
329
+ this._liveChatRecoveryTurns = /* @__PURE__ */ new Map();
274
330
  this.messages = [];
331
+ this._requestOriginMessageIds = /* @__PURE__ */ new Map();
332
+ this._heldTerminalFrames = /* @__PURE__ */ new Map();
275
333
  this._agentToolProgressEmitterInstance = null;
276
334
  this._inSerializedDetachedDeliverySlot = false;
277
335
  this._inFlightDetachedNotifications = /* @__PURE__ */ new Set();
278
336
  this._progressSeed = null;
279
337
  this._agentToolStreamProgress = new AgentToolStreamProgressThrottle();
338
+ this._rescheduledRecoveryIncidents = /* @__PURE__ */ new Set();
280
339
  this.#pendingCutover = null;
281
340
  this.lifecycle.use(this.sessions);
282
341
  this.lifecycle.use(this.streams);
@@ -352,10 +411,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
352
411
  const requestClientTools = clientTools?.length ? clientTools : void 0;
353
412
  const requestBody = Object.keys(customBody).length > 0 ? customBody : void 0;
354
413
  const epoch = this._turnQueue.generation;
414
+ const requestOriginIds = originMessageIds(messages);
415
+ if (requestOriginIds) this._requestOriginMessageIds.set(chatMessageId, requestOriginIds);
355
416
  const concurrencyDecision = this._getSubmitConcurrencyDecision(requestTrigger);
356
417
  if (concurrencyDecision.action === "drop") {
357
418
  this._rollbackDroppedSubmit(connection);
358
419
  this._completeSkippedRequest(connection, chatMessageId);
420
+ this._requestOriginMessageIds.delete(chatMessageId);
359
421
  return;
360
422
  }
361
423
  await withAgentSpan(this, "clear_previous_chat_state", "interaction", {
@@ -445,7 +507,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
445
507
  "cloudflare.agents.turn.trigger": requestTrigger,
446
508
  "cloudflare.agents.turn.admission": "queue",
447
509
  "cloudflare.agents.turn.generation": epoch
448
- }, () => this._repairInterruptedToolsBeforeTurn());
510
+ }, () => this._repairInterruptedToolsBeforeTurn({ continuation: false }));
449
511
  const response = await this.onChatMessage(async (_finishResult) => {}, {
450
512
  requestId: chatMessageId,
451
513
  abortSignal,
@@ -466,8 +528,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
466
528
  body: "No response was generated by the agent.",
467
529
  done: true,
468
530
  id: chatMessageId,
469
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
470
- }, [connection.id]);
531
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
532
+ outcome: "completed"
533
+ });
471
534
  }
472
535
  } finally {
473
536
  this._abortRegistry.remove(chatMessageId);
@@ -483,6 +546,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
483
546
  });
484
547
  } finally {
485
548
  this._settlePreStreamTurn(chatMessageId);
549
+ this._requestOriginMessageIds.delete(chatMessageId);
486
550
  }
487
551
  return;
488
552
  }
@@ -508,6 +572,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
508
572
  }
509
573
  if (event.type === "cancel") {
510
574
  this._abortRegistry.cancel(event.id);
575
+ await this._cancelScheduledRecovery(event.id);
511
576
  this._emit("message:cancel", { requestId: event.id });
512
577
  return;
513
578
  }
@@ -589,6 +654,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
589
654
  addColumnIfNotExists("alter table cf_ai_chat_agent_tool_runs add column summary text");
590
655
  addColumnIfNotExists("alter table cf_ai_chat_agent_tool_runs add column progress_json text");
591
656
  addColumnIfNotExists("alter table cf_ai_chat_agent_tool_runs add column last_signal_at integer");
657
+ addColumnIfNotExists("alter table cf_ai_chat_agent_tool_runs add column event_delivery text");
592
658
  this.sql`create index if not exists idx_ai_chat_agent_tool_request_id
593
659
  on cf_ai_chat_agent_tool_runs(request_id)`;
594
660
  this.sql`create table if not exists cf_ai_chat_agent_tool_milestones (
@@ -660,7 +726,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
660
726
  pendingResumeConnections: this._pendingResumeConnections,
661
727
  pendingChatTerminal: () => this._pendingChatTerminal(),
662
728
  persistOrphanedStream: (streamId) => this._persistOrphanedStream(streamId),
663
- isConnectionPresent: (connectionId) => this._isConnectionPresent(connectionId)
729
+ isConnectionPresent: (connectionId) => this._isConnectionPresent(connectionId),
730
+ holdsTerminalFrames: (requestId) => this._heldTerminalFrames.has(requestId)
664
731
  });
665
732
  }
666
733
  /**
@@ -683,7 +750,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
683
750
  }
684
751
  /** @internal Delegate to _resumableStream */
685
752
  _startStream(requestId, options = {}) {
686
- const streamId = this._resumableStream.start(requestId, options);
753
+ const originIds = this._requestOriginMessageIds.get(requestId) ?? this._activeChatRecoveryOriginIds;
754
+ const streamId = this._resumableStream.start(requestId, {
755
+ ...options,
756
+ ...originIds && { originMessageIds: originIds }
757
+ });
687
758
  this._preStream.flushOnStreamStart((c) => this._notifyStreamResuming(c));
688
759
  if (this._continuation.pending?.requestId === requestId) {
689
760
  this._continuation.activatePending();
@@ -693,9 +764,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
693
764
  return streamId;
694
765
  }
695
766
  /** @internal Delegate to _resumableStream */
696
- _completeStream(streamId) {
767
+ _completeStream(streamId, outcome) {
697
768
  const completedRequestId = this._resumableStream.activeRequestId;
698
- this._resumableStream.complete(streamId);
769
+ this._resumableStream.complete(streamId, outcome);
699
770
  this._afterStreamFinished(completedRequestId);
700
771
  }
701
772
  /**
@@ -703,9 +774,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
703
774
  * persists the message (`persistMessages` via `#pendingCutover`). `_reply`'s
704
775
  * finally settles it if no persist follows.
705
776
  */
706
- _finishStream(streamId) {
777
+ _finishStream(streamId, outcome) {
707
778
  const finishedRequestId = this._resumableStream.activeRequestId;
708
- this._resumableStream.finish(streamId);
779
+ this._resumableStream.finish(streamId, outcome);
709
780
  this._afterStreamFinished(finishedRequestId);
710
781
  }
711
782
  _afterStreamFinished(requestId) {
@@ -738,12 +809,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
738
809
  * per-chunk counter. Streaming deltas keep the buffer's own packing.
739
810
  */
740
811
  async _storeStreamChunk(streamId, body) {
741
- this._resumableStream.storeChunk(streamId, body);
812
+ const seq = this._resumableStream.storeChunk(streamId, body);
742
813
  let type;
743
814
  try {
744
815
  type = JSON.parse(body).type;
745
816
  } catch {}
746
817
  if (type === "tool-output-available" || type === "tool-output-error" || type === "tool-output-denied") this._resumableStream.flushBuffer();
818
+ return seq;
747
819
  }
748
820
  /** @internal Delegate to _resumableStream */
749
821
  _flushChunkBuffer() {
@@ -868,7 +940,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
868
940
  return {
869
941
  ...part,
870
942
  state: "output-error",
871
- errorText: "The tool call was interrupted before a result was recorded."
943
+ 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
944
  };
873
945
  }
874
946
  /**
@@ -904,11 +976,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
904
976
  * write, one broadcast), which also refreshes `this.messages`.
905
977
  * @internal
906
978
  */
907
- async _repairInterruptedToolsBeforeTurn() {
979
+ async _repairInterruptedToolsBeforeTurn(options) {
908
980
  const clientResolvable = this._clientResolvableToolNames();
909
981
  const repaired = repairInterruptedToolParts(this.messages, {
910
982
  repairPart: (part) => this.repairInterruptedToolPart(part),
911
- shouldRepair: (part) => !this._partAwaitsClientInteraction(part, clientResolvable)
983
+ shouldRepair: (part) => !this._partAwaitsClientInteraction(part, clientResolvable),
984
+ repairApprovalResponded: !options.continuation && !this._continuation.pending && !this._continuation.deferred
912
985
  });
913
986
  if (repaired.removedToolCalls === 0 && repaired.normalizedInputs === 0) return;
914
987
  await this.persistMessages(repaired.messages);
@@ -944,10 +1017,40 @@ var AIChatAgent = class AIChatAgent extends Agent {
944
1017
  `;
945
1018
  else this.sql`delete from cf_ai_chat_request_context where key = 'lastClientTools'`;
946
1019
  }
1020
+ _originMessageIdsFor(requestId) {
1021
+ return this._requestOriginMessageIds.get(requestId) ?? this._resumableStream.getOriginMessageIds(requestId) ?? this._activeChatRecoveryOriginIds;
1022
+ }
1023
+ _withOriginMessageIds(message) {
1024
+ if (message.type !== MessageType.CF_AGENT_USE_CHAT_RESPONSE || !(message.done || message.error)) return message;
1025
+ return withOriginMessageIds(message, this._originMessageIdsFor(message.id));
1026
+ }
947
1027
  _broadcastChatMessage(message, exclude) {
1028
+ message = this._withOriginMessageIds(message);
1029
+ if (message.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && (message.done || message.error)) {
1030
+ const held = this._heldTerminalFrames.get(message.id);
1031
+ if (held) {
1032
+ held.push({
1033
+ message,
1034
+ exclude
1035
+ });
1036
+ return;
1037
+ }
1038
+ }
948
1039
  const allExclusions = [...exclude || [], ...this._pendingResumeConnections];
949
1040
  this.broadcast(JSON.stringify(message), allExclusions);
950
1041
  }
1042
+ _releaseTerminalFrames(id, errorText) {
1043
+ const held = this._heldTerminalFrames.get(id);
1044
+ this._heldTerminalFrames.delete(id);
1045
+ if (!held) return;
1046
+ const failed = errorText !== void 0 && !held.some(({ message }) => message.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && message.error);
1047
+ for (const { message, exclude } of held) this._broadcastChatMessage(failed && message.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE ? {
1048
+ ...message,
1049
+ body: errorText,
1050
+ error: true,
1051
+ ...message.done && { outcome: "error" }
1052
+ } : message, exclude);
1053
+ }
951
1054
  /**
952
1055
  * Broadcasts a text event for non-SSE responses.
953
1056
  * This ensures plain text responses follow the AI SDK v5 stream protocol.
@@ -958,12 +1061,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
958
1061
  */
959
1062
  async _broadcastTextEvent(streamId, event, continuation) {
960
1063
  const body = JSON.stringify(event);
961
- await this._storeStreamChunk(streamId, body);
1064
+ const seq = await this._storeStreamChunk(streamId, body);
962
1065
  this._broadcastChatMessage({
963
1066
  body,
964
1067
  done: false,
965
1068
  id: event.id,
966
1069
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1070
+ ...seq !== void 0 && { seq },
967
1071
  ...continuation && { continuation: true }
968
1072
  });
969
1073
  }
@@ -1062,33 +1166,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
1062
1166
  * cache.
1063
1167
  */
1064
1168
  #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
- }
1169
+ this.#session.mirror({
1170
+ get: () => this.messages,
1171
+ set: (messages) => {
1172
+ this.messages = messages;
1173
+ },
1174
+ transform: (message) => this.#messageForCache(message)
1092
1175
  });
1093
1176
  }
1094
1177
  /**
@@ -1266,12 +1349,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
1266
1349
  } catch {}
1267
1350
  }
1268
1351
  _completeSkippedRequest(connection, requestId) {
1269
- this._sendDirectMessage(connection, {
1352
+ this._sendDirectMessage(connection, this._withOriginMessageIds({
1270
1353
  body: "",
1271
1354
  done: true,
1272
1355
  id: requestId,
1273
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
1274
- });
1356
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1357
+ outcome: "skipped"
1358
+ }));
1275
1359
  this._settlePreStreamTurn(requestId, { releaseParked: false });
1276
1360
  }
1277
1361
  /** Whether a connection with this id is still attached. */
@@ -1389,6 +1473,18 @@ var AIChatAgent = class AIChatAgent extends Agent {
1389
1473
  this._abortRegistry.cancel(requestId, reason);
1390
1474
  }
1391
1475
  /**
1476
+ * A cancel can land while the turn's recovery is waiting out its backoff,
1477
+ * with nothing in flight to abort: cancel the scheduled recovery instead,
1478
+ * so the queued callback bails when it fires.
1479
+ */
1480
+ async _cancelScheduledRecovery(requestId) {
1481
+ try {
1482
+ await this._chatRecoveryEngine().cancelScheduledRecovery(requestId);
1483
+ } catch (error) {
1484
+ console.error("[AIChatAgent] failed to cancel a scheduled chat recovery", error);
1485
+ }
1486
+ }
1487
+ /**
1392
1488
  * Abort every in-flight chat turn on this agent.
1393
1489
  *
1394
1490
  * Aborts all controllers in the registry and clears it. Used by
@@ -1529,8 +1625,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
1529
1625
  * continuation would never fire. A slow batch is re-checked here and simply
1530
1626
  * keeps holding (event-driven) until its remaining siblings answer.
1531
1627
  */
1532
- _onStreamingTurnFinalized() {
1628
+ _onStreamingTurnFinalized(finishReason) {
1533
1629
  this._streamingTurnActive = false;
1630
+ if (finishReason === "stop" && this._continuation.pending && !this._hasIncompleteToolBatch()) {
1631
+ this._clearPendingAutoContinuation(true);
1632
+ return;
1633
+ }
1534
1634
  this._autoContinuation.rearmForBatch();
1535
1635
  }
1536
1636
  /**
@@ -1581,8 +1681,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
1581
1681
  email: void 0
1582
1682
  }, async () => {
1583
1683
  const autoContinuationBody = async () => {
1684
+ let replying = false;
1584
1685
  try {
1585
- await this._repairInterruptedToolsBeforeTurn();
1686
+ await this._repairInterruptedToolsBeforeTurn({ continuation: true });
1586
1687
  const response = await this.onChatMessage(async (_finishResult) => {}, {
1587
1688
  requestId,
1588
1689
  abortSignal,
@@ -1593,7 +1694,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
1593
1694
  if (response) {
1594
1695
  if ((await this._reply(requestId, response, [], {
1595
1696
  continuation: true,
1596
- chatMessageId: requestId
1697
+ chatMessageId: requestId,
1698
+ onStreamStart: () => {
1699
+ replying = true;
1700
+ }
1597
1701
  })).status === "error") {
1598
1702
  this._clearAllAutoContinuationState(true);
1599
1703
  return;
@@ -1603,6 +1707,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
1603
1707
  this._clearPendingAutoContinuation(true);
1604
1708
  this._activateDeferredAutoContinuation();
1605
1709
  }
1710
+ } catch (error) {
1711
+ if (!replying && !abortSignal?.aborted && !isDurableObjectResetError(error)) await this._reportContinuationFailure(requestId, error);
1712
+ throw error;
1606
1713
  } finally {
1607
1714
  this._abortRegistry.remove(requestId);
1608
1715
  }
@@ -1623,6 +1730,33 @@ var AIChatAgent = class AIChatAgent extends Agent {
1623
1730
  });
1624
1731
  }
1625
1732
  /**
1733
+ * Report an auto-continuation that failed before it produced a response,
1734
+ * the way a stream error is reported: an error frame, a durable terminal
1735
+ * record, and `onChatResponse` with `status: "error"` for the assistant
1736
+ * message the continuation would have extended. Called inside the turn so
1737
+ * the response hook drains when the turn settles.
1738
+ */
1739
+ async _reportContinuationFailure(requestId, error) {
1740
+ const errorMessage = error instanceof Error ? error.message : String(error);
1741
+ this._broadcastChatMessage({
1742
+ body: errorMessage,
1743
+ done: true,
1744
+ error: true,
1745
+ id: requestId,
1746
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1747
+ continuation: true
1748
+ });
1749
+ const message = [...this.messages].reverse().find((candidate) => candidate.role === "assistant");
1750
+ if (message) this._pendingChatResponseResults.push({
1751
+ message,
1752
+ requestId,
1753
+ continuation: true,
1754
+ status: "error",
1755
+ error: errorMessage
1756
+ });
1757
+ else await this._recordChatTerminal(requestId, errorMessage);
1758
+ }
1759
+ /**
1626
1760
  * @returns Terminal status for the turn.
1627
1761
  */
1628
1762
  async _runProgrammaticChatTurn(requestId, clientTools, body, externalSignal) {
@@ -1640,7 +1774,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1640
1774
  const detachExternal = this._abortRegistry.linkExternal(requestId, externalSignal);
1641
1775
  try {
1642
1776
  const programmaticBody = async () => {
1643
- await this._repairInterruptedToolsBeforeTurn();
1777
+ await this._repairInterruptedToolsBeforeTurn({ continuation: false });
1644
1778
  const response = await this.onChatMessage(() => {}, {
1645
1779
  requestId,
1646
1780
  abortSignal,
@@ -1978,12 +2112,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
1978
2112
  const assistantIdsBeforeStart = new Set(this.messages.filter((message) => message.role === "assistant").map((message) => message.id));
1979
2113
  this.sql`
1980
2114
  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})
2115
+ (run_id, request_id, status, input_json, started_at, event_delivery)
2116
+ values (${options.runId}, null, 'running', ${AIChatAgent._stringifyAgentToolValue(input)}, ${startedAt}, ${options.eventDelivery === "terminal" ? "terminal" : null})
1983
2117
  `;
1984
2118
  this._agentToolAbortControllers.set(options.runId, controller);
1985
2119
  this._agentToolPreTurnAssistantIds.set(options.runId, assistantIdsBeforeStart);
1986
2120
  this._agentToolLiveSequences.set(options.runId, 0);
2121
+ if (options.eventDelivery === "terminal") this._agentToolTerminalOnlyRuns.add(options.runId);
1987
2122
  const abortFromParent = () => controller.abort(options.signal?.reason);
1988
2123
  if (options.signal?.aborted) abortFromParent();
1989
2124
  else options.signal?.addEventListener("abort", abortFromParent, { once: true });
@@ -2069,6 +2204,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2069
2204
  options.signal?.removeEventListener("abort", abortFromParent);
2070
2205
  this._agentToolAbortControllers.delete(options.runId);
2071
2206
  this._agentToolLiveSequences.delete(options.runId);
2207
+ this._agentToolTerminalOnlyRuns.delete(options.runId);
2072
2208
  this._agentToolProgressEmitterInstance?.forget(options.runId);
2073
2209
  if (this._agentToolAbortControllers.size === 0) this._agentToolRunsByRequestId.clear();
2074
2210
  else for (const [reqId, runId] of this._agentToolRunsByRequestId) if (runId === options.runId) this._agentToolRunsByRequestId.delete(reqId);
@@ -2120,6 +2256,19 @@ var AIChatAgent = class AIChatAgent extends Agent {
2120
2256
  async _reconcileStaleAgentToolChildRun(runId, row) {
2121
2257
  const recovery = await this._classifyAgentToolChildRecovery();
2122
2258
  if (recovery === "in-progress" || this._resumableStream.hasActiveStream()) return;
2259
+ if (row.error_message !== null) {
2260
+ const completedAt = Date.now();
2261
+ this.sql`
2262
+ update cf_ai_chat_agent_tool_runs
2263
+ set status = 'error', error_message = ${row.error_message},
2264
+ completed_at = ${completedAt}
2265
+ where run_id = ${runId}
2266
+ `;
2267
+ row.status = "error";
2268
+ row.completed_at = completedAt;
2269
+ this._closeAgentToolTailers(runId);
2270
+ return;
2271
+ }
2123
2272
  const messagesAfterStart = this._getAgentToolMessagesAfterStart(runId);
2124
2273
  if (recovery !== "failed" && messagesAfterStart.some((message) => message.role === "assistant")) {
2125
2274
  const input = AIChatAgent._parseAgentToolValue(row.input_json);
@@ -2193,10 +2342,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
2193
2342
  } catch {}
2194
2343
  }
2195
2344
  }
2196
- async inspectAgentToolRun(runId) {
2345
+ async inspectAgentToolRun(runId, options) {
2197
2346
  const row = this._getAgentToolRunRow(runId);
2198
2347
  if (!row) return null;
2199
- if (row.status === "running" && !this._agentToolAbortControllers.has(runId)) await this._reconcileStaleAgentToolChildRun(runId, row);
2348
+ if (options?.reconcile !== false && row.status === "running" && !this._agentToolAbortControllers.has(runId)) await this._reconcileStaleAgentToolChildRun(runId, row);
2200
2349
  const streamId = row.request_id ? this._getAgentToolStreamId(row.request_id) : void 0;
2201
2350
  const messagesAfterStart = this._getAgentToolMessagesAfterStart(runId);
2202
2351
  const input = AIChatAgent._parseAgentToolValue(row.input_json);
@@ -2253,8 +2402,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
2253
2402
  let lastEmitted = options?.afterSequence ?? -1;
2254
2403
  const emit = (chunk) => {
2255
2404
  if (closed) return;
2256
- if (chunk.sequence <= lastEmitted) return;
2257
- lastEmitted = chunk.sequence;
2405
+ if (!isPositionlessAgentToolChunk(chunk)) {
2406
+ if (chunk.sequence <= lastEmitted) return;
2407
+ lastEmitted = chunk.sequence;
2408
+ }
2258
2409
  try {
2259
2410
  controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
2260
2411
  } catch {
@@ -2287,6 +2438,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2287
2438
  return;
2288
2439
  }
2289
2440
  options?.signal?.addEventListener("abort", onAbort, { once: true });
2441
+ const seeded = this._seedAgentToolLiveSequence(runId);
2290
2442
  const forwarders = this._agentToolForwarders.get(runId) ?? /* @__PURE__ */ new Set();
2291
2443
  forwarders.add(forward);
2292
2444
  this._agentToolForwarders.set(runId, forwarders);
@@ -2302,10 +2454,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
2302
2454
  pending.length = 0;
2303
2455
  const inspection = await this.inspectAgentToolRun(runId);
2304
2456
  if (!inspection || inspection.status !== "running") {
2457
+ if (seeded) this._agentToolLiveSequences.delete(runId);
2305
2458
  close();
2306
2459
  return;
2307
2460
  }
2308
- if (lastEmitted > (options?.afterSequence ?? -1)) this._agentToolLiveSequences.set(runId, lastEmitted + 1);
2309
2461
  } catch (error) {
2310
2462
  closed = true;
2311
2463
  detach();
@@ -2332,6 +2484,23 @@ var AIChatAgent = class AIChatAgent extends Agent {
2332
2484
  _getAgentToolStreamId(requestId) {
2333
2485
  return this._resumableStream.latestStreamInfoForRequest(requestId)?.id;
2334
2486
  }
2487
+ /**
2488
+ * After this DO restarts, `_agentToolLiveSequences` is cold while the stored
2489
+ * backlog sits at N, and a chat-recovery resume re-attaches via
2490
+ * `tailAgentToolRun` without re-running `startAgentToolRun` (which seeds the
2491
+ * counter). Unseeded, the broadcast snoop numbers the recovered turn's chunks
2492
+ * from 0 and the tail's high-water dedupe drops them. Seeds only a running
2493
+ * run, so a terminal one doesn't re-heat the broadcast idle-guard; a warm
2494
+ * counter is authoritative. Returns whether it seeded.
2495
+ */
2496
+ _seedAgentToolLiveSequence(runId) {
2497
+ if (this._agentToolLiveSequences.has(runId)) return false;
2498
+ this._flushChunkBuffer();
2499
+ const row = this._getAgentToolRunRow(runId);
2500
+ if (!row?.request_id || row.status !== "running") return false;
2501
+ this._agentToolLiveSequences.set(runId, this._getAgentToolStoredChunks(row.request_id).length);
2502
+ return true;
2503
+ }
2335
2504
  _getAgentToolStoredChunks(requestId, afterSequence = -1) {
2336
2505
  const streamId = this._getAgentToolStreamId(requestId);
2337
2506
  if (!streamId) return [];
@@ -2351,6 +2520,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2351
2520
  this._agentToolClosers.delete(runId);
2352
2521
  }
2353
2522
  this._agentToolForwarders.delete(runId);
2523
+ if (!this._agentToolAbortControllers.has(runId)) this._agentToolTerminalOnlyRuns.delete(runId);
2354
2524
  }
2355
2525
  static _stringifyAgentToolValue(value) {
2356
2526
  if (value === void 0) return null;
@@ -2471,7 +2641,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2471
2641
  const abortSignal = this._abortRegistry.getSignal(requestId);
2472
2642
  const detachExternal = this._abortRegistry.linkExternal(requestId, options?.signal);
2473
2643
  try {
2474
- await this._repairInterruptedToolsBeforeTurn();
2644
+ await this._repairInterruptedToolsBeforeTurn({ continuation: true });
2475
2645
  const response = await this.onChatMessage(() => {}, {
2476
2646
  requestId,
2477
2647
  abortSignal,
@@ -2589,6 +2759,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2589
2759
  now: () => Date.now(),
2590
2760
  sweepStaleIncidents: (now) => sweepStaleChatRecoveryIncidents(this.ctx.storage, now),
2591
2761
  getIncident: async (key) => await this.ctx.storage.get(key) ?? null,
2762
+ listActiveIncidents: async () => (await listActiveChatRecoveryIncidents(this.ctx.storage)).map(({ incident }) => incident),
2592
2763
  readProgress: () => this._chatRecoveryProgressMarker(),
2593
2764
  isAwaitingClientInteraction: () => this.hasPendingClientInteraction(),
2594
2765
  putIncident: (key, incident) => this.ctx.storage.put(key, incident),
@@ -2606,7 +2777,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2606
2777
  scheduleRecovery: (callback, data, reason, delaySeconds) => this._enqueueChatRecovery(callback, data, reason, delaySeconds),
2607
2778
  setRecovering: (active, requestId) => this._setChatRecovering(active, requestId),
2608
2779
  onShouldKeepRecoveringError: (error) => console.error("[AIChatAgent] chatRecovery shouldKeepRecovering hook threw", error),
2609
- exhaustChatRecovery: (incident, config, partial, streamId, createdAt) => this._exhaustChatRecovery(incident, config, partial, streamId, createdAt),
2780
+ exhaustChatRecovery: (incident, config, partial, streamId, createdAt, originMessageIds) => this._exhaustChatRecovery(incident, config, partial, streamId, createdAt, originMessageIds),
2610
2781
  resolveRecoveryStream: (requestId) => this._resolveAIChatRecoveryStream(requestId),
2611
2782
  getPartialStreamText: (streamId) => this._getPartialStreamText(streamId),
2612
2783
  activeChatRecoveryRootRequestId: () => this._activeChatRecoveryRootRequestId,
@@ -2619,7 +2790,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2619
2790
  async _updateChatRecoveryIncident(incidentId, status, reason) {
2620
2791
  return this._chatRecoveryEngine().updateIncident(incidentId, status, reason);
2621
2792
  }
2622
- async _exhaustChatRecovery(incident, config, partial, streamId, createdAt) {
2793
+ async _exhaustChatRecovery(incident, config, partial, streamId, createdAt, originMessageIds) {
2623
2794
  await runChatRecoveryExhaustion({
2624
2795
  incident,
2625
2796
  config,
@@ -2632,14 +2803,16 @@ var AIChatAgent = class AIChatAgent extends Agent {
2632
2803
  onExhausted: config.onExhausted,
2633
2804
  onError: (error) => console.error("[AIChatAgent] chatRecovery onExhausted hook threw", error),
2634
2805
  terminalize: async (ctx) => {
2806
+ const messageIds = this._originMessageIdsFor(ctx.requestId) ?? originMessageIds;
2635
2807
  this._broadcastChatMessage({
2636
2808
  body: ctx.terminalMessage,
2637
2809
  done: true,
2638
2810
  error: true,
2639
2811
  id: ctx.requestId,
2640
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
2812
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
2813
+ ...messageIds ? { messageIds } : {}
2641
2814
  });
2642
- await this._recordChatTerminal(ctx.requestId, ctx.terminalMessage);
2815
+ await this._recordChatTerminal(ctx.requestId, ctx.terminalMessage, messageIds);
2643
2816
  await this._setChatRecovering(false);
2644
2817
  }
2645
2818
  });
@@ -2650,8 +2823,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
2650
2823
  * until a later turn supersedes it (`_clearChatTerminal`); a single record is
2651
2824
  * sufficient because only the most recent terminal is relevant.
2652
2825
  */
2653
- async _recordChatTerminal(requestId, body) {
2654
- await recordChatTerminal(this.ctx.storage, requestId, body);
2826
+ async _recordChatTerminal(requestId, body, messageIds = this._originMessageIdsFor(requestId)) {
2827
+ await recordChatTerminal(this.ctx.storage, requestId, body, messageIds);
2655
2828
  }
2656
2829
  /** Clear the durable terminal record once a later turn supersedes it (#1645). */
2657
2830
  async _clearChatTerminal() {
@@ -2769,6 +2942,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2769
2942
  */
2770
2943
  async _dispatchRecoveredChatTurn(input) {
2771
2944
  const { incident, options, snapshot, recoveryRootRequestId } = input;
2945
+ const originIds = this._originMessageIdsFor(input.requestId) ?? snapshot?.originMessageIds;
2772
2946
  const leaf = this.messages.length > 0 ? this.messages[this.messages.length - 1] : void 0;
2773
2947
  const lostPartialUserId = snapshot?.continuation === false && snapshot.latestUserMessageId && leaf?.role === "user" && leaf.id === snapshot.latestUserMessageId ? snapshot.latestUserMessageId : void 0;
2774
2948
  const targetId = input.detail.shouldRetryPreStream || lostPartialUserId !== void 0 ? void 0 : this._findLastAssistantMessage()?.id;
@@ -2781,7 +2955,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
2781
2955
  originalRequestId: recoveryRootRequestId,
2782
2956
  incidentId: incident.incidentId,
2783
2957
  lastBody: snapshot?.lastBody ?? null,
2784
- lastClientTools: snapshot?.lastClientTools ?? null
2958
+ lastClientTools: snapshot?.lastClientTools ?? null,
2959
+ ...originIds ? { originMessageIds: originIds } : {}
2785
2960
  }
2786
2961
  });
2787
2962
  else if (lostPartialUserId !== void 0 && options.continue !== false) await this._chatRecoveryEngine().scheduleRecovery({
@@ -2793,7 +2968,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
2793
2968
  originalRequestId: recoveryRootRequestId,
2794
2969
  incidentId: incident.incidentId,
2795
2970
  lastBody: snapshot?.lastBody ?? null,
2796
- lastClientTools: snapshot?.lastClientTools ?? null
2971
+ lastClientTools: snapshot?.lastClientTools ?? null,
2972
+ ...originIds ? { originMessageIds: originIds } : {}
2797
2973
  }
2798
2974
  });
2799
2975
  else if (options.continue !== false) await this._chatRecoveryEngine().scheduleRecovery({
@@ -2807,7 +2983,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
2807
2983
  ...snapshot ? {
2808
2984
  lastBody: snapshot.lastBody ?? null,
2809
2985
  lastClientTools: snapshot.lastClientTools ?? null
2810
- } : {}
2986
+ } : {},
2987
+ ...originIds ? { originMessageIds: originIds } : {}
2811
2988
  }
2812
2989
  });
2813
2990
  else await this._updateChatRecoveryIncident(incident.incidentId, "skipped", "continue_disabled");
@@ -2830,9 +3007,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
2830
3007
  return {};
2831
3008
  }
2832
3009
  async _chatRecoveryContinue(data) {
2833
- await this._dispatchChatRecovery("_chatRecoveryContinue", data, (onTurnStarted) => this._chatRecoveryContinueDetached(data, onTurnStarted));
3010
+ await this._dispatchChatRecovery("_chatRecoveryContinue", data, (onTurnStarted) => this._chatRecoveryOriginIdsScope.run(data?.originMessageIds, () => this._chatRecoveryContinueDetached(data, onTurnStarted)));
2834
3011
  }
2835
3012
  async _chatRecoveryContinueDetached(data, onTurnStarted) {
3013
+ if (await this._chatRecoveryEngine().isRecoveryCancelled(data?.incidentId)) return;
2836
3014
  const previousRootRequestId = this._activeChatRecoveryRootRequestId;
2837
3015
  this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
2838
3016
  try {
@@ -2854,7 +3032,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
2854
3032
  }
2855
3033
  this._applyRecoveredRequestContext(data);
2856
3034
  onTurnStarted?.();
3035
+ this._takeRecoveryReschedule(data?.incidentId);
2857
3036
  const result = await this.continueLastTurn();
3037
+ if (result.status !== "completed" && this._takeRecoveryReschedule(data?.incidentId)) return;
2858
3038
  await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
2859
3039
  } catch (error) {
2860
3040
  if (await this._handleRecoveryOom("_chatRecoveryContinue", data, error)) return;
@@ -2881,27 +3061,89 @@ var AIChatAgent = class AIChatAgent extends Agent {
2881
3061
  * schedule payload carries no `recoveredRequestId`.
2882
3062
  *
2883
3063
  * Returns `"exhausted"` when the budget was spent (terminal UX already
2884
- * delivered), or `"scheduled"` when a continuation was queued.
3064
+ * delivered), `"scheduled"` when a continuation was queued, or `"declined"`
3065
+ * / `"failed"` when `onChatRecovery` opted out or threw — the caller then
3066
+ * delivers the ordinary terminal error.
2885
3067
  */
2886
3068
  async _routeStallToBoundedRecovery(input) {
2887
3069
  const recoveryRootRequestId = this._activeChatRecoveryRootRequestId ?? input.requestId;
3070
+ const originIds = this._originMessageIdsFor(input.requestId);
2888
3071
  const latestUserMessageId = [...this.messages].reverse().find((m) => m.role === "user")?.id ?? null;
3072
+ const leaf = this.messages[this.messages.length - 1];
3073
+ const lostPartialUserId = !input.continuation && input.partialParts.length === 0 && leaf?.role === "user" && leaf.id === latestUserMessageId ? latestUserMessageId : void 0;
3074
+ const recoveryKind = lostPartialUserId ? "retry" : "continue";
2889
3075
  const { incident, config, exhausted } = await this._beginChatRecoveryIncident({
2890
3076
  requestId: input.requestId,
2891
3077
  recoveryRootRequestId,
2892
3078
  latestUserMessageId,
2893
- recoveryKind: "continue"
3079
+ recoveryKind
2894
3080
  });
3081
+ const partialText = input.partialParts.filter((p) => p.type === "text").map((p) => p.text).join("");
2895
3082
  if (exhausted) {
2896
- const partialText = input.partialParts.filter((p) => p.type === "text").map((p) => p.text).join("");
2897
3083
  await this._exhaustChatRecovery(incident, config, {
2898
3084
  text: partialText,
2899
3085
  parts: input.partialParts
2900
3086
  }, input.streamId, incident.firstSeenAt);
2901
3087
  return "exhausted";
2902
3088
  }
3089
+ const liveTurn = this._liveChatRecoveryTurns.get(input.requestId);
3090
+ let options;
3091
+ try {
3092
+ options = await this.onChatRecovery({
3093
+ incidentId: incident.incidentId,
3094
+ recoveryRootRequestId,
3095
+ attempt: incident.attempt,
3096
+ maxAttempts: incident.maxAttempts,
3097
+ recoveryKind,
3098
+ streamId: input.streamId,
3099
+ requestId: input.requestId,
3100
+ partialText,
3101
+ partialParts: input.partialParts,
3102
+ recoveryData: liveTurn?.recoveryData ?? null,
3103
+ messages: [...this.messages],
3104
+ lastBody: this._lastBody,
3105
+ lastClientTools: this._lastClientTools,
3106
+ createdAt: liveTurn?.createdAt ?? incident.firstSeenAt
3107
+ }) ?? {};
3108
+ } catch (error) {
3109
+ console.error("[AIChatAgent] onChatRecovery threw during stream recovery:", error);
3110
+ await this._updateChatRecoveryIncident(incident.incidentId, "failed", error instanceof Error ? error.message : String(error));
3111
+ return "failed";
3112
+ }
3113
+ const discardPartial = options.persist === false && !partialHasSettledToolResults(input.partialParts);
3114
+ if (discardPartial) await input.discardPartial();
3115
+ if (options.continue === false) {
3116
+ await this._updateChatRecoveryIncident(incident.incidentId, "skipped", "continue_disabled");
3117
+ return "declined";
3118
+ }
3119
+ const leafAfterDiscard = this.messages[this.messages.length - 1];
3120
+ const retryUserId = lostPartialUserId ?? (discardPartial && !input.continuation && leafAfterDiscard?.role === "user" ? leafAfterDiscard.id : void 0);
3121
+ const retries = await this._chatRecoveryEngine().recordTransientRetry(incident.incidentId);
3122
+ const delaySeconds = input.backoff ? chatRecoveryBackoffSeconds(retries) : void 0;
3123
+ const reason = this._activeChatRecoveryRootRequestId !== void 0 ? "chained_retry" : void 0;
3124
+ if (retryUserId) {
3125
+ await this._chatRecoveryEngine().scheduleRecovery({
3126
+ incident,
3127
+ delaySeconds,
3128
+ reason,
3129
+ recoveryKind: "retry",
3130
+ callback: "_chatRecoveryRetry",
3131
+ data: {
3132
+ targetUserId: retryUserId,
3133
+ originalRequestId: recoveryRootRequestId,
3134
+ incidentId: incident.incidentId,
3135
+ lastBody: this._lastBody ?? null,
3136
+ lastClientTools: this._lastClientTools ?? null,
3137
+ ...originIds ? { originMessageIds: originIds } : {}
3138
+ }
3139
+ });
3140
+ this._rescheduledRecoveryIncidents.add(incident.incidentId);
3141
+ return "scheduled";
3142
+ }
2903
3143
  await this._chatRecoveryEngine().scheduleRecovery({
2904
3144
  incident,
3145
+ delaySeconds,
3146
+ reason,
2905
3147
  recoveryKind: "continue",
2906
3148
  callback: "_chatRecoveryContinue",
2907
3149
  data: {
@@ -2909,11 +3151,29 @@ var AIChatAgent = class AIChatAgent extends Agent {
2909
3151
  originalRequestId: recoveryRootRequestId,
2910
3152
  incidentId: incident.incidentId,
2911
3153
  lastBody: this._lastBody ?? null,
2912
- lastClientTools: this._lastClientTools ?? null
3154
+ lastClientTools: this._lastClientTools ?? null,
3155
+ ...originIds ? { originMessageIds: originIds } : {}
2913
3156
  }
2914
3157
  });
3158
+ this._rescheduledRecoveryIncidents.add(incident.incidentId);
2915
3159
  return "scheduled";
2916
3160
  }
3161
+ _takeRecoveryReschedule(incidentId) {
3162
+ return incidentId !== void 0 && this._rescheduledRecoveryIncidents.delete(incidentId);
3163
+ }
3164
+ /**
3165
+ * {@link _routeStallToBoundedRecovery} for the stream `catch`: a routing
3166
+ * failure (e.g. a rejected incident write) degrades to `"failed"`, so the
3167
+ * caller still delivers its terminal error frame.
3168
+ */
3169
+ async _routeStreamInterruption(input) {
3170
+ try {
3171
+ return await this._routeStallToBoundedRecovery(input);
3172
+ } catch (error) {
3173
+ console.error("[AIChatAgent] routing a stream interruption into recovery failed; delivering the terminal error", error);
3174
+ return "failed";
3175
+ }
3176
+ }
2917
3177
  /**
2918
3178
  * Reschedule a recovery callback that timed out waiting for stable state,
2919
3179
  * consuming one attempt. Returns `true` if rescheduled, `false` if the
@@ -3075,9 +3335,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
3075
3335
  return lastMessage?.role === "user" && lastMessage.id === snapshot.latestUserMessageId;
3076
3336
  }
3077
3337
  async _chatRecoveryRetry(data) {
3078
- await this._dispatchChatRecovery("_chatRecoveryRetry", data, (onTurnStarted) => this._chatRecoveryRetryDetached(data, onTurnStarted));
3338
+ await this._dispatchChatRecovery("_chatRecoveryRetry", data, (onTurnStarted) => this._chatRecoveryOriginIdsScope.run(data?.originMessageIds, () => this._chatRecoveryRetryDetached(data, onTurnStarted)));
3079
3339
  }
3080
3340
  async _chatRecoveryRetryDetached(data, onTurnStarted) {
3341
+ if (await this._chatRecoveryEngine().isRecoveryCancelled(data?.incidentId)) return;
3081
3342
  const previousRootRequestId = this._activeChatRecoveryRootRequestId;
3082
3343
  this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
3083
3344
  try {
@@ -3103,7 +3364,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
3103
3364
  }
3104
3365
  this._applyRecoveredRequestContext(data);
3105
3366
  onTurnStarted?.();
3367
+ this._takeRecoveryReschedule(data?.incidentId);
3106
3368
  const result = await this._retryLastUserTurn(this._lastClientTools, this._lastBody);
3369
+ if (result.status !== "completed" && this._takeRecoveryReschedule(data?.incidentId)) return;
3107
3370
  await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
3108
3371
  } catch (error) {
3109
3372
  if (await this._handleRecoveryOom("_chatRecoveryRetry", data, error)) return;
@@ -3134,7 +3397,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3134
3397
  const mergedMessages = reconcileMessages(messages, priorMessages, (msg) => this._sanitizeMessageForPersistence(msg));
3135
3398
  const toWrite = [];
3136
3399
  for (const message of mergedMessages) {
3137
- const resolved = resolveToolMergeId(this._sanitizeMessageForPersistence(message), priorMessages);
3400
+ const resolved = this._sanitizeMessageForPersistence(message);
3138
3401
  const prior = priorById.get(resolved.id);
3139
3402
  if (prior && JSON.stringify(prior) === JSON.stringify(resolved)) continue;
3140
3403
  toWrite.push(resolved);
@@ -3469,6 +3732,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3469
3732
  streamCompleted.value = false;
3470
3733
  let continuationTextResumed = false;
3471
3734
  let continuationReasoningResumed = false;
3735
+ let finishReason;
3472
3736
  if (abortSignal && !abortSignal.aborted) abortSignal.addEventListener("abort", () => {
3473
3737
  reader.cancel().catch(() => {});
3474
3738
  }, { once: true });
@@ -3530,7 +3794,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
3530
3794
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
3531
3795
  ...continuation && { continuation: true }
3532
3796
  });
3533
- return { status: "completed" };
3797
+ return {
3798
+ status: "completed",
3799
+ finishReason
3800
+ };
3534
3801
  }
3535
3802
  const lines = decoder.decode(value).split("\n");
3536
3803
  for (const line of lines) if (line.startsWith("data: ") && line !== "data: [DONE]") try {
@@ -3562,7 +3829,25 @@ var AIChatAgent = class AIChatAgent extends Agent {
3562
3829
  skipServerApply = continuationReasoningResumed;
3563
3830
  }
3564
3831
  }
3565
- if (isReplayChunk(message.parts, data)) continue;
3832
+ if (isReplayChunk(message.parts, data)) {
3833
+ if (applyLateToolInput(message.parts, data) && this._approvalPersistedMessageId !== null && this._streamingMessage) await this.#session.upsertMessage(this._sanitizeMessageForPersistence({
3834
+ ...this._streamingMessage,
3835
+ parts: [...this._streamingMessage.parts]
3836
+ }));
3837
+ for (const forwarded of lateToolInputForwardChunks(message.parts, data)) {
3838
+ const chunkBody = JSON.stringify(forwarded);
3839
+ const seq = await this._storeStreamChunk(streamId, chunkBody);
3840
+ this._broadcastChatMessage({
3841
+ body: chunkBody,
3842
+ done: false,
3843
+ id,
3844
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
3845
+ ...seq !== void 0 && { seq },
3846
+ ...continuation && { continuation: true }
3847
+ });
3848
+ }
3849
+ continue;
3850
+ }
3566
3851
  const handled = skipServerApply ? true : applyChunkToParts(message.parts, data);
3567
3852
  if (data.type === "tool-approval-request" && this._streamingMessage) {
3568
3853
  const snapshot = {
@@ -3643,6 +3928,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3643
3928
  done: true,
3644
3929
  id,
3645
3930
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
3931
+ outcome: "error",
3646
3932
  ...continuation && { continuation: true }
3647
3933
  });
3648
3934
  return {
@@ -3665,37 +3951,43 @@ var AIChatAgent = class AIChatAgent extends Agent {
3665
3951
  }
3666
3952
  }
3667
3953
  if (data.type === "finish" && "finishReason" in data) {
3668
- const { finishReason, ...rest } = data;
3954
+ const { finishReason: chunkFinishReason, ...rest } = data;
3955
+ finishReason = chunkFinishReason;
3669
3956
  eventToSend = {
3670
3957
  ...rest,
3671
3958
  type: "finish",
3672
- messageMetadata: { finishReason }
3959
+ messageMetadata: { finishReason: chunkFinishReason }
3673
3960
  };
3674
3961
  }
3675
3962
  const chunkBody = JSON.stringify(eventToSend);
3676
- await this._storeStreamChunk(streamId, chunkBody);
3963
+ const seq = await this._storeStreamChunk(streamId, chunkBody);
3677
3964
  this._broadcastChatMessage({
3678
3965
  body: chunkBody,
3679
3966
  done: false,
3680
3967
  id,
3681
3968
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
3969
+ ...seq !== void 0 && { seq },
3682
3970
  ...continuation && { continuation: true }
3683
3971
  });
3684
3972
  } catch (_error) {}
3685
3973
  }
3686
3974
  if (!streamCompleted.value) {
3687
- this._finishStream(streamId);
3975
+ this._finishStream(streamId, "aborted");
3688
3976
  streamCompleted.value = true;
3689
3977
  this._broadcastChatMessage({
3690
3978
  body: "",
3691
3979
  done: true,
3692
3980
  id,
3693
3981
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
3982
+ outcome: "aborted",
3694
3983
  ...continuation && { continuation: true }
3695
3984
  });
3696
3985
  return { status: "aborted" };
3697
3986
  }
3698
- return { status: "completed" };
3987
+ return {
3988
+ status: "completed",
3989
+ finishReason
3990
+ };
3699
3991
  }
3700
3992
  async _sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation = false, abortSignal) {
3701
3993
  let textPart;
@@ -3765,13 +4057,14 @@ var AIChatAgent = class AIChatAgent extends Agent {
3765
4057
  type: "text-end",
3766
4058
  id
3767
4059
  }, continuation);
3768
- this._finishStream(streamId);
4060
+ this._finishStream(streamId, "aborted");
3769
4061
  streamCompleted.value = true;
3770
4062
  this._broadcastChatMessage({
3771
4063
  body: "",
3772
4064
  done: true,
3773
4065
  id,
3774
4066
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
4067
+ outcome: "aborted",
3775
4068
  ...continuation && { continuation: true }
3776
4069
  });
3777
4070
  return { status: "aborted" };
@@ -3795,7 +4088,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3795
4088
  return this._findAndUpdateToolPart(toolCallId, "_applyToolApproval", update.matchStates, update.apply);
3796
4089
  }
3797
4090
  async _reply(id, response, excludeBroadcastIds = [], options = {}) {
3798
- const { continuation = false, chatMessageId } = options;
4091
+ const { continuation = false, chatMessageId, onStreamStart } = options;
3799
4092
  const abortSignal = chatMessageId ? this._abortRegistry.getExistingSignal(chatMessageId) : void 0;
3800
4093
  return this.keepAliveWhile(() => this._tryCatchChat(async () => {
3801
4094
  if (!response.body) {
@@ -3810,39 +4103,64 @@ var AIChatAgent = class AIChatAgent extends Agent {
3810
4103
  this._activateDeferredAutoContinuation();
3811
4104
  return { status: "completed" };
3812
4105
  }
3813
- const message = this._createStreamingAssistantMessage(continuation);
3814
- const streamId = this._startStream(id, {
3815
- messageId: message.id,
3816
- continuation
3817
- });
3818
4106
  const reader = response.body.getReader();
4107
+ let message;
4108
+ let streamId;
4109
+ try {
4110
+ message = this._createStreamingAssistantMessage(continuation);
4111
+ streamId = this._startStream(id, {
4112
+ messageId: message.id,
4113
+ continuation
4114
+ });
4115
+ } catch (error) {
4116
+ reader.cancel(error).catch(() => {});
4117
+ throw error;
4118
+ }
3819
4119
  this._streamingMessage = message;
3820
4120
  const isSSE = (response.headers.get("content-type") || "").includes("text/event-stream");
3821
4121
  const streamCompleted = { value: false };
3822
4122
  let streamResult = { status: "completed" };
3823
4123
  let earlyPersistedId = null;
3824
4124
  let stallRouted = false;
4125
+ let discardPartial = false;
3825
4126
  this._streamingTurnActive = true;
4127
+ this._heldTerminalFrames.set(id, []);
4128
+ let persisted = false;
4129
+ onStreamStart?.();
3826
4130
  try {
3827
4131
  try {
3828
4132
  if (isSSE) streamResult = await this._streamSSEReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
3829
4133
  else streamResult = await this._sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
3830
4134
  } catch (error) {
3831
- if (error instanceof ChatStreamStalledError && !streamCompleted.value) {
4135
+ if (!streamCompleted.value && (error instanceof ChatStreamStalledError || !abortSignal?.aborted && isRecoverableStreamReadError(error))) {
3832
4136
  const targetAssistantId = message.parts.length > 0 ? message.id : void 0;
3833
- const outcome = await this._routeStallToBoundedRecovery({
4137
+ const outcome = await this._routeStreamInterruption({
3834
4138
  requestId: id,
3835
4139
  streamId,
3836
4140
  partialParts: message.parts,
3837
- targetAssistantId
4141
+ targetAssistantId,
4142
+ continuation,
4143
+ backoff: !(error instanceof ChatStreamStalledError),
4144
+ discardPartial: async () => {
4145
+ discardPartial = true;
4146
+ const earlyId = this._approvalPersistedMessageId;
4147
+ if (!earlyId || continuation) return;
4148
+ this._approvalPersistedMessageId = null;
4149
+ await this._deleteMessagesByIds([earlyId]);
4150
+ this._broadcastChatMessage({
4151
+ messages: this._messagesForClientSync(),
4152
+ type: MessageType.CF_AGENT_CHAT_MESSAGES
4153
+ });
4154
+ }
3838
4155
  });
3839
4156
  if (outcome === "scheduled") {
3840
- this._completeStream(streamId);
4157
+ this._completeStream(streamId, "recovering");
3841
4158
  this._broadcastChatMessage({
3842
4159
  body: "",
3843
4160
  done: true,
3844
4161
  id,
3845
4162
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
4163
+ outcome: "recovering",
3846
4164
  ...continuation && { continuation: true }
3847
4165
  });
3848
4166
  streamResult = { status: "aborted" };
@@ -3890,7 +4208,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3890
4208
  messageId: earlyPersistedId ?? message.id,
3891
4209
  discard: !this._agentToolRunsByRequestId.get(id)
3892
4210
  } : null;
3893
- if (message.parts.length > 0) if (earlyPersistedId) {
4211
+ if (message.parts.length > 0 && !discardPartial) if (earlyPersistedId) {
3894
4212
  const persistedMessage = {
3895
4213
  ...message,
3896
4214
  id: earlyPersistedId
@@ -3910,6 +4228,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
3910
4228
  } else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
3911
4229
  this.#pendingCutover = null;
3912
4230
  this._resumableStream.finalizePending();
4231
+ persisted = true;
4232
+ this._releaseTerminalFrames(id);
3913
4233
  this._pendingChatResponseResults.push({
3914
4234
  message,
3915
4235
  requestId: id,
@@ -3921,7 +4241,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
3921
4241
  } finally {
3922
4242
  this.#pendingCutover = null;
3923
4243
  this._resumableStream.finalizePending();
3924
- this._onStreamingTurnFinalized();
4244
+ this._releaseTerminalFrames(id, persisted ? void 0 : "Failed to save the response.");
4245
+ this._onStreamingTurnFinalized(streamResult.finishReason);
3925
4246
  }
3926
4247
  }));
3927
4248
  }