@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.d.ts CHANGED
@@ -1,6 +1,10 @@
1
1
  import {
2
2
  Agent,
3
3
  AgentContext,
4
+ AgentToolLifecycleResult,
5
+ AgentToolMilestone,
6
+ AgentToolProgress,
7
+ AgentToolRunInfo,
4
8
  AgentToolRunInspection,
5
9
  AgentToolStoredChunk,
6
10
  FiberRecoveryContext
@@ -20,6 +24,7 @@ import {
20
24
  ClientToolSchema as ClientToolSchema$1,
21
25
  MessageConcurrency,
22
26
  MessageConcurrency as MessageConcurrency$1,
27
+ OrphanPersistStore,
23
28
  ResolvedChatRecoveryConfig,
24
29
  ResumableStream,
25
30
  SaveMessagesOptions,
@@ -172,6 +177,24 @@ declare class AIChatAgent<
172
177
  * for the recovery that matters. See {@link ChatRecoveryConfig}.
173
178
  */
174
179
  chatRecovery: ChatRecoveryConfig$1;
180
+ /**
181
+ * Inactivity watchdog for the live model/transport stream, in milliseconds.
182
+ * If more than this many ms elapse between stream chunks, the turn is aborted
183
+ * and — when {@link chatRecovery} is enabled — routed into bounded recovery
184
+ * (the same continuation machinery as a deploy/eviction interruption, #1626)
185
+ * rather than parking forever on a hung provider. With recovery disabled, a
186
+ * stall instead surfaces as a terminal stream error (kills the spinner).
187
+ *
188
+ * Default `0` disables the watchdog (opt-in), matching `@cloudflare/think`.
189
+ * A value such as `60_000` (60s) is a reasonable starting point; tune it
190
+ * above your slowest legitimate inter-chunk gap (slow reasoning models, long
191
+ * tool calls) to avoid aborting healthy turns. Because the watchdog measures
192
+ * the gap between chunks — not total turn duration — a steadily streaming
193
+ * turn never trips it regardless of overall length.
194
+ *
195
+ * Assign as a class field or in the constructor, like {@link chatRecovery}.
196
+ */
197
+ chatStreamStallTimeoutMs: number;
175
198
  /** First queued overlap message index for merge strategy, keyed by epoch. */
176
199
  private _mergeQueuedUserStartIndexByEpoch;
177
200
  /** Shared admission policy state for overlapping submit-message requests. */
@@ -183,11 +206,29 @@ declare class AIChatAgent<
183
206
  * @internal
184
207
  */
185
208
  private _pendingResumeConnections;
209
+ /** Lazily-built shared resume-handshake driver (Tier-2). */
210
+ private _resumeHandshakeInstance;
186
211
  /**
187
212
  * Continuation lifecycle state: pending, deferred, active, and
188
213
  * connections awaiting a continuation stream to start.
189
214
  */
190
215
  private _continuation;
216
+ /**
217
+ * Accepted-but-not-yet-streamed turns and the connections parked waiting for
218
+ * one (#1784). Lets a client that reconnects/re-mounts during a turn's
219
+ * pre-stream window (queue, MCP wait, model latency) keep waiting instead of
220
+ * giving up — see the {@link ResumeHandshake} `preStream` seam.
221
+ *
222
+ * HIBERNATION INVARIANT: this is in-memory only and is NOT persisted. It is
223
+ * safe precisely because the pre-stream window cannot overlap hibernation: a
224
+ * turn between `begin()` and `_startStream()` is an unresolved `onMessage`
225
+ * handler promise (queue/debounce/MCP/model awaits) that pins the DO in
226
+ * memory, so the DO is only evicted once the turn either recorded a durable
227
+ * stream (resumed via `ResumableStream` on wake) or finished. This breaks if a
228
+ * pre-stream wait is ever moved onto a durable alarm that releases the DO; if
229
+ * that changes, this state must become durable.
230
+ */
231
+ private _preStream;
191
232
  private _agentToolForwarders;
192
233
  private _agentToolClosers;
193
234
  private _agentToolAbortControllers;
@@ -223,10 +264,19 @@ declare class AIChatAgent<
223
264
  */
224
265
  private _persistedMessageCache;
225
266
  /**
226
- * Small debounce window to batch adjacent client-side tool results/approvals
227
- * into a single server continuation turn.
267
+ * Shared auto-continuation barrier (#1649 / #1650): owns the coalesce timer
268
+ * and the double-fire guard. Parameterized by this agent's stream-active
269
+ * signal, apply-drain, and continuation-turn pipeline (`_fireAutoContinuation`).
228
270
  */
229
- private static AUTO_CONTINUATION_COALESCE_MS;
271
+ private _autoContinuation;
272
+ /**
273
+ * Stream-active gate for the auto-continuation barrier (#1650). True while an
274
+ * assistant turn is streaming in `_reply`: the parallel tool batch can still
275
+ * grow with tool calls the model hasn't emitted yet, so no completeness check
276
+ * is meaningful until the stream finalizes. `_onStreamingTurnFinalized`
277
+ * clears it and re-runs the barrier once the batch is fully materialized.
278
+ */
279
+ private _streamingTurnActive;
230
280
  /** Default wait for trailing-edge debounced overlapping submits. */
231
281
  private static MESSAGE_DEBOUNCE_MS;
232
282
  /**
@@ -317,27 +367,54 @@ declare class AIChatAgent<
317
367
  * attribution survives a DO restart mid-run; either outcome is cached.
318
368
  */
319
369
  private _agentToolRunForRequest;
370
+ /**
371
+ * Re-bind this facet's in-flight agent-tool child run to the CURRENT turn's
372
+ * request id. Parity with `@cloudflare/think`'s
373
+ * `_rebindAgentToolChildRunRequestId`.
374
+ *
375
+ * When this facet runs as an agent-tool child and its turn is interrupted, the
376
+ * recovery continuation (`continueLastTurn` / `_retryLastUserTurn`) mints a NEW
377
+ * request id but never flows through `startAgentToolRun`'s
378
+ * `_registerAgentToolTurn`. So `cf_ai_chat_agent_tool_runs.request_id` (and the
379
+ * in-memory attribution map) still point at the pre-eviction turn, and
380
+ * `broadcast` can no longer attribute the recovered turn's frames to the run.
381
+ * A long-running child then forwards nothing to the parent's re-attach tail,
382
+ * its no-progress budget elapses, and a healthy child is abandoned as
383
+ * `interrupted`. Re-binding keeps attribution alive across recovery.
384
+ *
385
+ * Safe to call on EVERY recovery continuation:
386
+ * - Facets that never ran as an agent-tool child have no
387
+ * `cf_ai_chat_agent_tool_runs` table → the guarded SELECT throws → no-op.
388
+ * - A facet whose run already settled has no active row → no-op.
389
+ * - A child DO is addressed by its `runId` (`subAgent(cls, runId)`), so it
390
+ * owns AT MOST ONE child-run row for its whole lifetime and is never reused
391
+ * as a top-level chat agent — the single active row is unambiguously this
392
+ * recovery's run. The `order by started_at desc limit 1` is defensive
393
+ * belt-and-suspenders for that invariant.
394
+ *
395
+ * Uses the same `status in ('starting','running')` active-run predicate as
396
+ * `_agentToolRunForRequest` and the `@cloudflare/think` counterpart.
397
+ */
398
+ private _rebindAgentToolChildRunRequestId;
320
399
  constructor(ctx: AgentContext, env: Env);
321
400
  private _ensureAgentToolTables;
401
+ private _persistAgentToolMilestone;
402
+ private _readAgentToolMilestones;
322
403
  private _flushAwaitingStreamStartConnections;
323
- private _mergeAutoContinuationPrerequisite;
324
- private _storeDeferredAutoContinuation;
325
404
  private _activateDeferredAutoContinuation;
326
405
  private _clearAllAutoContinuationState;
327
406
  private _clearPendingAutoContinuation;
328
407
  /**
329
- * Notify a connection about an active stream that can be resumed.
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.
408
+ * The shared resume-handshake driver (Tier-2). Lazily built; the
409
+ * `ResumableStream` / `ContinuationState` / pending set are stable after the
410
+ * constructor, so a single instance threads them for the agent's lifetime.
411
+ */
412
+ private _resumeHandshake;
413
+ /**
414
+ * Notify a connection about an active stream that can be resumed — delegates
415
+ * to the shared {@link ResumeHandshake}. Kept as a thin method because it is
416
+ * also called proactively from onConnect and the broadcast loop. See the
417
+ * driver for the #1733 double-send contract.
341
418
  * @param connection - The WebSocket connection to notify
342
419
  */
343
420
  private _notifyStreamResuming;
@@ -372,22 +449,29 @@ declare class AIChatAgent<
372
449
  idempotent?: boolean;
373
450
  }): Promise<void>;
