@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.
package/dist/index.d.ts CHANGED
@@ -1,477 +1,12 @@
1
- import { t as ResumableStream } from "./resumable-stream-DTLAk9XC.js";
2
1
  import {
3
- JSONSchema7,
4
- StreamTextOnFinishCallback,
5
- Tool,
6
- ToolSet,
7
- UIMessage
8
- } from "ai";
9
- import { Agent, AgentContext } from "agents";
10
-
11
- //#region src/index.d.ts
12
- /**
13
- * Schema for a client-defined tool sent from the browser.
14
- * These tools are executed on the client, not the server.
15
- *
16
- * **For most apps**, define tools on the server with `tool()` from `"ai"` —
17
- * you get full Zod type safety, server-side execution, and simpler code.
18
- * Use `onToolCall` in `useAgentChat` for tools that need client-side execution.
19
- *
20
- * **For SDKs and platforms** where the tool surface is determined dynamically
21
- * by the embedding application at runtime, client tool schemas let the
22
- * client register tools the server does not know about at deploy time.
23
- *
24
- * Note: Uses `parameters` (JSONSchema7) rather than AI SDK's `inputSchema`
25
- * because this is the wire format. Zod schemas cannot be serialized.
26
- */
27
- type ClientToolSchema = {
28
- /** Unique name for the tool */ name: string /** Human-readable description of what the tool does */;
29
- description?: Tool["description"] /** JSON Schema defining the tool's input parameters */;
30
- parameters?: JSONSchema7;
31
- };
32
- /**
33
- * Options passed to the onChatMessage handler.
34
- */
35
- type OnChatMessageOptions = {
36
- /**
37
- * Unique ID for this chat message exchange.
38
- *
39
- * For initial user messages this is the client-generated ID from the
40
- * `CF_AGENT_USE_CHAT_REQUEST` WebSocket frame. For tool continuations
41
- * (auto-continue after client tool results or approvals) this is a
42
- * server-generated ID.
43
- */
44
- requestId: string /** AbortSignal for cancelling the request */;
45
- abortSignal?: AbortSignal;
46
- /**
47
- * Tool schemas sent from the client for dynamic tool registration.
48
- * These represent tools that will be executed on the client side.
49
- * Use `createToolsFromClientSchemas()` to convert these to AI SDK tool format.
50
- *
51
- * **For most apps**, you do not need this — define tools on the server with
52
- * `tool()` from `"ai"` and use `onToolCall` for client-side execution.
53
- *
54
- * **For SDKs and platforms** where tools are defined dynamically by the
55
- * client at runtime and the server does not know the tool surface ahead
56
- * of time, this field carries the client-provided tool schemas.
57
- */
58
- clientTools?: ClientToolSchema[];
59
- /**
60
- * Custom body data sent from the client via `prepareSendMessagesRequest`
61
- * or the AI SDK's `body` option in `sendMessage`.
62
- *
63
- * Contains all fields from the request body except `messages` and `clientTools`,
64
- * which are handled separately.
65
- *
66
- * During tool continuations (auto-continue after client tool results), this
67
- * contains the body from the most recent chat request. The value is persisted
68
- * to SQLite so it survives Durable Object hibernation. It is cleared when the
69
- * chat is cleared via `CF_AGENT_CHAT_CLEAR`.
70
- */
71
- body?: Record<string, unknown>;
72
- };
73
- /**
74
- * Converts client tool schemas to AI SDK tool format.
75
- *
76
- * These tools have no `execute` function — when the AI model calls them,
77
- * the tool call is sent back to the client for execution.
78
- *
79
- * **For most apps**, define tools on the server with `tool()` from `"ai"`
80
- * for full Zod type safety. This helper is intended for SDK/platform use
81
- * cases where the tool surface is determined dynamically by the client.
82
- *
83
- * @param clientTools - Array of tool schemas from the client
84
- * @returns Record of AI SDK tools that can be spread into your tools object
85
- *
86
- * @example
87
- * ```typescript
88
- * // In onChatMessage:
89
- * const tools = {
90
- * ...createToolsFromClientSchemas(options.clientTools),
91
- * // server-defined tools with execute:
92
- * myServerTool: tool({ ... }),
93
- * };
94
- * ```
95
- */
96
- declare function createToolsFromClientSchemas(
97
- clientTools?: ClientToolSchema[]
98
- ): ToolSet;
99
- /**
100
- * Extension of Agent with built-in chat capabilities
101
- * @template Env Environment type containing bindings
102
- */
103
- declare class AIChatAgent<
104
- Env extends Cloudflare.Env = Cloudflare.Env,
105
- State = unknown
106
- > extends Agent<Env, State> {
107
- /**
108
- * Map of message `id`s to `AbortController`s
109
- * useful to propagate request cancellation signals for any external calls made by the agent
110
- */
111
- private _chatMessageAbortControllers;
112
- /**
113
- * Resumable stream manager -- handles chunk buffering, persistence, and replay.
114
- * @internal Protected for testing purposes.
115
- */
116
- protected _resumableStream: ResumableStream;
117
- /**
118
- * The message currently being streamed. Used to apply tool results
119
- * before the message is persisted.
120
- * @internal
121
- */
122
- private _streamingMessage;
123
- /**
124
- * Tracks the ID of a streaming message that was persisted early due to
125
- * a tool entering approval-requested state. When set, stream completion
126
- * updates the existing persisted message instead of appending a new one.
127
- * @internal
128
- */
129
- private _approvalPersistedMessageId;
130
- /**
131
- * Promise that resolves when the current stream completes.
132
- * Used to wait for message persistence before continuing after tool results.
133
- * @internal
134
- */
135
- private _streamCompletionPromise;
136
- private _streamCompletionResolve;
137
- /**
138
- * Set of connection IDs that are pending stream resume.
139
- * These connections have received CF_AGENT_STREAM_RESUMING but haven't sent ACK yet.
140
- * They should be excluded from live stream broadcasts until they ACK.
141
- * @internal
142
- */
143
- private _pendingResumeConnections;
144
- /**
145
- * Client tool schemas from the most recent chat request.
146
- * Stored so they can be passed to onChatMessage during tool continuations.
147
- * @internal
148
- */
149
- private _lastClientTools;
150
- /**
151
- * Custom body data from the most recent chat request.
152
- * Stored so it can be passed to onChatMessage during tool continuations.
153
- * @internal
154
- */
155
- private _lastBody;
156
- /**
157
- * Cache of last-persisted JSON for each message ID.
158
- * Used for incremental persistence: skip SQL writes for unchanged messages.
159
- * Lost on hibernation, repopulated from SQLite on wake.
160
- * @internal
161
- */
162
- private _persistedMessageCache;
163
- /** Maximum serialized message size before compaction (bytes). 1.8MB with headroom below SQLite's 2MB limit. */
164
- private static ROW_MAX_BYTES;
165
- /** Measure UTF-8 byte length of a string (accurate for SQLite row limits). */
166
- private static _byteLength;
167
- /**
168
- * Maximum number of messages to keep in SQLite storage.
169
- * When the conversation exceeds this limit, oldest messages are deleted
170
- * after each persist. Set to `undefined` (default) for no limit.
171
- *
172
- * This controls storage only — it does not affect what's sent to the LLM.
173
- * Use `pruneMessages()` from the AI SDK in your `onChatMessage` to control
174
- * LLM context separately.
175
- *
176
- * @example
177
- * ```typescript
178
- * class MyAgent extends AIChatAgent<Env> {
179
- * maxPersistedMessages = 100; // Keep last 100 messages in storage
180
- * }
181
- * ```
182
- */
183
- maxPersistedMessages: number | undefined;
184
- /**
185
- * When enabled, waits for all MCP server connections to be ready before
186
- * calling `onChatMessage`. This prevents the race condition where
187
- * `getAITools()` returns an incomplete set because connections are still
188
- * restoring after Durable Object hibernation.
189
- *
190
- * - `false` (default) — non-blocking; `onChatMessage` runs immediately.
191
- * - `true` — waits indefinitely for all connections to settle.
192
- * - `{ timeout: number }` — waits up to `timeout` milliseconds.
193
- *
194
- * For lower-level control, call `this.mcp.waitForConnections()` directly
195
- * inside your `onChatMessage` instead.
196
- *
197
- * @example
198
- * ```typescript
199
- * class MyAgent extends AIChatAgent<Env> {
200
- * waitForMcpConnections = true;
201
- * }
202
- * ```
203
- *
204
- * @example
205
- * ```typescript
206
- * class MyAgent extends AIChatAgent<Env> {
207
- * waitForMcpConnections = { timeout: 10_000 };
208
- * }
209
- * ```
210
- */
211
- waitForMcpConnections:
212
- | boolean
213
- | {
214
- timeout: number;
215
- };
216
- /** Array of chat messages for the current conversation */
217
- messages: UIMessage[];
218
- constructor(ctx: AgentContext, env: Env);
219
- /**
220
- * Notify a connection about an active stream that can be resumed.
221
- * The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
222
- * @param connection - The WebSocket connection to notify
223
- */
224
- private _notifyStreamResuming;
225
- /** @internal Delegate to _resumableStream */
226
- protected get _activeStreamId(): string | null;
227
- /** @internal Delegate to _resumableStream */
228
- protected get _activeRequestId(): string | null;
229
- /** @internal Delegate to _resumableStream */
230
- protected _startStream(requestId: string): string;
231
- /** @internal Delegate to _resumableStream */
232
- protected _completeStream(streamId: string): void;
233
- /** @internal Delegate to _resumableStream */
234
- protected _storeStreamChunk(streamId: string, body: string): void;
235
- /** @internal Delegate to _resumableStream */
236
- protected _flushChunkBuffer(): void;
237
- /** @internal Delegate to _resumableStream */
238
- protected _restoreActiveStream(): void;
239
- /** @internal Delegate to _resumableStream */
240
- protected _markStreamError(streamId: string): void;
241
- /**
242
- * Reconstruct and persist a partial assistant message from an orphaned
243
- * stream's stored chunks. Called when the DO wakes from hibernation and
244
- * discovers an active stream with no live LLM reader.
245
- *
246
- * Replays each chunk body through `applyChunkToParts` to rebuild the
247
- * message parts, then persists the result so it survives further refreshes.
248
- * @internal
249
- */
250
- private _persistOrphanedStream;
251
- /**
252
- * Restore _lastBody and _lastClientTools from SQLite.
253
- * Called in the constructor so these values survive DO hibernation.
254
- * @internal
255
- */
256
- private _restoreRequestContext;
257
- /**
258
- * Persist _lastBody and _lastClientTools to SQLite so they survive hibernation.
259
- * Uses upsert (INSERT OR REPLACE) so repeated calls are safe.
260
- * @internal
261
- */
262
- private _persistRequestContext;
263
- private _broadcastChatMessage;
264
- /**
265
- * Broadcasts a text event for non-SSE responses.
266
- * This ensures plain text responses follow the AI SDK v5 stream protocol.
267
- *
268
- * @param streamId - The stream identifier for chunk storage
269
- * @param event - The text event payload (text-start, text-delta with delta, or text-end)
270
- * @param continuation - Whether this is a continuation of a previous stream
271
- */
272
- private _broadcastTextEvent;
273
- private _loadMessagesFromDb;
274
- private _tryCatchChat;
275
- /**
276
- * Handle incoming chat messages and generate a response
277
- * @param onFinish Callback to be called when the response is finished
278
- * @param options Options including abort signal and client-defined tools
279
- * @returns Response to send to the client or undefined
280
- */
281
- onChatMessage(
282
- onFinish: StreamTextOnFinishCallback<ToolSet>,
283
- options?: OnChatMessageOptions
284
- ): Promise<Response | undefined>;
285
- /**
286
- * Save messages on the server side
287
- * @param messages Chat messages to save
288
- */
289
- saveMessages(messages: UIMessage[]): Promise<void>;
290
- persistMessages(
291
- messages: UIMessage[],
292
- excludeBroadcastIds?: string[],
293
- /** @internal */ options?: {
294
- _deleteStaleRows?: boolean;
295
- }
296
- ): Promise<void>;
297
- /**
298
- * Merges incoming messages with existing server state.
299
- * This preserves tool outputs that the server has (via _applyToolResult)
300
- * but the client doesn't have yet.
301
- *
302
- * @param incomingMessages - Messages from the client
303
- * @returns Messages with server's tool outputs preserved
304
- */
305
- private _mergeIncomingWithServerState;
306
- /**
307
- * Reconciles assistant message IDs between incoming client state and server state.
308
- *
309
- * The client can keep a different local ID for an assistant message than the one
310
- * persisted on the server (e.g. optimistic/local IDs). When that full history is
311
- * sent back, persisting by ID alone creates duplicate assistant rows. To prevent
312
- * this, we reuse the server ID for assistant messages that match by content,
313
- * while leaving tool-call messages to _resolveMessageForToolMerge.
314
- *
315
- * Uses a two-pass approach:
316
- * - Pass 1: resolve all exact-ID matches, claiming server indices.
317
- * - Pass 2: content-based matching for remaining non-tool assistant messages,
318
- * scanning only unclaimed server indices left-to-right.
319
- *
320
- * The two-pass design prevents exact-ID matches from advancing a cursor past
321
- * server messages that a later incoming message needs for content matching.
322
- * This fixes mismatches when two assistant messages have identical text
323
- * (e.g. "Sure", "I understand") — see #1008.
324
- */
325
- private _reconcileAssistantIdsWithServerState;
326
- private _hasToolCallPart;
327
- private _assistantMessageContentKey;
328
- /**
329
- * Resolves a message for persistence, handling tool result merging.
330
- * If the message contains tool parts with output-available state, checks if there's
331
- * an existing message with the same toolCallId that should be updated instead of
332
- * creating a duplicate. This prevents the "Duplicate item found" error from OpenAI
333
- * when client-side tool results arrive in a new request.
334
- *
335
- * @param message - The message to potentially merge
336
- * @returns The message with the correct ID (either original or merged)
337
- */
338
- private _resolveMessageForToolMerge;
339
- /**
340
- * Finds an existing assistant message that contains a tool part with the given toolCallId.
341
- * Used to detect when a tool result should update an existing message rather than
342
- * creating a new one.
343
- *
344
- * @param toolCallId - The tool call ID to search for
345
- * @returns The existing message if found, undefined otherwise
346
- */
347
- private _findMessageByToolCallId;
348
- /**
349
- * Sanitizes a message for persistence by removing ephemeral provider-specific
350
- * data that should not be stored or sent back in subsequent requests.
351
- *
352
- * Two-step process:
353
- *
354
- * 1. **Strip OpenAI ephemeral fields**: The AI SDK's @ai-sdk/openai provider
355
- * (v2.0.x+) defaults to using OpenAI's Responses API which assigns unique
356
- * itemIds and reasoningEncryptedContent to message parts. When persisted
357
- * and sent back, OpenAI rejects duplicate itemIds.
358
- *
359
- * 2. **Filter truly empty reasoning parts**: After stripping, reasoning parts
360
- * with no text and no remaining providerMetadata are removed. Parts that
361
- * still carry providerMetadata (e.g. Anthropic's redacted_thinking blocks
362
- * with providerMetadata.anthropic.redactedData) are preserved, as they
363
- * contain data required for round-tripping with the provider API.
364
- *
365
- * @param message - The message to sanitize
366
- * @returns A new message with ephemeral provider data removed
367
- */
368
- private _sanitizeMessageForPersistence;
369
- /**
370
- * Helper to strip OpenAI-specific ephemeral fields from a metadata object.
371
- * Removes itemId and reasoningEncryptedContent while preserving other fields.
372
- */
373
- private _stripOpenAIMetadata;
374
- /**
375
- * Deletes oldest messages from SQLite when the count exceeds maxPersistedMessages.
376
- * Called after each persist to keep storage bounded.
377
- */
378
- private _enforceMaxPersistedMessages;
379
- /**
380
- * Enforces SQLite row size limits by compacting tool outputs and text parts
381
- * when a serialized message exceeds the safety threshold (1.8MB).
382
- *
383
- * Only fires in pathological cases (extremely large tool outputs or text).
384
- * Returns the message unchanged if it fits within limits.
385
- *
386
- * Compaction strategy:
387
- * 1. Compact tool outputs over 1KB (replace with LLM-friendly summary)
388
- * 2. If still too big, truncate text parts from oldest to newest
389
- * 3. Add metadata so clients can detect compaction
390
- *
391
- * @param message - The message to check
392
- * @returns The message, compacted if necessary
393
- */
394
- private _enforceRowSizeLimit;
395
- /**
396
- * Truncates text parts in a message to fit within the row size limit.
397
- * Truncates from the first text part forward, keeping the last text part
398
- * as intact as possible (it is usually the most relevant).
399
- */
400
- private _truncateTextParts;
401
- /**
402
- * Shared helper for finding a tool part by toolCallId and applying an update.
403
- * Handles both streaming (in-memory) and persisted (SQLite) messages.
404
- *
405
- * Checks _streamingMessage first (tool results/approvals can arrive while
406
- * the AI is still streaming), then retries persisted messages with backoff
407
- * in case streaming completes between attempts.
408
- *
409
- * @param toolCallId - The tool call ID to find
410
- * @param callerName - Name for log messages (e.g. "_applyToolResult")
411
- * @param matchStates - Which tool part states to match
412
- * @param applyUpdate - Mutation to apply to the matched part (streaming: in-place, persisted: spread)
413
- * @returns true if the update was applied, false if not found or state didn't match
414
- */
415
- private _findAndUpdateToolPart;
416
- /**
417
- * Applies a tool result to an existing assistant message.
418
- * This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.
419
- * The server is the source of truth, so we update the message here and broadcast
420
- * the update to all clients.
421
- *
422
- * @param toolCallId - The tool call ID this result is for
423
- * @param _toolName - The name of the tool (unused, kept for API compat)
424
- * @param output - The output from the tool execution
425
- * @param overrideState - Optional state override ("output-error" to signal denial/failure)
426
- * @param errorText - Error message when overrideState is "output-error"
427
- * @returns true if the result was applied, false if the message was not found
428
- */
429
- private _applyToolResult;
430
- private _streamSSEReply;
431
- private _sendPlaintextReply;
432
- /**
433
- * Applies a tool approval response from the client, updating the persisted message.
434
- * This is called when the client sends CF_AGENT_TOOL_APPROVAL for tools with needsApproval.
435
- *
436
- * - approved=true transitions to approval-responded
437
- * - approved=false transitions to output-denied so convertToModelMessages
438
- * emits a tool_result for providers (e.g. Anthropic) that require it.
439
- *
440
- * @param toolCallId - The tool call ID this approval is for
441
- * @param approved - Whether the tool execution was approved
442
- * @returns true if the approval was applied, false if the message was not found
443
- */
444
- private _applyToolApproval;
445
- private _reply;
446
- /**
447
- * For the given message id, look up its associated AbortController
448
- * If the AbortController does not exist, create and store one in memory
449
- *
450
- * returns the AbortSignal associated with the AbortController
451
- */
452
- private _getAbortSignal;
453
- /**
454
- * Remove an abort controller from the cache of pending message responses
455
- */
456
- private _removeAbortController;
457
- /**
458
- * Propagate an abort signal for any requests associated with the given message id
459
- */
460
- private _cancelChatRequest;
461
- /**
462
- * Abort all pending requests and clear the cache of AbortControllers
463
- */
464
- private _destroyAbortControllers;
465
- /**
466
- * When the DO is destroyed, cancel all pending requests and clean up resources
467
- */
468
- destroy(): Promise<void>;
469
- }
470
- //#endregion
2
+ i as createToolsFromClientSchemas,
3
+ n as ClientToolSchema,
4
+ r as OnChatMessageOptions,
5
+ t as AIChatAgent
6
+ } from "./index-B09l5oPB.js";
471
7
  export {
472
8
  AIChatAgent,
473
9
  ClientToolSchema,
474
10
  OnChatMessageOptions,
475
11
  createToolsFromClientSchemas
476
12
  };
477
- //# sourceMappingURL=index.d.ts.map