@cloudflare/think 0.8.0 → 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.
package/dist/think.js CHANGED
@@ -1,11 +1,11 @@
1
- import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-BP1jgEfY.js";
1
+ import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-D_obpP6O.js";
2
2
  import { createWorkspaceTools } from "./tools/workspace.js";
3
- import { t as ThinkMessengerRuntime } from "./chat-sdk-CJwYlbp9.js";
3
+ import { t as ThinkMessengerRuntime } from "./chat-sdk-Bb93yaZh.js";
4
4
  import { Output, convertToModelMessages, jsonSchema, stepCountIs, streamText } from "ai";
5
5
  import * as skills from "agents/skills";
6
6
  import { SkillRegistry } from "agents/skills";
7
7
  import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
8
- import { AbortRegistry, CHAT_MESSAGE_TYPES, ContinuationState, ResumableStream, StreamAccumulator, SubmitConcurrencyController, TurnQueue, applyChunkToParts, applyToolUpdate, createChatFiberSnapshot, createToolsFromClientSchemas, crossMessageToolResultUpdate, enforceRowSizeLimit, parseProtocolMessage, reconcileMessages, resolveToolMergeId, sanitizeMessage, toolApprovalUpdate, toolResultUpdate, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
8
+ import { AbortRegistry, CHAT_MESSAGE_TYPES, ContinuationState, ResumableStream, StreamAccumulator, SubmitConcurrencyController, TurnQueue, applyChunkToParts, applyToolUpdate, createChatFiberSnapshot, createToolsFromClientSchemas, crossMessageToolResultUpdate, enforceRowSizeLimit, normalizeToolInput, parseProtocolMessage, reconcileMessages, resolveToolMergeId, sanitizeMessage, toolApprovalUpdate, toolResultUpdate, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
9
9
  import { Session, Session as Session$1 } from "agents/experimental/memory/session";
10
10
  import { truncateOlderMessages } from "agents/experimental/memory/utils";
11
11
  import { Workspace, Workspace as Workspace$1 } from "@cloudflare/shell";
@@ -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;
@@ -353,6 +352,8 @@ var Think = class Think extends Agent {
353
352
  this._insideResponseHook = false;
354
353
  this._insideInferenceLoop = false;
355
354
  this._pendingInteractionPromise = null;
355
+ this._interactionApplyTail = Promise.resolve();
356
+ this._streamingAssistant = null;
356
357
  this._submitConcurrency = new SubmitConcurrencyController({ defaultDebounceMs: Think.MESSAGE_DEBOUNCE_MS });
357
358
  this._agentToolForwarders = /* @__PURE__ */ new Map();
358
359
  this._agentToolClosers = /* @__PURE__ */ new Map();
@@ -412,8 +413,8 @@ var Think = class Think extends Agent {
412
413
  await this._reconcileDeclaredScheduledTasks();
413
414
  await this._recoverSubmissionsOnStart();
414
415
  this._recoverWorkflowNotifications();
415
- this._startSubmissionDrain();
416
- this._startWorkflowNotificationDrain();
416
+ if (this._hasPendingSubmissions()) this._startSubmissionDrain();
417
+ if (this._hasPendingWorkflowNotifications()) this._startWorkflowNotificationDrain();
417
418
  };
418
419
  }
419
420
  /**
@@ -434,37 +435,17 @@ var Think = class Think extends Agent {
434
435
  /**
435
436
  * Normalize a tool part's `input` into something the provider will accept.
436
437
  *
437
- * Two malformed shapes 400 modern providers (and persist forever once
438
- * written): a stringified-JSON `input` (e.g. `'{"prompt":"a cat"}'` instead
439
- * of the object) and a missing/`null` `input` on a settled or interrupted
440
- * tool call (Anthropic rejects a `tool_use` block whose `input` is absent).
441
- * We parse the former and default the latter to an empty object so the
442
- * tool-call/tool-result pair stays valid. Any other value is left untouched.
438
+ * Malformed shapes 400 modern providers and persist forever once written:
439
+ * a stringified-JSON `input` (e.g. `'{"prompt":"a cat"}'` instead of the
440
+ * object), and any non-object `input` — `null`, `undefined`, `""`, an array,
441
+ * or a primitive — on a settled or interrupted tool call (Anthropic rejects
442
+ * a `tool_use` block whose `input` is not an object). We parse the former and
443
+ * default the latter to an empty object so the tool-call/tool-result pair
444
+ * stays valid. Delegates to the shared `normalizeToolInput` so the read-side
445
+ * repair and the write-side accumulator guard enforce the same invariant.
443
446
  */
444
447
  _normalizeToolInput(record) {
445
- const raw = "input" in record ? record.input : void 0;
446
- if (typeof raw === "string") {
447
- const trimmed = raw.trim();
448
- if (trimmed.startsWith("{") || trimmed.startsWith("[")) try {
449
- return {
450
- input: JSON.parse(raw),
451
- changed: true
452
- };
453
- } catch {
454
- return {
455
- input: raw,
456
- changed: false
457
- };
458
- }
459
- }
460
- if (raw === void 0 || raw === null) return {
461
- input: {},
462
- changed: true
463
- };
464
- return {
465
- input: raw,
466
- changed: false
467
- };
448
+ return normalizeToolInput("input" in record ? record.input : void 0);
468
449
  }
469
450
  /**
470
451
  * Whether a tool part already has a settled result the provider accepts, so
@@ -1130,8 +1111,8 @@ var Think = class Think extends Agent {
1130
1111
  return error;
1131
1112
  }
1132
1113
  async _initializeExtensions() {
1133
- const { ExtensionManager } = await import("./manager-px912SoZ.js").then((n) => n.n);
1134
- const { sanitizeName } = await import("./manager-px912SoZ.js").then((n) => n.n);
1114
+ const { ExtensionManager } = await import("./manager-DnCkoyVo.js").then((n) => n.n);
1115
+ const { sanitizeName } = await import("./manager-DnCkoyVo.js").then((n) => n.n);
1135
1116
  const agentClassName = this.constructor.name;
1136
1117
  const agentId = this.ctx.id.toString();
1137
1118
  const ctxExports = this.ctx.exports;
@@ -1317,7 +1298,7 @@ var Think = class Think extends Agent {
1317
1298
  if (!this.extensionManager) return subclassConfig;
1318
1299
  const subscribers = this.extensionManager.getHookSubscribers("beforeTurn");
1319
1300
  if (subscribers.length === 0) return subclassConfig;
1320
- const { createTurnContextSnapshot, parseHookResult } = await import("./hook-proxy-DHwqL8MV.js");
1301
+ const { createTurnContextSnapshot, parseHookResult } = await import("./hook-proxy-CkF0EhRO.js");
1321
1302
  let snapshot = createTurnContextSnapshot(ctx);
1322
1303
  let accumulated = { ...subclassConfig };
1323
1304
  if (accumulated.system !== void 0) snapshot.system = accumulated.system;
@@ -1488,25 +1469,25 @@ var Think = class Think extends Agent {
1488
1469
  async _pipelineExtensionToolCallStart(event) {
1489
1470
  if (!this.extensionManager) return;
1490
1471
  if (this.extensionManager.getHookSubscribers("beforeToolCall").length === 0) return;
1491
- const { createToolCallStartSnapshot } = await import("./hook-proxy-DHwqL8MV.js");
1472
+ const { createToolCallStartSnapshot } = await import("./hook-proxy-CkF0EhRO.js");
1492
1473
  await this._dispatchExtensionObservation("beforeToolCall", createToolCallStartSnapshot(event));
1493
1474
  }
1494
1475
  async _pipelineExtensionToolCallFinish(event) {
1495
1476
  if (!this.extensionManager) return;
1496
1477
  if (this.extensionManager.getHookSubscribers("afterToolCall").length === 0) return;
1497
- const { createToolCallFinishSnapshot } = await import("./hook-proxy-DHwqL8MV.js");
1478
+ const { createToolCallFinishSnapshot } = await import("./hook-proxy-CkF0EhRO.js");
1498
1479
  await this._dispatchExtensionObservation("afterToolCall", createToolCallFinishSnapshot(event));
1499
1480
  }
1500
1481
  async _pipelineExtensionStepFinish(event) {
1501
1482
  if (!this.extensionManager) return;
1502
1483
  if (this.extensionManager.getHookSubscribers("onStepFinish").length === 0) return;
1503
- const { createStepFinishSnapshot } = await import("./hook-proxy-DHwqL8MV.js");
1484
+ const { createStepFinishSnapshot } = await import("./hook-proxy-CkF0EhRO.js");
1504
1485
  await this._dispatchExtensionObservation("onStepFinish", createStepFinishSnapshot(event));
1505
1486
  }
1506
1487
  async _pipelineExtensionChunk(event) {
1507
1488
  if (!this.extensionManager) return;
1508
1489
  if (this.extensionManager.getHookSubscribers("onChunk").length === 0) return;
1509
- const { createChunkSnapshot } = await import("./hook-proxy-DHwqL8MV.js");
1490
+ const { createChunkSnapshot } = await import("./hook-proxy-CkF0EhRO.js");
1510
1491
  await this._dispatchExtensionObservation("onChunk", createChunkSnapshot(event));
1511
1492
  }
1512
1493
  async _hostReadFile(path) {
@@ -2468,6 +2449,15 @@ var Think = class Think extends Agent {
2468
2449
  this._scheduleWorkflowNotificationAlarm();
2469
2450
  });
2470
2451
  }
2452
+ _hasPendingWorkflowNotifications() {
2453
+ this._ensureWorkflowNotificationTable();
2454
+ return this.sql`
2455
+ SELECT notification_id
2456
+ FROM cf_think_workflow_notifications
2457
+ WHERE delivered_at IS NULL
2458
+ LIMIT 1
2459
+ `.length > 0;
2460
+ }
2471
2461
  async _drainWorkflowNotifications() {
2472
2462
  if (this._drainingWorkflowNotifications) return;
2473
2463
  this._ensureWorkflowNotificationTable();
@@ -2668,6 +2658,15 @@ var Think = class Think extends Agent {
2668
2658
  console.error("[Think] Failed to drain submissions", error);
2669
2659
  });
2670
2660
  }
2661
+ _hasPendingSubmissions() {
2662
+ this._ensureSubmissionTable();
2663
+ return this.sql`
2664
+ SELECT submission_id
2665
+ FROM cf_think_submissions
2666
+ WHERE status = 'pending'
2667
+ LIMIT 1
2668
+ `.length > 0;
2669
+ }
2671
2670
  async _drainThinkSubmissions() {
2672
2671
  await this._drainSubmissions();
2673
2672
  }
@@ -3212,34 +3211,20 @@ var Think = class Think extends Agent {
3212
3211
  case "chat-request":
3213
3212
  if (event.init?.method === "POST") await this._handleChatRequest(connection, event);
3214
3213
  break;
3215
- case "tool-result": {
3214
+ case "tool-result":
3216
3215
  if (event.clientTools && Array.isArray(event.clientTools) && event.clientTools.length > 0) {
3217
3216
  this._lastClientTools = event.clientTools;
3218
3217
  this._persistClientTools();
3219
3218
  }
3220
- const resultPromise = Promise.resolve().then(async () => {
3221
- await this._applyToolResult(event.toolCallId, event.output, event.state, event.errorText);
3222
- return true;
3223
- });
3224
- this._pendingInteractionPromise = resultPromise;
3225
- resultPromise.finally(() => {
3226
- if (this._pendingInteractionPromise === resultPromise) this._pendingInteractionPromise = null;
3227
- }).catch(() => {});
3219
+ this._enqueueInteractionApply(() => this._applyToolResult(event.toolCallId, event.output, event.state, event.errorText));
3228
3220
  if (event.autoContinue) this._scheduleAutoContinuation(connection);
3221
+ else this._rearmPendingAutoContinuationForBatch();
3229
3222
  break;
3230
- }
3231
- case "tool-approval": {
3232
- const approvalPromise = Promise.resolve().then(async () => {
3233
- await this._applyToolApproval(event.toolCallId, event.approved);
3234
- return true;
3235
- });
3236
- this._pendingInteractionPromise = approvalPromise;
3237
- approvalPromise.finally(() => {
3238
- if (this._pendingInteractionPromise === approvalPromise) this._pendingInteractionPromise = null;
3239
- }).catch(() => {});
3223
+ case "tool-approval":
3224
+ this._enqueueInteractionApply(() => this._applyToolApproval(event.toolCallId, event.approved));
3240
3225
  if (event.autoContinue) this._scheduleAutoContinuation(connection);
3226
+ else this._rearmPendingAutoContinuationForBatch();
3241
3227
  break;
3242
- }
3243
3228
  case "clear":
3244
3229
  await this._handleClear(connection);
3245
3230
  break;
@@ -3443,6 +3428,8 @@ var Think = class Think extends Agent {
3443
3428
  }
3444
3429
  this._submitConcurrency.reset();
3445
3430
  this._pendingInteractionPromise = null;
3431
+ this._interactionApplyTail = Promise.resolve();
3432
+ this._streamingAssistant = null;
3446
3433
  this._continuationBarrierActive = false;
3447
3434
  this._continuation.sendResumeNone();
3448
3435
  this._continuation.clearAll();
@@ -3506,12 +3493,14 @@ var Think = class Think extends Agent {
3506
3493
  async _streamResultToRpcCallback(requestId, result, callback, abortSignal) {
3507
3494
  const streamId = this._resumableStream.start(requestId);
3508
3495
  const accumulator = new StreamAccumulator({ messageId: crypto.randomUUID() });
3496
+ this._streamingAssistant = accumulator;
3509
3497
  let streamFinalized = false;
3510
3498
  let assistantMsg = null;
3511
3499
  let aborted = false;
3512
3500
  let doneSent = false;
3513
3501
  let streamError;
3514
3502
  let pendingRpcError;
3503
+ let skipFinalizeRearm = false;
3515
3504
  const stallTimeoutMs = this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
3516
3505
  try {
3517
3506
  this._insideInferenceLoop = true;
@@ -3537,6 +3526,12 @@ var Think = class Think extends Agent {
3537
3526
  if (action?.type === "error") {
3538
3527
  streamError = action.error;
3539
3528
  this._emit("message:error", { error: streamError });
3529
+ this._emit("chat:request:failed", {
3530
+ requestId,
3531
+ stage: "stream",
3532
+ messagesPersisted: true,
3533
+ error: streamError
3534
+ });
3540
3535
  this._broadcastChat({
3541
3536
  type: MSG_CHAT_RESPONSE,
3542
3537
  id: requestId,
@@ -3624,6 +3619,7 @@ var Think = class Think extends Agent {
3624
3619
  });
3625
3620
  doneSent = true;
3626
3621
  }
3622
+ skipFinalizeRearm = true;
3627
3623
  await callback.onInterrupted?.();
3628
3624
  return;
3629
3625
  }
@@ -3633,6 +3629,7 @@ var Think = class Think extends Agent {
3633
3629
  streamFinalized = true;
3634
3630
  }
3635
3631
  doneSent = true;
3632
+ skipFinalizeRearm = true;
3636
3633
  await callback.onInterrupted?.();
3637
3634
  return;
3638
3635
  }
@@ -3677,6 +3674,9 @@ var Think = class Think extends Agent {
3677
3674
  error: errorMessage
3678
3675
  });
3679
3676
  await callback.onError(errorMessage);
3677
+ } finally {
3678
+ if (skipFinalizeRearm) this._streamingAssistant = null;
3679
+ else this._onStreamingTurnFinalized();
3680
3680
  }
3681
3681
  if (pendingRpcError) await callback.onError(pendingRpcError);
3682
3682
  }
@@ -3768,6 +3768,7 @@ var Think = class Think extends Agent {
3768
3768
  this._continuation.flushAwaitingConnections((c) => this._notifyStreamResuming(c));
3769
3769
  }
3770
3770
  const accumulator = new StreamAccumulator({ messageId: crypto.randomUUID() });
3771
+ this._streamingAssistant = accumulator;
3771
3772
  let doneSent = false;
3772
3773
  let streamAborted = false;
3773
3774
  let streamError;
@@ -3799,6 +3800,12 @@ var Think = class Think extends Agent {
3799
3800
  streamError = action.error;
3800
3801
  if (options?.captureProgrammaticStreamError) this._programmaticStreamErrors.set(requestId, streamError);
3801
3802
  this._emit("message:error", { error: streamError });
3803
+ this._emit("chat:request:failed", {
3804
+ requestId,
3805
+ stage: "stream",
3806
+ messagesPersisted: true,
3807
+ error: streamError
3808
+ });
3802
3809
  this._broadcastChat({
3803
3810
  type: MSG_CHAT_RESPONSE,
3804
3811
  id: requestId,
@@ -3861,12 +3868,14 @@ var Think = class Think extends Agent {
3861
3868
  });
3862
3869
  doneSent = true;
3863
3870
  }
3871
+ this._streamingAssistant = null;
3864
3872
  return { status: "aborted" };
3865
3873
  }
3866
3874
  if (outcome === "exhausted") {
3867
3875
  this._resumableStream.markError(streamId);
3868
3876
  this._pendingResumeConnections.clear();
3869
3877
  doneSent = true;
3878
+ this._streamingAssistant = null;
3870
3879
  return { status: "aborted" };
3871
3880
  }
3872
3881
  }
@@ -3920,6 +3929,7 @@ var Think = class Think extends Agent {
3920
3929
  } catch (e) {
3921
3930
  console.error("Failed to persist assistant message:", e);
3922
3931
  }
3932
+ this._onStreamingTurnFinalized();
3923
3933
  return streamError ? {
3924
3934
  status: "error",
3925
3935
  error: streamError
@@ -3965,6 +3975,37 @@ var Think = class Think extends Agent {
3965
3975
  this._lastBody = void 0;
3966
3976
  }
3967
3977
  }
3978
+ /**
3979
+ * Serialize a client-tool result/approval apply behind any in-flight apply
3980
+ * (#1649). Parallel tool results arrive as independent WebSocket messages,
3981
+ * and each apply is a read-modify-write of the full message in durable
3982
+ * storage. Running them concurrently means every apply reads the same
3983
+ * snapshot (all siblings still `input-available`), patches only its own part,
3984
+ * and writes the whole message back — so the last write clobbers the others
3985
+ * back to `input-available`, and the auto-continuation barrier later times
3986
+ * out and the transcript-repair backstop errors the lost siblings.
3987
+ *
3988
+ * Chaining each apply off `_interactionApplyTail` makes the read-modify-write
3989
+ * atomic per result and in arrival order. `_pendingInteractionPromise` is set
3990
+ * to the newest link so the barrier's single-slot wake-up still observes the
3991
+ * latest apply; because the chain is serial, awaiting it transitively waits
3992
+ * for every predecessor.
3993
+ *
3994
+ * @internal
3995
+ */
3996
+ _enqueueInteractionApply(apply) {
3997
+ const run = async () => {
3998
+ await apply();
3999
+ return true;
4000
+ };
4001
+ const resultPromise = this._interactionApplyTail.then(run, run);
4002
+ this._interactionApplyTail = resultPromise.then(() => void 0, () => void 0);
4003
+ this._pendingInteractionPromise = resultPromise;
4004
+ resultPromise.finally(() => {
4005
+ if (this._pendingInteractionPromise === resultPromise) this._pendingInteractionPromise = null;
4006
+ }).catch(() => {});
4007
+ return resultPromise;
4008
+ }
3968
4009
  async _applyToolResult(toolCallId, output, overrideState, errorText) {
3969
4010
  const update = toolResultUpdate(toolCallId, output, overrideState, errorText);
3970
4011
  await this._applyToolUpdateToMessages(update);
@@ -3974,29 +4015,41 @@ var Think = class Think extends Agent {
3974
4015
  await this._applyToolUpdateToMessages(update);
3975
4016
  }
3976
4017
  async _applyToolUpdateToMessages(update) {
4018
+ let broadcastMessage;
4019
+ const streaming = this._streamingAssistant;
4020
+ if (streaming) {
4021
+ const accParts = streaming.parts;
4022
+ const result = applyToolUpdate(accParts, update);
4023
+ if (result && result.parts[result.index] !== accParts[result.index]) {
4024
+ accParts[result.index] = result.parts[result.index];
4025
+ broadcastMessage = streaming.toMessage();
4026
+ }
4027
+ }
3977
4028
  const history = await this._readMessagesFromStorage();
3978
4029
  for (let i = 0; i < history.length; i++) {
3979
4030
  const msg = history[i];
3980
4031
  const msgParts = msg.parts;
3981
4032
  const result = applyToolUpdate(msgParts, update);
3982
4033
  if (result) {
3983
- if (result.parts[result.index] === msgParts[result.index]) return;
4034
+ if (result.parts[result.index] === msgParts[result.index]) break;
3984
4035
  const updatedMsg = {
3985
4036
  ...msg,
3986
4037
  parts: result.parts
3987
4038
  };
3988
4039
  const safe = await this._updateMessageInHistory(updatedMsg);
3989
4040
  this._patchCachedMessage(safe);
3990
- this._broadcast({
3991
- type: MSG_MESSAGE_UPDATED,
3992
- message: safe
3993
- });
3994
- return;
4041
+ broadcastMessage = safe;
4042
+ break;
3995
4043
  }
3996
4044
  }
4045
+ if (broadcastMessage) this._broadcast({
4046
+ type: MSG_MESSAGE_UPDATED,
4047
+ message: broadcastMessage
4048
+ });
3997
4049
  }
3998
4050
  hasPendingInteraction() {
3999
- return this.messages.some((message) => message.role === "assistant" && this._messageHasPendingInteraction(message));
4051
+ const clientResolvable = this._clientResolvableToolNames();
4052
+ return this.messages.some((message) => message.role === "assistant" && this._messageHasPendingInteraction(message, clientResolvable));
4000
4053
  }
4001
4054
  async waitUntilStable(options) {
4002
4055
  const deadline = options?.timeout != null ? Date.now() + options.timeout : null;
@@ -4025,8 +4078,56 @@ var Think = class Think extends Agent {
4025
4078
  clearTimeout(timer);
4026
4079
  return result;
4027
4080
  }
4028
- _messageHasPendingInteraction(message) {
4029
- return message.parts.some((part) => "state" in part && (part.state === "input-available" || part.state === "approval-requested"));
4081
+ _messageHasPendingInteraction(message, clientResolvable) {
4082
+ return message.parts.some((part) => this._partAwaitsClientInteraction(part, clientResolvable));
4083
+ }
4084
+ /**
4085
+ * Names of the tools whose interrupted `input-available` part can still be
4086
+ * resolved by the CLIENT after a restart — i.e. the client tools (no server
4087
+ * `execute`) from the last request, which the SPA answers by replaying a
4088
+ * `tool-result` over the WebSocket. A server tool is intentionally absent:
4089
+ * its `execute()` promise died with the evicted isolate, so nothing will
4090
+ * ever post its result.
4091
+ */
4092
+ _clientResolvableToolNames() {
4093
+ const names = /* @__PURE__ */ new Set();
4094
+ for (const tool of this._lastClientTools ?? []) if (tool?.name) names.add(tool.name);
4095
+ return names;
4096
+ }
4097
+ /** Extract a tool part's name from its `tool-<name>` / `dynamic-tool` shape. */
4098
+ _toolPartName(record) {
4099
+ const type = typeof record.type === "string" ? record.type : "";
4100
+ if (type === "dynamic-tool") return typeof record.toolName === "string" ? record.toolName : void 0;
4101
+ if (type.startsWith("tool-")) return type.slice(5);
4102
+ }
4103
+ /**
4104
+ * Whether a part is still awaiting a CLIENT interaction that can genuinely
4105
+ * arrive after a restart, so `waitUntilStable` must keep waiting for it:
4106
+ * - `approval-requested`: a reconnecting client can replay the approval.
4107
+ * - `input-available` for a CLIENT tool: the SPA can replay the
4108
+ * `tool-result` (this is why client-tool recovery works — see the
4109
+ * `tool-result` handler, which sets `_pendingInteractionPromise`).
4110
+ *
4111
+ * A SERVER tool's `input-available` is deliberately NOT pending. After an
4112
+ * eviction its `execute()` promise is gone and no interaction will ever
4113
+ * resolve it, so treating it as pending wedges `waitUntilStable` forever:
4114
+ * the recovery continuation times out every attempt, burns the attempt
4115
+ * budget on a wait that can never converge, and — if any transient
4116
+ * storage/schedule error throws on the way — the one-shot recovery alarm row
4117
+ * is swallowed and deleted with no terminal `onExhausted` (the half-finished
4118
+ * message wedges silently). Excluding it lets `waitUntilStable` converge so
4119
+ * `continueLastTurn` runs, where the existing transcript-repair pass
4120
+ * (`_repairTranscriptForProvider`) flips the orphan to an errored result and
4121
+ * the model proceeds.
4122
+ */
4123
+ _partAwaitsClientInteraction(part, clientResolvable) {
4124
+ if (!("state" in part)) return false;
4125
+ const record = part;
4126
+ const state = record.state;
4127
+ if (state === "approval-requested") return true;
4128
+ if (state !== "input-available") return false;
4129
+ const toolName = this._toolPartName(record);
4130
+ return toolName != null && clientResolvable.has(toolName);
4030
4131
  }
4031
4132
  _resolveChatRecoveryConfig() {
4032
4133
  const raw = this.chatRecovery;
@@ -4185,8 +4286,6 @@ var Think = class Think extends Agent {
4185
4286
  } catch (error) {
4186
4287
  console.error("[Think] chatRecovery onExhausted hook threw", error);
4187
4288
  }
4188
- await this._markRecoveredSubmissionInterrupted(incident.recoveryRootRequestId ?? incident.requestId, config.terminalMessage);
4189
- await this._recordTerminalChatStatus("interrupted", incident.requestId, config.terminalMessage);
4190
4289
  this._broadcastChat({
4191
4290
  type: MSG_CHAT_RESPONSE,
4192
4291
  id: incident.requestId,
@@ -4194,6 +4293,8 @@ var Think = class Think extends Agent {
4194
4293
  done: true,
4195
4294
  error: true
4196
4295
  });
4296
+ await this._markRecoveredSubmissionInterrupted(incident.recoveryRootRequestId ?? incident.requestId, config.terminalMessage);
4297
+ await this._recordTerminalChatStatus("interrupted", incident.requestId, config.terminalMessage);
4197
4298
  }
4198
4299
  /**
4199
4300
  * Route a stream-stall watchdog abort into bounded recovery instead of a
@@ -4459,19 +4560,26 @@ var Think = class Think extends Agent {
4459
4560
  return this._resumableStream.hasActiveStream() ? this._resumableStream.activeStreamId ?? "" : "";
4460
4561
  }
4461
4562
  /**
4462
- * Terminalize a recovery turn that has run out of stable-state-timeout retry
4463
- * budget — or whose incident record has vanished — by routing through the
4464
- * SAME `_exhaustChatRecovery` path as deploy-recovery and stall exhaustion
4563
+ * Terminalize a recovery turn that is giving up — whether because the
4564
+ * stable-state-timeout retry budget drained, or because the recovery
4565
+ * continuation threw a non-recoverable error — by routing through the SAME
4566
+ * `_exhaustChatRecovery` path as deploy-recovery and stall exhaustion
4465
4567
  * (#1626/#1631). It fires `onExhausted`, emits `chat:recovery:exhausted`,
4466
4568
  * marks the durable submission interrupted, records the terminal chat status,
4467
- * and delivers the configured `terminalMessage`.
4569
+ * and delivers the configured `terminalMessage`. `reason` carries the cause
4570
+ * (`stable_timeout` for a budget give-up, `recovery_error` for a thrown
4571
+ * error) through to `onExhausted` / `chat:recovery:exhausted`.
4468
4572
  *
4469
4573
  * This replaces the older give-up that only set the incident to `failed` and
4470
4574
  * completed the recovered submission as `error`, which bypassed
4471
4575
  * `_exhaustChatRecovery` entirely — so an app relying on `onExhausted` for the
4472
4576
  * terminal banner regressed to an eternal spinner when recovery gave up under
4473
- * extreme churn (the stable-state wait timing out every attempt until the
4474
- * budget drained). Shared by `_chatRecoveryRetry` and `_chatRecoveryContinue`.
4577
+ * extreme churn. The error path matters just as much: a non-reset throw in a
4578
+ * recovery callback is SWALLOWED by `Agent._executeScheduleCallback` (only a
4579
+ * code-update reset is re-thrown to preserve the one-shot row), so without
4580
+ * routing it here the alarm row is deleted with no terminal UX at all — the
4581
+ * half-finished message wedges silently. Shared by `_chatRecoveryRetry` and
4582
+ * `_chatRecoveryContinue`.
4475
4583
  *
4476
4584
  * Exactly-once terminalization is defended by two independent guards:
4477
4585
  * 1. The `stored?.status === "exhausted"` re-entry guard below — once an
@@ -4492,16 +4600,21 @@ var Think = class Think extends Agent {
4492
4600
  * • The record is swept AGAIN between two alarms (guard #1 re-persists on the
4493
4601
  * first, so this needs a second independent sweep) — vanishingly unlikely.
4494
4602
  */
4495
- async _exhaustRecoveryAfterStableTimeout(callback, data) {
4603
+ async _exhaustRecoveryGiveUp(callback, data, reason) {
4496
4604
  const config = this._resolveChatRecoveryConfig();
4497
4605
  const incidentKey = data?.incidentId ? this._chatRecoveryIncidentKey(data.incidentId) : null;
4498
- const stored = incidentKey ? await this.ctx.storage.get(incidentKey) : null;
4606
+ let stored = null;
4607
+ if (incidentKey) try {
4608
+ stored = await this.ctx.storage.get(incidentKey) ?? null;
4609
+ } catch (readError) {
4610
+ console.error("[Think] failed to read recovery incident during give-up; synthesizing", readError);
4611
+ }
4499
4612
  if (stored?.status === "exhausted") return;
4500
4613
  const rootRequestId = data?.originalRequestId ?? data?.recoveredRequestId ?? this._activeChatRecoveryRootRequestId ?? stored?.recoveryRootRequestId ?? stored?.requestId ?? "";
4501
4614
  const incident = stored ? {
4502
4615
  ...stored,
4503
4616
  status: "exhausted",
4504
- reason: "stable_timeout"
4617
+ reason
4505
4618
  } : {
4506
4619
  incidentId: data?.incidentId ?? crypto.randomUUID(),
4507
4620
  requestId: rootRequestId,
@@ -4512,9 +4625,13 @@ var Think = class Think extends Agent {
4512
4625
  status: "exhausted",
4513
4626
  firstSeenAt: Date.now(),
4514
4627
  lastAttemptAt: Date.now(),
4515
- reason: "stable_timeout"
4628
+ reason
4516
4629
  };
4517
- if (incidentKey) await this.ctx.storage.put(incidentKey, incident);
4630
+ if (incidentKey) try {
4631
+ await this.ctx.storage.put(incidentKey, incident);
4632
+ } catch (writeError) {
4633
+ console.error("[Think] failed to persist sealed recovery incident during give-up", writeError);
4634
+ }
4518
4635
  const streamId = this._resolveRecoveryStreamId(incident.recoveryRootRequestId ?? incident.requestId);
4519
4636
  const partial = streamId ? this._getPartialStreamText(streamId) : {
4520
4637
  text: "",
@@ -4522,6 +4639,61 @@ var Think = class Think extends Agent {
4522
4639
  };
4523
4640
  await this._exhaustChatRecovery(incident, config, partial, streamId, incident.firstSeenAt);
4524
4641
  }
4642
+ /**
4643
+ * Give-up after the stable-state-timeout retry budget drained. Thin wrapper
4644
+ * over `_exhaustRecoveryGiveUp` so the give-up cause is recorded as
4645
+ * `stable_timeout`.
4646
+ */
4647
+ _exhaustRecoveryAfterStableTimeout(callback, data) {
4648
+ return this._exhaustRecoveryGiveUp(callback, data, "stable_timeout");
4649
+ }
4650
+ /**
4651
+ * Whether an error is a transient "superseded isolate" failure — a deploy /
4652
+ * code update replaced the isolate mid-invocation. Mirrors the base `Agent`
4653
+ * check (`isDurableObjectCodeUpdateReset`) and MUST stay in lockstep with it:
4654
+ * the base `_executeScheduleCallback` re-throws this class for a one-shot row
4655
+ * (preserving it so the platform re-runs on the new code), so a recovery
4656
+ * callback must also re-throw — NOT terminalize — since recovery will re-run
4657
+ * and succeed on the fresh isolate. The matched family (kept identical to the
4658
+ * base):
4659
+ * - "Durable Object reset because its code was updated." (deploy bounce)
4660
+ * - "This script has been upgraded. Please send a new request to connect to
4661
+ * the new version." (a stub/connection to a superseded script)
4662
+ * "Network connection lost." is intentionally excluded (a connection error,
4663
+ * not an isolate replacement — see the base helper's note). The match stays
4664
+ * close to the verbatim platform strings so an ordinary error mentioning
4665
+ * those words isn't misclassified as a supersede.
4666
+ */
4667
+ _isDeployCodeUpdateReset(error) {
4668
+ const message = error instanceof Error ? error.message : typeof error === "string" ? error : "";
4669
+ return /reset because its code was updated|this script has been upgraded/i.test(message);
4670
+ }
4671
+ /**
4672
+ * Handle an error thrown by `_chatRecoveryContinue` / `_chatRecoveryRetry`
4673
+ * after the incident was opened.
4674
+ *
4675
+ * - A deploy code-update reset is re-thrown (after marking the incident
4676
+ * `failed` for observability) so `Agent._executeScheduleCallback` preserves
4677
+ * the one-shot alarm row and the platform re-runs recovery on the fresh
4678
+ * isolate — the turn can still recover, so it must NOT terminalize.
4679
+ * - Any OTHER error is terminalized through the give-up path
4680
+ * (`onExhausted` + the `terminalMessage` banner) and NOT re-thrown. This is
4681
+ * the fix for the silent-seal failure mode: `_executeScheduleCallback`
4682
+ * swallows a non-reset throw and then `alarm()` deletes the one-shot row, so
4683
+ * without terminalizing here the half-finished turn is dropped with no
4684
+ * terminal event and no banner (the user stares at a frozen message until
4685
+ * they send something new).
4686
+ */
4687
+ async _handleRecoveryCallbackError(callback, data, error) {
4688
+ if (this._isDeployCodeUpdateReset(error)) {
4689
+ const message = error instanceof Error ? error.message : String(error);
4690
+ await this._updateChatRecoveryIncident(data?.incidentId, "failed", message);
4691
+ if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, message);
4692
+ throw error;
4693
+ }
4694
+ console.error(`[Think] ${callback} threw during recovery; terminalizing instead of leaving the turn wedged`, error);
4695
+ await this._exhaustRecoveryGiveUp(callback, data, "recovery_error");
4696
+ }
4525
4697
  async _chatRecoveryRetry(data) {
4526
4698
  const recoveredSubmission = data?.recoveredRequestId ? this._readRunningSubmissionByRequestId(data.recoveredRequestId) : null;
4527
4699
  if (data?.recoveredRequestId && !recoveredSubmission) {
@@ -4555,9 +4727,7 @@ var Think = class Think extends Agent {
4555
4727
  await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
4556
4728
  if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, result.status, result.requestId || null, result.status === "completed" ? null : result.error ?? `Recovery retry ${result.status}.`);
4557
4729
  } catch (error) {
4558
- await this._updateChatRecoveryIncident(data?.incidentId, "failed", error instanceof Error ? error.message : String(error));
4559
- if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, error instanceof Error ? error.message : String(error));
4560
- throw error;
4730
+ await this._handleRecoveryCallbackError("_chatRecoveryRetry", data, error);
4561
4731
  } finally {
4562
4732
  this._activeChatRecoveryRootRequestId = previousRootRequestId;
4563
4733
  if (recoveredSubmission) this._submissionAbortControllers.delete(recoveredSubmission.submission_id);
@@ -4660,9 +4830,7 @@ var Think = class Think extends Agent {
4660
4830
  await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
4661
4831
  if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, result.status, result.requestId || null, result.status === "completed" ? null : result.error ?? `Recovery ${result.status}.`);
4662
4832
  } catch (error) {
4663
- await this._updateChatRecoveryIncident(data?.incidentId, "failed", error instanceof Error ? error.message : String(error));
4664
- if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, error instanceof Error ? error.message : String(error));
4665
- throw error;
4833
+ await this._handleRecoveryCallbackError("_chatRecoveryContinue", data, error);
4666
4834
  } finally {
4667
4835
  this._activeChatRecoveryRootRequestId = previousRootRequestId;
4668
4836
  if (recoveredSubmission) this._submissionAbortControllers.delete(recoveredSubmission.submission_id);
@@ -4744,6 +4912,40 @@ var Think = class Think extends Agent {
4744
4912
  this._continuation.awaitingConnections.set(connection.id, connection);
4745
4913
  this._resetAutoContinuationTimer();
4746
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
+ }
4747
4949
  _resetAutoContinuationTimer() {
4748
4950
  if (this._continuationTimer) clearTimeout(this._continuationTimer);
4749
4951
  this._continuationTimer = setTimeout(() => {
@@ -4760,48 +4962,64 @@ var Think = class Think extends Agent {
4760
4962
  * arrives while slower siblings are still `input-available`. Continuing then
4761
4963
  * would feed the provider an incomplete tool-result set
4762
4964
  * (`MissingToolResultsError`) or, via the transcript-repair backstop, silently
4763
- * error the in-flight sibling and run a spurious extra continuation. We hold
4764
- * the continuation on a barrier until the batch settles. The wait is bounded
4765
- * (`AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS`) so a genuinely orphaned tool
4766
- * call — e.g. the client disconnected mid-batch — still falls through to the
4767
- * 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.
4768
4984
  */
4769
4985
  _fireAutoContinuationWhenStable(connection) {
4770
4986
  if (!this._continuation.pending) return;
4771
4987
  if (this._continuation.pending.pastCoalesce) return;
4772
4988
  if (this._continuationBarrierActive) return;
4989
+ if (this._streamingAssistant) return;
4773
4990
  if (!this._pendingInteractionPromise && !this._hasIncompleteToolBatch()) {
4774
4991
  this._fireAutoContinuation(connection);
4775
4992
  return;
4776
4993
  }
4777
4994
  this._continuationBarrierActive = true;
4778
- this.keepAliveWhile(() => this._awaitToolBatch()).catch(() => {}).finally(() => {
4995
+ this.keepAliveWhile(() => this._drainInteractionApplies()).catch(() => {}).finally(() => {
4779
4996
  this._continuationBarrierActive = false;
4780
4997
  const pending = this._continuation.pending;
4781
- 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);
4782
5002
  });
4783
5003
  }
4784
5004
  /**
4785
- * Block until the latest assistant step's parallel tool batch is fully
4786
- * answered, or `AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS` elapses. Awaits the
4787
- * in-flight tool-result apply when one exists (so a sibling that lands
4788
- * 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.
4789
5012
  */
4790
- async _awaitToolBatch() {
4791
- const deadline = Date.now() + AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS;
4792
- while (Date.now() < deadline) {
5013
+ async _drainInteractionApplies() {
5014
+ let tail = this._interactionApplyTail;
5015
+ for (;;) {
4793
5016
  if (!this._continuation.pending) return;
4794
- const pending = this._pendingInteractionPromise;
4795
- if (pending) {
4796
- try {
4797
- await pending;
4798
- } catch {}
4799
- continue;
4800
- }
4801
- if (!this._hasIncompleteToolBatch()) return;
4802
- await new Promise((resolve) => setTimeout(resolve, 100));
5017
+ try {
5018
+ await tail;
5019
+ } catch {}
5020
+ if (this._interactionApplyTail === tail) return;
5021
+ tail = this._interactionApplyTail;
4803
5022
  }
4804
- console.warn(`[Think] Auto-continuation proceeding after waiting ${AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS}ms for unanswered parallel tool result(s) (#1649).`);
4805
5023
  }
4806
5024
  /**
4807
5025
  * `true` when the latest assistant message is mid-batch: it carries at least