@cloudflare/ai-chat 0.1.9 → 0.2.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
@@ -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-BbdbMsrQ.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.
255
266
  */
256
- private _streamCompletionPromise;
257
- private _streamCompletionResolve;
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.
272
+ */
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.
@@ -262,6 +278,19 @@ declare class AIChatAgent<
262
278
  * @internal
263
279
  */
264
280
  private _pendingResumeConnections;
281
+ /**
282
+ * Connections waiting for a stream to start after requesting resume.
283
+ * Used for client-side tool auto-continuations where the client asks to
284
+ * resume immediately after submitting tool output, before the server has
285
+ * started streaming the continuation turn.
286
+ */
287
+ private _awaitingStreamStartConnections;
288
+ /**
289
+ * True while an auto-continuation turn has been queued but has not yet
290
+ * started streaming. This suppresses immediate STREAM_RESUME_NONE replies
291
+ * so clients can attach to the upcoming continuation stream.
292
+ */
293
+ private _pendingAutoContinuation;
265
294
  /**
266
295
  * Client tool schemas from the most recent chat request.
267
296
  * Stored so they can be passed to onChatMessage during tool continuations.
@@ -337,6 +366,8 @@ declare class AIChatAgent<
337
366
  /** Array of chat messages for the current conversation */
338
367
  messages: UIMessage[];
339
368
  constructor(ctx: AgentContext, env: Env);
369
+ private _flushAwaitingStreamStartConnections;
370
+ private _clearPendingAutoContinuation;
340
371
  /**
341
372
  * Notify a connection about an active stream that can be resumed.
342
373
  * The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
@@ -393,6 +424,34 @@ declare class AIChatAgent<
393
424
  private _broadcastTextEvent;
394
425
  private _loadMessagesFromDb;
395
426
  private _tryCatchChat;
427
+ private isChatTurnActive;
428
+ private waitForIdle;
429
+ /** `true` when an assistant message is waiting on a client tool result or approval. */
430
+ protected hasPendingInteraction(): boolean;
431
+ /**
432
+ * Waits until the conversation is fully stable — no active stream, no
433
+ * pending client-tool interactions, and no queued continuation turns.
434
+ *
435
+ * Returns `true` when stable. Returns `false` if `timeout` expires before
436
+ * a pending interaction resolves. Safe to call at any time; if there is
437
+ * nothing pending it returns immediately.
438
+ */
439
+ protected waitUntilStable(options?: { timeout?: number }): Promise<boolean>;
440
+ private abortActiveTurn;
441
+ /**
442
+ * Aborts the active turn and invalidates queued continuations. Call this
443
+ * when intercepting `CF_AGENT_CHAT_CLEAR` before the SDK sees the message —
444
+ * the built-in handler calls it automatically.
445
+ */
446
+ protected resetTurnState(): void;
447
+ private _awaitWithDeadline;
448
+ private _messageHasPendingInteraction;
449
+ /**
450
+ * Run a chat turn exclusively so `_reply()` never overlaps with another
451
+ * streaming turn.
452
+ */
453
+ private _runExclusiveChatTurn;
454
+ private _queueAutoContinuation;
396
455
  /**
397
456
  * Handle incoming chat messages and generate a response
398
457
  * @param onFinish Callback to be called when the response is finished
@@ -403,6 +462,38 @@ declare class AIChatAgent<
403
462
  onFinish: StreamTextOnFinishCallback<ToolSet>,
404
463
  options?: OnChatMessageOptions
405
464
  ): Promise<Response | undefined>;
465
+ /**
466
+ * Override this method to apply custom transformations to messages before
467
+ * they are persisted to storage. This hook runs **after** the built-in
468
+ * sanitization (OpenAI metadata stripping, Anthropic provider-executed tool
469
+ * payload truncation, empty reasoning part filtering).
470
+ *
471
+ * The default implementation returns the message unchanged.
472
+ *
473
+ * @param message - The pre-sanitized message about to be persisted
474
+ * @returns The transformed message to persist
475
+ *
476
+ * @example
477
+ * ```ts
478
+ * class MyAgent extends AIChatAgent<Env> {
479
+ * protected sanitizeMessageForPersistence(
480
+ * message: UIMessage
481
+ * ): UIMessage {
482
+ * return {
483
+ * ...message,
484
+ * parts: message.parts.map(part => {
485
+ * if ("output" in part && typeof part.output === "string"
486
+ * && part.output.length > 1000) {
487
+ * return { ...part, output: "[redacted]" };
488
+ * }
489
+ * return part;
490
+ * })
491
+ * };
492
+ * }
493
+ * }
494
+ * ```
495
+ */
496
+ protected sanitizeMessageForPersistence(message: UIMessage): UIMessage;
406
497
  /**
407
498
  * Save messages on the server side
408
499
  * @param messages Chat messages to save
@@ -448,10 +539,12 @@ declare class AIChatAgent<
448
539
  private _assistantMessageContentKey;
449
540
  /**
450
541
  * 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.
542
+ * If the message contains tool parts with a toolCallId that already exists
543
+ * in a server-side message with a different ID, adopts the server's ID.
544
+ * This prevents duplicate rows when the client sends messages with
545
+ * client-generated IDs (e.g. nanoid from the AI SDK) that differ from
546
+ * the server-stamped IDs. Tool call IDs are unique per conversation,
547
+ * so matching by toolCallId is safe regardless of tool state (#1094).
455
548
  *
456
549
  * @param message - The message to potentially merge
457
550
  * @returns The message with the correct ID (either original or merged)
@@ -466,23 +559,33 @@ declare class AIChatAgent<
466
559
  * @returns The existing message if found, undefined otherwise
467
560
  */
