@cloudflare/ai-chat 0.3.0 → 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,4 +1,4 @@
1
- import { t as AIChatAgent } from "../index-BZiT3pOq.js";
1
+ import { AIChatAgent } from "../index.js";
2
2
 
3
3
  //#region src/experimental/forever.d.ts
4
4
  declare function withDurableChat<TBase extends typeof AIChatAgent>(Base: TBase): TBase;
package/dist/index.d.ts CHANGED
@@ -1,18 +1,632 @@
1
+ import { Agent, AgentContext } from "agents";
1
2
  import {
2
- a as OnChatMessageOptions,
3
- i as MessageConcurrency,
4
- n as ChatResponseResult,
5
- o as SaveMessagesResult,
6
- r as ClientToolSchema,
7
- s as createToolsFromClientSchemas,
8
- t as AIChatAgent
9
- } from "./index-BZiT3pOq.js";
3
+ ClientToolSchema,
4
+ ClientToolSchema as ClientToolSchema$1,
5
+ ResumableStream,
6
+ createToolsFromClientSchemas
7
+ } from "agents/chat";
8
+ import { StreamTextOnFinishCallback, ToolSet, UIMessage } from "ai";
9
+
10
+ //#region src/index.d.ts
11
+ type MessageConcurrency =
12
+ | "queue"
13
+ | "latest"
14
+ | "merge"
15
+ | "drop"
16
+ | {
17
+ strategy: "debounce";
18
+ debounceMs?: number;
19
+ };
20
+ /**
21
+ * Result passed to the `onChatResponse` lifecycle hook after a chat turn completes.
22
+ */
23
+ type ChatResponseResult = {
24
+ /** The finalized assistant message from this turn. */ message: UIMessage /** The request ID associated with this turn. */;
25
+ requestId: string /** Whether this turn was a continuation of a previous assistant turn. */;
26
+ continuation: boolean /** How the turn ended. */;
27
+ status:
28
+ | "completed"
29
+ | "error"
30
+ | "aborted" /** Error message when `status` is `"error"`. */;
31
+ error?: string;
32
+ };
33
+ /**
34
+ * Options passed to the onChatMessage handler.
35
+ */
36
+ type OnChatMessageOptions = {
37
+ /**
38
+ * Unique ID for this chat message exchange.
39
+ *
40
+ * For initial user messages this is the client-generated ID from the
41
+ * `CF_AGENT_USE_CHAT_REQUEST` WebSocket frame. For tool continuations
42
+ * (auto-continue after client tool results or approvals) this is a
43
+ * server-generated ID.
44
+ */
45
+ requestId: string /** AbortSignal for cancelling the request */;
46
+ abortSignal?: AbortSignal;
47
+ /**
48
+ * Tool schemas sent from the client for dynamic tool registration.
49
+ * These represent tools that will be executed on the client side.
50
+ * Use `createToolsFromClientSchemas()` to convert these to AI SDK tool format.
51
+ *
52
+ * **For most apps**, you do not need this — define tools on the server with
53
+ * `tool()` from `"ai"` and use `onToolCall` for client-side execution.
54
+ *
55
+ * **For SDKs and platforms** where tools are defined dynamically by the
56
+ * client at runtime and the server does not know the tool surface ahead
57
+ * of time, this field carries the client-provided tool schemas.
58
+ */
59
+ clientTools?: ClientToolSchema$1[];
60
+ /**
61
+ * Custom body data sent from the client via `prepareSendMessagesRequest`
62
+ * or the AI SDK's `body` option in `sendMessage`.
63
+ *
64
+ * Contains all fields from the request body except `messages` and `clientTools`,
65
+ * which are handled separately.
66
+ *
67
+ * During tool continuations (auto-continue after client tool results), this
68
+ * contains the body from the most recent chat request. The value is persisted
69
+ * to SQLite so it survives Durable Object hibernation. It is cleared when the
70
+ * chat is cleared via `CF_AGENT_CHAT_CLEAR`.
71
+ */
72
+ body?: Record<string, unknown>;
73
+ };
74
+ /**
75
+ * Result returned by `saveMessages()`.
76
+ */
77
+ type SaveMessagesResult = {
78
+ /** Server-generated request ID for the chat turn. */ requestId: string /** Whether the turn ran or was skipped (e.g. because the chat was cleared). */;
79
+ status: "completed" | "skipped";
80
+ };
81
+ /**
82
+ * Extension of Agent with built-in chat capabilities
83
+ * @template Env Environment type containing bindings
84
+ */
85
+ declare class AIChatAgent<
86
+ Env extends Cloudflare.Env = Cloudflare.Env,
87
+ State = unknown
88
+ > extends Agent<Env, State> {
89
+ /**
90
+ * Map of message `id`s to `AbortController`s
91
+ * useful to propagate request cancellation signals for any external calls made by the agent
92
+ */
93
+ private _chatMessageAbortControllers;
94
+ /**
95
+ * Resumable stream manager -- handles chunk buffering, persistence, and replay.
96
+ * @internal Protected for testing purposes.
97
+ */
98
+ protected _resumableStream: ResumableStream;
99
+ /**
100
+ * The message currently being streamed. Used to apply tool results
101
+ * before the message is persisted.
102
+ * @internal
103
+ */
104
+ private _streamingMessage;
105
+ /**
106
+ * Queued by `_reply` so the hook can fire after the turn lock releases.
107
+ * Uses an array to avoid losing results when multiple turns complete
108
+ * during a single `onChatResponse` call.
109
+ * @internal
110
+ */
111
+ private _pendingChatResponseResults;
112
+ /**
113
+ * Re-entrancy guard: true while `onChatResponse` is executing.
114
+ * Prevents recursive hook calls when the hook triggers `saveMessages`.
115
+ * @internal
116
+ */
117
+ private _insideResponseHook;
118
+ /**
119
+ * Resolves when the current pending client-tool interaction (tool result or
120
+ * approval) has been written to state. Set when an apply promise is created,
121
+ * cleared when it settles. Used by waitUntilStable to avoid polling.
122
+ */
123
+ private _pendingInteractionPromise;
124
+ /**
125
+ * Tracks the ID of a streaming message that was persisted early due to
126
+ * a tool entering approval-requested state. When set, stream completion
127
+ * updates the existing persisted message instead of appending a new one.
128
+ * @internal
129
+ */
130
+ private _approvalPersistedMessageId;
131
+ /**
132
+ * Serial queue for chat turns. Handles promise-chain serialization,
133
+ * generation-based invalidation on clear, and active-request tracking.
134
+ */
135
+ private _turnQueue;
136
+ /** First queued overlap message index for merge strategy, keyed by epoch. */
137
+ private _mergeQueuedUserStartIndexByEpoch;
138
+ /** Monotonic sequence for overlapping submit-message requests. */
139
+ private _submitSequence;
140
+ /** Latest overlapping submit-message sequence kept for latest/debounce. */
141
+ private _latestOverlappingSubmitSequence;
142
+ /** Active debounce timer handle, cleared on resetTurnState. */
143
+ private _activeDebounceTimer;
144
+ /** Resolve callback for the active debounce promise. */
145
+ private _activeDebounceResolve;
146
+ /**
147
+ * Set of connection IDs that are pending stream resume.
148
+ * These connections have received CF_AGENT_STREAM_RESUMING but haven't sent ACK yet.
149
+ * They should be excluded from live stream broadcasts until they ACK.
150
+ * @internal
151
+ */
152
+ private _pendingResumeConnections;
153
+ /**
154
+ * Continuation lifecycle state: pending, deferred, active, and
155
+ * connections awaiting a continuation stream to start.
156
+ */
157
+ private _continuation;
158
+ /**
159
+ * Client tool schemas from the most recent chat request.
160
+ * Stored so they can be passed to onChatMessage during tool continuations.
161
+ * @internal
162
+ */
163
+ private _lastClientTools;
164
+ /**
165
+ * Custom body data from the most recent chat request.
166
+ * Stored so it can be passed to onChatMessage during tool continuations.
167
+ * @internal
168
+ */
169
+ private _lastBody;
170
+ /**
171
+ * Cache of last-persisted JSON for each message ID.
172
+ * Used for incremental persistence: skip SQL writes for unchanged messages.
173
+ * Lost on hibernation, repopulated from SQLite on wake.
174
+ * @internal
175
+ */
176
+ private _persistedMessageCache;
177
+ /**
178
+ * Small debounce window to batch adjacent client-side tool results/approvals
179
+ * into a single server continuation turn.
180
+ */
181
+ private static AUTO_CONTINUATION_COALESCE_MS;
182
+ /** Default wait for trailing-edge debounced overlapping submits. */
183
+ private static MESSAGE_DEBOUNCE_MS;
184
+ /**
185
+ * Maximum number of messages to keep in SQLite storage.
186
+ * When the conversation exceeds this limit, oldest messages are deleted
187
+ * after each persist. Set to `undefined` (default) for no limit.
188
+ *
189
+ * This controls storage only — it does not affect what's sent to the LLM.
190
+ * Use `pruneMessages()` from the AI SDK in your `onChatMessage` to control
191
+ * LLM context separately.
192
+ *
193
+ * @example
194
+ * ```typescript
195
+ * class MyAgent extends AIChatAgent<Env> {
196
+ * maxPersistedMessages = 100; // Keep last 100 messages in storage
197
+ * }
198
+ * ```
199
+ */
200
+ maxPersistedMessages: number | undefined;
201
+ /**
202
+ * Controls how overlapping user submit requests behave while another chat
203
+ * turn is already active or queued.
204
+ *
205
+ * - `"queue"` (default) — queue every submit and process them in order.
206
+ * - `"latest"` — keep only the latest overlapping submit; superseded submits
207
+ * still persist their user messages, but do not start their own model turn.
208
+ * - `"merge"` — queue overlapping submits, then collapse their trailing user
209
+ * messages into one combined user turn before the latest queued turn runs.
210
+ * - `"drop"` — ignore overlapping submits entirely.
211
+ * - `{ strategy: "debounce" }` — trailing-edge latest with a quiet window.
212
+ *
213
+ * This setting only applies to `sendMessage()` / `trigger: "submit-message"`
214
+ * requests. Regenerations, tool continuations, approvals, clears, and
215
+ * programmatic `saveMessages()` calls keep their existing serialized
216
+ * behavior.
217
+ */
218
+ messageConcurrency: MessageConcurrency;
219
+ /**
220
+ * When enabled, waits for all MCP server connections to be ready before
221
+ * calling `onChatMessage`. This prevents the race condition where
222
+ * `getAITools()` returns an incomplete set because connections are still
223
+ * restoring after Durable Object hibernation.
224
+ *
225
+ * - `false` (default) — non-blocking; `onChatMessage` runs immediately.
226
+ * - `true` — waits indefinitely for all connections to settle.
227
+ * - `{ timeout: number }` — waits up to `timeout` milliseconds.
228
+ *
229
+ * For lower-level control, call `this.mcp.waitForConnections()` directly
230
+ * inside your `onChatMessage` instead.
231
+ *
232
+ * @example
233
+ * ```typescript
234
+ * class MyAgent extends AIChatAgent<Env> {
235
+ * waitForMcpConnections = true;
236
+ * }
237
+ * ```
238
+ *
239
+ * @example
240
+ * ```typescript
241
+ * class MyAgent extends AIChatAgent<Env> {
242
+ * waitForMcpConnections = { timeout: 10_000 };
243
+ * }
244
+ * ```
245
+ */
246
+ waitForMcpConnections:
247
+ | boolean
248
+ | {
249
+ timeout: number;
250
+ };
251
+ /** Array of chat messages for the current conversation */
252
+ messages: UIMessage[];
253
+ constructor(ctx: AgentContext, env: Env);
254
+ private _flushAwaitingStreamStartConnections;
255
+ private _mergeAutoContinuationPrerequisite;
256
+ private _storeDeferredAutoContinuation;
257
+ private _activateDeferredAutoContinuation;
258
+ private _clearAllAutoContinuationState;
259
+ private _clearPendingAutoContinuation;
260
+ /**
261
+ * Notify a connection about an active stream that can be resumed.
262
+ * The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
263
+ * @param connection - The WebSocket connection to notify
264
+ */
265
+ private _notifyStreamResuming;
266
+ /** @internal Delegate to _resumableStream */
267
+ protected get _activeStreamId(): string | null;
268
+ /** @internal Delegate to _resumableStream */
269
+ protected get _activeRequestId(): string | null;
270
+ /** @internal Delegate to _resumableStream */
271
+ protected _startStream(requestId: string): string;
272
+ /** @internal Delegate to _resumableStream */
273
+ protected _completeStream(streamId: string): void;
274
+ /** @internal Delegate to _resumableStream */
275
+ protected _storeStreamChunk(streamId: string, body: string): void;
276
+ /** @internal Delegate to _resumableStream */
277
+ protected _flushChunkBuffer(): void;
278
+ /** @internal Delegate to _resumableStream */
279
+ protected _restoreActiveStream(): void;
280
+ /** @internal Delegate to _resumableStream */
281
+ protected _markStreamError(streamId: string): void;
282
+ /**
283
+ * Reconstruct and persist a partial assistant message from an orphaned
284
+ * stream's stored chunks. Called when the DO wakes from hibernation and
285
+ * discovers an active stream with no live LLM reader.
286
+ *
287
+ * Replays each chunk body through `applyChunkToParts` to rebuild the
288
+ * message parts, then persists the result so it survives further refreshes.
289
+ * @internal
290
+ */
291
+ private _persistOrphanedStream;
292
+ /**
293
+ * Restore _lastBody and _lastClientTools from SQLite.
294
+ * Called in the constructor so these values survive DO hibernation.
295
+ * @internal
296
+ */
297
+ private _restoreRequestContext;
298
+ /**
299
+ * Persist _lastBody and _lastClientTools to SQLite so they survive hibernation.
300
+ * Uses upsert (INSERT OR REPLACE) so repeated calls are safe.
301
+ * @internal
302
+ */
303
+ private _persistRequestContext;
304
+ private _broadcastChatMessage;
305
+ /**
306
+ * Broadcasts a text event for non-SSE responses.
307
+ * This ensures plain text responses follow the AI SDK v5 stream protocol.
308
+ *
309
+ * @param streamId - The stream identifier for chunk storage
310
+ * @param event - The text event payload (text-start, text-delta with delta, or text-end)
311
+ * @param continuation - Whether this is a continuation of a previous stream
312
+ */
313
+ private _broadcastTextEvent;
314
+ private _loadMessagesFromDb;
315
+ private _tryCatchChat;
316
+ private isChatTurnActive;
317
+ private waitForIdle;
318
+ private _normalizeMessageConcurrency;
319
+ private _getSubmitConcurrencyDecision;
320
+ private _isSupersededSubmit;
321
+ private _waitForTimestamp;
322
+ private _cancelActiveDebounce;
323
+ private _mergeQueuedUserMessages;
324
+ private _getMergedQueuedUserMessages;
325
+ private static _mergeUserMessages;
326
+ private static _mergeMessageParts;
327
+ private static _cloneMessageParts;
328
+ private static _appendMergedText;
329
+ private _setRequestContext;
330
+ private _messagesForClientSync;
331
+ private _sendDirectMessage;
332
+ private _completeSkippedRequest;
333
+ private _rollbackDroppedSubmit;
334
+ /** `true` when an assistant message is waiting on a client tool result or approval. */
335
+ protected hasPendingInteraction(): boolean;
336
+ /**
337
+ * Waits until the conversation is fully stable — no active stream, no
338
+ * pending client-tool interactions, and no queued continuation turns.
339
+ *
340
+ * Returns `true` when stable. Returns `false` if `timeout` expires before
341
+ * a pending interaction resolves. Safe to call at any time; if there is
342
+ * nothing pending it returns immediately.
343
+ */
344
+ protected waitUntilStable(options?: { timeout?: number }): Promise<boolean>;
345
+ private abortActiveTurn;
346
+ /**
347
+ * Aborts the active turn and invalidates queued continuations. Call this
348
+ * when intercepting `CF_AGENT_CHAT_CLEAR` before the SDK sees the message —
349
+ * the built-in handler calls it automatically.
350
+ */
351
+ protected resetTurnState(): void;
352
+ private _awaitWithDeadline;
353
+ private _messageHasPendingInteraction;
354
+ /**
355
+ * Run a chat turn exclusively so `_reply()` never overlaps with another
356
+ * streaming turn.
357
+ */
358
+ private _runExclusiveChatTurn;
359
+ private _enqueueAutoContinuation;
360
+ private _awaitPendingAutoContinuationPrerequisite;
361
+ private _queueAutoContinuation;
362
+ private _runProgrammaticChatTurn;
363
+ /**
364
+ * Handle incoming chat messages and generate a response
365
+ * @param onFinish Callback to be called when the response is finished
366
+ * @param options Options including abort signal and client-defined tools
367
+ * @returns Response to send to the client or undefined
368
+ */
369
+ onChatMessage(
370
+ onFinish: StreamTextOnFinishCallback<ToolSet>,
371
+ options?: OnChatMessageOptions
372
+ ): Promise<Response | undefined>;
373
+ /**
374
+ * Called after a chat turn completes and the assistant message has been
375
+ * persisted. The turn lock is released before this hook runs, so it is
376
+ * safe to call `saveMessages` from inside.
377
+ *
378
+ * Fires for all turn completion paths: WebSocket chat requests,
379
+ * `saveMessages`, and auto-continuation.
380
+ *
381
+ * Responses triggered from inside `onChatResponse` (e.g. via `saveMessages`)
382
+ * do not fire `onChatResponse` recursively.
383
+ *
384
+ * The default implementation is a no-op.
385
+ *
386
+ * @param result - Information about the completed turn
387
+ *
388
+ * @example
389
+ * ```ts
390
+ * class MyAgent extends AIChatAgent<Env> {
391
+ * protected async onChatResponse(result: ChatResponseResult) {
392
+ * if (result.status === "completed") {
393
+ * this.broadcast(JSON.stringify({ streaming: false }));
394
+ * }
395
+ * }
396
+ * }
397
+ * ```
398
+ */
399
+ protected onChatResponse(_result: ChatResponseResult): void | Promise<void>;
400
+ /**
401
+ * Override this method to apply custom transformations to messages before
402
+ * they are persisted to storage. This hook runs **after** the built-in
403
+ * sanitization (OpenAI metadata stripping, Anthropic provider-executed tool
404
+ * payload truncation, empty reasoning part filtering).
405
+ *
406
+ * The default implementation returns the message unchanged.
407
+ *
408
+ * @param message - The pre-sanitized message about to be persisted
409
+ * @returns The transformed message to persist
410
+ *
411
+ * @example
412
+ * ```ts
413
+ * class MyAgent extends AIChatAgent<Env> {
414
+ * protected sanitizeMessageForPersistence(
415
+ * message: UIMessage
416
+ * ): UIMessage {
417
+ * return {
418
+ * ...message,
419
+ * parts: message.parts.map(part => {
420
+ * if ("output" in part && typeof part.output === "string"
421
+ * && part.output.length > 1000) {
422
+ * return { ...part, output: "[redacted]" };
423
+ * }
424
+ * return part;
425
+ * })
426
+ * };
427
+ * }
428
+ * }
429
+ * ```
430
+ */
431
+ protected sanitizeMessageForPersistence(message: UIMessage): UIMessage;
432
+ /**
433
+ * Persist messages and trigger `onChatMessage()` for a new response.
434
+ *
435
+ * Waits for any active chat turn to finish before starting, so scheduled
436
+ * or programmatic messages never overlap an in-flight stream.
437
+ *
438
+ * Pass a function to derive the next message list from the latest
439
+ * persisted `this.messages` when the turn actually starts. This avoids
440
+ * stale baselines when multiple `saveMessages()` calls queue up behind
441
+ * active work:
442
+ *
443
+ * ```ts
444
+ * await this.saveMessages((messages) => [...messages, syntheticMessage]);
445
+ * ```
446
+ *
447
+ * Returns `{ requestId, status }` so callers can detect whether the turn
448
+ * ran (`"completed"`) or was skipped because the chat was cleared
449
+ * (`"skipped"`).
450
+ */
451
+ saveMessages(
452
+ messages:
453
+ | UIMessage[]
454
+ | ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>)
455
+ ): Promise<SaveMessagesResult>;
456
+ persistMessages(
457
+ messages: UIMessage[],
458
+ excludeBroadcastIds?: string[],
459
+ /** @internal */ options?: {
460
+ _deleteStaleRows?: boolean;
461
+ }
462
+ ): Promise<void>;
463
+ /**
464
+ * Finds an existing assistant message that contains a tool part with the given toolCallId.
465
+ * Used to detect when a tool result should update an existing message rather than
466
+ * creating a new one.
467
+ *
468
+ * @param toolCallId - The tool call ID to search for
469
+ * @returns The existing message if found, undefined otherwise
470
+ */
471
+ private _findMessageByToolCallId;
472
+ private _findLastAssistantMessage;
473
+ private _createStreamingAssistantMessage;
474
+ /**
475
+ * Sanitizes a message for persistence by removing ephemeral provider-specific
476
+ * data that should not be stored or sent back in subsequent requests.
477
+ *
478
+ * Pipeline:
479
+ *
480
+ * 1. **Strip OpenAI ephemeral fields**: The AI SDK's @ai-sdk/openai provider
481
+ * (v2.0.x+) defaults to using OpenAI's Responses API which assigns unique
482
+ * itemIds and reasoningEncryptedContent to message parts. When persisted
483
+ * and sent back, OpenAI rejects duplicate itemIds.
484
+ *
485
+ * 2. **Truncate provider-executed tool payloads**: Server-side tool
486
+ * executions (e.g. Anthropic code_execution, text_editor) can produce
487
+ * 200KB+ payloads in `input` and `output`. These are truncated since the
488
+ * model has already consumed the results.
489
+ *
490
+ * 3. **Filter truly empty reasoning parts**: After stripping, reasoning parts
491
+ * with no text and no remaining providerMetadata are removed. Parts that
492
+ * still carry providerMetadata (e.g. Anthropic's redacted_thinking blocks
493
+ * with providerMetadata.anthropic.redactedData) are preserved, as they
494
+ * contain data required for round-tripping with the provider API.
495
+ *
496
+ * 4. **User hook**: Calls the overridable `sanitizeMessageForPersistence()`
497
+ * method, allowing subclasses to apply custom transformations.
498
+ *
499
+ * @param message - The message to sanitize
500
+ * @returns A new message with ephemeral provider data removed
501
+ */
502
+ private _sanitizeMessageForPersistence;
503
+ /**
504
+ * Truncates large string values in `input` and `output` of tool parts that
505
+ * were executed server-side by the provider (e.g. Anthropic code_execution,
506
+ * text_editor). These payloads can be 200KB+ and are dead weight once the
507
+ * model has consumed the result.
508
+ *
509
+ * Anthropic web tools are excluded because their outputs are replayed on
510
+ * subsequent turns. Within other tool payloads, opaque encrypted fields are
511
+ * always preserved verbatim.
512
+ */
513
+ private static _truncateProviderExecutedToolPayloads;
514
+ /**
515
+ * Recursively walks a value and truncates any string exceeding
516
+ * `PROVIDER_TOOL_MAX_STRING_LENGTH`, appending a size marker.
517
+ *
518
+ * The total output (content + marker) is kept within the threshold so
519
+ * re-running this function on already-truncated data is a no-op. Strings
520
+ * under opaque encrypted keys are preserved verbatim.
521
+ */
522
+ private static _truncateLargeStrings;
523
+ private static _shouldPreserveProviderToolPayload;
524
+ private static _getToolNameFromPart;
525
+ private static _isOpaqueReplayFieldKey;
526
+ /**
527
+ * Deletes oldest messages from SQLite when the count exceeds maxPersistedMessages.
528
+ * Called after each persist to keep storage bounded.
529
+ */
530
+ private _enforceMaxPersistedMessages;
531
+ /**
532
+ * Enforces SQLite row size limits by compacting tool outputs and text parts
533
+ * when a serialized message exceeds the safety threshold (1.8MB).
534
+ *
535
+ * Only fires in pathological cases (extremely large tool outputs or text).
536
+ * Returns the message unchanged if it fits within limits.
537
+ *
538
+ * Compaction strategy:
539
+ * 1. Compact tool outputs over 1KB (replace with LLM-friendly summary)
540
+ * 2. If still too big, truncate text parts from oldest to newest
541
+ * 3. Add metadata so clients can detect compaction
542
+ *
543
+ * @param message - The message to check
544
+ * @returns The message, compacted if necessary
545
+ */
546
+ private _enforceRowSizeLimit;
547
+ /**
548
+ * Truncates text parts in a message to fit within the row size limit.
549
+ * Truncates from the first text part forward, keeping the last text part
550
+ * as intact as possible (it is usually the most relevant).
551
+ */
552
+ private _truncateTextParts;
553
+ /**
554
+ * Shared helper for finding a tool part by toolCallId and applying an update.
555
+ * Handles both streaming (in-memory) and persisted (SQLite) messages.
556
+ *
557
+ * Checks _streamingMessage first (tool results/approvals can arrive while
558
+ * the AI is still streaming), then retries persisted messages with backoff
559
+ * in case streaming completes between attempts.
560
+ *
561
+ * @param toolCallId - The tool call ID to find
562
+ * @param callerName - Name for log messages (e.g. "_applyToolResult")
563
+ * @param matchStates - Which tool part states to match
564
+ * @param applyUpdate - Mutation to apply to the matched part (streaming: in-place, persisted: spread)
565
+ * @returns true if the update was applied, false if not found or state didn't match
566
+ */
567
+ private _findAndUpdateToolPart;
568
+ /**
569
+ * Applies a tool result to an existing assistant message.
570
+ * This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.
571
+ * The server is the source of truth, so we update the message here and broadcast
572
+ * the update to all clients.
573
+ *
574
+ * @param toolCallId - The tool call ID this result is for
575
+ * @param _toolName - The name of the tool (unused, kept for API compat)
576
+ * @param output - The output from the tool execution
577
+ * @param overrideState - Optional state override ("output-error" to signal denial/failure)
578
+ * @param errorText - Error message when overrideState is "output-error"
579
+ * @returns true if the result was applied, false if the message was not found
580
+ */
581
+ private _applyToolResult;
582
+ private _streamSSEReply;
583
+ private _sendPlaintextReply;
584
+ /**
585
+ * Applies a tool approval response from the client, updating the persisted message.
586
+ * This is called when the client sends CF_AGENT_TOOL_APPROVAL for tools with needsApproval.
587
+ *
588
+ * - approved=true transitions to approval-responded
589
+ * - approved=false transitions to output-denied so convertToModelMessages
590
+ * emits a tool_result for providers (e.g. Anthropic) that require it.
591
+ *
592
+ * @param toolCallId - The tool call ID this approval is for
593
+ * @param approved - Whether the tool execution was approved
594
+ * @returns true if the approval was applied, false if the message was not found
595
+ */
596
+ private _applyToolApproval;
597
+ private _reply;
598
+ /**
599
+ * For the given message id, look up its associated AbortController
600
+ * If the AbortController does not exist, create and store one in memory
601
+ *
602
+ * returns the AbortSignal associated with the AbortController
603
+ */
604
+ private _getAbortSignal;
605
+ /**
606
+ * Remove an abort controller from the cache of pending message responses
607
+ */
608
+ private _removeAbortController;
609
+ /**
610
+ * Propagate an abort signal for any requests associated with the given message id
611
+ */
612
+ private _cancelChatRequest;
613
+ /**
614
+ * Abort all pending requests and clear the cache of AbortControllers
615
+ */
616
+ private _destroyAbortControllers;
617
+ /**
618
+ * When the DO is destroyed, cancel all pending requests and clean up resources
619
+ */
620
+ destroy(): Promise<void>;
621
+ }
622
+ //#endregion
10
623
  export {
11
624
  AIChatAgent,
12
625
  ChatResponseResult,
13
- ClientToolSchema,
626
+ type ClientToolSchema,
14
627
  MessageConcurrency,
15
628
  OnChatMessageOptions,
16
629
  SaveMessagesResult,
17
630
  createToolsFromClientSchemas
18
631
  };
632
+ //# sourceMappingURL=index.d.ts.map