@cloudflare/ai-chat 0.3.1 → 0.3.2

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.
@@ -1,901 +0,0 @@
1
- import {
2
- JSONSchema7,
3
- StreamTextOnFinishCallback,
4
- Tool,
5
- ToolSet,
6
- UIMessage
7
- } from "ai";
8
- import { Agent, AgentContext, Connection } from "agents";
9
-
10
- //#region src/resumable-stream.d.ts
11
- /**
12
- * Minimal SQL interface matching Agent's this.sql tagged template.
13
- * Allows ResumableStream to work with the Agent's SQLite without
14
- * depending on the full Agent class.
15
- */
16
- type SqlTaggedTemplate = {
17
- <T = Record<string, unknown>>(
18
- strings: TemplateStringsArray,
19
- ...values: (string | number | boolean | null)[]
20
- ): T[];
21
- };
22
- declare class ResumableStream {
23
- private sql;
24
- private _activeStreamId;
25
- private _activeRequestId;
26
- private _streamChunkIndex;
27
- /**
28
- * Whether the active stream was started in this instance (true) or
29
- * restored from SQLite after hibernation/restart (false). An orphaned
30
- * stream has no live LLM reader — the ReadableStream was lost when the
31
- * DO was evicted.
32
- */
33
- private _isLive;
34
- private _chunkBuffer;
35
- private _isFlushingChunks;
36
- private _lastCleanupTime;
37
- constructor(sql: SqlTaggedTemplate);
38
- get activeStreamId(): string | null;
39
- get activeRequestId(): string | null;
40
- hasActiveStream(): boolean;
41
- /**
42
- * Whether the active stream has a live LLM reader (started in this
43
- * instance) vs being restored from SQLite after hibernation (orphaned).
44
- */
45
- get isLive(): boolean;
46
- /**
47
- * Start tracking a new stream for resumable streaming.
48
- * Creates metadata entry in SQLite and sets up tracking state.
49
- * @param requestId - The unique ID of the chat request
50
- * @returns The generated stream ID
51
- */
52
- start(requestId: string): string;
53
- /**
54
- * Mark a stream as completed and flush any pending chunks.
55
- * @param streamId - The stream to mark as completed
56
- */
57
- complete(streamId: string): void;
58
- /**
59
- * Mark a stream as errored and clean up state.
60
- * @param streamId - The stream to mark as errored
61
- */
62
- markError(streamId: string): void;
63
- /** Maximum chunk body size before skipping storage (bytes). Prevents SQLite row limit crash. */
64
- private static CHUNK_MAX_BYTES;
65
- /**
66
- * Buffer a stream chunk for batch write to SQLite.
67
- * Chunks exceeding the row size limit are skipped to prevent crashes.
68
- * The chunk is still broadcast to live clients (caller handles that),
69
- * but will be missing from replay on reconnection.
70
- * @param streamId - The stream this chunk belongs to
71
- * @param body - The serialized chunk body
72
- */
73
- storeChunk(streamId: string, body: string): void;
74
- /**
75
- * Flush buffered chunks to SQLite in a single batch.
76
- * Uses a lock to prevent concurrent flush operations.
77
- */
78
- flushBuffer(): void;
79
- /**
80
- * Send stored stream chunks to a connection for replay.
81
- * Chunks are marked with replay: true so the client can batch-apply them.
82
- *
83
- * Three outcomes:
84
- * - **Live stream**: sends chunks + `replayComplete` — client flushes and
85
- * continues receiving live chunks from the LLM reader.
86
- * - **Orphaned stream** (restored from SQLite after hibernation, no reader):
87
- * sends chunks + `done` and completes the stream. The caller should
88
- * reconstruct and persist the partial message from the stored chunks.
89
- * - **Completed during replay** (defensive): sends chunks + `done`.
90
- *
91
- * @param connection - The WebSocket connection
92
- * @param requestId - The original request ID
93
- * @returns The stream ID if the stream was orphaned and finalized, null otherwise.
94
- * When non-null the caller should reconstruct the message from chunks.
95
- */
96
- replayChunks(connection: Connection, requestId: string): string | null;
97
- /**
98
- * Restore active stream state if the agent was restarted during streaming.
99
- * Validates stream freshness to avoid sending stale resume notifications.
100
- */
101
- restore(): void;
102
- /**
103
- * Clear all stream data (called on chat history clear).
104
- */
105
- clearAll(): void;
106
- /**
107
- * Drop all stream tables (called on destroy).
108
- */
109
- destroy(): void;
110
- private _maybeCleanupOldStreams;
111
- /** @internal For testing only */
112
- getStreamChunks(streamId: string): Array<{
113
- body: string;
114
- chunk_index: number;
115
- }>;
116
- /** @internal For testing only */
117
- getStreamMetadata(streamId: string): {
118
- status: string;
119
- request_id: string;
120
- } | null;
121
- /** @internal For testing only */
122
- getAllStreamMetadata(): Array<{
123
- id: string;
124
- status: string;
125
- request_id: string;
126
- created_at: number;
127
- }>;
128
- /** @internal For testing only */
129
- insertStaleStream(streamId: string, requestId: string, ageMs: number): void;
130
- }
131
- //#endregion
132
- //#region src/index.d.ts
133
- /**
134
- * Schema for a client-defined tool sent from the browser.
135
- * These tools are executed on the client, not the server.
136
- *
137
- * **For most apps**, define tools on the server with `tool()` from `"ai"` —
138
- * you get full Zod type safety, server-side execution, and simpler code.
139
- * Use `onToolCall` in `useAgentChat` for tools that need client-side execution.
140
- *
141
- * **For SDKs and platforms** where the tool surface is determined dynamically
142
- * by the embedding application at runtime, client tool schemas let the
143
- * client register tools the server does not know about at deploy time.
144
- *
145
- * Note: Uses `parameters` (JSONSchema7) rather than AI SDK's `inputSchema`
146
- * because this is the wire format. Zod schemas cannot be serialized.
147
- */
148
- type ClientToolSchema = {
149
- /** Unique name for the tool */ name: string /** Human-readable description of what the tool does */;
150
- description?: Tool["description"] /** JSON Schema defining the tool's input parameters */;
151
- parameters?: JSONSchema7;
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
- };
175
- /**
176
- * Options passed to the onChatMessage handler.
177
- */
178
- type OnChatMessageOptions = {
179
- /**
180
- * Unique ID for this chat message exchange.
181
- *
182
- * For initial user messages this is the client-generated ID from the
183
- * `CF_AGENT_USE_CHAT_REQUEST` WebSocket frame. For tool continuations
184
- * (auto-continue after client tool results or approvals) this is a
185
- * server-generated ID.
186
- */
187
- requestId: string /** AbortSignal for cancelling the request */;
188
- abortSignal?: AbortSignal;
189
- /**
190
- * Tool schemas sent from the client for dynamic tool registration.
191
- * These represent tools that will be executed on the client side.
192
- * Use `createToolsFromClientSchemas()` to convert these to AI SDK tool format.
193
- *
194
- * **For most apps**, you do not need this — define tools on the server with
195
- * `tool()` from `"ai"` and use `onToolCall` for client-side execution.
196
- *
197
- * **For SDKs and platforms** where tools are defined dynamically by the
198
- * client at runtime and the server does not know the tool surface ahead
199
- * of time, this field carries the client-provided tool schemas.
200
- */
201
- clientTools?: ClientToolSchema[];
202
- /**
203
- * Custom body data sent from the client via `prepareSendMessagesRequest`
204
- * or the AI SDK's `body` option in `sendMessage`.
205
- *
206
- * Contains all fields from the request body except `messages` and `clientTools`,
207
- * which are handled separately.
208
- *
209
- * During tool continuations (auto-continue after client tool results), this
210
- * contains the body from the most recent chat request. The value is persisted
211
- * to SQLite so it survives Durable Object hibernation. It is cleared when the
212
- * chat is cleared via `CF_AGENT_CHAT_CLEAR`.
213
- */
214
- body?: Record<string, unknown>;
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
- };
223
- /**
224
- * Converts client tool schemas to AI SDK tool format.
225
- *
226
- * These tools have no `execute` function — when the AI model calls them,
227
- * the tool call is sent back to the client for execution.
228
- *
229
- * **For most apps**, define tools on the server with `tool()` from `"ai"`
230
- * for full Zod type safety. This helper is intended for SDK/platform use
231
- * cases where the tool surface is determined dynamically by the client.
232
- *
233
- * @param clientTools - Array of tool schemas from the client
234
- * @returns Record of AI SDK tools that can be spread into your tools object
235
- *
236
- * @example
237
- * ```typescript
238
- * // In onChatMessage:
239
- * const tools = {
240
- * ...createToolsFromClientSchemas(options.clientTools),
241
- * // server-defined tools with execute:
242
- * myServerTool: tool({ ... }),
243
- * };
244
- * ```
245
- */
246
- declare function createToolsFromClientSchemas(
247
- clientTools?: ClientToolSchema[]
248
- ): ToolSet;
249
- /**
250
- * Extension of Agent with built-in chat capabilities
251
- * @template Env Environment type containing bindings
252
- */
253
- declare class AIChatAgent<
254
- Env extends Cloudflare.Env = Cloudflare.Env,
255
- State = unknown
256
- > extends Agent<Env, State> {
257
- /**
258
- * Map of message `id`s to `AbortController`s
259
- * useful to propagate request cancellation signals for any external calls made by the agent
260
- */
261
- private _chatMessageAbortControllers;
262
- /**
263
- * Resumable stream manager -- handles chunk buffering, persistence, and replay.
264
- * @internal Protected for testing purposes.
265
- */
266
- protected _resumableStream: ResumableStream;
267
- /**
268
- * The message currently being streamed. Used to apply tool results
269
- * before the message is persisted.
270
- * @internal
271
- */
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;
286
- /**
287
- * Resolves when the current pending client-tool interaction (tool result or
288
- * approval) has been written to state. Set when an apply promise is created,
289
- * cleared when it settles. Used by waitUntilStable to avoid polling.
290
- */
291
- private _pendingInteractionPromise;
292
- /**
293
- * Tracks the ID of a streaming message that was persisted early due to
294
- * a tool entering approval-requested state. When set, stream completion
295
- * updates the existing persisted message instead of appending a new one.
296
- * @internal
297
- */
298
- private _approvalPersistedMessageId;
299
- /**
300
- * Promise chain used to serialize chat turns that call `onChatMessage()` and
301
- * stream a reply. Each new turn waits for the previous turn to finish,
302
- * including final message persistence.
303
- */
304
- private _chatTurnQueue;
305
- /**
306
- * Request ID for the chat turn currently running inside `_chatTurnQueue`.
307
- * Used by protected helpers that let subclasses inspect or abort the active turn.
308
- */
309
- private _activeChatTurnRequestId;
310
- /**
311
- * Monotonically increasing counter incremented on chat clear.
312
- * Queued turns that were enqueued under an older epoch are skipped,
313
- * preventing stale continuations from running after the user clears the chat.
314
- */
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;
328
- /**
329
- * Set of connection IDs that are pending stream resume.
330
- * These connections have received CF_AGENT_STREAM_RESUMING but haven't sent ACK yet.
331
- * They should be excluded from live stream broadcasts until they ACK.
332
- * @internal
333
- */
334
- private _pendingResumeConnections;
335
- /**
336
- * Connections waiting for a stream to start after requesting resume.
337
- * Used for client-side tool auto-continuations where the originating client
338
- * asks to resume immediately after submitting tool output, before the server
339
- * has started streaming the continuation turn.
340
- */
341
- private _awaitingStreamStartConnections;
342
- /**
343
- * True while an auto-continuation turn has been queued but has not yet
344
- * started streaming. This suppresses immediate STREAM_RESUME_NONE replies
345
- * so the originating client can attach to the upcoming continuation stream.
346
- */
347
- private _pendingAutoContinuation;
348
- /**
349
- * The latest connection/context to use for a queued auto-continuation.
350
- * Multiple rapid tool results are coalesced into a single turn, so we keep
351
- * the newest values here until that turn starts.
352
- */
353
- private _pendingAutoContinuationConnection;
354
- /**
355
- * Connection that initiated the pending auto-continuation.
356
- * Only this connection should wait for the continuation stream to start.
357
- */
358
- private _pendingAutoContinuationConnectionId;
359
- private _activeAutoContinuationConnectionId;
360
- private _activeAutoContinuationRequestId;
361
- private _pendingAutoContinuationPastCoalesce;
362
- private _pendingAutoContinuationClientTools;
363
- private _pendingAutoContinuationBody;
364
- private _pendingAutoContinuationErrorPrefix;
365
- private _pendingAutoContinuationRequestId;
366
- /**
367
- * Aggregate prerequisite for a queued auto-continuation.
368
- * Each new tool result/approval extends this promise so the single queued
369
- * continuation waits for every rapid-fire apply operation to finish.
370
- */
371
- private _pendingAutoContinuationPrerequisite;
372
- private _deferredAutoContinuation;
373
- /**
374
- * Client tool schemas from the most recent chat request.
375
- * Stored so they can be passed to onChatMessage during tool continuations.
376
- * @internal
377
- */
378
- private _lastClientTools;
379
- /**
380
- * Custom body data from the most recent chat request.
381
- * Stored so it can be passed to onChatMessage during tool continuations.
382
- * @internal
383
- */
384
- private _lastBody;
385
- /**
386
- * Cache of last-persisted JSON for each message ID.
387
- * Used for incremental persistence: skip SQL writes for unchanged messages.
388
- * Lost on hibernation, repopulated from SQLite on wake.
389
- * @internal
390
- */
391
- private _persistedMessageCache;
392
- /** Maximum serialized message size before compaction (bytes). 1.8MB with headroom below SQLite's 2MB limit. */
393
- private static ROW_MAX_BYTES;
394
- /**
395
- * Small debounce window to batch adjacent client-side tool results/approvals
396
- * into a single server continuation turn.
397
- */
398
- private static AUTO_CONTINUATION_COALESCE_MS;
399
- /** Default wait for trailing-edge debounced overlapping submits. */
400
- private static MESSAGE_DEBOUNCE_MS;
401
- /** Measure UTF-8 byte length of a string (accurate for SQLite row limits). */
402
- private static _byteLength;
403
- /**
404
- * Maximum number of messages to keep in SQLite storage.
405
- * When the conversation exceeds this limit, oldest messages are deleted
406
- * after each persist. Set to `undefined` (default) for no limit.
407
- *
408
- * This controls storage only — it does not affect what's sent to the LLM.
409
- * Use `pruneMessages()` from the AI SDK in your `onChatMessage` to control
410
- * LLM context separately.
411
- *
412
- * @example
413
- * ```typescript
414
- * class MyAgent extends AIChatAgent<Env> {
415
- * maxPersistedMessages = 100; // Keep last 100 messages in storage
416
- * }
417
- * ```
418
- */
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;
438
- /**
439
- * When enabled, waits for all MCP server connections to be ready before
440
- * calling `onChatMessage`. This prevents the race condition where
441
- * `getAITools()` returns an incomplete set because connections are still
442
- * restoring after Durable Object hibernation.
443
- *
444
- * - `false` (default) — non-blocking; `onChatMessage` runs immediately.
445
- * - `true` — waits indefinitely for all connections to settle.
446
- * - `{ timeout: number }` — waits up to `timeout` milliseconds.
447
- *
448
- * For lower-level control, call `this.mcp.waitForConnections()` directly
449
- * inside your `onChatMessage` instead.
450
- *
451
- * @example
452
- * ```typescript
453
- * class MyAgent extends AIChatAgent<Env> {
454
- * waitForMcpConnections = true;
455
- * }
456
- * ```
457
- *
458
- * @example
459
- * ```typescript
460
- * class MyAgent extends AIChatAgent<Env> {
461
- * waitForMcpConnections = { timeout: 10_000 };
462
- * }
463
- * ```
464
- */
465
- waitForMcpConnections:
466
- | boolean
467
- | {
468
- timeout: number;
469
- };
470
- /** Array of chat messages for the current conversation */
471
- messages: UIMessage[];
472
- constructor(ctx: AgentContext, env: Env);
473
- private _flushAwaitingStreamStartConnections;
474
- private _mergeAutoContinuationPrerequisite;
475
- private _storeDeferredAutoContinuation;
476
- private _activateDeferredAutoContinuation;
477
- private _clearDeferredAutoContinuation;
478
- private _clearAllAutoContinuationState;
479
- private _clearPendingAutoContinuation;
480
- /**
481
- * Notify a connection about an active stream that can be resumed.
482
- * The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
483
- * @param connection - The WebSocket connection to notify
484
- */
485
- private _notifyStreamResuming;
486
- /** @internal Delegate to _resumableStream */
487
- protected get _activeStreamId(): string | null;
488
- /** @internal Delegate to _resumableStream */
489
- protected get _activeRequestId(): string | null;
490
- /** @internal Delegate to _resumableStream */
491
- protected _startStream(requestId: string): string;
492
- /** @internal Delegate to _resumableStream */
493
- protected _completeStream(streamId: string): void;
494
- /** @internal Delegate to _resumableStream */
495
- protected _storeStreamChunk(streamId: string, body: string): void;
496
- /** @internal Delegate to _resumableStream */
497
- protected _flushChunkBuffer(): void;
498
- /** @internal Delegate to _resumableStream */
499
- protected _restoreActiveStream(): void;
500
- /** @internal Delegate to _resumableStream */
501
- protected _markStreamError(streamId: string): void;
502
- /**
503
- * Reconstruct and persist a partial assistant message from an orphaned
504
- * stream's stored chunks. Called when the DO wakes from hibernation and
505
- * discovers an active stream with no live LLM reader.
506
- *
507
- * Replays each chunk body through `applyChunkToParts` to rebuild the
508
- * message parts, then persists the result so it survives further refreshes.
509
- * @internal
510
- */
511
- private _persistOrphanedStream;
512
- /**
513
- * Restore _lastBody and _lastClientTools from SQLite.
514
- * Called in the constructor so these values survive DO hibernation.
515
- * @internal
516
- */
517
- private _restoreRequestContext;
518
- /**
519
- * Persist _lastBody and _lastClientTools to SQLite so they survive hibernation.
520
- * Uses upsert (INSERT OR REPLACE) so repeated calls are safe.
521
- * @internal
522
- */
523
- private _persistRequestContext;
524
- private _broadcastChatMessage;
525
- /**
526
- * Broadcasts a text event for non-SSE responses.
527
- * This ensures plain text responses follow the AI SDK v5 stream protocol.
528
- *
529
- * @param streamId - The stream identifier for chunk storage
530
- * @param event - The text event payload (text-start, text-delta with delta, or text-end)
531
- * @param continuation - Whether this is a continuation of a previous stream
532
- */
533
- private _broadcastTextEvent;
534
- private _loadMessagesFromDb;
535
- private _tryCatchChat;
536
- private isChatTurnActive;
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;
554
- /** `true` when an assistant message is waiting on a client tool result or approval. */
555
- protected hasPendingInteraction(): boolean;
556
- /**
557
- * Waits until the conversation is fully stable — no active stream, no
558
- * pending client-tool interactions, and no queued continuation turns.
559
- *
560
- * Returns `true` when stable. Returns `false` if `timeout` expires before
561
- * a pending interaction resolves. Safe to call at any time; if there is
562
- * nothing pending it returns immediately.
563
- */
564
- protected waitUntilStable(options?: { timeout?: number }): Promise<boolean>;
565
- private abortActiveTurn;
566
- /**
567
- * Aborts the active turn and invalidates queued continuations. Call this
568
- * when intercepting `CF_AGENT_CHAT_CLEAR` before the SDK sees the message —
569
- * the built-in handler calls it automatically.
570
- */
571
- protected resetTurnState(): void;
572
- private _awaitWithDeadline;
573
- private _messageHasPendingInteraction;
574
- /**
575
- * Run a chat turn exclusively so `_reply()` never overlaps with another
576
- * streaming turn.
577
- */
578
- private _runExclusiveChatTurn;
579
- private _enqueueAutoContinuation;
580
- private _awaitPendingAutoContinuationPrerequisite;
581
- private _queueAutoContinuation;
582
- private _runProgrammaticChatTurn;
583
- /**
584
- * Handle incoming chat messages and generate a response
585
- * @param onFinish Callback to be called when the response is finished
586
- * @param options Options including abort signal and client-defined tools
587
- * @returns Response to send to the client or undefined
588
- */
589
- onChatMessage(
590
- onFinish: StreamTextOnFinishCallback<ToolSet>,
591
- options?: OnChatMessageOptions
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>;
620
- /**
621
- * Override this method to apply custom transformations to messages before
622
- * they are persisted to storage. This hook runs **after** the built-in
623
- * sanitization (OpenAI metadata stripping, Anthropic provider-executed tool
624
- * payload truncation, empty reasoning part filtering).
625
- *
626
- * The default implementation returns the message unchanged.
627
- *
628
- * @param message - The pre-sanitized message about to be persisted
629
- * @returns The transformed message to persist
630
- *
631
- * @example
632
- * ```ts
633
- * class MyAgent extends AIChatAgent<Env> {
634
- * protected sanitizeMessageForPersistence(
635
- * message: UIMessage
636
- * ): UIMessage {
637
- * return {
638
- * ...message,
639
- * parts: message.parts.map(part => {
640
- * if ("output" in part && typeof part.output === "string"
641
- * && part.output.length > 1000) {
642
- * return { ...part, output: "[redacted]" };
643
- * }
644
- * return part;
645
- * })
646
- * };
647
- * }
648
- * }
649
- * ```
650
- */
651
- protected sanitizeMessageForPersistence(message: UIMessage): UIMessage;
652
- /**
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"`).
670
- */
671
- saveMessages(
672
- messages:
673
- | UIMessage[]
674
- | ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>)
675
- ): Promise<SaveMessagesResult>;
676
- persistMessages(
677
- messages: UIMessage[],
678
- excludeBroadcastIds?: string[],
679
- /** @internal */ options?: {
680
- _deleteStaleRows?: boolean;
681
- }
682
- ): Promise<void>;
683
- /**
684
- * Merges incoming messages with existing server state.
685
- * This preserves tool outputs that the server has (via _applyToolResult)
686
- * but the client doesn't have yet.
687
- *
688
- * @param incomingMessages - Messages from the client
689
- * @returns Messages with server's tool outputs preserved
690
- */
691
- private _mergeIncomingWithServerState;
692
- /**
693
- * Reconciles assistant message IDs between incoming client state and server state.
694
- *
695
- * The client can keep a different local ID for an assistant message than the one
696
- * persisted on the server (e.g. optimistic/local IDs). When that full history is
697
- * sent back, persisting by ID alone creates duplicate assistant rows. To prevent
698
- * this, we reuse the server ID for assistant messages that match by content,
699
- * while leaving tool-call messages to _resolveMessageForToolMerge.
700
- *
701
- * Uses a two-pass approach:
702
- * - Pass 1: resolve all exact-ID matches, claiming server indices.
703
- * - Pass 2: content-based matching for remaining non-tool assistant messages,
704
- * scanning only unclaimed server indices left-to-right.
705
- *
706
- * The two-pass design prevents exact-ID matches from advancing a cursor past
707
- * server messages that a later incoming message needs for content matching.
708
- * This fixes mismatches when two assistant messages have identical text
709
- * (e.g. "Sure", "I understand") — see #1008.
710
- */
711
- private _reconcileAssistantIdsWithServerState;
712
- private _hasToolCallPart;
713
- private _assistantMessageContentKey;
714
- /**
715
- * Resolves a message for persistence, handling tool result merging.
716
- * If the message contains tool parts with a toolCallId that already exists
717
- * in a server-side message with a different ID, adopts the server's ID.
718
- * This prevents duplicate rows when the client sends messages with
719
- * client-generated IDs (e.g. nanoid from the AI SDK) that differ from
720
- * the server-stamped IDs. Tool call IDs are unique per conversation,
721
- * so matching by toolCallId is safe regardless of tool state (#1094).
722
- *
723
- * @param message - The message to potentially merge
724
- * @returns The message with the correct ID (either original or merged)
725
- */
726
- private _resolveMessageForToolMerge;
727
- /**
728
- * Finds an existing assistant message that contains a tool part with the given toolCallId.
729
- * Used to detect when a tool result should update an existing message rather than
730
- * creating a new one.
731
- *
732
- * @param toolCallId - The tool call ID to search for
733
- * @returns The existing message if found, undefined otherwise
734
- */
735
- private _findMessageByToolCallId;
736
- private _findLastAssistantMessage;
737
- private _createStreamingAssistantMessage;
738
- /**
739
- * Sanitizes a message for persistence by removing ephemeral provider-specific
740
- * data that should not be stored or sent back in subsequent requests.
741
- *
742
- * Pipeline:
743
- *
744
- * 1. **Strip OpenAI ephemeral fields**: The AI SDK's @ai-sdk/openai provider
745
- * (v2.0.x+) defaults to using OpenAI's Responses API which assigns unique
746
- * itemIds and reasoningEncryptedContent to message parts. When persisted
747
- * and sent back, OpenAI rejects duplicate itemIds.
748
- *
749
- * 2. **Truncate provider-executed tool payloads**: Server-side tool
750
- * executions (e.g. Anthropic code_execution, text_editor) can produce
751
- * 200KB+ payloads in `input` and `output`. These are truncated since the
752
- * model has already consumed the results.
753
- *
754
- * 3. **Filter truly empty reasoning parts**: After stripping, reasoning parts
755
- * with no text and no remaining providerMetadata are removed. Parts that
756
- * still carry providerMetadata (e.g. Anthropic's redacted_thinking blocks
757
- * with providerMetadata.anthropic.redactedData) are preserved, as they
758
- * contain data required for round-tripping with the provider API.
759
- *
760
- * 4. **User hook**: Calls the overridable `sanitizeMessageForPersistence()`
761
- * method, allowing subclasses to apply custom transformations.
762
- *
763
- * @param message - The message to sanitize
764
- * @returns A new message with ephemeral provider data removed
765
- */
766
- private _sanitizeMessageForPersistence;
767
- /**
768
- * Helper to strip OpenAI-specific ephemeral fields from a metadata object.
769
- * Removes itemId and reasoningEncryptedContent while preserving other fields.
770
- */
771
- private _stripOpenAIMetadata;
772
- /**
773
- * Truncates large string values in `input` and `output` of tool parts that
774
- * were executed server-side by the provider (e.g. Anthropic code_execution,
775
- * text_editor). These payloads can be 200KB+ and are dead weight once the
776
- * model has consumed the result.
777
- *
778
- * Anthropic web tools are excluded because their outputs are replayed on
779
- * subsequent turns. Within other tool payloads, opaque encrypted fields are
780
- * always preserved verbatim.
781
- */
782
- private static _truncateProviderExecutedToolPayloads;
783
- /**
784
- * Recursively walks a value and truncates any string exceeding
785
- * `PROVIDER_TOOL_MAX_STRING_LENGTH`, appending a size marker.
786
- *
787
- * The total output (content + marker) is kept within the threshold so
788
- * re-running this function on already-truncated data is a no-op. Strings
789
- * under opaque encrypted keys are preserved verbatim.
790
- */
791
- private static _truncateLargeStrings;
792
- private static _shouldPreserveProviderToolPayload;
793
- private static _getToolNameFromPart;
794
- private static _isOpaqueReplayFieldKey;
795
- /**
796
- * Deletes oldest messages from SQLite when the count exceeds maxPersistedMessages.
797
- * Called after each persist to keep storage bounded.
798
- */
799
- private _enforceMaxPersistedMessages;
800
- /**
801
- * Enforces SQLite row size limits by compacting tool outputs and text parts
802
- * when a serialized message exceeds the safety threshold (1.8MB).
803
- *
804
- * Only fires in pathological cases (extremely large tool outputs or text).
805
- * Returns the message unchanged if it fits within limits.
806
- *
807
- * Compaction strategy:
808
- * 1. Compact tool outputs over 1KB (replace with LLM-friendly summary)
809
- * 2. If still too big, truncate text parts from oldest to newest
810
- * 3. Add metadata so clients can detect compaction
811
- *
812
- * @param message - The message to check
813
- * @returns The message, compacted if necessary
814
- */
815
- private _enforceRowSizeLimit;
816
- /**
817
- * Truncates text parts in a message to fit within the row size limit.
818
- * Truncates from the first text part forward, keeping the last text part
819
- * as intact as possible (it is usually the most relevant).
820
- */
821
- private _truncateTextParts;
822
- /**
823
- * Shared helper for finding a tool part by toolCallId and applying an update.
824
- * Handles both streaming (in-memory) and persisted (SQLite) messages.
825
- *
826
- * Checks _streamingMessage first (tool results/approvals can arrive while
827
- * the AI is still streaming), then retries persisted messages with backoff
828
- * in case streaming completes between attempts.
829
- *
830
- * @param toolCallId - The tool call ID to find
831
- * @param callerName - Name for log messages (e.g. "_applyToolResult")
832
- * @param matchStates - Which tool part states to match
833
- * @param applyUpdate - Mutation to apply to the matched part (streaming: in-place, persisted: spread)
834
- * @returns true if the update was applied, false if not found or state didn't match
835
- */
836
- private _findAndUpdateToolPart;
837
- /**
838
- * Applies a tool result to an existing assistant message.
839
- * This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.
840
- * The server is the source of truth, so we update the message here and broadcast
841
- * the update to all clients.
842
- *
843
- * @param toolCallId - The tool call ID this result is for
844
- * @param _toolName - The name of the tool (unused, kept for API compat)
845
- * @param output - The output from the tool execution
846
- * @param overrideState - Optional state override ("output-error" to signal denial/failure)
847
- * @param errorText - Error message when overrideState is "output-error"
848
- * @returns true if the result was applied, false if the message was not found
849
- */
850
- private _applyToolResult;
851
- private _streamSSEReply;
852
- private _sendPlaintextReply;
853
- /**
854
- * Applies a tool approval response from the client, updating the persisted message.
855
- * This is called when the client sends CF_AGENT_TOOL_APPROVAL for tools with needsApproval.
856
- *
857
- * - approved=true transitions to approval-responded
858
- * - approved=false transitions to output-denied so convertToModelMessages
859
- * emits a tool_result for providers (e.g. Anthropic) that require it.
860
- *
861
- * @param toolCallId - The tool call ID this approval is for
862
- * @param approved - Whether the tool execution was approved
863
- * @returns true if the approval was applied, false if the message was not found
864
- */
865
- private _applyToolApproval;
866
- private _reply;
867
- /**
868
- * For the given message id, look up its associated AbortController
869
- * If the AbortController does not exist, create and store one in memory
870
- *
871
- * returns the AbortSignal associated with the AbortController
872
- */
873
- private _getAbortSignal;
874
- /**
875
- * Remove an abort controller from the cache of pending message responses
876
- */
877
- private _removeAbortController;
878
- /**
879
- * Propagate an abort signal for any requests associated with the given message id
880
- */
881
- private _cancelChatRequest;
882
- /**
883
- * Abort all pending requests and clear the cache of AbortControllers
884
- */
885
- private _destroyAbortControllers;
886
- /**
887
- * When the DO is destroyed, cancel all pending requests and clean up resources
888
- */
889
- destroy(): Promise<void>;
890
- }
891
- //#endregion
892
- export {
893
- OnChatMessageOptions as a,
894
- MessageConcurrency as i,
895
- ChatResponseResult as n,
896
- SaveMessagesResult as o,
897
- ClientToolSchema as r,
898
- createToolsFromClientSchemas as s,
899
- AIChatAgent as t
900
- };
901
- //# sourceMappingURL=index-BZiT3pOq.d.ts.map