@cloudflare/think 0.19.0 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/think.js CHANGED
@@ -2,7 +2,7 @@ import { a as _assertClassBrand, i as _classPrivateFieldGet2, n as sanitizeName,
2
2
  import { createWorkspaceTools } from "./tools/workspace.js";
3
3
  import { createFetchTools } from "./tools/fetch.js";
4
4
  import { truncatePausedExecutionOutput } from "./tools/execute.js";
5
- import { g as MESSENGER_REPLY_FIBER_NAME, t as ThinkMessengerRuntime } from "./chat-sdk-B77QwYuj.js";
5
+ import { _ as MESSENGER_REPLY_FIBER_NAME, n as ThinkMessengerRuntime, t as DEFAULT_MESSENGER_CONCURRENCY } from "./chat-sdk-BEjKXjCm.js";
6
6
  import "./messengers/index.js";
7
7
  import { AsyncLocalStorage } from "node:async_hooks";
8
8
  import * as aiSdk from "ai";
@@ -13,8 +13,8 @@ import { anthropic } from "workers-ai-provider/anthropic";
13
13
  import { openai } from "workers-ai-provider/openai";
14
14
  import * as skills from "agents/skills";
15
15
  import { SkillRegistry } from "agents/skills";
16
- import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext, __DO_NOT_USE_WILL_BREAK__withInvocationScope, callable, getCurrentAgent, isDurableObjectMemoryLimitReset, isPlatformTransientError } from "agents";
17
- import { AbortRegistry, AgentToolProgressEmitter, AgentToolStreamProgressThrottle, AutoContinuationController, CHAT_MESSAGE_TYPES, CHAT_RECOVERY_PROGRESS_KEY, CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS, CHAT_RECOVERY_TASK_NAME, ChatRecoveryEngine, ChatStreamStalledError, ContinuationState, MAX_BOUND_PARAMS, PreStreamTurns, ResumableStream, ResumeHandshake, StreamAccumulator, SubmitConcurrencyController, TIMED_OUT, TurnQueue, aiSdkRecoveryCodec, applyToolUpdate, awaitWithDeadline, buildChatRecoveringFrame, buildInClauseStrings, chatRecoveryTaskRunOptions, classifyAgentToolChildRecovery, clearChatTerminal, clientResolvableToolNames, createChatFiberSnapshot, createChatRecoveryTaskDefinition, createChatStreams, createChatTurnTaskDefinition, createToolsFromClientSchemas, crossMessageToolResultUpdate, dispatchChatRecoveryToHandoff, drainInteractionApplies, enforceRowSizeLimit, hasIncompleteToolBatch, interceptAgentToolBroadcast, iterateWithStallWatchdog, listActiveChatRecoveryIncidents, normalizeToolInput, parseProtocolMessage, partAwaitsClientInteraction, pausedExecutionUpdate, pendingChatTerminal, persistReconstructedOrphan, readChatRecoveryProgress, reconcileMessages, recordChatTerminal, repairInterruptedToolParts, resolveChatRecoveryConfig, resolveToolMergeId, runChatRecoveryExhaustion, sanitizeMessage, setChatRecovering, sweepStaleChatRecoveryIncidents, toolApprovalUpdate, toolPartHasSettledResult, toolResultUpdate, truncateOlderMessages, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
16
+ import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext, __DO_NOT_USE_WILL_BREAK__withInvocationScope, callable, getCurrentAgent, isDurableObjectCodeUpdateReset, isDurableObjectMemoryLimitReset, isPlatformTransientError } from "agents";
17
+ import { AbortRegistry, AgentToolProgressEmitter, AgentToolStreamProgressThrottle, AutoContinuationController, CHAT_MESSAGE_TYPES, CHAT_RECOVERY_INCIDENT_KEY_PREFIX, CHAT_RECOVERY_PROGRESS_KEY, CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS, CHAT_RECOVERY_TASK_NAME, ChatRecoveryEngine, ChatStreamStalledError, ContinuationState, MAX_BOUND_PARAMS, PreStreamTurns, ResumableStream, ResumeHandshake, StreamAccumulator, SubmitConcurrencyController, TIMED_OUT, TurnQueue, aiSdkRecoveryCodec, applyToolUpdate, awaitWithDeadline, buildChatRecoveringFrame, buildInClauseStrings, chatRecoveryBackoffSeconds, chatRecoveryTaskRunOptions, classifyAgentToolChildRecovery, clearChatTerminal, clientResolvableToolNames, createChatFiberSnapshot, createChatRecoveryTaskDefinition, createChatStreams, createChatTurnTaskDefinition, createToolsFromClientSchemas, crossMessageToolResultUpdate, dispatchChatRecoveryToHandoff, drainInteractionApplies, enforceRowSizeLimit, hasIncompleteToolBatch, interceptAgentToolBroadcast, isDurableObjectResetError, isLateToolInputChunk, isPositionlessAgentToolChunk, iterateWithStallWatchdog, lateToolInputForwardChunks, listActiveChatRecoveryIncidents, normalizeToolInput, originMessageIds, parseProtocolMessage, partAwaitsClientInteraction, pausedExecutionUpdate, pendingChatTerminal, persistReconstructedOrphan, readChatRecoveryProgress, reconcileMessages, recordChatTerminal, repairInterruptedToolParts, resolveChatRecoveryConfig, retryAfterSeconds, runChatRecoveryExhaustion, sanitizeMessage, setChatRecovering, sweepStaleChatRecoveryIncidents, toolApprovalUpdate, toolPartHasSettledResult, toolResultUpdate, truncateOlderMessages, truncateOlderToolResults, unwrapChatFiberSnapshot, withOriginMessageIds, wrapChatFiberSnapshot } from "agents/chat";
18
18
  import { Sessions, isCompactionMessage } from "agents/sessions";
19
19
  import { AgentContextProvider, ContextBlocks } from "agents/context";
20
20
  import { Workspace, Workspace as Workspace$1 } from "@cloudflare/shell";
@@ -497,9 +497,9 @@ function resolveChannels(configured, messengers) {
497
497
  * WebSocket protocol to browser clients) and a **sub-agent** (called
498
498
  * via `chat()` over RPC from a parent agent).
499
499
  *
500
- * Each instance gets its own SQLite storage backed by Session — providing
501
- * tree-structured messages, context blocks, compaction, FTS5 search, and
502
- * multi-session support.
500
+ * Each instance holds one conversation in its own SQLite storage, backed by
501
+ * Sessions — providing tree-structured messages, context blocks, compaction,
502
+ * and FTS5 search.
503
503
  *
504
504
  * Configuration overrides:
