@cloudflare/ai-chat 0.5.1 → 0.5.3

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
@@ -253,8 +253,25 @@ await this.saveMessages((messages) => [
253
253
  ]);
254
254
  ```
255
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).
256
+ `saveMessages()` returns `{ requestId, status }`. The `status` field is
257
+ `"completed"` when the turn ran, `"skipped"` when it was invalidated mid-flight
258
+ (e.g. by a `chat-clear`), or `"aborted"` when an external `AbortSignal` cancelled
259
+ it. Pass `options.signal` to cancel a programmatic turn from outside without
260
+ knowing the internally-generated request id:
261
+
262
+ ```typescript
263
+ const controller = new AbortController();
264
+ const result = await this.saveMessages([userMsg], {
265
+ signal: controller.signal
266
+ });
267
+ if (result.status === "aborted") {
268
+ // ...
269
+ }
270
+ ```
271
+
272
+ This is the same shape `Think.saveMessages` uses — see
273
+ [`cloudflare/agents#1406`](https://github.com/cloudflare/agents/issues/1406)
274
+ for the helper-as-sub-agent pattern that motivated the API.
258
275
 
259
276
  ## Storage Management
260
277
 
@@ -337,18 +354,18 @@ async onChatMessage(onFinish, options) {
337
354
 
338
355
  Extends `Agent` from the `agents` package.
339
356
 
340
- | Property / Method | Type | Description |
341
- | ------------------------------------ | ----------------------------- | ------------------------------------------------------------------------------------------------- |
342
- | `messages` | `ChatMessage[]` | 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 |
357
+ | Property / Method | Type | Description |
358
+ | ------------------------------------ | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
359
+ | `messages` | `ChatMessage[]` | Current conversation messages (loaded from SQLite) |
360
+ | `maxPersistedMessages` | `number \| undefined` | Max messages to keep in SQLite. Default: unlimited |
361
+ | `messageConcurrency` | `MessageConcurrency` | Concurrency strategy for `sendMessage()` submits. Default: `"queue"` |
362
+ | `onChatMessage(onFinish?, options?)` | Override | Handle incoming chat messages. Return a `Response`. `onFinish` is optional. |
363
+ | `onChatResponse(result)` | Override | Called after a chat turn completes. `result` has `message`, `requestId`, `status`, `continuation` |
364
+ | `persistMessages(messages)` | `Promise<void>` | Manually persist messages (usually automatic) |
365
+ | `saveMessages(messages, options?)` | `Promise<SaveMessagesResult>` | Persist messages and trigger `onChatMessage`. Accepts array or function. `options.signal` cancels the turn externally. |
366
+ | `waitUntilStable()` | `Promise<boolean>` | Protected helper to wait until the conversation is fully stable |
367
+ | `resetTurnState()` | `void` | Protected helper to abort the active turn and invalidate queued continuations |
368
+ | `hasPendingInteraction()` | `boolean` | Protected helper to detect pending tool input or approval in assistant messages |
352
369
 
353
370
  ### `useAgentChat(options)`
354
371
 
package/dist/index.d.ts CHANGED
@@ -11,6 +11,8 @@ import {
11
11
  MessageConcurrency,
12
12
  MessageConcurrency as MessageConcurrency$1,
13
13
  ResumableStream,
14
+ SaveMessagesOptions,
15
+ SaveMessagesOptions as SaveMessagesOptions$1,
14
16
  SaveMessagesResult,
15
17
  SaveMessagesResult as SaveMessagesResult$1,
16
18
  createToolsFromClientSchemas
@@ -132,22 +134,8 @@ declare class AIChatAgent<
132
134
  chatRecovery: boolean;
133
135
  /** First queued overlap message index for merge strategy, keyed by epoch. */
134
136
  private _mergeQueuedUserStartIndexByEpoch;
135
- /** Monotonic sequence for overlapping submit-message requests. */
136
- private _submitSequence;
137
- /** Latest overlapping submit-message sequence kept for latest/debounce. */
138
- private _latestOverlappingSubmitSequence;
139
- /**
140
- * Tracks requests that have passed concurrency decision but haven't
141
- * yet been enqueued into `_turnQueue`. Bridges the gap caused by
142
- * `await persistMessages()` between the decision and the enqueue,
143
- * preventing a race where a subsequent message sees `queuedCount()=0`
144
- * and skips concurrency handling.
145
- */
146
- private _pendingEnqueueCount;
147
- /** Active debounce timer handle, cleared on resetTurnState. */
148
- private _activeDebounceTimer;
149
- /** Resolve callback for the active debounce promise. */
150
- private _activeDebounceResolve;
137
+ /** Shared admission policy state for overlapping submit-message requests. */
138
+ private _submitConcurrency;
151
139
  /**
152
140
  * Set of connection IDs that are pending stream resume.
153
141
  * These connections have received CF_AGENT_STREAM_RESUMING but haven't sent ACK yet.
@@ -338,11 +326,7 @@ declare class AIChatAgent<
338
326
  * `waitForIdle()` (tests, `waitUntilStable`, recovery code).
339
327
  */
340
328
  private waitForIdle;
341
- private _normalizeMessageConcurrency;
342
329
  private _getSubmitConcurrencyDecision;
343
- private _isSupersededSubmit;
344
- private _waitForTimestamp;
345
- private _cancelActiveDebounce;
346
330
  private _mergeQueuedUserMessages;
347
331
  private _getMergedQueuedUserMessages;
348
332
  private static _mergeUserMessages;
@@ -372,6 +356,34 @@ declare class AIChatAgent<
372
356
  * the built-in handler calls it automatically.
373
357
  */
374
358
  protected resetTurnState(): void;
359
+ /**
360
+ * Abort a single in-flight chat turn by request id.
361
+ *
362
+ * Equivalent to the cancel path that fires when a client sends a
363
+ * `chat-request-cancel` WebSocket message — the inference loop's
364
+ * signal aborts and the turn's `ChatResponseResult` reports
365
+ * `status: "aborted"`. No-op if no controller exists for `requestId`.
366
+ *
367
+ * Most callers don't have the request id and want
368
+ * {@link abortAllRequests} instead. Prefer
369
+ * {@link SaveMessagesOptions.signal} when driving a turn
370
+ * programmatically — it threads the abort intent in from the start
371
+ * without requiring the caller to know the id.
372
+ */
373
+ protected abortRequest(requestId: string, reason?: unknown): void;
374
+ /**
375
+ * Abort every in-flight chat turn on this agent.
376
+ *
377
+ * Aborts all controllers in the registry and clears it. Used by
378
+ * subclasses that drive single-purpose turns (e.g. an RPC-driven
379
+ * sub-agent helper that runs one turn at a time) and want a coarse
380
+ * "cancel whatever is running" handle without tracking request ids.
381
+ *
382
+ * Does NOT reset queued turns, continuation timers, or submit
383
+ * concurrency state — use {@link resetTurnState} for the full
384
+ * teardown that runs on `chat-clear`.
385
+ */
386
+ protected abortAllRequests(): void;
375
387
  private _awaitWithDeadline;
376
388
  private _messageHasPendingInteraction;
377
389
  /**
@@ -382,6 +394,12 @@ declare class AIChatAgent<
382
394
  private _enqueueAutoContinuation;
383
395
  private _awaitPendingAutoContinuationPrerequisite;
384
396
  private _queueAutoContinuation;
397
+ /**
398
+ * @returns `true` if the registry's controller for `requestId` was
399
+ * aborted during the turn (so the caller can surface
400
+ * `status: "aborted"` to the public API). Returns `false` for
401
+ * successful or errored completion.
402
+ */
385
403
  private _runProgrammaticChatTurn;
386
404
  /**
387
405
  * Handle incoming chat messages and generate a response
@@ -467,16 +485,23 @@ declare class AIChatAgent<
467
485
  * await this.saveMessages((messages) => [...messages, syntheticMessage]);
468
486
  * ```
469
487
  *
470
- * Returns `{ requestId, status }` so callers can detect whether the turn
471
- * ran (`"completed"`) or was skipped because the chat was cleared
472
- * (`"skipped"`).
488
+ * Pass `options.signal` to cancel the turn from outside without knowing
489
+ * the internally-generated request id. The signal is linked to the
490
+ * registry's controller for this turn — when it aborts, the inference
491
+ * loop's signal aborts and the result reports `status: "aborted"`.
492
+ * Pre-aborted signals short-circuit before any model work runs.
493
+ *
494
+ * Returns `{ requestId, status }` where `status` is `"completed"` when
495
+ * the turn ran, `"skipped"` when the chat was cleared, or `"aborted"`
496
+ * when an external signal cancelled it mid-stream.
473
497
  */
474
498
  saveMessages(
475
499
  messages:
476
500
  | UIMessage[]
477
501
  | ((
478
502
  currentMessages: readonly UIMessage[]
479
- ) => UIMessage[] | Promise<UIMessage[]>)
503
+ ) => UIMessage[] | Promise<UIMessage[]>),
504
+ options?: SaveMessagesOptions$1
480
505
  ): Promise<SaveMessagesResult$1>;
481
506
  /**
482
507
  * Trigger a continuation of the last assistant message without inserting
@@ -489,9 +514,13 @@ declare class AIChatAgent<
489
514
  * used by tool auto-continuation.
490
515
  *
491
516
  * Returns early if there is no assistant message to continue from.
517
+ *
518
+ * Pass `options.signal` to cancel the continuation from outside —
519
+ * matches the {@link saveMessages} contract.
492
520
  */
493
521
  protected continueLastTurn(
494
- body?: Record<string, unknown>
522
+ body?: Record<string, unknown>,
523
+ options?: SaveMessagesOptions$1
495
524
  ): Promise<SaveMessagesResult$1>;
496
525
  /**
497
526
  * Context passed to `onChatRecovery` when an interrupted chat stream
@@ -682,6 +711,7 @@ export {
682
711
  type ClientToolSchema,
683
712
  type MessageConcurrency,
684
713
  OnChatMessageOptions,
714
+ type SaveMessagesOptions,
685
715
  type SaveMessagesResult,
686
716
  createToolsFromClientSchemas
687
717
  };