@cloudflare/ai-chat 0.3.2 → 0.4.1

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,13 +1,38 @@
1
- import { Agent, AgentContext } from "agents";
1
+ import { Agent, AgentContext, FiberRecoveryContext } from "agents";
2
2
  import {
3
3
  ClientToolSchema,
4
4
  ClientToolSchema as ClientToolSchema$1,
5
+ MessagePart,
5
6
  ResumableStream,
6
7
  createToolsFromClientSchemas
7
8
  } from "agents/chat";
8
9
  import { StreamTextOnFinishCallback, ToolSet, UIMessage } from "ai";
9
10
 
10
11
  //#region src/index.d.ts
12
+ /**
13
+ * Context passed to `onChatRecovery` when an interrupted chat stream
14
+ * is detected after DO restart.
15
+ */
16
+ type ChatRecoveryContext = {
17
+ /** Stream ID from the interrupted stream. */ streamId: string /** Request ID from the interrupted stream. */;
18
+ requestId: string /** Partial text extracted from stored chunks. */;
19
+ partialText: string /** Partial message parts reconstructed from chunks. */;
20
+ partialParts: MessagePart[] /** Checkpoint data from `this.stash()` during the interrupted stream. */;
21
+ recoveryData: unknown | null /** Current persisted messages. */;
22
+ messages: UIMessage[] /** Custom body from the last chat request. */;
23
+ lastBody?: Record<
24
+ string,
25
+ unknown
26
+ > /** Client tool schemas from the last chat request. */;
27
+ lastClientTools?: ClientToolSchema$1[];
28
+ };
29
+ /**
30
+ * Options returned from `onChatRecovery` to control recovery behavior.
31
+ */
32
+ type ChatRecoveryOptions = {
33
+ /** Save the partial response from stored chunks. Default: true. */ persist?: boolean /** Schedule a continuation via continueLastTurn(). Default: true. */;
34
+ continue?: boolean;
35
+ };
11
36
  type MessageConcurrency =
12
37
  | "queue"
13
38
  | "latest"
@@ -70,6 +95,14 @@ type OnChatMessageOptions = {
70
95
  * chat is cleared via `CF_AGENT_CHAT_CLEAR`.
71
96
  */
72
97
  body?: Record<string, unknown>;
98
+ /**
99
+ * Whether this turn is a continuation of a previous assistant message
100
+ * (auto-continue after tool result, `continueLastTurn`, or recovery).
101
+ *
102
+ * Use this to adjust system prompts, select different models, skip
103
+ * expensive context assembly, or log differently for continuations.
104
+ */
105
+ continuation?: boolean;
73
106
  };
74
107
  /**
75
108
  * Result returned by `saveMessages()`.
@@ -87,10 +120,10 @@ declare class AIChatAgent<
87
120
  State = unknown
88
121
  > extends Agent<Env, State> {
89
122
  /**
90
- * Map of message `id`s to `AbortController`s
91
- * useful to propagate request cancellation signals for any external calls made by the agent
123
+ * Registry of per-request AbortControllers.
124
+ * Used to propagate cancellation signals for any external calls made by the agent.
92
125
  */
93
- private _chatMessageAbortControllers;
126
+ private _abortRegistry;
94
127
  /**
95
128
  * Resumable stream manager -- handles chunk buffering, persistence, and replay.
96
129
  * @internal Protected for testing purposes.
@@ -133,12 +166,26 @@ declare class AIChatAgent<
133
166
  * generation-based invalidation on clear, and active-request tracking.
134
167
  */
135
168
  private _turnQueue;
169
+ /**
170
+ * When true, chat turns are wrapped in `runFiber` for durable execution.
171
+ * Enables `onChatRecovery` hook and `this.stash()` during streaming.
172
+ * Set to `true` in subclasses to enable durable streaming.
173
+ */
174
+ unstable_chatRecovery: boolean;
136
175
  /** First queued overlap message index for merge strategy, keyed by epoch. */
137
176
  private _mergeQueuedUserStartIndexByEpoch;
138
177
  /** Monotonic sequence for overlapping submit-message requests. */
139
178
  private _submitSequence;
140
179
  /** Latest overlapping submit-message sequence kept for latest/debounce. */
141
180
  private _latestOverlappingSubmitSequence;
181
+ /**
182
+ * Tracks requests that have passed concurrency decision but haven't
183
+ * yet been enqueued into `_turnQueue`. Bridges the gap caused by
184
+ * `await persistMessages()` between the decision and the enqueue,
185
+ * preventing a race where a subsequent message sees `queuedCount()=0`
186
+ * and skips concurrency handling.
187
+ */
188
+ private _pendingEnqueueCount;
142
189
  /** Active debounce timer handle, cleared on resetTurnState. */
143
190
  private _activeDebounceTimer;
144
191
  /** Resolve callback for the active debounce promise. */
