@tangle-network/agent-runtime 2.3.4 → 2.3.8

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 (63) hide show
  1. package/dist/{activation-SA2R6STL.js → activation-CDPbi8JA.js} +2 -2
  2. package/dist/{activation-SA2R6STL.js.map → activation-CDPbi8JA.js.map} +1 -1
  3. package/dist/{activation-BAUOO9T-.d.ts → activation-Cks1h3Nw.d.ts} +2 -2
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +3 -3
  6. package/dist/{coordination-manager-BxnEJXsv.js → coordination-manager-DNrb7zMg.js} +4 -4
  7. package/dist/{coordination-manager-BxnEJXsv.js.map → coordination-manager-DNrb7zMg.js.map} +1 -1
  8. package/dist/{delegate-Drwq3e6S.js → delegate-CHdWyLz9.js} +2 -2
  9. package/dist/{delegate-Drwq3e6S.js.map → delegate-CHdWyLz9.js.map} +1 -1
  10. package/dist/durable.d.ts +1 -1
  11. package/dist/durable.js +6 -6
  12. package/dist/{graph-Bio7TWRa.js → graph-oOdDpXFH.js} +6 -6
  13. package/dist/graph-oOdDpXFH.js.map +1 -0
  14. package/dist/{improve-BaVcOScf.js → improve-BCjhWbVk.js} +5 -5
  15. package/dist/{improve-BaVcOScf.js.map → improve-BCjhWbVk.js.map} +1 -1
  16. package/dist/index.d.ts +3 -3
  17. package/dist/index.js +8 -8
  18. package/dist/intelligence.d.ts +2 -2
  19. package/dist/intelligence.js +3 -3
  20. package/dist/kernel.d.ts +1 -1
  21. package/dist/kernel.js +11 -11
  22. package/dist/{loop-runner-t4qfcieO.d.ts → loop-runner-Bkvx4Saw.d.ts} +2 -2
  23. package/dist/{loop-runner-w2R6GUSp.js → loop-runner-Cy1K7f-A.js} +2 -2
  24. package/dist/{loop-runner-w2R6GUSp.js.map → loop-runner-Cy1K7f-A.js.map} +1 -1
  25. package/dist/loop-runner-bin.d.ts +1 -1
  26. package/dist/loop-runner-bin.js +1 -1
  27. package/dist/mcp/bin.js +3 -3
  28. package/dist/mcp/index.d.ts +1 -1
  29. package/dist/mcp/index.js +4 -4
  30. package/dist/profiles.d.ts +1 -1
  31. package/dist/{provision-supervisor-DG4E0Viy.js → provision-supervisor-Pd95wA1X.js} +4 -4
  32. package/dist/{provision-supervisor-DG4E0Viy.js.map → provision-supervisor-Pd95wA1X.js.map} +1 -1
  33. package/dist/{root-stream-To4qAc0e.js → root-stream-Bsh5WFcg.js} +2 -2
  34. package/dist/{root-stream-To4qAc0e.js.map → root-stream-Bsh5WFcg.js.map} +1 -1
  35. package/dist/{run-cancellation-BhP0Nw6G.js → run-cancellation-CzQZUlHr.js} +2 -2
  36. package/dist/{run-cancellation-BhP0Nw6G.js.map → run-cancellation-CzQZUlHr.js.map} +1 -1
  37. package/dist/{runtime-DVwFHx7i.js → runtime-CWZ9q7lU.js} +11 -11
  38. package/dist/{runtime-DVwFHx7i.js.map → runtime-CWZ9q7lU.js.map} +1 -1
  39. package/dist/{search-executor-DRzb2WwZ.js → search-executor-CMPbMvpr.js} +3 -3
  40. package/dist/{search-executor-DRzb2WwZ.js.map → search-executor-CMPbMvpr.js.map} +1 -1
  41. package/dist/{server-BNsxRqPY.js → server-DyTbsg7n.js} +3 -3
  42. package/dist/{server-BNsxRqPY.js.map → server-DyTbsg7n.js.map} +1 -1
  43. package/dist/{structural-rollout-C49iL5Cn.js → structural-rollout-BUqZsIhX.js} +3 -3
  44. package/dist/{structural-rollout-C49iL5Cn.js.map → structural-rollout-BUqZsIhX.js.map} +1 -1
  45. package/dist/{supervise-BwUx_gjv.js → supervise-D1eYde7p.js} +49 -10
  46. package/dist/supervise-D1eYde7p.js.map +1 -0
  47. package/dist/{supervision-discovery-CVpmTroK.js → supervision-discovery-DmDWHwLu.js} +2 -2
  48. package/dist/{supervision-discovery-CVpmTroK.js.map → supervision-discovery-DmDWHwLu.js.map} +1 -1
  49. package/dist/{supervisor-ByarsrwH.js → supervisor-B8beIEqH.js} +23 -37
  50. package/dist/supervisor-B8beIEqH.js.map +1 -0
  51. package/dist/testing.d.ts +1 -1
  52. package/dist/testing.js +11 -11
  53. package/dist/{top-web-Dh1i-KLd.js → top-web-CUDlOKu0.js} +245 -233
  54. package/dist/top-web-CUDlOKu0.js.map +1 -0
  55. package/dist/tui/bin.js +3 -3
  56. package/dist/tui/index.d.ts +12 -9
  57. package/dist/tui/index.js +2 -2
  58. package/dist/{types-BGGZDz0I.d.ts → types-DzS0kBeK.d.ts} +4 -2
  59. package/package.json +1 -1
  60. package/dist/graph-Bio7TWRa.js.map +0 -1
  61. package/dist/supervise-BwUx_gjv.js.map +0 -1
  62. package/dist/supervisor-ByarsrwH.js.map +0 -1
  63. package/dist/top-web-Dh1i-KLd.js.map +0 -1
@@ -1,5 +1,5 @@
1
1
  import { a as cloneSpend, n as addSpend, w as zeroSpend } from "./util-BX20UJ9X.js";
2
- import { E as spawnJournalRecordEvents, I as verifyObserverRecords, N as FileObserverJournal, z as runtimeFailureCauseSchema } from "./root-stream-To4qAc0e.js";
2
+ import { F as verifyObserverRecords, M as FileObserverJournal, R as runtimeFailureCauseSchema, T as spawnJournalRecordEvents } from "./root-stream-Bsh5WFcg.js";
3
3
  import { o as readCommittedJsonLines } from "./jsonl-file-BBP9Dz9w.js";
4
4
  import { isRecord } from "@tangle-network/agent-core";
5
5
  import { resolve } from "node:path";
@@ -616,4 +616,4 @@ function compareText(left, right) {
616
616
  }
617
617
  export { projectPursuit as n, discoverDurableSupervisionRun as t };
618
618
 
