@tangle-network/agent-runtime 0.195.0 → 0.196.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 (105) hide show
  1. package/dist/{activation-DtIbcFOX.js → activation-BxMZybuo.js} +2 -2
  2. package/dist/{activation-DtIbcFOX.js.map → activation-BxMZybuo.js.map} +1 -1
  3. package/dist/agent.d.ts +2 -2
  4. package/dist/agent.js +3 -3
  5. package/dist/{analyst-loop-CSH7P-Bf.js → analyst-loop-BknOQUW5.js} +3 -3
  6. package/dist/{analyst-loop-CSH7P-Bf.js.map → analyst-loop-BknOQUW5.js.map} +1 -1
  7. package/dist/analyst-loop.d.ts +1 -1
  8. package/dist/analyst-loop.js +1 -1
  9. package/dist/{authored-code-DzYtiflw.js → authored-code-URmkdgjv.js} +2 -2
  10. package/dist/{authored-code-DzYtiflw.js.map → authored-code-URmkdgjv.js.map} +1 -1
  11. package/dist/{conversation-BXPWMOSd.js → conversation-BxJ0SIBM.js} +5 -5
  12. package/dist/{conversation-BXPWMOSd.js.map → conversation-BxJ0SIBM.js.map} +1 -1
  13. package/dist/conversation.d.ts +1 -1
  14. package/dist/conversation.js +1 -1
  15. package/dist/{coordination-driver-iSN-m3VX.js → coordination-driver-zkCrfEbS.js} +6 -6
  16. package/dist/{coordination-driver-iSN-m3VX.js.map → coordination-driver-zkCrfEbS.js.map} +1 -1
  17. package/dist/{delegate-DCC2muUd.js → delegate-D7sonS78.js} +3 -3
  18. package/dist/{delegate-DCC2muUd.js.map → delegate-D7sonS78.js.map} +1 -1
  19. package/dist/{delegation-status-BlsbSeOB.js → delegation-status-CF4D0NZ_.js} +2 -2
  20. package/dist/{delegation-status-BlsbSeOB.js.map → delegation-status-CF4D0NZ_.js.map} +1 -1
  21. package/dist/durable.d.ts +2 -2
  22. package/dist/durable.js +3 -3
  23. package/dist/{environment-provider-Dr-wfnHg.js → environment-provider-1fKZh2zl.js} +111 -13
  24. package/dist/environment-provider-1fKZh2zl.js.map +1 -0
  25. package/dist/{environment-provider-adVa6X7a.d.ts → environment-provider-B-I2jlQy.d.ts} +3 -3
  26. package/dist/environment-provider.d.ts +1 -1
  27. package/dist/environment-provider.js +1 -1
  28. package/dist/{errors-CDZ8XsVj.js → errors-DodWX-cb.js} +9 -1
  29. package/dist/errors-DodWX-cb.js.map +1 -0
  30. package/dist/{graph-DghidDx5.js → graph-BuS-NxXD.js} +30 -19
  31. package/dist/{graph-DghidDx5.js.map → graph-BuS-NxXD.js.map} +1 -1
  32. package/dist/graph.d.ts +3 -3
  33. package/dist/graph.js +6 -6
  34. package/dist/{improve-7VTwse1c.d.ts → improve-DZs0KXhK.d.ts} +3 -3
  35. package/dist/{improvement-cycle-bTBySunH.js → improvement-cycle-Tw5nYT5R.js} +8 -8
  36. package/dist/{improvement-cycle-bTBySunH.js.map → improvement-cycle-Tw5nYT5R.js.map} +1 -1
  37. package/dist/{index-DNx0nWZH.d.ts → index-CYOJsxSg.d.ts} +17 -8
  38. package/dist/{index-DO6DHgRP.d.ts → index-D9mb6fn2.d.ts} +3 -3
  39. package/dist/{index-CVD30soi.d.ts → index-ZnxSe6iK.d.ts} +4 -4
  40. package/dist/index.d.ts +10 -10
  41. package/dist/index.js +10 -10
  42. package/dist/intelligence.d.ts +6 -6
  43. package/dist/intelligence.js +4 -4
  44. package/dist/{jsonl-file-Bh1Q9nt0.js → jsonl-file-BEpaEYjT.js} +3 -3
  45. package/dist/{jsonl-file-Bh1Q9nt0.js.map → jsonl-file-BEpaEYjT.js.map} +1 -1
  46. package/dist/kernel.d.ts +6 -6
  47. package/dist/kernel.js +12 -12
  48. package/dist/{knowledge-U8WJ5xCI.js → knowledge-CPzT_Ve7.js} +4 -4
  49. package/dist/{knowledge-U8WJ5xCI.js.map → knowledge-CPzT_Ve7.js.map} +1 -1
  50. package/dist/knowledge.d.ts +1 -1
  51. package/dist/knowledge.js +1 -1
  52. package/dist/{loop-runner-bin-b4585v9Z.d.ts → loop-runner-bin-DwrSB04m.d.ts} +3 -3
  53. package/dist/{loop-runner-bin-BU2NACsF.js → loop-runner-bin-XKMc3Ld-.js} +5 -5
  54. package/dist/{loop-runner-bin-BU2NACsF.js.map → loop-runner-bin-XKMc3Ld-.js.map} +1 -1
  55. package/dist/loop-runner-bin.d.ts +1 -1
  56. package/dist/loop-runner-bin.js +1 -1
  57. package/dist/{materialization-vZssF9Nx.js → materialization-Cy0oM8tb.js} +2 -2
  58. package/dist/{materialization-vZssF9Nx.js.map → materialization-Cy0oM8tb.js.map} +1 -1
  59. package/dist/mcp/bin.js +4 -4
  60. package/dist/mcp/index.d.ts +6 -6
  61. package/dist/mcp/index.js +11 -11
  62. package/dist/mcp/memory-bin.js +1 -1
  63. package/dist/{memory-server-Crkevawz.js → memory-server-BR310Weg.js} +3 -3
  64. package/dist/{memory-server-Crkevawz.js.map → memory-server-BR310Weg.js.map} +1 -1
  65. package/dist/{model-policy-Wf2MxXJ9.js → model-policy-DKDyr-fc.js} +2 -2
  66. package/dist/{model-policy-Wf2MxXJ9.js.map → model-policy-DKDyr-fc.js.map} +1 -1
  67. package/dist/{openai-tools-BDwAdxk5.d.ts → openai-tools-CRQhVT_V.d.ts} +2 -2
  68. package/dist/{openai-tools-DmvmaG0a.js → openai-tools-DoQ32vpe.js} +2 -2
  69. package/dist/{openai-tools-DmvmaG0a.js.map → openai-tools-DoQ32vpe.js.map} +1 -1
  70. package/dist/primeintellect/index.d.ts +1 -1
  71. package/dist/profiles.d.ts +2 -2
  72. package/dist/profiles.js +2 -2
  73. package/dist/{provision-supervisor-CRPbnJiB.js → provision-supervisor-CpMMShE_.js} +7 -7
  74. package/dist/{provision-supervisor-CRPbnJiB.js.map → provision-supervisor-CpMMShE_.js.map} +1 -1
  75. package/dist/{redact-BOU77QfQ.js → redact-Cbl2O-4N.js} +19 -24
  76. package/dist/redact-Cbl2O-4N.js.map +1 -0
  77. package/dist/{runtime-B8x43nGP.d.ts → runtime-0xNaV6TJ.d.ts} +9 -6
  78. package/dist/{runtime-CuNJ0opC.js → runtime-DqRieJ6e.js} +16 -16
  79. package/dist/{runtime-CuNJ0opC.js.map → runtime-DqRieJ6e.js.map} +1 -1
  80. package/dist/{sandbox-events-DWeQRWxg.js → sandbox-events-DbC2WKKS.js} +19 -16
  81. package/dist/sandbox-events-DbC2WKKS.js.map +1 -0
  82. package/dist/{server-D6XmE1Du.js → server-BjB6ay4N.js} +6 -6
  83. package/dist/{server-D6XmE1Du.js.map → server-BjB6ay4N.js.map} +1 -1
  84. package/dist/{stream-agent-turn-DOtEsvCV.js → stream-agent-turn-Dt5mZpc3.js} +6 -6
  85. package/dist/{stream-agent-turn-DOtEsvCV.js.map → stream-agent-turn-Dt5mZpc3.js.map} +1 -1
  86. package/dist/{stream-agent-turn-B-gtBlOy.d.ts → stream-agent-turn-urHpmO_Z.d.ts} +3 -3
  87. package/dist/{structural-rollout-DxEQ77H7.js → structural-rollout-DPbZWgEm.js} +5 -5
  88. package/dist/{structural-rollout-DxEQ77H7.js.map → structural-rollout-DPbZWgEm.js.map} +1 -1
  89. package/dist/{substrate-qLePHqvH.d.ts → substrate-B4iT90Zv.d.ts} +2 -2
  90. package/dist/{supervise-C0V3pZXK.js → supervise-D9aNi8_f.js} +23 -9
  91. package/dist/supervise-D9aNi8_f.js.map +1 -0
  92. package/dist/testing.d.ts +2 -2
  93. package/dist/testing.js +12 -12
  94. package/dist/{tool-server-DEmLr9YY.js → tool-server-BJbCPhoW.js} +2 -2
  95. package/dist/{tool-server-DEmLr9YY.js.map → tool-server-BJbCPhoW.js.map} +1 -1
  96. package/dist/tui/index.d.ts +1 -1
  97. package/dist/tui/index.js +1 -1
  98. package/dist/{types-B_pNTBjK.d.ts → types-DFLZMaeh.d.ts} +2 -2
  99. package/dist/{types-BdolQ6Zi.d.ts → types-Q0PMagdm.d.ts} +3 -1
  100. package/package.json +1 -1
  101. package/dist/environment-provider-Dr-wfnHg.js.map +0 -1
  102. package/dist/errors-CDZ8XsVj.js.map +0 -1
  103. package/dist/redact-BOU77QfQ.js.map +0 -1
  104. package/dist/sandbox-events-DWeQRWxg.js.map +0 -1
  105. package/dist/supervise-C0V3pZXK.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { m as ValidationError } from "./errors-CDZ8XsVj.js";