468
561
  private _findMessageByToolCallId;
562
+ private _findLastAssistantMessage;
563
+ private _createStreamingAssistantMessage;
469
564
  /**
470
565
  * Sanitizes a message for persistence by removing ephemeral provider-specific
471
566
  * data that should not be stored or sent back in subsequent requests.
472
567
  *
473
- * Two-step process:
568
+ * Pipeline:
474
569
  *
475
570
  * 1. **Strip OpenAI ephemeral fields**: The AI SDK's @ai-sdk/openai provider
476
571
  * (v2.0.x+) defaults to using OpenAI's Responses API which assigns unique
477
572
  * itemIds and reasoningEncryptedContent to message parts. When persisted
478
573
  * and sent back, OpenAI rejects duplicate itemIds.
479
574
  *
480
- * 2. **Filter truly empty reasoning parts**: After stripping, reasoning parts
575
+ * 2. **Truncate provider-executed tool payloads**: Server-side tool
576
+ * executions (e.g. Anthropic code_execution, text_editor) can produce
577
+ * 200KB+ payloads in `input` and `output`. These are truncated since the
578
+ * model has already consumed the results.
579
+ *
580
+ * 3. **Filter truly empty reasoning parts**: After stripping, reasoning parts
481
581
  * with no text and no remaining providerMetadata are removed. Parts that
482
582
  * still carry providerMetadata (e.g. Anthropic's redacted_thinking blocks
483
583
  * with providerMetadata.anthropic.redactedData) are preserved, as they
484
584
  * contain data required for round-tripping with the provider API.
485
585
  *
586
+ * 4. **User hook**: Calls the overridable `sanitizeMessageForPersistence()`
587
+ * method, allowing subclasses to apply custom transformations.
588
+ *
486
589
  * @param message - The message to sanitize
487
590
  * @returns A new message with ephemeral provider data removed
488
591
  */
@@ -492,6 +595,21 @@ declare class AIChatAgent<
492
595
  * Removes itemId and reasoningEncryptedContent while preserving other fields.
493
596
  */
494
597
  private _stripOpenAIMetadata;
598
+ /**
599
+ * Truncates large string values in `input` and `output` of tool parts that
600
+ * were executed server-side by the provider (e.g. Anthropic code_execution,
601
+ * text_editor). These payloads can be 200KB+ and are dead weight once the
602
+ * model has consumed the result.
603
+ */
604
+ private static _truncateProviderExecutedToolPayloads;
605
+ /**
606
+ * Recursively walks a value and truncates any string exceeding
607
+ * `PROVIDER_TOOL_MAX_STRING_LENGTH`, appending a size marker.
608
+ *
609
+ * The total output (content + marker) is kept within the threshold so
610
+ * re-running this function on already-truncated data is a no-op.
611
+ */
612
+ private static _truncateLargeStrings;
495
613
  /**
496
614
  * Deletes oldest messages from SQLite when the count exceeds maxPersistedMessages.
497
615
  * Called after each persist to keep storage bounded.
@@ -595,4 +713,4 @@ export {
595
713
  OnChatMessageOptions as r,
596
714
  AIChatAgent as t
597
715
  };
598
- //# sourceMappingURL=index-BLQX_nE0.d.ts.map
716
+ //# sourceMappingURL=index-BbdbMsrQ.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-BbdbMsrQ.js";
7
7
  export {
8
8
  AIChatAgent,
9
9
  ClientToolSchema,