@cloudflare/ai-chat 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -33,7 +33,9 @@ import {
33
33
  SaveMessagesResult as SaveMessagesResult$1,
34
34
  createToolsFromClientSchemas
35
35
  } from "agents/chat";
36
+ import { Sessions } from "agents/sessions";
36
37
  import { GenerateTextOnFinishCallback, ToolSet, UIMessage } from "ai";
38
+ import { Streams } from "agents/streams";
37
39
 
38
40
  //#region src/index.d.ts
39
41
  type ChatRecoveryRetryData = {
@@ -100,21 +102,43 @@ type OnChatMessageOptions = {
100
102
  */
101
103
  continuation?: boolean;
102
104
  };
103
- /**
104
- * Extension of Agent with built-in chat capabilities
105
- * @template Env Environment type containing bindings
106
- */
107
105
  declare class AIChatAgent<
108
106
  Env extends Cloudflare.Env = Cloudflare.Env,
109
107
  State = unknown,
110
108
  Props extends Record<string, unknown> = Record<string, unknown>
111
109
  > extends Agent<Env, State, Props> {
110
+ #private;
112
111
  private _activeChatRecoveryRootRequestId;
113
112
  /**
114
113
  * Registry of per-request AbortControllers.
115
114
  * Used to propagate cancellation signals for any external calls made by the agent.
116
115
  */
117
116
  private _abortRegistry;
117
+ /** Durable chat history for this Agent. */
118
+ readonly sessions: Sessions;
119
+ /**
120
+ * Byte budget for wake-time transcript hydration into {@link messages}.
121
+ *
122
+ * `onStart` hydrates through `session.getRecentHistory(budget, …)`. The
123
+ * budget counts each stored row plus the continuation rows it was split
124
+ * across, so it bounds isolate memory: an oversized transcript hydrates
125
+ * as a bounded recent window
126
+ * instead of exhausting the isolate. Durable storage is never truncated by
127
+ * this — `sessions.session().getHistory()` still reads the full path, and
128
+ * the streamed `get-messages` route still serves every message.
129
+ *
130
+ * Set to `Number.POSITIVE_INFINITY` (or any non-positive value) to disable
131
+ * windowing and always hydrate the whole transcript.
132
+ *
133
+ * @default 32 * 1024 * 1024
134
+ */
135
+ hydrationByteBudget: number;
136
+ /**
137
+ * The Streams capability backing `_resumableStream`: chat's in-flight
138
+ * output lives in the shared durable chunk log, readable by any
139
+ * `streams.read()` consumer on this Durable Object.
140
+ */
141
+ readonly streams: Streams;
118
142
  /**
119
143
  * Resumable stream manager -- handles chunk buffering, persistence, and replay.
120
144
  * @internal Protected for testing purposes.
@@ -255,13 +279,6 @@ declare class AIChatAgent<
255
279
  * @internal
256
280
  */
257
281
  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
282
  /**
266
283
  * Shared auto-continuation barrier (#1649 / #1650): owns the coalesce timer
267
284
  * and the double-fire guard. Parameterized by this agent's stream-active
@@ -345,6 +362,35 @@ declare class AIChatAgent<
345
362
  | {
346
363
  timeout: number;
347
364
  };
365
+ /**
366
+ * Live chat-turn closures keyed by run nonce. A closure exists only in the
367
+ * isolate that accepted the turn; recovery after interruption never re-runs
368
+ * it — the definition's `recover` callback hands the interruption to the
369
+ * shared ChatRecoveryEngine instead.
370
+ */
371
+ private readonly _liveChatTurnClosures;
372
+ /**
373
+ * Register the shared chat-turn Task definition (see
374
+ * `agents/chat` `createChatTurnTaskDefinition` for the turn logic): the
375
+ * host wires its protected internals through the hooks.
376
+ */
377
+ private _registerChatTurnTaskDefinition;
378
+ /** Register the shared Tasks transport for recovery continuations. */
379
+ private _registerChatRecoveryTaskDefinition;
380
+ /**
381
+ * Run a queue-driven recovery callback to its model handoff and return;
382
+ * the turn continues as tracked alarm work, and a detached platform
383
+ * failure enqueues one replacement attempt through the same transport.
384
+ */
385
+ private _dispatchChatRecovery;
386
+ /**
387
+ * Enqueue one recovery attempt on the shared Tasks transport. Tasks
388
+ * mirrors a routed dynamic agent's wake to the root's alarm; the run
389
+ * itself, and this continuation's replay, still execute here. `dedupeKey`
390
+ * keys a retried enqueue so it joins its own prior attempt instead of
391
+ * duplicating it — see {@link chatRecoveryTaskRunOptions}.
392
+ */
393
+ private _enqueueChatRecovery;
348
394
  private _runChatRecoveryFiber;
349
395
  /**
350
396
  * Array of chat messages for the current conversation.
@@ -432,46 +478,33 @@ declare class AIChatAgent<
432
478
  /** @internal Delegate to _resumableStream */
433
479
  protected _completeStream(streamId: string): void;
434
480
  /**
435
- * Ensure a single cleanup alarm is pending for this DO's resumable-stream
436
- * buffers. Armed whenever a stream finishes (completes or errors) so that
437
- * idle/one-off chat DOs still reclaim their buffers — the lazy sweep in
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
481
+ * @internal The producer finished; leave the row for the cutover that
482
+ * persists the message (`persistMessages` via `#pendingCutover`). `_reply`'s
483
+ * finally settles it if no persist follows.
444
484
  */
445
- protected _ensureStreamCleanupScheduled({
446
- idempotent
447
- }?: {
448
- idempotent?: boolean;
449
- }): Promise<void>;
485
+ protected _finishStream(streamId: string): void;
486
+ private _afterStreamFinished;
450
487
  /**
451
- * Alarm callback: sweep aged stream buffers, re-arming while rows remain (see
452
- * the shared {@link cleanupStreamBuffers}). Public so it is reachable as a
453
- * schedule callback.
488
+ * @deprecated Streams are reclaimed at cutover and on the next stream
489
+ * start; no alarm is armed any more. Kept so a cleanup alarm persisted
490
+ * by an earlier version still resolves to a callback when it fires.
454
491
  * @internal
455
492
  */
456
493
  _cleanupStreamBuffers(): Promise<void>;
457
- /** @internal Delegate to _resumableStream. Also advances the recovery
458
- * progress counter at production time (see `_maybeBumpRecoveryProgress`). */
494
+ /**
495
+ * @internal Delegate to _resumableStream.
496
+ *
497
+ * A settled tool result (`tool-output-available` / `-error` / `-denied`)
498
+ * is flushed to SQLite immediately rather than waiting for the packed
499
+ * segment to fill: it captures a completed, often non-idempotent side
500
+ * effect (or a user's denial), and an isolate eviction before the next
501
+ * batch flush would lose it — recovery would re-anchor without it and
502
+ * re-run the tool. The flush is also what the recovery progress marker is
503
+ * derived from (`_chatRecoveryProgressMarker`), so a settled result counts
504
+ * as forward progress the moment it lands, as it did under the old
505
+ * per-chunk counter. Streaming deltas keep the buffer's own packing.
506
+ */
459
507
  protected _storeStreamChunk(streamId: string, body: string): Promise<void>;
460
- /** Per-isolate throttle for crediting recovery progress from mid-segment
461
- * streaming-content deltas (the shared `agents/chat` rule); reset per isolate
462
- * so the first delta after a restart always credits. */
463
- private _streamProgressCredit;
464
- /** Advance the recovery-progress counter when a chunk represents genuinely
465
- * new produced content. Uses the shared host-agnostic rule
466
- * ({@link shouldCreditStreamProgress}): a milestone (started segment / settled
467
- * tool) always credits, and a long single segment's streaming deltas credit
468
- * through a time throttle so the no-progress window doesn't false-fire while
469
- * content streams across crashes. Bumped at production time, so it reflects
470
- * real forward progress and is immune to client reconnects / recovery
471
- * re-persists (which replay or re-materialize stored chunks rather than flow
472
- * through here). This is what the recovery no-progress window keys off
473
- * (#1637), and stays compaction-proof (#1628). */
474
- private _maybeBumpRecoveryProgress;
475
508
  /** @internal Delegate to _resumableStream */
476
509
  protected _flushChunkBuffer(): void;
477
510
  /** @internal Delegate to _resumableStream */
@@ -490,9 +523,8 @@ declare class AIChatAgent<
490
523
  * `Think` and the client reducer use), replacing a hand-rolled chunk
491
524
  * switch; it owns the `start` / `finish` / `message-metadata` handling;
492
525
  * - (b) {@link _resolveOrphanTargetId} — the id to persist under (#1691);
493
- * - (c)+(d) upsert-by-id over the flat array, the `SessionProvider`-subset
494
- * store-write shape (`getMessage` → `updateMessage` / `appendMessage`)
495
- * that `Think._upsertMessageInHistory` implements over a Session tree.
526
+ * - (c)+(d) upsert-by-id through the shared `OrphanPersistStore` shape
527
+ * (`getMessage` → `updateMessage` / `appendMessage`).
496
528
  * When a row already owns the id, the shared `reconcileOrphanPartial`
497
529
  * merge preserves an in-place tool result rather than letting a replayed
498
530
  * chunk re-advance it (ai-chat has an early tool-approval persist; hosts
@@ -526,9 +558,9 @@ declare class AIChatAgent<
526
558
  fallbackId: string
527
559
  ): string;
528
560
  /**
529
- * The orphan-persist store adapter — orphan-persist steps **(c)/(d)** route
530
- * their write through this shared `OrphanPersistStore` seam (the
531
- * `SessionProvider` write-subset). Backed by ai-chat's flat `this.messages`
561
+ * The orphan-persist store adapter. Orphan-persist steps **(c)/(d)** route
562
+ * through the shared `OrphanPersistStore` seam, backed by ai-chat's
563
+ * `this.messages`
532
564
  * array + the existing `persistMessages` whole-array write path, so
533
565
  * reconcile/sanitize/row-size/broadcast all stay intact. Each mutating call
534
566
  * is exactly one `persistMessages` invocation; `parentId` is unused (a flat
@@ -618,7 +650,27 @@ declare class AIChatAgent<
618
650
  * @param continuation - Whether this is a continuation of a previous stream
619
651
  */
620
652
  private _broadcastTextEvent;
621
- private _loadMessagesFromDb;
653
+ /**
654
+ * Lift ai-chat's legacy flat table into the default Sessions chain.
655
+ *
656
+ * Runs in `onStart` (before hydration), not in the constructor: the lift is
657
+ * an async import through Sessions, and the constructor does no session
658
+ * storage work at all.
659
+ *
660
+ * Order is read first as ids alone, then message bodies are fetched in
661
+ * windows bounded by row count and bytes, so a large transcript never sits
662
+ * in the isolate at once. Once every readable row has a copy the legacy
663
+ * table is DROPPED rather than renamed: keeping it would leave the object
664
+ * holding its history twice.
665
+ */
666
+ private _migrateLegacyMessages;
667
+ /**
668
+ * Hydrate `this.messages` once per wake, bounded by
669
+ * {@link hydrationByteBudget}. This is the only transcript read on the
670
+ * startup path; every later change arrives through the Sessions change
671
+ * feed.
672
+ */
673
+ private _hydrateMessages;
622
674
  private _tryCatchChat;
623
675
  private isChatTurnActive;
624
676
  /**
@@ -1168,19 +1220,19 @@ declare class AIChatAgent<
1168
1220
  * recomputed from the live, mutable transcript. Compaction collapses older
1169
1221
  * assistant messages into a summary, lowering the count — so a turn that had
1170
1222
  * genuinely advanced could read as "no progress" between attempts and exhaust
1171
- * its budget prematurely (#1628). Instead we read a durably-persisted counter
1172
- * that only ever increments — bumped at production time when new content is
1173
- * streamed (see `_storeStreamChunk` / `_maybeBumpRecoveryProgress`), which is
1174
- * genuine forward progress and is immune to client reconnects / recovery
1175
- * re-persists — so compaction can never lower it and a reconnect can't fake
1176
- * it (#1637).
1223
+ * its budget prematurely (#1628). It then became a KV counter bumped per
1224
+ * credited chunk. It is now derived from the stream log the chunks were
1225
+ * already flushed to (`ResumableStream.progressMarker`): the log only grows
1226
+ * when new content lands durably, a reconnect replay or a recovery
1227
+ * re-persist reads it without appending (#1637), and compaction rewrites
1228
+ * the transcript, not the log. Nothing is written per chunk.
1229
+ *
1230
+ * The pre-derivation KV counter is folded in once per isolate, so a marker
1231
+ * an in-flight incident already recorded is never read lower after the
1232
+ * upgrade.
1177
1233
  */
1178
1234
  private _chatRecoveryProgressMarker;
1179
- /** Advance the durable recovery-progress counter. Called from
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;
1235
+ private _progressSeed;
1184
1236
  /** Per-isolate N9 throttle gate (shared `agents/chat` helper); reset per
1185
1237
  * isolate so the first forwarded chunk after a restart always credits. */
1186
1238
  private _agentToolStreamProgress;
@@ -1188,7 +1240,9 @@ declare class AIChatAgent<
1188
1240
  * N9: forwarding a sub-agent's chunks IS forward progress for this parent
1189
1241
  * turn, so credit the parent's recovery progress marker — otherwise a parent
1190
1242
  * 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. Only
1243
+ * no-progress window exhausts while the child is healthily streaming. The
1244
+ * child's output goes to clients, not to this object's stream log, so the
1245
+ * derived marker cannot see it; this is the one explicit credit left. Only
1192
1246
  * invoked after a child actually produced output (see
1193
1247
  * `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.
1194
1248
  * Throttled (and reset per isolate) so we never write storage per token.
@@ -1283,6 +1337,10 @@ declare class AIChatAgent<
1283
1337
  _ctx: ChatRecoveryContext$1
1284
1338
  ): Promise<ChatRecoveryOptions$1 | void>;
1285
1339
  _chatRecoveryContinue(data?: ChatRecoveryContinueData): Promise<void>;
1340
+ protected _chatRecoveryContinueDetached(
1341
+ data?: ChatRecoveryContinueData,
1342
+ onTurnStarted?: () => void
1343
+ ): Promise<void>;
1286
1344
  private _applyRecoveredRequestContext;
1287
1345
  /**
1288
1346
  * Route a live stream stall (the {@link chatStreamStallTimeoutMs} watchdog
@@ -1355,25 +1413,33 @@ declare class AIChatAgent<
1355
1413
  * Two residual at-least-once edges, both deliberately accepted as "deliver a
1356
1414
  * second banner" ≫ "silently drop the turn":
1357
1415
  * • No `incidentId` at all in the payload (only reachable via a direct/test
1358
- * invocation — every production scheduler carries one): the synthesized
1359
- * incident can't be persisted (no key), so the guard can't arm.
1416
+ * invocation — every production recovery enqueue carries one): the
1417
+ * synthesized incident can't be persisted (no key), so the guard can't
1418
+ * arm.
1360
1419
  * • The record is swept AGAIN between two alarms (the guard re-persists on
1361
1420
  * the first, so this needs a second independent sweep) — vanishingly
1362
1421
  * unlikely.
1363
1422
  */
1364
1423
  /**
1365
- * Recovery continuation callbacks the alarm-boundary OOM circuit breaker may
1366
- * back off / purge (#1825). See `Agent._cf_handleAlarmMemoryLimitReset`.
1424
+ * Host memory-limit policy hook (#1825), dispatched structurally by
1425
+ * Lifecycle's circuit breaker — protected because it is framework
1426
+ * machinery, not part of the public chat API. Tasks applies the breaker to
1427
+ * root recovery runs; the routed dynamic-agent fallback applies it to
1428
+ * `recoveryLoop` schedule rows (see `RecoveryLoopScheduleOptions`). At the
1429
+ * strike budget this hook seals active incidents via
1430
+ * {@link _cf_sealMemoryLimitedRecovery}.
1367
1431
  */
1368
- protected _cf_recoveryAlarmCallbacks(): string[];
1432
+ protected onAlarmMemoryLimit(context: {
1433
+ readonly sealed: boolean;
1434
+ }): Promise<void>;
1369
1435
  /**
1370
- * Seal any still-live recovery incident as an out-of-memory exhaustion when
1371
- * the alarm circuit breaker trips at its strike budget (#1825). Runs at the
1372
- * outermost alarm frame (post-unwind), so the terminal banner / `onExhausted`
1373
- * and the sealed-incident write can land where mid-turn writes OOMed. Reuses
1374
- * the shared give-up spine via the recovery engine.
1436
+ * Seal any still-live recovery incident as an out-of-memory exhaustion
1437
+ * when the alarm circuit breaker trips at its strike budget (#1825). Runs
1438
+ * at the outermost alarm frame (post-unwind), so the terminal banner /
1439
+ * `onExhausted` and the sealed-incident write can land where mid-turn
1440
+ * writes OOMed. Reuses the shared give-up spine via the recovery engine.
1375
1441
  */
1376
- protected _cf_sealMemoryLimitedRecovery(): Promise<void>;
1442
+ private _cf_sealMemoryLimitedRecovery;
1377
1443
  private _exhaustRecoveryAfterStableTimeout;
1378
1444
  /**
1379
1445
  * Apply the tight OOM-retry budget to a recovery error (#1825). Symmetric with
@@ -1399,6 +1465,10 @@ declare class AIChatAgent<
1399
1465
  private _handleRecoveryOom;
1400
1466
  private _shouldRetryRecoveredPreStreamTurn;
1401
1467
  _chatRecoveryRetry(data?: ChatRecoveryRetryData): Promise<void>;
1468
+ protected _chatRecoveryRetryDetached(
1469
+ data?: ChatRecoveryRetryData,
1470
+ onTurnStarted?: () => void
1471
+ ): Promise<void>;
1402
1472
  /**
1403
1473
  * Extract partial text and parts from stored stream chunks.
1404
1474
  */
@@ -1422,32 +1492,24 @@ declare class AIChatAgent<
1422
1492
  private _findLastAssistantMessage;
1423
1493
  private _createStreamingAssistantMessage;
1424
1494
  /**
1425
- * Sanitizes a message for persistence by removing ephemeral provider-specific
1426
- * data that should not be stored or sent back in subsequent requests.
1495
+ * Applies the ai-chat-specific normalization Sessions does not do.
1427
1496
  *
1428
- * Pipeline:
1497
+ * Sessions already strips OpenAI ephemeral fields (itemId,
1498
+ * reasoningEncryptedContent) and drops truly empty reasoning parts on every
1499
+ * write, so those steps are not repeated here.
1429
1500
  *
1430
- * 1. **Strip OpenAI ephemeral fields**: The AI SDK's @ai-sdk/openai provider
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.
1501
+ * Pipeline:
1434
1502
  *
1435
- * 2. **Truncate provider-executed tool payloads**: Server-side tool
1503
+ * 1. **Truncate provider-executed tool payloads**: Server-side tool
1436
1504
  * executions (e.g. Anthropic code_execution, text_editor) can produce
1437
1505
  * 200KB+ payloads in `input` and `output`. These are truncated since the
1438
1506
  * model has already consumed the results.
1439
1507
  *
1440
- * 3. **Filter truly empty reasoning parts**: After stripping, reasoning parts
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()`
1508
+ * 2. **User hook**: Calls the overridable `sanitizeMessageForPersistence()`
1447
1509
  * method, allowing subclasses to apply custom transformations.
1448
1510
  *
1449
1511
  * @param message - The message to sanitize
1450
- * @returns A new message with ephemeral provider data removed
1512
+ * @returns A new message with ai-chat's normalization applied
1451
1513
  */
1452
1514
  private _sanitizeMessageForPersistence;
1453
1515
  /**
@@ -1474,33 +1536,10 @@ declare class AIChatAgent<
1474
1536
  private static _getToolNameFromPart;
1475
1537
  private static _isOpaqueReplayFieldKey;
1476
1538
  /**
1477
- * Delete the given message rows from SQLite in batched `IN (...)` queries
1478
- * and evict them from the persistence cache. Batches stay within the SQLite
1479
- * 100 bound-parameter limit. No-op for an empty list.
1480
- * @internal
1539
+ * Delete message rows through Sessions. The change feed removes them from
1540
+ * `this.messages`.
1481
1541
  */
1482
1542
  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
1543
  /**
1505
1544
  * Shared helper for finding a tool part by toolCallId and applying an update.
1506
1545
  * Handles both streaming (in-memory) and persisted (SQLite) messages.