@cloudflare/ai-chat 0.1.9 → 0.2.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
@@ -22,7 +22,7 @@ export class ChatAgent extends AIChatAgent {
22
22
  const workersai = createWorkersAI({ binding: this.env.AI });
23
23
 
24
24
  const result = streamText({
25
- model: workersai("@cf/zai-org/glm-4.7-flash"),
25
+ model: workersai("@cf/moonshotai/kimi-k2.5"),
26
26
  messages: await convertToModelMessages(this.messages)
27
27
  });
28
28
 
@@ -110,7 +110,7 @@ export class ChatAgent extends AIChatAgent {
110
110
  const workersai = createWorkersAI({ binding: this.env.AI });
111
111
 
112
112
  const result = streamText({
113
- model: workersai("@cf/zai-org/glm-4.7-flash"),
113
+ model: workersai("@cf/moonshotai/kimi-k2.5"),
114
114
  messages: await convertToModelMessages(this.messages),
115
115
  tools: {
116
116
  getWeather: tool({
@@ -233,7 +233,7 @@ export class ChatAgent extends AIChatAgent {
233
233
  const workersai = createWorkersAI({ binding: this.env.AI });
234
234
 
235
235
  const result = streamText({
236
- model: workersai("@cf/zai-org/glm-4.7-flash"),
236
+ model: workersai("@cf/moonshotai/kimi-k2.5"),
237
237
  messages: pruneMessages({
238
238
  messages: await convertToModelMessages(this.messages),
239
239
  reasoning: "before-last-message",
@@ -281,13 +281,16 @@ async onChatMessage(onFinish, options) {
281
281
 
282
282
  Extends `Agent` from the `agents` package.
283
283
 
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` |
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 |
291
294
 
292
295
  ### `useAgentChat(options)`
293
296
 
@@ -1,4 +1,4 @@
1
- import { t as AIChatAgent } from "../index-BLQX_nE0.js";
1
+ import { t as AIChatAgent } from "../index-B09l5oPB.js";
2
2
 
3
3
  //#region src/experimental/forever.d.ts
4
4
  declare function withDurableChat<TBase extends typeof AIChatAgent>(Base: TBase): TBase;
@@ -241,6 +241,12 @@ declare class AIChatAgent<
241
241
  * @internal
242
242
  */
243
243
  private _streamingMessage;
244
+ /**
245
+ * Resolves when the current pending client-tool interaction (tool result or
246
+ * approval) has been written to state. Set when an apply promise is created,
247
+ * cleared when it settles. Used by waitUntilStable to avoid polling.
248
+ */
249
+ private _pendingInteractionPromise;
244
250
  /**
245
251
  * Tracks the ID of a streaming message that was persisted early due to
246
252
  * a tool entering approval-requested state. When set, stream completion
@@ -249,12 +255,22 @@ declare class AIChatAgent<
249
255
  */
250
256
  private _approvalPersistedMessageId;
251
257
  /**
252
- * Promise that resolves when the current stream completes.
253
- * Used to wait for message persistence before continuing after tool results.
254
- * @internal
258
+ * Promise chain used to serialize chat turns that call `onChatMessage()` and
259
+ * stream a reply. Each new turn waits for the previous turn to finish,
260
+ * including final message persistence.
261
+ */
262
+ private _chatTurnQueue;
263
+ /**
264
+ * Request ID for the chat turn currently running inside `_chatTurnQueue`.
265
+ * Used by protected helpers that let subclasses inspect or abort the active turn.
266
+ */
267
+ private _activeChatTurnRequestId;
268
+ /**
269
+ * Monotonically increasing counter incremented on chat clear.
270
+ * Queued turns that were enqueued under an older epoch are skipped,
271
+ * preventing stale continuations from running after the user clears the chat.
255
272
  */
256
- private _streamCompletionPromise;
257
- private _streamCompletionResolve;
273
+ private _chatEpoch;
258
274
  /**
259
275
  * Set of connection IDs that are pending stream resume.
260
276
  * These connections have received CF_AGENT_STREAM_RESUMING but haven't sent ACK yet.
@@ -393,6 +409,34 @@ declare class AIChatAgent<
393
409
  private _broadcastTextEvent;
394
410
  private _loadMessagesFromDb;
395
411
  private _tryCatchChat;
412
+ private isChatTurnActive;
413
+ private waitForIdle;
414
+ /** `true` when an assistant message is waiting on a client tool result or approval. */
415
+ protected hasPendingInteraction(): boolean;
416
+ /**
417
+ * Waits until the conversation is fully stable — no active stream, no
418
+ * pending client-tool interactions, and no queued continuation turns.
419
+ *
420
+ * Returns `true` when stable. Returns `false` if `timeout` expires before
421
+ * a pending interaction resolves. Safe to call at any time; if there is
422
+ * nothing pending it returns immediately.
423
+ */
424
+ protected waitUntilStable(options?: { timeout?: number }): Promise<boolean>;
425
+ private abortActiveTurn;
426
+ /**
427
+ * Aborts the active turn and invalidates queued continuations. Call this
428
+ * when intercepting `CF_AGENT_CHAT_CLEAR` before the SDK sees the message —
429
+ * the built-in handler calls it automatically.
430
+ */
431
+ protected resetTurnState(): void;
432
+ private _awaitWithDeadline;
433
+ private _messageHasPendingInteraction;
434
+ /**
435
+ * Run a chat turn exclusively so `_reply()` never overlaps with another
436
+ * streaming turn.
437
+ */
438
+ private _runExclusiveChatTurn;
439
+ private _queueAutoContinuation;
396
440
  /**
397
441
  * Handle incoming chat messages and generate a response
398
442
  * @param onFinish Callback to be called when the response is finished
@@ -403,6 +447,38 @@ declare class AIChatAgent<
403
447
  onFinish: StreamTextOnFinishCallback<ToolSet>,
404
448
  options?: OnChatMessageOptions
405
449
  ): Promise<Response | undefined>;
450
+ /**
451
+ * Override this method to apply custom transformations to messages before
452
+ * they are persisted to storage. This hook runs **after** the built-in
453
+ * sanitization (OpenAI metadata stripping, Anthropic provider-executed tool
454
+ * payload truncation, empty reasoning part filtering).
455
+ *
456
+ * The default implementation returns the message unchanged.
457
+ *
458
+ * @param message - The pre-sanitized message about to be persisted
459
+ * @returns The transformed message to persist
460
+ *
461
+ * @example
462
+ * ```ts
463
+ * class MyAgent extends AIChatAgent<Env> {
464
+ * protected sanitizeMessageForPersistence(
465
+ * message: UIMessage
466
+ * ): UIMessage {
467
+ * return {
468
+ * ...message,
469
+ * parts: message.parts.map(part => {
470
+ * if ("output" in part && typeof part.output === "string"
471
+ * && part.output.length > 1000) {
472
+ * return { ...part, output: "[redacted]" };
473
+ * }
474
+ * return part;
475
+ * })
476
+ * };
477
+ * }
478
+ * }
479
+ * ```
480
+ */
481
+ protected sanitizeMessageForPersistence(message: UIMessage): UIMessage;
406
482
  /**
407
483
  * Save messages on the server side
408
484
  * @param messages Chat messages to save
@@ -448,10 +524,12 @@ declare class AIChatAgent<
448
524
  private _assistantMessageContentKey;
449
525
  /**
450
526
  * Resolves a message for persistence, handling tool result merging.
451
- * If the message contains tool parts with output-available state, checks if there's
452
- * an existing message with the same toolCallId that should be updated instead of
453
- * creating a duplicate. This prevents the "Duplicate item found" error from OpenAI
454
- * when client-side tool results arrive in a new request.
527
+ * If the message contains tool parts with a toolCallId that already exists
528
+ * in a server-side message with a different ID, adopts the server's ID.
529
+ * This prevents duplicate rows when the client sends messages with
530
+ * client-generated IDs (e.g. nanoid from the AI SDK) that differ from
531
+ * the server-stamped IDs. Tool call IDs are unique per conversation,
532
+ * so matching by toolCallId is safe regardless of tool state (#1094).
455
533
  *
456
534
  * @param message - The message to potentially merge
457
535
  * @returns The message with the correct ID (either original or merged)
@@ -470,19 +548,27 @@ declare class AIChatAgent<
470
548
  * Sanitizes a message for persistence by removing ephemeral provider-specific
471
549
  * data that should not be stored or sent back in subsequent requests.
472
550
  *
473
- * Two-step process:
551
+ * Pipeline:
474
552
  *
475
553
  * 1. **Strip OpenAI ephemeral fields**: The AI SDK's @ai-sdk/openai provider
476
554
  * (v2.0.x+) defaults to using OpenAI's Responses API which assigns unique
477
555
  * itemIds and reasoningEncryptedContent to message parts. When persisted
478
556
  * and sent back, OpenAI rejects duplicate itemIds.
479
557
  *
480
- * 2. **Filter truly empty reasoning parts**: After stripping, reasoning parts
558
+ * 2. **Truncate provider-executed tool payloads**: Server-side tool
559
+ * executions (e.g. Anthropic code_execution, text_editor) can produce
560
+ * 200KB+ payloads in `input` and `output`. These are truncated since the
561
+ * model has already consumed the results.
562
+ *
563
+ * 3. **Filter truly empty reasoning parts**: After stripping, reasoning parts
481
564
  * with no text and no remaining providerMetadata are removed. Parts that
482
565
  * still carry providerMetadata (e.g. Anthropic's redacted_thinking blocks
483
566
  * with providerMetadata.anthropic.redactedData) are preserved, as they
484
567
  * contain data required for round-tripping with the provider API.
485
568
  *
569
+ * 4. **User hook**: Calls the overridable `sanitizeMessageForPersistence()`
570
+ * method, allowing subclasses to apply custom transformations.
571
+ *
486
572
  * @param message - The message to sanitize
487
573
  * @returns A new message with ephemeral provider data removed
488
574
  */
@@ -492,6 +578,21 @@ declare class AIChatAgent<
492
578
  * Removes itemId and reasoningEncryptedContent while preserving other fields.
493
579
  */
494
580
  private _stripOpenAIMetadata;
581
+ /**
582
+ * Truncates large string values in `input` and `output` of tool parts that
583
+ * were executed server-side by the provider (e.g. Anthropic code_execution,
584
+ * text_editor). These payloads can be 200KB+ and are dead weight once the
585
+ * model has consumed the result.
586
+ */
587
+ private static _truncateProviderExecutedToolPayloads;
588
+ /**
589
+ * Recursively walks a value and truncates any string exceeding
590
+ * `PROVIDER_TOOL_MAX_STRING_LENGTH`, appending a size marker.
591
+ *
592
+ * The total output (content + marker) is kept within the threshold so
593
+ * re-running this function on already-truncated data is a no-op.
594
+ */
595
+ private static _truncateLargeStrings;
495
596
  /**
496
597
  * Deletes oldest messages from SQLite when the count exceeds maxPersistedMessages.
497
598
  * Called after each persist to keep storage bounded.
@@ -595,4 +696,4 @@ export {
595
696
  OnChatMessageOptions as r,
596
697
  AIChatAgent as t
597
698
  };
598
- //# sourceMappingURL=index-BLQX_nE0.d.ts.map
699
+ //# sourceMappingURL=index-B09l5oPB.d.ts.map
package/dist/index.d.ts CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  n as ClientToolSchema,
4
4
  r as OnChatMessageOptions,
5
5
  t as AIChatAgent
6
- } from "./index-BLQX_nE0.js";
6
+ } from "./index-B09l5oPB.js";
7
7
  export {
8
8
  AIChatAgent,
9
9
  ClientToolSchema,