@cloudflare/ai-chat 0.2.6 → 0.3.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/README.md CHANGED
@@ -200,6 +200,62 @@ Disable with `resume: false`:
200
200
  const { messages } = useAgentChat({ agent, resume: false });
201
201
  ```
202
202
 
203
+ ## Overlapping Messages
204
+
205
+ When users submit a new message while another turn is still active, `AIChatAgent`
206
+ can queue, collapse, or drop the overlap server-side:
207
+
208
+ ```typescript
209
+ export class ChatAgent extends AIChatAgent {
210
+ messageConcurrency = "latest";
211
+
212
+ async onChatMessage() {
213
+ // ...
214
+ }
215
+ }
216
+ ```
217
+
218
+ Available strategies:
219
+
220
+ - `"queue"` (default) — process every submit in order
221
+ - `"latest"` — keep only the newest overlapping submit and skip any older queued overlap turns
222
+ - `"merge"` — queue overlapping submits, then collapse their queued user messages into one combined follow-up user turn
223
+ - `"drop"` — ignore overlapping submits
224
+ - `{ strategy: "debounce", debounceMs: 750 }` — wait for a quiet window, then run only the latest submit
225
+
226
+ **Choosing a strategy:** Use `"latest"` for focused assistants where the user
227
+ can correct themselves mid-stream. Use `"queue"` or `"merge"` for messaging
228
+ apps where every message matters. Use `"drop"` to prevent double-sends. Use
229
+ `"debounce"` when users send bursts of short messages.
230
+
231
+ **What the user sees:** With `"queue"`, every message gets its own response.
232
+ With `"latest"`, all messages appear but only the last overlapping one gets a
233
+ response. With `"merge"`, overlapping messages are collapsed into one. With
234
+ `"drop"`, the overlapping message briefly appears then disappears (rollback).
235
+
236
+ This setting only affects overlapping `sendMessage()` submits. Regenerate,
237
+ tool continuations, approvals, and programmatic `saveMessages()` calls keep the
238
+ existing serialized behavior. When `debounceMs` is missing or invalid,
239
+ `AIChatAgent` falls back to the default `750` ms window.
240
+
241
+ Pass a function to `saveMessages()` to derive from the latest transcript when
242
+ the turn actually starts — useful for schedule callbacks and webhook handlers
243
+ where messages may have changed since the call was made:
244
+
245
+ ```typescript
246
+ await this.saveMessages((messages) => [
247
+ ...messages,
248
+ {
249
+ id: crypto.randomUUID(),
250
+ role: "user",
251
+ parts: [{ type: "text", text: "Scheduled follow-up" }]
252
+ }
253
+ ]);
254
+ ```
255
+
256
+ `saveMessages()` returns `{ requestId, status }` — check `status` to detect
257
+ whether the turn was skipped (e.g. because the chat was cleared while queued).
258
+
203
259
  ## Storage Management
204
260
 
205
261
  ### Limiting stored messages
@@ -281,16 +337,18 @@ async onChatMessage(onFinish, options) {
281
337
 
282
338
  Extends `Agent` from the `agents` package.
283
339
 
284
- | Property / Method | Type | Description |
285
- | ------------------------------------ | --------------------- | ------------------------------------------------------------------------------- |
286
- | `messages` | `UIMessage[]` | Current conversation messages (loaded from SQLite) |
287
- | `maxPersistedMessages` | `number \| undefined` | Max messages to keep in SQLite. Default: unlimited |
288
- | `onChatMessage(onFinish?, options?)` | Override | Handle incoming chat messages. Return a `Response`. `onFinish` is optional. |
289
- | `persistMessages(messages)` | `Promise<void>` | Manually persist messages (usually automatic) |
290
- | `saveMessages(messages)` | `Promise<void>` | Persist messages and trigger `onChatMessage` |
291
- | `waitUntilStable()` | `Promise<boolean>` | Protected helper to wait until the conversation is fully stable |
292
- | `resetTurnState()` | `void` | Protected helper to abort the active turn and invalidate queued continuations |
293
- | `hasPendingInteraction()` | `boolean` | Protected helper to detect pending tool input or approval in assistant messages |
340
+ | Property / Method | Type | Description |
341
+ | ------------------------------------ | ----------------------------- | ------------------------------------------------------------------------------------------------- |
342
+ | `messages` | `UIMessage[]` | Current conversation messages (loaded from SQLite) |
343
+ | `maxPersistedMessages` | `number \| undefined` | Max messages to keep in SQLite. Default: unlimited |
344
+ | `messageConcurrency` | `MessageConcurrency` | Concurrency strategy for `sendMessage()` submits. Default: `"queue"` |
345
+ | `onChatMessage(onFinish?, options?)` | Override | Handle incoming chat messages. Return a `Response`. `onFinish` is optional. |
346
+ | `onChatResponse(result)` | Override | Called after a chat turn completes. `result` has `message`, `requestId`, `status`, `continuation` |
347
+ | `persistMessages(messages)` | `Promise<void>` | Manually persist messages (usually automatic) |
348
+ | `saveMessages(messages)` | `Promise<SaveMessagesResult>` | Persist messages and trigger `onChatMessage`. Accepts array or function. |
349
+ | `waitUntilStable()` | `Promise<boolean>` | Protected helper to wait until the conversation is fully stable |
350
+ | `resetTurnState()` | `void` | Protected helper to abort the active turn and invalidate queued continuations |
351
+ | `hasPendingInteraction()` | `boolean` | Protected helper to detect pending tool input or approval in assistant messages |
294
352
 
295
353
  ### `useAgentChat(options)`
296
354
 
@@ -1,4 +1,4 @@
1
- import { t as AIChatAgent } from "../index-C2k3fmRr.js";
1
+ import { t as AIChatAgent } from "../index-BZiT3pOq.js";
2
2
 
3
3
  //#region src/experimental/forever.d.ts
4
4
  declare function withDurableChat<TBase extends typeof AIChatAgent>(Base: TBase): TBase;
@@ -150,6 +150,28 @@ type ClientToolSchema = {
150
150
  description?: Tool["description"] /** JSON Schema defining the tool's input parameters */;
151
151
  parameters?: JSONSchema7;
152
152
  };
153
+ type MessageConcurrency =
154
+ | "queue"
155
+ | "latest"
156
+ | "merge"
157
+ | "drop"
158
+ | {
159
+ strategy: "debounce";
160
+ debounceMs?: number;
161
+ };
162
+ /**
163
+ * Result passed to the `onChatResponse` lifecycle hook after a chat turn completes.
164
+ */
165
+ type ChatResponseResult = {
166
+ /** The finalized assistant message from this turn. */ message: UIMessage /** The request ID associated with this turn. */;
167
+ requestId: string /** Whether this turn was a continuation of a previous assistant turn. */;
168
+ continuation: boolean /** How the turn ended. */;
169
+ status:
170
+ | "completed"
171
+ | "error"
172
+ | "aborted" /** Error message when `status` is `"error"`. */;
173
+ error?: string;
174
+ };
153
175
  /**
154
176
  * Options passed to the onChatMessage handler.
155
177
  */
@@ -191,6 +213,13 @@ type OnChatMessageOptions = {
191
213
  */
192
214
  body?: Record<string, unknown>;
193
215
  };
216
+ /**
217
+ * Result returned by `saveMessages()`.
218
+ */
219
+ type SaveMessagesResult = {
220
+ /** Server-generated request ID for the chat turn. */ requestId: string /** Whether the turn ran or was skipped (e.g. because the chat was cleared). */;
221
+ status: "completed" | "skipped";
222
+ };
194
223
  /**
195
224
  * Converts client tool schemas to AI SDK tool format.
196
225
  *
@@ -241,6 +270,19 @@ declare class AIChatAgent<
241
270
  * @internal
242
271
  */
243
272
  private _streamingMessage;
273
+ /**
274
+ * Queued by `_reply` so the hook can fire after the turn lock releases.
275
+ * Uses an array to avoid losing results when multiple turns complete
276
+ * during a single `onChatResponse` call.
277
+ * @internal
278
+ */
279
+ private _pendingChatResponseResults;
280
+ /**
281
+ * Re-entrancy guard: true while `onChatResponse` is executing.
282
+ * Prevents recursive hook calls when the hook triggers `saveMessages`.
283
+ * @internal
284
+ */
285
+ private _insideResponseHook;
244
286
  /**
245
287
  * Resolves when the current pending client-tool interaction (tool result or
246
288
  * approval) has been written to state. Set when an apply promise is created,
@@ -271,6 +313,18 @@ declare class AIChatAgent<
271
313
  * preventing stale continuations from running after the user clears the chat.
272
314
  */
273
315
  private _chatEpoch;
316
+ /** Number of active or queued chat turns per chat epoch. */
317
+ private _queuedChatTurnCountsByEpoch;
318
+ /** First queued overlap message index for merge strategy, keyed by epoch. */
319
+ private _mergeQueuedUserStartIndexByEpoch;
320
+ /** Monotonic sequence for overlapping submit-message requests. */
321
+ private _submitSequence;
322
+ /** Latest overlapping submit-message sequence kept for latest/debounce. */
323
+ private _latestOverlappingSubmitSequence;
324
+ /** Active debounce timer handle, cleared on resetTurnState. */
325
+ private _activeDebounceTimer;
326
+ /** Resolve callback for the active debounce promise. */
327
+ private _activeDebounceResolve;
274
328
  /**
275
329
  * Set of connection IDs that are pending stream resume.
276
330
  * These connections have received CF_AGENT_STREAM_RESUMING but haven't sent ACK yet.
@@ -342,6 +396,8 @@ declare class AIChatAgent<
342
396
  * into a single server continuation turn.
343
397
  */
344
398
  private static AUTO_CONTINUATION_COALESCE_MS;
399
+ /** Default wait for trailing-edge debounced overlapping submits. */
400
+ private static MESSAGE_DEBOUNCE_MS;
345
401
  /** Measure UTF-8 byte length of a string (accurate for SQLite row limits). */
346
402
  private static _byteLength;
347
403
  /**
@@ -361,6 +417,24 @@ declare class AIChatAgent<
361
417
  * ```
