@cloudflare/ai-chat 0.12.2 → 0.12.4
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/README.md +3 -3
- package/dist/index.d.ts +142 -1051
- package/dist/index.js +1559 -3763
- package/dist/index.js.map +1 -1
- package/package.json +5 -4
package/dist/index.d.ts
CHANGED
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
FiberRecoveryContext
|
|
12
12
|
} from "agents";
|
|
13
13
|
import {
|
|
14
|
+
ChatFrames,
|
|
14
15
|
ChatRecoveryConfig,
|
|
15
16
|
ChatRecoveryConfig as ChatRecoveryConfig$1,
|
|
16
17
|
ChatRecoveryContext,
|
|
@@ -21,25 +22,27 @@ import {
|
|
|
21
22
|
ChatRecoveryProgressContext,
|
|
22
23
|
ChatResponseResult,
|
|
23
24
|
ChatResponseResult as ChatResponseResult$1,
|
|
24
|
-
ChatTurnOutcome,
|
|
25
25
|
ClientToolSchema,
|
|
26
26
|
ClientToolSchema as ClientToolSchema$1,
|
|
27
27
|
MessageConcurrency,
|
|
28
28
|
MessageConcurrency as MessageConcurrency$1,
|
|
29
|
-
|
|
29
|
+
ReplyStreams,
|
|
30
30
|
ResolvedChatRecoveryConfig,
|
|
31
|
-
ResumableStream,
|
|
32
31
|
SaveMessagesOptions,
|
|
33
32
|
SaveMessagesOptions as SaveMessagesOptions$1,
|
|
34
33
|
SaveMessagesResult,
|
|
35
34
|
SaveMessagesResult as SaveMessagesResult$1,
|
|
35
|
+
SkippedTurnReason,
|
|
36
|
+
createChatTurnTaskDefinition,
|
|
36
37
|
createToolsFromClientSchemas
|
|
37
38
|
} from "agents/chat";
|
|
39
|
+
import { AgentTracer } from "agents/internal";
|
|
38
40
|
import { Sessions } from "agents/sessions";
|
|
39
41
|
import { GenerateTextOnFinishCallback, ToolSet, UIMessage } from "ai";
|
|
40
42
|
import { Streams } from "agents/streams";
|
|
41
43
|
|
|
42
|
-
//#region src/
|
|
44
|
+
//#region src/released-rows.d.ts
|
|
45
|
+
/** What a released version scheduled a retry with. */
|
|
43
46
|
type ChatRecoveryRetryData = {
|
|
44
47
|
targetUserId?: string;
|
|
45
48
|
originalRequestId?: string;
|
|
@@ -48,6 +51,7 @@ type ChatRecoveryRetryData = {
|
|
|
48
51
|
lastBody?: Record<string, unknown> | null;
|
|
49
52
|
lastClientTools?: ClientToolSchema$1[] | null;
|
|
50
53
|
};
|
|
54
|
+
/** What a released version scheduled a continue with. */
|
|
51
55
|
type ChatRecoveryContinueData = {
|
|
52
56
|
targetAssistantId?: string;
|
|
53
57
|
originalRequestId?: string;
|
|
@@ -56,6 +60,8 @@ type ChatRecoveryContinueData = {
|
|
|
56
60
|
lastBody?: Record<string, unknown> | null;
|
|
57
61
|
lastClientTools?: ClientToolSchema$1[] | null;
|
|
58
62
|
};
|
|
63
|
+
//#endregion
|
|
64
|
+
//#region src/index.d.ts
|
|
59
65
|
type ChatMessage = UIMessage;
|
|
60
66
|
/**
|
|
61
67
|
* Options passed to the onChatMessage handler.
|
|
@@ -112,21 +118,7 @@ declare class AIChatAgent<
|
|
|
112
118
|
Props extends object = object
|
|
113
119
|
> extends Agent<Env, State, Props> {
|
|
114
120
|
#private;
|
|
115
|
-
|
|
116
|
-
/**
|
|
117
|
-
* The originating user message ids of the active recovery chain (#2280),
|
|
118
|
-
* carried in the recovery payload because the successor turn runs under a
|
|
119
|
-
* fresh request id. Scoped to the recovery callback's async context, so a
|
|
120
|
-
* concurrent client request never inherits them.
|
|
121
|
-
*/
|
|
122
|
-
private _chatRecoveryOriginIdsScope;
|
|
123
|
-
private get _activeChatRecoveryOriginIds();
|
|
124
|
-
/**
|
|
125
|
-
* Registry of per-request AbortControllers.
|
|
126
|
-
* Used to propagate cancellation signals for any external calls made by the agent.
|
|
127
|
-
*/
|
|
128
|
-
private _abortRegistry;
|
|
129
|
-
/** Durable chat history for this Agent. */
|
|
121
|
+
/** Durable chat history for this Agent (lifts the pre-Sessions table). */
|
|
130
122
|
readonly sessions: Sessions;
|
|
131
123
|
/**
|
|
132
124
|
* Byte budget for wake-time transcript hydration into {@link messages}.
|
|
@@ -146,61 +138,11 @@ declare class AIChatAgent<
|
|
|
146
138
|
*/
|
|
147
139
|
hydrationByteBudget: number;
|
|
148
140
|
/**
|
|
149
|
-
* The Streams capability backing `
|
|
141
|
+
* The Streams capability backing `_replyStreams`: chat's in-flight
|
|
150
142
|
* output lives in the shared durable chunk log, readable by any
|
|
151
143
|
* `streams.read()` consumer on this Durable Object.
|
|
152
144
|
*/
|
|
153
145
|
readonly streams: Streams;
|
|
154
|
-
/**
|
|
155
|
-
* Resumable stream manager -- handles chunk buffering, persistence, and replay.
|
|
156
|
-
* @internal Protected for testing purposes.
|
|
157
|
-
*/
|
|
158
|
-
protected _resumableStream: ResumableStream;
|
|
159
|
-
/**
|
|
160
|
-
* The message currently being streamed. Used to apply tool results
|
|
161
|
-
* before the message is persisted.
|
|
162
|
-
* @internal
|
|
163
|
-
*/
|
|
164
|
-
private _streamingMessage;
|
|
165
|
-
/**
|
|
166
|
-
* Queued by `_reply` so the hook can fire after the turn lock releases.
|
|
167
|
-
* Uses an array to avoid losing results when multiple turns complete
|
|
168
|
-
* during a single `onChatResponse` call.
|
|
169
|
-
* @internal
|
|
170
|
-
*/
|
|
171
|
-
private _pendingChatResponseResults;
|
|
172
|
-
/**
|
|
173
|
-
* Re-entrancy guard: true while `onChatResponse` is executing.
|
|
174
|
-
* Prevents recursive hook calls when the hook triggers `saveMessages`.
|
|
175
|
-
* @internal
|
|
176
|
-
*/
|
|
177
|
-
private _insideResponseHook;
|
|
178
|
-
/**
|
|
179
|
-
* Resolves when the current pending client-tool interaction (tool result or
|
|
180
|
-
* approval) has been written to state. Set when an apply promise is created,
|
|
181
|
-
* cleared when it settles. Used by waitUntilStable to avoid polling.
|
|
182
|
-
*/
|
|
183
|
-
private _pendingInteractionPromise;
|
|
184
|
-
/**
|
|
185
|
-
* Serialization tail for client-tool result/approval applies (#1649). Each
|
|
186
|
-
* apply is a read-modify-write of the full message; running siblings from a
|
|
187
|
-
* parallel tool batch concurrently lets last-write-wins clobber the others
|
|
188
|
-
* back to `input-available`. Chaining every apply off this tail makes them
|
|
189
|
-
* commit atomically in arrival order.
|
|
190
|
-
*/
|
|
191
|
-
private _interactionApplyTail;
|
|
192
|
-
/**
|
|
193
|
-
* Tracks the ID of a streaming message that was persisted early due to
|
|
194
|
-
* a tool entering approval-requested state. When set, stream completion
|
|
195
|
-
* updates the existing persisted message instead of appending a new one.
|
|
196
|
-
* @internal
|
|
197
|
-
*/
|
|
198
|
-
private _approvalPersistedMessageId;
|
|
199
|
-
/**
|
|
200
|
-
* Serial queue for chat turns. Handles promise-chain serialization,
|
|
201
|
-
* generation-based invalidation on clear, and active-request tracking.
|
|
202
|
-
*/
|
|
203
|
-
private _turnQueue;
|
|
204
146
|
/**
|
|
205
147
|
* Durable chat recovery configuration. Every chat turn runs in `runFiber`,
|
|
206
148
|
* enabling `onChatRecovery` and `this.stash()` during streaming. Assign an
|
|
@@ -230,83 +172,50 @@ declare class AIChatAgent<
|
|
|
230
172
|
* Assign as a class field or in the constructor, like {@link chatRecovery}.
|
|
231
173
|
*/
|
|
232
174
|
chatStreamStallTimeoutMs: number;
|
|
233
|
-
/**
|
|
234
|
-
private
|
|
235
|
-
/**
|
|
236
|
-
private
|
|
237
|
-
/**
|
|
238
|
-
* Set of connection IDs that are pending stream resume.
|
|
239
|
-
* These connections have received CF_AGENT_STREAM_RESUMING but haven't sent ACK yet.
|
|
240
|
-
* They should be excluded from live stream broadcasts until they ACK.
|
|
241
|
-
* @internal
|
|
242
|
-
*/
|
|
243
|
-
private _pendingResumeConnections;
|
|
244
|
-
/** Lazily-built shared resume-handshake driver (Tier-2). */
|
|
245
|
-
private _resumeHandshakeInstance;
|
|
175
|
+
/** Where every chat frame to tabs goes out (the shared `ChatFrames`). */
|
|
176
|
+
private readonly _frames;
|
|
177
|
+
/** Rows a release before the chat module left, and their carry. */
|
|
178
|
+
private readonly _released;
|
|
246
179
|
/**
|
|
247
|
-
*
|
|
248
|
-
*
|
|
249
|
-
|
|
250
|
-
private _continuation;
|
|
251
|
-
/**
|
|
252
|
-
* Accepted-but-not-yet-streamed turns and the connections parked waiting for
|
|
253
|
-
* one (#1784). Lets a client that reconnects/re-mounts during a turn's
|
|
254
|
-
* pre-stream window (queue, MCP wait, model latency) keep waiting instead of
|
|
255
|
-
* giving up — see the {@link ResumeHandshake} `preStream` seam.
|
|
256
|
-
*
|
|
257
|
-
* HIBERNATION INVARIANT: this is in-memory only and is NOT persisted. It is
|
|
258
|
-
* safe precisely because the pre-stream window cannot overlap hibernation: a
|
|
259
|
-
* turn between `begin()` and `_startStream()` is an unresolved `onMessage`
|
|
260
|
-
* handler promise (queue/debounce/MCP/model awaits) that pins the DO in
|
|
261
|
-
* memory, so the DO is only evicted once the turn either recorded a durable
|
|
262
|
-
* stream (resumed via `ResumableStream` on wake) or finished. This breaks if a
|
|
263
|
-
* pre-stream wait is ever moved onto a durable alarm that releases the DO; if
|
|
264
|
-
* that changes, this state must become durable.
|
|
180
|
+
* The list a tab is sent: the stored messages, then those the waiting
|
|
181
|
+
* requests hold, in lane order, named in `queuedMessageIds` (a tab keeps
|
|
182
|
+
* them apart and draws them last).
|
|
265
183
|
*/
|
|
266
|
-
private
|
|
267
|
-
|
|
268
|
-
private
|
|
269
|
-
|
|
270
|
-
private
|
|
271
|
-
private _agentToolPreTurnAssistantIds;
|
|
272
|
-
private _agentToolLiveSequences;
|
|
273
|
-
/** Runs started with `eventDelivery: "terminal"`: their chunks are not broadcast. */
|
|
274
|
-
private _agentToolTerminalOnlyRuns;
|
|
184
|
+
private _clientView;
|
|
185
|
+
/** This agent's runs as an agent tool of a parent. */
|
|
186
|
+
private readonly _agentTool;
|
|
187
|
+
/** The news of this agent's detached runs, put into its chat. */
|
|
188
|
+
private readonly _detached;
|
|
275
189
|
/**
|
|
276
|
-
*
|
|
277
|
-
*
|
|
278
|
-
*
|
|
279
|
-
* belongs to a run iff it carries that run's turn request id, so an error
|
|
280
|
-
* in a user-driven turn or a concurrent run can never leak into another
|
|
281
|
-
* run's state (#1575).
|
|
190
|
+
* An agent-tool child this agent's turn waits on streamed: that counts as
|
|
191
|
+
* the turn's progress, so its no-progress window does not run out while
|
|
192
|
+
* the child works. At most one credit per 5 s, as released.
|
|
282
193
|
*/
|
|
283
|
-
|
|
194
|
+
protected _onAgentToolStreamProgress(): Promise<void>;
|
|
284
195
|
/**
|
|
285
196
|
* Client tool schemas from the most recent chat request.
|
|
286
|
-
*
|
|
287
|
-
* @internal
|
|
197
|
+
* @internal Kept for subclasses written against earlier releases.
|
|
288
198
|
*/
|
|
289
|
-
protected _lastClientTools: ClientToolSchema$1[] | undefined;
|
|
199
|
+
protected get _lastClientTools(): ClientToolSchema$1[] | undefined;
|
|
200
|
+
protected set _lastClientTools(clientTools: ClientToolSchema$1[] | undefined);
|
|
290
201
|
/**
|
|
291
202
|
* Custom body data from the most recent chat request.
|
|
292
|
-
*
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
protected _lastBody: Record<string, unknown> | undefined;
|
|
296
|
-
/**
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
*/
|
|
309
|
-
private _streamingTurnActive;
|
|
203
|
+
* @internal Kept for subclasses written against earlier releases.
|
|
204
|
+
*/
|
|
205
|
+
protected get _lastBody(): Record<string, unknown> | undefined;
|
|
206
|
+
protected set _lastBody(body: Record<string, unknown> | undefined);
|
|
207
|
+
/** @internal ai-chat 0.12's own tables, moved in the one migration. */
|
|
208
|
+
protected _releaseMigrationSteps(): ((storage: {
|
|
209
|
+
readonly sql: SqlStorage;
|
|
210
|
+
readonly kv: SyncKvStorage;
|
|
211
|
+
}) => void)[];
|
|
212
|
+
/** The chat module's stored request context: the tools and body of the last request. */
|
|
213
|
+
private _requestContextNow;
|
|
214
|
+
/** Replace the stored request context (`{}` deletes it). */
|
|
215
|
+
protected _setRequestContext(context: {
|
|
216
|
+
clientTools?: ClientToolSchema$1[];
|
|
217
|
+
body?: Record<string, unknown>;
|
|
218
|
+
}): Promise<void>;
|
|
310
219
|
/** Default wait for trailing-edge debounced overlapping submits. */
|
|
311
220
|
private static MESSAGE_DEBOUNCE_MS;
|
|
312
221
|
/**
|
|
@@ -376,44 +285,24 @@ declare class AIChatAgent<
|
|
|
376
285
|
| {
|
|
377
286
|
timeout: number;
|
|
378
287
|
};
|
|
379
|
-
/**
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
288
|
+
/** This agent as the chat module's host: the app's hooks, called. */
|
|
289
|
+
private readonly _turns;
|
|
290
|
+
/** A stop's work goes on after the call that asked for it returns. */
|
|
291
|
+
private _holdForStop;
|
|
292
|
+
/** One of this agent's grouping spans around `run`. */
|
|
293
|
+
private _chatSpan;
|
|
294
|
+
/**
|
|
295
|
+
* @internal What a turn's `invoke_agent` span is written with.
|
|
296
|
+
*/
|
|
297
|
+
protected _chatTracer(): AgentTracer;
|
|
298
|
+
/** What the chat module is given: the agent's capabilities and its tabs. */
|
|
299
|
+
private _chatDeps;
|
|
300
|
+
/** What the turn host is given; settings and `messages` are read live. */
|
|
301
|
+
private _forTurns;
|
|
302
|
+
/** The chat's lane: one turn at a time, joined as `messageConcurrency` says. */
|
|
303
|
+
private _chatLane;
|
|
304
|
+
/** The chat module's turn definition, and the two a release ran under. */
|
|
391
305
|
private _registerChatTurnTaskDefinition;
|
|
392
|
-
/** Register the shared Tasks transport for recovery continuations. */
|
|
393
|
-
private _registerChatRecoveryTaskDefinition;
|
|
394
|
-
/**
|
|
395
|
-
* Run a queue-driven recovery callback to its model handoff and return;
|
|
396
|
-
* the turn continues as tracked alarm work, and a detached platform
|
|
397
|
-
* failure enqueues one replacement attempt through the same transport.
|
|
398
|
-
*/
|
|
399
|
-
private _dispatchChatRecovery;
|
|
400
|
-
/**
|
|
401
|
-
* Enqueue one recovery attempt on the shared Tasks transport. Tasks
|
|
402
|
-
* mirrors a routed dynamic agent's wake to the root's alarm; the run
|
|
403
|
-
* itself, and this continuation's replay, still execute here. `dedupeKey`
|
|
404
|
-
* keys a retried enqueue so it joins its own prior attempt instead of
|
|
405
|
-
* duplicating it — see {@link chatRecoveryTaskRunOptions}.
|
|
406
|
-
*/
|
|
407
|
-
private _enqueueChatRecovery;
|
|
408
|
-
/**
|
|
409
|
-
* Start time and latest `stash()` data of each chat turn running in this
|
|
410
|
-
* isolate, keyed by request id. A live stream failure is recovered while the
|
|
411
|
-
* turn is still running, so `onChatRecovery` reads these instead of a fiber
|
|
412
|
-
* snapshot.
|
|
413
|
-
*/
|
|
414
|
-
private readonly _liveChatRecoveryTurns;
|
|
415
|
-
private _runChatRecoveryFiber;
|
|
416
|
-
private _runWrappedChatRecoveryFiber;
|
|
417
306
|
/**
|
|
418
307
|
* Array of chat messages for the current conversation.
|
|
419
308
|
*
|
|
@@ -423,182 +312,13 @@ declare class AIChatAgent<
|
|
|
423
312
|
* mutate the array directly.
|
|
424
313
|
*/
|
|
425
314
|
messages: UIMessage[];
|
|
315
|
+
/** The stored messages: `messages` without a continuation's prompt. */
|
|
316
|
+
private _stored;
|
|
426
317
|
broadcast(
|
|
427
318
|
msg: string | ArrayBuffer | ArrayBufferView,
|
|
428
319
|
without?: string[]
|
|
429
320
|
): void;
|
|
430
|
-
/**
|
|
431
|
-
* Durably record a run's stream error on its still-open row, so a stale-row
|
|
432
|
-
* reconcile after an eviction (before the finalizer seals `error`) still
|
|
433
|
-
* sees the failure. Leaves `status` to the finalizer / reconcile.
|
|
434
|
-
*/
|
|
435
|
-
private _recordAgentToolStreamError;
|
|
436
|
-
/**
|
|
437
|
-
* Resolve the agent-tool run whose turn owns a request id, or null when the
|
|
438
|
-
* request is not an agent-tool turn. Falls back to the persisted run row
|
|
439
|
-
* (written when the turn starts, see `_registerAgentToolTurn`) so
|
|
440
|
-
* attribution survives a DO restart mid-run; either outcome is cached.
|
|
441
|
-
*/
|
|
442
|
-
private _agentToolRunForRequest;
|
|
443
|
-
/**
|
|
444
|
-
* Re-bind this facet's in-flight agent-tool child run to the CURRENT turn's
|
|
445
|
-
* request id. Parity with `@cloudflare/think`'s
|
|
446
|
-
* `_rebindAgentToolChildRunRequestId`.
|
|
447
|
-
*
|
|
448
|
-
* When this facet runs as an agent-tool child and its turn is interrupted, the
|
|
449
|
-
* recovery continuation (`continueLastTurn` / `_retryLastUserTurn`) mints a NEW
|
|
450
|
-
* request id but never flows through `startAgentToolRun`'s
|
|
451
|
-
* `_registerAgentToolTurn`. So `cf_ai_chat_agent_tool_runs.request_id` (and the
|
|
452
|
-
* in-memory attribution map) still point at the pre-eviction turn, and
|
|
453
|
-
* `broadcast` can no longer attribute the recovered turn's frames to the run.
|
|
454
|
-
* A long-running child then forwards nothing to the parent's re-attach tail,
|
|
455
|
-
* its no-progress budget elapses, and a healthy child is abandoned as
|
|
456
|
-
* `interrupted`. Re-binding keeps attribution alive across recovery.
|
|
457
|
-
*
|
|
458
|
-
* Safe to call on EVERY recovery continuation:
|
|
459
|
-
* - Facets that never ran as an agent-tool child have no
|
|
460
|
-
* `cf_ai_chat_agent_tool_runs` table → the guarded SELECT throws → no-op.
|
|
461
|
-
* - A facet whose run already settled has no active row → no-op.
|
|
462
|
-
* - A child DO is addressed by its `runId` (`subAgent(cls, runId)`), so it
|
|
463
|
-
* owns AT MOST ONE child-run row for its whole lifetime and is never reused
|
|
464
|
-
* as a top-level chat agent — the single active row is unambiguously this
|
|
465
|
-
* recovery's run. The `order by started_at desc limit 1` is defensive
|
|
466
|
-
* belt-and-suspenders for that invariant.
|
|
467
|
-
*
|
|
468
|
-
* Uses the same `status in ('starting','running')` active-run predicate as
|
|
469
|
-
* `_agentToolRunForRequest` and the `@cloudflare/think` counterpart.
|
|
470
|
-
*/
|
|
471
|
-
private _rebindAgentToolChildRunRequestId;
|
|
472
321
|
constructor(ctx: AgentContext, env: Env);
|
|
473
|
-
private _ensureAgentToolTables;
|
|
474
|
-
private _persistAgentToolMilestone;
|
|
475
|
-
private _readAgentToolMilestones;
|
|
476
|
-
private _flushAwaitingStreamStartConnections;
|
|
477
|
-
private _activateDeferredAutoContinuation;
|
|
478
|
-
private _clearAllAutoContinuationState;
|
|
479
|
-
private _clearPendingAutoContinuation;
|
|
480
|
-
/**
|
|
481
|
-
* The shared resume-handshake driver (Tier-2). Lazily built; the
|
|
482
|
-
* `ResumableStream` / `ContinuationState` / pending set are stable after the
|
|
483
|
-
* constructor, so a single instance threads them for the agent's lifetime.
|
|
484
|
-
*/
|
|
485
|
-
private _resumeHandshake;
|
|
486
|
-
/**
|
|
487
|
-
* Notify a connection about an active stream that can be resumed — delegates
|
|
488
|
-
* to the shared {@link ResumeHandshake}. Kept as a thin method because it is
|
|
489
|
-
* also called proactively from onConnect and the broadcast loop. See the
|
|
490
|
-
* driver for the #1733 double-send contract.
|
|
491
|
-
* @param connection - The WebSocket connection to notify
|
|
492
|
-
*/
|
|
493
|
-
private _notifyStreamResuming;
|
|
494
|
-
/** @internal Delegate to _resumableStream */
|
|
495
|
-
protected get _activeStreamId(): string | null;
|
|
496
|
-
/** @internal Delegate to _resumableStream */
|
|
497
|
-
protected get _activeRequestId(): string | null;
|
|
498
|
-
/** @internal Delegate to _resumableStream */
|
|
499
|
-
protected _startStream(
|
|
500
|
-
requestId: string,
|
|
501
|
-
options?: {
|
|
502
|
-
messageId?: string;
|
|
503
|
-
continuation?: boolean;
|
|
504
|
-
}
|
|
505
|
-
): string;
|
|
506
|
-
/** @internal Delegate to _resumableStream */
|
|
507
|
-
protected _completeStream(streamId: string, outcome?: ChatTurnOutcome): void;
|
|
508
|
-
/**
|
|
509
|
-
* @internal The producer finished; leave the row for the cutover that
|
|
510
|
-
* persists the message (`persistMessages` via `#pendingCutover`). `_reply`'s
|
|
511
|
-
* finally settles it if no persist follows.
|
|
512
|
-
*/
|
|
513
|
-
protected _finishStream(streamId: string, outcome?: ChatTurnOutcome): void;
|
|
514
|
-
private _afterStreamFinished;
|
|
515
|
-
/**
|
|
516
|
-
* @deprecated Streams are reclaimed at cutover and on the next stream
|
|
517
|
-
* start; no alarm is armed any more. Kept so a cleanup alarm persisted
|
|
518
|
-
* by an earlier version still resolves to a callback when it fires.
|
|
519
|
-
* @internal
|
|
520
|
-
*/
|
|
521
|
-
_cleanupStreamBuffers(): Promise<void>;
|
|
522
|
-
/**
|
|
523
|
-
* @internal Delegate to _resumableStream.
|
|
524
|
-
*
|
|
525
|
-
* A settled tool result (`tool-output-available` / `-error` / `-denied`)
|
|
526
|
-
* is flushed to SQLite immediately rather than waiting for the packed
|
|
527
|
-
* segment to fill: it captures a completed, often non-idempotent side
|
|
528
|
-
* effect (or a user's denial), and an isolate eviction before the next
|
|
529
|
-
* batch flush would lose it — recovery would re-anchor without it and
|
|
530
|
-
* re-run the tool. The flush is also what the recovery progress marker is
|
|
531
|
-
* derived from (`_chatRecoveryProgressMarker`), so a settled result counts
|
|
532
|
-
* as forward progress the moment it lands, as it did under the old
|
|
533
|
-
* per-chunk counter. Streaming deltas keep the buffer's own packing.
|
|
534
|
-
*/
|
|
535
|
-
protected _storeStreamChunk(
|
|
536
|
-
streamId: string,
|
|
537
|
-
body: string
|
|
538
|
-
): Promise<number | undefined>;
|
|
539
|
-
/** @internal Delegate to _resumableStream */
|
|
540
|
-
protected _flushChunkBuffer(): void;
|
|
541
|
-
/** @internal Delegate to _resumableStream */
|
|
542
|
-
protected _restoreActiveStream(): void;
|
|
543
|
-
/** @internal Delegate to _resumableStream */
|
|
544
|
-
protected _markStreamError(streamId: string): void;
|
|
545
|
-
/**
|
|
546
|
-
* Reconstruct and persist a partial assistant message from an orphaned
|
|
547
|
-
* stream's stored chunks. Called when the DO wakes from hibernation and
|
|
548
|
-
* discovers an active stream with no live LLM reader.
|
|
549
|
-
*
|
|
550
|
-
* Built from the three orphan-persist seams the chat-recovery RFC factored
|
|
551
|
-
* out — all three are ai-chat's substrate-specific realizations of a shape
|
|
552
|
-
* `Think` shares:
|
|
553
|
-
* - (a) reconstruct via the shared `StreamAccumulator` (the same primitive
|
|
554
|
-
* `Think` and the client reducer use), replacing a hand-rolled chunk
|
|
555
|
-
* switch; it owns the `start` / `finish` / `message-metadata` handling;
|
|
556
|
-
* - (b) {@link _resolveOrphanTargetId} — the id to persist under (#1691);
|
|
557
|
-
* - (c)+(d) upsert-by-id through the shared `OrphanPersistStore` shape
|
|
558
|
-
* (`getMessage` → `updateMessage` / `appendMessage`).
|
|
559
|
-
* When a row already owns the id, the shared `reconcileOrphanPartial`
|
|
560
|
-
* merge preserves an in-place tool result rather than letting a replayed
|
|
561
|
-
* chunk re-advance it (ai-chat has an early tool-approval persist; hosts
|
|
562
|
-
* without one append straight through).
|
|
563
|
-
* @internal
|
|
564
|
-
*/
|
|
565
|
-
protected _persistOrphanedStream(streamId: string): Promise<void>;
|
|
566
|
-
/**
|
|
567
|
-
* Resolve the id an orphaned partial should persist under — orphan-persist
|
|
568
|
-
* step **(b)**, and the one legitimately per-package piece of the path: a
|
|
569
|
-
* flat `UIMessage[]` can't express the parent/child a Session tree uses to
|
|
570
|
-
* resolve this structurally, so ai-chat reads it from stream metadata.
|
|
571
|
-
*
|
|
572
|
-
* When the reconstructed message already adopted a provider `start.messageId`
|
|
573
|
-
* (kept as-is — the live path adopts it for new turns too) `reconstructedId`
|
|
574
|
-
* differs from `fallbackId` and is returned unchanged. Otherwise resolve to:
|
|
575
|
-
* - the id allocated when the stream started, recorded in stream metadata
|
|
576
|
-
* (#1691) — the SAME id the live path persists under (it only adopts a
|
|
577
|
-
* provider id, never invents one). A new turn stored its own fresh id, so
|
|
578
|
-
* it becomes its own message; a continuation stored the cloned
|
|
579
|
-
* last-assistant id, so it merges. This is what stops a new turn after a
|
|
580
|
-
* later user message from being folded into the previous assistant
|
|
581
|
-
* message (the #1691 corruption); or
|
|
582
|
-
* - (legacy rows written before the metadata column existed) the last
|
|
583
|
-
* assistant message, matching pre-#1691 behavior.
|
|
584
|
-
* @internal
|
|
585
|
-
*/
|
|
586
|
-
protected _resolveOrphanTargetId(
|
|
587
|
-
streamId: string,
|
|
588
|
-
reconstructedId: string,
|
|
589
|
-
fallbackId: string
|
|
590
|
-
): string;
|
|
591
|
-
/**
|
|
592
|
-
* The orphan-persist store adapter. Orphan-persist steps **(c)/(d)** route
|
|
593
|
-
* through the shared `OrphanPersistStore` seam, backed by ai-chat's
|
|
594
|
-
* `this.messages`
|
|
595
|
-
* array + the existing `persistMessages` whole-array write path, so
|
|
596
|
-
* reconcile/sanitize/row-size/broadcast all stay intact. Each mutating call
|
|
597
|
-
* is exactly one `persistMessages` invocation; `parentId` is unused (a flat
|
|
598
|
-
* array has no tree to attach to).
|
|
599
|
-
* @internal
|
|
600
|
-
*/
|
|
601
|
-
protected _orphanStore(): OrphanPersistStore;
|
|
602
322
|
/**
|
|
603
323
|
* Repair a single interrupted tool call — a tool part with no settled result,
|
|
604
324
|
* left behind when a stream was cut off mid-flight (e.g. a SERVER tool whose
|
|
@@ -626,151 +346,27 @@ declare class AIChatAgent<
|
|
|
626
346
|
part: UIMessage["parts"][number]
|
|
627
347
|
): UIMessage["parts"][number];
|
|
628
348
|
/**
|
|
629
|
-
*
|
|
630
|
-
*
|
|
631
|
-
* recovery callbacks). An interrupted server-tool orphan is flipped to a
|
|
632
|
-
* settled (errored) result — via the shared `agents/chat`
|
|
633
|
-
* `repairInterruptedToolParts` primitive, the SAME logic `@cloudflare/think`
|
|
634
|
-
* runs before its own inference (`_assembleModelMessages`) — so the app's next
|
|
635
|
-
* `convertToModelMessages(this.messages)` doesn't 400 with
|
|
636
|
-
* `AI_MissingToolResultsError`. Because the app owns the inference call, the
|
|
637
|
-
* framework can't repair "inside" it the way Think does; it repairs
|
|
638
|
-
* `this.messages` at each point right before handing control to
|
|
639
|
-
* `onChatMessage` instead. This reaches the cases the recovery-only repair
|
|
640
|
-
* missed, including a mixed client+server orphan whose client replay drives
|
|
641
|
-
* an auto-continuation.
|
|
642
|
-
*
|
|
643
|
-
* Scope: repair only ever flips a DEAD SERVER orphan (an interrupted tool with
|
|
644
|
-
* no settled result whose `execute()` died with the evicted isolate). A part
|
|
645
|
-
* still legitimately awaiting a CLIENT interaction — an `input-available`
|
|
646
|
-
* client tool the SPA replays, or an `approval-requested` part the user may
|
|
647
|
-
* still answer — is left verbatim via the shared `shouldRepair` skip, so it is
|
|
648
|
-
* never clobbered with an error. This is per-part (not a whole-transcript
|
|
649
|
-
* guard), so a fresh dead-server orphan at the leaf is still repaired even if
|
|
650
|
-
* an unrelated abandoned client orphan sits earlier in history.
|
|
349
|
+
* `true` when the chat is waiting on a client: a tool call a client still
|
|
350
|
+
* has to answer, or an approval it still has to give.
|
|
651
351
|
*
|
|
652
|
-
*
|
|
653
|
-
*
|
|
654
|
-
*
|
|
655
|
-
*
|
|
656
|
-
*
|
|
657
|
-
*
|
|
658
|
-
* write, one broadcast), which also refreshes `this.messages`.
|
|
659
|
-
* @internal
|
|
660
|
-
*/
|
|
661
|
-
private _repairInterruptedToolsBeforeTurn;
|
|
662
|
-
/**
|
|
663
|
-
* Restore _lastBody and _lastClientTools from SQLite.
|
|
664
|
-
* Called in the constructor so these values survive DO hibernation.
|
|
665
|
-
* @internal
|
|
352
|
+
* Every unanswered call in the stored transcript counts, whatever its tool.
|
|
353
|
+
* A reply is stored unanswered only when its stream finished on that call,
|
|
354
|
+
* which is what a client tool does; a reply that was cut off has its dead
|
|
355
|
+
* calls settled before it is stored. In the reply streaming now, only a
|
|
356
|
+
* tool the client sent a schema for counts, because a server tool sits at
|
|
357
|
+
* `input-available` while it runs.
|
|
666
358
|
*/
|
|
667
|
-
|
|
668
|
-
/**
|
|
669
|
-
* Persist _lastBody and _lastClientTools to SQLite so they survive hibernation.
|
|
670
|
-
* Uses upsert (INSERT OR REPLACE) so repeated calls are safe.
|
|
671
|
-
* @internal
|
|
672
|
-
*/
|
|
673
|
-
private _persistRequestContext;
|
|
674
|
-
/**
|
|
675
|
-
* User message ids a WebSocket chat request originated from (#2280), keyed
|
|
676
|
-
* by request id while the request is handled. After that (or after a
|
|
677
|
-
* restart) the request's stream metadata is the fallback.
|
|
678
|
-
*/
|
|
679
|
-
private _requestOriginMessageIds;
|
|
680
|
-
private _originMessageIdsFor;
|
|
681
|
-
private _withOriginMessageIds;
|
|
682
|
-
private _broadcastChatMessage;
|
|
683
|
-
/**
|
|
684
|
-
* `useAgentChat` flips to ready on the terminal `done` frame, and a message
|
|
685
|
-
* the user sends after that is replaced by any transcript broadcast that
|
|
686
|
-
* arrives later. So while `_reply` owns a request, its terminal frames (the
|
|
687
|
-
* `done` frame, and an in-band `error` frame, which clients also treat as
|
|
688
|
-
* terminal) are held here in order and sent only after the assistant message
|
|
689
|
-
* is persisted and broadcast.
|
|
690
|
-
*/
|
|
691
|
-
private _heldTerminalFrames;
|
|
692
|
-
private _releaseTerminalFrames;
|
|
693
|
-
/**
|
|
694
|
-
* Broadcasts a text event for non-SSE responses.
|
|
695
|
-
* This ensures plain text responses follow the AI SDK v5 stream protocol.
|
|
696
|
-
*
|
|
697
|
-
* @param streamId - The stream identifier for chunk storage
|
|
698
|
-
* @param event - The text event payload (text-start, text-delta with delta, or text-end)
|
|
699
|
-
* @param continuation - Whether this is a continuation of a previous stream
|
|
700
|
-
*/
|
|
701
|
-
private _broadcastTextEvent;
|
|
702
|
-
/**
|
|
703
|
-
* Lift ai-chat's legacy flat table into the default Sessions chain.
|
|
704
|
-
*
|
|
705
|
-
* Runs in `onStart` (before hydration), not in the constructor: the lift is
|
|
706
|
-
* an async import through Sessions, and the constructor does no session
|
|
707
|
-
* storage work at all.
|
|
708
|
-
*
|
|
709
|
-
* Order is read first as ids alone, then message bodies are fetched in
|
|
710
|
-
* windows bounded by row count and bytes, so a large transcript never sits
|
|
711
|
-
* in the isolate at once. Once every readable row has a copy the legacy
|
|
712
|
-
* table is DROPPED rather than renamed: keeping it would leave the object
|
|
713
|
-
* holding its history twice.
|
|
714
|
-
*/
|
|
715
|
-
private _migrateLegacyMessages;
|
|
716
|
-
/**
|
|
717
|
-
* Hydrate `this.messages` once per wake, bounded by
|
|
718
|
-
* {@link hydrationByteBudget}. This is the only transcript read on the
|
|
719
|
-
* startup path; every later change arrives through the Sessions change
|
|
720
|
-
* feed.
|
|
721
|
-
*/
|
|
722
|
-
private _hydrateMessages;
|
|
723
|
-
private _tryCatchChat;
|
|
724
|
-
private isChatTurnActive;
|
|
725
|
-
/**
|
|
726
|
-
* Wait until the agent is fully idle — both the turn queue is drained
|
|
727
|
-
* AND no submits are in flight between the concurrency decision and
|
|
728
|
-
* `_runExclusiveChatTurn` (mid-`persistMessages` etc.).
|
|
729
|
-
*
|
|
730
|
-
* Just awaiting `_turnQueue.waitForIdle()` would miss submits whose
|
|
731
|
-
* handlers have bumped `_latestOverlappingSubmitSequence` and
|
|
732
|
-
* incremented `_pendingEnqueueCount` but haven't yet reached
|
|
733
|
-
* `_runExclusiveChatTurn` — those would race with anything calling
|
|
734
|
-
* `waitForIdle()` (tests, `waitUntilStable`, recovery code).
|
|
735
|
-
*/
|
|
736
|
-
private waitForIdle;
|
|
359
|
+
protected hasPendingInteraction(): boolean;
|
|
737
360
|
/**
|
|
738
|
-
*
|
|
739
|
-
*
|
|
740
|
-
* mid-drain (#1650). Such an agent is NOT idle/stable: a continuation turn is
|
|
741
|
-
* imminent, so idle observers (recovery, idle-eviction, tests) must keep
|
|
742
|
-
* waiting until it either enqueues a turn or parks on an incomplete batch.
|
|
743
|
-
* A continuation that has already entered its turn (`pastCoalesce`) is
|
|
744
|
-
* covered by the turn queue, and a parked one (waiting on an unanswered
|
|
745
|
-
* sibling) is covered by `hasPendingInteraction()`, so neither is reported
|
|
746
|
-
* here.
|
|
361
|
+
* The ids of the messages the chat's waiting turns hold: questions not
|
|
362
|
+
* stored yet, which a turn stores when it starts.
|
|
747
363
|
*/
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
private static _cloneMessageParts;
|
|
755
|
-
private static _appendMergedText;
|
|
756
|
-
private _setRequestContext;
|
|
757
|
-
private _messagesForClientSync;
|
|
758
|
-
private _sendDirectMessage;
|
|
759
|
-
private _completeSkippedRequest;
|
|
760
|
-
/** Whether a connection with this id is still attached. */
|
|
761
|
-
private _isConnectionPresent;
|
|
762
|
-
/**
|
|
763
|
-
* Mark an accepted turn (#1784) as settled. When `releaseParked` (the default)
|
|
764
|
-
* and no accepted turn remains in flight and no stream is active, release every
|
|
765
|
-
* parked connection with STREAM_RESUME_NONE so a client that reconnected during
|
|
766
|
-
* the pre-stream window stops waiting. A no-op when the parked set was already
|
|
767
|
-
* flushed on stream start. Skip paths pass `releaseParked: false` so a parked
|
|
768
|
-
* client survives onto the successor turn (see `_completeSkippedRequest`).
|
|
769
|
-
*/
|
|
770
|
-
private _settlePreStreamTurn;
|
|
771
|
-
private _rollbackDroppedSubmit;
|
|
772
|
-
/** `true` when an assistant message is waiting on a client tool result or approval. */
|
|
773
|
-
protected hasPendingInteraction(): boolean;
|
|
364
|
+
protected _queuedMessageIds(): Set<string>;
|
|
365
|
+
/** The chat's turns that wait or run in its lane. */
|
|
366
|
+
protected _openChatTurns(): readonly {
|
|
367
|
+
runId: string;
|
|
368
|
+
status: string;
|
|
369
|
+
}[];
|
|
774
370
|
/**
|
|
775
371
|
* Waits until the conversation is fully stable — no active stream, no
|
|
776
372
|
* pending client-tool interactions, and no queued continuation turns.
|
|
@@ -779,22 +375,19 @@ declare class AIChatAgent<
|
|
|
779
375
|
* a pending interaction resolves. Safe to call at any time; if there is
|
|
780
376
|
* nothing pending it returns immediately.
|
|
781
377
|
*
|
|
782
|
-
* `pendingInteraction`
|
|
783
|
-
*
|
|
784
|
-
*
|
|
785
|
-
*
|
|
786
|
-
* {@link hasPendingClientInteraction} so a DEAD server-tool `input-available`
|
|
787
|
-
* orphan (its `execute()` died with the evicted isolate; nothing will resolve
|
|
788
|
-
* it) does NOT block stability — recovery then repairs it to an errored
|
|
789
|
-
* result and continues, instead of waiting until the budget is spent. This
|
|
790
|
-
* mirrors `@cloudflare/think`, whose single pending predicate is already
|
|
791
|
-
* client-only by construction.
|
|
378
|
+
* `pendingInteraction` replaces the check for a client still having
|
|
379
|
+
* something to answer. It defaults to {@link hasPendingInteraction}.
|
|
380
|
+
* Recovery passes {@link hasPendingClientInteraction}, which is the same
|
|
381
|
+
* check unless a subclass overrides it.
|
|
792
382
|
*/
|
|
793
383
|
protected waitUntilStable(options?: {
|
|
794
384
|
timeout?: number;
|
|
795
385
|
pendingInteraction?: () => boolean;
|
|
796
386
|
}): Promise<boolean>;
|
|
797
|
-
|
|
387
|
+
/** A tab cleared the chat. */
|
|
388
|
+
private _clearFromTab;
|
|
389
|
+
/** A tab sent its transcript back. */
|
|
390
|
+
private _messagesFromTab;
|
|
798
391
|
/**
|
|
799
392
|
* Aborts the active turn and invalidates queued continuations. Call this
|
|
800
393
|
* when intercepting `CF_AGENT_CHAT_CLEAR` before the SDK sees the message —
|
|
@@ -816,12 +409,6 @@ declare class AIChatAgent<
|
|
|
816
409
|
* without requiring the caller to know the id.
|
|
817
410
|
*/
|
|
818
411
|
protected abortRequest(requestId: string, reason?: unknown): void;
|
|
819
|
-
/**
|
|
820
|
-
* A cancel can land while the turn's recovery is waiting out its backoff,
|
|
821
|
-
* with nothing in flight to abort: cancel the scheduled recovery instead,
|
|
822
|
-
* so the queued callback bails when it fires.
|
|
823
|
-
*/
|
|
824
|
-
private _cancelScheduledRecovery;
|
|
825
412
|
/**
|
|
826
413
|
* Abort every in-flight chat turn on this agent.
|
|
827
414
|
*
|
|
@@ -830,109 +417,28 @@ declare class AIChatAgent<
|
|
|
830
417
|
* sub-agent helper that runs one turn at a time) and want a coarse
|
|
831
418
|
* "cancel whatever is running" handle without tracking request ids.
|
|
832
419
|
*
|
|
833
|
-
*
|
|
834
|
-
*
|
|
835
|
-
*
|
|
420
|
+
* A turn still waiting in the queue is aborted too: it ends `aborted`
|
|
421
|
+
* when it reaches the front, stores nothing and does not call the model.
|
|
422
|
+
*
|
|
423
|
+
* Every auto-continuation that waits to run is dropped too, whether a
|
|
424
|
+
* turn is running or not. A tool result that arrives afterwards continues
|
|
425
|
+
* as usual.
|
|
426
|
+
*
|
|
427
|
+
* Does NOT invalidate queued turns or submit concurrency state — use
|
|
428
|
+
* {@link resetTurnState} for the full teardown that runs on `chat-clear`.
|
|
836
429
|
*/
|
|
837
430
|
protected abortAllRequests(reason?: unknown): void;
|
|
838
|
-
private _awaitWithDeadline;
|
|
839
|
-
private _messageHasPendingInteraction;
|
|
840
431
|
/**
|
|
841
|
-
*
|
|
842
|
-
* still
|
|
843
|
-
*
|
|
844
|
-
*
|
|
432
|
+
* What chat recovery asks before it waits, parks or gives up: is a client
|
|
433
|
+
* still to answer something? The same check as
|
|
434
|
+
* {@link hasPendingInteraction} by default. The two used to differ: this
|
|
435
|
+
* one ignored a server tool call that died with its isolate. Such a call is
|
|
436
|
+
* now settled when its cut-off reply is stored, so neither sees one.
|
|
845
437
|
*
|
|
846
|
-
*
|
|
847
|
-
*
|
|
848
|
-
* excluded, because its `execute()` promise died with the evicted isolate and
|
|
849
|
-
* nothing will ever post its result — so it must NOT be treated as a healthy
|
|
850
|
-
* "waiting on the human" wait. Used to make a HITL turn budget-free during
|
|
851
|
-
* recovery so a slow human can't trip the no-progress / attempt / stable-
|
|
852
|
-
* timeout budgets; see `_beginChatRecoveryIncident` and
|
|
853
|
-
* `_parkRecoveryForPendingInteraction`. Mirrors `@cloudflare/think`'s
|
|
854
|
-
* `hasPendingInteraction`, which is already client-only by construction.
|
|
438
|
+
* Override it to change what recovery waits for without changing what
|
|
439
|
+
* {@link waitUntilStable} waits for elsewhere.
|
|
855
440
|
*/
|
|
856
441
|
protected hasPendingClientInteraction(): boolean;
|
|
857
|
-
private _messageAwaitsClientInteraction;
|
|
858
|
-
/**
|
|
859
|
-
* Whether a part is still awaiting a CLIENT interaction that can genuinely
|
|
860
|
-
* arrive after a restart: an `approval-requested` part (a reconnecting client
|
|
861
|
-
* replays the approval) or an `input-available` part for a CLIENT tool (the
|
|
862
|
-
* SPA replays the `tool-result`). A SERVER tool's `input-available` is NOT
|
|
863
|
-
* pending — its `execute()` died with the isolate. Mirrors `@cloudflare/think`.
|
|
864
|
-
*/
|
|
865
|
-
private _partAwaitsClientInteraction;
|
|
866
|
-
/**
|
|
867
|
-
* Names of the CLIENT-resolvable tools (the client-provided schemas from the
|
|
868
|
-
* last request, which have no server `execute`). Mirrors `@cloudflare/think`.
|
|
869
|
-
*/
|
|
870
|
-
private _clientResolvableToolNames;
|
|
871
|
-
/**
|
|
872
|
-
* Run a chat turn exclusively so `_reply()` never overlaps with another
|
|
873
|
-
* streaming turn.
|
|
874
|
-
*/
|
|
875
|
-
private _runExclusiveChatTurn;
|
|
876
|
-
/**
|
|
877
|
-
* Schedule an auto-continuation for a tool result/approval that opted in with
|
|
878
|
-
* `autoContinue: true` (#1650). Thin host wrapper that builds the
|
|
879
|
-
* {@link ContinuationSpec} and delegates to the shared
|
|
880
|
-
* {@link AutoContinuationController}, which owns the coalesce timer and the
|
|
881
|
-
* completeness-gated fire (shared with `@cloudflare/think`).
|
|
882
|
-
*/
|
|
883
|
-
private _scheduleAutoContinuation;
|
|
884
|
-
/**
|
|
885
|
-
* Re-arm the barrier for a result/approval that arrived WITHOUT `autoContinue`
|
|
886
|
-
* (#1650). A standalone errored result declines to continue on its own, but in
|
|
887
|
-
* a parallel batch a SIBLING may already have opted in — and this result can be
|
|
888
|
-
* the one that completes the batch, so we must re-run the barrier check. Unlike
|
|
889
|
-
* `_scheduleAutoContinuation` this NEVER creates a pending continuation (a
|
|
890
|
-
* standalone errored tool with no opted-in sibling must not auto-continue), and
|
|
891
|
-
* it no-ops once the continuation is running (`pastCoalesce`).
|
|
892
|
-
*/
|
|
893
|
-
private _rearmPendingAutoContinuationForBatch;
|
|
894
|
-
/**
|
|
895
|
-
* Called when a streaming assistant turn finalizes (its message, with ALL tool
|
|
896
|
-
* parts, is now persisted). Clears the stream-active gate and re-runs the
|
|
897
|
-
* barrier for a continuation the gate held (#1650). Essential for an all-fast
|
|
898
|
-
* parallel batch whose every result landed mid-stream: once the stream ends
|
|
899
|
-
* there is no further tool-result event to re-arm, so without this the held
|
|
900
|
-
* continuation would never fire. A slow batch is re-checked here and simply
|
|
901
|
-
* keeps holding (event-driven) until its remaining siblings answer.
|
|
902
|
-
*/
|
|
903
|
-
private _onStreamingTurnFinalized;
|
|
904
|
-
/**
|
|
905
|
-
* Drain every in-flight tool-result/approval apply, including any enqueued
|
|
906
|
-
* while we wait, so the subsequent `_hasIncompleteToolBatch()` re-check sees
|
|
907
|
-
* every result that has ALREADY arrived. Bounded by real apply activity (a
|
|
908
|
-
* storage write each), never by a fixed timer: the loop re-reads
|
|
909
|
-
* `_interactionApplyTail` after each await because a sibling can extend the
|
|
910
|
-
* tail mid-drain, and stops once the tail stops advancing. Mirrors
|
|
911
|
-
* `@cloudflare/think`'s `_drainInteractionApplies`.
|
|
912
|
-
*/
|
|
913
|
-
private _drainInteractionApplies;
|
|
914
|
-
/**
|
|
915
|
-
* `true` when the latest assistant message is mid-batch: it carries at least
|
|
916
|
-
* one settled tool result AND at least one tool call/approval still awaiting a
|
|
917
|
-
* client result. That is the #1649 signature — the model fanned out parallel
|
|
918
|
-
* tool calls and only some have been answered. Scoped to the leaf (the step
|
|
919
|
-
* the continuation answers) so an unrelated dangling tool in an earlier
|
|
920
|
-
* message doesn't block a legitimate follow-up continuation.
|
|
921
|
-
*/
|
|
922
|
-
private _hasIncompleteToolBatch;
|
|
923
|
-
private _fireAutoContinuation;
|
|
924
|
-
/**
|
|
925
|
-
* Report an auto-continuation that failed before it produced a response,
|
|
926
|
-
* the way a stream error is reported: an error frame, a durable terminal
|
|
927
|
-
* record, and `onChatResponse` with `status: "error"` for the assistant
|
|
928
|
-
* message the continuation would have extended. Called inside the turn so
|
|
929
|
-
* the response hook drains when the turn settles.
|
|
930
|
-
*/
|
|
931
|
-
private _reportContinuationFailure;
|
|
932
|
-
/**
|
|
933
|
-
* @returns Terminal status for the turn.
|
|
934
|
-
*/
|
|
935
|
-
private _runProgrammaticChatTurn;
|
|
936
442
|
/**
|
|
937
443
|
* Handle incoming chat messages and generate a response
|
|
938
444
|
* @param onFinish Callback to be called when the response is finished
|
|
@@ -1012,8 +518,6 @@ declare class AIChatAgent<
|
|
|
1012
518
|
runId: string;
|
|
1013
519
|
}
|
|
1014
520
|
): UIMessage;
|
|
1015
|
-
private _agentToolProgressEmitterInstance;
|
|
1016
|
-
private get _agentToolProgressEmitter();
|
|
1017
521
|
reportProgress<T = unknown>(
|
|
1018
522
|
progress: AgentToolProgress<T>,
|
|
1019
523
|
options?: {
|
|
@@ -1042,51 +546,12 @@ declare class AIChatAgent<
|
|
|
1042
546
|
output: unknown,
|
|
1043
547
|
messagesAfterStart: readonly UIMessage[]
|
|
1044
548
|
): string;
|
|
1045
|
-
/** True while running inside this agent's own serialized detached-delivery
|
|
1046
|
-
* turn slot (set by {@link _runDetachedDelivery}); lets a `react` notify run
|
|
1047
|
-
* its reply inline rather than enqueuing (which would deadlock) or interleaving
|
|
1048
|
-
* with a foreign turn. */
|
|
1049
|
-
private _inSerializedDetachedDeliverySlot;
|
|
1050
|
-
/** Notification ids (`detached-finish:*` / `detached-ms:*`) currently being
|
|
1051
|
-
* injected, to dedupe a concurrent warm-tail + backbone delivery of the same
|
|
1052
|
-
* milestone within one isolate before the persisted message exists. */
|
|
1053
|
-
private _inFlightDetachedNotifications;
|
|
1054
|
-
/**
|
|
1055
|
-
* Serialize detached terminal delivery against the chat turn queue. A
|
|
1056
|
-
* fast-path push or backbone tick can land mid-turn, and an `onFinish` that
|
|
1057
|
-
* mutates chat state (`saveMessages`, `setState`, a follow-up
|
|
1058
|
-
* `runAgentTool`) running concurrently with an active LLM turn is a data
|
|
1059
|
-
* race. Those paths never run synchronously inside a turn body (they fire
|
|
1060
|
-
* from `waitUntil` / a scheduled alarm), so enqueuing on the turn queue runs
|
|
1061
|
-
* the delivery strictly between turns without risk of self-deadlock.
|
|
1062
|
-
*
|
|
1063
|
-
* An explicit `cancelAgentTool` (`serialize` unset) may be invoked from
|
|
1064
|
-
* inside the very turn that triggers it, where enqueuing WOULD self-deadlock,
|
|
1065
|
-
* so it runs inline in the caller's (or a fresh) `agentContext`.
|
|
1066
|
-
*/
|
|
1067
549
|
protected _runDetachedDelivery(
|
|
1068
550
|
invoke: () => Promise<void>,
|
|
1069
551
|
options?: {
|
|
1070
552
|
serialize?: boolean;
|
|
1071
553
|
}
|
|
1072
554
|
): Promise<void>;
|
|
1073
|
-
/**
|
|
1074
|
-
* Inject a synthetic chat message for a detached-run notification, idempotent
|
|
1075
|
-
* on its deterministic `id` (a re-delivery from the warm tail + cold backbone
|
|
1076
|
-
* collapses to one — `persistMessages` is skipped when the id already exists).
|
|
1077
|
-
* When `react` is set the model then takes a turn over the new message.
|
|
1078
|
-
*
|
|
1079
|
-
* `@cloudflare/ai-chat` has no durable-submission layer (unlike Think's
|
|
1080
|
-
* `submitMessages`), so the turn cannot be enqueued-and-awaited from inside the
|
|
1081
|
-
* serialized delivery slot — `TurnQueue` has no re-entrancy bypass, so that
|
|
1082
|
-
* would self-deadlock. Instead: when we are already inside a turn slot (the
|
|
1083
|
-
* `serialize: true` finish delivery runs as its own enqueued turn) we run the
|
|
1084
|
-
* programmatic turn INLINE, reusing that slot — so the whole notify completes
|
|
1085
|
-
* before the ledger marks the slot delivered (eviction-safe). When we are not
|
|
1086
|
-
* inside a slot (a milestone fired from the `waitUntil` fast path or the
|
|
1087
|
-
* reconcile alarm) we enqueue a fresh turn normally.
|
|
1088
|
-
*/
|
|
1089
|
-
private _injectDetachedNotification;
|
|
1090
555
|
/**
|
|
1091
556
|
* Format the message injected by `detached: { notify }` when a background run
|
|
1092
557
|
* finishes. Override to customize the prose, or return an empty string to
|
|
@@ -1134,14 +599,14 @@ declare class AIChatAgent<
|
|
|
1134
599
|
mode: "react" | "narrate"
|
|
1135
600
|
): Promise<void>;
|
|
1136
601
|
/**
|
|
1137
|
-
*
|
|
1138
|
-
*
|
|
1139
|
-
*
|
|
1140
|
-
*
|
|
1141
|
-
*
|
|
1142
|
-
*
|
|
602
|
+
* Start this agent as an agent-tool run for a parent.
|
|
603
|
+
*
|
|
604
|
+
* @param options.signal - Aborting it cancels the run, the same as
|
|
605
|
+
* {@link cancelAgentToolRun}. An `AbortSignal` does not cross a Durable
|
|
606
|
+
* Object RPC call, so it works for a caller in the same isolate. A
|
|
607
|
+
* parent that reaches this agent over RPC cancels with
|
|
608
|
+
* `cancelAgentToolRun(runId, reason)`.
|
|
1143
609
|
*/
|
|
1144
|
-
private _registerAgentToolTurn;
|
|
1145
610
|
startAgentToolRun(
|
|
1146
611
|
input: unknown,
|
|
1147
612
|
options: {
|
|
@@ -1151,51 +616,12 @@ declare class AIChatAgent<
|
|
|
1151
616
|
}
|
|
1152
617
|
): Promise<AgentToolRunInspection>;
|
|
1153
618
|
cancelAgentToolRun(runId: string, reason?: unknown): Promise<void>;
|
|
1154
|
-
/**
|
|
1155
|
-
* Classify any in-flight chat-recovery on this child facet (#1630 / N6). A
|
|
1156
|
-
* child facet is dedicated to a single agent-tool run, so any recovery
|
|
1157
|
-
* incident is that run's. Incidents in `detected`/`scheduled`/`attempting`
|
|
1158
|
-
* mean recovery is still resolving the interrupted turn; `exhausted`/`failed`
|
|
1159
|
-
* mean recovery gave up; a completed recovery deletes its incident.
|
|
1160
|
-
*/
|
|
1161
|
-
private _classifyAgentToolChildRecovery;
|
|
1162
|
-
/**
|
|
1163
|
-
* Reconcile a stale (post-eviction) child run row from the child's own
|
|
1164
|
-
* durable recovery (#1630). The child facet self-heals its interrupted turn
|
|
1165
|
-
* via `chatRecovery`, but that path never writes the run row, so without this
|
|
1166
|
-
* the row strands `running` and the parent can only collect `interrupted`.
|
|
1167
|
-
*
|
|
1168
|
-
* Persisting the terminal here (rather than only computing it) is intentional:
|
|
1169
|
-
* it's a lazy materialization of the run's true terminal that also lets a
|
|
1170
|
-
* tailing parent's stream close promptly and makes subsequent inspects cheap.
|
|
1171
|
-
* While recovery is still resolving (active stream or in-progress incident)
|
|
1172
|
-
* the row is left `running` so the parent's bounded re-attach keeps waiting.
|
|
1173
|
-
* Mutates `row` in place when it settles so the caller can report it.
|
|
1174
|
-
*/
|
|
1175
|
-
private _reconcileStaleAgentToolChildRun;
|
|
1176
|
-
/**
|
|
1177
|
-
* Eagerly terminalize this child facet's OWN agent-tool run row(s) once a
|
|
1178
|
-
* recovered turn has settled. A recovered turn re-runs via either
|
|
1179
|
-
* `_chatRecoveryContinue` → `continueLastTurn` or, for a pre-stream eviction,
|
|
1180
|
-
* `_chatRecoveryRetry` → `_retryLastUserTurn` — neither flows through
|
|
1181
|
-
* `startAgentToolRun`'s finalizer, so without this the row strands `running`
|
|
1182
|
-
* and its tailers stay open until a parent inspect lazily reconciles it —
|
|
1183
|
-
* forcing a re-attached parent to wait out a full no-progress window before
|
|
1184
|
-
* collecting an already-finished result (#1630 follow-up). Reconciling here
|
|
1185
|
-
* closes the tail promptly so the parent collects the terminal immediately.
|
|
1186
|
-
* No-op on non-child facets (their `cf_ai_chat_agent_tool_runs` table is
|
|
1187
|
-
* empty) and on rows whose in-memory run is still live; the underlying
|
|
1188
|
-
* reconcile leaves a row `running` while its recovery is still in progress.
|
|
1189
|
-
* Mirrors `@cloudflare/think`.
|
|
1190
|
-
*/
|
|
1191
|
-
private _reconcileOwnStaleAgentToolChildRuns;
|
|
1192
619
|
inspectAgentToolRun(
|
|
1193
620
|
runId: string,
|
|
1194
|
-
|
|
621
|
+
_options?: {
|
|
1195
622
|
reconcile?: boolean;
|
|
1196
623
|
}
|
|
1197
624
|
): Promise<AgentToolRunInspection | null>;
|
|
1198
|
-
private static _progressSnapshotFromRow;
|
|
1199
625
|
getAgentToolChunks(
|
|
1200
626
|
runId: string,
|
|
1201
627
|
options?: {
|
|
@@ -1209,24 +635,6 @@ declare class AIChatAgent<
|
|
|
1209
635
|
signal?: AbortSignal;
|
|
1210
636
|
}
|
|
1211
637
|
): Promise<ReadableStream<AgentToolStoredChunk>>;
|
|
1212
|
-
private _getAgentToolRunRow;
|
|
1213
|
-
private _getAgentToolStreamId;
|
|
1214
|
-
/**
|
|
1215
|
-
* After this DO restarts, `_agentToolLiveSequences` is cold while the stored
|
|
1216
|
-
* backlog sits at N, and a chat-recovery resume re-attaches via
|
|
1217
|
-
* `tailAgentToolRun` without re-running `startAgentToolRun` (which seeds the
|
|
1218
|
-
* counter). Unseeded, the broadcast snoop numbers the recovered turn's chunks
|
|
1219
|
-
* from 0 and the tail's high-water dedupe drops them. Seeds only a running
|
|
1220
|
-
* run, so a terminal one doesn't re-heat the broadcast idle-guard; a warm
|
|
1221
|
-
* counter is authoritative. Returns whether it seeded.
|
|
1222
|
-
*/
|
|
1223
|
-
private _seedAgentToolLiveSequence;
|
|
1224
|
-
private _getAgentToolStoredChunks;
|
|
1225
|
-
private _getAgentToolMessagesAfterStart;
|
|
1226
|
-
private _closeAgentToolTailers;
|
|
1227
|
-
private static _stringifyAgentToolValue;
|
|
1228
|
-
private static _parseAgentToolValue;
|
|
1229
|
-
private static _extractLatestAssistantText;
|
|
1230
638
|
/**
|
|
1231
639
|
* Persist messages and trigger `onChatMessage()` for a new response.
|
|
1232
640
|
*
|
|
@@ -1246,7 +654,10 @@ declare class AIChatAgent<
|
|
|
1246
654
|
* the internally-generated request id. The signal is linked to the
|
|
1247
655
|
* registry's controller for this turn — when it aborts, the inference
|
|
1248
656
|
* loop's signal aborts and the result reports `status: "aborted"`.
|
|
1249
|
-
*
|
|
657
|
+
* A signal already aborted, or one that aborts while the turn waits in the
|
|
658
|
+
* queue, stops the turn before it starts: nothing is stored, `onChatMessage`
|
|
659
|
+
* and `onChatResponse` are not called, and the result reports
|
|
660
|
+
* `status: "aborted"`.
|
|
1250
661
|
*
|
|
1251
662
|
* Returns `{ requestId, status, error? }` where `status` is `"completed"`
|
|
1252
663
|
* when the turn ran, `"error"` when the stream reported an error,
|
|
@@ -1280,83 +691,11 @@ declare class AIChatAgent<
|
|
|
1280
691
|
body?: Record<string, unknown>,
|
|
1281
692
|
options?: SaveMessagesOptions$1
|
|
1282
693
|
): Promise<SaveMessagesResult$1>;
|
|
1283
|
-
private _retryLastUserTurn;
|
|
1284
694
|
/**
|
|
1285
695
|
* Context passed to `onChatRecovery` when an interrupted chat stream
|
|
1286
696
|
* is detected after DO restart.
|
|
1287
697
|
*/
|
|
1288
698
|
static readonly CHAT_FIBER_NAME = "__cf_internal_chat_turn";
|
|
1289
|
-
/**
|
|
1290
|
-
* Intercept internal chat fibers before they reach the user's
|
|
1291
|
-
* `onFiberRecovered` hook. Maps to `onChatRecovery`.
|
|
1292
|
-
* @internal
|
|
1293
|
-
*/
|
|
1294
|
-
private _resolveChatRecoveryConfig;
|
|
1295
|
-
/**
|
|
1296
|
-
* Monotonic forward-progress signal for recovery budget resets.
|
|
1297
|
-
*
|
|
1298
|
-
* This used to count assistant messages in `this.messages`, but that is
|
|
1299
|
-
* recomputed from the live, mutable transcript. Compaction collapses older
|
|
1300
|
-
* assistant messages into a summary, lowering the count — so a turn that had
|
|
1301
|
-
* genuinely advanced could read as "no progress" between attempts and exhaust
|
|
1302
|
-
* its budget prematurely (#1628). It then became a KV counter bumped per
|
|
1303
|
-
* credited chunk. It is now derived from the stream log the chunks were
|
|
1304
|
-
* already flushed to (`ResumableStream.progressMarker`): the log only grows
|
|
1305
|
-
* when new content lands durably, a reconnect replay or a recovery
|
|
1306
|
-
* re-persist reads it without appending (#1637), and compaction rewrites
|
|
1307
|
-
* the transcript, not the log. Nothing is written per chunk.
|
|
1308
|
-
*
|
|
1309
|
-
* The pre-derivation KV counter is folded in once per isolate, so a marker
|
|
1310
|
-
* an in-flight incident already recorded is never read lower after the
|
|
1311
|
-
* upgrade.
|
|
1312
|
-
*/
|
|
1313
|
-
private _chatRecoveryProgressMarker;
|
|
1314
|
-
private _progressSeed;
|
|
1315
|
-
/** Per-isolate N9 throttle gate (shared `agents/chat` helper); reset per
|
|
1316
|
-
* isolate so the first forwarded chunk after a restart always credits. */
|
|
1317
|
-
private _agentToolStreamProgress;
|
|
1318
|
-
/**
|
|
1319
|
-
* N9: forwarding a sub-agent's chunks IS forward progress for this parent
|
|
1320
|
-
* turn, so credit the parent's recovery progress marker — otherwise a parent
|
|
1321
|
-
* whose turn merely `await`s a child banks no progress of its own and its
|
|
1322
|
-
* no-progress window exhausts while the child is healthily streaming. The
|
|
1323
|
-
* child's output goes to clients, not to this object's stream log, so the
|
|
1324
|
-
* derived marker cannot see it; this is the one explicit credit left. Only
|
|
1325
|
-
* invoked after a child actually produced output (see
|
|
1326
|
-
* `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.
|
|
1327
|
-
* Throttled (and reset per isolate) so we never write storage per token.
|
|
1328
|
-
*/
|
|
1329
|
-
protected _onAgentToolStreamProgress(): Promise<void>;
|
|
1330
|
-
/**
|
|
1331
|
-
* Lazily-built shared recovery engine. The adapter arrows capture `this`, so a
|
|
1332
|
-
* single cached instance is correct across calls (and across future engine
|
|
1333
|
-
* methods). `AIChatAgent` has no interaction state to rehydrate, so it omits
|
|
1334
|
-
* the optional `ensureInteractionStateLoaded` hook.
|
|
1335
|
-
*/
|
|
1336
|
-
private _chatRecoveryEngineInstance?;
|
|
1337
|
-
private _chatRecoveryEngine;
|
|
1338
|
-
private _beginChatRecoveryIncident;
|
|
1339
|
-
private _updateChatRecoveryIncident;
|
|
1340
|
-
private _exhaustChatRecovery;
|
|
1341
|
-
/**
|
|
1342
|
-
* Persist a durable record of the last terminal turn so a client that
|
|
1343
|
-
* (re)connects after the turn ended still learns its outcome (#1645). Kept
|
|
1344
|
-
* until a later turn supersedes it (`_clearChatTerminal`); a single record is
|
|
1345
|
-
* sufficient because only the most recent terminal is relevant.
|
|
1346
|
-
*/
|
|
1347
|
-
private _recordChatTerminal;
|
|
1348
|
-
/** Clear the durable terminal record once a later turn supersedes it (#1645). */
|
|
1349
|
-
private _clearChatTerminal;
|
|
1350
|
-
private _pendingChatTerminal;
|
|
1351
|
-
/**
|
|
1352
|
-
* Build the on-connect "recovering…" replay frame (#1620), or `null` when no
|
|
1353
|
-
* (non-stale) recovery is in progress. A client that connects between recovery
|
|
1354
|
-
* attempts (no active stream) reads the turn as working rather than frozen.
|
|
1355
|
-
* A record older than the flag TTL is treated as abandoned (its terminal-clear
|
|
1356
|
-
* never ran) and skipped, so a dead recovery can't show "recovering…" forever.
|
|
1357
|
-
* Mirrors `@cloudflare/think`'s `_buildIdleConnectMessages` recovering replay.
|
|
1358
|
-
*/
|
|
1359
|
-
private _buildRecoveringConnectFrame;
|
|
1360
699
|
/**
|
|
1361
700
|
* Set or clear the live "recovering…" status (#1620). Persists a durable
|
|
1362
701
|
* record (so set/clear stay consistent across the isolates a recovery spans)
|
|
@@ -1365,39 +704,16 @@ declare class AIChatAgent<
|
|
|
1365
704
|
* client connecting mid-recovery isn't left looking frozen; the terminal
|
|
1366
705
|
* outcome is surfaced separately over the resume handshake (#1645).
|
|
1367
706
|
*/
|
|
707
|
+
/** The last change of the recovering status asked for, done or under way. */
|
|
708
|
+
private _recoveringStatus;
|
|
1368
709
|
private _setChatRecovering;
|
|
710
|
+
/**
|
|
711
|
+
* A chat turn's fiber row an older version left in the fiber ledger: recover
|
|
712
|
+
* it like a replayed chat-turn Task run. Every other fiber is the app's.
|
|
713
|
+
*/
|
|
1369
714
|
protected _handleInternalFiberRecovery(
|
|
1370
715
|
ctx: FiberRecoveryContext
|
|
1371
716
|
): Promise<boolean>;
|
|
1372
|
-
/**
|
|
1373
|
-
* Resolve the orphaned stream for a recovered chat turn — drives BOTH the wake
|
|
1374
|
-
* path (full result) and the give-up terminalization (which reads only
|
|
1375
|
-
* `.streamId`). Prefers the newest durable stream row keyed by the recovery-
|
|
1376
|
-
* root request id; falls back to the live active stream; `streamId` is `""`
|
|
1377
|
-
* when neither survives. `AIChatAgent` does not model terminal stream status,
|
|
1378
|
-
* so `streamStatus` is left `undefined` (keeping the engine's terminal-stream
|
|
1379
|
-
* branches dead here) — see the "substrate capabilities are optional" decision
|
|
1380
|
-
* in the RFC.
|
|
1381
|
-
*/
|
|
1382
|
-
private _resolveAIChatRecoveryStream;
|
|
1383
|
-
/**
|
|
1384
|
-
* Classify a recovered turn as `retry` or `continue`. The `shouldRetryPreStream`
|
|
1385
|
-
* detail is threaded to the dispatch decision; `emptyPartialNewTurn` only
|
|
1386
|
-
* influences the reported kind (an empty partial persists nothing, so a new turn
|
|
1387
|
-
* is re-run fresh rather than merged into the previous assistant — #1691). The
|
|
1388
|
-
* `persist: false` discard case stays "continue" here and only surfaces as
|
|
1389
|
-
* "retry" on the `chat:recovery:scheduled` event, decided in dispatch.
|
|
1390
|
-
*/
|
|
1391
|
-
private _classifyRecoveredChatTurn;
|
|
1392
|
-
/**
|
|
1393
|
-
* The retry/continue/skip decision for a recovered chat turn, run after the
|
|
1394
|
-
* partial is persisted and the stream completed. A NEW turn that left no
|
|
1395
|
-
* persisted assistant partial (the leaf is still the user message) is re-run
|
|
1396
|
-
* fresh instead of continued (which would clone + merge into the previous
|
|
1397
|
-
* assistant turn — #1691); this lost-partial check is re-derived here from the
|
|
1398
|
-
* now-updated leaf rather than carried from classify.
|
|
1399
|
-
*/
|
|
1400
|
-
private _dispatchRecoveredChatTurn;
|
|
1401
717
|
/**
|
|
1402
718
|
* Called when an interrupted chat stream is detected after restart.
|
|
1403
719
|
* Return options to control recovery:
|
|
@@ -1415,132 +731,27 @@ declare class AIChatAgent<
|
|
|
1415
731
|
protected onChatRecovery(
|
|
1416
732
|
_ctx: ChatRecoveryContext$1
|
|
1417
733
|
): Promise<ChatRecoveryOptions$1 | void>;
|
|
734
|
+
/** A continue an earlier version scheduled by name: carried onto the lane. */
|
|
1418
735
|
_chatRecoveryContinue(data?: ChatRecoveryContinueData): Promise<void>;
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
onTurnStarted?: () => void
|
|
1422
|
-
): Promise<void>;
|
|
1423
|
-
private _applyRecoveredRequestContext;
|
|
1424
|
-
/**
|
|
1425
|
-
* Route a live stream stall (the {@link chatStreamStallTimeoutMs} watchdog
|
|
1426
|
-
* fired) into the same bounded-recovery machinery a deploy/eviction
|
|
1427
|
-
* interruption uses (#1626). Mirrors `@cloudflare/think`'s stall path: open or
|
|
1428
|
-
* reuse the incident under the turn's recovery identity, deliver terminal UX
|
|
1429
|
-
* if the budget is spent, otherwise schedule a `_chatRecoveryContinue`.
|
|
1430
|
-
*
|
|
1431
|
-
* Unlike Think there is no durable-submission layer to complete here, so the
|
|
1432
|
-
* schedule payload carries no `recoveredRequestId`.
|
|
1433
|
-
*
|
|
1434
|
-
* Returns `"exhausted"` when the budget was spent (terminal UX already
|
|
1435
|
-
* delivered), `"scheduled"` when a continuation was queued, or `"declined"`
|
|
1436
|
-
* / `"failed"` when `onChatRecovery` opted out or threw — the caller then
|
|
1437
|
-
* delivers the ordinary terminal error.
|
|
1438
|
-
*/
|
|
1439
|
-
private _routeStallToBoundedRecovery;
|
|
1440
|
-
/** Incidents whose running recovery attempt scheduled the next attempt. */
|
|
1441
|
-
private _rescheduledRecoveryIncidents;
|
|
1442
|
-
private _takeRecoveryReschedule;
|
|
1443
|
-
/**
|
|
1444
|
-
* {@link _routeStallToBoundedRecovery} for the stream `catch`: a routing
|
|
1445
|
-
* failure (e.g. a rejected incident write) degrades to `"failed"`, so the
|
|
1446
|
-
* caller still delivers its terminal error frame.
|
|
1447
|
-
*/
|
|
1448
|
-
private _routeStreamInterruption;
|
|
1449
|
-
/**
|
|
1450
|
-
* Reschedule a recovery callback that timed out waiting for stable state,
|
|
1451
|
-
* consuming one attempt. Returns `true` if rescheduled, `false` if the
|
|
1452
|
-
* attempt budget is exhausted (caller should then fail terminally).
|
|
1453
|
-
*/
|
|
1454
|
-
private _rescheduleRecoveryAfterStableTimeout;
|
|
1455
|
-
/**
|
|
1456
|
-
* Park a recovery continuation that timed out waiting for stable state
|
|
1457
|
-
* because the turn is holding a pending CLIENT interaction (an
|
|
1458
|
-
* `input-available` client-tool part or an `approval-requested` part — see
|
|
1459
|
-
* `hasPendingClientInteraction`). Such a turn is WAITING ON THE HUMAN, not
|
|
1460
|
-
* stuck: the client replays the interrupted tool-result / approval after
|
|
1461
|
-
* reconnect, which drives a fresh continuation independently of the recovery
|
|
1462
|
-
* retry loop. Burning the attempt budget on that wait (each `waitUntilStable`
|
|
1463
|
-
* times out because the human hasn't answered) would seal a perfectly healthy
|
|
1464
|
-
* turn on `stable_timeout` — the symptom behind HITL "session recovery errors"
|
|
1465
|
-
* under deploy churn.
|
|
1466
|
-
*
|
|
1467
|
-
* So instead of rescheduling or exhausting, we stop the loop and mark the
|
|
1468
|
-
* incident `skipped` (reason `awaiting_client_interaction`). That retains the
|
|
1469
|
-
* incident record (a later genuine interruption re-evaluates it) while
|
|
1470
|
-
* resolving the live "recovering…" indicator via `_updateChatRecoveryIncident`
|
|
1471
|
-
* so the client sees the parked tool-call UI rather than an eternal spinner.
|
|
1472
|
-
* A client that never returns is reclaimed by the incident TTL sweep and DO
|
|
1473
|
-
* idle-eviction. SERVER-tool orphans are excluded by `hasPendingClientInteraction`
|
|
1474
|
-
* (their `execute` died with the isolate), so they still reschedule / exhaust
|
|
1475
|
-
* via the normal path. Mirrors the same helper in `@cloudflare/think`.
|
|
1476
|
-
*
|
|
1477
|
-
* Returns `true` when the recovery was parked (caller must return), `false`
|
|
1478
|
-
* when there is no pending client interaction (caller proceeds to the normal
|
|
1479
|
-
* reschedule / exhaustion path).
|
|
1480
|
-
*/
|
|
1481
|
-
private _parkRecoveryForPendingInteraction;
|
|
736
|
+
/** A retry an earlier version scheduled by name: carried onto the lane. */
|
|
737
|
+
_chatRecoveryRetry(data?: ChatRecoveryRetryData): Promise<void>;
|
|
1482
738
|
/**
|
|
1483
|
-
*
|
|
1484
|
-
*
|
|
1485
|
-
*
|
|
1486
|
-
* `
|
|
1487
|
-
* `terminalMessage`.
|
|
1488
|
-
*
|
|
1489
|
-
* This replaces the older give-up that only set the incident to `failed`,
|
|
1490
|
-
* which bypassed `_exhaustChatRecovery` entirely — so an app relying on
|
|
1491
|
-
* `onExhausted` for the terminal banner regressed to an eternal spinner when
|
|
1492
|
-
* recovery gave up under extreme churn. Shared by `_chatRecoveryRetry` and
|
|
1493
|
-
* `_chatRecoveryContinue`; mirrors the same helper in `@cloudflare/think`.
|
|
739
|
+
* Store `messages` as the transcript and broadcast it to every tab except
|
|
740
|
+
* `excludeBroadcastIds`. A message whose stored copy is the same is not
|
|
741
|
+
* written again. Override it to see or change what is stored; call
|
|
742
|
+
* `super.persistMessages` to write.
|
|
1494
743
|
*
|
|
1495
|
-
*
|
|
1496
|
-
*
|
|
1497
|
-
*
|
|
1498
|
-
*
|
|
1499
|
-
*
|
|
1500
|
-
* failed read synthesizes the incident and a failed seal write costs at most
|
|
1501
|
-
* a re-delivered banner on a duplicate alarm.
|
|
744
|
+
* A persist a turn makes (a client request's messages, the turn's reply)
|
|
745
|
+
* writes nothing once the chat was cleared since the turn started, checked
|
|
746
|
+
* before each write. The check follows the call through an override, and
|
|
747
|
+
* ends when that call returns: a persist started from work the override
|
|
748
|
+
* left running writes as any other call does.
|
|
1502
749
|
*
|
|
1503
|
-
*
|
|
1504
|
-
*
|
|
1505
|
-
*
|
|
1506
|
-
*
|
|
1507
|
-
* synthesized incident can't be persisted (no key), so the guard can't
|
|
1508
|
-
* arm.
|
|
1509
|
-
* • The record is swept AGAIN between two alarms (the guard re-persists on
|
|
1510
|
-
* the first, so this needs a second independent sweep) — vanishingly
|
|
1511
|
-
* unlikely.
|
|
1512
|
-
*/
|
|
1513
|
-
/**
|
|
1514
|
-
* Host memory-limit policy hook (#1825), dispatched structurally by
|
|
1515
|
-
* Lifecycle's circuit breaker — protected because it is framework
|
|
1516
|
-
* machinery, not part of the public chat API. Tasks applies the breaker to
|
|
1517
|
-
* root recovery runs; the routed dynamic-agent fallback applies it to
|
|
1518
|
-
* `recoveryLoop` schedule rows (see `RecoveryLoopScheduleOptions`). At the
|
|
1519
|
-
* strike budget this hook seals active incidents via
|
|
1520
|
-
* {@link _cf_sealMemoryLimitedRecovery}.
|
|
1521
|
-
*/
|
|
1522
|
-
protected onAlarmMemoryLimit(context: {
|
|
1523
|
-
readonly sealed: boolean;
|
|
1524
|
-
}): Promise<void>;
|
|
1525
|
-
/**
|
|
1526
|
-
* Seal any still-live recovery incident as an out-of-memory exhaustion
|
|
1527
|
-
* when the alarm circuit breaker trips at its strike budget (#1825). Runs
|
|
1528
|
-
* at the outermost alarm frame (post-unwind), so the terminal banner /
|
|
1529
|
-
* `onExhausted` and the sealed-incident write can land where mid-turn
|
|
1530
|
-
* writes OOMed. Reuses the shared give-up spine via the recovery engine.
|
|
750
|
+
* Appending a message while a client tool call is waiting on its result
|
|
751
|
+
* (a status note, say) moves the conversation on. When the result
|
|
752
|
+
* arrives it is stored, but the reply is not continued: the next turn
|
|
753
|
+
* reads the result. See `chat:continuation:dropped` with `moved_on`.
|
|
1531
754
|
*/
|
|
1532
|
-
private _cf_sealMemoryLimitedRecovery;
|
|
1533
|
-
private _exhaustRecoveryAfterStableTimeout;
|
|
1534
|
-
private _shouldRetryRecoveredPreStreamTurn;
|
|
1535
|
-
_chatRecoveryRetry(data?: ChatRecoveryRetryData): Promise<void>;
|
|
1536
|
-
protected _chatRecoveryRetryDetached(
|
|
1537
|
-
data?: ChatRecoveryRetryData,
|
|
1538
|
-
onTurnStarted?: () => void
|
|
1539
|
-
): Promise<void>;
|
|
1540
|
-
/**
|
|
1541
|
-
* Extract partial text and parts from stored stream chunks.
|
|
1542
|
-
*/
|
|
1543
|
-
private _getPartialStreamText;
|
|
1544
755
|
persistMessages(
|
|
1545
756
|
messages: UIMessage[],
|
|
1546
757
|
excludeBroadcastIds?: string[],
|
|
@@ -1548,17 +759,6 @@ declare class AIChatAgent<
|
|
|
1548
759
|
_deleteStaleRows?: boolean;
|
|
1549
760
|
}
|
|
1550
761
|
): Promise<void>;
|
|
1551
|
-
/**
|
|
1552
|
-
* Finds an existing assistant message that contains a tool part with the given toolCallId.
|
|
1553
|
-
* Used to detect when a tool result should update an existing message rather than
|
|
1554
|
-
* creating a new one.
|
|
1555
|
-
*
|
|
1556
|
-
* @param toolCallId - The tool call ID to search for
|
|
1557
|
-
* @returns The existing message if found, undefined otherwise
|
|
1558
|
-
*/
|
|
1559
|
-
private _findMessageByToolCallId;
|
|
1560
|
-
private _findLastAssistantMessage;
|
|
1561
|
-
private _createStreamingAssistantMessage;
|
|
1562
762
|
/**
|
|
1563
763
|
* Applies the ai-chat-specific normalization Sessions does not do.
|
|
1564
764
|
*
|
|
@@ -1580,121 +780,11 @@ declare class AIChatAgent<
|
|
|
1580
780
|
* @returns A new message with ai-chat's normalization applied
|
|
1581
781
|
*/
|
|
1582
782
|
private _sanitizeMessageForPersistence;
|
|
1583
|
-
/**
|
|
1584
|
-
* Truncates large string values in `input` and `output` of tool parts that
|
|
1585
|
-
* were executed server-side by the provider (e.g. Anthropic code_execution,
|
|
1586
|
-
* text_editor). These payloads can be 200KB+ and are dead weight once the
|
|
1587
|
-
* model has consumed the result.
|
|
1588
|
-
*
|
|
1589
|
-
* Anthropic web tools are excluded because their outputs are replayed on
|
|
1590
|
-
* subsequent turns. Within other tool payloads, opaque encrypted fields are
|
|
1591
|
-
* always preserved verbatim.
|
|
1592
|
-
*/
|
|
1593
|
-
private static _truncateProviderExecutedToolPayloads;
|
|
1594
|
-
/**
|
|
1595
|
-
* Recursively walks a value and truncates any string exceeding
|
|
1596
|
-
* `PROVIDER_TOOL_MAX_STRING_LENGTH`, appending a size marker.
|
|
1597
|
-
*
|
|
1598
|
-
* The total output (content + marker) is kept within the threshold so
|
|
1599
|
-
* re-running this function on already-truncated data is a no-op. Strings
|
|
1600
|
-
* under opaque encrypted keys are preserved verbatim.
|
|
1601
|
-
*/
|
|
1602
|
-
private static _truncateLargeStrings;
|
|
1603
|
-
private static _shouldPreserveProviderToolPayload;
|
|
1604
|
-
private static _getToolNameFromPart;
|
|
1605
|
-
private static _isOpaqueReplayFieldKey;
|
|
1606
783
|
/**
|
|
1607
784
|
* Delete message rows through Sessions. The change feed removes them from
|
|
1608
785
|
* `this.messages`.
|
|
1609
786
|
*/
|
|
1610
787
|
private _deleteMessagesByIds;
|
|
1611
|
-
/**
|
|
1612
|
-
* Shared helper for finding a tool part by toolCallId and applying an update.
|
|
1613
|
-
* Handles both streaming (in-memory) and persisted (SQLite) messages.
|
|
1614
|
-
*
|
|
1615
|
-
* Checks _streamingMessage first (tool results/approvals can arrive while
|
|
1616
|
-
* the AI is still streaming), then retries persisted messages with backoff
|
|
1617
|
-
* in case streaming completes between attempts.
|
|
1618
|
-
*
|
|
1619
|
-
* `applyUpdate` may return its argument by reference (or `{ ...part }`
|
|
1620
|
-
* with no semantic changes) to signal an idempotent no-op — this is
|
|
1621
|
-
* detected via `_isToolPartUnchanged` and short-circuits the SQLite
|
|
1622
|
-
* write and `MESSAGE_UPDATED` broadcast.
|
|
1623
|
-
*
|
|
1624
|
-
* @param toolCallId - The tool call ID to find
|
|
1625
|
-
* @param callerName - Name for log messages (e.g. "_applyToolResult")
|
|
1626
|
-
* @param matchStates - Which tool part states to match
|
|
1627
|
-
* @param applyUpdate - Mutation to apply to the matched part (streaming: in-place, persisted: spread)
|
|
1628
|
-
* @returns true if the update was applied (or matched as an idempotent
|
|
1629
|
-
* no-op), false if no matching part was found
|
|
1630
|
-
*/
|
|
1631
|
-
private _findAndUpdateToolPart;
|
|
1632
|
-
/**
|
|
1633
|
-
* Returns true if `applied` is the same reference as `original`, or if
|
|
1634
|
-
* the two have identical state-relevant fields. Used by
|
|
1635
|
-
* `_findAndUpdateToolPart` to detect idempotent re-applies and skip
|
|
1636
|
-
* SQLite writes plus `MESSAGE_UPDATED` broadcasts.
|
|
1637
|
-
*/
|
|
1638
|
-
private static _isToolPartUnchanged;
|
|
1639
|
-
/**
|
|
1640
|
-
* Serialize a client-tool result/approval apply behind any in-flight apply
|
|
1641
|
-
* (#1649, defensive). Each apply is a read-modify-write of the message and
|
|
1642
|
-
* parallel tool results arrive as independent WebSocket messages. Today
|
|
1643
|
-
* `_findAndUpdateToolPart` performs that read-modify-write synchronously (no
|
|
1644
|
-
* await between reading `this.messages` and the SQLite write), so concurrent
|
|
1645
|
-
* applies can't actually interleave — unlike Think, ai-chat does not exhibit
|
|
1646
|
-
* the #1649 clobber. This queue is a guard so the invariant survives if the
|
|
1647
|
-
* apply ever gains an await between read and write (e.g. async storage): each
|
|
1648
|
-
* apply commits atomically in arrival order.
|
|
1649
|
-
*
|
|
1650
|
-
* `_pendingInteractionPromise` is set to the newest link so the barrier's
|
|
1651
|
-
* single-slot wake-up observes the latest apply; because the chain is serial,
|
|
1652
|
-
* awaiting it transitively waits for every predecessor.
|
|
1653
|
-
*
|
|
1654
|
-
* @internal
|
|
1655
|
-
*/
|
|
1656
|
-
protected _enqueueInteractionApply(
|
|
1657
|
-
apply: () => Promise<boolean>
|
|
1658
|
-
): Promise<boolean>;
|
|
1659
|
-
/**
|
|
1660
|
-
* Applies a tool result to an existing assistant message.
|
|
1661
|
-
* This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.
|
|
1662
|
-
* The server is the source of truth, so we update the message here and broadcast
|
|
1663
|
-
* the update to all clients.
|
|
1664
|
-
*
|
|
1665
|
-
* `output-available` and `output-error` are accepted as valid starting
|
|
1666
|
-
* states for *idempotent* re-application — duplicate WS frames, second
|
|
1667
|
-
* tabs re-running the same tool, and provider-replay round-trips all
|
|
1668
|
-
* become silent no-ops rather than a warn + skipped update. The first
|
|
1669
|
-
* applied terminal result wins; subsequent results carrying *different*
|
|
1670
|
-
* data are also dropped (preserving the existing "first write wins"
|
|
1671
|
-
* contract — see `client-tool-duplicate-message.test.ts`). See issue
|
|
1672
|
-
* #1404.
|
|
1673
|
-
*
|
|
1674
|
-
* @param toolCallId - The tool call ID this result is for
|
|
1675
|
-
* @param _toolName - The name of the tool (unused, kept for API compat)
|
|
1676
|
-
* @param output - The output from the tool execution
|
|
1677
|
-
* @param overrideState - Optional state override ("output-error" to signal denial/failure)
|
|
1678
|
-
* @param errorText - Error message when overrideState is "output-error"
|
|
1679
|
-
* @returns true if the result was applied, false if the message was not found
|
|
1680
|
-
*/
|
|
1681
|
-
private _applyToolResult;
|
|
1682
|
-
private _streamSSEReply;
|
|
1683
|
-
private _sendPlaintextReply;
|
|
1684
|
-
/**
|
|
1685
|
-
* Applies a tool approval response from the client, updating the persisted message.
|
|
1686
|
-
* This is called when the client sends CF_AGENT_TOOL_APPROVAL for tools with needsApproval.
|
|
1687
|
-
*
|
|
1688
|
-
* - approved=true transitions to approval-responded
|
|
1689
|
-
* - approved=false transitions to output-denied so convertToModelMessages
|
|
1690
|
-
* emits a tool_result for providers (e.g. Anthropic) that require it.
|
|
1691
|
-
*
|
|
1692
|
-
* @param toolCallId - The tool call ID this approval is for
|
|
1693
|
-
* @param approved - Whether the tool execution was approved
|
|
1694
|
-
* @returns true if the approval was applied, false if the message was not found
|
|
1695
|
-
*/
|
|
1696
|
-
private _applyToolApproval;
|
|
1697
|
-
private _reply;
|
|
1698
788
|
/**
|
|
1699
789
|
* When the DO is destroyed, cancel all pending requests and clean up resources
|
|
1700
790
|
*/
|
|
@@ -1716,6 +806,7 @@ export {
|
|
|
1716
806
|
type ResolvedChatRecoveryConfig,
|
|
1717
807
|
type SaveMessagesOptions,
|
|
1718
808
|
type SaveMessagesResult,
|
|
809
|
+
type SkippedTurnReason,
|
|
1719
810
|
createToolsFromClientSchemas
|
|
1720
811
|
};
|
|
1721
812
|
//# sourceMappingURL=index.d.ts.map
|