619
- //# sourceMappingURL=supervision-discovery-CVpmTroK.js.map
619
+ //# sourceMappingURL=supervision-discovery-DmDWHwLu.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"supervision-discovery-CVpmTroK.js","names":[],"sources":["../src/durable/observer-projection.ts","../src/durable/supervision-discovery.ts"],"sourcesContent":["import { type RuntimeFailureCause, runtimeFailureCauseSchema } from '../runtime/failure-cause'\nimport type { SeatSegment } from '../runtime/supervise/seat-chain'\nimport type {\n BudgetOverspend,\n BudgetViolation,\n ExecutionBindingReceipt,\n ProfileMaterializationReceipt,\n ProviderModelExecutionEvidence,\n RetainedExecutionState,\n RetainedPendingCause,\n Spend,\n SpendChannel,\n SpendGap,\n WorkerTraceEvidence,\n} from '../runtime/supervise/types'\nimport { addSpend, cloneSpend, zeroSpend } from '../runtime/util'\nimport type { RuntimeDecisionKind, RuntimeHookTarget } from '../runtime-hooks'\nimport { type ObserverRecord, verifyObserverRecords } from './observer-journal'\n\n/**\n * One settled projection status, shared by runs and nodes. `down` is the journal's own word for a\n * failure (a settlement is journaled as `kind: 'down'`, cancellation included), so a consumer can\n * join run rows to node rows on `status` and read one failure population instead of two.\n */\nexport type PursuitStatus = 'running' | 'done' | 'down'\n\n/**\n * Where a node's dollar figure came from. `reported` = a provider billed all of it; `estimated` =\n * a model catalog priced all of it; `partial` = a provider billed part and a catalog priced the\n * rest; `unknown` = nothing priced it, so `usd` is a floor and never the cost.\n */\nexport type PursuitCostProvenance = 'reported' | 'estimated' | 'partial' | 'unknown'\n\n/**\n * One node's token usage by class. Cache and reasoning classes are absent when the provider did\n * not report them — absence is not zero. `tokensKnown` is `false` when work happened whose token\n * count no provider reported, which makes `input`/`output` a floor.\n */\nexport interface PursuitNodeUsage {\n readonly input: number\n readonly output: number\n readonly cacheRead?: number\n readonly cacheWrite?: number\n readonly reasoning?: number\n readonly tokensKnown: boolean\n}\n\n/**\n * One node's PLATFORM consumption — box wall time, the resource a subscription seat really pays.\n *\n * Kept apart from `PursuitNodeCost` because the two answer different questions and fail\n * independently: a seat run reports a truthful `$0` and real minutes, a caller-account run\n * reports real dollars and may report no minutes at all. Collapsing them into one \"spend known\"\n * figure hides which one is missing.\n *\n * Absent on a node that ran no box. `boxMinutes` absent WITH the block present says a box ran and\n * nothing measured it — a missing measurement is never a zero.\n */\nexport interface PursuitNodePlatform {\n readonly boxMinutes?: number\n /** `false` when a box ran whose time could not be closed, so `boxMinutes` is a floor. */\n readonly boxMinutesKnown: boolean\n /** `observed` = the platform billed the minutes; `estimated` = Runtime derived them from the box\n * lifetime it watched; `uncaptured` = a box ran and nothing measured it. */\n readonly provenance: 'observed' | 'estimated' | 'uncaptured'\n}\n\n/** One node's dollar cost with the provenance that decides whether it may be compared or summed. */\nexport interface PursuitNodeCost {\n readonly usd: number\n readonly usdKnown: boolean\n /** The part of `usd` a model catalog priced because no provider receipt covered it. */\n readonly usdEstimated?: number\n readonly provenance: PursuitCostProvenance\n}\n\n/**\n * One node's clock. `wallMs` is `settledAt - startedAt` and is deliberately distinct from the\n * executor-reported `spent.ms` sums, which under-report and overlap across parallel children.\n * `firstTokenAt` stays absent unless a provider reports that instant; it is never inferred from\n * `firstOutputAt`, which is when the node first reported usage for a turn.\n */\nexport interface PursuitNodeTiming {\n readonly startedAt: number\n readonly firstOutputAt?: number\n readonly firstTokenAt?: number\n readonly settledAt?: number\n readonly wallMs?: number\n}\n\n/** Where and how a node's execution was placed, read off its execution-binding receipt. */\ntype PursuitNodePlacement = Readonly<Record<string, string | number | boolean | null>>\n\n/**\n * One run's spend counted once, and each node's own share of it. `inclusive` and the entries of\n * `exclusiveByNode` are the two views a client needs to show a tree without double counting.\n */\nexport interface PursuitRunTotals {\n /**\n * The whole run counted once. A node's settled `spent` already contains the child work its own\n * nested tree reported, so summing only the run's top-level nodes plus every node's own\n * inference counts each model call exactly once.\n */\n readonly inclusive: Spend\n /**\n * Each node's own share: its reported spend and own inference minus what its direct children\n * reported. Keyed by node id, plus the run root when the root itself metered inference. The\n * entries sum to `inclusive` by construction.\n */\n readonly exclusiveByNode: Readonly<Record<string, Spend>>\n}\n\n/**\n * One attempt at one concrete Runtime run: the stretch of `agent.run` lifecycle from a `before`\n * to the `after` or `error` that settles it. A run whose first attempt threw and whose corrected\n * attempt settled is two rows, so `error` names only the attempt that failed.\n *\n * A `before` observed while an attempt is still open does not open another: it is a process\n * that resumed the run after the previous process died without a terminal record, and the row\n * counts it in `resumeCount`. The alternative, a row per process start, would leave the killed\n * process's row `running` for the rest of history.\n */\nexport interface PursuitRunProjection {\n readonly runId: string\n /** Zero-based position of this attempt among the run's attempts, in journal order. */\n readonly attemptIndex: number\n /** How many times a process resumed this attempt after a predecessor died mid-run. */\n readonly resumeCount: number\n readonly status: PursuitStatus\n readonly settledAt?: number\n readonly error?: string\n /** Runtime-classified root failure; absent in legacy observer history. */\n readonly failure?: RuntimeFailureCause\n /** Subscription execution of the root manager, ordered across seat changes. */\n readonly segments?: ReadonlyArray<SeatSegment>\n readonly resumeAt?: string\n readonly firstSequence: number\n readonly lastSequence: number\n readonly firstObservedAt: number\n readonly lastObservedAt: number\n readonly eventCount: number\n readonly decisionCount: number\n readonly targets: Readonly<Record<string, number>>\n readonly decisions: Readonly<Record<string, number>>\n readonly totals: PursuitRunTotals\n /** The nodes whose accounting is incomplete. Present exactly when non-empty. */\n readonly spendGaps?: ReadonlyArray<SpendGap>\n}\n\nexport interface PursuitNodeProjection {\n readonly id: string\n readonly parentId?: string\n /** Node ids are scoped to this concrete Runtime tree; `(runId,id)` is identity. */\n readonly runId: string\n readonly label?: string\n /** The runner that executed this node — the executor's own name, not a harness guess. */\n readonly runtime?: string\n readonly depth?: number\n readonly assignmentId?: string\n /** The settled sibling this node replaced, as its manager's spawn named it. Absent on a node\n * that replaced nothing. */\n readonly successorOf?: string\n readonly identity?: unknown\n readonly budget?: unknown\n readonly status: PursuitStatus\n readonly settledAt?: number\n /** The child work this node reported at settlement. Absent until a terminal record lands. */\n readonly spent?: Spend\n /** This node's OWN inference, re-homed from its nested tree. Absent when it drove no turns. */\n readonly ownInference?: Spend\n /** Absent until a spend record lands; the run's `spendGaps` then names the node. */\n readonly usage?: PursuitNodeUsage\n /** Absent until a spend record lands; the run's `spendGaps` then names the node. */\n readonly cost?: PursuitNodeCost\n /** What the node consumed on the PLATFORM. Absent on a node that ran no box. */\n readonly platform?: PursuitNodePlatform\n readonly timing?: PursuitNodeTiming\n /** The kernel-minted attempt this node's execution binding is keyed on. */\n readonly attemptId?: string\n /** The runner-native execution the node bound to: a request, session, run, process, or tree. */\n readonly execution?: { readonly kind: string; readonly id: string }\n /** The model the materialization receipt names, when the runner reported one. */\n readonly model?: string\n /** The concrete backend the profile materialized onto. */\n readonly backend?: string\n readonly placement?: PursuitNodePlacement\n /** Model-call identifiers this node's own turns reported, in order, deduplicated. */\n readonly modelCalls?: ReadonlyArray<string>\n readonly materialization?: ProfileMaterializationReceipt\n readonly executionBindings?: ReadonlyArray<ExecutionBindingReceipt>\n /** What the provider itself reported serving, and why it is unknown when it is. */\n readonly providerModel?: ProviderModelExecutionEvidence\n /** Content-addressed pointer to this node's persisted tool trace, or why there is none. */\n readonly trace?: WorkerTraceEvidence\n readonly outRef?: string\n readonly score?: number\n readonly valid?: boolean\n readonly reason?: string\n readonly failure?: RuntimeFailureCause\n /** Subscription execution of this logical child, ordered across seat changes. */\n readonly segments?: ReadonlyArray<SeatSegment>\n readonly resumeAt?: string\n readonly infra?: boolean\n /** Recorded by Runtime on the `agent.child` payload: `'pending'` at a retained child's\n * settlement, `'released'` when root settlement destroyed its environment without recovery,\n * `'release-unconfirmed'` when a final settlement closed its slot without confirming that.\n * The status stays `down` — the split is a sibling fact, not a fourth status. A second\n * `agent.child` for one node is already how a live-recovered child flips down→done, so the\n * fold overwrites in observed order; that event's `settledAt` is the original settlement, so\n * `settledAt` and `timing` do not move. */\n readonly retainedExecution?: RetainedExecutionState\n /** Why a retained child has no accepted result; see `RetainedPendingCause`. */\n readonly retainedPendingCause?: RetainedPendingCause\n /** When a final settlement closed a retained node's slot; absent while it is `'pending'`. */\n readonly releasedAt?: number\n /** Each channel on which the settled spend exceeded the node's reservation. The status is the\n * node's own outcome: a `done` node that overspent still delivered its output. */\n readonly budgetViolation?: BudgetViolation\n readonly firstSequence: number\n readonly lastSequence: number\n readonly firstObservedAt: number\n readonly lastObservedAt: number\n readonly eventCount: number\n readonly turnCount: number\n}\n\nexport interface PursuitProjection {\n readonly pursuitId: string\n /** Number of records in this concrete execution journal. */\n readonly sequence: number\n /** Digest-chain tip for this concrete execution journal. */\n readonly chainTip: string\n readonly firstObservedAt: number\n readonly lastObservedAt: number\n readonly runs: readonly PursuitRunProjection[]\n readonly nodes: readonly PursuitNodeProjection[]\n readonly eventCount: number\n readonly decisionCount: number\n}\n\ntype MutableRun = {\n -readonly [K in keyof Omit<\n PursuitRunProjection,\n 'totals' | 'spendGaps' | 'segments' | 'targets' | 'decisions'\n >]: PursuitRunProjection[K]\n} & {\n /** Whether this attempt has seen its own `before`; an attempt a journal opens without one\n * treats the first `before` it meets as its start, not as a resume. */\n started: boolean\n segments?: SeatSegment[]\n targets: Record<string, number>\n decisions: Record<string, number>\n /** Inference the run root drove itself, attributable to no spawned node. */\n rootInference?: Spend\n}\n\ntype MutableNode = {\n id: string\n parentId?: string\n runId: string\n /** The attempt whose process spawned this node; totals and gaps are folded per attempt. */\n attemptIndex: number\n label?: string\n runtime?: string\n depth?: number\n assignmentId?: string\n successorOf?: string\n identity?: unknown\n budget?: unknown\n status: PursuitStatus\n startedAt?: number\n settledAt?: number\n spent?: Spend\n ownInference?: Spend\n reasoningTokens?: number\n firstOutputAt?: number\n firstTokenAt?: number\n attemptId?: string\n execution?: { kind: string; id: string }\n model?: string\n backend?: string\n placement?: PursuitNodePlacement\n modelCalls: string[]\n materialization?: ProfileMaterializationReceipt\n executionBindings?: ReadonlyArray<ExecutionBindingReceipt>\n providerModel?: ProviderModelExecutionEvidence\n trace?: WorkerTraceEvidence\n outRef?: string\n score?: number\n valid?: boolean\n reason?: string\n failure?: RuntimeFailureCause\n segments?: SeatSegment[]\n resumeAt?: string\n infra?: boolean\n retainedExecution?: RetainedExecutionState\n retainedPendingCause?: RetainedPendingCause\n releasedAt?: number\n budgetViolation?: BudgetViolation\n firstSequence: number\n lastSequence: number\n firstObservedAt: number\n lastObservedAt: number\n eventCount: number\n turnCount: number\n}\n\n/**\n * Fold one append-only execution journal into a deterministic operator projection.\n *\n * This is intentionally a READ model, not another state machine: it does not own\n * execution, cannot steer agents, and can be rebuilt from the journal at any time.\n * Projection verifies the complete hash chain first, so an operator view can never\n * silently render a mutated or reordered observer history as trustworthy state.\n *\n * Topology comes only from Runtime's canonical `agent.spawn` facts. Terminal node\n * state comes only from `agent.child`; concrete run state comes only from the root\n * `agent.run` lifecycle emitted by `supervisePursuit`, one row per attempt. Node identity is\n * scoped to the concrete Runtime run so independent trees may both contain `root:s0` without\n * aliasing, and a node belongs to the attempt that spawned it.\n *\n * Usage, cost and timing are reported at the class the runtime measured them at. A missing\n * class stays ABSENT and the run names the node in `spendGaps`; nothing here converts an\n * unmeasured channel into a zero, because a fabricated zero is indistinguishable from free work.\n */\nexport function projectPursuit(records: readonly ObserverRecord[]): PursuitProjection {\n if (records.length === 0) {\n throw new TypeError('projectPursuit: at least one observer record is required')\n }\n const pursuitId = records[0]!.pursuitId\n const verified = verifyObserverRecords(records, pursuitId)\n const attempts = new Map<string, MutableRun[]>()\n const nodes = new Map<string, MutableNode>()\n let eventCount = 0\n let decisionCount = 0\n\n for (const record of verified) {\n const observed = record.event ?? record.decision\n if (!observed) throw new Error(`projectPursuit: record ${record.sequence} has no observation`)\n const run = currentAttempt(attempts, observed.runId, record)\n run.lastSequence = record.sequence\n run.lastObservedAt = record.observedAt\n\n if (record.event) {\n eventCount += 1\n run.eventCount += 1\n increment(run.targets, record.event.target)\n projectRunActivity(run, record)\n projectSpawnNode(nodes, record, run.attemptIndex)\n projectNodeActivity(nodes, record)\n projectSeat(run, nodes, record)\n projectTurn(run, nodes, record)\n } else if (record.decision) {\n decisionCount += 1\n run.decisionCount += 1\n increment(run.decisions, record.decision.kind)\n }\n }\n\n const byAttempt = new Map<string, MutableNode[]>()\n for (const node of nodes.values()) {\n const key = attemptKey(node.runId, node.attemptIndex)\n const list = byAttempt.get(key)\n if (list) list.push(node)\n else byAttempt.set(key, [node])\n }\n\n const first = verified[0]!\n const last = verified.at(-1)!\n return Object.freeze({\n pursuitId,\n sequence: last.sequence,\n chainTip: last.digest,\n firstObservedAt: first.observedAt,\n lastObservedAt: last.observedAt,\n runs: Object.freeze(\n [...attempts.values()]\n .flat()\n .sort((a, b) => a.firstSequence - b.firstSequence || a.runId.localeCompare(b.runId))\n .map((run) => freezeRun(run, byAttempt.get(attemptKey(run.runId, run.attemptIndex)) ?? [])),\n ),\n nodes: Object.freeze(\n [...nodes.values()]\n .sort(\n (a, b) =>\n a.firstSequence - b.firstSequence ||\n a.runId.localeCompare(b.runId) ||\n a.id.localeCompare(b.id),\n )\n .map(freezeNode),\n ),\n eventCount,\n decisionCount,\n })\n}\n\nfunction projectSeat(\n run: MutableRun,\n nodes: Map<string, MutableNode>,\n record: ObserverRecord,\n): void {\n const event = record.event\n if (event?.target !== 'agent.seat') return\n const payload = objectRecord(event.payload)\n const phase = stringField(payload, 'phase')\n const node = nodes.get(nodeKey(event.runId, stringField(payload, 'nodeId') ?? ''))\n const owner = node ?? run\n if (phase === 'paused') {\n const resumeAt = stringField(payload, 'resumeAt')\n if (resumeAt) owner.resumeAt = resumeAt\n return\n }\n if (phase === 'resumed') {\n delete owner.resumeAt\n return\n }\n const raw = objectRecord(payload?.segment)\n const seat = stringField(raw, 'seat')\n const harness = stringField(raw, 'harness')\n const provider = stringField(raw, 'provider')\n const model = stringField(raw, 'model')\n const startedAt = stringField(raw, 'startedAt')\n if (!seat || !harness || !provider || !model || !startedAt) return\n if (owner.segments === undefined) owner.segments = []\n const segments = owner.segments\n if (phase === 'started') {\n if (!segments.some((segment) => segment.startedAt === startedAt && segment.seat === seat)) {\n segments.push({ seat, harness, provider, model, startedAt })\n }\n } else if (phase === 'ended') {\n const endedAt = stringField(raw, 'endedAt')\n const reason = stringField(raw, 'reason') as SeatSegment['reason']\n if (!endedAt || !reason) return\n const index = segments.findIndex(\n (segment) => segment.startedAt === startedAt && segment.seat === seat,\n )\n if (index >= 0) segments[index] = { seat, harness, provider, model, startedAt, endedAt, reason }\n }\n}\n\nfunction attemptKey(runId: string, attemptIndex: number): string {\n return `${runId}\\u0000${attemptIndex}`\n}\n\n/**\n * The attempt a record belongs to. An `agent.run` `before` opens a new attempt when the run has\n * none or its latest attempt already settled; on an open attempt it is a resume. Every other\n * record joins the latest attempt, and a journal that never emitted `before` gets attempt 0.\n */\nfunction currentAttempt(\n attempts: Map<string, MutableRun[]>,\n runId: string,\n record: ObserverRecord,\n): MutableRun {\n const list = attempts.get(runId) ?? []\n if (list.length === 0) attempts.set(runId, list)\n const latest = list.at(-1)\n const isStart = record.event?.target === 'agent.run' && record.event.phase === 'before'\n if (latest !== undefined && (!isStart || latest.status === 'running')) {\n if (isStart) {\n if (latest.started) latest.resumeCount += 1\n latest.started = true\n }\n return latest\n }\n const created: MutableRun = {\n runId,\n attemptIndex: list.length,\n resumeCount: 0,\n started: isStart,\n status: 'running',\n firstSequence: record.sequence,\n lastSequence: record.sequence,\n firstObservedAt: record.observedAt,\n lastObservedAt: record.observedAt,\n eventCount: 0,\n decisionCount: 0,\n targets: {},\n decisions: {},\n }\n list.push(created)\n return created\n}\n\nfunction projectRunActivity(run: MutableRun, record: ObserverRecord): void {\n const event = record.event\n if (event?.target !== 'agent.run') return\n const payload = objectRecord(event.payload)\n const status = stringField(payload, 'status')\n const done = event.phase === 'after' || status === 'done'\n if (!done && event.phase !== 'error' && status !== 'failed') return\n // The `agent.run` hook payload spells a failure `failed`; the projection spells every\n // settled failure `down`, the journal's word, so run and node rows join on one vocabulary.\n run.status = done ? 'done' : 'down'\n run.settledAt = record.observedAt\n if (payload && Object.hasOwn(payload, 'failure'))\n run.failure = runtimeFailureCauseSchema.parse(payload.failure)\n const error = stringField(payload, 'error')\n if (error && (!done || run.failure !== undefined)) run.error = error\n}\n\nfunction nodeKey(runId: string, nodeId: string): string {\n return `${runId}\\u0000${nodeId}`\n}\n\nfunction projectSpawnNode(\n nodes: Map<string, MutableNode>,\n record: ObserverRecord,\n attemptIndex: number,\n): void {\n const event = record.event\n if (event?.target !== 'agent.spawn') return\n const payload = objectRecord(event.payload)\n const childId = stringField(payload, 'childId')\n if (!childId) return\n const key = nodeKey(event.runId, childId)\n const existing = nodes.get(key)\n if (existing) {\n existing.lastSequence = record.sequence\n existing.lastObservedAt = record.observedAt\n existing.eventCount += 1\n return\n }\n const label = stringField(payload, 'label')\n const runtime = stringField(payload, 'runtime')\n const depth = numberField(payload, 'depth')\n const assignmentId = stringField(payload, 'assignmentId')\n const successorOf = stringField(payload, 'successorOf')\n const attemptId = stringField(payload, 'attemptId')\n const startedAt = numberField(payload, 'startedAt')\n nodes.set(key, {\n id: childId,\n ...(event.parentId ? { parentId: event.parentId } : {}),\n runId: event.runId,\n attemptIndex,\n ...(label ? { label } : {}),\n ...(runtime ? { runtime } : {}),\n ...(depth !== undefined ? { depth } : {}),\n ...(assignmentId ? { assignmentId } : {}),\n ...(successorOf ? { successorOf } : {}),\n ...(attemptId ? { attemptId } : {}),\n // A spawn that predates the `startedAt` fact falls back to when the record was observed:\n // the spawn event is emitted synchronously with the spawn, so the two agree to the ms.\n startedAt: startedAt ?? record.observedAt,\n ...(payload && Object.hasOwn(payload, 'identity') ? { identity: payload.identity } : {}),\n ...(payload && Object.hasOwn(payload, 'budget') ? { budget: payload.budget } : {}),\n status: 'running',\n modelCalls: [],\n firstSequence: record.sequence,\n lastSequence: record.sequence,\n firstObservedAt: record.observedAt,\n lastObservedAt: record.observedAt,\n eventCount: 1,\n turnCount: 0,\n })\n}\n\nfunction projectNodeActivity(nodes: Map<string, MutableNode>, record: ObserverRecord): void {\n const event = record.event\n if (event === undefined) return\n if (event.target === 'agent.spawn') return\n const payload = objectRecord(event.payload)\n const nodeId =\n stringField(payload, 'childId') ??\n stringField(payload, 'nodeId') ??\n stringField(payload, 'workerId')\n if (!nodeId) return\n const node = nodes.get(nodeKey(event.runId, nodeId))\n if (!node) return\n node.lastSequence = record.sequence\n node.lastObservedAt = record.observedAt\n node.eventCount += 1\n\n if (event.target !== 'agent.child') return\n const status = stringField(payload, 'status')\n if (status !== 'done' && status !== 'down') return\n node.status = status\n node.settledAt = numberField(payload, 'settledAt') ?? record.observedAt\n const startedAt = numberField(payload, 'startedAt')\n if (startedAt !== undefined) node.startedAt = startedAt\n if (payload && Object.hasOwn(payload, 'spent')) node.spent = spendField(payload, 'spent')\n const metered = spendField(payload, 'metered')\n if (metered)\n node.ownInference = node.ownInference ? addSpend(node.ownInference, metered) : metered\n const runtime = stringField(payload, 'runtime')\n if (runtime) node.runtime = runtime\n const outRef = stringField(payload, 'outRef')\n if (outRef) node.outRef = outRef\n const score = numberField(payload, 'score')\n if (score !== undefined) node.score = score\n const valid = booleanField(payload, 'valid')\n if (valid !== undefined) node.valid = valid\n const reason = stringField(payload, 'reason')\n if (reason) node.reason = reason\n if (status === 'done') node.failure = undefined\n else if (payload && Object.hasOwn(payload, 'failure')) {\n node.failure = runtimeFailureCauseSchema.parse(payload.failure)\n }\n const infra = booleanField(payload, 'infra')\n if (infra !== undefined) node.infra = infra\n const retained = stringField(payload, 'retainedExecution')\n if (retained === 'pending' || retained === 'released' || retained === 'release-unconfirmed') {\n node.retainedExecution = retained\n }\n const cause = stringField(payload, 'retainedPendingCause')\n if (\n cause === 'unobservable' ||\n cause === 'provider-contract' ||\n cause === 'request-rejected' ||\n cause === 'transport' ||\n cause === 'nested-recovery'\n )\n node.retainedPendingCause = cause\n const releasedAt = numberField(payload, 'releasedAt')\n if (releasedAt !== undefined) node.releasedAt = releasedAt\n const budgetViolation = budgetViolationField(payload)\n if (budgetViolation) node.budgetViolation = budgetViolation\n attachSettlementEvidence(node, payload)\n}\n\n/**\n * Read the receipts a settlement carries. Each is taken as reported: an `unknown` receipt keeps\n * its `status` and `reason` so a client can show WHY a model or backend is missing instead of\n * showing nothing, and a receipt that never landed leaves every derived field absent.\n */\nfunction attachSettlementEvidence(\n node: MutableNode,\n payload: Record<string, unknown> | undefined,\n): void {\n const providerModel = payload?.providerModel as ProviderModelExecutionEvidence | undefined\n if (providerModel && typeof providerModel === 'object') node.providerModel = providerModel\n const trace = payload?.trace as WorkerTraceEvidence | undefined\n if (trace && typeof trace === 'object') node.trace = trace\n const bindings = payload?.executionBindings\n if (Array.isArray(bindings) && bindings.length > 0) {\n node.executionBindings = bindings as ReadonlyArray<ExecutionBindingReceipt>\n const known = bindings.find(\n (binding): binding is Extract<ExecutionBindingReceipt, { status: 'known' }> =>\n objectRecord(binding)?.status === 'known',\n )\n if (known) {\n node.placement = known.descriptor\n node.attemptId ??= known.attemptId\n }\n }\n const receipt = payload?.materialization as ProfileMaterializationReceipt | undefined\n if (!receipt || typeof receipt !== 'object') return\n node.materialization = receipt\n if (receipt.status !== 'known') return\n node.backend = receipt.backend\n if (receipt.model.status === 'known') node.model = receipt.model.id\n node.execution = { kind: receipt.execution.kind, id: receipt.execution.id }\n}\n\n/**\n * Fold one metered turn onto whoever drove it. `agent.turn` names its subject in `parentId` — the\n * node making the call — not in the payload, because the caller IS the subject. A turn the run\n * root drove belongs to no spawned node and lands on the run instead, so the run's totals stay\n * complete without inventing a node for the root.\n */\nfunction projectTurn(\n run: MutableRun,\n nodes: Map<string, MutableNode>,\n record: ObserverRecord,\n): void {\n const event = record.event\n if (event?.target !== 'agent.turn') return\n const payload = objectRecord(event.payload)\n const spend = spendField(payload, 'spend')\n const subject = event.parentId\n if (subject === undefined) return\n const node = nodes.get(nodeKey(event.runId, subject))\n if (!node) {\n if (!spend) return\n run.rootInference = run.rootInference ? addSpend(run.rootInference, spend) : spend\n return\n }\n node.turnCount += 1\n node.lastSequence = record.sequence\n node.lastObservedAt = record.observedAt\n if (spend) {\n node.ownInference = node.ownInference ? addSpend(node.ownInference, spend) : spend\n node.firstOutputAt ??= record.observedAt\n }\n const reasoning = numberField(payload, 'reasoningTokens')\n if (reasoning !== undefined) node.reasoningTokens = (node.reasoningTokens ?? 0) + reasoning\n const firstTokenAt = numberField(payload, 'firstTokenAt')\n if (firstTokenAt !== undefined) node.firstTokenAt ??= firstTokenAt\n const model = stringField(payload, 'model')\n if (model) node.model ??= model\n const callId = stringField(payload, 'callId')\n if (callId && !node.modelCalls.includes(callId)) node.modelCalls.push(callId)\n}\n\n/**\n * A node's whole reported cost: the child work its settlement reported plus the inference it drove\n * itself. `undefined` when neither landed — the run's `spendGaps` then names the node, so an\n * unaccounted node is visible instead of reading as free.\n */\nfunction nodeTotal(node: MutableNode): Spend | undefined {\n if (node.spent && node.ownInference) return addSpend(node.spent, node.ownInference)\n if (node.spent) return cloneSpend(node.spent)\n if (node.ownInference) return cloneSpend(node.ownInference)\n return undefined\n}\n\n/**\n * The run counted once, and each node's own share of it.\n *\n * A settled node's `spent` already contains the child work its nested tree reported, so summing\n * every node would count a driver's descendants twice. Inclusive therefore sums only the run's\n * TOP-LEVEL nodes — those whose parent is not another node of this run — plus the root's own\n * turns. Exclusive subtracts each node's direct children from its own total, which telescopes:\n * the exclusive entries sum back to `inclusive` exactly.\n */\nfunction runTotals(run: MutableRun, nodes: readonly MutableNode[]): PursuitRunTotals {\n const present = new Set(nodes.map((node) => node.id))\n const children = new Map<string, MutableNode[]>()\n for (const node of nodes) {\n if (node.parentId === undefined || !present.has(node.parentId)) continue\n const list = children.get(node.parentId)\n if (list) list.push(node)\n else children.set(node.parentId, [node])\n }\n const exclusiveByNode: Record<string, Spend> = {}\n let inclusive = run.rootInference ? cloneSpend(run.rootInference) : zeroSpend()\n if (run.rootInference) exclusiveByNode[run.runId] = cloneSpend(run.rootInference)\n for (const node of nodes) {\n const total = nodeTotal(node)\n if (total === undefined) continue\n if (node.parentId === undefined || !present.has(node.parentId)) {\n inclusive = addSpend(inclusive, total)\n }\n let exclusive = total\n for (const child of children.get(node.id) ?? []) {\n const childTotal = nodeTotal(child)\n if (childTotal !== undefined) exclusive = subtractSpend(exclusive, childTotal)\n }\n exclusiveByNode[node.id] = exclusive\n }\n return Object.freeze({\n inclusive: Object.freeze(inclusive),\n exclusiveByNode: Object.freeze(exclusiveByNode),\n })\n}\n\n/**\n * Remove a child's reported total from its parent's. Per channel, never below zero: a parent whose\n * executor reported less than its children did is a reporting gap, and a negative exclusive share\n * would be a fabricated number rather than a measurement.\n */\nfunction subtractSpend(a: Spend, b: Spend): Spend {\n const tokens = { ...a.tokens }\n tokens.input = Math.max(0, tokens.input - b.tokens.input)\n tokens.output = Math.max(0, tokens.output - b.tokens.output)\n if (a.tokens.cacheRead !== undefined)\n tokens.cacheRead = Math.max(0, a.tokens.cacheRead - (b.tokens.cacheRead ?? 0))\n if (a.tokens.cacheWrite !== undefined)\n tokens.cacheWrite = Math.max(0, a.tokens.cacheWrite - (b.tokens.cacheWrite ?? 0))\n if (a.tokens.freshInput !== undefined)\n tokens.freshInput = Math.max(0, a.tokens.freshInput - (b.tokens.freshInput ?? 0))\n return {\n iterations: Math.max(0, a.iterations - b.iterations),\n tokens,\n ...(a.tokensKnown === false || b.tokensKnown === false ? { tokensKnown: false } : {}),\n usd: Math.max(0, a.usd - b.usd),\n ...(a.usdKnown === false || b.usdKnown === false ? { usdKnown: false } : {}),\n ...(a.usdEstimated !== undefined\n ? { usdEstimated: Math.max(0, a.usdEstimated - (b.usdEstimated ?? 0)) }\n : {}),\n ms: Math.max(0, a.ms - b.ms),\n }\n}\n\n/** The nodes of one run whose accounting is incomplete, in the vocabulary the supervisor already\n * uses: `never-settled` = no terminal record, so every channel is unaccounted; `unreported` = a\n * record landed with a channel the provider did not report, so that channel is a floor. */\nfunction runSpendGaps(nodes: readonly MutableNode[]): SpendGap[] {\n const gaps: SpendGap[] = []\n for (const node of nodes) {\n const label = node.label\n if (node.status === 'running') {\n gaps.push({\n id: node.id,\n ...(label !== undefined ? { label } : {}),\n kind: 'never-settled',\n channels: ['tokens', 'usd'],\n })\n continue\n }\n const total = nodeTotal(node)\n const channels: SpendChannel[] = []\n if (total === undefined || total.tokensKnown === false) channels.push('tokens')\n if (total === undefined || total.usdKnown === false) channels.push('usd')\n if (channels.length === 0) continue\n gaps.push({\n id: node.id,\n ...(label !== undefined ? { label } : {}),\n kind: 'unreported',\n channels,\n })\n }\n return gaps\n}\n\nfunction usageOf(total: Spend, reasoning: number | undefined): PursuitNodeUsage {\n return {\n input: total.tokens.input,\n output: total.tokens.output,\n ...(total.tokens.cacheRead !== undefined ? { cacheRead: total.tokens.cacheRead } : {}),\n ...(total.tokens.cacheWrite !== undefined ? { cacheWrite: total.tokens.cacheWrite } : {}),\n ...(reasoning !== undefined ? { reasoning } : {}),\n tokensKnown: total.tokensKnown !== false && total.tokens.tokensKnown !== false,\n }\n}\n\nfunction costOf(total: Spend): PursuitNodeCost {\n const usdKnown = total.usdKnown !== false\n const estimated = total.usdEstimated\n const provenance: PursuitCostProvenance = usdKnown\n ? estimated === undefined || estimated === 0\n ? 'reported'\n : 'partial'\n : estimated === undefined\n ? 'unknown'\n : estimated >= total.usd\n ? 'estimated'\n : 'partial'\n return {\n usd: total.usd,\n usdKnown,\n ...(estimated !== undefined ? { usdEstimated: estimated } : {}),\n provenance,\n }\n}\n\n/** The platform block, or nothing at all when the node's spend names no box channel. */\nfunction platformOf(total: Spend): PursuitNodePlatform | undefined {\n if (total.boxMinutesProvenance === undefined) return undefined\n return {\n ...(total.boxMinutes !== undefined ? { boxMinutes: total.boxMinutes } : {}),\n boxMinutesKnown: total.boxMinutesKnown === true,\n provenance: total.boxMinutesProvenance,\n }\n}\n\nfunction timingOf(node: MutableNode): PursuitNodeTiming | undefined {\n if (node.startedAt === undefined) return undefined\n return {\n startedAt: node.startedAt,\n ...(node.firstOutputAt !== undefined ? { firstOutputAt: node.firstOutputAt } : {}),\n ...(node.firstTokenAt !== undefined ? { firstTokenAt: node.firstTokenAt } : {}),\n ...(node.settledAt !== undefined ? { settledAt: node.settledAt } : {}),\n ...(node.settledAt !== undefined\n ? { wallMs: Math.max(0, node.settledAt - node.startedAt) }\n : {}),\n }\n}\n\nfunction freezeRun(run: MutableRun, nodes: readonly MutableNode[]): PursuitRunProjection {\n const gaps = runSpendGaps(nodes)\n const { rootInference: _rootInference, started: _started, segments, ...rest } = run\n return Object.freeze({\n ...rest,\n ...(segments?.length\n ? { segments: Object.freeze(segments.map((segment) => Object.freeze(segment))) }\n : {}),\n targets: Object.freeze({ ...run.targets }),\n decisions: Object.freeze({ ...run.decisions }),\n totals: runTotals(run, nodes),\n ...(gaps.length > 0 ? { spendGaps: Object.freeze(gaps) } : {}),\n })\n}\n\nfunction freezeNode(node: MutableNode): PursuitNodeProjection {\n const {\n modelCalls,\n segments,\n reasoningTokens,\n startedAt: _startedAt,\n attemptIndex: _attemptIndex,\n ...rest\n } = node\n const total = nodeTotal(node)\n const timing = timingOf(node)\n return Object.freeze({\n ...rest,\n ...(segments?.length\n ? { segments: Object.freeze(segments.map((segment) => Object.freeze(segment))) }\n : {}),\n ...(modelCalls.length > 0 ? { modelCalls: Object.freeze([...modelCalls]) } : {}),\n ...(total !== undefined ? { usage: usageOf(total, reasoningTokens), cost: costOf(total) } : {}),\n ...(total !== undefined && platformOf(total) !== undefined\n ? { platform: platformOf(total) }\n : {}),\n ...(timing !== undefined ? { timing } : {}),\n })\n}\n\nfunction increment(\n target: Record<string, number>,\n key: RuntimeHookTarget | RuntimeDecisionKind,\n): void {\n target[key] = (target[key] ?? 0) + 1\n}\n\nfunction objectRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n}\n\n/** Read a journaled `Spend` without trusting the wire: a record missing the conserved channels is\n * not a zero-cost turn, it is an unparseable one, and it must not enter a total. */\nfunction spendField(value: Record<string, unknown> | undefined, key: string): Spend | undefined {\n const field = objectRecord(value?.[key])\n if (!field) return undefined\n const tokens = objectRecord(field.tokens)\n if (typeof field.usd !== 'number' || !Number.isFinite(field.usd)) return undefined\n if (!tokens || typeof tokens.input !== 'number' || typeof tokens.output !== 'number') {\n return undefined\n }\n return cloneSpend(field as unknown as Spend)\n}\n\n/** Read a journaled overspend without trusting the wire: one malformed channel drops the record,\n * so an unparseable entry is never reported as an overspend of some size. */\nfunction budgetViolationField(\n value: Record<string, unknown> | undefined,\n): BudgetViolation | undefined {\n const overspent = objectRecord(value?.budgetViolation)?.overspent\n if (!Array.isArray(overspent) || overspent.length === 0) return undefined\n const entries: BudgetOverspend[] = []\n for (const raw of overspent) {\n const entry = objectRecord(raw)\n const channel = stringField(entry, 'channel')\n const reserved = numberField(entry, 'reserved')\n const spent = numberField(entry, 'spent')\n if (channel === undefined || reserved === undefined || spent === undefined) return undefined\n entries.push({ channel: channel as BudgetOverspend['channel'], reserved, spent })\n }\n return { overspent: entries }\n}\n\nfunction stringField(value: Record<string, unknown> | undefined, key: string): string | undefined {\n const field = value?.[key]\n return typeof field === 'string' && field.length > 0 ? field : undefined\n}\n\nfunction numberField(value: Record<string, unknown> | undefined, key: string): number | undefined {\n const field = value?.[key]\n return typeof field === 'number' && Number.isFinite(field) ? field : undefined\n}\n\nfunction booleanField(\n value: Record<string, unknown> | undefined,\n key: string,\n): boolean | undefined {\n const field = value?.[key]\n return typeof field === 'boolean' ? field : undefined\n}\n","import { resolve } from 'node:path'\nimport { isRecord } from '@tangle-network/agent-core'\nimport type { NodeId } from '../runtime/supervise/types'\nimport { readCommittedJsonLines } from './jsonl-file'\nimport { FileObserverJournal } from './observer-journal'\nimport { spawnJournalRecordEvents } from './spawn-journal/record-events'\n\nexport interface DurableCoordinationStreamIdentity {\n readonly runId: string\n /** Exact owner ids present in the side-log, sorted for deterministic display. */\n readonly ownerIds: readonly string[]\n /** Records written before owner-scoped coordination identities were introduced. */\n readonly unscopedRecords: number\n readonly recordCount: number\n}\n\n/**\n * Identities discoverable from one `supervise({ runDir })` directory without\n * already knowing the root node or coordination run id stored inside it.\n */\nexport interface DurableSupervisionDiscovery {\n readonly runDir: string\n readonly observer?: { readonly path: string; readonly pursuitId: string }\n readonly spawnJournalPath: string\n readonly coordinationLogPath: string\n readonly roots: readonly NodeId[]\n /** `at` from each top-level root's `begin` record, index-aligned with `roots`. */\n readonly rootsBegunAt: readonly (string | null)[]\n readonly coordinationStreams: readonly DurableCoordinationStreamIdentity[]\n}\n\ntype SpawnJournalIdentityRecord = Readonly<\n Partial<Record<'kind' | 'root' | 'at' | 'event', unknown>>\n>\n\ntype CoordinationIdentityRecord = Readonly<Partial<Record<'runId' | 'ownerId', unknown>>>\n\n/**\n * Discover the stable identities recorded by Runtime's durable supervision\n * files. This is the developer-facing first step before calling\n * `FileSpawnJournal.loadTree(root)`, `loadSpawnForest(journal, root)`, or\n * `FileCoordinationLog.load(runId, ownerId)`.\n *\n * Missing files produce empty collections. A malformed committed JSONL record\n * still fails loud through the same parser used by the runtime; a torn final\n * append is ignored because it was never acknowledged as committed.\n */\nexport async function discoverDurableSupervisionRun(\n runDir: string,\n): Promise<DurableSupervisionDiscovery> {\n if (typeof runDir !== 'string' || runDir.trim().length === 0) {\n throw new TypeError('discoverDurableSupervisionRun: runDir must be a non-empty string')\n }\n\n const canonicalRunDir = resolve(runDir)\n const spawnJournalPath = `${canonicalRunDir}/spawn-journal.jsonl`\n const coordinationLogPath = `${canonicalRunDir}/coordination-log.jsonl`\n const nestedRoots = new Set<NodeId>()\n const rootsBegunAt = new Map<NodeId, string | null>()\n for await (const record of readCommittedJsonLines<SpawnJournalIdentityRecord>(spawnJournalPath, {\n allowMissing: true,\n })) {\n if (record.kind === 'begin') {\n if (typeof record.root !== 'string' || record.root.length === 0) {\n throw new Error(`${spawnJournalPath}: begin record has no non-empty string root identity`)\n }\n rootsBegunAt.set(record.root as NodeId, typeof record.at === 'string' ? record.at : null)\n continue\n }\n for (const event of spawnJournalRecordEvents(record)) {\n if (!isRecord(event) || event.kind !== 'spawned') continue\n if (!Object.hasOwn(event, 'ownedTreeRoot')) continue\n if (typeof event.ownedTreeRoot !== 'string' || event.ownedTreeRoot.length === 0) {\n throw new Error(\n `${spawnJournalPath}: spawned event ownedTreeRoot must be a non-empty string when present`,\n )\n }\n nestedRoots.add(event.ownedTreeRoot as NodeId)\n }\n }\n\n const streams = new Map<\n string,\n { owners: Set<string>; unscopedRecords: number; recordCount: number }\n >()\n for await (const record of readCommittedJsonLines<CoordinationIdentityRecord>(\n coordinationLogPath,\n { allowMissing: true },\n )) {\n if (typeof record.runId !== 'string' || record.runId.length === 0) {\n throw new Error(`${coordinationLogPath}: record has no non-empty string runId identity`)\n }\n const stream = streams.get(record.runId) ?? {\n owners: new Set<string>(),\n unscopedRecords: 0,\n recordCount: 0,\n }\n stream.recordCount += 1\n if (record.ownerId === undefined) {\n stream.unscopedRecords += 1\n } else if (typeof record.ownerId === 'string' && record.ownerId.length > 0) {\n stream.owners.add(record.ownerId)\n } else {\n throw new Error(`${coordinationLogPath}: ownerId must be a non-empty string when present`)\n }\n streams.set(record.runId, stream)\n }\n\n const coordinationStreams = [...streams.entries()]\n .sort(([left], [right]) => compareText(left, right))\n .map(([runId, stream]) =>\n Object.freeze({\n runId,\n ownerIds: Object.freeze([...stream.owners].sort(compareText)),\n unscopedRecords: stream.unscopedRecords,\n recordCount: stream.recordCount,\n }),\n )\n\n const observer = await FileObserverJournal.open(`${canonicalRunDir}/observer.jsonl`)\n const roots = [...rootsBegunAt.keys()].filter((root) => !nestedRoots.has(root)).sort(compareText)\n return Object.freeze({\n runDir: canonicalRunDir,\n ...(observer ? { observer: { path: observer.path, pursuitId: observer.pursuitId } } : {}),\n spawnJournalPath,\n coordinationLogPath,\n roots: Object.freeze(roots),\n rootsBegunAt: Object.freeze(roots.map((root) => rootsBegunAt.get(root) ?? null)),\n coordinationStreams: Object.freeze(coordinationStreams),\n })\n}\n\nfunction compareText(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAqUA,SAAgB,eAAe,SAAuD;CACpF,IAAI,QAAQ,WAAW,GACrB,MAAM,IAAI,UAAU,0DAA0D;CAEhF,MAAM,YAAY,QAAQ,EAAE,CAAE;CAC9B,MAAM,WAAW,sBAAsB,SAAS,SAAS;CACzD,MAAM,2BAAW,IAAI,IAA0B;CAC/C,MAAM,wBAAQ,IAAI,IAAyB;CAC3C,IAAI,aAAa;CACjB,IAAI,gBAAgB;CAEpB,KAAK,MAAM,UAAU,UAAU;EAC7B,MAAM,WAAW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G,oBAAoB,kDAAkD;EAE3F,QAAQ,IAAI,OAAO,OAAO,MAAM;CAClC;CAEA,MAAM,sBAAsB,CAAC,GAAG,QAAQ,QAAQ,CAAC,CAAC,CAC/C,MAAM,CAAC,OAAO,CAAC,WAAW,YAAY,MAAM,KAAK,CAAC,CAAC,CACnD,KAAK,CAAC,OAAO,YACZ,OAAO,OAAO;EACZ;EACA,UAAU,OAAO,OAAO,CAAC,GAAG,OAAO,MAAM,CAAC,CAAC,KAAK,WAAW,CAAC;EAC5D,iBAAiB,OAAO;EACxB,aAAa,OAAO;CACtB,CAAC,CACH;CAEF,MAAM,WAAW,MAAM,oBAAoB,KAAK,GAAG,gBAAgB,gBAAgB;CACnF,MAAM,QAAQ,CAAC,GAAG,aAAa,KAAK,CAAC,CAAC,CAAC,QAAQ,SAAS,CAAC,YAAY,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,WAAW;CAChG,OAAO,OAAO,OAAO;EACnB,QAAQ;EACR,GAAI,WAAW,EAAE,UAAU;GAAE,MAAM,SAAS;GAAM,WAAW,SAAS;EAAU,EAAE,IAAI,CAAC;EACvF;EACA;EACA,OAAO,OAAO,OAAO,KAAK;EAC1B,cAAc,OAAO,OAAO,MAAM,KAAK,SAAS,aAAa,IAAI,IAAI,KAAK,IAAI,CAAC;EAC/E,qBAAqB,OAAO,OAAO,mBAAmB;CACxD,CAAC;AACH;AAEA,SAAS,YAAY,MAAc,OAAuB;CACxD,OAAO,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;AAChD"}
1
+ {"version":3,"file":"supervision-discovery-DmDWHwLu.js","names":[],"sources":["../src/durable/observer-projection.ts","../src/durable/supervision-discovery.ts"],"sourcesContent":["import { type RuntimeFailureCause, runtimeFailureCauseSchema } from '../runtime/failure-cause'\nimport type { SeatSegment } from '../runtime/supervise/seat-chain'\nimport type {\n BudgetOverspend,\n BudgetViolation,\n ExecutionBindingReceipt,\n ProfileMaterializationReceipt,\n ProviderModelExecutionEvidence,\n RetainedExecutionState,\n RetainedPendingCause,\n Spend,\n SpendChannel,\n SpendGap,\n WorkerTraceEvidence,\n} from '../runtime/supervise/types'\nimport { addSpend, cloneSpend, zeroSpend } from '../runtime/util'\nimport type { RuntimeDecisionKind, RuntimeHookTarget } from '../runtime-hooks'\nimport { type ObserverRecord, verifyObserverRecords } from './observer-journal'\n\n/**\n * One settled projection status, shared by runs and nodes. `down` is the journal's own word for a\n * failure (a settlement is journaled as `kind: 'down'`, cancellation included), so a consumer can\n * join run rows to node rows on `status` and read one failure population instead of two.\n */\nexport type PursuitStatus = 'running' | 'done' | 'down'\n\n/**\n * Where a node's dollar figure came from. `reported` = a provider billed all of it; `estimated` =\n * a model catalog priced all of it; `partial` = a provider billed part and a catalog priced the\n * rest; `unknown` = nothing priced it, so `usd` is a floor and never the cost.\n */\nexport type PursuitCostProvenance = 'reported' | 'estimated' | 'partial' | 'unknown'\n\n/**\n * One node's token usage by class. Cache and reasoning classes are absent when the provider did\n * not report them — absence is not zero. `tokensKnown` is `false` when work happened whose token\n * count no provider reported, which makes `input`/`output` a floor.\n */\nexport interface PursuitNodeUsage {\n readonly input: number\n readonly output: number\n readonly cacheRead?: number\n readonly cacheWrite?: number\n readonly reasoning?: number\n readonly tokensKnown: boolean\n}\n\n/**\n * One node's PLATFORM consumption — box wall time, the resource a subscription seat really pays.\n *\n * Kept apart from `PursuitNodeCost` because the two answer different questions and fail\n * independently: a seat run reports a truthful `$0` and real minutes, a caller-account run\n * reports real dollars and may report no minutes at all. Collapsing them into one \"spend known\"\n * figure hides which one is missing.\n *\n * Absent on a node that ran no box. `boxMinutes` absent WITH the block present says a box ran and\n * nothing measured it — a missing measurement is never a zero.\n */\nexport interface PursuitNodePlatform {\n readonly boxMinutes?: number\n /** `false` when a box ran whose time could not be closed, so `boxMinutes` is a floor. */\n readonly boxMinutesKnown: boolean\n /** `observed` = the platform billed the minutes; `estimated` = Runtime derived them from the box\n * lifetime it watched; `uncaptured` = a box ran and nothing measured it. */\n readonly provenance: 'observed' | 'estimated' | 'uncaptured'\n}\n\n/** One node's dollar cost with the provenance that decides whether it may be compared or summed. */\nexport interface PursuitNodeCost {\n readonly usd: number\n readonly usdKnown: boolean\n /** The part of `usd` a model catalog priced because no provider receipt covered it. */\n readonly usdEstimated?: number\n readonly provenance: PursuitCostProvenance\n}\n\n/**\n * One node's clock. `wallMs` is `settledAt - startedAt` and is deliberately distinct from the\n * executor-reported `spent.ms` sums, which under-report and overlap across parallel children.\n * `firstTokenAt` stays absent unless a provider reports that instant; it is never inferred from\n * `firstOutputAt`, which is when the node first reported usage for a turn.\n */\nexport interface PursuitNodeTiming {\n readonly startedAt: number\n readonly firstOutputAt?: number\n readonly firstTokenAt?: number\n readonly settledAt?: number\n readonly wallMs?: number\n}\n\n/** Where and how a node's execution was placed, read off its execution-binding receipt. */\ntype PursuitNodePlacement = Readonly<Record<string, string | number | boolean | null>>\n\n/**\n * One run's spend counted once, and each node's own share of it. `inclusive` and the entries of\n * `exclusiveByNode` are the two views a client needs to show a tree without double counting.\n */\nexport interface PursuitRunTotals {\n /**\n * The whole run counted once. A node's settled `spent` already contains the child work its own\n * nested tree reported, so summing only the run's top-level nodes plus every node's own\n * inference counts each model call exactly once.\n */\n readonly inclusive: Spend\n /**\n * Each node's own share: its reported spend and own inference minus what its direct children\n * reported. Keyed by node id, plus the run root when the root itself metered inference. The\n * entries sum to `inclusive` by construction.\n */\n readonly exclusiveByNode: Readonly<Record<string, Spend>>\n}\n\n/**\n * One attempt at one concrete Runtime run: the stretch of `agent.run` lifecycle from a `before`\n * to the `after` or `error` that settles it. A run whose first attempt threw and whose corrected\n * attempt settled is two rows, so `error` names only the attempt that failed.\n *\n * A `before` observed while an attempt is still open does not open another: it is a process\n * that resumed the run after the previous process died without a terminal record, and the row\n * counts it in `resumeCount`. The alternative, a row per process start, would leave the killed\n * process's row `running` for the rest of history.\n */\nexport interface PursuitRunProjection {\n readonly runId: string\n /** Zero-based position of this attempt among the run's attempts, in journal order. */\n readonly attemptIndex: number\n /** How many times a process resumed this attempt after a predecessor died mid-run. */\n readonly resumeCount: number\n readonly status: PursuitStatus\n readonly settledAt?: number\n readonly error?: string\n /** Runtime-classified root failure; absent in legacy observer history. */\n readonly failure?: RuntimeFailureCause\n /** Subscription execution of the root manager, ordered across seat changes. */\n readonly segments?: ReadonlyArray<SeatSegment>\n readonly resumeAt?: string\n readonly firstSequence: number\n readonly lastSequence: number\n readonly firstObservedAt: number\n readonly lastObservedAt: number\n readonly eventCount: number\n readonly decisionCount: number\n readonly targets: Readonly<Record<string, number>>\n readonly decisions: Readonly<Record<string, number>>\n readonly totals: PursuitRunTotals\n /** The nodes whose accounting is incomplete. Present exactly when non-empty. */\n readonly spendGaps?: ReadonlyArray<SpendGap>\n}\n\nexport interface PursuitNodeProjection {\n readonly id: string\n readonly parentId?: string\n /** Node ids are scoped to this concrete Runtime tree; `(runId,id)` is identity. */\n readonly runId: string\n readonly label?: string\n /** The runner that executed this node — the executor's own name, not a harness guess. */\n readonly runtime?: string\n readonly depth?: number\n readonly assignmentId?: string\n /** The settled sibling this node replaced, as its manager's spawn named it. Absent on a node\n * that replaced nothing. */\n readonly successorOf?: string\n readonly identity?: unknown\n readonly budget?: unknown\n readonly status: PursuitStatus\n readonly settledAt?: number\n /** The child work this node reported at settlement. Absent until a terminal record lands. */\n readonly spent?: Spend\n /** This node's OWN inference, re-homed from its nested tree. Absent when it drove no turns. */\n readonly ownInference?: Spend\n /** Absent until a spend record lands; the run's `spendGaps` then names the node. */\n readonly usage?: PursuitNodeUsage\n /** Absent until a spend record lands; the run's `spendGaps` then names the node. */\n readonly cost?: PursuitNodeCost\n /** What the node consumed on the PLATFORM. Absent on a node that ran no box. */\n readonly platform?: PursuitNodePlatform\n readonly timing?: PursuitNodeTiming\n /** The kernel-minted attempt this node's execution binding is keyed on. */\n readonly attemptId?: string\n /** The runner-native execution the node bound to: a request, session, run, process, or tree. */\n readonly execution?: { readonly kind: string; readonly id: string }\n /** The model the materialization receipt names, when the runner reported one. */\n readonly model?: string\n /** The concrete backend the profile materialized onto. */\n readonly backend?: string\n readonly placement?: PursuitNodePlacement\n /** Model-call identifiers this node's own turns reported, in order, deduplicated. */\n readonly modelCalls?: ReadonlyArray<string>\n readonly materialization?: ProfileMaterializationReceipt\n readonly executionBindings?: ReadonlyArray<ExecutionBindingReceipt>\n /** What the provider itself reported serving, and why it is unknown when it is. */\n readonly providerModel?: ProviderModelExecutionEvidence\n /** Content-addressed pointer to this node's persisted tool trace, or why there is none. */\n readonly trace?: WorkerTraceEvidence\n readonly outRef?: string\n readonly score?: number\n readonly valid?: boolean\n readonly reason?: string\n readonly failure?: RuntimeFailureCause\n /** Subscription execution of this logical child, ordered across seat changes. */\n readonly segments?: ReadonlyArray<SeatSegment>\n readonly resumeAt?: string\n readonly infra?: boolean\n /** Recorded by Runtime on the `agent.child` payload: `'pending'` at a retained child's\n * settlement, `'released'` when root settlement destroyed its environment without recovery,\n * `'release-unconfirmed'` when a final settlement closed its slot without confirming that.\n * The status stays `down` — the split is a sibling fact, not a fourth status. A second\n * `agent.child` for one node is already how a live-recovered child flips down→done, so the\n * fold overwrites in observed order; that event's `settledAt` is the original settlement, so\n * `settledAt` and `timing` do not move. */\n readonly retainedExecution?: RetainedExecutionState\n /** Why a retained child has no accepted result; see `RetainedPendingCause`. */\n readonly retainedPendingCause?: RetainedPendingCause\n /** When a final settlement closed a retained node's slot; absent while it is `'pending'`. */\n readonly releasedAt?: number\n /** Each channel on which the settled spend exceeded the node's reservation. The status is the\n * node's own outcome: a `done` node that overspent still delivered its output. */\n readonly budgetViolation?: BudgetViolation\n readonly firstSequence: number\n readonly lastSequence: number\n readonly firstObservedAt: number\n readonly lastObservedAt: number\n readonly eventCount: number\n readonly turnCount: number\n}\n\nexport interface PursuitProjection {\n readonly pursuitId: string\n /** Number of records in this concrete execution journal. */\n readonly sequence: number\n /** Digest-chain tip for this concrete execution journal. */\n readonly chainTip: string\n readonly firstObservedAt: number\n readonly lastObservedAt: number\n readonly runs: readonly PursuitRunProjection[]\n readonly nodes: readonly PursuitNodeProjection[]\n readonly eventCount: number\n readonly decisionCount: number\n}\n\ntype MutableRun = {\n -readonly [K in keyof Omit<\n PursuitRunProjection,\n 'totals' | 'spendGaps' | 'segments' | 'targets' | 'decisions'\n >]: PursuitRunProjection[K]\n} & {\n /** Whether this attempt has seen its own `before`; an attempt a journal opens without one\n * treats the first `before` it meets as its start, not as a resume. */\n started: boolean\n segments?: SeatSegment[]\n targets: Record<string, number>\n decisions: Record<string, number>\n /** Inference the run root drove itself, attributable to no spawned node. */\n rootInference?: Spend\n}\n\ntype MutableNode = {\n id: string\n parentId?: string\n runId: string\n /** The attempt whose process spawned this node; totals and gaps are folded per attempt. */\n attemptIndex: number\n label?: string\n runtime?: string\n depth?: number\n assignmentId?: string\n successorOf?: string\n identity?: unknown\n budget?: unknown\n status: PursuitStatus\n startedAt?: number\n settledAt?: number\n spent?: Spend\n ownInference?: Spend\n reasoningTokens?: number\n firstOutputAt?: number\n firstTokenAt?: number\n attemptId?: string\n execution?: { kind: string; id: string }\n model?: string\n backend?: string\n placement?: PursuitNodePlacement\n modelCalls: string[]\n materialization?: ProfileMaterializationReceipt\n executionBindings?: ReadonlyArray<ExecutionBindingReceipt>\n providerModel?: ProviderModelExecutionEvidence\n trace?: WorkerTraceEvidence\n outRef?: string\n score?: number\n valid?: boolean\n reason?: string\n failure?: RuntimeFailureCause\n segments?: SeatSegment[]\n resumeAt?: string\n infra?: boolean\n retainedExecution?: RetainedExecutionState\n retainedPendingCause?: RetainedPendingCause\n releasedAt?: number\n budgetViolation?: BudgetViolation\n firstSequence: number\n lastSequence: number\n firstObservedAt: number\n lastObservedAt: number\n eventCount: number\n turnCount: number\n}\n\n/**\n * Fold one append-only execution journal into a deterministic operator projection.\n *\n * This is intentionally a READ model, not another state machine: it does not own\n * execution, cannot steer agents, and can be rebuilt from the journal at any time.\n * Projection verifies the complete hash chain first, so an operator view can never\n * silently render a mutated or reordered observer history as trustworthy state.\n *\n * Topology comes only from Runtime's canonical `agent.spawn` facts. Terminal node\n * state comes only from `agent.child`; concrete run state comes only from the root\n * `agent.run` lifecycle emitted by `supervisePursuit`, one row per attempt. Node identity is\n * scoped to the concrete Runtime run so independent trees may both contain `root:s0` without\n * aliasing, and a node belongs to the attempt that spawned it.\n *\n * Usage, cost and timing are reported at the class the runtime measured them at. A missing\n * class stays ABSENT and the run names the node in `spendGaps`; nothing here converts an\n * unmeasured channel into a zero, because a fabricated zero is indistinguishable from free work.\n */\nexport function projectPursuit(records: readonly ObserverRecord[]): PursuitProjection {\n if (records.length === 0) {\n throw new TypeError('projectPursuit: at least one observer record is required')\n }\n const pursuitId = records[0]!.pursuitId\n const verified = verifyObserverRecords(records, pursuitId)\n const attempts = new Map<string, MutableRun[]>()\n const nodes = new Map<string, MutableNode>()\n let eventCount = 0\n let decisionCount = 0\n\n for (const record of verified) {\n const observed = record.event ?? record.decision\n if (!observed) throw new Error(`projectPursuit: record ${record.sequence} has no observation`)\n const run = currentAttempt(attempts, observed.runId, record)\n run.lastSequence = record.sequence\n run.lastObservedAt = record.observedAt\n\n if (record.event) {\n eventCount += 1\n run.eventCount += 1\n increment(run.targets, record.event.target)\n projectRunActivity(run, record)\n projectSpawnNode(nodes, record, run.attemptIndex)\n projectNodeActivity(nodes, record)\n projectSeat(run, nodes, record)\n projectTurn(run, nodes, record)\n } else if (record.decision) {\n decisionCount += 1\n run.decisionCount += 1\n increment(run.decisions, record.decision.kind)\n }\n }\n\n const byAttempt = new Map<string, MutableNode[]>()\n for (const node of nodes.values()) {\n const key = attemptKey(node.runId, node.attemptIndex)\n const list = byAttempt.get(key)\n if (list) list.push(node)\n else byAttempt.set(key, [node])\n }\n\n const first = verified[0]!\n const last = verified.at(-1)!\n return Object.freeze({\n pursuitId,\n sequence: last.sequence,\n chainTip: last.digest,\n firstObservedAt: first.observedAt,\n lastObservedAt: last.observedAt,\n runs: Object.freeze(\n [...attempts.values()]\n .flat()\n .sort((a, b) => a.firstSequence - b.firstSequence || a.runId.localeCompare(b.runId))\n .map((run) => freezeRun(run, byAttempt.get(attemptKey(run.runId, run.attemptIndex)) ?? [])),\n ),\n nodes: Object.freeze(\n [...nodes.values()]\n .sort(\n (a, b) =>\n a.firstSequence - b.firstSequence ||\n a.runId.localeCompare(b.runId) ||\n a.id.localeCompare(b.id),\n )\n .map(freezeNode),\n ),\n eventCount,\n decisionCount,\n })\n}\n\nfunction projectSeat(\n run: MutableRun,\n nodes: Map<string, MutableNode>,\n record: ObserverRecord,\n): void {\n const event = record.event\n if (event?.target !== 'agent.seat') return\n const payload = objectRecord(event.payload)\n const phase = stringField(payload, 'phase')\n const node = nodes.get(nodeKey(event.runId, stringField(payload, 'nodeId') ?? ''))\n const owner = node ?? run\n if (phase === 'paused') {\n const resumeAt = stringField(payload, 'resumeAt')\n if (resumeAt) owner.resumeAt = resumeAt\n return\n }\n if (phase === 'resumed') {\n delete owner.resumeAt\n return\n }\n const raw = objectRecord(payload?.segment)\n const seat = stringField(raw, 'seat')\n const harness = stringField(raw, 'harness')\n const provider = stringField(raw, 'provider')\n const model = stringField(raw, 'model')\n const startedAt = stringField(raw, 'startedAt')\n if (!seat || !harness || !provider || !model || !startedAt) return\n if (owner.segments === undefined) owner.segments = []\n const segments = owner.segments\n if (phase === 'started') {\n if (!segments.some((segment) => segment.startedAt === startedAt && segment.seat === seat)) {\n segments.push({ seat, harness, provider, model, startedAt })\n }\n } else if (phase === 'ended') {\n const endedAt = stringField(raw, 'endedAt')\n const reason = stringField(raw, 'reason') as SeatSegment['reason']\n if (!endedAt || !reason) return\n const index = segments.findIndex(\n (segment) => segment.startedAt === startedAt && segment.seat === seat,\n )\n if (index >= 0) segments[index] = { seat, harness, provider, model, startedAt, endedAt, reason }\n }\n}\n\nfunction attemptKey(runId: string, attemptIndex: number): string {\n return `${runId}\\u0000${attemptIndex}`\n}\n\n/**\n * The attempt a record belongs to. An `agent.run` `before` opens a new attempt when the run has\n * none or its latest attempt already settled; on an open attempt it is a resume. Every other\n * record joins the latest attempt, and a journal that never emitted `before` gets attempt 0.\n */\nfunction currentAttempt(\n attempts: Map<string, MutableRun[]>,\n runId: string,\n record: ObserverRecord,\n): MutableRun {\n const list = attempts.get(runId) ?? []\n if (list.length === 0) attempts.set(runId, list)\n const latest = list.at(-1)\n const isStart = record.event?.target === 'agent.run' && record.event.phase === 'before'\n if (latest !== undefined && (!isStart || latest.status === 'running')) {\n if (isStart) {\n if (latest.started) latest.resumeCount += 1\n latest.started = true\n }\n return latest\n }\n const created: MutableRun = {\n runId,\n attemptIndex: list.length,\n resumeCount: 0,\n started: isStart,\n status: 'running',\n firstSequence: record.sequence,\n lastSequence: record.sequence,\n firstObservedAt: record.observedAt,\n lastObservedAt: record.observedAt,\n eventCount: 0,\n decisionCount: 0,\n targets: {},\n decisions: {},\n }\n list.push(created)\n return created\n}\n\nfunction projectRunActivity(run: MutableRun, record: ObserverRecord): void {\n const event = record.event\n if (event?.target !== 'agent.run') return\n const payload = objectRecord(event.payload)\n const status = stringField(payload, 'status')\n const done = event.phase === 'after' || status === 'done'\n if (!done && event.phase !== 'error' && status !== 'failed') return\n // The `agent.run` hook payload spells a failure `failed`; the projection spells every\n // settled failure `down`, the journal's word, so run and node rows join on one vocabulary.\n run.status = done ? 'done' : 'down'\n run.settledAt = record.observedAt\n if (payload && Object.hasOwn(payload, 'failure'))\n run.failure = runtimeFailureCauseSchema.parse(payload.failure)\n const error = stringField(payload, 'error')\n if (error && (!done || run.failure !== undefined)) run.error = error\n}\n\nfunction nodeKey(runId: string, nodeId: string): string {\n return `${runId}\\u0000${nodeId}`\n}\n\nfunction projectSpawnNode(\n nodes: Map<string, MutableNode>,\n record: ObserverRecord,\n attemptIndex: number,\n): void {\n const event = record.event\n if (event?.target !== 'agent.spawn') return\n const payload = objectRecord(event.payload)\n const childId = stringField(payload, 'childId')\n if (!childId) return\n const key = nodeKey(event.runId, childId)\n const existing = nodes.get(key)\n if (existing) {\n existing.lastSequence = record.sequence\n existing.lastObservedAt = record.observedAt\n existing.eventCount += 1\n return\n }\n const label = stringField(payload, 'label')\n const runtime = stringField(payload, 'runtime')\n const depth = numberField(payload, 'depth')\n const assignmentId = stringField(payload, 'assignmentId')\n const successorOf = stringField(payload, 'successorOf')\n const attemptId = stringField(payload, 'attemptId')\n const startedAt = numberField(payload, 'startedAt')\n nodes.set(key, {\n id: childId,\n ...(event.parentId ? { parentId: event.parentId } : {}),\n runId: event.runId,\n attemptIndex,\n ...(label ? { label } : {}),\n ...(runtime ? { runtime } : {}),\n ...(depth !== undefined ? { depth } : {}),\n ...(assignmentId ? { assignmentId } : {}),\n ...(successorOf ? { successorOf } : {}),\n ...(attemptId ? { attemptId } : {}),\n // A spawn that predates the `startedAt` fact falls back to when the record was observed:\n // the spawn event is emitted synchronously with the spawn, so the two agree to the ms.\n startedAt: startedAt ?? record.observedAt,\n ...(payload && Object.hasOwn(payload, 'identity') ? { identity: payload.identity } : {}),\n ...(payload && Object.hasOwn(payload, 'budget') ? { budget: payload.budget } : {}),\n status: 'running',\n modelCalls: [],\n firstSequence: record.sequence,\n lastSequence: record.sequence,\n firstObservedAt: record.observedAt,\n lastObservedAt: record.observedAt,\n eventCount: 1,\n turnCount: 0,\n })\n}\n\nfunction projectNodeActivity(nodes: Map<string, MutableNode>, record: ObserverRecord): void {\n const event = record.event\n if (event === undefined) return\n if (event.target === 'agent.spawn') return\n const payload = objectRecord(event.payload)\n const nodeId =\n stringField(payload, 'childId') ??\n stringField(payload, 'nodeId') ??\n stringField(payload, 'workerId')\n if (!nodeId) return\n const node = nodes.get(nodeKey(event.runId, nodeId))\n if (!node) return\n node.lastSequence = record.sequence\n node.lastObservedAt = record.observedAt\n node.eventCount += 1\n\n if (event.target !== 'agent.child') return\n const status = stringField(payload, 'status')\n if (status !== 'done' && status !== 'down') return\n node.status = status\n node.settledAt = numberField(payload, 'settledAt') ?? record.observedAt\n const startedAt = numberField(payload, 'startedAt')\n if (startedAt !== undefined) node.startedAt = startedAt\n if (payload && Object.hasOwn(payload, 'spent')) node.spent = spendField(payload, 'spent')\n const metered = spendField(payload, 'metered')\n if (metered)\n node.ownInference = node.ownInference ? addSpend(node.ownInference, metered) : metered\n const runtime = stringField(payload, 'runtime')\n if (runtime) node.runtime = runtime\n const outRef = stringField(payload, 'outRef')\n if (outRef) node.outRef = outRef\n const score = numberField(payload, 'score')\n if (score !== undefined) node.score = score\n const valid = booleanField(payload, 'valid')\n if (valid !== undefined) node.valid = valid\n const reason = stringField(payload, 'reason')\n if (reason) node.reason = reason\n if (status === 'done') node.failure = undefined\n else if (payload && Object.hasOwn(payload, 'failure')) {\n node.failure = runtimeFailureCauseSchema.parse(payload.failure)\n }\n const infra = booleanField(payload, 'infra')\n if (infra !== undefined) node.infra = infra\n const retained = stringField(payload, 'retainedExecution')\n if (retained === 'pending' || retained === 'released' || retained === 'release-unconfirmed') {\n node.retainedExecution = retained\n }\n const cause = stringField(payload, 'retainedPendingCause')\n if (\n cause === 'unobservable' ||\n cause === 'provider-contract' ||\n cause === 'request-rejected' ||\n cause === 'transport' ||\n cause === 'nested-recovery'\n )\n node.retainedPendingCause = cause\n const releasedAt = numberField(payload, 'releasedAt')\n if (releasedAt !== undefined) node.releasedAt = releasedAt\n const budgetViolation = budgetViolationField(payload)\n if (budgetViolation) node.budgetViolation = budgetViolation\n attachSettlementEvidence(node, payload)\n}\n\n/**\n * Read the receipts a settlement carries. Each is taken as reported: an `unknown` receipt keeps\n * its `status` and `reason` so a client can show WHY a model or backend is missing instead of\n * showing nothing, and a receipt that never landed leaves every derived field absent.\n */\nfunction attachSettlementEvidence(\n node: MutableNode,\n payload: Record<string, unknown> | undefined,\n): void {\n const providerModel = payload?.providerModel as ProviderModelExecutionEvidence | undefined\n if (providerModel && typeof providerModel === 'object') node.providerModel = providerModel\n const trace = payload?.trace as WorkerTraceEvidence | undefined\n if (trace && typeof trace === 'object') node.trace = trace\n const bindings = payload?.executionBindings\n if (Array.isArray(bindings) && bindings.length > 0) {\n node.executionBindings = bindings as ReadonlyArray<ExecutionBindingReceipt>\n const known = bindings.find(\n (binding): binding is Extract<ExecutionBindingReceipt, { status: 'known' }> =>\n objectRecord(binding)?.status === 'known',\n )\n if (known) {\n node.placement = known.descriptor\n node.attemptId ??= known.attemptId\n }\n }\n const receipt = payload?.materialization as ProfileMaterializationReceipt | undefined\n if (!receipt || typeof receipt !== 'object') return\n node.materialization = receipt\n if (receipt.status !== 'known') return\n node.backend = receipt.backend\n if (receipt.model.status === 'known') node.model = receipt.model.id\n node.execution = { kind: receipt.execution.kind, id: receipt.execution.id }\n}\n\n/**\n * Fold one metered turn onto whoever drove it. `agent.turn` names its subject in `parentId` — the\n * node making the call — not in the payload, because the caller IS the subject. A turn the run\n * root drove belongs to no spawned node and lands on the run instead, so the run's totals stay\n * complete without inventing a node for the root.\n */\nfunction projectTurn(\n run: MutableRun,\n nodes: Map<string, MutableNode>,\n record: ObserverRecord,\n): void {\n const event = record.event\n if (event?.target !== 'agent.turn') return\n const payload = objectRecord(event.payload)\n const spend = spendField(payload, 'spend')\n const subject = event.parentId\n if (subject === undefined) return\n const node = nodes.get(nodeKey(event.runId, subject))\n if (!node) {\n if (!spend) return\n run.rootInference = run.rootInference ? addSpend(run.rootInference, spend) : spend\n return\n }\n node.turnCount += 1\n node.lastSequence = record.sequence\n node.lastObservedAt = record.observedAt\n if (spend) {\n node.ownInference = node.ownInference ? addSpend(node.ownInference, spend) : spend\n node.firstOutputAt ??= record.observedAt\n }\n const reasoning = numberField(payload, 'reasoningTokens')\n if (reasoning !== undefined) node.reasoningTokens = (node.reasoningTokens ?? 0) + reasoning\n const firstTokenAt = numberField(payload, 'firstTokenAt')\n if (firstTokenAt !== undefined) node.firstTokenAt ??= firstTokenAt\n const model = stringField(payload, 'model')\n if (model) node.model ??= model\n const callId = stringField(payload, 'callId')\n if (callId && !node.modelCalls.includes(callId)) node.modelCalls.push(callId)\n}\n\n/**\n * A node's whole reported cost: the child work its settlement reported plus the inference it drove\n * itself. `undefined` when neither landed — the run's `spendGaps` then names the node, so an\n * unaccounted node is visible instead of reading as free.\n */\nfunction nodeTotal(node: MutableNode): Spend | undefined {\n if (node.spent && node.ownInference) return addSpend(node.spent, node.ownInference)\n if (node.spent) return cloneSpend(node.spent)\n if (node.ownInference) return cloneSpend(node.ownInference)\n return undefined\n}\n\n/**\n * The run counted once, and each node's own share of it.\n *\n * A settled node's `spent` already contains the child work its nested tree reported, so summing\n * every node would count a driver's descendants twice. Inclusive therefore sums only the run's\n * TOP-LEVEL nodes — those whose parent is not another node of this run — plus the root's own\n * turns. Exclusive subtracts each node's direct children from its own total, which telescopes:\n * the exclusive entries sum back to `inclusive` exactly.\n */\nfunction runTotals(run: MutableRun, nodes: readonly MutableNode[]): PursuitRunTotals {\n const present = new Set(nodes.map((node) => node.id))\n const children = new Map<string, MutableNode[]>()\n for (const node of nodes) {\n if (node.parentId === undefined || !present.has(node.parentId)) continue\n const list = children.get(node.parentId)\n if (list) list.push(node)\n else children.set(node.parentId, [node])\n }\n const exclusiveByNode: Record<string, Spend> = {}\n let inclusive = run.rootInference ? cloneSpend(run.rootInference) : zeroSpend()\n if (run.rootInference) exclusiveByNode[run.runId] = cloneSpend(run.rootInference)\n for (const node of nodes) {\n const total = nodeTotal(node)\n if (total === undefined) continue\n if (node.parentId === undefined || !present.has(node.parentId)) {\n inclusive = addSpend(inclusive, total)\n }\n let exclusive = total\n for (const child of children.get(node.id) ?? []) {\n const childTotal = nodeTotal(child)\n if (childTotal !== undefined) exclusive = subtractSpend(exclusive, childTotal)\n }\n exclusiveByNode[node.id] = exclusive\n }\n return Object.freeze({\n inclusive: Object.freeze(inclusive),\n exclusiveByNode: Object.freeze(exclusiveByNode),\n })\n}\n\n/**\n * Remove a child's reported total from its parent's. Per channel, never below zero: a parent whose\n * executor reported less than its children did is a reporting gap, and a negative exclusive share\n * would be a fabricated number rather than a measurement.\n */\nfunction subtractSpend(a: Spend, b: Spend): Spend {\n const tokens = { ...a.tokens }\n tokens.input = Math.max(0, tokens.input - b.tokens.input)\n tokens.output = Math.max(0, tokens.output - b.tokens.output)\n if (a.tokens.cacheRead !== undefined)\n tokens.cacheRead = Math.max(0, a.tokens.cacheRead - (b.tokens.cacheRead ?? 0))\n if (a.tokens.cacheWrite !== undefined)\n tokens.cacheWrite = Math.max(0, a.tokens.cacheWrite - (b.tokens.cacheWrite ?? 0))\n if (a.tokens.freshInput !== undefined)\n tokens.freshInput = Math.max(0, a.tokens.freshInput - (b.tokens.freshInput ?? 0))\n return {\n iterations: Math.max(0, a.iterations - b.iterations),\n tokens,\n ...(a.tokensKnown === false || b.tokensKnown === false ? { tokensKnown: false } : {}),\n usd: Math.max(0, a.usd - b.usd),\n ...(a.usdKnown === false || b.usdKnown === false ? { usdKnown: false } : {}),\n ...(a.usdEstimated !== undefined\n ? { usdEstimated: Math.max(0, a.usdEstimated - (b.usdEstimated ?? 0)) }\n : {}),\n ms: Math.max(0, a.ms - b.ms),\n }\n}\n\n/** The nodes of one run whose accounting is incomplete, in the vocabulary the supervisor already\n * uses: `never-settled` = no terminal record, so every channel is unaccounted; `unreported` = a\n * record landed with a channel the provider did not report, so that channel is a floor. */\nfunction runSpendGaps(nodes: readonly MutableNode[]): SpendGap[] {\n const gaps: SpendGap[] = []\n for (const node of nodes) {\n const label = node.label\n if (node.status === 'running') {\n gaps.push({\n id: node.id,\n ...(label !== undefined ? { label } : {}),\n kind: 'never-settled',\n channels: ['tokens', 'usd'],\n })\n continue\n }\n const total = nodeTotal(node)\n const channels: SpendChannel[] = []\n if (total === undefined || total.tokensKnown === false) channels.push('tokens')\n if (total === undefined || total.usdKnown === false) channels.push('usd')\n if (channels.length === 0) continue\n gaps.push({\n id: node.id,\n ...(label !== undefined ? { label } : {}),\n kind: 'unreported',\n channels,\n })\n }\n return gaps\n}\n\nfunction usageOf(total: Spend, reasoning: number | undefined): PursuitNodeUsage {\n return {\n input: total.tokens.input,\n output: total.tokens.output,\n ...(total.tokens.cacheRead !== undefined ? { cacheRead: total.tokens.cacheRead } : {}),\n ...(total.tokens.cacheWrite !== undefined ? { cacheWrite: total.tokens.cacheWrite } : {}),\n ...(reasoning !== undefined ? { reasoning } : {}),\n tokensKnown: total.tokensKnown !== false && total.tokens.tokensKnown !== false,\n }\n}\n\nfunction costOf(total: Spend): PursuitNodeCost {\n const usdKnown = total.usdKnown !== false\n const estimated = total.usdEstimated\n const provenance: PursuitCostProvenance = usdKnown\n ? estimated === undefined || estimated === 0\n ? 'reported'\n : 'partial'\n : estimated === undefined\n ? 'unknown'\n : estimated >= total.usd\n ? 'estimated'\n : 'partial'\n return {\n usd: total.usd,\n usdKnown,\n ...(estimated !== undefined ? { usdEstimated: estimated } : {}),\n provenance,\n }\n}\n\n/** The platform block, or nothing at all when the node's spend names no box channel. */\nfunction platformOf(total: Spend): PursuitNodePlatform | undefined {\n if (total.boxMinutesProvenance === undefined) return undefined\n return {\n ...(total.boxMinutes !== undefined ? { boxMinutes: total.boxMinutes } : {}),\n boxMinutesKnown: total.boxMinutesKnown === true,\n provenance: total.boxMinutesProvenance,\n }\n}\n\nfunction timingOf(node: MutableNode): PursuitNodeTiming | undefined {\n if (node.startedAt === undefined) return undefined\n return {\n startedAt: node.startedAt,\n ...(node.firstOutputAt !== undefined ? { firstOutputAt: node.firstOutputAt } : {}),\n ...(node.firstTokenAt !== undefined ? { firstTokenAt: node.firstTokenAt } : {}),\n ...(node.settledAt !== undefined ? { settledAt: node.settledAt } : {}),\n ...(node.settledAt !== undefined\n ? { wallMs: Math.max(0, node.settledAt - node.startedAt) }\n : {}),\n }\n}\n\nfunction freezeRun(run: MutableRun, nodes: readonly MutableNode[]): PursuitRunProjection {\n const gaps = runSpendGaps(nodes)\n const { rootInference: _rootInference, started: _started, segments, ...rest } = run\n return Object.freeze({\n ...rest,\n ...(segments?.length\n ? { segments: Object.freeze(segments.map((segment) => Object.freeze(segment))) }\n : {}),\n targets: Object.freeze({ ...run.targets }),\n decisions: Object.freeze({ ...run.decisions }),\n totals: runTotals(run, nodes),\n ...(gaps.length > 0 ? { spendGaps: Object.freeze(gaps) } : {}),\n })\n}\n\nfunction freezeNode(node: MutableNode): PursuitNodeProjection {\n const {\n modelCalls,\n segments,\n reasoningTokens,\n startedAt: _startedAt,\n attemptIndex: _attemptIndex,\n ...rest\n } = node\n const total = nodeTotal(node)\n const timing = timingOf(node)\n return Object.freeze({\n ...rest,\n ...(segments?.length\n ? { segments: Object.freeze(segments.map((segment) => Object.freeze(segment))) }\n : {}),\n ...(modelCalls.length > 0 ? { modelCalls: Object.freeze([...modelCalls]) } : {}),\n ...(total !== undefined ? { usage: usageOf(total, reasoningTokens), cost: costOf(total) } : {}),\n ...(total !== undefined && platformOf(total) !== undefined\n ? { platform: platformOf(total) }\n : {}),\n ...(timing !== undefined ? { timing } : {}),\n })\n}\n\nfunction increment(\n target: Record<string, number>,\n key: RuntimeHookTarget | RuntimeDecisionKind,\n): void {\n target[key] = (target[key] ?? 0) + 1\n}\n\nfunction objectRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n}\n\n/** Read a journaled `Spend` without trusting the wire: a record missing the conserved channels is\n * not a zero-cost turn, it is an unparseable one, and it must not enter a total. */\nfunction spendField(value: Record<string, unknown> | undefined, key: string): Spend | undefined {\n const field = objectRecord(value?.[key])\n if (!field) return undefined\n const tokens = objectRecord(field.tokens)\n if (typeof field.usd !== 'number' || !Number.isFinite(field.usd)) return undefined\n if (!tokens || typeof tokens.input !== 'number' || typeof tokens.output !== 'number') {\n return undefined\n }\n return cloneSpend(field as unknown as Spend)\n}\n\n/** Read a journaled overspend without trusting the wire: one malformed channel drops the record,\n * so an unparseable entry is never reported as an overspend of some size. */\nfunction budgetViolationField(\n value: Record<string, unknown> | undefined,\n): BudgetViolation | undefined {\n const overspent = objectRecord(value?.budgetViolation)?.overspent\n if (!Array.isArray(overspent) || overspent.length === 0) return undefined\n const entries: BudgetOverspend[] = []\n for (const raw of overspent) {\n const entry = objectRecord(raw)\n const channel = stringField(entry, 'channel')\n const reserved = numberField(entry, 'reserved')\n const spent = numberField(entry, 'spent')\n if (channel === undefined || reserved === undefined || spent === undefined) return undefined\n entries.push({ channel: channel as BudgetOverspend['channel'], reserved, spent })\n }\n return { overspent: entries }\n}\n\nfunction stringField(value: Record<string, unknown> | undefined, key: string): string | undefined {\n const field = value?.[key]\n return typeof field === 'string' && field.length > 0 ? field : undefined\n}\n\nfunction numberField(value: Record<string, unknown> | undefined, key: string): number | undefined {\n const field = value?.[key]\n return typeof field === 'number' && Number.isFinite(field) ? field : undefined\n}\n\nfunction booleanField(\n value: Record<string, unknown> | undefined,\n key: string,\n): boolean | undefined {\n const field = value?.[key]\n return typeof field === 'boolean' ? field : undefined\n}\n","import { resolve } from 'node:path'\nimport { isRecord } from '@tangle-network/agent-core'\nimport type { NodeId } from '../runtime/supervise/types'\nimport { readCommittedJsonLines } from './jsonl-file'\nimport { FileObserverJournal } from './observer-journal'\nimport { spawnJournalRecordEvents } from './spawn-journal/record-events'\n\nexport interface DurableCoordinationStreamIdentity {\n readonly runId: string\n /** Exact owner ids present in the side-log, sorted for deterministic display. */\n readonly ownerIds: readonly string[]\n /** Records written before owner-scoped coordination identities were introduced. */\n readonly unscopedRecords: number\n readonly recordCount: number\n}\n\n/**\n * Identities discoverable from one `supervise({ runDir })` directory without\n * already knowing the root node or coordination run id stored inside it.\n */\nexport interface DurableSupervisionDiscovery {\n readonly runDir: string\n readonly observer?: { readonly path: string; readonly pursuitId: string }\n readonly spawnJournalPath: string\n readonly coordinationLogPath: string\n readonly roots: readonly NodeId[]\n /** `at` from each top-level root's `begin` record, index-aligned with `roots`. */\n readonly rootsBegunAt: readonly (string | null)[]\n readonly coordinationStreams: readonly DurableCoordinationStreamIdentity[]\n}\n\ntype SpawnJournalIdentityRecord = Readonly<\n Partial<Record<'kind' | 'root' | 'at' | 'event', unknown>>\n>\n\ntype CoordinationIdentityRecord = Readonly<Partial<Record<'runId' | 'ownerId', unknown>>>\n\n/**\n * Discover the stable identities recorded by Runtime's durable supervision\n * files. This is the developer-facing first step before calling\n * `FileSpawnJournal.loadTree(root)`, `loadSpawnForest(journal, root)`, or\n * `FileCoordinationLog.load(runId, ownerId)`.\n *\n * Missing files produce empty collections. A malformed committed JSONL record\n * still fails loud through the same parser used by the runtime; a torn final\n * append is ignored because it was never acknowledged as committed.\n */\nexport async function discoverDurableSupervisionRun(\n runDir: string,\n): Promise<DurableSupervisionDiscovery> {\n if (typeof runDir !== 'string' || runDir.trim().length === 0) {\n throw new TypeError('discoverDurableSupervisionRun: runDir must be a non-empty string')\n }\n\n const canonicalRunDir = resolve(runDir)\n const spawnJournalPath = `${canonicalRunDir}/spawn-journal.jsonl`\n const coordinationLogPath = `${canonicalRunDir}/coordination-log.jsonl`\n const nestedRoots = new Set<NodeId>()\n const rootsBegunAt = new Map<NodeId, string | null>()\n for await (const record of readCommittedJsonLines<SpawnJournalIdentityRecord>(spawnJournalPath, {\n allowMissing: true,\n })) {\n if (record.kind === 'begin') {\n if (typeof record.root !== 'string' || record.root.length === 0) {\n throw new Error(`${spawnJournalPath}: begin record has no non-empty string root identity`)\n }\n rootsBegunAt.set(record.root as NodeId, typeof record.at === 'string' ? record.at : null)\n continue\n }\n for (const event of spawnJournalRecordEvents(record)) {\n if (!isRecord(event) || event.kind !== 'spawned') continue\n if (!Object.hasOwn(event, 'ownedTreeRoot')) continue\n if (typeof event.ownedTreeRoot !== 'string' || event.ownedTreeRoot.length === 0) {\n throw new Error(\n `${spawnJournalPath}: spawned event ownedTreeRoot must be a non-empty string when present`,\n )\n }\n nestedRoots.add(event.ownedTreeRoot as NodeId)\n }\n }\n\n const streams = new Map<\n string,\n { owners: Set<string>; unscopedRecords: number; recordCount: number }\n >()\n for await (const record of readCommittedJsonLines<CoordinationIdentityRecord>(\n coordinationLogPath,\n { allowMissing: true },\n )) {\n if (typeof record.runId !== 'string' || record.runId.length === 0) {\n throw new Error(`${coordinationLogPath}: record has no non-empty string runId identity`)\n }\n const stream = streams.get(record.runId) ?? {\n owners: new Set<string>(),\n unscopedRecords: 0,\n recordCount: 0,\n }\n stream.recordCount += 1\n if (record.ownerId === undefined) {\n stream.unscopedRecords += 1\n } else if (typeof record.ownerId === 'string' && record.ownerId.length > 0) {\n stream.owners.add(record.ownerId)\n } else {\n throw new Error(`${coordinationLogPath}: ownerId must be a non-empty string when present`)\n }\n streams.set(record.runId, stream)\n }\n\n const coordinationStreams = [...streams.entries()]\n .sort(([left], [right]) => compareText(left, right))\n .map(([runId, stream]) =>\n Object.freeze({\n runId,\n ownerIds: Object.freeze([...stream.owners].sort(compareText)),\n unscopedRecords: stream.unscopedRecords,\n recordCount: stream.recordCount,\n }),\n )\n\n const observer = await FileObserverJournal.open(`${canonicalRunDir}/observer.jsonl`)\n const roots = [...rootsBegunAt.keys()].filter((root) => !nestedRoots.has(root)).sort(compareText)\n return Object.freeze({\n runDir: canonicalRunDir,\n ...(observer ? { observer: { path: observer.path, pursuitId: observer.pursuitId } } : {}),\n spawnJournalPath,\n coordinationLogPath,\n roots: Object.freeze(roots),\n rootsBegunAt: Object.freeze(roots.map((root) => rootsBegunAt.get(root) ?? null)),\n coordinationStreams: Object.freeze(coordinationStreams),\n })\n}\n\nfunction compareText(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAqUA,SAAgB,eAAe,SAAuD;CACpF,IAAI,QAAQ,WAAW,GACrB,MAAM,IAAI,UAAU,0DAA0D;CAEhF,MAAM,YAAY,QAAQ,EAAE,CAAE;CAC9B,MAAM,WAAW,sBAAsB,SAAS,SAAS;CACzD,MAAM,2BAAW,IAAI,IAA0B;CAC/C,MAAM,wBAAQ,IAAI,IAAyB;CAC3C,IAAI,aAAa;CACjB,IAAI,gBAAgB;CAEpB,KAAK,MAAM,UAAU,UAAU;EAC7B,MAAM,WAAW,OAAO,SAAS,OAAO;EACxC,IAAI,CAAC,UAAU,MAAM,IAAI,MAAM,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C;CAEA,MAAM,sBAAsB,CAAC,GAAG,QAAQ,QAAQ,CAAC,CAAC,CAC/C,MAAM,CAAC,OAAO,CAAC,WAAW,YAAY,MAAM,KAAK,CAAC,CAAC,CACnD,KAAK,CAAC,OAAO,YACZ,OAAO,OAAO;EACZ;EACA,UAAU,OAAO,OAAO,CAAC,GAAG,OAAO,MAAM,CAAC,CAAC,KAAK,WAAW,CAAC;EAC5D,iBAAiB,OAAO;EACxB,aAAa,OAAO;CACtB,CAAC,CACH;CAEF,MAAM,WAAW,MAAM,oBAAoB,KAAK,GAAG,gBAAgB,gBAAgB;CACnF,MAAM,QAAQ,CAAC,GAAG,aAAa,KAAK,CAAC,CAAC,CAAC,QAAQ,SAAS,CAAC,YAAY,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,WAAW;CAChG,OAAO,OAAO,OAAO;EACnB,QAAQ;EACR,GAAI,WAAW,EAAE,UAAU;GAAE,MAAM,SAAS;GAAM,WAAW,SAAS;EAAU,EAAE,IAAI,CAAC;EACvF;EACA;EACA,OAAO,OAAO,OAAO,KAAK;EAC1B,cAAc,OAAO,OAAO,MAAM,KAAK,SAAS,aAAa,IAAI,IAAI,KAAK,IAAI,CAAC;EAC/E,qBAAqB,OAAO,OAAO,mBAAmB;CACxD,CAAC;AACH;AAEA,SAAS,YAAY,MAAc,OAAuB;CACxD,OAAO,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;AAChD"}
@@ -1,7 +1,7 @@
1
1
  import { c as RetainedInteractiveAdmissionError, d as RetainedRunDispatchBindingError, f as RuntimeRunStateError, i as ConfigError, l as RetainedInteractiveBindingError, m as ValidationError$1, r as BackendTransportError, t as AgentEvalError$1, u as RetainedRunAdmissionError } from "./errors-AzSuGI23.js";
2
2
  import { A as ACCEPTED_RESULT_GRACE_MS, B as teardownExecutor, C as withTimeout, E as addResourceSpend, F as armDeadlineTimer, I as boundedChildDeadlineAt, L as checkInIdleMs, O as resourceTelemetry, P as ROOT_DEADLINE_REASON, R as isDeadlineAbortReason, S as unmeteredSpend, T as zeroTokenUsage, V as teardownSurfaces, _ as roundBoxMinutes, a as cloneSpend, b as throwAbort, c as errorMessage, d as isAbortError$1, f as isAsyncIterable, g as randomUuid, h as randomSuffix, i as chargedTokens, j as CHILD_DEADLINE_REASON, k as withBudgetResources, m as promptCacheTokenClasses, n as addSpend, o as cloneTokenUsage, p as mapWithConcurrency, r as addTokenUsage, s as deleteBoxSafe, t as abortError, v as sleep, w as zeroSpend, x as throwIfAborted, y as stringifySafe, z as singleFlightTeardown } from "./util-BX20UJ9X.js";
3
3
  import { t as runTaskQueue } from "./task-queue-DbpZAp6C.js";
4
- import { $ as workspaceCaptureWriter, A as closesCursorSlot, At as sandboxLeafOutputFromEvents, B as runtimeFailureRemediationSchema, Bt as createSandboxUsageLedger, Dt as createSandboxToolPartState, E as spawnJournalRecordEvents, Et as assertValidSpend, Ft as extractTransportEventIdentity, G as RetainedExecutionPendingError, Gt as sandboxTerminalUsageField, H as settlementFailureCause, Ht as isSandboxTerminalEvent, It as parseCanonicalTransportEvent, J as leafContinuationExecutionId, Jt as parseCodexUsageRecord, K as executorEvidenceWriter, L as reportedFailureCause, Lt as assertSandboxServedModel, M as outsideCursorNamespace, Mt as sandboxProgressEvents, N as FileObserverJournal, O as encodeResultBlob, Q as retainedExecutorSeamKey, R as runtimeFailureCause, Rt as canonicalSandboxUsageMode, St as newUsageTotals, T as appendSpawnEvents, U as BUDGET_CONTINUATION_TASK, Ut as notifySandboxEventObserver, V as runtimeProviderCode, W as DISPATCH_NOT_ADMITTED_CODE, Wt as sandboxEventServedBackend, Y as prepareRetainedExecutor, Yt as recordValue, Z as retainedExecutorContext, _t as credentialCommandExit, bt as createBudgetPool, dt as contentAddress, et as UNAVAILABLE_CODES, ft as contentRef, gt as hashJson, ht as executorFailureReason, it as unavailablePauseMs, j as insideCursorNamespace, jt as sandboxOutputMarker, k as SpawnEventIndex, mt as executorFailureInfra, n as createRootStreamSink, ot as unavailableSignalInText, pt as executorFailure, q as isProvisioningRefusal, r as nodeStreamFile, st as unavailableSignalOfFailure, tt as UNAVAILABLE_STATUSES, ut as traceRootWriter, vt as isCredentialRefusal, w as FileSpawnJournal, wt as spendFromUsageTotals, xt as meterUsageEvent, yt as BudgetReconcileFault, zt as createSandboxTurnEventCollector } from "./root-stream-To4qAc0e.js";
4
+ import { $ as UNAVAILABLE_CODES, A as insideCursorNamespace, At as sandboxOutputMarker, B as runtimeProviderCode, C as FileSpawnJournal, Ct as spendFromUsageTotals, D as encodeResultBlob, Et as createSandboxToolPartState, Ft as parseCanonicalTransportEvent, G as executorEvidenceWriter, H as BUDGET_CONTINUATION_TASK, Ht as notifySandboxEventObserver, I as reportedFailureCause, It as assertSandboxServedModel, J as prepareRetainedExecutor, Jt as recordValue, K as isProvisioningRefusal, L as runtimeFailureCause, Lt as canonicalSandboxUsageMode, M as FileObserverJournal, O as SpawnEventIndex, Pt as extractTransportEventIdentity, Q as workspaceCaptureWriter, Rt as createSandboxTurnEventCollector, T as spawnJournalRecordEvents, Tt as assertValidSpend, U as DISPATCH_NOT_ADMITTED_CODE, Ut as sandboxEventServedBackend, V as settlementFailureCause, Vt as isSandboxTerminalEvent, W as RetainedExecutionPendingError, Wt as sandboxTerminalUsageField, X as retainedExecutorContext, Z as retainedExecutorSeamKey, _t as isCredentialRefusal, at as unavailableSignalInText, bt as meterUsageEvent, dt as contentRef, et as UNAVAILABLE_STATUSES, ft as executorFailure, gt as credentialCommandExit, ht as hashJson, j as outsideCursorNamespace, jt as sandboxProgressEvents, k as closesCursorSlot, kt as sandboxLeafOutputFromEvents, lt as traceRootWriter, mt as executorFailureReason, n as createRootStreamSink, ot as unavailableSignalOfFailure, pt as executorFailureInfra, q as leafContinuationExecutionId, qt as parseCodexUsageRecord, r as nodeStreamFile, rt as unavailablePauseMs, ut as contentAddress, vt as BudgetReconcileFault, w as appendSpawnEvents, xt as newUsageTotals, yt as createBudgetPool, z as runtimeFailureRemediationSchema, zt as createSandboxUsageLedger } from "./root-stream-Bsh5WFcg.js";
5
5
  import { _ as errorText, b as resolveRedactor, d as detachedSnapshot, f as shareParsedStrings, g as errorProperty, h as errorHttpStatus, l as sha256, m as errMessage, p as causeChain, v as defaultRedactor } from "./jsonl-file-BBP9Dz9w.js";
6
6
  import { _ as agentHarness, a as concreteProfileModel, c as profileModelExecutionSettings, d as assertRouterAutoDeclaration, f as assertRouterAutoResponse, g as observedModelMatchesDeclared, h as observedModelHasSnapshot, l as profileProviderModel, m as mergeObservedModelIdentity, o as enforceTokenLimits, s as profileBridgeWireModel, t as assertExecutableAgentProfile, u as resolveRouterRetryPolicy } from "./model-policy-C-RGAUW4.js";
7
7
  import { B as sha256Bytes$1, H as hasControlCharacter, I as deepFreezeCandidate, M as verifyWorkspaceSnapshotArtifacts, U as nativeSystemPrompt, c as verifyAgentCandidateWorkspaceTree, g as verifiedArtifactChunks, o as readAgentCandidateWorkspaceArtifactFiles, s as verifyAgentCandidateWorkspaceArtifacts, t as assertSandboxProfileCompatibility, v as verifyAgentCandidateWorkspaceArchive } from "./sandbox-profile-compat-DRiz9kME.js";
@@ -12473,25 +12473,18 @@ async function startRetainedRunInEnvironment(options) {
12473
12473
  });
