@cloudflare/ai-chat 0.8.5 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,39 +1,9 @@
1
- import "./types.js";
1
+ import { MessageType } from "./types.js";
2
2
  import { autoTransformMessages } from "./ai-chat-v5-migration.js";
3
3
  import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
4
- import { AbortRegistry, ContinuationState, MAX_BOUND_PARAMS, ROW_MAX_BYTES, ResumableStream, SubmitConcurrencyController, TurnQueue, applyChunkToParts, buildInClauseStrings, byteLength, createChatFiberSnapshot, createToolsFromClientSchemas, isReplayChunk, reconcileMessages, resolveToolMergeId, sanitizeMessage, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
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, parseProtocolMessage, partAwaitsClientInteraction, pendingChatTerminal, persistReconstructedOrphan, readChatRecoveryProgress, reconcileMessages, reconcileOrphanPartial, recordChatTerminal, repairInterruptedToolParts, resolveChatRecoveryConfig, resolveToolMergeId, runChatRecoveryExhaustion, sanitizeMessage, sendIfOpen, setChatRecovering, shouldCreditStreamProgress, sweepStaleChatRecoveryIncidents, toolApprovalUpdate, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
5
5
  import { nanoid } from "nanoid";
6
6
  //#region src/index.ts
7
- const CHAT_RECOVERY_INCIDENT_KEY_PREFIX = "cf:chat-recovery:incident:";
8
- const CHAT_RECOVERY_PROGRESS_KEY = "cf:chat-recovery:progress";
9
- const DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS = 10;
10
- const DEFAULT_CHAT_RECOVERY_MAX_WORK = Number.POSITIVE_INFINITY;
11
- const DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS = 1e4;
12
- const AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS = 6e4;
13
- const CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS = 3;
14
- const DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE = "The assistant was interrupted and could not recover. Please try again.";
15
- const CHAT_RECOVERING_KEY = "cf:chat:recovering";
16
- const CHAT_LAST_TERMINAL_KEY = "cf:chat:last-terminal";
17
- const CHAT_RECOVERY_INCIDENT_TTL_MS = 3600 * 1e3;
18
- const KV_DELETE_MAX_KEYS = 128;
19
- const DEFAULT_CHAT_RECOVERY_NO_PROGRESS_TIMEOUT_MS = 300 * 1e3;
20
- const CHAT_RECOVERY_ALARM_DEBOUNCE_MS = 30 * 1e3;
21
- const CHAT_RECOVERING_FLAG_TTL_MS = 900 * 1e3;
22
- const AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS = 5e3;
23
- const STREAM_CLEANUP_DELAY_SECONDS = 600;
24
- function sendIfOpen(connection, message) {
25
- try {
26
- connection.send(message);
27
- return true;
28
- } catch (error) {
29
- if (isWebSocketClosedSendError(error)) return false;
30
- throw error;
31
- }
32
- }
33
- function isWebSocketClosedSendError(error) {
34
- return error instanceof TypeError && error.message.includes("WebSocket send() after close");
35
- }
36
- const TIMED_OUT = Symbol("timed-out");
37
7
  /**
38
8
  * Provider-executed tool fields that contain opaque replay tokens and must be
39
9
  * persisted exactly as returned by the provider.
@@ -71,9 +41,6 @@ const agentToolChunkEncoder = new TextEncoder();
71
41
  * @template Env Environment type containing bindings
72
42
  */
73
43
  var AIChatAgent = class AIChatAgent extends Agent {
74
- static {
75
- this.AUTO_CONTINUATION_COALESCE_MS = 10;
76
- }
77
44
  static {
78
45
  this.MESSAGE_DEBOUNCE_MS = 750;
79
46
  }
@@ -93,25 +60,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
93
60
  });
94
61
  }
95
62
  broadcast(msg, without) {
96
- if ((this._agentToolForwarders.size > 0 || this._agentToolLiveSequences.size > 0) && typeof msg === "string") try {
97
- const parsed = JSON.parse(msg);
98
- if (parsed.type === "cf_agent_use_chat_response" && typeof parsed.id === "string") {
99
- const runId = this._agentToolRunForRequest(parsed.id);
100
- if (runId !== null) {
101
- if (parsed.error === true && typeof parsed.body === "string") this._agentToolLastErrors.set(runId, parsed.body);
102
- else if (typeof parsed.body === "string" && parsed.body.length > 0) {
103
- const sequence = this._agentToolLiveSequences.get(runId) ?? 0;
104
- this._agentToolLiveSequences.set(runId, sequence + 1);
105
- const chunk = {
106
- sequence,
107
- body: parsed.body
108
- };
109
- const forwarders = this._agentToolForwarders.get(runId);
110
- if (forwarders) for (const forward of forwarders) forward(chunk);
111
- }
112
- }
113
- }
114
- } catch {}
63
+ if (this._agentToolForwarders.size > 0 || this._agentToolLiveSequences.size > 0) interceptAgentToolBroadcast(msg, {
64
+ forwarders: this._agentToolForwarders,
65
+ liveSequences: this._agentToolLiveSequences,
66
+ lastErrors: this._agentToolLastErrors,
67
+ responseType: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
68
+ runForRequest: (requestId) => this._agentToolRunForRequest(requestId)
69
+ });
115
70
  super.broadcast(msg, without);
116
71
  }
