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