@cloudflare/ai-chat 0.11.0 → 0.12.1
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 +250 -121
- package/dist/index.js +840 -313
- package/dist/index.js.map +1 -1
- package/dist/react.d.ts +4 -0
- package/package.json +4 -3
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
Agent,
|
|
3
3
|
AgentContext,
|
|
4
|
+
AgentToolEventDelivery,
|
|
4
5
|
AgentToolLifecycleResult,
|
|
5
6
|
AgentToolMilestone,
|
|
6
7
|
AgentToolProgress,
|
|
@@ -20,6 +21,7 @@ import {
|
|
|
20
21
|
ChatRecoveryProgressContext,
|
|
21
22
|
ChatResponseResult,
|
|
22
23
|
ChatResponseResult as ChatResponseResult$1,
|
|
24
|
+
ChatTurnOutcome,
|
|
23
25
|
ClientToolSchema,
|
|
24
26
|
ClientToolSchema as ClientToolSchema$1,
|
|
25
27
|
MessageConcurrency,
|
|
@@ -33,12 +35,15 @@ import {
|
|
|
33
35
|
SaveMessagesResult as SaveMessagesResult$1,
|
|
34
36
|
createToolsFromClientSchemas
|
|
35
37
|
} from "agents/chat";
|
|
38
|
+
import { Sessions } from "agents/sessions";
|
|
36
39
|
import { GenerateTextOnFinishCallback, ToolSet, UIMessage } from "ai";
|
|
40
|
+
import { Streams } from "agents/streams";
|
|
37
41
|
|
|
38
42
|
//#region src/index.d.ts
|
|
39
43
|
type ChatRecoveryRetryData = {
|
|
40
44
|
targetUserId?: string;
|
|
41
45
|
originalRequestId?: string;
|
|
46
|
+
originMessageIds?: string[];
|
|
42
47
|
incidentId?: string;
|
|
43
48
|
lastBody?: Record<string, unknown> | null;
|
|
44
49
|
lastClientTools?: ClientToolSchema$1[] | null;
|
|
@@ -46,6 +51,7 @@ type ChatRecoveryRetryData = {
|
|
|
46
51
|
type ChatRecoveryContinueData = {
|
|
47
52
|
targetAssistantId?: string;
|
|
48
53
|
originalRequestId?: string;
|
|
54
|
+
originMessageIds?: string[];
|
|
49
55
|
incidentId?: string;
|
|
50
56
|
lastBody?: Record<string, unknown> | null;
|
|
51
57
|
lastClientTools?: ClientToolSchema$1[] | null;
|
|
@@ -100,21 +106,51 @@ type OnChatMessageOptions = {
|
|
|
100
106
|
*/
|
|
101
107
|
continuation?: boolean;
|
|
102
108
|
};
|
|
103
|
-
/**
|
|
104
|
-
* Extension of Agent with built-in chat capabilities
|
|
105
|
-
* @template Env Environment type containing bindings
|
|
106
|
-
*/
|
|
107
109
|
declare class AIChatAgent<
|
|
108
110
|
Env extends Cloudflare.Env = Cloudflare.Env,
|
|
109
111
|
State = unknown,
|
|
110
|
-
Props extends
|
|
112
|
+
Props extends object = object
|
|
111
113
|
> extends Agent<Env, State, Props> {
|
|
114
|
+
#private;
|
|
112
115
|
private _activeChatRecoveryRootRequestId;
|
|
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();
|
|
113
124
|
/**
|
|
114
125
|
* Registry of per-request AbortControllers.
|
|
115
126
|
* Used to propagate cancellation signals for any external calls made by the agent.
|
|
116
127
|
*/
|
|
117
128
|
private _abortRegistry;
|
|
129
|
+
/** Durable chat history for this Agent. */
|
|
130
|
+
readonly sessions: Sessions;
|
|
131
|
+
/**
|
|
132
|
+
* Byte budget for wake-time transcript hydration into {@link messages}.
|
|
133
|
+
*
|
|
134
|
+
* `onStart` hydrates through `session.getRecentHistory(budget, …)`. The
|
|
135
|
+
* budget counts each stored row plus the continuation rows it was split
|
|
136
|
+
* across, so it bounds isolate memory: an oversized transcript hydrates
|
|
137
|
+
* as a bounded recent window
|
|
138
|
+
* instead of exhausting the isolate. Durable storage is never truncated by
|
|
139
|
+
* this — `sessions.session().getHistory()` still reads the full path, and
|
|
140
|
+
* the streamed `get-messages` route still serves every message.
|
|
141
|
+
*
|
|
142
|
+
* Set to `Number.POSITIVE_INFINITY` (or any non-positive value) to disable
|
|
143
|
+
* windowing and always hydrate the whole transcript.
|
|
144
|
+
*
|
|
145
|
+
* @default 32 * 1024 * 1024
|
|
146
|
+
*/
|
|
147
|
+
hydrationByteBudget: number;
|
|
148
|
+
/**
|
|
149
|
+
* The Streams capability backing `_resumableStream`: chat's in-flight
|
|
150
|
+
* output lives in the shared durable chunk log, readable by any
|
|
151
|
+
* `streams.read()` consumer on this Durable Object.
|
|
152
|
+
*/
|
|
153
|
+
readonly streams: Streams;
|
|
118
154
|
/**
|
|
119
155
|
* Resumable stream manager -- handles chunk buffering, persistence, and replay.
|
|
120
156
|
* @internal Protected for testing purposes.
|
|
@@ -234,6 +270,8 @@ declare class AIChatAgent<
|
|
|
234
270
|
private _agentToolLastErrors;
|
|
235
271
|
private _agentToolPreTurnAssistantIds;
|
|
236
272
|
private _agentToolLiveSequences;
|
|
273
|
+
/** Runs started with `eventDelivery: "terminal"`: their chunks are not broadcast. */
|
|
274
|
+
private _agentToolTerminalOnlyRuns;
|
|
237
275
|
/**
|
|
238
276
|
* Request id → run id for in-flight agent-tool turns (null = resolved as
|
|
239
277
|
* not an agent-tool turn, cached so unrelated turns don't re-query SQLite
|
|
@@ -255,13 +293,6 @@ declare class AIChatAgent<
|
|
|
255
293
|
* @internal
|
|
256
294
|
*/
|
|
257
295
|
protected _lastBody: Record<string, unknown> | undefined;
|
|
258
|
-
/**
|
|
259
|
-
* Cache of last-persisted JSON for each message ID.
|
|
260
|
-
* Used for incremental persistence: skip SQL writes for unchanged messages.
|
|
261
|
-
* Lost on hibernation, repopulated from SQLite on wake.
|
|
262
|
-
* @internal
|
|
263
|
-
*/
|
|
264
|
-
private _persistedMessageCache;
|
|
265
296
|
/**
|
|
266
297
|
* Shared auto-continuation barrier (#1649 / #1650): owns the coalesce timer
|
|
267
298
|
* and the double-fire guard. Parameterized by this agent's stream-active
|
|
@@ -345,7 +376,44 @@ declare class AIChatAgent<
|
|
|
345
376
|
| {
|
|
346
377
|
timeout: number;
|
|
347
378
|
};
|
|
379
|
+
/**
|
|
380
|
+
* Live chat-turn closures keyed by run nonce. A closure exists only in the
|
|
381
|
+
* isolate that accepted the turn; recovery after interruption never re-runs
|
|
382
|
+
* it — the definition's `recover` callback hands the interruption to the
|
|
383
|
+
* shared ChatRecoveryEngine instead.
|
|
384
|
+
*/
|
|
385
|
+
private readonly _liveChatTurnClosures;
|
|
386
|
+
/**
|
|
387
|
+
* Register the shared chat-turn Task definition (see
|
|
388
|
+
* `agents/chat` `createChatTurnTaskDefinition` for the turn logic): the
|
|
389
|
+
* host wires its protected internals through the hooks.
|
|
390
|
+
*/
|
|
391
|
+
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;
|
|
348
415
|
private _runChatRecoveryFiber;
|
|
416
|
+
private _runWrappedChatRecoveryFiber;
|
|
349
417
|
/**
|
|
350
418
|
* Array of chat messages for the current conversation.
|
|
351
419
|
*
|
|
@@ -359,6 +427,12 @@ declare class AIChatAgent<
|
|
|
359
427
|
msg: string | ArrayBuffer | ArrayBufferView,
|
|
360
428
|
without?: string[]
|
|
361
429
|
): 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;
|
|
362
436
|
/**
|
|
363
437
|
* Resolve the agent-tool run whose turn owns a request id, or null when the
|
|
364
438
|
* request is not an agent-tool turn. Falls back to the persisted run row
|
|
@@ -430,48 +504,38 @@ declare class AIChatAgent<
|
|
|
430
504
|
}
|
|
431
505
|
): string;
|
|
432
506
|
/** @internal Delegate to _resumableStream */
|
|
433
|
-
protected _completeStream(streamId: string): void;
|
|
507
|
+
protected _completeStream(streamId: string, outcome?: ChatTurnOutcome): void;
|
|
434
508
|
/**
|
|
435
|
-
*
|
|
436
|
-
*
|
|
437
|
-
*
|
|
438
|
-
* {@link ResumableStream} only fires when a *subsequent* stream completes,
|
|
439
|
-
* which never happens for a chat that receives a single turn (#1706).
|
|
440
|
-
*
|
|
441
|
-
* `idempotent` dedupes on (callback, payload, owner) so repeated finishes
|
|
442
|
-
* collapse onto one pending alarm rather than stacking.
|
|
443
|
-
* @internal
|
|
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.
|
|
444
512
|
*/
|
|
445
|
-
protected
|
|
446
|
-
|
|
447
|
-
}?: {
|
|
448
|
-
idempotent?: boolean;
|
|
449
|
-
}): Promise<void>;
|
|
513
|
+
protected _finishStream(streamId: string, outcome?: ChatTurnOutcome): void;
|
|
514
|
+
private _afterStreamFinished;
|
|
450
515
|
/**
|
|
451
|
-
*
|
|
452
|
-
*
|
|
453
|
-
*
|
|
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.
|
|
454
519
|
* @internal
|
|
455
520
|
*/
|
|
456
521
|
_cleanupStreamBuffers(): Promise<void>;
|
|
457
|
-
/**
|
|
458
|
-
*
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
*
|
|
462
|
-
*
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
*
|
|
466
|
-
*
|
|
467
|
-
*
|
|
468
|
-
*
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
private _maybeBumpRecoveryProgress;
|
|
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>;
|
|
475
539
|
/** @internal Delegate to _resumableStream */
|
|
476
540
|
protected _flushChunkBuffer(): void;
|
|
477
541
|
/** @internal Delegate to _resumableStream */
|
|
@@ -490,9 +554,8 @@ declare class AIChatAgent<
|
|
|
490
554
|
* `Think` and the client reducer use), replacing a hand-rolled chunk
|
|
491
555
|
* switch; it owns the `start` / `finish` / `message-metadata` handling;
|
|
492
556
|
* - (b) {@link _resolveOrphanTargetId} — the id to persist under (#1691);
|
|
493
|
-
* - (c)+(d) upsert-by-id
|
|
494
|
-
*
|
|
495
|
-
* that `Think._upsertMessageInHistory` implements over a Session tree.
|
|
557
|
+
* - (c)+(d) upsert-by-id through the shared `OrphanPersistStore` shape
|
|
558
|
+
* (`getMessage` → `updateMessage` / `appendMessage`).
|
|
496
559
|
* When a row already owns the id, the shared `reconcileOrphanPartial`
|
|
497
560
|
* merge preserves an in-place tool result rather than letting a replayed
|
|
498
561
|
* chunk re-advance it (ai-chat has an early tool-approval persist; hosts
|
|
@@ -526,9 +589,9 @@ declare class AIChatAgent<
|
|
|
526
589
|
fallbackId: string
|
|
527
590
|
): string;
|
|
528
591
|
/**
|
|
529
|
-
* The orphan-persist store adapter
|
|
530
|
-
*
|
|
531
|
-
* `
|
|
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`
|
|
532
595
|
* array + the existing `persistMessages` whole-array write path, so
|
|
533
596
|
* reconcile/sanitize/row-size/broadcast all stay intact. Each mutating call
|
|
534
597
|
* is exactly one `persistMessages` invocation; `parentId` is unused (a flat
|
|
@@ -608,7 +671,25 @@ declare class AIChatAgent<
|
|
|
608
671
|
* @internal
|
|
609
672
|
*/
|
|
610
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;
|
|
611
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;
|
|
612
693
|
/**
|
|
613
694
|
* Broadcasts a text event for non-SSE responses.
|
|
614
695
|
* This ensures plain text responses follow the AI SDK v5 stream protocol.
|
|
@@ -618,7 +699,27 @@ declare class AIChatAgent<
|
|
|
618
699
|
* @param continuation - Whether this is a continuation of a previous stream
|
|
619
700
|
*/
|
|
620
701
|
private _broadcastTextEvent;
|
|
621
|
-
|
|
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;
|
|
622
723
|
private _tryCatchChat;
|
|
623
724
|
private isChatTurnActive;
|
|
624
725
|
/**
|
|
@@ -715,6 +816,12 @@ declare class AIChatAgent<
|
|
|
715
816
|
* without requiring the caller to know the id.
|
|
716
817
|
*/
|
|
717
818
|
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;
|
|
718
825
|
/**
|
|
719
826
|
* Abort every in-flight chat turn on this agent.
|
|
720
827
|
*
|
|
@@ -814,6 +921,14 @@ declare class AIChatAgent<
|
|
|
814
921
|
*/
|
|
815
922
|
private _hasIncompleteToolBatch;
|
|
816
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;
|
|
817
932
|
/**
|
|
818
933
|
* @returns Terminal status for the turn.
|
|
819
934
|
*/
|
|
@@ -1032,6 +1147,7 @@ declare class AIChatAgent<
|
|
|
1032
1147
|
options: {
|
|
1033
1148
|
runId: string;
|
|
1034
1149
|
signal?: AbortSignal;
|
|
1150
|
+
eventDelivery?: AgentToolEventDelivery;
|
|
1035
1151
|
}
|
|
1036
1152
|
): Promise<AgentToolRunInspection>;
|
|
1037
1153
|
cancelAgentToolRun(runId: string, reason?: unknown): Promise<void>;
|
|
@@ -1073,7 +1189,12 @@ declare class AIChatAgent<
|
|
|
1073
1189
|
* Mirrors `@cloudflare/think`.
|
|
1074
1190
|
*/
|
|
1075
1191
|
private _reconcileOwnStaleAgentToolChildRuns;
|
|
1076
|
-
inspectAgentToolRun(
|
|
1192
|
+
inspectAgentToolRun(
|
|
1193
|
+
runId: string,
|
|
1194
|
+
options?: {
|
|
1195
|
+
reconcile?: boolean;
|
|
1196
|
+
}
|
|
1197
|
+
): Promise<AgentToolRunInspection | null>;
|
|
1077
1198
|
private static _progressSnapshotFromRow;
|
|
1078
1199
|
getAgentToolChunks(
|
|
1079
1200
|
runId: string,
|
|
@@ -1090,6 +1211,16 @@ declare class AIChatAgent<
|
|
|
1090
1211
|
): Promise<ReadableStream<AgentToolStoredChunk>>;
|
|
1091
1212
|
private _getAgentToolRunRow;
|
|
1092
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;
|
|
1093
1224
|
private _getAgentToolStoredChunks;
|
|
1094
1225
|
private _getAgentToolMessagesAfterStart;
|
|
1095
1226
|
private _closeAgentToolTailers;
|
|
@@ -1168,19 +1299,19 @@ declare class AIChatAgent<
|
|
|
1168
1299
|
* recomputed from the live, mutable transcript. Compaction collapses older
|
|
1169
1300
|
* assistant messages into a summary, lowering the count — so a turn that had
|
|
1170
1301
|
* genuinely advanced could read as "no progress" between attempts and exhaust
|
|
1171
|
-
* its budget prematurely (#1628).
|
|
1172
|
-
*
|
|
1173
|
-
*
|
|
1174
|
-
*
|
|
1175
|
-
* re-
|
|
1176
|
-
*
|
|
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.
|
|
1177
1312
|
*/
|
|
1178
1313
|
private _chatRecoveryProgressMarker;
|
|
1179
|
-
|
|
1180
|
-
* `_maybeBumpRecoveryProgress` when new content is streamed (real,
|
|
1181
|
-
* reconnect-immune forward progress). The increment lives in the shared
|
|
1182
|
-
* engine (agents/chat); this is the package binding. */
|
|
1183
|
-
private _bumpChatRecoveryProgress;
|
|
1314
|
+
private _progressSeed;
|
|
1184
1315
|
/** Per-isolate N9 throttle gate (shared `agents/chat` helper); reset per
|
|
1185
1316
|
* isolate so the first forwarded chunk after a restart always credits. */
|
|
1186
1317
|
private _agentToolStreamProgress;
|
|
@@ -1188,7 +1319,9 @@ declare class AIChatAgent<
|
|
|
1188
1319
|
* N9: forwarding a sub-agent's chunks IS forward progress for this parent
|
|
1189
1320
|
* turn, so credit the parent's recovery progress marker — otherwise a parent
|
|
1190
1321
|
* whose turn merely `await`s a child banks no progress of its own and its
|
|
1191
|
-
* no-progress window exhausts while the child is healthily streaming.
|
|
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
|
|
1192
1325
|
* invoked after a child actually produced output (see
|
|
1193
1326
|
* `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.
|
|
1194
1327
|
* Throttled (and reset per isolate) so we never write storage per token.
|
|
@@ -1283,6 +1416,10 @@ declare class AIChatAgent<
|
|
|
1283
1416
|
_ctx: ChatRecoveryContext$1
|
|
1284
1417
|
): Promise<ChatRecoveryOptions$1 | void>;
|
|
1285
1418
|
_chatRecoveryContinue(data?: ChatRecoveryContinueData): Promise<void>;
|
|
1419
|
+
protected _chatRecoveryContinueDetached(
|
|
1420
|
+
data?: ChatRecoveryContinueData,
|
|
1421
|
+
onTurnStarted?: () => void
|
|
1422
|
+
): Promise<void>;
|
|
1286
1423
|
private _applyRecoveredRequestContext;
|
|
1287
1424
|
/**
|
|
1288
1425
|
* Route a live stream stall (the {@link chatStreamStallTimeoutMs} watchdog
|
|
@@ -1295,9 +1432,20 @@ declare class AIChatAgent<
|
|
|
1295
1432
|
* schedule payload carries no `recoveredRequestId`.
|
|
1296
1433
|
*
|
|
1297
1434
|
* Returns `"exhausted"` when the budget was spent (terminal UX already
|
|
1298
|
-
* delivered),
|
|
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.
|
|
1299
1438
|
*/
|
|
1300
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;
|
|
1301
1449
|
/**
|
|
1302
1450
|
* Reschedule a recovery callback that timed out waiting for stable state,
|
|
1303
1451
|
* consuming one attempt. Returns `true` if rescheduled, `false` if the
|
|
@@ -1355,25 +1503,33 @@ declare class AIChatAgent<
|
|
|
1355
1503
|
* Two residual at-least-once edges, both deliberately accepted as "deliver a
|
|
1356
1504
|
* second banner" ≫ "silently drop the turn":
|
|
1357
1505
|
* • No `incidentId` at all in the payload (only reachable via a direct/test
|
|
1358
|
-
* invocation — every production
|
|
1359
|
-
* incident can't be persisted (no key), so the guard can't
|
|
1506
|
+
* invocation — every production recovery enqueue carries one): the
|
|
1507
|
+
* synthesized incident can't be persisted (no key), so the guard can't
|
|
1508
|
+
* arm.
|
|
1360
1509
|
* • The record is swept AGAIN between two alarms (the guard re-persists on
|
|
1361
1510
|
* the first, so this needs a second independent sweep) — vanishingly
|
|
1362
1511
|
* unlikely.
|
|
1363
1512
|
*/
|
|
1364
1513
|
/**
|
|
1365
|
-
*
|
|
1366
|
-
*
|
|
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}.
|
|
1367
1521
|
*/
|
|
1368
|
-
protected
|
|
1522
|
+
protected onAlarmMemoryLimit(context: {
|
|
1523
|
+
readonly sealed: boolean;
|
|
1524
|
+
}): Promise<void>;
|
|
1369
1525
|
/**
|
|
1370
|
-
* Seal any still-live recovery incident as an out-of-memory exhaustion
|
|
1371
|
-
* the alarm circuit breaker trips at its strike budget (#1825). Runs
|
|
1372
|
-
* outermost alarm frame (post-unwind), so the terminal banner /
|
|
1373
|
-
* and the sealed-incident write can land where mid-turn
|
|
1374
|
-
* the shared give-up spine via the recovery engine.
|
|
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.
|
|
1375
1531
|
*/
|
|
1376
|
-
|
|
1532
|
+
private _cf_sealMemoryLimitedRecovery;
|
|
1377
1533
|
private _exhaustRecoveryAfterStableTimeout;
|
|
1378
1534
|
/**
|
|
1379
1535
|
* Apply the tight OOM-retry budget to a recovery error (#1825). Symmetric with
|
|
@@ -1399,6 +1555,10 @@ declare class AIChatAgent<
|
|
|
1399
1555
|
private _handleRecoveryOom;
|
|
1400
1556
|
private _shouldRetryRecoveredPreStreamTurn;
|
|
1401
1557
|
_chatRecoveryRetry(data?: ChatRecoveryRetryData): Promise<void>;
|
|
1558
|
+
protected _chatRecoveryRetryDetached(
|
|
1559
|
+
data?: ChatRecoveryRetryData,
|
|
1560
|
+
onTurnStarted?: () => void
|
|
1561
|
+
): Promise<void>;
|
|
1402
1562
|
/**
|
|
1403
1563
|
* Extract partial text and parts from stored stream chunks.
|
|
1404
1564
|
*/
|
|
@@ -1422,32 +1582,24 @@ declare class AIChatAgent<
|
|
|
1422
1582
|
private _findLastAssistantMessage;
|
|
1423
1583
|
private _createStreamingAssistantMessage;
|
|
1424
1584
|
/**
|
|
1425
|
-
*
|
|
1426
|
-
* data that should not be stored or sent back in subsequent requests.
|
|
1585
|
+
* Applies the ai-chat-specific normalization Sessions does not do.
|
|
1427
1586
|
*
|
|
1428
|
-
*
|
|
1587
|
+
* Sessions already strips OpenAI ephemeral fields (itemId,
|
|
1588
|
+
* reasoningEncryptedContent) and drops truly empty reasoning parts on every
|
|
1589
|
+
* write, so those steps are not repeated here.
|
|
1429
1590
|
*
|
|
1430
|
-
*
|
|
1431
|
-
* (v2.0.x+) defaults to using OpenAI's Responses API which assigns unique
|
|
1432
|
-
* itemIds and reasoningEncryptedContent to message parts. When persisted
|
|
1433
|
-
* and sent back, OpenAI rejects duplicate itemIds.
|
|
1591
|
+
* Pipeline:
|
|
1434
1592
|
*
|
|
1435
|
-
*
|
|
1593
|
+
* 1. **Truncate provider-executed tool payloads**: Server-side tool
|
|
1436
1594
|
* executions (e.g. Anthropic code_execution, text_editor) can produce
|
|
1437
1595
|
* 200KB+ payloads in `input` and `output`. These are truncated since the
|
|
1438
1596
|
* model has already consumed the results.
|
|
1439
1597
|
*
|
|
1440
|
-
*
|
|
1441
|
-
* with no text and no remaining providerMetadata are removed. Parts that
|
|
1442
|
-
* still carry providerMetadata (e.g. Anthropic's redacted_thinking blocks
|
|
1443
|
-
* with providerMetadata.anthropic.redactedData) are preserved, as they
|
|
1444
|
-
* contain data required for round-tripping with the provider API.
|
|
1445
|
-
*
|
|
1446
|
-
* 4. **User hook**: Calls the overridable `sanitizeMessageForPersistence()`
|
|
1598
|
+
* 2. **User hook**: Calls the overridable `sanitizeMessageForPersistence()`
|
|
1447
1599
|
* method, allowing subclasses to apply custom transformations.
|
|
1448
1600
|
*
|
|
1449
1601
|
* @param message - The message to sanitize
|
|
1450
|
-
* @returns A new message with
|
|
1602
|
+
* @returns A new message with ai-chat's normalization applied
|
|
1451
1603
|
*/
|
|
1452
1604
|
private _sanitizeMessageForPersistence;
|
|
1453
1605
|
/**
|
|
@@ -1474,33 +1626,10 @@ declare class AIChatAgent<
|
|
|
1474
1626
|
private static _getToolNameFromPart;
|
|
1475
1627
|
private static _isOpaqueReplayFieldKey;
|
|
1476
1628
|
/**
|
|
1477
|
-
* Delete
|
|
1478
|
-
*
|
|
1479
|
-
* 100 bound-parameter limit. No-op for an empty list.
|
|
1480
|
-
* @internal
|
|
1629
|
+
* Delete message rows through Sessions. The change feed removes them from
|
|
1630
|
+
* `this.messages`.
|
|
1481
1631
|
*/
|
|
1482
1632
|
private _deleteMessagesByIds;
|
|
1483
|
-
/**
|
|
1484
|
-
* Deletes oldest messages from SQLite when the count exceeds maxPersistedMessages.
|
|
1485
|
-
* Called after each persist to keep storage bounded.
|
|
1486
|
-
*/
|
|
1487
|
-
private _enforceMaxPersistedMessages;
|
|
1488
|
-
/**
|
|
1489
|
-
* Enforces SQLite row size limits by compacting tool outputs and text parts
|
|
1490
|
-
* when a serialized message exceeds the safety threshold (1.8MB).
|
|
1491
|
-
*
|
|
1492
|
-
* Only fires in pathological cases (extremely large tool outputs or text).
|
|
1493
|
-
* Returns the message unchanged if it fits within limits.
|
|
1494
|
-
*
|
|
1495
|
-
* Compaction strategy:
|
|
1496
|
-
* 1. Compact tool outputs over 1KB (replace with LLM-friendly summary)
|
|
1497
|
-
* 2. If still too big, truncate text parts from oldest to newest
|
|
1498
|
-
* 3. Add metadata so clients can detect compaction
|
|
1499
|
-
*
|
|
1500
|
-
* @param message - The message to check
|
|
1501
|
-
* @returns The message, compacted if necessary
|
|
1502
|
-
*/
|
|
1503
|
-
private _enforceRowSizeLimit;
|
|
1504
1633
|
/**
|
|
1505
1634
|
* Shared helper for finding a tool part by toolCallId and applying an update.
|
|
1506
1635
|
* Handles both streaming (in-memory) and persisted (SQLite) messages.
|