374
451
  /**
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.
452
+ * Alarm callback: sweep aged stream buffers, re-arming while rows remain (see
453
+ * the shared {@link cleanupStreamBuffers}). Public so it is reachable as a
454
+ * schedule callback.
378
455
  * @internal
379
456
  */
380
457
  _cleanupStreamBuffers(): Promise<void>;
381
458
  /** @internal Delegate to _resumableStream. Also advances the recovery
382
459
  * progress counter at production time (see `_maybeBumpRecoveryProgress`). */
383
460
  protected _storeStreamChunk(streamId: string, body: string): Promise<void>;
461
+ /** Per-isolate throttle for crediting recovery progress from mid-segment
462
+ * streaming-content deltas (the shared `agents/chat` rule); reset per isolate
463
+ * so the first delta after a restart always credits. */
464
+ private _streamProgressCredit;
384
465
  /** Advance the recovery-progress counter when a chunk represents genuinely
385
- * new produced content — a started text/reasoning segment or a settled tool
386
- * input/output. Bumped at production time (the streaming path), so it
387
- * reflects real forward progress and is immune to client reconnects /
388
- * recovery re-persists (which replay or re-materialize stored chunks rather
389
- * than flow through here). This is what the recovery no-progress window keys
390
- * off (#1637), and stays compaction-proof (#1628). */
466
+ * new produced content. Uses the shared host-agnostic rule
467
+ * ({@link shouldCreditStreamProgress}): a milestone (started segment / settled
468
+ * tool) always credits, and a long single segment's streaming deltas credit
469
+ * through a time throttle so the no-progress window doesn't false-fire while
470
+ * content streams across crashes. Bumped at production time, so it reflects
471
+ * real forward progress and is immune to client reconnects / recovery
472
+ * re-persists (which replay or re-materialize stored chunks rather than flow
473
+ * through here). This is what the recovery no-progress window keys off
474
+ * (#1637), and stays compaction-proof (#1628). */
391
475
  private _maybeBumpRecoveryProgress;
392
476
  /** @internal Delegate to _resumableStream */
393
477
  protected _flushChunkBuffer(): void;
@@ -400,11 +484,119 @@ declare class AIChatAgent<
400
484
  * stream's stored chunks. Called when the DO wakes from hibernation and
401
485
  * discovers an active stream with no live LLM reader.
402
486
  *
403
- * Replays each chunk body through `applyChunkToParts` to rebuild the
404
- * message parts, then persists the result so it survives further refreshes.
487
+ * Built from the three orphan-persist seams the chat-recovery RFC factored
488
+ * out — all three are ai-chat's substrate-specific realizations of a shape
489
+ * `Think` shares:
490
+ * - (a) reconstruct via the shared `StreamAccumulator` (the same primitive
491
+ * `Think` and the client reducer use), replacing a hand-rolled chunk
492
+ * switch; it owns the `start` / `finish` / `message-metadata` handling;
493
+ * - (b) {@link _resolveOrphanTargetId} — the id to persist under (#1691);
494
+ * - (c)+(d) upsert-by-id over the flat array, the `SessionProvider`-subset
495
+ * store-write shape (`getMessage` → `updateMessage` / `appendMessage`)
496
+ * that `Think._upsertMessageInHistory` implements over a Session tree.
497
+ * When a row already owns the id, the shared `reconcileOrphanPartial`
498
+ * merge preserves an in-place tool result rather than letting a replayed
499
+ * chunk re-advance it (ai-chat has an early tool-approval persist; hosts
500
+ * without one append straight through).
405
501
  * @internal
406
502
  */
407
503
  protected _persistOrphanedStream(streamId: string): Promise<void>;
504
+ /**
505
+ * Resolve the id an orphaned partial should persist under — orphan-persist
506
+ * step **(b)**, and the one legitimately per-package piece of the path: a
507
+ * flat `UIMessage[]` can't express the parent/child a Session tree uses to
508
+ * resolve this structurally, so ai-chat reads it from stream metadata.
509
+ *
510
+ * When the reconstructed message already adopted a provider `start.messageId`
511
+ * (kept as-is — the live path adopts it for new turns too) `reconstructedId`
512
+ * differs from `fallbackId` and is returned unchanged. Otherwise resolve to:
513
+ * - the id allocated when the stream started, recorded in stream metadata
514
+ * (#1691) — the SAME id the live path persists under (it only adopts a
515
+ * provider id, never invents one). A new turn stored its own fresh id, so
516
+ * it becomes its own message; a continuation stored the cloned
517
+ * last-assistant id, so it merges. This is what stops a new turn after a
518
+ * later user message from being folded into the previous assistant
519
+ * message (the #1691 corruption); or
520
+ * - (legacy rows written before the metadata column existed) the last
521
+ * assistant message, matching pre-#1691 behavior.
522
+ * @internal
523
+ */
524
+ protected _resolveOrphanTargetId(
525
+ streamId: string,
526
+ reconstructedId: string,
527
+ fallbackId: string
528
+ ): string;
529
+ /**
530
+ * The orphan-persist store adapter — orphan-persist steps **(c)/(d)** route
531
+ * their write through this shared `OrphanPersistStore` seam (the
532
+ * `SessionProvider` write-subset). Backed by ai-chat's flat `this.messages`
533
+ * array + the existing `persistMessages` whole-array write path, so
534
+ * reconcile/sanitize/row-size/broadcast all stay intact. Each mutating call
535
+ * is exactly one `persistMessages` invocation; `parentId` is unused (a flat
536
+ * array has no tree to attach to).
537
+ * @internal
538
+ */
539
+ protected _orphanStore(): OrphanPersistStore;
540
+ /**
541
+ * Repair a single interrupted tool call — a tool part with no settled result,
542
+ * left behind when a stream was cut off mid-flight (e.g. a SERVER tool whose
543
+ * `execute()` died with an evicted isolate, leaving an `input-available`
544
+ * orphan that nothing will ever resolve). Returns the replacement part that
545
+ * takes its place in the transcript; `input` has already been normalized to a
546
+ * valid object.
547
+ *
548
+ * The default flips it to an errored tool result so the record survives (no
549
+ * "disappearing" tool call) and `convertToModelMessages` still gets a
550
+ * tool-result for it, avoiding `AI_MissingToolResultsError` on the next
551
+ * provider call. This mirrors `@cloudflare/think` so ai-chat RECOVERS an
552
+ * interrupted server tool (repairs, then continues) instead of waiting on a
553
+ * dead orphan until its budget is spent.
554
+ *
555
+ * Override to customize the repaired shape for client-resolved tools — e.g.
556
+ * convert an interrupted question tool (no server `execute`, normally answered
557
+ * by the user's next message) into a plain text part so the model sees it as
558
+ * ordinary conversation rather than a tool error. A returned tool part MUST
559
+ * carry a settled result (`output-available` / `output-error` /
560
+ * `output-denied` or an `output` / `result` field); returning a non-tool part
561
+ * (e.g. text) is fine.
562
+ */
563
+ protected repairInterruptedToolPart(
564
+ part: UIMessage["parts"][number]
565
+ ): UIMessage["parts"][number];
566
+ /**
567
+ * Transcript repair, run before EVERY inference chokepoint (live submit, tool
568
+ * auto-continuation, `continueLastTurn`, `saveMessages`/retry, and the chat
569
+ * recovery callbacks). An interrupted server-tool orphan is flipped to a
570
+ * settled (errored) result — via the shared `agents/chat`
571
+ * `repairInterruptedToolParts` primitive, the SAME logic `@cloudflare/think`
572
+ * runs before its own inference (`_assembleModelMessages`) — so the app's next
573
+ * `convertToModelMessages(this.messages)` doesn't 400 with
574
+ * `AI_MissingToolResultsError`. Because the app owns the inference call, the
575
+ * framework can't repair "inside" it the way Think does; it repairs
576
+ * `this.messages` at each point right before handing control to
577
+ * `onChatMessage` instead. This reaches the cases the recovery-only repair
578
+ * missed: a mixed client+server orphan whose client replay drives an
579
+ * auto-continuation, and any agent running with `chatRecovery` disabled.
580
+ *
581
+ * Scope: repair only ever flips a DEAD SERVER orphan (an interrupted tool with
582
+ * no settled result whose `execute()` died with the evicted isolate). A part
583
+ * still legitimately awaiting a CLIENT interaction — an `input-available`
584
+ * client tool the SPA replays, or an `approval-requested` part the user may
585
+ * still answer — is left verbatim via the shared `shouldRepair` skip, so it is
586
+ * never clobbered with an error. This is per-part (not a whole-transcript
587
+ * guard), so a fresh dead-server orphan at the leaf is still repaired even if
588
+ * an unrelated abandoned client orphan sits earlier in history.
589
+ *
590
+ * Repair only ever reshapes ASSISTANT tool parts; it never touches user
591
+ * messages, so per-channel policy carried on the user message's
592
+ * `metadata.channel` (re-resolved on wake) is structurally untouched. It is a
593
+ * no-op (no write, no broadcast) when nothing needs repair — the common case
594
+ * for a healthy transcript. When anything changes, the corrected transcript is
595
+ * persisted and broadcast through the normal `persistMessages` write path (one
596
+ * write, one broadcast), which also refreshes `this.messages`.
597
+ * @internal
598
+ */
599
+ private _repairInterruptedToolsBeforeTurn;
408
600
  /**
409
601
  * Restore _lastBody and _lastClientTools from SQLite.
410
602
  * Called in the constructor so these values survive DO hibernation.
@@ -442,6 +634,18 @@ declare class AIChatAgent<
442
634
  * `waitForIdle()` (tests, `waitUntilStable`, recovery code).
443
635
  */
444
636
  private waitForIdle;
637
+ /**
638
+ * `true` when an auto-continuation is armed and going to fire on its own —
639
+ * its coalesce timer is still pending or its completeness barrier is
640
+ * mid-drain (#1650). Such an agent is NOT idle/stable: a continuation turn is
641
+ * imminent, so idle observers (recovery, idle-eviction, tests) must keep
642
+ * waiting until it either enqueues a turn or parks on an incomplete batch.
643
+ * A continuation that has already entered its turn (`pastCoalesce`) is
644
+ * covered by the turn queue, and a parked one (waiting on an unanswered
645
+ * sibling) is covered by `hasPendingInteraction()`, so neither is reported
646
+ * here.
647
+ */
648
+ private _hasArmedContinuation;
445
649
  private _getSubmitConcurrencyDecision;
446
650
  private _mergeQueuedUserMessages;
447
651
  private _getMergedQueuedUserMessages;
@@ -453,6 +657,17 @@ declare class AIChatAgent<
453
657
  private _messagesForClientSync;
454
658
  private _sendDirectMessage;
455
659
  private _completeSkippedRequest;
660
+ /** Whether a connection with this id is still attached. */
661
+ private _isConnectionPresent;
662
+ /**
663
+ * Mark an accepted turn (#1784) as settled. When `releaseParked` (the default)
664
+ * and no accepted turn remains in flight and no stream is active, release every
665
+ * parked connection with STREAM_RESUME_NONE so a client that reconnected during
666
+ * the pre-stream window stops waiting. A no-op when the parked set was already
667
+ * flushed on stream start. Skip paths pass `releaseParked: false` so a parked
668
+ * client survives onto the successor turn (see `_completeSkippedRequest`).
669
+ */
670
+ private _settlePreStreamTurn;
456
671
  private _rollbackDroppedSubmit;
457
672
  /** `true` when an assistant message is waiting on a client tool result or approval. */
458
673
  protected hasPendingInteraction(): boolean;
@@ -463,8 +678,22 @@ declare class AIChatAgent<
463
678
  * Returns `true` when stable. Returns `false` if `timeout` expires before
464
679
  * a pending interaction resolves. Safe to call at any time; if there is
465
680
  * nothing pending it returns immediately.
466
- */
467
- protected waitUntilStable(options?: { timeout?: number }): Promise<boolean>;
681
+ *
682
+ * `pendingInteraction` overrides which "still waiting" predicate gates
683
+ * stability. It defaults to the broad {@link hasPendingInteraction} (any
684
+ * `input-available` / `approval-requested` part) to preserve the documented
685
+ * semantics for app overrides. The recovery paths pass the narrower
686
+ * {@link hasPendingClientInteraction} so a DEAD server-tool `input-available`
687
+ * orphan (its `execute()` died with the evicted isolate; nothing will resolve
688
+ * it) does NOT block stability — recovery then repairs it to an errored
689
+ * result and continues, instead of waiting until the budget is spent. This
690
+ * mirrors `@cloudflare/think`, whose single pending predicate is already
691
+ * client-only by construction.
692
+ */
693
+ protected waitUntilStable(options?: {
694
+ timeout?: number;
695
+ pendingInteraction?: () => boolean;
696
+ }): Promise<boolean>;
468
697
  private abortActiveTurn;
469
698
  /**
470
699
  * Aborts the active turn and invalidates queued continuations. Call this
@@ -528,8 +757,6 @@ declare class AIChatAgent<
528
757
  * pending — its `execute()` died with the isolate. Mirrors `@cloudflare/think`.
529
758
  */
530
759
  private _partAwaitsClientInteraction;
531
- /** Extract a tool part's name from its `tool-<name>` / `dynamic-tool` shape. */
532
- private _toolPartName;
533
760
  /**
534
761
  * Names of the CLIENT-resolvable tools (the client-provided schemas from the
535
762
  * last request, which have no server `execute`). Mirrors `@cloudflare/think`.
@@ -540,23 +767,44 @@ declare class AIChatAgent<
540
767
  * streaming turn.
541
768
  */
542
769
  private _runExclusiveChatTurn;
543
- private _enqueueAutoContinuation;
544
- private _awaitPendingAutoContinuationPrerequisite;
545
770
  /**
546
- * Block until the latest assistant step's parallel tool batch is fully
547
- * answered, or `AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS` elapses. Awaits the
548
- * in-flight tool-result apply when one exists (so a sibling that lands
549
- * mid-wait is observed promptly) and polls otherwise. Runs inside the
550
- * continuation turn, so — unlike `waitUntilStable` — it must not wait on the
551
- * turn queue (that would deadlock).
552
- *
553
- * No concurrent-entry guard is needed (unlike Think's `_continuationBarrier
554
- * Active`): this runs inside the exclusive continuation turn, and a sibling
555
- * result arriving while it waits hits the merge branch of
556
- * `_enqueueAutoContinuation` (it updates `pending.prerequisite`) rather than
557
- * enqueuing a second turn — so the turn queue serializes barrier waits.
771
+ * Schedule an auto-continuation for a tool result/approval that opted in with
772
+ * `autoContinue: true` (#1650). Thin host wrapper that builds the
773
+ * {@link ContinuationSpec} and delegates to the shared
774
+ * {@link AutoContinuationController}, which owns the coalesce timer and the
775
+ * completeness-gated fire (shared with `@cloudflare/think`).
558
776
  */
559
- private _awaitPendingInteractionBarrier;
777
+ private _scheduleAutoContinuation;
778
+ /**
779
+ * Re-arm the barrier for a result/approval that arrived WITHOUT `autoContinue`
780
+ * (#1650). A standalone errored result declines to continue on its own, but in
781
+ * a parallel batch a SIBLING may already have opted in — and this result can be
782
+ * the one that completes the batch, so we must re-run the barrier check. Unlike
783
+ * `_scheduleAutoContinuation` this NEVER creates a pending continuation (a
784
+ * standalone errored tool with no opted-in sibling must not auto-continue), and
785
+ * it no-ops once the continuation is running (`pastCoalesce`).
786
+ */
787
+ private _rearmPendingAutoContinuationForBatch;
788
+ /**
789
+ * Called when a streaming assistant turn finalizes (its message, with ALL tool
790
+ * parts, is now persisted). Clears the stream-active gate and re-runs the
791
+ * barrier for a continuation the gate held (#1650). Essential for an all-fast
792
+ * parallel batch whose every result landed mid-stream: once the stream ends
793
+ * there is no further tool-result event to re-arm, so without this the held
794
+ * continuation would never fire. A slow batch is re-checked here and simply
795
+ * keeps holding (event-driven) until its remaining siblings answer.
796
+ */
797
+ private _onStreamingTurnFinalized;
798
+ /**
799
+ * Drain every in-flight tool-result/approval apply, including any enqueued
800
+ * while we wait, so the subsequent `_hasIncompleteToolBatch()` re-check sees
801
+ * every result that has ALREADY arrived. Bounded by real apply activity (a
802
+ * storage write each), never by a fixed timer: the loop re-reads
803
+ * `_interactionApplyTail` after each await because a sibling can extend the
804
+ * tail mid-drain, and stops once the tail stops advancing. Mirrors
805
+ * `@cloudflare/think`'s `_drainInteractionApplies`.
806
+ */
807
+ private _drainInteractionApplies;
560
808
  /**
561
809
  * `true` when the latest assistant message is mid-batch: it carries at least
562
810
  * one settled tool result AND at least one tool call/approval still awaiting a
@@ -566,7 +814,7 @@ declare class AIChatAgent<
566
814
  * message doesn't block a legitimate follow-up continuation.
567
815
  */
568
816
  private _hasIncompleteToolBatch;
569
- private _queueAutoContinuation;
817
+ private _fireAutoContinuation;
570
818
  /**
571
819
  * @returns Terminal status for the turn.
572
820
  */
@@ -650,6 +898,14 @@ declare class AIChatAgent<
650
898
  runId: string;
651
899
  }
652
900
  ): UIMessage;
