@cloudflare/think 0.8.1 → 0.8.2

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.
@@ -1782,6 +1782,33 @@ declare class Think<
1782
1782
  private _completeSkippedRequest;
1783
1783
  private _rollbackDroppedSubmit;
1784
1784
  private _scheduleAutoContinuation;
1785
+ /**
1786
+ * Re-arm the barrier for a tool result/approval that arrived WITHOUT
1787
+ * `autoContinue` (#1650). The client sends `autoContinue: false` for an
1788
+ * errored tool result (it declines to auto-continue a standalone error), but
1789
+ * in a parallel batch a SIBLING may already have requested continuation — and
1790
+ * this result can be the one that completes the batch. In that case we must
1791
+ * re-run the barrier check so the continuation the sibling requested still
1792
+ * fires once the batch is whole.
1793
+ *
1794
+ * Unlike `_scheduleAutoContinuation` this never CREATES a pending
1795
+ * continuation: a standalone errored tool (no opted-in sibling, so no pending)
1796
+ * must not auto-continue. It also no-ops once the continuation is running
1797
+ * (`pastCoalesce`) — a late result then defers/applies through the normal
1798
+ * path rather than re-arming.
1799
+ */
1800
+ private _rearmPendingAutoContinuationForBatch;
1801
+ /**
1802
+ * Called when a streaming assistant turn finalizes (its message, with ALL
1803
+ * tool parts, is now persisted). Clears the in-flight accumulator and re-runs
1804
+ * the auto-continuation barrier for a continuation the stream-active gate held
1805
+ * (#1650). This is essential for an all-fast parallel batch whose every result
1806
+ * landed mid-stream: once the stream ends there is no further tool-result
1807
+ * event to re-arm the barrier, so without this re-check the held continuation
1808
+ * would never fire. A slow batch is also re-checked here and simply continues
1809
+ * to hold (event-driven) until its remaining siblings answer.
1810
+ */
1811
+ private _onStreamingTurnFinalized;
1785
1812
  private _resetAutoContinuationTimer;
1786
1813
  /**
1787
1814
  * Fire an auto-continuation, but only once the model's parallel tool-call
@@ -1790,20 +1817,37 @@ declare class Think<
1790
1817
  * arrives while slower siblings are still `input-available`. Continuing then
1791
1818
  * would feed the provider an incomplete tool-result set
1792
1819
  * (`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.
1820
+ * error the in-flight sibling and run a spurious extra continuation.
1821
+ *
1822
+ * The barrier is event-driven (#1650). Auto-continuation is only ever
1823
+ * triggered by a tool-result/approval event, so rather than wait on a fixed
1824
+ * timer we drain the in-flight applies, re-check, and — if the batch is still
1825
+ * incomplete — return WITHOUT firing and WITHOUT holding the isolate, leaving
1826
+ * `_continuation.pending` in place. The next sibling's result re-arms the
1827
+ * coalesce timer (`_scheduleAutoContinuation`) and re-runs this check; the
1828
+ * continuation fires once the final sibling lands. If the in-memory pending
1829
+ * state is lost to eviction between siblings, the final result re-creates it
1830
+ * from the persisted transcript and fires with a complete batch — self-healing.
1831
+ * A true orphan (a sibling that never arrives) simply never auto-continues,
1832
+ * which is correct: there is nothing valid to continue, and a later user turn
1833
+ * / chat recovery repairs the transcript.
1834
+ *
1835
+ * The barrier also holds while the assistant turn is still streaming (the
1836
+ * stream-active gate below): mid-stream the batch can still grow with tool
1837
+ * calls the model hasn't emitted yet, so no completeness check is meaningful.
1838
+ * `_onStreamingTurnFinalized` re-runs the check once the stream ends.
1798
1839
  */
1799
1840
  private _fireAutoContinuationWhenStable;
1800
1841
  /**
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.
1842
+ * Drain every in-flight tool-result/approval apply, including any enqueued
1843
+ * while we wait, so the subsequent `_hasIncompleteToolBatch()` re-check sees
1844
+ * every result that has ALREADY arrived. Bounded by real apply activity (a
1845
+ * storage write each), never by a fixed timer: a batch with no further
1846
+ * results drains in the time its pending applies take and then returns. The
1847
+ * loop re-reads `_interactionApplyTail` after each await because a sibling can
1848
+ * extend the tail mid-drain; we stop once the tail stops advancing.
1805
1849
  */
