@tangle-network/agent-runtime 0.153.1 → 0.155.0

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.
Files changed (108) hide show
  1. package/dist/{activation-DKxQsHiO.js → activation-B4fRz8QL.js} +3 -3
  2. package/dist/{activation-DKxQsHiO.js.map → activation-B4fRz8QL.js.map} +1 -1
  3. package/dist/agent.d.ts +1 -1
  4. package/dist/agent.js +3 -3
  5. package/dist/{analyst-loop-B2kTHKNh.js → analyst-loop-Bouu53-l.js} +2 -2
  6. package/dist/{analyst-loop-B2kTHKNh.js.map → analyst-loop-Bouu53-l.js.map} +1 -1
  7. package/dist/analyst-loop.js +1 -1
  8. package/dist/{authoring-Tk2xFys0.js → authoring-8NW3YQvI.js} +2 -2
  9. package/dist/{authoring-Tk2xFys0.js.map → authoring-8NW3YQvI.js.map} +1 -1
  10. package/dist/candidate-execution/index.js +4 -4
  11. package/dist/{candidate-execution-CB9RJbbJ.js → candidate-execution-Ic92NMl9.js} +4 -4
  12. package/dist/{candidate-execution-CB9RJbbJ.js.map → candidate-execution-Ic92NMl9.js.map} +1 -1
  13. package/dist/{conversation-D64WyWrK.js → conversation-DLYKdh6W.js} +28 -13
  14. package/dist/{conversation-D64WyWrK.js.map → conversation-DLYKdh6W.js.map} +1 -1
  15. package/dist/conversation.d.ts +1 -1
  16. package/dist/conversation.js +1 -1
  17. package/dist/durable.d.ts +2 -2
  18. package/dist/durable.js +3 -6
  19. package/dist/durable.js.map +1 -1
  20. package/dist/{environment-provider-DJG0yIYl.d.ts → environment-provider-C_QI6VCG.d.ts} +2 -2
  21. package/dist/{environment-provider-D_MXw3jK.js → environment-provider-Dz9JB-X_.js} +134 -29
  22. package/dist/environment-provider-Dz9JB-X_.js.map +1 -0
  23. package/dist/environment-provider.d.ts +1 -1
  24. package/dist/environment-provider.js +1 -1
  25. package/dist/{executable-spec-BUcUcEPk.js → executable-spec-7ovS7PBo.js} +2 -2
  26. package/dist/{executable-spec-BUcUcEPk.js.map → executable-spec-7ovS7PBo.js.map} +1 -1
  27. package/dist/{graph-M0Qr4863.js → graph-BCzC-tnl.js} +3 -3
  28. package/dist/{graph-M0Qr4863.js.map → graph-BCzC-tnl.js.map} +1 -1
  29. package/dist/{improvement-cycle-CDxlGQGE.js → improvement-cycle-g6RsxGbg.js} +7 -7
  30. package/dist/{improvement-cycle-CDxlGQGE.js.map → improvement-cycle-g6RsxGbg.js.map} +1 -1
  31. package/dist/{index-Dlz7ejRx.d.ts → index-CNqUQfuv.d.ts} +13 -8
  32. package/dist/{index-LQfgFJoX.d.ts → index-DPFUNEdU.d.ts} +6 -4
  33. package/dist/{index-BihHgUAI.d.ts → index-DU6lU9GO.d.ts} +4 -4
  34. package/dist/index.d.ts +7 -7
  35. package/dist/index.js +13 -13
  36. package/dist/intelligence.d.ts +4 -4
  37. package/dist/intelligence.js +6 -6
  38. package/dist/jsonl-file-CDfsCI5s.js +59 -0
  39. package/dist/jsonl-file-CDfsCI5s.js.map +1 -0
  40. package/dist/kernel.d.ts +5 -5
  41. package/dist/kernel.js +10 -10
  42. package/dist/{knowledge-DM-i40b9.js → knowledge-BDoJh3Me.js} +5 -5
  43. package/dist/{knowledge-DM-i40b9.js.map → knowledge-BDoJh3Me.js.map} +1 -1
  44. package/dist/knowledge.d.ts +1 -1
  45. package/dist/knowledge.js +1 -1
  46. package/dist/{loop-runner-bin-pD5WJuqJ.js → loop-runner-bin-DyoELXnJ.js} +4 -4
  47. package/dist/{loop-runner-bin-pD5WJuqJ.js.map → loop-runner-bin-DyoELXnJ.js.map} +1 -1
  48. package/dist/{loop-runner-bin-D-BW51yr.d.ts → loop-runner-bin-mX79dLj2.d.ts} +3 -3
  49. package/dist/loop-runner-bin.d.ts +1 -1
  50. package/dist/loop-runner-bin.js +1 -1
  51. package/dist/{materialization-Bo6j3Hg9.js → materialization-Ct3I4wu3.js} +48 -4
  52. package/dist/materialization-Ct3I4wu3.js.map +1 -0
  53. package/dist/mcp/bin.js +3 -3
  54. package/dist/mcp/index.d.ts +3 -3
  55. package/dist/mcp/index.js +5 -5
  56. package/dist/{openai-tools-CWBywy-e.js → openai-tools-DUOEbKMV.js} +2 -2
  57. package/dist/{openai-tools-CWBywy-e.js.map → openai-tools-DUOEbKMV.js.map} +1 -1
  58. package/dist/{prepare-C3eFd3UA.js → prepare-DcMjMdj-.js} +19 -14
  59. package/dist/prepare-DcMjMdj-.js.map +1 -0
  60. package/dist/primeintellect/index.d.ts +1 -1
  61. package/dist/{protected-model-port-Dn2b6peS.js → protected-model-port-BzUkspPP.js} +2 -2
  62. package/dist/{protected-model-port-Dn2b6peS.js.map → protected-model-port-BzUkspPP.js.map} +1 -1
  63. package/dist/{redact-NAptmqKw.d.ts → redact-BT7-mX8G.d.ts} +3 -3
  64. package/dist/{runtime-RY_rvv7t.js → runtime-DW9t84HW.js} +60 -30
  65. package/dist/runtime-DW9t84HW.js.map +1 -0
  66. package/dist/{runtime-B-5dp5Iz.d.ts → runtime-DuueBLeO.d.ts} +4 -4
  67. package/dist/{sandbox-events-DMijDq2p.js → sandbox-events-BVjstFgb.js} +23 -3
  68. package/dist/sandbox-events-BVjstFgb.js.map +1 -0
  69. package/dist/{snapshot-cK9K420n.js → snapshot-CTAf4uuA.js} +8 -3
  70. package/dist/snapshot-CTAf4uuA.js.map +1 -0
  71. package/dist/{spawn-journal-CLguaA2A.js → spawn-journal-duo0EkOp.js} +31 -66
  72. package/dist/spawn-journal-duo0EkOp.js.map +1 -0
  73. package/dist/{stream-agent-turn-BGyszuPH.d.ts → stream-agent-turn-BbcwWw_J.d.ts} +2 -2
  74. package/dist/{stream-agent-turn-D6HoaRPV.js → stream-agent-turn-FRZAuXAL.js} +5 -6
  75. package/dist/stream-agent-turn-FRZAuXAL.js.map +1 -0
  76. package/dist/{structural-rollout-P1YxFRfl.js → structural-rollout-B1TocSdq.js} +24 -10
  77. package/dist/structural-rollout-B1TocSdq.js.map +1 -0
  78. package/dist/{supervise-BezbzKiJ.js → supervise-gZ3xYJs3.js} +54 -127
  79. package/dist/supervise-gZ3xYJs3.js.map +1 -0
  80. package/dist/{supervisor-DBVlPONC.js → supervisor-BmXD0WCJ.js} +109 -288
  81. package/dist/supervisor-BmXD0WCJ.js.map +1 -0
  82. package/dist/testing.d.ts +2 -2
  83. package/dist/testing.js +12 -12
  84. package/dist/{top-app-tKo9OrON.js → top-app-3rYfFPTW.js} +4 -62
  85. package/dist/top-app-3rYfFPTW.js.map +1 -0
  86. package/dist/tui/bin.js +1 -1
  87. package/dist/tui/index.d.ts +0 -1
  88. package/dist/tui/index.js +1 -1
  89. package/dist/{types-BPQhQRrC.d.ts → types-Cz5mCGlY.d.ts} +4 -4
  90. package/dist/{util-Bncw0o_F.js → util-D6ZEuBMi.js} +32 -2
  91. package/dist/util-D6ZEuBMi.js.map +1 -0
  92. package/dist/{workspace-archive-Dm73lTfB.js → workspace-archive-bugA3OwU.js} +2 -13
  93. package/dist/workspace-archive-bugA3OwU.js.map +1 -0
  94. package/package.json +4 -4
  95. package/dist/environment-provider-D_MXw3jK.js.map +0 -1
  96. package/dist/materialization-Bo6j3Hg9.js.map +0 -1
  97. package/dist/prepare-C3eFd3UA.js.map +0 -1
  98. package/dist/runtime-RY_rvv7t.js.map +0 -1
  99. package/dist/sandbox-events-DMijDq2p.js.map +0 -1
  100. package/dist/snapshot-cK9K420n.js.map +0 -1
  101. package/dist/spawn-journal-CLguaA2A.js.map +0 -1
  102. package/dist/stream-agent-turn-D6HoaRPV.js.map +0 -1
  103. package/dist/structural-rollout-P1YxFRfl.js.map +0 -1
  104. package/dist/supervise-BezbzKiJ.js.map +0 -1
  105. package/dist/supervisor-DBVlPONC.js.map +0 -1
  106. package/dist/top-app-tKo9OrON.js.map +0 -1
  107. package/dist/util-Bncw0o_F.js.map +0 -1
  108. package/dist/workspace-archive-Dm73lTfB.js.map +0 -1