901
+ private _agentToolProgressEmitterInstance;
902
+ private get _agentToolProgressEmitter();
903
+ reportProgress<T = unknown>(
904
+ progress: AgentToolProgress<T>,
905
+ options?: {
906
+ persist?: boolean;
907
+ }
908
+ ): Promise<void>;
653
909
  /**
654
910
  * Override to return structured agent-tool output instead of the default
655
911
  * final assistant text.
@@ -672,6 +928,97 @@ declare class AIChatAgent<
672
928
  output: unknown,
673
929
  messagesAfterStart: readonly UIMessage[]
674
930
  ): string;
931
+ /** True while running inside this agent's own serialized detached-delivery
932
+ * turn slot (set by {@link _runDetachedDelivery}); lets a `react` notify run
933
+ * its reply inline rather than enqueuing (which would deadlock) or interleaving
934
+ * with a foreign turn. */
935
+ private _inSerializedDetachedDeliverySlot;
936
+ /** Notification ids (`detached-finish:*` / `detached-ms:*`) currently being
937
+ * injected, to dedupe a concurrent warm-tail + backbone delivery of the same
938
+ * milestone within one isolate before the persisted message exists. */
939
+ private _inFlightDetachedNotifications;
940
+ /**
941
+ * Serialize detached terminal delivery against the chat turn queue. A
942
+ * fast-path push or backbone tick can land mid-turn, and an `onFinish` that
943
+ * mutates chat state (`saveMessages`, `setState`, a follow-up
944
+ * `runAgentTool`) running concurrently with an active LLM turn is a data
945
+ * race. Those paths never run synchronously inside a turn body (they fire
946
+ * from `waitUntil` / a scheduled alarm), so enqueuing on the turn queue runs
947
+ * the delivery strictly between turns without risk of self-deadlock.
948
+ *
949
+ * An explicit `cancelAgentTool` (`serialize` unset) may be invoked from
950
+ * inside the very turn that triggers it, where enqueuing WOULD self-deadlock,
951
+ * so it runs inline in the caller's (or a fresh) `agentContext`.
952
+ */
953
+ protected _runDetachedDelivery(
954
+ invoke: () => Promise<void>,
955
+ options?: {
956
+ serialize?: boolean;
957
+ }
958
+ ): Promise<void>;
959
+ /**
960
+ * Inject a synthetic chat message for a detached-run notification, idempotent
961
+ * on its deterministic `id` (a re-delivery from the warm tail + cold backbone
962
+ * collapses to one — `persistMessages` is skipped when the id already exists).
963
+ * When `react` is set the model then takes a turn over the new message.
964
+ *
965
+ * `@cloudflare/ai-chat` has no durable-submission layer (unlike Think's
966
+ * `submitMessages`), so the turn cannot be enqueued-and-awaited from inside the
967
+ * serialized delivery slot — `TurnQueue` has no re-entrancy bypass, so that
968
+ * would self-deadlock. Instead: when we are already inside a turn slot (the
969
+ * `serialize: true` finish delivery runs as its own enqueued turn) we run the
970
+ * programmatic turn INLINE, reusing that slot — so the whole notify completes
971
+ * before the ledger marks the slot delivered (eviction-safe). When we are not
972
+ * inside a slot (a milestone fired from the `waitUntil` fast path or the
973
+ * reconcile alarm) we enqueue a fresh turn normally.
974
+ */
975
+ private _injectDetachedNotification;
976
+ /**
977
+ * Format the message injected by `detached: { notify }` when a background run
978
+ * finishes. Override to customize the prose, or return an empty string to
979
+ * suppress the notification for a given outcome.
980
+ */
981
+ protected formatDetachedCompletion(
982
+ run: AgentToolRunInfo,
983
+ result: AgentToolLifecycleResult
984
+ ): string;
985
+ /**
986
+ * Targeted completion hook for `detached: { notify }`. Auto-wired by
987
+ * `runAgentTool` (resolved by name so the base `Agent` stays decoupled from the
988
+ * chat layer). Injects the formatted completion as a user turn so the model
989
+ * reacts to the background result. Idempotent per run + status (deterministic
990
+ * message id), so an exactly-once finish — or a soft give-up followed by a real
991
+ * completion — never injects a duplicate, while a give-up and a later real
992
+ * completion surface as two distinct messages.
993
+ */
994
+ _cfDetachedNotifyFinish(
995
+ run: AgentToolRunInfo,
996
+ result: AgentToolLifecycleResult
997
+ ): Promise<void>;
998
+ /**
999
+ * Format the message injected when a `detached: { onMilestones }` milestone is
1000
+ * reached. Override to customize the prose (or return an empty string to
1001
+ * suppress a given milestone).
1002
+ */
1003
+ protected formatDetachedMilestone(
1004
+ run: AgentToolRunInfo,
1005
+ milestone: AgentToolMilestone
1006
+ ): string;
1007
+ /**
1008
+ * Targeted milestone hook for `detached: { onMilestones }`. Idempotent per run
1009
+ * + milestone NAME (deterministic message id), so the warm tail and the cold
1010
+ * backbone reconcile converge to at most one message.
1011
+ *
1012
+ * - `"narrate"` (default): a synthetic **assistant** message injected directly
1013
+ * — no model turn.
1014
+ * - `"react"`: a **user** message followed by a model turn so the agent
1015
+ * responds to the milestone.
1016
+ */
1017
+ protected _deliverDetachedMilestone(
1018
+ run: AgentToolRunInfo,
1019
+ milestone: AgentToolMilestone,
1020
+ mode: "react" | "narrate"
1021
+ ): Promise<void>;
675
1022
  /**
676
1023
  * Bind the child turn that is about to stream to its agent-tool run, at
677
1024
  * the moment the turn's request id is first knowable (inside the turn,
@@ -728,6 +1075,7 @@ declare class AIChatAgent<
728
1075
  */