1
+ import { m as ValidationError } from "./errors-DodWX-cb.js";
2
2
  import { CanonicalStreamEventSchema, RuntimeEventEnvelopeSchema } from "@tangle-network/agent-interface";
3
3
  //#region src/runtime/harness-usage.ts
4
4
  /**
@@ -438,7 +438,18 @@ function createSandboxUsageLedger(harness) {
438
438
  sawCanonical = true;
439
439
  return call;
440
440
  }
441
- const usage = decodeHarnessUsage(event, harness);
441
+ let usage;
442
+ try {
443
+ usage = decodeHarnessUsage(event, harness);
444
+ } catch (err) {
445
+ return {
446
+ type: "llm_call",
447
+ model: agentRunName,
448
+ tokensKnown: false,
449
+ usdKnown: false,
450
+ tokensUnknownReason: err instanceof Error ? err.message : String(err)
451
+ };
452
+ }
442
453
  if (usage) held.push(usage);
443
454
  },
444
455
  settleTurn(agentRunName) {
@@ -507,8 +518,8 @@ function harnessUsageLlmCall(reports, agentRunName) {
507
518
  * Without this a cell reads `{tokens:0, cost:0}` and the backend-integrity guard correctly aborts the
508
519
  * matrix as a stub. `agentRunName` is the fallback model label for cost-only events (default `'agent'`).
509
520
  *
510
- * Pure by contract, like the extractors it folds: it never throws. A harness receipt it cannot read
511
- * is skipped, the result reports `tokensKnown: false`, and `tokensUnknownReason` carries the decode
521
+ * Pure by contract, like the ledger it folds: it never throws. A harness receipt the ledger cannot
522
+ * read leaves the result at `tokensKnown: false` with `tokensUnknownReason` carrying the decode
512
523
  * message — an unreadable receipt is a different fact from a turn that reported no usage, and a
513
524
  * post-hoc reader that threw would lose the whole failed turn it exists to report.
514
525
  */
@@ -530,25 +541,17 @@ function sumSandboxUsage(events, agentRunName = "agent") {
530
541
  costUsd += call.costUsd ?? 0;
531
542
  if (call.tokensKnown === false) tokensKnown = false;
532
543
  if (call.usdKnown === false) usdKnown = false;
544
+ unreadable ??= call.tokensUnknownReason;
533
545
  if (call.estimatedCostUsd !== void 0) {
534
546
  estimatedCostUsd += call.estimatedCostUsd;
535
547
  sawEstimate = true;
536
548
  }
537
549
  };
538
- const readable = (read) => {
539
- try {
540
- return read();
541
- } catch (err) {
542
- tokensKnown = false;
543
- unreadable ??= err instanceof Error ? err.message : String(err);
544
- return;
545
- }
546
- };
547
550
  for (const ev of events) {
548
- const call = readable(() => ledger.observe(ev, agentRunName));
551
+ const call = ledger.observe(ev, agentRunName);
549
552
  if (call) credit(call);
550
553
  }
551
- const harnessCall = readable(() => ledger.settleTurn(agentRunName));
554
+ const harnessCall = ledger.settleTurn(agentRunName);
552
555
  if (harnessCall) credit(harnessCall);
