@cloudflare/ai-chat 0.11.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,9 @@
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, ChatRecoveryEngine, ChatStreamStalledError, ContinuationState, MAX_BOUND_PARAMS, PreStreamTurns, ResumableStream, ResumeHandshake, STREAM_CLEANUP_DELAY_SECONDS, StreamProgressCreditThrottle, SubmitConcurrencyController, TIMED_OUT, TurnQueue, aiSdkRecoveryCodec, applyChunkToParts, awaitWithDeadline, buildChatRecoveringFrame, buildInClauseStrings, bumpChatRecoveryProgress, chatRecoverySchedulePolicy, classifyAgentToolChildRecovery, cleanupStreamBuffers, clearChatTerminal, clientResolvableToolNames, createChatFiberSnapshot, createToolsFromClientSchemas, drainInteractionApplies, enforceRowSizeLimit, hasIncompleteToolBatch, interceptAgentToolBroadcast, isReplayChunk, iterateWithStallWatchdog, listActiveChatRecoveryIncidents, parseProtocolMessage, partAwaitsClientInteraction, pendingChatTerminal, persistReconstructedOrphan, readChatRecoveryProgress, reconcileMessages, reconcileOrphanPartial, recordChatTerminal, repairInterruptedToolParts, resolveChatRecoveryConfig, resolveToolMergeId, runChatRecoveryExhaustion, sanitizeMessage, sendIfOpen, setChatRecovering, shouldCreditStreamProgress, 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";
6
+ import { Sessions } from "agents/sessions";
5
7
  import { nanoid } from "nanoid";
6
8
  //#region src/index.ts