362
418
  */
363
419
  maxPersistedMessages: number | undefined;
420
+ /**
421
+ * Controls how overlapping user submit requests behave while another chat
422
+ * turn is already active or queued.
423
+ *
424
+ * - `"queue"` (default) — queue every submit and process them in order.
425
+ * - `"latest"` — keep only the latest overlapping submit; superseded submits
426
+ * still persist their user messages, but do not start their own model turn.
427
+ * - `"merge"` — queue overlapping submits, then collapse their trailing user
428
+ * messages into one combined user turn before the latest queued turn runs.
429
+ * - `"drop"` — ignore overlapping submits entirely.
430
+ * - `{ strategy: "debounce" }` — trailing-edge latest with a quiet window.
431
+ *
432
+ * This setting only applies to `sendMessage()` / `trigger: "submit-message"`
433
+ * requests. Regenerations, tool continuations, approvals, clears, and
434
+ * programmatic `saveMessages()` calls keep their existing serialized
435
+ * behavior.
436
+ */
437
+ messageConcurrency: MessageConcurrency;
364
438
  /**
365
439
  * When enabled, waits for all MCP server connections to be ready before
366
440
  * calling `onChatMessage`. This prevents the race condition where
@@ -461,6 +535,22 @@ declare class AIChatAgent<
461
535
  private _tryCatchChat;
462
536
  private isChatTurnActive;
463
537
  private waitForIdle;
538
+ private _normalizeMessageConcurrency;
539
+ private _getSubmitConcurrencyDecision;
540
+ private _isSupersededSubmit;
541
+ private _waitForTimestamp;
542
+ private _cancelActiveDebounce;
543
+ private _mergeQueuedUserMessages;
544
+ private _getMergedQueuedUserMessages;
545
+ private static _mergeUserMessages;
546
+ private static _mergeMessageParts;
547
+ private static _cloneMessageParts;
548
+ private static _appendMergedText;
549
+ private _setRequestContext;
550
+ private _messagesForClientSync;
551
+ private _sendDirectMessage;
552
+ private _completeSkippedRequest;
553
+ private _rollbackDroppedSubmit;
464
554
  /** `true` when an assistant message is waiting on a client tool result or approval. */
