@cloudflare/ai-chat 0.1.8 → 0.1.9
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/ai-chat-v5-migration.js +1 -1
- package/dist/ai-chat-v5-migration.js.map +1 -1
- package/dist/experimental/forever.d.ts +2 -16
- package/dist/experimental/forever.js +1 -1
- package/dist/experimental/forever.js.map +1 -1
- package/dist/index-BLQX_nE0.d.ts +598 -0
- package/dist/index.d.ts +5 -470
- package/dist/index.js +2 -4
- package/dist/index.js.map +1 -1
- package/dist/{message-builder-uSvexDl2.js → message-builder-BAgcFJMf.js} +2 -2
- package/dist/{message-builder-uSvexDl2.js.map → message-builder-BAgcFJMf.js.map} +1 -1
- package/dist/react.js +13 -7
- package/dist/react.js.map +1 -1
- package/dist/types.js +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +3 -3
- package/dist/resumable-stream-DTLAk9XC.d.ts +0 -126
|
@@ -0,0 +1,598 @@
|
|
|
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
|
+
* Tracks the ID of a streaming message that was persisted early due to
|
|
246
|
+
* a tool entering approval-requested state. When set, stream completion
|
|
247
|
+
* updates the existing persisted message instead of appending a new one.
|
|
248
|
+
* @internal
|
|
249
|
+
*/
|
|
250
|
+
private _approvalPersistedMessageId;
|
|
251
|
+
/**
|
|
252
|
+
* Promise that resolves when the current stream completes.
|
|
253
|
+
* Used to wait for message persistence before continuing after tool results.
|
|
254
|
+
* @internal
|
|
255
|
+
*/
|
|
256
|
+
private _streamCompletionPromise;
|
|
257
|
+
private _streamCompletionResolve;
|
|
258
|
+
/**
|
|
259
|
+
* Set of connection IDs that are pending stream resume.
|
|
260
|
+
* These connections have received CF_AGENT_STREAM_RESUMING but haven't sent ACK yet.
|
|
261
|
+
* They should be excluded from live stream broadcasts until they ACK.
|
|
262
|
+
* @internal
|
|
263
|
+
*/
|
|
264
|
+
private _pendingResumeConnections;
|
|
265
|
+
/**
|
|
266
|
+
* Client tool schemas from the most recent chat request.
|
|
267
|
+
* Stored so they can be passed to onChatMessage during tool continuations.
|
|
268
|
+
* @internal
|
|
269
|
+
*/
|
|
270
|
+
private _lastClientTools;
|
|
271
|
+
/**
|
|
272
|
+
* Custom body data from the most recent chat request.
|
|
273
|
+
* Stored so it can be passed to onChatMessage during tool continuations.
|
|
274
|
+
* @internal
|
|
275
|
+
*/
|
|
276
|
+
private _lastBody;
|
|
277
|
+
/**
|
|
278
|
+
* Cache of last-persisted JSON for each message ID.
|
|
279
|
+
* Used for incremental persistence: skip SQL writes for unchanged messages.
|
|
280
|
+
* Lost on hibernation, repopulated from SQLite on wake.
|
|
281
|
+
* @internal
|
|
282
|
+
*/
|
|
283
|
+
private _persistedMessageCache;
|
|
284
|
+
/** Maximum serialized message size before compaction (bytes). 1.8MB with headroom below SQLite's 2MB limit. */
|
|
285
|
+
private static ROW_MAX_BYTES;
|
|
286
|
+
/** Measure UTF-8 byte length of a string (accurate for SQLite row limits). */
|
|
287
|
+
private static _byteLength;
|
|
288
|
+
/**
|
|
289
|
+
* Maximum number of messages to keep in SQLite storage.
|
|
290
|
+
* When the conversation exceeds this limit, oldest messages are deleted
|
|
291
|
+
* after each persist. Set to `undefined` (default) for no limit.
|
|
292
|
+
*
|
|
293
|
+
* This controls storage only — it does not affect what's sent to the LLM.
|
|
294
|
+
* Use `pruneMessages()` from the AI SDK in your `onChatMessage` to control
|
|
295
|
+
* LLM context separately.
|
|
296
|
+
*
|
|
297
|
+
* @example
|
|
298
|
+
* ```typescript
|
|
299
|
+
* class MyAgent extends AIChatAgent<Env> {
|
|
300
|
+
* maxPersistedMessages = 100; // Keep last 100 messages in storage
|
|
301
|
+
* }
|
|
302
|
+
* ```
|
|
303
|
+
*/
|
|
304
|
+
maxPersistedMessages: number | undefined;
|
|
305
|
+
/**
|
|
306
|
+
* When enabled, waits for all MCP server connections to be ready before
|
|
307
|
+
* calling `onChatMessage`. This prevents the race condition where
|
|
308
|
+
* `getAITools()` returns an incomplete set because connections are still
|
|
309
|
+
* restoring after Durable Object hibernation.
|
|
310
|
+
*
|
|
311
|
+
* - `false` (default) — non-blocking; `onChatMessage` runs immediately.
|
|
312
|
+
* - `true` — waits indefinitely for all connections to settle.
|
|
313
|
+
* - `{ timeout: number }` — waits up to `timeout` milliseconds.
|
|
314
|
+
*
|
|
315
|
+
* For lower-level control, call `this.mcp.waitForConnections()` directly
|
|
316
|
+
* inside your `onChatMessage` instead.
|
|
317
|
+
*
|
|
318
|
+
* @example
|
|
319
|
+
* ```typescript
|
|
320
|
+
* class MyAgent extends AIChatAgent<Env> {
|
|
321
|
+
* waitForMcpConnections = true;
|
|
322
|
+
* }
|
|
323
|
+
* ```
|
|
324
|
+
*
|
|
325
|
+
* @example
|
|
326
|
+
* ```typescript
|
|
327
|
+
* class MyAgent extends AIChatAgent<Env> {
|
|
328
|
+
* waitForMcpConnections = { timeout: 10_000 };
|
|
329
|
+
* }
|
|
330
|
+
* ```
|
|
331
|
+
*/
|
|
332
|
+
waitForMcpConnections:
|
|
333
|
+
| boolean
|
|
334
|
+
| {
|
|
335
|
+
timeout: number;
|
|
336
|
+
};
|
|
337
|
+
/** Array of chat messages for the current conversation */
|
|
338
|
+
messages: UIMessage[];
|
|
339
|
+
constructor(ctx: AgentContext, env: Env);
|
|
340
|
+
/**
|
|
341
|
+
* Notify a connection about an active stream that can be resumed.
|
|
342
|
+
* The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
|
|
343
|
+
* @param connection - The WebSocket connection to notify
|
|
344
|
+
*/
|
|
345
|
+
private _notifyStreamResuming;
|
|
346
|
+
/** @internal Delegate to _resumableStream */
|
|
347
|
+
protected get _activeStreamId(): string | null;
|
|
348
|
+
/** @internal Delegate to _resumableStream */
|
|
349
|
+
protected get _activeRequestId(): string | null;
|
|
350
|
+
/** @internal Delegate to _resumableStream */
|
|
351
|
+
protected _startStream(requestId: string): string;
|
|
352
|
+
/** @internal Delegate to _resumableStream */
|
|
353
|
+
protected _completeStream(streamId: string): void;
|
|
354
|
+
/** @internal Delegate to _resumableStream */
|
|
355
|
+
protected _storeStreamChunk(streamId: string, body: string): void;
|
|
356
|
+
/** @internal Delegate to _resumableStream */
|
|
357
|
+
protected _flushChunkBuffer(): void;
|
|
358
|
+
/** @internal Delegate to _resumableStream */
|
|
359
|
+
protected _restoreActiveStream(): void;
|
|
360
|
+
/** @internal Delegate to _resumableStream */
|
|
361
|
+
protected _markStreamError(streamId: string): void;
|
|
362
|
+
/**
|
|
363
|
+
* Reconstruct and persist a partial assistant message from an orphaned
|
|
364
|
+
* stream's stored chunks. Called when the DO wakes from hibernation and
|
|
365
|
+
* discovers an active stream with no live LLM reader.
|
|
366
|
+
*
|
|
367
|
+
* Replays each chunk body through `applyChunkToParts` to rebuild the
|
|
368
|
+
* message parts, then persists the result so it survives further refreshes.
|
|
369
|
+
* @internal
|
|
370
|
+
*/
|
|
371
|
+
private _persistOrphanedStream;
|
|
372
|
+
/**
|
|
373
|
+
* Restore _lastBody and _lastClientTools from SQLite.
|
|
374
|
+
* Called in the constructor so these values survive DO hibernation.
|
|
375
|
+
* @internal
|
|
376
|
+
*/
|
|
377
|
+
private _restoreRequestContext;
|
|
378
|
+
/**
|
|
379
|
+
* Persist _lastBody and _lastClientTools to SQLite so they survive hibernation.
|
|
380
|
+
* Uses upsert (INSERT OR REPLACE) so repeated calls are safe.
|
|
381
|
+
* @internal
|
|
382
|
+
*/
|
|
383
|
+
private _persistRequestContext;
|
|
384
|
+
private _broadcastChatMessage;
|
|
385
|
+
/**
|
|
386
|
+
* Broadcasts a text event for non-SSE responses.
|
|
387
|
+
* This ensures plain text responses follow the AI SDK v5 stream protocol.
|
|
388
|
+
*
|
|
389
|
+
* @param streamId - The stream identifier for chunk storage
|
|
390
|
+
* @param event - The text event payload (text-start, text-delta with delta, or text-end)
|
|
391
|
+
* @param continuation - Whether this is a continuation of a previous stream
|
|
392
|
+
*/
|
|
393
|
+
private _broadcastTextEvent;
|
|
394
|
+
private _loadMessagesFromDb;
|
|
395
|
+
private _tryCatchChat;
|
|
396
|
+
/**
|
|
397
|
+
* Handle incoming chat messages and generate a response
|
|
398
|
+
* @param onFinish Callback to be called when the response is finished
|
|
399
|
+
* @param options Options including abort signal and client-defined tools
|
|
400
|
+
* @returns Response to send to the client or undefined
|
|
401
|
+
*/
|
|
402
|
+
onChatMessage(
|
|
403
|
+
onFinish: StreamTextOnFinishCallback<ToolSet>,
|
|
404
|
+
options?: OnChatMessageOptions
|
|
405
|
+
): Promise<Response | undefined>;
|
|
406
|
+
/**
|
|
407
|
+
* Save messages on the server side
|
|
408
|
+
* @param messages Chat messages to save
|
|
409
|
+
*/
|
|
410
|
+
saveMessages(messages: UIMessage[]): Promise<void>;
|
|
411
|
+
persistMessages(
|
|
412
|
+
messages: UIMessage[],
|
|
413
|
+
excludeBroadcastIds?: string[],
|
|
414
|
+
/** @internal */ options?: {
|
|
415
|
+
_deleteStaleRows?: boolean;
|
|
416
|
+
}
|
|
417
|
+
): Promise<void>;
|
|
418
|
+
/**
|
|
419
|
+
* Merges incoming messages with existing server state.
|
|
420
|
+
* This preserves tool outputs that the server has (via _applyToolResult)
|
|
421
|
+
* but the client doesn't have yet.
|
|
422
|
+
*
|
|
423
|
+
* @param incomingMessages - Messages from the client
|
|
424
|
+
* @returns Messages with server's tool outputs preserved
|
|
425
|
+
*/
|
|
426
|
+
private _mergeIncomingWithServerState;
|
|
427
|
+
/**
|
|
428
|
+
* Reconciles assistant message IDs between incoming client state and server state.
|
|
429
|
+
*
|
|
430
|
+
* The client can keep a different local ID for an assistant message than the one
|
|
431
|
+
* persisted on the server (e.g. optimistic/local IDs). When that full history is
|
|
432
|
+
* sent back, persisting by ID alone creates duplicate assistant rows. To prevent
|
|
433
|
+
* this, we reuse the server ID for assistant messages that match by content,
|
|
434
|
+
* while leaving tool-call messages to _resolveMessageForToolMerge.
|
|
435
|
+
*
|
|
436
|
+
* Uses a two-pass approach:
|
|
437
|
+
* - Pass 1: resolve all exact-ID matches, claiming server indices.
|
|
438
|
+
* - Pass 2: content-based matching for remaining non-tool assistant messages,
|
|
439
|
+
* scanning only unclaimed server indices left-to-right.
|
|
440
|
+
*
|
|
441
|
+
* The two-pass design prevents exact-ID matches from advancing a cursor past
|
|
442
|
+
* server messages that a later incoming message needs for content matching.
|
|
443
|
+
* This fixes mismatches when two assistant messages have identical text
|
|
444
|
+
* (e.g. "Sure", "I understand") — see #1008.
|
|
445
|
+
*/
|
|
446
|
+
private _reconcileAssistantIdsWithServerState;
|
|
447
|
+
private _hasToolCallPart;
|
|
448
|
+
private _assistantMessageContentKey;
|
|
449
|
+
/**
|
|
450
|
+
* Resolves a message for persistence, handling tool result merging.
|
|
451
|
+
* If the message contains tool parts with output-available state, checks if there's
|
|
452
|
+
* an existing message with the same toolCallId that should be updated instead of
|
|
453
|
+
* creating a duplicate. This prevents the "Duplicate item found" error from OpenAI
|
|
454
|
+
* when client-side tool results arrive in a new request.
|
|
455
|
+
*
|
|
456
|
+
* @param message - The message to potentially merge
|
|
457
|
+
* @returns The message with the correct ID (either original or merged)
|
|
458
|
+
*/
|
|
459
|
+
private _resolveMessageForToolMerge;
|
|
460
|
+
/**
|
|
461
|
+
* Finds an existing assistant message that contains a tool part with the given toolCallId.
|
|
462
|
+
* Used to detect when a tool result should update an existing message rather than
|
|
463
|
+
* creating a new one.
|
|
464
|
+
*
|
|
465
|
+
* @param toolCallId - The tool call ID to search for
|
|
466
|
+
* @returns The existing message if found, undefined otherwise
|
|
467
|
+
*/
|
|
468
|
+
private _findMessageByToolCallId;
|
|
469
|
+
/**
|
|
470
|
+
* Sanitizes a message for persistence by removing ephemeral provider-specific
|
|
471
|
+
* data that should not be stored or sent back in subsequent requests.
|
|
472
|
+
*
|
|
473
|
+
* Two-step process:
|
|
474
|
+
*
|
|
475
|
+
* 1. **Strip OpenAI ephemeral fields**: The AI SDK's @ai-sdk/openai provider
|
|
476
|
+
* (v2.0.x+) defaults to using OpenAI's Responses API which assigns unique
|
|
477
|
+
* itemIds and reasoningEncryptedContent to message parts. When persisted
|
|
478
|
+
* and sent back, OpenAI rejects duplicate itemIds.
|
|
479
|
+
*
|
|
480
|
+
* 2. **Filter truly empty reasoning parts**: After stripping, reasoning parts
|
|
481
|
+
* with no text and no remaining providerMetadata are removed. Parts that
|
|
482
|
+
* still carry providerMetadata (e.g. Anthropic's redacted_thinking blocks
|
|
483
|
+
* with providerMetadata.anthropic.redactedData) are preserved, as they
|
|
484
|
+
* contain data required for round-tripping with the provider API.
|
|
485
|
+
*
|
|
486
|
+
* @param message - The message to sanitize
|
|
487
|
+
* @returns A new message with ephemeral provider data removed
|
|
488
|
+
*/
|
|
489
|
+
private _sanitizeMessageForPersistence;
|
|
490
|
+
/**
|
|
491
|
+
* Helper to strip OpenAI-specific ephemeral fields from a metadata object.
|
|
492
|
+
* Removes itemId and reasoningEncryptedContent while preserving other fields.
|
|
493
|
+
*/
|
|
494
|
+
private _stripOpenAIMetadata;
|
|
495
|
+
/**
|
|
496
|
+
* Deletes oldest messages from SQLite when the count exceeds maxPersistedMessages.
|
|
497
|
+
* Called after each persist to keep storage bounded.
|
|
498
|
+
*/
|
|
499
|
+
private _enforceMaxPersistedMessages;
|
|
500
|
+
/**
|
|
501
|
+
* Enforces SQLite row size limits by compacting tool outputs and text parts
|
|
502
|
+
* when a serialized message exceeds the safety threshold (1.8MB).
|
|
503
|
+
*
|
|
504
|
+
* Only fires in pathological cases (extremely large tool outputs or text).
|
|
505
|
+
* Returns the message unchanged if it fits within limits.
|
|
506
|
+
*
|
|
507
|
+
* Compaction strategy:
|
|
508
|
+
* 1. Compact tool outputs over 1KB (replace with LLM-friendly summary)
|
|
509
|
+
* 2. If still too big, truncate text parts from oldest to newest
|
|
510
|
+
* 3. Add metadata so clients can detect compaction
|
|
511
|
+
*
|
|
512
|
+
* @param message - The message to check
|
|
513
|
+
* @returns The message, compacted if necessary
|
|
514
|
+
*/
|
|
515
|
+
private _enforceRowSizeLimit;
|
|
516
|
+
/**
|
|
517
|
+
* Truncates text parts in a message to fit within the row size limit.
|
|
518
|
+
* Truncates from the first text part forward, keeping the last text part
|
|
519
|
+
* as intact as possible (it is usually the most relevant).
|
|
520
|
+
*/
|
|
521
|
+
private _truncateTextParts;
|
|
522
|
+
/**
|
|
523
|
+
* Shared helper for finding a tool part by toolCallId and applying an update.
|
|
524
|
+
* Handles both streaming (in-memory) and persisted (SQLite) messages.
|
|
525
|
+
*
|
|
526
|
+
* Checks _streamingMessage first (tool results/approvals can arrive while
|
|
527
|
+
* the AI is still streaming), then retries persisted messages with backoff
|
|
528
|
+
* in case streaming completes between attempts.
|
|
529
|
+
*
|
|
530
|
+
* @param toolCallId - The tool call ID to find
|
|
531
|
+
* @param callerName - Name for log messages (e.g. "_applyToolResult")
|
|
532
|
+
* @param matchStates - Which tool part states to match
|
|
533
|
+
* @param applyUpdate - Mutation to apply to the matched part (streaming: in-place, persisted: spread)
|
|
534
|
+
* @returns true if the update was applied, false if not found or state didn't match
|
|
535
|
+
*/
|
|
536
|
+
private _findAndUpdateToolPart;
|
|
537
|
+
/**
|
|
538
|
+
* Applies a tool result to an existing assistant message.
|
|
539
|
+
* This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.
|
|
540
|
+
* The server is the source of truth, so we update the message here and broadcast
|
|
541
|
+
* the update to all clients.
|
|
542
|
+
*
|
|
543
|
+
* @param toolCallId - The tool call ID this result is for
|
|
544
|
+
* @param _toolName - The name of the tool (unused, kept for API compat)
|
|
545
|
+
* @param output - The output from the tool execution
|
|
546
|
+
* @param overrideState - Optional state override ("output-error" to signal denial/failure)
|
|
547
|
+
* @param errorText - Error message when overrideState is "output-error"
|
|
548
|
+
* @returns true if the result was applied, false if the message was not found
|
|
549
|
+
*/
|
|
550
|
+
private _applyToolResult;
|
|
551
|
+
private _streamSSEReply;
|
|
552
|
+
private _sendPlaintextReply;
|
|
553
|
+
/**
|
|
554
|
+
* Applies a tool approval response from the client, updating the persisted message.
|
|
555
|
+
* This is called when the client sends CF_AGENT_TOOL_APPROVAL for tools with needsApproval.
|
|
556
|
+
*
|
|
557
|
+
* - approved=true transitions to approval-responded
|
|
558
|
+
* - approved=false transitions to output-denied so convertToModelMessages
|
|
559
|
+
* emits a tool_result for providers (e.g. Anthropic) that require it.
|
|
560
|
+
*
|
|
561
|
+
* @param toolCallId - The tool call ID this approval is for
|
|
562
|
+
* @param approved - Whether the tool execution was approved
|
|
563
|
+
* @returns true if the approval was applied, false if the message was not found
|
|
564
|
+
*/
|
|
565
|
+
private _applyToolApproval;
|
|
566
|
+
private _reply;
|
|
567
|
+
/**
|
|
568
|
+
* For the given message id, look up its associated AbortController
|
|
569
|
+
* If the AbortController does not exist, create and store one in memory
|
|
570
|
+
*
|
|
571
|
+
* returns the AbortSignal associated with the AbortController
|
|
572
|
+
*/
|
|
573
|
+
private _getAbortSignal;
|
|
574
|
+
/**
|
|
575
|
+
* Remove an abort controller from the cache of pending message responses
|
|
576
|
+
*/
|
|
577
|
+
private _removeAbortController;
|
|
578
|
+
/**
|
|
579
|
+
* Propagate an abort signal for any requests associated with the given message id
|
|
580
|
+
*/
|
|
581
|
+
private _cancelChatRequest;
|
|
582
|
+
/**
|
|
583
|
+
* Abort all pending requests and clear the cache of AbortControllers
|
|
584
|
+
*/
|
|
585
|
+
private _destroyAbortControllers;
|
|
586
|
+
/**
|
|
587
|
+
* When the DO is destroyed, cancel all pending requests and clean up resources
|
|
588
|
+
*/
|
|
589
|
+
destroy(): Promise<void>;
|
|
590
|
+
}
|
|
591
|
+
//#endregion
|
|
592
|
+
export {
|
|
593
|
+
createToolsFromClientSchemas as i,
|
|
594
|
+
ClientToolSchema as n,
|
|
595
|
+
OnChatMessageOptions as r,
|
|
596
|
+
AIChatAgent as t
|
|
597
|
+
};
|
|
598
|
+
//# sourceMappingURL=index-BLQX_nE0.d.ts.map
|