@tangle-network/agent-runtime 0.180.0 → 0.182.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 (85) hide show
  1. package/dist/{activation-BNd8DB7m.js → activation-BfLdmBd5.js} +2 -2
  2. package/dist/{activation-BNd8DB7m.js.map → activation-BfLdmBd5.js.map} +1 -1
  3. package/dist/agent.d.ts +2 -2
  4. package/dist/agent.js +3 -3
  5. package/dist/{analyst-loop-Bouu53-l.js → analyst-loop-DCTra9Qy.js} +2 -2
  6. package/dist/{analyst-loop-Bouu53-l.js.map → analyst-loop-DCTra9Qy.js.map} +1 -1
  7. package/dist/analyst-loop.d.ts +1 -1
  8. package/dist/analyst-loop.js +1 -1
  9. package/dist/{authoring-UTj7_GAd.js → authoring-Dh_8qg7q.js} +2 -2
  10. package/dist/{authoring-UTj7_GAd.js.map → authoring-Dh_8qg7q.js.map} +1 -1
  11. package/dist/{conversation-BREx2hi-.js → conversation-BSgEebIo.js} +2 -2
  12. package/dist/{conversation-BREx2hi-.js.map → conversation-BSgEebIo.js.map} +1 -1
  13. package/dist/conversation.d.ts +1 -1
  14. package/dist/conversation.js +1 -1
  15. package/dist/{coordination-driver-CZdORo2F.js → coordination-driver-DBvHI8ZG.js} +2 -2
  16. package/dist/{coordination-driver-CZdORo2F.js.map → coordination-driver-DBvHI8ZG.js.map} +1 -1
  17. package/dist/durable.d.ts +2 -2
  18. package/dist/durable.js +1 -1
  19. package/dist/{environment-provider-DKyMWQJd.js → environment-provider-C4elwcpo.js} +2 -2
  20. package/dist/{environment-provider-DKyMWQJd.js.map → environment-provider-C4elwcpo.js.map} +1 -1
  21. package/dist/{environment-provider-BG0Lll6Y.d.ts → environment-provider-CzohJCuk.d.ts} +3 -3
  22. package/dist/environment-provider.d.ts +1 -1
  23. package/dist/environment-provider.js +1 -1
  24. package/dist/{graph-lskY1sph.js → graph-lU6GacsN.js} +2 -2
  25. package/dist/{graph-lskY1sph.js.map → graph-lU6GacsN.js.map} +1 -1
  26. package/dist/graph.d.ts +3 -3
  27. package/dist/graph.js +3 -3
  28. package/dist/{improvement-cycle-CwPaVYsD.js → improvement-cycle-DezfYhlh.js} +5 -5
  29. package/dist/{improvement-cycle-CwPaVYsD.js.map → improvement-cycle-DezfYhlh.js.map} +1 -1
  30. package/dist/{index-C_xAZx46.d.ts → index-BG4l6MHH.d.ts} +4 -4
  31. package/dist/{index-C_5ADJEz.d.ts → index-DHSZjuLC.d.ts} +3 -3
  32. package/dist/{index-W1pLy7b2.d.ts → index-z2A6q-v0.d.ts} +83 -11
  33. package/dist/index.d.ts +9 -9
  34. package/dist/index.js +9 -9
  35. package/dist/intelligence.d.ts +5 -5
  36. package/dist/intelligence.js +4 -4
  37. package/dist/kernel.d.ts +7 -7
  38. package/dist/kernel.js +12 -12
  39. package/dist/{knowledge-oEjtVYZK.js → knowledge-CioWuU6F.js} +3 -3
  40. package/dist/{knowledge-oEjtVYZK.js.map → knowledge-CioWuU6F.js.map} +1 -1
  41. package/dist/knowledge.d.ts +1 -1
  42. package/dist/knowledge.js +1 -1
  43. package/dist/{loop-runner-bin-Byrn0ovS.d.ts → loop-runner-bin-Dj0GJJWz.d.ts} +3 -3
  44. package/dist/{loop-runner-bin-C6ppaK7_.js → loop-runner-bin-Rzj8NOjr.js} +4 -4
  45. package/dist/{loop-runner-bin-C6ppaK7_.js.map → loop-runner-bin-Rzj8NOjr.js.map} +1 -1
  46. package/dist/loop-runner-bin.d.ts +1 -1
  47. package/dist/loop-runner-bin.js +1 -1
  48. package/dist/mcp/bin.js +3 -3
  49. package/dist/mcp/index.d.ts +9 -6
  50. package/dist/mcp/index.js +9 -5
  51. package/dist/mcp/index.js.map +1 -1
  52. package/dist/{openai-tools-NgZyaVWA.js → openai-tools-B4Gbj7BL.js} +2 -2
  53. package/dist/{openai-tools-NgZyaVWA.js.map → openai-tools-B4Gbj7BL.js.map} +1 -1
  54. package/dist/{openai-tools-wkxQ2aEw.d.ts → openai-tools-Cbk5uBUu.d.ts} +2 -2
  55. package/dist/primeintellect/index.d.ts +1 -1
  56. package/dist/profiles.d.ts +2 -2
  57. package/dist/{provision-supervisor-C2qAsvwJ.js → provision-supervisor-BBPNrEQk.js} +4 -4
  58. package/dist/{provision-supervisor-C2qAsvwJ.js.map → provision-supervisor-BBPNrEQk.js.map} +1 -1
  59. package/dist/{redact-Td4Z49qK.d.ts → redact-BYcuQ6R_.d.ts} +3 -3
  60. package/dist/{runtime-BcJkcqyq.d.ts → runtime-B-DLSfE5.d.ts} +57 -9
  61. package/dist/{runtime-CFttcekr.js → runtime-Db1JYl9P.js} +29 -14
  62. package/dist/runtime-Db1JYl9P.js.map +1 -0
  63. package/dist/{sandbox-events-BVjstFgb.js → sandbox-events-DGXLxiuX.js} +216 -11
  64. package/dist/sandbox-events-DGXLxiuX.js.map +1 -0
  65. package/dist/{stream-agent-turn-CPj9SqVm.js → stream-agent-turn-B5Cmq-u3.js} +47 -22
  66. package/dist/stream-agent-turn-B5Cmq-u3.js.map +1 -0
  67. package/dist/{stream-agent-turn-BJcmeOjJ.d.ts → stream-agent-turn-DY-y9yW1.d.ts} +3 -3
  68. package/dist/{structural-rollout-wSlpkkiV.js → structural-rollout-dG-cTxPq.js} +3 -3
  69. package/dist/{structural-rollout-wSlpkkiV.js.map → structural-rollout-dG-cTxPq.js.map} +1 -1
  70. package/dist/{substrate-AJoT4HIz.d.ts → substrate-RrmNZoL3.d.ts} +2 -2
  71. package/dist/{supervise-CSvq9RSA.js → supervise-rDa_CeUP.js} +3 -3
  72. package/dist/{supervise-CSvq9RSA.js.map → supervise-rDa_CeUP.js.map} +1 -1
  73. package/dist/{supervisor-wgifgrsR.js → supervisor-Df9kT_z3.js} +171 -87
  74. package/dist/supervisor-Df9kT_z3.js.map +1 -0
  75. package/dist/testing.d.ts +2 -2
  76. package/dist/testing.js +12 -12
  77. package/dist/tui/index.d.ts +1 -1
  78. package/dist/tui/index.js +1 -1
  79. package/dist/{types-CuObZjDz.d.ts → types-B-rWcun_.d.ts} +2 -2
  80. package/dist/{types-DpdfZoQ3.d.ts → types-CrTTgig6.d.ts} +25 -2
  81. package/package.json +1 -1
  82. package/dist/runtime-CFttcekr.js.map +0 -1
  83. package/dist/sandbox-events-BVjstFgb.js.map +0 -1
  84. package/dist/stream-agent-turn-CPj9SqVm.js.map +0 -1
  85. package/dist/supervisor-wgifgrsR.js.map +0 -1
