@cloudflare/think 0.19.0 → 0.20.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.
@@ -23,6 +23,7 @@ import {
23
23
  StopCondition as StopCondition$1,
24
24
  StreamTextOnChunkCallback,
25
25
  TextStreamPart,
26
+ TextStreamPart as TextStreamPart$1,
26
27
  ToolSet,
27
28
  TypedToolCall,
28
29
  TypedToolCall as TypedToolCall$1,
@@ -67,6 +68,7 @@ import {
67
68
  ChatRecoveryProgressContext,
68
69
  ChatResponseResult,
69
70
  ChatResponseResult as ChatResponseResult$1,
71
+ ChatTurnOutcome,
70
72
  ClientToolExecutor,
71
73
  ClientToolSchema,
72
74
  MessageConcurrency,
@@ -108,6 +110,8 @@ import {
108
110
  Adapter,
109
111
  Attachment,
110
112
  Author,
113
+ ConcurrencyConfig,
114
+ ConcurrencyStrategy,
111
115
  Message,
112
116
  Thread
113
117
  } from "chat";
@@ -348,8 +352,15 @@ declare function messengerChannel(
348
352
  //#region src/think.d.ts
349
353
  type ChatRecoveryRetryData = {
350
354
  targetUserId?: string;
355
+ /**
356
+ * Set when the interrupted turn regenerated `targetUserId`: the leaf the new
357
+ * response branches beside. The retry answers `targetUserId` as a sibling
358
+ * branch, and only while this is still the leaf.
359
+ */
360
+ regeneratedLeafId?: string;
351
361
  originalRequestId?: string;
352
362
  incidentId?: string;
363
+ originMessageIds?: string[];
353
364
  lastBody?: Record<string, unknown> | null;
354
365
  lastClientTools?: ClientToolSchema[] | null;
355
366
  recoveredRequestId?: string;
@@ -358,6 +369,7 @@ type ChatRecoveryContinueData = {
358
369
  targetAssistantId?: string;
359
370
  originalRequestId?: string;
360
371
  incidentId?: string;
372
+ originMessageIds?: string[];
361
373
  lastBody?: Record<string, unknown> | null;
362
374
  lastClientTools?: ClientToolSchema[] | null;
363
375
  recoveredRequestId?: string;
@@ -422,9 +434,43 @@ interface StreamCallback {
422
434
  * Note: a deploy/eviction interruption kills the isolate (and this callback)
423
435
  * before this can fire — the caller observes a transport break instead. This
424
436
  * fires only for an in-isolate interruption (the stall→recovery path).
437
+ *
438
+ * `info.deliversRecoveredReply` is true when the interrupted turn was a
439
+ * messenger turn and this agent will post the recovered answer (or the
440
+ * interrupted apology, if recovery gives up) to the messenger thread itself.
425
441
  */
426
- onInterrupted?(): void | Promise<void>;
442
+ onInterrupted?(info?: ChatInterruptedInfo): void | Promise<void>;
427
443
  }
444
+ interface ChatInterruptedInfo {
445
+ deliversRecoveredReply?: boolean;
446
+ }
447
+ /**
448
+ * Produces server-authored assistant-message metadata from AI SDK stream parts.
449
+ * Forwarded to the AI SDK `toUIMessageStream` so a Think turn can stamp
450
+ * structured metadata onto the assistant message it persists. Called for every
451
+ * stream part; use `part.type` to choose when to return metadata (`start` and
452
+ * `finish` are the conventional points). Each non-`undefined` return is
453
+ * shallow-merged into the message's metadata. The return value is broadcast to
454
+ * clients and persisted, so it must be
455
+ * JSON-serializable and must not carry server-only secrets.
456
+ *
457
+ * `continuation` is true when the turn continues an earlier one (a recovery
458
+ * continuation or an auto-continue after a tool result). A recovery
459
+ * continuation streams into the interrupted assistant message, so its `start`
460
+ * part cannot overwrite keys that message already has: a `createdAt` stamped
461
+ * on the original `start` survives. Keys the continuation's `start` adds, and
462
+ * everything from later parts, merge as usual.
463
+ *
464
+ * The `Metadata` parameter defaults to the opaque `Record<string, unknown>` used
465
+ * everywhere metadata rides today; it is the seam a future typed-metadata story
466
+ * (issue #1676) narrows without a breaking change.
467
+ */
468
+ type MessageMetadataCallback<
469
+ Metadata extends Record<string, unknown> = Record<string, unknown>
470
+ > = (options: {
471
+ part: TextStreamPart<ToolSet>;
472
+ continuation: boolean;
473
+ }) => Metadata | undefined;
428
474
  /**
429
475
  * Minimal interface for the result of the inference loop.
430
476
  * The AI SDK's `streamText()` result satisfies this interface.
@@ -492,8 +538,9 @@ interface RunTurnBase {
492
538
  /**
493
539
  * Channel id this turn belongs to (resolved against `configureChannels()` /
494
540
  * `getMessengers()`). Sets the turn-scoped channel context and is persisted on
495
- * the user message so a recovered/continued turn re-resolves it. Defaults to
496
- * the implicit `web` channel.
541
+ * the user message so a recovered/continued turn re-resolves it. Omit it to
542
+ * run without a channel context. (WebSocket chat turns always run on the
543
+ * implicit `web` channel.)
497
544
  */
498
545
  channel?: string;
499
546
  }
@@ -522,7 +569,13 @@ interface RunTurnStream extends RunTurnBase {
522
569
  type RunTurnOptions = RunTurnWait | RunTurnSubmit | RunTurnStream;
523
570
  /** Result of {@link Think.runTurn} in `mode: "wait"`. */
524
571
  type TurnResult = SaveMessagesResult & {
525
- message?: SessionMessage;
572
+ /** Persisted assistant produced by this completed turn; absent otherwise. */ message?: SessionMessage;
573
+ /**
574
+ * Parsed structured output when the turn's `TurnConfig.output` produced
575
+ * one. A structured output that fails to parse ends the turn with
576
+ * `status: "error"`.
577
+ */
578
+ output?: unknown;
526
579
  continuation: boolean;
527
580
  };
528
581
  declare const ACTION_BRAND: unique symbol;
@@ -631,6 +684,14 @@ interface PendingApproval {
631
684
  source: "action" | "codemode";
632
685
  descriptor: ActionApprovalDescriptor;
633
686
  }
687
+ interface RejectExecutionOptions {
688
+ /**
689
+ * Whether Think starts a model continuation after recording the rejection.
690
+ * Defaults to `true`. Set this to `false` when the caller wants the
691
+ * conversation to remain paused until a later user turn.
692
+ */
693
+ autoContinue?: boolean;
694
+ }
634
695
  interface ActionConfig<
635
696
  InputSchema extends FlexibleSchema = FlexibleSchema,
636
697
  Output = unknown
@@ -671,6 +732,7 @@ declare function action<
671
732
  Output = unknown
672
733
  >(config: ActionConfig<InputSchema, Output>): Action<InputSchema, Output>;
673
734
  declare function isAction(value: unknown): value is Action;
735
+ /** What admitted a turn. Exposed on {@link ActiveTurn} and {@link TurnContext}. */
674
736
  type TurnTrigger =
675
737
  | "ws-chat"
676
738
  | "rpc"
@@ -855,11 +917,47 @@ type ThinkSubmissionInspection = {
855
917
  metadata?: Record<string, unknown>;
856
918
  createdAt: number;
857
919
  startedAt?: number;
858
- completedAt?: number;
920
+ completedAt?: number /** Id of the assistant message this submission's turn persisted. */;
921
+ messageId?: string;
859
922
  };
860
923
  type SubmitMessagesResult = ThinkSubmissionInspection & {
861
924
  accepted: boolean;
862
925
  };
926
+ type WaitForSubmissionOptions = {
927
+ /**
928
+ * Stop waiting after this many milliseconds and return the submission as it
929
+ * is then, still `pending` or `running`, or `null` if it was deleted.
930
+ */
931
+ timeoutMs?: number;
932
+ };
933
+ /** What {@link Think.cancelSubmission} did. */
934
+ type CancelSubmissionResult =
935
+ | {
936
+ /** No submission has this id. */ outcome: "not_found";
937
+ submissionId: string;
938
+ }
939
+ | {
940
+ /** The submission had already finished; nothing changed. */ outcome: "already_terminal";
941
+ submissionId: string;
942
+ submission: ThinkSubmissionInspection;
943
+ }
944
+ | {
945
+ /** The submission is now `aborted`. */ outcome: "cancelled";
946
+ submissionId: string;
947
+ /**
948
+ * `"pending"`: removed before its turn started. `"running"`: its turn
949
+ * had been claimed and was signalled to abort; side effects already
950
+ * under way may still finish.
951
+ */
952
+ previousStatus: "pending" | "running";
953
+ /**
954
+ * Whether any of the submission's messages were written to the
955
+ * conversation when it was cancelled. A claimed submission can still be
956
+ * `false` when it is cancelled before its turn applies them.
957
+ */
958
+ messagesApplied: boolean;
959
+ submission: ThinkSubmissionInspection;
960
+ };
863
961
  type ListSubmissionsOptions = {
864
962
  status?: ThinkSubmissionStatus | ThinkSubmissionStatus[];
865
963
  limit?: number;
@@ -910,16 +1008,54 @@ interface TurnInput {
910
1008
  interface TurnContext {
911
1009
  /** Assembled system prompt (from context blocks or getSystemPrompt fallback). */
912
1010
  system: string;
913
- /** Assembled model messages (truncated, pruned). */
1011
+ /**
1012
+ * Assembled model messages (truncated, pruned). When a `whenChanged:
1013
+ * "remind"` context block has changed since the prompt froze, its current
1014
+ * value rides at the end, inside the last user message when there is one.
1015
+ */
914
1016
  messages: ModelMessage[];
915
1017
  /** Merged tool set (workspace + getTools + session + MCP + client + caller). */
916
1018
  tools: ToolSet;
917
- /** The language model from getModel(). */
1019
+ /**
1020
+ * The language model from getModel(), resolved on first read — a
1021
+ * `beforeTurn` that returns its own `model` without reading this never
1022
+ * resolves the default.
1023
+ */
918
1024
  model: LanguageModel;
919
1025
  /** Whether this is a continuation turn. */
920
1026
  continuation: boolean;
921
1027
  /** Custom body fields from the client request. */
922
1028
  body?: Record<string, unknown>;
1029
+ /**
1030
+ * The request this turn runs for: the same id `beforePersist`,
1031
+ * `onChatResponse` and `onChatError` see. Undefined for inference that runs
1032
+ * outside an admitted turn.
1033
+ */
1034
+ requestId?: string;
1035
+ /** What admitted this turn. Undefined outside an admitted turn. */
1036
+ trigger?: TurnTrigger;
1037
+ /**
1038
+ * Aborts when the turn is cancelled. Pass it to any I/O `beforeTurn` awaits
1039
+ * so a stopped turn does not wait for it to finish.
1040
+ */
1041
+ abortSignal?: AbortSignal;
1042
+ /**
1043
+ * The messenger thread this turn answers, fixed when the turn was admitted.
1044
+ * Unlike {@link Think.getMessengerContext}, it never falls back to another
1045
+ * turn's message.
1046
+ */
1047
+ messenger?: MessengerContext;
1048
+ }
1049
+ /**
1050
+ * The turn currently running on this agent. See {@link Think.activeTurn}.
1051
+ */
1052
+ interface ActiveTurn {
1053
+ /** Request id shared by every hook, tool call and event of this turn. */
1054
+ requestId: string;
1055
+ trigger: TurnTrigger;
1056
+ continuation: boolean;
1057
+ /** Channel the turn resolved to, when it has one. */
1058
+ channel?: string;
923
1059
  }
924
1060
  /**
925
1061
  * Configuration returned by the `beforeTurn` hook to override defaults.
@@ -956,6 +1092,17 @@ interface TurnConfig {
956
1092
  * for this turn. Defaults to the instance-level `sendReasoning` setting.
957
1093
  */
958
1094
  sendReasoning?: boolean;
1095
+ /**
1096
+ * Produces server-authored assistant-message metadata for this turn — the
1097
+ * write path that lets a turn attach structured metadata (e.g. a `createdAt`
1098
+ * timestamp) to the assistant message Think persists, matching the AI SDK
1099
+ * `messageMetadata` callback base `AIChatAgent` + `streamText` already accept.
1100
+ * Overrides the instance-level {@link Think.messageMetadata} for this turn.
1101
+ * Configure from a Think subclass; sandboxed extensions cannot send functions
1102
+ * over RPC. See {@link MessageMetadataCallback} for when it is called and the
1103
+ * serialization constraints on its return value.
1104
+ */
1105
+ messageMetadata?: MessageMetadataCallback;
959
1106
  /**
960
1107
  * Override the stream-stall inactivity watchdog timeout for THIS turn only
961
1108
  * (ms; `0` disables it for this turn). Defaults to the instance-level
@@ -1045,8 +1192,10 @@ interface TurnConfig {
1045
1192
  *
1046
1193
  * - `context_overflow` — the prompt exceeded the model's context window
1047
1194
  * (Anthropic `"prompt is too long"`, OpenAI `context_length_exceeded`, …).
1048
- * The only category Think currently acts on (auto-compact + retry).
1049
- * - `rate_limit` / `transient` — reserved for future backoff/retry policies.
1195
+ * Think compacts and retries when `contextOverflow.reactive` is enabled.
1196
+ * - `rate_limit` / `transient` — a stream error worth retrying (a 429, a
1197
+ * dropped connection). Think routes the turn into bounded chat recovery, like
1198
+ * a stream stall, and schedules the continuation with exponential backoff.
1050
1199
  * - `fatal` — unrecoverable; surface terminally.
1051
1200
  * - `unknown` — default; Think applies its existing terminal behavior.
1052
1201
  */
@@ -1147,6 +1296,12 @@ interface ChatErrorContext {
1147
1296
  requestId?: string;
1148
1297
  stage: "parse" | "persist" | "turn" | "stream" | "recovery" | "transcript";
1149
1298
  messagesPersisted?: boolean;
1299
+ /**
1300
+ * `true` when the failed turn was a server-started continuation (for
1301
+ * example after a tool approval or a client tool result) rather than a
1302
+ * turn a client or caller submitted.
1303
+ */
1304
+ continuation?: boolean;
1150
1305
  /**
1151
1306
  * App-provided semantic classification (from `classifyChatError`), when
1152
1307
  * known. Lets `onChatError` overrides and observers distinguish e.g. a
@@ -1230,6 +1385,11 @@ type ToolCallContextExtras = {
1230
1385
  | undefined /** The conversation messages available at tool execution time. */;
1231
1386
  readonly messages: ReadonlyArray<ModelMessage> /** Signal for cancelling the operation. */;
1232
1387
  readonly abortSignal: AbortSignal | undefined;
1388
+ /**
1389
+ * Request id of the turn making this call, matching `TurnContext.requestId`
1390
+ * and `onChatResponse`. Undefined outside an admitted turn.
1391
+ */
1392
+ readonly requestId?: string;
1233
1393
  };
1234
1394
  /**
1235
1395
  * The `TypedToolCall<TOOLS>` union, re-keyed so that discriminating on
@@ -1325,7 +1485,8 @@ type ToolCallResultBase = {
1325
1485
  readonly stepNumber: number | undefined;
1326
1486
  readonly messages: ReadonlyArray<ModelMessage> /** Wall-clock execution time in milliseconds. */;
1327
1487
  readonly toolExecutionMs: number /** @deprecated Prefer `toolExecutionMs`. */;
1328
- readonly durationMs: number;
1488
+ readonly durationMs: number /** Request id of the turn that made this call; see `ToolCallContext`. */;
1489
+ readonly requestId?: string;
1329
1490
  };
1330
1491
  /**
1331
1492
  * The discriminated success/failure outcome of a tool call. On success the
@@ -1428,10 +1589,18 @@ type ThinkModel = LanguageModel | ThinkModelId;
1428
1589
  declare class Think<
1429
1590
  Env extends Cloudflare.Env = Cloudflare.Env,
1430
1591
  State = unknown,
1431
- Props extends Record<string, unknown> = Record<string, unknown>
1592
+ Props extends object = object
1432
1593
  > extends Agent<Env, State, Props> {
1433
1594
  #private;
1434
1595
  private _activeChatRecoveryRootRequestId;
1596
+ /**
1597
+ * The originating user message ids of the active recovery chain (#2280),
1598
+ * carried in the recovery payload because the successor turn runs under a
1599
+ * fresh request id. Scoped to the recovery callback's async context, so a
1600
+ * concurrent client request never inherits them.
1601
+ */
1602
+ private _chatRecoveryOriginIdsScope;
1603
+ private get _activeChatRecoveryOriginIds();
1435
1604
  private static readonly CONFIG_KEYS;
1436
1605
  /**
1437
1606
  * Whether Think automatically converts connected MCP tools to AI SDK tools
@@ -1481,6 +1650,16 @@ declare class Think<
1481
1650
  * @default "queue"
1482
1651
  */
1483
1652
  messageConcurrency: MessageConcurrency;
1653
+ /**
1654
+ * How the Chat SDK handles messages that arrive in a messenger thread while
1655
+ * the agent is still answering, or before it starts. Accepts any Chat SDK
1656
+ * `concurrency` value: `"queue"`, `"debounce"`, `"burst"`, `"concurrent"`,
1657
+ * `"drop"`, or a `ConcurrencyConfig`. One setting covers every messenger on
1658
+ * the agent. Set it as a class field: it is read before `onStart` runs.
1659
+ *
1660
+ * @default { strategy: "burst", debounceMs: 600 }
1661
+ */
1662
+ messengerConcurrency: MessengerConcurrency;
1484
1663
  /**
1485
1664
  * Byte budget for hydrating the persisted transcript into the in-memory
1486
1665
  * message cache (`this.messages`).
@@ -1510,6 +1689,11 @@ declare class Think<
1510
1689
  * non-positive value) to disable windowing and always hydrate the full
1511
1690
  * transcript.
1512
1691
  *
1692
+ * Once the transcript exceeds the budget, the hydrated window's start
1693
+ * slides forward as messages are added, which rewrites the start of the
1694
+ * prompt and defeats provider prompt caching (and the step alignment of
1695
+ * `truncationStep`) until the transcript fits again.
1696
+ *
1513
1697
  * @default 32 * 1024 * 1024
1514
1698
  */
1515
1699
  hydrationByteBudget: number;
@@ -1531,9 +1715,13 @@ declare class Think<
1531
1715
  * `false` keeps aged media in the conversation, so the model keeps seeing
1532
1716
  * it. It does NOT change where Sessions keeps the bytes.
1533
1717
  *
1534
- * `keepRecentMessages` is clamped to at least the recent window the model
1535
- * replays at full fidelity (4 messages), so eviction can never rewrite
1536
- * content the model still sees.
1718
+ * Eviction only rewrites messages below the stepped read-time truncation
1719
+ * cutoff (see `truncationStep`), moved back whole steps until at least
1720
+ * `keepRecentMessages` messages stay above it. It therefore never rewrites
1721
+ * a message the model still replays at full fidelity, and it changes the
1722
+ * cached prompt prefix at most once per truncation step rather than every
1723
+ * turn. The media of up to `keepRecentMessages + truncationStep - 1`
1724
+ * recent messages can stay in context.
1537
1725
  *
1538
1726
  * @default true
1539
1727
  */
@@ -1584,13 +1772,20 @@ declare class Think<
1584
1772
  * e.g. via a health RPC — without subclassing.
1585
1773
  */
1586
1774
  getOnStartDegradations(): ReadonlyArray<OnStartDegradation>;
1587
- private _activeMessengerContext?;
1588
1775
  /**
1589
1776
  * Turn-scoped channel context (superset of `_activeMessengerContext`). Set on
1590
1777
  * both the queue and submit admission paths via `_withChannelContext`, read by
1591
1778
  * `deliverNotice` and per-channel policy. Save/restore keeps nested turns safe.
1592
1779
  */
1593
1780
  private _activeChannelContext?;
1781
+ /**
1782
+ * Channel of the latest queue turn that ran inference, which a continuation
1783
+ * without an explicit channel extends. Cleared by `resetTurnState`. Differs from the latest user message's
1784
+ * channel when a WebSocket regeneration reuses a message another channel
1785
+ * stored, or a continuation ran on an explicit channel. In memory only:
1786
+ * after an eviction, continuations fall back to history.
1787
+ */
1788
+ private _lastTurnChannel?;
1594
1789
  /**
1595
1790
  * Live delivery surface for the active turn, bound by `deliverMessengerReply`
1596
1791
  * so `deliverNotice` can post to the originating channel mid-turn. Save/restore
@@ -1741,10 +1936,21 @@ declare class Think<
1741
1936
  * the next one. A returned tool part MUST carry a settled result
1742
1937
  * (`output-available` / `output-error` / `output-denied` or an
1743
1938
  * `output`/`result` field); returning a non-tool part (e.g. text) is fine.
1939
+ *
1940
+ * It also receives an approved call that never ran (state still
1941
+ * `approval-responded`) once a later turn moves past it without a
1942
+ * continuation executing it.
1744
1943
  */
1745
1944
  protected repairInterruptedToolPart(
1746
1945
  part: UIMessage["parts"][number]
1747
1946
  ): UIMessage["parts"][number];
1947
+ /**
1948
+ * Whether the inference being prepared may repair `approval-responded`
1949
+ * parts: it is not a continuation, and no continuation is waiting to run
1950
+ * them.
1951
+ */
1952
+ private _repairApprovalRespondedThisTurn;
1953
+ private _mayRepairApprovalResponded;
1748
1954
  private _repairToolTranscriptParts;
1749
1955
  private _repairTranscriptForProvider;
1750
1956
  /**
@@ -1821,9 +2027,10 @@ declare class Think<
1821
2027
  * once the rewritten row is stored, its Sessions attachment reference is
1822
2028
  * gone and the blob is reaped, so the bytes live in exactly one place.
1823
2029
  *
1824
- * The aged cutoff is `keepRecentMessages` clamped to at least
1825
- * `MODEL_RECENT_WINDOW`: messages the model still replays at full fidelity
1826
- * are never rewritten, whatever the configuration says.
2030
+ * The aged cutoff is {@link mediaEvictionCutoff}: the stepped truncation
2031
+ * cutoff, kept at least `keepRecentMessages` back. Messages the model still
2032
+ * replays at full fidelity are never rewritten, whatever the configuration
2033
+ * says, and the cutoff moves only once per truncation step.
1827
2034
  *
1828
2035
  * Best-effort: failures are logged and the next pass retries. When a pass
1829
2036
  * stops at `maxRowsPerPass` having made progress, the next one is scheduled
@@ -1887,16 +2094,15 @@ declare class Think<
1887
2094
  * `MODEL_RECENT_WINDOW`; `getHistory()` still reads the full path.
1888
2095
  */
1889
2096
  private _syncMessages;
1890
- /** Patch or append one message in the live cache after a durable write. */
1891
- private _upsertCachedMessage;
2097
+ /** Patch a message that is already present in the live cache. */
2098
+ private _patchCachedMessage;
1892
2099
  /**
1893
- * Patch a message that is already present in the live cache. An update
1894
- * that enlarges the message (a tool result landing on it) grows the cache
1895
- * exactly as an append does, so it is charged against the hydration
1896
- * budget the same way; and it may have put an inline payload on an aged
1897
- * row, so a fruitless eviction pass no longer stands.
2100
+ * An update that enlarges a cached message (a tool result landing on it)
2101
+ * grows the cache exactly as an append does, so it is charged against the
2102
+ * hydration budget the same way; and it may have put an inline payload on
2103
+ * an aged row, so a fruitless eviction pass no longer stands.
1898
2104
  */
1899
- private _patchCachedMessage;
2105
+ private _noteCachedReplacement;
1900
2106
  private _appendMessageToHistory;
1901
2107
  private _updateMessageInHistory;
1902
2108
  private _upsertMessageInHistory;
@@ -1945,6 +2151,8 @@ declare class Think<
1945
2151
  private _pendingInteractionPromise;
1946
2152
  private _interactionApplyTail;
1947
2153
  private _streamingAssistant;
2154
+ private _deferredResolvedPauses;
2155
+ private _deferredResolvedPausesLoad;
1948
2156
  private _submitConcurrency;
1949
2157
  private static MESSAGE_DEBOUNCE_MS;
1950
2158
  private _agentToolForwarders;
@@ -1953,6 +2161,8 @@ declare class Think<
1953
2161
  private _agentToolLastErrors;
1954
2162
  private _agentToolPreTurnAssistantIds;
1955
2163
  private _agentToolLiveSequences;
2164
+ /** Runs started with `eventDelivery: "terminal"`: their chunks are not broadcast. */
2165
+ private _agentToolTerminalOnlyRuns;
1956
2166
  /**
1957
2167
  * Request id → run id for in-flight agent-tool turns (null = resolved as
1958
2168
  * not an agent-tool turn, cached so unrelated turns don't re-query SQLite
@@ -1964,15 +2174,23 @@ declare class Think<
1964
2174
  private _agentToolRunsByRequestId;
1965
2175
  private _submissionTableEnsured;
1966
2176
  private _declaredScheduledTasksTableEnsured;
2177
+ private _warnedFacetScheduledTasksDisarmed;
1967
2178
  private _actionLedgerTableEnsured;
1968
2179
  private _actionPendingTableEnsured;
1969
2180
  private _submissionAbortControllers;
2181
+ private _submissionsApplyingMessages;
1970
2182
  private _programmaticStreamErrors;
1971
2183
  protected static submissionRecoveryStaleMs: number;
1972
2184
  broadcast(
1973
2185
  msg: string | ArrayBuffer | ArrayBufferView,
1974
2186
  without?: string[]
1975
2187
  ): void;
2188
+ /**
2189
+ * Durably record a run's stream error on its still-open child-run row, so a
2190
+ * stale-row reconcile after an eviction (before the finalizer seals `error`)
2191
+ * still sees the failure. Leaves `status` to the finalizer / reconcile.
2192
+ */
2193
+ private _recordAgentToolStreamError;
1976
2194
  /**
1977
2195
  * Resolve the agent-tool run whose turn owns a request id, or null when the
1978
2196
  * request is not an agent-tool turn. Falls back to the persisted child-run
@@ -1999,7 +2217,7 @@ declare class Think<
1999
2217
  *
2000
2218
  * Safe to call on EVERY recovery continuation:
2001
2219
  * - Facets that never ran as an agent-tool child have no
2002
- * `cf_agent_tool_child_runs` table → the guarded SELECT throws → no-op.
2220
+ * `cf_agent_tool_child_runs` table → no-op (the table is not created).
2003
2221
  * - A facet whose run already settled has no `starting`/`running` row → no-op.
2004
2222
  * - A child DO is addressed by its `runId` (`subAgent(cls, runId)`), so it
2005
2223
  * owns AT MOST ONE child-run row for its whole lifetime and is never reused
@@ -2096,6 +2314,22 @@ declare class Think<
2096
2314
  * lifetime of the agent (the default `this.env.AI` always is).
2097
2315
  */
2098
2316
  private _defaultProvider?;
2317
+ /**
2318
+ * Return AI Gateway options for a string model resolved by the default
2319
+ * provider. Called on every {@link resolveModel} call: once per turn for the
2320
+ * default model (skipped when `beforeTurn` returns its own `model` without
2321
+ * reading `ctx.model`), plus once for each string `model` override returned
2322
+ * from `beforeTurn` or `beforeStep`. It can read {@link activeTurn}, the
2323
+ * messenger context, or agent state. Use it to pick a gateway `id` and to
2324
+ * attach `metadata`, which AI Gateway records on the request log as
2325
+ * `cf-aig-metadata`. It must return synchronously; a returned Promise is
2326
+ * rejected with an error.
2327
+ *
2328
+ * Defaults to `undefined`: catalog slugs use the account's `default`
2329
+ * gateway, and `@cf/...` ids call Workers AI without a gateway. Not called
2330
+ * for a model that is already a `LanguageModel`.
2331
+ */
2332
+ getGateway(_model: string): GatewayOptions | undefined;
2099
2333
  /**
2100
2334
  * Resolve a model value into a concrete AI SDK `LanguageModel`.
2101
2335
  *
@@ -2128,12 +2362,22 @@ declare class Think<
2128
2362
  */
2129
2363
  configureChannels(): ThinkChannels | Promise<ThinkChannels>;
2130
2364
  getMessengerContext(): MessengerContext | undefined;
2365
+ private _activeMessengerContext;
2131
2366
  chatWithMessengerContext(
2132
2367
  userMessage: string | UIMessage,
2133
2368
  callback: StreamCallback,
2134
2369
  context: MessengerContext,
2135
2370
  options?: ChatOptions
2136
2371
  ): Promise<void>;
2372
+ /**
2373
+ * The turn currently running on this agent, readable from `beforeTurn`,
2374
+ * `beforeToolCall`, tool `execute`, `onChatResponse` and anything they call.
2375
+ * Undefined outside a turn, including from code a turn scheduled to run
2376
+ * later.
2377
+ */
2378
+ get activeTurn(): ActiveTurn | undefined;
2379
+ /** The admitted-turn store of the turn running now, if the caller is in it. */
2380
+ private _activeAdmittedTurn;
2137
2381
  /**
2138
2382
  * Bind the live messenger delivery surface for the active turn so
2139
2383
  * `deliverNotice` can post to the originating channel while a messenger turn
@@ -2144,6 +2388,8 @@ declare class Think<
2144
2388
  /**
2145
2389
  * The channel context for the active turn, if the turn resolved to a channel.
2146
2390
  * Readable from tools/hooks during a turn (e.g. to branch on `kind`).
2391
+ * Undefined outside a turn, like {@link activeTurn} — including from work a
2392
+ * turn left behind that runs while a later turn holds another channel.
2147
2393
  */
2148
2394
  get activeChannel(): ChannelContext | undefined;
2149
2395
  /**
@@ -2176,6 +2422,7 @@ declare class Think<
2176
2422
  private _turnMetadataFromMessages;
2177
2423
  /** Re-resolve the channel for a continuation from the latest user message. */
2178
2424
  private _channelFromLatestUserMessage;
2425
+ private _channelForAutoContinuation;
2179
2426
  /**
2180
2427
  * Deliver a no-turn, channel-routed message — a deterministic status, fallback,
2181
2428
  * or notice — straight to the channel's delivery surface WITHOUT invoking the
@@ -2198,6 +2445,24 @@ declare class Think<
2198
2445
  },
2199
2446
  options?: DeliverNoticeOptions
2200
2447
  ): Promise<void>;
2448
+ /**
2449
+ * Post a recovered messenger reply, or the interrupted apology, to a thread.
2450
+ * Called by a conversation sub-agent (or this agent) once chat recovery of
2451
+ * an interrupted messenger turn settles; only the host holds the messenger
2452
+ * runtime (#2106).
2453
+ *
2454
+ * @internal
2455
+ */
2456
+ _cf_deliverRecoveredMessengerReply(input: {
2457
+ messengerId: string;
2458
+ threadId: string;
2459
+ outcome: "completed" | "interrupted";
2460
+ text?: string;
2461
+ partialPosted?: boolean;
2462
+ chunk: number;
2463
+ }): Promise<{
2464
+ chunks: number;
2465
+ }>;
2201
2466
  /**
2202
2467
  * The active turn's channel id, if any. Prefers the turn-scoped channel
2203
2468
  * context, then the active messenger turn's id; web turns have none, so
@@ -2208,6 +2473,26 @@ declare class Think<
2208
2473
  private _initializeChannels;
2209
2474
  /** Return code-declared scheduled tasks for this agent. */
2210
2475
  getScheduledTasks(): ThinkScheduledTasks | Promise<ThinkScheduledTasks>;
2476
+ /**
2477
+ * Return which instances of this class arm the declared scheduled tasks.
2478
+ *
2479
+ * `"root"` (the default) arms them only on the top-level agent. Because
2480
+ * `getScheduledTasks()` is usually a static code declaration, it returns the
2481
+ * same tasks on every instance — so without this scope an agent that also
2482
+ * has sub-agents would arm one private copy per live facet and dispatch each
2483
+ * occurrence once per facet on top of the root (#1877).
2484
+ *
2485
+ * Return `"all"` to arm on facets as well. That is only correct when
2486
+ * `getScheduledTasks()` genuinely varies per facet (for example when it
2487
+ * reads per-facet state), since each facet then owns an independent
2488
+ * schedule.
2489
+ *
2490
+ * The value must be stable across wakes. Reporting `"root"` on a facet that
2491
+ * previously armed cancels its occurrences, so a scope that flickers with
2492
+ * request-scoped or not-yet-loaded state will repeatedly tear down and
2493
+ * re-create that facet's schedule.
2494
+ */
2495
+ getScheduledTasksScope(): "root" | "all" | Promise<"root" | "all">;
2211
2496
  /**
2212
2497
  * Reconcile code-declared scheduled tasks immediately.
2213
2498
  * Static declarations are reconciled on startup automatically; call this
@@ -2225,6 +2510,12 @@ declare class Think<
2225
2510
  * it — the definition's `recover` callback hands the interruption to the
2226
2511
  * shared ChatRecoveryEngine instead.
2227
2512
  */
2513
+ /**
2514
+ * Start time and latest `stash()` data of each chat turn running in this
2515
+ * isolate, keyed by request id. A stream stall is recovered while the turn is
2516
+ * still live, so `onChatRecovery` reads these instead of a fiber snapshot.
2517
+ */
2518
+ private readonly _liveChatRecoveryTurns;
2228
2519
  private readonly _liveChatTurnClosures;
2229
2520
  /**
2230
2521
  * Register the shared chat-turn Task definition (see
@@ -2270,10 +2561,25 @@ declare class Think<
2270
2561
  accepted: boolean;
2271
2562
  }>;
2272
2563
  private _runChatRecoveryFiber;
2564
+ private _runWrappedChatRecoveryFiber;
2273
2565
  private _systemPromptForTurn;
2274
2566
  private _buildThinkCapabilityBlock;
2275
2567
  /** Maximum number of tool-call steps per turn. Override via property or per-turn via TurnConfig. */
2276
2568
  maxSteps: number;
2569
+ /**
2570
+ * Read-time truncation moves its cutoff once every this many messages, so
2571
+ * the provider's cached prompt prefix survives the turns in between. Up to
2572
+ * `truncationStep + 3` recent messages stay at full fidelity. Set it to `1`
2573
+ * to cut every turn, which keeps the fewest full-fidelity messages for
2574
+ * models with a small context window. `Infinity` never moves the cutoff, so
2575
+ * read-time truncation is off and every message stays at full fidelity;
2576
+ * media eviction then keeps exactly `keepRecentMessages` and rewrites the
2577
+ * prefix whenever a message ages out. Other non-finite or non-positive
2578
+ * values behave like `1`.
2579
+ *
2580
+ * @default 8
2581
+ */
2582
+ truncationStep: number;
2277
2583
  /**
2278
2584
  * Retention window for settled action ledger rows. Deleting a row ends the
2279
2585
  * idempotency guarantee for that key, so increase these windows for side
@@ -2309,6 +2615,16 @@ declare class Think<
2309
2615
  * per turn by returning `sendReasoning` from `beforeTurn`.
2310
2616
  */
2311
2617
  sendReasoning: boolean;
2618
+ /**
2619
+ * Default writer for server-authored assistant-message metadata, applied to
2620
+ * every turn. Override (or supply) per turn by returning `messageMetadata`
2621
+ * from `beforeTurn` ({@link TurnConfig.messageMetadata}). Set this when the
2622
+ * metadata is turn-independent — e.g. stamping a `createdAt` timestamp on
2623
+ * every assistant message — so callers need not repeat it in `beforeTurn`.
2624
+ * See {@link MessageMetadataCallback} for when it is called and the
2625
+ * serialization constraints on its return value.
2626
+ */
2627
+ messageMetadata?: MessageMetadataCallback;
2312
2628
  /**
2313
2629
  * Inactivity watchdog for the streaming read loop, in milliseconds.
2314
2630
  *
@@ -2366,6 +2682,14 @@ declare class Think<
2366
2682
  * are serialized, so a single value is safe.
2367
2683
  */
2368
2684
  private _turnModelMessageBaseline;
2685
+ /** The context reminder the current turn was assembled with. */
2686
+ private _turnContextReminder;
2687
+ /**
2688
+ * The last message the current turn's model history reaches, when that is
2689
+ * not the leaf: a regeneration answers its parent user message, so the
2690
+ * response it replaces (a stored sibling branch) stays out of the prompt.
2691
+ */
2692
+ private _turnHistoryLeafId;
2369
2693
  /**
2370
2694
  * The assembled tool set for the current turn, captured in
2371
2695
  * `_runInferenceLoop`. The proactive guard reuses it to convert the
@@ -2683,15 +3007,16 @@ declare class Think<
2683
3007
  * knowledge into core. The app does know its provider/model, so it owns the
2684
3008
  * mapping — the same split Think already uses for `tokenCounter`.
2685
3009
  *
2686
- * Currently this hook drives **only** context-overflow recovery: it is
2687
- * consulted when a turn errors **and** `contextOverflow.reactive` is enabled
2688
- * (if reactive is off, it is not called). Return `"context_overflow"` to run
2689
- * the compact-and-retry backstop; if recovery cannot save the turn, that
2690
- * classification is surfaced on the terminal `onChatError` call via
2691
- * {@link ChatErrorContext.classification}. The other categories are reserved
2692
- * for future use — returning one today is a no-op (the turn terminalizes as
2693
- * usual) and it is **not** forwarded to `onChatError`. Returning
2694
- * `void`/`"unknown"` keeps the existing terminal behavior.
3010
+ * Think consults it when a turn's stream errors. Return `"context_overflow"`
3011
+ * to run the compact-and-retry backstop (only when `contextOverflow.reactive`
3012
+ * is enabled); if recovery cannot save the turn, that classification is
3013
+ * surfaced on the terminal `onChatError` call via
3014
+ * {@link ChatErrorContext.classification}. Return `"transient"` or
3015
+ * `"rate_limit"` to route the turn into bounded chat recovery (the same path
3016
+ * as a stream stall: `onChatRecovery`, `chatRecovery.maxAttempts`, then the
3017
+ * exhaustion message), with the continuation delayed by exponential backoff.
3018
+ * Returning `void`, `"fatal"`, or `"unknown"` keeps the existing terminal
3019
+ * behavior.
2695
3020
  *
2696
3021
  * The argument may be an `Error`, an AI SDK `APICallError` (with
2697
3022
  * `statusCode`/`responseBody`), or — for in-stream provider errors that
@@ -2718,12 +3043,28 @@ declare class Think<
2718
3043
  _ctx?: ChatErrorContext
2719
3044
  ): ChatErrorClassification | void;
2720
3045
  /**
2721
- * Whether an error (thrown or surfaced as an in-stream error string) should
2722
- * trigger the opt-in compact-and-retry backstop. Consults the app's
2723
- * `classifyChatError` and the `contextOverflow.reactive` flag. Centralized
2724
- * so both stream consumers (WebSocket + RPC) classify identically.
3046
+ * The app's `classifyChatError` verdict for a stream error (thrown or
3047
+ * surfaced as an in-stream error string). Call once per error: the hook may
3048
+ * be stateful or have side effects.
3049
+ */
3050
+ private _classifyStreamError;
3051
+ /**
3052
+ * Whether a classified stream error should trigger the opt-in
3053
+ * compact-and-retry backstop. Centralized so both stream consumers
3054
+ * (WebSocket + RPC) decide identically.
2725
3055
  */
2726
3056
  private _isRecoverableContextOverflow;
3057
+ /**
3058
+ * The `"transient"` or `"rate_limit"` class the app assigned a stream
3059
+ * error, else `undefined`. Such errors route into bounded chat recovery like
3060
+ * a stream stall instead of terminalizing the turn (#2085). Without a
3061
+ * `classifyChatError` override nothing is transient, so today's terminal
3062
+ * behavior is unchanged. A Durable Object reset is never transient here: the
3063
+ * restart's own recovery owns the turn.
3064
+ */
3065
+ private _transientStreamClassification;
3066
+ /** The provider `Retry-After` to honor for a rate-limited stream error. */
3067
+ private _streamErrorRetryAfter;
2727
3068
  /**
2728
3069
  * Compact the session in response to a context overflow (reactive backstop or
2729
3070
  * proactive guard). Returns whether history was actually shortened — a no-op
@@ -2744,6 +3085,14 @@ declare class Think<
2744
3085
  */
2745
3086
  private _finalizeContextOverflowError;
2746
3087
  private _initializeExtensions;
3088
+ /**
3089
+ * The repaired history the current turn's model request is built from: the
3090
+ * active path, cut at `_turnHistoryLeafId` when one is set. A leaf off the
3091
+ * cached path (another branch, or outside a windowed cache) is read from
3092
+ * storage. The cut comes before repair so messages past the leaf, which the
3093
+ * request never sees, are not rewritten.
3094
+ */
3095
+ private _turnHistory;
2747
3096
  /**
2748
3097
  * Assemble provider-ready model messages from the current session history:
2749
3098
  * repair the transcript, truncate older messages, drop any still-incomplete
@@ -2790,7 +3139,8 @@ declare class Think<
2790
3139
  /**
2791
3140
  * The single convergence point for all chat turn entry paths.
2792
3141
  * Merges tools, assembles context, fires lifecycle hooks, wraps tools
2793
- * for interception, and calls streamText.
3142
+ * for interception, and calls streamText. `historyLeafId` cuts the model
3143
+ * history at that message (see `_turnHistoryLeafId`).
2794
3144
  */
2795
3145
  private _runInferenceLoop;
2796
3146
  private _prepareInferenceInvocation;
@@ -2962,8 +3312,10 @@ declare class Think<
2962
3312
  * an active turn (a tool `execute`, a lifecycle hook) deadlocks on the turn
2963
3313
  * queue — identical to calling {@link Think.saveMessages} or
2964
3314
  * {@link Think.continueLastTurn} from there. Prefer `mode: "submit"` or
2965
- * {@link Think.addMessages} instead. Precise nested-call detection is deferred
2966
- * to `_admitTurn` (step 3).
3315
+ * {@link Think.addMessages} instead. A submitted turn runs only after the
3316
+ * current turn ends, so {@link Think.waitForSubmission} on it from inside
3317
+ * the turn throws rather than deadlocking. Precise nested-call detection is
3318
+ * deferred to `_admitTurn` (step 3).
2967
3319
  *
2968
3320
  * **Empty input (`wait`).** String, single-message, and array inputs that
2969
3321
  * normalize to an empty list short-circuit to `{ status: "skipped" }` without
@@ -3089,6 +3441,7 @@ declare class Think<
3089
3441
  input: unknown,
3090
3442
  options: {
3091
3443
  runId: string;
3444
+ eventDelivery?: "full" | "terminal";
3092
3445
  }
3093
3446
  ): Promise<AgentToolRunInspection>;
3094
3447
  cancelAgentToolRun(runId: string, reason?: unknown): Promise<void>;
@@ -3100,7 +3453,12 @@ declare class Think<
3100
3453
  * completed recovery deletes its incident.
3101
3454
  */
3102
3455
  private _classifyAgentToolChildRecovery;
3103
- inspectAgentToolRun(runId: string): Promise<AgentToolRunInspection | null>;
3456
+ inspectAgentToolRun(
3457
+ runId: string,
3458
+ options?: {
3459
+ reconcile?: boolean;
3460
+ }
3461
+ ): Promise<AgentToolRunInspection | null>;
3104
3462
  private _isStaleAgentToolChildRun;
3105
3463
  /**
3106
3464
  * Reconcile a stale (post-eviction) child run row from the child's own
@@ -3139,6 +3497,16 @@ declare class Think<
3139
3497
  afterSequence?: number;
3140
3498
  }
3141
3499
  ): Promise<AgentToolStoredChunk[]>;
3500
+ /**
3501
+ * After this DO restarts, `_agentToolLiveSequences` is cold while the stored
3502
+ * backlog sits at N, and a chat-recovery resume re-attaches via
3503
+ * `tailAgentToolRun` without re-running `startAgentToolRun` (which seeds the
3504
+ * counter). Unseeded, the broadcast snoop numbers the recovered turn's chunks
3505
+ * from 0 and the tail's high-water dedupe drops them. Seeds only a
3506
+ * non-terminal run, so a terminal one doesn't re-heat the broadcast
3507
+ * idle-guard; a warm counter is authoritative. Returns whether it seeded.
3508
+ */
3509
+ private _seedAgentToolLiveSequence;
3142
3510
  tailAgentToolRun(
3143
3511
  runId: string,
3144
3512
  options?: {
@@ -3215,9 +3583,30 @@ declare class Think<
3215
3583
  private _normalizeDeclaredScheduledTasks;
3216
3584
  private _declaredScheduledTasksForNow;
3217
3585
  private _declaredScheduleOwnerKey;
3586
+ /**
3587
+ * Whether this instance arms the declared scheduled tasks.
3588
+ *
3589
+ * The root always arms. Facets only arm when the class opts in via
3590
+ * `getScheduledTasksScope()`; see that hook for why root-only is the
3591
+ * default (#1877). `parentPath` is hydrated before the reconcile step of
3592
+ * `onStart` — persisted by `_cf_initAsFacet` on a facet's first boot, and
3593
+ * restored from storage by the base agent on every later wake.
3594
+ */
3595
+ private _declaredScheduledTasksArmedHere;
3218
3596
  private _declaredScheduleValidationError;
3219
3597
  private _nextDeclaredScheduleTimeForConfig;
3220
3598
  private _reconcileDeclaredScheduledTasks;
3599
+ /**
3600
+ * Warn once when a sub-agent declares tasks it will not arm.
3601
+ *
3602
+ * Two populations need this, and only one of them leaves a trace. A facet
3603
+ * upgrading from the pre-#1877 default has rows to prune, so `armedCount`
3604
+ * is non-zero. A facet declaring tasks for the first time under the root
3605
+ * default never armed anything, so the only way to tell it apart from a
3606
+ * class that declares nothing is to ask — otherwise its schedule is
3607
+ * silently inert, which is the failure mode #1877 was filed about.
3608
+ */
3609
+ private _warnFacetScheduledTasksDisarmed;
3221
3610
  private _scheduleDeclaredTaskOccurrence;
3222
3611
  private _scheduleDeclaredTaskOccurrenceAt;
3223
3612
  private _advanceDeclaredScheduledTask;
@@ -3238,6 +3627,36 @@ declare class Think<
3238
3627
  private _serializeMetadata;
3239
3628
  private _readWorkflowPromptContext;
3240
3629
  private _emitSubmissionStatus;
3630
+ private _resolveSubmissionWaiters;
3631
+ private _submissionWaiters;
3632
+ /**
3633
+ * Submissions whose row is terminal but whose `onSubmissionStatus` has not
3634
+ * finished. `waitForSubmission` keeps waiting for these.
3635
+ */
3636
+ private _terminalStatusEmits;
3637
+ /** Waiters of a submission deleted while its terminal emit was in flight. */
3638
+ private _waitersHeldForDeletedEmit;
3639
+ /**
3640
+ * Resolve once the submission reaches a terminal status (`completed`,
3641
+ * `aborted`, `skipped` or `error`), after `onSubmissionStatus` has run for
3642
+ * it. Resolves immediately for a submission that already finished, and with
3643
+ * `null` for an unknown id. An `error` status resolves rather than rejects;
3644
+ * read `status` and `error` from the result.
3645
+ *
3646
+ * The wait lives in this object's memory, so it rejects if the object
3647
+ * restarts. The submission itself is durable: call again to keep waiting.
3648
+ *
3649
+ * Throws when called from inside a turn (a tool `execute`, a lifecycle
3650
+ * hook) or from `onSubmissionStatus` for a submission that has not
3651
+ * finished: a submission only runs once the current turn frees the turn
3652
+ * queue, and its status settles only after the hook returns, so the wait
3653
+ * could never resolve. Return the submission id and wait from outside the
3654
+ * turn instead.
3655
+ */
3656
+ waitForSubmission(
3657
+ submissionId: string,
3658
+ options?: WaitForSubmissionOptions
3659
+ ): Promise<ThinkSubmissionInspection | null>;
3241
3660
  protected onSubmissionStatus(
3242
3661
  _submission: ThinkSubmissionInspection
3243
3662
  ): void | Promise<void>;
@@ -3283,10 +3702,14 @@ declare class Think<
3283
3702
  options?: ListSubmissionsOptions
3284
3703
  ): Promise<ThinkSubmissionInspection[]>;
3285
3704
  deleteSubmission(submissionId: string): Promise<boolean>;
3705
+ private _releaseDeletedSubmissionWaiters;
3286
3706
  deleteSubmissions(options?: DeleteSubmissionsOptions): Promise<number>;
3287
3707
  private _listTerminalSubmissionRowsForDelete;
3288
3708
  private _isTerminalSubmissionStatus;
3289
- cancelSubmission(submissionId: string, reason?: unknown): Promise<void>;
3709
+ cancelSubmission(
3710
+ submissionId: string,
3711
+ reason?: unknown
3712
+ ): Promise<CancelSubmissionResult>;
3290
3713
  submitMessages(
3291
3714
  messages: UIMessage[],
3292
3715
  options?: SubmitMessagesOptions
@@ -3417,7 +3840,8 @@ declare class Think<
3417
3840
  * (Phase 4), "generate more" buttons, and self-correction.
3418
3841
  *
3419
3842
  * Note: this creates a new message, not an append to the existing one.
3420
- * True continuation-as-append (chunk rewriting) is planned for Phase 4.
3843
+ * Recovery continuations (`trigger: "recovery-continue"`) are the exception:
3844
+ * they stream into the interrupted assistant message so it stays one message.
3421
3845
  *
3422
3846
  * Returns early with `status: "skipped"` if there is no assistant message
3423
3847
  * to continue from.
@@ -3432,6 +3856,7 @@ declare class Think<
3432
3856
  channel?: string;
3433
3857
  }
3434
3858
  ): Promise<SaveMessagesResult>;
3859
+ private _continueLastTurn;
3435
3860
  private _retryLastUserTurn;
3436
3861
  private _setupProtocolHandlers;
3437
3862
  private _handleProtocolEvent;
@@ -3468,6 +3893,17 @@ declare class Think<
3468
3893
  * without requiring the caller to know the id.
3469
3894
  */
3470
3895
  cancelChat(requestId: string, reason?: string): void;
3896
+ /**
3897
+ * A cancel can land while the turn's recovery is waiting out its backoff,
3898
+ * with nothing in flight to abort: cancel the scheduled recovery instead,
3899
+ * so the queued callback bails when it fires.
3900
+ */
3901
+ private _cancelScheduledRecovery;
3902
+ /**
3903
+ * Whether the user cancelled this recovery while it was scheduled. A
3904
+ * submission the recovery owned settles as `aborted`.
3905
+ */
3906
+ private _recoveryCancelled;
3471
3907
  /** Abort every in-flight chat turn on this agent. */
3472
3908
  cancelAllChats(): void;
3473
3909
  protected abortRequest(requestId: string, reason?: unknown): void;
@@ -3543,6 +3979,7 @@ declare class Think<
3543
3979
  * cannot drift between the live and recovery writes.
3544
3980
  */
3545
3981
  private _strippedForPersist;
3982
+ /** Resolves to `false` when stripping left nothing to persist. */
3546
3983
  private _persistAssistantMessage;
3547
3984
  /**
3548
3985
  * The cutover: persist the finished turn's assistant message, settle its
@@ -3563,6 +4000,14 @@ declare class Think<
3563
4000
  private _streamCutoverOptions;
3564
4001
  /** Write only inside the transaction that settles this exact request's stream. */
3565
4002
  private _recordSubmissionTurnResult;
4003
+ private _recordSubmissionMessage;
4004
+ /**
4005
+ * Cancellation settles a submission as `aborted` before the stream persists
4006
+ * its partial; link that message without touching the terminal status. A
4007
+ * row that never started (a reused submission id cancelled while queued)
4008
+ * cannot own the partial.
4009
+ */
4010
+ private _recordAbortedSubmissionMessage;
3566
4011
  /** Empty/stripped messages have the same atomic outcome cutover as messages. */
3567
4012
  private _finalizeSubmissionStream;
3568
4013
  /** Keep overflow chunks for consumers, but never call that segment an answer. */
@@ -3601,16 +4046,19 @@ declare class Think<
3601
4046
  */
3602
4047
  private _serverTranscriptForReconcile;
3603
4048
  /**
3604
- * Persist an incoming message after reconciliation. For assistant
3605
- * messages, also resolve their ID against any server-side row that
3606
- * already owns the same `toolCallId` so we update the existing row
3607
- * instead of inserting an orphan duplicate.
4049
+ * Persist an incoming message after batch reconciliation has resolved
4050
+ * assistant IDs (one-to-one against server rows) and merged any
4051
+ * server-owned tool outputs.
3608
4052
  *
3609
4053
  * A message whose stored form is what the server already holds is skipped
3610
4054
  * outright. The client posts its whole transcript on every request, so
3611
4055
  * without this every prior message would cost Sessions an existence read
3612
4056
  * plus a full-row compare (and, for media, a decode and hash of every
3613
4057
  * payload) per turn — reads spent discovering nothing changed.
4058
+ *
4059
+ * Reserved metadata (`channel`, `turnMetadata`) is server-owned. The client's
4060
+ * copy is ignored, a stored row keeps its own, and a new user message gets
4061
+ * `channel` when the caller supplies one.
3614
4062
  */
3615
4063
  private _persistIncomingMessage;
3616
4064
  /**
@@ -3717,10 +4165,16 @@ declare class Think<
3717
4165
  * transcript's paused output is replaced with
3718
4166
  * `{ status: "rejected", executionId, reason }` and the chat
3719
4167
  * auto-continues so the model can adapt (or explain) instead of erroring.
4168
+ * Pass `{ autoContinue: false }` to record the rejection without starting a
4169
+ * model continuation.
3720
4170
  *
3721
4171
  * Client-callable.
3722
4172
  */
3723
- rejectExecution(executionId: string, reason?: string): Promise<unknown>;
4173
+ rejectExecution(
4174
+ executionId: string,
4175
+ reason?: string,
4176
+ options?: RejectExecutionOptions
4177
+ ): Promise<unknown>;
3724
4178
  /**
3725
4179
  * Reject a parked `kind: "durable-pause"` action. Claim-by-delete consumes
3726
4180
  * the pending row (idempotent across tabs/recovery), the action's `execute`
@@ -3743,19 +4197,40 @@ declare class Think<
3743
4197
  */
3744
4198
  private _applyExecutionOutcome;
3745
4199
  /**
3746
- * Find the tool part holding the paused output of `executionId` — in the
3747
- * in-flight streaming accumulator first (an approval can land while a new
3748
- * turn streams), then the persisted transcript, newest message first.
3749
- */
3750
- private _findPausedExecutionToolCall;
3751
- /**
3752
- * Find the tool part carrying `executionId` in its output. With
4200
+ * Find the tool part carrying `executionId` in its output — in the in-flight
4201
+ * streaming accumulator first (an approval can land while a new turn
4202
+ * streams), then the in-memory transcript, newest message first. With
3753
4203
  * `pausedOnly`, only a still-paused output matches — used to locate the
3754
4204
  * part an approval outcome should replace. Without it, any settled output
3755
4205
  * matches — used to distinguish "already resolved elsewhere" from "the
3756
4206
  * part is gone from the transcript" (e.g. compacted away).
3757
4207
  */
3758
4208
  private _findExecutionToolCall;
4209
+ /**
4210
+ * {@link _findExecutionToolCall}, falling back to storage when the hydrated
4211
+ * window does not cover the whole transcript, so a long-lived pause is
4212
+ * still resolved in place.
4213
+ */
4214
+ private _findExecutionToolCallDurably;
4215
+ /**
4216
+ * Text and reasoning the model wrote after a paused tool result were written
4217
+ * against the pending state ("once approved, ..."). Once the pause resolves
4218
+ * they contradict the result, so drop them before the continuation reads the
4219
+ * transcript. Tool, file, and other parts after the pause stay.
4220
+ *
4221
+ * While the turn that paused is still streaming, its accumulator owns the
4222
+ * message and appends deltas to the last text part, so parts cannot be
4223
+ * removed underneath it. The drop is deferred to the next inference, which
4224
+ * is queued behind that turn and runs after it persists.
4225
+ *
4226
+ * The resolved pause stays recorded (see `_rememberResolvedPause`) until
4227
+ * the drop has been applied.
4228
+ */
4229
+ private _dropGenerationAfterResolvedPause;
4230
+ private _loadResolvedPauses;
4231
+ private _rememberResolvedPause;
4232
+ private _forgetResolvedPause;
4233
+ private _flushDeferredResolvedPauses;
3759
4234
  private _applyToolUpdateToMessages;
3760
4235
  /**
3761
4236
  * The persisted message that owns `toolCallId`, read as one row — or
@@ -3877,26 +4352,69 @@ declare class Think<
3877
4352
  * Route a stream-stall watchdog abort into bounded recovery instead of a
3878
4353
  * terminal error (#1626). A stall happens inside a LIVE isolate (no DO
3879
4354
  * restart), so the normal restart-detected recovery path never runs — we
3880
- * open/advance a recovery incident here and schedule a continuation, reusing
3881
- * the SAME budget (`maxAttempts` + wall-clock window + progress-aware reset)
3882
- * as deploy/eviction recovery. A transient hang recovers; a persistently
3883
- * hanging provider exhausts the budget. Idempotency matches deploy recovery:
3884
- * settled tool results are durable and won't re-run, but a tool that was
3885
- * mid-execution when the stall fired re-runs on the continuation.
4355
+ * open/advance a recovery incident here and schedule recovery, reusing the
4356
+ * SAME budget (`maxAttempts` + wall-clock window + progress-aware reset) and
4357
+ * the same `onChatRecovery` decision as deploy/eviction recovery (#2042). A
4358
+ * transient hang recovers; a persistently hanging provider exhausts the
4359
+ * budget. Idempotency matches deploy recovery: settled tool results are
4360
+ * durable and won't re-run, but a tool that was mid-execution when the stall
4361
+ * fired re-runs on the continuation.
4362
+ *
4363
+ * A stall before the first assistant chunk leaves the user's message as the
4364
+ * leaf, so there is nothing to continue: it schedules a retry of that user
4365
+ * turn instead (#1941).
4366
+ *
4367
+ * `persistPartial` saves the settled partial and resolves to its message id
4368
+ * (or `undefined` when nothing was saved). It runs unless `onChatRecovery`
4369
+ * returns `persist: false` and the partial holds no settled tool results.
3886
4370
  *
3887
4371
  * Returns:
3888
- * - `"scheduled"` — a continuation was scheduled; the caller suppresses the
4372
+ * - `"scheduled"` — recovery was scheduled; the caller suppresses the
3889
4373
  * terminal error and closes the stream cleanly.
3890
4374
  * - `"exhausted"` — the budget is spent; this routes through the SAME
3891
4375
  * `_exhaustChatRecovery` path as deploy recovery (fires `onExhausted`,
3892
4376
  * emits `chat:recovery:exhausted`, marks the submission interrupted, and
3893
- * delivers the configured `terminalMessage`). The caller must NOT run the
3894
- * generic terminal path — the terminal UX is already delivered.
4377
+ * delivers the configured `terminalMessage`).
4378
+ * - `"declined"` — `onChatRecovery` returned `continue: false`; the turn is
4379
+ * marked interrupted and the declined message is delivered.
4380
+ * - `"failed"` — `onChatRecovery` threw; the incident is marked `failed` and
4381
+ * the caller runs its generic terminal error path.
4382
+ *
4383
+ * For `"exhausted"` and `"declined"` the terminal UX is already delivered, so
4384
+ * the caller must NOT run the generic terminal path.
3895
4385
  */
3896
4386
  private _routeStallToBoundedRecovery;
4387
+ /**
4388
+ * {@link _routeStallToBoundedRecovery} for a stream consumer's `catch`: a
4389
+ * routing failure (e.g. a rejected incident write) degrades to `"failed"`,
4390
+ * so the caller still delivers its terminal error frame.
4391
+ */
4392
+ private _routeStreamInterruption;
4393
+ /**
4394
+ * Submissions whose turn scheduled recovery: the recovery completes them,
4395
+ * so the submission runner must leave them `running`.
4396
+ */
4397
+ private _recoveryOwnedSubmissions;
4398
+ private _claimSubmissionForRecovery;
4399
+ /**
4400
+ * Incidents marked `failed` only for observability while the platform
4401
+ * re-runs the same recovery attempt; their messenger reply stays pending.
4402
+ */
4403
+ private _deferringRecoveryIncidents;
4404
+ /** Incidents whose running recovery attempt scheduled the next attempt. */
4405
+ private _rescheduledRecoveryIncidents;
4406
+ private _takeRecoveryReschedule;
4407
+ private _latestUserLeafId;
3897
4408
  protected _handleInternalFiberRecovery(
3898
4409
  ctx: FiberRecoveryContext
3899
4410
  ): Promise<boolean>;
4411
+ /**
4412
+ * A turn that owes its response hook and already persisted its message
4413
+ * finished: its stream rows may be gone with the cutover, so recovery would
4414
+ * otherwise re-run it. Fire the owed hook and settle the submission instead.
4415
+ */
4416
+ private _settlePersistedChatTurn;
4417
+ private _recoverChatFiber;
3900
4418
  /**
3901
4419
  * Resolve the orphaned stream + its terminal status for a recovered chat turn.
3902
4420
  * Drives BOTH the wake path (full result) and the give-up terminalization
@@ -4122,6 +4640,12 @@ declare class Think<
4122
4640
  * until the override returns.
4123
4641
  */
4124
4642
  private _runRecoveredTurnAfterAcceptance;
4643
+ /**
4644
+ * The workflow prompt of the submission a recovery turn is completing. A
4645
+ * structured prompt must re-arm its final-answer tool on the recovered turn,
4646
+ * or the turn can never produce the output the workflow waits for.
4647
+ */
4648
+ private _recoveredWorkflowPrompt;
4125
4649
  _chatRecoveryRetry(data?: ChatRecoveryRetryData): Promise<void>;
4126
4650
  protected _chatRecoveryRetryDetached(
4127
4651
  data?: ChatRecoveryRetryData,
@@ -4187,6 +4711,12 @@ declare class Think<
4187
4711
  * to hold (event-driven) until its remaining siblings answer.
4188
4712
  */
4189
4713
  private _onStreamingTurnFinalized;
4714
+ /**
4715
+ * A pause resolved without a continuation while its turn was streaming; its
4716
+ * deferred drop runs when that turn finalizes instead of at the next
4717
+ * inference.
4718
+ */
4719
+ private _flushResolvedPausesOnFinalize;
4190
4720
  /**
4191
4721
  * Drain every in-flight tool-result/approval apply, including any enqueued
4192
4722
  * while we wait, so the subsequent `_hasIncompleteToolBatch()` re-check sees
@@ -4207,6 +4737,34 @@ declare class Think<
4207
4737
  */
4208
4738
  private _hasIncompleteToolBatch;
4209
4739
  private _fireAutoContinuation;
4740
+ /**
4741
+ * Report a continuation turn that failed before it streamed, the way a
4742
+ * failed client turn is reported: `onChatError`, `chat:request:failed`, a
4743
+ * recorded terminal status, `onChatResponse` for the assistant message it
4744
+ * would have extended, and an error frame. Aborts and Durable Object resets
4745
+ * are left to their own paths.
4746
+ *
4747
+ * @returns Whether the failure was reported.
4748
+ */
4749
+ private _reportContinuationFailure;
4750
+ /**
4751
+ * Settle the continuation state when an auto-continuation turn ends (#2443).
4752
+ *
4753
+ * A turn only owns `pending` until its stream starts: `_streamResult` moves
4754
+ * that pending to the active slot, freeing `pending` for the NEXT
4755
+ * continuation. A client tool result that lands while this turn is still
4756
+ * streaming (a fast client tool chained across steps) creates that next
4757
+ * pending, and the stream-finalize re-arm fires it. So `pending` is cleared
4758
+ * here only while it still holds this turn's request — a turn that never
4759
+ * streamed (failed, aborted, or produced nothing before its stream started).
4760
+ * Clearing unconditionally would drop the newer pending and stall the chat.
4761
+ *
4762
+ * A newer pending that has not started also covers any `deferred` follow-up:
4763
+ * that result arrived before this turn's stream and the newer continuation
4764
+ * runs after it, so firing the deferred too would run a redundant turn that
4765
+ * replays a transcript ending in assistant text.
4766
+ */
4767
+ private _settleContinuationTurn;
4210
4768
  private _activateDeferredContinuation;
4211
4769
  /**
4212
4770
  * Queue a continuation turn that does NOT require a live client connection.
@@ -4246,6 +4804,76 @@ declare class Think<
4246
4804
  */
4247
4805
  private _renderChannelAttachments;
4248
4806
  private _fireResponseHook;
4807
+ /**
4808
+ * Fire a live turn's response hook, then drop its pending marker. When the
4809
+ * bookkeeping before `onChatResponse` throws (attachment delivery, the
4810
+ * terminal-status write), the hook has not run: the marker is kept, with
4811
+ * this outcome, so the next start replays it.
4812
+ */
4813
+ private _fireLiveResponseHook;
4814
+ /** Request ids whose response hook the live turn still owes. */
4815
+ private _responseHooksInFlight;
4816
+ private _pendingResponseHookReplay;
4817
+ /**
4818
+ * Record, before the assistant message is persisted, that this turn owes
4819
+ * `onChatResponse`, so a reset between the persist and the hook replays it.
4820
+ */
4821
+ private _rememberPendingResponseHook;
4822
+ private _forgetPendingResponseHook;
4823
+ /**
4824
+ * Fire the response hooks a reset interrupted. A hook whose message never
4825
+ * persisted is dropped: that turn is recovered, and fires, on its own.
4826
+ */
4827
+ private _replayPendingResponseHooks;
4828
+ private _replayPendingResponseHooksNow;
4829
+ /** Request ids whose interruption handed messenger delivery to recovery. */
4830
+ private _messengerRecoveryClaims;
4831
+ /**
4832
+ * An interrupted messenger turn that recovery will continue: record where
4833
+ * the recovered answer goes before the continuation is scheduled, so the
4834
+ * messenger delivery can skip its apology (#2106). A continuation attempt
4835
+ * of the same incident keeps the existing record.
4836
+ */
4837
+ private _claimMessengerRecoveryDelivery;
4838
+ /**
4839
+ * Durably record a messenger reply's outcome before its recovery incident
4840
+ * settles: once the incident is terminal, nothing re-emits the event that
4841
+ * would settle the reply after a reset. The recovered text is read before
4842
+ * any await, so a later turn cannot replace it.
4843
+ */
4844
+ private _stageMessengerRecoveryOutcome;
4845
+ private _recoveredReplyText;
4846
+ /** Incidents whose messenger reply is being delivered by this isolate. */
4847
+ private _settlingMessengerRecoveries;
4848
+ private _settleMessengerRecovery;
4849
+ /** The latest delivery of each recovered reply key, in call order. */
4850
+ private _messengerRecoveryDeliveries;
4851
+ /**
4852
+ * Deliver a recovered reply after any delivery of the same key already
4853
+ * running in this isolate: startup replay, live settlement and scheduled
4854
+ * retries interleave across awaits, and each must see the cursor the
4855
+ * previous one advanced.
4856
+ */
4857
+ private _deliverMessengerRecovery;
4858
+ /**
4859
+ * Post a settled recovered reply, one post at a time, then drop its record.
4860
+ * Each post goes out at most once: the cursor advances before it, and a
4861
+ * rejected post may still have landed (a timeout after the platform
4862
+ * accepted it), so the retry resumes with the next post.
4863
+ */
4864
+ private _postMessengerRecovery;
4865
+ /** Retry a recovered messenger reply whose live delivery failed. */
4866
+ private _retryMessengerRecoveryDeliveryLater;
4867
+ /**
4868
+ * Retry delivering a recovered messenger reply (see
4869
+ * {@link _retryMessengerRecoveryDeliveryLater}).
4870
+ * @internal Schedule callback.
4871
+ */
4872
+ _cfRetryMessengerRecoveryDelivery(payload: {
4873
+ key: string;
4874
+ attempts: number;
4875
+ }): Promise<void>;
4876
+ private _replayMessengerRecoveryDeliveries;
4249
4877
  /**
4250
4878
  * Persist (on `error`/`interrupted`) or clear (on `completed`/`aborted`) the
4251
4879
  * durable terminal record so it can be replayed to clients on reconnect, and
@@ -4323,16 +4951,29 @@ declare class Think<
4323
4951
  requestId: string,
4324
4952
  options?: {
4325
4953
  messageId?: string;
4954
+ parentMessageId?: string;
4955
+ continuation?: boolean;
4326
4956
  }
4327
4957
  ): string;
4328
4958
  /** Mark a resumable stream completed (settled now, rows kept until reclaim). */
4329
- protected _completeResumableStream(streamId: string): void;
4959
+ protected _completeResumableStream(
4960
+ streamId: string,
4961
+ outcome?: ChatTurnOutcome
4962
+ ): void;
4963
+ /**
4964
+ * A connection offered the stream that never ACKed (`resume: false`, or
4965
+ * gone quiet) must still get the terminal frame and every later broadcast.
4966
+ */
4967
+ private _afterResumableStreamEnded;
4330
4968
  /**
4331
4969
  * The producer finished; leave the row for the cutover that persists the
4332
4970
  * assistant message (`_persistAssistantMessageWithCutover`). Every path
4333
4971
  * that calls this must end in that cutover or `finalizePending()`.
4334
4972
  */
4335
- protected _finishResumableStream(streamId: string): void;
4973
+ protected _finishResumableStream(
4974
+ streamId: string,
4975
+ outcome?: ChatTurnOutcome
4976
+ ): void;
4336
4977
  /** Mark a resumable stream errored. */
4337
4978
  protected _errorResumableStream(streamId: string, requestId?: string): void;
4338
4979
  /**
@@ -4341,8 +4982,24 @@ declare class Think<
4341
4982
  * an earlier version still resolves to a callback when it fires.
4342
4983
  */
4343
4984
  _cleanupStreamBuffers(): Promise<void>;
4985
+ /**
4986
+ * The message an orphaned stream's assistant message branches from, so the
4987
+ * reconstructed message lands where the live turn would have persisted it:
4988
+ * a regeneration beside the response it replaces, not under it. Undefined
4989
+ * for a turn that appends to the latest leaf, and on an `agents` release
4990
+ * that does not record the parent.
4991
+ */
4992
+ private _orphanParentId;
4344
4993
  private _persistOrphanedStream;
4345
4994
  private _broadcastChat;
4995
+ /**
4996
+ * User message ids a WebSocket chat request originated from (#2280), keyed
4997
+ * by request id while the request is handled. After that (or after a
4998
+ * restart) the request's stream metadata is the fallback.
4999
+ */
5000
+ private _requestOriginMessageIds;
5001
+ private _originMessageIdsFor;
5002
+ private _withOriginMessageIds;
4346
5003
  private _broadcast;
4347
5004
  private _broadcastMessages;
4348
5005
  }
@@ -4421,11 +5078,24 @@ interface MessengerContext {
4421
5078
  message?: MessengerMessage;
4422
5079
  messengerId: string;
4423
5080
  provider: string;
5081
+ /**
5082
+ * Earlier messages folded into this event, oldest first. A quick run of
5083
+ * messages in one thread is answered once, for its newest message (the Chat
5084
+ * SDK `burst` concurrency strategy); the rest arrive here. They are part of
5085
+ * this turn's input: the model-facing user message renders them before
5086
+ * `message`, and their attachments are listed with its own.
5087
+ */
5088
+ skipped?: MessengerMessage[];
4424
5089
  thread: MessengerThread;
4425
5090
  }
4426
5091
  interface MessengerEvent extends MessengerContext {
4427
5092
  raw?: unknown;
4428
5093
  }
5094
+ /**
5095
+ * The context persisted on a messenger turn's user message. Built from the
5096
+ * serializable form of the event, so raw platform payloads and attachment
5097
+ * bytes are never stored and a live turn matches its recovered replay.
5098
+ */
4429
5099
  declare function messengerContextFromEvent(
4430
5100
  event: MessengerEvent
4431
5101
  ): MessengerContext;
@@ -4459,10 +5129,16 @@ declare const ERROR_MESSENGER_RESPONSE =
4459
5129
  declare const INTERRUPTED_MESSENGER_RESPONSE =
4460
5130
  "Sorry, my reply was interrupted. Please send your message again if you'd like me to retry.";
4461
5131
  interface TextStreamCallbackOptions {
5132
+ /**
5133
+ * Streamed as the reply when a turn completes without text, so surfaces that
5134
+ * wait for the first chunk before posting never post an empty message.
5135
+ */
5136
+ emptyText?: string;
4462
5137
  onVisibleStart?: () => Promise<void> | void;
4463
5138
  visibleSoftLimit?: number;
4464
5139
  }
4465
5140
  declare class TextStreamCallback extends RpcTarget implements StreamCallback {
5141
+ private readonly emptyText?;
4466
5142
  private readonly onVisibleStart?;
4467
5143
  private readonly textSegmentJoiner;
4468
5144
  private readonly visibleChunks;
@@ -4471,6 +5147,7 @@ declare class TextStreamCallback extends RpcTarget implements StreamCallback {
4471
5147
  private chatRequestId?;
4472
5148
  private closed;
4473
5149
  private interrupted;
5150
+ private recoveredReplyDelivered;
4474
5151
  private error?;
4475
5152
  private text;
4476
5153
  private visibleClosed;
@@ -4482,11 +5159,20 @@ declare class TextStreamCallback extends RpcTarget implements StreamCallback {
4482
5159
  onEvent(json: string): void;
4483
5160
  onDone(): void;
4484
5161
  onError(error: string): void;
4485
- onInterrupted(): void;
5162
+ onInterrupted(info?: ChatInterruptedInfo): void;
4486
5163
  wasInterrupted(): boolean;
5164
+ /** Whether the target posts the recovered reply to the thread itself. */
5165
+ targetDeliversRecoveredReply(): boolean;
5166
+ /** Ends a completed turn, streaming `emptyText` if it produced no text. */
5167
+ complete(): void;
4487
5168
  close(): void;
4488
5169
  fail(error: unknown): void;
4489
5170
  hasText(): boolean;
5171
+ /**
5172
+ * Resolves `true` once there is visible text to post, or `false` when the
5173
+ * stream ends without any, so a caller can avoid posting an empty reply.
5174
+ */
5175
+ hasVisibleOutput(): Promise<boolean>;
4490
5176
  remainingText(): string;
4491
5177
  requestId(): string | undefined;
4492
5178
  textSoFar(): string;
@@ -4583,6 +5269,13 @@ interface MessengerDeliveryPolicy {
4583
5269
  callback: TextStreamCallback
4584
5270
  ): boolean;
4585
5271
  splitText?(text: string): string[];
5272
+ /**
5273
+ * How often, in milliseconds, the typing indicator is re-sent until the
5274
+ * reply's first text is posted. Platforms expire the indicator after a few
5275
+ * seconds. `0` sends it once.
5276
+ * @default 4000
5277
+ */
5278
+ typingRefreshMs?: number;
4586
5279
  visibleSoftLimit?: number;
4587
5280
  }
4588
5281
  interface DeliverMessengerReplyOptions {
@@ -4649,6 +5342,9 @@ interface MessengerDefinition {
4649
5342
  | ((request: Request) => boolean | Response | Promise<boolean | Response>);
4650
5343
  }
4651
5344
  type ThinkMessengers = Record<string, MessengerDefinition>;
5345
+ /** The Chat SDK `concurrency` setting for a Think agent's messengers. */
5346
+ type MessengerConcurrency = ConcurrencyStrategy | ConcurrencyConfig;
5347
+ declare const DEFAULT_MESSENGER_CONCURRENCY: MessengerConcurrency;
4652
5348
  interface NormalizedMessengerDefinition extends MessengerDefinition {
4653
5349
  id: string;
4654
5350
  path: string;
@@ -4669,6 +5365,14 @@ interface ChatSdkMessengerEventInput {
4669
5365
  eventKind: MessengerEventKind;
4670
5366
  message?: Message;
4671
5367
  raw?: unknown;
5368
+ /**
5369
+ * Earlier messages the Chat SDK's concurrency strategy folded into this one,
5370
+ * oldest first (`MessageContext.skipped`). The runtime's `burst` strategy
5371
+ * answers only the newest message of a quick run and reports the rest here.
5372
+ * {@link defaultChatSdkEvent} carries them on the event's `skipped` so they
5373
+ * reach the model; a custom `toEvent` that ignores them drops them.
5374
+ */
5375
+ skipped?: readonly Message[];
4672
5376
  thread: Thread;
4673
5377
  }
4674
5378
  interface MessengerThinkTarget {
@@ -4717,6 +5421,8 @@ interface MessengerThinkHost extends MessengerThinkTarget {
4717
5421
  agentClass: SubAgentClass<T>,
4718
5422
  name: string
4719
5423
  ): Promise<SubAgentStub<T>>;
5424
+ /** Keep the host alive while background messenger work runs. */
5425
+ keepAliveWhile?<T>(fn: () => Promise<T>): Promise<T>;
4720
5426
  }
4721
5427
  interface MessengerFiberStartResult {
4722
5428
  accepted: boolean;
@@ -4739,7 +5445,14 @@ declare class ThinkMessengerRuntime {
4739
5445
  private readonly definitionsByAdapterName;
4740
5446
  private readonly definitionsById;
4741
5447
  private readonly definitions;
4742
- constructor(definitions: ThinkMessengers, host: MessengerThinkHost);
5448
+ private readonly concurrency;
5449
+ constructor(
5450
+ definitions: ThinkMessengers,
5451
+ host: MessengerThinkHost,
5452
+ options?: {
5453
+ concurrency?: MessengerConcurrency;
5454
+ }
5455
+ );
4743
5456
  get size(): number;
4744
5457
  initialize(): void;
4745
5458
  handleRequest(request: Request): Promise<Response | undefined>;
@@ -4756,8 +5469,25 @@ declare class ThinkMessengerRuntime {
4756
5469
  persistRecoverySnapshot?: (
4757
5470
  snapshot: ReturnType<typeof messengerReplySnapshot>
4758
5471
  ) => Promise<void> | void;
5472
+ /**
5473
+ * Whether the caller replays this recovery after it throws `error`.
5474
+ * Messages queued behind the reply are drained only once it settles,
5475
+ * so they are never answered ahead of it. Default: no replay.
5476
+ */
5477
+ retriesAfter?: (error: unknown) => boolean;
4759
5478
  }
4760
5479
  ): Promise<boolean>;
5480
+ private recoverReply;
5481
+ /**
5482
+ * Messages queued behind a reply are drained only by the Chat SDK handler
5483
+ * holding the thread lock. When the isolate running that reply dies, the
5484
+ * queue is stranded until another message arrives, so recovery drains it:
5485
+ * once the dead holder's lock expires, take the lock and hand the queue to
5486
+ * the SDK's own drain. A live holder drains the queue itself, which ends
5487
+ * the wait.
5488
+ */
5489
+ private drainQueuedMessagesInBackground;
5490
+ private drainQueuedMessages;
4761
5491
  private createChat;
4762
5492
  /** Whether this isolate still holds the live closure for one reply. */
4763
5493
  hasLiveReply(nonce: string): boolean;
@@ -4785,13 +5515,35 @@ declare class ThinkMessengerRuntime {
4785
5515
  channelId: string,
4786
5516
  threadId?: string
4787
5517
  ): Promise<MessengerDeliverySurface | undefined>;
5518
+ /**
5519
+ * Post what chat recovery produced for an interrupted messenger turn: the
5520
+ * text the thread has not seen yet, or the interrupted apology when
5521
+ * recovery gave up. The reply may span several posts; this posts only post
5522
+ * number `chunk` (skipped when out of range) and returns how many there
5523
+ * are, so the caller can checkpoint between posts.
5524
+ */
5525
+ deliverRecoveredReply(input: {
5526
+ messengerId: string;
5527
+ threadId: string;
5528
+ outcome: "completed" | "interrupted";
5529
+ text?: string;
5530
+ partialPosted?: boolean;
5531
+ chunk: number;
5532
+ }): Promise<{
5533
+ chunks: number;
5534
+ }>;
4788
5535
  private resolveTarget;
4789
5536
  private definitionForThread;
4790
5537
  private definitionForThreadId;
4791
5538
  private hasUniqueProvider;
4792
5539
  private shardThread;
4793
5540
  private shardStateKey;
4794
- private reviveChatObject;
5541
+ /**
5542
+ * `ThreadImpl.fromJSON` (what `chat.reviver()` calls) builds the thread
5543
+ * without the Chat's streaming config, so a recovered reply would fall back to
5544
+ * the `"..."` placeholder. Rebuild it from the same fields with that config.
5545
+ */
5546
+ private reviveThread;
4795
5547
  private toEvent;
4796
5548
  }
4797
5549
  declare function normalizeMessengers(
@@ -4829,162 +5581,171 @@ declare function toMessengerAttachment(
4829
5581
  ): MessengerAttachment;
4830
5582
  //#endregion
4831
5583
  export {
4832
- MessengerThread as $,
4833
- StepConfig as $t,
4834
- MESSENGER_REPLY_FIBER_NAME as A,
4835
- Workspace$1 as An,
4836
- ExtensionConfig as At,
4837
- messengerReplyFailureMode as B,
4838
- ChannelIngress as Bn,
4839
- ReplyAttachment as Bt,
4840
- toMessengerThread as C,
4841
- TurnConfig as Cn,
4842
- ChatResponseResult$1 as Ct,
4843
- EMPTY_MESSENGER_RESPONSE as D,
4844
- TurnResult as Dn,
4845
- ContextOverflowConfig as Dt,
4846
- DeliveryTag as E,
4847
- TurnInputMessages as En,
4848
- ChunkPart as Et,
4849
- MessengerReplyStage as F,
4850
- ChannelCapabilities as Fn,
4851
- OnStartDegradation as Ft,
4852
- MessengerAction as G,
4853
- MediaEvictionConfig as Gn,
4854
- RunTurnSubmit as Gt,
4855
- messengerReplySnapshot as H,
4856
- NormalizedChannelDefinition as Hn,
4857
- RunTurnBase as Ht,
4858
- TextStreamCallback as I,
4859
- ChannelContext as In,
4860
- PendingApproval as It,
4861
- MessengerCapabilities as J,
4862
- SessionContextOptions as Jn,
4863
- SaveMessagesResult$1 as Jt,
4864
- MessengerAttachment as K,
4865
- CompactAfterOptions as Kn,
4866
- RunTurnWait as Kt,
4867
- TextStreamCallbackOptions as L,
4868
- ChannelDefinition as Ln,
4869
- PrepareStepContext as Lt,
4870
- MessengerDeliverySurface as M,
4871
- defaultContextOverflowClassifier as Mn,
4872
- FiberRecoveryContext$1 as Mt,
4873
- MessengerDeliveryTarget as N,
4874
- isAction as Nn,
4875
- ListSubmissionsOptions as Nt,
4876
- ERROR_MESSENGER_RESPONSE as O,
4877
- TypedToolCall$1 as On,
4878
- DeleteSubmissionsOptions as Ot,
4879
- MessengerReplySnapshot as P,
4880
- skills as Pn,
4881
- MessageConcurrency$1 as Pt,
4882
- MessengerMessage as Q,
4883
- SkillWorkspaceSeedOptions$1 as Qt,
4884
- defaultDeliveryTag as R,
4885
- ChannelDeliveryPolicy as Rn,
4886
- PrepareStepFunction$1 as Rt,
4887
- toMessengerMessage as S,
4888
- ToolCallResultContext as Sn,
4889
- ChatRecoveryProgressContext as St,
4890
- DeliveryKind as T,
4891
- TurnInput as Tn,
4892
- ChunkContext as Tt,
4893
- parseMessengerReplySnapshot as U,
4894
- ThinkChannels as Un,
4895
- RunTurnOptions as Ut,
4896
- messengerReplyRecoveryMode as V,
4897
- ChannelKind as Vn,
4898
- ResolvedChatRecoveryConfig as Vt,
4899
- ChannelSpeakerLabel as W,
4900
- messengerChannel as Wn,
4901
- RunTurnStream as Wt,
4902
- MessengerEvent as X,
4903
- SkillRunContext as Xt,
4904
- MessengerContext as Y,
4905
- ThinkSession as Yn,
4906
- SessionMessage$1 as Yt,
4907
- MessengerEventKind as Z,
4908
- SkillSource$1 as Zt,
4909
- idempotencyKeyForEvent as _,
4910
- ThinkSubmissionStatus as _n,
4911
- ChatOptions as _t,
4912
- MessengerConversationTarget as a,
4913
- SubmitMessagesOptions as an,
4914
- ActionApprovalDescriptor as at,
4915
- toMessengerAttachment as b,
4916
- ToolCallContext as bn,
4917
- ChatRecoveryExhaustedContext as bt,
4918
- MessengerThinkHost as c,
4919
- Think as cn,
4920
- ActionAuthorizationDecision as ct,
4921
- ThinkMessengerRuntime as d,
4922
- ThinkModelId as dn,
4923
- ActionIdempotencyKey as dt,
4924
- StepContext as en,
4925
- messengerContextFromEvent as et,
4926
- ThinkMessengerStateAgent as f,
4927
- ThinkScheduledTask as fn,
4928
- ActionKind as ft,
4929
- defaultConversationName as g,
4930
- ThinkSubmissionInspection as gn,
4931
- ChatErrorContext as gt,
4932
- defaultChatSdkEvent as h,
4933
- ThinkScheduledTasks as hn,
4934
- ChatErrorClassification as ht,
4935
- MessengerConversationResolver as i,
4936
- StreamableResult as in,
4937
- Action as it,
4938
- MessengerDeliveryPolicy as j,
4939
- action as jn,
4940
- FiberContext$1 as jt,
4941
- INTERRUPTED_MESSENGER_RESPONSE as k,
4942
- TypedToolResult as kn,
4943
- DeliverNoticeOptions as kt,
4944
- MessengerThinkTarget as l,
4945
- ThinkIntervalSchedule as ln,
4946
- ActionConfig as lt,
4947
- chatSdkMessenger as m,
4948
- ThinkScheduledTaskSchedule as mn,
4949
- AddMessagesOptions as mt,
5584
+ MessengerEventKind as $,
5585
+ messengerChannel as $n,
5586
+ RunTurnWait as $t,
5587
+ ERROR_MESSENGER_RESPONSE as A,
5588
+ TurnConfig as An,
5589
+ ChunkContext as At,
5590
+ defaultDeliveryTag as B,
5591
+ action as Bn,
5592
+ MessageMetadataCallback as Bt,
5593
+ toMessengerAuthor as C,
5594
+ ThinkSubmissionInspection as Cn,
5595
+ ChatRecoveryConfig$1 as Ct,
5596
+ DeliveryKind as D,
5597
+ ToolCallContext as Dn,
5598
+ ChatRecoveryProgressContext as Dt,
5599
+ DeliverMessengerReplyOptions as E,
5600
+ ThinkWallClockSchedule as En,
5601
+ ChatRecoveryOptions$1 as Et,
5602
+ MessengerDeliveryTarget as F,
5603
+ TurnTrigger as Fn,
5604
+ ExtensionConfig as Ft,
5605
+ parseMessengerReplySnapshot as G,
5606
+ ChannelContext as Gn,
5607
+ PrepareStepResult$1 as Gt,
5608
+ messengerReplyFailureMode as H,
5609
+ isAction as Hn,
5610
+ PendingApproval as Ht,
5611
+ MessengerReplySnapshot as I,
5612
+ TypedToolCall$1 as In,
5613
+ FiberContext$1 as It,
5614
+ MessengerAttachment as J,
5615
+ ChannelDeliverySurface as Jn,
5616
+ ResolvedChatRecoveryConfig as Jt,
5617
+ ChannelSpeakerLabel as K,
5618
+ ChannelDefinition as Kn,
5619
+ RejectExecutionOptions as Kt,
5620
+ MessengerReplyStage as L,
5621
+ TypedToolResult as Ln,
5622
+ FiberRecoveryContext$1 as Lt,
5623
+ MESSENGER_REPLY_FIBER_NAME as M,
5624
+ TurnInput as Mn,
5625
+ ContextOverflowConfig as Mt,
5626
+ MessengerDeliveryPolicy as N,
5627
+ TurnInputMessages as Nn,
5628
+ DeleteSubmissionsOptions as Nt,
5629
+ DeliveryTag as O,
5630
+ ToolCallDecision as On,
5631
+ ChatResponseResult$1 as Ot,
5632
+ MessengerDeliverySurface as P,
5633
+ TurnResult as Pn,
5634
+ DeliverNoticeOptions as Pt,
5635
+ MessengerEvent as Q,
5636
+ ThinkChannels as Qn,
5637
+ RunTurnSubmit as Qt,
5638
+ TextStreamCallback as R,
5639
+ WaitForSubmissionOptions as Rn,
5640
+ ListSubmissionsOptions as Rt,
5641
+ toMessengerAttachment as S,
5642
+ ThinkScheduledTasks as Sn,
5643
+ ChatOptions as St,
5644
+ toMessengerThread as T,
5645
+ ThinkTime as Tn,
5646
+ ChatRecoveryExhaustedContext as Tt,
5647
+ messengerReplyRecoveryMode as U,
5648
+ skills as Un,
5649
+ PrepareStepContext as Ut,
5650
+ deliverMessengerReply as V,
5651
+ defaultContextOverflowClassifier as Vn,
5652
+ OnStartDegradation as Vt,
5653
+ messengerReplySnapshot as W,
5654
+ ChannelCapabilities as Wn,
5655
+ PrepareStepFunction$1 as Wt,
5656
+ MessengerCapabilities as X,
5657
+ ChannelKind as Xn,
5658
+ RunTurnOptions as Xt,
5659
+ MessengerAuthor as Y,
5660
+ ChannelIngress as Yn,
5661
+ RunTurnBase as Yt,
5662
+ MessengerContext as Z,
5663
+ NormalizedChannelDefinition as Zn,
5664
+ RunTurnStream as Zt,
5665
+ defaultChatSdkEvent as _,
5666
+ ThinkModel as _n,
5667
+ AddMessagesOptions as _t,
5668
+ MessengerConversationMode as a,
5669
+ SkillWorkspaceSeedOptions$1 as an,
5670
+ toMessengerUserMessage as at,
5671
+ normalizeMessengers as b,
5672
+ ThinkScheduledTaskContext as bn,
5673
+ ChatErrorContext as bt,
5674
+ MessengerDefinition as c,
5675
+ StepResult as cn,
5676
+ ActionApprovalPolicy as ct,
5677
+ MessengerThinkTarget as d,
5678
+ StreamableResult as dn,
5679
+ ActionConfig as dt,
5680
+ SaveMessagesOptions$1 as en,
5681
+ MediaEvictionConfig as er,
5682
+ MessengerMessage as et,
5683
+ NormalizedMessengerDefinition as f,
5684
+ SubmitMessagesOptions as fn,
5685
+ ActionContext as ft,
5686
+ chatSdkMessenger as g,
5687
+ ThinkIntervalSchedule as gn,
5688
+ ActiveTurn as gt,
5689
+ ThinkMessengers as h,
5690
+ Think as hn,
5691
+ ActionPermissionSpec as ht,
5692
+ MessengerConcurrency as i,
5693
+ SkillSource$1 as in,
5694
+ ThinkSession as ir,
5695
+ serializableMessengerEvent as it,
5696
+ INTERRUPTED_MESSENGER_RESPONSE as j,
5697
+ TurnContext as jn,
5698
+ ChunkPart as jt,
5699
+ EMPTY_MESSENGER_RESPONSE as k,
5700
+ ToolCallResultContext as kn,
5701
+ ChatStartEvent as kt,
5702
+ MessengerRespondTo as l,
5703
+ StopCondition$1 as ln,
5704
+ ActionAuthorizationContext as lt,
5705
+ ThinkMessengerStateAgent as m,
5706
+ TextStreamPart$1 as mn,
5707
+ ActionKind as mt,
4950
5708
  ChatSdkMessengerOptions as n,
4951
- StopCondition$1 as nn,
4952
- serializableMessengerEvent as nt,
4953
- MessengerDefinition as o,
4954
- SubmitMessagesResult as on,
4955
- ActionApprovalPolicy as ot,
4956
- ThinkMessengers as p,
4957
- ThinkScheduledTaskContext as pn,
4958
- ActionPermissionSpec as pt,
4959
- MessengerAuthor as q,
4960
- CompactionErrorHandler as qn,
4961
- SaveMessagesOptions$1 as qt,
4962
- MessengerConversationMode as r,
4963
- StreamCallback as rn,
4964
- toMessengerUserMessage as rt,
4965
- MessengerRespondTo as s,
4966
- TextStreamPart as sn,
4967
- ActionAuthorizationContext as st,
5709
+ SessionMessage$1 as nn,
5710
+ CompactionErrorHandler as nr,
5711
+ messengerContextFromEvent as nt,
5712
+ MessengerConversationResolver as o,
5713
+ StepConfig as on,
5714
+ Action as ot,
5715
+ ThinkMessengerRuntime as p,
5716
+ SubmitMessagesResult as pn,
5717
+ ActionIdempotencyKey as pt,
5718
+ MessengerAction as q,
5719
+ ChannelDeliveryPolicy as qn,
5720
+ ReplyAttachment as qt,
5721
+ DEFAULT_MESSENGER_CONCURRENCY as r,
5722
+ SkillRunContext as rn,
5723
+ SessionContextOptions as rr,
5724
+ resolveChannelSpeakerLabel as rt,
5725
+ MessengerConversationTarget as s,
5726
+ StepContext as sn,
5727
+ ActionApprovalDescriptor as st,
4968
5728
  ChatSdkMessengerEventInput as t,
4969
- StepResult as tn,
4970
- resolveChannelSpeakerLabel as tt,
4971
- NormalizedMessengerDefinition as u,
4972
- ThinkModel as un,
4973
- ActionContext as ut,
4974
- normalizeMessengers as v,
4975
- ThinkTime as vn,
4976
- ChatRecoveryConfig$1 as vt,
4977
- DeliverMessengerReplyOptions as w,
4978
- TurnContext as wn,
4979
- ChatStartEvent as wt,
4980
- toMessengerAuthor as x,
4981
- ToolCallDecision as xn,
4982
- ChatRecoveryOptions$1 as xt,
4983
- resolveSelfMention as y,
4984
- ThinkWallClockSchedule as yn,
4985
- ChatRecoveryContext$1 as yt,
4986
- deliverMessengerReply as z,
4987
- ChannelDeliverySurface as zn,
4988
- PrepareStepResult$1 as zt
5729
+ SaveMessagesResult$1 as tn,
5730
+ CompactAfterOptions as tr,
5731
+ MessengerThread as tt,
5732
+ MessengerThinkHost as u,
5733
+ StreamCallback as un,
5734
+ ActionAuthorizationDecision as ut,
5735
+ defaultConversationName as v,
5736
+ ThinkModelId as vn,
5737
+ CancelSubmissionResult as vt,
5738
+ toMessengerMessage as w,
5739
+ ThinkSubmissionStatus as wn,
5740
+ ChatRecoveryContext$1 as wt,
5741
+ resolveSelfMention as x,
5742
+ ThinkScheduledTaskSchedule as xn,
5743
+ ChatInterruptedInfo as xt,
5744
+ idempotencyKeyForEvent as y,
5745
+ ThinkScheduledTask as yn,
5746
+ ChatErrorClassification as yt,
5747
+ TextStreamCallbackOptions as z,
5748
+ Workspace$1 as zn,
5749
+ MessageConcurrency$1 as zt
4989
5750
  };
4990
- //# sourceMappingURL=index-BLkPlEbF.d.ts.map
5751
+ //# sourceMappingURL=index-CmhSKa6U.d.ts.map