@cloudflare/ai-chat 0.7.2 → 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 +36 -5
- package/dist/index.d.ts +166 -4
- package/dist/index.js +597 -67
- package/dist/index.js.map +1 -1
- package/dist/react.d.ts +10 -0
- package/dist/react.js +75 -13
- package/dist/react.js.map +1 -1
- package/dist/types.d.ts +20 -1
- package/dist/types.js +9 -0
- package/dist/types.js.map +1 -1
- package/package.json +2 -2
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,
|
|
@@ -29,12 +33,14 @@ import { StreamTextOnFinishCallback, ToolSet, UIMessage } from "ai";
|
|
|
29
33
|
type ChatRecoveryRetryData = {
|
|
30
34
|
targetUserId?: string;
|
|
31
35
|
originalRequestId?: string;
|
|
36
|
+
incidentId?: string;
|
|
32
37
|
lastBody?: Record<string, unknown> | null;
|
|
33
38
|
lastClientTools?: ClientToolSchema$1[] | null;
|
|
34
39
|
};
|
|
35
40
|
type ChatRecoveryContinueData = {
|
|
36
41
|
targetAssistantId?: string;
|
|
37
42
|
originalRequestId?: string;
|
|
43
|
+
incidentId?: string;
|
|
38
44
|
lastBody?: Record<string, unknown> | null;
|
|
39
45
|
lastClientTools?: ClientToolSchema$1[] | null;
|
|
40
46
|
};
|
|
@@ -97,6 +103,7 @@ declare class AIChatAgent<
|
|
|
97
103
|
State = unknown,
|
|
98
104
|
Props extends Record<string, unknown> = Record<string, unknown>
|
|
99
105
|
> extends Agent<Env, State, Props> {
|
|
106
|
+
private _activeChatRecoveryRootRequestId;
|
|
100
107
|
/**
|
|
101
108
|
* Registry of per-request AbortControllers.
|
|
102
109
|
* Used to propagate cancellation signals for any external calls made by the agent.
|
|
@@ -149,7 +156,7 @@ declare class AIChatAgent<
|
|
|
149
156
|
* Enables `onChatRecovery` hook and `this.stash()` during streaming.
|
|
150
157
|
* Set to `true` in subclasses to enable durable streaming.
|
|
151
158
|
*/
|
|
152
|
-
chatRecovery:
|
|
159
|
+
chatRecovery: ChatRecoveryConfig$1;
|
|
153
160
|
/** First queued overlap message index for merge strategy, keyed by epoch. */
|
|
154
161
|
private _mergeQueuedUserStartIndexByEpoch;
|
|
155
162
|
/** Shared admission policy state for overlapping submit-message requests. */
|
|
@@ -302,8 +309,17 @@ declare class AIChatAgent<
|
|
|
302
309
|
protected _startStream(requestId: string): string;
|
|
303
310
|
/** @internal Delegate to _resumableStream */
|
|
304
311
|
protected _completeStream(streamId: string): void;
|
|
305
|
-
/** @internal Delegate to _resumableStream
|
|
306
|
-
|
|
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;
|
|
307
323
|
/** @internal Delegate to _resumableStream */
|
|
308
324
|
protected _flushChunkBuffer(): void;
|
|
309
325
|
/** @internal Delegate to _resumableStream */
|
|
@@ -319,7 +335,7 @@ declare class AIChatAgent<
|
|
|
319
335
|
* message parts, then persists the result so it survives further refreshes.
|
|
320
336
|
* @internal
|
|
321
337
|
*/
|
|
322
|
-
protected _persistOrphanedStream(streamId: string): void
|
|
338
|
+
protected _persistOrphanedStream(streamId: string): Promise<void>;
|
|
323
339
|
/**
|
|
324
340
|
* Restore _lastBody and _lastClientTools from SQLite.
|
|
325
341
|
* Called in the constructor so these values survive DO hibernation.
|
|
@@ -424,6 +440,30 @@ declare class AIChatAgent<
|
|
|
424
440
|
private _runExclusiveChatTurn;
|
|
425
441
|
private _enqueueAutoContinuation;
|
|
426
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;
|
|
427
467
|
private _queueAutoContinuation;
|
|
428
468
|
/**
|
|
429
469
|
* @returns Terminal status for the turn.
|
|
@@ -538,6 +578,28 @@ declare class AIChatAgent<
|
|
|
538
578
|
}
|
|
539
579
|
): Promise<AgentToolRunInspection>;
|
|
540
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;
|
|
541
603
|
inspectAgentToolRun(runId: string): Promise<AgentToolRunInspection | null>;
|
|
542
604
|
getAgentToolChunks(
|
|
543
605
|
runId: string,
|
|
@@ -624,6 +686,60 @@ declare class AIChatAgent<
|
|
|
624
686
|
* `onFiberRecovered` hook. Maps to `onChatRecovery`.
|
|
625
687
|
* @internal
|
|
626
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;
|
|
627
743
|
protected _handleInternalFiberRecovery(
|
|
628
744
|
ctx: FiberRecoveryContext
|
|
629
745
|
): Promise<boolean>;
|
|
@@ -646,6 +762,49 @@ declare class AIChatAgent<
|
|
|
646
762
|
): Promise<ChatRecoveryOptions$1 | void>;
|
|
647
763
|
_chatRecoveryContinue(data?: ChatRecoveryContinueData): Promise<void>;
|
|
648
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;
|
|
649
808
|
private _shouldRetryRecoveredPreStreamTurn;
|
|
650
809
|
_chatRecoveryRetry(data?: ChatRecoveryRetryData): Promise<void>;
|
|
651
810
|
/**
|
|
@@ -825,12 +984,15 @@ declare class AIChatAgent<
|
|
|
825
984
|
export {
|
|
826
985
|
AIChatAgent,
|
|
827
986
|
ChatMessage,
|
|
987
|
+
type ChatRecoveryConfig,
|
|
828
988
|
type ChatRecoveryContext,
|
|
989
|
+
type ChatRecoveryExhaustedContext,
|
|
829
990
|
type ChatRecoveryOptions,
|
|
830
991
|
type ChatResponseResult,
|
|
831
992
|
type ClientToolSchema,
|
|
832
993
|
type MessageConcurrency,
|
|
833
994
|
OnChatMessageOptions,
|
|
995
|
+
type ResolvedChatRecoveryConfig,
|
|
834
996
|
type SaveMessagesOptions,
|
|
835
997
|
type SaveMessagesResult,
|
|
836
998
|
createToolsFromClientSchemas
|