@@ -3,10 +3,10 @@ import { c as RetainedInteractiveAdmissionError, d as RetainedRunDispatchBinding
3
3
  import { n as detachedSnapshot } from "./snapshot-CTAf4uuA.js";
4
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, n as FileSpawnJournal, o as closesCursorSlot, p as driverRuntime, u as pendingWaits, x as contentAddress } from "./spawn-journal--N8Ten1q.js";
5
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, m as parseCanonicalTransportEvent, p as extractTransportEventIdentity, r as createSandboxToolPartState, s as mapSandboxToolEvent, t as assertSandboxServedModel, u as sandboxProgressEvents } from "./sandbox-events-BVjstFgb.js";
6
+ import { _ as parseCodexUsageRecord, c as mapSandboxToolEvent, d as sandboxProgressEvents, h as parseCanonicalTransportEvent, i as createSandboxUsageLedger, l as notifySandboxEventObserver, m as extractTransportEventIdentity, r as createSandboxToolPartState, t as assertSandboxServedModel, u as sandboxEventServedBackend } from "./sandbox-events-DGXLxiuX.js";
7
7
  import { n as executableAgentSpecSnapshot, r as projectSandboxOutcome, t as executableAgentProfileSnapshot } from "./executable-spec-CkGvdPds.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 { c as linkAbort, i as resolveAgentEnvironmentProvider, l as runAbortable, n as providerAsExecutor, r as providerAsSandboxClient, s as abortError$1 } from "./environment-provider-DKyMWQJd.js";
9
+ import { c as linkAbort, i as resolveAgentEnvironmentProvider, l as runAbortable, n as providerAsExecutor, r as providerAsSandboxClient, s as abortError$1 } from "./environment-provider-C4elwcpo.js";
10
10
  import { i as notifyRuntimeHookEvent } from "./runtime-hooks-tXpAarhW.js";
11
11
  import { n as assertNoSymlinkDescendant, r as publishExclusiveDurableFile } from "./durable-file-g3YdfEh4.js";
12
12
  import { AGENT_PROFILE_MATERIALIZATION_AXES, AgentEnvironmentCapabilitiesSchema, AgentExactRunControlRefSchema, AgentInteractiveSessionControlClaimAcknowledgementSchema, AgentInteractiveSessionControlClaimSchema, AgentInteractiveSessionPromptAcknowledgementSchema, AgentInteractiveSessionRefSchema, AgentInteractiveSessionStatusSchema, AgentInteractiveSessionStopAcknowledgementSchema, AgentNativeContextContinuationResultSchema, AgentTurnInputSchema, AgentTurnResultSchema, ContextTransferRequestSchema, InteractionAcknowledgementSchema, InteractionResponseCommandSchema, NativeContextBoundaryProofSchema, NativeContextContinuationRequestSchema, REASONING_EFFORTS, RuntimeEventEnvelopeSchema, TerminalReplayWindowSchema, TerminalSessionRefSchema, agentInteractiveSessionControlClaimAcknowledgementMatchesRequest, agentInteractiveSessionControlClaimMatchesRef, agentInteractiveSessionPromptAcknowledgementMatchesCommand, agentInteractiveSessionRefMatchesStart, agentInteractiveSessionRunRef, agentInteractiveSessionStatusMatchesRef, agentInteractiveSessionStopAcknowledgementMatchesCommand, agentNativeContextContinuationResultMatchesRequest, agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, exactAgentInteractiveSessionStart, harnessTypeSchema, nativeContextContinuationTurnDigest, nativeReasoningControl, profileMaterializationAxes, profileMaterializationAxes as profileMaterializationAxes$1, renderInputPartsAsText, sha256DigestSchema } from "@tangle-network/agent-interface";
@@ -1548,7 +1548,13 @@ function processGroupExists(processGroupId) {
1548
1548
  return true;
1549
1549
  }
1550
1550
  }