465
555
  protected hasPendingInteraction(): boolean;
466
556
  /**
@@ -489,6 +579,7 @@ declare class AIChatAgent<
489
579
  private _enqueueAutoContinuation;
490
580
  private _awaitPendingAutoContinuationPrerequisite;
491
581
  private _queueAutoContinuation;
582
+ private _runProgrammaticChatTurn;
492
583
  /**
493
584
  * Handle incoming chat messages and generate a response
494
585
  * @param onFinish Callback to be called when the response is finished
@@ -499,6 +590,33 @@ declare class AIChatAgent<
499
590
  onFinish: StreamTextOnFinishCallback<ToolSet>,
500
591
  options?: OnChatMessageOptions
501
592
  ): Promise<Response | undefined>;
593
+ /**
594
+ * Called after a chat turn completes and the assistant message has been
595
+ * persisted. The turn lock is released before this hook runs, so it is
596
+ * safe to call `saveMessages` from inside.
597
+ *
598
+ * Fires for all turn completion paths: WebSocket chat requests,
599
+ * `saveMessages`, and auto-continuation.
600
+ *
601
+ * Responses triggered from inside `onChatResponse` (e.g. via `saveMessages`)
602
+ * do not fire `onChatResponse` recursively.
603
+ *
604
+ * The default implementation is a no-op.
605
+ *
606
+ * @param result - Information about the completed turn
607
+ *
608
+ * @example
609
+ * ```ts
610
+ * class MyAgent extends AIChatAgent<Env> {
611
+ * protected async onChatResponse(result: ChatResponseResult) {
612
+ * if (result.status === "completed") {
613
+ * this.broadcast(JSON.stringify({ streaming: false }));
614
+ * }
615
+ * }
616
+ * }
617
+ * ```
618
+ */
619
+ protected onChatResponse(_result: ChatResponseResult): void | Promise<void>;
502
620
  /**
503
621
  * Override this method to apply custom transformations to messages before
504
622
  * they are persisted to storage. This hook runs **after** the built-in
@@ -532,10 +650,29 @@ declare class AIChatAgent<
532
650
  */