12474
12474
  }
12475
12475
  /**
12476
- * Bind an existing environment to the retained key it was created under.
12476
+ * Bind an existing environment to the retained key it was created under, from the metadata the
12477
+ * provider's own `get` or `create` record carries. One read, no listing.
12477
12478
  *
12478
- * The record `provider.get` just returned carries that environment's metadata, and it is the
12479
- * same record a metadata-filtered `list` would match. Reading it costs one request. Listing
12480
- * costs a walk of the caller's whole inventory, and on Tangle Sandbox that walk cannot finish
12481
- * past 2,000 sandboxes: the list route caps `offset` at 1,000 and answers 400. Measured
12482
- * 2026-10-04: 17 of 20 archived Discovery runs hit that 400 (46 times), each on a later turn in
12483
- * an environment that had already done work, and each attempt ended terminally. The listing remains for a provider whose
12484
- * `get` returns no metadata.
12479
+ * A metadata-filtered `list` used to stand in when that record had none. The only provider with
12480
+ * detached session control and a `list` (Tangle Sandbox) filters client-side, so the fallback
12481
+ * walked the caller's whole inventory: on Braid's ~68.5k-sandbox account, ~55 pages at ~1.4 s
12482
+ * each before admission (2026-10-28), and past 2,000 sandboxes the route answered 400
12483
+ * (2026-10-04). A record without metadata cannot prove ownership, so it is refused at once.
12485
12484
  */