505
505
  * - getModel() — return a model id string (resolved via the
@@ -581,18 +581,73 @@ const agentToolChunkEncoder = new TextEncoder();
581
581
  const agentsAISDKInvocationBounded = Symbol.for("cloudflare.agents.ai-sdk.invocation-bounded");
582
582
  const usesAISDKV7Telemetry = "registerTelemetry" in aiSdk;
583
583
  /**
584
- * The recent-message span the model sees at FULL fidelity each turn —
585
- * `truncateOlderMessages`' default `keepRecent` (see `_assembleModelMessages`).
584
+ * The shortest recent-message span the model sees at FULL fidelity each turn
585
+ * (see `_assembleModelMessages` and {@link MODEL_TRUNCATION_STEP}).
586
586
  *
587
587
  * Both memory bounds are anchored to this window (#1710):
588
588
  * - budgeted hydration (`hydrationByteBudget`) is a hard byte ceiling, so a
589
589
  * window of unusually large messages can be shorter than this; the model
590
590
  * then sees what fits rather than exhausting isolate memory;
591
- * - media eviction never rewrites messages inside it (the
592
- * `keepRecentMessages` clamp), so the rows the model replays at full
593
- * fidelity are never stripped.
591
+ * - media eviction never rewrites messages above the stepped truncation
592
+ * cutoff (see {@link mediaEvictionCutoff}), so the rows the model replays
593
+ * at full fidelity are never stripped.
594
594
  */
595
595
  const MODEL_RECENT_WINDOW = 4;
596
+ /**
597
+ * Default `truncationStep`. Read-time truncation cuts the history at a
598
+ * multiple of this many messages,
599
+ * so the full-fidelity span grows from `MODEL_RECENT_WINDOW` to
600
+ * `MODEL_RECENT_WINDOW + MODEL_TRUNCATION_STEP - 1` messages between cuts.
601
+ * Providers cache on a byte-identical prompt prefix, and a cutoff that moved
602
+ * every turn rewrote a message near the end of that prefix on every turn
603
+ * (#2200). Stepping it rewrites the prefix once per step instead.
604
+ */
605
+ const MODEL_TRUNCATION_STEP = 8;
606
+ /**
607
+ * Drop the keys of a `start` chunk's metadata that the extended assistant
608
+ * message already carries, so a recovery continuation re-running the metadata
609
+ * writer cannot overwrite them (#2321).
610
+ */
611
+ function withoutOverwrittenStartMetadata(chunk, existing) {
612
+ if (chunk.type !== "start" || existing === null || typeof existing !== "object" || chunk.messageMetadata === null || typeof chunk.messageMetadata !== "object") return chunk;
613
+ const messageMetadata = Object.fromEntries(Object.entries(chunk.messageMetadata).filter(([key]) => !Object.prototype.hasOwnProperty.call(existing, key)));
614
+ return {
615
+ ...chunk,
616
+ messageMetadata
617
+ };
618
+ }
619
+ /** Copy a turn context without reading its lazily resolved `model`. */
620
+ function turnContextWithoutModel(ctx) {
621
+ const { model: _model, ...descriptors } = Object.getOwnPropertyDescriptors(ctx);
622
+ return Object.defineProperties({}, descriptors);
623
+ }
624
+ /** `Infinity` never moves the cutoff; any other invalid step cuts every turn. */
625
+ function truncationStepSize(step) {
626
+ if (step === Number.POSITIVE_INFINITY) return step;
627
+ return Number.isFinite(step) ? Math.max(1, Math.floor(step)) : 1;
628
+ }
629
+ function truncationKeepRecent(messageCount, step) {
630
+ const safeStep = truncationStepSize(step);
631
+ if (messageCount <= MODEL_RECENT_WINDOW) return MODEL_RECENT_WINDOW;
632
+ if (safeStep === Number.POSITIVE_INFINITY) return messageCount;
633
+ return MODEL_RECENT_WINDOW + (messageCount - MODEL_RECENT_WINDOW) % safeStep;
634
+ }
635
+ /**
636
+ * Index below which media eviction may rewrite messages: the stepped
637
+ * truncation cutoff, moved back whole steps until at least
638
+ * `keepRecentMessages` messages stay above it. It only moves when the
639
+ * truncation cutoff does, so eviction rewrites the cached prompt prefix at
640
+ * most once per step and never inside the full-fidelity window (#2356).
641
+ * With stepping disabled (`truncationStep = Infinity`) there is no cutoff to
642
+ * align with, and eviction keeps exactly `keepRecentMessages`.
643
+ */
644
+ function mediaEvictionCutoff(messageCount, keepRecentMessages, step) {
645
+ const keep = Math.max(keepRecentMessages, MODEL_RECENT_WINDOW);
646
+ const safeStep = truncationStepSize(step);
647
+ if (safeStep === Number.POSITIVE_INFINITY) return Math.max(0, messageCount - keep);
648
+ const stepsBack = Math.ceil((keep - MODEL_RECENT_WINDOW) / safeStep);
649
+ return Math.max(0, messageCount - truncationKeepRecent(messageCount, safeStep) - stepsBack * safeStep);
650
+ }
596
651
  const DEFAULT_ACTION_TIMEOUT_MS = 3e4;
597
652
  /** Whether a workspace can receive raw bytes, which skills projection needs. */
598
653
  function hasWriteFileBytes(workspace) {
@@ -602,6 +657,109 @@ const ACTION_OUTPUT_MAX_CHARS = 2e4;
602
657
  const MAX_REPLY_ATTACHMENTS_PER_TURN = 32;
603
658
  const ACTION_LEDGER_SWEEP_INTERVAL_MS = 3600 * 1e3;
604
659
  const ACTION_LEDGER_LAST_SWEPT_KEY = "cf_think_action_ledger:last_swept_at";
660
+ const DEFERRED_RESOLVED_PAUSES_KEY = "cf_think_deferred_resolved_pauses";
661
+ const PENDING_RESPONSE_HOOK_PREFIX = "cf_think_pending_response_hook:";
662
+ const MESSENGER_RECOVERY_PREFIX = "cf_think_messenger_recovery:";
663
+ const MESSENGER_RECOVERY_RETRY_CALLBACK = "_cfRetryMessengerRecoveryDelivery";
664
+ const MESSENGER_RECOVERY_MAX_RETRIES = 8;
665
+ const WORKERS_AI_MODEL_PREFIXES = ["@cf/", "@hf/"];
666
+ function isWorkersAIModelId(model) {
667
+ return WORKERS_AI_MODEL_PREFIXES.some((prefix) => model.startsWith(prefix) && model.length > prefix.length);
668
+ }
669
+ function messageText(message) {
670
+ return (message?.parts ?? []).filter((p) => p.type === "text").map((p) => p.text).join("");
671
+ }
672
+ function settleMessengerRecoveryDelivery(delivery, outcome, text) {
673
+ if (outcome !== "completed") return {
674
+ ...delivery,
675
+ outcome
676
+ };
677
+ const recovered = text ?? "";
678
+ return {
679
+ ...delivery,
680
+ outcome,
681
+ text: recovered.startsWith(delivery.partialText) ? recovered.slice(delivery.partialText.length) : recovered
682
+ };
683
+ }
684
+ /**
685
+ * Carries an in-stream error that `classifyChatError` marked transient out of
686
+ * the drain loop, so it reaches the same recovery routing as a thrown error.
687
+ * `original` is the provider error the stream reported, when it had one.
688
+ */
689
+ var TransientChatStreamError = class extends Error {
690
+ constructor(message, classification, original) {
691
+ super(message);
692
+ this.classification = classification;
693
+ this.original = original;
694
+ this.name = "TransientChatStreamError";
695
+ }
696
+ };
697
+ function isPausedToolPart(part) {
698
+ const output = part.output;
699
+ return part.state === "output-available" && output != null && typeof output === "object" && output.status === "paused";
700
+ }
701
+ function ownsPausedToolCall(message, toolCallId) {
702
+ return message.parts.some((part) => part.toolCallId === toolCallId && isPausedToolPart(part));
703
+ }
704
+ /** The tool call id of a part whose output carries `executionId`, if any. */
705
+ function executionToolCallIn(message, executionId, pausedOnly) {
706
+ if (message.role !== "assistant") return null;
707
+ for (const part of message.parts) {
708
+ if (part.state !== "output-available") continue;
709
+ if (typeof part.toolCallId !== "string") continue;
710
+ const output = part.output;
711
+ if (output != null && typeof output === "object" && (!pausedOnly || output.status === "paused") && output.executionId === executionId) return part.toolCallId;
712
+ }
713
+ return null;
714
+ }
715
+ /**
716
+ * A client that missed a pause's resolution resubmits its part still paused,
717
+ * and reconciliation protects server results only from pre-output client
718
+ * states. Keep the server's resolved part, and drop the pending-state text
719
+ * after it as the resolution did.
720
+ *
721
+ * Providers may reuse a toolCallId across turns, so the resolution is taken
722
+ * only from the server row the message reconciled to; a pause still pending
723
+ * there stays pending. A resolution on any other row can belong to another
724
+ * turn.
725
+ */
726
+ function keepResolvedPauses(incoming, serverMessages) {
727
+ const resolvedByMessage = /* @__PURE__ */ new Map();
728
+ for (const message of serverMessages) {
729
+ if (message.role !== "assistant") continue;
730
+ for (const part of message.parts) {
731
+ const record = part;
732
+ if (typeof record.toolCallId === "string" && (record.state === "output-available" || record.state === "output-error" || record.state === "output-denied") && !isPausedToolPart(record)) {
733
+ let own = resolvedByMessage.get(message.id);
734
+ if (!own) {
735
+ own = /* @__PURE__ */ new Map();
736
+ resolvedByMessage.set(message.id, own);
737
+ }
738
+ own.set(record.toolCallId, part);
739
+ }
740
+ }
741
+ }
742
+ if (resolvedByMessage.size === 0) return incoming;
743
+ return incoming.map((message) => {
744
+ if (message.role !== "assistant") return message;
745
+ const own = resolvedByMessage.get(message.id);
746
+ if (!own) return message;
747
+ const stale = /* @__PURE__ */ new Map();
748
+ for (const part of message.parts) {
749
+ const record = part;
750
+ if (typeof record.toolCallId !== "string" || !isPausedToolPart(record)) continue;
751
+ const server = own.get(record.toolCallId);
752
+ if (server) stale.set(record.toolCallId, server);
753
+ }
754
+ if (stale.size === 0) return message;
755
+ let parts = message.parts;
756
+ for (const [toolCallId, server] of stale) parts = dropGenerationAfterToolCall(parts.map((part) => "toolCallId" in part && part.toolCallId === toolCallId ? server : part), toolCallId);
757
+ return {
758
+ ...message,
759
+ parts
760
+ };
761
+ });
762
+ }
605
763
  const ACTION_PENDING_SWEEP_INTERVAL_MS = 3600 * 1e3;
606
764
  const ACTION_PENDING_LAST_SWEPT_KEY = "cf_think_action_pending_approvals:last_swept_at";
607
765
  /** Prefix for durable-pause action execution ids (vs codemode execution ids). */
@@ -671,6 +829,17 @@ function streamErrorToString(error) {
671
829
  }
672
830
  }
673
831
  /**
832
+ * A recovery continuation opens its own text and reasoning parts, and an end
833
+ * chunk only closes the newest part of its type, so a part the interruption
834
+ * left streaming would never be closed.
835
+ */
836
+ function settleInterruptedPart(part) {
837
+ return (part.type === "text" || part.type === "reasoning") && part.state === "streaming" ? {
838
+ ...part,
839
+ state: "done"
840
+ } : part;
841
+ }
842
+ /**
674
843
  * Normalizes the AI SDK tool-execution-finished event across major versions.
675
844
  *
676
845
  * Think registers a single `experimental_onToolCallFinish` callback, which is
@@ -1049,6 +1218,10 @@ function nextDeclaredScheduleTime(schedule, now, previousScheduledFor) {
1049
1218
  }
1050
1219
  throw new Error("Unable to compute next scheduled task occurrence");
1051
1220
  }
1221
+ function regenerationParentOf(snapshot) {
1222
+ const parentId = snapshot?.branchParentId;
1223
+ return typeof parentId === "string" ? parentId : void 0;
1224
+ }
1052
1225
  const CONTINUE_CHECKPOINT_PROMPT = "Continue your previous response from exactly where it left off. Do not repeat any of it.";
1053
1226
  /**
1054
1227
  * Ensure a model request does not end in an assistant message.
@@ -1069,6 +1242,40 @@ function ensureValidContinueCheckpoint(messages) {
1069
1242
  content: CONTINUE_CHECKPOINT_PROMPT
1070
1243
  }];
1071
1244
  }
1245
+ /**
1246
+ * Carry a context reminder (`ContextBlocks.reminder()`) after the cached
1247
+ * prefix without persisting it. It joins the final user message when there is
1248
+ * one, since not every provider accepts two user messages in a row. A request
1249
+ * ending in a partial assistant message gets the continue checkpoint here,
1250
+ * carrying the reminder, so `ensureValidContinueCheckpoint` adds nothing.
1251
+ */
1252
+ function withContextReminder(messages, reminder) {
1253
+ if (!reminder || messages.length === 0) return messages;
1254
+ const part = {
1255
+ type: "text",
1256
+ text: reminder
1257
+ };
1258
+ const lastIndex = messages.length - 1;
1259
+ const last = messages[lastIndex];
1260
+ if (last.role === "user") {
1261
+ const content = typeof last.content === "string" ? [{
1262
+ type: "text",
1263
+ text: last.content
1264
+ }, part] : [...last.content, part];
1265
+ return [...messages.slice(0, lastIndex), {
1266
+ ...last,
1267
+ content
1268
+ }];
1269
+ }
1270
+ const content = last.role === "assistant" ? [{
1271
+ type: "text",
1272
+ text: CONTINUE_CHECKPOINT_PROMPT
1273
+ }, part] : [part];
1274
+ return [...messages, {
1275
+ role: "user",
1276
+ content
1277
+ }];
1278
+ }
1072
1279
  const ACTION_BRAND = Symbol.for("cf.think.action");
1073
1280
  function action(config) {
1074
1281
  if (config.kind === "durable-pause" && config.approval === false) throw new Error(`Action "${config.name ?? "(anonymous)"}": kind "durable-pause" with approval: false never parks for approval, defeating the purpose. Use kind "server" for an inline action, or omit approval (or set a predicate) to gate when it parks.`);
@@ -1082,7 +1289,14 @@ function isAction(value) {
1082
1289
  return typeof value === "object" && value !== null && value[ACTION_BRAND] === true;
1083
1290
  }
1084
1291
  const admittedTurnContext = new AsyncLocalStorage();
1292
+ const messengerTurnContext = new AsyncLocalStorage();
1085
1293
  const recoveredTurnAcceptanceContext = new AsyncLocalStorage();
1294
+ function isTransientClassification(classification) {
1295
+ return classification === "transient" || classification === "rate_limit";
1296
+ }
1297
+ const continuationOutputContext = new AsyncLocalStorage();
1298
+ const waitTurnResultContext = new AsyncLocalStorage();
1299
+ const submissionStatusHookContext = new AsyncLocalStorage();
1086
1300
  const inferenceStreamFinalizers = /* @__PURE__ */ new WeakMap();
1087
1301
  const THINK_WORKFLOW_PROMPT_METADATA_KEY = "__thinkWorkflowPrompt";
1088
1302
  /** Queue callback that delivers one terminal-submission workflow event. */
@@ -1104,6 +1318,7 @@ const WORKFLOW_NOTIFICATION_MAX_BACKOFF_SECONDS = 600;
1104
1318
  const WORKFLOW_NOTIFICATION_GIVE_UP_MS = 720 * 60 * 1e3;
1105
1319
  /** Queue callback that runs one connection-less continuation turn. */
1106
1320
  const CONNECTIONLESS_CONTINUATION_CALLBACK = "_cfRunConnectionlessContinuation";
1321
+ const CONNECTIONLESS_CONTINUATION_QUEUE_ID = "connectionless-continuation";
1107
1322
  /** Queue callback that runs one media-eviction pass. */
1108
1323
  const MEDIA_EVICTION_CALLBACK = "_cfEvictAgedMedia";
1109
1324
  /** Queue callback that runs one pending submission. */
@@ -1128,6 +1343,31 @@ const cachedMessageEncoder = new TextEncoder();
1128
1343
  function cachedMessageBytes(message) {
1129
1344
  return cachedMessageEncoder.encode(JSON.stringify(message)).byteLength;
1130
1345
  }
1346
+ function reservedMetadataOf(message) {
1347
+ const metadata = message.metadata;
1348
+ if (typeof metadata !== "object" || metadata === null || Array.isArray(metadata)) return;
1349
+ const reserved = {};
1350
+ for (const key of RESERVED_MESSAGE_METADATA_KEYS) if (key in metadata) reserved[key] = metadata[key];
1351
+ return Object.keys(reserved).length > 0 ? reserved : void 0;
1352
+ }
1353
+ /**
1354
+ * `parts` without the text and reasoning that follow the part for
1355
+ * `toolCallId`, up to the end of the step that read its output: the rest of
1356
+ * the tool call's own step and the next one. Later steps answer other tool
1357
+ * results and are kept. Returns `parts` itself when nothing is dropped.
1358
+ */
1359
+ function dropGenerationAfterToolCall(parts, toolCallId) {
1360
+ const index = parts.findIndex((part) => "toolCallId" in part && part.toolCallId === toolCallId);
1361
+ if (index === -1) return parts;
1362
+ let end = parts.length;
1363
+ let stepStarts = 0;
1364
+ for (let i = index + 1; i < parts.length; i++) if (parts[i].type === "step-start" && ++stepStarts === 2) {
1365
+ end = i;
1366
+ break;
1367
+ }
1368
+ const kept = parts.filter((part, i) => i <= index || i >= end || part.type !== "text" && part.type !== "reasoning");
1369
+ return kept.length === parts.length ? parts : kept;
1370
+ }
1131
1371
  /**
1132
1372
  * The stored form of a client-sourced message's metadata: Sessions drops the
1133
1373
  * reserved keys on every client write, so a compare against a stored row has
@@ -1262,6 +1502,15 @@ function defaultContextOverflowClassifier(error) {
1262
1502
  * so the messenger runtime's recovery gate is unchanged.
1263
1503
  */
1264
1504
  const MESSENGER_REPLY_TASK_DEFINITION = "__cf_internal_messenger_reply";
1505
+ const declaredPrototypeMembers = /* @__PURE__ */ new WeakMap();
1506
+ function snapshotDeclaredMembers(prototype) {
1507
+ for (let current = prototype; current && current !== Think.prototype; current = Object.getPrototypeOf(current)) if (!declaredPrototypeMembers.has(current)) declaredPrototypeMembers.set(current, new Set(Reflect.ownKeys(current)));
1508
+ }
1509
+ function isMethodOverridden(instance, methodName) {
1510
+ if (Object.prototype.hasOwnProperty.call(instance, methodName)) return true;
1511
+ for (let current = Object.getPrototypeOf(instance); current && current !== Think.prototype; current = Object.getPrototypeOf(current)) if (declaredPrototypeMembers.get(current)?.has(methodName)) return true;
1512
+ return false;
1513
+ }
1265
1514
  var _contextBlocks = /* @__PURE__ */ new WeakMap();
1266
1515
  var _Think_brand = /* @__PURE__ */ new WeakSet();
1267
1516
  var _configCache = /* @__PURE__ */ new WeakMap();
@@ -1269,6 +1518,9 @@ var _configTableReady = /* @__PURE__ */ new WeakMap();
1269
1518
  var _configMemo = /* @__PURE__ */ new WeakMap();
1270
1519
  var _agentToolChildRunTableReady = /* @__PURE__ */ new WeakMap();
1271
1520
  var Think = class Think extends Agent {
1521
+ get _activeChatRecoveryOriginIds() {
1522
+ return this._chatRecoveryOriginIdsScope.getStore();
1523
+ }
1272
1524
  /**
1273
1525
  * The agent's context blocks. Available once the Lifecycle has started.
1274
1526
  */
@@ -1286,8 +1538,10 @@ var Think = class Think extends Agent {
1286
1538
  return [...this._onStartDegradations];
1287
1539
  }
1288
1540
  constructor(ctx, env) {
1541
+ snapshotDeclaredMembers(new.target.prototype);
1289
1542
  super(ctx, env);
1290
1543
  _classPrivateMethodInitSpec(this, _Think_brand);
1544
+ this._chatRecoveryOriginIdsScope = new AsyncLocalStorage();
1291
1545
  this.includeMcpTools = true;
1292
1546
  this.waitForMcpConnections = false;
1293
1547
  this.storeMessages = false;
@@ -1297,6 +1551,7 @@ var Think = class Think extends Agent {
1297
1551
  this._loggedSkillWarnings = /* @__PURE__ */ new Set();
1298
1552
  this._loggedProtocolWarnings = /* @__PURE__ */ new Set();
1299
1553
  this.messageConcurrency = "queue";
1554
+ this.messengerConcurrency = DEFAULT_MESSENGER_CONCURRENCY;
1300
1555
  this.hydrationByteBudget = 32 * 1024 * 1024;
1301
1556
  this.mediaEviction = true;
1302
1557
  this.chatRecovery = true;
@@ -1306,6 +1561,7 @@ var Think = class Think extends Agent {
1306
1561
  this._onStartDegradations = [];
1307
1562
  this.workspaceBash = true;
1308
1563
  this.fetchTools = false;
1564
+ this._repairApprovalRespondedThisTurn = false;
1309
1565
  this._mediaEvictionRunning = false;
1310
1566
  this._mediaEvictionPending = false;
1311
1567
  this._mediaEvictionAppendsDuringPass = 0;
@@ -1338,6 +1594,7 @@ var Think = class Think extends Agent {
1338
1594
  this._pendingInteractionPromise = null;
1339
1595
  this._interactionApplyTail = Promise.resolve();
1340
1596
  this._streamingAssistant = null;
1597
+ this._deferredResolvedPauses = /* @__PURE__ */ new Map();
1341
1598
  this._submitConcurrency = new SubmitConcurrencyController({ defaultDebounceMs: Think.MESSAGE_DEBOUNCE_MS });
1342
1599
  this._agentToolForwarders = /* @__PURE__ */ new Map();
1343
1600
  this._agentToolClosers = /* @__PURE__ */ new Map();
@@ -1345,18 +1602,23 @@ var Think = class Think extends Agent {
1345
1602
  this._agentToolLastErrors = /* @__PURE__ */ new Map();
1346
1603
  this._agentToolPreTurnAssistantIds = /* @__PURE__ */ new Map();
1347
1604
  this._agentToolLiveSequences = /* @__PURE__ */ new Map();
1605
+ this._agentToolTerminalOnlyRuns = /* @__PURE__ */ new Set();
1348
1606
  this._agentToolRunsByRequestId = /* @__PURE__ */ new Map();
1349
1607
  this._submissionTableEnsured = false;
1350
1608
  this._declaredScheduledTasksTableEnsured = false;
1609
+ this._warnedFacetScheduledTasksDisarmed = false;
1351
1610
  this._actionLedgerTableEnsured = false;
1352
1611
  this._actionPendingTableEnsured = false;
1353
1612
  this._submissionAbortControllers = /* @__PURE__ */ new Map();
1613
+ this._submissionsApplyingMessages = /* @__PURE__ */ new Set();
1354
1614
  this._programmaticStreamErrors = /* @__PURE__ */ new Map();
1355
1615
  _classPrivateFieldInitSpec(this, _configCache, null);
1356
1616
  _classPrivateFieldInitSpec(this, _configTableReady, false);
1357
1617
  _classPrivateFieldInitSpec(this, _configMemo, /* @__PURE__ */ new Map());
1618
+ this._liveChatRecoveryTurns = /* @__PURE__ */ new Map();
1358
1619
  this._liveChatTurnClosures = /* @__PURE__ */ new Map();
1359
1620
  this.maxSteps = 10;
1621
+ this.truncationStep = MODEL_TRUNCATION_STEP;
1360
1622
  this.actionLedgerRetention = {
1361
1623
  settledMs: 720 * 60 * 60 * 1e3,
1362
1624
  pendingMs: 2160 * 60 * 60 * 1e3,
@@ -1367,6 +1629,7 @@ var Think = class Think extends Agent {
1367
1629
  this.sendReasoning = true;
1368
1630
  this.chatStreamStallTimeoutMs = 0;
1369
1631
  this._turnModelMessageBaseline = 0;
1632
+ this._turnContextReminder = null;
1370
1633
  this._activeTurnTools = {};
1371
1634
  this._activeTurnActionMetadata = /* @__PURE__ */ new Map();
1372
1635
  this._activeTurnAuthorization = { allowed: true };
@@ -1379,9 +1642,21 @@ var Think = class Think extends Agent {
1379
1642
  this.hookTimeout = 5e3;
1380
1643
  _classPrivateFieldInitSpec(this, _agentToolChildRunTableReady, false);
1381
1644
  this._agentToolProgressEmitterInstance = null;
1645
+ this._submissionWaiters = /* @__PURE__ */ new Map();
1646
+ this._terminalStatusEmits = /* @__PURE__ */ new Set();
1647
+ this._waitersHeldForDeletedEmit = /* @__PURE__ */ new Map();
1382
1648
  this._persistedRequestContext = {};
1383
1649
  this._progressSeed = null;
1384
1650
  this._agentToolStreamProgress = new AgentToolStreamProgressThrottle();
1651
+ this._recoveryOwnedSubmissions = /* @__PURE__ */ new Set();
1652
+ this._deferringRecoveryIncidents = /* @__PURE__ */ new Set();
1653
+ this._rescheduledRecoveryIncidents = /* @__PURE__ */ new Set();
1654
+ this._flushResolvedPausesOnFinalize = false;
1655
+ this._responseHooksInFlight = /* @__PURE__ */ new Set();
1656
+ this._messengerRecoveryClaims = /* @__PURE__ */ new Set();
1657
+ this._settlingMessengerRecoveries = /* @__PURE__ */ new Set();
1658
+ this._messengerRecoveryDeliveries = /* @__PURE__ */ new Map();
1659
+ this._requestOriginMessageIds = /* @__PURE__ */ new Map();
1385
1660
  this.lifecycle.use(this.sessions);
1386
1661
  this.lifecycle.use(this.streams);
1387
1662
  this._registerChatTurnTaskDefinition();
@@ -1398,39 +1673,45 @@ var Think = class Think extends Agent {
1398
1673
  _classPrivateFieldSet2(_contextBlocks, this, new ContextBlocks([...await this.configureContext(), ...this.session.internal_takePendingContext()], this.session.internal_promptStore() ?? _assertClassBrand(_Think_brand, this, _contextProvider).call(this, "_system_prompt"), (label) => _assertClassBrand(_Think_brand, this, _contextProvider).call(this, label)));
1399
1674
  await _classPrivateFieldGet2(_contextBlocks, this).load();
1400
1675
  this._unsubscribeSessionChanges?.();
1401
- this._unsubscribeSessionChanges = this.sessions.subscribe(async (event) => {
1402
- if (event.sessionId !== this.session.sessionId) return;
1403
- switch (event.type) {
1404
- case "append":
1405
- if (!event.inserted || event.parentId !== void 0) await this._syncMessages();
1406
- else {
1407
- this._upsertCachedMessage(event.message);
1408
- this._noteCachedGrowth(cachedMessageBytes(event.message));
1409
- if (this._mediaEvictionFruitless) this._mediaEvictionFruitless.appendsSince++;
1410
- if (this._mediaEvictionRunning) this._mediaEvictionAppendsDuringPass++;
1411
- this._scheduleMediaEvictionPass();
1412
- }
1413
- break;
1414
- case "import":
1415
- this._cacheCoversActivePath = false;
1416
- break;
1417
- case "compaction":
1418
- await this._syncMessages();
1419
- break;
1420
- case "update":
1421
- if (this._cachedMessages.some((message) => message.id === event.message.id)) this._patchCachedMessage(event.message);
1422
- break;
1423
- case "clear":
1424
- this._replaceCachedMessages([]);
1425
- this._cacheCoversActivePath = true;
1426
- break;
1427
- case "delete":
1428
- await this._syncMessages();
1429
- break;
1430
- case "compact":
1431
- await this._syncMessages();
1432
- await _classPrivateFieldGet2(_contextBlocks, this)?.refreshSystemPrompt();
1433
- break;
1676
+ this._unsubscribeSessionChanges = this.sessions.session(this.session.sessionId).mirror({
1677
+ get: () => this._cachedMessages,
1678
+ set: (messages) => {
1679
+ this._replaceCachedMessages(messages);
1680
+ },
1681
+ transform: (message) => message,
1682
+ intercept: async (event) => {
1683
+ switch (event.type) {
1684
+ case "append":
1685
+ if (event.inserted && event.parentId === void 0) return false;
1686
+ await this._syncMessages();
1687
+ return true;
1688
+ case "import":
1689
+ this._cacheCoversActivePath = false;
1690
+ return true;
1691
+ case "clear":
1692
+ this._replaceCachedMessages([]);
1693
+ this._cacheCoversActivePath = true;
1694
+ return true;
1695
+ case "compaction":
1696
+ case "delete":
1697
+ await this._syncMessages();
1698
+ return true;
1699
+ case "compact":
1700
+ await this._syncMessages();
1701
+ await _classPrivateFieldGet2(_contextBlocks, this)?.refreshSystemPrompt();
1702
+ return true;
1703
+ default: return false;
1704
+ }
1705
+ },
1706
+ onApplied: (event, message, previous) => {
1707
+ if (event.type === "update") {
1708
+ if (previous) this._noteCachedReplacement(previous, message);
1709
+ return;
1710
+ }
1711
+ this._noteCachedGrowth(cachedMessageBytes(message));
1712
+ if (this._mediaEvictionFruitless) this._mediaEvictionFruitless.appendsSince++;
1713
+ if (this._mediaEvictionRunning) this._mediaEvictionAppendsDuringPass++;
1714
+ this._scheduleMediaEvictionPass();
1434
1715
  }
1435
1716
  });
1436
1717
  await this._initializeSkills();
@@ -1455,6 +1736,8 @@ var Think = class Think extends Agent {
1455
1736
  await this._sweepActionLedger();
1456
1737
  await this._sweepActionPendingApprovals();
1457
1738
  await this._migrateLegacyWorkflowNotifications();
1739
+ await this._replayPendingResponseHooks();
1740
+ await this._replayMessengerRecoveryDeliveries();
1458
1741
  await this._recoverSubmissionsOnStart();
1459
1742
  }, "Pending submissions / workflow notifications were not recovered on this wake; the next successful wake will recover them."));
1460
1743
  update({
@@ -1558,29 +1841,40 @@ var Think = class Think extends Agent {
1558
1841
  * the next one. A returned tool part MUST carry a settled result
1559
1842
  * (`output-available` / `output-error` / `output-denied` or an
1560
1843
  * `output`/`result` field); returning a non-tool part (e.g. text) is fine.
1844
+ *
1845
+ * It also receives an approved call that never ran (state still
1846
+ * `approval-responded`) once a later turn moves past it without a
1847
+ * continuation executing it.
1561
1848
  */
1562
1849
  repairInterruptedToolPart(part) {
1563
1850
  return {
1564
1851
  ...part,
1565
1852
  state: "output-error",
1566
- errorText: "The tool call was interrupted before a result was recorded."
1853
+ errorText: part.state === "approval-responded" ? "The tool call was approved but did not run before the next turn started." : "The tool call was interrupted before a result was recorded."
1567
1854
  };
1568
1855
  }
1569
- _repairToolTranscriptParts(messages) {
1856
+ async _mayRepairApprovalResponded(continuation) {
1857
+ if (continuation) return false;
1858
+ if (this._continuation.pending || this._continuation.deferred) return false;
1859
+ return await this.getQueue(CONNECTIONLESS_CONTINUATION_QUEUE_ID) === void 0;
1860
+ }
1861
+ _repairToolTranscriptParts(messages, options = {}) {
1570
1862
  return repairInterruptedToolParts(messages, {
1571
1863
  repairPart: (part) => this.repairInterruptedToolPart(part),
1572
1864
  isSettled: (record) => this._toolPartHasSettledResult(record),
1573
- normalizeInput: (input) => normalizeToolInput(input)
1865
+ normalizeInput: (input) => normalizeToolInput(input),
1866
+ repairApprovalResponded: options.repairApprovalResponded
1574
1867
  });
1575
1868
  }
1576
1869
  async _repairTranscriptForProvider(messages) {
1577
- const repair = this._repairToolTranscriptParts(messages);
1870
+ const repair = this._repairToolTranscriptParts(messages, { repairApprovalResponded: this._repairApprovalRespondedThisTurn });
1578
1871
  if (repair.removedToolCalls === 0 && repair.normalizedInputs === 0) return messages;
1579
1872
  for (const message of repair.messages) {
1580
1873
  const original = messages.find((candidate) => candidate.id === message.id);
1581
1874
  if (original && original.parts !== message.parts) await this.session.updateMessage(message);
1582
1875
  }
1583
- this._replaceCachedMessages(repair.messages);
1876
+ const repairedById = new Map(repair.messages.map((message) => [message.id, message]));
1877
+ this._replaceCachedMessages(this.messages.map((message) => repairedById.get(message.id) ?? message));
1584
1878
  this._broadcastMessages();
1585
1879
  this._emit("chat:transcript:repaired", {
1586
1880
  removedToolCalls: repair.removedToolCalls,
@@ -1651,7 +1945,7 @@ var Think = class Think extends Agent {
1651
1945
  if (this._agedRowsHiddenFromCache()) {
1652
1946
  const fruitless = this._mediaEvictionFruitless;
1653
1947
  if (fruitless !== null && this._lastHydration !== null && fruitless.storedBytes === this._lastHydration.totalContentBytes && fruitless.appendsSince < keepRecent) return;
1654
- } else if (!this._cachedMessages.slice(0, Math.max(0, this._cachedMessages.length - keepRecent)).some((message) => hasEvictableMedia(message, config.minPartBytes))) return;
1948
+ } else if (!this._cachedMessages.slice(0, mediaEvictionCutoff(this._cachedMessages.length, config.keepRecentMessages, this.truncationStep)).some((message) => hasEvictableMedia(message, config.minPartBytes))) return;
1655
1949
  this.queue(MEDIA_EVICTION_CALLBACK, void 0, { id: "media-eviction" }).catch((error) => {
1656
1950
  console.error("[Think] Failed to queue media eviction pass", error);
1657
1951
  });
@@ -1674,9 +1968,10 @@ var Think = class Think extends Agent {
1674
1968
  * once the rewritten row is stored, its Sessions attachment reference is
1675
1969
  * gone and the blob is reaped, so the bytes live in exactly one place.
1676
1970
  *
1677
- * The aged cutoff is `keepRecentMessages` clamped to at least
1678
- * `MODEL_RECENT_WINDOW`: messages the model still replays at full fidelity
1679
- * are never rewritten, whatever the configuration says.
1971
+ * The aged cutoff is {@link mediaEvictionCutoff}: the stepped truncation
1972
+ * cutoff, kept at least `keepRecentMessages` back. Messages the model still
1973
+ * replays at full fidelity are never rewritten, whatever the configuration
1974
+ * says, and the cutoff moves only once per truncation step.
1680
1975
  *
1681
1976
  * Best-effort: failures are logged and the next pass retries. When a pass
1682
1977
  * stops at `maxRowsPerPass` having made progress, the next one is scheduled
@@ -1705,8 +2000,7 @@ var Think = class Think extends Agent {
1705
2000
  return null;
1706
2001
  }
1707
2002
  const stats = await this.session.getHistoryRowStats();
1708
- const keepRecent = Math.max(config.keepRecentMessages, MODEL_RECENT_WINDOW);
1709
- const aged = stats.slice(0, Math.max(0, stats.length - keepRecent));
2003
+ const aged = stats.slice(0, mediaEvictionCutoff(stats.length, config.keepRecentMessages, this.truncationStep));
1710
2004
  let processed = 0;
1711
2005
  for (const row of aged) {
1712
2006
  if (row.bytes < config.minPartBytes) continue;
@@ -1817,24 +2111,22 @@ var Think = class Think extends Agent {
1817
2111
  this._scheduleMediaEvictionPass();
1818
2112
  return hydrated;
1819
2113
  }
1820
- /** Patch or append one message in the live cache after a durable write. */
1821
- _upsertCachedMessage(message) {
1822
- const index = this._cachedMessages.findIndex((m) => m.id === message.id);
1823
- if (index === -1) this._cachedMessages.push(message);
1824
- else this._cachedMessages[index] = message;
1825
- }
1826
- /**
1827
- * Patch a message that is already present in the live cache. An update
1828
- * that enlarges the message (a tool result landing on it) grows the cache
1829
- * exactly as an append does, so it is charged against the hydration
1830
- * budget the same way; and it may have put an inline payload on an aged
1831
- * row, so a fruitless eviction pass no longer stands.
1832
- */
2114
+ /** Patch a message that is already present in the live cache. */
1833
2115
  _patchCachedMessage(message) {
1834
2116
  const index = this._cachedMessages.findIndex((m) => m.id === message.id);
1835
2117
  if (index === -1) return;
1836
- const grew = cachedMessageBytes(message) - cachedMessageBytes(this._cachedMessages[index]);
2118
+ const previous = this._cachedMessages[index];
1837
2119
  this._cachedMessages[index] = message;
2120
+ this._noteCachedReplacement(previous, message);
2121
+ }
2122
+ /**
2123
+ * An update that enlarges a cached message (a tool result landing on it)
2124
+ * grows the cache exactly as an append does, so it is charged against the
2125
+ * hydration budget the same way; and it may have put an inline payload on
2126
+ * an aged row, so a fruitless eviction pass no longer stands.
2127
+ */
2128
+ _noteCachedReplacement(previous, next) {
2129
+ const grew = cachedMessageBytes(next) - cachedMessageBytes(previous);
1838
2130
  if (grew > 0) {
1839
2131
  this._noteCachedGrowth(grew);
1840
2132
  this._mediaEvictionFruitless = null;
@@ -1882,16 +2174,35 @@ var Think = class Think extends Agent {
1882
2174
  return (await this._syncMessages()).slice();
1883
2175
  }
1884
2176
  broadcast(msg, without) {
1885
- if (this._agentToolForwarders.size > 0 || this._agentToolLiveSequences.size > 0) interceptAgentToolBroadcast(msg, {
1886
- forwarders: this._agentToolForwarders,
1887
- liveSequences: this._agentToolLiveSequences,
1888
- lastErrors: this._agentToolLastErrors,
1889
- responseType: MSG_CHAT_RESPONSE,
1890
- runForRequest: (requestId) => this._agentToolRunForRequest(requestId)
1891
- });
2177
+ if (this._agentToolForwarders.size > 0 || this._agentToolLiveSequences.size > 0 || this._agentToolTerminalOnlyRuns.size > 0) {
2178
+ const chunkRunId = interceptAgentToolBroadcast(msg, {
2179
+ forwarders: this._agentToolForwarders,
2180
+ liveSequences: this._agentToolLiveSequences,
2181
+ lastErrors: this._agentToolLastErrors,
2182
+ onError: (runId, body) => this._recordAgentToolStreamError(runId, body),
2183
+ responseType: MSG_CHAT_RESPONSE,
2184
+ runForRequest: (requestId) => this._agentToolRunForRequest(requestId),
2185
+ terminalOnlyRuns: this._agentToolTerminalOnlyRuns
2186
+ });
2187
+ if (chunkRunId !== null && this._agentToolTerminalOnlyRuns.has(chunkRunId)) return;
2188
+ }
1892
2189
  super.broadcast(msg, without);
1893
2190
  }
1894
2191
  /**
2192
+ * Durably record a run's stream error on its still-open child-run row, so a
2193
+ * stale-row reconcile after an eviction (before the finalizer seals `error`)
2194
+ * still sees the failure. Leaves `status` to the finalizer / reconcile.
2195
+ */
2196
+ _recordAgentToolStreamError(runId, body) {
2197
+ try {
2198
+ this.sql`
2199
+ UPDATE cf_agent_tool_child_runs
2200
+ SET error_message = ${body}
2201
+ WHERE run_id = ${runId} AND completed_at IS NULL
2202
+ `;
2203
+ } catch {}
2204
+ }
2205
+ /**
1895
2206
  * Resolve the agent-tool run whose turn owns a request id, or null when the
1896
2207
  * request is not an agent-tool turn. Falls back to the persisted child-run
1897
2208
  * row (whose `request_id` is written when the run's turn is bound, see
@@ -1901,11 +2212,13 @@ var Think = class Think extends Agent {
1901
2212
  _agentToolRunForRequest(requestId) {
1902
2213
  const cached = this._agentToolRunsByRequestId.get(requestId);
1903
2214
  if (cached !== void 0) return cached;
1904
- const runId = this.sql`
1905
- SELECT run_id FROM cf_agent_tool_child_runs
2215
+ const rows = this.sql`
2216
+ SELECT run_id, event_delivery FROM cf_agent_tool_child_runs
1906
2217
  WHERE request_id = ${requestId} AND status IN ('starting', 'running')
1907
2218
  LIMIT 1
1908
- `[0]?.run_id ?? null;
2219
+ `;
2220
+ const runId = rows[0]?.run_id ?? null;
2221
+ if (runId && rows[0]?.event_delivery === "terminal") this._agentToolTerminalOnlyRuns.add(runId);
1909
2222
  this._agentToolRunsByRequestId.set(requestId, runId);
1910
2223
  return runId;
1911
2224
  }
@@ -1927,7 +2240,7 @@ var Think = class Think extends Agent {
1927
2240
  *
1928
2241
  * Safe to call on EVERY recovery continuation:
1929
2242
  * - Facets that never ran as an agent-tool child have no
1930
- * `cf_agent_tool_child_runs` table → the guarded SELECT throws → no-op.
2243
+ * `cf_agent_tool_child_runs` table → no-op (the table is not created).
1931
2244
  * - A facet whose run already settled has no `starting`/`running` row → no-op.
1932
2245
  * - A child DO is addressed by its `runId` (`subAgent(cls, runId)`), so it
1933
2246
  * owns AT MOST ONE child-run row for its whole lifetime and is never reused
@@ -1940,18 +2253,21 @@ var Think = class Think extends Agent {
1940
2253
  * invariant note there).
1941
2254
  */
1942
2255
  _rebindAgentToolChildRunRequestId(requestId) {
1943
- let runId;
1944
- try {
1945
- runId = this.sql`
1946
- SELECT run_id FROM cf_agent_tool_child_runs
1947
- WHERE status IN ('starting', 'running')
1948
- ORDER BY started_at DESC
1949
- LIMIT 1
1950
- `[0]?.run_id;
1951
- } catch {
1952
- return;
1953
- }
2256
+ if (this.sql`
2257
+ SELECT name FROM sqlite_master
2258
+ WHERE type = 'table' AND name = 'cf_agent_tool_child_runs'
2259
+ `.length === 0) return;
2260
+ this._ensureAgentToolChildRunTable();
2261
+ const rows = this.sql`
2262
+ SELECT run_id, event_delivery FROM cf_agent_tool_child_runs
2263
+ WHERE status IN ('starting', 'running')
2264
+ ORDER BY started_at DESC
2265
+ LIMIT 1
2266
+ `;
2267
+ const runId = rows[0]?.run_id;
2268
+ const terminalOnly = rows[0]?.event_delivery === "terminal";
1954
2269
  if (!runId) return;
2270
+ if (terminalOnly) this._agentToolTerminalOnlyRuns.add(runId);
1955
2271
  this._agentToolRunsByRequestId.set(requestId, runId);
1956
2272
  this.sql`
1957
2273
  UPDATE cf_agent_tool_child_runs
@@ -2107,6 +2423,22 @@ var Think = class Think extends Agent {
2107
2423
  return binding;
2108
2424
  }
2109
2425
  /**
2426
+ * Return AI Gateway options for a string model resolved by the default
2427
+ * provider. Called on every {@link resolveModel} call: once per turn for the
2428
+ * default model (skipped when `beforeTurn` returns its own `model` without
2429
+ * reading `ctx.model`), plus once for each string `model` override returned
2430
+ * from `beforeTurn` or `beforeStep`. It can read {@link activeTurn}, the
2431
+ * messenger context, or agent state. Use it to pick a gateway `id` and to
2432
+ * attach `metadata`, which AI Gateway records on the request log as
2433
+ * `cf-aig-metadata`. It must return synchronously; a returned Promise is
2434
+ * rejected with an error.
2435
+ *
2436
+ * Defaults to `undefined`: catalog slugs use the account's `default`
2437
+ * gateway, and `@cf/...` ids call Workers AI without a gateway. Not called
2438
+ * for a model that is already a `LanguageModel`.
2439
+ */
2440
+ getGateway(_model) {}
2441
+ /**
2110
2442
  * Resolve a model value into a concrete AI SDK `LanguageModel`.
2111
2443
  *
2112
2444
  * Defaults to resolving {@link getModel}. A `LanguageModel` is returned as-is;
@@ -2117,11 +2449,19 @@ var Think = class Think extends Agent {
2117
2449
  */
2118
2450
  resolveModel(model = this.getModel()) {
2119
2451
  if (typeof model !== "string") return model;
2452
+ const isWorkersAI = isWorkersAIModelId(model);
2453
+ const slash = model.indexOf("/");
2454
+ if (!isWorkersAI && (model.startsWith("@") || slash <= 0 || slash === model.length - 1)) throw new Error(`Invalid model id ${JSON.stringify(model)}. Use a Workers AI id (e.g. "@cf/moonshotai/kimi-k2.7-code") or a "<provider>/<model>" AI Gateway slug (e.g. "openai/gpt-5.5"), or return a LanguageModel.`);
2455
+ const gateway = this.getGateway(model);
2456
+ if (gateway !== null && typeof gateway === "object" && typeof gateway.then === "function") throw new Error(`getGateway() returned a Promise for model "${model}". It must return GatewayOptions (or undefined) synchronously; resolve any async lookup in beforeTurn and return the model from there instead.`);
2120
2457
  this._defaultProvider ??= createWorkersAI({
2121
2458
  binding: this.getAIBinding(),
2122
2459
  providers: [openai, anthropic]
2123
2460
  });
2124
- return model.startsWith("@cf/") ? this._defaultProvider(model, { sessionAffinity: this.sessionAffinity }) : this._defaultProvider(model);
2461
+ return isWorkersAI ? this._defaultProvider(model, {
2462
+ sessionAffinity: this.sessionAffinity,
2463
+ ...gateway && { gateway }
2464
+ }) : this._defaultProvider(model, gateway && { gateway });
2125
2465
  }
2126
2466
  /**
2127
2467
  * Return the fallback system prompt for the assistant.
@@ -2161,22 +2501,53 @@ var Think = class Think extends Agent {
2161
2501
  return {};
2162
2502
  }
2163
2503
  getMessengerContext() {
2164
- if (this._activeMessengerContext) return this._activeMessengerContext;
2504
+ const active = this._activeMessengerContext();
2505
+ if (active) return active;
2165
2506
  return this.messages.at(-1)?.metadata?.messenger;
2166
2507
  }
2508
+ _activeMessengerContext() {
2509
+ const store = messengerTurnContext.getStore();
2510
+ return store?.agent === this && !store.ended ? store.context : void 0;
2511
+ }
2167
2512
  async chatWithMessengerContext(userMessage, callback, context, options) {
2168
- const previous = this._activeMessengerContext;
2169
- this._activeMessengerContext = context;
2513
+ const store = {
2514
+ agent: this,
2515
+ context,
2516
+ ended: false
2517
+ };
2170
2518
  try {
2171
- await this.chat(userMessage, callback, {
2519
+ await messengerTurnContext.run(store, () => this.chat(userMessage, callback, {
2172
2520
  ...options,
2173
2521
  channel: context.messengerId
2174
- });
2522
+ }));
2175
2523
  } finally {
2176
- this._activeMessengerContext = previous;
2524
+ store.ended = true;
2177
2525
  }
2178
2526
  }
2179
2527
  /**
2528
+ * The turn currently running on this agent, readable from `beforeTurn`,
2529
+ * `beforeToolCall`, tool `execute`, `onChatResponse` and anything they call.
2530
+ * Undefined outside a turn, including from code a turn scheduled to run
2531
+ * later.
2532
+ */
2533
+ get activeTurn() {
2534
+ const turn = this._activeAdmittedTurn();
2535
+ if (!turn) return void 0;
2536
+ return {
2537
+ requestId: turn.requestId,
2538
+ trigger: turn.trigger,
2539
+ continuation: turn.continuation ?? false,
2540
+ ...turn.channel !== void 0 && { channel: turn.channel }
2541
+ };
2542
+ }
2543
+ /** The admitted-turn store of the turn running now, if the caller is in it. */
2544
+ _activeAdmittedTurn() {
2545
+ const turn = admittedTurnContext.getStore();
2546
+ if (!turn || turn.agent !== this) return void 0;
2547
+ if (this._turnQueue.activeRequestId !== turn.requestId) return void 0;
2548
+ return turn;
2549
+ }
2550
+ /**
2180
2551
  * Bind the live messenger delivery surface for the active turn so
2181
2552
  * `deliverNotice` can post to the originating channel while a messenger turn
2182
2553
  * is running. Returns a restore function; save/restore keeps nested turns
@@ -2192,9 +2563,13 @@ var Think = class Think extends Agent {
2192
2563
  /**
2193
2564
  * The channel context for the active turn, if the turn resolved to a channel.
2194
2565
  * Readable from tools/hooks during a turn (e.g. to branch on `kind`).
2566
+ * Undefined outside a turn, like {@link activeTurn} — including from work a
2567
+ * turn left behind that runs while a later turn holds another channel.
2195
2568
  */
2196
2569
  get activeChannel() {
2197
- return this._activeChannelContext;
2570
+ const turn = this._activeAdmittedTurn();
2571
+ const context = this._activeChannelContext;
2572
+ return turn && context?.channelId === turn.channel ? context : void 0;
2198
2573
  }
2199
2574
  /**
2200
2575
  * The server-supplied metadata stamped on the active turn's user message
@@ -2282,6 +2657,9 @@ var Think = class Think extends Agent {
2282
2657
  _channelFromLatestUserMessage() {
2283
2658
  return this._channelFromMessages(this.messages);
2284
2659
  }
2660
+ _channelForAutoContinuation() {
2661
+ return this._lastTurnChannel ? this._lastTurnChannel.channel : this._channelFromLatestUserMessage();
2662
+ }
2285
2663
  /**
2286
2664
  * Deliver a no-turn, channel-routed message — a deterministic status, fallback,
2287
2665
  * or notice — straight to the channel's delivery surface WITHOUT invoking the
@@ -2337,12 +2715,24 @@ var Think = class Think extends Agent {
2337
2715
  }
2338
2716
  }
2339
2717
  /**
2718
+ * Post a recovered messenger reply, or the interrupted apology, to a thread.
2719
+ * Called by a conversation sub-agent (or this agent) once chat recovery of
2720
+ * an interrupted messenger turn settles; only the host holds the messenger
2721
+ * runtime (#2106).
2722
+ *
2723
+ * @internal
2724
+ */
2725
+ async _cf_deliverRecoveredMessengerReply(input) {
2726
+ if (!this._messengerRuntime) throw new Error(`Cannot deliver a recovered reply for messenger "${input.messengerId}": this agent has no messenger runtime`);
2727
+ return this._messengerRuntime.deliverRecoveredReply(input);
2728
+ }
2729
+ /**
2340
2730
  * The active turn's channel id, if any. Prefers the turn-scoped channel
2341
2731
  * context, then the active messenger turn's id; web turns have none, so
2342
2732
  * `deliverNotice` defaults to `"web"`.
2343
2733
  */
2344
2734
  _activeChannelId() {
2345
- return this._activeChannelContext?.channelId ?? this._activeMessengerContext?.messengerId;
2735
+ return this.activeChannel?.channelId ?? this._activeMessengerContext()?.messengerId;
2346
2736
  }
2347
2737
  _noticeMessage(text, kind = "notice") {
2348
2738
  return {
@@ -2360,7 +2750,7 @@ var Think = class Think extends Agent {
2360
2750
  const { channels, messengers: messengerDefs } = resolveChannels(await this.configureChannels(), this.getMessengers());
2361
2751
  this._channels = channels;
2362
2752
  if (Object.keys(messengerDefs).length === 0) return;
2363
- this._messengerRuntime = new ThinkMessengerRuntime(messengerDefs, this);
2753
+ this._messengerRuntime = new ThinkMessengerRuntime(messengerDefs, this, { concurrency: this.messengerConcurrency });
2364
2754
  this._messengerRuntime.initialize();
2365
2755
  }
2366
2756
  /** Return code-declared scheduled tasks for this agent. */
@@ -2368,6 +2758,28 @@ var Think = class Think extends Agent {
2368
2758
  return {};
2369
2759
  }
2370
2760
  /**
2761
+ * Return which instances of this class arm the declared scheduled tasks.
2762
+ *
2763
+ * `"root"` (the default) arms them only on the top-level agent. Because
2764
+ * `getScheduledTasks()` is usually a static code declaration, it returns the
2765
+ * same tasks on every instance — so without this scope an agent that also
2766
+ * has sub-agents would arm one private copy per live facet and dispatch each
2767
+ * occurrence once per facet on top of the root (#1877).
2768
+ *
2769
+ * Return `"all"` to arm on facets as well. That is only correct when
2770
+ * `getScheduledTasks()` genuinely varies per facet (for example when it
2771
+ * reads per-facet state), since each facet then owns an independent
2772
+ * schedule.
2773
+ *
2774
+ * The value must be stable across wakes. Reporting `"root"` on a facet that
2775
+ * previously armed cancels its occurrences, so a scope that flickers with
2776
+ * request-scoped or not-yet-loaded state will repeatedly tear down and
2777
+ * re-create that facet's schedule.
2778
+ */
2779
+ getScheduledTasksScope() {
2780
+ return "root";
2781
+ }
2782
+ /**
2371
2783
  * Reconcile code-declared scheduled tasks immediately.
2372
2784
  * Static declarations are reconciled on startup automatically; call this
2373
2785
  * after changing app-owned data that `getScheduledTasks()` reads.
@@ -2460,9 +2872,12 @@ var Think = class Think extends Agent {
2460
2872
  createdAt,
2461
2873
  recoveryReason: "interrupted"
2462
2874
  };
2463
- await runtime.handleFiberRecovery(ctx, { persistRecoverySnapshot: async (snapshot) => {
2464
- await this.ctx.storage.put(persistKey, snapshot);
2465
- } });
2875
+ await runtime.handleFiberRecovery(ctx, {
2876
+ persistRecoverySnapshot: async (snapshot) => {
2877
+ await this.ctx.storage.put(persistKey, snapshot);
2878
+ },
2879
+ retriesAfter: (error) => isPlatformTransientError(error) || isDurableObjectMemoryLimitReset(error) || isDurableObjectCodeUpdateReset(error)
2880
+ });
2466
2881
  await this.ctx.storage.delete(persistKey);
2467
2882
  return;
2468
2883
  }
@@ -2491,17 +2906,36 @@ var Think = class Think extends Agent {
2491
2906
  metadata: input.metadata
2492
2907
  })).accepted };
2493
2908
  }
2494
- async _runChatRecoveryFiber(requestId, continuation, fn) {
2495
- const snapshot = createChatFiberSnapshot({
2496
- kind: "think-chat-turn",
2497
- requestId,
2498
- recoveryRootRequestId: this._activeChatRecoveryRootRequestId ?? requestId,
2499
- continuation,
2500
- messages: this.messages,
2501
- lastBody: this._lastBody,
2502
- lastClientTools: this._lastClientTools
2503
- });
2504
- const wrap = (data) => wrapChatFiberSnapshot("__cfThinkChatFiberSnapshot", snapshot, data);
2909
+ async _runChatRecoveryFiber(requestId, continuation, fn, branchParentId) {
2910
+ const snapshot = {
2911
+ ...createChatFiberSnapshot({
2912
+ kind: "think-chat-turn",
2913
+ requestId,
2914
+ recoveryRootRequestId: this._activeChatRecoveryRootRequestId ?? requestId,
2915
+ continuation,
2916
+ messages: this.messages,
2917
+ lastBody: this._lastBody,
2918
+ lastClientTools: this._lastClientTools,
2919
+ originMessageIds: this._originMessageIdsFor(requestId)
2920
+ }),
2921
+ ...branchParentId !== void 0 && { branchParentId }
2922
+ };
2923
+ const liveTurn = {
2924
+ createdAt: Date.now(),
2925
+ recoveryData: null
2926
+ };
2927
+ const wrap = (data) => {
2928
+ liveTurn.recoveryData = data;
2929
+ return wrapChatFiberSnapshot("__cfThinkChatFiberSnapshot", snapshot, data);
2930
+ };
2931
+ this._liveChatRecoveryTurns.set(requestId, liveTurn);
2932
+ try {
2933
+ return await this._runWrappedChatRecoveryFiber(requestId, continuation, wrap, fn);
2934
+ } finally {
2935
+ if (this._liveChatRecoveryTurns.get(requestId) === liveTurn) this._liveChatRecoveryTurns.delete(requestId);
2936
+ }
2937
+ }
2938
+ async _runWrappedChatRecoveryFiber(requestId, continuation, wrap, fn) {
2505
2939
  const acceptance = recoveredTurnAcceptanceContext.getStore();
2506
2940
  const onAccepted = acceptance?.agent === this ? acceptance.onAccepted : void 0;
2507
2941
  if (this.parentPath.length > 0) return this._runFiberWithStashWrapper(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
@@ -2659,7 +3093,7 @@ var Think = class Think extends Agent {
2659
3093
  try {
2660
3094
  const sources = await this.getSkills();
2661
3095
  if (sources.length === 0) return;
2662
- if (this.getSystemPrompt !== Think.prototype.getSystemPrompt) {
3096
+ if (isMethodOverridden(this, "getSystemPrompt")) {
2663
3097
  const warning = "getSystemPrompt() is only used as a fallback when no context blocks are configured. getSkills() registers a skills context block, so move always-on instructions into configureContext() instead.";
2664
3098
  if (!this._loggedSkillWarnings.has(warning)) {
2665
3099
  this._loggedSkillWarnings.add(warning);
@@ -2971,15 +3405,16 @@ var Think = class Think extends Agent {
2971
3405
  * knowledge into core. The app does know its provider/model, so it owns the
2972
3406
  * mapping — the same split Think already uses for `tokenCounter`.
2973
3407
  *
2974
- * Currently this hook drives **only** context-overflow recovery: it is
2975
- * consulted when a turn errors **and** `contextOverflow.reactive` is enabled
2976
- * (if reactive is off, it is not called). Return `"context_overflow"` to run
2977
- * the compact-and-retry backstop; if recovery cannot save the turn, that
2978
- * classification is surfaced on the terminal `onChatError` call via
2979
- * {@link ChatErrorContext.classification}. The other categories are reserved
2980
- * for future use — returning one today is a no-op (the turn terminalizes as
2981
- * usual) and it is **not** forwarded to `onChatError`. Returning
2982
- * `void`/`"unknown"` keeps the existing terminal behavior.
3408
+ * Think consults it when a turn's stream errors. Return `"context_overflow"`
3409
+ * to run the compact-and-retry backstop (only when `contextOverflow.reactive`
3410
+ * is enabled); if recovery cannot save the turn, that classification is
3411
+ * surfaced on the terminal `onChatError` call via
3412
+ * {@link ChatErrorContext.classification}. Return `"transient"` or
3413
+ * `"rate_limit"` to route the turn into bounded chat recovery (the same path
3414
+ * as a stream stall: `onChatRecovery`, `chatRecovery.maxAttempts`, then the
3415
+ * exhaustion message), with the continuation delayed by exponential backoff.
3416
+ * Returning `void`, `"fatal"`, or `"unknown"` keeps the existing terminal
3417
+ * behavior.
2983
3418
  *
2984
3419
  * The argument may be an `Error`, an AI SDK `APICallError` (with
2985
3420
  * `statusCode`/`responseBody`), or — for in-stream provider errors that
@@ -3003,33 +3438,59 @@ var Think = class Think extends Agent {
3003
3438
  */
3004
3439
  classifyChatError(_error, _ctx) {}
3005
3440
  /**
3006
- * Whether an error (thrown or surfaced as an in-stream error string) should
3007
- * trigger the opt-in compact-and-retry backstop. Consults the app's
3008
- * `classifyChatError` and the `contextOverflow.reactive` flag. Centralized
3009
- * so both stream consumers (WebSocket + RPC) classify identically.
3441
+ * The app's `classifyChatError` verdict for a stream error (thrown or
3442
+ * surfaced as an in-stream error string). Call once per error: the hook may
3443
+ * be stateful or have side effects.
3444
+ */
3445
+ _classifyStreamError(error, requestId) {
3446
+ if (!isMethodOverridden(this, "classifyChatError")) return void 0;
3447
+ try {
3448
+ return this.classifyChatError(error, {
3449
+ stage: "stream",
3450
+ requestId
3451
+ }) ?? void 0;
3452
+ } catch (err) {
3453
+ console.warn(`[Think] classifyChatError threw; treating as unclassified: ${err instanceof Error ? err.message : String(err)}`);
3454
+ return;
3455
+ }
3456
+ }
3457
+ /**
3458
+ * Whether a classified stream error should trigger the opt-in
3459
+ * compact-and-retry backstop. Centralized so both stream consumers
3460
+ * (WebSocket + RPC) decide identically.
3010
3461
  */
3011
- _isRecoverableContextOverflow(error, requestId) {
3462
+ _isRecoverableContextOverflow(classification) {
3012
3463
  if (!this._overflowReactiveEnabled) return false;
3013
- if (this.classifyChatError === Think.prototype.classifyChatError) {
3464
+ if (!isMethodOverridden(this, "classifyChatError")) {
3014
3465
  if (!this._warnedMissingClassifier) {
3015
3466
  this._warnedMissingClassifier = true;
3016
3467
  console.warn("[Think] contextOverflow.reactive is enabled but classifyChatError() is not overridden, so no error will ever be treated as a context overflow and recovery will never run. Override classifyChatError() (or assign the exported defaultContextOverflowClassifier) to return \"context_overflow\" for your provider's context-window error (e.g. Anthropic \"prompt is too long\", OpenAI context_length_exceeded).");
3017
3468
  }
3018
3469
  return false;
3019
3470
  }
3020
- let classification;
3021
- try {
3022
- classification = this.classifyChatError(error, {
3023
- stage: "stream",
3024
- requestId
3025
- });
3026
- } catch (err) {
3027
- console.warn(`[Think] classifyChatError threw; treating as non-overflow: ${err instanceof Error ? err.message : String(err)}`);
3028
- return false;
3029
- }
3030
3471
  return classification === "context_overflow";
3031
3472
  }
3032
3473
  /**
3474
+ * The `"transient"` or `"rate_limit"` class the app assigned a stream
3475
+ * error, else `undefined`. Such errors route into bounded chat recovery like
3476
+ * a stream stall instead of terminalizing the turn (#2085). Without a
3477
+ * `classifyChatError` override nothing is transient, so today's terminal
3478
+ * behavior is unchanged. A Durable Object reset is never transient here: the
3479
+ * restart's own recovery owns the turn.
3480
+ */
3481
+ _transientStreamClassification(error, requestId) {
3482
+ if (error instanceof TransientChatStreamError) return error.classification;
3483
+ if (error instanceof ChatStreamStalledError) return void 0;
3484
+ if (isDurableObjectResetError(error)) return void 0;
3485
+ const classification = this._classifyStreamError(error, requestId);
3486
+ return isTransientClassification(classification) ? classification : void 0;
3487
+ }
3488
+ /** The provider `Retry-After` to honor for a rate-limited stream error. */
3489
+ _streamErrorRetryAfter(error, classification) {
3490
+ if (classification !== "rate_limit") return void 0;
3491
+ return retryAfterSeconds(error instanceof TransientChatStreamError ? error.original : error);
3492
+ }
3493
+ /**
3033
3494
  * Compact the session in response to a context overflow (reactive backstop or
3034
3495
  * proactive guard). Returns whether history was actually shortened — a no-op
3035
3496
  * compaction (returns `null`) means a retry would just overflow again, so the
@@ -3040,7 +3501,7 @@ var Think = class Think extends Agent {
3040
3501
  */
3041
3502
  async _compactForContextOverflow(reason, extra) {
3042
3503
  try {
3043
- const result = await this.session.compact();
3504
+ const result = await this.session.compact(this._turnHistoryLeafId);
3044
3505
  const shortened = Boolean(result);
3045
3506
  this._emit("chat:context:compacted", {
3046
3507
  reason,
@@ -3115,6 +3576,22 @@ var Think = class Think extends Agent {
3115
3576
  });
3116
3577
  }
3117
3578
  /**
3579
+ * The repaired history the current turn's model request is built from: the
3580
+ * active path, cut at `_turnHistoryLeafId` when one is set. A leaf off the
3581
+ * cached path (another branch, or outside a windowed cache) is read from
3582
+ * storage. The cut comes before repair so messages past the leaf, which the
3583
+ * request never sees, are not rewritten.
3584
+ */
3585
+ async _turnHistory() {
3586
+ const leafId = this._turnHistoryLeafId;
3587
+ if (leafId === void 0) return this._repairTranscriptForProvider(this.messages);
3588
+ const cut = this.messages.findIndex((message) => message.id === leafId);
3589
+ if (cut >= 0) return this._repairTranscriptForProvider(this.messages.slice(0, cut + 1));
3590
+ const budget = this.hydrationByteBudget;
3591
+ const path = Number.isFinite(budget) && budget > 0 ? (await this.session.getRecentHistory(budget, { leafId })).messages : await this.session.getHistory({ leafId });
3592
+ return this._repairTranscriptForProvider(path);
3593
+ }
3594
+ /**
3118
3595
  * Assemble provider-ready model messages from the current session history:
3119
3596
  * repair the transcript, truncate older messages, drop any still-incomplete
3120
3597
  * tool calls, and convert to `ModelMessage[]`. Shared by the turn entry point
@@ -3122,7 +3599,12 @@ var Think = class Think extends Agent {
3122
3599
  * head through the exact same pipeline.
3123
3600
  */
3124
3601
  async _assembleModelMessages(tools) {
3125
- const truncated = truncateOlderMessages((await this._repairTranscriptForProvider(this.messages)).map(toProviderSafeExecutionOutcomeMessage));
3602
+ const providerSafeHistory = (await this._turnHistory()).map(toProviderSafeExecutionOutcomeMessage);
3603
+ const keepRecent = truncationKeepRecent(providerSafeHistory.length, this.truncationStep);
3604
+ const truncated = truncateOlderMessages(providerSafeHistory, {
3605
+ keepRecent,
3606
+ toolOutputs: false
3607
+ });
3126
3608
  const incompleteAfterRepair = this._incompleteToolCallIds(truncated);
3127
3609
  if (incompleteAfterRepair.length > 0) {
3128
3610
  console.warn(`[Think] ${incompleteAfterRepair.length} incomplete tool call(s) survived transcript repair and will be dropped by ignoreIncompleteToolCalls: ${incompleteAfterRepair.join(", ")}. This indicates a gap in _repairToolTranscriptParts.`);
@@ -3132,10 +3614,10 @@ var Think = class Think extends Agent {
3132
3614
  toolCallIds: incompleteAfterRepair
3133
3615
  });
3134
3616
  }
3135
- return convertToModelMessages(truncated, {
3617
+ return truncateOlderToolResults(await convertToModelMessages(truncated, {
3136
3618
  tools,
3137
3619
  ignoreIncompleteToolCalls: true
3138
- });
3620
+ }), truncated, { keepRecent });
3139
3621
  }
3140
3622
  /**
3141
3623
  * Proactive context guard (Layer 1). Runs before each step from the
@@ -3167,7 +3649,7 @@ var Think = class Think extends Agent {
3167
3649
  try {
3168
3650
  this._proactiveCompactionsThisRun++;
3169
3651
  if (!await this._compactForContextOverflow("proactive")) return void 0;
3170
- const head = await this._assembleModelMessages(this._activeTurnTools);
3652
+ const head = withContextReminder(await this._assembleModelMessages(this._activeTurnTools), this._turnContextReminder);
3171
3653
  const tail = event.messages.slice(this._turnModelMessageBaseline);
3172
3654
  const merged = [...head, ...tail];
3173
3655
  this._turnModelMessageBaseline = head.length;
@@ -3261,11 +3743,13 @@ var Think = class Think extends Agent {
3261
3743
  /**
3262
3744
  * The single convergence point for all chat turn entry paths.
3263
3745
  * Merges tools, assembles context, fires lifecycle hooks, wraps tools
3264
- * for interception, and calls streamText.
3746
+ * for interception, and calls streamText. `historyLeafId` cuts the model
3747
+ * history at that message (see `_turnHistoryLeafId`).
3265
3748
  */
3266
- async _runInferenceLoop(input) {
3749
+ async _runInferenceLoop(input, historyLeafId) {
3267
3750
  const turn = admittedTurnContext.getStore();
3268
- return (await withAgentSpan(this, "prepare_agent", "turn", {
3751
+ const active = this._activeAdmittedTurn();
3752
+ const result = (await withAgentSpan(this, "prepare_agent", "turn", {
3269
3753
  "cloudflare.agents.component": "think",
3270
3754
  ...turn?.agent === this ? {
3271
3755
  "cloudflare.agents.turn.request_id": turn.requestId,
@@ -3275,14 +3759,19 @@ var Think = class Think extends Agent {
3275
3759
  "cloudflare.agents.turn.continuation": turn.continuation,
3276
3760
  "cloudflare.agents.turn.generation": turn.generation
3277
3761
  } : {}
3278
- }, () => this._prepareInferenceInvocation(input)))();
3762
+ }, () => this._prepareInferenceInvocation(input, historyLeafId)))();
3763
+ if (active) this._lastTurnChannel = { channel: active.channel };
3764
+ return result;
3279
3765
  }
3280
- async _prepareInferenceInvocation(input) {
3766
+ async _prepareInferenceInvocation(input, historyLeafId) {
3767
+ this._turnHistoryLeafId = historyLeafId;
3768
+ await this._flushDeferredResolvedPauses();
3281
3769
  const includeMcpTools = this.includeMcpTools;
3282
3770
  this._activeStallTimeoutMs = void 0;
3283
3771
  this._activeTurnAuthorization = { allowed: true };
3284
3772
  this._activeTurnApprovedActionInputs = this._approvedActionInputsFromTranscript();
3285
3773
  this._proactiveCompactionsThisRun = 0;
3774
+ this._repairApprovalRespondedThisTurn = await this._mayRepairApprovalResponded(input.continuation);
3286
3775
  if (this.waitForMcpConnections) {
3287
3776
  const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : 1e4;
3288
3777
  await this.mcp.waitForConnections({ timeout });
@@ -3320,23 +3809,35 @@ var Think = class Think extends Agent {
3320
3809
  const rawBaseSystem = await this.context.freezeSystemPrompt() || this.getSystemPrompt();
3321
3810
  const baseSystem = channelInstructions ? `${channelInstructions}\n\n${rawBaseSystem}` : rawBaseSystem;
3322
3811
  const system = this._systemPromptForTurn(baseSystem, tools);
3323
- const messages = await this._assembleModelMessages(tools);
3812
+ this._turnContextReminder = await this.context.reminder();
3813
+ const messages = withContextReminder(await this._assembleModelMessages(tools), this._turnContextReminder);
3324
3814
  if (messages.length === 0) throw new Error("No messages to send to the model. This usually means the chat request arrived before any messages were persisted.");
3325
- const model = this.resolveModel();
3815
+ let defaultModel;
3816
+ const resolveDefaultModel = () => defaultModel ??= this.resolveModel();
3817
+ const turn = this.activeTurn;
3818
+ const messenger = this._activeMessengerContext();
3326
3819
  const ctx = {
3327
3820
  system,
3328
3821
  messages,
3329
3822
  tools,
3330
- model,
3823
+ get model() {
3824
+ return resolveDefaultModel();
3825
+ },
3331
3826
  continuation: input.continuation,
3332
- body: input.body
3827
+ body: input.body,
3828
+ ...turn && {
3829
+ requestId: turn.requestId,
3830
+ trigger: turn.trigger
3831
+ },
3832
+ ...input.signal && { abortSignal: input.signal },
3833
+ ...messenger && { messenger }
3333
3834
  };
3334
3835
  const subclassConfig = await this.beforeTurn(ctx) ?? {};
3335
3836
  const config = await this._pipelineExtensionBeforeTurn(ctx, subclassConfig);
3336
3837
  const workflowPrompt = input.workflowPrompt;
3337
3838
  const structuredOutputSchema = workflowPrompt?.output ? jsonSchema(workflowPrompt.output.schema) : void 0;
3338
3839
  const wantsStructuredOutput = structuredOutputSchema !== void 0;
3339
- const finalModel = config.model != null ? this.resolveModel(config.model) : model;
3840
+ const finalModel = config.model != null ? this.resolveModel(config.model) : resolveDefaultModel();
3340
3841
  const finalSystem = config.instructions ?? config.system ?? this._systemPromptForTurn(baseSystem, config.tools ? {
3341
3842
  ...tools,
3342
3843
  ...config.tools
@@ -3347,7 +3848,7 @@ var Think = class Think extends Agent {
3347
3848
  ...config.tools
3348
3849
  } : tools;
3349
3850
  const finalTurnContext = {
3350
- ...ctx,
3851
+ ...turnContextWithoutModel(ctx),
3351
3852
  system: finalSystem,
3352
3853
  messages: finalMessages,
3353
3854
  tools: mergedTools,
@@ -3369,6 +3870,12 @@ var Think = class Think extends Agent {
3369
3870
  this._activeTurnTools = mergedTools;
3370
3871
  const finalMaxSteps = config.maxSteps ?? channelDefinition?.maxTurns ?? this.maxSteps;
3371
3872
  const finalSendReasoning = config.sendReasoning ?? this.sendReasoning;
3873
+ const metadataWriter = config.messageMetadata ?? this.messageMetadata;
3874
+ const continuation = input.continuation ?? false;
3875
+ const finalMessageMetadata = metadataWriter && ((options) => metadataWriter({
3876
+ ...options,
3877
+ continuation
3878
+ }));
3372
3879
  this._activeStallTimeoutMs = config.chatStreamStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
3373
3880
  const finalOutput = config.output;
3374
3881
  const turnSystem = wantsStructuredOutput ? [finalSystem, thinkFinalAnswerInstruction(finalAnswerToolName)].filter(Boolean).join("\n\n") : finalSystem;
@@ -3447,12 +3954,14 @@ var Think = class Think extends Agent {
3447
3954
  const e = normalizeToolFinishEvent(event);
3448
3955
  if (e.toolCall.toolName === finalAnswerToolName) return;
3449
3956
  const { success, output, error } = e;
3957
+ const requestId = this.activeTurn?.requestId;
3450
3958
  const base = {
3451
3959
  ...e.toolCall,
3452
3960
  stepNumber: e.stepNumber,
3453
3961
  messages: e.messages,
3454
3962
  toolExecutionMs: e.toolExecutionMs,
3455
- durationMs: e.toolExecutionMs
3963
+ durationMs: e.toolExecutionMs,
3964
+ ...requestId !== void 0 && { requestId }
3456
3965
  };
3457
3966
  const ctx = success ? {
3458
3967
  ...base,
@@ -3501,7 +4010,7 @@ var Think = class Think extends Agent {
3501
4010
  const last = finalCalls[finalCalls.length - 1];
3502
4011
  if (!last) throw new Error(`Model ended the turn without calling the ${finalAnswerToolName} tool`);
3503
4012
  return last.input;
3504
- }) : finalOutput && result.output ? Promise.resolve(result.output) : void 0;
4013
+ }) : finalOutput ? Promise.resolve(result.output) : void 0;
3505
4014
  if (outputPromise) outputPromise.catch(() => {});
3506
4015
  const streamResult = {
3507
4016
  toUIMessageStream: (options) => {
@@ -3509,7 +4018,8 @@ var Think = class Think extends Agent {
3509
4018
  const onError = options?.onError ?? streamErrorToString;
3510
4019
  return readableStreamToAsyncIterable(result.toUIMessageStream({
3511
4020
  sendReasoning,
3512
- onError
4021
+ onError,
4022
+ messageMetadata: finalMessageMetadata
3513
4023
  }));
3514
4024
  },
3515
4025
  output: outputPromise
@@ -3903,8 +4413,8 @@ var Think = class Think extends Agent {
3903
4413
  if (!this.extensionManager) return subclassConfig;
3904
4414
  const subscribers = this.extensionManager.getHookSubscribers("beforeTurn");
3905
4415
  if (subscribers.length === 0) return subclassConfig;
3906
- const { createTurnContextSnapshot, parseHookResult } = await import("./hook-proxy-Dogs9wbj.js");
3907
- let snapshot = createTurnContextSnapshot(ctx);
4416
+ const { createTurnContextSnapshot, parseHookResult } = await import("./hook-proxy-DY2sBNa0.js");
4417
+ let snapshot = createTurnContextSnapshot(ctx, subclassConfig.model ?? void 0);
3908
4418
  let accumulated = { ...subclassConfig };
3909
4419
  if (accumulated.system !== void 0) snapshot.system = accumulated.system;
3910
4420
  if (accumulated.maxSteps !== void 0) snapshot.messageCount = ctx.messages.length;
@@ -4080,11 +4590,13 @@ var Think = class Think extends Agent {
4080
4590
  input,
4081
4591
  ...isDynamic ? { dynamic: true } : {}
4082
4592
  };
4593
+ const requestId = this.activeTurn?.requestId;
4083
4594
  const ctx = {
4084
4595
  ...toolCallBase,
4085
4596
  stepNumber: void 0,
4086
4597
  messages: options.messages,
4087
- abortSignal: options.abortSignal
4598
+ abortSignal: options.abortSignal,
4599
+ ...requestId !== void 0 && { requestId }
4088
4600
  };
4089
4601
  const decision = await this.beforeToolCall(ctx);
4090
4602
  const dispatchInput = decision && decision.action === "allow" && decision.input ? decision.input : input;
@@ -4119,34 +4631,37 @@ var Think = class Think extends Agent {
4119
4631
  async _pipelineExtensionToolCallStart(event) {
4120
4632
  if (!this.extensionManager) return;
4121
4633
  if (this.extensionManager.getHookSubscribers("beforeToolCall").length === 0) return;
4122
- const { createToolCallStartSnapshot } = await import("./hook-proxy-Dogs9wbj.js");
4634
+ const { createToolCallStartSnapshot } = await import("./hook-proxy-DY2sBNa0.js");
4123
4635
  await this._dispatchExtensionObservation("beforeToolCall", createToolCallStartSnapshot(event));
4124
4636
  }
4125
4637
  async _pipelineExtensionToolCallFinish(event) {
4126
4638
  if (!this.extensionManager) return;
4127
4639
  if (this.extensionManager.getHookSubscribers("afterToolCall").length === 0) return;
4128
- const { createToolCallFinishSnapshot } = await import("./hook-proxy-Dogs9wbj.js");
4640
+ const { createToolCallFinishSnapshot } = await import("./hook-proxy-DY2sBNa0.js");
4129
4641
  await this._dispatchExtensionObservation("afterToolCall", createToolCallFinishSnapshot(event));
4130
4642
  }
4131
4643
  async _pipelineExtensionStepFinish(event) {
4132
4644
  if (!this.extensionManager) return;
4133
4645
  if (this.extensionManager.getHookSubscribers("onStepFinish").length === 0) return;
4134
- const { createStepFinishSnapshot } = await import("./hook-proxy-Dogs9wbj.js");
4646
+ const { createStepFinishSnapshot } = await import("./hook-proxy-DY2sBNa0.js");
4135
4647
  await this._dispatchExtensionObservation("onStepFinish", createStepFinishSnapshot(event));
4136
4648
  }
4137
4649
  async _pipelineExtensionChunk(event) {
4138
4650
  if (!this.extensionManager) return;
4139
4651
  if (this.extensionManager.getHookSubscribers("onChunk").length === 0) return;
4140
- const { createChunkSnapshot } = await import("./hook-proxy-Dogs9wbj.js");
4652
+ const { createChunkSnapshot } = await import("./hook-proxy-DY2sBNa0.js");
4141
4653
  await this._dispatchExtensionObservation("onChunk", createChunkSnapshot(event));
4142
4654
  }
4143
4655
  async _hostReadFile(path) {
4656
+ await this.__unsafe_ensureInitialized();
4144
4657
  return await this.workspace.readFile(path) ?? null;
4145
4658
  }
4146
4659
  async _hostWriteFile(path, content) {
4660
+ await this.__unsafe_ensureInitialized();
4147
4661
  await this.workspace.writeFile(path, content);
4148
4662
  }
4149
4663
  async _hostDeleteFile(path) {
4664
+ await this.__unsafe_ensureInitialized();
4150
4665
  try {
4151
4666
  await this.workspace.rm(path);
4152
4667
  return true;
@@ -4155,6 +4670,7 @@ var Think = class Think extends Agent {
4155
4670
  }
4156
4671
  }
4157
4672
  async _hostListFiles(dir) {
4673
+ await this.__unsafe_ensureInitialized();
4158
4674
  return (await this.workspace.readDir(dir)).map((e) => ({
4159
4675
  name: e.name,
4160
4676
  type: e.type,
@@ -4163,12 +4679,15 @@ var Think = class Think extends Agent {
4163
4679
  }));
4164
4680
  }
4165
4681
  async _hostGetContext(label) {
4682
+ await this.__unsafe_ensureInitialized();
4166
4683
  return this.context.getBlock(label)?.content ?? null;
4167
4684
  }
4168
4685
  async _hostSetContext(label, content) {
4686
+ await this.__unsafe_ensureInitialized();
4169
4687
  await this.context.setBlock(label, content);
4170
4688
  }
4171
4689
  async _hostGetMessages(limit) {
4690
+ await this.__unsafe_ensureInitialized();
4172
4691
  const history = this.messages;
4173
4692
  return (limit !== void 0 && limit !== null ? limit <= 0 ? [] : history.slice(-limit) : history).map((m) => ({
4174
4693
  id: m.id,
@@ -4177,6 +4696,7 @@ var Think = class Think extends Agent {
4177
4696
  }));
4178
4697
  }
4179
4698
  async _hostSendMessage(content) {
4699
+ await this.__unsafe_ensureInitialized();
4180
4700
  const msg = {
4181
4701
  id: crypto.randomUUID(),
4182
4702
  role: "user",
@@ -4188,6 +4708,7 @@ var Think = class Think extends Agent {
4188
4708
  await this._appendMessageToHistory(msg);
4189
4709
  }
4190
4710
  async _hostGetSessionInfo() {
4711
+ await this.__unsafe_ensureInitialized();
4191
4712
  return { messageCount: this.messages.length };
4192
4713
  }
4193
4714
  async _admitTurn(spec) {
@@ -4211,9 +4732,13 @@ var Think = class Think extends Agent {
4211
4732
  }
4212
4733
  _assertNotInsideAdmittedTurn(trigger) {
4213
4734
  if (admittedTurnContext.getStore()?.agent !== this) return;
4214
- throw new Error(`Think turn admission (${trigger}) cannot be called from inside an active turn; use runTurn({ mode: "submit" }) or addMessages() instead`);
4735
+ throw new Error(`Think turn admission (${trigger}) cannot be called from inside an active turn; use runTurn({ mode: "submit" }) or addMessages() instead, and do not waitForSubmission() on it from inside the turn`);
4215
4736
  }
4216
- async _runInsideAdmittedTurnBody(spec) {
4737
+ async _runInsideAdmittedTurnBody(admitted) {
4738
+ const spec = admitted.inheritChannel ? {
4739
+ ...admitted,
4740
+ channel: this._channelForAutoContinuation()
4741
+ } : admitted;
4217
4742
  return __DO_NOT_USE_WILL_BREAK__withInvocationScope(() => withAgentSpan(this, "chat_turn", "turn", {
4218
4743
  "cloudflare.agents.component": "think",
4219
4744
  "cloudflare.agents.turn.request_id": spec.requestId,
@@ -4405,46 +4930,68 @@ var Think = class Think extends Agent {
4405
4930
  if (typeof input === "function") throw new Error("runTurn({ mode: \"submit\" }) does not support function input until _admitTurn (step 3)");
4406
4931
  }
4407
4932
  async _enrichTurnResult(result, continuation) {
4408
- let message;
4409
- if (result.status === "completed") {
4410
- const leaf = await this.session.getLatestLeaf();
4411
- if (leaf?.role === "assistant") message = leaf;
4412
- }
4933
+ const capture = waitTurnResultContext.getStore();
4934
+ const messageId = result.status === "completed" && capture?.agent === this ? capture.messageIds.get(result.requestId) : void 0;
4935
+ const message = messageId !== void 0 ? await this.session.getMessage(messageId) : null;
4413
4936
  return {
4414
4937
  ...result,
4415
4938
  continuation,
4416
- message
4939
+ ...message !== null && { message }
4417
4940
  };
4418
4941
  }
4419
4942
  async _runTurnWait(options) {
4420
4943
  this._validateRunTurnAdmission(options, "wait");
4421
- if (options.continuation === true) {
4422
- const result = await this.continueLastTurn(options.body, {
4423
- signal: options.signal,
4424
- channel: options.channel
4425
- });
4426
- return this._enrichTurnResult(result, true);
4427
- }
4428
- const input = options.input;
4429
- if (input === void 0) throw new TypeError("runTurn: supply either input or continuation: true");
4430
- if (typeof input === "function") {
4431
- const result = await this._runProgrammaticMessagesTurn(crypto.randomUUID(), input, {
4944
+ const capture = {
4945
+ agent: this,
4946
+ messageIds: /* @__PURE__ */ new Map()
4947
+ };
4948
+ return waitTurnResultContext.run(capture, async () => {
4949
+ if (options.continuation === true) {
4950
+ const continueOptions = {
4951
+ signal: options.signal,
4952
+ channel: options.channel
4953
+ };
4954
+ if (!isMethodOverridden(this, "continueLastTurn")) {
4955
+ const result = await this._continueLastTurn(options.body, {
4956
+ ...continueOptions,
4957
+ captureOutput: true
4958
+ });
4959
+ return this._enrichTurnResult(result, true);
4960
+ }
4961
+ const outputCapture = {
4962
+ agent: this,
4963
+ taken: false
4964
+ };
4965
+ const returned = await continuationOutputContext.run(outputCapture, () => this.continueLastTurn(options.body, continueOptions));
4966
+ const captured = outputCapture.result;
4967
+ return this._enrichTurnResult(captured?.requestId === returned.requestId && "output" in captured ? {
4968
+ ...returned,
4969
+ output: captured.output
4970
+ } : returned, true);
4971
+ }
4972
+ const input = options.input;
4973
+ if (input === void 0) throw new TypeError("runTurn: supply either input or continuation: true");
4974
+ if (typeof input === "function") {
4975
+ const result = await this._runProgrammaticMessagesTurn(crypto.randomUUID(), input, {
4976
+ signal: options.signal,
4977
+ channel: options.channel,
4978
+ captureOutput: true
4979
+ });
4980
+ return this._enrichTurnResult(result, false);
4981
+ }
4982
+ const messages = this._normalizeRunTurnMessages(input);
4983
+ if (messages.length === 0) return {
4984
+ requestId: "",
4985
+ status: "skipped",
4986
+ continuation: false
4987
+ };
4988
+ const result = await this._runProgrammaticMessagesTurn(crypto.randomUUID(), messages, {
4432
4989
  signal: options.signal,
4433
- channel: options.channel
4990
+ channel: options.channel,
4991
+ captureOutput: true
4434
4992
  });
4435
4993
  return this._enrichTurnResult(result, false);
4436
- }
4437
- const messages = this._normalizeRunTurnMessages(input);
4438
- if (messages.length === 0) return {
4439
- requestId: "",
4440
- status: "skipped",
4441
- continuation: false
4442
- };
4443
- const result = await this._runProgrammaticMessagesTurn(crypto.randomUUID(), messages, {
4444
- signal: options.signal,
4445
- channel: options.channel
4446
4994
  });
4447
- return this._enrichTurnResult(result, false);
4448
4995
  }
4449
4996
  async _runTurnSubmit(options) {
4450
4997
  this._validateRunTurnAdmission(options, "submit");
@@ -4505,6 +5052,7 @@ var Think = class Think extends Agent {
4505
5052
  this._addAgentToolChildRunColumnIfMissing("ALTER TABLE cf_agent_tool_child_runs ADD COLUMN output_json TEXT");
4506
5053
  this._addAgentToolChildRunColumnIfMissing("ALTER TABLE cf_agent_tool_child_runs ADD COLUMN progress_json TEXT");
4507
5054
  this._addAgentToolChildRunColumnIfMissing("ALTER TABLE cf_agent_tool_child_runs ADD COLUMN last_signal_at INTEGER");
5055
+ this._addAgentToolChildRunColumnIfMissing("ALTER TABLE cf_agent_tool_child_runs ADD COLUMN event_delivery TEXT");
4508
5056
  this.sql`
4509
5057
  CREATE TABLE IF NOT EXISTS cf_agent_tool_milestones (
4510
5058
  run_id TEXT NOT NULL,
@@ -4576,7 +5124,7 @@ var Think = class Think extends Agent {
4576
5124
  streamId: row.stream_id ?? void 0,
4577
5125
  output: storedOutput,
4578
5126
  summary: row.summary ?? void 0,
4579
- error: row.error_message ?? void 0,
5127
+ error: row.completed_at === null ? void 0 : row.error_message ?? void 0,
4580
5128
  startedAt: row.started_at,
4581
5129
  completedAt: row.completed_at ?? void 0,
4582
5130
  ...(() => {
@@ -4801,13 +5349,16 @@ var Think = class Think extends Agent {
4801
5349
  const existing = this._readAgentToolChildRun(options.runId);
4802
5350
  if (existing) return this._inspectionFromChildRow(existing);
4803
5351
  const startedAt = Date.now();
5352
+ const eventDelivery = options.eventDelivery === "terminal" ? "terminal" : null;
4804
5353
  this.sql`
4805
- INSERT INTO cf_agent_tool_child_runs (run_id, status, started_at)
4806
- VALUES (${options.runId}, 'starting', ${startedAt})
5354
+ INSERT INTO cf_agent_tool_child_runs
5355
+ (run_id, status, started_at, event_delivery)
5356
+ VALUES (${options.runId}, 'starting', ${startedAt}, ${eventDelivery})
4807
5357
  `;
4808
5358
  const controller = new AbortController();
4809
5359
  this._agentToolAbortControllers.set(options.runId, controller);
4810
5360
  this._agentToolLiveSequences.set(options.runId, 0);
5361
+ if (eventDelivery === "terminal") this._agentToolTerminalOnlyRuns.add(options.runId);
4811
5362
  this._agentToolPreTurnAssistantIds.set(options.runId, new Set(this.messages.filter((m) => m.role === "assistant").map((m) => m.id)));
4812
5363
  const epoch = this._turnQueue.generation;
4813
5364
  this.keepAliveWhile(async () => {
@@ -4860,6 +5411,7 @@ var Think = class Think extends Agent {
4860
5411
  this._agentToolAbortControllers.delete(options.runId);
4861
5412
  this._agentToolForwarders.delete(options.runId);
4862
5413
  this._agentToolLiveSequences.delete(options.runId);
5414
+ this._agentToolTerminalOnlyRuns.delete(options.runId);
4863
5415
  this._agentToolProgressEmitterInstance?.forget(options.runId);
4864
5416
  if (this._agentToolAbortControllers.size === 0) this._agentToolRunsByRequestId.clear();
4865
5417
  else for (const [reqId, runId] of this._agentToolRunsByRequestId) if (runId === options.runId) this._agentToolRunsByRequestId.delete(reqId);
@@ -4900,10 +5452,10 @@ var Think = class Think extends Agent {
4900
5452
  _classifyAgentToolChildRecovery() {
4901
5453
  return classifyAgentToolChildRecovery(this.ctx.storage);
4902
5454
  }
4903
- async inspectAgentToolRun(runId) {
5455
+ async inspectAgentToolRun(runId, options) {
4904
5456
  let row = this._readAgentToolChildRun(runId);
4905
5457
  if (!row) return null;
4906
- if (this._isStaleAgentToolChildRun(row)) {
5458
+ if (options?.reconcile !== false && this._isStaleAgentToolChildRun(row)) {
4907
5459
  await this._reconcileStaleAgentToolChildRun(runId);
4908
5460
  row = this._readAgentToolChildRun(runId) ?? row;
4909
5461
  }
@@ -4927,6 +5479,18 @@ var Think = class Think extends Agent {
4927
5479
  async _reconcileStaleAgentToolChildRun(runId) {
4928
5480
  const recovery = await this._classifyAgentToolChildRecovery();
4929
5481
  if (recovery === "in-progress" || this._resumableStream.hasActiveStream()) return;
5482
+ const recordedError = this._readAgentToolChildRun(runId)?.error_message;
5483
+ if (recordedError != null) {
5484
+ this.sql`
5485
+ UPDATE cf_agent_tool_child_runs
5486
+ SET status = 'error',
5487
+ error_message = ${recordedError},
5488
+ completed_at = ${Date.now()}
5489
+ WHERE run_id = ${runId} AND completed_at IS NULL
5490
+ `;
5491
+ this._finalizeAgentToolChildRunTailers(runId);
5492
+ return;
5493
+ }
4930
5494
  if (recovery !== "failed" && this._hasRecoveredAgentToolAssistantTurn(runId)) {
4931
5495
  const output = this.getAgentToolOutput(runId);
4932
5496
  const summary = this.getAgentToolSummary(runId, output);
@@ -4956,6 +5520,7 @@ var Think = class Think extends Agent {
4956
5520
  this._agentToolLiveSequences.delete(runId);
4957
5521
  this._agentToolLastErrors.delete(runId);
4958
5522
  this._agentToolPreTurnAssistantIds.delete(runId);
5523
+ if (!this._agentToolAbortControllers.has(runId)) this._agentToolTerminalOnlyRuns.delete(runId);
4959
5524
  }
4960
5525
  /**
4961
5526
  * Eagerly terminalize this child facet's OWN agent-tool run row(s) once a
@@ -4998,6 +5563,23 @@ var Think = class Think extends Agent {
4998
5563
  body: chunk.body
4999
5564
  }));
5000
5565
  }
5566
+ /**
5567
+ * After this DO restarts, `_agentToolLiveSequences` is cold while the stored
5568
+ * backlog sits at N, and a chat-recovery resume re-attaches via
5569
+ * `tailAgentToolRun` without re-running `startAgentToolRun` (which seeds the
5570
+ * counter). Unseeded, the broadcast snoop numbers the recovered turn's chunks
5571
+ * from 0 and the tail's high-water dedupe drops them. Seeds only a
5572
+ * non-terminal run, so a terminal one doesn't re-heat the broadcast
5573
+ * idle-guard; a warm counter is authoritative. Returns whether it seeded.
5574
+ */
5575
+ _seedAgentToolLiveSequence(runId) {
5576
+ if (this._agentToolLiveSequences.has(runId)) return false;
5577
+ const row = this._readAgentToolChildRun(runId);
5578
+ if (!row?.stream_id || row.completed_at !== null) return false;
5579
+ this._resumableStream.flushBuffer();
5580
+ this._agentToolLiveSequences.set(runId, this._resumableStream.getStreamChunks(row.stream_id).length);
5581
+ return true;
5582
+ }
5001
5583
  async tailAgentToolRun(runId, options) {
5002
5584
  const self = this;
5003
5585
  const signal = options?.signal;
@@ -5028,8 +5610,11 @@ var Think = class Think extends Agent {
5028
5610
  signal?.addEventListener("abort", close, { once: true });
5029
5611
  let lastEmitted = options?.afterSequence ?? -1;
5030
5612
  const emit = (chunk) => {
5031
- if (closed || chunk.sequence <= lastEmitted) return;
5032
- lastEmitted = chunk.sequence;
5613
+ if (closed) return;
5614
+ if (!isPositionlessAgentToolChunk(chunk)) {
5615
+ if (chunk.sequence <= lastEmitted) return;
5616
+ lastEmitted = chunk.sequence;
5617
+ }
5033
5618
  try {
5034
5619
  controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
5035
5620
  } catch {
@@ -5047,6 +5632,7 @@ var Think = class Think extends Agent {
5047
5632
  }
5048
5633
  emit(chunk);
5049
5634
  };
5635
+ const seeded = self._seedAgentToolLiveSequence(runId);
5050
5636
  const forwarders = self._agentToolForwarders.get(runId) ?? /* @__PURE__ */ new Set();
5051
5637
  forwarders.add(forward);
5052
5638
  self._agentToolForwarders.set(runId, forwarders);
@@ -5064,10 +5650,10 @@ var Think = class Think extends Agent {
5064
5650
  pending.length = 0;
5065
5651
  const row = self._readAgentToolChildRun(runId);
5066
5652
  if (!row || row.completed_at !== null) {
5653
+ if (seeded) self._agentToolLiveSequences.delete(runId);
5067
5654
  close();
5068
5655
  return;
5069
5656
  }
5070
- if (lastEmitted > (options?.afterSequence ?? -1)) self._agentToolLiveSequences.set(runId, lastEmitted + 1);
5071
5657
  } catch (error) {
5072
5658
  closed = true;
5073
5659
  detach();
@@ -5521,6 +6107,19 @@ var Think = class Think extends Agent {
5521
6107
  _declaredScheduleOwnerKey() {
5522
6108
  return stableHash(this.selfPath);
5523
6109
  }
6110
+ /**
6111
+ * Whether this instance arms the declared scheduled tasks.
6112
+ *
6113
+ * The root always arms. Facets only arm when the class opts in via
6114
+ * `getScheduledTasksScope()`; see that hook for why root-only is the
6115
+ * default (#1877). `parentPath` is hydrated before the reconcile step of
6116
+ * `onStart` — persisted by `_cf_initAsFacet` on a facet's first boot, and
6117
+ * restored from storage by the base agent on every later wake.
6118
+ */
6119
+ async _declaredScheduledTasksArmedHere() {
6120
+ if (this.parentPath.length === 0) return true;
6121
+ return await this.getScheduledTasksScope() === "all";
6122
+ }
5524
6123
  _declaredScheduleValidationError(rawSchedule, taskTimezone, defaultTimezone) {
5525
6124
  const result = tryParseDeclaredTaskSchedule(rawSchedule, taskTimezone, defaultTimezone === void 0 ? void 0 : validateTimezone(defaultTimezone));
5526
6125
  return result.ok ? null : result.error;
@@ -5530,7 +6129,8 @@ var Think = class Think extends Agent {
5530
6129
  return nextDeclaredScheduleTime(parseDeclaredTaskSchedule(rawSchedule, options.taskTimezone, resolvedDefaultTimezone), now, options.previousScheduledFor);
5531
6130
  }
5532
6131
  async _reconcileDeclaredScheduledTasks() {
5533
- const tasks = await this._declaredScheduledTasksForNow();
6132
+ const armed = await this._declaredScheduledTasksArmedHere();
6133
+ const tasks = armed ? await this._declaredScheduledTasksForNow() : /* @__PURE__ */ new Map();
5534
6134
  this._ensureDeclaredScheduledTasksTable();
5535
6135
  const ownerKey = this._declaredScheduleOwnerKey();
5536
6136
  const now = Date.now();
@@ -5598,6 +6198,29 @@ var Think = class Think extends Agent {
5598
6198
  AND task_id = ${row.task_id}
5599
6199
  `;
5600
6200
  }
6201
+ if (!armed) await this._warnFacetScheduledTasksDisarmed(existing.length);
6202
+ }
6203
+ /**
6204
+ * Warn once when a sub-agent declares tasks it will not arm.
6205
+ *
6206
+ * Two populations need this, and only one of them leaves a trace. A facet
6207
+ * upgrading from the pre-#1877 default has rows to prune, so `armedCount`
6208
+ * is non-zero. A facet declaring tasks for the first time under the root
6209
+ * default never armed anything, so the only way to tell it apart from a
6210
+ * class that declares nothing is to ask — otherwise its schedule is
6211
+ * silently inert, which is the failure mode #1877 was filed about.
6212
+ */
6213
+ async _warnFacetScheduledTasksDisarmed(armedCount) {
6214
+ if (this._warnedFacetScheduledTasksDisarmed) return;
6215
+ let declaredCount = armedCount;
6216
+ if (declaredCount === 0) try {
6217
+ declaredCount = Object.keys(await this.getScheduledTasks()).length;
6218
+ } catch {
6219
+ return;
6220
+ }
6221
+ if (declaredCount === 0) return;
6222
+ this._warnedFacetScheduledTasksDisarmed = true;
6223
+ console.warn(`[Think] Sub-agent "${this.name}" declares ${declaredCount} scheduled task(s) that are not armed here. Declared tasks run on the root agent only, so each occurrence fires once rather than once per live sub-agent (#1877)` + (armedCount > 0 ? "; the occurrences this sub-agent had already armed have been cancelled" : ``) + ". Override getScheduledTasksScope() to return \"all\" if this class intentionally declares per-sub-agent tasks.");
5601
6224
  }
5602
6225
  async _scheduleDeclaredTaskOccurrence(task, now, previousScheduledFor) {
5603
6226
  const next = nextDeclaredScheduleTime(task.schedule, now, previousScheduledFor);
@@ -5633,6 +6256,7 @@ var Think = class Think extends Agent {
5633
6256
  }
5634
6257
  async _runDeclaredScheduledTask(payload) {
5635
6258
  if (!payload || typeof payload.taskId !== "string" || typeof payload.scheduleHash !== "string" || typeof payload.scheduledFor !== "number") throw new Error("Invalid declared scheduled task payload");
6259
+ if (!await this._declaredScheduledTasksArmedHere()) return;
5636
6260
  const row = this._readDeclaredScheduledTaskRow(payload.taskId);
5637
6261
  if (!row || row.schedule_hash !== payload.scheduleHash) return;
5638
6262
  if (row.next_run_at !== null && row.next_run_at > payload.scheduledFor) return;
@@ -5696,10 +6320,15 @@ var Think = class Think extends Agent {
5696
6320
  -- Closed vocabulary: 'completed' | 'aborted' | 'retry'. NULL is legacy
5697
6321
  -- or an unsettled attempt; 'retry' is NOT terminal completion evidence.
5698
6322
  result_status TEXT,
5699
- output_json TEXT
6323
+ output_json TEXT,
6324
+ message_id TEXT
5700
6325
  )
5701
6326
  `;
5702
- for (const statement of ["ALTER TABLE cf_think_submissions ADD COLUMN result_status TEXT", "ALTER TABLE cf_think_submissions ADD COLUMN output_json TEXT"]) try {
6327
+ for (const statement of [
6328
+ "ALTER TABLE cf_think_submissions ADD COLUMN result_status TEXT",
6329
+ "ALTER TABLE cf_think_submissions ADD COLUMN output_json TEXT",
6330
+ "ALTER TABLE cf_think_submissions ADD COLUMN message_id TEXT"
6331
+ ]) try {
5703
6332
  this.ctx.storage.sql.exec(statement);
5704
6333
  } catch (error) {
5705
6334
  if (!(error instanceof Error ? error.message : String(error)).toLowerCase().includes("duplicate column")) throw error;
@@ -5723,7 +6352,8 @@ var Think = class Think extends Agent {
5723
6352
  return this.sql`
5724
6353
  SELECT submission_id, idempotency_key, request_id, stream_id, status,
5725
6354
  messages_json, metadata_json, error_message, created_at,
5726
- messages_applied_at, started_at, completed_at, result_status, output_json
6355
+ messages_applied_at, started_at, completed_at, result_status, output_json,
6356
+ message_id
5727
6357
  FROM cf_think_submissions
5728
6358
  WHERE submission_id = ${submissionId}
5729
6359
  LIMIT 1
@@ -5734,7 +6364,8 @@ var Think = class Think extends Agent {
5734
6364
  return this.sql`
5735
6365
  SELECT submission_id, idempotency_key, request_id, stream_id, status,
5736
6366
  messages_json, metadata_json, error_message, created_at,
5737
- messages_applied_at, started_at, completed_at, result_status, output_json
6367
+ messages_applied_at, started_at, completed_at, result_status, output_json,
6368
+ message_id
5738
6369
  FROM cf_think_submissions
5739
6370
  WHERE idempotency_key = ${idempotencyKey}
5740
6371
  LIMIT 1
@@ -5752,7 +6383,8 @@ var Think = class Think extends Agent {
5752
6383
  return this.sql`
5753
6384
  SELECT submission_id, idempotency_key, request_id, stream_id, status,
5754
6385
  messages_json, metadata_json, error_message, created_at,
5755
- messages_applied_at, started_at, completed_at, result_status, output_json
6386
+ messages_applied_at, started_at, completed_at, result_status, output_json,
6387
+ message_id
5756
6388
  FROM cf_think_submissions
5757
6389
  ORDER BY created_at DESC, submission_id DESC
5758
6390
  LIMIT ${limit}
@@ -5762,7 +6394,8 @@ var Think = class Think extends Agent {
5762
6394
  return this.sql`
5763
6395
  SELECT submission_id, idempotency_key, request_id, stream_id, status,
5764
6396
  messages_json, metadata_json, error_message, created_at,
5765
- messages_applied_at, started_at, completed_at, result_status, output_json
6397
+ messages_applied_at, started_at, completed_at, result_status, output_json,
6398
+ message_id
5766
6399
  FROM cf_think_submissions
5767
6400
  WHERE status = ${status}
5768
6401
  ORDER BY created_at DESC, submission_id DESC
@@ -5780,7 +6413,8 @@ var Think = class Think extends Agent {
5780
6413
  metadata: metadata ?? void 0,
5781
6414
  createdAt: row.created_at,
5782
6415
  startedAt: row.started_at ?? void 0,
5783
- completedAt: row.completed_at ?? void 0
6416
+ completedAt: row.completed_at ?? void 0,
6417
+ ...row.message_id !== null && { messageId: row.message_id }
5784
6418
  };
5785
6419
  }
5786
6420
  _parseJsonObject(value) {
@@ -5825,6 +6459,8 @@ var Think = class Think extends Agent {
5825
6459
  }
5826
6460
  async _emitSubmissionStatus(row) {
5827
6461
  const inspection = this._inspectionFromSubmissionRow(row);
6462
+ const terminal = this._isTerminalSubmissionStatus(inspection.status);
6463
+ if (terminal) this._terminalStatusEmits.add(inspection.submissionId);
5828
6464
  this._emit("submission:status", {
5829
6465
  submissionId: inspection.submissionId,
5830
6466
  requestId: inspection.requestId,
@@ -5844,19 +6480,86 @@ var Think = class Think extends Agent {
5844
6480
  error: inspection.error
5845
6481
  });
5846
6482
  }
5847
- await this.keepAliveWhile(async () => {
5848
- try {
5849
- await this.onSubmissionStatus(inspection);
5850
- } catch (error) {
5851
- console.error("[Think] onSubmissionStatus failed", error);
6483
+ try {
6484
+ await this.keepAliveWhile(async () => {
6485
+ const hook = {
6486
+ agent: this,
6487
+ ended: false
6488
+ };
6489
+ try {
6490
+ await submissionStatusHookContext.run(hook, () => this.onSubmissionStatus(inspection));
6491
+ } catch (error) {
6492
+ console.error("[Think] onSubmissionStatus failed", error);
6493
+ } finally {
6494
+ hook.ended = true;
6495
+ }
6496
+ });
6497
+ } finally {
6498
+ if (terminal) {
6499
+ const id = inspection.submissionId;
6500
+ this._terminalStatusEmits.delete(id);
6501
+ const held = this._waitersHeldForDeletedEmit.get(id);
6502
+ this._waitersHeldForDeletedEmit.delete(id);
6503
+ for (const waiter of held ?? []) waiter(inspection);
6504
+ if (this._readSubmission(id)?.created_at === row.created_at) this._resolveSubmissionWaiters(inspection);
5852
6505
  }
5853
- });
6506
+ }
6507
+ }
6508
+ _resolveSubmissionWaiters(submission) {
6509
+ const waiters = this._submissionWaiters.get(submission.submissionId);
6510
+ this._submissionWaiters.delete(submission.submissionId);
6511
+ for (const waiter of waiters ?? []) waiter(submission);
5854
6512
  }
5855
- onSubmissionStatus(_submission) {}
5856
6513
  /**
5857
- * Queue the workflow event for a submission that just went terminal.
6514
+ * Resolve once the submission reaches a terminal status (`completed`,
6515
+ * `aborted`, `skipped` or `error`), after `onSubmissionStatus` has run for
6516
+ * it. Resolves immediately for a submission that already finished, and with
6517
+ * `null` for an unknown id. An `error` status resolves rather than rejects;
6518
+ * read `status` and `error` from the result.
5858
6519
  *
5859
- * The item is written synchronously (the Lifecycle has started whenever a
6520
+ * The wait lives in this object's memory, so it rejects if the object
6521
+ * restarts. The submission itself is durable: call again to keep waiting.
6522
+ *
6523
+ * Throws when called from inside a turn (a tool `execute`, a lifecycle
6524
+ * hook) or from `onSubmissionStatus` for a submission that has not
6525
+ * finished: a submission only runs once the current turn frees the turn
6526
+ * queue, and its status settles only after the hook returns, so the wait
6527
+ * could never resolve. Return the submission id and wait from outside the
6528
+ * turn instead.
6529
+ */
6530
+ async waitForSubmission(submissionId, options) {
6531
+ const row = this._readSubmission(submissionId);
6532
+ if (!row) return null;
6533
+ if (this._isTerminalSubmissionStatus(row.status) && !this._terminalStatusEmits.has(submissionId)) return this._inspectionFromSubmissionRow(row);
6534
+ const hook = submissionStatusHookContext.getStore();
6535
+ if (hook?.agent === this && !hook.ended) throw new Error("waitForSubmission() cannot be called from onSubmissionStatus: the submission settles only after the hook returns");
6536
+ if (this._activeAdmittedTurn()) throw new Error("waitForSubmission() cannot be called from inside an active turn: the submission runs only after this turn ends");
6537
+ return new Promise((resolve) => {
6538
+ let timer;
6539
+ const waiter = (submission) => {
6540
+ clearTimeout(timer);
6541
+ resolve(submission);
6542
+ };
6543
+ let waiters = this._submissionWaiters.get(submissionId);
6544
+ if (!waiters) {
6545
+ waiters = /* @__PURE__ */ new Set();
6546
+ this._submissionWaiters.set(submissionId, waiters);
6547
+ }
6548
+ waiters.add(waiter);
6549
+ if (options?.timeoutMs !== void 0) timer = setTimeout(() => {
6550
+ const current = this._submissionWaiters.get(submissionId);
6551
+ current?.delete(waiter);
6552
+ if (current?.size === 0) this._submissionWaiters.delete(submissionId);
6553
+ const latest = this._readSubmission(submissionId);
6554
+ resolve(latest ? this._inspectionFromSubmissionRow(latest) : null);
6555
+ }, options.timeoutMs);
6556
+ });
6557
+ }
6558
+ onSubmissionStatus(_submission) {}
6559
+ /**
6560
+ * Queue the workflow event for a submission that just went terminal.
6561
+ *
6562
+ * The item is written synchronously (the Lifecycle has started whenever a
5860
6563
  * submission transitions), so call this in the same synchronous block as
5861
6564
  * the terminal status write: the two commit together and no recovery scan
5862
6565
  * is needed. A repeated push for the same submission and event type
@@ -5975,8 +6678,24 @@ var Think = class Think extends Agent {
5975
6678
  WHERE submission_id = ${submissionId}
5976
6679
  AND status IN ('completed', 'aborted', 'skipped', 'error')
5977
6680
  `;
6681
+ this._releaseDeletedSubmissionWaiters([row]);
5978
6682
  return true;
5979
6683
  }
6684
+ _releaseDeletedSubmissionWaiters(rows) {
6685
+ for (const row of rows) {
6686
+ const id = row.submission_id;
6687
+ if (!this._terminalStatusEmits.has(id)) {
6688
+ this._resolveSubmissionWaiters(this._inspectionFromSubmissionRow(row));
6689
+ continue;
6690
+ }
6691
+ const waiters = this._submissionWaiters.get(id);
6692
+ if (!waiters) continue;
6693
+ this._submissionWaiters.delete(id);
6694
+ const held = this._waitersHeldForDeletedEmit.get(id) ?? /* @__PURE__ */ new Set();
6695
+ for (const waiter of waiters) held.add(waiter);
6696
+ this._waitersHeldForDeletedEmit.set(id, held);
6697
+ }
6698
+ }
5980
6699
  async deleteSubmissions(options) {
5981
6700
  this._ensureSubmissionTable();
5982
6701
  const statuses = this._normalizeStatusFilter(options?.status) ?? /* @__PURE__ */ new Set([
@@ -5987,7 +6706,8 @@ var Think = class Think extends Agent {
5987
6706
  ]);
5988
6707
  const limit = Math.min(Math.max(options?.limit ?? 100, 1), 500);
5989
6708
  const completedBefore = options?.completedBefore?.getTime();
5990
- const idsToDelete = [...statuses].flatMap((status) => this._listTerminalSubmissionRowsForDelete(status, limit, completedBefore)).sort((a, b) => (a.completed_at ?? a.created_at) === (b.completed_at ?? b.created_at) ? a.created_at - b.created_at : (a.completed_at ?? a.created_at) - (b.completed_at ?? b.created_at)).slice(0, limit).filter((row) => this._isTerminalSubmissionStatus(row.status)).map((row) => row.submission_id);
6709
+ const rowsToDelete = [...statuses].flatMap((status) => this._listTerminalSubmissionRowsForDelete(status, limit, completedBefore)).sort((a, b) => (a.completed_at ?? a.created_at) === (b.completed_at ?? b.created_at) ? a.created_at - b.created_at : (a.completed_at ?? a.created_at) - (b.completed_at ?? b.created_at)).slice(0, limit).filter((row) => this._isTerminalSubmissionStatus(row.status));
6710
+ const idsToDelete = rowsToDelete.map((row) => row.submission_id);
5991
6711
  let deleted = 0;
5992
6712
  for (let i = 0; i < idsToDelete.length; i += MAX_BOUND_PARAMS) {
5993
6713
  const batch = idsToDelete.slice(i, i + MAX_BOUND_PARAMS);
@@ -5995,13 +6715,15 @@ var Think = class Think extends Agent {
5995
6715
  this.sql(strings, ...batch);
5996
6716
  deleted += batch.length;
5997
6717
  }
6718
+ this._releaseDeletedSubmissionWaiters(rowsToDelete);
5998
6719
  return deleted;
5999
6720
  }
6000
6721
  _listTerminalSubmissionRowsForDelete(status, limit, completedBefore) {
6001
6722
  if (completedBefore === void 0) return this.sql`
6002
6723
  SELECT submission_id, idempotency_key, request_id, stream_id, status,
6003
6724
  messages_json, metadata_json, error_message, created_at,
6004
- messages_applied_at, started_at, completed_at, result_status, output_json
6725
+ messages_applied_at, started_at, completed_at, result_status, output_json,
6726
+ message_id
6005
6727
  FROM cf_think_submissions
6006
6728
  WHERE status = ${status}
6007
6729
  ORDER BY completed_at ASC, created_at ASC
@@ -6010,7 +6732,8 @@ var Think = class Think extends Agent {
6010
6732
  return this.sql`
6011
6733
  SELECT submission_id, idempotency_key, request_id, stream_id, status,
6012
6734
  messages_json, metadata_json, error_message, created_at,
6013
- messages_applied_at, started_at, completed_at, result_status, output_json
6735
+ messages_applied_at, started_at, completed_at, result_status, output_json,
6736
+ message_id
6014
6737
  FROM cf_think_submissions
6015
6738
  WHERE status = ${status}
6016
6739
  AND completed_at IS NOT NULL
@@ -6024,7 +6747,18 @@ var Think = class Think extends Agent {
6024
6747
  }
6025
6748
  async cancelSubmission(submissionId, reason) {
6026
6749
  const row = this._readSubmission(submissionId);
6027
- if (!row || this._isTerminalSubmissionStatus(row.status)) return;
6750
+ if (!row) return {
6751
+ outcome: "not_found",
6752
+ submissionId
6753
+ };
6754
+ if (this._isTerminalSubmissionStatus(row.status)) return {
6755
+ outcome: "already_terminal",
6756
+ submissionId,
6757
+ submission: this._inspectionFromSubmissionRow(row)
6758
+ };
6759
+ const previousStatus = row.status;
6760
+ let messagesApplied = row.messages_applied_at !== null || this._submissionsApplyingMessages.has(submissionId);
6761
+ const runningHere = this._submissionAbortControllers.has(submissionId);
6028
6762
  const completedAt = Date.now();
6029
6763
  const errorMessage = reason === void 0 ? null : reason instanceof Error ? reason.message : String(reason);
6030
6764
  this._submissionAbortControllers.get(submissionId)?.abort(reason);
@@ -6040,11 +6774,30 @@ var Think = class Think extends Agent {
6040
6774
  AND status IN ('pending', 'running')
6041
6775
  `;
6042
6776
  const updated = this._readSubmission(submissionId);
6043
- if (updated?.status === "aborted") {
6044
- this._enqueueTerminalWorkflowNotification(updated);
6777
+ if (!updated) return {
6778
+ outcome: "not_found",
6779
+ submissionId
6780
+ };
6781
+ if (updated.status !== "aborted") return {
6782
+ outcome: "already_terminal",
6783
+ submissionId,
6784
+ submission: this._inspectionFromSubmissionRow(updated)
6785
+ };
6786
+ this._enqueueTerminalWorkflowNotification(updated);
6787
+ this._terminalStatusEmits.add(submissionId);
6788
+ try {
6789
+ if (!messagesApplied && previousStatus === "running" && !runningHere) messagesApplied = await this._getSubmissionMessagesAppliedState(updated) !== "none";
6045
6790
  await this.dequeue(submissionRunItemId(submissionId));
6791
+ } finally {
6046
6792
  await this._emitSubmissionStatus(updated);
6047
6793
  }
6794
+ return {
6795
+ outcome: "cancelled",
6796
+ submissionId,
6797
+ previousStatus,
6798
+ messagesApplied,
6799
+ submission: this._inspectionFromSubmissionRow(updated)
6800
+ };
6048
6801
  }
6049
6802
  async submitMessages(messages, options) {
6050
6803
  messages = this._stampChannel(messages, options?.channel);
@@ -6149,11 +6902,12 @@ var Think = class Think extends Agent {
6149
6902
  `;
6150
6903
  const claimed = this._readSubmission(row.submission_id);
6151
6904
  if (!claimed || claimed.status !== "running") return;
6152
- await this._emitSubmissionStatus(claimed);
6153
6905
  const controller = new AbortController();
6154
6906
  this._submissionAbortControllers.set(row.submission_id, controller);
6155
6907
  let output;
6908
+ let finalizedHere = false;
6156
6909
  try {
6910
+ await this._emitSubmissionStatus(claimed);
6157
6911
  const messages = this._parseSubmissionMessages(row.messages_json);
6158
6912
  const metadata = this._parseJsonObject(row.metadata_json);
6159
6913
  const workflowPrompt = this._readWorkflowPromptContext(metadata);
@@ -6165,6 +6919,9 @@ var Think = class Think extends Agent {
6165
6919
  allowNested: true,
6166
6920
  workflowPrompt: workflowPrompt ?? void 0,
6167
6921
  shouldApplyMessages: () => this._readSubmission(row.submission_id)?.status === "running",
6922
+ onApplyingMessages: () => {
6923
+ this._submissionsApplyingMessages.add(row.submission_id);
6924
+ },
6168
6925
  onMessagesApplied: () => {
6169
6926
  this.sql`
6170
6927
  UPDATE cf_think_submissions
@@ -6176,12 +6933,14 @@ var Think = class Think extends Agent {
6176
6933
  }
6177
6934
  });
6178
6935
  output = result.output;
6936
+ if (this._recoveryOwnedSubmissions.delete(row.submission_id)) return;
6179
6937
  const streamId = this._resumableStream.getAllStreamMetadata().find((metadata) => metadata.request_id === result.requestId)?.id ?? null;
6180
6938
  const streamError = this._programmaticStreamErrors.get(result.requestId);
6181
6939
  const finalStatus = this._getSubmissionFinalStatus(result.status, result.error ?? streamError);
6182
6940
  const errorMessage = result.error ?? streamError ?? null;
6183
6941
  const completedAt = Date.now();
6184
6942
  this.ctx.storage.transactionSync(() => {
6943
+ finalizedHere = this._readSubmission(row.submission_id)?.status === "running";
6185
6944
  this.sql`
6186
6945
  UPDATE cf_think_submissions
6187
6946
  SET status = ${finalStatus},
@@ -6201,6 +6960,7 @@ var Think = class Think extends Agent {
6201
6960
  const errorMessage = error instanceof Error ? error.message : String(error);
6202
6961
  const completedAt = Date.now();
6203
6962
  this.ctx.storage.transactionSync(() => {
6963
+ finalizedHere = this._readSubmission(row.submission_id)?.status === "running";
6204
6964
  this.sql`
6205
6965
  UPDATE cf_think_submissions
6206
6966
  SET status = 'error',
@@ -6217,8 +6977,9 @@ var Think = class Think extends Agent {
6217
6977
  } finally {
6218
6978
  this._programmaticStreamErrors.delete(requestId);
6219
6979
  this._submissionAbortControllers.delete(row.submission_id);
6980
+ this._submissionsApplyingMessages.delete(row.submission_id);
6220
6981
  const updated = this._readSubmission(row.submission_id);
6221
- if (updated && this._isTerminalSubmissionStatus(updated.status)) await this._emitSubmissionStatus(updated);
6982
+ if (finalizedHere && updated && this._isTerminalSubmissionStatus(updated.status)) await this._emitSubmissionStatus(updated);
6222
6983
  }
6223
6984
  }
6224
6985
  _getSubmissionFinalStatus(resultStatus, streamError) {
@@ -6229,7 +6990,8 @@ var Think = class Think extends Agent {
6229
6990
  const pending = this.sql`
6230
6991
  SELECT submission_id, idempotency_key, request_id, stream_id, status,
6231
6992
  messages_json, metadata_json, error_message, created_at,
6232
- messages_applied_at, started_at, completed_at, result_status, output_json
6993
+ messages_applied_at, started_at, completed_at, result_status, output_json,
6994
+ message_id
6233
6995
  FROM cf_think_submissions
6234
6996
  WHERE status = 'pending'
6235
6997
  `;
@@ -6240,18 +7002,36 @@ var Think = class Think extends Agent {
6240
7002
  completed_at = ${Date.now()}
6241
7003
  WHERE status = 'pending'
6242
7004
  `;
7005
+ const skipped = [];
6243
7006
  for (const row of pending) {
6244
- this._enqueueTerminalWorkflowNotification(this._readSubmission(row.submission_id));
7007
+ const updated = this._readSubmission(row.submission_id);
7008
+ this._enqueueTerminalWorkflowNotification(updated);
7009
+ if (updated) {
7010
+ skipped.push(updated);
7011
+ this._terminalStatusEmits.add(updated.submission_id);
7012
+ }
6245
7013
  this.dequeue(submissionRunItemId(row.submission_id)).catch((error) => {
6246
7014
  console.error("[Think] Failed to dequeue skipped submission", error);
6247
7015
  });
6248
7016
  }
6249
- return pending;
7017
+ return skipped;
6250
7018
  }
6251
7019
  async _emitSkippedSubmissions(skipped) {
6252
7020
  for (const row of skipped) {
6253
- const updated = this._readSubmission(row.submission_id);
6254
- if (updated?.status === "skipped") await this._emitSubmissionStatus(updated);
7021
+ const id = row.submission_id;
7022
+ const updated = this._readSubmission(id);
7023
+ if (updated?.status === "skipped" && updated.created_at === row.created_at) try {
7024
+ await this._emitSubmissionStatus(updated);
7025
+ continue;
7026
+ } catch (error) {
7027
+ console.error("[Think] Failed to emit skipped submission", error);
7028
+ }
7029
+ this._terminalStatusEmits.delete(id);
7030
+ const held = this._waitersHeldForDeletedEmit.get(id);
7031
+ this._waitersHeldForDeletedEmit.delete(id);
7032
+ const inspection = this._inspectionFromSubmissionRow(row);
7033
+ for (const waiter of held ?? []) waiter(inspection);
7034
+ if (updated?.created_at === row.created_at) this._resolveSubmissionWaiters(inspection);
6255
7035
  }
6256
7036
  }
6257
7037
  async _recoverSubmissionsOnStart() {
@@ -6259,7 +7039,8 @@ var Think = class Think extends Agent {
6259
7039
  const running = this.sql`
6260
7040
  SELECT submission_id, idempotency_key, request_id, stream_id, status,
6261
7041
  messages_json, metadata_json, error_message, created_at,
6262
- messages_applied_at, started_at, completed_at, result_status, output_json
7042
+ messages_applied_at, started_at, completed_at, result_status, output_json,
7043
+ message_id
6263
7044
  FROM cf_think_submissions
6264
7045
  WHERE status = 'running'
6265
7046
  `;
@@ -6364,6 +7145,7 @@ var Think = class Think extends Agent {
6364
7145
  if (this.sql`
6365
7146
  SELECT id FROM cf_agents_runs
6366
7147
  WHERE name = ${this.constructor.CHAT_FIBER_NAME + ":" + requestId}
7148
+ AND completed_at IS NULL
6367
7149
  LIMIT 1
6368
7150
  `.length > 0) return true;
6369
7151
  if (this._recoverableChatTurnTaskCreatedAt(requestId) !== null) return true;
@@ -6375,6 +7157,7 @@ var Think = class Think extends Agent {
6375
7157
  const fiberRows = this.sql`
6376
7158
  SELECT created_at FROM cf_agents_runs
6377
7159
  WHERE name = ${this.constructor.CHAT_FIBER_NAME + ":" + row.request_id}
7160
+ AND completed_at IS NULL
6378
7161
  LIMIT 1
6379
7162
  `;
6380
7163
  if (fiberRows[0] && fiberRows[0].created_at >= cutoff) return true;
@@ -6528,6 +7311,7 @@ var Think = class Think extends Agent {
6528
7311
  status = "aborted";
6529
7312
  return;
6530
7313
  }
7314
+ options?.onApplyingMessages?.();
6531
7315
  for (const msg of this._stampChannel(resolved, channel)) await this._appendMessageToHistory(msg);
6532
7316
  options?.onMessagesApplied?.();
6533
7317
  this._broadcastMessages();
@@ -6607,7 +7391,8 @@ var Think = class Think extends Agent {
6607
7391
  * (Phase 4), "generate more" buttons, and self-correction.
6608
7392
  *
6609
7393
  * Note: this creates a new message, not an append to the existing one.
6610
- * True continuation-as-append (chunk rewriting) is planned for Phase 4.
7394
+ * Recovery continuations (`trigger: "recovery-continue"`) are the exception:
7395
+ * they stream into the interrupted assistant message so it stays one message.
6611
7396
  *
6612
7397
  * Returns early with `status: "skipped"` if there is no assistant message
6613
7398
  * to continue from.
@@ -6616,6 +7401,18 @@ var Think = class Think extends Agent {
6616
7401
  * matches the {@link saveMessages} contract.
6617
7402
  */
6618
7403
  async continueLastTurn(body, options) {
7404
+ const store = continuationOutputContext.getStore();
7405
+ const capture = store?.agent === this && !store.taken ? store : void 0;
7406
+ if (capture) capture.taken = true;
7407
+ const full = await this._continueLastTurn(body, capture ? {
7408
+ ...options,
7409
+ captureOutput: true
7410
+ } : options);
7411
+ if (capture) capture.result = full;
7412
+ const { output: _output, ...result } = full;
7413
+ return result;
7414
+ }
7415
+ async _continueLastTurn(body, options) {
6619
7416
  const trigger = options?.trigger ?? "programmatic";
6620
7417
  this._assertNotInsideAdmittedTurn(trigger);
6621
7418
  const lastLeaf = await this.session.getLatestLeaf();
@@ -6627,17 +7424,20 @@ var Think = class Think extends Agent {
6627
7424
  this._rebindAgentToolChildRunRequestId(requestId);
6628
7425
  const clientTools = this._lastClientTools;
6629
7426
  const resolvedBody = body ?? this._lastBody;
7427
+ const workflowPrompt = this._recoveredWorkflowPrompt();
7428
+ const captureOutput = options?.captureOutput || Boolean(workflowPrompt?.output);
6630
7429
  const epoch = this._turnQueue.generation;
6631
- const channel = options?.channel ?? this._channelFromLatestUserMessage();
6632
7430
  let status = "completed";
6633
7431
  let error;
7432
+ let output;
6634
7433
  let wasAborted = false;
6635
7434
  await this._admitTurn({
6636
7435
  admission: "queue",
6637
7436
  trigger,
6638
7437
  requestId,
6639
7438
  continuation: true,
6640
- channel,
7439
+ channel: options?.channel,
7440
+ inheritChannel: options?.channel === void 0,
6641
7441
  getStatus: () => status,
6642
7442
  execute: async () => {
6643
7443
  if (this._turnQueue.generation !== epoch) {
@@ -6657,12 +7457,18 @@ var Think = class Think extends Agent {
6657
7457
  signal: abortSignal,
6658
7458
  clientTools,
6659
7459
  body: resolvedBody,
7460
+ workflowPrompt,
6660
7461
  continuation: true
6661
7462
  }));
6662
7463
  if (result) {
6663
- const streamResult = await this._streamResult(requestId, result, abortSignal, { continuation: true });
7464
+ const streamResult = await this._streamResult(requestId, result, abortSignal, {
7465
+ continuation: true,
7466
+ extendLeafAssistant: trigger === "recovery-continue",
7467
+ captureOutput
7468
+ });
6664
7469
  status = streamResult.status;
6665
7470
  error = streamResult.error;
7471
+ output = streamResult.output;
6666
7472
  }
6667
7473
  };
6668
7474
  await this._runChatRecoveryFiber(requestId, true, continueTurnBody);
@@ -6678,14 +7484,16 @@ var Think = class Think extends Agent {
6678
7484
  return {
6679
7485
  requestId,
6680
7486
  status,
6681
- ...error !== void 0 && { error }
7487
+ ...error !== void 0 && { error },
7488
+ ...output !== void 0 && { output }
6682
7489
  };
6683
7490
  }
6684
7491
  async _retryLastUserTurn(clientTools, body, options) {
6685
7492
  const trigger = options?.trigger ?? "recovery-retry";
6686
7493
  this._assertNotInsideAdmittedTurn(trigger);
6687
- const lastLeaf = await this.session.getLatestLeaf();
6688
- if (!lastLeaf || lastLeaf.role !== "user") return {
7494
+ const branchParentId = options?.branchParentId;
7495
+ const target = branchParentId === void 0 ? await this.session.getLatestLeaf() : await this.session.getMessage(branchParentId);
7496
+ if (!target || target.role !== "user") return {
6689
7497
  requestId: "",
6690
7498
  status: "skipped"
6691
7499
  };
@@ -6693,6 +7501,7 @@ var Think = class Think extends Agent {
6693
7501
  this._rebindAgentToolChildRunRequestId(requestId);
6694
7502
  const epoch = this._turnQueue.generation;
6695
7503
  const channel = options?.channel ?? this._channelFromLatestUserMessage();
7504
+ const workflowPrompt = this._recoveredWorkflowPrompt();
6696
7505
  let status = "completed";
6697
7506
  let error;
6698
7507
  let wasAborted = false;
@@ -6721,15 +7530,19 @@ var Think = class Think extends Agent {
6721
7530
  signal: abortSignal,
6722
7531
  clientTools,
6723
7532
  body,
7533
+ workflowPrompt,
6724
7534
  continuation: false
6725
- }));
7535
+ }, branchParentId));
6726
7536
  if (result) {
6727
- const streamResult = await this._streamResult(requestId, result, abortSignal);
7537
+ const streamResult = await this._streamResult(requestId, result, abortSignal, {
7538
+ captureOutput: Boolean(workflowPrompt?.output),
7539
+ parentId: branchParentId
7540
+ });
6728
7541
  status = streamResult.status;
6729
7542
  error = streamResult.error;
6730
7543
  }
6731
7544
  };
6732
- await this._runChatRecoveryFiber(requestId, false, retryTurnBody);
7545
+ await this._runChatRecoveryFiber(requestId, false, retryTurnBody, branchParentId);
6733
7546
  } finally {
6734
7547
  if (abortSignal?.aborted) wasAborted = true;
6735
7548
  detachExternal();
@@ -6818,6 +7631,7 @@ var Think = class Think extends Agent {
6818
7631
  break;
6819
7632
  case "cancel":
6820
7633
  this._aborts.cancel(event.id);
7634
+ await this._cancelScheduledRecovery(event.id);
6821
7635
  break;
6822
7636
  case "messages":
6823
7637
  if (!this._loggedProtocolWarnings.has("client-pushed-messages")) {
@@ -6859,10 +7673,13 @@ var Think = class Think extends Agent {
6859
7673
  const requestId = event.id;
6860
7674
  let messagesPersisted = false;
6861
7675
  let failureStage = "persist";
7676
+ const requestOriginIds = originMessageIds(incomingMessages);
7677
+ if (requestOriginIds) this._requestOriginMessageIds.set(requestId, requestOriginIds);
6862
7678
  const concurrencyDecision = this._getSubmitConcurrencyDecision(isSubmitMessage);
6863
7679
  if (concurrencyDecision.action === "drop") {
6864
7680
  this._rollbackDroppedSubmit(connection);
6865
7681
  this._completeSkippedRequest(connection, requestId);
7682
+ this._requestOriginMessageIds.delete(requestId);
6866
7683
  return;
6867
7684
  }
6868
7685
  await withAgentSpan(this, "clear_previous_chat_state", "interaction", {
@@ -6902,7 +7719,8 @@ var Think = class Think extends Agent {
6902
7719
  const reconciledTurn = await this._reconcileAndPersistIncoming(incomingMessages, {
6903
7720
  requestId,
6904
7721
  isRegeneration,
6905
- isCurrent: () => this._turnQueue.generation === epoch
7722
+ isCurrent: () => this._turnQueue.generation === epoch,
7723
+ channel: "web"
6906
7724
  });
6907
7725
  if (!reconciledTurn) {
6908
7726
  this._completeSkippedRequest(connection, requestId);
@@ -6920,6 +7738,7 @@ var Think = class Think extends Agent {
6920
7738
  requestId,
6921
7739
  generation: epoch,
6922
7740
  continuation: false,
7741
+ channel: "web",
6923
7742
  onQueued: releaseIfPending,
6924
7743
  execute: async () => {
6925
7744
  if (this._submitConcurrency.isSuperseded(concurrencyDecision.submitSequence)) {
@@ -6949,7 +7768,7 @@ var Think = class Think extends Agent {
6949
7768
  clientTools: clientToolsForTurn,
6950
7769
  body: bodyForTurn,
6951
7770
  continuation: false
6952
- }));
7771
+ }, branchParentId));
6953
7772
  if (!result) {
6954
7773
  this._broadcastChat({
6955
7774
  type: MSG_CHAT_RESPONSE,
@@ -7002,13 +7821,14 @@ var Think = class Think extends Agent {
7002
7821
  return;
7003
7822
  }
7004
7823
  };
7005
- await this._runChatRecoveryFiber(requestId, false, chatTurnBody);
7824
+ await this._runChatRecoveryFiber(requestId, false, chatTurnBody, branchParentId);
7006
7825
  }
7007
7826
  })).status === "stale") this._broadcastChat({
7008
7827
  type: MSG_CHAT_RESPONSE,
7009
7828
  id: requestId,
7010
7829
  body: "",
7011
- done: true
7830
+ done: true,
7831
+ outcome: "skipped"
7012
7832
  });
7013
7833
  });
7014
7834
  } catch (error) {
@@ -7035,6 +7855,7 @@ var Think = class Think extends Agent {
7035
7855
  } finally {
7036
7856
  releaseIfPending();
7037
7857
  this._aborts.remove(requestId);
7858
+ this._requestOriginMessageIds.delete(requestId);
7038
7859
  this._settlePreStreamTurn(requestId);
7039
7860
  }
7040
7861
  }
@@ -7057,6 +7878,7 @@ var Think = class Think extends Agent {
7057
7878
  });
7058
7879
  this._autoContinuation.reset();
7059
7880
  this._submitConcurrency.reset();
7881
+ this._lastTurnChannel = void 0;
7060
7882
  this._pendingInteractionPromise = null;
7061
7883
  this._interactionApplyTail = Promise.resolve();
7062
7884
  this._streamingAssistant = null;
@@ -7087,6 +7909,28 @@ var Think = class Think extends Agent {
7087
7909
  */
7088
7910
  cancelChat(requestId, reason) {
7089
7911
  this._aborts.cancel(requestId, reason);
7912
+ this.keepAliveWhile(() => this._cancelScheduledRecovery(requestId));
7913
+ }
7914
+ /**
7915
+ * A cancel can land while the turn's recovery is waiting out its backoff,
7916
+ * with nothing in flight to abort: cancel the scheduled recovery instead,
7917
+ * so the queued callback bails when it fires.
7918
+ */
7919
+ async _cancelScheduledRecovery(requestId) {
7920
+ try {
7921
+ await this._chatRecoveryEngine().cancelScheduledRecovery(requestId);
7922
+ } catch (error) {
7923
+ console.error("[Think] failed to cancel a scheduled chat recovery", error);
7924
+ }
7925
+ }
7926
+ /**
7927
+ * Whether the user cancelled this recovery while it was scheduled. A
7928
+ * submission the recovery owned settles as `aborted`.
7929
+ */
7930
+ async _recoveryCancelled(data) {
7931
+ if (!await this._chatRecoveryEngine().isRecoveryCancelled(data?.incidentId)) return false;
7932
+ if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "aborted", null, null);
7933
+ return true;
7090
7934
  }
7091
7935
  /** Abort every in-flight chat turn on this agent. */
7092
7936
  cancelAllChats() {
@@ -7151,6 +7995,12 @@ var Think = class Think extends Agent {
7151
7995
  ...previous,
7152
7996
  input: normalizeToolInput(chunk.input).input
7153
7997
  });
7998
+ } else if (chunk.type === "tool-input-delta" && typeof chunk.inputTextDelta === "string") {
7999
+ const previous = pendingActionCalls.get(toolCallId);
8000
+ if (previous) pendingActionCalls.set(toolCallId, {
8001
+ ...previous,
8002
+ inputText: (previous.inputText ?? "") + chunk.inputTextDelta
8003
+ });
7154
8004
  }
7155
8005
  }
7156
8006
  if (chunk.type === "tool-output-available" && toolCallId) {
@@ -7182,7 +8032,7 @@ var Think = class Think extends Agent {
7182
8032
  toolCallId,
7183
8033
  action: metadata.actionName,
7184
8034
  summary: metadata.summary,
7185
- input: pending.input ?? {},
8035
+ input: pending.input ?? (pending.inputText !== void 0 ? normalizeToolInput(pending.inputText).input : {}),
7186
8036
  permissions: metadata.permissions ?? [],
7187
8037
  ...metadata.risk !== void 0 && { risk: metadata.risk },
7188
8038
  kind: metadata.kind
@@ -7258,10 +8108,14 @@ var Think = class Think extends Agent {
7258
8108
  this._streamingAssistant = accumulator;
7259
8109
  let streamFinalized = false;
7260
8110
  let assistantMsg = null;
8111
+ let persistedAssistantId;
8112
+ let streamDrained = false;
7261
8113
  let aborted = false;
7262
8114
  let doneSent = false;
7263
8115
  let streamError;
8116
+ let streamErrorCause;
7264
8117
  let pendingRpcError;
8118
+ let thrownError;
7265
8119
  let skipFinalizeRearm = false;
7266
8120
  let overflowRetry = false;
7267
8121
  const stallTimeoutMs = this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
@@ -7273,8 +8127,12 @@ var Think = class Think extends Agent {
7273
8127
  hasFlushedContent: false
7274
8128
  };
7275
8129
  const pendingActionCalls = /* @__PURE__ */ new Map();
8130
+ const approvalRequests = /* @__PURE__ */ new Map();
7276
8131
  try {
7277
- const guardedStream = iterateWithStallWatchdog(result.toUIMessageStream({ onError: streamErrorToString }), stallTimeoutMs, () => {
8132
+ const guardedStream = iterateWithStallWatchdog(result.toUIMessageStream({ onError: (error) => {
8133
+ streamErrorCause = error;
8134
+ return streamErrorToString(error);
8135
+ } }), stallTimeoutMs, () => {
7278
8136
  this._emit("chat:stream:stalled", {
7279
8137
  requestId,
7280
8138
  timeoutMs: stallTimeoutMs
@@ -7287,14 +8145,33 @@ var Think = class Think extends Agent {
7287
8145
  break;
7288
8146
  }
7289
8147
  const streamChunk = this._annotateActionApprovalChunk(requestId, chunk, pendingActionCalls, accumulator.parts);
8148
+ const lateToolInput = isLateToolInputChunk(accumulator.parts, streamChunk);
8149
+ if (streamChunk.type === "tool-approval-request") approvalRequests.set(streamChunk.toolCallId ?? "", streamChunk);
7290
8150
  const { action } = accumulator.applyChunk(streamChunk);
7291
8151
  this._applyActionApprovalDescriptorToParts(streamChunk, accumulator.parts);
8152
+ if (lateToolInput) {
8153
+ for (const forwarded of lateToolInputForwardChunks(accumulator.parts, streamChunk, approvalRequests.get(streamChunk.toolCallId ?? ""))) {
8154
+ const chunkBody = JSON.stringify(forwarded);
8155
+ const seq = await this._storeChunkDurably(streamId, forwarded, chunkBody, flushState);
8156
+ this._broadcastChat({
8157
+ type: MSG_CHAT_RESPONSE,
8158
+ id: requestId,
8159
+ body: chunkBody,
8160
+ done: false,
8161
+ ...seq !== void 0 && { seq }
8162
+ });
8163
+ await callback.onEvent(chunkBody);
8164
+ }
8165
+ continue;
8166
+ }
7292
8167
  if (action?.type === "error") {
7293
8168
  streamError = action.error;
7294
- if (options?.overflowRecovery && this._isRecoverableContextOverflow(streamError, requestId)) {
8169
+ const classification = this._classifyStreamError(streamErrorCause ?? streamError, requestId);
8170
+ if (options?.overflowRecovery && this._isRecoverableContextOverflow(classification)) {
7295
8171
  overflowRetry = true;
7296
8172
  break;
7297
8173
  }
8174
+ if (isTransientClassification(classification) && !isDurableObjectResetError(streamErrorCause ?? streamError)) throw new TransientChatStreamError(streamError, classification, streamErrorCause);
7298
8175
  this._emit("message:error", { error: streamError });
7299
8176
  this._emit("chat:request:failed", {
7300
8177
  requestId,
@@ -7313,12 +8190,13 @@ var Think = class Think extends Agent {
7313
8190
  }
7314
8191
  this._alignStreamStartId(streamChunk, action, accumulator, false);
7315
8192
  const chunkBody = JSON.stringify(streamChunk);
7316
- await this._storeChunkDurably(streamId, streamChunk, chunkBody, flushState);
8193
+ const seq = await this._storeChunkDurably(streamId, streamChunk, chunkBody, flushState);
7317
8194
  this._broadcastChat({
7318
8195
  type: MSG_CHAT_RESPONSE,
7319
8196
  id: requestId,
7320
8197
  body: chunkBody,
7321
- done: false
8198
+ done: false,
8199
+ ...seq !== void 0 && { seq }
7322
8200
  });
7323
8201
  await callback.onEvent(chunkBody);
7324
8202
  }
@@ -7335,64 +8213,62 @@ var Think = class Think extends Agent {
7335
8213
  error: streamError
7336
8214
  };
7337
8215
  }
8216
+ streamDrained = true;
7338
8217
  if (streamError) this._errorResumableStream(streamId, requestId);
7339
- else this._finishResumableStream(streamId);
8218
+ else this._finishResumableStream(streamId, aborted ? "aborted" : "completed");
7340
8219
  streamFinalized = true;
7341
- this._broadcastChat({
7342
- type: MSG_CHAT_RESPONSE,
7343
- id: requestId,
7344
- body: "",
7345
- done: true
7346
- });
7347
- doneSent = true;
7348
8220
  assistantMsg = accumulator.toMessage();
8221
+ const response = {
8222
+ message: assistantMsg,
8223
+ requestId,
8224
+ continuation: false,
8225
+ status: streamError ? "error" : aborted ? "aborted" : "completed",
8226
+ ...streamError && { error: streamError }
8227
+ };
7349
8228
  if (accumulator.parts.length > 0) {
7350
- await this._persistAssistantMessageWithCutover(streamId, assistantMsg, void 0, this._streamCutoverOptions(requestId), {
8229
+ await this._rememberPendingResponseHook(response);
8230
+ persistedAssistantId = await this._persistAssistantMessageWithCutover(streamId, assistantMsg, void 0, this._streamCutoverOptions(requestId), {
7351
8231
  requestId,
7352
8232
  result: { status: aborted ? "aborted" : "completed" }
7353
8233
  });
7354
8234
  this._broadcastMessages();
7355
8235
  }
7356
- this._finalizeSubmissionStream(requestId, { status: aborted ? "aborted" : "completed" });
7357
- if (streamError) {
7358
- await this._fireResponseHook({
7359
- message: assistantMsg,
7360
- requestId,
7361
- continuation: false,
7362
- status: "error",
7363
- error: streamError
7364
- });
7365
- pendingRpcError = streamError;
7366
- } else if (!aborted) {
7367
- await callback.onDone();
7368
- await this._fireResponseHook({
7369
- message: assistantMsg,
7370
- requestId,
7371
- continuation: false,
7372
- status: "completed"
7373
- });
7374
- } else await this._fireResponseHook({
7375
- message: assistantMsg,
7376
- requestId,
7377
- continuation: false,
7378
- status: "aborted"
8236
+ this._broadcastChat({
8237
+ type: MSG_CHAT_RESPONSE,
8238
+ id: requestId,
8239
+ body: "",
8240
+ done: true,
8241
+ outcome: response.status
7379
8242
  });
8243
+ doneSent = true;
8244
+ this._finalizeSubmissionStream(requestId, { status: aborted ? "aborted" : "completed" });
8245
+ if (streamError) pendingRpcError = streamError;
8246
+ else if (!aborted) await callback.onDone();
8247
+ await this._fireLiveResponseHook(response);
7380
8248
  } catch (error) {
7381
- if (error instanceof ChatStreamStalledError) {
7382
- if (!assistantMsg && accumulator.parts.length > 0) {
7383
- assistantMsg = accumulator.toMessage();
7384
- await this._persistAssistantMessage(assistantMsg);
7385
- this._broadcastMessages();
7386
- }
7387
- const outcome = await this._routeStallToBoundedRecovery({
8249
+ const stalled = error instanceof ChatStreamStalledError;
8250
+ const transientClassification = stalled || streamDrained || abortSignal?.aborted ? void 0 : this._transientStreamClassification(error, requestId);
8251
+ if (!streamDrained && (stalled || transientClassification)) {
8252
+ const outcome = await this._routeStreamInterruption({
7388
8253
  requestId,
7389
8254
  streamId,
7390
- partialParts: (assistantMsg ?? accumulator.toMessage()).parts,
7391
- targetAssistantId: assistantMsg?.id
8255
+ backoff: !stalled,
8256
+ retryAfterSeconds: this._streamErrorRetryAfter(error, transientClassification),
8257
+ partialParts: accumulator.toMessage().parts,
8258
+ persistPartial: async () => {
8259
+ if (persistedAssistantId) return persistedAssistantId;
8260
+ if (accumulator.parts.length === 0) return void 0;
8261
+ const partial = accumulator.toMessage();
8262
+ if (!await this._persistAssistantMessage(partial)) return;
8263
+ assistantMsg = partial;
8264
+ persistedAssistantId = partial.id;
8265
+ this._broadcastMessages();
8266
+ return persistedAssistantId;
8267
+ }
7392
8268
  });
7393
8269
  if (outcome === "scheduled") {
7394
8270
  if (!streamFinalized) {
7395
- this._completeResumableStream(streamId);
8271
+ this._completeResumableStream(streamId, "recovering");
7396
8272
  streamFinalized = true;
7397
8273
  }
7398
8274
  if (!doneSent) {
@@ -7400,15 +8276,16 @@ var Think = class Think extends Agent {
7400
8276
  type: MSG_CHAT_RESPONSE,
7401
8277
  id: requestId,
7402
8278
  body: "",
7403
- done: true
8279
+ done: true,
8280
+ outcome: "recovering"
7404
8281
  });
7405
8282
  doneSent = true;
7406
8283
  }
7407
8284
  skipFinalizeRearm = true;
7408
- await callback.onInterrupted?.();
8285
+ await callback.onInterrupted?.(this._messengerRecoveryClaims.delete(requestId) ? { deliversRecoveredReply: true } : void 0);
7409
8286
  return { status: "aborted" };
7410
8287
  }
7411
- if (outcome === "exhausted") {
8288
+ if (outcome === "exhausted" || outcome === "declined") {
7412
8289
  if (!streamFinalized) {
7413
8290
  this._errorResumableStream(streamId, requestId);
7414
8291
  streamFinalized = true;
@@ -7419,25 +8296,28 @@ var Think = class Think extends Agent {
7419
8296
  return { status: "aborted" };
7420
8297
  }
7421
8298
  }
7422
- if (!streamFinalized) {
8299
+ if (!streamFinalized || this._resumableStream.pendingCutoverId === streamId) {
7423
8300
  this._errorResumableStream(streamId, requestId);
7424
8301
  streamFinalized = true;
7425
8302
  }
7426
- if (!doneSent) {
7427
- const streamError = error instanceof Error ? error.message : "Stream error";
7428
- this._broadcastChat({
7429
- type: MSG_CHAT_RESPONSE,
7430
- id: requestId,
7431
- body: streamError,
7432
- done: true,
7433
- error: true
7434
- });
7435
- doneSent = true;
7436
- }
7437
- if (!assistantMsg && accumulator.parts.length > 0) {
7438
- assistantMsg = accumulator.toMessage();
7439
- await this._persistAssistantMessage(assistantMsg);
7440
- this._broadcastMessages();
8303
+ try {
8304
+ if (!assistantMsg && accumulator.parts.length > 0) {
8305
+ assistantMsg = accumulator.toMessage();
8306
+ await this._persistAssistantMessage(assistantMsg);
8307
+ this._broadcastMessages();
8308
+ }
8309
+ } finally {
8310
+ if (!doneSent) {
8311
+ const streamError = error instanceof Error ? error.message : "Stream error";
8312
+ this._broadcastChat({
8313
+ type: MSG_CHAT_RESPONSE,
8314
+ id: requestId,
8315
+ body: streamError,
8316
+ done: true,
8317
+ error: true
8318
+ });
8319
+ doneSent = true;
8320
+ }
7441
8321
  }
7442
8322
  const wrapped = this.onChatError(error, {
7443
8323
  requestId,
@@ -7445,26 +8325,33 @@ var Think = class Think extends Agent {
7445
8325
  messagesPersisted: true
7446
8326
  });
7447
8327
  const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
8328
+ thrownError = errorMessage;
7448
8329
  this._emit("chat:request:failed", {
7449
8330
  requestId,
7450
8331
  stage: "stream",
7451
8332
  messagesPersisted: true,
7452
8333
  error: errorMessage
7453
8334
  });
7454
- if (assistantMsg) await this._fireResponseHook({
8335
+ if (assistantMsg) await this._fireLiveResponseHook({
7455
8336
  message: assistantMsg,
7456
8337
  requestId,
7457
8338
  continuation: false,
7458
8339
  status: "error",
7459
8340
  error: errorMessage
7460
8341
  });
8342
+ else await this._forgetPendingResponseHook(requestId).catch(() => {});
7461
8343
  await callback.onError(errorMessage);
7462
8344
  } finally {
7463
8345
  if (skipFinalizeRearm) this._streamingAssistant = null;
7464
8346
  else this._onStreamingTurnFinalized();
7465
8347
  }
7466
8348
  if (pendingRpcError) await callback.onError(pendingRpcError);
7467
- return { status: streamError || pendingRpcError ? "error" : aborted ? "aborted" : "completed" };
8349
+ const error = thrownError ?? pendingRpcError ?? streamError;
8350
+ if (error !== void 0) return {
8351
+ status: "error",
8352
+ error
8353
+ };
8354
+ return { status: aborted ? "aborted" : "completed" };
7468
8355
  }
7469
8356
  /**
7470
8357
  * Whether storing this chunk should immediately flush the resumable-stream
@@ -7490,28 +8377,42 @@ var Think = class Think extends Agent {
7490
8377
  * step, never an already-completed tool call).
7491
8378
  */
7492
8379
  async _storeChunkDurably(streamId, chunk, chunkBody, state) {
7493
- this._resumableStream.storeChunk(streamId, chunkBody);
8380
+ const seq = this._resumableStream.storeChunk(streamId, chunkBody);
7494
8381
  state.chunksSinceFlush++;
7495
8382
  if (this._shouldFlushRecoverableChunk(chunk, state.chunksSinceFlush, state.hasFlushedContent)) {
7496
8383
  this._resumableStream.flushBuffer();
7497
8384
  state.chunksSinceFlush = 0;
7498
8385
  state.hasFlushedContent = true;
7499
8386
  }
8387
+ return seq;
7500
8388
  }
7501
8389
  async _streamResult(requestId, result, abortSignal, options) {
7502
8390
  const clearGen = this._turnQueue.generation;
7503
- const streamId = this._startResumableStream(requestId);
7504
8391
  const continuation = options?.continuation ?? false;
7505
8392
  const parentId = options?.parentId;
8393
+ const streamId = this._startResumableStream(requestId, {
8394
+ continuation,
8395
+ ...parentId !== void 0 && { parentMessageId: parentId }
8396
+ });
7506
8397
  if (this._continuation.pending?.requestId === requestId) {
7507
8398
  this._continuation.activatePending();
7508
8399
  this._continuation.flushAwaitingConnections((c) => this._notifyStreamResuming(c));
7509
8400
  }
7510
- const accumulator = new StreamAccumulator({ messageId: crypto.randomUUID() });
8401
+ const leaf = this.messages.at(-1);
8402
+ const continuationAssistant = continuation && options?.extendLeafAssistant && leaf?.role === "assistant" ? leaf : void 0;
8403
+ const leafMetadata = continuationAssistant?.metadata;
8404
+ const accumulator = new StreamAccumulator({
8405
+ messageId: continuationAssistant?.id ?? crypto.randomUUID(),
8406
+ continuation: continuationAssistant !== void 0,
8407
+ existingParts: continuationAssistant?.parts.map(settleInterruptedPart),
8408
+ existingMetadata: leafMetadata !== null && typeof leafMetadata === "object" ? leafMetadata : void 0
8409
+ });
7511
8410
  this._streamingAssistant = accumulator;
7512
8411
  let doneSent = false;
8412
+ let terminalFrame;
7513
8413
  let streamAborted = false;
7514
8414
  let streamError;
8415
+ let streamErrorCause;
7515
8416
  let output;
7516
8417
  let overflowRetry = false;
7517
8418
  const flushState = {
@@ -7519,12 +8420,16 @@ var Think = class Think extends Agent {
7519
8420
  hasFlushedContent: false
7520
8421
  };
7521
8422
  const pendingActionCalls = /* @__PURE__ */ new Map();
8423
+ const approvalRequests = /* @__PURE__ */ new Map();
7522
8424
  const stallTimeoutMs = this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
7523
8425
  let streamDrainedNaturally = false;
7524
8426
  try {
7525
8427
  this._insideInferenceLoop = true;
7526
8428
  try {
7527
- const guardedStream = iterateWithStallWatchdog(result.toUIMessageStream({ onError: streamErrorToString }), stallTimeoutMs, () => {
8429
+ const guardedStream = iterateWithStallWatchdog(result.toUIMessageStream({ onError: (error) => {
8430
+ streamErrorCause = error;
8431
+ return streamErrorToString(error);
8432
+ } }), stallTimeoutMs, () => {
7528
8433
  this._emit("chat:stream:stalled", {
7529
8434
  requestId,
7530
8435
  timeoutMs: stallTimeoutMs
@@ -7536,16 +8441,35 @@ var Think = class Think extends Agent {
7536
8441
  streamAborted = true;
7537
8442
  break;
7538
8443
  }
7539
- const streamChunk = this._annotateActionApprovalChunk(requestId, chunk, pendingActionCalls, accumulator.parts);
8444
+ const streamChunk = withoutOverwrittenStartMetadata(this._annotateActionApprovalChunk(requestId, chunk, pendingActionCalls, accumulator.parts), continuationAssistant ? leafMetadata : void 0);
8445
+ const lateToolInput = isLateToolInputChunk(accumulator.parts, streamChunk);
8446
+ if (streamChunk.type === "tool-approval-request") approvalRequests.set(streamChunk.toolCallId ?? "", streamChunk);
7540
8447
  const { action } = accumulator.applyChunk(streamChunk);
7541
8448
  this._applyActionApprovalDescriptorToParts(streamChunk, accumulator.parts);
8449
+ if (lateToolInput) {
8450
+ for (const forwarded of lateToolInputForwardChunks(accumulator.parts, streamChunk, approvalRequests.get(streamChunk.toolCallId ?? ""))) {
8451
+ const chunkBody = JSON.stringify(forwarded);
8452
+ const seq = await this._storeChunkDurably(streamId, forwarded, chunkBody, flushState);
8453
+ this._broadcastChat({
8454
+ type: MSG_CHAT_RESPONSE,
8455
+ id: requestId,
8456
+ body: chunkBody,
8457
+ done: false,
8458
+ ...seq !== void 0 && { seq },
8459
+ ...continuation && { continuation: true }
8460
+ });
8461
+ }
8462
+ continue;
8463
+ }
7542
8464
  if (action?.type === "cross-message-tool-update") await this._applyToolUpdateToMessages(crossMessageToolResultUpdate(action.toolCallId, action.updateType, action.output, action.errorText, action.preliminary));
7543
8465
  if (action?.type === "error") {
7544
8466
  streamError = action.error;
7545
- if (options?.overflowRecovery && this._isRecoverableContextOverflow(streamError, requestId)) {
8467
+ const classification = this._classifyStreamError(streamErrorCause ?? streamError, requestId);
8468
+ if (options?.overflowRecovery && this._isRecoverableContextOverflow(classification)) {
7546
8469
  overflowRetry = true;
7547
8470
  break;
7548
8471
  }
8472
+ if (isTransientClassification(classification) && !isDurableObjectResetError(streamErrorCause ?? streamError)) throw new TransientChatStreamError(streamError, classification, streamErrorCause);
7549
8473
  if (options?.captureProgrammaticStreamError) this._programmaticStreamErrors.set(requestId, streamError);
7550
8474
  this._emit("message:error", { error: streamError });
7551
8475
  this._emit("chat:request:failed", {
@@ -7566,12 +8490,13 @@ var Think = class Think extends Agent {
7566
8490
  }
7567
8491
  this._alignStreamStartId(streamChunk, action, accumulator, continuation);
7568
8492
  const chunkBody = JSON.stringify(streamChunk);
7569
- await this._storeChunkDurably(streamId, streamChunk, chunkBody, flushState);
8493
+ const seq = await this._storeChunkDurably(streamId, streamChunk, chunkBody, flushState);
7570
8494
  this._broadcastChat({
7571
8495
  type: MSG_CHAT_RESPONSE,
7572
8496
  id: requestId,
7573
8497
  body: chunkBody,
7574
8498
  done: false,
8499
+ ...seq !== void 0 && { seq },
7575
8500
  ...continuation && { continuation: true }
7576
8501
  });
7577
8502
  }
@@ -7589,33 +8514,38 @@ var Think = class Think extends Agent {
7589
8514
  return { status: "aborted" };
7590
8515
  }
7591
8516
  if (streamError) this._errorResumableStream(streamId, requestId);
7592
- else this._finishResumableStream(streamId);
8517
+ else this._finishResumableStream(streamId, streamAborted ? "aborted" : "completed");
7593
8518
  this._pendingResumeConnections.clear();
7594
- this._broadcastChat({
8519
+ terminalFrame = {
7595
8520
  type: MSG_CHAT_RESPONSE,
7596
8521
  id: requestId,
7597
8522
  body: "",
7598
8523
  done: true,
8524
+ outcome: streamError ? "error" : streamAborted ? "aborted" : "completed",
7599
8525
  ...continuation && { continuation: true }
7600
- });
8526
+ };
7601
8527
  doneSent = true;
7602
8528
  } catch (error) {
7603
- if (error instanceof ChatStreamStalledError) {
7604
- let targetAssistantId;
8529
+ const stalled = error instanceof ChatStreamStalledError;
8530
+ const transientClassification = stalled || abortSignal?.aborted ? void 0 : this._transientStreamClassification(error, requestId);
8531
+ if (stalled || transientClassification) {
7605
8532
  const partialMsg = accumulator.toMessage();
7606
- if (this._turnQueue.generation === clearGen && accumulator.parts.length > 0) {
7607
- await this._persistAssistantMessage(partialMsg, parentId);
7608
- this._broadcastMessages();
7609
- targetAssistantId = partialMsg.id;
7610
- }
7611
- const outcome = await this._routeStallToBoundedRecovery({
8533
+ const outcome = await this._routeStreamInterruption({
7612
8534
  requestId,
7613
8535
  streamId,
8536
+ backoff: !stalled,
8537
+ retryAfterSeconds: this._streamErrorRetryAfter(error, transientClassification),
7614
8538
  partialParts: partialMsg.parts,
7615
- targetAssistantId
8539
+ branchParentId: parentId,
8540
+ persistPartial: async () => {
8541
+ if (this._turnQueue.generation !== clearGen || accumulator.parts.length === 0) return;
8542
+ if (!await this._persistAssistantMessage(partialMsg, parentId)) return;
8543
+ this._broadcastMessages();
8544
+ return partialMsg.id;
8545
+ }
7616
8546
  });
7617
8547
  if (outcome === "scheduled") {
7618
- this._completeResumableStream(streamId);
8548
+ this._completeResumableStream(streamId, "recovering");
7619
8549
  this._pendingResumeConnections.clear();
7620
8550
  if (!doneSent) {
7621
8551
  this._broadcastChat({
@@ -7623,6 +8553,7 @@ var Think = class Think extends Agent {
7623
8553
  id: requestId,
7624
8554
  body: "",
7625
8555
  done: true,
8556
+ outcome: "recovering",
7626
8557
  ...continuation && { continuation: true }
7627
8558
  });
7628
8559
  doneSent = true;
@@ -7630,7 +8561,7 @@ var Think = class Think extends Agent {
7630
8561
  this._streamingAssistant = null;
7631
8562
  return { status: "aborted" };
7632
8563
  }
7633
- if (outcome === "exhausted") {
8564
+ if (outcome === "exhausted" || outcome === "declined") {
7634
8565
  this._errorResumableStream(streamId, requestId);
7635
8566
  this._pendingResumeConnections.clear();
7636
8567
  doneSent = true;
@@ -7643,63 +8574,90 @@ var Think = class Think extends Agent {
7643
8574
  this._errorResumableStream(streamId, requestId);
7644
8575
  this._pendingResumeConnections.clear();
7645
8576
  if (!doneSent) {
7646
- this._broadcastChat({
8577
+ terminalFrame = {
7647
8578
  type: MSG_CHAT_RESPONSE,
7648
8579
  id: requestId,
7649
8580
  body: streamError,
7650
8581
  done: true,
7651
8582
  error: true,
7652
8583
  ...continuation && { continuation: true }
7653
- });
8584
+ };
7654
8585
  doneSent = true;
7655
8586
  }
7656
8587
  } finally {
7657
8588
  if (!doneSent) {
7658
8589
  this._errorResumableStream(streamId, requestId);
7659
8590
  this._pendingResumeConnections.clear();
7660
- this._broadcastChat({
8591
+ terminalFrame = {
7661
8592
  type: MSG_CHAT_RESPONSE,
7662
8593
  id: requestId,
7663
8594
  body: "",
7664
8595
  done: true,
7665
8596
  ...continuation && { continuation: true }
7666
- });
8597
+ };
7667
8598
  }
7668
8599
  }
7669
- if (options?.captureOutput && result.output && !streamError && !streamAborted) try {
7670
- output = await result.output;
7671
- } catch (error) {
7672
- streamError = error instanceof Error ? error.message : "Structured output error";
7673
- if (options.captureProgrammaticStreamError) this._programmaticStreamErrors.set(requestId, streamError);
7674
- this._errorResumableStream(streamId, requestId);
7675
- }
7676
- const submissionResult = streamAborted ? { status: "aborted" } : {
7677
- status: "completed",
7678
- output
8600
+ const sendTerminalFrame = () => {
8601
+ if (!terminalFrame) return;
8602
+ this._broadcastChat(terminalFrame);
8603
+ terminalFrame = void 0;
7679
8604
  };
7680
- if (this._turnQueue.generation === clearGen) try {
7681
- const assistantMsg = accumulator.toMessage();
7682
- if (accumulator.parts.length > 0) {
7683
- await this._persistAssistantMessageWithCutover(streamId, assistantMsg, parentId, this._streamCutoverOptions(requestId), {
8605
+ try {
8606
+ if (options?.captureOutput && result.output && !streamError && !streamAborted) try {
8607
+ output = await result.output;
8608
+ } catch (error) {
8609
+ streamError = error instanceof Error ? error.message : "Structured output error";
8610
+ if (options.captureProgrammaticStreamError) this._programmaticStreamErrors.set(requestId, streamError);
8611
+ this._errorResumableStream(streamId, requestId);
8612
+ if (terminalFrame) terminalFrame = {
8613
+ ...terminalFrame,
8614
+ outcome: "error"
8615
+ };
8616
+ }
8617
+ const submissionResult = streamAborted ? { status: "aborted" } : {
8618
+ status: "completed",
8619
+ output
8620
+ };
8621
+ if (this._turnQueue.generation === clearGen) try {
8622
+ const assistantMsg = accumulator.toMessage();
8623
+ const response = {
8624
+ message: assistantMsg,
7684
8625
  requestId,
7685
- result: submissionResult
7686
- });
7687
- this._broadcastMessages();
8626
+ continuation,
8627
+ status: streamError ? "error" : streamAborted ? "aborted" : "completed",
8628
+ error: streamError
8629
+ };
8630
+ if (accumulator.parts.length > 0) {
8631
+ await this._rememberPendingResponseHook(response);
8632
+ const persistedMessageId = await this._persistAssistantMessageWithCutover(streamId, assistantMsg, parentId, this._streamCutoverOptions(requestId), {
8633
+ requestId,
8634
+ result: submissionResult
8635
+ });
8636
+ if (!streamError && !streamAborted && persistedMessageId !== void 0) {
8637
+ const capture = waitTurnResultContext.getStore();
8638
+ if (capture?.agent === this) capture.messageIds.set(requestId, persistedMessageId);
8639
+ }
8640
+ this._broadcastMessages();
8641
+ }
8642
+ sendTerminalFrame();
8643
+ this._finalizeSubmissionStream(requestId, submissionResult);
8644
+ await this._fireLiveResponseHook(response);
8645
+ } catch (e) {
8646
+ await this._forgetPendingResponseHook(requestId).catch(() => {});
8647
+ console.error("Failed to persist assistant message:", e);
8648
+ streamError = e instanceof Error ? e.message : "Assistant message persistence failed";
8649
+ this._errorResumableStream(streamId, requestId);
8650
+ if (terminalFrame && !terminalFrame.error) terminalFrame = {
8651
+ ...terminalFrame,
8652
+ body: streamError,
8653
+ error: true,
8654
+ outcome: "error"
8655
+ };
7688
8656
  }
7689
8657
  this._finalizeSubmissionStream(requestId, submissionResult);
7690
- await this._fireResponseHook({
7691
- message: assistantMsg,
7692
- requestId,
7693
- continuation,
7694
- status: streamError ? "error" : streamAborted ? "aborted" : "completed",
7695
- error: streamError
7696
- });
7697
- } catch (e) {
7698
- console.error("Failed to persist assistant message:", e);
7699
- streamError = e instanceof Error ? e.message : "Assistant message persistence failed";
7700
- this._errorResumableStream(streamId, requestId);
8658
+ } finally {
8659
+ sendTerminalFrame();
7701
8660
  }
7702
- this._finalizeSubmissionStream(requestId, submissionResult);
7703
8661
  this._onStreamingTurnFinalized();
7704
8662
  return streamError ? {
7705
8663
  status: "error",
@@ -7724,10 +8682,12 @@ var Think = class Think extends Agent {
7724
8682
  if (stripped === msg) return msg;
7725
8683
  return stripped.parts.some((part) => part.type !== "step-start") ? stripped : null;
7726
8684
  }
8685
+ /** Resolves to `false` when stripping left nothing to persist. */
7727
8686
  async _persistAssistantMessage(msg, parentId) {
7728
8687
  const toPersist = this._strippedForPersist(msg);
7729
- if (toPersist === null) return;
8688
+ if (toPersist === null) return false;
7730
8689
  await this._upsertMessageInHistory(toPersist, parentId);
8690
+ return true;
7731
8691
  }
7732
8692
  /**
7733
8693
  * The cutover: persist the finished turn's assistant message, settle its
@@ -7738,10 +8698,11 @@ var Think = class Think extends Agent {
7738
8698
  */
7739
8699
  async _persistAssistantMessageWithCutover(streamId, msg, parentId, options = {}, submission) {
7740
8700
  const toPersist = this._strippedForPersist(msg);
7741
- if (toPersist === null) return;
8701
+ if (toPersist === null) return void 0;
7742
8702
  if (this._resumableStream.pendingCutoverId !== streamId) {
7743
8703
  await this._upsertMessageInHistory(toPersist, parentId);
7744
- return;
8704
+ if (submission) this._recordSubmissionMessage(submission.requestId, toPersist.id);
8705
+ return toPersist.id;
7745
8706
  }
7746
8707
  const sync = this.sessions.session().__DO_NOT_USE_WILL_BREAK__sync();
7747
8708
  let after;
@@ -7751,13 +8712,14 @@ var Think = class Think extends Agent {
7751
8712
  parentId,
7752
8713
  source: "server"
7753
8714
  }).after;
7754
- if (submission) this._recordSubmissionTurnResult(submission.requestId, submission.result);
8715
+ if (submission) this._recordSubmissionTurnResult(submission.requestId, submission.result, toPersist.id);
7755
8716
  }, options);
7756
8717
  } catch (error) {
7757
8718
  sync.abandon();
7758
8719
  throw error;
7759
8720
  }
7760
8721
  await after?.();
8722
+ return toPersist.id;
7761
8723
  }
7762
8724
  /**
7763
8725
  * Whether this turn's stream rows can go with its cutover. An agent-tool
@@ -7771,14 +8733,46 @@ var Think = class Think extends Agent {
7771
8733
  return { discard: !this._agentToolRunsByRequestId.get(requestId) };
7772
8734
  }
7773
8735
  /** Write only inside the transaction that settles this exact request's stream. */
7774
- _recordSubmissionTurnResult(requestId, result) {
8736
+ _recordSubmissionTurnResult(requestId, result, messageId) {
7775
8737
  const row = this._readRunningSubmissionForRecovery(requestId);
7776
- if (!row || row.request_id !== requestId) return;
8738
+ if (!row || row.request_id !== requestId) {
8739
+ if (messageId) this._recordAbortedSubmissionMessage(requestId, messageId);
8740
+ return;
8741
+ }
7777
8742
  this.sql`
7778
8743
  UPDATE cf_think_submissions
7779
8744
  SET result_status = ${result.status},
7780
- output_json = ${result.status === "completed" && result.output !== void 0 ? JSON.stringify(result.output) : null}
8745
+ output_json = ${result.status === "completed" && result.output !== void 0 ? JSON.stringify(result.output) : null},
8746
+ message_id = COALESCE(${messageId ?? null}, message_id)
8747
+ WHERE submission_id = ${row.submission_id} AND status = 'running'
8748
+ `;
8749
+ }
8750
+ _recordSubmissionMessage(requestId, messageId) {
8751
+ const row = this._readRunningSubmissionForRecovery(requestId);
8752
+ if (!row || row.request_id !== requestId) {
8753
+ this._recordAbortedSubmissionMessage(requestId, messageId);
8754
+ return;
8755
+ }
8756
+ this.sql`
8757
+ UPDATE cf_think_submissions
8758
+ SET message_id = ${messageId}
7781
8759
  WHERE submission_id = ${row.submission_id} AND status = 'running'
8760
+ `;
8761
+ }
8762
+ /**
8763
+ * Cancellation settles a submission as `aborted` before the stream persists
8764
+ * its partial; link that message without touching the terminal status. A
8765
+ * row that never started (a reused submission id cancelled while queued)
8766
+ * cannot own the partial.
8767
+ */
8768
+ _recordAbortedSubmissionMessage(requestId, messageId) {
8769
+ this.sql`
8770
+ UPDATE cf_think_submissions
8771
+ SET message_id = ${messageId}
8772
+ WHERE request_id = ${requestId}
8773
+ AND status = 'aborted'
8774
+ AND started_at IS NOT NULL
8775
+ AND message_id IS NULL
7782
8776
  `;
7783
8777
  }
7784
8778
  /** Empty/stripped messages have the same atomic outcome cutover as messages. */
@@ -7836,14 +8830,14 @@ var Think = class Think extends Agent {
7836
8830
  };
7837
8831
  const serverMessages = await withAgentSpan(this, "load_chat_history", "interaction", spanAttributes, () => this._serverTranscriptForReconcile());
7838
8832
  const serverMessagesById = new Map(serverMessages.map((message) => [message.id, message]));
7839
- const reconciled = reconcileMessages(incomingMessages, serverMessages, sanitizeMessage);
8833
+ const reconciled = keepResolvedPauses(reconcileMessages(incomingMessages, serverMessages, sanitizeMessage), serverMessages);
7840
8834
  let branchParentId;
7841
8835
  if (options.isRegeneration && reconciled.length > 0) branchParentId = reconciled[reconciled.length - 1].id;
7842
8836
  return await withAgentSpan(this, "persist_incoming_messages", "interaction", spanAttributes, async () => {
7843
8837
  if (!options.isCurrent()) return false;
7844
8838
  for (const msg of reconciled) {
7845
8839
  if (!options.isCurrent()) return false;
7846
- await this._persistIncomingMessage(msg, serverMessages, serverMessagesById);
8840
+ await this._persistIncomingMessage(msg, serverMessagesById, options.channel);
7847
8841
  }
7848
8842
  if (!options.isCurrent()) return false;
7849
8843
  if (!this._cacheCoversActivePath) await this._syncMessages();
@@ -7865,22 +8859,36 @@ var Think = class Think extends Agent {
7865
8859
  return this._readMessagesFromStorage();
7866
8860
  }
7867
8861
  /**
7868
- * Persist an incoming message after reconciliation. For assistant
7869
- * messages, also resolve their ID against any server-side row that
7870
- * already owns the same `toolCallId` so we update the existing row
7871
- * instead of inserting an orphan duplicate.
8862
+ * Persist an incoming message after batch reconciliation has resolved
8863
+ * assistant IDs (one-to-one against server rows) and merged any
8864
+ * server-owned tool outputs.
7872
8865
  *
7873
8866
  * A message whose stored form is what the server already holds is skipped
7874
8867
  * outright. The client posts its whole transcript on every request, so
7875
8868
  * without this every prior message would cost Sessions an existence read
7876
8869
  * plus a full-row compare (and, for media, a decode and hash of every
7877
8870
  * payload) per turn — reads spent discovering nothing changed.
7878
- */
7879
- async _persistIncomingMessage(msg, serverMessages, serverMessagesById) {
7880
- const resolved = msg.role === "assistant" ? resolveToolMergeId(msg, serverMessages) : msg;
7881
- const prior = serverMessagesById?.get(resolved.id);
7882
- if (prior && JSON.stringify(prior) === JSON.stringify(stripReservedMetadata(sanitizeMessage(resolved)))) return;
7883
- await this._upsertMessageInHistory(resolved, void 0, "client");
8871
+ *
8872
+ * Reserved metadata (`channel`, `turnMetadata`) is server-owned. The client's
8873
+ * copy is ignored, a stored row keeps its own, and a new user message gets
8874
+ * `channel` when the caller supplies one.
8875
+ */
8876
+ async _persistIncomingMessage(msg, serverMessagesById, channel) {
8877
+ const prior = serverMessagesById?.get(msg.id);
8878
+ const incoming = stripReservedMetadata(sanitizeMessage(msg));
8879
+ if (prior && JSON.stringify(stripReservedMetadata(prior)) === JSON.stringify(incoming)) return;
8880
+ const reserved = prior ? reservedMetadataOf(prior) : incoming.role === "user" && channel ? { channel } : void 0;
8881
+ if (!reserved) {
8882
+ await this._upsertMessageInHistory(msg, void 0, "client");
8883
+ return;
8884
+ }
8885
+ await this._upsertMessageInHistory({
8886
+ ...incoming,
8887
+ metadata: {
8888
+ ...incoming.metadata,
8889
+ ...reserved
8890
+ }
8891
+ }, void 0, "server");
7884
8892
  }
7885
8893
  _persistRequestContextKey(key, value) {
7886
8894
  const json = value ? JSON.stringify(value) : void 0;
@@ -8157,11 +9165,13 @@ var Think = class Think extends Agent {
8157
9165
  * transcript's paused output is replaced with
8158
9166
  * `{ status: "rejected", executionId, reason }` and the chat
8159
9167
  * auto-continues so the model can adapt (or explain) instead of erroring.
9168
+ * Pass `{ autoContinue: false }` to record the rejection without starting a
9169
+ * model continuation.
8160
9170
  *
8161
9171
  * Client-callable.
8162
9172
  */
8163
- async rejectExecution(executionId, reason) {
8164
- if (executionId.startsWith(ACTION_PAUSE_ID_PREFIX)) return await this._rejectActionPause(executionId, reason);
9173
+ async rejectExecution(executionId, reason, options) {
9174
+ if (executionId.startsWith(ACTION_PAUSE_ID_PREFIX)) return await this._rejectActionPause(executionId, reason, options);
8165
9175
  const runtime = this._codemodeRuntime();
8166
9176
  if (!runtime) return {
8167
9177
  status: "error",
@@ -8187,7 +9197,7 @@ var Think = class Think extends Agent {
8187
9197
  executionId,
8188
9198
  reason: reason ?? "Rejected by user"
8189
9199
  };
8190
- await this._applyExecutionOutcome(executionId, output);
9200
+ await this._applyExecutionOutcome(executionId, output, options);
8191
9201
  return output;
8192
9202
  }
8193
9203
  /**
@@ -8196,7 +9206,7 @@ var Think = class Think extends Agent {
8196
9206
  * never runs, and the paused transcript part is replaced with a `rejected`
8197
9207
  * outcome so the model can adapt or explain.
8198
9208
  */
8199
- async _rejectActionPause(executionId, reason) {
9209
+ async _rejectActionPause(executionId, reason, options) {
8200
9210
  const row = this._claimActionPendingRow(executionId);
8201
9211
  if (!row) return {
8202
9212
  status: "error",
@@ -8216,7 +9226,7 @@ var Think = class Think extends Agent {
8216
9226
  executionId
8217
9227
  }
8218
9228
  });
8219
- await this._applyExecutionOutcome(executionId, output);
9229
+ await this._applyExecutionOutcome(executionId, output, options);
8220
9230
  return output;
8221
9231
  }
8222
9232
  /**
@@ -8232,10 +9242,10 @@ var Think = class Think extends Agent {
8232
9242
  * assembly projects this narrowly identified note to ordinary user context
8233
9243
  * without changing its durable authorship.
8234
9244
  */
8235
- async _applyExecutionOutcome(executionId, output) {
8236
- const toolCallId = this._findPausedExecutionToolCall(executionId);
9245
+ async _applyExecutionOutcome(executionId, output, options) {
9246
+ const toolCallId = await this._findExecutionToolCallDurably(executionId, true);
8237
9247
  if (!toolCallId) {
8238
- if (this._findExecutionToolCall(executionId) != null) return false;
9248
+ if (await this._findExecutionToolCallDurably(executionId) != null) return false;
8239
9249
  let summary;
8240
9250
  try {
8241
9251
  summary = JSON.stringify(output)?.slice(0, 4e3) ?? String(output);
@@ -8251,7 +9261,20 @@ var Think = class Think extends Agent {
8251
9261
  text: `[${outcomeSource}] The paused execution "${executionId}" was resolved, but its tool call is no longer in the transcript (it may have been compacted). Outcome: ${summary}`
8252
9262
  }]
8253
9263
  });
8254
- } else await this._enqueueInteractionApply(() => this._applyToolUpdateToMessages(pausedExecutionUpdate(toolCallId, executionId, output)));
9264
+ } else await this._enqueueInteractionApply(async () => {
9265
+ await this._rememberResolvedPause(toolCallId, {
9266
+ executionId,
9267
+ output
9268
+ });
9269
+ await this._applyToolUpdateToMessages(pausedExecutionUpdate(toolCallId, executionId, output));
9270
+ await this._dropGenerationAfterResolvedPause(toolCallId);
9271
+ });
9272
+ if (options?.autoContinue === false) {
9273
+ if (toolCallId && this._deferredResolvedPauses.has(toolCallId)) if (this._streamingAssistant) this._flushResolvedPausesOnFinalize = true;
9274
+ else await this._enqueueInteractionApply(() => this._flushDeferredResolvedPauses());
9275
+ this._rearmPendingAutoContinuationForBatch();
9276
+ return true;
9277
+ }
8255
9278
  const { connection } = getCurrentAgent();
8256
9279
  let target = connection;
8257
9280
  if (!target) for (const open of this.getConnections()) {
@@ -8263,38 +9286,103 @@ var Think = class Think extends Agent {
8263
9286
  return true;
8264
9287
  }
8265
9288
  /**
8266
- * Find the tool part holding the paused output of `executionId` — in the
8267
- * in-flight streaming accumulator first (an approval can land while a new
8268
- * turn streams), then the persisted transcript, newest message first.
8269
- */
8270
- _findPausedExecutionToolCall(executionId) {
8271
- return this._findExecutionToolCall(executionId, true);
8272
- }
8273
- /**
8274
- * Find the tool part carrying `executionId` in its output. With
9289
+ * Find the tool part carrying `executionId` in its output — in the in-flight
9290
+ * streaming accumulator first (an approval can land while a new turn
9291
+ * streams), then the in-memory transcript, newest message first. With
8275
9292
  * `pausedOnly`, only a still-paused output matches — used to locate the
8276
9293
  * part an approval outcome should replace. Without it, any settled output
8277
9294
  * matches — used to distinguish "already resolved elsewhere" from "the
8278
9295
  * part is gone from the transcript" (e.g. compacted away).
8279
9296
  */
8280
9297
  _findExecutionToolCall(executionId, pausedOnly = false) {
8281
- const matches = (part) => {
8282
- if (part.state !== "output-available") return false;
8283
- if (typeof part.toolCallId !== "string") return false;
8284
- const output = part.output;
8285
- return output != null && typeof output === "object" && (!pausedOnly || output.status === "paused") && output.executionId === executionId;
8286
- };
8287
9298
  const streaming = this._streamingAssistant;
8288
9299
  if (streaming) {
8289
- for (const part of streaming.parts) if (matches(part)) return part.toolCallId;
9300
+ const found = executionToolCallIn({
9301
+ role: "assistant",
9302
+ parts: streaming.parts
9303
+ }, executionId, pausedOnly);
9304
+ if (found) return found;
8290
9305
  }
8291
9306
  for (let i = this.messages.length - 1; i >= 0; i--) {
8292
- const message = this.messages[i];
8293
- if (message.role !== "assistant") continue;
8294
- for (const part of message.parts) if (matches(part)) return part.toolCallId;
9307
+ const found = executionToolCallIn(this.messages[i], executionId, pausedOnly);
9308
+ if (found) return found;
8295
9309
  }
8296
9310
  return null;
8297
9311
  }
9312
+ /**
9313
+ * {@link _findExecutionToolCall}, falling back to storage when the hydrated
9314
+ * window does not cover the whole transcript, so a long-lived pause is
9315
+ * still resolved in place.
9316
+ */
9317
+ async _findExecutionToolCallDurably(executionId, pausedOnly = false) {
9318
+ const found = this._findExecutionToolCall(executionId, pausedOnly);
9319
+ if (found || this._cacheCoversActivePath) return found;
9320
+ for await (const message of this.session.history({ newestFirst: true })) {
9321
+ const stored = executionToolCallIn(message, executionId, pausedOnly);
9322
+ if (stored) return stored;
9323
+ }
9324
+ return null;
9325
+ }
9326
+ /**
9327
+ * Text and reasoning the model wrote after a paused tool result were written
9328
+ * against the pending state ("once approved, ..."). Once the pause resolves
9329
+ * they contradict the result, so drop them before the continuation reads the
9330
+ * transcript. Tool, file, and other parts after the pause stay.
9331
+ *
9332
+ * While the turn that paused is still streaming, its accumulator owns the
9333
+ * message and appends deltas to the last text part, so parts cannot be
9334
+ * removed underneath it. The drop is deferred to the next inference, which
9335
+ * is queued behind that turn and runs after it persists.
9336
+ *
9337
+ * The resolved pause stays recorded (see `_rememberResolvedPause`) until
9338
+ * the drop has been applied.
9339
+ */
9340
+ async _dropGenerationAfterResolvedPause(toolCallId) {
9341
+ if (this._streamingAssistant?.parts.some((part) => "toolCallId" in part && part.toolCallId === toolCallId)) return;
9342
+ const owner = await this._resolveToolCallOwner(toolCallId, void 0);
9343
+ const parts = owner ? dropGenerationAfterToolCall(owner.parts, toolCallId) : void 0;
9344
+ if (owner && parts && parts !== owner.parts) {
9345
+ const safe = await this._updateMessageInHistory({
9346
+ ...owner,
9347
+ parts
9348
+ });
9349
+ this._patchCachedMessage(safe);
9350
+ this._broadcast({
9351
+ type: MSG_MESSAGE_UPDATED,
9352
+ message: safe
9353
+ });
9354
+ }
9355
+ await this._forgetResolvedPause(toolCallId);
9356
+ }
9357
+ _loadResolvedPauses() {
9358
+ this._deferredResolvedPausesLoad ??= (async () => {
9359
+ const stored = await this.ctx.storage.get(DEFERRED_RESOLVED_PAUSES_KEY);
9360
+ for (const [toolCallId, outcome] of stored ?? []) if (!this._deferredResolvedPauses.has(toolCallId)) this._deferredResolvedPauses.set(toolCallId, outcome);
9361
+ })().catch((error) => {
9362
+ this._deferredResolvedPausesLoad = void 0;
9363
+ throw error;
9364
+ });
9365
+ return this._deferredResolvedPausesLoad;
9366
+ }
9367
+ async _rememberResolvedPause(toolCallId, outcome) {
9368
+ await this._loadResolvedPauses();
9369
+ this._deferredResolvedPauses.set(toolCallId, outcome);
9370
+ await this.ctx.storage.put(DEFERRED_RESOLVED_PAUSES_KEY, [...this._deferredResolvedPauses]);
9371
+ }
9372
+ async _forgetResolvedPause(toolCallId) {
9373
+ await this._loadResolvedPauses();
9374
+ if (!this._deferredResolvedPauses.delete(toolCallId)) return;
9375
+ if (this._deferredResolvedPauses.size === 0) await this.ctx.storage.delete(DEFERRED_RESOLVED_PAUSES_KEY);
9376
+ else await this.ctx.storage.put(DEFERRED_RESOLVED_PAUSES_KEY, [...this._deferredResolvedPauses]);
9377
+ }
9378
+ async _flushDeferredResolvedPauses() {
9379
+ await this._loadResolvedPauses();
9380
+ for (const [toolCallId, outcome] of [...this._deferredResolvedPauses]) {
9381
+ const owner = await this._resolveToolCallOwner(toolCallId, void 0);
9382
+ if (owner && ownsPausedToolCall(owner, toolCallId)) await this._applyToolUpdateToMessages(pausedExecutionUpdate(toolCallId, outcome.executionId, outcome.output));
9383
+ await this._dropGenerationAfterResolvedPause(toolCallId);
9384
+ }
9385
+ }
8298
9386
  async _applyToolUpdateToMessages(update) {
8299
9387
  let broadcastMessage;
8300
9388
  const streaming = this._streamingAssistant;
@@ -8514,22 +9602,27 @@ var Think = class Think extends Agent {
8514
9602
  tryHandleNonChatFiberRecovery: (ctx) => this._messengerRuntime?.handleFiberRecovery(ctx) ?? Promise.resolve(false),
8515
9603
  readProgress: () => this._chatRecoveryProgressMarker(),
8516
9604
  isAwaitingClientInteraction: () => this.hasPendingInteraction(),
9605
+ listActiveIncidents: async () => (await listActiveChatRecoveryIncidents(this.ctx.storage)).map(({ incident }) => incident),
8517
9606
  putIncident: (key, incident) => this.ctx.storage.put(key, incident),
8518
9607
  deleteIncident: async (key) => {
8519
9608
  await this.ctx.storage.delete(key);
8520
9609
  },
8521
- emitRecoveryEvent: (event) => this._emit(event.type, {
8522
- incidentId: event.incidentId,
8523
- requestId: event.requestId,
8524
- attempt: event.attempt,
8525
- maxAttempts: event.maxAttempts,
8526
- recoveryKind: event.recoveryKind,
8527
- ...event.reason ? { reason: event.reason } : {}
8528
- }),
9610
+ emitRecoveryEvent: (event) => {
9611
+ this._emit(event.type, {
9612
+ incidentId: event.incidentId,
9613
+ requestId: event.requestId,
9614
+ attempt: event.attempt,
9615
+ maxAttempts: event.maxAttempts,
9616
+ recoveryKind: event.recoveryKind,
9617
+ ...event.reason ? { reason: event.reason } : {}
9618
+ });
9619
+ if (event.type === "chat:recovery:completed") this._settleMessengerRecovery(event.incidentId, "completed");
9620
+ else if (event.type === "chat:recovery:skipped" || event.type === "chat:recovery:failed" && !this._deferringRecoveryIncidents.has(event.incidentId)) this._settleMessengerRecovery(event.incidentId, "interrupted");
9621
+ },
8529
9622
  scheduleRecovery: (callback, data, reason, delaySeconds) => this._enqueueChatRecovery(callback, data, reason, delaySeconds),
8530
9623
  setRecovering: (active, requestId) => this._setChatRecovering(active, requestId),
8531
9624
  onShouldKeepRecoveringError: (error) => console.error("[Think] chatRecovery shouldKeepRecovering hook threw", error),
8532
- exhaustChatRecovery: (incident, config, partial, streamId, createdAt) => this._exhaustChatRecovery(incident, config, partial, streamId, createdAt),
9625
+ exhaustChatRecovery: (incident, config, partial, streamId, createdAt, originMessageIds) => this._exhaustChatRecovery(incident, config, partial, streamId, createdAt, originMessageIds),
8533
9626
  resolveRecoveryStream: (requestId) => this._resolveThinkRecoveryStream(requestId),
8534
9627
  getPartialStreamText: (streamId) => this._getPartialStreamText(streamId),
8535
9628
  activeChatRecoveryRootRequestId: () => this._activeChatRecoveryRootRequestId,
@@ -8539,7 +9632,7 @@ var Think = class Think extends Agent {
8539
9632
  async _updateChatRecoveryIncident(incidentId, status, reason) {
8540
9633
  return this._chatRecoveryEngine().updateIncident(incidentId, status, reason);
8541
9634
  }
8542
- async _exhaustChatRecovery(incident, config, partial, streamId, createdAt) {
9635
+ async _exhaustChatRecovery(incident, config, partial, streamId, createdAt, originMessageIds) {
8543
9636
  await runChatRecoveryExhaustion({
8544
9637
  incident,
8545
9638
  config,
@@ -8548,18 +9641,23 @@ var Think = class Think extends Agent {
8548
9641
  streamId,
8549
9642
  createdAt
8550
9643
  }, {
8551
- emit: (event) => this._emit("chat:recovery:exhausted", event),
9644
+ emit: (event) => {
9645
+ this._emit("chat:recovery:exhausted", event);
9646
+ this._settleMessengerRecovery(incident.incidentId, "interrupted");
9647
+ },
8552
9648
  onExhausted: config.onExhausted,
8553
9649
  onError: (error) => console.error("[Think] chatRecovery onExhausted hook threw", error),
8554
9650
  terminalize: async (ctx) => {
9651
+ const messageIds = this._originMessageIdsFor(ctx.requestId) ?? originMessageIds;
8555
9652
  this._broadcastChat({
8556
9653
  type: MSG_CHAT_RESPONSE,
8557
9654
  id: ctx.requestId,
8558
9655
  body: ctx.terminalMessage,
8559
9656
  done: true,
8560
- error: true
9657
+ error: true,
9658
+ ...messageIds ? { messageIds } : {}
8561
9659
  });
8562
- await this._recordTerminalChatStatus("interrupted", ctx.requestId, ctx.terminalMessage);
9660
+ await this._recordTerminalChatStatus("interrupted", ctx.requestId, ctx.terminalMessage, messageIds);
8563
9661
  await this._markRecoveredSubmissionInterrupted(ctx.recoveryRootRequestId ?? ctx.requestId, ctx.terminalMessage);
8564
9662
  }
8565
9663
  });
@@ -8568,56 +9666,187 @@ var Think = class Think extends Agent {
8568
9666
  * Route a stream-stall watchdog abort into bounded recovery instead of a
8569
9667
  * terminal error (#1626). A stall happens inside a LIVE isolate (no DO
8570
9668
  * restart), so the normal restart-detected recovery path never runs — we
8571
- * open/advance a recovery incident here and schedule a continuation, reusing
8572
- * the SAME budget (`maxAttempts` + wall-clock window + progress-aware reset)
8573
- * as deploy/eviction recovery. A transient hang recovers; a persistently
8574
- * hanging provider exhausts the budget. Idempotency matches deploy recovery:
8575
- * settled tool results are durable and won't re-run, but a tool that was
8576
- * mid-execution when the stall fired re-runs on the continuation.
9669
+ * open/advance a recovery incident here and schedule recovery, reusing the
9670
+ * SAME budget (`maxAttempts` + wall-clock window + progress-aware reset) and
9671
+ * the same `onChatRecovery` decision as deploy/eviction recovery (#2042). A
9672
+ * transient hang recovers; a persistently hanging provider exhausts the
9673
+ * budget. Idempotency matches deploy recovery: settled tool results are
9674
+ * durable and won't re-run, but a tool that was mid-execution when the stall
9675
+ * fired re-runs on the continuation.
9676
+ *
9677
+ * A stall before the first assistant chunk leaves the user's message as the
9678
+ * leaf, so there is nothing to continue: it schedules a retry of that user
9679
+ * turn instead (#1941).
9680
+ *
9681
+ * `persistPartial` saves the settled partial and resolves to its message id
9682
+ * (or `undefined` when nothing was saved). It runs unless `onChatRecovery`
9683
+ * returns `persist: false` and the partial holds no settled tool results.
8577
9684
  *
8578
9685
  * Returns:
8579
- * - `"scheduled"` — a continuation was scheduled; the caller suppresses the
9686
+ * - `"scheduled"` — recovery was scheduled; the caller suppresses the
8580
9687
  * terminal error and closes the stream cleanly.
8581
9688
  * - `"exhausted"` — the budget is spent; this routes through the SAME
8582
9689
  * `_exhaustChatRecovery` path as deploy recovery (fires `onExhausted`,
8583
9690
  * emits `chat:recovery:exhausted`, marks the submission interrupted, and
8584
- * delivers the configured `terminalMessage`). The caller must NOT run the
8585
- * generic terminal path — the terminal UX is already delivered.
9691
+ * delivers the configured `terminalMessage`).
9692
+ * - `"declined"` — `onChatRecovery` returned `continue: false`; the turn is
9693
+ * marked interrupted and the declined message is delivered.
9694
+ * - `"failed"` — `onChatRecovery` threw; the incident is marked `failed` and
9695
+ * the caller runs its generic terminal error path.
9696
+ *
9697
+ * For `"exhausted"` and `"declined"` the terminal UX is already delivered, so
9698
+ * the caller must NOT run the generic terminal path.
8586
9699
  */
8587
9700
  async _routeStallToBoundedRecovery(input) {
8588
9701
  const recoveryRootRequestId = this._activeChatRecoveryRootRequestId ?? input.requestId;
9702
+ const originIds = this._originMessageIdsFor(input.requestId);
8589
9703
  const latestUserMessageId = [...this.messages].reverse().find((m) => m.role === "user")?.id ?? null;
9704
+ const retryTargetUserId = input.partialParts.length === 0 ? input.branchParentId ?? await this._latestUserLeafId() : null;
9705
+ const recoveryKind = retryTargetUserId ? "retry" : "continue";
8590
9706
  const { incident, config, exhausted } = await this._beginChatRecoveryIncident({
8591
9707
  requestId: input.requestId,
8592
9708
  recoveryRootRequestId,
8593
9709
  latestUserMessageId,
8594
- recoveryKind: "continue"
9710
+ recoveryKind
8595
9711
  });
9712
+ const partialText = input.partialParts.filter((p) => p.type === "text").map((p) => p.text).join("");
8596
9713
  if (exhausted) {
8597
- const partialText = input.partialParts.filter((p) => p.type === "text").map((p) => p.text).join("");
9714
+ await input.persistPartial();
8598
9715
  await this._exhaustChatRecovery(incident, config, {
8599
9716
  text: partialText,
8600
9717
  parts: input.partialParts
8601
9718
  }, input.streamId, incident.firstSeenAt);
8602
9719
  return "exhausted";
8603
9720
  }
9721
+ const liveTurn = this._liveChatRecoveryTurns.get(input.requestId);
9722
+ let options;
9723
+ try {
9724
+ options = await this.onChatRecovery({
9725
+ incidentId: incident.incidentId,
9726
+ recoveryRootRequestId,
9727
+ attempt: incident.attempt,
9728
+ maxAttempts: incident.maxAttempts,
9729
+ recoveryKind,
9730
+ streamId: input.streamId,
9731
+ requestId: input.requestId,
9732
+ partialText,
9733
+ partialParts: input.partialParts,
9734
+ recoveryData: liveTurn?.recoveryData ?? null,
9735
+ messages: [...this.messages],
9736
+ lastBody: this._lastBody,
9737
+ lastClientTools: this._lastClientTools,
9738
+ createdAt: liveTurn?.createdAt ?? incident.firstSeenAt
9739
+ }) ?? {};
9740
+ } catch (error) {
9741
+ console.error("[Think] onChatRecovery threw during stall recovery:", error);
9742
+ await input.persistPartial();
9743
+ await this._updateChatRecoveryIncident(incident.incidentId, "failed", error instanceof Error ? error.message : String(error));
9744
+ return "failed";
9745
+ }
9746
+ const targetAssistantId = options.persist !== false || this._getPartialStreamText(input.streamId).hasSettledToolResults ? await input.persistPartial() : void 0;
8604
9747
  const recoveredRequestId = this._readRunningSubmissionForRecovery(recoveryRootRequestId)?.submission_id;
9748
+ if (options.continue === false) {
9749
+ await this._updateChatRecoveryIncident(incident.incidentId, "skipped", "continue_disabled");
9750
+ const declinedMessage = "Submission was interrupted and automatic continuation was declined.";
9751
+ await this._markRecoveredSubmissionInterrupted(recoveryRootRequestId, declinedMessage);
9752
+ await this._recordTerminalChatStatus("interrupted", input.requestId, declinedMessage);
9753
+ this._broadcastChat({
9754
+ type: MSG_CHAT_RESPONSE,
9755
+ id: input.requestId,
9756
+ body: declinedMessage,
9757
+ done: true,
9758
+ error: true
9759
+ });
9760
+ return "declined";
9761
+ }
9762
+ const unansweredUserId = targetAssistantId ? null : input.partialParts.length === 0 ? retryTargetUserId : input.branchParentId ?? await this._latestUserLeafId();
9763
+ await this._claimMessengerRecoveryDelivery(input.requestId, incident.incidentId, partialText);
9764
+ const retries = await this._chatRecoveryEngine().recordTransientRetry(incident.incidentId);
9765
+ const delaySeconds = input.backoff ? chatRecoveryBackoffSeconds(retries, input.retryAfterSeconds) : void 0;
9766
+ const reason = this._activeChatRecoveryRootRequestId !== void 0 ? "chained_retry" : void 0;
9767
+ if (unansweredUserId) {
9768
+ await this._chatRecoveryEngine().scheduleRecovery({
9769
+ incident,
9770
+ delaySeconds,
9771
+ reason,
9772
+ recoveryKind: "retry",
9773
+ callback: "_chatRecoveryRetry",
9774
+ data: {
9775
+ targetUserId: unansweredUserId,
9776
+ ...input.branchParentId !== void 0 && { regeneratedLeafId: (await this.session.getLatestLeaf())?.id },
9777
+ originalRequestId: recoveryRootRequestId,
9778
+ incidentId: incident.incidentId,
9779
+ lastBody: this._lastBody ?? null,
9780
+ lastClientTools: this._lastClientTools ?? null,
9781
+ ...originIds ? { originMessageIds: originIds } : {},
9782
+ ...recoveredRequestId ? { recoveredRequestId } : {}
9783
+ }
9784
+ });
9785
+ this._rescheduledRecoveryIncidents.add(incident.incidentId);
9786
+ this._claimSubmissionForRecovery(recoveredRequestId, reason);
9787
+ return "scheduled";
9788
+ }
8605
9789
  await this._chatRecoveryEngine().scheduleRecovery({
8606
9790
  incident,
9791
+ delaySeconds,
9792
+ reason,
8607
9793
  recoveryKind: "continue",
8608
9794
  callback: "_chatRecoveryContinue",
8609
9795
  data: {
8610
- ...input.targetAssistantId ? { targetAssistantId: input.targetAssistantId } : {},
9796
+ ...targetAssistantId ? { targetAssistantId } : {},
8611
9797
  originalRequestId: recoveryRootRequestId,
8612
9798
  incidentId: incident.incidentId,
8613
9799
  lastBody: this._lastBody ?? null,
8614
9800
  lastClientTools: this._lastClientTools ?? null,
9801
+ ...originIds ? { originMessageIds: originIds } : {},
8615
9802
  ...recoveredRequestId ? { recoveredRequestId } : {}
8616
9803
  }
8617
9804
  });
9805
+ this._rescheduledRecoveryIncidents.add(incident.incidentId);
9806
+ this._claimSubmissionForRecovery(recoveredRequestId, reason);
8618
9807
  return "scheduled";
8619
9808
  }
9809
+ /**
9810
+ * {@link _routeStallToBoundedRecovery} for a stream consumer's `catch`: a
9811
+ * routing failure (e.g. a rejected incident write) degrades to `"failed"`,
9812
+ * so the caller still delivers its terminal error frame.
9813
+ */
9814
+ async _routeStreamInterruption(input) {
9815
+ try {
9816
+ return await this._routeStallToBoundedRecovery(input);
9817
+ } catch (error) {
9818
+ console.error("[Think] routing a stream interruption into recovery failed; delivering the terminal error", error);
9819
+ return "failed";
9820
+ }
9821
+ }
9822
+ _claimSubmissionForRecovery(submissionId, reason) {
9823
+ if (submissionId && reason === void 0) this._recoveryOwnedSubmissions.add(submissionId);
9824
+ }
9825
+ _takeRecoveryReschedule(incidentId) {
9826
+ return incidentId !== void 0 && this._rescheduledRecoveryIncidents.delete(incidentId);
9827
+ }
9828
+ async _latestUserLeafId() {
9829
+ const leaf = await this.session.getLatestLeaf();
9830
+ return leaf?.role === "user" ? leaf.id : null;
9831
+ }
8620
9832
  async _handleInternalFiberRecovery(ctx) {
9833
+ const chatFiberPrefix = this.constructor.CHAT_FIBER_NAME + ":";
9834
+ if (ctx.name.startsWith(chatFiberPrefix) && await this._settlePersistedChatTurn(ctx.name.slice(chatFiberPrefix.length))) return true;
9835
+ return this._recoverChatFiber(ctx);
9836
+ }
9837
+ /**
9838
+ * A turn that owes its response hook and already persisted its message
9839
+ * finished: its stream rows may be gone with the cutover, so recovery would
9840
+ * otherwise re-run it. Fire the owed hook and settle the submission instead.
9841
+ */
9842
+ async _settlePersistedChatTurn(requestId) {
9843
+ const hook = await this.ctx.storage.get(PENDING_RESPONSE_HOOK_PREFIX + requestId);
9844
+ if (!hook || !await this.session.getMessage(hook.messageId)) return false;
9845
+ await this._replayPendingResponseHooks(requestId);
9846
+ await this._completeRecoveredSubmission(requestId, hook.status === "error" ? "error" : "completed", requestId, hook.error ?? null);
9847
+ return true;
9848
+ }
9849
+ _recoverChatFiber(ctx) {
8621
9850
  return this._chatRecoveryEngine().handleChatFiberRecovery(ctx, {
8622
9851
  chatFiberPrefix: () => this.constructor.CHAT_FIBER_NAME + ":",
8623
9852
  unwrapRecoverySnapshot: (fiber) => {
@@ -8714,6 +9943,7 @@ var Think = class Think extends Agent {
8714
9943
  async _dispatchRecoveredThinkTurn(input) {
8715
9944
  const { incident, options, snapshot, requestId, recoveryRootRequestId, streamStatus } = input;
8716
9945
  const { retryTargetUserId } = input.detail;
9946
+ const originIds = this._originMessageIdsFor(requestId) ?? snapshot?.originMessageIds;
8717
9947
  const streamIsTerminal = streamStatus === "completed" || streamStatus === "error";
8718
9948
  const shouldRetry = retryTargetUserId !== null && options.continue !== false && !streamIsTerminal;
8719
9949
  const lastLeaf = shouldRetry ? null : await this.session.getLatestLeaf();
@@ -8728,10 +9958,12 @@ var Think = class Think extends Agent {
8728
9958
  callback: "_chatRecoveryRetry",
8729
9959
  data: {
8730
9960
  targetUserId: retryTargetUserId,
9961
+ ...regenerationParentOf(snapshot) !== void 0 && snapshot?.latestMessageId && { regeneratedLeafId: snapshot.latestMessageId },
8731
9962
  originalRequestId: recoveryRootRequestId,
8732
9963
  incidentId: incident.incidentId,
8733
9964
  lastBody: snapshot?.lastBody ?? null,
8734
9965
  lastClientTools: snapshot?.lastClientTools ?? null,
9966
+ ...originIds ? { originMessageIds: originIds } : {},
8735
9967
  ...recoveredRequestId ? { recoveredRequestId } : {}
8736
9968
  }
8737
9969
  });
@@ -8747,6 +9979,7 @@ var Think = class Think extends Agent {
8747
9979
  lastBody: snapshot.lastBody ?? null,
8748
9980
  lastClientTools: snapshot.lastClientTools ?? null
8749
9981
  } : {},
9982
+ ...originIds ? { originMessageIds: originIds } : {},
8750
9983
  ...recoveredRequestId ? { recoveredRequestId } : {}
8751
9984
  }
8752
9985
  });
@@ -8765,8 +9998,14 @@ var Think = class Think extends Agent {
8765
9998
  } else await this._updateChatRecoveryIncident(incident.incidentId, "skipped", streamIsTerminal ? "stream_terminal" : "not_recoverable");
8766
9999
  }
8767
10000
  async _recoverablePreStreamUserId(snapshot, partial) {
8768
- if (!snapshot || snapshot.continuation || !snapshot.latestUserMessageId || partial.text || partial.parts.length > 0) return null;
10001
+ if (!snapshot || snapshot.continuation || !snapshot.latestUserMessageId || partial.text || partial.parts.length > 0 && this._strippedForPersist({
10002
+ id: "",
10003
+ role: "assistant",
10004
+ parts: partial.parts
10005
+ }) !== null) return null;
8769
10006
  const lastLeaf = await this.session.getLatestLeaf();
10007
+ const branchParentId = regenerationParentOf(snapshot);
10008
+ if (branchParentId !== void 0) return lastLeaf !== null && lastLeaf.id === snapshot.latestMessageId ? branchParentId : null;
8770
10009
  return lastLeaf?.role === "user" && lastLeaf.id === snapshot.latestUserMessageId ? snapshot.latestUserMessageId : null;
8771
10010
  }
8772
10011
  async _hasPersistedRecoveredAssistant(snapshot) {
@@ -9007,10 +10246,14 @@ var Think = class Think extends Agent {
9007
10246
  if (await this._handleRecoveryOom(callback, data, error)) return;
9008
10247
  if (isPlatformTransientError(error)) {
9009
10248
  const message = error instanceof Error ? error.message : String(error);
10249
+ const incidentId = data?.incidentId;
10250
+ if (incidentId) this._deferringRecoveryIncidents.add(incidentId);
9010
10251
  try {
9011
- await this._updateChatRecoveryIncident(data?.incidentId, "failed", message);
10252
+ await this._updateChatRecoveryIncident(incidentId, "failed", message);
9012
10253
  } catch (bookkeepingError) {
9013
10254
  console.error("[Think] failed to mark recovery incident failed before deferring", bookkeepingError);
10255
+ } finally {
10256
+ if (incidentId) this._deferringRecoveryIncidents.delete(incidentId);
9014
10257
  }
9015
10258
  throw error;
9016
10259
  }
@@ -9037,15 +10280,27 @@ var Think = class Think extends Agent {
9037
10280
  `;
9038
10281
  onTurnStarted?.();
9039
10282
  };
10283
+ const workflowPrompt = recoveredSubmission ? this._readWorkflowPromptContext(this._parseJsonObject(recoveredSubmission.metadata_json)) : null;
9040
10284
  return recoveredTurnAcceptanceContext.run({
9041
10285
  agent: this,
9042
- onAccepted
10286
+ onAccepted,
10287
+ workflowPrompt: workflowPrompt ?? void 0
9043
10288
  }, run);
9044
10289
  }
10290
+ /**
10291
+ * The workflow prompt of the submission a recovery turn is completing. A
10292
+ * structured prompt must re-arm its final-answer tool on the recovered turn,
10293
+ * or the turn can never produce the output the workflow waits for.
10294
+ */
10295
+ _recoveredWorkflowPrompt() {
10296
+ const acceptance = recoveredTurnAcceptanceContext.getStore();
10297
+ return acceptance?.agent === this ? acceptance.workflowPrompt : void 0;
10298
+ }
9045
10299
  async _chatRecoveryRetry(data) {
9046
- await this._dispatchChatRecovery("_chatRecoveryRetry", data, (onTurnStarted) => this._chatRecoveryRetryDetached(data, onTurnStarted));
10300
+ await this._dispatchChatRecovery("_chatRecoveryRetry", data, (onTurnStarted) => this._chatRecoveryOriginIdsScope.run(data?.originMessageIds, () => this._chatRecoveryRetryDetached(data, onTurnStarted)));
9047
10301
  }
9048
10302
  async _chatRecoveryRetryDetached(data, onTurnStarted) {
10303
+ if (await this._recoveryCancelled(data)) return;
9049
10304
  const recoveredSubmission = data?.recoveredRequestId ? this._readRunningSubmissionForRecovery(data.recoveredRequestId) : null;
9050
10305
  if (data?.recoveredRequestId && !recoveredSubmission) {
9051
10306
  await this._updateChatRecoveryIncident(data.incidentId, "skipped", "submission_not_running");
@@ -9064,21 +10319,27 @@ var Think = class Think extends Agent {
9064
10319
  return;
9065
10320
  }
9066
10321
  const lastLeaf = await this.session.getLatestLeaf();
9067
- if (!lastLeaf || lastLeaf.role !== "user") {
10322
+ const regeneratedLeafId = data?.regeneratedLeafId;
10323
+ if (!lastLeaf || regeneratedLeafId === void 0 && lastLeaf.role !== "user") {
9068
10324
  await this._updateChatRecoveryIncident(data?.incidentId, "skipped", "no_unanswered_user_message");
9069
10325
  if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "skipped", null, null);
9070
10326
  return;
9071
10327
  }
9072
- if (data?.targetUserId && lastLeaf.id !== data.targetUserId) {
10328
+ const expectedLeafId = regeneratedLeafId ?? data?.targetUserId;
10329
+ if (expectedLeafId && lastLeaf.id !== expectedLeafId) {
9073
10330
  await this._updateChatRecoveryIncident(data?.incidentId, "skipped", "conversation_changed");
9074
10331
  if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "skipped", null, null);
9075
10332
  return;
9076
10333
  }
9077
10334
  this._applyRecoveredRequestContext(data);
9078
- const result = await this._runRecoveredTurnAfterAcceptance(recoveredSubmission, onTurnStarted, () => this._retryLastUserTurn(this._lastClientTools, this._lastBody, controller ? {
9079
- signal: controller.signal,
9080
- trigger: "recovery-retry"
9081
- } : { trigger: "recovery-retry" }));
10335
+ this._takeRecoveryReschedule(data?.incidentId);
10336
+ const result = await this._runRecoveredTurnAfterAcceptance(recoveredSubmission, onTurnStarted, () => this._retryLastUserTurn(this._lastClientTools, this._lastBody, {
10337
+ ...controller && { signal: controller.signal },
10338
+ trigger: "recovery-retry",
10339
+ ...regeneratedLeafId !== void 0 && { branchParentId: data?.targetUserId }
10340
+ }));
10341
+ if (result.status !== "completed" && this._takeRecoveryReschedule(data?.incidentId)) return;
10342
+ await this._stageMessengerRecoveryOutcome(data, result.status);
9082
10343
  await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
9083
10344
  if (data?.recoveredRequestId) await this._completeRecoveredSubmission(recoveredSubmission ?? data.recoveredRequestId, result.status, result.requestId || null, result.status === "completed" ? null : result.error ?? `Recovery retry ${result.status}.`);
9084
10345
  } catch (error) {
@@ -9101,7 +10362,8 @@ var Think = class Think extends Agent {
9101
10362
  const rows = this.sql`
9102
10363
  SELECT submission_id, idempotency_key, request_id, stream_id, status,
9103
10364
  messages_json, metadata_json, error_message, created_at,
9104
- messages_applied_at, started_at, completed_at, result_status, output_json
10365
+ messages_applied_at, started_at, completed_at, result_status, output_json,
10366
+ message_id
9105
10367
  FROM cf_think_submissions
9106
10368
  WHERE submission_id = ${recoveredRequestId}
9107
10369
  OR (request_id = ${recoveredRequestId} AND status = 'running')
@@ -9169,9 +10431,10 @@ var Think = class Think extends Agent {
9169
10431
  return {};
9170
10432
  }
9171
10433
  async _chatRecoveryContinue(data) {
9172
- await this._dispatchChatRecovery("_chatRecoveryContinue", data, (onTurnStarted) => this._chatRecoveryContinueDetached(data, onTurnStarted));
10434
+ await this._dispatchChatRecovery("_chatRecoveryContinue", data, (onTurnStarted) => this._chatRecoveryOriginIdsScope.run(data?.originMessageIds, () => this._chatRecoveryContinueDetached(data, onTurnStarted)));
9173
10435
  }
9174
10436
  async _chatRecoveryContinueDetached(data, onTurnStarted) {
10437
+ if (await this._recoveryCancelled(data)) return;
9175
10438
  const recoveredSubmission = data?.recoveredRequestId ? this._readRunningSubmissionForRecovery(data.recoveredRequestId) : null;
9176
10439
  if (data?.recoveredRequestId && !recoveredSubmission) {
9177
10440
  await this._updateChatRecoveryIncident(data.incidentId, "skipped", "submission_not_running");
@@ -9199,10 +10462,13 @@ var Think = class Think extends Agent {
9199
10462
  return;
9200
10463
  }
9201
10464
  this._applyRecoveredRequestContext(data);
10465
+ this._takeRecoveryReschedule(data?.incidentId);
9202
10466
  const result = await this._runRecoveredTurnAfterAcceptance(recoveredSubmission, onTurnStarted, () => this.continueLastTurn(void 0, controller ? {
9203
10467
  signal: controller.signal,
9204
10468
  trigger: "recovery-continue"
9205
10469
  } : { trigger: "recovery-continue" }));
10470
+ if (result.status !== "completed" && this._takeRecoveryReschedule(data?.incidentId)) return;
10471
+ await this._stageMessengerRecoveryOutcome(data, result.status);
9206
10472
  await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
9207
10473
  if (data?.recoveredRequestId) await this._completeRecoveredSubmission(recoveredSubmission ?? data.recoveredRequestId, result.status, result.requestId || null, result.status === "completed" ? null : result.error ?? `Recovery ${result.status}.`);
9208
10474
  } catch (error) {
@@ -9235,12 +10501,13 @@ var Think = class Think extends Agent {
9235
10501
  });
9236
10502
  }
9237
10503
  _completeSkippedRequest(connection, requestId) {
9238
- connection.send(JSON.stringify({
10504
+ connection.send(JSON.stringify(this._withOriginMessageIds({
9239
10505
  type: MSG_CHAT_RESPONSE,
9240
10506
  id: requestId,
9241
10507
  body: "",
9242
- done: true
9243
- }));
10508
+ done: true,
10509
+ outcome: "skipped"
10510
+ })));
9244
10511
  this._settlePreStreamTurn(requestId, { releaseParked: false });
9245
10512
  }
9246
10513
  /**
@@ -9299,6 +10566,12 @@ var Think = class Think extends Agent {
9299
10566
  */
9300
10567
  _onStreamingTurnFinalized() {
9301
10568
  this._streamingAssistant = null;
10569
+ if (this._flushResolvedPausesOnFinalize) {
10570
+ this._flushResolvedPausesOnFinalize = false;
10571
+ this.keepAliveWhile(() => this._enqueueInteractionApply(() => this._flushDeferredResolvedPauses())).catch((error) => {
10572
+ console.error("[Think] Failed to apply resolved pauses", error);
10573
+ });
10574
+ }
9302
10575
  this._autoContinuation.rearmForBatch();
9303
10576
  }
9304
10577
  /**
@@ -9329,11 +10602,13 @@ var Think = class Think extends Agent {
9329
10602
  if (!pending) return;
9330
10603
  const { connection, requestId, clientTools } = pending;
9331
10604
  const abortSignal = this._aborts.getSignal(requestId);
10605
+ let reported = false;
9332
10606
  this._admitTurn({
9333
10607
  admission: "queue",
9334
10608
  trigger: "auto-continuation",
9335
10609
  requestId,
9336
10610
  continuation: true,
10611
+ inheritChannel: true,
9337
10612
  allowNested: true,
9338
10613
  execute: async () => {
9339
10614
  if (this._continuation.pending) this._continuation.pending.pastCoalesce = true;
@@ -9357,18 +10632,89 @@ var Think = class Think extends Agent {
9357
10632
  }
9358
10633
  };
9359
10634
  await this._runChatRecoveryFiber(requestId, true, continuationBody);
10635
+ } catch (error) {
10636
+ if (!streamed) reported = await this._reportContinuationFailure(requestId, error, abortSignal);
10637
+ throw error;
9360
10638
  } finally {
9361
10639
  this._aborts.remove(requestId);
9362
- if (!streamed) this._continuation.sendResumeNone();
9363
- this._continuation.clearPending();
9364
- this._activateDeferredContinuation();
10640
+ this._settleContinuationTurn(requestId, streamed);
9365
10641
  }
9366
10642
  }
9367
10643
  }).catch((error) => {
9368
- console.error("[Think] Auto-continuation failed:", error);
10644
+ if (!reported) console.error("[Think] Auto-continuation failed:", error);
9369
10645
  this._aborts.remove(requestId);
9370
10646
  });
9371
10647
  }
10648
+ /**
10649
+ * Report a continuation turn that failed before it streamed, the way a
10650
+ * failed client turn is reported: `onChatError`, `chat:request:failed`, a
10651
+ * recorded terminal status, `onChatResponse` for the assistant message it
10652
+ * would have extended, and an error frame. Aborts and Durable Object resets
10653
+ * are left to their own paths.
10654
+ *
10655
+ * @returns Whether the failure was reported.
10656
+ */
10657
+ async _reportContinuationFailure(requestId, error, abortSignal) {
10658
+ if (abortSignal?.aborted || isDurableObjectResetError(error)) return false;
10659
+ const wrapped = this.onChatError(error, {
10660
+ requestId,
10661
+ stage: "turn",
10662
+ messagesPersisted: true,
10663
+ continuation: true
10664
+ });
10665
+ const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
10666
+ this._emit("chat:request:failed", {
10667
+ requestId,
10668
+ stage: "turn",
10669
+ messagesPersisted: true,
10670
+ error: errorMessage
10671
+ });
10672
+ await this._recordTerminalChatStatus("error", requestId, errorMessage).catch((recordError) => {
10673
+ console.error("[Think] failed to record a continuation failure:", recordError);
10674
+ });
10675
+ this._broadcastChat({
10676
+ type: MSG_CHAT_RESPONSE,
10677
+ id: requestId,
10678
+ body: errorMessage,
10679
+ done: true,
10680
+ error: true,
10681
+ continuation: true
10682
+ });
10683
+ const message = [...this.messages].reverse().find((candidate) => candidate.role === "assistant");
10684
+ if (message) await this._fireLiveResponseHook({
10685
+ message,
10686
+ requestId,
10687
+ continuation: true,
10688
+ status: "error",
10689
+ error: errorMessage
10690
+ });
10691
+ return true;
10692
+ }
10693
+ /**
10694
+ * Settle the continuation state when an auto-continuation turn ends (#2443).
10695
+ *
10696
+ * A turn only owns `pending` until its stream starts: `_streamResult` moves
10697
+ * that pending to the active slot, freeing `pending` for the NEXT
10698
+ * continuation. A client tool result that lands while this turn is still
10699
+ * streaming (a fast client tool chained across steps) creates that next
10700
+ * pending, and the stream-finalize re-arm fires it. So `pending` is cleared
10701
+ * here only while it still holds this turn's request — a turn that never
10702
+ * streamed (failed, aborted, or produced nothing before its stream started).
10703
+ * Clearing unconditionally would drop the newer pending and stall the chat.
10704
+ *
10705
+ * A newer pending that has not started also covers any `deferred` follow-up:
10706
+ * that result arrived before this turn's stream and the newer continuation
10707
+ * runs after it, so firing the deferred too would run a redundant turn that
10708
+ * replays a transcript ending in assistant text.
10709
+ */
10710
+ _settleContinuationTurn(requestId, streamed) {
10711
+ const pending = this._continuation.pending;
10712
+ if (pending?.requestId === requestId) {
10713
+ if (!streamed) this._continuation.sendResumeNone();
10714
+ this._continuation.clearPending();
10715
+ } else if (pending && !pending.pastCoalesce) this._continuation.clearDeferred();
10716
+ this._activateDeferredContinuation();
10717
+ }
9372
10718
  _activateDeferredContinuation() {
9373
10719
  this._autoContinuation.activateDeferredAndReschedule();
9374
10720
  }
@@ -9384,7 +10730,7 @@ var Think = class Think extends Agent {
9384
10730
  * continuation is pending or running coalesce onto the single item.
9385
10731
  */
9386
10732
  async _queueConnectionlessContinuation() {
9387
- await this.queue(CONNECTIONLESS_CONTINUATION_CALLBACK, void 0, { id: "connectionless-continuation" });
10733
+ await this.queue(CONNECTIONLESS_CONTINUATION_CALLBACK, void 0, { id: CONNECTIONLESS_CONTINUATION_QUEUE_ID });
9388
10734
  }
9389
10735
  /**
9390
10736
  * Run one connection-less continuation turn. Mirrors the connection-bound
@@ -9396,12 +10742,15 @@ var Think = class Think extends Agent {
9396
10742
  async _cfRunConnectionlessContinuation() {
9397
10743
  const requestId = crypto.randomUUID();
9398
10744
  const abortSignal = this._aborts.getSignal(requestId);
10745
+ let streamed = false;
10746
+ let reported = false;
9399
10747
  try {
9400
10748
  await this._admitTurn({
9401
10749
  admission: "queue",
9402
10750
  trigger: "auto-continuation",
9403
10751
  requestId,
9404
10752
  continuation: true,
10753
+ inheritChannel: true,
9405
10754
  allowNested: true,
9406
10755
  execute: async () => {
9407
10756
  const continuationBody = async () => {
@@ -9416,13 +10765,21 @@ var Think = class Think extends Agent {
9416
10765
  body: this._lastBody,
9417
10766
  continuation: true
9418
10767
  }));
9419
- if (result) await this._streamResult(requestId, result, abortSignal, { continuation: true });
10768
+ if (result) {
10769
+ await this._streamResult(requestId, result, abortSignal, { continuation: true });
10770
+ streamed = true;
10771
+ }
9420
10772
  };
9421
- await this._runChatRecoveryFiber(requestId, true, continuationBody);
10773
+ try {
10774
+ await this._runChatRecoveryFiber(requestId, true, continuationBody);
10775
+ } catch (error) {
10776
+ if (!streamed) reported = await this._reportContinuationFailure(requestId, error, abortSignal);
10777
+ throw error;
10778
+ }
9422
10779
  }
9423
10780
  });
9424
10781
  } catch (error) {
9425
- console.error("[Think] Connection-less continuation failed:", error);
10782
+ if (!reported) console.error("[Think] Connection-less continuation failed:", error);
9426
10783
  } finally {
9427
10784
  this._aborts.remove(requestId);
9428
10785
  }
@@ -9493,6 +10850,227 @@ var Think = class Think extends Agent {
9493
10850
  }
9494
10851
  }
9495
10852
  /**
10853
+ * Fire a live turn's response hook, then drop its pending marker. When the
10854
+ * bookkeeping before `onChatResponse` throws (attachment delivery, the
10855
+ * terminal-status write), the hook has not run: the marker is kept, with
10856
+ * this outcome, so the next start replays it.
10857
+ */
10858
+ async _fireLiveResponseHook(result) {
10859
+ try {
10860
+ await this._fireResponseHook(result);
10861
+ } catch (error) {
10862
+ console.error("[Think] onChatResponse deferred to replay:", error);
10863
+ await this._rememberPendingResponseHook(result).catch(() => {});
10864
+ this._responseHooksInFlight.delete(result.requestId);
10865
+ return;
10866
+ }
10867
+ await this._forgetPendingResponseHook(result.requestId).catch((error) => {
10868
+ console.error("[Think] failed to clear a response hook marker:", error);
10869
+ });
10870
+ }
10871
+ /**
10872
+ * Record, before the assistant message is persisted, that this turn owes
10873
+ * `onChatResponse`, so a reset between the persist and the hook replays it.
10874
+ */
10875
+ async _rememberPendingResponseHook(result) {
10876
+ this._responseHooksInFlight.add(result.requestId);
10877
+ const pending = {
10878
+ requestId: result.requestId,
10879
+ messageId: result.message.id,
10880
+ continuation: result.continuation,
10881
+ status: result.status,
10882
+ ...result.error !== void 0 && { error: result.error }
10883
+ };
10884
+ await this.ctx.storage.put(PENDING_RESPONSE_HOOK_PREFIX + result.requestId, pending);
10885
+ }
10886
+ async _forgetPendingResponseHook(requestId) {
10887
+ await this.ctx.storage.delete(PENDING_RESPONSE_HOOK_PREFIX + requestId);
10888
+ this._responseHooksInFlight.delete(requestId);
10889
+ }
10890
+ /**
10891
+ * Fire the response hooks a reset interrupted. A hook whose message never
10892
+ * persisted is dropped: that turn is recovered, and fires, on its own.
10893
+ */
10894
+ _replayPendingResponseHooks(requestId) {
10895
+ const tracked = (this._pendingResponseHookReplay ?? Promise.resolve()).catch(() => {}).then(() => this._replayPendingResponseHooksNow(requestId)).finally(() => {
10896
+ if (this._pendingResponseHookReplay === tracked) this._pendingResponseHookReplay = void 0;
10897
+ });
10898
+ this._pendingResponseHookReplay = tracked;
10899
+ return tracked;
10900
+ }
10901
+ async _replayPendingResponseHooksNow(requestId) {
10902
+ const pending = requestId === void 0 ? await this.ctx.storage.list({ prefix: PENDING_RESPONSE_HOOK_PREFIX }) : /* @__PURE__ */ new Map([[PENDING_RESPONSE_HOOK_PREFIX + requestId, await this.ctx.storage.get(PENDING_RESPONSE_HOOK_PREFIX + requestId)]]);
10903
+ for (const [key, hook] of pending) {
10904
+ if (!hook || this._responseHooksInFlight.has(hook.requestId)) continue;
10905
+ if (requestId === void 0 && this._hasRecoverableChatTurn(hook.requestId)) continue;
10906
+ const message = await this.session.getMessage(hook.messageId);
10907
+ if (message) await this._fireResponseHook({
10908
+ message,
10909
+ requestId: hook.requestId,
10910
+ continuation: hook.continuation,
10911
+ status: hook.status,
10912
+ ...hook.error !== void 0 && { error: hook.error },
10913
+ recovered: true
10914
+ });
10915
+ await this.ctx.storage.delete(key);
10916
+ }
10917
+ }
10918
+ /**
10919
+ * An interrupted messenger turn that recovery will continue: record where
10920
+ * the recovered answer goes before the continuation is scheduled, so the
10921
+ * messenger delivery can skip its apology (#2106). A continuation attempt
10922
+ * of the same incident keeps the existing record.
10923
+ */
10924
+ async _claimMessengerRecoveryDelivery(requestId, incidentId, partialText) {
10925
+ const context = this._activeMessengerContext();
10926
+ if (!context) return;
10927
+ const delivery = {
10928
+ messengerId: context.messengerId,
10929
+ threadId: context.thread.id,
10930
+ partialText
10931
+ };
10932
+ await this.ctx.storage.put(MESSENGER_RECOVERY_PREFIX + incidentId, delivery);
10933
+ this._messengerRecoveryClaims.add(requestId);
10934
+ }
10935
+ /**
10936
+ * Durably record a messenger reply's outcome before its recovery incident
10937
+ * settles: once the incident is terminal, nothing re-emits the event that
10938
+ * would settle the reply after a reset. The recovered text is read before
10939
+ * any await, so a later turn cannot replace it.
10940
+ */
10941
+ async _stageMessengerRecoveryOutcome(data, status) {
10942
+ if (!data?.incidentId) return;
10943
+ const text = status === "completed" ? this._recoveredReplyText(data) : void 0;
10944
+ const key = MESSENGER_RECOVERY_PREFIX + data.incidentId;
10945
+ const delivery = await this.ctx.storage.get(key);
10946
+ if (!delivery || delivery.outcome) return;
10947
+ await this.ctx.storage.put(key, settleMessengerRecoveryDelivery(delivery, text === void 0 ? "interrupted" : "completed", text));
10948
+ }
10949
+ _recoveredReplyText(data) {
10950
+ const messages = this.messages;
10951
+ let reply;
10952
+ if ("targetAssistantId" in data && data.targetAssistantId) reply = messages.find((m) => m.id === data.targetAssistantId);
10953
+ else if ("targetUserId" in data && data.targetUserId) {
10954
+ const index = messages.findIndex((m) => m.id === data.targetUserId);
10955
+ const next = index >= 0 ? messages[index + 1] : void 0;
10956
+ if (next?.role === "assistant") reply = next;
10957
+ }
10958
+ reply ??= messages.filter((m) => m.role === "assistant").at(-1);
10959
+ return messageText(reply);
10960
+ }
10961
+ _settleMessengerRecovery(incidentId, outcome) {
10962
+ const text = outcome === "completed" ? messageText(this.messages.filter((m) => m.role === "assistant").at(-1)) : void 0;
10963
+ if (this._settlingMessengerRecoveries.has(incidentId)) return;
10964
+ this._settlingMessengerRecoveries.add(incidentId);
10965
+ const key = MESSENGER_RECOVERY_PREFIX + incidentId;
10966
+ this.keepAliveWhile(async () => {
10967
+ let delivery = await this.ctx.storage.get(key);
10968
+ if (!delivery) return;
10969
+ if (!delivery.outcome) {
10970
+ delivery = settleMessengerRecoveryDelivery(delivery, outcome, text);
10971
+ await this.ctx.storage.put(key, delivery);
10972
+ }
10973
+ await this._deliverMessengerRecovery(key);
10974
+ }).catch((error) => this._retryMessengerRecoveryDeliveryLater(key, 0, error)).finally(() => {
10975
+ this._settlingMessengerRecoveries.delete(incidentId);
10976
+ });
10977
+ }
10978
+ /**
10979
+ * Deliver a recovered reply after any delivery of the same key already
10980
+ * running in this isolate: startup replay, live settlement and scheduled
10981
+ * retries interleave across awaits, and each must see the cursor the
10982
+ * previous one advanced.
10983
+ */
10984
+ async _deliverMessengerRecovery(key) {
10985
+ const run = (this._messengerRecoveryDeliveries.get(key) ?? Promise.resolve()).then(() => this._postMessengerRecovery(key));
10986
+ const tail = run.catch(() => {});
10987
+ this._messengerRecoveryDeliveries.set(key, tail);
10988
+ try {
10989
+ await run;
10990
+ } finally {
10991
+ if (this._messengerRecoveryDeliveries.get(key) === tail) this._messengerRecoveryDeliveries.delete(key);
10992
+ }
10993
+ }
10994
+ /**
10995
+ * Post a settled recovered reply, one post at a time, then drop its record.
10996
+ * Each post goes out at most once: the cursor advances before it, and a
10997
+ * rejected post may still have landed (a timeout after the platform
10998
+ * accepted it), so the retry resumes with the next post.
10999
+ */
11000
+ async _postMessengerRecovery(key) {
11001
+ let delivery = await this.ctx.storage.get(key);
11002
+ if (!delivery?.outcome) return;
11003
+ const input = {
11004
+ messengerId: delivery.messengerId,
11005
+ threadId: delivery.threadId,
11006
+ outcome: delivery.outcome,
11007
+ ...delivery.text !== void 0 && { text: delivery.text },
11008
+ partialPosted: delivery.partialText.trim().length > 0
11009
+ };
11010
+ const parent = this.parentPath.at(-1);
11011
+ const host = parent ? await this.parentAgent({ name: parent.className }) : this;
11012
+ let chunks;
11013
+ for (;;) {
11014
+ delivery = await this.ctx.storage.get(key);
11015
+ if (!delivery?.outcome) return;
11016
+ const posted = delivery.posted ?? 0;
11017
+ if (chunks !== void 0 && posted >= chunks) break;
11018
+ await this.ctx.storage.put(key, {
11019
+ ...delivery,
11020
+ posted: posted + 1
11021
+ });
11022
+ ({chunks} = await host._cf_deliverRecoveredMessengerReply({
11023
+ ...input,
11024
+ chunk: posted
11025
+ }));
11026
+ }
11027
+ await this.ctx.storage.delete(key);
11028
+ }
11029
+ /** Retry a recovered messenger reply whose live delivery failed. */
11030
+ async _retryMessengerRecoveryDeliveryLater(key, attempts, error) {
11031
+ if (attempts >= MESSENGER_RECOVERY_MAX_RETRIES) {
11032
+ console.error(`[Think] recovered messenger reply delivery failed ${attempts + 1} times; the next wake replays it`, error);
11033
+ return;
11034
+ }
11035
+ const delaySeconds = 2 ** (attempts + 1);
11036
+ console.error(`[Think] recovered messenger reply delivery failed; retrying in ${delaySeconds}s`, error);
11037
+ try {
11038
+ await this.schedule(delaySeconds, MESSENGER_RECOVERY_RETRY_CALLBACK, {
11039
+ key,
11040
+ attempts: attempts + 1
11041
+ });
11042
+ } catch (scheduleError) {
11043
+ console.error("[Think] failed to schedule a recovered messenger reply retry", scheduleError);
11044
+ }
11045
+ }
11046
+ /**
11047
+ * Retry delivering a recovered messenger reply (see
11048
+ * {@link _retryMessengerRecoveryDeliveryLater}).
11049
+ * @internal Schedule callback.
11050
+ */
11051
+ async _cfRetryMessengerRecoveryDelivery(payload) {
11052
+ try {
11053
+ await this._deliverMessengerRecovery(payload.key);
11054
+ } catch (error) {
11055
+ await this._retryMessengerRecoveryDeliveryLater(payload.key, payload.attempts, error);
11056
+ }
11057
+ }
11058
+ async _replayMessengerRecoveryDeliveries() {
11059
+ const pending = await this.ctx.storage.list({ prefix: MESSENGER_RECOVERY_PREFIX });
11060
+ for (const [key, delivery] of pending) {
11061
+ if (!delivery.outcome) {
11062
+ const incident = await this.ctx.storage.get(CHAT_RECOVERY_INCIDENT_KEY_PREFIX + encodeURIComponent(key.slice(28)));
11063
+ if (incident && incident.status !== "skipped" && incident.status !== "exhausted") continue;
11064
+ await this.ctx.storage.put(key, settleMessengerRecoveryDelivery(delivery, "interrupted"));
11065
+ }
11066
+ try {
11067
+ await this._deliverMessengerRecovery(key);
11068
+ } catch (error) {
11069
+ await this._retryMessengerRecoveryDeliveryLater(key, 0, error);
11070
+ }
11071
+ }
11072
+ }
11073
+ /**
9496
11074
  * Persist (on `error`/`interrupted`) or clear (on `completed`/`aborted`) the
9497
11075
  * durable terminal record so it can be replayed to clients on reconnect, and
9498
11076
  * resolve any in-progress "recovering…" indicator. A `completed`/`aborted`
@@ -9503,8 +11081,8 @@ var Think = class Think extends Agent {
9503
11081
  * The storage primitives are shared with `@cloudflare/ai-chat`
9504
11082
  * (`_recordChatTerminal` / `_clearChatTerminal` / `_pendingChatTerminal`).
9505
11083
  */
9506
- async _recordTerminalChatStatus(status, requestId, body) {
9507
- if (status === "error" || status === "interrupted") await this._recordChatTerminal(requestId, body);
11084
+ async _recordTerminalChatStatus(status, requestId, body, messageIds) {
11085
+ if (status === "error" || status === "interrupted") await this._recordChatTerminal(requestId, body, messageIds);
9508
11086
  else await this._clearChatTerminal();
9509
11087
  await this._setChatRecovering(false);
9510
11088
  }
@@ -9514,8 +11092,8 @@ var Think = class Think extends Agent {
9514
11092
  * until a later turn supersedes it (`_clearChatTerminal`); a single record is
9515
11093
  * sufficient because only the most recent terminal is relevant.
9516
11094
  */
9517
- async _recordChatTerminal(requestId, body) {
9518
- await recordChatTerminal(this.ctx.storage, requestId, body);
11095
+ async _recordChatTerminal(requestId, body, messageIds = this._originMessageIdsFor(requestId)) {
11096
+ await recordChatTerminal(this.ctx.storage, requestId, body, messageIds);
9519
11097
  }
9520
11098
  /** Clear the durable terminal record once a later turn supersedes it (#1645). */
9521
11099
  async _clearChatTerminal() {
@@ -9555,7 +11133,8 @@ var Think = class Think extends Agent {
9555
11133
  async _buildIdleConnectMessages() {
9556
11134
  const messages = [{
9557
11135
  type: MSG_CHAT_MESSAGES,
9558
- messages: this.messages
11136
+ messages: this.messages,
11137
+ connect: true
9559
11138
  }];
9560
11139
  const recoveringFrame = await buildChatRecoveringFrame(this.ctx.storage, MSG_CHAT_RECOVERING, Date.now());
9561
11140
  if (recoveringFrame) messages.push(recoveringFrame);
@@ -9604,24 +11183,38 @@ var Think = class Think extends Agent {
9604
11183
  * an actively streaming run from being reclaimed before it goes quiet (#1706).
9605
11184
  */
9606
11185
  _startResumableStream(requestId, options) {
9607
- const streamId = this._resumableStream.start(requestId, options);
11186
+ const originIds = this._requestOriginMessageIds.get(requestId) ?? this._activeChatRecoveryOriginIds;
11187
+ const streamId = this._resumableStream.start(requestId, {
11188
+ ...options,
11189
+ ...originIds && { originMessageIds: originIds }
11190
+ });
9608
11191
  this._preStream.flushOnStreamStart((c) => this._notifyStreamResuming(c));
9609
11192
  return streamId;
9610
11193
  }
9611
11194
  /** Mark a resumable stream completed (settled now, rows kept until reclaim). */
9612
- _completeResumableStream(streamId) {
9613
- this._resumableStream.complete(streamId);
11195
+ _completeResumableStream(streamId, outcome) {
11196
+ this._resumableStream.complete(streamId, outcome);
11197
+ this._afterResumableStreamEnded();
11198
+ }
11199
+ /**
11200
+ * A connection offered the stream that never ACKed (`resume: false`, or
11201
+ * gone quiet) must still get the terminal frame and every later broadcast.
11202
+ */
11203
+ _afterResumableStreamEnded() {
11204
+ this._pendingResumeConnections.clear();
9614
11205
  }
9615
11206
  /**
9616
11207
  * The producer finished; leave the row for the cutover that persists the
9617
11208
  * assistant message (`_persistAssistantMessageWithCutover`). Every path
9618
11209
  * that calls this must end in that cutover or `finalizePending()`.
9619
11210
  */
9620
- _finishResumableStream(streamId) {
9621
- this._resumableStream.finish(streamId);
11211
+ _finishResumableStream(streamId, outcome) {
11212
+ this._resumableStream.finish(streamId, outcome);
11213
+ this._afterResumableStreamEnded();
9622
11214
  }
9623
11215
  /** Mark a resumable stream errored. */
9624
11216
  _errorResumableStream(streamId, requestId) {
11217
+ this._afterResumableStreamEnded();
9625
11218
  this.ctx.storage.transactionSync(() => {
9626
11219
  this._resumableStream.markError(streamId);
9627
11220
  if (requestId) this._recordSubmissionTurnResult(requestId, { status: "error" });
@@ -9635,20 +11228,50 @@ var Think = class Think extends Agent {
9635
11228
  async _cleanupStreamBuffers() {
9636
11229
  this._resumableStream.reclaim();
9637
11230
  }
11231
+ /**
11232
+ * The message an orphaned stream's assistant message branches from, so the
11233
+ * reconstructed message lands where the live turn would have persisted it:
11234
+ * a regeneration beside the response it replaces, not under it. Undefined
11235
+ * for a turn that appends to the latest leaf, and on an `agents` release
11236
+ * that does not record the parent.
11237
+ */
11238
+ _orphanParentId(streamId) {
11239
+ return this._resumableStream.getStreamParentMessageId?.(streamId) ?? void 0;
11240
+ }
9638
11241
  async _persistOrphanedStream(streamId) {
9639
11242
  this._resumableStream.flushBuffer();
9640
11243
  const chunks = this._resumableStream.getStreamChunks(streamId);
9641
11244
  if (chunks.length === 0) return;
9642
- if (await persistReconstructedOrphan(chunks, {
9643
- store: this._orphanStore(),
11245
+ let persistedId;
11246
+ const store = this._orphanStore();
11247
+ const parentId = this._orphanParentId(streamId);
11248
+ if (!await persistReconstructedOrphan(chunks, {
11249
+ store: parentId === void 0 ? store : {
11250
+ ...store,
11251
+ appendMessage: (message) => store.appendMessage(message, parentId)
11252
+ },
9644
11253
  fallbackId: crypto.randomUUID(),
9645
- prepare: (message) => this._strippedForPersist(message),
11254
+ prepare: (message) => {
11255
+ const prepared = this._strippedForPersist(message);
11256
+ persistedId = prepared?.id;
11257
+ return prepared;
11258
+ },
9646
11259
  merge: (_existing, incoming) => incoming
9647
- })) this._broadcastMessages();
11260
+ })) return;
11261
+ const requestId = this._resumableStream.getStreamMetadata(streamId)?.request_id;
11262
+ if (requestId && persistedId) this._recordSubmissionMessage(requestId, persistedId);
11263
+ this._broadcastMessages();
9648
11264
  }
9649
11265
  _broadcastChat(message, exclude) {
9650
11266
  const allExclusions = [...exclude || [], ...this._pendingResumeConnections];
9651
- this.broadcast(JSON.stringify(message), allExclusions);
11267
+ this.broadcast(JSON.stringify(this._withOriginMessageIds(message)), allExclusions);
11268
+ }
11269
+ _originMessageIdsFor(requestId) {
11270
+ return this._requestOriginMessageIds.get(requestId) ?? this._resumableStream.getOriginMessageIds(requestId) ?? this._activeChatRecoveryOriginIds;
11271
+ }
11272
+ _withOriginMessageIds(message) {
11273
+ if (message.type !== MSG_CHAT_RESPONSE || typeof message.id !== "string" || !(message.done || message.error)) return message;
11274
+ return withOriginMessageIds(message, this._originMessageIdsFor(message.id));
9652
11275
  }
9653
11276
  _broadcast(message, exclude) {
9654
11277
  this.broadcast(JSON.stringify(message), exclude);