1551
- /** Parse and validate the one terminal usage event emitted by `codex exec --json`. */
1551
+ /**
1552
+ * Parse and validate the one terminal usage event emitted by `codex exec --json`.
1553
+ *
1554
+ * The JSONL framing is this surface's own; the usage RECORD is read by `parseCodexUsageRecord`,
1555
+ * the one codex usage reader the sandbox decoder also calls, so both surfaces hold the same field
1556
+ * policy and the same two cross-field invariants.
1557
+ */
1552
1558
  function parseCodexTokenUsage(stdout) {
1553
1559
  const completed = [];
1554
1560
  for (const [index, line] of stdout.split(/\r?\n/).entries()) {
@@ -1557,34 +1563,25 @@ function parseCodexTokenUsage(stdout) {
1557
1563
  try {
1558
1564
  event = JSON.parse(line);
1559
1565
  } catch {
1560
- throw new Error(`runLocalHarness: Codex JSONL line ${index + 1} is not valid JSON`);
1566
+ throw new ValidationError(`runLocalHarness: Codex JSONL line ${index + 1} is not valid JSON`);
1561
1567
  }
1562
1568
  if (isRecord(event) && event.type === "turn.completed") completed.push(event);
1563
1569
  }
1564
- if (completed.length !== 1) throw new Error(`runLocalHarness: expected exactly one Codex turn.completed usage event, received ${completed.length}`);
1570
+ if (completed.length !== 1) throw new ValidationError(`runLocalHarness: expected exactly one Codex turn.completed usage event, received ${completed.length}`);
1565
1571
  const event = completed[0];
1566
- if (!isRecord(event) || !isRecord(event.usage)) throw new Error("runLocalHarness: Codex turn.completed event is missing usage");
1567
- const usage = event.usage;
1568
- const inputTokens = naturalNumber(usage.input_tokens, "input_tokens");
1569
- const cachedInputTokens = naturalNumber(usage.cached_input_tokens, "cached_input_tokens");
1570
- const outputTokens = naturalNumber(usage.output_tokens, "output_tokens");
1571
- const reasoningOutputTokens = naturalNumber(usage.reasoning_output_tokens, "reasoning_output_tokens");
1572
- if (cachedInputTokens > inputTokens) throw new Error("runLocalHarness: Codex cached_input_tokens exceeds input_tokens");
1573
- if (reasoningOutputTokens > outputTokens) throw new Error("runLocalHarness: Codex reasoning_output_tokens exceeds output_tokens");
1572
+ if (!isRecord(event) || !isRecord(event.usage)) throw new ValidationError("runLocalHarness: Codex turn.completed event is missing usage");
1573
+ const record = parseCodexUsageRecord(event.usage, "runLocalHarness: Codex");
1574
1574
  return {
1575
- inputTokens,
1576
- cachedInputTokens,
1577
- outputTokens,
1578
- reasoningOutputTokens
1575
+ inputTokens: record.inputTokens,
1576
+ cachedInputTokens: record.cachedInputTokens,
1577
+ outputTokens: record.outputTokens,
1578
+ reasoningOutputTokens: record.reasoningOutputTokens,
1579
+ ...record.cacheWriteInputTokens === void 0 ? {} : { cacheWriteInputTokens: record.cacheWriteInputTokens }
1579
1580
  };
1580
1581
  }
1581
1582
  function isRecord(value) {
1582
1583
  return value !== null && typeof value === "object" && !Array.isArray(value);
1583
1584
  }
1584
- function naturalNumber(value, field) {
1585
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new Error(`runLocalHarness: Codex usage.${field} must be a non-negative safe integer`);
1586
- return value;
1587
- }
1588
1585
  //#endregion
1589
1586
  //#region src/mcp/worktree.ts
1590
1587
  /**
@@ -4113,6 +4110,58 @@ function routerBrain(cfg, opts = {}) {
4113
4110
  };
4114
4111
  }
4115
4112
  //#endregion
4113
+ //#region src/runtime/prompt-options.ts
4114
+ /** Keys the kernel owns on every prompt it sends; a caller value never carries them past here. */
4115
+ const kernelOwnedPromptKeys = /* @__PURE__ */ new Set(["sessionId", "signal"]);
4116
+ /**
4117
+ * Validate and normalize a caller's `promptOptions`.
4118
+ *
4119
+ * @param value the raw value from the execution context.
4120
+ * @param where the field path to name in the error, e.g. `'runAgentRounds: ctx.promptOptions'`.
4121
+ * @returns the options minus the kernel-owned keys, or `undefined` when the caller supplied none.
4122
+ * @throws ValidationError when the value is present but is not a plain object.
4123
+ */
4124
+ function readPromptOptions(value, where) {
4125
+ if (value === void 0) return void 0;
4126
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new ValidationError(`${where} must be an object of SDK PromptOptions`);
4127
+ const owned = {};
4128
+ for (const [key, entry] of Object.entries(value)) {
4129
+ if (kernelOwnedPromptKeys.has(key)) continue;
4130
+ owned[key] = entry;
4131
+ }
4132
+ return owned;
4133
+ }
4134
+ const instrumentPromptKeys = ["backend", "model"];
4135
+ /**
4136
+ * Refuse a per-prompt option a boxless `SandboxClient` seam cannot honor.
4137
+ *
4138
+ * These seams present an in-process executor as a box: there is no sandbox to reconfigure, so an
4139
+ * instrument key — `backend` (the harness to run and the credential to run it on) or `model` (the
4140
+ * id to serve the turn) — states an intent the seam can only drop. Dropping it would run the turn
4141
+ * on a different instrument than the caller asked for and report nothing, so it fails here
4142
+ * instead, before the prompt runs.
4143
+ *
4144
+ * Every other key stays accepted and ignored: `timeoutMs` and `context` shape how a box executes
4145
+ * a turn, not which instrument serves it, and an in-process executor answers on its own terms.
4146
+ *
4147
+ * What counts as a valid value is {@link readPromptOptions}, so a boxless seam holds a caller to
4148
+ * the same contract as the kernels: absent is fine, an object is read, anything else throws.
4149
+ *
4150
+ * @param options the per-prompt options the seam received.
4151
+ * @param seam the seam to name in the error, e.g. `'inlineSandboxClient'`.
4152
+ * @param keys the instrument keys this seam cannot honor. A seam that hands its per-prompt
4153
+ * options to a caller-supplied callback passes only the keys the callback cannot act on.
4154
+ * @throws ValidationError when the options are not an object, or carry one of `keys`.
4155
+ */
4156
+ function assertBoxlessPromptOptions(options, seam, keys = instrumentPromptKeys) {
4157
+ const supplied = readPromptOptions(options, `${seam}: promptOptions`);
4158
+ if (supplied === void 0) return;
4159
+ for (const key of keys) {
4160
+ if (supplied[key] === void 0) continue;
4161
+ throw new ValidationError(`${seam}: promptOptions.${key} cannot apply without a box`);
4162
+ }
4163
+ }
4164
+ //#endregion
4116
4165
  //#region src/runtime/sandbox-acquire.ts
4117
4166
  /**
4118
4167
  * HTTP statuses where create should be retried — gateway timeouts
@@ -4417,7 +4466,7 @@ function createSandboxLineage(client, capabilities, options = {}) {
4417
4466
  await assertSessionLive(handle.box, handle.sessionId);
4418
4467
  return promptEvents(streaming, handle.box, prompt, handle.sessionId, signal, promptOptions);
4419
4468
  },
4420
- async fork(parent, prompts, specs, signal) {
4469
+ async fork(parent, prompts, specs, signal, promptOptions) {
4421
4470
  if (prompts.length === 0) throw new ValidationError("SandboxLineage.fork: prompts must be non-empty");
4422
4471
  if (signal.aborted) throwAbort();
4423
4472
  const branched = await branchParent(parent.box, prompts.length, forkConcurrency, signal);
@@ -4438,7 +4487,7 @@ function createSandboxLineage(client, capabilities, options = {}) {
4438
4487
  box,
4439
4488
  sessionId
4440
4489
  },
4441
- events: promptEvents(streaming, box, prompts[i], sessionId, signal)
4490
+ events: promptEvents(streaming, box, prompts[i], sessionId, signal, promptOptions)
4442
4491
  };
4443
4492
  });
4444
4493
  }
@@ -4460,7 +4509,7 @@ function createSandboxLineage(client, capabilities, options = {}) {
4460
4509
  box,
4461
4510
  sessionId
4462
4511
  },
4463
- events: promptEvents(streaming, box, prompt, sessionId, signal)
4512
+ events: promptEvents(streaming, box, prompt, sessionId, signal, promptOptions)
4464
4513
  };
4465
4514
  }
4466
4515
  const box = await acquireFresh(spec, signal);
@@ -4470,7 +4519,7 @@ function createSandboxLineage(client, capabilities, options = {}) {
4470
4519
  box,
4471
4520
  sessionId
4472
4521
  },
4473
- events: promptEvents(streaming, box, prompt, sessionId, signal)
4522
+ events: promptEvents(streaming, box, prompt, sessionId, signal, promptOptions)
4474
4523
  };
4475
4524
  });
4476
4525
  },
@@ -4583,6 +4632,7 @@ async function runAgentRounds(options) {
4583
4632
  if (!Number.isFinite(maxConcurrency) || maxConcurrency <= 0) throw new ValidationError("runAgentRounds: maxConcurrency must be > 0");
4584
4633
  const sandboxStreaming = options.lineage?.streaming ?? "sse";
4585
4634
  if (!options.ctx?.sandboxClient || typeof options.ctx.sandboxClient.create !== "function") throw new ValidationError("runAgentRounds: ctx.sandboxClient.create is required");
4635
+ const promptOptions = readPromptOptions(options.ctx.promptOptions, "runAgentRounds: ctx.promptOptions");
4586
4636
  const now = options.now ?? Date.now;
4587
4637
  const runId = options.runId ?? `loop-${randomSuffix()}`;
4588
4638
  const loopStart = now();
@@ -4598,7 +4648,7 @@ async function runAgentRounds(options) {
4598
4648
  ownedBoxes.push(box);
4599
4649
  options.onWorkerBox?.(box);
4600
4650
  } : void 0;
4601
- const lineageState = await setUpLineage(options, maxConcurrency, recordMount);
4651
+ const lineageState = await setUpLineage(options, maxConcurrency, recordMount, promptOptions);
4602
4652
  emitRunLoopHook(options, {
4603
4653
  target: "agent.run",
4604
4654
  phase: "before",
@@ -4711,7 +4761,8 @@ async function runAgentRounds(options) {
4711
4761
  collectBox,
4712
4762
  lineagePlan,
4713
4763
  lineageState,
4714
- recordMount
4764
+ recordMount,
4765
+ ...promptOptions === void 0 ? {} : { promptOptions }
4715
4766
  });
4716
4767
  if (controller.signal.aborted) throwAbort();
4717
4768
  emitRunLoopHook(options, {
@@ -4760,7 +4811,7 @@ async function runAgentRounds(options) {
4760
4811
  * Rejects the lineage + `onWorkerBox` combination: both claim the same
4761
4812
  * box-ownership channel, and silently honoring one would leak or double-free.
4762
4813
  */
4763
- async function setUpLineage(options, maxConcurrency, recordMount) {
4814
+ async function setUpLineage(options, maxConcurrency, recordMount, promptOptions) {
4764
4815
  const lineageOpts = options.lineage;
4765
4816
  if (!lineageOpts || !lineageOpts.sessionContinuity && !lineageOpts.forkFanout) return void 0;
4766
4817
  if (options.onWorkerBox) throw new ValidationError("runAgentRounds: `lineage` and `onWorkerBox` both own worker boxes — pass only one");
@@ -4772,6 +4823,7 @@ async function setUpLineage(options, maxConcurrency, recordMount) {
4772
4823
  recordMount
4773
4824
  }),
4774
4825
  options: lineageOpts,
4826
+ ...promptOptions === void 0 ? {} : { promptOptions },
4775
4827
  handles: /* @__PURE__ */ new Map(),
4776
4828
  canPrune: typeof options.driver.describePlan !== "function"
4777
4829
  };
@@ -4804,7 +4856,7 @@ function planLineageRound(state, specs, slice, parentIndex, signal) {
4804
4856
  };
4805
4857
  if (slice.length === 1 && parent && state.options.sessionContinuity) return [{ async acquire() {
4806
4858
  return {
4807
- events: await lineage.continue(parent, promptFor(0), signal),
4859
+ events: await lineage.continue(parent, promptFor(0), signal, state.promptOptions),
4808
4860
  handle: parent
4809
4861
  };
4810
4862
  } }];
@@ -4813,7 +4865,7 @@ function planLineageRound(state, specs, slice, parentIndex, signal) {
4813
4865
  const childSpecs = slice.map((_, offset) => specAt(offset));
4814
4866
  let forked;
4815
4867
  const ensureForked = () => {
4816
- forked ??= lineage.fork(parent, prompts, childSpecs, signal);
4868
+ forked ??= lineage.fork(parent, prompts, childSpecs, signal, state.promptOptions);
4817
4869
  return forked;
4818
4870
  };
4819
4871
  return slice.map((_, offset) => ({ async acquire() {
@@ -4823,7 +4875,7 @@ function planLineageRound(state, specs, slice, parentIndex, signal) {
4823
4875
  } }));
4824
4876
  }
4825
4877
  return slice.map((_, offset) => ({ async acquire() {
4826
- return lineage.start(specAt(offset), promptFor(offset), signal);
4878
+ return lineage.start(specAt(offset), promptFor(offset), signal, state.promptOptions);
4827
4879
  } }));
4828
4880
  }
4829
4881
  /**
@@ -4905,6 +4957,25 @@ async function executeIteration(args) {
4905
4957
  });
4906
4958
  let box;
4907
4959
  let lineageOwned = false;
4960
+ let sawLlmCall = false;
4961
+ const usageLedger = createSandboxUsageLedger(spec.profile.harness);
4962
+ const creditLlmCall = (llmCall) => {
4963
+ sawLlmCall = true;
4964
+ slot.costUsd += llmCall.costUsd ?? 0;
4965
+ if (llmCall.usdKnown === false) slot.costUsdKnown = false;
4966
+ if (llmCall.estimatedCostUsd !== void 0) slot.estimatedCostUsd = (slot.estimatedCostUsd ?? 0) + llmCall.estimatedCostUsd;
4967
+ if (llmCall.promptCache) {
4968
+ slot.promptCache ??= {};
4969
+ mergeUsageMetadata(slot.promptCache, llmCall.promptCache);
4970
+ }
4971
+ addTokenUsage(slot.tokenUsage, {
4972
+ input: llmCall.tokensIn,
4973
+ output: llmCall.tokensOut,
4974
+ ...llmCall.tokensKnown === false ? { tokensKnown: false } : {},
4975
+ ...promptCacheTokenClasses(llmCall.tokensIn, llmCall.promptCache)
4976
+ });
4977
+ args.ctx.runHandle?.observe(llmCall);
4978
+ };
4908
4979
  try {
4909
4980
  let stream;
4910
4981
  const source = args.lineagePlan?.[args.item.index - args.baseIndex];
@@ -4917,7 +4988,11 @@ async function executeIteration(args) {
4917
4988
  } else {
4918
4989
  box = await createSandboxForSpec(args.ctx.sandboxClient, spec, args.signal, args.recordMount);
4919
4990
  const prompt = spec.taskToPrompt(args.item.task);
4920
- stream = args.streaming === "poll" ? promptEvents("poll", box, prompt, `${args.runId}-i${args.item.index}`, args.signal) : box.streamPrompt(prompt, { signal: args.signal });
4991
+ const promptOptions = args.promptOptions;
4992
+ stream = args.streaming === "poll" ? promptEvents("poll", box, prompt, `${args.runId}-i${args.item.index}`, args.signal, promptOptions) : box.streamPrompt(prompt, {
4993
+ ...promptOptions ?? {},
4994
+ signal: args.signal
4995
+ });
4921
4996
  }
4922
4997
  const placement = describeSandboxPlacement(args.ctx.sandboxClient, box);
4923
4998
  await emitTrace(args.ctx.traceEmitter, {
@@ -4942,7 +5017,6 @@ async function executeIteration(args) {
4942
5017
  ...spec.profile.model?.provider !== void 0 ? { provider: spec.profile.model.provider } : {},
4943
5018
  ...requestedModel !== void 0 ? { model: requestedModel } : {}
4944
5019
  };
4945
- let sawLlmCall = false;
4946
5020
  const outcomeTracker = createAgentRunOutcomeTracker();
4947
5021
  for await (const event of stream) {
4948
5022
  events.push(event);
@@ -4951,26 +5025,12 @@ async function executeIteration(args) {
4951
5025
  iterationIndex: args.item.index,
4952
5026
  agentRunName: slot.agentRunName
4953
5027
  });
4954
- const llmCall = extractLlmCallEvent(event, slot.agentRunName);
4955
- if (llmCall) {
4956
- sawLlmCall = true;
4957
- slot.costUsd += llmCall.costUsd ?? 0;
4958
- if (llmCall.usdKnown === false) slot.costUsdKnown = false;
4959
- if (llmCall.estimatedCostUsd !== void 0) slot.estimatedCostUsd = (slot.estimatedCostUsd ?? 0) + llmCall.estimatedCostUsd;
4960
- if (llmCall.promptCache) {
4961
- slot.promptCache ??= {};
4962
- mergeUsageMetadata(slot.promptCache, llmCall.promptCache);
4963
- }
4964
- addTokenUsage(slot.tokenUsage, {
4965
- input: llmCall.tokensIn,
4966
- output: llmCall.tokensOut,
4967
- ...llmCall.tokensKnown === false ? { tokensKnown: false } : {},
4968
- ...promptCacheTokenClasses(llmCall.tokensIn, llmCall.promptCache)
4969
- });
4970
- args.ctx.runHandle?.observe(llmCall);
4971
- }
5028
+ const llmCall = usageLedger.observe(event, slot.agentRunName);
5029
+ if (llmCall) creditLlmCall(llmCall);
4972
5030
  assertSandboxServedModel(event, requested);
4973
5031
  }
5032
+ const harnessCall = usageLedger.settleTurn(slot.agentRunName);
5033
+ if (harnessCall) creditLlmCall(harnessCall);
4974
5034
  const outcome = outcomeTracker.finish();
4975
5035
  slot.sandboxOutcome = outcome;
4976
5036
  if (!sawLlmCall) {
@@ -4989,6 +5049,8 @@ async function executeIteration(args) {
4989
5049
  else if (projection.status !== "completed") slot.verdict = projection.verdict;
4990
5050
  } catch (err) {
4991
5051
  slot.error = err instanceof Error ? err : new Error(String(err));
5052
+ const abortedCall = usageLedger.settleTurn(slot.agentRunName);
5053
+ if (abortedCall) creditLlmCall(abortedCall);
4992
5054
  } finally {
4993
5055
  slot.endedAt = args.now();
4994
5056
  await emitTrace(args.ctx.traceEmitter, {
@@ -6464,7 +6526,7 @@ function createSteerableSandboxSession(args) {
6464
6526
  ...args.traceEnv && Object.keys(args.traceEnv).length > 0 ? { env: args.traceEnv } : {}
6465
6527
  }
6466
6528
  };
6467
- const promptOptions = readPromptOptions(args.loopCtx);
6529
+ const promptOptions = readPromptOptions(args.loopCtx?.promptOptions, "steerable sandbox worker: loopCtx.promptOptions");
6468
6530
  const requestedModel = concreteProfileModel(args.profile);
6469
6531
  const requested = {
6470
6532
  ...args.profile.model?.provider !== void 0 ? { provider: args.profile.model.provider } : {},
@@ -6477,6 +6539,50 @@ function createSteerableSandboxSession(args) {
6477
6539
  let handle;
6478
6540
  state.session = () => handle;
6479
6541
  let nextPrompt = args.taskToPrompt(task);
6542
+ const usageLedger = createSandboxUsageLedger(args.harness);
6543
+ let usageFailure;
6544
+ const readUsage = (read) => {
6545
+ try {
6546
+ return read();
6547
+ } catch (err) {
6548
+ tokensKnown = false;
6549
+ const message = err instanceof Error ? err.message : String(err);
6550
+ usageFailure ??= message;
6551
+ activity.push({
6552
+ at: now(),
6553
+ kind: "note",
6554
+ label: "usage-unreadable",
6555
+ detail: message
6556
+ });
6557
+ return;
6558
+ }
6559
+ };
6560
+ function* creditCall(call) {
6561
+ const callTokensKnown = call.tokensKnown !== false && typeof call.tokensIn === "number" && typeof call.tokensOut === "number";
6562
+ if (!callTokensKnown) tokensKnown = false;
6563
+ const input = call.tokensIn ?? 0;
6564
+ const output = call.tokensOut ?? 0;
6565
+ if (input || output || !callTokensKnown) {
6566
+ const usage = {
6567
+ kind: "tokens",
6568
+ input,
6569
+ output,
6570
+ ...callTokensKnown ? {} : { tokensKnown: false },
6571
+ ...promptCacheTokenClasses(call.tokensIn, call.promptCache)
6572
+ };
6573
+ addTokenUsage(tokens, usage);
6574
+ yield usage;
6575
+ }
6576
+ if (typeof call.costUsd === "number" && call.costUsd > 0) {
6577
+ usd += call.costUsd;
6578
+ yield {
6579
+ kind: "cost",
6580
+ usd: call.costUsd,
6581
+ usdKnown: false,
6582
+ provenance: "uncaptured"
6583
+ };
6584
+ }
6585
+ }
6480
6586
  try {
6481
6587
  for (let turn = 0; maxTurns === 0 || turn < maxTurns; turn += 1) {
6482
6588
  const pending = args.inbox.drain();
@@ -6525,39 +6631,23 @@ function createSteerableSandboxSession(args) {
6525
6631
  kind: "progress",
6526
6632
  progress
6527
6633
  };
6528
- const call = extractLlmCallEvent(event, spec.name ?? String(args.harness));
6634
+ const call = readUsage(() => usageLedger.observe(event, spec.name ?? String(args.harness)));
6529
6635
  if (call) {
6530
6636
  sawLlmCall = true;
6531
- const callTokensKnown = call.tokensKnown !== false && typeof call.tokensIn === "number" && typeof call.tokensOut === "number";
6532
- if (!callTokensKnown) tokensKnown = false;
6533
- const input = call.tokensIn ?? 0;
6534
- const output = call.tokensOut ?? 0;
6535
- if (input || output || !callTokensKnown) {
6536
- const usage = {
6537
- kind: "tokens",
6538
- input,
6539
- output,
6540
- ...callTokensKnown ? {} : { tokensKnown: false },
6541
- ...promptCacheTokenClasses(call.tokensIn, call.promptCache)
6542
- };
6543
- addTokenUsage(tokens, usage);
6544
- yield usage;
6545
- }
6546
- if (typeof call.costUsd === "number" && call.costUsd > 0) {
6547
- usd += call.costUsd;
6548
- yield {
6549
- kind: "cost",
6550
- usd: call.costUsd,
6551
- usdKnown: false,
6552
- provenance: "uncaptured"
6553
- };
6554
- }
6637
+ yield* creditCall(call);
6555
6638
  }
6556
6639
  assertSandboxServedModel(event, requested);
6557
6640
  }
6641
+ const harnessCall = readUsage(() => usageLedger.settleTurn(spec.name ?? String(args.harness)));
6642
+ if (harnessCall) {
6643
+ sawLlmCall = true;
6644
+ yield* creditCall(harnessCall);
6645
+ }
6558
6646
  state.latestOutcome = outcomeTracker.finish();
6559
6647
  } catch (e) {
6560
6648
  cleanup();
6649
+ const abortedCall = readUsage(() => usageLedger.settleTurn(spec.name ?? String(args.harness)));
6650
+ if (abortedCall) yield* creditCall(abortedCall);
6561
6651
  if (isInterruptAbort(e, interruptSig, signal, args.controller.signal)) {
6562
6652
  activity.push({
6563
6653
  at: now(),
@@ -6613,7 +6703,8 @@ function createSteerableSandboxSession(args) {
6613
6703
  ...state.servedBackend === void 0 ? {} : { servedBackend: state.servedBackend },
6614
6704
  turns: state.turns,
6615
6705
  toolCalls: state.toolCalls,
6616
- ...state.latestOutcome ? { outcome: state.latestOutcome } : {}
6706
+ ...state.latestOutcome ? { outcome: state.latestOutcome } : {},
6707
+ ...usageFailure === void 0 ? {} : { tokensUnknownReason: usageFailure }
6617
6708
  };
6618
6709
  const verdict = state.latestOutcome ? projectSandboxOutcome(state.latestOutcome).verdict : void 0;
6619
6710
  state.artifact = {
@@ -6710,13 +6801,6 @@ function readFinalText(event) {
6710
6801
  const alt = data.text;
6711
6802
  return typeof alt === "string" ? alt : void 0;
6712
6803
  }
6713
- /** Prompt options the composed loop context already carries (agent profile / cwd), forwarded so
6714
- * a steerable worker runs with the same box configuration as the single-shot path. */
6715
- function readPromptOptions(loopCtx) {
6716
- const opts = loopCtx?.promptOptions;
6717
- if (!opts || typeof opts !== "object") return void 0;
6718
- return opts;
6719
- }
6720
6804
  //#endregion
6721
6805
  //#region src/runtime/supervise/worker-trace.ts
6722
6806
  /**
@@ -15452,6 +15536,6 @@ function isNonEmptySpend(s) {
15452
15536
  return s.iterations > 0 || s.tokens.input > 0 || s.tokens.output > 0 || s.usd > 0 || s.ms > 0 || s.tokensKnown === false || s.usdKnown === false;
15453
15537
  }
15454
15538
  //#endregion
15455
- export { bridgeModelRouteRefusal as $, buildLoopSpanNodes as $t, readWorkerInteractiveBinding as A, fullProfileMaterialization as An, peerMailVerbNames as At, retainedCreateMaterial as B, validateProfileMaterialization as Bn, createSandboxLineage as Bt, timerAt as C, localHarnessExecutable as Cn, AUTHORITY_MARKERS as Ct, readWorkerInteractiveAdmissions as D, assertProfileMaterialization as Dn, createPeerMailbox as Dt, interactiveAdmissionSeamKey as E, AGENT_PROFILE_MATERIALIZATION_AXES as En, claimsAuthority as Et, startRetainedInteractiveRun as F, promptResourceProfileMaterialization as Fn, TERMINAL_DECISIONS as Ft, rollingDispatch as G, canonicalObservedModel as Gt, effectiveConcurrency as H, acquireSandbox as Ht, reconnectRetainedRun as I, renderProfileMaterializationIssues as In, createSandboxForSpec as It, assertValidBudget as J, mergeTraceEnv as Jt, DEFAULT_SUCCESSFUL_SHUTDOWN_MS as K, observedModelMatchesDeclared as Kt, recoverRetainedRun as L, renderUnsupported as Ln, defaultSelectWinner as Lt, workerInteractiveBindingsDir as M, promptControlProfileMaterialization as Mn, isTerminalNodeStatus as Mt, reconnectRetainedInteractiveRun as N, promptModelProfileMaterialization as Nn, createInPlaceCliExecutor as Nt, workerInteractiveAdmissionFile as O, controlProfileMaterialization as On, isPeerMailEnvelope as Ot, recoverRetainedInteractiveRun as P, promptOnlyProfileMaterialization as Pn, taskToPrompt as Pt, bridgeAdmissionRead as Q, buildLoopOtelSpans as Qt, startRetainedRun as R, sandboxActProfileMaterialization as Rn, isTerminalDecision as Rt, pollFor as S, harnessSupportsReasoningEffort as Sn, createInbox as St, waitUntil as T, CodexExecutionDiagnosticError as Tn, PEER_MAIL_WIRE_KEY as Tt, freeSlots as U, routerBrain as Ut, destroyInteractiveEnvironment as V, worktreeCliProfileMaterialization as Vn, probeSandboxCapabilities as Vt, queueOf as W, runBrainLoop as Wt, spendFromUsageEvents as X, traceContextToEnv as Xt, createBudgetPool as Y, readTraceContextFromEnv as Yt, bindReusableExecutorExecutionId as Z, INTELLIGENCE_WIRE_VERSION as Zt, recordScopeOwnerMaterialization as _, captureWorktreeDiff as _n, decodeToolPart as _t, uncertainSpawnBudgets as a, generateSpanId as an, createExecutor as at, createWaitProbes as b, DEFAULT_LOCAL_HARNESS as bn, createActivityLog as bt, pickBestDelivered as c, padTraceId as cn, createWorktreeCliExecutor as ct, driverChild as d, createRuntimeStreamEventCollector as dn, workerTraceEnv as dt, buildRuntimeEventOtelSpans as en, bridgeRuntimeAttachmentsKey as et, withDriverExecutor as f, sanitizeAgentRuntimeEvent as fn, workerTraceHeaders as ft, meterRuntimeOwnedProviderAttempt as g, runWorktreeHarness as gn, createPushTraceSource as gt, meterRuntimeOwnedAccounting as h, runSettledCommand as hn, createSteerableSandboxSession as ht, sumMeasuredSpendFromEvents as i, flatOtelSpan as in, cliWorktreeExecutor as it, workerInteractiveBindingFile as j, profileMaterializationAxes$1 as jn, isLiveNodeStatus as jt, attachWorker as k, defineProfileMaterializationContract as kn, peerMailTools as kt, runFinalizer as l, toOtelAttributes as ln, WORKER_TRACE_PROPAGATION as lt, deriveNodeExecutionIdentity as m, sanitizeRuntimeStreamEvent as mn, DEFAULT_SANDBOX_STEERING_MAX_TURNS as mt, createSupervisor as n, createOtelExporter as nn, captureReusableExecutorConfig as nt, bestDelivered as o, loopEventToOtelSpan as on, createExecutorRegistry as ot, createScope as p, sanitizeKnowledgeReadinessReport as pn, workerTraceSeamKey as pt, teardownExecutor as q, createPropagatingTraceEmitter as qt, maxSeqOf as r, exportEvalRuns as rn, cliInPlaceExecutor as rt, collectDelivered as s, padSpanId as sn, snapshotExecutorConfig as st, createRootHandle as t, createOpenInferenceFileExporter as tn, bridgeStopSignalKey as tt, runTree as u, createRuntimeEventCollector as un, readWorkerTraceContext as ut, scopeOwnerExecutorNodeContext as v, createWorktree as vn, sandboxSessionTraceSource as vt, validateWaitSpec as w, parseCodexTokenUsage as wn, DEFAULT_PEER_MAIL_LIMITS as wt, isWaitOutcome as x, LOCAL_HARNESSES as xn, readWorkerProgress as xt, settledToIteration as y, removeWorktree as yn, DEFAULT_STALL_AFTER_MS as yt, startRetainedRunInEnvironment as z, unsupportedProfileDimensions as zn, runAgentRounds as zt };
15539
+ export { bridgeModelRouteRefusal as $, INTELLIGENCE_WIRE_VERSION as $t, readWorkerInteractiveBinding as A, controlProfileMaterialization as An, peerMailVerbNames as At, retainedCreateMaterial as B, sandboxActProfileMaterialization as Bn, createSandboxLineage as Bt, timerAt as C, LOCAL_HARNESSES as Cn, AUTHORITY_MARKERS as Ct, readWorkerInteractiveAdmissions as D, CodexExecutionDiagnosticError as Dn, createPeerMailbox as Dt, interactiveAdmissionSeamKey as E, parseCodexTokenUsage as En, claimsAuthority as Et, startRetainedInteractiveRun as F, promptModelProfileMaterialization as Fn, TERMINAL_DECISIONS as Ft, rollingDispatch as G, routerBrain as Gt, effectiveConcurrency as H, validateProfileMaterialization as Hn, acquireSandbox as Ht, reconnectRetainedRun as I, promptOnlyProfileMaterialization as In, createSandboxForSpec as It, assertValidBudget as J, observedModelMatchesDeclared as Jt, DEFAULT_SUCCESSFUL_SHUTDOWN_MS as K, runBrainLoop as Kt, recoverRetainedRun as L, promptResourceProfileMaterialization as Ln, defaultSelectWinner as Lt, workerInteractiveBindingsDir as M, fullProfileMaterialization as Mn, isTerminalNodeStatus as Mt, reconnectRetainedInteractiveRun as N, profileMaterializationAxes$1 as Nn, createInPlaceCliExecutor as Nt, workerInteractiveAdmissionFile as O, AGENT_PROFILE_MATERIALIZATION_AXES as On, isPeerMailEnvelope as Ot, recoverRetainedInteractiveRun as P, promptControlProfileMaterialization as Pn, taskToPrompt as Pt, bridgeAdmissionRead as Q, traceContextToEnv as Qt, startRetainedRun as R, renderProfileMaterializationIssues as Rn, isTerminalDecision as Rt, pollFor as S, DEFAULT_LOCAL_HARNESS as Sn, createInbox as St, waitUntil as T, localHarnessExecutable as Tn, PEER_MAIL_WIRE_KEY as Tt, freeSlots as U, worktreeCliProfileMaterialization as Un, assertBoxlessPromptOptions as Ut, destroyInteractiveEnvironment as V, unsupportedProfileDimensions as Vn, probeSandboxCapabilities as Vt, queueOf as W, readPromptOptions as Wt, spendFromUsageEvents as X, mergeTraceEnv as Xt, createBudgetPool as Y, createPropagatingTraceEmitter as Yt, bindReusableExecutorExecutionId as Z, readTraceContextFromEnv as Zt, recordScopeOwnerMaterialization as _, runSettledCommand as _n, decodeToolPart as _t, uncertainSpawnBudgets as a, exportEvalRuns as an, createExecutor as at, createWaitProbes as b, createWorktree as bn, createActivityLog as bt, pickBestDelivered as c, loopEventToOtelSpan as cn, createWorktreeCliExecutor as ct, driverChild as d, toOtelAttributes as dn, workerTraceEnv as dt, buildLoopOtelSpans as en, bridgeRuntimeAttachmentsKey as et, withDriverExecutor as f, createRuntimeEventCollector as fn, workerTraceHeaders as ft, meterRuntimeOwnedProviderAttempt as g, sanitizeRuntimeStreamEvent as gn, createPushTraceSource as gt, meterRuntimeOwnedAccounting as h, sanitizeKnowledgeReadinessReport as hn, createSteerableSandboxSession as ht, sumMeasuredSpendFromEvents as i, createOtelExporter as in, cliWorktreeExecutor as it, workerInteractiveBindingFile as j, defineProfileMaterializationContract as jn, isLiveNodeStatus as jt, attachWorker as k, assertProfileMaterialization as kn, peerMailTools as kt, runFinalizer as l, padSpanId as ln, WORKER_TRACE_PROPAGATION as lt, deriveNodeExecutionIdentity as m, sanitizeAgentRuntimeEvent as mn, DEFAULT_SANDBOX_STEERING_MAX_TURNS as mt, createSupervisor as n, buildRuntimeEventOtelSpans as nn, captureReusableExecutorConfig as nt, bestDelivered as o, flatOtelSpan as on, createExecutorRegistry as ot, createScope as p, createRuntimeStreamEventCollector as pn, workerTraceSeamKey as pt, teardownExecutor as q, canonicalObservedModel as qt, maxSeqOf as r, createOpenInferenceFileExporter as rn, cliInPlaceExecutor as rt, collectDelivered as s, generateSpanId as sn, snapshotExecutorConfig as st, createRootHandle as t, buildLoopSpanNodes as tn, bridgeStopSignalKey as tt, runTree as u, padTraceId as un, readWorkerTraceContext as ut, scopeOwnerExecutorNodeContext as v, runWorktreeHarness as vn, sandboxSessionTraceSource as vt, validateWaitSpec as w, harnessSupportsReasoningEffort as wn, DEFAULT_PEER_MAIL_LIMITS as wt, isWaitOutcome as x, removeWorktree as xn, readWorkerProgress as xt, settledToIteration as y, captureWorktreeDiff as yn, DEFAULT_STALL_AFTER_MS as yt, startRetainedRunInEnvironment as z, renderUnsupported as zn, runAgentRounds as zt };
15456
15540
 
15457
- //# sourceMappingURL=supervisor-wgifgrsR.js.map
15541
+ //# sourceMappingURL=supervisor-Df9kT_z3.js.map