533
651
  protected sanitizeMessageForPersistence(message: UIMessage): UIMessage;
534
652
  /**
535
- * Save messages on the server side
536
- * @param messages Chat messages to save
653
+ * Persist messages and trigger `onChatMessage()` for a new response.
654
+ *
655
+ * Waits for any active chat turn to finish before starting, so scheduled
656
+ * or programmatic messages never overlap an in-flight stream.
657
+ *
658
+ * Pass a function to derive the next message list from the latest
659
+ * persisted `this.messages` when the turn actually starts. This avoids
660
+ * stale baselines when multiple `saveMessages()` calls queue up behind
661
+ * active work:
662
+ *
663
+ * ```ts
664
+ * await this.saveMessages((messages) => [...messages, syntheticMessage]);
665
+ * ```
666
+ *
667
+ * Returns `{ requestId, status }` so callers can detect whether the turn
668
+ * ran (`"completed"`) or was skipped because the chat was cleared
669
+ * (`"skipped"`).
537
670
  */
538
- saveMessages(messages: UIMessage[]): Promise<void>;
671
+ saveMessages(
672
+ messages:
673
+ | UIMessage[]
674
+ | ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>)
675
+ ): Promise<SaveMessagesResult>;
539
676
  persistMessages(
540
677
  messages: UIMessage[],
541
678
  excludeBroadcastIds?: string[],
@@ -753,9 +890,12 @@ declare class AIChatAgent<
753
890
  }
754
891
  //#endregion
755
892
  export {
756
- createToolsFromClientSchemas as i,
757
- ClientToolSchema as n,
758
- OnChatMessageOptions as r,
893
+ OnChatMessageOptions as a,
894
+ MessageConcurrency as i,
895
+ ChatResponseResult as n,
896
+ SaveMessagesResult as o,
897
+ ClientToolSchema as r,
898
+ createToolsFromClientSchemas as s,
759
899
  AIChatAgent as t
760
900
  };
761
- //# sourceMappingURL=index-C2k3fmRr.d.ts.map
901
+ //# sourceMappingURL=index-BZiT3pOq.d.ts.map
package/dist/index.d.ts CHANGED
@@ -1,12 +1,18 @@
1
1
  import {
2
- i as createToolsFromClientSchemas,
3
- n as ClientToolSchema,
4
- r as OnChatMessageOptions,
2
+ a as OnChatMessageOptions,
3
+ i as MessageConcurrency,
4
+ n as ChatResponseResult,
5
+ o as SaveMessagesResult,
6
+ r as ClientToolSchema,
7
+ s as createToolsFromClientSchemas,
5
8
  t as AIChatAgent
6
- } from "./index-C2k3fmRr.js";
9
+ } from "./index-BZiT3pOq.js";
7
10
  export {
8
11
  AIChatAgent,
12
+ ChatResponseResult,
9
13
  ClientToolSchema,
14
+ MessageConcurrency,
10
15
  OnChatMessageOptions,
16
+ SaveMessagesResult,
11
17
  createToolsFromClientSchemas
12
18
  };