@cloudflare/think 0.8.1 → 0.8.3

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.
@@ -53,6 +53,7 @@ import {
53
53
  ChatRecoveryExhaustedContext,
54
54
  ChatRecoveryOptions,
55
55
  ChatRecoveryOptions as ChatRecoveryOptions$1,
56
+ ChatRecoveryProgressContext,
56
57
  ChatResponseResult,
57
58
  ChatResponseResult as ChatResponseResult$1,
58
59
  ClientToolSchema,
@@ -399,10 +400,126 @@ interface TurnConfig {
399
400
  */
400
401
  output?: Parameters<typeof streamText>[0]["output"];
401
402
  }
403
+ /**
404
+ * Provider-agnostic semantic classification of a chat-turn error.
405
+ *
406
+ * Think ships **no** provider-specific string/code matching — the app owns
407
+ * that knowledge (it knows which provider/model it talks to), exactly like the
408
+ * `tokenCounter` it already passes to `compactAfter()`. An app teaches Think
409
+ * what an error *means* by overriding `classifyChatError()`; Think then reacts
410
+ * generically (e.g. compact-and-retry on `context_overflow`).
411
+ *
412
+ * - `context_overflow` — the prompt exceeded the model's context window
413
+ * (Anthropic `"prompt is too long"`, OpenAI `context_length_exceeded`, …).
414
+ * The only category Think currently acts on (auto-compact + retry).
415
+ * - `rate_limit` / `transient` — reserved for future backoff/retry policies.
416
+ * - `fatal` — unrecoverable; surface terminally.
417
+ * - `unknown` — default; Think applies its existing terminal behavior.
418
+ */
419
+ type ChatErrorClassification =
420
+ | "context_overflow"
421
+ | "rate_limit"
422
+ | "transient"
423
+ | "fatal"
424
+ | "unknown";
425
+ /**
426
+ * Opt-in handling for a turn that overflows the model's context window
427
+ * mid-flight. Compaction (`compactAfter()`) is only checked between turns, so a
428
+ * long, tool-heavy turn can grow past the window before the next check; the
429
+ * provider then rejects the request (`"prompt is too long"` /
430
+ * `context_length_exceeded`). Both layers reuse the session's compaction
431
+ * function and are provider-agnostic — the app maps the error via
432
+ * {@link Think.classifyChatError}; Think never matches provider strings itself.
433
+ *
434
+ * Set `Think.contextOverflow` to enable. Leaving it unset disables both layers
435
+ * (existing terminal behavior).
436
+ */
437
+ interface ContextOverflowConfig {
438
+ /**
439
+ * Reactive backstop. When a turn fails with an error classified as
440
+ * `"context_overflow"`, discard the truncated partial, run
441
+ * `session.compact()`, and re-run the turn from the compacted history. The
442
+ * partial is intentionally not persisted: the turn restarts from scratch, so
443
+ * keeping the cut-off assistant message would orphan it beside the recovered
444
+ * answer (and duplicate any tool work the retry re-issues). If compaction
445
+ * cannot shorten history or the retry budget is spent, the overflow surfaces
446
+ * terminally through `onChatError` (classified) — it never loops or ends
447
+ * silently. Default `false`.
448
+ */
449
+ reactive?: boolean;
450
+ /**
451
+ * Maximum compact-and-retry attempts for a single overflowing turn (the
452
+ * reactive backstop). Independent of the proactive guard's cap — see
453
+ * {@link proactive.maxCompactions}. Default `1`.
454
+ */
455
+ maxRetries?: number;
456
+ /**
457
+ * Proactive guard. Before each step, read the previous step's model-reported
458
+ * `usage.inputTokens` and, if it crosses `maxInputTokens * (headroom ?? 0.9)`,
459
+ * compact in place and feed the recompacted history into the upcoming step —
460
+ * heading off the provider rejection before it happens. Keys off usage (every
461
+ * provider reports it), not provider error strings. Unset disables it.
462
+ *
463
+ * If a provider omits `inputTokens`, the guard falls back to `usage.totalTokens`
464
+ * (input + output) — a safe over-approximation that compacts slightly early
465
+ * rather than missing the threshold. If neither is reported, the guard does
466
+ * nothing that step (the reactive backstop still catches a genuine overflow).
467
+ *
468
+ * `maxCompactions` caps how many times the guard may compact within a single
469
+ * step loop (default `1`, floored at `1`). It is independent of
470
+ * {@link maxRetries} (the reactive budget): a no-op compaction would repeat on
471
+ * every step, so the cap stops the guard from compacting (and emitting
472
+ * `chat:context:compacted`) on each one.
473
+ */
474
+ proactive?: {
475
+ maxInputTokens: number;
476
+ headroom?: number;
477
+ maxCompactions?: number;
478
+ };
479
+ }
480
+ /**
481
+ * Opt-in default classifier for {@link Think.classifyChatError}. Matches the
482
+ * context-window-overflow error messages of the common providers (Anthropic,
483
+ * OpenAI, Google, Bedrock, Mistral, …) and returns `"context_overflow"`.
484
+ *
485
+ * Think ships this as an explicitly-imported helper rather than wiring it into
486
+ * core, so the framework default stays free of provider strings. Assign it (or
487
+ * delegate to it) when you do not need custom classification:
488
+ *
489
+ * @example
490
+ * ```typescript
491
+ * import { Think, defaultContextOverflowClassifier } from "@cloudflare/think";
492
+ *
493
+ * export class MyAgent extends Think<Env> {
494
+ * override contextOverflow = { reactive: true };
495
+ * override classifyChatError = defaultContextOverflowClassifier;
496
+ * }
497
+ * ```
498
+ *
499
+ * Or combine with your own checks:
500
+ *
501
+ * @example
502
+ * ```typescript
503
+ * override classifyChatError(error: unknown): ChatErrorClassification | void {
504
+ * if (isMyRateLimit(error)) return "rate_limit";
505
+ * return defaultContextOverflowClassifier(error);
506
+ * }
507
+ * ```
508
+ */
509
+ declare function defaultContextOverflowClassifier(
510
+ error: unknown
511
+ ): ChatErrorClassification | undefined;
402
512
  interface ChatErrorContext {
403
513
  requestId?: string;
404
514
  stage: "parse" | "persist" | "turn" | "stream" | "recovery" | "transcript";
405
515
  messagesPersisted?: boolean;
516
+ /**
517
+ * App-provided semantic classification (from `classifyChatError`), when
518
+ * known. Lets `onChatError` overrides and observers distinguish e.g. a
519
+ * context-overflow from a generic provider failure without re-matching
520
+ * provider strings.
521
+ */
522
+ classification?: ChatErrorClassification;
406
523
  }
407
524
  /**
408
525
  * Context passed to the `beforeStep` hook before each AI SDK step in
@@ -612,6 +729,12 @@ declare class Think<
612
729
  /**
613
730
  * When true, chat turns are wrapped in `runFiber` for durable execution.
614
731
  * Enables `onChatRecovery` hook and `this.stash()` during streaming.
732
+ *
733
+ * Assign this as a class field or in the constructor — NOT in `onStart()`.
734
+ * On every wake the SDK evaluates recovery budgets (and may seal an
735
+ * interrupted turn, firing `onExhausted`) before `onStart()` runs, so a config
736
+ * set in `onStart()` is applied too late and the built-in defaults are used
737
+ * for the recovery that matters. See {@link ChatRecoveryConfig}.
615
738
  */
616
739
  chatRecovery: ChatRecoveryConfig;
617
740
  static readonly CHAT_FIBER_NAME = "__cf_internal_chat_turn";
@@ -904,6 +1027,53 @@ declare class Think<
904
1027
  * top of every `_runInferenceLoop`.
905
1028
  */
906
1029
  private _activeStallTimeoutMs;
1030
+ /**
1031
+ * Opt-in handling for a turn that overflows the context window mid-flight.
1032
+ * See {@link ContextOverflowConfig}. Unset (the default) leaves the existing
1033
+ * terminal behavior unchanged.
1034
+ *
1035
+ * @example
1036
+ * ```typescript
1037
+ * override contextOverflow = {
1038
+ * reactive: true,
1039
+ * proactive: { maxInputTokens: 200_000 }
1040
+ * };
1041
+ * ```
1042
+ */
1043
+ contextOverflow?: ContextOverflowConfig;
1044
+ /** Whether the reactive compact-and-retry backstop is enabled. */
1045
+ private get _overflowReactiveEnabled();
1046
+ /** Reactive compact-and-retry budget. */
1047
+ private get _overflowMaxRetries();
1048
+ /** Proactive guard config, when enabled. */
1049
+ private get _overflowGuard();
1050
+ /** Per-run cap on proactive compactions (independent of the reactive budget). */
1051
+ private get _overflowProactiveMaxCompactions();
1052
+ /**
1053
+ * Count of model messages assembled from history at the start of the current
1054
+ * turn (captured in `_runInferenceLoop`). The proactive guard uses it to
1055
+ * splice this turn's in-flight steps onto a freshly recompacted head. Turns
1056
+ * are serialized, so a single value is safe.
1057
+ */
1058
+ private _turnModelMessageBaseline;
1059
+ /**
1060
+ * The assembled tool set for the current turn, captured in
1061
+ * `_runInferenceLoop`. The proactive guard reuses it to convert the
1062
+ * recompacted history through the same `convertToModelMessages` tool schemas.
1063
+ * Turns are serialized, so a single value is safe.
1064
+ */
1065
+ private _activeTurnTools;
1066
+ /**
1067
+ * Number of times the proactive guard has compacted within the current
1068
+ * `_runInferenceLoop` (reset at the top of each run). Capped at
1069
+ * `contextOverflow.proactive.maxCompactions` (default `1`) so a guard that
1070
+ * keeps reading over-budget usage can't compact on every step — once the head
1071
+ * is summarized, further compaction no-ops anyway, and a genuine remaining
1072
+ * overflow falls through to the reactive backstop.
1073
+ */
1074
+ private _proactiveCompactionsThisRun;
1075
+ /** One-time guard for the "recovery enabled but no classifier" DX warning. */
1076
+ private _warnedMissingClassifier;
907
1077
  /**
908
1078
  * Configure the session. Called once during `onStart`.
909
1079
  * Override to add context blocks, compaction, search, skills.
@@ -1111,7 +1281,103 @@ declare class Think<
1111
1281
  * Override to customize error handling (e.g. logging, metrics).
1112
1282
  */
1113
1283
  onChatError(error: unknown, _ctx?: ChatErrorContext): unknown;
1284
+ /**
1285
+ * Classify a raw chat-turn error into a provider-agnostic category.
1286
+ *
1287
+ * Think deliberately ships **no** provider-specific matching: it cannot know
1288
+ * that Anthropic's `"prompt is too long"` or OpenAI's
1289
+ * `context_length_exceeded` means "context overflow" without baking provider
1290
+ * knowledge into core. The app does know its provider/model, so it owns the
1291
+ * mapping — the same split Think already uses for `tokenCounter`.
1292
+ *
1293
+ * Currently this hook drives **only** context-overflow recovery: it is
1294
+ * consulted when a turn errors **and** `contextOverflow.reactive` is enabled
1295
+ * (if reactive is off, it is not called). Return `"context_overflow"` to run
1296
+ * the compact-and-retry backstop; if recovery cannot save the turn, that
1297
+ * classification is surfaced on the terminal `onChatError` call via
1298
+ * {@link ChatErrorContext.classification}. The other categories are reserved
1299
+ * for future use — returning one today is a no-op (the turn terminalizes as
1300
+ * usual) and it is **not** forwarded to `onChatError`. Returning
1301
+ * `void`/`"unknown"` keeps the existing terminal behavior.
1302
+ *
1303
+ * The argument may be an `Error`, an AI SDK `APICallError` (with
1304
+ * `statusCode`/`responseBody`), or — for in-stream provider errors that
1305
+ * surface as a stream error part rather than a throw — the error message
1306
+ * string. Narrow accordingly.
1307
+ *
1308
+ * The second argument carries a {@link ChatErrorContext}: when consulted for
1309
+ * overflow recovery it is `{ stage: "stream", requestId }`, so a classifier
1310
+ * can correlate the error with the in-flight turn (e.g. to call
1311
+ * {@link cancelChat}).
1312
+ *
1313
+ * @example Anthropic + OpenAI context-overflow
1314
+ * ```typescript
1315
+ * classifyChatError(error: unknown): ChatErrorClassification | void {
1316
+ * const text = error instanceof Error ? error.message : String(error);
1317
+ * if (/prompt is too long|context length|context_length_exceeded|maximum context/i.test(text)) {
1318
+ * return "context_overflow";
1319
+ * }
1320
+ * }
1321
+ * ```
1322
+ */
1323
+ classifyChatError(
1324
+ _error: unknown,
1325
+ _ctx?: ChatErrorContext
1326
+ ): ChatErrorClassification | void;
1327
+ /**
1328
+ * Whether an error (thrown or surfaced as an in-stream error string) should
1329
+ * trigger the opt-in compact-and-retry backstop. Consults the app's
1330
+ * `classifyChatError` and the `contextOverflow.reactive` flag. Centralized
1331
+ * so both stream consumers (WebSocket + RPC) classify identically.
1332
+ */
1333
+ private _isRecoverableContextOverflow;
1334
+ /**
1335
+ * Compact the session in response to a context overflow (reactive backstop or
1336
+ * proactive guard). Returns whether history was actually shortened — a no-op
1337
+ * compaction (returns `null`) means a retry would just overflow again, so the
1338
+ * caller should fall through to the terminal error rather than loop.
1339
+ *
1340
+ * This is the single emit point for `chat:context:compacted`, so callers must
1341
+ * NOT emit it again.
1342
+ */
1343
+ private _compactForContextOverflow;
1344
+ /**
1345
+ * Finalize a context overflow that recovery could not fix (compaction was a
1346
+ * no-op, or the retry budget is spent). Routes the error through
1347
+ * `onChatError` with `classification: "context_overflow"` and emits
1348
+ * `chat:request:failed`, so every overflow terminal — whichever path it took
1349
+ * — is reported identically. Returns the (possibly app-reshaped) message for
1350
+ * the caller to deliver via its own transport (RPC callback / WS broadcast).
1351
+ */
1352
+ private _finalizeContextOverflowError;
1114
1353
  private _initializeExtensions;
1354
+ /**
1355
+ * Assemble provider-ready model messages from the current session history:
1356
+ * repair the transcript, truncate older messages, drop any still-incomplete
1357
+ * tool calls, and convert to `ModelMessage[]`. Shared by the turn entry point
1358
+ * and the proactive context guard so a mid-turn recompaction rebuilds the
1359
+ * head through the exact same pipeline.
1360
+ */
1361
+ private _assembleModelMessages;
1362
+ /**
1363
+ * Proactive context guard (Layer 1). Runs before each step from the
1364
+ * `prepareStep` wrapper. If `contextOverflow.proactive` is set and the *previous*
1365
+ * step's model-reported input tokens cross the budget, compact the session in
1366
+ * place and return recompacted messages for the upcoming step — heading off a
1367
+ * provider context-overflow 400 before it happens.
1368
+ *
1369
+ * Keys off `usage.inputTokens` (provider-agnostic; every provider reports it)
1370
+ * rather than any provider error string, and reuses `_assembleModelMessages`
1371
+ * so the recompacted head goes through the same repair/convert pipeline. The
1372
+ * current turn's in-flight steps (everything after `_turnModelMessageBaseline`)
1373
+ * are spliced back on so no completed work is lost.
1374
+ *
1375
+ * Best-effort: any failure (no-op compaction, reconciliation that would leave
1376
+ * an incomplete tool pair) returns `undefined` so the step proceeds unchanged
1377
+ * and the reactive backstop (`contextOverflow.reactive`) can still
1378
+ * catch a genuine overflow.
1379
+ */
1380
+ private _maybeProactiveContextCompact;
1115
1381
  /**
1116
1382
  * The single convergence point for all chat turn entry paths.
1117
1383
  * Merges tools, assembles context, fires lifecycle hooks, wraps tools
@@ -1265,6 +1531,22 @@ declare class Think<
1265
1531
  private _reconcileStaleAgentToolChildRun;
1266
1532
  /** Release a re-attached run's live tail + per-run streaming bookkeeping. */
1267
1533
  private _finalizeAgentToolChildRunTailers;
1534
+ /**
1535
+ * Eagerly terminalize this child facet's OWN agent-tool run row(s) once a
1536
+ * recovered turn has settled. A recovered turn re-runs via either
1537
+ * `_chatRecoveryContinue` → `continueLastTurn` or, for a pre-stream eviction,
1538
+ * `_chatRecoveryRetry` (a fresh user turn) — neither flows through
1539
+ * `startAgentToolRun`'s finalizer, so without this the run row strands
1540
+ * `running` and its tailers stay open until a parent inspect lazily
1541
+ * reconciles it — forcing a re-attached parent to wait out a full no-progress
1542
+ * window before collecting an already-finished result (#1630 follow-up).
1543
+ * Reconciling here closes the tail promptly so the parent collects the
1544
+ * terminal immediately. No-op on non-child facets (their
1545
+ * `cf_agent_tool_child_runs` table is empty) and on rows whose in-memory run
1546
+ * is still live (those are finalized by `startAgentToolRun`); the underlying
1547
+ * reconcile leaves a row `running` while its recovery is still in progress.
1548
+ */
1549
+ private _reconcileOwnStaleAgentToolChildRuns;
1268
1550
  getAgentToolChunks(
1269
1551
  runId: string,
1270
1552
  options?: {
@@ -1676,6 +1958,45 @@ declare class Think<
1676
1958
  * `@cloudflare/ai-chat`.
1677
1959
  */
1678
1960
  private _rescheduleRecoveryAfterStableTimeout;
1961
+ /**
1962
+ * Park a recovery continuation that timed out waiting for stable state
1963
+ * because the turn is holding a pending CLIENT interaction (an
1964
+ * `input-available` client-tool part or an `approval-requested` part — see
1965
+ * `hasPendingInteraction`). Such a turn is WAITING ON THE HUMAN, not stuck:
1966
+ * the SPA replays the interrupted tool-result / approval after reconnect,
1967
+ * which drives a fresh continuation via the auto-continuation barrier
1968
+ * independently of the recovery retry loop. Burning the attempt budget on
1969
+ * that wait (each `waitUntilStable` times out because the human hasn't
1970
+ * answered) would seal a perfectly healthy turn on `stable_timeout` — the
1971
+ * exact symptom behind HITL "session recovery errors" under deploy churn.
1972
+ *
1973
+ * So instead of rescheduling or exhausting, we stop the loop and mark the
1974
+ * incident `skipped` (reason `awaiting_client_interaction`). That retains the
1975
+ * incident record (a later genuine interruption re-evaluates it) while
1976
+ * resolving the live "recovering…" indicator via `_updateChatRecoveryIncident`
1977
+ * so the client sees the parked tool-call UI rather than an eternal spinner.
1978
+ * A client that never returns is reclaimed by the incident TTL sweep and DO
1979
+ * idle-eviction. SERVER-tool orphans are excluded by `hasPendingInteraction`
1980
+ * (their `execute` died with the isolate), so they still recover normally.
1981
+ *
1982
+ * For a SUBMISSION-backed turn (`recoveredRequestId` present) the recovery
1983
+ * loop is the submission row's SOLE completion driver after a restart, and the
1984
+ * client's replay resumes the conversation as an independent auto-continuation
1985
+ * that never touches the submission. Parking would therefore leave the row
1986
+ * `running` until `_recoverSubmissionsOnStart` swept it to `error` on the next
1987
+ * restart. We instead complete it `completed` here: the park condition is a
1988
+ * fully-materialized client tool call in the leaf, which is exactly the
1989
+ * terminal state a non-interrupted submission reaches when its step emits a
1990
+ * client tool call (the model does not block on client tools — see
1991
+ * `_runProgrammaticMessagesTurn`, which marks such a step `completed`). The
1992
+ * human round-trip then proceeds via the normal auto-continuation, identical
1993
+ * to the non-crash flow.
1994
+ *
1995
+ * Returns `true` when the recovery was parked (caller must return), `false`
1996
+ * when there is no pending client interaction (caller proceeds to the normal
1997
+ * reschedule / exhaustion path).
1998
+ */
1999
+ private _parkRecoveryForPendingInteraction;
1679
2000
  /**
1680
2001
  * Resolve the stream id for a recovery turn so the give-up terminalization
1681
2002
  * can surface whatever partial the turn produced. Prefers the durable stream
@@ -1782,6 +2103,33 @@ declare class Think<
1782
2103
  private _completeSkippedRequest;
1783
2104
  private _rollbackDroppedSubmit;
1784
2105
  private _scheduleAutoContinuation;
2106
+ /**
2107
+ * Re-arm the barrier for a tool result/approval that arrived WITHOUT
2108
+ * `autoContinue` (#1650). The client sends `autoContinue: false` for an
2109
+ * errored tool result (it declines to auto-continue a standalone error), but
2110
+ * in a parallel batch a SIBLING may already have requested continuation — and
2111
+ * this result can be the one that completes the batch. In that case we must
2112
+ * re-run the barrier check so the continuation the sibling requested still
2113
+ * fires once the batch is whole.
2114
+ *
2115
+ * Unlike `_scheduleAutoContinuation` this never CREATES a pending
2116
+ * continuation: a standalone errored tool (no opted-in sibling, so no pending)
2117
+ * must not auto-continue. It also no-ops once the continuation is running
2118
+ * (`pastCoalesce`) — a late result then defers/applies through the normal
2119
+ * path rather than re-arming.
2120
+ */
2121
+ private _rearmPendingAutoContinuationForBatch;
2122
+ /**
2123
+ * Called when a streaming assistant turn finalizes (its message, with ALL
2124
+ * tool parts, is now persisted). Clears the in-flight accumulator and re-runs
2125
+ * the auto-continuation barrier for a continuation the stream-active gate held
2126
+ * (#1650). This is essential for an all-fast parallel batch whose every result
2127
+ * landed mid-stream: once the stream ends there is no further tool-result
2128
+ * event to re-arm the barrier, so without this re-check the held continuation
2129
+ * would never fire. A slow batch is also re-checked here and simply continues
2130
+ * to hold (event-driven) until its remaining siblings answer.
2131
+ */
2132
+ private _onStreamingTurnFinalized;
1785
2133
  private _resetAutoContinuationTimer;
1786
2134
  /**
1787
2135
  * Fire an auto-continuation, but only once the model's parallel tool-call
@@ -1790,20 +2138,37 @@ declare class Think<
1790
2138
  * arrives while slower siblings are still `input-available`. Continuing then
1791
2139
  * would feed the provider an incomplete tool-result set
1792
2140
  * (`MissingToolResultsError`) or, via the transcript-repair backstop, silently
1793
- * error the in-flight sibling and run a spurious extra continuation. We hold
1794
- * the continuation on a barrier until the batch settles. The wait is bounded
1795
- * (`AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS`) so a genuinely orphaned tool
1796
- * call — e.g. the client disconnected mid-batch — still falls through to the
1797
- * repair backstop rather than pinning the continuation open forever.
2141
+ * error the in-flight sibling and run a spurious extra continuation.
2142
+ *
2143
+ * The barrier is event-driven (#1650). Auto-continuation is only ever
2144
+ * triggered by a tool-result/approval event, so rather than wait on a fixed
2145
+ * timer we drain the in-flight applies, re-check, and — if the batch is still
2146
+ * incomplete — return WITHOUT firing and WITHOUT holding the isolate, leaving
2147
+ * `_continuation.pending` in place. The next sibling's result re-arms the
2148
+ * coalesce timer (`_scheduleAutoContinuation`) and re-runs this check; the
2149
+ * continuation fires once the final sibling lands. If the in-memory pending
2150
+ * state is lost to eviction between siblings, the final result re-creates it
2151
+ * from the persisted transcript and fires with a complete batch — self-healing.
2152
+ * A true orphan (a sibling that never arrives) simply never auto-continues,
2153
+ * which is correct: there is nothing valid to continue, and a later user turn
2154
+ * / chat recovery repairs the transcript.
2155
+ *
2156
+ * The barrier also holds while the assistant turn is still streaming (the
2157
+ * stream-active gate below): mid-stream the batch can still grow with tool
2158
+ * calls the model hasn't emitted yet, so no completeness check is meaningful.
2159
+ * `_onStreamingTurnFinalized` re-runs the check once the stream ends.
1798
2160
  */
1799
2161
  private _fireAutoContinuationWhenStable;
1800
2162
  /**
1801
- * Block until the latest assistant step's parallel tool batch is fully
1802
- * answered, or `AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS` elapses. Awaits the
1803
- * in-flight tool-result apply when one exists (so a sibling that lands
1804
- * mid-wait is observed promptly) and polls otherwise.
2163
+ * Drain every in-flight tool-result/approval apply, including any enqueued
2164
+ * while we wait, so the subsequent `_hasIncompleteToolBatch()` re-check sees
2165
+ * every result that has ALREADY arrived. Bounded by real apply activity (a
2166
+ * storage write each), never by a fixed timer: a batch with no further
2167
+ * results drains in the time its pending applies take and then returns. The
2168
+ * loop re-reads `_interactionApplyTail` after each await because a sibling can
2169
+ * extend the tail mid-drain; we stop once the tail stops advancing.
1805
2170
  */
1806
- private _awaitToolBatch;
2171
+ private _drainInteractionApplies;
1807
2172
  /**
1808
2173
  * `true` when the latest assistant message is mid-batch: it carries at least
1809
2174
  * one settled tool result AND at least one tool call/approval still awaiting a
@@ -2198,112 +2563,116 @@ declare function toMessengerAttachment(
2198
2563
  //#endregion
2199
2564
  export {
2200
2565
  toMessengerUserMessage as $,
2201
- defineScheduledTasks as $t,
2566
+ TypedToolCall$1 as $t,
2202
2567
  MessengerDeliverySurface as A,
2203
- StreamableResult as At,
2568
+ StepResult as At,
2204
2569
  parseMessengerReplySnapshot as B,
2205
- ThinkSubmissionInspection as Bt,
2570
+ ThinkScheduledTaskContext as Bt,
2206
2571
  toMessengerThread as C,
2207
- SkillRunContext as Ct,
2572
+ SaveMessagesOptions$1 as Ct,
2208
2573
  INTERRUPTED_MESSENGER_RESPONSE as D,
2209
- StepResult as Dt,
2574
+ SkillSource$1 as Dt,
2210
2575
  ERROR_MESSENGER_RESPONSE as E,
2211
- StepContext as Et,
2576
+ SkillRunContext as Et,
2212
2577
  TextStreamCallbackOptions as F,
2213
- ThinkIntervalSchedule as Ft,
2578
+ SubmitMessagesResult as Ft,
2214
2579
  MessengerCapabilities as G,
2215
- ToolCallDecision as Gt,
2580
+ ThinkTime as Gt,
2216
2581
  MessengerAction as H,
2217
- ThinkTime as Ht,
2582
+ ThinkScheduledTasks as Ht,
2218
2583
  deliverMessengerReply as I,
2219
- ThinkScheduledTask as It,
2584
+ TextStreamPart as It,
2220
2585
  MessengerEventKind as J,
2221
- TurnContext as Jt,
2586
+ ToolCallDecision as Jt,
2222
2587
  MessengerContext as K,
2223
- ToolCallResultContext as Kt,
2588
+ ThinkWallClockSchedule as Kt,
2224
2589
  messengerReplyFailureMode as L,
2225
- ThinkScheduledTaskContext as Lt,
2590
+ Think as Lt,
2226
2591
  MessengerReplySnapshot as M,
2227
- SubmitMessagesResult as Mt,
2592
+ StreamCallback as Mt,
2228
2593
  MessengerReplyStage as N,
2229
- TextStreamPart as Nt,
2594
+ StreamableResult as Nt,
2230
2595
  MESSENGER_REPLY_FIBER_NAME as O,
2231
- StopCondition$1 as Ot,
2596
+ StepConfig as Ot,
2232
2597
  TextStreamCallback as P,
2233
- Think as Pt,
2598
+ SubmitMessagesOptions as Pt,
2234
2599
  serializableMessengerEvent as Q,
2235
- Workspace$1 as Qt,
2600
+ TurnInput as Qt,
2236
2601
  messengerReplyRecoveryMode as R,
2237
- ThinkScheduledTaskSchedule as Rt,
2602
+ ThinkIntervalSchedule as Rt,
2238
2603
  toMessengerMessage as S,
2239
- Session$1 as St,
2604
+ ResolvedChatRecoveryConfig as St,
2240
2605
  EMPTY_MESSENGER_RESPONSE as T,
2241
- StepConfig as Tt,
2606
+ Session$1 as Tt,
2242
2607
  MessengerAttachment as U,
2243
- ThinkWallClockSchedule as Ut,
2608
+ ThinkSubmissionInspection as Ut,
2244
2609
  textDeltaFromStreamChunk as V,
2245
- ThinkSubmissionStatus as Vt,
2610
+ ThinkScheduledTaskSchedule as Vt,
2246
2611
  MessengerAuthor as W,
2247
- ToolCallContext as Wt,
2612
+ ThinkSubmissionStatus as Wt,
2248
2613
  MessengerThread as X,
2249
- TypedToolCall$1 as Xt,
2614
+ TurnConfig as Xt,
2250
2615
  MessengerMessage as Y,
2251
- TurnInput as Yt,
2616
+ ToolCallResultContext as Yt,
2252
2617
  messengerContextFromEvent as Z,
2253
- TypedToolResult as Zt,
2618
+ TurnContext as Zt,
2254
2619
  defineMessengers as _,
2255
- PrepareStepFunction$1 as _t,
2620
+ ListSubmissionsOptions as _t,
2256
2621
  MessengerConversationTarget as a,
2257
- ChatRecoveryOptions$1 as at,
2622
+ ChatRecoveryExhaustedContext as at,
2258
2623
  toMessengerAttachment as b,
2259
- SaveMessagesOptions$1 as bt,
2624
+ PrepareStepFunction$1 as bt,
2260
2625
  MessengerThinkHost as c,
2261
- ChunkContext as ct,
2626
+ ChatResponseResult$1 as ct,
2262
2627
  ThinkMessengerRuntime as d,
2263
- ExtensionConfig as dt,
2264
- skills as en,
2265
- ChatErrorContext as et,
2628
+ ChunkPart as dt,
2629
+ TypedToolResult as en,
2630
+ ChatErrorClassification as et,
2266
2631
  ThinkMessengerStateAgent as f,
2267
- FiberContext$1 as ft,
2632
+ ContextOverflowConfig as ft,
2268
2633
  defaultConversationName as g,
2269
- PrepareStepContext as gt,
2634
+ FiberRecoveryContext$1 as gt,
2270
2635
  defaultChatSdkEvent as h,
2271
- MessageConcurrency$1 as ht,
2636
+ FiberContext$1 as ht,
2272
2637
  MessengerConversationResolver as i,
2273
- ChatRecoveryExhaustedContext as it,
2638
+ skills as in,
2639
+ ChatRecoveryContext$1 as it,
2274
2640
  MessengerDeliveryTarget as j,
2275
- SubmitMessagesOptions as jt,
2641
+ StopCondition$1 as jt,
2276
2642
  MessengerDeliveryPolicy as k,
2277
- StreamCallback as kt,
2643
+ StepContext as kt,
2278
2644
  MessengerThinkTarget as l,
2279
- ChunkPart as lt,
2645
+ ChatStartEvent as lt,
2280
2646
  chatSdkMessenger as m,
2281
- ListSubmissionsOptions as mt,
2647
+ ExtensionConfig as mt,
2282
2648
  ChatSdkMessengerOptions as n,
2283
- ChatRecoveryConfig$1 as nt,
2649
+ defaultContextOverflowClassifier as nn,
2650
+ ChatOptions as nt,
2284
2651
  MessengerDefinition as o,
2285
- ChatResponseResult$1 as ot,
2652
+ ChatRecoveryOptions$1 as ot,
2286
2653
  ThinkMessengers as p,
2287
- FiberRecoveryContext$1 as pt,
2654
+ DeleteSubmissionsOptions as pt,
2288
2655
  MessengerEvent as q,
2289
- TurnConfig as qt,
2656
+ ToolCallContext as qt,
2290
2657
  MessengerConversationMode as r,
2291
- ChatRecoveryContext$1 as rt,
2658
+ defineScheduledTasks as rn,
2659
+ ChatRecoveryConfig$1 as rt,
2292
2660
  MessengerRespondTo as s,
2293
- ChatStartEvent as st,
2661
+ ChatRecoveryProgressContext as st,
2294
2662
  ChatSdkMessengerEventInput as t,
2295
- ChatOptions as tt,
2663
+ Workspace$1 as tn,
2664
+ ChatErrorContext as tt,
2296
2665
  NormalizedMessengerDefinition as u,
2297
- DeleteSubmissionsOptions as ut,
2666
+ ChunkContext as ut,
2298
2667
  idempotencyKeyForEvent as v,
2299
- PrepareStepResult$1 as vt,
2668
+ MessageConcurrency$1 as vt,
2300
2669
  DeliverMessengerReplyOptions as w,
2301
- SkillSource$1 as wt,
2670
+ SaveMessagesResult$1 as wt,
2302
2671
  toMessengerAuthor as x,
2303
- SaveMessagesResult$1 as xt,
2672
+ PrepareStepResult$1 as xt,
2304
2673
  normalizeMessengers as y,
2305
- ResolvedChatRecoveryConfig as yt,
2674
+ PrepareStepContext as yt,
2306
2675
  messengerReplySnapshot as z,
2307
- ThinkScheduledTasks as zt
2676
+ ThinkScheduledTask as zt
2308
2677
  };
2309
- //# sourceMappingURL=index-DpPdyY46.d.ts.map
2678
+ //# sourceMappingURL=index-By2rkaOh.d.ts.map