@cloudflare/ai-chat 0.8.3 → 0.8.5

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.d.ts CHANGED
@@ -194,7 +194,15 @@ declare class AIChatAgent<
194
194
  private _agentToolLastErrors;
195
195
  private _agentToolPreTurnAssistantIds;
196
196
  private _agentToolLiveSequences;
197
- private _agentToolActiveRunId;
197
+ /**
198
+ * Request id → run id for in-flight agent-tool turns (null = resolved as
199
+ * not an agent-tool turn, cached so unrelated turns don't re-query SQLite
200
+ * per frame). Drives frame attribution in {@link broadcast}: a frame
201
+ * belongs to a run iff it carries that run's turn request id, so an error
202
+ * in a user-driven turn or a concurrent run can never leak into another
203
+ * run's state (#1575).
204
+ */
205
+ private _agentToolRunsByRequestId;
198
206
  /**
199
207
  * Client tool schemas from the most recent chat request.
200
208
  * Stored so they can be passed to onChatMessage during tool continuations.
@@ -302,6 +310,13 @@ declare class AIChatAgent<
302
310
  msg: string | ArrayBuffer | ArrayBufferView,
303
311
  without?: string[]
304
312
  ): void;
313
+ /**
314
+ * Resolve the agent-tool run whose turn owns a request id, or null when the
315
+ * request is not an agent-tool turn. Falls back to the persisted run row
316
+ * (written when the turn starts, see `_registerAgentToolTurn`) so
317
+ * attribution survives a DO restart mid-run; either outcome is cached.
318
+ */
319
+ private _agentToolRunForRequest;
305
320
  constructor(ctx: AgentContext, env: Env);
306
321
  private _ensureAgentToolTables;
307
322
  private _flushAwaitingStreamStartConnections;
@@ -313,6 +328,16 @@ declare class AIChatAgent<
313
328
  /**
314
329
  * Notify a connection about an active stream that can be resumed.
315
330
  * The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
331
+ *
332
+ * A connection can legitimately be notified more than once for the same
333
+ * request — proactively from onConnect AND in response to its
334
+ * CF_AGENT_STREAM_RESUME_REQUEST (#1733). This is intentional and must NOT
335
+ * be deduped here: an explicit resume request always deserves a response
336
+ * (the client's reconnectToStream would otherwise hang until its safety
337
+ * timeout, with no replay), and the proactive notify is required for
338
+ * clients that never send a resume request. The notify itself is a single
339
+ * tiny frame; clients are responsible for deduping the ACK so the full
340
+ * chunk buffer is not replayed twice.
316
341
  * @param connection - The WebSocket connection to notify
317
342
  */
318
343
  private _notifyStreamResuming;
@@ -321,9 +346,38 @@ declare class AIChatAgent<
321
346
  /** @internal Delegate to _resumableStream */
322
347
  protected get _activeRequestId(): string | null;
323
348
  /** @internal Delegate to _resumableStream */
324
- protected _startStream(requestId: string): string;
349
+ protected _startStream(
350
+ requestId: string,
351
+ options?: {
352
+ messageId?: string;
353
+ continuation?: boolean;
354
+ }
355
+ ): string;
325
356
  /** @internal Delegate to _resumableStream */
326
357
  protected _completeStream(streamId: string): void;
358
+ /**
359
+ * Ensure a single cleanup alarm is pending for this DO's resumable-stream
360
+ * buffers. Armed whenever a stream finishes (completes or errors) so that
361
+ * idle/one-off chat DOs still reclaim their buffers — the lazy sweep in
362
+ * {@link ResumableStream} only fires when a *subsequent* stream completes,
363
+ * which never happens for a chat that receives a single turn (#1706).
364
+ *
365
+ * `idempotent` dedupes on (callback, payload, owner) so repeated finishes
366
+ * collapse onto one pending alarm rather than stacking.
367
+ * @internal
368
+ */
369
+ protected _ensureStreamCleanupScheduled({
370
+ idempotent
371
+ }?: {
372
+ idempotent?: boolean;
373
+ }): Promise<void>;
374
+ /**
375
+ * Alarm callback: sweep aged stream buffers, then re-arm only while rows
376
+ * remain so a fully-swept DO stops waking itself. Public so it is reachable
377
+ * as a schedule callback.
378
+ * @internal
379
+ */
380
+ _cleanupStreamBuffers(): Promise<void>;
327
381
  /** @internal Delegate to _resumableStream. Also advances the recovery
328
382
  * progress counter at production time (see `_maybeBumpRecoveryProgress`). */