117
72
  /**
@@ -125,12 +80,60 @@ var AIChatAgent = class AIChatAgent extends Agent {
125
80
  if (cached !== void 0) return cached;
126
81
  const runId = this.sql`
127
82
  select run_id from cf_ai_chat_agent_tool_runs
128
- where request_id = ${requestId} and status = 'running'
83
+ where request_id = ${requestId} and status in ('starting', 'running')
129
84
  limit 1
130
85
  `?.[0]?.run_id ?? null;
131
86
  this._agentToolRunsByRequestId.set(requestId, runId);
132
87
  return runId;
133
88
  }
89
+ /**
90
+ * Re-bind this facet's in-flight agent-tool child run to the CURRENT turn's
91
+ * request id. Parity with `@cloudflare/think`'s
92
+ * `_rebindAgentToolChildRunRequestId`.
93
+ *
94
+ * When this facet runs as an agent-tool child and its turn is interrupted, the
95
+ * recovery continuation (`continueLastTurn` / `_retryLastUserTurn`) mints a NEW
96
+ * request id but never flows through `startAgentToolRun`'s
97
+ * `_registerAgentToolTurn`. So `cf_ai_chat_agent_tool_runs.request_id` (and the
98
+ * in-memory attribution map) still point at the pre-eviction turn, and
99
+ * `broadcast` can no longer attribute the recovered turn's frames to the run.
100
+ * A long-running child then forwards nothing to the parent's re-attach tail,
101
+ * its no-progress budget elapses, and a healthy child is abandoned as
102
+ * `interrupted`. Re-binding keeps attribution alive across recovery.
103
+ *
104
+ * Safe to call on EVERY recovery continuation:
105
+ * - Facets that never ran as an agent-tool child have no
106
+ * `cf_ai_chat_agent_tool_runs` table → the guarded SELECT throws → no-op.
107
+ * - A facet whose run already settled has no active row → no-op.
108
+ * - A child DO is addressed by its `runId` (`subAgent(cls, runId)`), so it
109
+ * owns AT MOST ONE child-run row for its whole lifetime and is never reused
110
+ * as a top-level chat agent — the single active row is unambiguously this
111
+ * recovery's run. The `order by started_at desc limit 1` is defensive
112
+ * belt-and-suspenders for that invariant.
113
+ *
114
+ * Uses the same `status in ('starting','running')` active-run predicate as
115
+ * `_agentToolRunForRequest` and the `@cloudflare/think` counterpart.
116
+ */
117
+ _rebindAgentToolChildRunRequestId(requestId) {
118
+ let runId;
119
+ try {
120
+ runId = this.sql`
121
+ select run_id from cf_ai_chat_agent_tool_runs
122
+ where status in ('starting', 'running')
123
+ order by started_at desc
124
+ limit 1
125
+ `?.[0]?.run_id;
126
+ } catch {
127
+ return;
128
+ }
129
+ if (!runId) return;
130
+ this._agentToolRunsByRequestId.set(requestId, runId);
131
+ this.sql`
132
+ update cf_ai_chat_agent_tool_runs
133
+ set request_id = ${requestId}
134
+ where run_id = ${runId}
135
+ `;
136
+ }
134
137
  constructor(ctx, env) {
135
138
  super(ctx, env);
136
139
  this._streamingMessage = null;
@@ -141,10 +144,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
141
144
  this._approvalPersistedMessageId = null;
142
145
  this._turnQueue = new TurnQueue();
143
146
  this.chatRecovery = false;
147
+ this.chatStreamStallTimeoutMs = 0;
144
148
  this._mergeQueuedUserStartIndexByEpoch = /* @__PURE__ */ new Map();
145
149
  this._submitConcurrency = new SubmitConcurrencyController({ defaultDebounceMs: AIChatAgent.MESSAGE_DEBOUNCE_MS });
146
150
  this._pendingResumeConnections = /* @__PURE__ */ new Set();
151
+ this._resumeHandshakeInstance = null;
147
152
  this._continuation = new ContinuationState();
153
+ this._preStream = new PreStreamTurns();
148
154
  this._agentToolForwarders = /* @__PURE__ */ new Map();
149
155
  this._agentToolClosers = /* @__PURE__ */ new Map();
150
156
  this._agentToolAbortControllers = /* @__PURE__ */ new Map();
@@ -153,11 +159,26 @@ var AIChatAgent = class AIChatAgent extends Agent {
153
159
  this._agentToolLiveSequences = /* @__PURE__ */ new Map();
154
160
  this._agentToolRunsByRequestId = /* @__PURE__ */ new Map();
155
161
  this._persistedMessageCache = /* @__PURE__ */ new Map();
162
+ this._autoContinuation = new AutoContinuationController({
163
+ continuation: this._continuation,
164
+ generateRequestId: () => nanoid(),
165
+ isStreamActive: () => this._streamingTurnActive,
166
+ hasPendingInteraction: () => this._pendingInteractionPromise !== null,
167
+ hasIncompleteToolBatch: () => this._hasIncompleteToolBatch(),
168
+ drainInteractionApplies: () => this._drainInteractionApplies(),
169
+ keepAliveWhile: (fn) => this.keepAliveWhile(fn),
170
+ fire: () => this._fireAutoContinuation()
171
+ });
172
+ this._streamingTurnActive = false;
156
173
  this.maxPersistedMessages = void 0;
157
174
  this.messageConcurrency = "queue";
158
175
  this.waitForMcpConnections = { timeout: 1e4 };
159
176
  this.messages = [];
160
- this._lastAgentToolStreamProgressAt = 0;
177
+ this._streamProgressCredit = new StreamProgressCreditThrottle();
178
+ this._agentToolProgressEmitterInstance = null;
179
+ this._inSerializedDetachedDeliverySlot = false;
180
+ this._inFlightDetachedNotifications = /* @__PURE__ */ new Set();
181
+ this._agentToolStreamProgress = new AgentToolStreamProgressThrottle();
161
182
  this.sql`create table if not exists cf_ai_chat_agent_messages (
162
183
  id text primary key,
163
184
  message text not null,
@@ -177,26 +198,27 @@ var AIChatAgent = class AIChatAgent extends Agent {
177
198
  this.onConnect = async (connection, ctx) => {
178
199
  if (this._cf_requestTargetsSubAgent(ctx.request)) return _onConnect(connection, ctx);
179
200
  if (this._resumableStream.hasActiveStream()) this._notifyStreamResuming(connection);
201
+ else if (this._preStream.park(connection)) {} else {
202
+ const recoveringFrame = await this._buildRecoveringConnectFrame();
203
+ if (recoveringFrame) sendIfOpen(connection, JSON.stringify(recoveringFrame));
204
+ }
180
205
  return _onConnect(connection, ctx);
181
206
  };
182
207
  const _onClose = this.onClose.bind(this);
183
208
  this.onClose = async (connection, code, reason, wasClean) => {
184
209
  this._pendingResumeConnections.delete(connection.id);
185
210
  this._continuation.releaseConnection(connection.id);
211
+ this._preStream.release(connection.id);
186
212
  return _onClose(connection, code, reason, wasClean);
187
213
  };
188
214
  const _onMessage = this.onMessage.bind(this);
189
215
  this.onMessage = async (connection, message) => {
190
216
  if (this._cf_connectionTargetsSubAgent(connection)) return _onMessage(connection, message);
191
217
  if (typeof message === "string") {
192
- let data;
193
- try {
194
- data = JSON.parse(message);
195
- } catch (_error) {
196
- return _onMessage(connection, message);
197
- }
198
- if (data.type === "cf_agent_use_chat_request" && data.init.method === "POST") {
199
- const { body } = data.init;
218
+ const event = parseProtocolMessage(message);
219
+ if (!event) return _onMessage(connection, message);
220
+ if (event.type === "chat-request" && event.init.method === "POST") {
221
+ const { body } = event.init;
200
222
  if (!body) {
201
223
  console.warn("[AIChatAgent] Received chat request with empty body, ignoring");
202
224
  return;
@@ -209,7 +231,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
209
231
  return;
210
232
  }
211
233
  const { messages, clientTools, trigger: _trigger, ...customBody } = parsed;
212
- const chatMessageId = data.id;
234
+ const chatMessageId = event.id;
213
235
  const transformedMessages = autoTransformMessages(messages);
214
236
  const requestTrigger = _trigger === "regenerate-message" ? "regenerate-message" : "submit-message";
215
237
  const requestClientTools = clientTools?.length ? clientTools : void 0;
@@ -222,138 +244,135 @@ var AIChatAgent = class AIChatAgent extends Agent {
222
244
  return;
223
245
  }
224
246
  await this._clearChatTerminal();
225
- const releasePendingEnqueue = this._submitConcurrency.beginEnqueue();
247
+ this._preStream.begin(chatMessageId);
226
248
  try {
227
- this._broadcastChatMessage({
228
- messages: transformedMessages,
229
- type: "cf_agent_chat_messages"
230
- }, [connection.id]);
231
- await this.persistMessages(transformedMessages, [connection.id], { _deleteStaleRows: true });
232
- if (concurrencyDecision.strategy === "merge") await this._mergeQueuedUserMessages(epoch);
233
- } finally {
234
- releasePendingEnqueue();
235
- }
236
- return this._runExclusiveChatTurn(chatMessageId, async () => {
237
- if (this._submitConcurrency.isSuperseded(concurrencyDecision.submitSequence)) {
238
- this._completeSkippedRequest(connection, chatMessageId);
239
- return;
249
+ const releasePendingEnqueue = this._submitConcurrency.beginEnqueue();
250
+ try {
251
+ this._broadcastChatMessage({
252
+ messages: transformedMessages,
253
+ type: MessageType.CF_AGENT_CHAT_MESSAGES
254
+ }, [connection.id]);
255
+ await this.persistMessages(transformedMessages, [connection.id], { _deleteStaleRows: true });
256
+ if (concurrencyDecision.strategy === "merge") await this._mergeQueuedUserMessages(epoch);
257
+ } finally {
258
+ releasePendingEnqueue();
240
259
  }
241
- if (concurrencyDecision.debounceUntilMs !== null) {
242
- await this._submitConcurrency.waitForTimestamp(concurrencyDecision.debounceUntilMs);
243
- if (this._turnQueue.generation !== epoch) {
244
- this._completeSkippedRequest(connection, chatMessageId);
245
- return;
246
- }
260
+ await this._runExclusiveChatTurn(chatMessageId, async () => {
247
261
  if (this._submitConcurrency.isSuperseded(concurrencyDecision.submitSequence)) {
248
262
  this._completeSkippedRequest(connection, chatMessageId);
249
263
  return;
250
264
  }
251
- }
252
- if (concurrencyDecision.strategy === "merge") {
253
- await this._mergeQueuedUserMessages(epoch);
254
- if (this._turnQueue.generation !== epoch) {
255
- this._completeSkippedRequest(connection, chatMessageId);
256
- return;
265
+ if (concurrencyDecision.debounceUntilMs !== null) {
266
+ await this._submitConcurrency.waitForTimestamp(concurrencyDecision.debounceUntilMs);
267
+ if (this._turnQueue.generation !== epoch) {
268
+ this._completeSkippedRequest(connection, chatMessageId);
269
+ return;
270
+ }
271
+ if (this._submitConcurrency.isSuperseded(concurrencyDecision.submitSequence)) {
272
+ this._completeSkippedRequest(connection, chatMessageId);
273
+ return;
274
+ }
257
275
  }
258
- if (this._submitConcurrency.isSuperseded(concurrencyDecision.submitSequence)) {
259
- this._completeSkippedRequest(connection, chatMessageId);
260
- return;
276
+ if (concurrencyDecision.strategy === "merge") {
277
+ await this._mergeQueuedUserMessages(epoch);
278
+ if (this._turnQueue.generation !== epoch) {
279
+ this._completeSkippedRequest(connection, chatMessageId);
280
+ return;
281
+ }
282
+ if (this._submitConcurrency.isSuperseded(concurrencyDecision.submitSequence)) {
283
+ this._completeSkippedRequest(connection, chatMessageId);
284
+ return;
285
+ }
261
286
  }
262
- }
263
- if (this.waitForMcpConnections) {
264
- const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : void 0;
265
- await this.mcp.waitForConnections(timeout != null ? { timeout } : void 0);
266
- }
267
- this._setRequestContext(requestClientTools, requestBody);
268
- this._emit("message:request");
269
- const abortSignal = this._abortRegistry.getSignal(chatMessageId);
270
- return this._tryCatchChat(async () => {
271
- return __DO_NOT_USE_WILL_BREAK__agentContext.run({
272
- agent: this,
273
- connection,
274
- request: void 0,
275
- email: void 0
276
- }, async () => {
277
- const chatTurnBody = async () => {
278
- try {
279
- const response = await this.onChatMessage(async (_finishResult) => {}, {
280
- requestId: chatMessageId,
281
- abortSignal,
282
- clientTools: requestClientTools,
283
- body: requestBody,
284
- continuation: false
285
- });
286
- if (response) await this._reply(chatMessageId, response, [connection.id], { chatMessageId });
287
- else {
288
- console.warn(`[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`);
289
- this._broadcastChatMessage({
290
- body: "No response was generated by the agent.",
291
- done: true,
292
- id: chatMessageId,
293
- type: "cf_agent_use_chat_response"
294
- }, [connection.id]);
287
+ if (this.waitForMcpConnections) {
288
+ const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : void 0;
289
+ await this.mcp.waitForConnections(timeout != null ? { timeout } : void 0);
290
+ }
291
+ this._setRequestContext(requestClientTools, requestBody);
292
+ this._emit("message:request");
293
+ const abortSignal = this._abortRegistry.getSignal(chatMessageId);
294
+ return this._tryCatchChat(async () => {
295
+ return __DO_NOT_USE_WILL_BREAK__agentContext.run({
296
+ agent: this,
297
+ connection,
298
+ request: void 0,
299
+ email: void 0
300
+ }, async () => {
301
+ const chatTurnBody = async () => {
302
+ try {
303
+ await this._repairInterruptedToolsBeforeTurn();
304
+ const response = await this.onChatMessage(async (_finishResult) => {}, {
305
+ requestId: chatMessageId,
306
+ abortSignal,
307
+ clientTools: requestClientTools,
308
+ body: requestBody,
309
+ continuation: false
310
+ });
311
+ if (response) await this._reply(chatMessageId, response, [connection.id], { chatMessageId });
312
+ else {
313
+ console.warn(`[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`);
314
+ this._broadcastChatMessage({
315
+ body: "No response was generated by the agent.",
316
+ done: true,
317
+ id: chatMessageId,
318
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
319
+ }, [connection.id]);
320
+ }
321
+ } finally {
322
+ this._abortRegistry.remove(chatMessageId);
323
+ this._settlePreStreamTurn(chatMessageId);
295
324
  }
296
- } finally {
297
- this._abortRegistry.remove(chatMessageId);
298
- }
299
- };
300
- if (this.chatRecovery) await this._runChatRecoveryFiber(chatMessageId, false, chatTurnBody);
301
- else await chatTurnBody();
325
+ };
326
+ if (this.chatRecovery) await this._runChatRecoveryFiber(chatMessageId, false, chatTurnBody);
327
+ else await chatTurnBody();
328
+ });
302
329
  });
330
+ }, {
331
+ epoch,
332
+ onStale: () => this._completeSkippedRequest(connection, chatMessageId)
303
333
  });
304
- }, {
305
- epoch,
306
- onStale: () => this._completeSkippedRequest(connection, chatMessageId)
307
- });
334
+ } finally {
335
+ this._settlePreStreamTurn(chatMessageId);
336
+ }
337
+ return;
308
338
  }
309
- if (data.type === "cf_agent_chat_clear") {
339
+ if (event.type === "clear") {
310
340
  this.resetTurnState();
311
341
  this.sql`delete from cf_ai_chat_agent_messages`;
312
342
  await this._clearChatTerminal();
313
343
  this._resumableStream.clearAll();
314
344
  this._pendingResumeConnections.clear();
345
+ this._preStream.releaseAwaiting();
346
+ this._preStream.reset();
315
347
  this._lastClientTools = void 0;
316
348
  this._lastBody = void 0;
317
349
  this._persistRequestContext();
318
350
  this._persistedMessageCache.clear();
319
351
  this.messages = [];
320
- this._broadcastChatMessage({ type: "cf_agent_chat_clear" }, [connection.id]);
352
+ this._broadcastChatMessage({ type: MessageType.CF_AGENT_CHAT_CLEAR }, [connection.id]);
321
353
  this._emit("message:clear");
322
354
  return;
323
355
  }
324
- if (data.type === "cf_agent_chat_messages") {
325
- const transformedMessages = autoTransformMessages(data.messages);
356
+ if (event.type === "messages") {
357
+ const transformedMessages = autoTransformMessages(event.messages);
326
358
  await this.persistMessages(transformedMessages, [connection.id]);
327
359
  return;
328
360
  }
329
- if (data.type === "cf_agent_chat_request_cancel") {
330
- this._abortRegistry.cancel(data.id);
331
- this._emit("message:cancel", { requestId: data.id });
361
+ if (event.type === "cancel") {
362
+ this._abortRegistry.cancel(event.id);
363
+ this._emit("message:cancel", { requestId: event.id });
332
364
  return;
333
365
  }
334
- if (data.type === "cf_agent_stream_resume_request") {
335
- if (this._resumableStream.hasActiveStream()) if (this._continuation.activeRequestId === this._resumableStream.activeRequestId && this._continuation.activeConnectionId !== null && this._continuation.activeConnectionId !== connection.id) sendIfOpen(connection, JSON.stringify({ type: "cf_agent_stream_resume_none" }));
336
- else this._notifyStreamResuming(connection);
337
- else if (this._continuation.pending !== null && (this._continuation.pending.connectionId === null || this._continuation.pending.connectionId === connection.id)) this._continuation.awaitingConnections.set(connection.id, connection);
338
- else if (await this._replayTerminalOnResume(connection)) {} else sendIfOpen(connection, JSON.stringify({ type: "cf_agent_stream_resume_none" }));
366
+ if (event.type === "stream-resume-request") {
367
+ await this._resumeHandshake().handleResumeRequest(connection);
339
368
  return;
340
369
  }
341
- if (data.type === "cf_agent_stream_resume_ack") {
342
- this._pendingResumeConnections.delete(connection.id);
343
- if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === data.id) {
344
- const orphanedStreamId = this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
345
- if (orphanedStreamId) await this._persistOrphanedStream(orphanedStreamId);
346
- } else if (this._resumableStream.hasActiveStream()) {} else if (await this._replayTerminalOnAck(connection, data.id)) {} else if (!this._resumableStream.replayCompletedChunksByRequestId(connection, data.id)) sendIfOpen(connection, JSON.stringify({
347
- body: "",
348
- done: true,
349
- id: data.id,
350
- type: "cf_agent_use_chat_response",
351
- replay: true
352
- }));
370
+ if (event.type === "stream-resume-ack") {
371
+ await this._resumeHandshake().handleResumeAck(connection, event.id);
353
372
  return;
354
373
  }
355
- if (data.type === "cf_agent_tool_result") {
356
- const { toolCallId, toolName, output, state, errorText, autoContinue, clientTools } = data;
374
+ if (event.type === "tool-result") {
375
+ const { toolCallId, toolName, output, state, errorText, autoContinue, clientTools } = event;
357
376
  if (clientTools?.length) {
358
377
  this._lastClientTools = clientTools;
359
378
  this._persistRequestContext();
@@ -363,18 +382,20 @@ var AIChatAgent = class AIChatAgent extends Agent {
363
382
  toolCallId,
364
383
  toolName
365
384
  });
366
- const applyPromise = this._enqueueInteractionApply(() => this._applyToolResult(toolCallId, toolName, output, overrideState, errorText));
367
- if (autoContinue) this._enqueueAutoContinuation(connection, clientTools ?? this._lastClientTools, this._lastBody, "[AIChatAgent] Tool continuation failed:", applyPromise);
385
+ this._enqueueInteractionApply(() => this._applyToolResult(toolCallId, toolName, output, overrideState, errorText));
386
+ if (autoContinue) this._scheduleAutoContinuation(connection, clientTools ?? this._lastClientTools, this._lastBody, "[AIChatAgent] Tool continuation failed:");
387
+ else this._rearmPendingAutoContinuationForBatch();
368
388
  return;
369
389
  }
370
- if (data.type === "cf_agent_tool_approval") {
371
- const { toolCallId, approved, autoContinue } = data;
390
+ if (event.type === "tool-approval") {
391
+ const { toolCallId, approved, autoContinue } = event;
372
392
  this._emit("tool:approval", {
373
393
  toolCallId,
374
394
  approved
375
395
  });
376
- const approvalPromise = this._enqueueInteractionApply(() => this._applyToolApproval(toolCallId, approved));
377
- if (autoContinue) this._enqueueAutoContinuation(connection, this._lastClientTools, this._lastBody, "[AIChatAgent] Tool approval continuation failed:", approvalPromise);
396
+ this._enqueueInteractionApply(() => this._applyToolApproval(toolCallId, approved));
397
+ if (autoContinue) this._scheduleAutoContinuation(connection, this._lastClientTools, this._lastBody, "[AIChatAgent] Tool approval continuation failed:");
398
+ else this._rearmPendingAutoContinuationForBatch();
378
399
  return;
379
400
  }
380
401
  }
@@ -410,35 +431,56 @@ var AIChatAgent = class AIChatAgent extends Agent {
410
431
  addColumnIfNotExists("alter table cf_ai_chat_agent_tool_runs add column input_json text");
411
432
  addColumnIfNotExists("alter table cf_ai_chat_agent_tool_runs add column output_json text");
412
433
  addColumnIfNotExists("alter table cf_ai_chat_agent_tool_runs add column summary text");
434
+ addColumnIfNotExists("alter table cf_ai_chat_agent_tool_runs add column progress_json text");
435
+ addColumnIfNotExists("alter table cf_ai_chat_agent_tool_runs add column last_signal_at integer");
413
436
  this.sql`create index if not exists idx_ai_chat_agent_tool_request_id
414
437
  on cf_ai_chat_agent_tool_runs(request_id)`;
438
+ this.sql`create table if not exists cf_ai_chat_agent_tool_milestones (
439
+ run_id text not null,
440
+ sequence integer not null,
441
+ name text not null,
442
+ data_json text,
443
+ at integer not null,
444
+ primary key (run_id, sequence)
445
+ )`;
446
+ }
447
+ _persistAgentToolMilestone(runId, name, data, at) {
448
+ this._ensureAgentToolTables();
449
+ const sequence = this.sql`
450
+ select coalesce(max(sequence), -1) + 1 as next
451
+ from cf_ai_chat_agent_tool_milestones where run_id = ${runId}
452
+ `[0]?.next ?? 0;
453
+ this.sql`
454
+ insert or ignore into cf_ai_chat_agent_tool_milestones
455
+ (run_id, sequence, name, data_json, at)
456
+ values (
457
+ ${runId}, ${sequence}, ${name},
458
+ ${data !== void 0 ? JSON.stringify(data) : null}, ${at}
459
+ )
460
+ `;
461
+ this.sql`update cf_ai_chat_agent_tool_runs set last_signal_at = ${at}
462
+ where run_id = ${runId}`;
463
+ return sequence;
464
+ }
465
+ _readAgentToolMilestones(runId) {
466
+ this._ensureAgentToolTables();
467
+ return this.sql`
468
+ select sequence, name, data_json, at
469
+ from cf_ai_chat_agent_tool_milestones
470
+ where run_id = ${runId} order by sequence asc
471
+ `.map((row) => ({
472
+ name: row.name,
473
+ sequence: row.sequence,
474
+ at: row.at,
475
+ ...row.data_json != null ? { data: JSON.parse(row.data_json) } : {}
476
+ }));
415
477
  }
416
478
  _flushAwaitingStreamStartConnections() {
417
479
  if (!this._resumableStream.hasActiveStream()) return;
418
480
  this._continuation.flushAwaitingConnections((c) => this._notifyStreamResuming(c));
419
481
  }
420
- _mergeAutoContinuationPrerequisite(current, next) {
421
- if (!next) return current;
422
- if (!current) return next;
423
- return Promise.all([current, next]).then(([currentApplied, nextApplied]) => {
424
- return currentApplied && nextApplied;
425
- });
426
- }
427
- _storeDeferredAutoContinuation(connection, clientTools, body, errorPrefix, prerequisite) {
428
- const existing = this._continuation.deferred;
429
- this._continuation.deferred = {
430
- connection,
431
- connectionId: connection.id,
432
- clientTools,
433
- body,
434
- errorPrefix,
435
- prerequisite: this._mergeAutoContinuationPrerequisite(existing?.prerequisite ?? null, prerequisite)
436
- };
437
- }
438
482
  _activateDeferredAutoContinuation() {
439
- const pending = this._continuation.activateDeferred(() => nanoid());
440
- if (!pending) return;
441
- this._queueAutoContinuation(pending.requestId);
483
+ this._autoContinuation.activateDeferredAndReschedule();
442
484
  }
443
485
  _clearAllAutoContinuationState(sendNone = false) {
444
486
  this._clearPendingAutoContinuation(sendNone);
@@ -449,26 +491,31 @@ var AIChatAgent = class AIChatAgent extends Agent {
449
491
  this._continuation.clearPending();
450
492
  }
451
493
  /**
452
- * Notify a connection about an active stream that can be resumed.
453
- * The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
454
- *
455
- * A connection can legitimately be notified more than once for the same
456
- * request — proactively from onConnect AND in response to its
457
- * CF_AGENT_STREAM_RESUME_REQUEST (#1733). This is intentional and must NOT
458
- * be deduped here: an explicit resume request always deserves a response
459
- * (the client's reconnectToStream would otherwise hang until its safety
460
- * timeout, with no replay), and the proactive notify is required for
461
- * clients that never send a resume request. The notify itself is a single
462
- * tiny frame; clients are responsible for deduping the ACK so the full
463
- * chunk buffer is not replayed twice.
494
+ * The shared resume-handshake driver (Tier-2). Lazily built; the
495
+ * `ResumableStream` / `ContinuationState` / pending set are stable after the
496
+ * constructor, so a single instance threads them for the agent's lifetime.
497
+ */
498
+ _resumeHandshake() {
499
+ return this._resumeHandshakeInstance ??= new ResumeHandshake({
500
+ responseMessageType: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
501
+ resumableStream: this._resumableStream,
502
+ continuation: this._continuation,
503
+ preStream: this._preStream,
504
+ pendingResumeConnections: this._pendingResumeConnections,
505
+ pendingChatTerminal: () => this._pendingChatTerminal(),
506
+ persistOrphanedStream: (streamId) => this._persistOrphanedStream(streamId),
507
+ isConnectionPresent: (connectionId) => this._isConnectionPresent(connectionId)
508
+ });
509
+ }
510
+ /**
511
+ * Notify a connection about an active stream that can be resumed — delegates
512
+ * to the shared {@link ResumeHandshake}. Kept as a thin method because it is
513
+ * also called proactively from onConnect and the broadcast loop. See the
514
+ * driver for the #1733 double-send contract.
464
515
  * @param connection - The WebSocket connection to notify
465
516
  */
466
517
  _notifyStreamResuming(connection) {
467
- if (!this._resumableStream.hasActiveStream()) return;
468
- if (sendIfOpen(connection, JSON.stringify({
469
- type: "cf_agent_stream_resuming",
470
- id: this._resumableStream.activeRequestId
471
- }))) this._pendingResumeConnections.add(connection.id);
518
+ this._resumeHandshake().notifyStreamResuming(connection);
472
519
  }
473
520
  /** @internal Delegate to _resumableStream */
474
521
  get _activeStreamId() {
@@ -481,6 +528,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
481
528
  /** @internal Delegate to _resumableStream */
482
529
  _startStream(requestId, options = {}) {
483
530
  const streamId = this._resumableStream.start(requestId, options);
531
+ this._preStream.flushOnStreamStart((c) => this._notifyStreamResuming(c));
484
532
  if (this._continuation.pending?.requestId === requestId) {
485
533
  this._continuation.activatePending();
486
534
  this._flushAwaitingStreamStartConnections();
@@ -515,14 +563,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
515
563
  await this.schedule(STREAM_CLEANUP_DELAY_SECONDS, "_cleanupStreamBuffers", void 0, { idempotent });
516
564
  }
517
565
  /**
518
- * Alarm callback: sweep aged stream buffers, then re-arm only while rows
519
- * remain so a fully-swept DO stops waking itself. Public so it is reachable
520
- * as a schedule callback.
566
+ * Alarm callback: sweep aged stream buffers, re-arming while rows remain (see
567
+ * the shared {@link cleanupStreamBuffers}). Public so it is reachable as a
568
+ * schedule callback.
521
569
  * @internal
522
570
  */
523
571
  async _cleanupStreamBuffers() {
524
- this._resumableStream.cleanup();
525
- if (this._resumableStream.hasReclaimableStreams()) await this._ensureStreamCleanupScheduled({ idempotent: false });
572
+ await cleanupStreamBuffers(this._resumableStream, () => this._ensureStreamCleanupScheduled({ idempotent: false }));
526
573
  }
527
574
  /** @internal Delegate to _resumableStream. Also advances the recovery
528
575
  * progress counter at production time (see `_maybeBumpRecoveryProgress`). */
@@ -535,14 +582,22 @@ var AIChatAgent = class AIChatAgent extends Agent {
535
582
  await this._maybeBumpRecoveryProgress(type);
536
583
  }
537
584
  /** Advance the recovery-progress counter when a chunk represents genuinely
538
- * new produced content — a started text/reasoning segment or a settled tool
539
- * input/output. Bumped at production time (the streaming path), so it
540
- * reflects real forward progress and is immune to client reconnects /
541
- * recovery re-persists (which replay or re-materialize stored chunks rather
542
- * than flow through here). This is what the recovery no-progress window keys
543
- * off (#1637), and stays compaction-proof (#1628). */
585
+ * new produced content. Uses the shared host-agnostic rule
586
+ * ({@link shouldCreditStreamProgress}): a milestone (started segment / settled
587
+ * tool) always credits, and a long single segment's streaming deltas credit
588
+ * through a time throttle so the no-progress window doesn't false-fire while
589
+ * content streams across crashes. Bumped at production time, so it reflects
590
+ * real forward progress and is immune to client reconnects / recovery
591
+ * re-persists (which replay or re-materialize stored chunks rather than flow
592
+ * through here). This is what the recovery no-progress window keys off
593
+ * (#1637), and stays compaction-proof (#1628). */
544
594
  async _maybeBumpRecoveryProgress(type) {
545
- if (type === "text-start" || type === "reasoning-start" || type === "tool-input-available" || type === "tool-output-available" || type === "tool-output-error" || type === "tool-output-denied") await this._bumpChatRecoveryProgress();
595
+ if (shouldCreditStreamProgress({
596
+ codec: aiSdkRecoveryCodec,
597
+ type,
598
+ throttle: this._streamProgressCredit,
599
+ now: Date.now()
600
+ })) await this._bumpChatRecoveryProgress();
546
601
  }
547
602
  /** @internal Delegate to _resumableStream */
548
603
  _flushChunkBuffer() {
@@ -568,51 +623,151 @@ var AIChatAgent = class AIChatAgent extends Agent {
568
623
  * stream's stored chunks. Called when the DO wakes from hibernation and
569
624
  * discovers an active stream with no live LLM reader.
570
625
  *
571
- * Replays each chunk body through `applyChunkToParts` to rebuild the
572
- * message parts, then persists the result so it survives further refreshes.
626
+ * Built from the three orphan-persist seams the chat-recovery RFC factored
627
+ * out — all three are ai-chat's substrate-specific realizations of a shape
628
+ * `Think` shares:
629
+ * - (a) reconstruct via the shared `StreamAccumulator` (the same primitive
630
+ * `Think` and the client reducer use), replacing a hand-rolled chunk
631
+ * switch; it owns the `start` / `finish` / `message-metadata` handling;
632
+ * - (b) {@link _resolveOrphanTargetId} — the id to persist under (#1691);
633
+ * - (c)+(d) upsert-by-id over the flat array, the `SessionProvider`-subset
634
+ * store-write shape (`getMessage` → `updateMessage` / `appendMessage`)
635
+ * that `Think._upsertMessageInHistory` implements over a Session tree.
636
+ * When a row already owns the id, the shared `reconcileOrphanPartial`
637
+ * merge preserves an in-place tool result rather than letting a replayed
638
+ * chunk re-advance it (ai-chat has an early tool-approval persist; hosts
639
+ * without one append straight through).
573
640
  * @internal
574
641
  */
575
642
  async _persistOrphanedStream(streamId) {
576
643
  const chunks = this._resumableStream.getStreamChunks(streamId);
577
644
  if (!chunks.length) return;
578
645
  const fallbackId = `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
579
- const message = {
580
- id: fallbackId,
581
- role: "assistant",
582
- parts: []
646
+ await persistReconstructedOrphan(chunks, {
647
+ store: this._orphanStore(),
648
+ fallbackId,
649
+ prepare: (message) => {
650
+ message.id = this._resolveOrphanTargetId(streamId, message.id, fallbackId);
651
+ return message;
652
+ },
653
+ merge: (existing, incoming) => reconcileOrphanPartial(existing, incoming)
654
+ });
655
+ }
656
+ /**
657
+ * Resolve the id an orphaned partial should persist under — orphan-persist
658
+ * step **(b)**, and the one legitimately per-package piece of the path: a
659
+ * flat `UIMessage[]` can't express the parent/child a Session tree uses to
660
+ * resolve this structurally, so ai-chat reads it from stream metadata.
661
+ *
662
+ * When the reconstructed message already adopted a provider `start.messageId`
663
+ * (kept as-is — the live path adopts it for new turns too) `reconstructedId`
664
+ * differs from `fallbackId` and is returned unchanged. Otherwise resolve to:
665
+ * - the id allocated when the stream started, recorded in stream metadata
666
+ * (#1691) — the SAME id the live path persists under (it only adopts a
667
+ * provider id, never invents one). A new turn stored its own fresh id, so
668
+ * it becomes its own message; a continuation stored the cloned
669
+ * last-assistant id, so it merges. This is what stops a new turn after a
670
+ * later user message from being folded into the previous assistant
671
+ * message (the #1691 corruption); or
672
+ * - (legacy rows written before the metadata column existed) the last
673
+ * assistant message, matching pre-#1691 behavior.
674
+ * @internal
675
+ */
676
+ _resolveOrphanTargetId(streamId, reconstructedId, fallbackId) {
677
+ if (reconstructedId !== fallbackId) return reconstructedId;
678
+ const storedId = this._resumableStream.getStreamMessageId(streamId);
679
+ if (storedId != null) return storedId;
680
+ for (let i = this.messages.length - 1; i >= 0; i--) if (this.messages[i].role === "assistant") return this.messages[i].id;
681
+ return reconstructedId;
682
+ }
683
+ /**
684
+ * The orphan-persist store adapter — orphan-persist steps **(c)/(d)** route
685
+ * their write through this shared `OrphanPersistStore` seam (the
686
+ * `SessionProvider` write-subset). Backed by ai-chat's flat `this.messages`
687
+ * array + the existing `persistMessages` whole-array write path, so
688
+ * reconcile/sanitize/row-size/broadcast all stay intact. Each mutating call
689
+ * is exactly one `persistMessages` invocation; `parentId` is unused (a flat
690
+ * array has no tree to attach to).
691
+ * @internal
692
+ */
693
+ _orphanStore() {
694
+ return {
695
+ getMessage: (id) => this.messages.find((m) => m.id === id) ?? null,
696
+ appendMessage: (message) => this.persistMessages([...this.messages, message]),
697
+ updateMessage: (message) => this.persistMessages(this.messages.map((m) => m.id === message.id ? message : m))
583
698
  };
584
- for (const chunk of chunks) try {
585
- const data = JSON.parse(chunk.body);
586
- if (data.type === "start" && data.messageId != null) message.id = data.messageId;
587
- if ((data.type === "start" || data.type === "finish" || data.type === "message-metadata") && data.messageMetadata != null) message.metadata = message.metadata ? {
588
- ...message.metadata,
589
- ...data.messageMetadata
590
- } : data.messageMetadata;
591
- applyChunkToParts(message.parts, data);
592
- } catch {}
593
- if (message.parts.length > 0) {
594
- if (message.id === fallbackId) {
595
- const storedId = this._resumableStream.getStreamMessageId(streamId);
596
- if (storedId != null) message.id = storedId;
597
- else for (let i = this.messages.length - 1; i >= 0; i--) if (this.messages[i].role === "assistant") {
598
- message.id = this.messages[i].id;
599
- break;
600
- }
601
- }
602
- const existingIdx = this.messages.findIndex((m) => m.id === message.id);
603
- if (existingIdx >= 0) {
604
- const existing = this.messages[existingIdx];
605
- const existingToolCallIds = new Set(existing.parts.filter((p) => "toolCallId" in p).map((p) => p.toolCallId));
606
- const newParts = message.parts.filter((p) => !("toolCallId" in p && existingToolCallIds.has(p.toolCallId)));
607
- message.parts = [...existing.parts, ...newParts];
608
- if (existing.metadata) message.metadata = message.metadata ? {
609
- ...existing.metadata,
610
- ...message.metadata
611
- } : existing.metadata;
612
- }
613
- const updatedMessages = existingIdx >= 0 ? this.messages.map((m, i) => i === existingIdx ? message : m) : [...this.messages, message];
614
- await this.persistMessages(updatedMessages);
615
- }
699
+ }
700
+ /**
701
+ * Repair a single interrupted tool call — a tool part with no settled result,
702
+ * left behind when a stream was cut off mid-flight (e.g. a SERVER tool whose
703
+ * `execute()` died with an evicted isolate, leaving an `input-available`
704
+ * orphan that nothing will ever resolve). Returns the replacement part that
705
+ * takes its place in the transcript; `input` has already been normalized to a
706
+ * valid object.
707
+ *
708
+ * The default flips it to an errored tool result so the record survives (no
709
+ * "disappearing" tool call) and `convertToModelMessages` still gets a
710
+ * tool-result for it, avoiding `AI_MissingToolResultsError` on the next
711
+ * provider call. This mirrors `@cloudflare/think` so ai-chat RECOVERS an
712
+ * interrupted server tool (repairs, then continues) instead of waiting on a
713
+ * dead orphan until its budget is spent.
714
+ *
715
+ * Override to customize the repaired shape for client-resolved tools — e.g.
716
+ * convert an interrupted question tool (no server `execute`, normally answered
717
+ * by the user's next message) into a plain text part so the model sees it as
718
+ * ordinary conversation rather than a tool error. A returned tool part MUST
719
+ * carry a settled result (`output-available` / `output-error` /
720
+ * `output-denied` or an `output` / `result` field); returning a non-tool part
721
+ * (e.g. text) is fine.
722
+ */
723
+ repairInterruptedToolPart(part) {
724
+ return {
725
+ ...part,
726
+ state: "output-error",
727
+ errorText: "The tool call was interrupted before a result was recorded."
728
+ };
729
+ }
730
+ /**
731
+ * Transcript repair, run before EVERY inference chokepoint (live submit, tool
732
+ * auto-continuation, `continueLastTurn`, `saveMessages`/retry, and the chat
733
+ * recovery callbacks). An interrupted server-tool orphan is flipped to a
734
+ * settled (errored) result — via the shared `agents/chat`
735
+ * `repairInterruptedToolParts` primitive, the SAME logic `@cloudflare/think`
736
+ * runs before its own inference (`_assembleModelMessages`) — so the app's next
737
+ * `convertToModelMessages(this.messages)` doesn't 400 with
738
+ * `AI_MissingToolResultsError`. Because the app owns the inference call, the
739
+ * framework can't repair "inside" it the way Think does; it repairs
740
+ * `this.messages` at each point right before handing control to
741
+ * `onChatMessage` instead. This reaches the cases the recovery-only repair
742
+ * missed: a mixed client+server orphan whose client replay drives an
743
+ * auto-continuation, and any agent running with `chatRecovery` disabled.
744
+ *
745
+ * Scope: repair only ever flips a DEAD SERVER orphan (an interrupted tool with
746
+ * no settled result whose `execute()` died with the evicted isolate). A part
747
+ * still legitimately awaiting a CLIENT interaction — an `input-available`
748
+ * client tool the SPA replays, or an `approval-requested` part the user may
749
+ * still answer — is left verbatim via the shared `shouldRepair` skip, so it is
750
+ * never clobbered with an error. This is per-part (not a whole-transcript
751
+ * guard), so a fresh dead-server orphan at the leaf is still repaired even if
752
+ * an unrelated abandoned client orphan sits earlier in history.
753
+ *
754
+ * Repair only ever reshapes ASSISTANT tool parts; it never touches user
755
+ * messages, so per-channel policy carried on the user message's
756
+ * `metadata.channel` (re-resolved on wake) is structurally untouched. It is a
757
+ * no-op (no write, no broadcast) when nothing needs repair — the common case
758
+ * for a healthy transcript. When anything changes, the corrected transcript is
759
+ * persisted and broadcast through the normal `persistMessages` write path (one
760
+ * write, one broadcast), which also refreshes `this.messages`.
761
+ * @internal
762
+ */
763
+ async _repairInterruptedToolsBeforeTurn() {
764
+ const clientResolvable = this._clientResolvableToolNames();
765
+ const repaired = repairInterruptedToolParts(this.messages, {
766
+ repairPart: (part) => this.repairInterruptedToolPart(part),
767
+ shouldRepair: (part) => !this._partAwaitsClientInteraction(part, clientResolvable)
768
+ });
769
+ if (repaired.removedToolCalls === 0 && repaired.normalizedInputs === 0) return;
770
+ await this.persistMessages(repaired.messages);
616
771
  }
617
772
  /**
618
773
  * Restore _lastBody and _lastClientTools from SQLite.
@@ -664,7 +819,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
664
819
  body,
665
820
  done: false,
666
821
  id: event.id,
667
- type: "cf_agent_use_chat_response",
822
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
668
823
  ...continuation && { continuation: true }
669
824
  });
670
825
  }
@@ -709,7 +864,25 @@ var AIChatAgent = class AIChatAgent extends Agent {
709
864
  * `waitForIdle()` (tests, `waitUntilStable`, recovery code).
710
865
  */
711
866
  async waitForIdle() {
712
- await this._submitConcurrency.waitForIdle(() => this._turnQueue.waitForIdle());
867
+ for (;;) {
868
+ await this._submitConcurrency.waitForIdle(() => this._turnQueue.waitForIdle());
869
+ if (!this._hasArmedContinuation()) return;
870
+ await new Promise((resolve) => setTimeout(resolve, AutoContinuationController.COALESCE_MS));
871
+ }
872
+ }
873
+ /**
874
+ * `true` when an auto-continuation is armed and going to fire on its own —
875
+ * its coalesce timer is still pending or its completeness barrier is
876
+ * mid-drain (#1650). Such an agent is NOT idle/stable: a continuation turn is
877
+ * imminent, so idle observers (recovery, idle-eviction, tests) must keep
878
+ * waiting until it either enqueues a turn or parks on an incomplete batch.
879
+ * A continuation that has already entered its turn (`pastCoalesce`) is
880
+ * covered by the turn queue, and a parked one (waiting on an unanswered
881
+ * sibling) is covered by `hasPendingInteraction()`, so neither is reported
882
+ * here.
883
+ */
884
+ _hasArmedContinuation() {
885
+ return this._continuation.pending !== null && !this._continuation.pending.pastCoalesce && this._autoContinuation.isArmed();
713
886
  }
714
887
  _getSubmitConcurrencyDecision(trigger) {
715
888
  const decision = this._submitConcurrency.decide({
@@ -805,13 +978,30 @@ var AIChatAgent = class AIChatAgent extends Agent {
805
978
  body: "",
806
979
  done: true,
807
980
  id: requestId,
808
- type: "cf_agent_use_chat_response"
981
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
809
982
  });
983
+ this._settlePreStreamTurn(requestId, { releaseParked: false });
984
+ }
985
+ /** Whether a connection with this id is still attached. */
986
+ _isConnectionPresent(connectionId) {
987
+ return this.getConnection(connectionId) !== void 0;
988
+ }
989
+ /**
990
+ * Mark an accepted turn (#1784) as settled. When `releaseParked` (the default)
991
+ * and no accepted turn remains in flight and no stream is active, release every
992
+ * parked connection with STREAM_RESUME_NONE so a client that reconnected during
993
+ * the pre-stream window stops waiting. A no-op when the parked set was already
994
+ * flushed on stream start. Skip paths pass `releaseParked: false` so a parked
995
+ * client survives onto the successor turn (see `_completeSkippedRequest`).
996
+ */
997
+ _settlePreStreamTurn(requestId, options = {}) {
998
+ const idle = this._preStream.settle(requestId);
999
+ if ((options.releaseParked ?? true) && idle && !this._resumableStream.hasActiveStream()) this._preStream.releaseAwaiting();
810
1000
  }
811
1001
  _rollbackDroppedSubmit(connection) {
812
1002
  this._sendDirectMessage(connection, {
813
1003
  messages: this._messagesForClientSync(),
814
- type: "cf_agent_chat_messages"
1004
+ type: MessageType.CF_AGENT_CHAT_MESSAGES
815
1005
  });
816
1006
  }
817
1007
  /** `true` when an assistant message is waiting on a client tool result or approval. */
@@ -826,16 +1016,32 @@ var AIChatAgent = class AIChatAgent extends Agent {
826
1016
  * Returns `true` when stable. Returns `false` if `timeout` expires before
827
1017
  * a pending interaction resolves. Safe to call at any time; if there is
828
1018
  * nothing pending it returns immediately.
1019
+ *
1020
+ * `pendingInteraction` overrides which "still waiting" predicate gates
1021
+ * stability. It defaults to the broad {@link hasPendingInteraction} (any
1022
+ * `input-available` / `approval-requested` part) to preserve the documented
1023
+ * semantics for app overrides. The recovery paths pass the narrower
1024
+ * {@link hasPendingClientInteraction} so a DEAD server-tool `input-available`
1025
+ * orphan (its `execute()` died with the evicted isolate; nothing will resolve
1026
+ * it) does NOT block stability — recovery then repairs it to an errored
1027
+ * result and continues, instead of waiting until the budget is spent. This
1028
+ * mirrors `@cloudflare/think`, whose single pending predicate is already
1029
+ * client-only by construction.
829
1030
  */
830
1031
  async waitUntilStable(options) {
831
1032
  const deadline = options?.timeout != null ? Date.now() + options.timeout : null;
1033
+ const hasPendingInteraction = options?.pendingInteraction ?? (() => this.hasPendingInteraction());
832
1034
  while (true) {
833
1035
  while (true) {
834
1036
  if (await this._awaitWithDeadline(this._turnQueue.waitForIdle(), deadline) === TIMED_OUT) return false;
835
1037
  if (this._submitConcurrency.pendingEnqueueCount === 0) break;
836
1038
  if (await this._awaitWithDeadline(new Promise((resolve) => setTimeout(resolve, 5)), deadline) === TIMED_OUT) return false;
837
1039
  }
838
- if (!this.hasPendingInteraction()) return true;
1040
+ if (!hasPendingInteraction()) {
1041
+ if (!this._hasArmedContinuation()) return true;
1042
+ if (await this._awaitWithDeadline(new Promise((resolve) => setTimeout(resolve, AutoContinuationController.COALESCE_MS)), deadline) === TIMED_OUT) return false;
1043
+ continue;
1044
+ }
839
1045
  const pending = this._pendingInteractionPromise;
840
1046
  if (pending) {
841
1047
  let result;
@@ -865,8 +1071,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
865
1071
  this._submitConcurrency.reset();
866
1072
  this._pendingInteractionPromise = null;
867
1073
  this._interactionApplyTail = Promise.resolve();
1074
+ this._autoContinuation.reset();
1075
+ this._streamingTurnActive = false;
868
1076
  this._continuation.sendResumeNone();
869
1077
  this._continuation.clearAll();
1078
+ this._preStream.releaseAwaiting();
1079
+ this._preStream.reset();
870
1080
  this._pendingChatResponseResults.length = 0;
871
1081
  }
872
1082
  /**
@@ -901,15 +1111,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
901
1111
  abortAllRequests(reason) {
902
1112
  this._abortRegistry.destroyAll(reason);
903
1113
  }
904
- async _awaitWithDeadline(promise, deadline) {
905
- if (deadline == null) return promise;
906
- const remainingMs = Math.max(0, deadline - Date.now());
907
- let timer;
908
- const result = await Promise.race([promise, new Promise((resolve) => {
909
- timer = setTimeout(() => resolve(TIMED_OUT), remainingMs);
910
- })]);
911
- clearTimeout(timer);
912
- return result;
1114
+ _awaitWithDeadline(promise, deadline) {
1115
+ return awaitWithDeadline(promise, deadline);
913
1116
  }
914
1117
  _messageHasPendingInteraction(message) {
915
1118
  return message.parts.some((part) => "state" in part && (part.state === "input-available" || part.state === "approval-requested"));
@@ -946,28 +1149,14 @@ var AIChatAgent = class AIChatAgent extends Agent {
946
1149
  * pending — its `execute()` died with the isolate. Mirrors `@cloudflare/think`.
947
1150
  */
948
1151
  _partAwaitsClientInteraction(part, clientResolvable) {
949
- if (!("state" in part)) return false;
950
- const record = part;
951
- const state = record.state;
952
- if (state === "approval-requested") return true;
953
- if (state !== "input-available") return false;
954
- const toolName = this._toolPartName(record);
955
- return toolName != null && clientResolvable.has(toolName);
956
- }
957
- /** Extract a tool part's name from its `tool-<name>` / `dynamic-tool` shape. */
958
- _toolPartName(record) {
959
- const type = typeof record.type === "string" ? record.type : "";
960
- if (type === "dynamic-tool") return typeof record.toolName === "string" ? record.toolName : void 0;
961
- if (type.startsWith("tool-")) return type.slice(5);
1152
+ return partAwaitsClientInteraction(part, clientResolvable);
962
1153
  }
963
1154
  /**
964
1155
  * Names of the CLIENT-resolvable tools (the client-provided schemas from the
965
1156
  * last request, which have no server `execute`). Mirrors `@cloudflare/think`.
966
1157
  */
967
1158
  _clientResolvableToolNames() {
968
- const names = /* @__PURE__ */ new Set();
969
- for (const tool of this._lastClientTools ?? []) if (tool?.name) names.add(tool.name);
970
- return names;
1159
+ return clientResolvableToolNames(this._lastClientTools);
971
1160
  }
972
1161
  /**
973
1162
  * Run a chat turn exclusively so `_reply()` never overlaps with another
@@ -1007,75 +1196,57 @@ var AIChatAgent = class AIChatAgent extends Agent {
1007
1196
  }
1008
1197
  return result.value;
1009
1198
  }
1010
- _enqueueAutoContinuation(connection, clientTools, body, errorPrefix, prerequisite) {
1011
- if (this._continuation.pending) {
1012
- if (this._continuation.pending.pastCoalesce) {
1013
- this._storeDeferredAutoContinuation(connection, clientTools, body, errorPrefix, prerequisite);
1014
- return;
1015
- }
1016
- this._continuation.pending.connection = connection;
1017
- this._continuation.pending.connectionId = connection.id;
1018
- this._continuation.awaitingConnections.set(connection.id, connection);
1019
- this._continuation.pending.clientTools = clientTools;
1020
- this._continuation.pending.body = body;
1021
- this._continuation.pending.errorPrefix = errorPrefix;
1022
- this._continuation.pending.prerequisite = this._mergeAutoContinuationPrerequisite(this._continuation.pending.prerequisite, prerequisite);
1023
- return;
1024
- }
1025
- const requestId = nanoid();
1026
- this._continuation.pending = {
1199
+ /**
1200
+ * Schedule an auto-continuation for a tool result/approval that opted in with
1201
+ * `autoContinue: true` (#1650). Thin host wrapper that builds the
1202
+ * {@link ContinuationSpec} and delegates to the shared
1203
+ * {@link AutoContinuationController}, which owns the coalesce timer and the
1204
+ * completeness-gated fire (shared with `@cloudflare/think`).
1205
+ */
1206
+ _scheduleAutoContinuation(connection, clientTools, body, errorPrefix) {
1207
+ this._autoContinuation.schedule({
1027
1208
  connection,
1028
- connectionId: connection.id,
1029
- requestId,
1030
1209
  clientTools,
1031
1210
  body,
1032
- errorPrefix,
1033
- prerequisite: this._mergeAutoContinuationPrerequisite(null, prerequisite),
1034
- pastCoalesce: false
1035
- };
1036
- this._continuation.awaitingConnections.set(connection.id, connection);
1037
- this._queueAutoContinuation(requestId);
1211
+ errorPrefix
1212
+ });
1038
1213
  }
1039
- async _awaitPendingAutoContinuationPrerequisite() {
1040
- while (true) {
1041
- const prerequisite = this._continuation.pending?.prerequisite;
1042
- if (!prerequisite) break;
1043
- if (!await prerequisite) return false;
1044
- await new Promise((resolve) => setTimeout(resolve, AIChatAgent.AUTO_CONTINUATION_COALESCE_MS));
1045
- if (this._continuation.pending?.prerequisite === prerequisite) break;
1046
- }
1047
- await this._awaitPendingInteractionBarrier();
1048
- return true;
1214
+ /**
1215
+ * Re-arm the barrier for a result/approval that arrived WITHOUT `autoContinue`
1216
+ * (#1650). A standalone errored result declines to continue on its own, but in
1217
+ * a parallel batch a SIBLING may already have opted in — and this result can be
1218
+ * the one that completes the batch, so we must re-run the barrier check. Unlike
1219
+ * `_scheduleAutoContinuation` this NEVER creates a pending continuation (a
1220
+ * standalone errored tool with no opted-in sibling must not auto-continue), and
1221
+ * it no-ops once the continuation is running (`pastCoalesce`).
1222
+ */
1223
+ _rearmPendingAutoContinuationForBatch() {
1224
+ this._autoContinuation.rearmForBatch();
1049
1225
  }
1050
1226
  /**
1051
- * Block until the latest assistant step's parallel tool batch is fully
1052
- * answered, or `AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS` elapses. Awaits the
1053
- * in-flight tool-result apply when one exists (so a sibling that lands
1054
- * mid-wait is observed promptly) and polls otherwise. Runs inside the
1055
- * continuation turn, so — unlike `waitUntilStable` — it must not wait on the
1056
- * turn queue (that would deadlock).
1057
- *
1058
- * No concurrent-entry guard is needed (unlike Think's `_continuationBarrier
1059
- * Active`): this runs inside the exclusive continuation turn, and a sibling
1060
- * result arriving while it waits hits the merge branch of
1061
- * `_enqueueAutoContinuation` (it updates `pending.prerequisite`) rather than
1062
- * enqueuing a second turn — so the turn queue serializes barrier waits.
1227
+ * Called when a streaming assistant turn finalizes (its message, with ALL tool
1228
+ * parts, is now persisted). Clears the stream-active gate and re-runs the
1229
+ * barrier for a continuation the gate held (#1650). Essential for an all-fast
1230
+ * parallel batch whose every result landed mid-stream: once the stream ends
1231
+ * there is no further tool-result event to re-arm, so without this the held
1232
+ * continuation would never fire. A slow batch is re-checked here and simply
1233
+ * keeps holding (event-driven) until its remaining siblings answer.
1063
1234
  */
1064
- async _awaitPendingInteractionBarrier() {
1065
- const deadline = Date.now() + AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS;
1066
- while (Date.now() < deadline) {
1067
- if (!this._continuation.pending) return;
1068
- const pending = this._pendingInteractionPromise;
1069
- if (pending) {
1070
- try {
1071
- await pending;
1072
- } catch {}
1073
- continue;
1074
- }
1075
- if (!this._hasIncompleteToolBatch()) return;
1076
- await new Promise((resolve) => setTimeout(resolve, 100));
1077
- }
1078
- console.warn(`[AIChatAgent] Auto-continuation proceeding after waiting ${AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS}ms for unanswered parallel tool result(s) (#1649).`);
1235
+ _onStreamingTurnFinalized() {
1236
+ this._streamingTurnActive = false;
1237
+ this._autoContinuation.rearmForBatch();
1238
+ }
1239
+ /**
1240
+ * Drain every in-flight tool-result/approval apply, including any enqueued
1241
+ * while we wait, so the subsequent `_hasIncompleteToolBatch()` re-check sees
1242
+ * every result that has ALREADY arrived. Bounded by real apply activity (a
1243
+ * storage write each), never by a fixed timer: the loop re-reads
1244
+ * `_interactionApplyTail` after each await because a sibling can extend the
1245
+ * tail mid-drain, and stops once the tail stops advancing. Mirrors
1246
+ * `@cloudflare/think`'s `_drainInteractionApplies`.
1247
+ */
1248
+ _drainInteractionApplies() {
1249
+ return drainInteractionApplies(() => this._continuation.pending !== null, () => this._interactionApplyTail);
1079
1250
  }
1080
1251
  /**
1081
1252
  * `true` when the latest assistant message is mid-batch: it carries at least
@@ -1086,33 +1257,16 @@ var AIChatAgent = class AIChatAgent extends Agent {
1086
1257
  * message doesn't block a legitimate follow-up continuation.
1087
1258
  */
1088
1259
  _hasIncompleteToolBatch() {
1089
- const messages = this.messages;
1090
- let leaf;
1091
- for (let i = messages.length - 1; i >= 0; i--) if (messages[i].role === "assistant") {
1092
- leaf = messages[i];
1093
- break;
1094
- }
1095
- if (!leaf) return false;
1096
- let hasPending = false;
1097
- let hasSettled = false;
1098
- for (const part of leaf.parts) {
1099
- const record = part;
1100
- const state = record.state;
1101
- if (state === "input-available" || state === "approval-requested") hasPending = true;
1102
- else if (typeof record.type === "string" && (record.type.startsWith("tool-") || record.type === "dynamic-tool") && (state === "output-available" || state === "output-error" || state === "output-denied" || state === "approval-responded")) hasSettled = true;
1103
- if (hasPending && hasSettled) return true;
1104
- }
1105
- return false;
1260
+ return hasIncompleteToolBatch(this.messages);
1106
1261
  }
1107
- _queueAutoContinuation(requestId) {
1262
+ _fireAutoContinuation() {
1263
+ const pending = this._continuation.pending;
1264
+ if (!pending) return;
1265
+ const requestId = pending.requestId;
1108
1266
  const epoch = this._turnQueue.generation;
1109
1267
  this._runExclusiveChatTurn(requestId, async () => {
1110
1268
  const dispose = await this.keepAlive();
1111
1269
  try {
1112
- if (!await this._awaitPendingAutoContinuationPrerequisite()) {
1113
- this._clearAllAutoContinuationState(true);
1114
- return;
1115
- }
1116
1270
  const connection = this._continuation.pending?.connection;
1117
1271
  if (!connection) {
1118
1272
  this._clearAllAutoContinuationState(true);
@@ -1131,6 +1285,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1131
1285
  }, async () => {
1132
1286
  const autoContinuationBody = async () => {
1133
1287
  try {
1288
+ await this._repairInterruptedToolsBeforeTurn();
1134
1289
  const response = await this.onChatMessage(async (_finishResult) => {}, {
1135
1290
  requestId,
1136
1291
  abortSignal,
@@ -1189,6 +1344,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1189
1344
  const detachExternal = this._abortRegistry.linkExternal(requestId, externalSignal);
1190
1345
  try {
1191
1346
  const programmaticBody = async () => {
1347
+ await this._repairInterruptedToolsBeforeTurn();
1192
1348
  const response = await this.onChatMessage(() => {}, {
1193
1349
  requestId,
1194
1350
  abortSignal,
@@ -1300,6 +1456,41 @@ var AIChatAgent = class AIChatAgent extends Agent {
1300
1456
  }]
1301
1457
  };
1302
1458
  }
1459
+ get _agentToolProgressEmitter() {
1460
+ if (!this._agentToolProgressEmitterInstance) this._agentToolProgressEmitterInstance = new AgentToolProgressEmitter({
1461
+ resolveActiveRun: () => {
1462
+ const requestId = this._activeRequestId;
1463
+ if (!requestId) return null;
1464
+ const runId = this._agentToolRunsByRequestId.get(requestId);
1465
+ return runId ? {
1466
+ runId,
1467
+ requestId
1468
+ } : null;
1469
+ },
1470
+ broadcast: (requestId, chunkBody) => {
1471
+ this._broadcastChatMessage({
1472
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1473
+ id: requestId,
1474
+ body: chunkBody,
1475
+ done: false
1476
+ });
1477
+ },
1478
+ persistSnapshot: (runId, snapshot, at) => {
1479
+ this._ensureAgentToolTables();
1480
+ this.sql`
1481
+ update cf_ai_chat_agent_tool_runs
1482
+ set progress_json = ${JSON.stringify(snapshot)},
1483
+ last_signal_at = ${at}
1484
+ where run_id = ${runId}
1485
+ `;
1486
+ },
1487
+ persistMilestone: (runId, name, data, at) => this._persistAgentToolMilestone(runId, name, data, at)
1488
+ });
1489
+ return this._agentToolProgressEmitterInstance;
1490
+ }
1491
+ async reportProgress(progress, options) {
1492
+ if (this._agentToolProgressEmitter.report(progress, options) === "inactive") console.warn("[ai-chat] reportProgress() was called outside of an active agent-tool run; ignoring. Call it from within an onChatMessage turn that is running as a sub-agent.");
1493
+ }
1303
1494
  /**
1304
1495
  * Override to return structured agent-tool output instead of the default
1305
1496
  * final assistant text.
@@ -1320,6 +1511,150 @@ var AIChatAgent = class AIChatAgent extends Agent {
1320
1511
  }
1321
1512
  }
1322
1513
  /**
1514
+ * Serialize detached terminal delivery against the chat turn queue. A
1515
+ * fast-path push or backbone tick can land mid-turn, and an `onFinish` that
1516
+ * mutates chat state (`saveMessages`, `setState`, a follow-up
1517
+ * `runAgentTool`) running concurrently with an active LLM turn is a data
1518
+ * race. Those paths never run synchronously inside a turn body (they fire
1519
+ * from `waitUntil` / a scheduled alarm), so enqueuing on the turn queue runs
1520
+ * the delivery strictly between turns without risk of self-deadlock.
1521
+ *
1522
+ * An explicit `cancelAgentTool` (`serialize` unset) may be invoked from
1523
+ * inside the very turn that triggers it, where enqueuing WOULD self-deadlock,
1524
+ * so it runs inline in the caller's (or a fresh) `agentContext`.
1525
+ */
1526
+ async _runDetachedDelivery(invoke, options) {
1527
+ const inContext = () => __DO_NOT_USE_WILL_BREAK__agentContext.run({
1528
+ agent: this,
1529
+ connection: void 0,
1530
+ request: void 0,
1531
+ email: void 0
1532
+ }, invoke);
1533
+ if (!options?.serialize) {
1534
+ if (__DO_NOT_USE_WILL_BREAK__agentContext.getStore()?.agent === this) {
1535
+ await invoke();
1536
+ return;
1537
+ }
1538
+ await inContext();
1539
+ return;
1540
+ }
1541
+ await this.keepAliveWhile(() => this._turnQueue.enqueue(`detached-delivery:${crypto.randomUUID()}`, async () => {
1542
+ this._inSerializedDetachedDeliverySlot = true;
1543
+ try {
1544
+ await inContext();
1545
+ } finally {
1546
+ this._inSerializedDetachedDeliverySlot = false;
1547
+ }
1548
+ }));
1549
+ }
1550
+ /**
1551
+ * Inject a synthetic chat message for a detached-run notification, idempotent
1552
+ * on its deterministic `id` (a re-delivery from the warm tail + cold backbone
1553
+ * collapses to one — `persistMessages` is skipped when the id already exists).
1554
+ * When `react` is set the model then takes a turn over the new message.
1555
+ *
1556
+ * `@cloudflare/ai-chat` has no durable-submission layer (unlike Think's
1557
+ * `submitMessages`), so the turn cannot be enqueued-and-awaited from inside the
1558
+ * serialized delivery slot — `TurnQueue` has no re-entrancy bypass, so that
1559
+ * would self-deadlock. Instead: when we are already inside a turn slot (the
1560
+ * `serialize: true` finish delivery runs as its own enqueued turn) we run the
1561
+ * programmatic turn INLINE, reusing that slot — so the whole notify completes
1562
+ * before the ledger marks the slot delivered (eviction-safe). When we are not
1563
+ * inside a slot (a milestone fired from the `waitUntil` fast path or the
1564
+ * reconcile alarm) we enqueue a fresh turn normally.
1565
+ */
1566
+ async _injectDetachedNotification(id, role, text, metadata, options) {
1567
+ if (this._inFlightDetachedNotifications.has(id) || this.messages.some((message) => message.id === id)) return;
1568
+ this._inFlightDetachedNotifications.add(id);
1569
+ try {
1570
+ await this.persistMessages([...this.messages, {
1571
+ id,
1572
+ role,
1573
+ parts: [{
1574
+ type: "text",
1575
+ text
1576
+ }],
1577
+ metadata
1578
+ }]);
1579
+ if (!options.react) return;
1580
+ const runReply = (requestId) => this._runProgrammaticChatTurn(requestId, this._lastClientTools, this._lastBody, void 0);
1581
+ if (this._inSerializedDetachedDeliverySlot) await runReply(this._turnQueue.activeRequestId ?? nanoid());
1582
+ else if (this._turnQueue.isActive) {
1583
+ const requestId = nanoid();
1584
+ this.keepAliveWhile(() => this._runExclusiveChatTurn(requestId, () => runReply(requestId)));
1585
+ } else {
1586
+ const requestId = nanoid();
1587
+ await this._runExclusiveChatTurn(requestId, () => runReply(requestId));
1588
+ }
1589
+ } finally {
1590
+ this._inFlightDetachedNotifications.delete(id);
1591
+ }
1592
+ }
1593
+ /**
1594
+ * Format the message injected by `detached: { notify }` when a background run
1595
+ * finishes. Override to customize the prose, or return an empty string to
1596
+ * suppress the notification for a given outcome.
1597
+ */
1598
+ formatDetachedCompletion(run, result) {
1599
+ const label = `Background task "${run.agentType}" (run ${run.runId})`;
1600
+ switch (result.status) {
1601
+ case "completed": return result.summary ? `${label} finished:\n\n${result.summary}` : `${label} finished successfully.`;
1602
+ case "error": return `${label} failed${result.error ? `: ${result.error}` : "."}`;
1603
+ case "aborted": return `${label} was cancelled.`;
1604
+ case "interrupted": return result.reason === "budget-exceeded" ? `${label} ran out of time before completing and was stopped.` : `${label} was interrupted before completing${result.error ? `: ${result.error}` : "."}`;
1605
+ default: return `${label} ended (${result.status}).`;
1606
+ }
1607
+ }
1608
+ /**
1609
+ * Targeted completion hook for `detached: { notify }`. Auto-wired by
1610
+ * `runAgentTool` (resolved by name so the base `Agent` stays decoupled from the
1611
+ * chat layer). Injects the formatted completion as a user turn so the model
1612
+ * reacts to the background result. Idempotent per run + status (deterministic
1613
+ * message id), so an exactly-once finish — or a soft give-up followed by a real
1614
+ * completion — never injects a duplicate, while a give-up and a later real
1615
+ * completion surface as two distinct messages.
1616
+ */
1617
+ async _cfDetachedNotifyFinish(run, result) {
1618
+ const text = this.formatDetachedCompletion(run, result);
1619
+ if (!text) return;
1620
+ await this._injectDetachedNotification(`detached-finish:${run.runId}:${result.status}`, "user", text, {
1621
+ source: run.notifySource ?? "detached-agent-tool",
1622
+ runId: run.runId,
1623
+ agentType: run.agentType,
1624
+ status: result.status
1625
+ }, { react: true });
1626
+ }
1627
+ /**
1628
+ * Format the message injected when a `detached: { onMilestones }` milestone is
1629
+ * reached. Override to customize the prose (or return an empty string to
1630
+ * suppress a given milestone).
1631
+ */
1632
+ formatDetachedMilestone(run, milestone) {
1633
+ const label = `Background task "${run.agentType}" (run ${run.runId})`;
1634
+ const detail = milestone.data !== void 0 ? `\n\n${JSON.stringify(milestone.data, null, 2)}` : "";
1635
+ return `${label} reached milestone "${milestone.name}".${detail}`;
1636
+ }
1637
+ /**
1638
+ * Targeted milestone hook for `detached: { onMilestones }`. Idempotent per run
1639
+ * + milestone NAME (deterministic message id), so the warm tail and the cold
1640
+ * backbone reconcile converge to at most one message.
1641
+ *
1642
+ * - `"narrate"` (default): a synthetic **assistant** message injected directly
1643
+ * — no model turn.
1644
+ * - `"react"`: a **user** message followed by a model turn so the agent
1645
+ * responds to the milestone.
1646
+ */
1647
+ async _deliverDetachedMilestone(run, milestone, mode) {
1648
+ const text = this.formatDetachedMilestone(run, milestone);
1649
+ if (!text) return;
1650
+ await this._injectDetachedNotification(`detached-ms:${run.runId}:${milestone.name}`, mode === "narrate" ? "assistant" : "user", text, {
1651
+ source: run.notifySource ?? "detached-agent-tool",
1652
+ runId: run.runId,
1653
+ agentType: run.agentType,
1654
+ milestone: milestone.name
1655
+ }, { react: mode === "react" });
1656
+ }
1657
+ /**
1323
1658
  * Bind the child turn that is about to stream to its agent-tool run, at
1324
1659
  * the moment the turn's request id is first knowable (inside the turn,
1325
1660
  * before any frame is broadcast). The in-memory mapping drives frame
@@ -1439,6 +1774,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1439
1774
  options.signal?.removeEventListener("abort", abortFromParent);
1440
1775
  this._agentToolAbortControllers.delete(options.runId);
1441
1776
  this._agentToolLiveSequences.delete(options.runId);
1777
+ this._agentToolProgressEmitterInstance?.forget(options.runId);
1442
1778
  if (this._agentToolAbortControllers.size === 0) this._agentToolRunsByRequestId.clear();
1443
1779
  else for (const [reqId, runId] of this._agentToolRunsByRequestId) if (runId === options.runId) this._agentToolRunsByRequestId.delete(reqId);
1444
1780
  this._agentToolLastErrors.delete(options.runId);
@@ -1470,14 +1806,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
1470
1806
  * mean recovery is still resolving the interrupted turn; `exhausted`/`failed`
1471
1807
  * mean recovery gave up; a completed recovery deletes its incident.
1472
1808
  */
1473
- async _classifyAgentToolChildRecovery() {
1474
- const entries = await this.ctx.storage.list({ prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX });
1475
- let failed = false;
1476
- for (const incident of entries.values()) {
1477
- if (incident.status === "detected" || incident.status === "scheduled" || incident.status === "attempting") return "in-progress";
1478
- if (incident.status === "exhausted" || incident.status === "failed") failed = true;
1479
- }
1480
- return failed ? "failed" : "none";
1809
+ _classifyAgentToolChildRecovery() {
1810
+ return classifyAgentToolChildRecovery(this.ctx.storage);
1481
1811
  }
1482
1812
  /**
1483
1813
  * Reconcile a stale (post-eviction) child run row from the child's own
@@ -1579,6 +1909,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
1579
1909
  runId,
1580
1910
  input
1581
1911
  }, messagesAfterStart) : void 0;
1912
+ const progress = AIChatAgent._progressSnapshotFromRow(row);
1913
+ const milestones = this._readAgentToolMilestones(runId);
1582
1914
  return {
1583
1915
  runId,
1584
1916
  status: row.status,
@@ -1588,9 +1920,22 @@ var AIChatAgent = class AIChatAgent extends Agent {
1588
1920
  summary: row.status === "completed" ? row.summary ?? "" : void 0,
1589
1921
  error: row.status === "error" ? row.error_message ?? void 0 : void 0,
1590
1922
  startedAt: row.started_at,
1591
- completedAt: row.completed_at ?? void 0
1923
+ completedAt: row.completed_at ?? void 0,
1924
+ ...progress ? { progress } : {},
1925
+ ...milestones.length > 0 ? { milestones } : {}
1592
1926
  };
1593
1927
  }
1928
+ static _progressSnapshotFromRow(row) {
1929
+ if (row.progress_json == null || row.last_signal_at == null) return;
1930
+ try {
1931
+ return {
1932
+ ...JSON.parse(row.progress_json),
1933
+ at: row.last_signal_at
1934
+ };
1935
+ } catch {
1936
+ return { at: row.last_signal_at };
1937
+ }
1938
+ }
1594
1939
  async getAgentToolChunks(runId, options) {
1595
1940
  this._flushChunkBuffer();
1596
1941
  const row = this._getAgentToolRunRow(runId);
@@ -1646,7 +1991,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
1646
1991
  _getAgentToolRunRow(runId) {
1647
1992
  return this.sql`
1648
1993
  select run_id, request_id, status, input_json, output_json, summary,
1649
- error_message, started_at, completed_at
1994
+ error_message, started_at, completed_at, progress_json,
1995
+ last_signal_at
1650
1996
  from cf_ai_chat_agent_tool_runs
1651
1997
  where run_id = ${runId}
1652
1998
  `[0] ?? null;
@@ -1775,6 +2121,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1775
2121
  status: "skipped"
1776
2122
  };
1777
2123
  const requestId = nanoid();
2124
+ this._rebindAgentToolChildRunRequestId(requestId);
1778
2125
  const clientTools = this._lastClientTools;
1779
2126
  const resolvedBody = body ?? this._lastBody;
1780
2127
  const epoch = this._turnQueue.generation;
@@ -1798,6 +2145,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1798
2145
  const abortSignal = this._abortRegistry.getSignal(requestId);
1799
2146
  const detachExternal = this._abortRegistry.linkExternal(requestId, options?.signal);
1800
2147
  try {
2148
+ await this._repairInterruptedToolsBeforeTurn();
1801
2149
  const response = await this.onChatMessage(() => {}, {
1802
2150
  requestId,
1803
2151
  abortSignal,
@@ -1839,6 +2187,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1839
2187
  status: "skipped"
1840
2188
  };
1841
2189
  const requestId = nanoid();
2190
+ this._rebindAgentToolChildRunRequestId(requestId);
1842
2191
  const epoch = this._turnQueue.generation;
1843
2192
  let status = "completed";
1844
2193
  let error;
@@ -1867,24 +2216,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1867
2216
  * @internal
1868
2217
  */
1869
2218
  _resolveChatRecoveryConfig() {
1870
- const raw = this.chatRecovery;
1871
- const custom = typeof raw === "object" ? raw : void 0;
1872
- return {
1873
- enabled: raw !== false,
1874
- maxAttempts: Math.max(1, Math.floor(custom?.maxAttempts ?? DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS)),
1875
- stableTimeoutMs: Math.max(0, Math.floor(custom?.stableTimeoutMs ?? DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS)),
1876
- terminalMessage: custom?.terminalMessage ?? DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE,
1877
- noProgressTimeoutMs: Math.max(0, Math.floor(custom?.noProgressTimeoutMs ?? DEFAULT_CHAT_RECOVERY_NO_PROGRESS_TIMEOUT_MS)),
1878
- maxRecoveryWork: typeof custom?.maxRecoveryWork === "number" && custom.maxRecoveryWork >= 0 ? custom.maxRecoveryWork : DEFAULT_CHAT_RECOVERY_MAX_WORK,
1879
- ...custom?.shouldKeepRecovering ? { shouldKeepRecovering: custom.shouldKeepRecovering } : {},
1880
- ...custom?.onExhausted ? { onExhausted: custom.onExhausted } : {}
1881
- };
1882
- }
1883
- _chatRecoveryIncidentId(input) {
1884
- return [input.recoveryRootRequestId ?? input.requestId, input.latestUserMessageId ?? ""].join(":");
1885
- }
1886
- _chatRecoveryIncidentKey(incidentId) {
1887
- return `${CHAT_RECOVERY_INCIDENT_KEY_PREFIX}${encodeURIComponent(incidentId)}`;
2219
+ return resolveChatRecoveryConfig(this.chatRecovery);
1888
2220
  }
1889
2221
  /**
1890
2222
  * Monotonic forward-progress signal for recovery budget resets.
@@ -1901,14 +2233,14 @@ var AIChatAgent = class AIChatAgent extends Agent {
1901
2233
  * it (#1637).
1902
2234
  */
1903
2235
  async _chatRecoveryProgressMarker() {
1904
- return await this.ctx.storage.get(CHAT_RECOVERY_PROGRESS_KEY) ?? 0;
2236
+ return readChatRecoveryProgress(this.ctx.storage);
1905
2237
  }
1906
2238
  /** Advance the durable recovery-progress counter. Called from
1907
2239
  * `_maybeBumpRecoveryProgress` when new content is streamed (real,
1908
- * reconnect-immune forward progress). */
2240
+ * reconnect-immune forward progress). The increment lives in the shared
2241
+ * engine (agents/chat); this is the package binding. */
1909
2242
  async _bumpChatRecoveryProgress() {
1910
- const current = await this.ctx.storage.get(CHAT_RECOVERY_PROGRESS_KEY) ?? 0;
1911
- await this.ctx.storage.put(CHAT_RECOVERY_PROGRESS_KEY, current + 1);
2243
+ return bumpChatRecoveryProgress(this.ctx.storage);
1912
2244
  }
1913
2245
  /**
1914
2246
  * N9: forwarding a sub-agent's chunks IS forward progress for this parent
@@ -1920,160 +2252,70 @@ var AIChatAgent = class AIChatAgent extends Agent {
1920
2252
  * Throttled (and reset per isolate) so we never write storage per token.
1921
2253
  */
1922
2254
  async _onAgentToolStreamProgress() {
1923
- const now = Date.now();
1924
- if (now - this._lastAgentToolStreamProgressAt < AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS) return;
1925
- this._lastAgentToolStreamProgressAt = now;
1926
- await this._bumpChatRecoveryProgress();
1927
- }
1928
- /** Whether a reconstructed partial carries any settled (provider-accepted)
1929
- * tool result — the completed, often non-idempotent work that a
1930
- * `{ persist: false }` recovery return would silently discard.
1931
- * `convertToModelMessages` treats `output-available` / `output-error` /
1932
- * `output-denied` (or a part carrying `output`/`result`) as settled. */
1933
- _partialHasSettledToolResults(parts) {
1934
- return parts.some((part) => {
1935
- const record = part;
1936
- const type = typeof record.type === "string" ? record.type : "";
1937
- if (!(type.startsWith("tool-") || type === "dynamic-tool")) return false;
1938
- if ("output" in record || "result" in record) return true;
1939
- const state = typeof record.state === "string" ? record.state : "";
1940
- return state === "output-available" || state === "output-error" || state === "output-denied";
2255
+ if (this._agentToolStreamProgress.shouldCredit(Date.now())) await this._bumpChatRecoveryProgress();
2256
+ }
2257
+ _chatRecoveryEngine() {
2258
+ return this._chatRecoveryEngineInstance ??= new ChatRecoveryEngine({
2259
+ resolveConfig: () => this._resolveChatRecoveryConfig(),
2260
+ now: () => Date.now(),
2261
+ sweepStaleIncidents: (now) => sweepStaleChatRecoveryIncidents(this.ctx.storage, now),
2262
+ getIncident: async (key) => await this.ctx.storage.get(key) ?? null,
2263
+ readProgress: () => this._chatRecoveryProgressMarker(),
2264
+ isAwaitingClientInteraction: () => this.hasPendingClientInteraction(),
2265
+ putIncident: (key, incident) => this.ctx.storage.put(key, incident),
2266
+ deleteIncident: async (key) => {
2267
+ await this.ctx.storage.delete(key);
2268
+ },
2269
+ emitRecoveryEvent: (event) => this._emit(event.type, {
2270
+ incidentId: event.incidentId,
2271
+ requestId: event.requestId,
2272
+ attempt: event.attempt,
2273
+ maxAttempts: event.maxAttempts,
2274
+ recoveryKind: event.recoveryKind,
2275
+ ...event.reason ? { reason: event.reason } : {}
2276
+ }),
2277
+ scheduleRecovery: async (callback, data, reason, delaySeconds) => {
2278
+ await this.schedule(delaySeconds, callback, data, chatRecoverySchedulePolicy(reason));
2279
+ },
2280
+ setRecovering: (active, requestId) => this._setChatRecovering(active, requestId),
2281
+ onShouldKeepRecoveringError: (error) => console.error("[AIChatAgent] chatRecovery shouldKeepRecovering hook threw", error),
2282
+ exhaustChatRecovery: (incident, config, partial, streamId, createdAt) => this._exhaustChatRecovery(incident, config, partial, streamId, createdAt),
2283
+ resolveRecoveryStream: (requestId) => this._resolveAIChatRecoveryStream(requestId),
2284
+ getPartialStreamText: (streamId) => this._getPartialStreamText(streamId),
2285
+ activeChatRecoveryRootRequestId: () => this._activeChatRecoveryRootRequestId,
2286
+ onGiveUpBookkeepingError: (phase, error) => console.error(phase === "read" ? "[AIChatAgent] failed to read recovery incident during give-up; synthesizing" : "[AIChatAgent] failed to persist sealed recovery incident during give-up", error)
1941
2287
  });
1942
2288
  }
1943
- /** Sweep recovery incidents that have been inactive past the TTL. */
1944
- async _sweepStaleChatRecoveryIncidents(now) {
1945
- const entries = await this.ctx.storage.list({ prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX });
1946
- const staleKeys = [];
1947
- for (const [key, incident] of entries) if (now - (incident?.lastAttemptAt ?? incident?.firstSeenAt ?? 0) > CHAT_RECOVERY_INCIDENT_TTL_MS) staleKeys.push(key);
1948
- for (let i = 0; i < staleKeys.length; i += KV_DELETE_MAX_KEYS) await this.ctx.storage.delete(staleKeys.slice(i, i + KV_DELETE_MAX_KEYS));
1949
- }
1950
2289
  async _beginChatRecoveryIncident(input) {
1951
- const config = this._resolveChatRecoveryConfig();
1952
- const incidentId = this._chatRecoveryIncidentId(input);
1953
- const key = this._chatRecoveryIncidentKey(incidentId);
1954
- const now = input.nowMs ?? Date.now();
1955
- await this._sweepStaleChatRecoveryIncidents(now);
1956
- const existing = await this.ctx.storage.get(key);
1957
- const prevProgress = existing?.progress ?? 0;
1958
- const currentProgress = await this._chatRecoveryProgressMarker();
1959
- const madeProgress = existing != null && currentProgress > prevProgress;
1960
- const awaitingClientInteraction = this.hasPendingClientInteraction();
1961
- const lastProgressAt = madeProgress || awaitingClientInteraction ? now : existing?.lastProgressAt ?? existing?.firstSeenAt ?? now;
1962
- const noProgressExceeded = existing != null && !awaitingClientInteraction && now - lastProgressAt > config.noProgressTimeoutMs;
1963
- const workBaseline = existing?.workBaseline ?? currentProgress;
1964
- const progress = Math.max(prevProgress, currentProgress);
1965
- const work = progress - workBaseline;
1966
- const workBudgetExceeded = existing != null && Number.isFinite(config.maxRecoveryWork) && work > config.maxRecoveryWork;
1967
- const debounced = existing != null && !madeProgress && now - existing.lastAttemptAt < CHAT_RECOVERY_ALARM_DEBOUNCE_MS;
1968
- const attempt = madeProgress ? 1 : debounced ? existing?.attempt ?? 1 : (existing?.attempt ?? 0) + 1;
1969
- let abortedByCaller = false;
1970
- if (existing != null && !awaitingClientInteraction && config.shouldKeepRecovering && !noProgressExceeded && !workBudgetExceeded && attempt <= config.maxAttempts) try {
1971
- abortedByCaller = await config.shouldKeepRecovering({
1972
- incidentId,
1973
- requestId: input.requestId,
1974
- recoveryRootRequestId: input.recoveryRootRequestId ?? input.requestId,
1975
- attempt,
1976
- maxAttempts: config.maxAttempts,
1977
- recoveryKind: input.recoveryKind,
1978
- work,
1979
- ageMs: now - (existing.firstSeenAt ?? now)
1980
- }) === false;
1981
- } catch (error) {
1982
- console.error("[AIChatAgent] chatRecovery shouldKeepRecovering hook threw", error);
1983
- }
1984
- const exhausted = !awaitingClientInteraction && (noProgressExceeded || workBudgetExceeded || abortedByCaller || attempt > config.maxAttempts);
1985
- const incident = {
1986
- incidentId,
1987
- requestId: input.requestId,
1988
- recoveryRootRequestId: input.recoveryRootRequestId ?? input.requestId,
1989
- recoveryKind: input.recoveryKind,
1990
- attempt,
1991
- maxAttempts: config.maxAttempts,
1992
- status: exhausted ? "exhausted" : "attempting",
1993
- firstSeenAt: existing?.firstSeenAt ?? now,
1994
- lastAttemptAt: now,
1995
- lastProgressAt,
1996
- progress,
1997
- workBaseline,
1998
- ...exhausted ? { reason: workBudgetExceeded ? "work_budget_exceeded" : noProgressExceeded ? "no_progress_timeout" : abortedByCaller ? "recovery_aborted" : "max_attempts_exceeded" } : {}
1999
- };
2000
- await this.ctx.storage.put(key, incident);
2001
- if (!existing) this._emit("chat:recovery:detected", {
2002
- incidentId,
2003
- requestId: input.requestId,
2004
- attempt,
2005
- maxAttempts: config.maxAttempts,
2006
- recoveryKind: input.recoveryKind
2007
- });
2008
- this._emit("chat:recovery:attempt", {
2009
- incidentId,
2010
- requestId: input.requestId,
2011
- attempt,
2012
- maxAttempts: config.maxAttempts,
2013
- recoveryKind: input.recoveryKind
2014
- });
2015
- return {
2016
- incident,
2017
- config,
2018
- exhausted
2019
- };
2290
+ return this._chatRecoveryEngine().beginIncident(input);
2020
2291
  }
2021
2292
  async _updateChatRecoveryIncident(incidentId, status, reason) {
2022
- if (!incidentId) return;
2023
- const key = this._chatRecoveryIncidentKey(incidentId);
2024
- const incident = await this.ctx.storage.get(key);
2025
- if (!incident) return;
2026
- if (status === "completed") await this.ctx.storage.delete(key);
2027
- else {
2028
- const updated = {
2029
- ...incident,
2030
- status,
2031
- ...reason ? { reason } : {}
2032
- };
2033
- await this.ctx.storage.put(key, updated);
2034
- }
2035
- const eventType = status === "completed" ? "chat:recovery:completed" : status === "skipped" ? "chat:recovery:skipped" : status === "failed" ? "chat:recovery:failed" : void 0;
2036
- if (eventType) this._emit(eventType, {
2037
- incidentId,
2038
- requestId: incident.requestId,
2039
- attempt: incident.attempt,
2040
- maxAttempts: incident.maxAttempts,
2041
- recoveryKind: incident.recoveryKind,
2042
- ...reason ? { reason } : {}
2043
- });
2044
- if (status === "scheduled") await this._setChatRecovering(true, incident.recoveryRootRequestId ?? incident.requestId);
2045
- else if (status === "completed" || status === "skipped" || status === "failed") await this._setChatRecovering(false);
2293
+ return this._chatRecoveryEngine().updateIncident(incidentId, status, reason);
2046
2294
  }
2047
2295
  async _exhaustChatRecovery(incident, config, partial, streamId, createdAt) {
2048
- const ctx = {
2049
- incidentId: incident.incidentId,
2050
- requestId: incident.requestId,
2051
- recoveryRootRequestId: incident.recoveryRootRequestId ?? incident.requestId,
2052
- attempt: incident.attempt,
2053
- maxAttempts: incident.maxAttempts,
2054
- recoveryKind: incident.recoveryKind,
2055
- streamId,
2056
- createdAt,
2296
+ await runChatRecoveryExhaustion({
2297
+ incident,
2298
+ config,
2057
2299
  partialText: partial.text,
2058
2300
  partialParts: partial.parts,
2059
- reason: incident.reason ?? "max_attempts_exceeded",
2060
- terminalMessage: config.terminalMessage
2061
- };
2062
- this._emit("chat:recovery:exhausted", ctx);
2063
- try {
2064
- await config.onExhausted?.(ctx);
2065
- } catch (error) {
2066
- console.error("[AIChatAgent] chatRecovery onExhausted hook threw", error);
2067
- }
2068
- await this._recordChatTerminal(incident.requestId, config.terminalMessage);
2069
- this._broadcastChatMessage({
2070
- body: config.terminalMessage,
2071
- done: true,
2072
- error: true,
2073
- id: incident.requestId,
2074
- type: "cf_agent_use_chat_response"
2301
+ streamId,
2302
+ createdAt
2303
+ }, {
2304
+ emit: (event) => this._emit("chat:recovery:exhausted", event),
2305
+ onExhausted: config.onExhausted,
2306
+ onError: (error) => console.error("[AIChatAgent] chatRecovery onExhausted hook threw", error),
2307
+ terminalize: async (ctx) => {
2308
+ this._broadcastChatMessage({
2309
+ body: ctx.terminalMessage,
2310
+ done: true,
2311
+ error: true,
2312
+ id: ctx.requestId,
2313
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
2314
+ });
2315
+ await this._recordChatTerminal(ctx.requestId, ctx.terminalMessage);
2316
+ await this._setChatRecovering(false);
2317
+ }
2075
2318
  });
2076
- await this._setChatRecovering(false);
2077
2319
  }
2078
2320
  /**
2079
2321
  * Persist a durable record of the last terminal turn so a client that
@@ -2082,87 +2324,89 @@ var AIChatAgent = class AIChatAgent extends Agent {
2082
2324
  * sufficient because only the most recent terminal is relevant.
2083
2325
  */
2084
2326
  async _recordChatTerminal(requestId, body) {
2085
- await this.ctx.storage.put(CHAT_LAST_TERMINAL_KEY, {
2086
- requestId,
2087
- body
2088
- });
2327
+ await recordChatTerminal(this.ctx.storage, requestId, body);
2089
2328
  }
2090
2329
  /** Clear the durable terminal record once a later turn supersedes it (#1645). */
2091
2330
  async _clearChatTerminal() {
2092
- await this.ctx.storage.delete(CHAT_LAST_TERMINAL_KEY);
2331
+ await clearChatTerminal(this.ctx.storage);
2093
2332
  }
2094
2333
  async _pendingChatTerminal() {
2095
- return await this.ctx.storage.get(CHAT_LAST_TERMINAL_KEY) ?? null;
2096
- }
2097
- /**
2098
- * Replay a pending terminal outcome (#1645) over the resume handshake so a
2099
- * reconnecting client surfaces it exactly like a live exhaustion. The bare
2100
- * terminal frame is dropped by the client unless it arrives on a resumed
2101
- * stream — the only path that reaches the transport's stream reader and
2102
- * becomes `useChat.error` — so we drive `STREAM_RESUMING` here and deliver
2103
- * the error frame once the client ACKs (see `_replayTerminalOnAck`).
2104
- * Returns true if a terminal was pending (and `STREAM_RESUMING` was sent).
2105
- */
2106
- async _replayTerminalOnResume(connection) {
2107
- const pending = await this._pendingChatTerminal();
2108
- if (!pending) return false;
2109
- sendIfOpen(connection, JSON.stringify({
2110
- type: "cf_agent_stream_resuming",
2111
- id: pending.requestId
2112
- }));
2113
- return true;
2334
+ return pendingChatTerminal(this.ctx.storage);
2114
2335
  }
2115
2336
  /**
2116
- * Deliver the pending terminal error frame on the resumed stream the client
2117
- * ACKed (#1645). The record is retained (not cleared) so concurrent
2118
- * reconnects (e.g. multiple tabs) each learn the outcome; it is cleared when
2119
- * a later turn supersedes it.
2337
+ * Build the on-connect "recovering…" replay frame (#1620), or `null` when no
2338
+ * (non-stale) recovery is in progress. A client that connects between recovery
2339
+ * attempts (no active stream) reads the turn as working rather than frozen.
2340
+ * A record older than the flag TTL is treated as abandoned (its terminal-clear
2341
+ * never ran) and skipped, so a dead recovery can't show "recovering…" forever.
2342
+ * Mirrors `@cloudflare/think`'s `_buildIdleConnectMessages` recovering replay.
2120
2343
  */
2121
- async _replayTerminalOnAck(connection, requestId) {
2122
- const pending = await this._pendingChatTerminal();
2123
- if (!pending || pending.requestId !== requestId) return false;
2124
- if (!this._resumableStream.replayErroredChunksByRequestId(connection, pending.requestId)) return true;
2125
- sendIfOpen(connection, JSON.stringify({
2126
- body: pending.body,
2127
- done: true,
2128
- error: true,
2129
- id: pending.requestId,
2130
- type: "cf_agent_use_chat_response"
2131
- }));
2132
- return true;
2344
+ async _buildRecoveringConnectFrame() {
2345
+ return buildChatRecoveringFrame(this.ctx.storage, MessageType.CF_AGENT_CHAT_RECOVERING, Date.now());
2133
2346
  }
2134
2347
  /**
2135
2348
  * Set or clear the live "recovering…" status (#1620). Persists a durable
2136
2349
  * record (so set/clear stay consistent across the isolates a recovery spans)
2137
2350
  * and broadcasts a `CF_AGENT_CHAT_RECOVERING` frame on a genuine transition.
2138
- * NOTE: the live "recovering…" signal is still not replayed on connect — only
2139
- * the terminal outcome is (#1645, via the resume handshake).
2351
+ * The status is also replayed on connect (`_buildRecoveringConnectFrame`) so a
2352
+ * client connecting mid-recovery isn't left looking frozen; the terminal
2353
+ * outcome is surfaced separately over the resume handshake (#1645).
2140
2354
  */
2141
2355
  async _setChatRecovering(active, requestId) {
2142
- const existing = await this.ctx.storage.get(CHAT_RECOVERING_KEY);
2143
- const activeExisting = existing && Date.now() - (existing.at ?? 0) < CHAT_RECOVERING_FLAG_TTL_MS;
2144
- if (active) {
2145
- if (activeExisting) return;
2146
- await this.ctx.storage.put(CHAT_RECOVERING_KEY, {
2147
- ...requestId ? { requestId } : {},
2148
- at: Date.now()
2149
- });
2150
- } else {
2151
- if (!existing) return;
2152
- await this.ctx.storage.delete(CHAT_RECOVERING_KEY);
2153
- requestId = requestId ?? existing.requestId;
2154
- }
2155
- this._broadcastChatMessage({
2156
- type: "cf_agent_chat_recovering",
2157
- recovering: active,
2158
- ...requestId ? { id: requestId } : {}
2356
+ await setChatRecovering(active, requestId, {
2357
+ storage: this.ctx.storage,
2358
+ messageType: MessageType.CF_AGENT_CHAT_RECOVERING,
2359
+ broadcast: (frame) => this._broadcastChatMessage(frame),
2360
+ now: Date.now()
2159
2361
  });
2160
2362
  }
2161
2363
  async _handleInternalFiberRecovery(ctx) {
2162
- const chatPrefix = this.constructor.CHAT_FIBER_NAME + ":";
2163
- if (!ctx.name.startsWith(chatPrefix)) return false;
2164
- const requestId = ctx.name.slice(chatPrefix.length);
2165
- const { snapshot: recoverySnapshot, user: recoveryData } = unwrapChatFiberSnapshot("__cfAIChatFiberSnapshot", ctx.snapshot, "ai-chat-turn");
2364
+ return this._chatRecoveryEngine().handleChatFiberRecovery(ctx, {
2365
+ chatFiberPrefix: () => this.constructor.CHAT_FIBER_NAME + ":",
2366
+ unwrapRecoverySnapshot: (fiber) => {
2367
+ const { snapshot, user } = unwrapChatFiberSnapshot("__cfAIChatFiberSnapshot", fiber.snapshot, "ai-chat-turn");
2368
+ return {
2369
+ snapshot,
2370
+ recoveryData: user
2371
+ };
2372
+ },
2373
+ classifyRecoveredTurn: (input) => this._classifyRecoveredChatTurn(input),
2374
+ invokeOnChatRecovery: (input) => this.onChatRecovery({
2375
+ incidentId: input.incident.incidentId,
2376
+ recoveryRootRequestId: input.recoveryRootRequestId,
2377
+ attempt: input.incident.attempt,
2378
+ maxAttempts: input.incident.maxAttempts,
2379
+ recoveryKind: input.recoveryKind,
2380
+ streamId: input.streamId,
2381
+ requestId: input.requestId,
2382
+ partialText: input.partial.text,
2383
+ partialParts: input.partial.parts,
2384
+ recoveryData: input.recoveryData,
2385
+ messages: [...this.messages],
2386
+ lastBody: input.snapshot?.lastBody ?? this._lastBody,
2387
+ lastClientTools: input.snapshot?.lastClientTools ?? this._lastClientTools,
2388
+ createdAt: input.createdAt
2389
+ }),
2390
+ shouldPersistOrphanedPartial: (input) => input.streamStillActive,
2391
+ persistOrphanedStream: (streamId) => this._persistOrphanedStream(streamId),
2392
+ completeRecoveredStream: (streamId) => {
2393
+ this._resumableStream.complete(streamId);
2394
+ this._ensureStreamCleanupScheduled();
2395
+ },
2396
+ dispatchRecoveredTurn: (input) => this._dispatchRecoveredChatTurn(input)
2397
+ });
2398
+ }
2399
+ /**
2400
+ * Resolve the orphaned stream for a recovered chat turn — drives BOTH the wake
2401
+ * path (full result) and the give-up terminalization (which reads only
2402
+ * `.streamId`). Prefers the newest durable stream row keyed by the recovery-
2403
+ * root request id; falls back to the live active stream; `streamId` is `""`
2404
+ * when neither survives. `AIChatAgent` does not model terminal stream status,
2405
+ * so `streamStatus` is left `undefined` (keeping the engine's terminal-stream
2406
+ * branches dead here) — see the "substrate capabilities are optional" decision
2407
+ * in the RFC.
2408
+ */
2409
+ _resolveAIChatRecoveryStream(requestId) {
2166
2410
  let streamId = "";
2167
2411
  if (requestId) {
2168
2412
  const rows = this.sql`
@@ -2173,108 +2417,81 @@ var AIChatAgent = class AIChatAgent extends Agent {
2173
2417
  if (rows.length > 0) streamId = rows[0].id;
2174
2418
  }
2175
2419
  if (!streamId && this._resumableStream.hasActiveStream()) streamId = this._resumableStream.activeStreamId ?? "";
2176
- const partial = streamId ? this._getPartialStreamText(streamId) : {
2177
- text: "",
2178
- parts: []
2420
+ const streamStillActive = Boolean(streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId);
2421
+ return {
2422
+ streamId,
2423
+ streamStillActive
2179
2424
  };
2180
- const streamStillActive = streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId;
2181
- const shouldRetryPreStream = this._shouldRetryRecoveredPreStreamTurn(recoverySnapshot, streamId ?? "", partial);
2425
+ }
2426
+ /**
2427
+ * Classify a recovered turn as `retry` or `continue`. The `shouldRetryPreStream`
2428
+ * detail is threaded to the dispatch decision; `emptyPartialNewTurn` only
2429
+ * influences the reported kind (an empty partial persists nothing, so a new turn
2430
+ * is re-run fresh rather than merged into the previous assistant — #1691). The
2431
+ * `persist: false` discard case stays "continue" here and only surfaces as
2432
+ * "retry" on the `chat:recovery:scheduled` event, decided in dispatch.
2433
+ */
2434
+ _classifyRecoveredChatTurn(input) {
2435
+ const shouldRetryPreStream = this._shouldRetryRecoveredPreStreamTurn(input.snapshot, input.streamId, input.partial);
2182
2436
  const preStreamLeaf = this.messages.length > 0 ? this.messages[this.messages.length - 1] : void 0;
2183
- const emptyPartialNewTurn = !!streamId && recoverySnapshot?.continuation === false && !!recoverySnapshot.latestUserMessageId && partial.text === "" && partial.parts.length === 0 && preStreamLeaf?.role === "user" && preStreamLeaf.id === recoverySnapshot.latestUserMessageId;
2184
- const recoveryKind = shouldRetryPreStream || emptyPartialNewTurn ? "retry" : "continue";
2185
- const recoveryRootRequestId = recoverySnapshot?.recoveryRootRequestId ?? requestId;
2186
- const { incident, config, exhausted } = await this._beginChatRecoveryIncident({
2187
- requestId,
2188
- recoveryRootRequestId,
2189
- latestUserMessageId: recoverySnapshot?.latestUserMessageId,
2190
- recoveryKind
2437
+ const emptyPartialNewTurn = !!input.streamId && input.snapshot?.continuation === false && !!input.snapshot.latestUserMessageId && input.partial.text === "" && input.partial.parts.length === 0 && preStreamLeaf?.role === "user" && preStreamLeaf.id === input.snapshot.latestUserMessageId;
2438
+ return {
2439
+ recoveryKind: shouldRetryPreStream || emptyPartialNewTurn ? "retry" : "continue",
2440
+ detail: { shouldRetryPreStream }
2441
+ };
2442
+ }
2443
+ /**
2444
+ * The retry/continue/skip decision for a recovered chat turn, run after the
2445
+ * partial is persisted and the stream completed. A NEW turn that left no
2446
+ * persisted assistant partial (the leaf is still the user message) is re-run
2447
+ * fresh instead of continued (which would clone + merge into the previous
2448
+ * assistant turn — #1691); this lost-partial check is re-derived here from the
2449
+ * now-updated leaf rather than carried from classify.
2450
+ */
2451
+ async _dispatchRecoveredChatTurn(input) {
2452
+ const { incident, options, snapshot, recoveryRootRequestId } = input;
2453
+ const leaf = this.messages.length > 0 ? this.messages[this.messages.length - 1] : void 0;
2454
+ const lostPartialUserId = snapshot?.continuation === false && snapshot.latestUserMessageId && leaf?.role === "user" && leaf.id === snapshot.latestUserMessageId ? snapshot.latestUserMessageId : void 0;
2455
+ const targetId = input.detail.shouldRetryPreStream || lostPartialUserId !== void 0 ? void 0 : this._findLastAssistantMessage()?.id;
2456
+ if (input.detail.shouldRetryPreStream && options.continue !== false) await this._chatRecoveryEngine().scheduleRecovery({
2457
+ incident,
2458
+ recoveryKind: input.recoveryKind,
2459
+ callback: "_chatRecoveryRetry",
2460
+ data: {
2461
+ targetUserId: snapshot?.latestUserMessageId,
2462
+ originalRequestId: recoveryRootRequestId,
2463
+ incidentId: incident.incidentId,
2464
+ lastBody: snapshot?.lastBody ?? null,
2465
+ lastClientTools: snapshot?.lastClientTools ?? null
2466
+ }
2191
2467
  });
2192
- if (exhausted) {
2193
- if (streamStillActive) await this._persistOrphanedStream(streamId);
2194
- await this._exhaustChatRecovery(incident, config, partial, streamId, ctx.createdAt);
2195
- return true;
2196
- }
2197
- try {
2198
- const options = await this.onChatRecovery({
2468
+ else if (lostPartialUserId !== void 0 && options.continue !== false) await this._chatRecoveryEngine().scheduleRecovery({
2469
+ incident,
2470
+ recoveryKind: "retry",
2471
+ callback: "_chatRecoveryRetry",
2472
+ data: {
2473
+ targetUserId: lostPartialUserId,
2474
+ originalRequestId: recoveryRootRequestId,
2199
2475
  incidentId: incident.incidentId,
2200
- recoveryRootRequestId,
2201
- attempt: incident.attempt,
2202
- maxAttempts: incident.maxAttempts,
2203
- recoveryKind,
2204
- streamId: streamId ?? "",
2205
- requestId,
2206
- partialText: partial.text,
2207
- partialParts: partial.parts,
2208
- recoveryData,
2209
- messages: [...this.messages],
2210
- lastBody: recoverySnapshot?.lastBody ?? this._lastBody,
2211
- lastClientTools: recoverySnapshot?.lastClientTools ?? this._lastClientTools,
2212
- createdAt: ctx.createdAt
2213
- }) ?? {};
2214
- if (streamStillActive && (options.persist !== false || this._partialHasSettledToolResults(partial.parts))) await this._persistOrphanedStream(streamId);
2215
- if (streamStillActive) {
2216
- this._resumableStream.complete(streamId);
2217
- this._ensureStreamCleanupScheduled();
2476
+ lastBody: snapshot?.lastBody ?? null,
2477
+ lastClientTools: snapshot?.lastClientTools ?? null
2218
2478
  }
2219
- const leaf = this.messages.length > 0 ? this.messages[this.messages.length - 1] : void 0;
2220
- const lostPartialUserId = recoverySnapshot?.continuation === false && recoverySnapshot.latestUserMessageId && leaf?.role === "user" && leaf.id === recoverySnapshot.latestUserMessageId ? recoverySnapshot.latestUserMessageId : void 0;
2221
- const targetId = shouldRetryPreStream || lostPartialUserId !== void 0 ? void 0 : this._findLastAssistantMessage()?.id;
2222
- if (shouldRetryPreStream && options.continue !== false) {
2223
- await this._updateChatRecoveryIncident(incident.incidentId, "scheduled");
2224
- this._emit("chat:recovery:scheduled", {
2225
- incidentId: incident.incidentId,
2226
- requestId,
2227
- attempt: incident.attempt,
2228
- maxAttempts: incident.maxAttempts,
2229
- recoveryKind
2230
- });
2231
- await this.schedule(0, "_chatRecoveryRetry", {
2232
- targetUserId: recoverySnapshot.latestUserMessageId,
2233
- originalRequestId: recoveryRootRequestId,
2234
- incidentId: incident.incidentId,
2235
- lastBody: recoverySnapshot.lastBody ?? null,
2236
- lastClientTools: recoverySnapshot.lastClientTools ?? null
2237
- }, { idempotent: true });
2238
- } else if (lostPartialUserId !== void 0 && options.continue !== false) {
2239
- await this._updateChatRecoveryIncident(incident.incidentId, "scheduled");
2240
- this._emit("chat:recovery:scheduled", {
2241
- incidentId: incident.incidentId,
2242
- requestId,
2243
- attempt: incident.attempt,
2244
- maxAttempts: incident.maxAttempts,
2245
- recoveryKind: "retry"
2246
- });
2247
- await this.schedule(0, "_chatRecoveryRetry", {
2248
- targetUserId: lostPartialUserId,
2249
- originalRequestId: recoveryRootRequestId,
2250
- incidentId: incident.incidentId,
2251
- lastBody: recoverySnapshot?.lastBody ?? null,
2252
- lastClientTools: recoverySnapshot?.lastClientTools ?? null
2253
- }, { idempotent: true });
2254
- } else if (options.continue !== false) {
2255
- await this._updateChatRecoveryIncident(incident.incidentId, "scheduled");
2256
- this._emit("chat:recovery:scheduled", {
2257
- incidentId: incident.incidentId,
2258
- requestId,
2259
- attempt: incident.attempt,
2260
- maxAttempts: incident.maxAttempts,
2261
- recoveryKind
2262
- });
2263
- await this.schedule(0, "_chatRecoveryContinue", {
2264
- ...targetId ? { targetAssistantId: targetId } : {},
2265
- originalRequestId: recoveryRootRequestId,
2266
- incidentId: incident.incidentId,
2267
- ...recoverySnapshot ? {
2268
- lastBody: recoverySnapshot.lastBody ?? null,
2269
- lastClientTools: recoverySnapshot.lastClientTools ?? null
2270
- } : {}
2271
- }, { idempotent: true });
2272
- } else await this._updateChatRecoveryIncident(incident.incidentId, "skipped", "continue_disabled");
2273
- return true;
2274
- } catch (error) {
2275
- await this._updateChatRecoveryIncident(incident.incidentId, "failed", error instanceof Error ? error.message : String(error));
2276
- throw error;
2277
- }
2479
+ });
2480
+ else if (options.continue !== false) await this._chatRecoveryEngine().scheduleRecovery({
2481
+ incident,
2482
+ recoveryKind: input.recoveryKind,
2483
+ callback: "_chatRecoveryContinue",
2484
+ data: {
2485
+ ...targetId ? { targetAssistantId: targetId } : {},
2486
+ originalRequestId: recoveryRootRequestId,
2487
+ incidentId: incident.incidentId,
2488
+ ...snapshot ? {
2489
+ lastBody: snapshot.lastBody ?? null,
2490
+ lastClientTools: snapshot.lastClientTools ?? null
2491
+ } : {}
2492
+ }
2493
+ });
2494
+ else await this._updateChatRecoveryIncident(incident.incidentId, "skipped", "continue_disabled");
2278
2495
  }
2279
2496
  /**
2280
2497
  * Called when an interrupted chat stream is detected after restart.
@@ -2298,7 +2515,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
2298
2515
  this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
2299
2516
  try {
2300
2517
  const recoveryConfig = this._resolveChatRecoveryConfig();
2301
- if (!await this.waitUntilStable({ timeout: recoveryConfig.stableTimeoutMs })) {
2518
+ if (!await this.waitUntilStable({
2519
+ timeout: recoveryConfig.stableTimeoutMs,
2520
+ pendingInteraction: () => this.hasPendingClientInteraction()
2521
+ })) {
2302
2522
  if (await this._parkRecoveryForPendingInteraction(data)) return;
2303
2523
  console.warn("[AIChatAgent] _chatRecoveryContinue timed out waiting for stable state");
2304
2524
  if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryContinue", data, recoveryConfig.maxAttempts)) return;
@@ -2325,25 +2545,64 @@ var AIChatAgent = class AIChatAgent extends Agent {
2325
2545
  if ("lastClientTools" in data || "lastBody" in data) this._persistRequestContext();
2326
2546
  }
2327
2547
  /**
2548
+ * Route a live stream stall (the {@link chatStreamStallTimeoutMs} watchdog
2549
+ * fired) into the same bounded-recovery machinery a deploy/eviction
2550
+ * interruption uses (#1626). Mirrors `@cloudflare/think`'s stall path: open or
2551
+ * reuse the incident under the turn's recovery identity, deliver terminal UX
2552
+ * if the budget is spent, otherwise schedule a `_chatRecoveryContinue`.
2553
+ *
2554
+ * Unlike Think there is no durable-submission layer to complete here, so the
2555
+ * schedule payload carries no `recoveredRequestId`.
2556
+ *
2557
+ * Returns `"disabled"` when chat recovery is off (the caller then surfaces the
2558
+ * stall as a terminal stream error — the watchdog's "kill the spinner"
2559
+ * guarantee), `"exhausted"` when the budget was spent (terminal UX already
2560
+ * delivered), or `"scheduled"` when a continuation was queued.
2561
+ */
2562
+ async _routeStallToBoundedRecovery(input) {
2563
+ if (!this._resolveChatRecoveryConfig().enabled) return "disabled";
2564
+ const recoveryRootRequestId = this._activeChatRecoveryRootRequestId ?? input.requestId;
2565
+ const latestUserMessageId = [...this.messages].reverse().find((m) => m.role === "user")?.id ?? null;
2566
+ const { incident, config, exhausted } = await this._beginChatRecoveryIncident({
2567
+ requestId: input.requestId,
2568
+ recoveryRootRequestId,
2569
+ latestUserMessageId,
2570
+ recoveryKind: "continue"
2571
+ });
2572
+ if (exhausted) {
2573
+ const partialText = input.partialParts.filter((p) => p.type === "text").map((p) => p.text).join("");
2574
+ await this._exhaustChatRecovery(incident, config, {
2575
+ text: partialText,
2576
+ parts: input.partialParts
2577
+ }, input.streamId, incident.firstSeenAt);
2578
+ return "exhausted";
2579
+ }
2580
+ await this._chatRecoveryEngine().scheduleRecovery({
2581
+ incident,
2582
+ recoveryKind: "continue",
2583
+ callback: "_chatRecoveryContinue",
2584
+ data: {
2585
+ ...input.targetAssistantId ? { targetAssistantId: input.targetAssistantId } : {},
2586
+ originalRequestId: recoveryRootRequestId,
2587
+ incidentId: incident.incidentId,
2588
+ lastBody: this._lastBody ?? null,
2589
+ lastClientTools: this._lastClientTools ?? null
2590
+ }
2591
+ });
2592
+ return "scheduled";
2593
+ }
2594
+ /**
2328
2595
  * Reschedule a recovery callback that timed out waiting for stable state,
2329
2596
  * consuming one attempt. Returns `true` if rescheduled, `false` if the
2330
2597
  * attempt budget is exhausted (caller should then fail terminally).
2331
2598
  */
2332
2599
  async _rescheduleRecoveryAfterStableTimeout(callback, data, maxAttempts) {
2333
- const incidentKey = data?.incidentId ? this._chatRecoveryIncidentKey(data.incidentId) : null;
2334
- const incident = incidentKey ? await this.ctx.storage.get(incidentKey) : null;
2335
- if (!incident || !incidentKey) return false;
2336
- const attempt = incident.attempt ?? 0;
2337
- if (attempt >= (incident.maxAttempts ?? maxAttempts)) return false;
2338
- await this.ctx.storage.put(incidentKey, {
2339
- ...incident,
2340
- attempt: attempt + 1,
2341
- status: "scheduled",
2342
- lastAttemptAt: Date.now(),
2343
- reason: "stable_timeout_retry"
2600
+ return this._chatRecoveryEngine().rescheduleAfterStableTimeout({
2601
+ incidentId: data?.incidentId,
2602
+ callback,
2603
+ data,
2604
+ fallbackMaxAttempts: maxAttempts
2344
2605
  });
2345
- await this.schedule(CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS, callback, data ?? {}, { idempotent: false });
2346
- return true;
2347
2606
  }
2348
2607
  /**
2349
2608
  * Park a recovery continuation that timed out waiting for stable state
@@ -2377,19 +2636,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
2377
2636
  return true;
2378
2637
  }
2379
2638
  /**
2380
- * Resolve the stream id for a recovery turn so the give-up terminalization
2381
- * can surface whatever partial the turn produced. Prefers the durable stream
2382
- * row keyed by the recovery-root request id; falls back to the live active
2383
- * stream. Returns `""` when neither is available.
2384
- */
2385
- _resolveRecoveryStreamId(requestId) {
2386
- if (requestId) {
2387
- const fromMetadata = this._resumableStream.getAllStreamMetadata().find((metadata) => metadata.request_id === requestId)?.id;
2388
- if (fromMetadata) return fromMetadata;
2389
- }
2390
- return this._resumableStream.hasActiveStream() ? this._resumableStream.activeStreamId ?? "" : "";
2391
- }
2392
- /**
2393
2639
  * Terminalize a recovery turn that has run out of stable-state-timeout retry
2394
2640
  * budget — or whose incident record has vanished — by routing through the
2395
2641
  * SAME `_exhaustChatRecovery` path as deploy-recovery exhaustion. It fires
@@ -2419,44 +2665,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
2419
2665
  * the first, so this needs a second independent sweep) — vanishingly
2420
2666
  * unlikely.
2421
2667
  */
2422
- async _exhaustRecoveryAfterStableTimeout(callback, data) {
2423
- const config = this._resolveChatRecoveryConfig();
2424
- const incidentKey = data?.incidentId ? this._chatRecoveryIncidentKey(data.incidentId) : null;
2425
- let stored = null;
2426
- if (incidentKey) try {
2427
- stored = await this.ctx.storage.get(incidentKey) ?? null;
2428
- } catch (readError) {
2429
- console.error("[AIChatAgent] failed to read recovery incident during give-up; synthesizing", readError);
2430
- }
2431
- if (stored?.status === "exhausted") return;
2432
- const rootRequestId = data?.originalRequestId ?? this._activeChatRecoveryRootRequestId ?? stored?.recoveryRootRequestId ?? stored?.requestId ?? "";
2433
- const incident = stored ? {
2434
- ...stored,
2435
- status: "exhausted",
2436
- reason: "stable_timeout"
2437
- } : {
2438
- incidentId: data?.incidentId ?? crypto.randomUUID(),
2439
- requestId: rootRequestId,
2440
- recoveryRootRequestId: rootRequestId,
2441
- recoveryKind: callback === "_chatRecoveryRetry" ? "retry" : "continue",
2442
- attempt: config.maxAttempts,
2443
- maxAttempts: config.maxAttempts,
2444
- status: "exhausted",
2445
- firstSeenAt: Date.now(),
2446
- lastAttemptAt: Date.now(),
2668
+ _exhaustRecoveryAfterStableTimeout(callback, data) {
2669
+ return this._chatRecoveryEngine().exhaustRecoveryGiveUp({
2670
+ callback,
2671
+ data,
2447
2672
  reason: "stable_timeout"
2448
- };
2449
- const streamId = this._resolveRecoveryStreamId(incident.recoveryRootRequestId ?? incident.requestId);
2450
- const partial = streamId ? this._getPartialStreamText(streamId) : {
2451
- text: "",
2452
- parts: []
2453
- };
2454
- await this._exhaustChatRecovery(incident, config, partial, streamId, incident.firstSeenAt);
2455
- if (incidentKey) try {
2456
- await this.ctx.storage.put(incidentKey, incident);
2457
- } catch (writeError) {
2458
- console.error("[AIChatAgent] failed to persist sealed recovery incident during give-up", writeError);
2459
- }
2673
+ });
2460
2674
  }
2461
2675
  _shouldRetryRecoveredPreStreamTurn(snapshot, streamId, partial) {
2462
2676
  if (!snapshot || snapshot.continuation || !snapshot.latestUserMessageId || streamId || partial.text || partial.parts.length > 0) return false;
@@ -2468,7 +2682,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
2468
2682
  this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
2469
2683
  try {
2470
2684
  const recoveryConfig = this._resolveChatRecoveryConfig();
2471
- if (!await this.waitUntilStable({ timeout: recoveryConfig.stableTimeoutMs })) {
2685
+ if (!await this.waitUntilStable({
2686
+ timeout: recoveryConfig.stableTimeoutMs,
2687
+ pendingInteraction: () => this.hasPendingClientInteraction()
2688
+ })) {
2472
2689
  if (await this._parkRecoveryForPendingInteraction(data)) return;
2473
2690
  console.warn("[AIChatAgent] _chatRecoveryRetry timed out waiting for stable state");
2474
2691
  if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryRetry", data, recoveryConfig.maxAttempts)) return;
@@ -2496,15 +2713,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2496
2713
  * Extract partial text and parts from stored stream chunks.
2497
2714
  */
2498
2715
  _getPartialStreamText(streamId) {
2499
- const chunks = this._resumableStream.getStreamChunks(streamId);
2500
- const parts = [];
2501
- for (const chunk of chunks) try {
2502
- applyChunkToParts(parts, JSON.parse(chunk.body));
2503
- } catch {}
2504
- return {
2505
- text: parts.filter((p) => p.type === "text" && "text" in p).map((p) => p.text).join(""),
2506
- parts
2507
- };
2716
+ return aiSdkRecoveryCodec.toRecoveryPartial(this._resumableStream.getStreamChunks(streamId).map((chunk) => chunk.body));
2508
2717
  }
2509
2718
  async persistMessages(messages, excludeBroadcastIds = [], options) {
2510
2719
  const mergedMessages = reconcileMessages(messages, this.messages, (msg) => this._sanitizeMessageForPersistence(msg));
@@ -2535,7 +2744,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2535
2744
  this.messages = autoTransformMessages(persisted);
2536
2745
  this._broadcastChatMessage({
2537
2746
  messages: mergedMessages,
2538
- type: "cf_agent_chat_messages"
2747
+ type: MessageType.CF_AGENT_CHAT_MESSAGES
2539
2748
  }, excludeBroadcastIds);
2540
2749
  }
2541
2750
  /**
@@ -2706,77 +2915,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2706
2915
  * @returns The message, compacted if necessary
2707
2916
  */
2708
2917
  _enforceRowSizeLimit(message) {
2709
- let json = JSON.stringify(message);
2710
- let size = byteLength(json);
2711
- if (size <= ROW_MAX_BYTES) return message;
2712
- if (message.role !== "assistant") {
2713
- console.warn(`[AIChatAgent] Non-assistant message ${message.id} is ${size} bytes, exceeds row limit. Truncating text parts.`);
2714
- return this._truncateTextParts(message);
2715
- }
2716
- console.warn(`[AIChatAgent] Message ${message.id} is ${size} bytes, compacting tool outputs to fit SQLite row limit`);
2717
- const compactedToolCallIds = [];
2718
- const compactedParts = message.parts.map((part) => {
2719
- if ("output" in part && "toolCallId" in part && "state" in part && part.state === "output-available") {
2720
- const outputJson = JSON.stringify(part.output);
2721
- if (outputJson.length > 1e3) {
2722
- compactedToolCallIds.push(part.toolCallId);
2723
- return {
2724
- ...part,
2725
- output: `This tool output was too large to persist in storage (${outputJson.length} bytes). If the user asks about this data, suggest re-running the tool. Preview: ${outputJson.slice(0, 500)}...`
2726
- };
2727
- }
2728
- }
2729
- return part;
2730
- });
2731
- let result = {
2732
- ...message,
2733
- parts: compactedParts
2734
- };
2735
- if (compactedToolCallIds.length > 0) result.metadata = {
2736
- ...result.metadata ?? {},
2737
- compactedToolOutputs: compactedToolCallIds
2738
- };
2739
- json = JSON.stringify(result);
2740
- size = byteLength(json);
2741
- if (size <= ROW_MAX_BYTES) return result;
2742
- console.warn(`[AIChatAgent] Message ${message.id} still ${size} bytes after tool compaction, truncating text parts`);
2743
- return this._truncateTextParts(result);
2744
- }
2745
- /**
2746
- * Truncates text parts in a message to fit within the row size limit.
2747
- * Truncates from the first text part forward, keeping the last text part
2748
- * as intact as possible (it is usually the most relevant).
2749
- */
2750
- _truncateTextParts(message) {
2751
- const compactedTextPartIndices = [];
2752
- const parts = [...message.parts];
2753
- for (let i = 0; i < parts.length; i++) {
2754
- const part = parts[i];
2755
- if (part.type === "text" && "text" in part) {
2756
- const text = part.text;
2757
- if (text.length > 1e3) {
2758
- compactedTextPartIndices.push(i);
2759
- parts[i] = {
2760
- ...part,
2761
- text: `[Text truncated for storage (${text.length} chars). First 500 chars: ${text.slice(0, 500)}...]`
2762
- };
2763
- const candidate = {
2764
- ...message,
2765
- parts
2766
- };
2767
- if (byteLength(JSON.stringify(candidate)) <= ROW_MAX_BYTES) break;
2768
- }
2769
- }
2770
- }
2771
- const result = {
2772
- ...message,
2773
- parts
2774
- };
2775
- if (compactedTextPartIndices.length > 0) result.metadata = {
2776
- ...result.metadata ?? {},
2777
- compactedTextParts: compactedTextPartIndices
2778
- };
2779
- return result;
2918
+ return enforceRowSizeLimit(message, { warn: (m) => console.warn(`[AIChatAgent] ${m}`) });
2780
2919
  }
2781
2920
  /**
2782
2921
  * Shared helper for finding a tool part by toolCallId and applying an update.
@@ -2862,13 +3001,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
2862
3001
  }
2863
3002
  if (!hasRealChange) return true;
2864
3003
  if (isStreamingMessage) this._broadcastChatMessage({
2865
- type: "cf_agent_message_updated",
3004
+ type: MessageType.CF_AGENT_MESSAGE_UPDATED,
2866
3005
  message
2867
3006
  });
2868
3007
  else {
2869
3008
  const broadcastMessage = this._findMessageByToolCallId(toolCallId);
2870
3009
  if (broadcastMessage) this._broadcastChatMessage({
2871
- type: "cf_agent_message_updated",
3010
+ type: MessageType.CF_AGENT_MESSAGE_UPDATED,
2872
3011
  message: broadcastMessage
2873
3012
  });
2874
3013
  }
@@ -2966,11 +3105,48 @@ var AIChatAgent = class AIChatAgent extends Agent {
2966
3105
  if (abortSignal && !abortSignal.aborted) abortSignal.addEventListener("abort", () => {
2967
3106
  reader.cancel().catch(() => {});
2968
3107
  }, { once: true });
3108
+ const stallTimeoutMs = this.chatStreamStallTimeoutMs;
3109
+ let pull;
3110
+ if (stallTimeoutMs > 0) {
3111
+ const guarded = iterateWithStallWatchdog({ [Symbol.asyncIterator]() {
3112
+ return {
3113
+ async next() {
3114
+ const { done, value } = await reader.read();
3115
+ return done || value === void 0 ? {
3116
+ done: true,
3117
+ value: void 0
3118
+ } : {
3119
+ done: false,
3120
+ value
3121
+ };
3122
+ },
3123
+ async return() {
3124
+ await reader.cancel().catch(() => {});
3125
+ return {
3126
+ done: true,
3127
+ value: void 0
3128
+ };
3129
+ }
3130
+ };
3131
+ } }, stallTimeoutMs, () => {
3132
+ reader.cancel().catch(() => {});
3133
+ })[Symbol.asyncIterator]();
3134
+ pull = async () => {
3135
+ const next = await guarded.next();
3136
+ return next.done ? {
3137
+ done: true,
3138
+ value: void 0
3139
+ } : {
3140
+ done: false,
3141
+ value: next.value
3142
+ };
3143
+ };
3144
+ } else pull = () => reader.read();
2969
3145
  while (true) {
2970
3146
  if (abortSignal?.aborted) break;
2971
3147
  let readResult;
2972
3148
  try {
2973
- readResult = await reader.read();
3149
+ readResult = await pull();
2974
3150
  } catch (readError) {
2975
3151
  if (abortSignal?.aborted) break;
2976
3152
  throw readError;
@@ -2984,7 +3160,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2984
3160
  body: "",
2985
3161
  done: true,
2986
3162
  id,
2987
- type: "cf_agent_use_chat_response",
3163
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
2988
3164
  ...continuation && { continuation: true }
2989
3165
  });
2990
3166
  return { status: "completed" };
@@ -3093,7 +3269,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3093
3269
  body: error,
3094
3270
  done: false,
3095
3271
  id,
3096
- type: "cf_agent_use_chat_response",
3272
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
3097
3273
  ...continuation && { continuation: true }
3098
3274
  });
3099
3275
  this._markStreamError(streamId);
@@ -3104,7 +3280,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3104
3280
  body: "",
3105
3281
  done: true,
3106
3282
  id,
3107
- type: "cf_agent_use_chat_response",
3283
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
3108
3284
  ...continuation && { continuation: true }
3109
3285
  });
3110
3286
  return {
@@ -3114,9 +3290,17 @@ var AIChatAgent = class AIChatAgent extends Agent {
3114
3290
  }
3115
3291
  }
3116
3292
  let eventToSend = data;
3117
- if (continuation && data.type === "start" && "messageId" in data) {
3118
- const { messageId: _, ...rest } = data;
3119
- eventToSend = rest;
3293
+ if (data.type === "start") {
3294
+ if (continuation && "messageId" in data) {
3295
+ const { messageId: _, ...rest } = data;
3296
+ eventToSend = rest;
3297
+ } else if (!continuation) {
3298
+ const startData = data;
3299
+ if (startData.messageId == null) eventToSend = {
3300
+ ...startData,
3301
+ messageId: message.id
3302
+ };
3303
+ }
3120
3304
  }
3121
3305
  if (data.type === "finish" && "finishReason" in data) {
3122
3306
  const { finishReason, ...rest } = data;
@@ -3132,7 +3316,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3132
3316
  body: chunkBody,
3133
3317
  done: false,
3134
3318
  id,
3135
- type: "cf_agent_use_chat_response",
3319
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
3136
3320
  ...continuation && { continuation: true }
3137
3321
  });
3138
3322
  } catch (_error) {}
@@ -3144,7 +3328,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3144
3328
  body: "",
3145
3329
  done: true,
3146
3330
  id,
3147
- type: "cf_agent_use_chat_response",
3331
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
3148
3332
  ...continuation && { continuation: true }
3149
3333
  });
3150
3334
  return { status: "aborted" };
@@ -3198,7 +3382,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3198
3382
  body: "",
3199
3383
  done: true,
3200
3384
  id,
3201
- type: "cf_agent_use_chat_response",
3385
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
3202
3386
  ...continuation && { continuation: true }
3203
3387
  });
3204
3388
  return { status: "completed" };
@@ -3225,7 +3409,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3225
3409
  body: "",
3226
3410
  done: true,
3227
3411
  id,
3228
- type: "cf_agent_use_chat_response",
3412
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
3229
3413
  ...continuation && { continuation: true }
3230
3414
  });
3231
3415
  return { status: "aborted" };
@@ -3245,14 +3429,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
3245
3429
  * @returns true if the approval was applied, false if the message was not found
3246
3430
  */
3247
3431
  async _applyToolApproval(toolCallId, approved) {
3248
- return this._findAndUpdateToolPart(toolCallId, "_applyToolApproval", ["input-available", "approval-requested"], (part) => ({
3249
- ...part,
3250
- state: approved ? "approval-responded" : "output-denied",
3251
- approval: {
3252
- ...part.approval,
3253
- approved
3254
- }
3255
- }));
3432
+ const update = toolApprovalUpdate(toolCallId, approved);
3433
+ return this._findAndUpdateToolPart(toolCallId, "_applyToolApproval", update.matchStates, update.apply);
3256
3434
  }
3257
3435
  async _reply(id, response, excludeBroadcastIds = [], options = {}) {
3258
3436
  const { continuation = false, chatMessageId } = options;
@@ -3264,7 +3442,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3264
3442
  body: "",
3265
3443
  done: true,
3266
3444
  id,
3267
- type: "cf_agent_use_chat_response",
3445
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
3268
3446
  ...continuation && { continuation: true }
3269
3447
  });
3270
3448
  this._activateDeferredAutoContinuation();
@@ -3281,64 +3459,99 @@ var AIChatAgent = class AIChatAgent extends Agent {
3281
3459
  const streamCompleted = { value: false };
3282
3460
  let streamResult = { status: "completed" };
3283
3461
  let earlyPersistedId = null;
3462
+ let stallRouted = false;
3463
+ this._streamingTurnActive = true;
3284
3464
  try {
3285
- if (isSSE) streamResult = await this._streamSSEReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
3286
- else streamResult = await this._sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
3287
- } catch (error) {
3288
- const errorMessage = error instanceof Error ? error.message : String(error);
3289
- streamResult = {
3290
- status: "error",
3291
- error: errorMessage
3292
- };
3293
- if (!streamCompleted.value) {
3294
- this._markStreamError(streamId);
3295
- this._broadcastChatMessage({
3296
- body: errorMessage,
3297
- done: true,
3298
- error: true,
3299
- id,
3300
- type: "cf_agent_use_chat_response",
3301
- ...continuation && { continuation: true }
3302
- });
3303
- this._emit("message:error", { error: errorMessage });
3304
- streamCompleted.value = true;
3305
- }
3306
- } finally {
3307
- reader.releaseLock();
3308
- this._streamingMessage = null;
3309
- earlyPersistedId = this._approvalPersistedMessageId;
3310
- this._approvalPersistedMessageId = null;
3311
- if (chatMessageId) {
3312
- this._abortRegistry.remove(chatMessageId);
3313
- if (streamCompleted.value && streamResult.status !== "error") this._emit("message:response");
3465
+ try {
3466
+ if (isSSE) streamResult = await this._streamSSEReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
3467
+ else streamResult = await this._sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
3468
+ } catch (error) {
3469
+ if (error instanceof ChatStreamStalledError && !streamCompleted.value) {
3470
+ const targetAssistantId = message.parts.length > 0 ? message.id : void 0;
3471
+ const outcome = await this._routeStallToBoundedRecovery({
3472
+ requestId: id,
3473
+ streamId,
3474
+ partialParts: message.parts,
3475
+ targetAssistantId
3476
+ });
3477
+ if (outcome === "scheduled") {
3478
+ this._completeStream(streamId);
3479
+ this._broadcastChatMessage({
3480
+ body: "",
3481
+ done: true,
3482
+ id,
3483
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
3484
+ ...continuation && { continuation: true }
3485
+ });
3486
+ streamResult = { status: "aborted" };
3487
+ streamCompleted.value = true;
3488
+ stallRouted = true;
3489
+ } else if (outcome === "exhausted") {
3490
+ this._markStreamError(streamId);
3491
+ streamResult = { status: "aborted" };
3492
+ streamCompleted.value = true;
3493
+ stallRouted = true;
3494
+ }
3495
+ }
3496
+ if (!stallRouted) {
3497
+ const errorMessage = error instanceof Error ? error.message : String(error);
3498
+ streamResult = {
3499
+ status: "error",
3500
+ error: errorMessage
3501
+ };
3502
+ if (!streamCompleted.value) {
3503
+ this._markStreamError(streamId);
3504
+ this._broadcastChatMessage({
3505
+ body: errorMessage,
3506
+ done: true,
3507
+ error: true,
3508
+ id,
3509
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
3510
+ ...continuation && { continuation: true }
3511
+ });
3512
+ this._emit("message:error", { error: errorMessage });
3513
+ streamCompleted.value = true;
3514
+ }
3515
+ }
3516
+ } finally {
3517
+ reader.releaseLock();
3518
+ this._streamingMessage = null;
3519
+ earlyPersistedId = this._approvalPersistedMessageId;
3520
+ this._approvalPersistedMessageId = null;
3521
+ if (chatMessageId) {
3522
+ this._abortRegistry.remove(chatMessageId);
3523
+ if (streamCompleted.value && streamResult.status !== "error" && !stallRouted) this._emit("message:response");
3524
+ }
3314
3525
  }
3315
- }
3316
- if (message.parts.length > 0) if (earlyPersistedId) {
3317
- const persistedMessage = {
3318
- ...message,
3319
- id: earlyPersistedId
3320
- };
3321
- const existingIdx = this.messages.findIndex((msg) => msg.id === earlyPersistedId);
3322
- const updatedMessages = [...this.messages];
3323
- if (existingIdx >= 0) updatedMessages[existingIdx] = persistedMessage;
3324
- else updatedMessages.push(persistedMessage);
3325
- await this.persistMessages(updatedMessages, excludeBroadcastIds);
3326
- } else if (continuation) {
3327
- const existingIdx = this.messages.findIndex((msg) => msg.id === message.id);
3328
- if (existingIdx >= 0) {
3526
+ if (message.parts.length > 0) if (earlyPersistedId) {
3527
+ const persistedMessage = {
3528
+ ...message,
3529
+ id: earlyPersistedId
3530
+ };
3531
+ const existingIdx = this.messages.findIndex((msg) => msg.id === earlyPersistedId);
3329
3532
  const updatedMessages = [...this.messages];
3330
- updatedMessages[existingIdx] = message;
3533
+ if (existingIdx >= 0) updatedMessages[existingIdx] = persistedMessage;
3534
+ else updatedMessages.push(persistedMessage);
3331
3535
  await this.persistMessages(updatedMessages, excludeBroadcastIds);
3536
+ } else if (continuation) {
3537
+ const existingIdx = this.messages.findIndex((msg) => msg.id === message.id);
3538
+ if (existingIdx >= 0) {
3539
+ const updatedMessages = [...this.messages];
3540
+ updatedMessages[existingIdx] = message;
3541
+ await this.persistMessages(updatedMessages, excludeBroadcastIds);
3542
+ } else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
3332
3543
  } else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
3333
- } else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
3334
- this._pendingChatResponseResults.push({
3335
- message,
3336
- requestId: id,
3337
- continuation,
3338
- status: streamResult.status,
3339
- ...streamResult.error !== void 0 && { error: streamResult.error }
3340
- });
3341
- return streamResult;
3544
+ this._pendingChatResponseResults.push({
3545
+ message,
3546
+ requestId: id,
3547
+ continuation,
3548
+ status: streamResult.status,
3549
+ ...streamResult.error !== void 0 && { error: streamResult.error }
3550
+ });
3551
+ return streamResult;
3552
+ } finally {
3553
+ this._onStreamingTurnFinalized();
3554
+ }
3342
3555
  }));
3343
3556
  }
3344
3557
  /**