@@ -1,12 +1,12 @@
1
- import { C as unknownExecutionBindingReceipt, S as runtimeOwnedScopeOwnerRuntime, a as authoredProfileDigest, b as runtimeOwnedExecutorProviderEvidence, c as knownExecutionBindingReceipt, f as recordRuntimeOwnedProviderAttemptStart, g as runtimeOwnedDeferredExecutorRuntime, h as recordRuntimeOwnedProviderModel, l as knownMaterializationReceipt, m as recordRuntimeOwnedProviderIdentityConflict, n as attestRuntimeOwnedExecutor, o as finalizeRuntimeOwnedPendingExecutor, p as recordRuntimeOwnedProviderDispatchNotStarted, r as attestRuntimeOwnedPendingExecutor, s as inheritRuntimeOwnedExecutorAttestation, t as attestRuntimeOwnedDeferredExecutor, u as newExecutionAttemptId, v as runtimeOwnedExecutorExecutionBinding, w as unknownMaterializationReceipt, x as runtimeOwnedPendingExecutorMaterialization, y as runtimeOwnedExecutorMaterialization } from "./materialization-Bo6j3Hg9.js";
1
+ import { C as runtimeOwnedScopeOwnerRuntime, S as runtimeOwnedPendingExecutorMaterialization, T as unknownMaterializationReceipt, _ as runtimeOwnedDeferredExecutorRuntime, a as authoredProfileDigest, b as runtimeOwnedExecutorMaterialization, c as knownExecutionBindingReceipt, g as recordRuntimeOwnedProviderModel, h as recordRuntimeOwnedProviderIdentityConflict, l as knownMaterializationReceipt, m as recordRuntimeOwnedProviderDispatchNotStarted, n as attestRuntimeOwnedExecutor, o as finalizeRuntimeOwnedPendingExecutor, p as recordRuntimeOwnedProviderAttemptStart, r as attestRuntimeOwnedPendingExecutor, s as inheritRuntimeOwnedExecutorAttestation, t as attestRuntimeOwnedDeferredExecutor, u as newExecutionAttemptId, w as unknownExecutionBindingReceipt, x as runtimeOwnedExecutorProviderEvidence, y as runtimeOwnedExecutorExecutionBinding } from "./materialization-Ct3I4wu3.js";
2
2
  import { f as RuntimeRunStateError, m as ValidationError, r as BackendTransportError } from "./errors-CDZ8XsVj.js";
3
- import { t as detachedSnapshot } from "./snapshot-cK9K420n.js";
4
- import { S as contentAddress, a as aggregateProviderModelEvidence, c as pendingWaits, g as runtimeOwnedNestedDriverTreeRoot, h as nestedDriverTreeRoot, l as replaySpawnTree, m as driverRuntime, o as loadSpawnForest, p as attestNestedDriverTreeOwner, s as materializeTreeView, v as captureWorkerTraceEvidence } from "./spawn-journal-CLguaA2A.js";
5
- import { _ as withTimeout, a as cloneTokenUsage, d as randomSuffix, f as randomUuid, g as throwIfAborted, h as throwAbort, l as mapWithConcurrency, m as stringifySafe, n as addTokenUsage, o as deleteBoxSafe, p as sleep, r as chargedTokens, s as hasCompleteCacheBreakdown, t as addSpend, u as promptCacheTokenClasses, v as zeroSpend, y as zeroTokenUsage } from "./util-Bncw0o_F.js";
6
- import { c as sandboxEventServedBackend, i as extractLlmCallEvent, l as sandboxProgressEvents, o as mapSandboxToolEvent, r as createSandboxToolPartState, s as notifySandboxEventObserver, t as assertSandboxServedModel } from "./sandbox-events-DMijDq2p.js";
7
- import { n as executableAgentSpecSnapshot, r as projectSandboxOutcome, t as executableAgentProfileSnapshot } from "./executable-spec-BUcUcEPk.js";
3
+ import { n as detachedSnapshot } from "./snapshot-CTAf4uuA.js";
4
+ import { _ as captureWorkerTraceEvidence, a as aggregateProviderModelEvidence, c as loadSpawnForest, d as replaySpawnTree, f as attestNestedDriverTreeOwner, h as runtimeOwnedNestedDriverTreeRoot, l as materializeTreeView, m as nestedDriverTreeRoot, o as closesCursorSlot, p as driverRuntime, u as pendingWaits, x as contentAddress } from "./spawn-journal-duo0EkOp.js";
5
+ import { _ as unmeteredSpend, a as cloneTokenUsage, b as zeroTokenUsage, d as randomSuffix, f as randomUuid, g as throwIfAborted, h as throwAbort, l as mapWithConcurrency, m as stringifySafe, n as addTokenUsage, o as deleteBoxSafe, p as sleep, r as chargedTokens, s as hasCompleteCacheBreakdown, t as addSpend, u as promptCacheTokenClasses, v as withTimeout, y as zeroSpend } from "./util-D6ZEuBMi.js";
6
+ import { c as notifySandboxEventObserver, i as extractLlmCallEvent, l as sandboxEventServedBackend, r as createSandboxToolPartState, s as mapSandboxToolEvent, t as assertSandboxServedModel, u as sandboxProgressEvents } from "./sandbox-events-BVjstFgb.js";
7
+ import { n as executableAgentSpecSnapshot, r as projectSandboxOutcome, t as executableAgentProfileSnapshot } from "./executable-spec-7ovS7PBo.js";
8
8
  import { a as concreteProfileModel, c as profileModelExecutionSettings, d as agentHarness, o as enforceTokenLimits, s as profileBridgeWireModel, t as assertExecutableAgentProfile, u as resolveRouterRetryPolicy } from "./model-policy-Sw4ywhtL.js";
9
- import { i as resolveAgentEnvironmentProvider, n as providerAsExecutor, r as providerAsSandboxClient } from "./environment-provider-D_MXw3jK.js";
9
+ import { c as linkAbort, i as resolveAgentEnvironmentProvider, l as runAbortable, n as providerAsExecutor, r as providerAsSandboxClient, s as abortError } from "./environment-provider-Dz9JB-X_.js";
10
10
  import { i as notifyRuntimeHookEvent } from "./runtime-hooks-tXpAarhW.js";