@@ -160,13 +207,13 @@ declare class AIChatAgent<
160
207
  * Stored so they can be passed to onChatMessage during tool continuations.
161
208
  * @internal
162
209
  */
163
- private _lastClientTools;
210
+ protected _lastClientTools: ClientToolSchema$1[] | undefined;
164
211
  /**
165
212
  * Custom body data from the most recent chat request.
166
213
  * Stored so it can be passed to onChatMessage during tool continuations.
167
214
  * @internal
168
215
  */
169
- private _lastBody;
216
+ protected _lastBody: Record<string, unknown> | undefined;
170
217
  /**
171
218
  * Cache of last-persisted JSON for each message ID.
172
219
  * Used for incremental persistence: skip SQL writes for unchanged messages.
@@ -288,7 +335,7 @@ declare class AIChatAgent<
288
335
  * message parts, then persists the result so it survives further refreshes.
289
336
  * @internal
290
337
  */
291
- private _persistOrphanedStream;
338
+ protected _persistOrphanedStream(streamId: string): void;
292
339
  /**
293
340
  * Restore _lastBody and _lastClientTools from SQLite.
294
341
  * Called in the constructor so these values survive DO hibernation.
@@ -453,6 +500,53 @@ declare class AIChatAgent<
453
500
  | UIMessage[]
454
501
  | ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>)
455
502
  ): Promise<SaveMessagesResult>;
503
+ /**
504
+ * Trigger a continuation of the last assistant message without inserting
505
+ * a new user message. The LLM sees the full conversation (including the
506
+ * partial assistant response) and generates a continuation that appends
507
+ * to the same message.
508
+ *
509
+ * This uses `continuation: true` in `_reply`, which clones the last
510
+ * assistant message and appends new parts to it — the same mechanism
511
+ * used by tool auto-continuation.
512
+ *
513
+ * Returns early if there is no assistant message to continue from.
514
+ */
515
+ protected continueLastTurn(
516
+ body?: Record<string, unknown>
517
+ ): Promise<SaveMessagesResult>;
518
+ /**
519
+ * Context passed to `onChatRecovery` when an interrupted chat stream
520
+ * is detected after DO restart.
521
+ */
522
+ static readonly CHAT_FIBER_NAME = "__cf_internal_chat_turn";
523
+ /**
524
+ * Intercept internal chat fibers before they reach the user's
525
+ * `onFiberRecovered` hook. Maps to `onChatRecovery`.
526
+ * @internal
527
+ */
528
+ protected _handleInternalFiberRecovery(
529
+ ctx: FiberRecoveryContext
530
+ ): Promise<boolean>;
531
+ /**
532
+ * Called when an interrupted chat stream is detected after restart.
533
+ * Return options to control recovery:
534
+ *
535
+ * - `{}` (default): persist partial response + schedule continuation
536
+ * - `{ continue: false }`: persist but don't continue
537
+ * - `{ persist: false, continue: false }`: handle everything yourself
538
+ *
539
+ * `ctx.recoveryData` contains any data checkpointed via `this.stash()`
540
+ * during streaming (e.g., OpenAI `responseId`).
541
+ */
542
+ protected onChatRecovery(
543
+ _ctx: ChatRecoveryContext
544
+ ): Promise<ChatRecoveryOptions>;
545
+ _chatRecoveryContinue(data?: { targetAssistantId?: string }): Promise<void>;
546
+ /**
547
+ * Extract partial text and parts from stored stream chunks.
548
+ */
549
+ private _getPartialStreamText;
456
550
  persistMessages(
457
551
  messages: UIMessage[],
458
552
  excludeBroadcastIds?: string[],
@@ -595,25 +689,6 @@ declare class AIChatAgent<
595
689
  */
596
690
  private _applyToolApproval;
597
691
  private _reply;
598
- /**
599
- * For the given message id, look up its associated AbortController
600
- * If the AbortController does not exist, create and store one in memory
601
- *
602
- * returns the AbortSignal associated with the AbortController
603
- */
604
- private _getAbortSignal;
605
- /**
606
- * Remove an abort controller from the cache of pending message responses
607
- */
608
- private _removeAbortController;
609
- /**
610
- * Propagate an abort signal for any requests associated with the given message id
611
- */
612
- private _cancelChatRequest;
613
- /**
614
- * Abort all pending requests and clear the cache of AbortControllers
615
- */
616
- private _destroyAbortControllers;
617
692
  /**
618
693
  * When the DO is destroyed, cancel all pending requests and clean up resources
619
694
  */
@@ -622,6 +697,8 @@ declare class AIChatAgent<
622
697
  //#endregion
623
698
  export {
624
699
  AIChatAgent,
700
+ ChatRecoveryContext,
701
+ ChatRecoveryOptions,
625
702
  ChatResponseResult,
626
703
  type ClientToolSchema,
627
704
  MessageConcurrency,