12486
12485
  async function assertRetainedEnvironmentOwnership(provider, environment, idempotencyKey) {
12487
- const unbound = () => /* @__PURE__ */ new Error(`provider "${provider.name}" could not bind environment "${environment.id}" to its retained idempotency key`);
12488
- if (environment.metadata !== void 0) {
12489
- if (environment.metadata.retainedIdempotencyKey !== idempotencyKey) throw unbound();
12490
- return;
12491
- }
12492
- if (!provider.list) throw new Error(`provider "${provider.name}" cannot prove retained environment ownership by metadata`);
12493
- const matches = (await provider.list({ metadata: { retainedIdempotencyKey: idempotencyKey } })).filter((summary) => summary.id === environment.id && summary.provider === provider.name);
12494
- if (matches.length !== 1 || matches[0]?.metadata?.retainedIdempotencyKey !== idempotencyKey) throw unbound();
12486
+ if (environment.metadata === void 0) throw new Error(`provider "${provider.name}" returned environment "${environment.id}" without metadata, so it cannot prove retained environment ownership`);
12487
+ if (environment.metadata.retainedIdempotencyKey !== idempotencyKey) throw new Error(`provider "${provider.name}" could not bind environment "${environment.id}" to its retained idempotency key`);
12495
12488
  }
12496
12489
  async function dispatchRetainedRun(options) {
12497
12490
  const { environment, identity } = options;
@@ -21277,12 +21270,7 @@ async function checkpointOwnerWorkspace(scope, state) {
21277
21270
  * archive until the root's budget deadline aborted the rotation.
21278
21271
  */
21279
21272
  // src/runtime/supervise/retained-owner-evidence.ts
21280
- /**
21281
- * The workspace evidence of a retained owner's turns: which attempts hold a verified capture
21282
- * receipt, recapture before a source is reused, and evidence debt. An accepted turn whose capture
21283
- * fails owes its evidence; the node continues elsewhere, the source is never mutated, captures
21284
- * retry on backoff while the supervisor lives, and the release keeps a source still owed.
21285
- */
21273
+ /** Retained-owner capture receipts, source verification before reuse, and accepted-turn evidence debt. */
21286
21274
  /** One grouping for release and the evidence gate before another owner invocation. */
21287
21275
  function ownerWorkspaceAttempts(events, nodeId) {
21288
21276
  const attempts = [];
@@ -21388,12 +21376,7 @@ function ownerCaptureIdentity(attempt, owner) {
21388
21376
  node
21389
21377
  };
21390
21378
  }
21391
- /**
21392
- * Recover evidence before reuse. A source without a complete receipt is never mutated. A failed
21393
- * turn's capture failure is journaled as its evidence and the next invocation starts in another
21394
- * environment. An accepted turn's failure is evidence debt ({@link owePendingEvidence}): the turn
21395
- * stands, and neither the node nor its supervisor stops. Returns the sources whose capture failed.
21396
- */
21379
+ /** Recover evidence before reuse. Failed unverified turns keep their invocation; accepted turns owe evidence. */
21397
21380
  async function reconcileOwnerWorkspaceBeforeReuse(state, signal) {
21398
21381
  const { args } = state;
21399
21382
  const indebted = /* @__PURE__ */ new Set();
@@ -21414,13 +21397,16 @@ async function reconcileOwnerWorkspaceBeforeReuse(state, signal) {
21414
21397
  } catch (cause) {
21415
21398
  const failure = capturePendingMessage(attempt.executionId ?? args.nodeId, cause);
21416
21399
  if (executorFailureReason(attempt.result) === void 0) await owePendingEvidence(state, events, attempt, environmentId, failure);
21417
- else await state.context.onEvidence({
21418
- executionId: attempt.executionId,
21419
- environmentId,
21420
- controlRef: attempt.controlByEnvironment.get(environmentId),
21421
- ...ownerCaptureIdentity(attempt, args),
21422
- workspaceCaptureFailure: failure
21423
- });
21400
+ else {
21401
+ await state.context.onEvidence({
21402
+ executionId: attempt.executionId,
21403
+ environmentId,
21404
+ controlRef: attempt.controlByEnvironment.get(environmentId),
21405
+ ...ownerCaptureIdentity(attempt, args),
21406
+ workspaceCaptureFailure: failure
21407
+ });
21408
+ throw new RetainedExecutionPendingError(new Error(failure, { cause }), "unobservable");
21409
+ }
21424
21410
  indebted.add(environmentId);
21425
21411
  state.forceNewSession = true;
21426
21412
  }
@@ -29701,4 +29687,4 @@ async function noWinner(settled, rejection) {
29701
29687
  }
29702
29688
  export { abandonScopeRetainedOwnerInvocation as $, gateFactoryOnDeliverable as $n, providerAttemptEvidence as $r, persistHarnessTranscript as $t, noteScopeOwnerPlannedExecution as A, isPeerMailEnvelope as An, terminateProcessTreeAndConfirm as Ar, TERMINAL_DECISIONS as At, deriveNodeExecutionIdentity as B, HarnessTurnFailedError as Bn, sandboxActProfileMaterialization as Br, resolveAgentEnvironmentProvider as Bt, interactiveAdmissionSeamKey as C, createInbox as Cn, bridgeRuntimeAttachmentsKey as Cr, createSteerableSandboxSession as Ct, recoverRetainedInteractiveRun as D, PEER_MAIL_WIRE_KEY as Dn, runWorktreeHarness as Dr, createSandboxForSpec as Dt, reconnectRetainedInteractiveRun as E, DEFAULT_PEER_MAIL_LIMITS as En, runSettledCommand as Er, readPromptOptions as Et, coordinationProfileToolPrefix as F, createActivityLog as Fn, fullProfileMaterialization as Fr, runCodeMode as Ft, meterRuntimeOwnedProviderAttempt as G, undispatchedCredentialExit as Gn, attestRuntimeOwnedScopeOwner as Gr, recoverRetainedRun as Gt, queueOf as H, causedByPartialFailure as Hn, unsupportedProfileDimensions as Hr, LEAF_CONTINUATION_TASK as Ht, providerVisibleProfile as I, readWorkerProgress as In, profileMaterializationAxes$1 as Ir, toolResultText as It, recordScopeOwnerPause as J, SeatChainExhaustedError as Jn, finalizeRuntimeOwnedPendingExecutor as Jr, retainedCreateMaterial as Jt, recordScopeOwnerBarrenPause as K, upstreamUnavailableSignal as Kn, authoredAgentIdentity as Kr, startRetainedRun as Kt, runtimeGraphMetadataKey as L, isLiveNodeStatus as Ln, promptControlProfileMaterialization as Lr, createRouterTranscript as Lt, restoreScopeOwnerAcceptedExecution as M, peerMailVerbNames as Mn, assertProfileMaterializes as Mr, codeModeArguments as Mt, scopeOwnerExecutorNodeContext as N, taskToPrompt$1 as Nn, controlProfileMaterialization as Nr, codeModeModelOutput as Nt, startRetainedInteractiveRun as O, claimsAuthority as On, LOCAL_HARNESSES as Or, createSandboxLineage as Ot, coordinationMcpAlias as P, DEFAULT_STALL_AFTER_MS as Pn, defineProfileMaterializationContract as Pr, createCodeModeTools as Pt, resolveSpawnResourcePaths as Q, CheckUnavailableError as Qn, newExecutionAttemptId as Qr, harnessTranscriptArtifact as Qt, settledToIteration as R, isTerminalNodeStatus as Rn, promptModelProfileMaterialization as Rr, routerBrain as Rt, workerTraceAnalysisStore as S, INBOX_RECEIPT_KEY as Sn, signalAbortError as Sr, DEFAULT_SANDBOX_STEERING_MAX_TURNS as St, readWorkerInteractiveBinding as T, AUTHORITY_MARKERS as Tn, defaultRunCommand as Tr, assertBoxlessPromptOptions as Tt, rollingDispatch as U, classifyDriverFailure as Un, worktreeCliProfileMaterialization as Ur, providerAsSandboxClient as Ut, freeSlots as V, abandonablePending as Vn, sandboxProfileMaterialization as Vr, providerAsExecutor as Vt, meterRuntimeOwnedAccounting as W, summarizeDriverAttempts as Wn, attestRuntimeOwnedPendingExecutor as Wr, reconnectRetainedRun as Wt, scopeRetainedOwnerResourceReader as X, seatExecutionProfile as Xn, knownExecutionBindingReceipt as Xr, environmentGone as Xt, prepareScopeRetainedOwnerSeatSwitch as Y, authoredSeatStages as Yn, inheritRuntimeOwnedExecutorAttestation as Yr, destroyInteractiveEnvironment as Yt, environmentReader as Z, subscriptionUsageLimitSignal as Zn, knownMaterializationReceipt as Zr, captureHarnessTranscript as Zt, withDriverExecutor as _, promptFromAgentTurnInput as _i, loopEventToOtelSpan as _n, readCodexRolloutSession as _r, createExecutorRegistry as _t, assertRunParking as a, runtimeOwnedPendingExecutorMaterialization as ai, createWorktreeCliExecutor as an, bestComposite as ar, scopeRetainedOwnerTurnEnded as at, isTraceAnalysisStore as b, sanitizeKnowledgeReadinessReport as bn, linkAbort as br, createExecutor as bt, sleepScopeWait as c, unknownMaterializationReceipt as ci, createPropagatingTraceEmitter as cn, failedItems as cr, noteScopeRetainedOwnerCoordination as ct, runFinalizer as d, isRuntimeFlowBrain as di, buildLoopSpanNodes as dn, bridgeModelRouteRefusal as dr, scopeRetainedOwnerContext as dt, recordRuntimeOwnedDriveHarnessProviderEvidence as ei, readHarnessTranscript as en, gateOnDeliverable as er, consumeScopeRetainedOwnerResult as et, runTree as f, runtimeFlowAgent as fi, buildRuntimeEventOtelSpans as fn, priceTokens as fr, scopeRetainedOwnerJournalRoot as ft, isDriverSpec as g, awaitAbortable$1 as gi, generateSpanId as gn, harnessUsageIsEmpty as gr, InMemorySpawnJournal as gt, driverExecutorFactory as h, readSandboxOutcome as hi, flatOtelSpan as hn, createCodexRolloutStoreReader as hr, InMemoryResultBlobStore as ht, RunParkedError as i, runtimeOwnedExecutorProviderEvidence as ii, openSlotGroup as in, admitContinuationPolicy as ir, beginScopeRetainedOwnerDrive as it, recordScopeOwnerMaterialization as j, peerMailTools as jn, assertProfileMaterialization as jr, defaultSelectWinner as jt, beginScopeOwnerAttempt as k, createPeerMailbox as kn, harnessInvocation as kr, acquireSandbox as kt, withRunParking as l, executableAgentProfileSnapshot as li, readTraceContextFromEnv as ln, isFiniteNumber as lr, bindScopeRetainedOwnerEnvironmentId as lt, driverChild as m, projectSandboxOutcome as mi, createOtelExporter as mn, addHarnessUsage as mr, materializeTreeView as mt, createSupervisor as n, runtimeOwnedExecutorExecutionBinding as ni, retainHarnessTranscript as nn, verdictFromJudgeScore as nr, scopeRetainedOwnerPriorSpend as nt, bindScopeParkingDrain as o, runtimeOwnedScopeOwnerRuntime as oi, createInPlaceCliExecutor as on, checkVerdictOf as or, reconcileScopeRetainedOwnerEnvironment as ot, createRootHandle as p, runtimeFlowBrain as pi, createOpenInferenceFileExporter as pn, ROUTER_PRICE_SOURCE as pr, loadSpawnForest as pt, recordScopeOwnerDriverAttempt as q, SeatChain as qn, authoredProfileDigest as qr, startRetainedRunInEnvironment as qt, assertResumeLimits as r, runtimeOwnedExecutorMaterialization as ri, createWorkerSlots as rn, CONTINUATIONS_DIR as rr, scopeRetainedOwnerResult as rt, readRunParking as s, unknownExecutionBindingReceipt as si, WORKER_TRACE_PROPAGATION as sn, createContinuationKeeper as sr, scopeRetainedOwnerRestorePoint as st, DEFAULT_MAX_DEPTH as t, runtimeOwnedDriveHarnessProviderEvidence as ti, resolveHarnessTranscriptCapture as tn, mapExecutorResult as tr, prepareScopeRetainedOwnerTask as tt, bestDelivered as u, executableAgentSpecSnapshot as ui, buildLoopOtelSpans as un, bridgeAdmissionRefusal as ur, bindScopeRetainedOwnerProvider as ut, createScope as v, promptOptionsFromAgentTurnInput as vi, createRuntimeEventCollector as vn, createPushTraceSource as vr, bindReusableExecutorExecutionId as vt, attachWorker as w, failPendingAfter as wn, bridgeStopSignalKey as wr, runAgentRounds as wt, parseWorkerToolTraceArtifact as x, sanitizeRuntimeStreamEvent as xn, runAbortable as xr, snapshotExecutorConfig as xt, replaySpawnTree as y, providerMessageText as yi, createRuntimeStreamEventCollector as yn, RunCancellationReason as yr, captureReusableExecutorConfig as yt, assertRecursiveReservationPolicy as z, DriverAttemptsExhaustedError as zn, renderUnsupported as zr, createAgentEnvironmentProviderRegistry as zt };
29703
29689
 
29704
- //# sourceMappingURL=supervisor-ByarsrwH.js.map
29690
+ //# sourceMappingURL=supervisor-B8beIEqH.js.map