329
383
  protected _storeStreamChunk(streamId: string, body: string): Promise<void>;
@@ -618,6 +672,15 @@ declare class AIChatAgent<
618
672
  output: unknown,
619
673
  messagesAfterStart: readonly UIMessage[]
620
674
  ): string;
675
+ /**
676
+ * Bind the child turn that is about to stream to its agent-tool run, at
677
+ * the moment the turn's request id is first knowable (inside the turn,
678
+ * before any frame is broadcast). The in-memory mapping drives frame
679
+ * attribution in {@link broadcast}; the run row's `request_id` is
680
+ * persisted here rather than at terminal so attribution also survives a
681
+ * DO restart mid-run (#1575).
682
+ */
683
+ private _registerAgentToolTurn;
621
684
  startAgentToolRun(
622
685
  input: unknown,
623
686
  options: {
@@ -796,12 +859,39 @@ declare class AIChatAgent<
796
859
  private _beginChatRecoveryIncident;
797
860
  private _updateChatRecoveryIncident;
798
861
  private _exhaustChatRecovery;
862
+ /**
863
+ * Persist a durable record of the last terminal turn so a client that
864
+ * (re)connects after the turn ended still learns its outcome (#1645). Kept
865
+ * until a later turn supersedes it (`_clearChatTerminal`); a single record is
866
+ * sufficient because only the most recent terminal is relevant.
867
+ */
868
+ private _recordChatTerminal;
869
+ /** Clear the durable terminal record once a later turn supersedes it (#1645). */
870
+ private _clearChatTerminal;
871
+ private _pendingChatTerminal;
872
+ /**
873
+ * Replay a pending terminal outcome (#1645) over the resume handshake so a
874
+ * reconnecting client surfaces it exactly like a live exhaustion. The bare
875
+ * terminal frame is dropped by the client unless it arrives on a resumed
876
+ * stream — the only path that reaches the transport's stream reader and
877
+ * becomes `useChat.error` — so we drive `STREAM_RESUMING` here and deliver
878
+ * the error frame once the client ACKs (see `_replayTerminalOnAck`).
879
+ * Returns true if a terminal was pending (and `STREAM_RESUMING` was sent).
880
+ */
881
+ private _replayTerminalOnResume;
882
+ /**
883
+ * Deliver the pending terminal error frame on the resumed stream the client
884
+ * ACKed (#1645). The record is retained (not cleared) so concurrent
885
+ * reconnects (e.g. multiple tabs) each learn the outcome; it is cleared when
886
+ * a later turn supersedes it.
887
+ */
888
+ private _replayTerminalOnAck;
799
889
  /**
800
890
  * Set or clear the live "recovering…" status (#1620). Persists a durable
801
891
  * record (so set/clear stay consistent across the isolates a recovery spans)
802
892
  * and broadcasts a `CF_AGENT_CHAT_RECOVERING` frame on a genuine transition.
803
- * NOTE: AIChatAgent does not yet replay this on connect (no idle-connect
804
- * hydration; tracked in #1645) — this is the live signal only.
893
+ * NOTE: the live "recovering…" signal is still not replayed on connect — only
894
+ * the terminal outcome is (#1645, via the resume handshake).
805
895
  */
806
896
  private _setChatRecovering;
807
897
  protected _handleInternalFiberRecovery(
@@ -882,9 +972,10 @@ declare class AIChatAgent<
882
972
  * Exactly-once terminalization here rests SOLELY on the
883
973
  * `stored?.status === "exhausted"` re-entry guard below — unlike
884
974
  * `@cloudflare/think`, `@cloudflare/ai-chat` has no durable-submission layer
885
- * to short-circuit a duplicate alarm earlier. The sealed incident is
886
- * re-persisted even when the record was found missing, so a swept record is
887
- * re-armed for the guard on the next alarm.
975
+ * to short-circuit a duplicate alarm earlier. The incident read/write are
976
+ * best-effort because they back only that guard, not the terminal UX: a
977
+ * failed read synthesizes the incident and a failed seal write costs at most
978
+ * a re-delivered banner on a duplicate alarm.
888
979
  *
889
980
  * Two residual at-least-once edges, both deliberately accepted as "deliver a
890
981
  * second banner" ≫ "silently drop the turn":
package/dist/index.js CHANGED
@@ -13,12 +13,14 @@ const AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS = 6e4;
13
13
  const CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS = 3;
14
14
  const DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE = "The assistant was interrupted and could not recover. Please try again.";
15
15
  const CHAT_RECOVERING_KEY = "cf:chat:recovering";
16
+ const CHAT_LAST_TERMINAL_KEY = "cf:chat:last-terminal";
16
17
  const CHAT_RECOVERY_INCIDENT_TTL_MS = 3600 * 1e3;
17
18
  const KV_DELETE_MAX_KEYS = 128;
18
19
  const DEFAULT_CHAT_RECOVERY_NO_PROGRESS_TIMEOUT_MS = 300 * 1e3;
19
20
  const CHAT_RECOVERY_ALARM_DEBOUNCE_MS = 30 * 1e3;
20
21
  const CHAT_RECOVERING_FLAG_TTL_MS = 900 * 1e3;
21
22
  const AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS = 5e3;
23
+ const STREAM_CLEANUP_DELAY_SECONDS = 600;
22
24
  function sendIfOpen(connection, message) {
23
25
  try {
24
26
  connection.send(message);
@@ -91,28 +93,44 @@ var AIChatAgent = class AIChatAgent extends Agent {
91
93
  });
92
94
  }
93
95
  broadcast(msg, without) {
94
- if (this._agentToolForwarders.size > 0 && typeof msg === "string") try {
96
+ if ((this._agentToolForwarders.size > 0 || this._agentToolLiveSequences.size > 0) && typeof msg === "string") try {
95
97
  const parsed = JSON.parse(msg);
96
- if (parsed.type === "cf_agent_use_chat_response") {
97
- if (parsed.error === true && typeof parsed.body === "string") {
98
- const runIds = this._agentToolActiveRunId !== null ? [this._agentToolActiveRunId] : [...this._agentToolForwarders.keys()];
99
- for (const runId of runIds) this._agentToolLastErrors.set(runId, parsed.body);
100
- } else if (typeof parsed.body === "string" && parsed.body.length > 0) {
101
- const entries = this._agentToolActiveRunId !== null ? [[this._agentToolActiveRunId, this._agentToolForwarders.get(this._agentToolActiveRunId) ?? /* @__PURE__ */ new Set()]] : [...this._agentToolForwarders.entries()];
102
- for (const [runId, forwarders] of entries) {
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
103
  const sequence = this._agentToolLiveSequences.get(runId) ?? 0;
104
104
  this._agentToolLiveSequences.set(runId, sequence + 1);
105
105
  const chunk = {
106
106
  sequence,
107
107
  body: parsed.body
108
108
  };
109
- for (const forward of forwarders) forward(chunk);
109
+ const forwarders = this._agentToolForwarders.get(runId);
110
+ if (forwarders) for (const forward of forwarders) forward(chunk);
110
111
  }
111
112
  }
112
113
  }
113
114
  } catch {}
114
115
  super.broadcast(msg, without);
115
116
  }
117
+ /**
118
+ * Resolve the agent-tool run whose turn owns a request id, or null when the
119
+ * request is not an agent-tool turn. Falls back to the persisted run row
120
+ * (written when the turn starts, see `_registerAgentToolTurn`) so
121
+ * attribution survives a DO restart mid-run; either outcome is cached.
122
+ */
123
+ _agentToolRunForRequest(requestId) {
124
+ const cached = this._agentToolRunsByRequestId.get(requestId);
125
+ if (cached !== void 0) return cached;
126
+ const runId = this.sql`
127
+ select run_id from cf_ai_chat_agent_tool_runs
128
+ where request_id = ${requestId} and status = 'running'
129
+ limit 1
130
+ `?.[0]?.run_id ?? null;
131
+ this._agentToolRunsByRequestId.set(requestId, runId);
132
+ return runId;
133
+ }
116
134
  constructor(ctx, env) {
117
135
  super(ctx, env);
118
136
  this._streamingMessage = null;
@@ -133,7 +151,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
133
151
  this._agentToolLastErrors = /* @__PURE__ */ new Map();
134
152
  this._agentToolPreTurnAssistantIds = /* @__PURE__ */ new Map();
135
153
  this._agentToolLiveSequences = /* @__PURE__ */ new Map();
136
- this._agentToolActiveRunId = null;
154
+ this._agentToolRunsByRequestId = /* @__PURE__ */ new Map();
137
155
  this._persistedMessageCache = /* @__PURE__ */ new Map();
138
156
  this.maxPersistedMessages = void 0;
139
157
  this.messageConcurrency = "queue";
@@ -203,6 +221,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
203
221
  this._completeSkippedRequest(connection, chatMessageId);
204
222
  return;
205
223
  }
224
+ await this._clearChatTerminal();
206
225
  const releasePendingEnqueue = this._submitConcurrency.beginEnqueue();
207
226
  try {
208
227
  this._broadcastChatMessage({
@@ -290,6 +309,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
290
309
  if (data.type === "cf_agent_chat_clear") {
291
310
  this.resetTurnState();
292
311
  this.sql`delete from cf_ai_chat_agent_messages`;
312
+ await this._clearChatTerminal();
293
313
  this._resumableStream.clearAll();
294
314
  this._pendingResumeConnections.clear();
295
315
  this._lastClientTools = void 0;
@@ -315,7 +335,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
315
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" }));
316
336
  else this._notifyStreamResuming(connection);
317
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);
318
- else sendIfOpen(connection, JSON.stringify({ type: "cf_agent_stream_resume_none" }));
338
+ else if (await this._replayTerminalOnResume(connection)) {} else sendIfOpen(connection, JSON.stringify({ type: "cf_agent_stream_resume_none" }));
319
339
  return;
320
340
  }
321
341
  if (data.type === "cf_agent_stream_resume_ack") {
@@ -323,7 +343,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
323
343
  if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === data.id) {
324
344
  const orphanedStreamId = this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
325
345
  if (orphanedStreamId) await this._persistOrphanedStream(orphanedStreamId);
326
- } else if (this._resumableStream.hasActiveStream()) {} else if (!this._resumableStream.replayCompletedChunksByRequestId(connection, data.id)) sendIfOpen(connection, JSON.stringify({
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({
327
347
  body: "",
328
348
  done: true,
329
349
  id: data.id,
@@ -431,6 +451,16 @@ var AIChatAgent = class AIChatAgent extends Agent {
431
451
  /**
432
452
  * Notify a connection about an active stream that can be resumed.
433
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.
434
464
  * @param connection - The WebSocket connection to notify
435
465
  */
436
466
  _notifyStreamResuming(connection) {
@@ -449,13 +479,14 @@ var AIChatAgent = class AIChatAgent extends Agent {
449
479
  return this._resumableStream?.activeRequestId ?? null;
450
480
  }
451
481
  /** @internal Delegate to _resumableStream */
452
- _startStream(requestId) {
453
- const streamId = this._resumableStream.start(requestId);
482
+ _startStream(requestId, options = {}) {
483
+ const streamId = this._resumableStream.start(requestId, options);
454
484
  if (this._continuation.pending?.requestId === requestId) {
455
485
  this._continuation.activatePending();
456
486
  this._flushAwaitingStreamStartConnections();
457
487
  this._activateDeferredAutoContinuation();
458
488
  }
489
+ this._ensureStreamCleanupScheduled();
459
490
  return streamId;
460
491
  }
461
492
  /** @internal Delegate to _resumableStream */
@@ -467,6 +498,31 @@ var AIChatAgent = class AIChatAgent extends Agent {
467
498
  this._continuation.activeRequestId = null;
468
499
  this._continuation.activeConnectionId = null;
469
500
  }
501
+ this._ensureStreamCleanupScheduled();
502
+ }
503
+ /**
504
+ * Ensure a single cleanup alarm is pending for this DO's resumable-stream
505
+ * buffers. Armed whenever a stream finishes (completes or errors) so that
506
+ * idle/one-off chat DOs still reclaim their buffers — the lazy sweep in
507
+ * {@link ResumableStream} only fires when a *subsequent* stream completes,
508
+ * which never happens for a chat that receives a single turn (#1706).
509
+ *
510
+ * `idempotent` dedupes on (callback, payload, owner) so repeated finishes
511
+ * collapse onto one pending alarm rather than stacking.
512
+ * @internal
513
+ */
514
+ async _ensureStreamCleanupScheduled({ idempotent = true } = {}) {
515
+ await this.schedule(STREAM_CLEANUP_DELAY_SECONDS, "_cleanupStreamBuffers", void 0, { idempotent });
516
+ }
517
+ /**
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.
521
+ * @internal
522
+ */
523
+ async _cleanupStreamBuffers() {
524
+ this._resumableStream.cleanup();
525
+ if (this._resumableStream.hasReclaimableStreams()) await this._ensureStreamCleanupScheduled({ idempotent: false });
470
526
  }
471
527
  /** @internal Delegate to _resumableStream. Also advances the recovery
472
528
  * progress counter at production time (see `_maybeBumpRecoveryProgress`). */
@@ -505,6 +561,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
505
561
  this._continuation.activeRequestId = null;
506
562
  this._continuation.activeConnectionId = null;
507
563
  }
564
+ this._ensureStreamCleanupScheduled();
508
565
  }
509
566
  /**
510
567
  * Reconstruct and persist a partial assistant message from an orphaned
@@ -535,7 +592,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
535
592
  } catch {}
536
593
  if (message.parts.length > 0) {
537
594
  if (message.id === fallbackId) {
538
- for (let i = this.messages.length - 1; i >= 0; i--) if (this.messages[i].role === "assistant") {
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") {
539
598
  message.id = this.messages[i].id;
540
599
  break;
541
600
  }
@@ -543,7 +602,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
543
602
  const existingIdx = this.messages.findIndex((m) => m.id === message.id);
544
603
  if (existingIdx >= 0) {
545
604
  const existing = this.messages[existingIdx];
546
- message.parts = [...existing.parts, ...message.parts];
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];
547
608
  if (existing.metadata) message.metadata = message.metadata ? {
548
609
  ...existing.metadata,
549
610
  ...message.metadata
@@ -926,6 +987,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
926
987
  await this.keepAliveWhile(async () => {
927
988
  while (this._pendingChatResponseResults.length > 0) {
928
989
  const chatResult = this._pendingChatResponseResults.shift();
990
+ if (chatResult.status === "completed" || chatResult.status === "aborted") await this._clearChatTerminal();
991
+ else if (chatResult.status === "error") await this._recordChatTerminal(chatResult.requestId, chatResult.error ?? "The assistant encountered an error.");
929
992
  try {
930
993
  await this.onChatResponse(chatResult);
931
994
  } catch (hookError) {
@@ -1256,6 +1319,27 @@ var AIChatAgent = class AIChatAgent extends Agent {
1256
1319
  return String(output);
1257
1320
  }
1258
1321
  }
1322
+ /**
1323
+ * Bind the child turn that is about to stream to its agent-tool run, at
1324
+ * the moment the turn's request id is first knowable (inside the turn,
1325
+ * before any frame is broadcast). The in-memory mapping drives frame
1326
+ * attribution in {@link broadcast}; the run row's `request_id` is
1327
+ * persisted here rather than at terminal so attribution also survives a
1328
+ * DO restart mid-run (#1575).
1329
+ */
1330
+ _registerAgentToolTurn(runId) {
1331
+ const requestId = this._turnQueue.activeRequestId;
1332
+ if (requestId === null) {
1333
+ console.warn(`[AIChatAgent] agent-tool run ${runId} has no active request id at turn start; frame attribution will be skipped`);
1334
+ return;
1335
+ }
1336
+ this._agentToolRunsByRequestId.set(requestId, runId);
1337
+ this.sql`
1338
+ update cf_ai_chat_agent_tool_runs
1339
+ set request_id = ${requestId}
1340
+ where run_id = ${runId}
1341
+ `;
1342
+ }
1259
1343
  async startAgentToolRun(input, options) {
1260
1344
  const existing = await this.inspectAgentToolRun(options.runId);
1261
1345
  if (existing) return existing;
@@ -1280,7 +1364,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1280
1364
  const previousBody = this._lastBody;
1281
1365
  this._setRequestContext(void 0, { agentToolInput: input });
1282
1366
  const result = await this.saveMessages(async (messages) => {
1283
- this._agentToolActiveRunId = options.runId;
1367
+ this._registerAgentToolTurn(options.runId);
1284
1368
  return [...messages, this.formatAgentToolInput(input, { runId: options.runId })];
1285
1369
  }, { signal: controller.signal }).finally(() => {
1286
1370
  this._setRequestContext(previousClientTools, previousBody);
@@ -1355,7 +1439,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
1355
1439
  options.signal?.removeEventListener("abort", abortFromParent);
1356
1440
  this._agentToolAbortControllers.delete(options.runId);
1357
1441
  this._agentToolLiveSequences.delete(options.runId);
1358
- if (this._agentToolActiveRunId === options.runId) this._agentToolActiveRunId = null;
1442
+ if (this._agentToolAbortControllers.size === 0) this._agentToolRunsByRequestId.clear();
1443
+ else for (const [reqId, runId] of this._agentToolRunsByRequestId) if (runId === options.runId) this._agentToolRunsByRequestId.delete(reqId);
1359
1444
  this._agentToolLastErrors.delete(options.runId);
1360
1445
  this._agentToolPreTurnAssistantIds.delete(options.runId);
1361
1446
  this._closeAgentToolTailers(options.runId);
@@ -1980,6 +2065,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1980
2065
  } catch (error) {
1981
2066
  console.error("[AIChatAgent] chatRecovery onExhausted hook threw", error);
1982
2067
  }
2068
+ await this._recordChatTerminal(incident.requestId, config.terminalMessage);
1983
2069
  this._broadcastChatMessage({
1984
2070
  body: config.terminalMessage,
1985
2071
  done: true,
@@ -1990,11 +2076,67 @@ var AIChatAgent = class AIChatAgent extends Agent {
1990
2076
  await this._setChatRecovering(false);
1991
2077
  }
1992
2078
  /**
2079
+ * Persist a durable record of the last terminal turn so a client that
2080
+ * (re)connects after the turn ended still learns its outcome (#1645). Kept
2081
+ * until a later turn supersedes it (`_clearChatTerminal`); a single record is
2082
+ * sufficient because only the most recent terminal is relevant.
2083
+ */
2084
+ async _recordChatTerminal(requestId, body) {
2085
+ await this.ctx.storage.put(CHAT_LAST_TERMINAL_KEY, {
2086
+ requestId,
2087
+ body
2088
+ });
2089
+ }
2090
+ /** Clear the durable terminal record once a later turn supersedes it (#1645). */
2091
+ async _clearChatTerminal() {
2092
+ await this.ctx.storage.delete(CHAT_LAST_TERMINAL_KEY);
2093
+ }
2094
+ 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;
2114
+ }
2115
+ /**
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.
2120
+ */
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;
2133
+ }
2134
+ /**
1993
2135
  * Set or clear the live "recovering…" status (#1620). Persists a durable
1994
2136
  * record (so set/clear stay consistent across the isolates a recovery spans)
1995
2137
  * and broadcasts a `CF_AGENT_CHAT_RECOVERING` frame on a genuine transition.
1996
- * NOTE: AIChatAgent does not yet replay this on connect (no idle-connect
1997
- * hydration; tracked in #1645) — this is the live signal only.
2138
+ * NOTE: the live "recovering…" signal is still not replayed on connect — only
2139
+ * the terminal outcome is (#1645, via the resume handshake).
1998
2140
  */
1999
2141
  async _setChatRecovering(active, requestId) {
2000
2142
  const existing = await this.ctx.storage.get(CHAT_RECOVERING_KEY);
@@ -2037,7 +2179,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
2037
2179
  };
2038
2180
  const streamStillActive = streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId;
2039
2181
  const shouldRetryPreStream = this._shouldRetryRecoveredPreStreamTurn(recoverySnapshot, streamId ?? "", partial);
2040
- const recoveryKind = shouldRetryPreStream ? "retry" : "continue";
2182
+ 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";
2041
2185
  const recoveryRootRequestId = recoverySnapshot?.recoveryRootRequestId ?? requestId;
2042
2186
  const { incident, config, exhausted } = await this._beginChatRecoveryIncident({
2043
2187
  requestId,
@@ -2068,8 +2212,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
2068
2212
  createdAt: ctx.createdAt
2069
2213
  }) ?? {};
2070
2214
  if (streamStillActive && (options.persist !== false || this._partialHasSettledToolResults(partial.parts))) await this._persistOrphanedStream(streamId);
2071
- if (streamStillActive) this._resumableStream.complete(streamId);
2072
- const targetId = shouldRetryPreStream ? void 0 : this._findLastAssistantMessage()?.id;
2215
+ if (streamStillActive) {
2216
+ this._resumableStream.complete(streamId);
2217
+ this._ensureStreamCleanupScheduled();
2218
+ }
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;
2073
2222
  if (shouldRetryPreStream && options.continue !== false) {
2074
2223
  await this._updateChatRecoveryIncident(incident.incidentId, "scheduled");
2075
2224
  this._emit("chat:recovery:scheduled", {
@@ -2086,6 +2235,22 @@ var AIChatAgent = class AIChatAgent extends Agent {
2086
2235
  lastBody: recoverySnapshot.lastBody ?? null,
2087
2236
  lastClientTools: recoverySnapshot.lastClientTools ?? null
2088
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 });
2089
2254
  } else if (options.continue !== false) {
2090
2255
  await this._updateChatRecoveryIncident(incident.incidentId, "scheduled");
2091
2256
  this._emit("chat:recovery:scheduled", {
@@ -2240,9 +2405,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
2240
2405
  * Exactly-once terminalization here rests SOLELY on the
2241
2406
  * `stored?.status === "exhausted"` re-entry guard below — unlike
2242
2407
  * `@cloudflare/think`, `@cloudflare/ai-chat` has no durable-submission layer
2243
- * to short-circuit a duplicate alarm earlier. The sealed incident is
2244
- * re-persisted even when the record was found missing, so a swept record is
2245
- * re-armed for the guard on the next alarm.
2408
+ * to short-circuit a duplicate alarm earlier. The incident read/write are
2409
+ * best-effort because they back only that guard, not the terminal UX: a
2410
+ * failed read synthesizes the incident and a failed seal write costs at most
2411
+ * a re-delivered banner on a duplicate alarm.
2246
2412
  *
2247
2413
  * Two residual at-least-once edges, both deliberately accepted as "deliver a
2248
2414
  * second banner" ≫ "silently drop the turn":
@@ -2256,7 +2422,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
2256
2422
  async _exhaustRecoveryAfterStableTimeout(callback, data) {
2257
2423
  const config = this._resolveChatRecoveryConfig();
2258
2424
  const incidentKey = data?.incidentId ? this._chatRecoveryIncidentKey(data.incidentId) : null;
2259
- const stored = incidentKey ? await this.ctx.storage.get(incidentKey) : 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
+ }
2260
2431
  if (stored?.status === "exhausted") return;
2261
2432
  const rootRequestId = data?.originalRequestId ?? this._activeChatRecoveryRootRequestId ?? stored?.recoveryRootRequestId ?? stored?.requestId ?? "";
2262
2433
  const incident = stored ? {
@@ -2275,13 +2446,17 @@ var AIChatAgent = class AIChatAgent extends Agent {
2275
2446
  lastAttemptAt: Date.now(),
2276
2447
  reason: "stable_timeout"
2277
2448
  };
2278
- if (incidentKey) await this.ctx.storage.put(incidentKey, incident);
2279
2449
  const streamId = this._resolveRecoveryStreamId(incident.recoveryRootRequestId ?? incident.requestId);
2280
2450
  const partial = streamId ? this._getPartialStreamText(streamId) : {
2281
2451
  text: "",
2282
2452
  parts: []
2283
2453
  };
2284
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
+ }
2285
2460
  }
2286
2461
  _shouldRetryRecoveredPreStreamTurn(snapshot, streamId, partial) {
2287
2462
  if (!snapshot || snapshot.continuation || !snapshot.latestUserMessageId || streamId || partial.text || partial.parts.length > 0) return false;
@@ -3095,9 +3270,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
3095
3270
  this._activateDeferredAutoContinuation();
3096
3271
  return { status: "completed" };
3097
3272
  }
3098
- const streamId = this._startStream(id);
3099
- const reader = response.body.getReader();
3100
3273
  const message = this._createStreamingAssistantMessage(continuation);
3274
+ const streamId = this._startStream(id, {
3275
+ messageId: message.id,
3276
+ continuation
3277
+ });
3278
+ const reader = response.body.getReader();
3101
3279
  this._streamingMessage = message;
3102
3280
  const isSSE = (response.headers.get("content-type") || "").includes("text/event-stream");
3103
3281
  const streamCompleted = { value: false };