1806
- private _awaitToolBatch;
1850
+ private _drainInteractionApplies;
1807
1851
  /**
1808
1852
  * `true` when the latest assistant message is mid-batch: it carries at least
1809
1853
  * one settled tool result AND at least one tool call/approval still awaiting a
@@ -2306,4 +2350,4 @@ export {
2306
2350
  messengerReplySnapshot as z,
2307
2351
  ThinkScheduledTasks as zt
2308
2352
  };
2309
- //# sourceMappingURL=index-DpPdyY46.d.ts.map
2353
+ //# sourceMappingURL=index-CKAMYQXB.d.ts.map
@@ -52,7 +52,7 @@ import {
52
52
  x as toMessengerAuthor,
53
53
  y as normalizeMessengers,
54
54
  z as messengerReplySnapshot
55
- } from "../index-DpPdyY46.js";
55
+ } from "../index-CKAMYQXB.js";
56
56
  export {
57
57
  type ChatSdkMessengerEventInput,
58
58
  type ChatSdkMessengerOptions,
@@ -2,7 +2,7 @@ import {
2
2
  P as TextStreamCallback,
3
3
  n as ChatSdkMessengerOptions,
4
4
  o as MessengerDefinition
5
- } from "../index-DpPdyY46.js";
5
+ } from "../index-CKAMYQXB.js";
6
6
  import { TelegramAdapterConfig } from "@chat-adapter/telegram";
7
7
 
8
8
  //#region src/messengers/telegram.d.ts
package/dist/think.d.ts CHANGED
@@ -55,7 +55,7 @@ import {
55
55
  xt as SaveMessagesResult,
56
56
  yt as ResolvedChatRecoveryConfig,
57
57
  zt as ThinkScheduledTasks
58
- } from "./index-DpPdyY46.js";
58
+ } from "./index-CKAMYQXB.js";
59
59
  export {
60
60
  ChatErrorContext,
61
61
  ChatOptions,
package/dist/think.js CHANGED
@@ -292,7 +292,6 @@ const CHAT_RECOVERY_INCIDENT_KEY_PREFIX = "cf:chat-recovery:incident:";
292
292
  const CHAT_RECOVERY_PROGRESS_KEY = "cf:chat-recovery:progress";
293
293
  const DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS = 10;
294
294
  const DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS = 1e4;
295
- const AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS = 6e4;
296
295
  const CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS = 3;
297
296
  const DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE = "The assistant was interrupted and could not recover. Please try again.";
298
297
  const CHAT_RECOVERY_INCIDENT_TTL_MS = 3600 * 1e3;
@@ -3219,10 +3218,12 @@ var Think = class Think extends Agent {
3219
3218
  }
3220
3219
  this._enqueueInteractionApply(() => this._applyToolResult(event.toolCallId, event.output, event.state, event.errorText));
3221
3220
  if (event.autoContinue) this._scheduleAutoContinuation(connection);
3221
+ else this._rearmPendingAutoContinuationForBatch();
3222
3222
  break;
3223
3223
  case "tool-approval":
3224
3224
  this._enqueueInteractionApply(() => this._applyToolApproval(event.toolCallId, event.approved));
3225
3225
  if (event.autoContinue) this._scheduleAutoContinuation(connection);
3226
+ else this._rearmPendingAutoContinuationForBatch();
3226
3227
  break;
3227
3228
  case "clear":
3228
3229
  await this._handleClear(connection);
@@ -3499,6 +3500,7 @@ var Think = class Think extends Agent {
3499
3500
  let doneSent = false;
3500
3501
  let streamError;
3501
3502
  let pendingRpcError;
3503
+ let skipFinalizeRearm = false;
3502
3504
  const stallTimeoutMs = this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
3503
3505
  try {
3504
3506
  this._insideInferenceLoop = true;
@@ -3617,6 +3619,7 @@ var Think = class Think extends Agent {
3617
3619
  });
3618
3620
  doneSent = true;
3619
3621
  }
3622
+ skipFinalizeRearm = true;
3620
3623
  await callback.onInterrupted?.();
3621
3624
  return;
3622
3625
  }
@@ -3626,6 +3629,7 @@ var Think = class Think extends Agent {
3626
3629
  streamFinalized = true;
3627
3630
  }
3628
3631
  doneSent = true;
3632
+ skipFinalizeRearm = true;
3629
3633
  await callback.onInterrupted?.();
3630
3634
  return;
3631
3635
  }
@@ -3671,7 +3675,8 @@ var Think = class Think extends Agent {
3671
3675
  });
3672
3676
  await callback.onError(errorMessage);
3673
3677
  } finally {
3674
- this._streamingAssistant = null;
3678
+ if (skipFinalizeRearm) this._streamingAssistant = null;
3679
+ else this._onStreamingTurnFinalized();
3675
3680
  }
3676
3681
  if (pendingRpcError) await callback.onError(pendingRpcError);
3677
3682
  }
@@ -3924,7 +3929,7 @@ var Think = class Think extends Agent {
3924
3929
  } catch (e) {
3925
3930
  console.error("Failed to persist assistant message:", e);
3926
3931
  }
3927
- this._streamingAssistant = null;
3932
+ this._onStreamingTurnFinalized();
3928
3933
  return streamError ? {
3929
3934
  status: "error",
3930
3935
  error: streamError
@@ -4907,6 +4912,40 @@ var Think = class Think extends Agent {
4907
4912
  this._continuation.awaitingConnections.set(connection.id, connection);
4908
4913
  this._resetAutoContinuationTimer();
4909
4914
  }
4915
+ /**
4916
+ * Re-arm the barrier for a tool result/approval that arrived WITHOUT
4917
+ * `autoContinue` (#1650). The client sends `autoContinue: false` for an
4918
+ * errored tool result (it declines to auto-continue a standalone error), but
4919
+ * in a parallel batch a SIBLING may already have requested continuation — and
4920
+ * this result can be the one that completes the batch. In that case we must
4921
+ * re-run the barrier check so the continuation the sibling requested still
4922
+ * fires once the batch is whole.
4923
+ *
4924
+ * Unlike `_scheduleAutoContinuation` this never CREATES a pending
4925
+ * continuation: a standalone errored tool (no opted-in sibling, so no pending)
4926
+ * must not auto-continue. It also no-ops once the continuation is running
4927
+ * (`pastCoalesce`) — a late result then defers/applies through the normal
4928
+ * path rather than re-arming.
4929
+ */
4930
+ _rearmPendingAutoContinuationForBatch() {
4931
+ const pending = this._continuation.pending;
4932
+ if (!pending || pending.pastCoalesce) return;
4933
+ this._resetAutoContinuationTimer();
4934
+ }
4935
+ /**
4936
+ * Called when a streaming assistant turn finalizes (its message, with ALL
4937
+ * tool parts, is now persisted). Clears the in-flight accumulator and re-runs
4938
+ * the auto-continuation barrier for a continuation the stream-active gate held
4939
+ * (#1650). This is essential for an all-fast parallel batch whose every result
4940
+ * landed mid-stream: once the stream ends there is no further tool-result
4941
+ * event to re-arm the barrier, so without this re-check the held continuation
4942
+ * would never fire. A slow batch is also re-checked here and simply continues
4943
+ * to hold (event-driven) until its remaining siblings answer.
4944
+ */
4945
+ _onStreamingTurnFinalized() {
4946
+ this._streamingAssistant = null;
4947
+ this._rearmPendingAutoContinuationForBatch();
4948
+ }
4910
4949
  _resetAutoContinuationTimer() {
4911
4950
  if (this._continuationTimer) clearTimeout(this._continuationTimer);
4912
4951
  this._continuationTimer = setTimeout(() => {
@@ -4923,48 +4962,64 @@ var Think = class Think extends Agent {
4923
4962
  * arrives while slower siblings are still `input-available`. Continuing then
4924
4963
  * would feed the provider an incomplete tool-result set
4925
4964
  * (`MissingToolResultsError`) or, via the transcript-repair backstop, silently
4926
- * error the in-flight sibling and run a spurious extra continuation. We hold
4927
- * the continuation on a barrier until the batch settles. The wait is bounded
4928
- * (`AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS`) so a genuinely orphaned tool
4929
- * call — e.g. the client disconnected mid-batch — still falls through to the
4930
- * repair backstop rather than pinning the continuation open forever.
4965
+ * error the in-flight sibling and run a spurious extra continuation.
4966
+ *
4967
+ * The barrier is event-driven (#1650). Auto-continuation is only ever
4968
+ * triggered by a tool-result/approval event, so rather than wait on a fixed
4969
+ * timer we drain the in-flight applies, re-check, and — if the batch is still
4970
+ * incomplete — return WITHOUT firing and WITHOUT holding the isolate, leaving
4971
+ * `_continuation.pending` in place. The next sibling's result re-arms the
4972
+ * coalesce timer (`_scheduleAutoContinuation`) and re-runs this check; the
4973
+ * continuation fires once the final sibling lands. If the in-memory pending
4974
+ * state is lost to eviction between siblings, the final result re-creates it
4975
+ * from the persisted transcript and fires with a complete batch — self-healing.
4976
+ * A true orphan (a sibling that never arrives) simply never auto-continues,
4977
+ * which is correct: there is nothing valid to continue, and a later user turn
4978
+ * / chat recovery repairs the transcript.
4979
+ *
4980
+ * The barrier also holds while the assistant turn is still streaming (the
4981
+ * stream-active gate below): mid-stream the batch can still grow with tool
4982
+ * calls the model hasn't emitted yet, so no completeness check is meaningful.
4983
+ * `_onStreamingTurnFinalized` re-runs the check once the stream ends.
4931
4984
  */
4932
4985
  _fireAutoContinuationWhenStable(connection) {
4933
4986
  if (!this._continuation.pending) return;
4934
4987
  if (this._continuation.pending.pastCoalesce) return;
4935
4988
  if (this._continuationBarrierActive) return;
4989
+ if (this._streamingAssistant) return;
4936
4990
  if (!this._pendingInteractionPromise && !this._hasIncompleteToolBatch()) {
4937
4991
  this._fireAutoContinuation(connection);
4938
4992
  return;
4939
4993
  }
4940
4994
  this._continuationBarrierActive = true;
4941
- this.keepAliveWhile(() => this._awaitToolBatch()).catch(() => {}).finally(() => {
4995
+ this.keepAliveWhile(() => this._drainInteractionApplies()).catch(() => {}).finally(() => {
4942
4996
  this._continuationBarrierActive = false;
4943
4997
  const pending = this._continuation.pending;
4944
- if (pending) this._fireAutoContinuation(pending.connection);
4998
+ if (!pending || pending.pastCoalesce) return;
4999
+ if (this._streamingAssistant) return;
5000
+ if (this._hasIncompleteToolBatch()) return;
5001
+ this._fireAutoContinuation(pending.connection);
4945
5002
  });
4946
5003
  }
4947
5004
  /**
4948
- * Block until the latest assistant step's parallel tool batch is fully
4949
- * answered, or `AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS` elapses. Awaits the
4950
- * in-flight tool-result apply when one exists (so a sibling that lands
4951
- * mid-wait is observed promptly) and polls otherwise.
5005
+ * Drain every in-flight tool-result/approval apply, including any enqueued
5006
+ * while we wait, so the subsequent `_hasIncompleteToolBatch()` re-check sees
5007
+ * every result that has ALREADY arrived. Bounded by real apply activity (a
5008
+ * storage write each), never by a fixed timer: a batch with no further
5009
+ * results drains in the time its pending applies take and then returns. The
5010
+ * loop re-reads `_interactionApplyTail` after each await because a sibling can
5011
+ * extend the tail mid-drain; we stop once the tail stops advancing.
4952
5012
  */
4953
- async _awaitToolBatch() {
4954
- const deadline = Date.now() + AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS;
4955
- while (Date.now() < deadline) {
5013
+ async _drainInteractionApplies() {
5014
+ let tail = this._interactionApplyTail;
5015
+ for (;;) {
4956
5016
  if (!this._continuation.pending) return;
4957
- const pending = this._pendingInteractionPromise;
4958
- if (pending) {
4959
- try {
4960
- await pending;
4961
- } catch {}
4962
- continue;
4963
- }
4964
- if (!this._hasIncompleteToolBatch()) return;
4965
- await new Promise((resolve) => setTimeout(resolve, 100));
5017
+ try {
5018
+ await tail;
5019
+ } catch {}
5020
+ if (this._interactionApplyTail === tail) return;
5021
+ tail = this._interactionApplyTail;
4966
5022
  }
4967
- console.warn(`[Think] Auto-continuation proceeding after waiting ${AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS}ms for unanswered parallel tool result(s) (#1649).`);
4968
5023
  }
4969
5024
  /**
4970
5025
  * `true` when the latest assistant message is mid-batch: it carries at least