11
11
  import { AGENT_PROFILE_MATERIALIZATION_AXES, AgentTurnInputSchema, REASONING_EFFORTS, agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, profileMaterializationAxes, profileMaterializationAxes as profileMaterializationAxes$1, renderInputPartsAsText, sha256DigestSchema } from "@tangle-network/agent-interface";
12
12
  import { estimateCost, isModelPriced } from "@tangle-network/agent-eval";
@@ -5274,6 +5274,36 @@ function priceUnreceiptedWork(work) {
5274
5274
  };
5275
5275
  }
5276
5276
  //#endregion
5277
+ //#region src/runtime/supervise/node-status.ts
5278
+ /**
5279
+ * Which {@link NodeStatus} values mean the node is finished.
5280
+ *
5281
+ * `'waiting'` is deliberately NOT terminal: a wait-state node holds no executor, no box and no
5282
+ * conserved budget, so it is neither in flight nor settled. Callers that must also exclude it say
5283
+ * so at their own site, because "finished" and "not a live worker" are different questions.
5284
+ */
5285
+ const terminalNodeStatuses = /* @__PURE__ */ new Set([
5286
+ "done",
5287
+ "failed",
5288
+ "cancelled"
5289
+ ]);
5290
+ /**
5291
+ * True once a node has reached a terminal status.
5292
+ *
5293
+ * The single owner of this rule. Written per call site it drifts silently: a status added to
5294
+ * `NodeStatus` is classified by whichever sites the author remembered, and the ones they missed
5295
+ * keep a dead node in the live set — a stop rule that never fires, mail delivered to a worker that
5296
+ * cannot read it, or a cancel answered `not_live` for a node that is still running.
5297
+ */
5298
+ function isTerminalNodeStatus(status) {
5299
+ return terminalNodeStatuses.has(status);
5300
+ }
5301
+ /** True while a node has not yet reached a terminal status. The complement of
5302
+ * {@link isTerminalNodeStatus}, so the two can never disagree. */
5303
+ function isLiveNodeStatus(status) {
5304
+ return !terminalNodeStatuses.has(status);
5305
+ }
5306
+ //#endregion
5277
5307
  //#region src/runtime/supervise/peer-mail.ts
5278
5308
  /**
5279
5309
  *
@@ -5359,7 +5389,6 @@ function isPeerMailEnvelope(value) {
5359
5389
  function isPeerMailKind(value) {
5360
5390
  return value === "ask" || value === "tell" || value === "challenge" || value === "answer";
5361
5391
  }
5362
- const isLiveStatus = (status) => status !== "done" && status !== "failed" && status !== "cancelled";
5363
5392
  /** Create the run's post office. One per manager scope; the manager's siblings are its addresses. */
