@cloudflare/ai-chat 0.12.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 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,
@@ -41,6 +43,7 @@ import { Streams } from "agents/streams";
41
43
  type ChatRecoveryRetryData = {
42
44
  targetUserId?: string;
43
45
  originalRequestId?: string;
46
+ originMessageIds?: string[];
44
47
  incidentId?: string;
45
48
  lastBody?: Record<string, unknown> | null;
46
49
  lastClientTools?: ClientToolSchema$1[] | null;
@@ -48,6 +51,7 @@ type ChatRecoveryRetryData = {
48
51
  type ChatRecoveryContinueData = {
49
52
  targetAssistantId?: string;
50
53
  originalRequestId?: string;
54
+ originMessageIds?: string[];
51
55
  incidentId?: string;
52
56
  lastBody?: Record<string, unknown> | null;
53
57
  lastClientTools?: ClientToolSchema$1[] | null;
@@ -105,10 +109,18 @@ type OnChatMessageOptions = {
105
109
  declare class AIChatAgent<
106
110
  Env extends Cloudflare.Env = Cloudflare.Env,
107
111
  State = unknown,
108
- Props extends Record<string, unknown> = Record<string, unknown>
112
+ Props extends object = object
109
113
  > extends Agent<Env, State, Props> {
110
114
  #private;
111
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();
112
124
  /**
113
125
  * Registry of per-request AbortControllers.
114
126
  * Used to propagate cancellation signals for any external calls made by the agent.
@@ -258,6 +270,8 @@ declare class AIChatAgent<
258
270
  private _agentToolLastErrors;
259
271
  private _agentToolPreTurnAssistantIds;
260
272
  private _agentToolLiveSequences;
273
+ /** Runs started with `eventDelivery: "terminal"`: their chunks are not broadcast. */
274
+ private _agentToolTerminalOnlyRuns;
261
275
  /**
262
276
  * Request id → run id for in-flight agent-tool turns (null = resolved as
263
277
  * not an agent-tool turn, cached so unrelated turns don't re-query SQLite
@@ -391,7 +405,15 @@ declare class AIChatAgent<
391
405
  * duplicating it — see {@link chatRecoveryTaskRunOptions}.
392
406
  */
393
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;
394
415
  private _runChatRecoveryFiber;
416
+ private _runWrappedChatRecoveryFiber;
395
417
  /**
396
418
  * Array of chat messages for the current conversation.
397
419
  *
@@ -405,6 +427,12 @@ declare class AIChatAgent<
405
427
  msg: string | ArrayBuffer | ArrayBufferView,
406
428
  without?: string[]
407
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;
408
436
  /**
409
437
  * Resolve the agent-tool run whose turn owns a request id, or null when the
410
438
  * request is not an agent-tool turn. Falls back to the persisted run row
@@ -476,13 +504,13 @@ declare class AIChatAgent<
476
504
  }
477
505
  ): string;
478
506
  /** @internal Delegate to _resumableStream */
479
- protected _completeStream(streamId: string): void;
507
+ protected _completeStream(streamId: string, outcome?: ChatTurnOutcome): void;
480
508
  /**
481
509
  * @internal The producer finished; leave the row for the cutover that
482
510
  * persists the message (`persistMessages` via `#pendingCutover`). `_reply`'s
483
511
  * finally settles it if no persist follows.
484
512
  */
485
- protected _finishStream(streamId: string): void;
513
+ protected _finishStream(streamId: string, outcome?: ChatTurnOutcome): void;
486
514
  private _afterStreamFinished;
487
515
  /**
488
516
  * @deprecated Streams are reclaimed at cutover and on the next stream
@@ -504,7 +532,10 @@ declare class AIChatAgent<
504
532
  * as forward progress the moment it lands, as it did under the old
505
533
  * per-chunk counter. Streaming deltas keep the buffer's own packing.
506
534
  */
507
- protected _storeStreamChunk(streamId: string, body: string): Promise<void>;
535
+ protected _storeStreamChunk(
536
+ streamId: string,
537
+ body: string
538
+ ): Promise<number | undefined>;
508
539
  /** @internal Delegate to _resumableStream */
509
540
  protected _flushChunkBuffer(): void;
510
541
  /** @internal Delegate to _resumableStream */
@@ -640,7 +671,25 @@ declare class AIChatAgent<
640
671
  * @internal
641
672
  */
642
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;
643
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;
644
693
  /**
645
694
  * Broadcasts a text event for non-SSE responses.
646
695
  * This ensures plain text responses follow the AI SDK v5 stream protocol.
@@ -767,6 +816,12 @@ declare class AIChatAgent<
767
816
  * without requiring the caller to know the id.
768
817
  */
769
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;
770
825
  /**
771
826
  * Abort every in-flight chat turn on this agent.
772
827
  *
@@ -866,6 +921,14 @@ declare class AIChatAgent<
866
921
  */
867
922
  private _hasIncompleteToolBatch;
868
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;
869
932
  /**
870
933
  * @returns Terminal status for the turn.
871
934
  */
@@ -1084,6 +1147,7 @@ declare class AIChatAgent<
1084
1147
  options: {
1085
1148
  runId: string;
1086
1149
  signal?: AbortSignal;
1150
+ eventDelivery?: AgentToolEventDelivery;
1087
1151
  }
1088
1152
  ): Promise<AgentToolRunInspection>;
1089
1153
  cancelAgentToolRun(runId: string, reason?: unknown): Promise<void>;
@@ -1125,7 +1189,12 @@ declare class AIChatAgent<
1125
1189
  * Mirrors `@cloudflare/think`.
1126
1190
  */
1127
1191
  private _reconcileOwnStaleAgentToolChildRuns;
1128
- inspectAgentToolRun(runId: string): Promise<AgentToolRunInspection | null>;
1192
+ inspectAgentToolRun(
1193
+ runId: string,
1194
+ options?: {
1195
+ reconcile?: boolean;
1196
+ }
1197
+ ): Promise<AgentToolRunInspection | null>;
1129
1198
  private static _progressSnapshotFromRow;
1130
1199
  getAgentToolChunks(
1131
1200
  runId: string,
@@ -1142,6 +1211,16 @@ declare class AIChatAgent<
1142
1211
  ): Promise<ReadableStream<AgentToolStoredChunk>>;
1143
1212
  private _getAgentToolRunRow;
1144
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;
1145
1224
  private _getAgentToolStoredChunks;
1146
1225
  private _getAgentToolMessagesAfterStart;
1147
1226
  private _closeAgentToolTailers;
@@ -1353,9 +1432,20 @@ declare class AIChatAgent<
1353
1432
  * schedule payload carries no `recoveredRequestId`.
1354
1433
  *
1355
1434
  * Returns `"exhausted"` when the budget was spent (terminal UX already
1356
- * delivered), or `"scheduled"` when a continuation was queued.
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.
1357
1438
  */
1358
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;
1359
1449
  /**
1360
1450
  * Reschedule a recovery callback that timed out waiting for stable state,
1361
1451
  * consuming one attempt. Returns `true` if rescheduled, `false` if the