@cloudflare/ai-chat 0.7.1 → 0.8.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/README.md CHANGED
@@ -248,6 +248,35 @@ Streams automatically resume on disconnect/reconnect. No configuration needed.
248
248
 
249
249
  When a client disconnects mid-stream, chunks are buffered in SQLite. On reconnect, the client receives all buffered chunks and continues receiving the live stream.
250
250
 
251
+ This handles browser disconnects, navigation, and React cleanup while the Durable Object keeps running. To recover after the Durable Object itself is evicted during a model call, opt in to `chatRecovery`.
252
+
253
+ ## Durable Chat Recovery
254
+
255
+ `AIChatAgent` defaults `chatRecovery` to `false`. Enable it when you want chat turns to survive Worker deploys, Durable Object eviction, or process restarts:
256
+
257
+ ```typescript
258
+ import type {
259
+ ChatRecoveryContext,
260
+ ChatRecoveryOptions
261
+ } from "@cloudflare/ai-chat";
262
+
263
+ export class ChatAgent extends AIChatAgent<Env> {
264
+ override chatRecovery = {
265
+ maxAttempts: 6,
266
+ terminalMessage: "The assistant was interrupted. Please try again."
267
+ };
268
+
269
+ override async onChatRecovery(
270
+ ctx: ChatRecoveryContext
271
+ ): Promise<ChatRecoveryOptions> {
272
+ console.log("Recovering", ctx.incidentId, ctx.recoveryKind);
273
+ return {}; // persist partial output and continue/retry when possible
274
+ }
275
+ }
276
+ ```
277
+
278
+ See [`docs/chat-agents.md`](../../docs/chat-agents.md#stream-recovery) for provider-specific recovery strategies and observability events.
279
+
251
280
  Generic client stream abort/cleanup is local-only by default: the server turn continues and can be resumed later. An explicit `stop()` still cancels the server turn:
252
281
 
253
282
  ```tsx
@@ -431,9 +460,11 @@ Extends `Agent` from the `agents` package.
431
460
  | Property / Method | Type | Description |
432
461
  | ------------------------------------ | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
433
462
  | `messages` | `ChatMessage[]` | Current conversation messages (loaded from SQLite) |
463
+ | `chatRecovery` | `ChatRecoveryConfig` | Opt-in Durable Object eviction recovery for chat turns. Default: `false` |
434
464
  | `maxPersistedMessages` | `number \| undefined` | Max messages to keep in SQLite. Default: unlimited |
435
465
  | `messageConcurrency` | `MessageConcurrency` | Concurrency strategy for `sendMessage()` submits. Default: `"queue"` |
436
466
  | `onChatMessage(onFinish?, options?)` | Override | Handle incoming chat messages. Return a `Response`. `onFinish` is optional. |
467
+ | `onChatRecovery(ctx)` | Override | Customize recovery after a chat turn is interrupted while `chatRecovery` is enabled |
437
468
  | `onChatResponse(result)` | Override | Called after a chat turn completes. `result` has `message`, `requestId`, `status`, `continuation` |
438
469
  | `persistMessages(messages)` | `Promise<void>` | Manually persist messages (usually automatic) |
439
470
  | `saveMessages(messages, options?)` | `Promise<SaveMessagesResult>` | Persist messages and trigger `onChatMessage`. Accepts array or function. `options.signal` cancels the turn externally. |
@@ -472,11 +503,11 @@ React hook for chat interactions. Wraps the AI SDK's `useChat` with WebSocket tr
472
503
 
473
504
  ### Exports
474
505
 
475
- | Import path | What it provides |
476
- | --------------------------- | ------------------------------------------------------------ |
477
- | `@cloudflare/ai-chat` | `AIChatAgent`, `ChatMessage`, `createToolsFromClientSchemas` |
478
- | `@cloudflare/ai-chat/react` | `useAgentChat` |
479
- | `@cloudflare/ai-chat/types` | `MessageType`, `OutgoingMessage`, `IncomingMessage` |
506
+ | Import path | What it provides |
507
+ | --------------------------- | --------------------------------------------------------------------------------------------------------- |
508
+ | `@cloudflare/ai-chat` | `AIChatAgent`, `ChatMessage`, `createToolsFromClientSchemas`, `ChatRecoveryContext`, `ChatRecoveryConfig` |
509
+ | `@cloudflare/ai-chat/react` | `useAgentChat` |
510
+ | `@cloudflare/ai-chat/types` | `MessageType`, `OutgoingMessage`, `IncomingMessage` |
480
511
 
481
512
  ## Examples
482
513
 
package/dist/index.d.ts CHANGED
@@ -6,8 +6,11 @@ import {
6
6
  FiberRecoveryContext
7
7
  } from "agents";
8
8
  import {
9
+ ChatRecoveryConfig,
10
+ ChatRecoveryConfig as ChatRecoveryConfig$1,
9
11
  ChatRecoveryContext,
10
12
  ChatRecoveryContext as ChatRecoveryContext$1,
13
+ ChatRecoveryExhaustedContext,
11
14
  ChatRecoveryOptions,
12
15
  ChatRecoveryOptions as ChatRecoveryOptions$1,
13
16
  ChatResponseResult,
@@ -16,6 +19,7 @@ import {
16
19
  ClientToolSchema as ClientToolSchema$1,
17
20
  MessageConcurrency,
18
21
  MessageConcurrency as MessageConcurrency$1,
22
+ ResolvedChatRecoveryConfig,
19
23
  ResumableStream,
20
24
  SaveMessagesOptions,
21
25
  SaveMessagesOptions as SaveMessagesOptions$1,
@@ -26,6 +30,20 @@ import {
26
30
  import { StreamTextOnFinishCallback, ToolSet, UIMessage } from "ai";
27
31
 
28
32
  //#region src/index.d.ts
33
+ type ChatRecoveryRetryData = {
34
+ targetUserId?: string;
35
+ originalRequestId?: string;
36
+ incidentId?: string;
37
+ lastBody?: Record<string, unknown> | null;
38
+ lastClientTools?: ClientToolSchema$1[] | null;
39
+ };
40
+ type ChatRecoveryContinueData = {
41
+ targetAssistantId?: string;
42
+ originalRequestId?: string;
43
+ incidentId?: string;
44
+ lastBody?: Record<string, unknown> | null;
45
+ lastClientTools?: ClientToolSchema$1[] | null;
46
+ };
29
47
  type ChatMessage = UIMessage;
30
48
  /**
31
49
  * Options passed to the onChatMessage handler.
@@ -85,6 +103,7 @@ declare class AIChatAgent<
85
103
  State = unknown,
86
104
  Props extends Record<string, unknown> = Record<string, unknown>
87
105
  > extends Agent<Env, State, Props> {
106
+ private _activeChatRecoveryRootRequestId;
88
107
  /**
89
108
  * Registry of per-request AbortControllers.
90
109
  * Used to propagate cancellation signals for any external calls made by the agent.
@@ -137,7 +156,7 @@ declare class AIChatAgent<
137
156
  * Enables `onChatRecovery` hook and `this.stash()` during streaming.
138
157
  * Set to `true` in subclasses to enable durable streaming.
139
158
  */
140
- chatRecovery: boolean;
159
+ chatRecovery: ChatRecoveryConfig$1;
141
160
  /** First queued overlap message index for merge strategy, keyed by epoch. */
142
161
  private _mergeQueuedUserStartIndexByEpoch;
143
162
  /** Shared admission policy state for overlapping submit-message requests. */
@@ -254,6 +273,7 @@ declare class AIChatAgent<
254
273
  | {
255
274
  timeout: number;
256
275
  };
276
+ private _runChatRecoveryFiber;
257
277
  /**
258
278
  * Array of chat messages for the current conversation.
259
279
  *
@@ -289,8 +309,17 @@ declare class AIChatAgent<
289
309
  protected _startStream(requestId: string): string;
290
310
  /** @internal Delegate to _resumableStream */
291
311
  protected _completeStream(streamId: string): void;
292
- /** @internal Delegate to _resumableStream */
293
- protected _storeStreamChunk(streamId: string, body: string): void;
312
+ /** @internal Delegate to _resumableStream. Also advances the recovery
313
+ * progress counter at production time (see `_maybeBumpRecoveryProgress`). */
314
+ protected _storeStreamChunk(streamId: string, body: string): Promise<void>;
315
+ /** Advance the recovery-progress counter when a chunk represents genuinely
316
+ * new produced content — a started text/reasoning segment or a settled tool
317
+ * input/output. Bumped at production time (the streaming path), so it
318
+ * reflects real forward progress and is immune to client reconnects /
319
+ * recovery re-persists (which replay or re-materialize stored chunks rather
320
+ * than flow through here). This is what the recovery no-progress window keys
321
+ * off (#1637), and stays compaction-proof (#1628). */
322
+ private _maybeBumpRecoveryProgress;
294
323
  /** @internal Delegate to _resumableStream */
295
324
  protected _flushChunkBuffer(): void;
296
325
  /** @internal Delegate to _resumableStream */
@@ -306,7 +335,7 @@ declare class AIChatAgent<
306
335
  * message parts, then persists the result so it survives further refreshes.
307
336
  * @internal
308
337
  */
309
- protected _persistOrphanedStream(streamId: string): void;
338
+ protected _persistOrphanedStream(streamId: string): Promise<void>;
310
339
  /**
311
340
  * Restore _lastBody and _lastClientTools from SQLite.
312
341
  * Called in the constructor so these values survive DO hibernation.
@@ -411,12 +440,33 @@ declare class AIChatAgent<
411
440
  private _runExclusiveChatTurn;
412
441
  private _enqueueAutoContinuation;
413
442
  private _awaitPendingAutoContinuationPrerequisite;
443
+ /**
444
+ * Block until the latest assistant step's parallel tool batch is fully
445
+ * answered, or `AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS` elapses. Awaits the
446
+ * in-flight tool-result apply when one exists (so a sibling that lands
447
+ * mid-wait is observed promptly) and polls otherwise. Runs inside the
448
+ * continuation turn, so — unlike `waitUntilStable` — it must not wait on the
449
+ * turn queue (that would deadlock).
450
+ *
451
+ * No concurrent-entry guard is needed (unlike Think's `_continuationBarrier
452
+ * Active`): this runs inside the exclusive continuation turn, and a sibling
453
+ * result arriving while it waits hits the merge branch of
454
+ * `_enqueueAutoContinuation` (it updates `pending.prerequisite`) rather than
455
+ * enqueuing a second turn — so the turn queue serializes barrier waits.
456
+ */
457
+ private _awaitPendingInteractionBarrier;
458
+ /**
459
+ * `true` when the latest assistant message is mid-batch: it carries at least
460
+ * one settled tool result AND at least one tool call/approval still awaiting a
461
+ * client result. That is the #1649 signature — the model fanned out parallel
462
+ * tool calls and only some have been answered. Scoped to the leaf (the step
463
+ * the continuation answers) so an unrelated dangling tool in an earlier
464
+ * message doesn't block a legitimate follow-up continuation.
465
+ */
466
+ private _hasIncompleteToolBatch;
414
467
  private _queueAutoContinuation;
415
468
  /**
416
- * @returns `true` if the registry's controller for `requestId` was
417
- * aborted during the turn (so the caller can surface
418
- * `status: "aborted"` to the public API). Returns `false` for
419
- * successful or errored completion.
469
+ * @returns Terminal status for the turn.
420
470
  */
421
471
  private _runProgrammaticChatTurn;
422
472
  /**
@@ -528,6 +578,28 @@ declare class AIChatAgent<
528
578
  }
529
579
  ): Promise<AgentToolRunInspection>;
530
580
  cancelAgentToolRun(runId: string, reason?: unknown): Promise<void>;
581
+ /**
582
+ * Classify any in-flight chat-recovery on this child facet (#1630 / N6). A
583
+ * child facet is dedicated to a single agent-tool run, so any recovery
584
+ * incident is that run's. Incidents in `detected`/`scheduled`/`attempting`
585
+ * mean recovery is still resolving the interrupted turn; `exhausted`/`failed`
586
+ * mean recovery gave up; a completed recovery deletes its incident.
587
+ */
588
+ private _classifyAgentToolChildRecovery;
589
+ /**
590
+ * Reconcile a stale (post-eviction) child run row from the child's own
591
+ * durable recovery (#1630). The child facet self-heals its interrupted turn
592
+ * via `chatRecovery`, but that path never writes the run row, so without this
593
+ * the row strands `running` and the parent can only collect `interrupted`.
594
+ *
595
+ * Persisting the terminal here (rather than only computing it) is intentional:
596
+ * it's a lazy materialization of the run's true terminal that also lets a
597
+ * tailing parent's stream close promptly and makes subsequent inspects cheap.
598
+ * While recovery is still resolving (active stream or in-progress incident)
599
+ * the row is left `running` so the parent's bounded re-attach keeps waiting.
600
+ * Mutates `row` in place when it settles so the caller can report it.
601
+ */
602
+ private _reconcileStaleAgentToolChildRun;
531
603
  inspectAgentToolRun(runId: string): Promise<AgentToolRunInspection | null>;
532
604
  getAgentToolChunks(
533
605
  runId: string,
@@ -571,9 +643,10 @@ declare class AIChatAgent<
571
643
  * loop's signal aborts and the result reports `status: "aborted"`.
572
644
  * Pre-aborted signals short-circuit before any model work runs.
573
645
  *
574
- * Returns `{ requestId, status }` where `status` is `"completed"` when
575
- * the turn ran, `"skipped"` when the chat was cleared, or `"aborted"`
576
- * when an external signal cancelled it mid-stream.
646
+ * Returns `{ requestId, status, error? }` where `status` is `"completed"`
647
+ * when the turn ran, `"error"` when the stream reported an error,
648
+ * `"skipped"` when the chat was cleared, or `"aborted"` when an external
649
+ * signal cancelled it mid-stream.
577
650
  */
578
651
  saveMessages(
579
652
  messages:
@@ -602,6 +675,7 @@ declare class AIChatAgent<
602
675
  body?: Record<string, unknown>,
603
676
  options?: SaveMessagesOptions$1
604
677
  ): Promise<SaveMessagesResult$1>;
678
+ private _retryLastUserTurn;
605
679
  /**
606
680
  * Context passed to `onChatRecovery` when an interrupted chat stream
607
681
  * is detected after DO restart.
@@ -612,6 +686,60 @@ declare class AIChatAgent<
612
686
  * `onFiberRecovered` hook. Maps to `onChatRecovery`.
613
687
  * @internal
614
688
  */
689
+ private _resolveChatRecoveryConfig;
690
+ private _chatRecoveryIncidentId;
691
+ private _chatRecoveryIncidentKey;
692
+ /**
693
+ * Monotonic forward-progress signal for recovery budget resets.
694
+ *
695
+ * This used to count assistant messages in `this.messages`, but that is
696
+ * recomputed from the live, mutable transcript. Compaction collapses older
697
+ * assistant messages into a summary, lowering the count — so a turn that had
698
+ * genuinely advanced could read as "no progress" between attempts and exhaust
699
+ * its budget prematurely (#1628). Instead we read a durably-persisted counter
700
+ * that only ever increments — bumped at production time when new content is
701
+ * streamed (see `_storeStreamChunk` / `_maybeBumpRecoveryProgress`), which is
702
+ * genuine forward progress and is immune to client reconnects / recovery
703
+ * re-persists — so compaction can never lower it and a reconnect can't fake
704
+ * it (#1637).
705
+ */
706
+ private _chatRecoveryProgressMarker;
707
+ /** Advance the durable recovery-progress counter. Called from
708
+ * `_maybeBumpRecoveryProgress` when new content is streamed (real,
709
+ * reconnect-immune forward progress). */
710
+ private _bumpChatRecoveryProgress;
711
+ /** In-memory wall-clock of the last N9 child-stream progress bump (reset per
712
+ * isolate so the first forwarded chunk after a restart always credits). */
713
+ private _lastAgentToolStreamProgressAt;
714
+ /**
715
+ * N9: forwarding a sub-agent's chunks IS forward progress for this parent
716
+ * turn, so credit the parent's recovery progress marker — otherwise a parent
717
+ * whose turn merely `await`s a child banks no progress of its own and its
718
+ * no-progress window exhausts while the child is healthily streaming. Only
719
+ * invoked after a child actually produced output (see
720
+ * `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.
721
+ * Throttled (and reset per isolate) so we never write storage per token.
722
+ */
723
+ protected _onAgentToolStreamProgress(): Promise<void>;
724
+ /** Whether a reconstructed partial carries any settled (provider-accepted)
725
+ * tool result — the completed, often non-idempotent work that a
726
+ * `{ persist: false }` recovery return would silently discard.
727
+ * `convertToModelMessages` treats `output-available` / `output-error` /
728
+ * `output-denied` (or a part carrying `output`/`result`) as settled. */
729
+ private _partialHasSettledToolResults;
730
+ /** Sweep recovery incidents that have been inactive past the TTL. */
731
+ private _sweepStaleChatRecoveryIncidents;
732
+ private _beginChatRecoveryIncident;
733
+ private _updateChatRecoveryIncident;
734
+ private _exhaustChatRecovery;
735
+ /**
736
+ * Set or clear the live "recovering…" status (#1620). Persists a durable
737
+ * record (so set/clear stay consistent across the isolates a recovery spans)
738
+ * and broadcasts a `CF_AGENT_CHAT_RECOVERING` frame on a genuine transition.
739
+ * NOTE: AIChatAgent does not yet replay this on connect (no idle-connect
740
+ * hydration; tracked in #1645) — this is the live signal only.
741
+ */
742
+ private _setChatRecovering;
615
743
  protected _handleInternalFiberRecovery(
616
744
  ctx: FiberRecoveryContext
617
745
  ): Promise<boolean>;
@@ -624,12 +752,61 @@ declare class AIChatAgent<
624
752
  * - `{ persist: false, continue: false }`: handle everything yourself
625
753
  *
626
754
  * `ctx.recoveryData` contains any data checkpointed via `this.stash()`
627
- * during streaming (e.g., OpenAI `responseId`).
755
+ * during the turn (e.g., OpenAI `responseId`). If recovery happens before
756
+ * any stream chunks exist and the latest message is still the unanswered
757
+ * user message from the interrupted turn, the framework retries that turn
758
+ * automatically unless continuation is disabled.
628
759
  */
629
760
  protected onChatRecovery(
630
761
  _ctx: ChatRecoveryContext$1
631
- ): Promise<ChatRecoveryOptions$1>;
632
- _chatRecoveryContinue(data?: { targetAssistantId?: string }): Promise<void>;
762
+ ): Promise<ChatRecoveryOptions$1 | void>;
763
+ _chatRecoveryContinue(data?: ChatRecoveryContinueData): Promise<void>;
764
+ private _applyRecoveredRequestContext;
765
+ /**
766
+ * Reschedule a recovery callback that timed out waiting for stable state,
767
+ * consuming one attempt. Returns `true` if rescheduled, `false` if the
768
+ * attempt budget is exhausted (caller should then fail terminally).
769
+ */
770
+ private _rescheduleRecoveryAfterStableTimeout;
771
+ /**
772
+ * Resolve the stream id for a recovery turn so the give-up terminalization
773
+ * can surface whatever partial the turn produced. Prefers the durable stream
774
+ * row keyed by the recovery-root request id; falls back to the live active
775
+ * stream. Returns `""` when neither is available.
776
+ */
777
+ private _resolveRecoveryStreamId;
778
+ /**
779
+ * Terminalize a recovery turn that has run out of stable-state-timeout retry
780
+ * budget — or whose incident record has vanished — by routing through the
781
+ * SAME `_exhaustChatRecovery` path as deploy-recovery exhaustion. It fires
782
+ * `onExhausted`, emits `chat:recovery:exhausted`, and delivers the configured
783
+ * `terminalMessage`.
784
+ *
785
+ * This replaces the older give-up that only set the incident to `failed`,
786
+ * which bypassed `_exhaustChatRecovery` entirely — so an app relying on
787
+ * `onExhausted` for the terminal banner regressed to an eternal spinner when
788
+ * recovery gave up under extreme churn. Shared by `_chatRecoveryRetry` and
789
+ * `_chatRecoveryContinue`; mirrors the same helper in `@cloudflare/think`.
790
+ *
791
+ * Exactly-once terminalization here rests SOLELY on the
792
+ * `stored?.status === "exhausted"` re-entry guard below — unlike
793
+ * `@cloudflare/think`, `@cloudflare/ai-chat` has no durable-submission layer
794
+ * to short-circuit a duplicate alarm earlier. The sealed incident is
795
+ * re-persisted even when the record was found missing, so a swept record is
796
+ * re-armed for the guard on the next alarm.
797
+ *
798
+ * Two residual at-least-once edges, both deliberately accepted as "deliver a
799
+ * second banner" ≫ "silently drop the turn":
800
+ * • No `incidentId` at all in the payload (only reachable via a direct/test
801
+ * invocation — every production scheduler carries one): the synthesized
802
+ * incident can't be persisted (no key), so the guard can't arm.
803
+ * • The record is swept AGAIN between two alarms (the guard re-persists on
804
+ * the first, so this needs a second independent sweep) — vanishingly
805
+ * unlikely.
806
+ */
807
+ private _exhaustRecoveryAfterStableTimeout;
808
+ private _shouldRetryRecoveredPreStreamTurn;
809
+ _chatRecoveryRetry(data?: ChatRecoveryRetryData): Promise<void>;
633
810
  /**
634
811
  * Extract partial text and parts from stored stream chunks.
635
812
  */
@@ -807,12 +984,15 @@ declare class AIChatAgent<
807
984
  export {
808
985
  AIChatAgent,
809
986
  ChatMessage,
987
+ type ChatRecoveryConfig,
810
988
  type ChatRecoveryContext,
989
+ type ChatRecoveryExhaustedContext,
811
990
  type ChatRecoveryOptions,
812
991
  type ChatResponseResult,
813
992
  type ClientToolSchema,
814
993
  type MessageConcurrency,
815
994
  OnChatMessageOptions,
995
+ type ResolvedChatRecoveryConfig,
816
996
  type SaveMessagesOptions,
817
997
  type SaveMessagesResult,
818
998
  createToolsFromClientSchemas