5364
5393
  function createPeerMailbox(opts) {
5365
5394
  const limits = Object.freeze({
@@ -5399,7 +5428,7 @@ function createPeerMailbox(opts) {
5399
5428
  await opts.publish(event);
5400
5429
  return event;
5401
5430
  };
5402
- const liveNodes = () => opts.scope.view.nodes.filter((node) => isLiveStatus(node.status));
5431
+ const liveNodes = () => opts.scope.view.nodes.filter((node) => isLiveNodeStatus(node.status));
5403
5432
  const mailbox = {
5404
5433
  limits,
5405
5434
  setEndpoint(baseUrl) {
@@ -5474,7 +5503,7 @@ function createPeerMailbox(opts) {
5474
5503
  if (opts.scope.signal.aborted) return record(envelope, "scope-stopped");
5475
5504
  const node = opts.scope.view.nodes.find((candidate) => candidate.id === to);
5476
5505
  if (node === void 0) return record(envelope, "unknown-worker");
5477
- if (!isLiveStatus(node.status)) return record(envelope, "already-settled");
5506
+ if (!isLiveNodeStatus(node.status)) return record(envelope, "already-settled");
5478
5507
  let delivered = false;
5479
5508
  try {
5480
5509
  delivered = opts.scope.send(to, { [PEER_MAIL_WIRE_KEY]: envelope });
@@ -5701,6 +5730,29 @@ function createInbox() {
5701
5730
  }
5702
5731
  //#endregion
5703
5732
  //#region src/runtime/supervise/progress.ts
5733
+ /**
5734
+ *
5735
+ * The LIVE read-model of a still-RUNNING worker — what a driver can see BEFORE the worker settles.
5736
+ *
5737
+ * Until this existed, `observe_agent` on a running worker returned `{status:'running', spent:{0,0},
5738
+ * outRef:null, output:null}`: nothing a brain could act on, so a brain that wanted to steer had no
5739
+ * evidence to steer FROM. This is the other half of the steering wire (the first half is
5740
+ * `Executor.deliver`): a supervisor cannot correct a worker it cannot watch.
5741
+ *
5742
+ * Two layers, both pull-based — no timer, no background task, so it is safe to leave on:
5743
+ *
5744
+ * - The SCOPE layer, available for EVERY executor with no executor cooperation at all: usage
5745
+ * events are timestamped as they arrive, so `lastActivityAt` / `idleMs` / `stalled` /
5746
+ * `tokens` / `turns` are derived from the stream the conserved pool already meters.
5747
+ * - The EXECUTOR layer, optional enrichment via `Executor.progress()`: the tool/file activity
5748
+ * the harness exposes, its own turn count, and how many steers are queued but unread.
5749
+ *
5750
+ * `stalled` is a DERIVED read, computed at observation time against `stallAfterMs` — never a
5751
+ * background watchdog. A worker that has produced no metered activity for longer than the
5752
+ * threshold reads `stalled: true`; nothing is killed, nothing is retried. The driver decides.
5753
+ *
5754
+ * @experimental
5755
+ */
5704
5756
  /** How long a worker may produce no metered activity before a `progress()` read calls it stalled.
5705
5757
  * Deliberately generous: a coding harness routinely spends minutes inside one tool call, and a
5706
5758
  * false stall that provokes a steer is worse than a late one. */
@@ -5743,7 +5795,7 @@ function createActivityLog(limit = 12) {
5743
5795
  /** Fold the scope-derived facts and the executor's optional enrichment into one read. Pure: the
5744
5796
  * caller supplies `now`, so a test can observe a stall without waiting for one. */
5745
5797
  function readWorkerProgress(scope, executor, now, stallAfterMs = DEFAULT_STALL_AFTER_MS) {
5746
- const live = scope.status !== "done" && scope.status !== "failed" && scope.status !== "cancelled";
5798
+ const live = isLiveNodeStatus(scope.status);
5747
5799
  const executorActivityAt = executor?.recentActivity?.length ? executor.recentActivity[executor.recentActivity.length - 1].at : 0;
5748
5800
  const lastActivityAt = Math.max(scope.lastActivityAt, executorActivityAt);
5749
5801
  const idleMs = Math.max(0, now - lastActivityAt);
@@ -5850,15 +5902,21 @@ const decodeOpenAiPart = (p) => {
5850
5902
  ...str(p.id) ? { callId: p.id } : str(fn?.id) ? { callId: fn?.id } : {}
5851
5903
  };
5852
5904
  };
5853
- /** The harness decoder registry. Add a harness by adding one entry. */
5905
+ /** kimi-code streams BOTH shapes on one session an Anthropic `tool_use` content block AND a
5906
+ * top-level OpenAI `tool_calls` entry (cli-bridge `kimi.ts` surfaces each from a different part of
5907
+ * the wire). A decoder that reads only one of them drops half of a kimi worker's tool calls, and
5908
+ * drops them silently: the trace simply reports fewer calls. */
5909
+ const decodeKimiPart = (p) => decodeAnthropicPart(p) ?? decodeOpenAiPart(p);
5910
+ /** The harness → decoder registry. Add a harness by adding one entry.
5911
+ *
5912
+ * Keyed by `HarnessType`, the vocabulary the `harness` argument is actually drawn from, so a key
5913
+ * no caller can produce does not compile. `codex` is registered although the bridge's `codex.ts`
5914
+ * never yields `tool_calls`; the entry states which family it would belong to. */
5854
5915
  const toolPartDecoders = {
5855
5916
  opencode: decodeOpencodePart,
5856
5917
  "claude-code": decodeAnthropicPart,
5857
- anthropic: decodeAnthropicPart,
5858
5918
  codex: decodeOpenAiPart,
5859
- openai: decodeOpenAiPart,
5860
- router: decodeOpenAiPart,
5861
- kimi: decodeOpenAiPart
5919
+ "kimi-code": decodeKimiPart
5862
5920
  };
5863
5921
  /** Decode a part with a specific harness's adapter when known, else try every registered adapter
5864
5922
  * (the composite — robust to mixed/unknown streams). Never throws. */
@@ -6503,7 +6561,7 @@ function createWorktreeCliExecutor(options) {
6503
6561
  runtime: "cli",
6504
6562
  budgetExempt,
6505
6563
  async execute(task, signal) {
6506
- const linked = linkSignals$1(signal, controller.signal);
6564
+ const linked = linkAbort(signal, controller.signal).signal;
6507
6565
  const started = Date.now();
6508
6566
  const taskPrompt = executionTaskPrompt(task, options.taskPrompt);
6509
6567
  run = await runWorktreeHarness({
@@ -6628,20 +6686,6 @@ function executionTaskPrompt(task, configuredPrompt) {
6628
6686
  }
6629
6687
  throw new ValidationError("createWorktreeCliExecutor: execute task must be JSON-serializable");
6630
6688
  }
6631
- /** Link two abort signals into one that fires when either does. Returns `undefined` when neither
6632
- * is present so the harness runner gets no signal at all. */
6633
- function linkSignals$1(a, b) {
6634
- if (a.aborted || b.aborted) {
6635
- const c = new AbortController();
6636
- c.abort();
6637
- return c.signal;
6638
- }
6639
- const c = new AbortController();
6640
- const onAbort = () => c.abort();
6641
- a.addEventListener("abort", onAbort, { once: true });
6642
- b.addEventListener("abort", onAbort, { once: true });
6643
- return c.signal;
6644
- }
6645
6689
  //#endregion
6646
6690
  //#region src/runtime/supervise/runtime.ts
6647
6691
  /**
@@ -6813,36 +6857,6 @@ function contentRef(prefix, value) {
6813
6857
  return `${prefix}:${(h >>> 0).toString(16).padStart(8, "0")}`;
6814
6858
  }
6815
6859
  /**
6816
- * The spend of work that HAPPENED and reported no usage receipt.
6817
- *
6818
- * Not the same value as a plain zero even though both carry `{0,0}` tokens and `$0`. A bare zero
6819
- * asserts a MEASUREMENT — "this ran and cost nothing" — and every consumer downstream reads it that
6820
- * way: the pool keeps reporting `readout().tokensKnown === true`, the journal totals stay clean, the
6821
- * OTEL span records a priced zero, and a caller's token-denominated ceiling can never fire no matter
6822
- * how much the work really burned. A ceiling that cannot fire is worse than no ceiling, because it
6823
- * reads as protection.
6824
- *
6825
- * `Spend.tokensKnown` is the marker the substrate already threads end to end for exactly this case
6826
- * (`budget.ts`, `otel-spans.ts`, `spawn-journal.ts`, `supervisor.ts`): the work is recorded, the
6827
- * zero is labelled a floor rather than a total, and every rollup that touches it reports its balance
6828
- * as a ceiling rather than a measurement. Use this — never a bare zero — whenever a runtime cannot
6829
- * see what its worker spent.
6830
- *
6831
- * The same rule applies to dollars. A dollar-capped run must refuse an executor whose billed spend
6832
- * is unknowable; `budgetExempt` does not authorize Runtime to relabel unknown spend as a measured
6833
- * zero. Callers that require dollar accounting must use a backend with a trusted billing receipt.
6834
- */
6835
- function unmeteredSpend(ms) {
6836
- return {
6837
- iterations: 0,
6838
- tokens: zeroTokenUsage(),
6839
- tokensKnown: false,
6840
- usd: 0,
6841
- usdKnown: false,
6842
- ms
6843
- };
6844
- }
6845
- /**
6846
6860
  * A direct OpenAI-compatible Router chat-completion. One-shot: resolves a
6847
6861
  * `ExecutorResult` and reports its terminal usage as `UsageEvent`s through the
6848
6862
  * conserved pool. Reports REAL token usage — when the provider omits `usage`,
@@ -6872,12 +6886,7 @@ const routerInlineExecutor = (spec, ctx) => {
6872
6886
  if (!seam.routerBaseUrl || !seam.routerKey) throw new ValidationError("routerInlineExecutor: RouterSeam.routerBaseUrl + routerKey required");
6873
6887
  const profileExecution = routerProfileExecution(spec.profile, seam, { multiTurn: false });
6874
6888
  const requestIdentity = routerRequestIdentity(ctx);
6875
- const controller = new AbortController();
6876
- const abortIfSignalled = () => {
6877
- if (ctx.signal.aborted) controller.abort();
6878
- };
6879
- abortIfSignalled();
6880
- if (!ctx.signal.aborted) ctx.signal.addEventListener("abort", abortIfSignalled, { once: true });
6889
+ const controller = linkAbort(ctx.signal);
6881
6890
  let artifact;
6882
6891
  const executionId = ctx.node?.nodeId ?? `router-request-${randomUUID()}`;
6883
6892
  const attemptId = ctx.node?.attemptId ?? newExecutionAttemptId(executionId);
@@ -6887,7 +6896,7 @@ const routerInlineExecutor = (spec, ctx) => {
6887
6896
  async execute(task, signal) {
6888
6897
  const messages = taskToMessages(task, spec, profileExecution.systemPrompt);
6889
6898
  const started = Date.now();
6890
- const linked = linkSignals(signal, controller.signal);
6899
+ const linked = linkAbort(signal, controller.signal).signal;
6891
6900
  const extraBody = {
6892
6901
  ...profileExecution.extraBody ?? {},
6893
6902
  ...profileExecution.reasoningEffort ? { reasoning_effort: profileExecution.reasoningEffort } : {}
@@ -6928,7 +6937,7 @@ const routerInlineExecutor = (spec, ctx) => {
6928
6937
  tokens: r.usage ? cloneTokenUsage({
6929
6938
  input: r.usage.input,
6930
6939
  output: r.usage.output,
6931
- ...routerPromptCacheUsage(r.usage.input, r.cache)
6940
+ ...promptCacheTokenClasses(r.usage.input, r.cache)
6932
6941
  }) : zeroTokenUsage(),
6933
6942
  usd: r.billedCostUsd ?? 0,
6934
6943
  ...r.usage ? {} : { tokensKnown: false },
@@ -7027,22 +7036,6 @@ function mergePromptCache(target, cache) {
7027
7036
  }
7028
7037
  if (cache.status !== void 0) target.status = cache.status;
7029
7038
  }
7030
- /** Preserve a complete Router cache split; an incomplete provider receipt stays unknown. */
7031
- function routerPromptCacheUsage(input, cache) {
7032
- if (cache === void 0) return {};
7033
- const read = cache.readTokens;
7034
- const write = cache.writeTokens;
7035
- if (read === void 0 && write === void 0) return {};
7036
- if (input === void 0 || !isCacheTokenCount(read) || !isCacheTokenCount(write) || read + write > input) return { cacheBreakdownKnown: false };
7037
- return {
7038
- freshInput: input - read - write,
7039
- cacheRead: read,
7040
- cacheWrite: write
7041
- };
7042
- }
7043
- function isCacheTokenCount(value) {
7044
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
7045
- }
7046
7039
  async function runRouterTransport(context, call) {
7047
7040
  try {
7048
7041
  return await call();
@@ -7070,12 +7063,7 @@ const routerToolsInlineExecutor = (spec, ctx) => {
7070
7063
  const enabledToolNames = new Set(seam.tools.map((tool) => tool.function.name));
7071
7064
  const maxTurns = profileExecution.maxTurns ?? 0;
7072
7065
  const requestIdentity = routerRequestIdentity(ctx);
7073
- const controller = new AbortController();
7074
- const abortIfSignalled = () => {
7075
- if (ctx.signal.aborted) controller.abort();
7076
- };
7077
- abortIfSignalled();
7078
- if (!ctx.signal.aborted) ctx.signal.addEventListener("abort", abortIfSignalled, { once: true });
7066
+ const controller = linkAbort(ctx.signal);
7079
7067
  const inbox = createInbox();
7080
7068
  let artifact;
7081
7069
  const executionId = ctx.node?.nodeId ?? `router-tools-run-${randomUUID()}`;
@@ -7110,7 +7098,7 @@ const routerToolsInlineExecutor = (spec, ctx) => {
7110
7098
  });
7111
7099
  return pending.length > 0;
7112
7100
  };
7113
- const external = mergeAbortSignals(signal, controller.signal);
7101
+ const external = linkAbort(signal, controller.signal).signal;
7114
7102
  try {
7115
7103
  for (let t = 0; maxTurns === 0 || t < maxTurns; t += 1) {
7116
7104
  flush();
@@ -7163,12 +7151,12 @@ const routerToolsInlineExecutor = (spec, ctx) => {
7163
7151
  addTokenUsage(tokens, {
7164
7152
  input: res.usage.input,
7165
7153
  output: res.usage.output,
7166
- ...routerPromptCacheUsage(res.usage.input, res.cache)
7154
+ ...promptCacheTokenClasses(res.usage.input, res.cache)
7167
7155
  });
7168
7156
  if (res.usage.reasoning !== void 0) reasoningTokens += res.usage.reasoning;
7169
7157
  else reasoningKnown = false;
7170
7158
  } else {
7171
- addTokenUsage(tokens, routerPromptCacheUsage(void 0, res.cache));
7159
+ addTokenUsage(tokens, promptCacheTokenClasses(void 0, res.cache));
7172
7160
  tokensKnown = false;
7173
7161
  reasoningKnown = false;
7174
7162
  }
@@ -7386,12 +7374,7 @@ const sandboxExecutor = (spec, ctx) => {
7386
7374
  if (!Number.isFinite(maxIterations) || maxIterations <= 0) throw new ValidationError("sandboxExecutor: maxIterations must be > 0");
7387
7375
  const sandboxTokenLimits = enforceTokenLimits(profileModelExecutionSettings(spec.profile, "sandboxExecutor").tokenLimits, "sandbox", "sandboxExecutor");
7388
7376
  const traceEnv = workerTraceEnv(ctx);
7389
- const controller = new AbortController();
7390
- const abortIfSignalled = () => {
7391
- if (ctx.signal.aborted) controller.abort();
7392
- };
7393
- abortIfSignalled();
7394
- if (!ctx.signal.aborted) ctx.signal.addEventListener("abort", abortIfSignalled, { once: true });
7377
+ const controller = linkAbort(ctx.signal);
7395
7378
  let artifact;
7396
7379
  const executionId = ctx.node?.nodeId ?? `sandbox-run-${randomUUID()}`;
7397
7380
  const attemptId = ctx.node?.attemptId ?? newExecutionAttemptId(executionId);
@@ -7508,14 +7491,7 @@ const sandboxExecutor = (spec, ctx) => {
7508
7491
  }, sandboxMaterialization, sandboxBinding);
7509
7492
  };
7510
7493
  async function* streamSandboxLeaf(args) {
7511
- const linked = new AbortController();
7512
- const cascadeExternal = () => linked.abort(abortReasonOf(args.signal));
7513
- const cascadeScope = () => linked.abort(abortReasonOf(args.controller.signal));
7514
- if (args.signal.aborted || args.controller.signal.aborted) linked.abort(abortReasonOf(args.signal.aborted ? args.signal : args.controller.signal));
7515
- else {
7516
- args.signal.addEventListener("abort", cascadeExternal, { once: true });
7517
- args.controller.signal.addEventListener("abort", cascadeScope, { once: true });
7518
- }
7494
+ const linked = linkAbort(args.signal, args.controller.signal);
7519
7495
  const agentRun = {
7520
7496
  profile: args.spec.profile,
7521
7497
  taskToPrompt: (t) => taskToPrompt(t),
@@ -7603,8 +7579,7 @@ async function* streamSandboxLeaf(args) {
7603
7579
  provenance: "uncaptured"
7604
7580
  };
7605
7581
  } finally {
7606
- args.signal.removeEventListener("abort", cascadeExternal);
7607
- args.controller.signal.removeEventListener("abort", cascadeScope);
7582
+ linked.release();
7608
7583
  }
7609
7584
  }
7610
7585
  /** The loop's own failure, when NO iteration produced an output: the first error it
@@ -7650,12 +7625,7 @@ const cliExecutor = (_spec, ctx) => {
7650
7625
  const seam = readSeam(ctx, cliSeamKey, "cli");
7651
7626
  if (!seam.bin) throw new ValidationError("cliExecutor: CliSeam.bin required");
7652
7627
  const traceEnv = workerTraceEnv(ctx);
7653
- const controller = new AbortController();
7654
- const abortIfSignalled = () => {
7655
- if (ctx.signal.aborted) controller.abort();
7656
- };
7657
- abortIfSignalled();
7658
- if (!ctx.signal.aborted) ctx.signal.addEventListener("abort", abortIfSignalled, { once: true });
7628
+ const controller = linkAbort(ctx.signal);
7659
7629
  let proc;
7660
7630
  let artifact;
7661
7631
  const executionId = ctx.node?.nodeId ?? `cli-process-${randomUUID()}`;
@@ -7822,12 +7792,7 @@ const bridgeExecutor = (spec, ctx) => {
7822
7792
  const sessionId = seam.sessionId ?? `bridge-${spec.profile.name ?? "worker"}-${randomUUID()}`;
7823
7793
  const attemptId = ctx.node?.attemptId ?? newExecutionAttemptId(sessionId);
7824
7794
  const traceHeaders = workerTraceHeaders(ctx);
7825
- const controller = new AbortController();
7826
- const abortIfSignalled = () => {
7827
- if (ctx.signal.aborted) controller.abort();
7828
- };
7829
- abortIfSignalled();
7830
- if (!ctx.signal.aborted) ctx.signal.addEventListener("abort", abortIfSignalled, { once: true });
7795
+ const controller = linkAbort(ctx.signal);
7831
7796
  const inbox = createInbox();
7832
7797
  let artifact;
7833
7798
  const activeRuns = /* @__PURE__ */ new Map();
@@ -8182,7 +8147,7 @@ function readBridgeRunState(runId, body) {
8182
8147
  async function* streamBridgeSession(args) {
8183
8148
  const { seam, inbox, observation } = args;
8184
8149
  const started = Date.now();
8185
- const external = mergeAbortSignals(args.signal, args.controller.signal);
8150
+ const external = linkAbort(args.signal, args.controller.signal).signal;
8186
8151
  const tokens = zeroTokenUsage();
8187
8152
  let tokensKnown = true;
8188
8153
  let usd = 0;
@@ -9310,7 +9275,7 @@ function bridgeWorktreeExecutor(spec, ctx, seam) {
9310
9275
  execute(task, signal) {
9311
9276
  return (async function* bridgeWorktreeStream() {
9312
9277
  const started = Date.now();
9313
- const linked = mergeAbortSignals(signal, controller.signal);
9278
+ const linked = linkAbort(signal, controller.signal).signal;
9314
9279
  let bridgeArtifact;
9315
9280
  try {
9316
9281
  worktree = await createWorktree({
@@ -9587,6 +9552,11 @@ function snapshotExecutorConfig(config) {
9587
9552
  });
9588
9553
  }
9589
9554
  case "cli": return detachedSnapshot(config, `createExecutor ${config.backend} config`);
9555
+ default: {
9556
+ const named = config.backend;
9557
+ const supported = Object.keys(WORKER_TRACE_PROPAGATION).sort().join(", ");
9558
+ throw new ValidationError(`createExecutor: no backend named ${JSON.stringify(named)}; supported backends are ${supported}`);
9559
+ }
9590
9560
  }
9591
9561
  }
9592
9562
  /** A backend config reused for multiple workers/managers cannot pin execution identity. */
@@ -9922,113 +9892,6 @@ function singleShotDriver(maxIterations) {
9922
9892
  }
9923
9893
  };
9924
9894
  }
9925
- /** Link two abort signals into one that fires when either does. Returns
9926
- * `undefined` when neither is present so `fetch` gets no signal at all. */
9927
- function linkSignals(a, b) {
9928
- if (a.aborted || b.aborted) {
9929
- const c = new AbortController();
9930
- c.abort(abortReasonOf(a.aborted ? a : b));
9931
- return c.signal;
9932
- }
9933
- const c = new AbortController();
9934
- a.addEventListener("abort", () => c.abort(abortReasonOf(a)), { once: true });
9935
- b.addEventListener("abort", () => c.abort(abortReasonOf(b)), { once: true });
9936
- return c.signal;
9937
- }
9938
- /** The reason a signal carries, or a named fallback. A cascade that drops the upstream reason
9939
- * turns every downstream death into the generic "execution aborted": the worker's `down`
9940
- * record then says nothing about WHY, which is what makes a whole class of child mortality
9941
- * undiagnosable from the journal alone. */
9942
- function abortReasonOf(signal, fallback = "aborted by parent scope") {
9943
- const reason = signal.reason;
9944
- if (typeof reason === "string" && reason.length > 0) return reason;
9945
- if (reason instanceof Error && reason.name !== "AbortError" && reason.message.length > 0) return reason.message;
9946
- return fallback;
9947
- }
9948
- /** Combine N abort signals into one that fires when ANY does. Node-portable (no `AbortSignal.any`,
9949
- * which needs >=20.3 — the package floor is >=20). Module-exported (not package surface) so
9950
- * sibling leaf executors share the one portable implementation. */
9951
- function mergeAbortSignals(...signals) {
9952
- const c = new AbortController();
9953
- const onAbort = () => c.abort();
9954
- for (const s of signals) {
9955
- if (s.aborted) {
9956
- c.abort();
9957
- break;
9958
- }
9959
- s.addEventListener("abort", onAbort, { once: true });
9960
- }
9961
- return c.signal;
9962
- }
9963
- //#endregion
9964
- //#region src/runtime/supervise/abortable.ts
9965
- /**
9966
- * One abort race for the supervision tree.
9967
- *
9968
- * Every layer that can be cancelled needs the same two things: an `AbortError` that
9969
- * carries the signal's own reason, and a settle-once race between the work and the
9970
- * signal. Written per layer, the race drifts — the listener stops being removed on
9971
- * one path, or a late resolution overwrites a cancellation that already won.
9972
- *
9973
- * The fallback message is the only thing a layer supplies, so the error still names
9974
- * which layer cancelled.
9975
- */
9976
- /** An `AbortError` carrying the signal's own string reason, or `fallback` when it states none. */
9977
- function abortError(signal, fallback) {
9978
- const reason = signal.reason;
9979
- const error = new Error(typeof reason === "string" && reason.length > 0 ? reason : fallback);
9980
- error.name = "AbortError";
9981
- return error;
9982
- }
9983
- /**
9984
- * Settle `act()` against `signal`. The first outcome wins and the listener is always
9985
- * removed, so neither a late resolution nor a late abort can settle the promise twice.
9986
- * The losing promise stays observed, so a late rejection cannot surface as an unhandled
9987
- * process error.
9988
- *
9989
- * The abort rejection is deferred one microtask so a result the action had ALREADY
9990
- * produced still wins. It does not hand the race to a listener the action registers
9991
- * from inside `act()`: this function subscribes before it calls `act()`, so its own
9992
- * abort handler runs first and settles the promise. A caller that must let the action
9993
- * observe the abort itself has to hold a live promise and await that instead.
9994
- *
9995
- * A synchronous throw from `act()` propagates as the rejection, not as an abort.
9996
- */
9997
- async function runAbortable(act, signal, fallback) {
9998
- if (signal.aborted) throw abortError(signal, fallback);
9999
- return await new Promise((resolve, reject) => {
10000
- let settled = false;
10001
- const cleanup = () => signal.removeEventListener("abort", onAbort);
10002
- const onAbort = () => {
10003
- queueMicrotask(() => {
10004
- if (settled) return;
10005
- settled = true;
10006
- cleanup();
10007
- reject(abortError(signal, fallback));
10008
- });
10009
- };
10010
- signal.addEventListener("abort", onAbort, { once: true });
10011
- let work;
10012
- try {
10013
- work = Promise.resolve(act());
10014
- } catch (error) {
10015
- cleanup();
10016
- reject(error);
10017
- return;
10018
- }
10019
- work.then((value) => {
10020
- if (settled) return;
10021
- settled = true;
10022
- cleanup();
10023
- resolve(value);
10024
- }, (error) => {
10025
- if (settled) return;
10026
- settled = true;
10027
- cleanup();
10028
- reject(error);
10029
- });
10030
- });
10031
- }
10032
9895
  //#endregion
10033
9896
  //#region src/runtime/supervise/budget.ts
10034
9897
  /**
@@ -11497,13 +11360,10 @@ function createScope(args) {
11497
11360
  return;
11498
11361
  }
11499
11362
  }
11500
- function terminalNodeStatus(status) {
11501
- return status === "done" || status === "failed" || status === "cancelled";
11502
- }
11503
11363
  function interactive(nodeId) {
11504
11364
  const child = children.get(nodeId);
11505
11365
  if (!child) return noInteractiveSession("unknown-node");
11506
- if (child.wait || child.executorDone || terminalNodeStatus(child.status)) return noInteractiveSession("not-live");
11366
+ if (child.wait || child.executorDone || isTerminalNodeStatus(child.status)) return noInteractiveSession("not-live");
11507
11367
  if (!child.readInteractive) return noInteractiveSession("executor-exposes-no-interactive-session");
11508
11368
  let reported;
11509
11369
  try {
@@ -11577,7 +11437,7 @@ function createScope(args) {
11577
11437
  return {
11578
11438
  live: liveWorkerCapacity.live,
11579
11439
  freeSlots: freeSlots(liveWorkerCapacity.live, liveWorkerCapacity.max),
11580
- unconfirmed: Object.freeze([...children.values()].filter((child) => (child.status === "done" || child.status === "failed" || child.status === "cancelled") && !child.cleanupConfirmed).map((child) => Object.freeze({
11440
+ unconfirmed: Object.freeze([...children.values()].filter((child) => isTerminalNodeStatus(child.status) && !child.cleanupConfirmed).map((child) => Object.freeze({
11581
11441
  id: child.id,
11582
11442
  label: child.label,
11583
11443
  runtime: child.runtime,
@@ -12515,32 +12375,13 @@ function isSettled(ev) {
12515
12375
  /** Sum the conserved spend over the nested tree's settled events — the honest per-channel
12516
12376
  * roll-up of the whole sub-tree's child WORK. */
12517
12377
  function sumSpend(settled) {
12518
- const total = zeroSpend();
12519
- for (const ev of settled) {
12520
- total.iterations += ev.spent.iterations;
12521
- addTokenUsage(total.tokens, ev.spent.tokens);
12522
- if (ev.spent.tokensKnown === false) total.tokensKnown = false;
12523
- total.usd += ev.spent.usd;
12524
- if (ev.spent.usdKnown === false) total.usdKnown = false;
12525
- total.ms += ev.spent.ms;
12526
- }
12527
- return total;
12378
+ return settled.reduce((total, ev) => addSpend(total, ev.spent), zeroSpend());
12528
12379
  }
12529
12380
  /** Sum the nested tree's `metered` events — the sub-tree's whole driver INFERENCE (this driver's
12530
12381
  * own turns + any sub-driver inference already re-homed into this tree). Re-homed up to the parent
12531
12382
  * as one `metered` event; never reconciled (already pool-debited live via `observe`). */
12532
12383
  function sumMetered(events) {
12533
- const total = zeroSpend();
12534
- for (const ev of events) {
12535
- if (ev.kind !== "metered") continue;
12536
- total.iterations += ev.spend.iterations;
12537
- addTokenUsage(total.tokens, ev.spend.tokens);
12538
- if (ev.spend.tokensKnown === false) total.tokensKnown = false;
12539
- total.usd += ev.spend.usd;
12540
- if (ev.spend.usdKnown === false) total.usdKnown = false;
12541
- total.ms += ev.spend.ms;
12542
- }
12543
- return total;
12384
+ return events.reduce((total, ev) => ev.kind === "metered" ? addSpend(total, ev.spend) : total, zeroSpend());
12544
12385
  }
12545
12386
  /** An all-zero spend that carries an UNKNOWN marker counts as non-zero: a sub-driver whose turns
12546
12387
  * went unmeasured did real work, and dropping its `metered` event here would re-hide upstream the
@@ -12725,8 +12566,8 @@ async function runFinalizer(finalizer, args) {
12725
12566
  * - Join barrier: when `act()` settles (resolve OR reject), every still-live child is
12726
12567
  * torn down before `run` returns — the generalization of the kernel's
12727
12568
  * `finally{ Promise.allSettled(destroy) }` barrier (run-loop.ts) from boxes to the
12728
- * whole sub-tree. A teardown failure is `allSettled`'d and journaled as a
12729
- * `cancelled` event; it NEVER masks act()'s own outcome. act()'s rejection is the
12569
+ * whole sub-tree. A teardown failure is `allSettled`'d and journaled per node as a
12570
+ * `teardown-unconfirmed` event; it NEVER masks act()'s own outcome. act()'s rejection is the
12730
12571
  * PRIMARY error (the kernel's firstError precedence), so a teardown throw during the
12731
12572
  * barrier can never overwrite the real failure.
12732
12573
  * - Abort cascade: a root abort (caller signal, `RootHandle.abort`, a tripped breaker,
@@ -12882,7 +12723,7 @@ function rootDeadline(root) {
12882
12723
  }
12883
12724
  /** Child reservations whose spawn was durable but whose terminal record never landed. */
12884
12725
  function uncertainSpawnBudgets(events) {
12885
- const terminal = new Set(events.filter((event) => event.kind === "settled" || event.kind === "cancelled" || event.kind === "woken").map((event) => event.id));
12726
+ const terminal = new Set(events.filter(closesCursorSlot).map((event) => event.id));
12886
12727
  return events.filter((event) => event.kind === "spawned" && event.parent !== void 0 && !terminal.has(event.id)).map((event) => event.budget);
12887
12728
  }
12888
12729
  /** Highest `seq` among events matching `pred`, or `-1` when none match (so a resumed scope's
@@ -12982,7 +12823,7 @@ function createSupervisor() {
12982
12823
  settled,
12983
12824
  view: materializeTreeView(prior),
12984
12825
  maxSpawnOrdinal: maxSeqOf(prior, (ev) => ev.kind === "spawned"),
12985
- maxCursorSeq: maxSeqOf(prior, (ev) => ev.kind === "settled" || ev.kind === "cancelled" || ev.kind === "woken"),
12826
+ maxCursorSeq: maxSeqOf(prior, closesCursorSlot),
12986
12827
  maxWaitOrdinal: maxSeqOf(prior, (ev) => ev.kind === "waiting"),
12987
12828
  waits: pendingWaits(prior),
12988
12829
  keys: keyedAssignments(prior, settled),
@@ -13422,7 +13263,7 @@ function spendGapsFromEvents(events) {
13422
13263
  const labels = /* @__PURE__ */ new Map();
13423
13264
  const terminal = /* @__PURE__ */ new Set();
13424
13265
  for (const ev of events) if (ev.kind === "spawned") labels.set(ev.id, ev.label);
13425
- else if (ev.kind === "settled" || ev.kind === "cancelled" || ev.kind === "woken") terminal.add(ev.id);
13266
+ else if (closesCursorSlot(ev)) terminal.add(ev.id);
13426
13267
  const gaps = /* @__PURE__ */ new Map();
13427
13268
  const record = (id, kind, channels) => {
13428
13269
  if (channels.length === 0) return;
@@ -13474,35 +13315,15 @@ function sumSpendFromEvents(events) {
13474
13315
  return totals;
13475
13316
  }
13476
13317
  function sumMeasuredSpendFromEvents(events) {
13477
- const childWork = {
13478
- iterations: 0,
13479
- tokens: zeroTokenUsage(),
13480
- usd: 0,
13481
- ms: 0
13482
- };
13483
- const driverInference = {
13484
- iterations: 0,
13485
- tokens: zeroTokenUsage(),
13486
- usd: 0,
13487
- ms: 0
13488
- };
13489
- for (const ev of events) if (ev.kind === "settled") accumulate(childWork, ev.spent);
13490
- else if (ev.kind === "metered") accumulate(driverInference, ev.spend);
13318
+ let childWork = zeroSpend();
13319
+ let driverInference = zeroSpend();
13320
+ for (const ev of events) if (ev.kind === "settled") childWork = addSpend(childWork, ev.spent);
13321
+ else if (ev.kind === "metered") driverInference = addSpend(driverInference, ev.spend);
13491
13322
  return {
13492
13323
  childWork,
13493
13324
  driverInference
13494
13325
  };
13495
13326
  }
13496
- /** Add `b` into `a` in place, per channel. */
13497
- function accumulate(a, b) {
13498
- a.iterations += b.iterations;
13499
- addTokenUsage(a.tokens, b.tokens);
13500
- if (b.tokensKnown === false) a.tokensKnown = false;
13501
- a.usd += b.usd;
13502
- if (b.usdKnown === false) a.usdKnown = false;
13503
- if (b.usdEstimated !== void 0) a.usdEstimated = (a.usdEstimated ?? 0) + b.usdEstimated;
13504
- a.ms += b.ms;
13505
- }
13506
13327
  /** True when any driver metered inference this run (so the winner carries a `spentBreakdown`).
13507
13328
  * Checks every channel `addSpend` sums — including `ms` — so the gate stays consistent with the
13508
13329
  * total even though the coordination driver currently stamps `ms: 0`. */
@@ -13510,6 +13331,6 @@ function isNonEmptySpend(s) {
13510
13331
  return s.iterations > 0 || s.tokens.input > 0 || s.tokens.output > 0 || s.usd > 0 || s.ms > 0 || s.tokensKnown === false || s.usdKnown === false;
13511
13332
  }
13512
13333
  //#endregion
13513
- export { DEFAULT_STALL_AFTER_MS as $, localHarnessExecutable as $t, createBudgetPool as A, buildRuntimeEventOtelSpans as At, createExecutorRegistry as B, createRuntimeEventCollector as Bt, effectiveConcurrency as C, createPropagatingTraceEmitter as Ct, DEFAULT_SUCCESSFUL_SHUTDOWN_MS as D, INTELLIGENCE_WIRE_VERSION as Dt, rollingDispatch as E, traceContextToEnv as Et, bridgeRuntimeAttachmentsKey as F, generateSpanId as Ft, workerTraceEnv as G, runSettledCommand as Gt, createWorktreeCliExecutor as H, sanitizeAgentRuntimeEvent as Ht, bridgeStopSignalKey as I, loopEventToOtelSpan as It, DEFAULT_SANDBOX_STEERING_MAX_TURNS as J, createWorktree as Jt, workerTraceHeaders as K, runWorktreeHarness as Kt, captureReusableExecutorConfig as L, padSpanId as Lt, bindReusableExecutorExecutionId as M, createOtelExporter as Mt, bridgeAdmissionRead as N, exportEvalRuns as Nt, teardownExecutor as O, buildLoopOtelSpans as Ot, bridgeModelRouteRefusal as P, flatOtelSpan as Pt, sandboxSessionTraceSource as Q, harnessSupportsReasoningEffort as Qt, cliWorktreeExecutor as R, padTraceId as Rt, waitUntil as S, observedModelMatchesDeclared as St, queueOf as T, readTraceContextFromEnv as Tt, WORKER_TRACE_PROPAGATION as U, sanitizeKnowledgeReadinessReport as Ut, snapshotExecutorConfig as V, createRuntimeStreamEventCollector as Vt, readWorkerTraceContext as W, sanitizeRuntimeStreamEvent as Wt, createPushTraceSource as X, DEFAULT_LOCAL_HARNESS as Xt, createSteerableSandboxSession as Y, removeWorktree as Yt, decodeToolPart as Z, LOCAL_HARNESSES as Zt, createWaitProbes as _, worktreeCliProfileMaterialization as _n, probeSandboxCapabilities as _t, pickBestDelivered as a, defineProfileMaterializationContract as an, PEER_MAIL_WIRE_KEY as at, timerAt as b, runBrainLoop as bt, driverChild as c, promptControlProfileMaterialization as cn, isPeerMailEnvelope as ct, deriveNodeExecutionIdentity as d, promptResourceProfileMaterialization as dn, TERMINAL_DECISIONS as dt, parseCodexTokenUsage as en, createActivityLog as et, meterRuntimeOwnedAccounting as f, renderProfileMaterializationIssues as fn, createSandboxForSpec as ft, settledToIteration as g, validateProfileMaterialization as gn, createSandboxLineage as gt, scopeOwnerExecutorNodeContext as h, unsupportedProfileDimensions as hn, runAgentRounds as ht, collectDelivered as i, controlProfileMaterialization as in, DEFAULT_PEER_MAIL_LIMITS as it, spendFromUsageEvents as j, createOpenInferenceFileExporter as jt, assertValidBudget as k, buildLoopSpanNodes as kt, withDriverExecutor as l, promptModelProfileMaterialization as ln, peerMailTools as lt, recordScopeOwnerMaterialization as m, sandboxActProfileMaterialization as mn, isTerminalDecision as mt, createSupervisor as n, AGENT_PROFILE_MATERIALIZATION_AXES as nn, createInbox as nt, runFinalizer as o, fullProfileMaterialization as on, claimsAuthority as ot, meterRuntimeOwnedProviderAttempt as p, renderUnsupported as pn, defaultSelectWinner as pt, workerTraceSeamKey as q, captureWorktreeDiff as qt, bestDelivered as r, assertProfileMaterialization as rn, AUTHORITY_MARKERS as rt, runTree as s, profileMaterializationAxes$1 as sn, createPeerMailbox as st, createRootHandle as t, CodexExecutionDiagnosticError as tn, readWorkerProgress as tt, createScope as u, promptOnlyProfileMaterialization as un, peerMailVerbNames as ut, isWaitOutcome as v, acquireSandbox as vt, freeSlots as w, mergeTraceEnv as wt, validateWaitSpec as x, canonicalObservedModel as xt, pollFor as y, routerBrain as yt, createExecutor as z, toOtelAttributes as zt };
13334
+ export { DEFAULT_STALL_AFTER_MS as $, LOCAL_HARNESSES as $t, createBudgetPool as A, buildLoopOtelSpans as At, createExecutorRegistry as B, padTraceId as Bt, effectiveConcurrency as C, canonicalObservedModel as Ct, DEFAULT_SUCCESSFUL_SHUTDOWN_MS as D, readTraceContextFromEnv as Dt, rollingDispatch as E, mergeTraceEnv as Et, bridgeRuntimeAttachmentsKey as F, exportEvalRuns as Ft, workerTraceEnv as G, sanitizeKnowledgeReadinessReport as Gt, createWorktreeCliExecutor as H, createRuntimeEventCollector as Ht, bridgeStopSignalKey as I, flatOtelSpan as It, DEFAULT_SANDBOX_STEERING_MAX_TURNS as J, runWorktreeHarness as Jt, workerTraceHeaders as K, sanitizeRuntimeStreamEvent as Kt, captureReusableExecutorConfig as L, generateSpanId as Lt, bindReusableExecutorExecutionId as M, buildRuntimeEventOtelSpans as Mt, bridgeAdmissionRead as N, createOpenInferenceFileExporter as Nt, teardownExecutor as O, traceContextToEnv as Ot, bridgeModelRouteRefusal as P, createOtelExporter as Pt, sandboxSessionTraceSource as Q, DEFAULT_LOCAL_HARNESS as Qt, cliWorktreeExecutor as R, loopEventToOtelSpan as Rt, waitUntil as S, runBrainLoop as St, queueOf as T, createPropagatingTraceEmitter as Tt, WORKER_TRACE_PROPAGATION as U, createRuntimeStreamEventCollector as Ut, snapshotExecutorConfig as V, toOtelAttributes as Vt, readWorkerTraceContext as W, sanitizeAgentRuntimeEvent as Wt, createPushTraceSource as X, createWorktree as Xt, createSteerableSandboxSession as Y, captureWorktreeDiff as Yt, decodeToolPart as Z, removeWorktree as Zt, createWaitProbes as _, unsupportedProfileDimensions as _n, runAgentRounds as _t, pickBestDelivered as a, assertProfileMaterialization as an, PEER_MAIL_WIRE_KEY as at, timerAt as b, acquireSandbox as bt, driverChild as c, fullProfileMaterialization as cn, isPeerMailEnvelope as ct, deriveNodeExecutionIdentity as d, promptModelProfileMaterialization as dn, isLiveNodeStatus as dt, harnessSupportsReasoningEffort as en, createActivityLog as et, meterRuntimeOwnedAccounting as f, promptOnlyProfileMaterialization as fn, isTerminalNodeStatus as ft, settledToIteration as g, sandboxActProfileMaterialization as gn, isTerminalDecision as gt, scopeOwnerExecutorNodeContext as h, renderUnsupported as hn, defaultSelectWinner as ht, collectDelivered as i, AGENT_PROFILE_MATERIALIZATION_AXES as in, DEFAULT_PEER_MAIL_LIMITS as it, spendFromUsageEvents as j, buildLoopSpanNodes as jt, assertValidBudget as k, INTELLIGENCE_WIRE_VERSION as kt, withDriverExecutor as l, profileMaterializationAxes$1 as ln, peerMailTools as lt, recordScopeOwnerMaterialization as m, renderProfileMaterializationIssues as mn, createSandboxForSpec as mt, createSupervisor as n, parseCodexTokenUsage as nn, createInbox as nt, runFinalizer as o, controlProfileMaterialization as on, claimsAuthority as ot, meterRuntimeOwnedProviderAttempt as p, promptResourceProfileMaterialization as pn, TERMINAL_DECISIONS as pt, workerTraceSeamKey as q, runSettledCommand as qt, bestDelivered as r, CodexExecutionDiagnosticError as rn, AUTHORITY_MARKERS as rt, runTree as s, defineProfileMaterializationContract as sn, createPeerMailbox as st, createRootHandle as t, localHarnessExecutable as tn, readWorkerProgress as tt, createScope as u, promptControlProfileMaterialization as un, peerMailVerbNames as ut, isWaitOutcome as v, validateProfileMaterialization as vn, createSandboxLineage as vt, freeSlots as w, observedModelMatchesDeclared as wt, validateWaitSpec as x, routerBrain as xt, pollFor as y, worktreeCliProfileMaterialization as yn, probeSandboxCapabilities as yt, createExecutor as z, padSpanId as zt };
13514
13335
 
13515
- //# sourceMappingURL=supervisor-DBVlPONC.js.map
13336
+ //# sourceMappingURL=supervisor-BmXD0WCJ.js.map