@cloudflare/ai-chat 0.1.8 → 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.
@@ -0,0 +1,699 @@
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
+ /**
154
+ * Options passed to the onChatMessage handler.
155
+ */
156
+ type OnChatMessageOptions = {
157
+ /**
158
+ * Unique ID for this chat message exchange.
159
+ *
160
+ * For initial user messages this is the client-generated ID from the
161
+ * `CF_AGENT_USE_CHAT_REQUEST` WebSocket frame. For tool continuations
162
+ * (auto-continue after client tool results or approvals) this is a
163
+ * server-generated ID.
164
+ */
165
+ requestId: string /** AbortSignal for cancelling the request */;
166
+ abortSignal?: AbortSignal;
167
+ /**
168
+ * Tool schemas sent from the client for dynamic tool registration.
169
+ * These represent tools that will be executed on the client side.
170
+ * Use `createToolsFromClientSchemas()` to convert these to AI SDK tool format.
171
+ *
172
+ * **For most apps**, you do not need this — define tools on the server with
173
+ * `tool()` from `"ai"` and use `onToolCall` for client-side execution.
174
+ *
175
+ * **For SDKs and platforms** where tools are defined dynamically by the
176
+ * client at runtime and the server does not know the tool surface ahead
177
+ * of time, this field carries the client-provided tool schemas.
178
+ */
179
+ clientTools?: ClientToolSchema[];
180
+ /**
181
+ * Custom body data sent from the client via `prepareSendMessagesRequest`
182
+ * or the AI SDK's `body` option in `sendMessage`.
183
+ *
184
+ * Contains all fields from the request body except `messages` and `clientTools`,
185
+ * which are handled separately.
186
+ *
187
+ * During tool continuations (auto-continue after client tool results), this
188
+ * contains the body from the most recent chat request. The value is persisted
189
+ * to SQLite so it survives Durable Object hibernation. It is cleared when the
190
+ * chat is cleared via `CF_AGENT_CHAT_CLEAR`.
191
+ */
192
+ body?: Record<string, unknown>;
193
+ };
194
+ /**
195
+ * Converts client tool schemas to AI SDK tool format.
196
+ *
197
+ * These tools have no `execute` function — when the AI model calls them,
198
+ * the tool call is sent back to the client for execution.
199
+ *
200
+ * **For most apps**, define tools on the server with `tool()` from `"ai"`
201
+ * for full Zod type safety. This helper is intended for SDK/platform use
202
+ * cases where the tool surface is determined dynamically by the client.
203
+ *
204
+ * @param clientTools - Array of tool schemas from the client
205
+ * @returns Record of AI SDK tools that can be spread into your tools object
206
+ *
207
+ * @example
208
+ * ```typescript
209
+ * // In onChatMessage:
210
+ * const tools = {
211
+ * ...createToolsFromClientSchemas(options.clientTools),
212
+ * // server-defined tools with execute:
213
+ * myServerTool: tool({ ... }),
214
+ * };
215
+ * ```
216
+ */
217
+ declare function createToolsFromClientSchemas(
218
+ clientTools?: ClientToolSchema[]
219
+ ): ToolSet;
220
+ /**
221
+ * Extension of Agent with built-in chat capabilities
222
+ * @template Env Environment type containing bindings
223
+ */
224
+ declare class AIChatAgent<
225
+ Env extends Cloudflare.Env = Cloudflare.Env,
226
+ State = unknown
227
+ > extends Agent<Env, State> {
228
+ /**
229
+ * Map of message `id`s to `AbortController`s
230
+ * useful to propagate request cancellation signals for any external calls made by the agent
231
+ */
232
+ private _chatMessageAbortControllers;
233
+ /**
234
+ * Resumable stream manager -- handles chunk buffering, persistence, and replay.
235
+ * @internal Protected for testing purposes.
236
+ */
237
+ protected _resumableStream: ResumableStream;
238
+ /**
239
+ * The message currently being streamed. Used to apply tool results
240
+ * before the message is persisted.
241
+ * @internal
242
+ */
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;
250
+ /**
251
+ * Tracks the ID of a streaming message that was persisted early due to
252
+ * a tool entering approval-requested state. When set, stream completion
253
+ * updates the existing persisted message instead of appending a new one.
254
+ * @internal
255
+ */
256
+ private _approvalPersistedMessageId;
257
+ /**
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.
272
+ */
273
+ private _chatEpoch;
274
+ /**
275
+ * Set of connection IDs that are pending stream resume.
276
+ * These connections have received CF_AGENT_STREAM_RESUMING but haven't sent ACK yet.
277
+ * They should be excluded from live stream broadcasts until they ACK.
278
+ * @internal
279
+ */
280
+ private _pendingResumeConnections;
281
+ /**
282
+ * Client tool schemas from the most recent chat request.
283
+ * Stored so they can be passed to onChatMessage during tool continuations.
284
+ * @internal
285
+ */
286
+ private _lastClientTools;
287
+ /**
288
+ * Custom body data from the most recent chat request.
289
+ * Stored so it can be passed to onChatMessage during tool continuations.
290
+ * @internal
291
+ */
292
+ private _lastBody;
293
+ /**
294
+ * Cache of last-persisted JSON for each message ID.
295
+ * Used for incremental persistence: skip SQL writes for unchanged messages.
296
+ * Lost on hibernation, repopulated from SQLite on wake.
297
+ * @internal
298
+ */
299
+ private _persistedMessageCache;
300
+ /** Maximum serialized message size before compaction (bytes). 1.8MB with headroom below SQLite's 2MB limit. */
301
+ private static ROW_MAX_BYTES;
302
+ /** Measure UTF-8 byte length of a string (accurate for SQLite row limits). */
303
+ private static _byteLength;
304
+ /**
305
+ * Maximum number of messages to keep in SQLite storage.
306
+ * When the conversation exceeds this limit, oldest messages are deleted
307
+ * after each persist. Set to `undefined` (default) for no limit.
308
+ *
309
+ * This controls storage only — it does not affect what's sent to the LLM.
310
+ * Use `pruneMessages()` from the AI SDK in your `onChatMessage` to control
311
+ * LLM context separately.
312
+ *
313
+ * @example
314
+ * ```typescript
315
+ * class MyAgent extends AIChatAgent<Env> {
316
+ * maxPersistedMessages = 100; // Keep last 100 messages in storage
317
+ * }
318
+ * ```
319
+ */
320
+ maxPersistedMessages: number | undefined;
321
+ /**
322
+ * When enabled, waits for all MCP server connections to be ready before
323
+ * calling `onChatMessage`. This prevents the race condition where
324
+ * `getAITools()` returns an incomplete set because connections are still
325
+ * restoring after Durable Object hibernation.
326
+ *
327
+ * - `false` (default) — non-blocking; `onChatMessage` runs immediately.
328
+ * - `true` — waits indefinitely for all connections to settle.
329
+ * - `{ timeout: number }` — waits up to `timeout` milliseconds.
330
+ *
331
+ * For lower-level control, call `this.mcp.waitForConnections()` directly
332
+ * inside your `onChatMessage` instead.
333
+ *
334
+ * @example
335
+ * ```typescript
336
+ * class MyAgent extends AIChatAgent<Env> {
337
+ * waitForMcpConnections = true;
338
+ * }
339
+ * ```
340
+ *
341
+ * @example
342
+ * ```typescript
343
+ * class MyAgent extends AIChatAgent<Env> {
344
+ * waitForMcpConnections = { timeout: 10_000 };
345
+ * }
346
+ * ```
347
+ */
348
+ waitForMcpConnections:
349
+ | boolean
350
+ | {
351
+ timeout: number;
352
+ };
353
+ /** Array of chat messages for the current conversation */
354
+ messages: UIMessage[];
355
+ constructor(ctx: AgentContext, env: Env);
356
+ /**
357
+ * Notify a connection about an active stream that can be resumed.
358
+ * The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
359
+ * @param connection - The WebSocket connection to notify
360
+ */
361
+ private _notifyStreamResuming;
362
+ /** @internal Delegate to _resumableStream */
363
+ protected get _activeStreamId(): string | null;
364
+ /** @internal Delegate to _resumableStream */
365
+ protected get _activeRequestId(): string | null;
366
+ /** @internal Delegate to _resumableStream */
367
+ protected _startStream(requestId: string): string;
368
+ /** @internal Delegate to _resumableStream */
369
+ protected _completeStream(streamId: string): void;
370
+ /** @internal Delegate to _resumableStream */
371
+ protected _storeStreamChunk(streamId: string, body: string): void;
372
+ /** @internal Delegate to _resumableStream */
373
+ protected _flushChunkBuffer(): void;
374
+ /** @internal Delegate to _resumableStream */
375
+ protected _restoreActiveStream(): void;
376
+ /** @internal Delegate to _resumableStream */
377
+ protected _markStreamError(streamId: string): void;
378
+ /**
379
+ * Reconstruct and persist a partial assistant message from an orphaned
380
+ * stream's stored chunks. Called when the DO wakes from hibernation and
381
+ * discovers an active stream with no live LLM reader.
382
+ *
383
+ * Replays each chunk body through `applyChunkToParts` to rebuild the
384
+ * message parts, then persists the result so it survives further refreshes.
385
+ * @internal
386
+ */
387
+ private _persistOrphanedStream;
388
+ /**
389
+ * Restore _lastBody and _lastClientTools from SQLite.
390
+ * Called in the constructor so these values survive DO hibernation.
391
+ * @internal
392
+ */
393
+ private _restoreRequestContext;
394
+ /**
395
+ * Persist _lastBody and _lastClientTools to SQLite so they survive hibernation.
396
+ * Uses upsert (INSERT OR REPLACE) so repeated calls are safe.
397
+ * @internal
398
+ */
399
+ private _persistRequestContext;
400
+ private _broadcastChatMessage;
401
+ /**
402
+ * Broadcasts a text event for non-SSE responses.
403
+ * This ensures plain text responses follow the AI SDK v5 stream protocol.
404
+ *
405
+ * @param streamId - The stream identifier for chunk storage
406
+ * @param event - The text event payload (text-start, text-delta with delta, or text-end)
407
+ * @param continuation - Whether this is a continuation of a previous stream
408
+ */
409
+ private _broadcastTextEvent;
410
+ private _loadMessagesFromDb;
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;
440
+ /**
441
+ * Handle incoming chat messages and generate a response
442
+ * @param onFinish Callback to be called when the response is finished
443
+ * @param options Options including abort signal and client-defined tools
444
+ * @returns Response to send to the client or undefined
445
+ */
446
+ onChatMessage(
447
+ onFinish: StreamTextOnFinishCallback<ToolSet>,
448
+ options?: OnChatMessageOptions
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;
482
+ /**
483
+ * Save messages on the server side
484
+ * @param messages Chat messages to save
485
+ */
486
+ saveMessages(messages: UIMessage[]): Promise<void>;
487
+ persistMessages(
488
+ messages: UIMessage[],
489
+ excludeBroadcastIds?: string[],
490
+ /** @internal */ options?: {
491
+ _deleteStaleRows?: boolean;
492
+ }
493
+ ): Promise<void>;
494
+ /**
495
+ * Merges incoming messages with existing server state.
496
+ * This preserves tool outputs that the server has (via _applyToolResult)
497
+ * but the client doesn't have yet.
498
+ *
499
+ * @param incomingMessages - Messages from the client
500
+ * @returns Messages with server's tool outputs preserved
501
+ */
502
+ private _mergeIncomingWithServerState;
503
+ /**
504
+ * Reconciles assistant message IDs between incoming client state and server state.
505
+ *
506
+ * The client can keep a different local ID for an assistant message than the one
507
+ * persisted on the server (e.g. optimistic/local IDs). When that full history is
508
+ * sent back, persisting by ID alone creates duplicate assistant rows. To prevent
509
+ * this, we reuse the server ID for assistant messages that match by content,
510
+ * while leaving tool-call messages to _resolveMessageForToolMerge.
511
+ *
512
+ * Uses a two-pass approach:
513
+ * - Pass 1: resolve all exact-ID matches, claiming server indices.
514
+ * - Pass 2: content-based matching for remaining non-tool assistant messages,
515
+ * scanning only unclaimed server indices left-to-right.
516
+ *
517
+ * The two-pass design prevents exact-ID matches from advancing a cursor past
518
+ * server messages that a later incoming message needs for content matching.
519
+ * This fixes mismatches when two assistant messages have identical text
520
+ * (e.g. "Sure", "I understand") — see #1008.
521
+ */
522
+ private _reconcileAssistantIdsWithServerState;
523
+ private _hasToolCallPart;
524
+ private _assistantMessageContentKey;
525
+ /**
526
+ * Resolves a message for persistence, handling tool result merging.
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).
533
+ *
534
+ * @param message - The message to potentially merge
535
+ * @returns The message with the correct ID (either original or merged)
536
+ */
537
+ private _resolveMessageForToolMerge;
538
+ /**
539
+ * Finds an existing assistant message that contains a tool part with the given toolCallId.
540
+ * Used to detect when a tool result should update an existing message rather than
541
+ * creating a new one.
542
+ *
543
+ * @param toolCallId - The tool call ID to search for
544
+ * @returns The existing message if found, undefined otherwise
545
+ */
546
+ private _findMessageByToolCallId;
547
+ /**
548
+ * Sanitizes a message for persistence by removing ephemeral provider-specific
549
+ * data that should not be stored or sent back in subsequent requests.
550
+ *
551
+ * Pipeline:
552
+ *
553
+ * 1. **Strip OpenAI ephemeral fields**: The AI SDK's @ai-sdk/openai provider
554
+ * (v2.0.x+) defaults to using OpenAI's Responses API which assigns unique
555
+ * itemIds and reasoningEncryptedContent to message parts. When persisted
556
+ * and sent back, OpenAI rejects duplicate itemIds.
557
+ *
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
564
+ * with no text and no remaining providerMetadata are removed. Parts that
565
+ * still carry providerMetadata (e.g. Anthropic's redacted_thinking blocks
566
+ * with providerMetadata.anthropic.redactedData) are preserved, as they
567
+ * contain data required for round-tripping with the provider API.
568
+ *
569
+ * 4. **User hook**: Calls the overridable `sanitizeMessageForPersistence()`
570
+ * method, allowing subclasses to apply custom transformations.
571
+ *
572
+ * @param message - The message to sanitize
573
+ * @returns A new message with ephemeral provider data removed
574
+ */
575
+ private _sanitizeMessageForPersistence;
576
+ /**
577
+ * Helper to strip OpenAI-specific ephemeral fields from a metadata object.
578
+ * Removes itemId and reasoningEncryptedContent while preserving other fields.
579
+ */
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;
596
+ /**
597
+ * Deletes oldest messages from SQLite when the count exceeds maxPersistedMessages.
598
+ * Called after each persist to keep storage bounded.
599
+ */
600
+ private _enforceMaxPersistedMessages;
601
+ /**
602
+ * Enforces SQLite row size limits by compacting tool outputs and text parts
603
+ * when a serialized message exceeds the safety threshold (1.8MB).
604
+ *
605
+ * Only fires in pathological cases (extremely large tool outputs or text).
606
+ * Returns the message unchanged if it fits within limits.
607
+ *
608
+ * Compaction strategy:
609
+ * 1. Compact tool outputs over 1KB (replace with LLM-friendly summary)
610
+ * 2. If still too big, truncate text parts from oldest to newest
611
+ * 3. Add metadata so clients can detect compaction
612
+ *
613
+ * @param message - The message to check
614
+ * @returns The message, compacted if necessary
615
+ */
616
+ private _enforceRowSizeLimit;
617
+ /**
618
+ * Truncates text parts in a message to fit within the row size limit.
619
+ * Truncates from the first text part forward, keeping the last text part
620
+ * as intact as possible (it is usually the most relevant).
621
+ */
622
+ private _truncateTextParts;
623
+ /**
624
+ * Shared helper for finding a tool part by toolCallId and applying an update.
625
+ * Handles both streaming (in-memory) and persisted (SQLite) messages.
626
+ *
627
+ * Checks _streamingMessage first (tool results/approvals can arrive while
628
+ * the AI is still streaming), then retries persisted messages with backoff
629
+ * in case streaming completes between attempts.
630
+ *
631
+ * @param toolCallId - The tool call ID to find
632
+ * @param callerName - Name for log messages (e.g. "_applyToolResult")
633
+ * @param matchStates - Which tool part states to match
634
+ * @param applyUpdate - Mutation to apply to the matched part (streaming: in-place, persisted: spread)
635
+ * @returns true if the update was applied, false if not found or state didn't match
636
+ */
637
+ private _findAndUpdateToolPart;
638
+ /**
639
+ * Applies a tool result to an existing assistant message.
640
+ * This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.
641
+ * The server is the source of truth, so we update the message here and broadcast
642
+ * the update to all clients.
643
+ *
644
+ * @param toolCallId - The tool call ID this result is for
645
+ * @param _toolName - The name of the tool (unused, kept for API compat)
646
+ * @param output - The output from the tool execution
647
+ * @param overrideState - Optional state override ("output-error" to signal denial/failure)
648
+ * @param errorText - Error message when overrideState is "output-error"
649
+ * @returns true if the result was applied, false if the message was not found
650
+ */
651
+ private _applyToolResult;
652
+ private _streamSSEReply;
653
+ private _sendPlaintextReply;
654
+ /**
655
+ * Applies a tool approval response from the client, updating the persisted message.
656
+ * This is called when the client sends CF_AGENT_TOOL_APPROVAL for tools with needsApproval.
657
+ *
658
+ * - approved=true transitions to approval-responded
659
+ * - approved=false transitions to output-denied so convertToModelMessages
660
+ * emits a tool_result for providers (e.g. Anthropic) that require it.
661
+ *
662
+ * @param toolCallId - The tool call ID this approval is for
663
+ * @param approved - Whether the tool execution was approved
664
+ * @returns true if the approval was applied, false if the message was not found
665
+ */
666
+ private _applyToolApproval;
667
+ private _reply;
668
+ /**
669
+ * For the given message id, look up its associated AbortController
670
+ * If the AbortController does not exist, create and store one in memory
671
+ *
672
+ * returns the AbortSignal associated with the AbortController
673
+ */
674
+ private _getAbortSignal;
675
+ /**
676
+ * Remove an abort controller from the cache of pending message responses
677
+ */
678
+ private _removeAbortController;
679
+ /**
680
+ * Propagate an abort signal for any requests associated with the given message id
681
+ */
682
+ private _cancelChatRequest;
683
+ /**
684
+ * Abort all pending requests and clear the cache of AbortControllers
685
+ */
686
+ private _destroyAbortControllers;
687
+ /**
688
+ * When the DO is destroyed, cancel all pending requests and clean up resources
689
+ */
690
+ destroy(): Promise<void>;
691
+ }
692
+ //#endregion
693
+ export {
694
+ createToolsFromClientSchemas as i,
695
+ ClientToolSchema as n,
696
+ OnChatMessageOptions as r,
697
+ AIChatAgent as t
698
+ };
699
+ //# sourceMappingURL=index-B09l5oPB.d.ts.map