7
9
  function withAgentSpan(host, operation, storagePhase, attributes, run) {
@@ -19,6 +21,14 @@ const PROVIDER_TOOL_OPAQUE_STRING_KEY_PREFIX = "encrypted";
19
21
  */
20
22
  const PROVIDER_TOOL_MAX_STRING_LENGTH = 500;
21
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
+ /**
22
32
  * Validates that a parsed message has the minimum required structure.
23
33
  * Returns false for messages that would cause runtime errors downstream
24
34
  * (e.g. in convertToModelMessages or the UI layer).
@@ -43,10 +53,70 @@ const agentToolChunkEncoder = new TextEncoder();
43
53
  * Extension of Agent with built-in chat capabilities
44
54
  * @template Env Environment type containing bindings
45
55
  */
56
+ /** Bounds for one window of the legacy lift: rows and their summed bytes. */
57
+ const LEGACY_LIFT_WINDOW_ROWS = 25;
58
+ const LEGACY_LIFT_WINDOW_BYTES = 4 * 1024 * 1024;
46
59
  var AIChatAgent = class AIChatAgent extends Agent {
60
+ get _activeChatRecoveryOriginIds() {
61
+ return this._chatRecoveryOriginIdsScope.getStore();
62
+ }
63
+ /** The default linear conversation handle. */
64
+ #session;
47
65
  static {
48
66
  this.MESSAGE_DEBOUNCE_MS = 750;
49
67
  }
68
+ /**
69
+ * Register the shared chat-turn Task definition (see
70
+ * `agents/chat` `createChatTurnTaskDefinition` for the turn logic): the
71
+ * host wires its protected internals through the hooks.
72
+ */
73
+ _registerChatTurnTaskDefinition() {
74
+ const chatFiberName = this.constructor.CHAT_FIBER_NAME;
75
+ this.tasks.register(chatFiberName, createChatTurnTaskDefinition({
76
+ definitionName: chatFiberName,
77
+ storage: this.ctx.storage,
78
+ getRunCreatedAt: async (runId) => (await this.tasks.get(runId))?.createdAt ?? null,
79
+ getLiveClosure: (nonce) => this._liveChatTurnClosures.get(nonce),
80
+ keepAliveWhile: (fn) => this.keepAliveWhile(fn),
81
+ withStash: (context, fn) => this._withFiberStash(context, fn),
82
+ handleRecovery: (ctx) => this._handleInternalFiberRecovery(ctx)
83
+ }));
84
+ }
85
+ /** Register the shared Tasks transport for recovery continuations. */
86
+ _registerChatRecoveryTaskDefinition() {
87
+ this.tasks.register(CHAT_RECOVERY_TASK_NAME, createChatRecoveryTaskDefinition({
88
+ _chatRecoveryContinue: (data) => this._chatRecoveryContinue(data),
89
+ _chatRecoveryRetry: (data) => this._chatRecoveryRetry(data)
90
+ }));
91
+ }
92
+ /**
93
+ * Run a queue-driven recovery callback to its model handoff and return;
94
+ * the turn continues as tracked alarm work, and a detached platform
95
+ * failure enqueues one replacement attempt through the same transport.
96
+ */
97
+ _dispatchChatRecovery(callback, data, detached) {
98
+ return dispatchChatRecoveryToHandoff({
99
+ detached,
100
+ track: (turn) => this.lifecycle.trackAlarmWork(turn),
101
+ redefer: (dedupeKey) => this._enqueueChatRecovery(callback, data ?? {}, "redefer", CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS, dedupeKey),
102
+ onDetachedError: (error) => console.error(`[AIChatAgent] ${callback} dispatch failed`, error)
103
+ });
104
+ }
105
+ /**
106
+ * Enqueue one recovery attempt on the shared Tasks transport. Tasks
107
+ * mirrors a routed dynamic agent's wake to the root's alarm; the run
108
+ * itself, and this continuation's replay, still execute here. `dedupeKey`
109
+ * keys a retried enqueue so it joins its own prior attempt instead of
110
+ * duplicating it — see {@link chatRecoveryTaskRunOptions}.
111
+ */
112
+ async _enqueueChatRecovery(callback, data, reason, delaySeconds, dedupeKey) {
113
+ const input = {
114
+ callback,
115
+ data,
116
+ delaySeconds
117
+ };
118
+ await this.tasks.__DO_NOT_USE_WILL_BREAK__enqueue(CHAT_RECOVERY_TASK_NAME, input, chatRecoveryTaskRunOptions(input, reason, dedupeKey));
119
+ }
50
120
  async _runChatRecoveryFiber(requestId, continuation, fn) {
51
121
  const snapshot = createChatFiberSnapshot({
52
122
  kind: "ai-chat-turn",
@@ -55,24 +125,92 @@ var AIChatAgent = class AIChatAgent extends Agent {
55
125
  continuation,
56
126
  messages: this.messages,
57
127
  lastBody: this._lastBody,
58
- lastClientTools: this._lastClientTools
128
+ lastClientTools: this._lastClientTools,
129
+ originMessageIds: this._originMessageIdsFor(requestId)
59
130
  });
60
- return this._runFiberWithStashWrapper(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => fn(), {
61
- initialSnapshot: wrapChatFiberSnapshot("__cfAIChatFiberSnapshot", snapshot, null),
62
- wrapStash: (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) {
147
+ if (this.parentPath.length > 0) return this._runFiberWithStashWrapper(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => fn(), {
148
+ initialSnapshot: wrap(null),
149
+ wrapStash: wrap
150
+ });
151
+ const nonce = nanoid();
152
+ let resolveOutcome;
153
+ let rejectOutcome;
154
+ const outcome = new Promise((resolve, reject) => {
155
+ resolveOutcome = resolve;
156
+ rejectOutcome = reject;
157
+ });
158
+ outcome.catch(() => {});
159
+ const ambient = __DO_NOT_USE_WILL_BREAK__agentContext.getStore();
160
+ this._liveChatTurnClosures.set(nonce, {
161
+ initial: wrap(null),
162
+ wrap,
163
+ run: ambient ? () => __DO_NOT_USE_WILL_BREAK__agentContext.run(ambient, fn) : fn,
164
+ settle: {
165
+ resolve: resolveOutcome,
166
+ reject: rejectOutcome
167
+ }
63
168
  });
169
+ try {
170
+ await this.tasks.__DO_NOT_USE_WILL_BREAK__runAttached(this.constructor.CHAT_FIBER_NAME, {
171
+ requestId,
172
+ continuation,
173
+ nonce
174
+ }, {
175
+ runId: `chat_${nonce}`,
176
+ retain: false,
177
+ metadata: { requestId }
178
+ });
179
+ return await outcome;
180
+ } finally {
181
+ this._liveChatTurnClosures.delete(nonce);
182
+ }
64
183
  }
65
184
  broadcast(msg, without) {
66
- if (this._agentToolForwarders.size > 0 || this._agentToolLiveSequences.size > 0) interceptAgentToolBroadcast(msg, {
67
- forwarders: this._agentToolForwarders,
68
- liveSequences: this._agentToolLiveSequences,
69
- lastErrors: this._agentToolLastErrors,
70
- responseType: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
71
- runForRequest: (requestId) => this._agentToolRunForRequest(requestId)
72
- });
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
+ }
73
197
  super.broadcast(msg, without);
74
198
  }
75
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
+ /**
76
214
  * Resolve the agent-tool run whose turn owns a request id, or null when the
77
215
  * request is not an agent-tool turn. Falls back to the persisted run row
78
216
  * (written when the turn starts, see `_registerAgentToolTurn`) so
@@ -81,11 +219,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
81
219
  _agentToolRunForRequest(requestId) {
82
220
  const cached = this._agentToolRunsByRequestId.get(requestId);
83
221
  if (cached !== void 0) return cached;
84
- const runId = this.sql`
85
- 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
86
224
  where request_id = ${requestId} and status in ('starting', 'running')
87
225
  limit 1
88
- `?.[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);
89
229
  this._agentToolRunsByRequestId.set(requestId, runId);
90
230
  return runId;
91
231
  }
@@ -119,17 +259,21 @@ var AIChatAgent = class AIChatAgent extends Agent {
119
259
  */
120
260
  _rebindAgentToolChildRunRequestId(requestId) {
121
261
  let runId;
262
+ let terminalOnly = false;
122
263
  try {
123
- runId = this.sql`
124
- 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
125
266
  where status in ('starting', 'running')
126
267
  order by started_at desc
127
268
  limit 1
128
- `?.[0]?.run_id;
269
+ `;
270
+ runId = rows?.[0]?.run_id;
271
+ terminalOnly = rows?.[0]?.event_delivery === "terminal";
129
272
  } catch {
130
273
  return;
131
274
  }
132
275
  if (!runId) return;
276
+ if (terminalOnly) this._agentToolTerminalOnlyRuns.add(runId);
133
277
  this._agentToolRunsByRequestId.set(requestId, runId);
134
278
  this.sql`
135
279
  update cf_ai_chat_agent_tool_runs
@@ -139,6 +283,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
139
283
  }
140
284
  constructor(ctx, env) {
141
285
  super(ctx, env);
286
+ this._chatRecoveryOriginIdsScope = new AsyncLocalStorage();
287
+ this.sessions = new Sessions();
288
+ this.hydrationByteBudget = 32 * 1024 * 1024;
289
+ this.#session = this.sessions.session();
290
+ this.streams = createChatStreams();
142
291
  this._streamingMessage = null;
143
292
  this._pendingChatResponseResults = [];
144
293
  this._insideResponseHook = false;
@@ -160,8 +309,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
160
309
  this._agentToolLastErrors = /* @__PURE__ */ new Map();
161
310
  this._agentToolPreTurnAssistantIds = /* @__PURE__ */ new Map();
162
311
  this._agentToolLiveSequences = /* @__PURE__ */ new Map();
312
+ this._agentToolTerminalOnlyRuns = /* @__PURE__ */ new Set();
163
313
  this._agentToolRunsByRequestId = /* @__PURE__ */ new Map();
164
- this._persistedMessageCache = /* @__PURE__ */ new Map();
165
314
  this._autoContinuation = new AutoContinuationController({
166
315
  continuation: this._continuation,
167
316
  generateRequestId: () => nanoid(),
@@ -176,19 +325,24 @@ var AIChatAgent = class AIChatAgent extends Agent {
176
325
  this.maxPersistedMessages = void 0;
177
326
  this.messageConcurrency = "queue";
178
327
  this.waitForMcpConnections = { timeout: 1e4 };
328
+ this._liveChatTurnClosures = /* @__PURE__ */ new Map();
329
+ this._liveChatRecoveryTurns = /* @__PURE__ */ new Map();
179
330
  this.messages = [];
180
- this._streamProgressCredit = new StreamProgressCreditThrottle();
331
+ this._requestOriginMessageIds = /* @__PURE__ */ new Map();
332
+ this._heldTerminalFrames = /* @__PURE__ */ new Map();
181
333
  this._agentToolProgressEmitterInstance = null;
182
334
  this._inSerializedDetachedDeliverySlot = false;
183
335
  this._inFlightDetachedNotifications = /* @__PURE__ */ new Set();
336
+ this._progressSeed = null;
184
337
  this._agentToolStreamProgress = new AgentToolStreamProgressThrottle();
338
+ this._rescheduledRecoveryIncidents = /* @__PURE__ */ new Set();
339
+ this.#pendingCutover = null;
340
+ this.lifecycle.use(this.sessions);
341
+ this.lifecycle.use(this.streams);
342
+ this._registerChatTurnTaskDefinition();
343
+ this._registerChatRecoveryTaskDefinition();
185
344
  withAgentSpan(this, "chat_initialization", "initialization", { "cloudflare.agents.component": "ai_chat" }, (update) => {
186
345
  withAgentSpan(this, "initialize_chat_storage", "initialization", { "cloudflare.agents.component": "ai_chat" }, () => {
187
- this.sql`create table if not exists cf_ai_chat_agent_messages (
188
- id text primary key,
189
- message text not null,
190
- created_at datetime default current_timestamp
191
- )`;
192
346
  this.sql`create table if not exists cf_ai_chat_request_context (
193
347
  key text primary key,
194
348
  value text not null
@@ -197,15 +351,22 @@ var AIChatAgent = class AIChatAgent extends Agent {
197
351
  });
198
352
  withAgentSpan(this, "restore_chat_request_context", "initialization", { "cloudflare.agents.component": "ai_chat" }, () => this._restoreRequestContext());
199
353
  withAgentSpan(this, "initialize_resumable_stream", "initialization", { "cloudflare.agents.component": "ai_chat" }, () => {
200
- this._resumableStream = new ResumableStream(this.sql.bind(this));
201
- });
202
- const rawMessages = withAgentSpan(this, "load_chat_messages", "initialization", { "cloudflare.agents.component": "ai_chat" }, () => this._loadMessagesFromDb());
203
- this.messages = autoTransformMessages(rawMessages);
204
- update({
205
- "cloudflare.agents.chat.messages.loaded": rawMessages.length,
206
- "cloudflare.agents.chat.active_stream.restored": this._resumableStream.hasActiveStream()
354
+ this._resumableStream = new ResumableStream(this.streams, this.sql.bind(this), { onProgress: (durable) => {
355
+ this.ctx.storage.put(CHAT_RECOVERY_PROGRESS_KEY, durable).catch(() => {});
356
+ } });
207
357
  });
358
+ update({ "cloudflare.agents.chat.active_stream.restored": this._resumableStream.hasActiveStream() });
208
359
  });
360
+ this.#subscribeToSessionChanges();
361
+ const _onStart = this.onStart.bind(this);
362
+ this.onStart = async (props) => {
363
+ await withAgentSpan(this, "load_chat_messages", "startup", { "cloudflare.agents.component": "ai_chat" }, async (update) => {
364
+ await this._migrateLegacyMessages();
365
+ await this._hydrateMessages();
366
+ update({ "cloudflare.agents.chat.messages.loaded": this.messages.length });
367
+ });
368
+ return _onStart(props);
369
+ };
209
370
  this._abortRegistry = new AbortRegistry();
210
371
  const _onConnect = this.onConnect.bind(this);
211
372
  this.onConnect = async (connection, ctx) => {
@@ -250,10 +411,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
250
411
  const requestClientTools = clientTools?.length ? clientTools : void 0;
251
412
  const requestBody = Object.keys(customBody).length > 0 ? customBody : void 0;
252
413
  const epoch = this._turnQueue.generation;
414
+ const requestOriginIds = originMessageIds(messages);
415
+ if (requestOriginIds) this._requestOriginMessageIds.set(chatMessageId, requestOriginIds);
253
416
  const concurrencyDecision = this._getSubmitConcurrencyDecision(requestTrigger);
254
417
  if (concurrencyDecision.action === "drop") {
255
418
  this._rollbackDroppedSubmit(connection);
256
419
  this._completeSkippedRequest(connection, chatMessageId);
420
+ this._requestOriginMessageIds.delete(chatMessageId);
257
421
  return;
258
422
  }
259
423
  await withAgentSpan(this, "clear_previous_chat_state", "interaction", {
@@ -343,7 +507,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
343
507
  "cloudflare.agents.turn.trigger": requestTrigger,
344
508
  "cloudflare.agents.turn.admission": "queue",
345
509
  "cloudflare.agents.turn.generation": epoch
346
- }, () => this._repairInterruptedToolsBeforeTurn());
510
+ }, () => this._repairInterruptedToolsBeforeTurn({ continuation: false }));
347
511
  const response = await this.onChatMessage(async (_finishResult) => {}, {
348
512
  requestId: chatMessageId,
349
513
  abortSignal,
@@ -364,8 +528,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
364
528
  body: "No response was generated by the agent.",
365
529
  done: true,
366
530
  id: chatMessageId,
367
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
368
- }, [connection.id]);
531
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
532
+ outcome: "completed"
533
+ });
369
534
  }
370
535
  } finally {
371
536
  this._abortRegistry.remove(chatMessageId);
@@ -381,12 +546,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
381
546
  });
382
547
  } finally {
383
548
  this._settlePreStreamTurn(chatMessageId);
549
+ this._requestOriginMessageIds.delete(chatMessageId);
384
550
  }
385
551
  return;
386
552
  }
387
553
  if (event.type === "clear") {
388
554
  this.resetTurnState();
389
- this.sql`delete from cf_ai_chat_agent_messages`;
555
+ await this.#session.clearMessages();
390
556
  await this._clearChatTerminal();
391
557
  this._resumableStream.clearAll();
392
558
  this._pendingResumeConnections.clear();
@@ -395,8 +561,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
395
561
  this._lastClientTools = void 0;
396
562
  this._lastBody = void 0;
397
563
  this._persistRequestContext();
398
- this._persistedMessageCache.clear();
399
- this.messages = [];
400
564
  this._broadcastChatMessage({ type: MessageType.CF_AGENT_CHAT_CLEAR }, [connection.id]);
401
565
  this._emit("message:clear");
402
566
  return;
@@ -408,6 +572,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
408
572
  }
409
573
  if (event.type === "cancel") {
410
574
  this._abortRegistry.cancel(event.id);
575
+ await this._cancelScheduledRecovery(event.id);
411
576
  this._emit("message:cancel", { requestId: event.id });
412
577
  return;
413
578
  }
@@ -460,7 +625,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
460
625
  const _onRequest = this.onRequest.bind(this);
461
626
  this.onRequest = async (request) => {
462
627
  return this._tryCatchChat(async () => {
463
- if (new URL(request.url).pathname.split("/").pop() === "get-messages") return Response.json(this._loadMessagesFromDb());
628
+ if (new URL(request.url).pathname.split("/").pop() === "get-messages") return new Response(this.#streamMessagesAsJson(), { headers: { "content-type": "application/json" } });
464
629
  return _onRequest(request);
465
630
  });
466
631
  };
@@ -489,6 +654,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
489
654
  addColumnIfNotExists("alter table cf_ai_chat_agent_tool_runs add column summary text");
490
655
  addColumnIfNotExists("alter table cf_ai_chat_agent_tool_runs add column progress_json text");
491
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");
492
658
  this.sql`create index if not exists idx_ai_chat_agent_tool_request_id
493
659
  on cf_ai_chat_agent_tool_runs(request_id)`;
494
660
  this.sql`create table if not exists cf_ai_chat_agent_tool_milestones (
@@ -560,7 +726,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
560
726
  pendingResumeConnections: this._pendingResumeConnections,
561
727
  pendingChatTerminal: () => this._pendingChatTerminal(),
562
728
  persistOrphanedStream: (streamId) => this._persistOrphanedStream(streamId),
563
- isConnectionPresent: (connectionId) => this._isConnectionPresent(connectionId)
729
+ isConnectionPresent: (connectionId) => this._isConnectionPresent(connectionId),
730
+ holdsTerminalFrames: (requestId) => this._heldTerminalFrames.has(requestId)
564
731
  });
565
732
  }
566
733
  /**
@@ -583,77 +750,72 @@ var AIChatAgent = class AIChatAgent extends Agent {
583
750
  }
584
751
  /** @internal Delegate to _resumableStream */
585
752
  _startStream(requestId, options = {}) {
586
- 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
+ });
587
758
  this._preStream.flushOnStreamStart((c) => this._notifyStreamResuming(c));
588
759
  if (this._continuation.pending?.requestId === requestId) {
589
760
  this._continuation.activatePending();
590
761
  this._flushAwaitingStreamStartConnections();
591
762
  this._activateDeferredAutoContinuation();
592
763
  }
593
- this._ensureStreamCleanupScheduled();
594
764
  return streamId;
595
765
  }
596
766
  /** @internal Delegate to _resumableStream */
597
- _completeStream(streamId) {
767
+ _completeStream(streamId, outcome) {
598
768
  const completedRequestId = this._resumableStream.activeRequestId;
599
- this._resumableStream.complete(streamId);
769
+ this._resumableStream.complete(streamId, outcome);
770
+ this._afterStreamFinished(completedRequestId);
771
+ }
772
+ /**
773
+ * @internal The producer finished; leave the row for the cutover that
774
+ * persists the message (`persistMessages` via `#pendingCutover`). `_reply`'s
775
+ * finally settles it if no persist follows.
776
+ */
777
+ _finishStream(streamId, outcome) {
778
+ const finishedRequestId = this._resumableStream.activeRequestId;
779
+ this._resumableStream.finish(streamId, outcome);
780
+ this._afterStreamFinished(finishedRequestId);
781
+ }
782
+ _afterStreamFinished(requestId) {
600
783
  this._pendingResumeConnections.clear();
601
- if (completedRequestId === this._continuation.activeRequestId) {
784
+ if (requestId === this._continuation.activeRequestId) {
602
785
  this._continuation.activeRequestId = null;
603
786
  this._continuation.activeConnectionId = null;
604
787
  }
605
- this._ensureStreamCleanupScheduled();
606
788
  }
607
789
  /**
608
- * Ensure a single cleanup alarm is pending for this DO's resumable-stream
609
- * buffers. Armed whenever a stream finishes (completes or errors) so that
610
- * idle/one-off chat DOs still reclaim their buffers — the lazy sweep in
611
- * {@link ResumableStream} only fires when a *subsequent* stream completes,
612
- * which never happens for a chat that receives a single turn (#1706).
613
- *
614
- * `idempotent` dedupes on (callback, payload, owner) so repeated finishes
615
- * collapse onto one pending alarm rather than stacking.
790
+ * @deprecated Streams are reclaimed at cutover and on the next stream
791
+ * start; no alarm is armed any more. Kept so a cleanup alarm persisted
792
+ * by an earlier version still resolves to a callback when it fires.
616
793
  * @internal
617
794
  */
618
- async _ensureStreamCleanupScheduled({ idempotent = true } = {}) {
619
- await this.schedule(STREAM_CLEANUP_DELAY_SECONDS, "_cleanupStreamBuffers", void 0, { idempotent });
795
+ async _cleanupStreamBuffers() {
796
+ this._resumableStream.reclaim();
620
797
  }
621
798
  /**
622
- * Alarm callback: sweep aged stream buffers, re-arming while rows remain (see
623
- * the shared {@link cleanupStreamBuffers}). Public so it is reachable as a
624
- * schedule callback.
625
- * @internal
799
+ * @internal Delegate to _resumableStream.
800
+ *
801
+ * A settled tool result (`tool-output-available` / `-error` / `-denied`)
802
+ * is flushed to SQLite immediately rather than waiting for the packed
803
+ * segment to fill: it captures a completed, often non-idempotent side
804
+ * effect (or a user's denial), and an isolate eviction before the next
805
+ * batch flush would lose it — recovery would re-anchor without it and
806
+ * re-run the tool. The flush is also what the recovery progress marker is
807
+ * derived from (`_chatRecoveryProgressMarker`), so a settled result counts
808
+ * as forward progress the moment it lands, as it did under the old
809
+ * per-chunk counter. Streaming deltas keep the buffer's own packing.
626
810
  */
627
- async _cleanupStreamBuffers() {
628
- await cleanupStreamBuffers(this._resumableStream, () => this._ensureStreamCleanupScheduled({ idempotent: false }));
629
- }
630
- /** @internal Delegate to _resumableStream. Also advances the recovery
631
- * progress counter at production time (see `_maybeBumpRecoveryProgress`). */
632
811
  async _storeStreamChunk(streamId, body) {
633
- this._resumableStream.storeChunk(streamId, body);
812
+ const seq = this._resumableStream.storeChunk(streamId, body);
634
813
  let type;
635
814
  try {
636
815
  type = JSON.parse(body).type;
637
816
  } catch {}
638
- await this._maybeBumpRecoveryProgress(type);
639
- }
640
- /** Advance the recovery-progress counter when a chunk represents genuinely
641
- * new produced content. Uses the shared host-agnostic rule
642
- * ({@link shouldCreditStreamProgress}): a milestone (started segment / settled
643
- * tool) always credits, and a long single segment's streaming deltas credit
644
- * through a time throttle so the no-progress window doesn't false-fire while
645
- * content streams across crashes. Bumped at production time, so it reflects
646
- * real forward progress and is immune to client reconnects / recovery
647
- * re-persists (which replay or re-materialize stored chunks rather than flow
648
- * through here). This is what the recovery no-progress window keys off
649
- * (#1637), and stays compaction-proof (#1628). */
650
- async _maybeBumpRecoveryProgress(type) {
651
- if (shouldCreditStreamProgress({
652
- codec: aiSdkRecoveryCodec,
653
- type,
654
- throttle: this._streamProgressCredit,
655
- now: Date.now()
656
- })) await this._bumpChatRecoveryProgress();
817
+ if (type === "tool-output-available" || type === "tool-output-error" || type === "tool-output-denied") this._resumableStream.flushBuffer();
818
+ return seq;
657
819
  }
658
820
  /** @internal Delegate to _resumableStream */
659
821
  _flushChunkBuffer() {
@@ -672,7 +834,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
672
834
  this._continuation.activeRequestId = null;
673
835
  this._continuation.activeConnectionId = null;
674
836
  }
675
- this._ensureStreamCleanupScheduled();
676
837
  }
677
838
  /**
678
839
  * Reconstruct and persist a partial assistant message from an orphaned
@@ -686,9 +847,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
686
847
  * `Think` and the client reducer use), replacing a hand-rolled chunk
687
848
  * switch; it owns the `start` / `finish` / `message-metadata` handling;
688
849
  * - (b) {@link _resolveOrphanTargetId} — the id to persist under (#1691);
689
- * - (c)+(d) upsert-by-id over the flat array, the `SessionProvider`-subset
690
- * store-write shape (`getMessage` → `updateMessage` / `appendMessage`)
691
- * that `Think._upsertMessageInHistory` implements over a Session tree.
850
+ * - (c)+(d) upsert-by-id through the shared `OrphanPersistStore` shape
851
+ * (`getMessage` → `updateMessage` / `appendMessage`).
692
852
  * When a row already owns the id, the shared `reconcileOrphanPartial`
693
853
  * merge preserves an in-place tool result rather than letting a replayed
694
854
  * chunk re-advance it (ai-chat has an early tool-approval persist; hosts
@@ -737,9 +897,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
737
897
  return reconstructedId;
738
898
  }
739
899
  /**
740
- * The orphan-persist store adapter — orphan-persist steps **(c)/(d)** route
741
- * their write through this shared `OrphanPersistStore` seam (the
742
- * `SessionProvider` write-subset). Backed by ai-chat's flat `this.messages`
900
+ * The orphan-persist store adapter. Orphan-persist steps **(c)/(d)** route
901
+ * through the shared `OrphanPersistStore` seam, backed by ai-chat's
902
+ * `this.messages`
743
903
  * array + the existing `persistMessages` whole-array write path, so
744
904
  * reconcile/sanitize/row-size/broadcast all stay intact. Each mutating call
745
905
  * is exactly one `persistMessages` invocation; `parentId` is unused (a flat
@@ -780,7 +940,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
780
940
  return {
781
941
  ...part,
782
942
  state: "output-error",
783
- 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."
784
944
  };
785
945
  }
786
946
  /**
@@ -816,11 +976,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
816
976
  * write, one broadcast), which also refreshes `this.messages`.
817
977
  * @internal
818
978
  */
819
- async _repairInterruptedToolsBeforeTurn() {
979
+ async _repairInterruptedToolsBeforeTurn(options) {
820
980
  const clientResolvable = this._clientResolvableToolNames();
821
981
  const repaired = repairInterruptedToolParts(this.messages, {
822
982
  repairPart: (part) => this.repairInterruptedToolPart(part),
823
- shouldRepair: (part) => !this._partAwaitsClientInteraction(part, clientResolvable)
983
+ shouldRepair: (part) => !this._partAwaitsClientInteraction(part, clientResolvable),
984
+ repairApprovalResponded: !options.continuation && !this._continuation.pending && !this._continuation.deferred
824
985
  });
825
986
  if (repaired.removedToolCalls === 0 && repaired.normalizedInputs === 0) return;
826
987
  await this.persistMessages(repaired.messages);
@@ -856,10 +1017,40 @@ var AIChatAgent = class AIChatAgent extends Agent {
856
1017
  `;
857
1018
  else this.sql`delete from cf_ai_chat_request_context where key = 'lastClientTools'`;
858
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
+ }
859
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
+ }
860
1039
  const allExclusions = [...exclude || [], ...this._pendingResumeConnections];
861
1040
  this.broadcast(JSON.stringify(message), allExclusions);
862
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
+ }
863
1054
  /**
864
1055
  * Broadcasts a text event for non-SSE responses.
865
1056
  * This ensures plain text responses follow the AI SDK v5 stream protocol.
@@ -870,33 +1061,161 @@ var AIChatAgent = class AIChatAgent extends Agent {
870
1061
  */
871
1062
  async _broadcastTextEvent(streamId, event, continuation) {
872
1063
  const body = JSON.stringify(event);
873
- await this._storeStreamChunk(streamId, body);
1064
+ const seq = await this._storeStreamChunk(streamId, body);
874
1065
  this._broadcastChatMessage({
875
1066
  body,
876
1067
  done: false,
877
1068
  id: event.id,
878
1069
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1070
+ ...seq !== void 0 && { seq },
879
1071
  ...continuation && { continuation: true }
880
1072
  });
881
1073
  }
882
- _loadMessagesFromDb() {
883
- const rows = this.sql`select * from cf_ai_chat_agent_messages order by created_at` || [];
884
- this._persistedMessageCache.clear();
885
- return rows.map((row) => {
886
- try {
887
- const messageStr = row.message;
888
- const parsed = JSON.parse(messageStr);
889
- if (!isValidMessageStructure(parsed)) {
890
- console.warn(`[AIChatAgent] Skipping invalid message ${row.id}: missing or malformed id, role, or parts`);
891
- return null;
1074
+ /**
1075
+ * Lift ai-chat's legacy flat table into the default Sessions chain.
1076
+ *
1077
+ * Runs in `onStart` (before hydration), not in the constructor: the lift is
1078
+ * an async import through Sessions, and the constructor does no session
1079
+ * storage work at all.
1080
+ *
1081
+ * Order is read first as ids alone, then message bodies are fetched in
1082
+ * windows bounded by row count and bytes, so a large transcript never sits
1083
+ * in the isolate at once. Once every readable row has a copy the legacy
1084
+ * table is DROPPED rather than renamed: keeping it would leave the object
1085
+ * holding its history twice.
1086
+ */
1087
+ async _migrateLegacyMessages() {
1088
+ if (!(this.ctx.storage.sql.exec(`SELECT name FROM sqlite_master
1089
+ WHERE type = 'table' AND name = 'cf_ai_chat_agent_messages'`).toArray().length > 0)) return;
1090
+ const order = this.sql`
1091
+ SELECT id, LENGTH(CAST(message AS BLOB)) AS bytes, created_at
1092
+ FROM cf_ai_chat_agent_messages
1093
+ ORDER BY created_at ASC, rowid ASC
1094
+ `;
1095
+ let parentId = null;
1096
+ let imported = 0;
1097
+ let skipped = 0;
1098
+ let index = 0;
1099
+ while (index < order.length) {
1100
+ const window = [];
1101
+ let bytes = 0;
1102
+ while (index < order.length && window.length < LEGACY_LIFT_WINDOW_ROWS && (window.length === 0 || bytes + order[index].bytes <= LEGACY_LIFT_WINDOW_BYTES)) {
1103
+ bytes += order[index].bytes;
1104
+ window.push(order[index]);
1105
+ index++;
1106
+ }
1107
+ const ids = JSON.stringify(window.map((row) => row.id));
1108
+ const bodies = new Map(this.sql`
1109
+ SELECT id, message FROM cf_ai_chat_agent_messages
1110
+ WHERE id IN (SELECT value FROM json_each(${ids}))
1111
+ `.map((row) => [row.id, row.message]));
1112
+ for (const row of window) {
1113
+ const body = bodies.get(row.id);
1114
+ if (body === void 0) {
1115
+ skipped++;
1116
+ continue;
1117
+ }
1118
+ try {
1119
+ const message = autoTransformMessages([JSON.parse(body)])[0];
1120
+ if (!message || !isValidMessageStructure(message)) {
1121
+ console.warn(`[AIChatAgent] Skipping invalid legacy message ${row.id}: missing or malformed id, role, or parts`);
1122
+ skipped++;
1123
+ continue;
1124
+ }
1125
+ const parsedTime = typeof row.created_at === "number" ? row.created_at : Date.parse(String(row.created_at ?? ""));
1126
+ await this.#session.importMessage(message, {
1127
+ parentId,
1128
+ createdAt: Number.isFinite(parsedTime) ? parsedTime : imported
1129
+ });
1130
+ parentId = message.id;
1131
+ imported++;
1132
+ } catch (error) {
1133
+ console.error(`Failed to migrate message ${row.id}:`, error);
1134
+ skipped++;
892
1135
  }
893
- this._persistedMessageCache.set(parsed.id, messageStr);
894
- return parsed;
895
- } catch (error) {
896
- console.error(`Failed to parse message ${row.id}:`, error);
897
- return null;
898
1136
  }
899
- }).filter((msg) => msg !== null);
1137
+ }
1138
+ if (skipped === 0 && imported === order.length) {
1139
+ this.ctx.storage.sql.exec("DROP TABLE cf_ai_chat_agent_messages");
1140
+ return;
1141
+ }
1142
+ console.error(`[AIChatAgent] Legacy lift imported ${imported} of ${order.length} rows (${skipped} skipped); leaving cf_ai_chat_agent_messages in place so they remain recoverable.`);
1143
+ }
1144
+ /**
1145
+ * Hydrate `this.messages` once per wake, bounded by
1146
+ * {@link hydrationByteBudget}. This is the only transcript read on the
1147
+ * startup path; every later change arrives through the Sessions change
1148
+ * feed.
1149
+ */
1150
+ async _hydrateMessages() {
1151
+ const budget = this.hydrationByteBudget;
1152
+ const stored = Number.isFinite(budget) && budget > 0 ? (await this.#session.getRecentHistory(budget)).messages : await this.#session.getHistory();
1153
+ const messages = [];
1154
+ for (const message of stored) {
1155
+ if (!isValidMessageStructure(message)) {
1156
+ console.warn(`[AIChatAgent] Skipping invalid message ${message?.id}: missing or malformed id, role, or parts`);
1157
+ continue;
1158
+ }
1159
+ messages.push(message);
1160
+ }
1161
+ this.messages = autoTransformMessages(messages);
1162
+ }
1163
+ /**
1164
+ * Mirror `this.messages` from the Sessions change feed. Every durable write
1165
+ * dispatches here synchronously, so write sites never hand-patch the
1166
+ * cache.
1167
+ */
1168
+ #subscribeToSessionChanges() {
1169
+ this.#session.mirror({
1170
+ get: () => this.messages,
1171
+ set: (messages) => {
1172
+ this.messages = messages;
1173
+ },
1174
+ transform: (message) => this.#messageForCache(message)
1175
+ });
1176
+ }
1177
+ /**
1178
+ * Turn a stored row into its in-memory form. A stored row is exactly what
1179
+ * the write returned, so this never costs a re-read.
1180
+ */
1181
+ #messageForCache(message) {
1182
+ const stored = message;
1183
+ return autoTransformMessages([stored])[0] ?? stored;
1184
+ }
1185
+ /**
1186
+ * Serialize the whole transcript as a JSON array of messages without ever
1187
+ * holding it in one string: `historyBatches()` yields bounded batches and
1188
+ * each batch is encoded straight into the response body.
1189
+ */
1190
+ #streamMessagesAsJson() {
1191
+ const encoder = new TextEncoder();
1192
+ const batches = this.#session.historyBatches();
1193
+ let opened = false;
1194
+ let first = true;
1195
+ return new ReadableStream({
1196
+ pull: async (controller) => {
1197
+ if (!opened) {
1198
+ opened = true;
1199
+ controller.enqueue(encoder.encode("["));
1200
+ return;
1201
+ }
1202
+ const next = await batches.next();
1203
+ if (next.done) {
1204
+ controller.enqueue(encoder.encode("]"));
1205
+ controller.close();
1206
+ return;
1207
+ }
1208
+ let chunk = "";
1209
+ for (const message of autoTransformMessages(next.value)) {
1210
+ chunk += `${first ? "" : ","}${JSON.stringify(message)}`;
1211
+ first = false;
1212
+ }
1213
+ if (chunk.length > 0) controller.enqueue(encoder.encode(chunk));
1214
+ },
1215
+ cancel: async () => {
1216
+ await batches.return?.(void 0);
1217
+ }
1218
+ });
900
1219
  }
901
1220
  async _tryCatchChat(fn) {
902
1221
  try {
@@ -1030,12 +1349,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
1030
1349
  } catch {}
1031
1350
  }
1032
1351
  _completeSkippedRequest(connection, requestId) {
1033
- this._sendDirectMessage(connection, {
1352
+ this._sendDirectMessage(connection, this._withOriginMessageIds({
1034
1353
  body: "",
1035
1354
  done: true,
1036
1355
  id: requestId,
1037
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
1038
- });
1356
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1357
+ outcome: "skipped"
1358
+ }));
1039
1359
  this._settlePreStreamTurn(requestId, { releaseParked: false });
1040
1360
  }
1041
1361
  /** Whether a connection with this id is still attached. */
@@ -1153,6 +1473,18 @@ var AIChatAgent = class AIChatAgent extends Agent {
1153
1473
  this._abortRegistry.cancel(requestId, reason);
1154
1474
  }
1155
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
+ /**
1156
1488
  * Abort every in-flight chat turn on this agent.
1157
1489
  *
1158
1490
  * Aborts all controllers in the registry and clears it. Used by
@@ -1293,8 +1625,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
1293
1625
  * continuation would never fire. A slow batch is re-checked here and simply
1294
1626
  * keeps holding (event-driven) until its remaining siblings answer.
1295
1627
  */
1296
- _onStreamingTurnFinalized() {
1628
+ _onStreamingTurnFinalized(finishReason) {
1297
1629
  this._streamingTurnActive = false;
1630
+ if (finishReason === "stop" && this._continuation.pending && !this._hasIncompleteToolBatch()) {
1631
+ this._clearPendingAutoContinuation(true);
1632
+ return;
1633
+ }
1298
1634
  this._autoContinuation.rearmForBatch();
1299
1635
  }
1300
1636
  /**
@@ -1345,8 +1681,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
1345
1681
  email: void 0
1346
1682
  }, async () => {
1347
1683
  const autoContinuationBody = async () => {
1684
+ let replying = false;
1348
1685
  try {
1349
- await this._repairInterruptedToolsBeforeTurn();
1686
+ await this._repairInterruptedToolsBeforeTurn({ continuation: true });
1350
1687
  const response = await this.onChatMessage(async (_finishResult) => {}, {
1351
1688
  requestId,
1352
1689
  abortSignal,
@@ -1357,7 +1694,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
1357
1694
  if (response) {
1358
1695
  if ((await this._reply(requestId, response, [], {
1359
1696
  continuation: true,
1360
- chatMessageId: requestId
1697
+ chatMessageId: requestId,
1698
+ onStreamStart: () => {
1699
+ replying = true;
1700
+ }
1361
1701
  })).status === "error") {
1362
1702
  this._clearAllAutoContinuationState(true);
1363
1703
  return;
@@ -1367,6 +1707,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
1367
1707
  this._clearPendingAutoContinuation(true);
1368
1708
  this._activateDeferredAutoContinuation();
1369
1709
  }
1710
+ } catch (error) {
1711
+ if (!replying && !abortSignal?.aborted && !isDurableObjectResetError(error)) await this._reportContinuationFailure(requestId, error);
1712
+ throw error;
1370
1713
  } finally {
1371
1714
  this._abortRegistry.remove(requestId);
1372
1715
  }
@@ -1387,6 +1730,33 @@ var AIChatAgent = class AIChatAgent extends Agent {
1387
1730
  });
1388
1731
  }
1389
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
+ /**
1390
1760
  * @returns Terminal status for the turn.
1391
1761
  */
1392
1762
  async _runProgrammaticChatTurn(requestId, clientTools, body, externalSignal) {
@@ -1404,7 +1774,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1404
1774
  const detachExternal = this._abortRegistry.linkExternal(requestId, externalSignal);
1405
1775
  try {
1406
1776
  const programmaticBody = async () => {
1407
- await this._repairInterruptedToolsBeforeTurn();
1777
+ await this._repairInterruptedToolsBeforeTurn({ continuation: false });
1408
1778
  const response = await this.onChatMessage(() => {}, {
1409
1779
  requestId,
1410
1780
  abortSignal,
@@ -1742,12 +2112,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
1742
2112
  const assistantIdsBeforeStart = new Set(this.messages.filter((message) => message.role === "assistant").map((message) => message.id));
1743
2113
  this.sql`
1744
2114
  insert into cf_ai_chat_agent_tool_runs
1745
- (run_id, request_id, status, input_json, started_at)
1746
- 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})
1747
2117
  `;
1748
2118
  this._agentToolAbortControllers.set(options.runId, controller);
1749
2119
  this._agentToolPreTurnAssistantIds.set(options.runId, assistantIdsBeforeStart);
1750
2120
  this._agentToolLiveSequences.set(options.runId, 0);
2121
+ if (options.eventDelivery === "terminal") this._agentToolTerminalOnlyRuns.add(options.runId);
1751
2122
  const abortFromParent = () => controller.abort(options.signal?.reason);
1752
2123
  if (options.signal?.aborted) abortFromParent();
1753
2124
  else options.signal?.addEventListener("abort", abortFromParent, { once: true });
@@ -1833,6 +2204,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1833
2204
  options.signal?.removeEventListener("abort", abortFromParent);
1834
2205
  this._agentToolAbortControllers.delete(options.runId);
1835
2206
  this._agentToolLiveSequences.delete(options.runId);
2207
+ this._agentToolTerminalOnlyRuns.delete(options.runId);
1836
2208
  this._agentToolProgressEmitterInstance?.forget(options.runId);
1837
2209
  if (this._agentToolAbortControllers.size === 0) this._agentToolRunsByRequestId.clear();
1838
2210
  else for (const [reqId, runId] of this._agentToolRunsByRequestId) if (runId === options.runId) this._agentToolRunsByRequestId.delete(reqId);
@@ -1884,6 +2256,19 @@ var AIChatAgent = class AIChatAgent extends Agent {
1884
2256
  async _reconcileStaleAgentToolChildRun(runId, row) {
1885
2257
  const recovery = await this._classifyAgentToolChildRecovery();
1886
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
+ }
1887
2272
  const messagesAfterStart = this._getAgentToolMessagesAfterStart(runId);
1888
2273
  if (recovery !== "failed" && messagesAfterStart.some((message) => message.role === "assistant")) {
1889
2274
  const input = AIChatAgent._parseAgentToolValue(row.input_json);
@@ -1957,10 +2342,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
1957
2342
  } catch {}
1958
2343
  }
1959
2344
  }
1960
- async inspectAgentToolRun(runId) {
2345
+ async inspectAgentToolRun(runId, options) {
1961
2346
  const row = this._getAgentToolRunRow(runId);
1962
2347
  if (!row) return null;
1963
- 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);
1964
2349
  const streamId = row.request_id ? this._getAgentToolStreamId(row.request_id) : void 0;
1965
2350
  const messagesAfterStart = this._getAgentToolMessagesAfterStart(runId);
1966
2351
  const input = AIChatAgent._parseAgentToolValue(row.input_json);
@@ -2017,8 +2402,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
2017
2402
  let lastEmitted = options?.afterSequence ?? -1;
2018
2403
  const emit = (chunk) => {
2019
2404
  if (closed) return;
2020
- if (chunk.sequence <= lastEmitted) return;
2021
- lastEmitted = chunk.sequence;
2405
+ if (!isPositionlessAgentToolChunk(chunk)) {
2406
+ if (chunk.sequence <= lastEmitted) return;
2407
+ lastEmitted = chunk.sequence;
2408
+ }
2022
2409
  try {
2023
2410
  controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
2024
2411
  } catch {
@@ -2051,6 +2438,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2051
2438
  return;
2052
2439
  }
2053
2440
  options?.signal?.addEventListener("abort", onAbort, { once: true });
2441
+ const seeded = this._seedAgentToolLiveSequence(runId);
2054
2442
  const forwarders = this._agentToolForwarders.get(runId) ?? /* @__PURE__ */ new Set();
2055
2443
  forwarders.add(forward);
2056
2444
  this._agentToolForwarders.set(runId, forwarders);
@@ -2066,10 +2454,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
2066
2454
  pending.length = 0;
2067
2455
  const inspection = await this.inspectAgentToolRun(runId);
2068
2456
  if (!inspection || inspection.status !== "running") {
2457
+ if (seeded) this._agentToolLiveSequences.delete(runId);
2069
2458
  close();
2070
2459
  return;
2071
2460
  }
2072
- if (lastEmitted > (options?.afterSequence ?? -1)) this._agentToolLiveSequences.set(runId, lastEmitted + 1);
2073
2461
  } catch (error) {
2074
2462
  closed = true;
2075
2463
  detach();
@@ -2094,13 +2482,24 @@ var AIChatAgent = class AIChatAgent extends Agent {
2094
2482
  `[0] ?? null;
2095
2483
  }
2096
2484
  _getAgentToolStreamId(requestId) {
2097
- return this.sql`
2098
- select id, status, request_id
2099
- from cf_ai_chat_stream_metadata
2100
- where request_id = ${requestId}
2101
- order by rowid desc
2102
- limit 1
2103
- `[0]?.id;
2485
+ return this._resumableStream.latestStreamInfoForRequest(requestId)?.id;
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;
2104
2503
  }
2105
2504
  _getAgentToolStoredChunks(requestId, afterSequence = -1) {
2106
2505
  const streamId = this._getAgentToolStreamId(requestId);
@@ -2121,6 +2520,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2121
2520
  this._agentToolClosers.delete(runId);
2122
2521
  }
2123
2522
  this._agentToolForwarders.delete(runId);
2523
+ if (!this._agentToolAbortControllers.has(runId)) this._agentToolTerminalOnlyRuns.delete(runId);
2124
2524
  }
2125
2525
  static _stringifyAgentToolValue(value) {
2126
2526
  if (value === void 0) return null;
@@ -2241,7 +2641,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2241
2641
  const abortSignal = this._abortRegistry.getSignal(requestId);
2242
2642
  const detachExternal = this._abortRegistry.linkExternal(requestId, options?.signal);
2243
2643
  try {
2244
- await this._repairInterruptedToolsBeforeTurn();
2644
+ await this._repairInterruptedToolsBeforeTurn({ continuation: true });
2245
2645
  const response = await this.onChatMessage(() => {}, {
2246
2646
  requestId,
2247
2647
  abortSignal,
@@ -2320,34 +2720,38 @@ var AIChatAgent = class AIChatAgent extends Agent {
2320
2720
  * recomputed from the live, mutable transcript. Compaction collapses older
2321
2721
  * assistant messages into a summary, lowering the count — so a turn that had
2322
2722
  * genuinely advanced could read as "no progress" between attempts and exhaust
2323
- * its budget prematurely (#1628). Instead we read a durably-persisted counter
2324
- * that only ever increments — bumped at production time when new content is
2325
- * streamed (see `_storeStreamChunk` / `_maybeBumpRecoveryProgress`), which is
2326
- * genuine forward progress and is immune to client reconnects / recovery
2327
- * re-persists — so compaction can never lower it and a reconnect can't fake
2328
- * it (#1637).
2723
+ * its budget prematurely (#1628). It then became a KV counter bumped per
2724
+ * credited chunk. It is now derived from the stream log the chunks were
2725
+ * already flushed to (`ResumableStream.progressMarker`): the log only grows
2726
+ * when new content lands durably, a reconnect replay or a recovery
2727
+ * re-persist reads it without appending (#1637), and compaction rewrites
2728
+ * the transcript, not the log. Nothing is written per chunk.
2729
+ *
2730
+ * The pre-derivation KV counter is folded in once per isolate, so a marker
2731
+ * an in-flight incident already recorded is never read lower after the
2732
+ * upgrade.
2329
2733
  */
2330
2734
  async _chatRecoveryProgressMarker() {
2331
- return readChatRecoveryProgress(this.ctx.storage);
2332
- }
2333
- /** Advance the durable recovery-progress counter. Called from
2334
- * `_maybeBumpRecoveryProgress` when new content is streamed (real,
2335
- * reconnect-immune forward progress). The increment lives in the shared
2336
- * engine (agents/chat); this is the package binding. */
2337
- async _bumpChatRecoveryProgress() {
2338
- return bumpChatRecoveryProgress(this.ctx.storage);
2735
+ this._progressSeed ??= readChatRecoveryProgress(this.ctx.storage).then((legacy) => this._resumableStream.seedProgress(legacy), (error) => {
2736
+ this._progressSeed = null;
2737
+ throw error;
2738
+ });
2739
+ await this._progressSeed;
2740
+ return this._resumableStream.progressMarker();
2339
2741
  }
2340
2742
  /**
2341
2743
  * N9: forwarding a sub-agent's chunks IS forward progress for this parent
2342
2744
  * turn, so credit the parent's recovery progress marker — otherwise a parent
2343
2745
  * whose turn merely `await`s a child banks no progress of its own and its
2344
- * no-progress window exhausts while the child is healthily streaming. Only
2746
+ * no-progress window exhausts while the child is healthily streaming. The
2747
+ * child's output goes to clients, not to this object's stream log, so the
2748
+ * derived marker cannot see it; this is the one explicit credit left. Only
2345
2749
  * invoked after a child actually produced output (see
2346
2750
  * `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.
2347
2751
  * Throttled (and reset per isolate) so we never write storage per token.
2348
2752
  */
2349
2753
  async _onAgentToolStreamProgress() {
2350
- if (this._agentToolStreamProgress.shouldCredit(Date.now())) await this._bumpChatRecoveryProgress();
2754
+ if (this._agentToolStreamProgress.shouldCredit(Date.now())) this._resumableStream.creditProgress();
2351
2755
  }
2352
2756
  _chatRecoveryEngine() {
2353
2757
  return this._chatRecoveryEngineInstance ??= new ChatRecoveryEngine({
@@ -2355,6 +2759,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2355
2759
  now: () => Date.now(),
2356
2760
  sweepStaleIncidents: (now) => sweepStaleChatRecoveryIncidents(this.ctx.storage, now),
2357
2761
  getIncident: async (key) => await this.ctx.storage.get(key) ?? null,
2762
+ listActiveIncidents: async () => (await listActiveChatRecoveryIncidents(this.ctx.storage)).map(({ incident }) => incident),
2358
2763
  readProgress: () => this._chatRecoveryProgressMarker(),
2359
2764
  isAwaitingClientInteraction: () => this.hasPendingClientInteraction(),
2360
2765
  putIncident: (key, incident) => this.ctx.storage.put(key, incident),
@@ -2369,12 +2774,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
2369
2774
  recoveryKind: event.recoveryKind,
2370
2775
  ...event.reason ? { reason: event.reason } : {}
2371
2776
  }),
2372
- scheduleRecovery: async (callback, data, reason, delaySeconds) => {
2373
- await this.schedule(delaySeconds, callback, data, chatRecoverySchedulePolicy(reason));
2374
- },
2777
+ scheduleRecovery: (callback, data, reason, delaySeconds) => this._enqueueChatRecovery(callback, data, reason, delaySeconds),
2375
2778
  setRecovering: (active, requestId) => this._setChatRecovering(active, requestId),
2376
2779
  onShouldKeepRecoveringError: (error) => console.error("[AIChatAgent] chatRecovery shouldKeepRecovering hook threw", error),
2377
- 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),
2378
2781
  resolveRecoveryStream: (requestId) => this._resolveAIChatRecoveryStream(requestId),
2379
2782
  getPartialStreamText: (streamId) => this._getPartialStreamText(streamId),
2380
2783
  activeChatRecoveryRootRequestId: () => this._activeChatRecoveryRootRequestId,
@@ -2387,7 +2790,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2387
2790
  async _updateChatRecoveryIncident(incidentId, status, reason) {
2388
2791
  return this._chatRecoveryEngine().updateIncident(incidentId, status, reason);
2389
2792
  }
2390
- async _exhaustChatRecovery(incident, config, partial, streamId, createdAt) {
2793
+ async _exhaustChatRecovery(incident, config, partial, streamId, createdAt, originMessageIds) {
2391
2794
  await runChatRecoveryExhaustion({
2392
2795
  incident,
2393
2796
  config,
@@ -2400,14 +2803,16 @@ var AIChatAgent = class AIChatAgent extends Agent {
2400
2803
  onExhausted: config.onExhausted,
2401
2804
  onError: (error) => console.error("[AIChatAgent] chatRecovery onExhausted hook threw", error),
2402
2805
  terminalize: async (ctx) => {
2806
+ const messageIds = this._originMessageIdsFor(ctx.requestId) ?? originMessageIds;
2403
2807
  this._broadcastChatMessage({
2404
2808
  body: ctx.terminalMessage,
2405
2809
  done: true,
2406
2810
  error: true,
2407
2811
  id: ctx.requestId,
2408
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
2812
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
2813
+ ...messageIds ? { messageIds } : {}
2409
2814
  });
2410
- await this._recordChatTerminal(ctx.requestId, ctx.terminalMessage);
2815
+ await this._recordChatTerminal(ctx.requestId, ctx.terminalMessage, messageIds);
2411
2816
  await this._setChatRecovering(false);
2412
2817
  }
2413
2818
  });
@@ -2418,8 +2823,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
2418
2823
  * until a later turn supersedes it (`_clearChatTerminal`); a single record is
2419
2824
  * sufficient because only the most recent terminal is relevant.
2420
2825
  */
2421
- async _recordChatTerminal(requestId, body) {
2422
- 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);
2423
2828
  }
2424
2829
  /** Clear the durable terminal record once a later turn supersedes it (#1645). */
2425
2830
  async _clearChatTerminal() {
@@ -2486,7 +2891,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
2486
2891
  persistOrphanedStream: (streamId) => this._persistOrphanedStream(streamId),
2487
2892
  completeRecoveredStream: (streamId) => {
2488
2893
  this._resumableStream.complete(streamId);
2489
- this._ensureStreamCleanupScheduled();
2490
2894
  },
2491
2895
  dispatchRecoveredTurn: (input) => this._dispatchRecoveredChatTurn(input)
2492
2896
  });
@@ -2503,14 +2907,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2503
2907
  */
2504
2908
  _resolveAIChatRecoveryStream(requestId) {
2505
2909
  let streamId = "";
2506
- if (requestId) {
2507
- const rows = this.sql`
2508
- SELECT id FROM cf_ai_chat_stream_metadata
2509
- WHERE request_id = ${requestId}
2510
- ORDER BY created_at DESC LIMIT 1
2511
- `;
2512
- if (rows.length > 0) streamId = rows[0].id;
2513
- }
2910
+ if (requestId) streamId = this._resumableStream.latestStreamInfoForRequest(requestId)?.id ?? "";
2514
2911
  if (!streamId && this._resumableStream.hasActiveStream()) streamId = this._resumableStream.activeStreamId ?? "";
2515
2912
  const streamStillActive = Boolean(streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId);
2516
2913
  return {
@@ -2545,6 +2942,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2545
2942
  */
2546
2943
  async _dispatchRecoveredChatTurn(input) {
2547
2944
  const { incident, options, snapshot, recoveryRootRequestId } = input;
2945
+ const originIds = this._originMessageIdsFor(input.requestId) ?? snapshot?.originMessageIds;
2548
2946
  const leaf = this.messages.length > 0 ? this.messages[this.messages.length - 1] : void 0;
2549
2947
  const lostPartialUserId = snapshot?.continuation === false && snapshot.latestUserMessageId && leaf?.role === "user" && leaf.id === snapshot.latestUserMessageId ? snapshot.latestUserMessageId : void 0;
2550
2948
  const targetId = input.detail.shouldRetryPreStream || lostPartialUserId !== void 0 ? void 0 : this._findLastAssistantMessage()?.id;
@@ -2557,7 +2955,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
2557
2955
  originalRequestId: recoveryRootRequestId,
2558
2956
  incidentId: incident.incidentId,
2559
2957
  lastBody: snapshot?.lastBody ?? null,
2560
- lastClientTools: snapshot?.lastClientTools ?? null
2958
+ lastClientTools: snapshot?.lastClientTools ?? null,
2959
+ ...originIds ? { originMessageIds: originIds } : {}
2561
2960
  }
2562
2961
  });
2563
2962
  else if (lostPartialUserId !== void 0 && options.continue !== false) await this._chatRecoveryEngine().scheduleRecovery({
@@ -2569,7 +2968,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
2569
2968
  originalRequestId: recoveryRootRequestId,
2570
2969
  incidentId: incident.incidentId,
2571
2970
  lastBody: snapshot?.lastBody ?? null,
2572
- lastClientTools: snapshot?.lastClientTools ?? null
2971
+ lastClientTools: snapshot?.lastClientTools ?? null,
2972
+ ...originIds ? { originMessageIds: originIds } : {}
2573
2973
  }
2574
2974
  });
2575
2975
  else if (options.continue !== false) await this._chatRecoveryEngine().scheduleRecovery({
@@ -2583,7 +2983,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
2583
2983
  ...snapshot ? {
2584
2984
  lastBody: snapshot.lastBody ?? null,
2585
2985
  lastClientTools: snapshot.lastClientTools ?? null
2586
- } : {}
2986
+ } : {},
2987
+ ...originIds ? { originMessageIds: originIds } : {}
2587
2988
  }
2588
2989
  });
2589
2990
  else await this._updateChatRecoveryIncident(incident.incidentId, "skipped", "continue_disabled");
@@ -2606,6 +3007,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
2606
3007
  return {};
2607
3008
  }
2608
3009
  async _chatRecoveryContinue(data) {
3010
+ await this._dispatchChatRecovery("_chatRecoveryContinue", data, (onTurnStarted) => this._chatRecoveryOriginIdsScope.run(data?.originMessageIds, () => this._chatRecoveryContinueDetached(data, onTurnStarted)));
3011
+ }
3012
+ async _chatRecoveryContinueDetached(data, onTurnStarted) {
3013
+ if (await this._chatRecoveryEngine().isRecoveryCancelled(data?.incidentId)) return;
2609
3014
  const previousRootRequestId = this._activeChatRecoveryRootRequestId;
2610
3015
  this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
2611
3016
  try {
@@ -2626,7 +3031,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
2626
3031
  return;
2627
3032
  }
2628
3033
  this._applyRecoveredRequestContext(data);
3034
+ onTurnStarted?.();
3035
+ this._takeRecoveryReschedule(data?.incidentId);
2629
3036
  const result = await this.continueLastTurn();
3037
+ if (result.status !== "completed" && this._takeRecoveryReschedule(data?.incidentId)) return;
2630
3038
  await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
2631
3039
  } catch (error) {
2632
3040
  if (await this._handleRecoveryOom("_chatRecoveryContinue", data, error)) return;
@@ -2653,27 +3061,89 @@ var AIChatAgent = class AIChatAgent extends Agent {
2653
3061
  * schedule payload carries no `recoveredRequestId`.
2654
3062
  *
2655
3063
  * Returns `"exhausted"` when the budget was spent (terminal UX already
2656
- * 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.
2657
3067
  */
2658
3068
  async _routeStallToBoundedRecovery(input) {
2659
3069
  const recoveryRootRequestId = this._activeChatRecoveryRootRequestId ?? input.requestId;
3070
+ const originIds = this._originMessageIdsFor(input.requestId);
2660
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";
2661
3075
  const { incident, config, exhausted } = await this._beginChatRecoveryIncident({
2662
3076
  requestId: input.requestId,
2663
3077
  recoveryRootRequestId,
2664
3078
  latestUserMessageId,
2665
- recoveryKind: "continue"
3079
+ recoveryKind
2666
3080
  });
3081
+ const partialText = input.partialParts.filter((p) => p.type === "text").map((p) => p.text).join("");
2667
3082
  if (exhausted) {
2668
- const partialText = input.partialParts.filter((p) => p.type === "text").map((p) => p.text).join("");
2669
3083
  await this._exhaustChatRecovery(incident, config, {
2670
3084
  text: partialText,
2671
3085
  parts: input.partialParts
2672
3086
  }, input.streamId, incident.firstSeenAt);
2673
3087
  return "exhausted";
2674
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
+ }
2675
3143
  await this._chatRecoveryEngine().scheduleRecovery({
2676
3144
  incident,
3145
+ delaySeconds,
3146
+ reason,
2677
3147
  recoveryKind: "continue",
2678
3148
  callback: "_chatRecoveryContinue",
2679
3149
  data: {
@@ -2681,11 +3151,29 @@ var AIChatAgent = class AIChatAgent extends Agent {
2681
3151
  originalRequestId: recoveryRootRequestId,
2682
3152
  incidentId: incident.incidentId,
2683
3153
  lastBody: this._lastBody ?? null,
2684
- lastClientTools: this._lastClientTools ?? null
3154
+ lastClientTools: this._lastClientTools ?? null,
3155
+ ...originIds ? { originMessageIds: originIds } : {}
2685
3156
  }
2686
3157
  });
3158
+ this._rescheduledRecoveryIncidents.add(incident.incidentId);
2687
3159
  return "scheduled";
2688
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
+ }
2689
3177
  /**
2690
3178
  * Reschedule a recovery callback that timed out waiting for stable state,
2691
3179
  * consuming one attempt. Returns `true` if rescheduled, `false` if the
@@ -2754,25 +3242,32 @@ var AIChatAgent = class AIChatAgent extends Agent {
2754
3242
  * Two residual at-least-once edges, both deliberately accepted as "deliver a
2755
3243
  * second banner" ≫ "silently drop the turn":
2756
3244
  * • No `incidentId` at all in the payload (only reachable via a direct/test
2757
- * invocation — every production scheduler carries one): the synthesized
2758
- * incident can't be persisted (no key), so the guard can't arm.
3245
+ * invocation — every production recovery enqueue carries one): the
3246
+ * synthesized incident can't be persisted (no key), so the guard can't
3247
+ * arm.
2759
3248
  * • The record is swept AGAIN between two alarms (the guard re-persists on
2760
3249
  * the first, so this needs a second independent sweep) — vanishingly
2761
3250
  * unlikely.
2762
3251
  */
2763
3252
  /**
2764
- * Recovery continuation callbacks the alarm-boundary OOM circuit breaker may
2765
- * back off / purge (#1825). See `Agent._cf_handleAlarmMemoryLimitReset`.
3253
+ * Host memory-limit policy hook (#1825), dispatched structurally by
3254
+ * Lifecycle's circuit breaker — protected because it is framework
3255
+ * machinery, not part of the public chat API. Tasks applies the breaker to
3256
+ * root recovery runs; the routed dynamic-agent fallback applies it to
3257
+ * `recoveryLoop` schedule rows (see `RecoveryLoopScheduleOptions`). At the
3258
+ * strike budget this hook seals active incidents via
3259
+ * {@link _cf_sealMemoryLimitedRecovery}.
2766
3260
  */
2767
- _cf_recoveryAlarmCallbacks() {
2768
- return ["_chatRecoveryContinue", "_chatRecoveryRetry"];
3261
+ async onAlarmMemoryLimit(context) {
3262
+ if (!context.sealed) return;
3263
+ await this._cf_sealMemoryLimitedRecovery();
2769
3264
  }
2770
3265
  /**
2771
- * Seal any still-live recovery incident as an out-of-memory exhaustion when
2772
- * the alarm circuit breaker trips at its strike budget (#1825). Runs at the
2773
- * outermost alarm frame (post-unwind), so the terminal banner / `onExhausted`
2774
- * and the sealed-incident write can land where mid-turn writes OOMed. Reuses
2775
- * the shared give-up spine via the recovery engine.
3266
+ * Seal any still-live recovery incident as an out-of-memory exhaustion
3267
+ * when the alarm circuit breaker trips at its strike budget (#1825). Runs
3268
+ * at the outermost alarm frame (post-unwind), so the terminal banner /
3269
+ * `onExhausted` and the sealed-incident write can land where mid-turn
3270
+ * writes OOMed. Reuses the shared give-up spine via the recovery engine.
2776
3271
  */
2777
3272
  async _cf_sealMemoryLimitedRecovery() {
2778
3273
  const active = await listActiveChatRecoveryIncidents(this.ctx.storage);
@@ -2840,6 +3335,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
2840
3335
  return lastMessage?.role === "user" && lastMessage.id === snapshot.latestUserMessageId;
2841
3336
  }
2842
3337
  async _chatRecoveryRetry(data) {
3338
+ await this._dispatchChatRecovery("_chatRecoveryRetry", data, (onTurnStarted) => this._chatRecoveryOriginIdsScope.run(data?.originMessageIds, () => this._chatRecoveryRetryDetached(data, onTurnStarted)));
3339
+ }
3340
+ async _chatRecoveryRetryDetached(data, onTurnStarted) {
3341
+ if (await this._chatRecoveryEngine().isRecoveryCancelled(data?.incidentId)) return;
2843
3342
  const previousRootRequestId = this._activeChatRecoveryRootRequestId;
2844
3343
  this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
2845
3344
  try {
@@ -2864,7 +3363,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
2864
3363
  return;
2865
3364
  }
2866
3365
  this._applyRecoveredRequestContext(data);
3366
+ onTurnStarted?.();
3367
+ this._takeRecoveryReschedule(data?.incidentId);
2867
3368
  const result = await this._retryLastUserTurn(this._lastClientTools, this._lastBody);
3369
+ if (result.status !== "completed" && this._takeRecoveryReschedule(data?.incidentId)) return;
2868
3370
  await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
2869
3371
  } catch (error) {
2870
3372
  if (await this._handleRecoveryOom("_chatRecoveryRetry", data, error)) return;
@@ -2880,33 +3382,53 @@ var AIChatAgent = class AIChatAgent extends Agent {
2880
3382
  _getPartialStreamText(streamId) {
2881
3383
  return aiSdkRecoveryCodec.toRecoveryPartial(this._resumableStream.getStreamChunks(streamId).map((chunk) => chunk.body));
2882
3384
  }
3385
+ /**
3386
+ * The turn whose finished stream is waiting for its message write: the
3387
+ * cutover rides on the instance, not on an argument, so a subclass that
3388
+ * overrides {@link persistMessages} and calls `super` with only the
3389
+ * messages still lands the message, the stream's settlement and the
3390
+ * deletion of its rows in one transaction. Consumed by the first persist
3391
+ * that carries the turn's message; cleared when the turn ends.
3392
+ */
3393
+ #pendingCutover;
2883
3394
  async persistMessages(messages, excludeBroadcastIds = [], options) {
2884
- const mergedMessages = reconcileMessages(messages, this.messages, (msg) => this._sanitizeMessageForPersistence(msg));
3395
+ const priorMessages = [...this.messages];
3396
+ const priorById = new Map(priorMessages.map((m) => [m.id, m]));
3397
+ const mergedMessages = reconcileMessages(messages, priorMessages, (msg) => this._sanitizeMessageForPersistence(msg));
3398
+ const toWrite = [];
2885
3399
  for (const message of mergedMessages) {
2886
- const resolved = resolveToolMergeId(this._sanitizeMessageForPersistence(message), this.messages);
2887
- const safe = this._enforceRowSizeLimit(resolved);
2888
- const json = JSON.stringify(safe);
2889
- if (this._persistedMessageCache.get(safe.id) === json) continue;
2890
- this.sql`
2891
- insert into cf_ai_chat_agent_messages (id, message)
2892
- values (${safe.id}, ${json})
2893
- on conflict(id) do update set message = excluded.message
2894
- `;
2895
- this._persistedMessageCache.set(safe.id, json);
3400
+ const resolved = this._sanitizeMessageForPersistence(message);
3401
+ const prior = priorById.get(resolved.id);
3402
+ if (prior && JSON.stringify(prior) === JSON.stringify(resolved)) continue;
3403
+ toWrite.push(resolved);
2896
3404
  }
3405
+ const cutover = this.#pendingCutover;
3406
+ if (cutover && mergedMessages.some((message) => message.id === cutover.messageId)) {
3407
+ this.#pendingCutover = null;
3408
+ const sync = this.#session.__DO_NOT_USE_WILL_BREAK__sync();
3409
+ const afters = [];
3410
+ try {
3411
+ this._resumableStream.cutover(cutover.streamId, () => {
3412
+ for (const message of toWrite) afters.push(sync.upsert(message).after);
3413
+ }, { discard: cutover.discard });
3414
+ } catch (error) {
3415
+ sync.abandon();
3416
+ throw error;
3417
+ }
3418
+ for (const after of afters) await after();
3419
+ } else for (const message of toWrite) await this.#session.upsertMessage(message);
2897
3420
  if (options?._deleteStaleRows) {
2898
- const serverIds = new Set(this.messages.map((m) => m.id));
2899
- if (mergedMessages.every((m) => serverIds.has(m.id))) {
2900
- const keepIds = new Set(mergedMessages.map((m) => m.id));
2901
- const staleIds = (this.sql`
2902
- select id from cf_ai_chat_agent_messages
2903
- ` || []).map((row) => row.id).filter((id) => !keepIds.has(id));
2904
- this._deleteMessagesByIds(staleIds);
3421
+ const serverIds = new Set(priorMessages.map((message) => message.id));
3422
+ if (mergedMessages.every((message) => serverIds.has(message.id))) {
3423
+ const keepIds = new Set(mergedMessages.map((message) => message.id));
3424
+ await this._deleteMessagesByIds(this.messages.map((message) => message.id).filter((id) => !keepIds.has(id)));
2905
3425
  }
2906
3426
  }
2907
- if (this.maxPersistedMessages != null) this._enforceMaxPersistedMessages();
2908
- const persisted = this._loadMessagesFromDb();
2909
- this.messages = autoTransformMessages(persisted);
3427
+ if (this.maxPersistedMessages != null) {
3428
+ const stored = await this.#session.getHistoryRowStats();
3429
+ const excess = stored.length - this.maxPersistedMessages;
3430
+ if (excess > 0) await this._deleteMessagesByIds(stored.slice(0, excess).map((row) => row.id));
3431
+ }
2910
3432
  this._broadcastChatMessage({
2911
3433
  messages: mergedMessages,
2912
3434
  type: MessageType.CF_AGENT_CHAT_MESSAGES
@@ -2941,38 +3463,29 @@ var AIChatAgent = class AIChatAgent extends Agent {
2941
3463
  };
2942
3464
  }
2943
3465
  /**
2944
- * Sanitizes a message for persistence by removing ephemeral provider-specific
2945
- * data that should not be stored or sent back in subsequent requests.
3466
+ * Applies the ai-chat-specific normalization Sessions does not do.
2946
3467
  *
2947
- * Pipeline:
3468
+ * Sessions already strips OpenAI ephemeral fields (itemId,
3469
+ * reasoningEncryptedContent) and drops truly empty reasoning parts on every
3470
+ * write, so those steps are not repeated here.
2948
3471
  *
2949
- * 1. **Strip OpenAI ephemeral fields**: The AI SDK's @ai-sdk/openai provider
2950
- * (v2.0.x+) defaults to using OpenAI's Responses API which assigns unique
2951
- * itemIds and reasoningEncryptedContent to message parts. When persisted
2952
- * and sent back, OpenAI rejects duplicate itemIds.
3472
+ * Pipeline:
2953
3473
  *
2954
- * 2. **Truncate provider-executed tool payloads**: Server-side tool
3474
+ * 1. **Truncate provider-executed tool payloads**: Server-side tool
2955
3475
  * executions (e.g. Anthropic code_execution, text_editor) can produce
2956
3476
  * 200KB+ payloads in `input` and `output`. These are truncated since the
2957
3477
  * model has already consumed the results.
2958
3478
  *
2959
- * 3. **Filter truly empty reasoning parts**: After stripping, reasoning parts
2960
- * with no text and no remaining providerMetadata are removed. Parts that
2961
- * still carry providerMetadata (e.g. Anthropic's redacted_thinking blocks
2962
- * with providerMetadata.anthropic.redactedData) are preserved, as they
2963
- * contain data required for round-tripping with the provider API.
2964
- *
2965
- * 4. **User hook**: Calls the overridable `sanitizeMessageForPersistence()`
3479
+ * 2. **User hook**: Calls the overridable `sanitizeMessageForPersistence()`
2966
3480
  * method, allowing subclasses to apply custom transformations.
2967
3481
  *
2968
3482
  * @param message - The message to sanitize
2969
- * @returns A new message with ephemeral provider data removed
3483
+ * @returns A new message with ai-chat's normalization applied
2970
3484
  */
2971
3485
  _sanitizeMessageForPersistence(message) {
2972
- const baseSanitized = sanitizeMessage(message);
2973
- const parts = baseSanitized.parts.map((part) => AIChatAgent._truncateProviderExecutedToolPayloads(part));
3486
+ const parts = message.parts.map((part) => AIChatAgent._truncateProviderExecutedToolPayloads(part));
2974
3487
  return this.sanitizeMessageForPersistence({
2975
- ...baseSanitized,
3488
+ ...message,
2976
3489
  parts
2977
3490
  });
2978
3491
  }
@@ -3033,54 +3546,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
3033
3546
  return key.startsWith(PROVIDER_TOOL_OPAQUE_STRING_KEY_PREFIX);
3034
3547
  }
3035
3548
  /**
3036
- * Delete the given message rows from SQLite in batched `IN (...)` queries
3037
- * and evict them from the persistence cache. Batches stay within the SQLite
3038
- * 100 bound-parameter limit. No-op for an empty list.
3039
- * @internal
3549
+ * Delete message rows through Sessions. The change feed removes them from
3550
+ * `this.messages`.
3040
3551
  */
3041
- _deleteMessagesByIds(ids) {
3042
- for (let i = 0; i < ids.length; i += MAX_BOUND_PARAMS) {
3043
- const batch = ids.slice(i, i + MAX_BOUND_PARAMS);
3044
- const strings = buildInClauseStrings("delete from cf_ai_chat_agent_messages where id in ", batch.length);
3045
- this.sql(strings, ...batch);
3046
- for (const id of batch) this._persistedMessageCache.delete(id);
3047
- }
3048
- }
3049
- /**
3050
- * Deletes oldest messages from SQLite when the count exceeds maxPersistedMessages.
3051
- * Called after each persist to keep storage bounded.
3052
- */
3053
- _enforceMaxPersistedMessages() {
3054
- if (this.maxPersistedMessages == null) return;
3055
- const count = this.sql`
3056
- select count(*) as cnt from cf_ai_chat_agent_messages
3057
- `?.[0]?.cnt ?? 0;
3058
- if (count <= this.maxPersistedMessages) return;
3059
- const excess = count - this.maxPersistedMessages;
3060
- const toDelete = this.sql`
3061
- select id from cf_ai_chat_agent_messages
3062
- order by created_at asc
3063
- limit ${excess}
3064
- `;
3065
- if (toDelete && toDelete.length > 0) this._deleteMessagesByIds(toDelete.map((row) => row.id));
3066
- }
3067
- /**
3068
- * Enforces SQLite row size limits by compacting tool outputs and text parts
3069
- * when a serialized message exceeds the safety threshold (1.8MB).
3070
- *
3071
- * Only fires in pathological cases (extremely large tool outputs or text).
3072
- * Returns the message unchanged if it fits within limits.
3073
- *
3074
- * Compaction strategy:
3075
- * 1. Compact tool outputs over 1KB (replace with LLM-friendly summary)
3076
- * 2. If still too big, truncate text parts from oldest to newest
3077
- * 3. Add metadata so clients can detect compaction
3078
- *
3079
- * @param message - The message to check
3080
- * @returns The message, compacted if necessary
3081
- */
3082
- _enforceRowSizeLimit(message) {
3083
- return enforceRowSizeLimit(message, { warn: (m) => console.warn(`[AIChatAgent] ${m}`) });
3552
+ async _deleteMessagesByIds(ids) {
3553
+ if (ids.length === 0) return;
3554
+ await this.#session.deleteMessages(ids);
3084
3555
  }
3085
3556
  /**
3086
3557
  * Shared helper for finding a tool part by toolCallId and applying an update.
@@ -3148,16 +3619,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
3148
3619
  ...message,
3149
3620
  parts: updatedParts
3150
3621
  });
3151
- const safe = this._enforceRowSizeLimit(updatedMessage);
3152
- const json = JSON.stringify(safe);
3153
- this.sql`
3154
- update cf_ai_chat_agent_messages
3155
- set message = ${json}
3156
- where id = ${message.id}
3157
- `;
3158
- this._persistedMessageCache.set(message.id, json);
3159
- const persisted = this._loadMessagesFromDb();
3160
- this.messages = autoTransformMessages(persisted);
3622
+ if (!await this.#session.updateMessage(updatedMessage)) {
3623
+ const index = this.messages.findIndex((candidate) => candidate.id === updatedMessage.id);
3624
+ if (index !== -1) this.messages[index] = autoTransformMessages([updatedMessage])[0];
3625
+ }
3161
3626
  }
3162
3627
  }
3163
3628
  if (!wasFound) {
@@ -3267,6 +3732,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3267
3732
  streamCompleted.value = false;
3268
3733
  let continuationTextResumed = false;
3269
3734
  let continuationReasoningResumed = false;
3735
+ let finishReason;
3270
3736
  if (abortSignal && !abortSignal.aborted) abortSignal.addEventListener("abort", () => {
3271
3737
  reader.cancel().catch(() => {});
3272
3738
  }, { once: true });
@@ -3319,7 +3785,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3319
3785
  const { done, value } = readResult;
3320
3786
  if (done) {
3321
3787
  if (abortSignal?.aborted) break;
3322
- this._completeStream(streamId);
3788
+ this._finishStream(streamId);
3323
3789
  streamCompleted.value = true;
3324
3790
  this._broadcastChatMessage({
3325
3791
  body: "",
@@ -3328,7 +3794,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
3328
3794
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
3329
3795
  ...continuation && { continuation: true }
3330
3796
  });
3331
- return { status: "completed" };
3797
+ return {
3798
+ status: "completed",
3799
+ finishReason
3800
+ };
3332
3801
  }
3333
3802
  const lines = decoder.decode(value).split("\n");
3334
3803
  for (const line of lines) if (line.startsWith("data: ") && line !== "data: [DONE]") try {
@@ -3360,7 +3829,25 @@ var AIChatAgent = class AIChatAgent extends Agent {
3360
3829
  skipServerApply = continuationReasoningResumed;
3361
3830
  }
3362
3831
  }
3363
- 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
+ }
3364
3851
  const handled = skipServerApply ? true : applyChunkToParts(message.parts, data);
3365
3852
  if (data.type === "tool-approval-request" && this._streamingMessage) {
3366
3853
  const snapshot = {
@@ -3368,13 +3855,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
3368
3855
  parts: [...this._streamingMessage.parts]
3369
3856
  };
3370
3857
  const sanitized = this._sanitizeMessageForPersistence(snapshot);
3371
- const json = JSON.stringify(sanitized);
3372
- this.sql`
3373
- INSERT INTO cf_ai_chat_agent_messages (id, message)
3374
- VALUES (${sanitized.id}, ${json})
3375
- ON CONFLICT(id) DO UPDATE SET message = excluded.message
3376
- `;
3377
- this._approvalPersistedMessageId = sanitized.id;
3858
+ const stored = await this.#session.upsertMessage(sanitized);
3859
+ this._approvalPersistedMessageId = stored.message.id;
3378
3860
  }
3379
3861
  if ((data.type === "tool-output-available" || data.type === "tool-output-error") && data.toolCallId) {
3380
3862
  if (!message.parts.some((p) => "toolCallId" in p && p.toolCallId === data.toolCallId)) if (data.type === "tool-output-available") this._findAndUpdateToolPart(data.toolCallId, "_streamSSEReply", [
@@ -3446,6 +3928,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3446
3928
  done: true,
3447
3929
  id,
3448
3930
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
3931
+ outcome: "error",
3449
3932
  ...continuation && { continuation: true }
3450
3933
  });
3451
3934
  return {
@@ -3468,37 +3951,43 @@ var AIChatAgent = class AIChatAgent extends Agent {
3468
3951
  }
3469
3952
  }
3470
3953
  if (data.type === "finish" && "finishReason" in data) {
3471
- const { finishReason, ...rest } = data;
3954
+ const { finishReason: chunkFinishReason, ...rest } = data;
3955
+ finishReason = chunkFinishReason;
3472
3956
  eventToSend = {
3473
3957
  ...rest,
3474
3958
  type: "finish",
3475
- messageMetadata: { finishReason }
3959
+ messageMetadata: { finishReason: chunkFinishReason }
3476
3960
  };
3477
3961
  }
3478
3962
  const chunkBody = JSON.stringify(eventToSend);
3479
- await this._storeStreamChunk(streamId, chunkBody);
3963
+ const seq = await this._storeStreamChunk(streamId, chunkBody);
3480
3964
  this._broadcastChatMessage({
3481
3965
  body: chunkBody,
3482
3966
  done: false,
3483
3967
  id,
3484
3968
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
3969
+ ...seq !== void 0 && { seq },
3485
3970
  ...continuation && { continuation: true }
3486
3971
  });
3487
3972
  } catch (_error) {}
3488
3973
  }
3489
3974
  if (!streamCompleted.value) {
3490
- this._completeStream(streamId);
3975
+ this._finishStream(streamId, "aborted");
3491
3976
  streamCompleted.value = true;
3492
3977
  this._broadcastChatMessage({
3493
3978
  body: "",
3494
3979
  done: true,
3495
3980
  id,
3496
3981
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
3982
+ outcome: "aborted",
3497
3983
  ...continuation && { continuation: true }
3498
3984
  });
3499
3985
  return { status: "aborted" };
3500
3986
  }
3501
- return { status: "completed" };
3987
+ return {
3988
+ status: "completed",
3989
+ finishReason
3990
+ };
3502
3991
  }
3503
3992
  async _sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation = false, abortSignal) {
3504
3993
  let textPart;
@@ -3541,7 +4030,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3541
4030
  type: "text-end",
3542
4031
  id
3543
4032
  }, continuation);
3544
- this._completeStream(streamId);
4033
+ this._finishStream(streamId);
3545
4034
  streamCompleted.value = true;
3546
4035
  this._broadcastChatMessage({
3547
4036
  body: "",
@@ -3568,13 +4057,14 @@ var AIChatAgent = class AIChatAgent extends Agent {
3568
4057
  type: "text-end",
3569
4058
  id
3570
4059
  }, continuation);
3571
- this._completeStream(streamId);
4060
+ this._finishStream(streamId, "aborted");
3572
4061
  streamCompleted.value = true;
3573
4062
  this._broadcastChatMessage({
3574
4063
  body: "",
3575
4064
  done: true,
3576
4065
  id,
3577
4066
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
4067
+ outcome: "aborted",
3578
4068
  ...continuation && { continuation: true }
3579
4069
  });
3580
4070
  return { status: "aborted" };
@@ -3598,7 +4088,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3598
4088
  return this._findAndUpdateToolPart(toolCallId, "_applyToolApproval", update.matchStates, update.apply);
3599
4089
  }
3600
4090
  async _reply(id, response, excludeBroadcastIds = [], options = {}) {
3601
- const { continuation = false, chatMessageId } = options;
4091
+ const { continuation = false, chatMessageId, onStreamStart } = options;
3602
4092
  const abortSignal = chatMessageId ? this._abortRegistry.getExistingSignal(chatMessageId) : void 0;
3603
4093
  return this.keepAliveWhile(() => this._tryCatchChat(async () => {
3604
4094
  if (!response.body) {
@@ -3613,39 +4103,64 @@ var AIChatAgent = class AIChatAgent extends Agent {
3613
4103
  this._activateDeferredAutoContinuation();
3614
4104
  return { status: "completed" };
3615
4105
  }
3616
- const message = this._createStreamingAssistantMessage(continuation);
3617
- const streamId = this._startStream(id, {
3618
- messageId: message.id,
3619
- continuation
3620
- });
3621
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
+ }
3622
4119
  this._streamingMessage = message;
3623
4120
  const isSSE = (response.headers.get("content-type") || "").includes("text/event-stream");
3624
4121
  const streamCompleted = { value: false };
3625
4122
  let streamResult = { status: "completed" };
3626
4123
  let earlyPersistedId = null;
3627
4124
  let stallRouted = false;
4125
+ let discardPartial = false;
3628
4126
  this._streamingTurnActive = true;
4127
+ this._heldTerminalFrames.set(id, []);
4128
+ let persisted = false;
4129
+ onStreamStart?.();
3629
4130
  try {
3630
4131
  try {
3631
4132
  if (isSSE) streamResult = await this._streamSSEReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
3632
4133
  else streamResult = await this._sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
3633
4134
  } catch (error) {
3634
- if (error instanceof ChatStreamStalledError && !streamCompleted.value) {
4135
+ if (!streamCompleted.value && (error instanceof ChatStreamStalledError || !abortSignal?.aborted && isRecoverableStreamReadError(error))) {
3635
4136
  const targetAssistantId = message.parts.length > 0 ? message.id : void 0;
3636
- const outcome = await this._routeStallToBoundedRecovery({
4137
+ const outcome = await this._routeStreamInterruption({
3637
4138
  requestId: id,
3638
4139
  streamId,
3639
4140
  partialParts: message.parts,
3640
- 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
+ }
3641
4155
  });
3642
4156
  if (outcome === "scheduled") {
3643
- this._completeStream(streamId);
4157
+ this._completeStream(streamId, "recovering");
3644
4158
  this._broadcastChatMessage({
3645
4159
  body: "",
3646
4160
  done: true,
3647
4161
  id,
3648
4162
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
4163
+ outcome: "recovering",
3649
4164
  ...continuation && { continuation: true }
3650
4165
  });
3651
4166
  streamResult = { status: "aborted" };
@@ -3688,7 +4203,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
3688
4203
  if (streamCompleted.value && streamResult.status !== "error" && !stallRouted) this._emit("message:response");
3689
4204
  }
3690
4205
  }
3691
- if (message.parts.length > 0) if (earlyPersistedId) {
4206
+ this.#pendingCutover = this._resumableStream.pendingCutoverId === streamId ? {
4207
+ streamId,
4208
+ messageId: earlyPersistedId ?? message.id,
4209
+ discard: !this._agentToolRunsByRequestId.get(id)
4210
+ } : null;
4211
+ if (message.parts.length > 0 && !discardPartial) if (earlyPersistedId) {
3692
4212
  const persistedMessage = {
3693
4213
  ...message,
3694
4214
  id: earlyPersistedId
@@ -3706,6 +4226,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
3706
4226
  await this.persistMessages(updatedMessages, excludeBroadcastIds);
3707
4227
  } else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
3708
4228
  } else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
4229
+ this.#pendingCutover = null;
4230
+ this._resumableStream.finalizePending();
4231
+ persisted = true;
4232
+ this._releaseTerminalFrames(id);
3709
4233
  this._pendingChatResponseResults.push({
3710
4234
  message,
3711
4235
  requestId: id,
@@ -3715,7 +4239,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
3715
4239
  });
3716
4240
  return streamResult;
3717
4241
  } finally {
3718
- this._onStreamingTurnFinalized();
4242
+ this.#pendingCutover = null;
4243
+ this._resumableStream.finalizePending();
4244
+ this._releaseTerminalFrames(id, persisted ? void 0 : "Failed to save the response.");
4245
+ this._onStreamingTurnFinalized(streamResult.finishReason);
3719
4246
  }
3720
4247
  }));
3721
4248
  }