729
1076
  private _reconcileOwnStaleAgentToolChildRuns;
730
1077
  inspectAgentToolRun(runId: string): Promise<AgentToolRunInspection | null>;
1078
+ private static _progressSnapshotFromRow;
731
1079
  getAgentToolChunks(
732
1080
  runId: string,
733
1081
  options?: {
@@ -814,8 +1162,6 @@ declare class AIChatAgent<
814
1162
  * @internal
815
1163
  */
816
1164
  private _resolveChatRecoveryConfig;
817
- private _chatRecoveryIncidentId;
818
- private _chatRecoveryIncidentKey;
819
1165
  /**
820
1166
  * Monotonic forward-progress signal for recovery budget resets.
821
1167
  *
@@ -833,11 +1179,12 @@ declare class AIChatAgent<
833
1179
  private _chatRecoveryProgressMarker;
834
1180
  /** Advance the durable recovery-progress counter. Called from
835
1181
  * `_maybeBumpRecoveryProgress` when new content is streamed (real,
836
- * reconnect-immune forward progress). */
1182
+ * reconnect-immune forward progress). The increment lives in the shared
1183
+ * engine (agents/chat); this is the package binding. */
837
1184
  private _bumpChatRecoveryProgress;
838
- /** In-memory wall-clock of the last N9 child-stream progress bump (reset per
839
- * isolate so the first forwarded chunk after a restart always credits). */
840
- private _lastAgentToolStreamProgressAt;
1185
+ /** Per-isolate N9 throttle gate (shared `agents/chat` helper); reset per
1186
+ * isolate so the first forwarded chunk after a restart always credits. */
1187
+ private _agentToolStreamProgress;
841
1188
  /**
842
1189
  * N9: forwarding a sub-agent's chunks IS forward progress for this parent
843
1190
  * turn, so credit the parent's recovery progress marker — otherwise a parent
@@ -848,14 +1195,14 @@ declare class AIChatAgent<
848
1195
  * Throttled (and reset per isolate) so we never write storage per token.
849
1196
  */
850
1197
  protected _onAgentToolStreamProgress(): Promise<void>;
851
- /** Whether a reconstructed partial carries any settled (provider-accepted)
852
- * tool result — the completed, often non-idempotent work that a
853
- * `{ persist: false }` recovery return would silently discard.
854
- * `convertToModelMessages` treats `output-available` / `output-error` /
855
- * `output-denied` (or a part carrying `output`/`result`) as settled. */
856
- private _partialHasSettledToolResults;
857
- /** Sweep recovery incidents that have been inactive past the TTL. */
858
- private _sweepStaleChatRecoveryIncidents;
1198
+ /**
1199
+ * Lazily-built shared recovery engine. The adapter arrows capture `this`, so a
1200
+ * single cached instance is correct across calls (and across future engine
1201
+ * methods). `AIChatAgent` has no interaction state to rehydrate, so it omits
1202
+ * the optional `ensureInteractionStateLoaded` hook.
1203
+ */
1204
+ private _chatRecoveryEngineInstance?;
1205
+ private _chatRecoveryEngine;
859
1206
  private _beginChatRecoveryIncident;
860
1207
  private _updateChatRecoveryIncident;
861
1208
  private _exhaustChatRecovery;
@@ -870,33 +1217,55 @@ declare class AIChatAgent<
870
1217
  private _clearChatTerminal;
871
1218
  private _pendingChatTerminal;
872
1219
  /**
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).
1220
+ * Build the on-connect "recovering…" replay frame (#1620), or `null` when no
1221
+ * (non-stale) recovery is in progress. A client that connects between recovery
1222
+ * attempts (no active stream) reads the turn as working rather than frozen.
1223
+ * A record older than the flag TTL is treated as abandoned (its terminal-clear
1224
+ * never ran) and skipped, so a dead recovery can't show "recovering…" forever.
1225
+ * Mirrors `@cloudflare/think`'s `_buildIdleConnectMessages` recovering replay.
880
1226
  */
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;
1227
+ private _buildRecoveringConnectFrame;
889
1228
  /**
890
1229
  * Set or clear the live "recovering…" status (#1620). Persists a durable
891
1230
  * record (so set/clear stay consistent across the isolates a recovery spans)
892
1231
  * and broadcasts a `CF_AGENT_CHAT_RECOVERING` frame on a genuine transition.
893
- * NOTE: the live "recovering…" signal is still not replayed on connect — only
894
- * the terminal outcome is (#1645, via the resume handshake).
1232
+ * The status is also replayed on connect (`_buildRecoveringConnectFrame`) so a
1233
+ * client connecting mid-recovery isn't left looking frozen; the terminal
1234
+ * outcome is surfaced separately over the resume handshake (#1645).
895
1235
  */
896
1236
  private _setChatRecovering;
897
1237
  protected _handleInternalFiberRecovery(
898
1238
  ctx: FiberRecoveryContext
899
1239
  ): Promise<boolean>;
1240
+ /**
1241
+ * Resolve the orphaned stream for a recovered chat turn — drives BOTH the wake
1242
+ * path (full result) and the give-up terminalization (which reads only
1243
+ * `.streamId`). Prefers the newest durable stream row keyed by the recovery-
1244
+ * root request id; falls back to the live active stream; `streamId` is `""`
1245
+ * when neither survives. `AIChatAgent` does not model terminal stream status,
1246
+ * so `streamStatus` is left `undefined` (keeping the engine's terminal-stream
1247
+ * branches dead here) — see the "substrate capabilities are optional" decision
1248
+ * in the RFC.
1249
+ */
1250
+ private _resolveAIChatRecoveryStream;
1251
+ /**
1252
+ * Classify a recovered turn as `retry` or `continue`. The `shouldRetryPreStream`
1253
+ * detail is threaded to the dispatch decision; `emptyPartialNewTurn` only
1254
+ * influences the reported kind (an empty partial persists nothing, so a new turn
1255
+ * is re-run fresh rather than merged into the previous assistant — #1691). The
1256
+ * `persist: false` discard case stays "continue" here and only surfaces as
1257
+ * "retry" on the `chat:recovery:scheduled` event, decided in dispatch.
1258
+ */
1259
+ private _classifyRecoveredChatTurn;
1260
+ /**
1261
+ * The retry/continue/skip decision for a recovered chat turn, run after the
1262
+ * partial is persisted and the stream completed. A NEW turn that left no
1263
+ * persisted assistant partial (the leaf is still the user message) is re-run
1264
+ * fresh instead of continued (which would clone + merge into the previous
1265
+ * assistant turn — #1691); this lost-partial check is re-derived here from the
1266
+ * now-updated leaf rather than carried from classify.
1267
+ */
1268
+ private _dispatchRecoveredChatTurn;
900
1269
  /**
901
1270
  * Called when an interrupted chat stream is detected after restart.
902
1271
  * Return options to control recovery:
@@ -916,6 +1285,22 @@ declare class AIChatAgent<
916
1285
  ): Promise<ChatRecoveryOptions$1 | void>;
917
1286
  _chatRecoveryContinue(data?: ChatRecoveryContinueData): Promise<void>;
918
1287
  private _applyRecoveredRequestContext;
1288
+ /**
1289
+ * Route a live stream stall (the {@link chatStreamStallTimeoutMs} watchdog
1290
+ * fired) into the same bounded-recovery machinery a deploy/eviction
1291
+ * interruption uses (#1626). Mirrors `@cloudflare/think`'s stall path: open or
1292
+ * reuse the incident under the turn's recovery identity, deliver terminal UX
1293
+ * if the budget is spent, otherwise schedule a `_chatRecoveryContinue`.
1294
+ *
1295
+ * Unlike Think there is no durable-submission layer to complete here, so the
1296
+ * schedule payload carries no `recoveredRequestId`.
1297
+ *
1298
+ * Returns `"disabled"` when chat recovery is off (the caller then surfaces the
1299
+ * stall as a terminal stream error — the watchdog's "kill the spinner"
1300
+ * guarantee), `"exhausted"` when the budget was spent (terminal UX already
1301
+ * delivered), or `"scheduled"` when a continuation was queued.
1302
+ */
1303
+ private _routeStallToBoundedRecovery;
919
1304
  /**
920
1305
  * Reschedule a recovery callback that timed out waiting for stable state,
921
1306
  * consuming one attempt. Returns `true` if rescheduled, `false` if the
@@ -949,13 +1334,6 @@ declare class AIChatAgent<
949
1334
  * reschedule / exhaustion path).
950
1335
  */
951
1336
  private _parkRecoveryForPendingInteraction;
952
- /**
953
- * Resolve the stream id for a recovery turn so the give-up terminalization
954
- * can surface whatever partial the turn produced. Prefers the durable stream
955
- * row keyed by the recovery-root request id; falls back to the live active
956
- * stream. Returns `""` when neither is available.
957
- */
958
- private _resolveRecoveryStreamId;
959
1337
  /**
960
1338
  * Terminalize a recovery turn that has run out of stable-state-timeout retry
961
1339
  * budget — or whose incident record has vanished — by routing through the
@@ -1091,12 +1469,6 @@ declare class AIChatAgent<
1091
1469
  * @returns The message, compacted if necessary
1092
1470
  */
1093
1471
  private _enforceRowSizeLimit;
1094
- /**
1095
- * Truncates text parts in a message to fit within the row size limit.
1096
- * Truncates from the first text part forward, keeping the last text part
1097
- * as intact as possible (it is usually the most relevant).
1098
- */
1099
- private _truncateTextParts;
1100
1472
  /**
1101
1473
  * Shared helper for finding a tool part by toolCallId and applying an update.
1102
1474
  * Handles both streaming (in-memory) and persisted (SQLite) messages.