553
556
  return {
554
557
  input,
@@ -923,4 +926,4 @@ function sandboxProgressEvents(event, state) {
923
926
  //#endregion
924
927
  export { parseCodexUsageRecord as _, extractLlmCallEvent as a, mapSandboxToolEvent as c, sandboxProgressEvents as d, sandboxTerminalUsageField as f, decodeHarnessUsage as g, parseCanonicalTransportEvent as h, createSandboxUsageLedger as i, notifySandboxEventObserver as l, extractTransportEventIdentity as m, canonicalStreamEventFromSandboxEvent as n, isSandboxTerminalEvent as o, sumSandboxUsage as p, createSandboxToolPartState as r, mapSandboxEvent as s, assertSandboxServedModel as t, sandboxEventServedBackend as u };
925
928
 
926
- //# sourceMappingURL=sandbox-events-DWeQRWxg.js.map
929
+ //# sourceMappingURL=sandbox-events-DbC2WKKS.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sandbox-events-DbC2WKKS.js","names":["plainRecord"],"sources":["../src/runtime/harness-usage.ts","../src/runtime/timestamps.ts","../src/runtime/sandbox-transport-events.ts","../src/runtime/sandbox-events.ts"],"sourcesContent":["/**\n * Harness-native token-usage decoders — the ONE registry of per-harness usage wire shapes.\n *\n * A sandbox backend that reports usage under a canonical event (`llm_call`, `cost.usage`,\n * `usage`, or a terminal `usage` / `tokenUsage` record) is read by `extractLlmCallEvent`\n * (`sandbox-events.ts`). A harness that reports usage ONLY inside its own event needs an adapter,\n * and every such adapter lives here — the same rule the tool-part decoders follow\n * (`supervise/trace-source.ts`): one entry per harness family, each owning its real wire shape,\n * while the kernel's accounting stays harness-agnostic.\n *\n * A worker whose usage no reader decodes settles with `tokensKnown: false` and pays nothing into\n * the conserved budget pool, so equal-compute accounting cannot see it. That is why a decode\n * failure here is a typed error rather than a skip: a usage receipt the runtime cannot read must\n * not settle as a turn that spent nothing. The live-stream paths turn the typed error into a\n * settled failure that carries the message; the post-hoc readers degrade to `tokensKnown: false`.\n *\n * This module also owns `parseCodexUsageRecord`, the single reader of codex's `turn.completed`\n * usage record. `runLocalHarness` reads the same record off `codex exec --json` stdout and calls\n * the same function, so both surfaces hold the same field policy and the same two cross-field\n * invariants.\n */\n\nimport type { HarnessType } from '@tangle-network/agent-interface'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport { ValidationError } from '../errors'\n\n/**\n * Codex's `turn.completed` usage record, validated.\n *\n * Four counters are required, which is the set every observed codex build reports.\n * `cacheWriteInputTokens` is optional: the codex CLI reports it and a provider-normalized capture\n * omits it, and an absent counter must stay absent rather than become a zero that claims the\n * provider measured no cache write.\n */\nexport interface CodexUsageRecord {\n /** Total prompt tokens for the turn, the cached ones included. */\n readonly inputTokens: number\n /** The part of `inputTokens` the provider served from its prompt cache. */\n readonly cachedInputTokens: number\n /** Total completion tokens for the turn, the reasoning ones included. */\n readonly outputTokens: number\n /** The part of `outputTokens` the model spent on reasoning. */\n readonly reasoningOutputTokens: number\n /** The part of `inputTokens` the provider wrote into its prompt cache. */\n readonly cacheWriteInputTokens?: number\n}\n\n/**\n * Read and validate one codex `turn.completed` usage record.\n *\n * Every counter must be a non-negative safe integer. Two cross-field invariants hold, and they are\n * what states that the two named counters are SUBSETS of their totals rather than additions to\n * them: `cached_input_tokens <= input_tokens` and `reasoning_output_tokens <= output_tokens`.\n * Measured against the codex CLI: a turn reporting `output_tokens 1523` with\n * `reasoning_output_tokens 1516` answered with about seven tokens of text.\n *\n * `label` names the surface the record came from, so one message serves both readers.\n * Throws `ValidationError` on any violation.\n */\nexport function parseCodexUsageRecord(usage: unknown, label: string): CodexUsageRecord {\n const record = plainRecord(usage)\n if (record === undefined) {\n throw new ValidationError(`${label}: usage must be an object, received ${describe(usage)}`)\n }\n const inputTokens = naturalNumber(record.input_tokens, 'input_tokens', label)\n const cachedInputTokens = naturalNumber(record.cached_input_tokens, 'cached_input_tokens', label)\n const outputTokens = naturalNumber(record.output_tokens, 'output_tokens', label)\n const reasoningOutputTokens = naturalNumber(\n record.reasoning_output_tokens,\n 'reasoning_output_tokens',\n label,\n )\n const cacheWriteInputTokens =\n record.cache_write_input_tokens === undefined\n ? undefined\n : naturalNumber(record.cache_write_input_tokens, 'cache_write_input_tokens', label)\n if (cachedInputTokens > inputTokens) {\n throw new ValidationError(`${label}: cached_input_tokens exceeds input_tokens`)\n }\n if (reasoningOutputTokens > outputTokens) {\n throw new ValidationError(`${label}: reasoning_output_tokens exceeds output_tokens`)\n }\n return {\n inputTokens,\n cachedInputTokens,\n outputTokens,\n reasoningOutputTokens,\n ...(cacheWriteInputTokens === undefined ? {} : { cacheWriteInputTokens }),\n }\n}\n\n/**\n * One harness's own token-usage report for one turn, in the runtime's field names.\n *\n * `input` is the provider's TOTAL prompt count and `output` is its TOTAL completion count.\n * The other three counters CLASSIFY a part of one of those totals; none of them adds to it.\n * `cachedInput` and `cacheWriteInput` classify `input`, which is the convention\n * `promptCacheTokenClasses` (`util.ts`) folds: `freshInput = input - cacheRead - cacheWrite`.\n * `reasoningOutput` classifies `output`.\n *\n * A counter the harness does not report stays absent, because a zero would claim the harness\n * measured none.\n */\nexport interface HarnessUsage {\n /** The harness family whose adapter produced this report. */\n readonly harness: HarnessType\n /** Total prompt tokens the provider charged for the turn, the cached ones included. */\n readonly input: number\n /** Total completion tokens the provider charged for the turn, the reasoning ones included. */\n readonly output: number\n /** The part of `input` the provider served from its prompt cache. */\n readonly cachedInput?: number\n /** The part of `input` the provider wrote into its prompt cache. */\n readonly cacheWriteInput?: number\n /** The part of `output` the model spent on reasoning. Never added to `output`. */\n readonly reasoningOutput?: number\n}\n\n/**\n * Decode one harness's own usage report off a sandbox event, or `undefined` when the event carries\n * no usage for that harness. ONE adapter per harness family — each owns its real wire shape. Add a\n * harness by adding a decoder and registering it; no other code changes.\n *\n * A decoder throws `ValidationError` when the event IS the harness's usage carrier and its\n * numbers cannot be read.\n */\nexport type HarnessUsageDecoder = (event: SandboxEvent) => HarnessUsage | undefined\n\n/** Names the wire record every codex decode error is reported against. */\nconst codexUsageContext = 'codex turn.completed'\n\n/**\n * codex reports the tokens of a turn inside its own `turn.completed` event, which rides the\n * transport as `{ type: 'raw', data: { type: 'turn.completed', usage: { … } } }`. It emits no\n * canonical usage event, so this adapter is a codex worker's only usage source.\n *\n * The record is read by `parseCodexUsageRecord`, the same reader `runLocalHarness` uses on the\n * codex CLI's own stdout, so both surfaces hold one field policy and both cross-field invariants.\n *\n * A `turn.completed` that carries a `usage` member the reader cannot read is a `ValidationError`\n * naming the field. A `turn.completed` with no `usage` member reports no usage at all, which\n * leaves the turn's tokens unknown rather than zero.\n */\nconst decodeCodexTurnUsage: HarnessUsageDecoder = (event) => {\n if (String(event.type ?? '') !== 'raw') return undefined\n const data = plainRecord(event.data)\n if (data === undefined || data.type !== 'turn.completed' || data.usage === undefined) {\n return undefined\n }\n const record = parseCodexUsageRecord(data.usage, codexUsageContext)\n return {\n harness: 'codex',\n input: record.inputTokens,\n output: record.outputTokens,\n cachedInput: record.cachedInputTokens,\n reasoningOutput: record.reasoningOutputTokens,\n ...(record.cacheWriteInputTokens === undefined\n ? {}\n : { cacheWriteInput: record.cacheWriteInputTokens }),\n }\n}\n\n/**\n * The harness → usage-decoder registry. Add a harness by adding one entry.\n *\n * Keyed by `HarnessType`, the vocabulary the `harness` argument is drawn from, so a key no caller\n * can produce does not compile. A harness absent from this registry reports usage through the\n * canonical events or not at all.\n */\nconst harnessUsageDecoders: Partial<Record<HarnessType, HarnessUsageDecoder>> = {\n codex: decodeCodexTurnUsage,\n}\n\n/**\n * Decode a sandbox event with one harness's adapter, or `undefined` when the event carries no\n * harness-native usage.\n *\n * A NAMED harness reads with that harness's adapter only, and a named harness with no adapter\n * reports nothing. It never falls through to another harness's adapter: a different harness's\n * `turn.completed` decoded as codex would either drop the counters codex does not name or fail on\n * a field codex requires, and both answers would be about the wrong harness. The composite over\n * every registered adapter runs only when the caller cannot name the harness.\n *\n * Throws `ValidationError` when an adapter recognizes the event as its harness's usage carrier and\n * cannot read the numbers.\n */\nexport function decodeHarnessUsage(\n event: SandboxEvent,\n harness?: HarnessType,\n): HarnessUsage | undefined {\n if (!event || typeof event !== 'object') return undefined\n if (harness !== undefined) return harnessUsageDecoders[harness]?.(event)\n for (const decode of new Set(Object.values(harnessUsageDecoders))) {\n const usage = decode(event)\n if (usage !== undefined) return usage\n }\n return undefined\n}\n\nfunction plainRecord(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n}\n\nfunction naturalNumber(value: unknown, field: string, label: string): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n throw new ValidationError(\n `${label}: usage.${field} must be a non-negative safe integer, received ${describe(value)}`,\n )\n }\n return value\n}\n\nfunction describe(value: unknown): string {\n if (value === null) return 'null'\n if (typeof value === 'number' || typeof value === 'boolean') return String(value)\n if (typeof value === 'string') return JSON.stringify(value)\n if (Array.isArray(value)) return 'an array'\n return typeof value\n}\n","import { RuntimeEventEnvelopeSchema } from '@tangle-network/agent-interface'\n\nconst validTimestamp = '2026-01-01T00:00:00.000Z'\n\n/** Validate a timestamp with the public runtime envelope contract. */\nexport function assertRuntimeTimestamp(value: unknown, label: string): asserts value is string {\n try {\n RuntimeEventEnvelopeSchema.parse({\n runId: 'runtime',\n eventId: 'event',\n sequence: 0,\n occurredAt: value,\n receivedAt: validTimestamp,\n event: { type: 'status', status: 'processing' },\n })\n } catch (error) {\n throw new Error(`${label} must be a valid ISO timestamp`, { cause: error })\n }\n}\n\n/** Return whether a value satisfies the public runtime timestamp contract. */\nexport function isRuntimeTimestamp(value: unknown): value is string {\n try {\n assertRuntimeTimestamp(value, 'occurredAt')\n return true\n } catch {\n return false\n }\n}\n","import { CanonicalStreamEventSchema, type StreamEvent } from '@tangle-network/agent-interface'\nimport { assertRuntimeTimestamp } from './timestamps'\n\n/**\n * Transport type whose payload is the harness's OWN event, passed through verbatim.\n *\n * A `raw` payload names a harness-native type from a vocabulary the canonical schema does not\n * define (codex emits `thread.started` / `turn.started` / `turn.completed`). The transport type is\n * therefore the only canonical statement such an event makes, and its payload must never be read\n * as a canonical type: the mismatch guard below exists to catch a producer that MISLABELS a\n * canonical event, which a harness-native payload cannot do. A payload that does satisfy the\n * canonical `raw` shape (`backend` + `event`) still parses; anything else is not a canonical\n * event, and the caller reads it off the transport event instead.\n */\nconst harnessNativePayloadType = 'raw'\n\n/** Parse canonical payload fields without treating transport identity as event data. */\nexport function parseCanonicalTransportEvent(\n type: unknown,\n data: Record<string, unknown>,\n normalized: unknown,\n source: string,\n): StreamEvent | undefined {\n if (!isRecord(data)) {\n throw new Error(`${source} emitted a canonical event without an object payload`)\n }\n const outerType = String(type ?? '')\n const harnessNative = outerType === harnessNativePayloadType\n if (normalized !== undefined) {\n if (\n !harnessNative &&\n typeof normalized === 'object' &&\n normalized !== null &&\n 'type' in normalized &&\n typeof normalized.type === 'string' &&\n normalized.type !== outerType\n ) {\n throw new Error(\n `${source} canonical event type \"${normalized.type}\" does not match transport type \"${outerType}\"`,\n )\n }\n const candidate = CanonicalStreamEventSchema.safeParse(normalized)\n if (!candidate.success) {\n if (harnessNative) return undefined\n throw new Error(`${source} emitted an invalid normalized canonical event`, {\n cause: candidate.error,\n })\n }\n return candidate.data\n }\n const {\n type: embeddedType,\n eventId: _eventId,\n cursor: _cursor,\n sequence: _sequence,\n occurredAt: _occurredAt,\n normalized: _normalized,\n ...payload\n } = data\n if (!harnessNative && embeddedType !== undefined && embeddedType !== outerType) {\n throw new Error(\n `${source} canonical event type \"${String(embeddedType)}\" does not match transport type \"${outerType}\"`,\n )\n }\n const candidate = CanonicalStreamEventSchema.safeParse({ ...payload, type: outerType })\n return candidate.success ? candidate.data : undefined\n}\n\n/** Identity fields carried by either the transport envelope or its data payload. */\nexport interface TransportEventIdentity {\n readonly eventId?: string\n readonly cursor?: string\n readonly sequence?: number\n readonly occurredAt?: string\n}\n\n/** Extract shared event identity without privileging one provider wire shape. */\nexport function extractTransportEventIdentity(event: unknown): TransportEventIdentity {\n const record = isRecord(event) ? event : {}\n const data = isRecord(record.data) ? record.data : {}\n const providerEvent = isRecord(record.providerEvent) ? record.providerEvent : {}\n const providerData = isRecord(providerEvent.data) ? providerEvent.data : {}\n const eventId = canonicalEventId(record, data, providerEvent, providerData)\n const cursor = stableString(\n record.cursor ?? data.cursor ?? providerEvent.cursor ?? providerData.cursor,\n )\n const sequence = optionalSequence(\n record.sequence ?? data.sequence ?? providerEvent.sequence ?? providerData.sequence,\n )\n const occurredAt = optionalTimestamp(\n record.occurredAt ?? data.occurredAt ?? providerEvent.occurredAt ?? providerData.occurredAt,\n )\n return {\n ...(eventId === undefined ? {} : { eventId }),\n ...(cursor === undefined ? {} : { cursor }),\n ...(sequence === undefined ? {} : { sequence }),\n ...(occurredAt === undefined ? {} : { occurredAt }),\n }\n}\n\nfunction canonicalEventId(\n record: Record<string, unknown>,\n data: Record<string, unknown>,\n providerEvent: Record<string, unknown>,\n providerData: Record<string, unknown>,\n): string | undefined {\n const candidates = [\n ['data.eventId', data.eventId],\n ['providerEvent.eventId', providerEvent.eventId],\n ['providerData.eventId', providerData.eventId],\n ['record.eventId', record.eventId],\n ] as const\n const present = candidates.filter(([, value]) => value !== undefined)\n // `record.id` may be the provider's replay cursor, so use it only without a canonical field.\n if (present.length === 0) return stableString(record.id ?? providerEvent.id)\n\n const normalized = present.map(([source, value]) => {\n const eventId = stableString(value)\n if (eventId === undefined) throw new Error(`transport event ${source} must be a stable string`)\n return { source, eventId }\n })\n const first = normalized[0]!\n if (normalized.some((candidate) => candidate.eventId !== first.eventId)) {\n throw new Error('transport event canonical identities disagree')\n }\n return first.eventId\n}\n\nfunction stableString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 && value.trim() === value ? value : undefined\n}\n\nfunction finiteNonNegativeInteger(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n}\n\nfunction optionalSequence(value: unknown): number | undefined {\n if (value === undefined) return undefined\n if (finiteNonNegativeInteger(value) === undefined) {\n throw new Error('transport event sequence must be a non-negative safe integer')\n }\n return value as number\n}\n\nfunction optionalTimestamp(value: unknown): string | undefined {\n if (value === undefined) return undefined\n assertRuntimeTimestamp(value, 'occurredAt')\n return value\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n","/**\n * Sandbox-event → runtime-event mapping.\n *\n * The sandbox SDK emits a polymorphic `SandboxEvent = { type, data, id? }`\n * whose `type` vocabulary is backend-determined (opencode, etc.) rather than\n * enumerated by the SDK. Two consumers project it:\n * - the loop kernel's cost ledger (`extractLlmCallEvent`, and\n * `createSandboxUsageLedger` for a turn's full accounting) — sums usage off\n * every cost-bearing event, regardless of stream shape;\n * - the `AgentRuntime.act` streaming contract (`mapSandboxEvent`) — projects\n * incremental events to the `RuntimeStreamEvent` chat-UX vocabulary.\n *\n * Both live here so the empirically-observed `type` vocabulary has one home.\n * A harness that reports usage only inside its OWN event is decoded by the\n * per-harness registry in `harness-usage.ts`; this module holds the canonical\n * fold and the once-per-turn precedence rule between the two sources.\n */\n\nimport type { HarnessType, StreamEvent } from '@tangle-network/agent-interface'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport type { RuntimeStreamEvent } from '../types'\nimport { decodeHarnessUsage, type HarnessUsage } from './harness-usage'\nimport { parseCanonicalTransportEvent } from './sandbox-transport-events'\nimport type { ExecutorProgressEvent } from './supervise/types'\n\n/** The canonical usage receipt every accounting path in the kernel reads. */\ntype LlmCallEvent = RuntimeStreamEvent & { type: 'llm_call' }\n\nconst CANONICAL_STREAM_EVENT_TYPES: ReadonlySet<string> = new Set([\n 'child-task',\n 'message.part.updated',\n 'tool-heartbeat',\n 'tool-slow',\n 'model-processing',\n 'status',\n 'warning',\n 'raw',\n 'session.updated',\n 'interaction',\n 'interaction.cancel',\n 'plan.submitted',\n])\n\n/** Decode one known Agent Interface event from a Sandbox event. */\nexport function canonicalStreamEventFromSandboxEvent(event: SandboxEvent): StreamEvent | undefined {\n if (!event || typeof event !== 'object') return undefined\n const type = String(event.type ?? '')\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n const normalized = data.normalized\n if (normalized === undefined && !CANONICAL_STREAM_EVENT_TYPES.has(type)) return undefined\n return parseCanonicalTransportEvent(type, data, normalized, 'sandbox')\n}\n\n/**\n * Forward a sandbox event to an optional observer without letting observer\n * behavior affect the run. The observer receives a defensive copy, synchronous\n * throws are swallowed, and returned promises are deliberately not awaited.\n */\nexport function notifySandboxEventObserver<Meta>(\n event: SandboxEvent,\n observer: ((event: SandboxEvent, meta: Meta) => void | PromiseLike<void>) | undefined,\n meta: Meta,\n): void {\n if (!observer) return\n try {\n const result = observer(cloneEventForObserver(event), meta)\n if (result && typeof result.then === 'function') {\n void result.then(undefined, () => {})\n }\n } catch {\n // Live observation is optional and must never interrupt the event stream.\n }\n}\n\nfunction cloneEventForObserver(event: SandboxEvent): SandboxEvent {\n try {\n return structuredClone(event)\n } catch {\n return copyPlainSpine(event, new WeakMap()) as SandboxEvent\n }\n}\n\nfunction copyPlainSpine(value: unknown, seen: WeakMap<object, unknown>): unknown {\n if (value === null || typeof value !== 'object') return value\n const existing = seen.get(value)\n if (existing !== undefined) return existing\n if (Array.isArray(value)) {\n const copy: unknown[] = []\n seen.set(value, copy)\n for (const item of value) copy.push(copyPlainSpine(item, seen))\n return copy\n }\n const proto = Object.getPrototypeOf(value)\n if (proto !== Object.prototype && proto !== null) return {}\n const copy: Record<string, unknown> = {}\n seen.set(value, copy)\n for (const [key, child] of Object.entries(value)) {\n copy[key] = copyPlainSpine(child, seen)\n }\n return copy\n}\n\n/** The provider/model the platform reports it actually bound to a turn, when it reports one.\n * `source` is the platform's own account of where that choice came from — `environment` means\n * the platform chose, not the request. */\nexport interface SandboxServedBackend {\n readonly provider?: string\n readonly model?: string\n readonly source?: string\n}\n\n/**\n * Read the served execution identity off one Sandbox event.\n *\n * The platform reports `effectiveBackend` on `execution.started` and again on the terminal\n * event (`@tangle-network/sandbox`, `EffectiveBackend`). Absence returns `undefined`\n * and must stay unknown — a request is not a receipt, so nothing here may be inferred from\n * what was asked for.\n */\nexport function sandboxEventServedBackend(event: SandboxEvent): SandboxServedBackend | undefined {\n if (!event || typeof event !== 'object') return undefined\n const data = plainRecord(event.data)\n const served = plainRecord(data?.effectiveBackend)\n if (!served) return undefined\n const provider = firstString(served.provider)\n const model = firstString(served.model)\n const source = firstString(served.source)\n if (provider === undefined && model === undefined) return undefined\n return {\n ...(provider !== undefined ? { provider } : {}),\n ...(model !== undefined ? { model } : {}),\n ...(source !== undefined ? { source } : {}),\n }\n}\n\n/**\n * Fail the execution when the platform reports serving a model other than the exact one asked for.\n *\n * Measured motive (agent-runtime#892, live infrastructure 2026-08-17): 6 of 6 boxes whose profile\n * declared `zai-coding-plan/glm-5.2` reported\n * `{\"provider\":\"openai-compat\",\"model\":\"deepseek/deepseek-v4-flash\",\"source\":\"environment\"}`,\n * while the materialization receipt recorded the declared model as `status: \"known\"`. Sending\n * `backend.model` makes that substitution unlikely; only reading the report back makes it\n * detectable. A run that cannot say which model produced its evidence must not settle as one\n * that can.\n *\n * Silent when the platform reports no served model: unobserved stays unobserved.\n */\nexport function assertSandboxServedModel(\n event: SandboxEvent,\n expected: { readonly provider?: string; readonly model?: string } | undefined,\n): void {\n const wanted = expected?.model?.trim()\n if (!wanted) return\n const served = sandboxEventServedBackend(event)\n if (served?.model === undefined) return\n if (sameModelId(served.model, wanted, [served.provider, expected?.provider])) return\n const attribution = [\n served.provider !== undefined ? `provider ${JSON.stringify(served.provider)}` : undefined,\n served.source !== undefined ? `source ${JSON.stringify(served.source)}` : undefined,\n ].filter((part): part is string => part !== undefined)\n const detail = attribution.length > 0 ? ` (${attribution.join(', ')})` : ''\n throw new Error(\n `sandbox served model ${JSON.stringify(served.model)}${detail} instead of the exact profile model ${JSON.stringify(wanted)}`,\n )\n}\n\n/**\n * Do two model ids name the same model, allowing for routing prefixes?\n *\n * Either side may spell the model bare (`glm-5.2`), provider-qualified\n * (`zai-coding-plan/glm-5.2`), or route-qualified, and the platform reports the provider in its\n * own field rather than always in the id. So the comparison drops any known provider prefix and\n * then accepts a `/`-boundary suffix match: a longer route to the SAME leaf model is a routing\n * difference, not a substitution.\n *\n * What it deliberately does NOT absorb is a different leaf: `glm-5.2` against `glm-5.3` stays a\n * mismatch, which is the substitution measured directly against the provider API (a request for\n * `glm-5.2` was served `glm-5.3`). A version suffix is the whole difference between two\n * instruments, so nothing here may treat it as noise.\n */\nfunction sameModelId(\n served: string,\n wanted: string,\n providers: readonly (string | undefined)[],\n): boolean {\n const a = stripProviderPrefix(served, providers)\n const b = stripProviderPrefix(wanted, providers)\n return a === b || a.endsWith(`/${b}`) || b.endsWith(`/${a}`)\n}\n\nfunction stripProviderPrefix(id: string, providers: readonly (string | undefined)[]): string {\n let out = id.trim().toLowerCase()\n for (const provider of providers) {\n const prefix = provider?.trim().toLowerCase()\n if (prefix && out.startsWith(`${prefix}/`)) out = out.slice(prefix.length + 1)\n }\n return out\n}\n\nfunction firstString(...values: unknown[]): string | undefined {\n return values.find((value): value is string => typeof value === 'string' && value.length > 0)\n}\n\n/**\n * The sandbox event types that END a turn.\n *\n * One list, because two consumers ask this question about the same wire event and must agree: the\n * usage credit below, and the terminal-text lift in `stream-agent-turn.ts`. Written separately they\n * drifted by exactly one member — `message.completed` credited tokens and dollars while its final\n * text was never lifted, so a backend whose terminal frame carries that type produced a run that\n * was billed and recorded no answer.\n */\nexport const sandboxTerminalEventTypes = ['message.completed', 'result', 'final', 'done'] as const\n\nexport type SandboxTerminalEventType = (typeof sandboxTerminalEventTypes)[number]\n\nconst terminalTypes: ReadonlySet<string> = new Set<string>(sandboxTerminalEventTypes)\n\n/** True for an event type that ends a sandbox turn. */\nexport function isSandboxTerminalEvent(type: string): type is SandboxTerminalEventType {\n return terminalTypes.has(type)\n}\n\n/**\n * Which member of a terminal event's `data` carries its usage receipt.\n *\n * The one place the terminal types legitimately differ, stated rather than implied by two lists:\n * sandbox 0.4.0's `done` reports under `tokenUsage` with the cost at the top level, every other\n * terminal type reports under `usage`.\n */\nexport function sandboxTerminalUsageField(type: SandboxTerminalEventType): 'usage' | 'tokenUsage' {\n return type === 'done' ? 'tokenUsage' : 'usage'\n}\n\n/**\n * Extract a `RuntimeStreamEvent`-shaped `llm_call` from a sandbox event when\n * the event carries usage/cost data. Returns `undefined` for non-cost events\n * so the kernel can iterate the full stream without branching.\n *\n * Pure by contract: it never throws on a failed run. The terminal truth\n * boundary is the public Sandbox outcome tracker, applied after the complete\n * stream. Post-hoc readers — {@link sumSandboxUsage}, the\n * analyst trace store, the chat projection — must stay able to read a failed\n * turn's events, which is when reading them matters most.\n *\n * Canonical cost-carrying types observed in the wild:\n * - `llm_call` — `data: { model, tokensIn, tokensOut, costUsd, ... }`\n * - `message.completed` / `result` — `data: { usage: { inputTokens,\n * outputTokens, totalCostUsd? } }`\n * - `cost.usage` / `usage` — same shape under a dedicated type\n *\n * Numeric coercion is strict: `Number.isFinite` gates every accumulator write\n * so a sentinel `NaN` from a misbehaving backend cannot poison the ledger.\n */\nexport function extractLlmCallEvent(\n event: SandboxEvent,\n agentRunName: string,\n): (RuntimeStreamEvent & { type: 'llm_call' }) | undefined {\n if (!event || typeof event !== 'object') return undefined\n const type = String(event.type ?? '')\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n\n if (type === 'llm_call' || type === 'cost.usage' || type === 'usage') {\n return buildLlmCall(data, agentRunName)\n }\n if (isSandboxTerminalEvent(type) && sandboxTerminalUsageField(type) === 'usage') {\n const usage = data.usage as Record<string, unknown> | undefined\n if (!usage || typeof usage !== 'object') return undefined\n // `PromptResult.costUsd` — the platform's own provider-reported model cost for the prompt —\n // is a SIBLING of `usage` on the terminal event, not a member of it, so reading only `usage`\n // dropped every dollar the SDK reported. The runtime priced nothing here, so this is a\n // receipt: it settles `usdKnown: true`. A terminal event that reports no number leaves the\n // dollar channel unknown, never a measured zero.\n return buildLlmCall(\n {\n ...usage,\n model: data.model ?? usage.model,\n ...(usage.costUsd === undefined && data.costUsd !== undefined\n ? { costUsd: data.costUsd }\n : {}),\n },\n agentRunName,\n )\n }\n // sandbox 0.4.0 terminal event: `data = { tokenUsage: { inputTokens, outputTokens,\n // reasoningTokens, cacheReadInputTokens }, totalCostUsd }`. Usage lives under\n // `tokenUsage` (not `usage`) and the cost is top-level — neither matched the\n // branches above, so an in-process loopDispatch run reported {0,0} and the\n // backend-integrity guard misread a real run as a stub. Reasoning tokens are\n // billed output (reasoning models), so they fold into the output count. The prompt-cache\n // counters are read off the SAME `tokenUsage` record rather than re-derived, because only\n // that record states what the provider billed.\n if (type === 'done') {\n const usage = data.tokenUsage as Record<string, unknown> | undefined\n if (!usage || typeof usage !== 'object') return undefined\n const out = pickFiniteNumber(usage, ['outputTokens', 'completion_tokens', 'tokensOut'])\n const reasoning = pickFiniteNumber(usage, ['reasoningTokens'])\n const mergedOut =\n out !== undefined || reasoning !== undefined ? (out ?? 0) + (reasoning ?? 0) : undefined\n const cache = readPromptCacheUsage(usage)\n return buildLlmCall(\n {\n inputTokens: usage.inputTokens,\n outputTokens: mergedOut,\n totalCostUsd: data.totalCostUsd,\n // The `PromptResult.costUsd` the polled-prompt path forwards onto its synthetic terminal\n // event. `totalCostUsd` is the live SSE spelling of the same fact; a stream carries one or\n // the other, never both.\n ...(data.costUsd === undefined ? {} : { costUsd: data.costUsd }),\n model: data.model ?? usage.model,\n ...(cache !== undefined ? { promptCache: cache } : {}),\n },\n agentRunName,\n )\n }\n return undefined\n}\n\n/**\n * Per-turn usage accounting over BOTH the canonical events and the harness-native ones.\n *\n * Some harnesses report a turn's tokens only inside their own event (`harness-usage.ts`), and a\n * stream may carry that report AND a canonical usage event for the same turn. Crediting both\n * counts one turn twice, so this ledger holds the precedence rule: a canonical usage event WINS,\n * and a harness-native report is credited only for a turn in which no canonical usage arrived.\n *\n * The harness-native report is held until the turn ends, because it can arrive before the\n * canonical answer is known — codex emits `turn.completed` ahead of the terminal transport\n * events. Call {@link SandboxUsageLedger.observe} for every event of a turn, then\n * {@link SandboxUsageLedger.settleTurn} once at the turn boundary; settling also resets the\n * ledger for the next turn, so one ledger serves a whole multi-turn session.\n *\n * The ledger never throws on a receipt it cannot read: `observe` returns a receipt with\n * `tokensKnown: false` and `tokensUnknownReason`, so one policy serves every consumer.\n */\nexport interface SandboxUsageLedger {\n /** Account one event. Returns the canonical usage receipt to credit now, if the event is one. */\n observe(\n event: SandboxEvent,\n agentRunName: string,\n ): (RuntimeStreamEvent & { type: 'llm_call' }) | undefined\n /** End the turn. Returns the held harness-native receipt when no canonical usage arrived. */\n settleTurn(agentRunName: string): (RuntimeStreamEvent & { type: 'llm_call' }) | undefined\n}\n\n/** A {@link SandboxUsageLedger} for one worker. Pass the worker's harness to decode with that\n * harness's adapter; omit it to try every registered adapter. */\nexport function createSandboxUsageLedger(harness?: HarnessType): SandboxUsageLedger {\n let held: HarnessUsage[] = []\n let sawCanonical = false\n return {\n observe(event, agentRunName) {\n const call = extractLlmCallEvent(event, agentRunName)\n if (call) {\n sawCanonical = true\n return call\n }\n let usage: HarnessUsage | undefined\n try {\n usage = decodeHarnessUsage(event, harness)\n } catch (err) {\n // A receipt the ledger cannot read is a measurement fact, not an outcome fact. It is\n // answered like any other receipt, marked unknown with the decode message, so every\n // consumer marks the spend unknown through the fold it already applies and none decides\n // on its own whether an unreadable counter fails the turn. Before the ledger owned this,\n // the leaf kernel failed the iteration and, as a ValidationError, the whole batch.\n return {\n type: 'llm_call',\n model: agentRunName,\n tokensKnown: false,\n usdKnown: false,\n tokensUnknownReason: err instanceof Error ? err.message : String(err),\n }\n }\n // Every report of the turn is kept: a stream carrying more than one is more than one\n // charge, and keeping only the last would drop tokens the provider billed.\n if (usage) held.push(usage)\n return undefined\n },\n settleTurn(agentRunName) {\n const reports = held\n const canonical = sawCanonical\n held = []\n sawCanonical = false\n if (canonical || reports.length === 0) return undefined\n return harnessUsageLlmCall(reports, agentRunName)\n },\n }\n}\n\n/**\n * Fold harness-native usage reports into the canonical `llm_call` the accounting paths read.\n *\n * Every counter a `HarnessUsage` carries beside `input` and `output` CLASSIFIES one of those two\n * totals, so none of them is added to the total it describes:\n *\n * - the prompt-cache counters classify `input` and ride `promptCache`, the convention the\n * terminal `tokenUsage` branch above already follows and `promptCacheTokenClasses` folds,\n * where `freshInput = input - cacheRead - cacheWrite`;\n * - `reasoningOutput` classifies `output`. Codex counts its reasoning tokens INSIDE\n * `output_tokens` — a turn reporting `output_tokens 1523` with `reasoning_output_tokens 1516`\n * answered with about seven tokens of text — and `parseCodexUsageRecord` holds that as an\n * invariant. The canonical `llm_call` carries no reasoning class, so the count is not\n * forwarded to {@link buildLlmCall}, whose `reasoningTokens` input is for the sandbox\n * `tokenUsage` record that reports reasoning BESIDE its output count.\n *\n * A counter no report carried stays absent, because a zero would claim the provider measured none.\n */\nfunction harnessUsageLlmCall(\n reports: readonly HarnessUsage[],\n agentRunName: string,\n): LlmCallEvent | undefined {\n let inputTokens = 0\n let outputTokens = 0\n let readTokens: number | undefined\n let writeTokens: number | undefined\n for (const report of reports) {\n inputTokens += report.input\n outputTokens += report.output\n if (report.cachedInput !== undefined) readTokens = (readTokens ?? 0) + report.cachedInput\n if (report.cacheWriteInput !== undefined)\n writeTokens = (writeTokens ?? 0) + report.cacheWriteInput\n }\n const promptCache: Record<string, number> = {}\n if (readTokens !== undefined) promptCache.readTokens = readTokens\n if (writeTokens !== undefined) promptCache.writeTokens = writeTokens\n return buildLlmCall(\n {\n inputTokens,\n outputTokens,\n ...(Object.keys(promptCache).length > 0 ? { promptCache } : {}),\n },\n agentRunName,\n )\n}\n\n/**\n * Sum the token usage + USD cost of a sandbox turn's events — the one honest way to meter an\n * `openSandboxRun` cell. Folds a {@link SandboxUsageLedger} over the stream, so it reads usage off\n * EVERY backend event shape — the canonical events plus a harness that reports usage only in its\n * own event — and a `runProfileMatrix` dispatch can report it to `ctx.cost`:\n *\n * receipt: (turn) => {\n * const u = sumSandboxUsage(turn.events)\n * return { model, inputTokens: u.input, outputTokens: u.output,\n * ...(u.tokensKnown === false ? { usageUnknown: true } : {}),\n * ...(u.usdKnown !== false && u.costUsd > 0 ? { actualCostUsd: u.costUsd } : {}),\n * ...(u.usdKnown === false ? { costUnknown: true } : {}),\n * ...(u.estimatedCostUsd !== undefined ? { estimatedCostUsd: u.estimatedCostUsd } : {}) }\n * }\n *\n * Without this a cell reads `{tokens:0, cost:0}` and the backend-integrity guard correctly aborts the\n * matrix as a stub. `agentRunName` is the fallback model label for cost-only events (default `'agent'`).\n *\n * Pure by contract, like the ledger it folds: it never throws. A harness receipt the ledger cannot\n * read leaves the result at `tokensKnown: false` with `tokensUnknownReason` carrying the decode\n * message — an unreadable receipt is a different fact from a turn that reported no usage, and a\n * post-hoc reader that threw would lose the whole failed turn it exists to report.\n */\nexport function sumSandboxUsage(\n events: readonly SandboxEvent[],\n agentRunName = 'agent',\n): {\n input: number\n output: number\n costUsd: number\n tokensKnown?: false\n usdKnown?: false\n estimatedCostUsd?: number\n tokensUnknownReason?: string\n} {\n let input = 0\n let output = 0\n let costUsd = 0\n let estimatedCostUsd = 0\n let sawEstimate = false\n let sawCall = false\n let tokensKnown = true\n let usdKnown = true\n let unreadable: string | undefined\n const ledger = createSandboxUsageLedger()\n const credit = (call: LlmCallEvent): void => {\n sawCall = true\n input += call.tokensIn ?? 0\n output += call.tokensOut ?? 0\n costUsd += call.costUsd ?? 0\n if (call.tokensKnown === false) tokensKnown = false\n if (call.usdKnown === false) usdKnown = false\n // The FIRST decode message is kept: it names the receipt the ledger could not read, and a\n // later one from the same turn does not make the answer any more unknown.\n unreadable ??= call.tokensUnknownReason\n if (call.estimatedCostUsd !== undefined) {\n estimatedCostUsd += call.estimatedCostUsd\n sawEstimate = true\n }\n }\n for (const ev of events) {\n const call = ledger.observe(ev, agentRunName)\n if (call) credit(call)\n }\n const harnessCall = ledger.settleTurn(agentRunName)\n if (harnessCall) credit(harnessCall)\n return {\n input,\n output,\n costUsd,\n ...(sawCall && tokensKnown ? {} : { tokensKnown: false as const }),\n ...(sawCall && usdKnown ? {} : { usdKnown: false as const }),\n ...(sawEstimate ? { estimatedCostUsd } : {}),\n ...(unreadable === undefined ? {} : { tokensUnknownReason: unreadable }),\n }\n}\n\nfunction buildLlmCall(\n data: Record<string, unknown>,\n agentRunName: string,\n): (RuntimeStreamEvent & { type: 'llm_call' }) | undefined {\n const tokensIn = pickFiniteNumber(data, ['tokensIn', 'inputTokens', 'prompt_tokens'])\n const outputTokens = pickFiniteNumber(data, ['tokensOut', 'outputTokens', 'completion_tokens'])\n const reasoningTokens = pickFiniteNumber(data, ['reasoningTokens'])\n const tokensOut =\n outputTokens !== undefined || reasoningTokens !== undefined\n ? (outputTokens ?? 0) + (reasoningTokens ?? 0)\n : undefined\n const reportedCostUsd = pickFiniteNumber(data, ['costUsd', 'totalCostUsd', 'cost_usd', 'cost'])\n const explicitTokensKnown = data.tokensKnown ?? data.tokens_known\n const explicitCostKnown = data.costKnown ?? data.cost_known ?? data.usdKnown ?? data.usd_known\n const costProvenance = data.costProvenance ?? data.cost_provenance\n const explicitEstimate = pickFiniteNumber(data, ['estimatedCostUsd', 'estimated_cost_usd'])\n const catalogEstimate =\n costProvenance === 'catalog-estimate' ? (explicitEstimate ?? reportedCostUsd) : explicitEstimate\n const costUsd = costProvenance === 'catalog-estimate' ? undefined : reportedCostUsd\n const promptCache = readPromptCacheUsage(data)\n const tokensKnown =\n explicitTokensKnown !== false && tokensIn !== undefined && tokensOut !== undefined\n // Sandbox's canonical terminal `totalCostUsd` is already the provider-reported receipt. The\n // current SDK carries no provenance tag, so absence means the canonical receipt rather than\n // \"unknown\". Explicit estimates and explicit false-known markers remain unknown.\n const usdKnown =\n explicitCostKnown !== false &&\n costUsd !== undefined &&\n (costProvenance === undefined ||\n costProvenance === 'provider-receipt' ||\n costProvenance === 'billing-receipt')\n if (\n tokensIn === undefined &&\n tokensOut === undefined &&\n costUsd === undefined &&\n catalogEstimate === undefined &&\n promptCache === undefined &&\n explicitTokensKnown !== false &&\n explicitCostKnown !== false\n ) {\n return undefined\n }\n const model = typeof data.model === 'string' && data.model.length > 0 ? data.model : agentRunName\n const event: RuntimeStreamEvent & { type: 'llm_call' } = {\n type: 'llm_call',\n model,\n }\n if (tokensIn !== undefined) event.tokensIn = tokensIn\n if (tokensOut !== undefined) event.tokensOut = tokensOut\n if (!tokensKnown) event.tokensKnown = false\n if (costUsd !== undefined) event.costUsd = costUsd\n if (!usdKnown) event.usdKnown = false\n if (catalogEstimate !== undefined) event.estimatedCostUsd = catalogEstimate\n if (promptCache !== undefined) event.promptCache = promptCache\n return event\n}\n\n/**\n * Every wire spelling of a prompt-cache READ counter, in precedence order: the canonical name\n * first, then the spellings observed on the paths that reach this extractor — the sandbox terminal\n * `tokenUsage` record, the cli-bridge OpenAI-compatible usage object (which normalizes every\n * backend to Anthropic's `cache_read_input_tokens`), Anthropic verbatim, OpenAI's\n * `prompt_tokens_details.cached_tokens`, and DeepSeek's `prompt_cache_hit_tokens`.\n */\nconst PROMPT_CACHE_READ_KEYS = [\n 'readTokens',\n 'read_tokens',\n 'cacheReadInputTokens',\n 'cache_read_input_tokens',\n 'cacheRead',\n 'cache_read',\n 'cachedInputTokens',\n 'cachedTokens',\n 'cached_tokens',\n 'prompt_cache_hit_tokens',\n]\n\n/**\n * Every wire spelling of a prompt-cache WRITE counter. OpenAI reports no write counter at all, so\n * an OpenAI-shaped usage record matches nothing here and the write stays absent — which is the\n * point: absent is not zero.\n */\nconst PROMPT_CACHE_WRITE_KEYS = [\n 'writeTokens',\n 'write_tokens',\n 'cacheWriteInputTokens',\n 'cache_write_input_tokens',\n 'cacheCreationInputTokens',\n 'cache_creation_input_tokens',\n 'cacheWrite',\n 'cache_write',\n]\n\nconst PROMPT_CACHE_MISS_KEYS = ['missTokens', 'miss_tokens', 'prompt_cache_miss_tokens']\n\nconst PROMPT_CACHE_SAVINGS_KEYS = ['readSavingsUsd', 'read_savings_usd']\n\n/**\n * Read the provider's own prompt-cache accounting off one usage-bearing event payload, in the\n * `PromptCacheUsage` vocabulary the router, driver, and chat-client paths already speak.\n *\n * Two sources, one record. A payload that already carries a `promptCache` / `prompt_cache` object\n * is forwarded VERBATIM — those fields are the provider's own report, and an unrecognized one must\n * stay visible rather than be bucketed away. On top of that, flat provider counters are translated\n * to the canonical names, filling only the names the verbatim object did not already define.\n *\n * A counter the payload does not carry is left out. Defaulting it to zero would assert the provider\n * measured no cache, which is a different fact from a provider that reported nothing — and it is\n * the fact the budget reads to decide whether its charge is a measurement or a bound.\n */\nfunction readPromptCacheUsage(\n data: Record<string, unknown>,\n): Record<string, number | string> | undefined {\n const declared = finiteMetadata(data.promptCache ?? data.prompt_cache)\n const nested = plainRecord(data.promptCache) ?? plainRecord(data.prompt_cache)\n const details = plainRecord(data.prompt_tokens_details)\n const sources = [nested, data, details].filter(\n (s): s is Record<string, unknown> => s !== undefined,\n )\n\n const canonical: Record<string, number | string> = {}\n const readTokens = pickTokenCount(sources, PROMPT_CACHE_READ_KEYS)\n const writeTokens = pickTokenCount(sources, PROMPT_CACHE_WRITE_KEYS)\n const missTokens = pickTokenCount(sources, PROMPT_CACHE_MISS_KEYS)\n const readSavingsUsd = pickNonNegativeNumber(sources, PROMPT_CACHE_SAVINGS_KEYS)\n const status =\n nested !== undefined && typeof nested.status === 'string' ? nested.status : undefined\n if (readTokens !== undefined) canonical.readTokens = readTokens\n if (writeTokens !== undefined) canonical.writeTokens = writeTokens\n if (missTokens !== undefined) canonical.missTokens = missTokens\n if (readSavingsUsd !== undefined) canonical.readSavingsUsd = readSavingsUsd\n if (status !== undefined) canonical.status = status\n\n const merged = { ...canonical, ...declared }\n return Object.keys(merged).length > 0 ? merged : undefined\n}\n\nfunction plainRecord(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n}\n\nfunction pickTokenCount(\n sources: readonly Record<string, unknown>[],\n keys: readonly string[],\n): number | undefined {\n for (const key of keys) {\n for (const source of sources) {\n const value = source[key]\n if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0) return value\n }\n }\n return undefined\n}\n\nfunction pickNonNegativeNumber(\n sources: readonly Record<string, unknown>[],\n keys: readonly string[],\n): number | undefined {\n for (const key of keys) {\n for (const source of sources) {\n const value = source[key]\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0) return value\n }\n }\n return undefined\n}\n\nfunction finiteMetadata(value: unknown): Record<string, number | string> | undefined {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined\n const result: Record<string, number | string> = {}\n for (const [key, entry] of Object.entries(value)) {\n if ((typeof entry === 'number' && Number.isFinite(entry)) || typeof entry === 'string') {\n result[key] = entry\n }\n }\n return Object.keys(result).length > 0 ? result : undefined\n}\n\nfunction pickFiniteNumber(data: Record<string, unknown>, keys: string[]): number | undefined {\n for (const key of keys) {\n const value = data[key]\n if (typeof value === 'number' && Number.isFinite(value)) return value\n }\n return undefined\n}\n\n/**\n * Cross-event state for {@link mapSandboxToolEvent}. Sandbox backends emit a\n * tool invocation as MANY `message.part.updated` frames on the same call id\n * (pending → running → completed), so faithful projection needs per-call\n * status memory: one `tool_call` on first sighting, at most one `tool_result`\n * on the terminal transition, nothing on intermediate re-frames. Create one\n * state per turn via {@link createSandboxToolPartState}.\n *\n * @experimental\n */\nexport interface SandboxToolPartState {\n /** Last seen status per tool call id. A terminal status is sticky — later\n * frames on a settled call project to nothing. */\n statusByCall: Map<string, string>\n /** Sequence for synthesized call ids when an event carries none. */\n seq: number\n}\n\n/**\n * Fresh per-turn {@link SandboxToolPartState} for {@link mapSandboxToolEvent} — an\n * empty call-status map so each turn projects tool frames independently.\n *\n * @experimental\n */\nexport function createSandboxToolPartState(): SandboxToolPartState {\n return { statusByCall: new Map(), seq: 0 }\n}\n\n/** Statuses that settle one tool call as a failure. A failed tool call stays a tool result:\n * the run's terminal state comes from the public Sandbox outcome tracker, never from here. */\nconst TERMINAL_FAILURE = /^(error|errored|failed|failure|cancelled|canceled|timeout|timed_out)$/i\n\n/**\n * Project one `SandboxEvent` onto the `tool_call` / `tool_result` variants of\n * `RuntimeStreamEvent` — the tool-part projection `mapSandboxEvent`\n * deliberately does NOT perform. Opt-in and additive: `mapSandboxEvent`'s\n * default vocabulary (text/reasoning deltas + `llm_call`) is unchanged;\n * consumers that need the tool surface (chat UIs rendering tool activity)\n * compose this projector alongside it — `streamAgentTurn` does exactly that\n * under its `preserveToolParts` option.\n *\n * Handled shapes (observed on the opencode / claude-code sandbox backends):\n * - `message.part.updated` with `part.type === 'tool'` — stateful: a\n * `tool_call` on the call id's first frame (args from `state.input` or\n * `state.metadata.input`), a `tool_result` when the status transitions to\n * `completed` (result from `state.output` / `metadata.output`) or to a\n * terminal failure (result is `{ error, status, output? }` — the error\n * surfaced in-band, never dropped).\n * - bare `tool*` event types (`tool.call`, `tool_result`, …) — stateless:\n * `*result*` types project to `tool_result`, the rest to `tool_call`.\n *\n * Returns `[]` for every non-tool event.\n *\n * @experimental\n */\nexport function mapSandboxToolEvent(\n event: SandboxEvent,\n state: SandboxToolPartState,\n): (RuntimeStreamEvent & { type: 'tool_call' | 'tool_result' })[] {\n if (!event || typeof event !== 'object') return []\n const type = String(event.type ?? '')\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n\n if (type === 'message.part.updated') {\n const part =\n data.part && typeof data.part === 'object' ? (data.part as Record<string, unknown>) : {}\n if (String(part.type ?? '') !== 'tool') return []\n return projectToolPart(part, state, typeof event.id === 'string' ? event.id : undefined)\n }\n\n if (type.includes('tool')) {\n const callId =\n pickString(data, ['toolCallId', 'tool_use_id', 'id']) ??\n (typeof event.id === 'string' ? event.id : undefined) ??\n `sandbox-tool-${++state.seq}`\n const toolName = pickString(data, ['name', 'toolName', 'tool']) ?? 'sandbox_tool'\n if (type.includes('result')) {\n return [\n {\n type: 'tool_result',\n toolName,\n toolCallId: callId,\n result: data.output ?? data.result ?? data.content ?? data,\n },\n ]\n }\n return [\n { type: 'tool_call', toolName, toolCallId: callId, args: data.input ?? data.args ?? {} },\n ]\n }\n\n return []\n}\n\nfunction projectToolPart(\n part: Record<string, unknown>,\n state: SandboxToolPartState,\n eventId: string | undefined,\n): (RuntimeStreamEvent & { type: 'tool_call' | 'tool_result' })[] {\n const callId =\n pickString(part, ['callID', 'callId', 'toolCallId', 'id']) ??\n eventId ??\n `sandbox-tool-${++state.seq}`\n const toolName = pickString(part, ['tool', 'toolName', 'name']) ?? 'sandbox_tool'\n const toolState =\n part.state && typeof part.state === 'object' ? (part.state as Record<string, unknown>) : {}\n const metadata =\n toolState.metadata && typeof toolState.metadata === 'object'\n ? (toolState.metadata as Record<string, unknown>)\n : {}\n const status = pickString(toolState, ['status']) ?? 'updated'\n\n const previous = state.statusByCall.get(callId)\n const settled =\n previous === 'completed' || (previous !== undefined && TERMINAL_FAILURE.test(previous))\n if (settled) return []\n\n const out: (RuntimeStreamEvent & { type: 'tool_call' | 'tool_result' })[] = []\n if (previous === undefined) {\n out.push({\n type: 'tool_call',\n toolName,\n toolCallId: callId,\n args: toolState.input ?? metadata.input ?? {},\n })\n }\n state.statusByCall.set(callId, status)\n\n if (status === 'completed') {\n out.push({\n type: 'tool_result',\n toolName,\n toolCallId: callId,\n result: toolState.output ?? metadata.output ?? '',\n })\n } else if (TERMINAL_FAILURE.test(status)) {\n const message =\n pickString(toolState, ['error', 'message']) ??\n pickString(metadata, ['error', 'message']) ??\n `sandbox tool ended with status ${status}`\n const output = toolState.output ?? metadata.output\n out.push({\n type: 'tool_result',\n toolName,\n toolCallId: callId,\n result: { error: message, status, ...(output !== undefined ? { output } : {}) },\n })\n }\n return out\n}\n\nfunction pickString(data: Record<string, unknown>, keys: string[]): string | undefined {\n for (const key of keys) {\n const value = data[key]\n if (typeof value === 'string' && value.length > 0) return value\n }\n return undefined\n}\n\n/**\n * Project one `SandboxEvent` onto the `RuntimeStreamEvent` chat-UX vocabulary,\n * for runtimes that bridge a sandbox `streamPrompt` into the\n * `AgentRuntime.act` streaming contract. Returns `undefined` for events that\n * have no faithful projection — the raw stream is preserved separately for the\n * `OutputAdapter`, so an unmapped event never loses data.\n *\n * Mapped (the task-optional incremental variants — no synthesized task\n * lifecycle, no guessed tool-part shapes):\n * - `message.part.updated` text part → `text_delta`\n * - `message.part.updated` reasoning/thinking part → `reasoning_delta`\n * - cost-bearing events → `llm_call` (shared with the ledger extractor)\n *\n * Tool parts are deliberately NOT mapped here (unchanged default) — compose\n * {@link mapSandboxToolEvent} alongside when a consumer needs them.\n *\n * The opencode backend emits incremental text as\n * `{ type: 'message.part.updated', data: { part: { type, text }, delta } }`;\n * `delta` is the increment, `part.text` the running accumulation.\n */\nexport function mapSandboxEvent(\n event: SandboxEvent,\n opts: { agentRunName?: string } = {},\n): RuntimeStreamEvent | undefined {\n if (!event || typeof event !== 'object') return undefined\n const type = String(event.type ?? '')\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n\n if (type === 'message.part.updated') {\n const part =\n data.part && typeof data.part === 'object' ? (data.part as Record<string, unknown>) : {}\n const partType = String(part.type ?? '')\n const delta = typeof data.delta === 'string' ? data.delta : undefined\n const text = delta ?? (typeof part.text === 'string' ? part.text : undefined)\n if (text === undefined) return undefined\n if (partType === 'text') return { type: 'text_delta', text }\n if (partType === 'reasoning' || partType === 'thinking')\n return { type: 'reasoning_delta', text }\n return undefined\n }\n\n return extractLlmCallEvent(event, opts.agentRunName ?? 'agent')\n}\n\n/**\n * Project one `SandboxEvent` onto Runtime's executor progress vocabulary: incremental text and\n * reasoning, tool calls and results, and an interaction request. It composes the existing\n * projections ({@link mapSandboxEvent}, {@link mapSandboxToolEvent}, and the canonical Agent\n * Interface decode) so every sandbox-shaped executor publishes live output through one reader.\n * Usage-bearing events project to nothing here — accounting stays on the `tokens`/`cost`\n * channels.\n *\n * Pass one {@link SandboxToolPartState} per turn so a multi-frame tool call yields one call and\n * at most one result.\n *\n * @experimental\n */\nexport function sandboxProgressEvents(\n event: SandboxEvent,\n state: SandboxToolPartState,\n): ExecutorProgressEvent[] {\n const canonical = canonicalStreamEventFromSandboxEvent(event)\n if (canonical?.type === 'interaction') {\n return [{ kind: 'interaction', request: canonical.request }]\n }\n if (canonical?.type === 'child-task') {\n return [{ kind: 'child_task', event: canonical }]\n }\n const tools = mapSandboxToolEvent(event, state).map((projected) =>\n projected.type === 'tool_call'\n ? ({\n kind: 'tool_call',\n toolName: projected.toolName,\n ...(projected.toolCallId === undefined ? {} : { toolCallId: projected.toolCallId }),\n ...(projected.args === undefined ? {} : { args: projected.args }),\n } as const)\n : ({\n kind: 'tool_result',\n toolName: projected.toolName,\n ...(projected.toolCallId === undefined ? {} : { toolCallId: projected.toolCallId }),\n ...(projected.result === undefined ? {} : { result: projected.result }),\n } as const),\n )\n if (tools.length > 0) return tools\n const mapped = mapSandboxEvent(event)\n if (mapped?.type === 'text_delta') return [{ kind: 'text_delta', text: mapped.text }]\n if (mapped?.type === 'reasoning_delta') return [{ kind: 'reasoning_delta', text: mapped.text }]\n return []\n}\n\nexport {\n extractTransportEventIdentity,\n parseCanonicalTransportEvent,\n type TransportEventIdentity,\n} from './sandbox-transport-events'\n"],"mappings":";;;;;;;;;;;;;;;A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OAAO;CAAK,CAAC;CACpF,IAAI,QAAQ,SAAS,mBAAmB,OAAO,CAAC;EAAE,MAAM;EAAmB,MAAM,OAAO;CAAK,CAAC;CAC9F,OAAO,CAAC;AACV"}
@@ -1,8 +1,8 @@
1
- import { m as ValidationError, t as AgentEvalError } from "./errors-CDZ8XsVj.js";
2
- import { Tn as buildLoopSpanNodes } from "./redact-BOU77QfQ.js";
3
- import { t as createStdioToolServer } from "./tool-server-DEmLr9YY.js";
4
- import { n as delegate } from "./delegate-DCC2muUd.js";
5
- import { _ as InMemoryFeedbackStore, c as DELEGATION_HISTORY_TOOL_NAME, f as DELEGATE_FEEDBACK_DESCRIPTION, h as createDelegateFeedbackHandler, i as createDelegationStatusHandler, l as createDelegationHistoryHandler, m as DELEGATE_FEEDBACK_TOOL_NAME, n as DELEGATION_STATUS_INPUT_SCHEMA, o as DELEGATION_HISTORY_DESCRIPTION, p as DELEGATE_FEEDBACK_INPUT_SCHEMA, r as DELEGATION_STATUS_TOOL_NAME, s as DELEGATION_HISTORY_INPUT_SCHEMA, t as DELEGATION_STATUS_DESCRIPTION } from "./delegation-status-BlsbSeOB.js";
1
+ import { m as ValidationError, t as AgentEvalError } from "./errors-DodWX-cb.js";
2
+ import { Tn as buildLoopSpanNodes } from "./redact-Cbl2O-4N.js";
3
+ import { t as createStdioToolServer } from "./tool-server-BJbCPhoW.js";
4
+ import { n as delegate } from "./delegate-D7sonS78.js";
5
+ import { _ as InMemoryFeedbackStore, c as DELEGATION_HISTORY_TOOL_NAME, f as DELEGATE_FEEDBACK_DESCRIPTION, h as createDelegateFeedbackHandler, i as createDelegationStatusHandler, l as createDelegationHistoryHandler, m as DELEGATE_FEEDBACK_TOOL_NAME, n as DELEGATION_STATUS_INPUT_SCHEMA, o as DELEGATION_HISTORY_DESCRIPTION, p as DELEGATE_FEEDBACK_INPUT_SCHEMA, r as DELEGATION_STATUS_TOOL_NAME, s as DELEGATION_HISTORY_INPUT_SCHEMA, t as DELEGATION_STATUS_DESCRIPTION } from "./delegation-status-CF4D0NZ_.js";
6
6
  import { n as UI_LENSES } from "./substrate-B0TYNrXn.js";
7
7
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
8
8
  import path, { dirname } from "node:path";
@@ -1308,4 +1308,4 @@ function createInProcessTransport() {
1308
1308
  //#endregion
1309
1309
  export { composeLoopTraceEmitters as C, capDelegationTrace as S, FileDelegationStore as _, DELEGATE_UI_AUDIT_TOOL_NAME as a, DELEGATION_TRACE_MAX_SPANS as b, DELEGATE_DESCRIPTION as c, createDelegateHandler as d, validateDelegateArgs as f, DelegationStateCorruptError as g, DelegationPersistenceError as h, DELEGATE_UI_AUDIT_INPUT_SCHEMA as i, DELEGATE_INPUT_SCHEMA as l, hashIdempotencyInput as m, createMcpServer as n, createDelegateUiAuditHandler as o, DelegationTaskQueue as p, DELEGATE_UI_AUDIT_DESCRIPTION as r, validateDelegateUiAuditArgs as s, createInProcessTransport as t, DELEGATE_TOOL_NAME as u, InMemoryDelegationStore as v, createDelegationTraceCollector as w, buildDelegationTraceSpans as x, DELEGATION_TRACE_MAX_BYTES as y };
1310
1310
 
1311
- //# sourceMappingURL=server-D6XmE1Du.js.map
1311
+ //# sourceMappingURL=server-BjB6ay4N.js.map