@tangle-network/agent-runtime 0.153.1 → 0.153.2

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 (93) hide show
  1. package/dist/{activation-DKxQsHiO.js → activation-Bbic0THc.js} +3 -3
  2. package/dist/{activation-DKxQsHiO.js.map → activation-Bbic0THc.js.map} +1 -1
  3. package/dist/agent.d.ts +1 -1
  4. package/dist/agent.js +3 -3
  5. package/dist/{analyst-loop-B2kTHKNh.js → analyst-loop-Bouu53-l.js} +2 -2
  6. package/dist/{analyst-loop-B2kTHKNh.js.map → analyst-loop-Bouu53-l.js.map} +1 -1
  7. package/dist/analyst-loop.js +1 -1
  8. package/dist/{authoring-Tk2xFys0.js → authoring-CcVhJ1lP.js} +2 -2
  9. package/dist/{authoring-Tk2xFys0.js.map → authoring-CcVhJ1lP.js.map} +1 -1
  10. package/dist/candidate-execution/index.js +4 -4
  11. package/dist/{candidate-execution-CB9RJbbJ.js → candidate-execution-DYOB1juU.js} +4 -4
  12. package/dist/{candidate-execution-CB9RJbbJ.js.map → candidate-execution-DYOB1juU.js.map} +1 -1
  13. package/dist/{conversation-D64WyWrK.js → conversation-BHMwAiMo.js} +27 -12
  14. package/dist/{conversation-D64WyWrK.js.map → conversation-BHMwAiMo.js.map} +1 -1
  15. package/dist/conversation.d.ts +1 -1
  16. package/dist/conversation.js +1 -1
  17. package/dist/durable.d.ts +1 -1
  18. package/dist/durable.js +3 -6
  19. package/dist/durable.js.map +1 -1
  20. package/dist/{environment-provider-D_MXw3jK.js → environment-provider-3eCszBEm.js} +134 -29
  21. package/dist/environment-provider-3eCszBEm.js.map +1 -0
  22. package/dist/environment-provider.js +1 -1
  23. package/dist/{graph-M0Qr4863.js → graph-CIh2HDmH.js} +3 -3
  24. package/dist/{graph-M0Qr4863.js.map → graph-CIh2HDmH.js.map} +1 -1
  25. package/dist/{improvement-cycle-CDxlGQGE.js → improvement-cycle-GCDSsTN6.js} +6 -6
  26. package/dist/{improvement-cycle-CDxlGQGE.js.map → improvement-cycle-GCDSsTN6.js.map} +1 -1
  27. package/dist/{index-Dlz7ejRx.d.ts → index-DLn9WI-f.d.ts} +4 -3
  28. package/dist/{index-BihHgUAI.d.ts → index-lMADJLfq.d.ts} +2 -2
  29. package/dist/{index-LQfgFJoX.d.ts → index-rxVSm9-z.d.ts} +5 -3
  30. package/dist/index.d.ts +4 -4
  31. package/dist/index.js +13 -13
  32. package/dist/intelligence.js +6 -6
  33. package/dist/jsonl-file-CDfsCI5s.js +59 -0
  34. package/dist/jsonl-file-CDfsCI5s.js.map +1 -0
  35. package/dist/kernel.d.ts +1 -1
  36. package/dist/kernel.js +10 -10
  37. package/dist/{knowledge-DM-i40b9.js → knowledge-CaY53BW2.js} +5 -5
  38. package/dist/{knowledge-DM-i40b9.js.map → knowledge-CaY53BW2.js.map} +1 -1
  39. package/dist/knowledge.d.ts +1 -1
  40. package/dist/knowledge.js +1 -1
  41. package/dist/{loop-runner-bin-D-BW51yr.d.ts → loop-runner-bin-BwPqxKhR.d.ts} +2 -2
  42. package/dist/{loop-runner-bin-pD5WJuqJ.js → loop-runner-bin-Dw43kB_-.js} +4 -4
  43. package/dist/{loop-runner-bin-pD5WJuqJ.js.map → loop-runner-bin-Dw43kB_-.js.map} +1 -1
  44. package/dist/loop-runner-bin.d.ts +1 -1
  45. package/dist/loop-runner-bin.js +1 -1
  46. package/dist/{materialization-Bo6j3Hg9.js → materialization-Dl9J8ek4.js} +27 -2
  47. package/dist/materialization-Dl9J8ek4.js.map +1 -0
  48. package/dist/mcp/bin.js +3 -3
  49. package/dist/mcp/index.d.ts +1 -1
  50. package/dist/mcp/index.js +5 -5
  51. package/dist/{openai-tools-CWBywy-e.js → openai-tools-C4XKuK4t.js} +2 -2
  52. package/dist/{openai-tools-CWBywy-e.js.map → openai-tools-C4XKuK4t.js.map} +1 -1
  53. package/dist/{prepare-C3eFd3UA.js → prepare-C5tI-H4o.js} +2 -2
  54. package/dist/{prepare-C3eFd3UA.js.map → prepare-C5tI-H4o.js.map} +1 -1
  55. package/dist/{protected-model-port-Dn2b6peS.js → protected-model-port-DHDKNeY7.js} +2 -2
  56. package/dist/{protected-model-port-Dn2b6peS.js.map → protected-model-port-DHDKNeY7.js.map} +1 -1
  57. package/dist/{runtime-RY_rvv7t.js → runtime--Jsq8JCC.js} +46 -28
  58. package/dist/runtime--Jsq8JCC.js.map +1 -0
  59. package/dist/{sandbox-events-DMijDq2p.js → sandbox-events-BVjstFgb.js} +23 -3
  60. package/dist/sandbox-events-BVjstFgb.js.map +1 -0
  61. package/dist/{spawn-journal-CLguaA2A.js → spawn-journal-BLnveCRS.js} +30 -65
  62. package/dist/spawn-journal-BLnveCRS.js.map +1 -0
  63. package/dist/{stream-agent-turn-D6HoaRPV.js → stream-agent-turn-DYi8ymsU.js} +4 -5
  64. package/dist/stream-agent-turn-DYi8ymsU.js.map +1 -0
  65. package/dist/{structural-rollout-P1YxFRfl.js → structural-rollout-D7V-HgXJ.js} +23 -9
  66. package/dist/structural-rollout-D7V-HgXJ.js.map +1 -0
  67. package/dist/{supervise-BezbzKiJ.js → supervise-k_8VOASb.js} +38 -74
  68. package/dist/supervise-k_8VOASb.js.map +1 -0
  69. package/dist/{supervisor-DBVlPONC.js → supervisor-CMZsJ7Wn.js} +90 -266
  70. package/dist/supervisor-CMZsJ7Wn.js.map +1 -0
  71. package/dist/testing.d.ts +1 -1
  72. package/dist/testing.js +12 -12
  73. package/dist/{top-app-tKo9OrON.js → top-app-3rYfFPTW.js} +4 -62
  74. package/dist/top-app-3rYfFPTW.js.map +1 -0
  75. package/dist/tui/bin.js +1 -1
  76. package/dist/tui/index.d.ts +0 -1
  77. package/dist/tui/index.js +1 -1
  78. package/dist/{util-Bncw0o_F.js → util-D6ZEuBMi.js} +32 -2
  79. package/dist/util-D6ZEuBMi.js.map +1 -0
  80. package/dist/{workspace-archive-Dm73lTfB.js → workspace-archive-B9ui4rrR.js} +2 -2
  81. package/dist/{workspace-archive-Dm73lTfB.js.map → workspace-archive-B9ui4rrR.js.map} +1 -1
  82. package/package.json +4 -4
  83. package/dist/environment-provider-D_MXw3jK.js.map +0 -1
  84. package/dist/materialization-Bo6j3Hg9.js.map +0 -1
  85. package/dist/runtime-RY_rvv7t.js.map +0 -1
  86. package/dist/sandbox-events-DMijDq2p.js.map +0 -1
  87. package/dist/spawn-journal-CLguaA2A.js.map +0 -1
  88. package/dist/stream-agent-turn-D6HoaRPV.js.map +0 -1
  89. package/dist/structural-rollout-P1YxFRfl.js.map +0 -1
  90. package/dist/supervise-BezbzKiJ.js.map +0 -1
  91. package/dist/supervisor-DBVlPONC.js.map +0 -1
  92. package/dist/top-app-tKo9OrON.js.map +0 -1
  93. package/dist/util-Bncw0o_F.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"top-app-tKo9OrON.js","names":[],"sources":["../src/tui/top-model.ts","../src/tui/top-app.ts"],"sourcesContent":["/**\n * The read side of the supervisor-run TUI: turn the on-disk run layout into one `TopSnapshot`, and\n * render that snapshot to an ANSI frame.\n *\n * This module never derives a run path itself. Every directory and per-worker file it reads comes\n * from `../runtime/supervise/run-layout` — the same module the writers use — so the reader cannot\n * drift from the layout the way an independently-versioned copy of the contract would.\n *\n * Extracted from the `loops` repo (`src/top-model.ts`), which held a hand-joined copy of the\n * layout. Rendering is deliberately unchanged: raw ANSI, zero dependencies.\n *\n * This is the OPERATOR view: what is on disk right now, for a human watching a workspace. It\n * carries no model-call identity, so its per-supervisor totals cannot be joined with root stream\n * events without double counting. A client that needs one execution's totals reads\n * `projectPursuit` from `../durable` instead.\n *\n * @experimental\n */\n\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'\nimport { basename, join, resolve } from 'node:path'\nimport {\n legacySupervisorRunsRoot,\n safeWorkerFile,\n supervisorRunsRoot,\n supervisorWorkersDir,\n} from '../runtime/supervise/run-layout'\n\nexport interface TopSnapshot {\n readonly root: string\n readonly generatedAt: number\n readonly supervisors: SupervisorView[]\n /** `partial` when at least one discovered source could not be read completely. */\n readonly completeness: TopSnapshotCompleteness\n /** One bounded entry per skipped or partially read source; empty when complete. */\n readonly diagnostics: ReadonlyArray<TopSnapshotDiagnostic>\n /** Run directories found under the runs roots, readable or not. */\n readonly discovered: number\n /** Run directories whose state.json parsed into a valid supervisor view. */\n readonly loaded: number\n}\n\nexport type TopSnapshotCompleteness = 'complete' | 'partial'\n\nexport type TopSnapshotDiagnosticSource =\n | 'supervisor-state'\n | 'journal'\n | 'progress'\n | 'worker-tail'\n\nexport type TopSnapshotDiagnosticReason =\n | 'unreadable'\n | 'partial-json'\n | 'invalid-state'\n | 'missing'\n\n/**\n * One skipped or partially read snapshot source. `path` is relative to the run directory and\n * never carries file contents, so a diagnostic is safe to show or log without leaking run data.\n */\nexport interface TopSnapshotDiagnostic {\n readonly source: TopSnapshotDiagnosticSource\n readonly runId?: string\n readonly path: string\n readonly reason: TopSnapshotDiagnosticReason\n}\n\nexport interface SupervisorBase {\n readonly id: string\n readonly status: string\n readonly task: string\n readonly workspaceDir: string\n readonly budget: number\n readonly verifyCmd?: string\n readonly workerModel?: string\n readonly driverModel?: string\n readonly verdict?: string\n readonly progress?: string\n readonly startedAt?: string\n readonly completedAt?: string\n readonly maxSandboxes?: number\n readonly maxLifetimeSeconds?: number\n readonly idleTimeoutSeconds?: number\n readonly maxUsd?: number\n readonly maxDepth?: number\n}\n\nexport interface SupervisorView extends SupervisorBase {\n readonly stateDir: string\n readonly resultSpentUsd?: number\n readonly resultSpentTokens?: number\n readonly workers: WorkerView[]\n readonly progressTail: string[]\n readonly journalTail: TopJournalEvent[]\n readonly driverSpend: SpendStats\n readonly totals: SupervisorTotals\n}\n\nexport interface WorkerView {\n readonly id: string\n readonly label: string\n readonly cwd?: string\n readonly eventFile?: string\n readonly parent?: string\n readonly runtime?: string\n readonly status: 'running' | 'done' | 'down' | 'cancelled'\n readonly verdict?: string\n readonly infra?: boolean\n readonly startedAt?: string\n readonly endedAt?: string\n readonly latencyMs: number\n readonly budget?: BudgetStats\n readonly spend: SpendStats\n readonly metered: SpendStats\n readonly liveTail: string[]\n readonly outRef?: string\n readonly reason?: string\n}\n\nexport interface SupervisorTotals {\n readonly workers: number\n readonly running: number\n readonly done: number\n readonly down: number\n readonly cancelled: number\n readonly inFlight: number\n readonly settled: number\n readonly tokensInput: number\n readonly tokensOutput: number\n readonly tokensTotal: number\n readonly usd: number\n readonly latencyMs: number\n readonly workerLatency: Distribution\n}\n\nexport interface Distribution {\n readonly n: number\n readonly min: number\n readonly median: number\n readonly p90: number\n readonly max: number\n}\n\nexport interface BudgetStats {\n readonly maxIterations?: number\n readonly maxTokens?: number\n readonly maxUsd?: number\n}\n\nexport interface SpendStats {\n readonly iterations: number\n readonly tokensInput: number\n readonly tokensOutput: number\n readonly usd: number\n readonly ms: number\n}\n\nexport type TopJournalEvent =\n | {\n readonly kind: 'spawned'\n readonly id: string\n readonly parent?: string\n readonly label?: string\n readonly budget?: unknown\n readonly runtime?: string\n readonly seq?: number\n readonly at?: string\n }\n | {\n readonly kind: 'settled'\n readonly id: string\n readonly status?: string\n readonly outRef?: string\n readonly verdict?: unknown\n readonly spent?: unknown\n readonly infra?: boolean\n readonly seq?: number\n readonly at?: string\n }\n | {\n readonly kind: 'cancelled'\n readonly id: string\n readonly reason?: string\n readonly seq?: number\n readonly at?: string\n }\n | {\n readonly kind: 'metered'\n readonly id: string\n readonly spend?: unknown\n readonly seq?: number\n readonly at?: string\n }\n\ninterface SupervisorState extends SupervisorBase {\n readonly result?: {\n readonly spentUsd?: number\n readonly spentTokens?: number\n }\n}\n\ninterface MutableWorker {\n id: string\n label: string\n cwd?: string\n eventFile?: string\n parent?: string\n runtime?: string\n status: 'running' | 'done' | 'down' | 'cancelled'\n verdict?: string\n infra?: boolean\n startedAt?: string\n endedAt?: string\n budget?: BudgetStats\n spend: SpendStats\n metered: SpendStats\n liveTail: string[]\n outRef?: string\n reason?: string\n}\n\ninterface WorkerEventTail {\n readonly file: string\n readonly lines: string[]\n readonly cwd?: string\n}\n\n/** A diagnostic before its run id is attached; `loadTopSnapshot` adds `runId`. */\ninterface SourceDiagnostic {\n readonly source: TopSnapshotDiagnosticSource\n readonly path: string\n readonly reason: TopSnapshotDiagnosticReason\n}\n\n/**\n * What one snapshot source read produced: the value it could recover, and the bounded diagnostics\n * the read raised. Every reader returns this one shape, so the loader folds them identically.\n */\ninterface SourceRead<T> {\n readonly value: T\n readonly diagnostics: readonly SourceDiagnostic[]\n}\n\nexport interface RenderOptions {\n readonly width?: number\n readonly height?: number\n readonly color?: boolean\n readonly selectedSupervisorId?: string\n readonly selectedWorkerId?: string\n readonly focus?: 'supervisors' | 'workers'\n readonly mode?: 'overview' | 'detail' | 'log'\n readonly notice?: string\n readonly steerInput?: {\n readonly active: boolean\n readonly value: string\n readonly workerLabel?: string\n }\n}\n\nexport interface RenderTarget {\n readonly row: number\n readonly kind: 'supervisor' | 'worker'\n readonly id: string\n readonly supervisorId?: string\n}\n\nexport interface RenderedTopFrame {\n readonly frame: string\n readonly targets: RenderTarget[]\n}\n\nconst emptySpend: SpendStats = { iterations: 0, tokensInput: 0, tokensOutput: 0, usd: 0, ms: 0 }\n// Width accounting depends on stripping SGR sequences, which begin with a literal ESC. Matching\n// the control character is the point of an ANSI-aware renderer, not an accident.\n// biome-ignore lint/suspicious/noControlCharactersInRegex: SGR sequences begin with ESC\nconst ansiPattern = /\\x1b\\[[0-9;?]*[ -/]*[@-~]/g\n\nconst colors = {\n reset: '\\x1b[0m',\n dim: '\\x1b[2m',\n bold: '\\x1b[1m',\n red: '\\x1b[31m',\n green: '\\x1b[32m',\n yellow: '\\x1b[33m',\n blue: '\\x1b[34m',\n magenta: '\\x1b[35m',\n cyan: '\\x1b[36m',\n white: '\\x1b[37m',\n inverse: '\\x1b[7m',\n}\n\n/**\n * Read every supervisor run under one workspace into a single point-in-time snapshot.\n *\n * Pure with respect to the process: it only reads, and it never throws for a writer mid-append.\n * An unreadable or half-written source is still skipped — an operator view must survive a live\n * writer — but every skip is reported as one bounded `TopSnapshotDiagnostic`, so a client can\n * tell a removed run from a partial read. `now` is injectable so elapsed time is deterministic\n * under test.\n */\nexport function loadTopSnapshot(rootDir: string, now = Date.now()): TopSnapshot {\n const root = resolve(rootDir)\n const supervisors: SupervisorView[] = []\n const diagnostics: TopSnapshotDiagnostic[] = []\n let discovered = 0\n const report = (runId: string, sources: readonly SourceDiagnostic[]): void => {\n for (const source of sources) diagnostics.push({ ...source, runId })\n }\n // `.loops` is the pre-rename state dir; runs already on disk there stay visible.\n for (const runsRoot of [supervisorRunsRoot(root), legacySupervisorRunsRoot(root)]) {\n if (!existsSync(runsRoot)) continue\n for (const entry of readdirSync(runsRoot)) {\n const dir = join(runsRoot, entry)\n if (!isDirectory(dir)) continue\n discovered += 1\n const state = readSupervisorState(dir)\n report(entry, state.diagnostics)\n if (!state.value) continue\n const journal = readJournal(dir)\n const progress = readProgressTail(dir, 8)\n const workerEvents = readWorkerEventTails(supervisorWorkersDir(dir), 8)\n report(entry, [...journal.diagnostics, ...progress.diagnostics, ...workerEvents.diagnostics])\n supervisors.push(\n buildSupervisorView(\n state.value,\n dir,\n journal.value,\n progress.value,\n now,\n workerEvents.value,\n ),\n )\n }\n }\n supervisors.sort((a, b) => String(b.startedAt ?? '').localeCompare(String(a.startedAt ?? '')))\n return {\n root,\n generatedAt: now,\n supervisors,\n completeness: diagnostics.length === 0 ? 'complete' : 'partial',\n diagnostics,\n discovered,\n loaded: supervisors.length,\n }\n}\n\n/**\n * The journal file a run dir actually carries. `createFileRunContext` — this repo's own durable\n * writer — names it `spawn-journal.jsonl`; `journal.jsonl` is the retired bare-event file older\n * runs left behind. First existing name wins; a reader that knew only the retired name would show\n * zero workers for every current run.\n */\nconst journalFileNames = ['spawn-journal.jsonl', 'journal.jsonl'] as const\n\nfunction readJournal(eventDir: string): SourceRead<TopJournalEvent[]> {\n const path = journalFileNames.find((candidate) => existsSync(join(eventDir, candidate)))\n if (!path) return { value: [], diagnostics: [] }\n const read = readSourceFile(join(eventDir, path), 'journal', path)\n if (read.value === undefined) return { value: [], diagnostics: read.diagnostics }\n const out: TopJournalEvent[] = []\n let partial = false\n for (const line of read.value.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed) continue\n try {\n const parsed = JSON.parse(trimmed) as Record<string, unknown>\n const event = (parsed.event ?? parsed) as Record<string, unknown>\n if (isSpawnEvent(event)) out.push(event)\n } catch {\n // A corrupt line is expected while the writer is mid-append; keep the lines that parsed.\n partial = true\n }\n }\n return {\n value: out,\n diagnostics: partial ? [{ source: 'journal', path, reason: 'partial-json' }] : [],\n }\n}\n\nfunction buildSupervisorView(\n state: SupervisorState,\n stateDir: string,\n events: readonly TopJournalEvent[],\n progressTail: readonly string[],\n now: number,\n workerEventTails = new Map<string, WorkerEventTail>(),\n): SupervisorView {\n const workers = new Map<string, MutableWorker>()\n let driverSpend = emptySpend\n // `state.json` and the spawn journal are written by DIFFERENT producers, and their ids need not\n // agree: the journal's root is the runtime's `runId`, which defaults to a literal unrelated to\n // the supervisor id the state file records. Recover the journal's own root from its parentless\n // root spawn, and treat EITHER id as the root everywhere. Checking only `state.id` — which the\n // metered/settled/cancelled branches used to do — manufactures a phantom worker named after the\n // runId that never settles, sorts first as RUNNING, and silently captures every steer and cancel.\n const journalRootId = events.find(\n (event) => event.kind === 'spawned' && !event.parent && event.label === 'root',\n )?.id\n const isRoot = (id: string): boolean => id === state.id || id === journalRootId\n\n for (const event of events) {\n if (event.kind === 'spawned') {\n if (isRoot(event.id) || (!event.parent && event.label === 'root')) continue\n const worker = ensureWorker(workers, event.id, event.label ?? event.id)\n worker.label = event.label ?? worker.label\n if (event.parent) worker.parent = event.parent\n if (event.runtime) worker.runtime = event.runtime\n worker.status = 'running'\n if (event.at) worker.startedAt = event.at\n const budget = parseBudget(event.budget)\n if (budget) worker.budget = budget\n continue\n }\n\n if (event.kind === 'settled') {\n if (isRoot(event.id)) continue\n const worker = ensureWorker(workers, event.id, event.id)\n worker.status = event.status === 'down' ? 'down' : 'done'\n if (event.at) worker.endedAt = event.at\n if (event.outRef) worker.outRef = event.outRef\n if (event.infra !== undefined) worker.infra = event.infra\n const verdict = describeVerdict(event.verdict)\n if (verdict) worker.verdict = verdict\n worker.spend = addSpend(worker.spend, parseSpend(event.spent))\n continue\n }\n\n if (event.kind === 'cancelled') {\n if (isRoot(event.id)) continue\n const worker = ensureWorker(workers, event.id, event.id)\n worker.status = 'cancelled'\n if (event.at) worker.endedAt = event.at\n if (event.reason) worker.reason = event.reason\n continue\n }\n\n if (event.kind === 'metered') {\n const spend = parseSpend(event.spend)\n if (isRoot(event.id)) {\n driverSpend = addSpend(driverSpend, spend)\n } else {\n const worker = ensureWorker(workers, event.id, event.id)\n worker.metered = addSpend(worker.metered, spend)\n }\n }\n }\n\n const workerViews = [...workers.values()]\n .map((worker) => {\n // Tails are keyed by file stem, which the writer put through `safeWorkerFile`; a label\n // carrying characters that stem strips would otherwise never find its own events.\n const tail =\n workerEventTails.get(worker.label) ??\n workerEventTails.get(safeWorkerFile(worker.label)) ??\n workerEventTails.get(worker.id)\n worker.liveTail = tail?.lines ?? []\n if (tail?.cwd) worker.cwd = tail.cwd\n if (tail?.file) worker.eventFile = tail.file\n return finalizeWorker(worker, now)\n })\n .sort((a, b) => compareWorker(a, b))\n\n const totals = supervisorTotals(state, workerViews, driverSpend, now)\n return {\n id: state.id,\n stateDir,\n status: state.status,\n task: state.task,\n workspaceDir: state.workspaceDir,\n budget: state.budget,\n ...(state.verifyCmd ? { verifyCmd: state.verifyCmd } : {}),\n ...(state.workerModel ? { workerModel: state.workerModel } : {}),\n ...(state.driverModel ? { driverModel: state.driverModel } : {}),\n ...(state.verdict ? { verdict: state.verdict } : {}),\n ...(state.progress ? { progress: state.progress } : {}),\n ...(state.startedAt ? { startedAt: state.startedAt } : {}),\n ...(state.completedAt ? { completedAt: state.completedAt } : {}),\n ...(state.maxSandboxes !== undefined ? { maxSandboxes: state.maxSandboxes } : {}),\n ...(state.maxLifetimeSeconds !== undefined\n ? { maxLifetimeSeconds: state.maxLifetimeSeconds }\n : {}),\n ...(state.idleTimeoutSeconds !== undefined\n ? { idleTimeoutSeconds: state.idleTimeoutSeconds }\n : {}),\n ...(state.maxUsd !== undefined ? { maxUsd: state.maxUsd } : {}),\n ...(state.maxDepth !== undefined ? { maxDepth: state.maxDepth } : {}),\n ...(state.result?.spentUsd !== undefined ? { resultSpentUsd: state.result.spentUsd } : {}),\n ...(state.result?.spentTokens !== undefined\n ? { resultSpentTokens: state.result.spentTokens }\n : {}),\n workers: workerViews,\n progressTail: [...progressTail],\n journalTail: events.slice(-12),\n driverSpend,\n totals,\n }\n}\n\n/** Render one snapshot to an ANSI frame. Use this when nothing needs to be clickable. */\nexport function renderTopFrame(snapshot: TopSnapshot, options: RenderOptions = {}): string {\n return renderTopFrameWithLayout(snapshot, options).frame\n}\n\n/**\n * Render one snapshot, returning the frame together with the row→entity map a mouse click resolves\n * against. The layout is the only thing that knows which row is which run or worker, so emitting it\n * alongside the text is what keeps click handling out of the renderer.\n */\nexport function renderTopFrameWithLayout(\n snapshot: TopSnapshot,\n options: RenderOptions = {},\n): RenderedTopFrame {\n const width = Math.max(88, options.width ?? 128)\n const height = Math.max(24, options.height ?? 42)\n const color = options.color ?? false\n const focus = options.focus ?? 'supervisors'\n const mode = options.mode ?? 'overview'\n const selectedSupervisor = selectSupervisor(snapshot, options.selectedSupervisorId)\n const selectedWorker = selectedSupervisor\n ? selectWorker(selectedSupervisor, options.selectedWorkerId)\n : undefined\n const targets: RenderTarget[] = []\n const lines: string[] = []\n\n const push = (line = '', target?: Omit<RenderTarget, 'row'>) => {\n if (lines.length >= height) return\n if (target) targets.push({ row: lines.length, ...target })\n lines.push(fitAnsi(line, width))\n }\n\n const aggregate = aggregateSnapshot(snapshot)\n push(\n `${paint('SUPERVISOR TOP', 'bold', color)} ${paint(snapshot.root, 'dim', color)} ` +\n `runs ${aggregate.supervisors} workers ${aggregate.workers} live ${aggregate.running} ` +\n `done ${aggregate.done} down ${aggregate.down} ` +\n `${formatMoney(aggregate.usd)} tok ${formatTokens(aggregate.tokensInput)}/${formatTokens(aggregate.tokensOutput)}`,\n )\n push(\n `${paint('keys', 'dim', color)} up/down select left/right run tab focus enter detail o overview l log s steer a shell c cancel mouse q quit`,\n )\n if (options.notice) push(paint(options.notice, 'yellow', color))\n if (snapshot.completeness === 'partial')\n push(\n paint(\n `partial snapshot: ${snapshot.diagnostics.length} source${\n snapshot.diagnostics.length === 1 ? '' : 's'\n } skipped or truncated; runs loaded ${snapshot.loaded}/${snapshot.discovered}`,\n 'yellow',\n color,\n ),\n )\n if (options.steerInput?.active) push(renderSteerInput(options.steerInput, width, color))\n push(rule(width, color))\n\n if (snapshot.supervisors.length === 0) {\n if (snapshot.discovered > 0) {\n push(paint('NO READABLE SUPERVISORS', 'yellow', color))\n push(\n `${snapshot.discovered} run director${snapshot.discovered === 1 ? 'y' : 'ies'} found under ${supervisorRunsRoot(snapshot.root)}, none readable`,\n )\n } else {\n push(paint('NO SUPERVISORS', 'yellow', color))\n push(`No run state under ${supervisorRunsRoot(snapshot.root)}`)\n }\n push(\n `A run appears here once its driver writes state.json; re-point with: agent-runtime-top <root>`,\n )\n return { frame: `${lines.join('\\n')}\\n`, targets }\n }\n\n push(sectionTitle('SUPERVISORS', focus === 'supervisors', color))\n push(\n ` id status workers spend tok in/out latency task`,\n )\n for (const supervisor of snapshot.supervisors.slice(0, 9)) {\n const selected = supervisor.id === selectedSupervisor?.id\n const status = statusText(supervisor.status, color)\n const pointer = selected ? paint('>', 'cyan', color) : ' '\n const rowFocus = selected && focus === 'supervisors' ? 'inverse' : undefined\n const workerSummary = `${supervisor.totals.running}/${supervisor.totals.workers} live`\n const task = compact(supervisor.task, 34)\n const line =\n `${pointer} ${pad(supervisor.id, 21)} ${pad(status, 12)} ${pad(workerSummary, 13)} ` +\n `${pad(formatMoney(supervisor.totals.usd), 12)} ` +\n `${pad(`${formatTokens(supervisor.totals.tokensInput)}/${formatTokens(supervisor.totals.tokensOutput)}`, 16)} ` +\n `${pad(formatDuration(supervisor.totals.latencyMs), 12)} ${task}`\n push(rowFocus ? paint(line, rowFocus, color) : line, { kind: 'supervisor', id: supervisor.id })\n }\n\n if (!selectedSupervisor) return { frame: `${lines.join('\\n')}\\n`, targets }\n\n push()\n push(sectionTitle(`WORKERS ${selectedSupervisor.id}`, focus === 'workers', color))\n push(\n ` id state runtime latency cost tok in/out score detail`,\n )\n for (const worker of selectedSupervisor.workers.slice(0, 12)) {\n const selected = worker.id === selectedWorker?.id\n const pointer = selected ? paint('>', 'cyan', color) : ' '\n const rowFocus = selected && focus === 'workers' ? 'inverse' : undefined\n const score = worker.verdict ?? (worker.status === 'done' ? 'done' : worker.status)\n const detail = worker.reason ?? worker.outRef ?? worker.parent ?? ''\n const spend = totalSpend(worker)\n const line =\n `${pointer} ${pad(worker.label, 12)} ${pad(statusText(worker.status, color), 12)} ` +\n `${pad(worker.runtime ?? '-', 10)} ${pad(formatDuration(worker.latencyMs), 12)} ` +\n `${pad(formatMoney(spend.usd), 11)} ` +\n `${pad(`${formatTokens(spend.tokensInput)}/${formatTokens(spend.tokensOutput)}`, 16)} ` +\n `${pad(compact(score, 9), 10)} ${compact(detail, 30)}`\n push(rowFocus ? paint(line, rowFocus, color) : line, {\n kind: 'worker',\n id: worker.id,\n supervisorId: selectedSupervisor.id,\n })\n }\n if (selectedSupervisor.workers.length === 0) push(' no workers spawned yet')\n\n push()\n push(sectionTitle('OBSERVABILITY', false, color))\n for (const line of renderStatusBars(selectedSupervisor, width, color)) push(line)\n push()\n for (const line of renderCostBars(selectedSupervisor, width, color)) push(line)\n push()\n for (const line of renderTokenBars(selectedSupervisor, width, color)) push(line)\n push()\n for (const line of renderLatencyHistogram(selectedSupervisor, width, color)) push(line)\n\n push()\n if (mode === 'log') {\n push(sectionTitle('JOURNAL TAIL', false, color))\n for (const line of renderJournalTail(selectedSupervisor, width, color)) push(line)\n } else {\n push(sectionTitle(mode === 'detail' ? 'DETAIL' : 'RUN SUMMARY', false, color))\n for (const line of renderDetail(selectedSupervisor, selectedWorker, mode, width, color))\n push(line)\n }\n\n return { frame: `${lines.join('\\n')}\\n`, targets }\n}\n\nfunction ensureWorker(\n workers: Map<string, MutableWorker>,\n id: string,\n label: string,\n): MutableWorker {\n const existing = workers.get(id)\n if (existing) return existing\n const created: MutableWorker = {\n id,\n label,\n status: 'running',\n spend: emptySpend,\n metered: emptySpend,\n liveTail: [],\n }\n workers.set(id, created)\n return created\n}\n\nfunction finalizeWorker(worker: MutableWorker, now: number): WorkerView {\n const startMs = parseTime(worker.startedAt)\n const endMs = parseTime(worker.endedAt) ?? (worker.status === 'running' ? now : startMs)\n const latencyMs = startMs !== undefined && endMs !== undefined ? Math.max(0, endMs - startMs) : 0\n return {\n id: worker.id,\n label: worker.label,\n ...(worker.cwd ? { cwd: worker.cwd } : {}),\n ...(worker.eventFile ? { eventFile: worker.eventFile } : {}),\n ...(worker.parent ? { parent: worker.parent } : {}),\n ...(worker.runtime ? { runtime: worker.runtime } : {}),\n status: worker.status,\n ...(worker.verdict ? { verdict: worker.verdict } : {}),\n ...(worker.infra !== undefined ? { infra: worker.infra } : {}),\n ...(worker.startedAt ? { startedAt: worker.startedAt } : {}),\n ...(worker.endedAt ? { endedAt: worker.endedAt } : {}),\n latencyMs,\n ...(worker.budget ? { budget: worker.budget } : {}),\n spend: worker.spend,\n metered: worker.metered,\n liveTail: worker.liveTail,\n ...(worker.outRef ? { outRef: worker.outRef } : {}),\n ...(worker.reason ? { reason: worker.reason } : {}),\n }\n}\n\nfunction supervisorTotals(\n state: SupervisorState,\n workers: readonly WorkerView[],\n driverSpend: SpendStats,\n now: number,\n): SupervisorTotals {\n const workerSpends = workers.map(totalSpend)\n const tokenInput = sum(workerSpends.map((spend) => spend.tokensInput)) + driverSpend.tokensInput\n const tokenOutput =\n sum(workerSpends.map((spend) => spend.tokensOutput)) + driverSpend.tokensOutput\n const computedUsd = sum(workerSpends.map((spend) => spend.usd)) + driverSpend.usd\n const usd = computedUsd > 0 ? computedUsd : (state.result?.spentUsd ?? 0)\n const started = parseTime(state.startedAt)\n const completed = parseTime(state.completedAt)\n const latencyMs = started !== undefined ? Math.max(0, (completed ?? now) - started) : 0\n const latencies = workers.map((worker) => worker.latencyMs).filter((ms) => ms > 0)\n return {\n workers: workers.length,\n running: workers.filter((worker) => worker.status === 'running').length,\n done: workers.filter((worker) => worker.status === 'done').length,\n down: workers.filter((worker) => worker.status === 'down').length,\n cancelled: workers.filter((worker) => worker.status === 'cancelled').length,\n inFlight: workers.filter((worker) => worker.status === 'running').length,\n settled: workers.filter((worker) => worker.status !== 'running').length,\n tokensInput: tokenInput,\n tokensOutput: tokenOutput,\n tokensTotal: tokenInput + tokenOutput,\n usd,\n latencyMs,\n workerLatency: distribution(latencies),\n }\n}\n\nfunction aggregateSnapshot(snapshot: TopSnapshot): {\n supervisors: number\n workers: number\n running: number\n done: number\n down: number\n usd: number\n tokensInput: number\n tokensOutput: number\n} {\n return {\n supervisors: snapshot.supervisors.length,\n workers: sum(snapshot.supervisors.map((supervisor) => supervisor.totals.workers)),\n running: sum(snapshot.supervisors.map((supervisor) => supervisor.totals.running)),\n done: sum(snapshot.supervisors.map((supervisor) => supervisor.totals.done)),\n down: sum(snapshot.supervisors.map((supervisor) => supervisor.totals.down)),\n usd: sum(snapshot.supervisors.map((supervisor) => supervisor.totals.usd)),\n tokensInput: sum(snapshot.supervisors.map((supervisor) => supervisor.totals.tokensInput)),\n tokensOutput: sum(snapshot.supervisors.map((supervisor) => supervisor.totals.tokensOutput)),\n }\n}\n\nfunction compareWorker(a: WorkerView, b: WorkerView): number {\n const aStart = parseTime(a.startedAt) ?? 0\n const bStart = parseTime(b.startedAt) ?? 0\n if (a.status === 'running' && b.status !== 'running') return -1\n if (b.status === 'running' && a.status !== 'running') return 1\n return aStart - bStart || a.label.localeCompare(b.label)\n}\n\nfunction totalSpend(worker: WorkerView): SpendStats {\n return addSpend(worker.spend, worker.metered)\n}\n\nfunction addSpend(a: SpendStats, b: SpendStats): SpendStats {\n return {\n iterations: a.iterations + b.iterations,\n tokensInput: a.tokensInput + b.tokensInput,\n tokensOutput: a.tokensOutput + b.tokensOutput,\n usd: a.usd + b.usd,\n ms: a.ms + b.ms,\n }\n}\n\nfunction parseSpend(value: unknown): SpendStats {\n if (!isRecord(value)) return emptySpend\n const tokens = isRecord(value.tokens) ? value.tokens : {}\n return {\n iterations: numberValue(value.iterations),\n tokensInput: numberValue(tokens.input),\n tokensOutput: numberValue(tokens.output),\n usd: numberValue(value.usd),\n ms: numberValue(value.ms),\n }\n}\n\nfunction parseBudget(value: unknown): BudgetStats | undefined {\n if (!isRecord(value)) return undefined\n const budget: BudgetStats = {\n ...(typeof value.maxIterations === 'number' ? { maxIterations: value.maxIterations } : {}),\n ...(typeof value.maxTokens === 'number' ? { maxTokens: value.maxTokens } : {}),\n ...(typeof value.maxUsd === 'number' ? { maxUsd: value.maxUsd } : {}),\n }\n return Object.keys(budget).length ? budget : undefined\n}\n\nfunction describeVerdict(value: unknown): string | undefined {\n if (!isRecord(value)) return undefined\n if (typeof value.valid === 'boolean') return value.valid ? 'valid' : 'invalid'\n if (typeof value.score === 'number') return `score ${value.score.toFixed(2)}`\n return undefined\n}\n\nfunction distribution(values: readonly number[]): Distribution {\n if (values.length === 0) return { n: 0, min: 0, median: 0, p90: 0, max: 0 }\n const sorted = [...values].sort((a, b) => a - b)\n return {\n n: sorted.length,\n min: sorted[0] ?? 0,\n median: percentile(sorted, 0.5),\n p90: percentile(sorted, 0.9),\n max: sorted[sorted.length - 1] ?? 0,\n }\n}\n\nfunction percentile(sorted: readonly number[], p: number): number {\n if (sorted.length === 0) return 0\n const idx = Math.min(sorted.length - 1, Math.max(0, Math.ceil(sorted.length * p) - 1))\n return sorted[idx] ?? 0\n}\n\nfunction renderStatusBars(supervisor: SupervisorView, width: number, color: boolean): string[] {\n const total = Math.max(1, supervisor.totals.workers)\n const barWidth = Math.max(12, Math.min(28, width - 58))\n return [\n `status ` +\n `${pad('running', 9)} ${bar(supervisor.totals.running, total, barWidth, '#', color, 'yellow')} ${supervisor.totals.running}` +\n ` ${pad('done', 5)} ${bar(supervisor.totals.done, total, barWidth, '#', color, 'green')} ${supervisor.totals.done}` +\n ` ${pad('down', 5)} ${bar(supervisor.totals.down, total, barWidth, '#', color, 'red')} ${supervisor.totals.down}`,\n ]\n}\n\nfunction renderCostBars(supervisor: SupervisorView, width: number, color: boolean): string[] {\n const workers = supervisor.workers\n .map((worker) => ({ worker, spend: totalSpend(worker) }))\n .sort((a, b) => b.spend.usd - a.spend.usd)\n .slice(0, 6)\n const maxUsd = Math.max(\n 0.000001,\n ...workers.map((row) => row.spend.usd),\n supervisor.driverSpend.usd,\n )\n const out = [\n `cost total ${formatMoney(supervisor.totals.usd)} driver ${formatMoney(supervisor.driverSpend.usd)}`,\n ]\n const barWidth = Math.max(18, Math.min(46, width - 38))\n for (const row of workers) {\n out.push(\n ` ${pad(row.worker.label, 12)} ${bar(row.spend.usd, maxUsd, barWidth, '$', color, 'magenta')} ${formatMoney(row.spend.usd)}`,\n )\n }\n if (workers.length === 0) out.push(' no worker cost yet')\n return out\n}\n\nfunction renderTokenBars(supervisor: SupervisorView, width: number, color: boolean): string[] {\n const rows = supervisor.workers\n .map((worker) => ({\n worker,\n spend: totalSpend(worker),\n total: totalSpend(worker).tokensInput + totalSpend(worker).tokensOutput,\n }))\n .sort((a, b) => b.total - a.total)\n .slice(0, 6)\n const maxTokens = Math.max(\n 1,\n ...rows.map((row) => row.total),\n supervisor.driverSpend.tokensInput + supervisor.driverSpend.tokensOutput,\n )\n const out = [\n `tokens total in ${formatTokens(supervisor.totals.tokensInput)} / out ${formatTokens(supervisor.totals.tokensOutput)} ` +\n `driver ${formatTokens(supervisor.driverSpend.tokensInput)}/${formatTokens(supervisor.driverSpend.tokensOutput)}`,\n ]\n const barWidth = Math.max(18, Math.min(46, width - 44))\n for (const row of rows) {\n out.push(\n ` ${pad(row.worker.label, 12)} ${stackedTokenBar(row.spend.tokensInput, row.spend.tokensOutput, maxTokens, barWidth, color)} ` +\n `${formatTokens(row.spend.tokensInput)}/${formatTokens(row.spend.tokensOutput)}`,\n )\n }\n if (rows.length === 0) out.push(' no worker tokens yet')\n return out\n}\n\nfunction renderLatencyHistogram(\n supervisor: SupervisorView,\n width: number,\n color: boolean,\n): string[] {\n const values = supervisor.workers.map((worker) => worker.latencyMs).filter((value) => value > 0)\n const summary = supervisor.totals.workerLatency\n const out = [\n `latency n=${summary.n} min ${formatDuration(summary.min)} p50 ${formatDuration(summary.median)} ` +\n `p90 ${formatDuration(summary.p90)} max ${formatDuration(summary.max)}`,\n ]\n if (values.length === 0) {\n out.push(' no latency samples yet')\n return out\n }\n const bins = histogram(values, 6)\n const maxCount = Math.max(1, ...bins.map((bin) => bin.count))\n const barWidth = Math.max(18, Math.min(48, width - 34))\n for (const bin of bins) {\n out.push(\n ` ${pad(`${formatDuration(bin.min)}-${formatDuration(bin.max)}`, 15)} ` +\n `${bar(bin.count, maxCount, barWidth, '#', color, 'blue')} ${bin.count}`,\n )\n }\n return out\n}\n\nfunction renderDetail(\n supervisor: SupervisorView,\n worker: WorkerView | undefined,\n mode: 'overview' | 'detail' | 'log',\n width: number,\n color: boolean,\n): string[] {\n if (mode === 'detail' && worker) {\n const spend = totalSpend(worker)\n return [\n `worker ${paint(worker.label, 'bold', color)} (${worker.id}) ${statusText(worker.status, color)} latency ${formatDuration(worker.latencyMs)}`,\n `tokens in/out ${formatTokens(spend.tokensInput)}/${formatTokens(spend.tokensOutput)} cost ${formatMoney(spend.usd)} iterations ${spend.iterations}`,\n `parent ${worker.parent ?? '-'} runtime ${worker.runtime ?? '-'} out ${worker.outRef ?? '-'}${worker.infra ? ' infra' : ''}`,\n `cwd ${compact(worker.cwd ?? '-', width - 5)}`,\n `events ${compact(worker.eventFile ?? '-', width - 8)}`,\n ...(worker.reason ? [`reason ${compact(worker.reason, width - 7)}`] : []),\n ...renderWorkerTail(worker, width, color),\n ]\n }\n\n const caps = [\n supervisor.maxSandboxes !== undefined ? `boxes ${supervisor.maxSandboxes}` : undefined,\n supervisor.maxUsd !== undefined ? `max ${formatMoney(supervisor.maxUsd)}` : undefined,\n supervisor.maxDepth !== undefined ? `depth ${supervisor.maxDepth}` : undefined,\n supervisor.maxLifetimeSeconds !== undefined\n ? `ttl ${supervisor.maxLifetimeSeconds}s`\n : undefined,\n ].filter((value): value is string => value !== undefined)\n return [\n `task ${compact(supervisor.task, width - 7)}`,\n `workspace ${compact(supervisor.workspaceDir, width - 12)}`,\n `verify ${compact(supervisor.verifyCmd ?? '-', width - 9)}`,\n `models worker ${supervisor.workerModel ?? '-'} / driver ${supervisor.driverModel ?? '-'} caps ${caps.join(' | ') || '-'}`,\n `progress ${compact(supervisor.progress ?? supervisor.verdict ?? supervisor.status, width - 10)}`,\n ]\n}\n\nfunction renderJournalTail(supervisor: SupervisorView, width: number, color: boolean): string[] {\n if (supervisor.journalTail.length === 0) return [' no journal events yet']\n return supervisor.journalTail.map((event) => {\n const at = event.at ? formatClock(event.at) : '--:--:--'\n if (event.kind === 'spawned')\n return ` ${at} ${paint('spawn', 'yellow', color)} ${pad(event.label ?? event.id, 16)} ${event.id}`\n if (event.kind === 'settled') {\n const spend = parseSpend(event.spent)\n return ` ${at} ${statusText(event.status ?? 'settled', color)} ${pad(event.id, 18)} ${formatMoney(spend.usd)} ${formatTokens(spend.tokensInput)}/${formatTokens(spend.tokensOutput)}`\n }\n if (event.kind === 'metered') {\n const spend = parseSpend(event.spend)\n return ` ${at} ${paint('meter', 'cyan', color)} ${pad(event.id, 18)} ${formatMoney(spend.usd)} ${formatTokens(spend.tokensInput)}/${formatTokens(spend.tokensOutput)}`\n }\n return ` ${at} ${paint('cancel', 'red', color)} ${pad(event.id, 18)} ${compact(event.reason ?? '', width - 32)}`\n })\n}\n\nfunction renderWorkerTail(worker: WorkerView, width: number, color: boolean): string[] {\n if (worker.liveTail.length === 0) return ['live events: none recorded yet']\n return [\n 'live events:',\n ...worker.liveTail\n .slice(-5)\n .map((line) => ` ${paint(compact(formatWorkerEvent(line), width - 2), 'dim', color)}`),\n ]\n}\n\nfunction renderSteerInput(\n input: NonNullable<RenderOptions['steerInput']>,\n width: number,\n color: boolean,\n): string {\n const target = input.workerLabel ?? '-'\n const value = compact(input.value, Math.max(10, width - target.length - 14))\n return `${paint('steer', 'cyan', color)} ${target} > ${value}${paint('_', 'inverse', color)}`\n}\n\nfunction formatWorkerEvent(line: string): string {\n try {\n const parsed = JSON.parse(line) as Record<string, unknown>\n const at = typeof parsed.at === 'string' ? formatClock(parsed.at) : '--:--:--'\n const kind = typeof parsed.kind === 'string' ? parsed.kind : 'event'\n if (kind === 'progress')\n return `${at} progress iter ${numberValue(parsed.iteration)} ${String(parsed.phase ?? '')}`\n if (kind === 'started') return `${at} started ${String(parsed.cwd ?? '')}`\n if (kind === 'message') {\n const state = parsed.queued === true ? 'queued' : 'sent'\n const source =\n typeof parsed.source === 'string' && parsed.source.length > 0 ? `${parsed.source} ` : ''\n const message =\n typeof parsed.message === 'string' && parsed.message.length > 0 ? ` ${parsed.message}` : ''\n return `${at} ${source}steer ${state} delivered=${String(parsed.delivered)}${message}`\n }\n if (kind === 'verify') {\n return `${at} verify passed=${String(parsed.passed)} exit=${String(parsed.exitCode ?? '-')}${evidenceSnippet(parsed.outputTail, 160)}`\n }\n if (kind === 'finished') {\n const branch = typeof parsed.branch === 'string' ? ` branch=${parsed.branch}` : ''\n const files = typeof parsed.filesChanged === 'number' ? ` files=${parsed.filesChanged}` : ''\n const tests =\n typeof parsed.testPassed === 'boolean' ? ` tests=${String(parsed.testPassed)}` : ''\n return `${at} finished passed=${String(parsed.passed)} patchBytes=${numberValue(parsed.patchBytes)}${files}${tests}${branch}${evidenceSnippet(parsed.evidence, 220)}`\n }\n if (kind === 'error') return `${at} error ${String(parsed.error ?? '')}`\n return `${at} ${kind}`\n } catch {\n return line\n }\n}\n\n/** One-line the settle evidence / verify tail a worker event carries so the\n * failure is legible in the tail view (the full block stays in the ndjson). */\nfunction evidenceSnippet(value: unknown, max: number): string {\n if (typeof value !== 'string') return ''\n const oneLine = value.replace(/\\s+/g, ' ').trim()\n return oneLine ? ` :: ${compact(oneLine, max)}` : ''\n}\n\nfunction histogram(\n values: readonly number[],\n count: number,\n): Array<{ min: number; max: number; count: number }> {\n const min = Math.min(...values)\n const max = Math.max(...values)\n if (min === max) return [{ min, max, count: values.length }]\n const step = (max - min) / count\n return Array.from({ length: count }, (_, index) => {\n const low = min + step * index\n const high = index === count - 1 ? max : min + step * (index + 1)\n const binCount = values.filter(\n (value) => value >= low && (index === count - 1 ? value <= high : value < high),\n ).length\n return { min: low, max: high, count: binCount }\n }).filter((bin) => bin.count > 0)\n}\n\nfunction bar(\n value: number,\n max: number,\n width: number,\n ch: string,\n color: boolean,\n colorName: keyof typeof colors,\n): string {\n const filled = Math.max(0, Math.min(width, Math.round((value / Math.max(max, 0.000001)) * width)))\n const text = ch.repeat(filled).padEnd(width, '.')\n return paint(text, colorName, color)\n}\n\nfunction stackedTokenBar(\n input: number,\n output: number,\n max: number,\n width: number,\n color: boolean,\n): string {\n const inputWidth = Math.round((input / Math.max(max, 1)) * width)\n const outputWidth = Math.round((output / Math.max(max, 1)) * width)\n const clippedInput = Math.min(width, inputWidth)\n const clippedOutput = Math.min(width - clippedInput, outputWidth)\n const rest = Math.max(0, width - clippedInput - clippedOutput)\n return `${paint('#'.repeat(clippedInput), 'cyan', color)}${paint('+'.repeat(clippedOutput), 'green', color)}${'.'.repeat(rest)}`\n}\n\nfunction sectionTitle(title: string, focused: boolean, color: boolean): string {\n const text = focused ? `[${title}]` : title\n return paint(text, focused ? 'cyan' : 'bold', color)\n}\n\nfunction statusText(status: string, color: boolean): string {\n if (['completed', 'done', 'delivered', 'valid'].includes(status))\n return paint(status.toUpperCase(), 'green', color)\n if (['failed', 'down', 'cancelled', 'invalid', 'error'].includes(status))\n return paint(status.toUpperCase(), 'red', color)\n if (['running', 'spawned', 'settled'].includes(status))\n return paint(status.toUpperCase(), 'yellow', color)\n return paint(status.toUpperCase(), 'white', color)\n}\n\nfunction selectSupervisor(\n snapshot: TopSnapshot,\n requested: string | undefined,\n): SupervisorView | undefined {\n if (requested) {\n const found = snapshot.supervisors.find((supervisor) => supervisor.id === requested)\n if (found) return found\n }\n return snapshot.supervisors[0]\n}\n\nfunction selectWorker(\n supervisor: SupervisorView,\n requested: string | undefined,\n): WorkerView | undefined {\n if (requested) {\n const found = supervisor.workers.find((worker) => worker.id === requested)\n if (found) return found\n }\n return supervisor.workers[0]\n}\n\n/**\n * Read one source file under a run directory. An absent file is not a defect on its own — the\n * writer may not have reached it yet — so it reads as `undefined` with no diagnostic; only a\n * failed read raises one. `path` stays run-relative and never carries file contents.\n */\nfunction readSourceFile(\n file: string,\n source: TopSnapshotDiagnosticSource,\n path: string,\n): SourceRead<string | undefined> {\n if (!existsSync(file)) return { value: undefined, diagnostics: [] }\n try {\n return { value: readFileSync(file, 'utf8'), diagnostics: [] }\n } catch {\n return { value: undefined, diagnostics: [{ source, path, reason: 'unreadable' }] }\n }\n}\n\nfunction tailLines(raw: string | undefined, maxLines: number): string[] {\n if (raw === undefined) return []\n return raw.trim().split('\\n').filter(Boolean).slice(-maxLines)\n}\n\nfunction readProgressTail(dir: string, maxLines: number): SourceRead<string[]> {\n const path = 'progress.ndjson'\n const read = readSourceFile(join(dir, path), 'progress', path)\n return { value: tailLines(read.value, maxLines), diagnostics: read.diagnostics }\n}\n\nfunction readWorkerEventTails(\n dir: string,\n maxLines: number,\n): SourceRead<Map<string, WorkerEventTail>> {\n const out = new Map<string, WorkerEventTail>()\n if (!existsSync(dir)) return { value: out, diagnostics: [] }\n const workersDir = basename(dir)\n let entries: string[]\n try {\n entries = readdirSync(dir)\n } catch {\n return {\n value: out,\n diagnostics: [{ source: 'worker-tail', path: workersDir, reason: 'unreadable' }],\n }\n }\n const diagnostics: SourceDiagnostic[] = []\n for (const entry of entries) {\n // `<label>.inbox.ndjson` is the down-leg steer queue, not this worker's control-event log.\n if (!entry.endsWith('.ndjson') || entry.endsWith('.inbox.ndjson')) continue\n const file = join(dir, entry)\n const read = readSourceFile(file, 'worker-tail', join(workersDir, entry))\n diagnostics.push(...read.diagnostics)\n const lines = tailLines(read.value, maxLines)\n const cwd = workerCwd(lines)\n out.set(entry.slice(0, -'.ndjson'.length), { file, lines, ...(cwd ? { cwd } : {}) })\n }\n return { value: out, diagnostics }\n}\n\nfunction workerCwd(lines: readonly string[]): string | undefined {\n for (const line of [...lines].reverse()) {\n try {\n const parsed = JSON.parse(line) as Record<string, unknown>\n if (parsed.kind === 'started' && typeof parsed.cwd === 'string' && parsed.cwd.trim())\n return parsed.cwd\n } catch {\n // Corrupt worker events are rendered raw in the detail tail.\n }\n }\n return undefined\n}\n\nfunction readSupervisorState(dir: string): SourceRead<SupervisorState | undefined> {\n const path = 'state.json'\n const read = readSourceFile(join(dir, path), 'supervisor-state', path)\n if (read.diagnostics.length > 0) return { value: undefined, diagnostics: read.diagnostics }\n if (read.value === undefined)\n return {\n value: undefined,\n diagnostics: [{ source: 'supervisor-state', path, reason: 'missing' }],\n }\n let parsed: Partial<SupervisorState>\n try {\n parsed = JSON.parse(read.value) as Partial<SupervisorState>\n } catch {\n return {\n value: undefined,\n diagnostics: [{ source: 'supervisor-state', path, reason: 'partial-json' }],\n }\n }\n if (!isSupervisorState(parsed))\n return {\n value: undefined,\n diagnostics: [{ source: 'supervisor-state', path, reason: 'invalid-state' }],\n }\n return { value: parsed, diagnostics: [] }\n}\n\nfunction isSupervisorState(value: Partial<SupervisorState> | undefined): value is SupervisorState {\n return (\n value !== undefined &&\n typeof value.id === 'string' &&\n typeof value.status === 'string' &&\n typeof value.task === 'string' &&\n typeof value.workspaceDir === 'string' &&\n typeof value.budget === 'number'\n )\n}\n\nfunction isSpawnEvent(value: Record<string, unknown>): value is TopJournalEvent {\n return (\n (value.kind === 'spawned' && typeof value.id === 'string') ||\n (value.kind === 'settled' && typeof value.id === 'string') ||\n (value.kind === 'cancelled' && typeof value.id === 'string') ||\n (value.kind === 'metered' && typeof value.id === 'string')\n )\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n\nfunction isDirectory(path: string): boolean {\n try {\n return statSync(path).isDirectory()\n } catch {\n return false\n }\n}\n\nfunction numberValue(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0\n}\n\nfunction parseTime(value: string | undefined): number | undefined {\n if (!value) return undefined\n const parsed = Date.parse(value)\n return Number.isFinite(parsed) ? parsed : undefined\n}\n\nfunction sum(values: readonly number[]): number {\n return values.reduce((total, value) => total + value, 0)\n}\n\nfunction formatClock(value: string): string {\n const parsed = parseTime(value)\n if (parsed === undefined) return '--:--:--'\n return new Date(parsed).toISOString().slice(11, 19)\n}\n\nfunction formatMoney(value: number): string {\n if (value === 0) return '$0'\n if (Math.abs(value) < 0.01) return `$${value.toFixed(4)}`\n return `$${value.toFixed(2)}`\n}\n\nfunction formatTokens(value: number): string {\n if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}m`\n if (value >= 1_000) return `${(value / 1_000).toFixed(1)}k`\n return `${Math.round(value)}`\n}\n\nfunction formatDuration(ms: number): string {\n if (!Number.isFinite(ms) || ms <= 0) return '0s'\n if (ms < 1000) return `${Math.round(ms)}ms`\n const seconds = ms / 1000\n if (seconds < 60) return `${seconds.toFixed(seconds < 10 ? 1 : 0)}s`\n const minutes = seconds / 60\n if (minutes < 60) return `${minutes.toFixed(minutes < 10 ? 1 : 0)}m`\n return `${(minutes / 60).toFixed(1)}h`\n}\n\nfunction compact(value: string, width: number): string {\n if (width <= 1) return ''\n if (value.length <= width) return value\n return `${value.slice(0, width - 1)}~`\n}\n\nfunction pad(value: string, width: number): string {\n const visible = visibleLength(value)\n if (visible >= width) return fitAnsi(value, width)\n return `${value}${' '.repeat(width - visible)}`\n}\n\nfunction rule(width: number, color: boolean): string {\n return paint('-'.repeat(width), 'dim', color)\n}\n\nfunction paint(\n value: string,\n colorName: keyof typeof colors | undefined,\n enabled: boolean,\n): string {\n if (!enabled || !colorName) return value\n return `${colors[colorName]}${value}${colors.reset}`\n}\n\nfunction visibleLength(value: string): number {\n return stripAnsi(value).length\n}\n\nfunction stripAnsi(value: string): string {\n return value.replace(ansiPattern, '')\n}\n\nfunction fitAnsi(value: string, width: number): string {\n if (visibleLength(value) <= width) return value\n let out = ''\n let visible = 0\n for (let i = 0; i < value.length; i += 1) {\n const ch = value[i]\n if (ch === '\\x1b') {\n const rest = value.slice(i)\n // An escape sequence must be copied whole and counted as zero visible columns; truncating\n // inside one would emit a half-sequence the terminal interprets against the next line.\n // biome-ignore lint/suspicious/noControlCharactersInRegex: SGR sequences begin with ESC\n const match = /^\\x1b\\[[0-9;?]*[ -/]*[@-~]/.exec(rest)\n if (match) {\n out += match[0]\n i += match[0].length - 1\n continue\n }\n }\n if (visible >= width - 1) {\n out += '~'\n break\n }\n out += ch\n visible += 1\n }\n if (out.includes('\\x1b[') && !out.endsWith(colors.reset)) out += colors.reset\n return out\n}\n","/**\n * The interactive side of the supervisor-run TUI: a keypress/mouse loop over the frames\n * `./top-model` renders, plus the operator controls that write back to the run — steer a live\n * worker, cancel one worker, and request cancellation of a whole run.\n *\n * The controls go through the owned run layout: steers via `writeWorkerSteer` (the durable inbox\n * append) and worker cancellation via `cancelWorker` (the acknowledged operation the runtime's\n * turn loop applies). Run-level cancellation targets the ROOT, which has no acknowledged runtime\n * path yet for a non-retained tree — it stays a `cancel.request.json` write inside the run\n * directory for a host process to honor. Nothing here joins a path from the workspace root.\n *\n * Extracted from the `loops` repo (`src/top.ts`). The module-level singletons are the origin's\n * shape and are kept: this drives one terminal, and `runTopApp` is its one entry point.\n *\n * @experimental\n */\n\nimport { spawnSync } from 'node:child_process'\nimport { randomUUID } from 'node:crypto'\nimport { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { emitKeypressEvents } from 'node:readline'\nimport { cancelRun, cancelWorker, writeWorkerSteer } from '../runtime/supervise/run-layout'\nimport {\n loadTopSnapshot,\n type RenderTarget,\n renderTopFrameWithLayout,\n type TopSnapshot,\n} from './top-model'\n\ninterface UiState {\n root: string\n color: boolean\n focus: 'supervisors' | 'workers'\n mode: 'overview' | 'detail' | 'log'\n selectedSupervisorId: string | undefined\n selectedWorkerId: string | undefined\n notice: string | undefined\n steerInput: {\n active: boolean\n value: string\n }\n}\n\n/** @experimental How the app was invoked. Defaults read `process.argv` / `process.cwd()`. */\nexport interface TopAppOptions {\n readonly argv?: readonly string[]\n readonly cwd?: string\n}\n\nlet state: UiState = initialState([], process.cwd())\nlet snapshot: TopSnapshot = {\n root: state.root,\n generatedAt: 0,\n supervisors: [],\n completeness: 'complete',\n diagnostics: [],\n discovered: 0,\n loaded: 0,\n}\nlet targets: RenderTarget[] = []\nlet timer: NodeJS.Timeout | undefined\n\n/**\n * Render exactly one frame and return it. This is the non-interactive path — `--once`, a pipe, a\n * test — so it never touches raw mode, the alternate screen, or `process.exit`.\n */\nexport function renderTopOnce(options: TopAppOptions = {}): string {\n const args = [...(options.argv ?? process.argv.slice(2))]\n state = initialState(args, options.cwd ?? process.cwd())\n snapshot = loadTopSnapshot(state.root)\n clampSelection()\n return renderTopFrameWithLayout(snapshot, {\n color: state.color,\n width: process.stdout.columns ?? 128,\n focus: state.focus,\n mode: state.mode,\n ...(state.selectedSupervisorId ? { selectedSupervisorId: state.selectedSupervisorId } : {}),\n ...(state.selectedWorkerId ? { selectedWorkerId: state.selectedWorkerId } : {}),\n steerInput: renderSteerInputState(),\n }).frame\n}\n\n/**\n * Run the TUI. With a TTY on both ends and no `--once` this takes over the terminal until `q`;\n * otherwise it writes a single frame to stdout and returns.\n */\nexport function runTopApp(options: TopAppOptions = {}): void {\n const args = [...(options.argv ?? process.argv.slice(2))]\n if (!process.stdout.isTTY || !process.stdin.isTTY || args.includes('--once')) {\n process.stdout.write(renderTopOnce(options))\n return\n }\n state = initialState(args, options.cwd ?? process.cwd())\n snapshot = loadTopSnapshot(state.root)\n start()\n}\n\nfunction initialState(args: readonly string[], cwd: string): UiState {\n const rootArg = args.find((arg) => !arg.startsWith('-'))\n return {\n root: resolve(rootArg ?? cwd),\n color: Boolean(process.stdout.isTTY) && !args.includes('--no-color'),\n focus: args.includes('--detail') ? 'workers' : 'supervisors',\n mode: args.includes('--log') ? 'log' : args.includes('--detail') ? 'detail' : 'overview',\n selectedSupervisorId: undefined,\n selectedWorkerId: undefined,\n notice: undefined,\n steerInput: { active: false, value: '' },\n }\n}\n\nfunction start(): void {\n process.stdout.write('\\x1b[?1049h\\x1b[?25l\\x1b[?1000h\\x1b[?1006h')\n emitKeypressEvents(process.stdin)\n process.stdin.setRawMode(true)\n process.stdin.resume()\n process.stdin.on('keypress', onKey)\n process.stdin.on('data', onData)\n process.on('SIGINT', stop)\n draw()\n timer = setInterval(draw, 1000)\n}\n\nfunction stop(): void {\n if (timer) clearInterval(timer)\n process.stdin.setRawMode(false)\n process.stdout.write('\\x1b[?1000l\\x1b[?1006l\\x1b[?25h\\x1b[?1049l')\n process.exit(0)\n}\n\nfunction pauseUi(): void {\n if (timer) {\n clearInterval(timer)\n timer = undefined\n }\n process.stdin.setRawMode(false)\n process.stdin.pause()\n process.stdout.write('\\x1b[?1000l\\x1b[?1006l\\x1b[?25h\\x1b[?1049l')\n}\n\nfunction resumeUi(): void {\n process.stdout.write('\\x1b[?1049h\\x1b[?25l\\x1b[?1000h\\x1b[?1006h')\n process.stdin.setRawMode(true)\n process.stdin.resume()\n draw()\n timer = setInterval(draw, 1000)\n}\n\nfunction draw(): void {\n snapshot = loadTopSnapshot(state.root)\n clampSelection()\n const rendered = renderTopFrameWithLayout(snapshot, {\n width: process.stdout.columns ?? 128,\n height: process.stdout.rows ?? 42,\n color: state.color,\n focus: state.focus,\n mode: state.mode,\n ...(state.notice ? { notice: state.notice } : {}),\n ...(state.selectedSupervisorId ? { selectedSupervisorId: state.selectedSupervisorId } : {}),\n ...(state.selectedWorkerId ? { selectedWorkerId: state.selectedWorkerId } : {}),\n steerInput: renderSteerInputState(),\n })\n targets = rendered.targets\n process.stdout.write(`\\x1b[2J\\x1b[H${rendered.frame}`)\n}\n\nfunction onKey(str: string, key: { name?: string; ctrl?: boolean }): void {\n state.notice = undefined\n if (key.ctrl && key.name === 'c') stop()\n if (state.steerInput.active) {\n handleSteerInput(str, key)\n draw()\n return\n }\n if (key.name === 'q' || key.name === 'escape') stop()\n if (key.name === 'tab') {\n state.focus = state.focus === 'supervisors' ? 'workers' : 'supervisors'\n } else if (key.name === 'up') {\n moveSelection(-1)\n } else if (key.name === 'down') {\n moveSelection(1)\n } else if (key.name === 'left') {\n moveSupervisor(-1)\n } else if (key.name === 'right') {\n moveSupervisor(1)\n } else if (key.name === 'return') {\n state.mode = 'detail'\n state.focus = 'workers'\n } else if (key.name === 'o') {\n state.mode = 'overview'\n } else if (key.name === 'l') {\n state.mode = 'log'\n } else if (key.name === 's') {\n startSteerInput()\n } else if (key.name === 'a') {\n state.mode = 'detail'\n openWorkerShell()\n } else if (key.name === 'c') {\n requestCancel()\n }\n draw()\n}\n\nfunction handleSteerInput(str: string, key: { name?: string; ctrl?: boolean }): void {\n if (key.name === 'escape') {\n state.steerInput = { active: false, value: '' }\n return\n }\n if (key.name === 'return') {\n submitSteerInput()\n return\n }\n if (key.name === 'backspace') {\n state.steerInput.value = state.steerInput.value.slice(0, -1)\n return\n }\n if (key.ctrl && key.name === 'u') {\n state.steerInput.value = ''\n return\n }\n if (\n key.ctrl ||\n key.name === 'tab' ||\n key.name === 'up' ||\n key.name === 'down' ||\n key.name === 'left' ||\n key.name === 'right'\n ) {\n return\n }\n if (!str || str === '\\r' || str === '\\n') return\n if ([...str].every((char) => char >= ' ' && char !== '\\x7f')) state.steerInput.value += str\n}\n\nfunction onData(data: Buffer): void {\n const click = parseMouse(data.toString('utf8'))\n if (!click) return\n const target = targets.find((candidate) => candidate.row === click.row)\n if (!target) return\n state.notice = undefined\n if (target.kind === 'supervisor') {\n state.focus = 'supervisors'\n state.selectedSupervisorId = target.id\n state.selectedWorkerId = undefined\n } else {\n state.focus = 'workers'\n state.mode = 'detail'\n state.selectedSupervisorId = target.supervisorId\n state.selectedWorkerId = target.id\n }\n draw()\n}\n\nfunction startSteerInput(): void {\n state.mode = 'detail'\n state.focus = 'workers'\n if (!selectedSupervisor()) {\n state.notice = 'no supervisor selected'\n return\n }\n if (!selectedWorker()) {\n state.notice = 'no worker selected'\n return\n }\n state.steerInput = { active: true, value: '' }\n}\n\nfunction submitSteerInput(): void {\n const supervisor = selectedSupervisor()\n const worker = selectedWorker()\n const message = state.steerInput.value\n state.steerInput = { active: false, value: '' }\n if (!supervisor) {\n state.notice = 'no supervisor selected'\n return\n }\n if (!worker) {\n state.notice = 'no worker selected'\n return\n }\n try {\n // The snapshot already carries the worker LABEL the layout keys inboxes by, so this is the\n // direct durable append with no id-to-label resolution step in between.\n const written = writeWorkerSteer(state.root, supervisor.id, worker.label, message, 'human')\n state.notice = `steer queued for ${supervisor.id}/${written.worker}`\n } catch (err) {\n state.notice = `steer failed: ${err instanceof Error ? err.message : String(err)}`\n }\n}\n\nfunction parseMouse(raw: string): { col: number; row: number } | undefined {\n // ESC is the literal first byte of an SGR mouse report; matching the control character IS the\n // parse, so the control-character rule does not apply to a terminal escape decoder.\n // biome-ignore lint/suspicious/noControlCharactersInRegex: SGR mouse reports begin with ESC\n const match = /\\x1b\\[<(\\d+);(\\d+);(\\d+)([mM])/.exec(raw)\n if (match?.[4] !== 'M') return undefined\n const col = Number(match[2])\n const row = Number(match[3])\n if (!Number.isFinite(col) || !Number.isFinite(row)) return undefined\n return { col: col - 1, row: row - 1 }\n}\n\nfunction moveSelection(delta: number): void {\n if (state.focus === 'supervisors') {\n moveSupervisor(delta)\n return\n }\n const supervisor = selectedSupervisor()\n if (!supervisor || supervisor.workers.length === 0) return\n const current = Math.max(\n 0,\n supervisor.workers.findIndex((worker) => worker.id === state.selectedWorkerId),\n )\n const next = wrap(current + delta, supervisor.workers.length)\n const worker = supervisor.workers[next]\n if (worker) state.selectedWorkerId = worker.id\n}\n\nfunction moveSupervisor(delta: number): void {\n if (snapshot.supervisors.length === 0) return\n const current = Math.max(\n 0,\n snapshot.supervisors.findIndex((supervisor) => supervisor.id === state.selectedSupervisorId),\n )\n const next = wrap(current + delta, snapshot.supervisors.length)\n const supervisor = snapshot.supervisors[next]\n if (!supervisor) return\n state.selectedSupervisorId = supervisor.id\n state.selectedWorkerId = supervisor.workers[0]?.id\n}\n\nfunction clampSelection(): void {\n if (snapshot.supervisors.length === 0) {\n state.selectedSupervisorId = undefined\n state.selectedWorkerId = undefined\n return\n }\n const supervisor = selectedSupervisor() ?? snapshot.supervisors[0]\n if (!supervisor) return\n state.selectedSupervisorId = supervisor.id\n const worker =\n supervisor.workers.find((candidate) => candidate.id === state.selectedWorkerId) ??\n supervisor.workers[0]\n state.selectedWorkerId = worker?.id\n}\n\nfunction selectedSupervisor(): TopSnapshot['supervisors'][number] | undefined {\n return snapshot.supervisors.find((supervisor) => supervisor.id === state.selectedSupervisorId)\n}\n\nfunction selectedWorker(): TopSnapshot['supervisors'][number]['workers'][number] | undefined {\n const supervisor = selectedSupervisor()\n return supervisor?.workers.find((worker) => worker.id === state.selectedWorkerId)\n}\n\nfunction renderSteerInputState(): { active: boolean; value: string; workerLabel?: string } {\n const worker = selectedWorker()\n return {\n active: state.steerInput.active,\n value: state.steerInput.value,\n ...(worker?.label ? { workerLabel: worker.label } : {}),\n }\n}\n\nfunction openWorkerShell(): void {\n const worker = selectedWorker()\n if (!worker?.cwd) {\n state.notice = 'no worker worktree recorded yet'\n return\n }\n if (!existsSync(worker.cwd)) {\n state.notice = `worker worktree is gone: ${worker.cwd}`\n return\n }\n const shell = process.env.SHELL ?? '/bin/bash'\n state.notice = `returned from ${worker.label}`\n pauseUi()\n spawnSync(shell, [], {\n cwd: worker.cwd,\n stdio: 'inherit',\n env: {\n ...process.env,\n AGENT_SUPERVISOR_ROOT: state.root,\n AGENT_SUPERVISOR_ID: state.selectedSupervisorId ?? '',\n AGENT_WORKER_ID: worker.id,\n AGENT_WORKER_LABEL: worker.label,\n },\n })\n resumeUi()\n}\n\nfunction requestCancel(): void {\n const supervisor = selectedSupervisor()\n if (!supervisor) {\n state.notice = 'no supervisor selected'\n return\n }\n if (supervisor.status !== 'running') {\n state.notice = `${supervisor.id} is ${supervisor.status}; no cancel request written`\n return\n }\n // Worker focus cancels ONE worker through the acknowledged runtime path: the request lands in\n // the run layout's cancellation inbox, the run's own turn loop applies the abort to exactly\n // that worker's subtree, and the acknowledgement records what it proved.\n const worker = state.focus === 'workers' ? selectedWorker() : undefined\n if (worker) {\n if (worker.status !== 'running') {\n state.notice = `${worker.label} is ${worker.status}; nothing to cancel`\n return\n }\n // The request names the exact node id, so it routes to the manager that owns the worker at\n // ANY depth — the owning manager's turn loop applies the abort to exactly that subtree.\n try {\n const record = cancelWorker(supervisor.stateDir, worker.id, randomUUID(), {\n reason: 'operator requested cancel from TUI',\n source: 'agent-runtime-top',\n })\n state.notice =\n record.effect === 'unknown'\n ? `cancel queued for ${supervisor.id}/${worker.label} (op ${record.operationId}); awaiting runtime acknowledgement`\n : `cancel ${record.effect} for ${supervisor.id}/${worker.label} (op ${record.operationId})`\n } catch (err) {\n state.notice = `cancel request failed: ${err instanceof Error ? err.message : String(err)}`\n }\n return\n }\n // Supervisor focus cancels the WHOLE run through the same acknowledged contract: the request\n // lands in the run layout, the run's root manager aborts the whole tree through the one cascade\n // controller it already has, and `supervise()` records the terminal effect.\n try {\n const record = cancelRun(supervisor.stateDir, randomUUID(), {\n reason: 'operator requested cancel from TUI',\n source: 'agent-runtime-top',\n })\n state.notice =\n record.effect === 'unknown'\n ? `run cancel queued for ${supervisor.id} (op ${record.operationId}); awaiting runtime acknowledgement`\n : `run cancel ${record.effect} for ${supervisor.id} (op ${record.operationId})`\n } catch (err) {\n state.notice = `cancel request failed: ${err instanceof Error ? err.message : String(err)}`\n }\n}\n\nfunction wrap(value: number, size: number): number {\n return ((value % size) + size) % size\n}\n"],"m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AAS,MAAM,UAAU,YAAY,eAAe,IAAI,KAAA;CAC9D,IAAI,QAAQ;EACV,IAAI,OAAO,WAAW,WAAW;GAC/B,MAAM,SAAS,GAAG,OAAO,MAAM,MAAM,OAAO,OAAO;GACnD;EACF;EAGA,IAAI;GACF,MAAM,SAAS,aAAa,WAAW,UAAU,OAAO,IAAI,WAAW,GAAG;IACxE,QAAQ;IACR,QAAQ;GACV,CAAC;GACD,MAAM,SACJ,OAAO,WAAW,YACd,qBAAqB,WAAW,GAAG,GAAG,OAAO,MAAM,OAAO,OAAO,YAAY,uCAC7E,UAAU,OAAO,OAAO,OAAO,WAAW,GAAG,GAAG,OAAO,MAAM,OAAO,OAAO,YAAY;EAC/F,SAAS,KAAK;GACZ,MAAM,SAAS,0BAA0B,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;EAC1F;EACA;CACF;CAIA,IAAI;EACF,MAAM,SAAS,UAAU,WAAW,UAAU,WAAW,GAAG;GAC1D,QAAQ;GACR,QAAQ;EACV,CAAC;EACD,MAAM,SACJ,OAAO,WAAW,YACd,yBAAyB,WAAW,GAAG,OAAO,OAAO,YAAY,uCACjE,cAAc,OAAO,OAAO,OAAO,WAAW,GAAG,OAAO,OAAO,YAAY;CACnF,SAAS,KAAK;EACZ,MAAM,SAAS,0BAA0B,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;CAC1F;AACF;AAEA,SAAS,KAAK,OAAe,MAAsB;CACjD,QAAS,QAAQ,OAAQ,QAAQ;AACnC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"util-Bncw0o_F.js","names":[],"sources":["../src/runtime/util.ts"],"sourcesContent":["/**\n *\n * Internal loop-kernel utilities shared across the kernel, drivers, and the\n * sandbox-acquire layer. Not part of the public barrel surface.\n *\n * @experimental\n */\n\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport type { Spend } from './supervise/types'\nimport type { LoopTokenUsage } from './types'\n\n/**\n * Best-effort sandbox delete. Skips instances without a `delete` (test fakes);\n * swallows errors (the platform reaps on expiry). Returns `false` when delete\n * threw, `true` otherwise, so callers can surface a leak if they choose.\n */\nexport async function deleteBoxSafe(box: SandboxInstance | undefined): Promise<boolean> {\n if (!box || typeof (box as { delete?: unknown }).delete !== 'function') return true\n try {\n await box.delete()\n return true\n } catch {\n return false\n }\n}\n\n/** Short base36 id for trace correlation. Not cryptographic, not collision-free. */\nexport function randomSuffix(len = 8): string {\n return Math.random()\n .toString(36)\n .slice(2, 2 + len)\n}\n\n/** Collision-resistant id for sandbox naming (find-by-name recovery must be unique). */\nexport function randomUuid(): string {\n return crypto.randomUUID()\n}\n\n/** Construct an AbortError. Downstream code pattern-matches on `err.name`. */\nexport function abortError(): Error {\n const err = new Error('aborted')\n err.name = 'AbortError'\n return err\n}\n\n/** Throw an AbortError. */\nexport function throwAbort(): never {\n throw abortError()\n}\n\n/** Throw if the signal is already aborted; otherwise no-op. */\nexport function throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) throw abortError()\n}\n\n/** True for any error whose `name` is `AbortError` (the cross-kernel abort contract). */\nexport function isAbortError(err: unknown): boolean {\n return err instanceof Error && err.name === 'AbortError'\n}\n\n/**\n * Sleep that resolves early on abort and always clears its timer so it never\n * keeps the event loop alive. Resolves (does not reject) on abort — callers\n * re-check the signal explicitly after the sleep.\n */\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal?.aborted) {\n resolve()\n return\n }\n let onAbort: (() => void) | undefined\n const timer = setTimeout(() => {\n if (onAbort && signal) signal.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n if (signal) {\n onAbort = () => {\n clearTimeout(timer)\n resolve()\n }\n signal.addEventListener('abort', onAbort, { once: true })\n }\n })\n}\n\n/**\n * Race a promise against a timeout. Resolves with the value if it settles in\n * time, otherwise resolves with `undefined`. Always clears the timer.\n */\nexport function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T | undefined> {\n return new Promise<T | undefined>((resolve) => {\n const timer = setTimeout(() => resolve(undefined), ms)\n promise.then(\n (value) => {\n clearTimeout(timer)\n resolve(value)\n },\n () => {\n clearTimeout(timer)\n resolve(undefined)\n },\n )\n })\n}\n\ninterface StringifyOptions {\n /** Pretty-print with 2-space indent. Default false (compact). */\n pretty?: boolean\n /** Truncate to this many chars, appending `…`. Default unbounded. */\n max?: number\n}\n\n/**\n * `JSON.stringify` with a `String()` fallback on throw (cyclic / non-JSON).\n * Strings pass through unstringified so a preview of a string output is the\n * string itself, not a quoted re-encoding.\n */\nexport function stringifySafe(value: unknown, opts: StringifyOptions = {}): string {\n let s: string\n try {\n if (typeof value === 'string') {\n s = value\n } else {\n const json = opts.pretty ? JSON.stringify(value, null, 2) : JSON.stringify(value)\n s = json ?? String(value)\n }\n } catch {\n s = String(value)\n }\n if (opts.max !== undefined && s.length > opts.max) return `${s.slice(0, opts.max)}…`\n return s\n}\n\n/** A fresh zero token-usage accumulator. */\nexport function zeroTokenUsage(): LoopTokenUsage {\n return { input: 0, output: 0 }\n}\n\n/**\n * Sum the catalog-priced part of a dollar total across spends, as a field to spread.\n *\n * Returns nothing when no input carried one. A fold of pure provider receipts must not gain a\n * `usdEstimated: 0`, which would read as \"this runtime checked and priced none\" on a path that\n * never prices at all.\n */\nexport function usdEstimatedOf(...spends: ReadonlyArray<{ usdEstimated?: number }>): {\n usdEstimated?: number\n} {\n let total = 0\n let priced = false\n for (const spend of spends) {\n if (spend.usdEstimated === undefined) continue\n priced = true\n total += spend.usdEstimated\n }\n return priced ? { usdEstimated: total } : {}\n}\n\n/** A conserved spend with every channel at zero and no completeness claim on it. */\nexport function zeroSpend(): Spend {\n return { iterations: 0, tokens: zeroTokenUsage(), usd: 0, ms: 0 }\n}\n\n/** Copy a conserved spend without dropping a completeness marker or the catalog-priced part. */\nexport function cloneSpend(spend: Spend): Spend {\n return {\n iterations: spend.iterations,\n tokens: cloneTokenUsage(spend.tokens),\n ...(spend.tokensKnown === false ? { tokensKnown: false } : {}),\n usd: spend.usd,\n ...(spend.usdKnown === false ? { usdKnown: false } : {}),\n ...(spend.usdEstimated !== undefined ? { usdEstimated: spend.usdEstimated } : {}),\n ms: spend.ms,\n }\n}\n\n/**\n * Sum two conserved spends per channel. Tokens and dollars never fold into each other, an\n * incomplete input keeps the sum incomplete on that channel, and the catalog-priced part of the\n * dollar total is summed separately so `usd - usdEstimated` still names what a provider billed.\n */\nexport function addSpend(a: Spend, b: Spend): Spend {\n const tokens = cloneTokenUsage(a.tokens)\n addTokenUsage(tokens, b.tokens)\n return {\n iterations: a.iterations + b.iterations,\n tokens,\n ...(a.tokensKnown === false || b.tokensKnown === false ? { tokensKnown: false } : {}),\n usd: a.usd + b.usd,\n ...(a.usdKnown === false || b.usdKnown === false ? { usdKnown: false } : {}),\n ...usdEstimatedOf(a, b),\n ms: a.ms + b.ms,\n }\n}\n\n/** Copy a token subtotal without dropping optional provider cache telemetry. */\nexport function cloneTokenUsage(usage: LoopTokenUsage): LoopTokenUsage {\n const cacheBreakdownUnknown =\n usage.cacheBreakdownKnown === false || (usage.input > 0 && !hasClassifiedCacheBreakdown(usage))\n return {\n input: usage.input,\n output: usage.output,\n ...(usage.tokensKnown === false ? { tokensKnown: false as const } : {}),\n ...(usage.freshInput !== undefined ? { freshInput: usage.freshInput } : {}),\n ...(usage.cacheRead !== undefined ? { cacheRead: usage.cacheRead } : {}),\n ...(usage.cacheWrite !== undefined ? { cacheWrite: usage.cacheWrite } : {}),\n ...(cacheBreakdownUnknown ? { cacheBreakdownKnown: false as const } : {}),\n }\n}\n\n/** True only when every positive prompt token has a consistent cache classification. */\nexport function hasCompleteCacheBreakdown(usage: LoopTokenUsage): boolean {\n if (usage.cacheBreakdownKnown === false) return false\n return hasClassifiedCacheBreakdown(usage)\n}\n\nfunction hasClassifiedCacheBreakdown(usage: LoopTokenUsage): boolean {\n if (usage.input === 0) return true\n if (\n usage.freshInput === undefined ||\n usage.cacheRead === undefined ||\n usage.cacheWrite === undefined\n ) {\n return false\n }\n return usage.freshInput + usage.cacheRead + usage.cacheWrite === usage.input\n}\n\n/**\n * The token charge for one observation: every token counted ONCE, at the moment it first enters\n * the context — `input − cacheRead + output`.\n *\n * `input` is a rolled-up prompt total that re-counts a cached prefix on every turn that reads it,\n * so charging `input` makes a 100K prefix read 40 times cost 4.1M for content authored once. A\n * cache read is content that was already charged when it was written, so it is the one class the\n * charge subtracts. Under a complete split the result is exactly `freshInput + cacheWrite`. No\n * price weight is involved: this counts work, and money is a separate channel.\n *\n * The subtraction form is what makes the charge ADDITIVE. `input` and `cacheRead` both accumulate\n * through `addTokenUsage`, so the charge on an aggregate equals the sum of the charges on the\n * records that built it — including an aggregate that mixes classified and unclassified turns,\n * where the unclassified remainder is charged in full and only the reported cache reads are\n * credited. A form that read `freshInput + cacheWrite` directly loses that: one unclassified turn\n * would drop the whole aggregate to `input + output` and over-charge every classified turn with it.\n *\n * The one arithmetic guarantee: a set of classes that does not FIT inside the prompt total it\n * partitions credits nothing, so the charge is never below `output` and a class that overflows its\n * own total buys no tokens. It is not a guarantee against a provider that reports a cache read it\n * never served — that provider can under-report `input` just as easily, and the token channel is an\n * accounting unit, not a trust boundary. Prompt tokens the provider left unclassified are charged\n * in full, so a spend with no readable split charges an upper bound on newly-presented work rather\n * than a measurement, and every caller that enforces a ceiling must report the difference\n * (`BudgetPool` does it through `readout().cacheBreakdownKnown`).\n */\nexport function chargedTokens(usage: LoopTokenUsage): number {\n return usage.input - creditedCacheRead(usage) + usage.output\n}\n\n/** `cacheRead` if the reported classes fit inside `input`, else nothing. */\nfunction creditedCacheRead(usage: LoopTokenUsage): number {\n const { cacheRead } = usage\n if (cacheRead === undefined) return 0\n return classifiedTotal(usage, cacheRead) > usage.input ? 0 : cacheRead\n}\n\nfunction classifiedTotal(usage: Partial<LoopTokenUsage>, cacheRead: number): number {\n return (usage.freshInput ?? 0) + cacheRead + (usage.cacheWrite ?? 0)\n}\n\n/** The prompt-cache token classes of one observation, as `LoopTokenUsage` members. */\nexport type PromptCacheTokenClasses = Pick<\n LoopTokenUsage,\n 'freshInput' | 'cacheRead' | 'cacheWrite' | 'cacheBreakdownKnown'\n>\n\n/**\n * Translate one provider prompt-cache report into the prompt token classes `addTokenUsage` folds\n * and `chargedTokens` credits.\n *\n * The input is the open `promptCache` record an `llm_call` carries, keyed by the `PromptCacheUsage`\n * vocabulary (`readTokens`, `writeTokens`). Providers report that vocabulary unevenly, and the\n * three outcomes are different facts that must not collapse into one another:\n *\n * - **Nothing reported** — no classes and no marker. The caller's own unknown handling decides,\n * because a provider that says nothing about caching has not said the split is unknowable.\n * - **Read and write both reported, and fitting inside `input`** — a complete partition, so\n * `freshInput` is the remainder and the split is known.\n * - **One counter reported, or classes that overflow `input`** — the counters that ARE measured\n * pass through and `cacheBreakdownKnown` is false. A read with no write counter (OpenAI reports\n * no write) still credits the read it measured, while declaring the rest unclassified so the\n * charge stays a declared upper bound. An overflowing claim buys nothing: it cannot be a\n * partition of a total it exceeds.\n *\n * A counter the provider did not report stays absent. A zero would claim the provider measured no\n * cache, which is a different fact from a provider that did not report.\n */\nexport function promptCacheTokenClasses(\n input: number | undefined,\n promptCache: Readonly<Record<string, number | string>> | undefined,\n): PromptCacheTokenClasses {\n if (promptCache === undefined) return {}\n const read = tokenCount(promptCache.readTokens)\n const write = tokenCount(promptCache.writeTokens)\n if (read === undefined && write === undefined) return {}\n if (input === undefined || (read ?? 0) + (write ?? 0) > input) {\n return { cacheBreakdownKnown: false }\n }\n if (read !== undefined && write !== undefined) {\n return { freshInput: input - read - write, cacheRead: read, cacheWrite: write }\n }\n return {\n ...(read !== undefined ? { cacheRead: read } : {}),\n ...(write !== undefined ? { cacheWrite: write } : {}),\n cacheBreakdownKnown: false,\n }\n}\n\nfunction tokenCount(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n}\n\n/**\n * Add the observed subtotal into `acc`; token and cache incompleteness are sticky.\n *\n * A delta whose classes do not FIT inside its own `input` contributes its prompt total and NO\n * classes. Folding them in would hide the overflow: the accumulator's larger `input` can absorb a\n * class total that overflowed the one delta that reported it, and `chargedTokens` would then credit\n * at the aggregate a cache read it refuses at the record. That is the one way the charge could come\n * out below the sum of the charges on the records that built it.\n */\nexport function addTokenUsage(acc: LoopTokenUsage, delta: Partial<LoopTokenUsage>): void {\n acc.input += delta.input ?? 0\n acc.output += delta.output ?? 0\n if (delta.tokensKnown === false) acc.tokensKnown = false\n\n const input = delta.input ?? 0\n const fits = classifiedTotal(delta, delta.cacheRead ?? 0) <= input\n if (fits) {\n if (delta.freshInput !== undefined) acc.freshInput = (acc.freshInput ?? 0) + delta.freshInput\n if (delta.cacheRead !== undefined) acc.cacheRead = (acc.cacheRead ?? 0) + delta.cacheRead\n if (delta.cacheWrite !== undefined) acc.cacheWrite = (acc.cacheWrite ?? 0) + delta.cacheWrite\n }\n\n const classified =\n fits &&\n delta.freshInput !== undefined &&\n delta.cacheRead !== undefined &&\n delta.cacheWrite !== undefined &&\n delta.freshInput + delta.cacheRead + delta.cacheWrite === input\n // A provider that reports prompt input without all three classes leaves the\n // split unknown. Do not let an earlier complete turn make the aggregate look\n // complete after a later unclassified positive-input turn.\n if (delta.cacheBreakdownKnown === false || (input > 0 && !classified)) {\n acc.cacheBreakdownKnown = false\n }\n}\n\n/**\n * Map `items` through `fn` with at most `limit` calls in flight at once,\n * preserving input order in the result. On the first `fn` rejection no NEW\n * items are picked up; already-in-flight calls are awaited, then the first\n * error is rethrown. `limit` is clamped to ≥ 1.\n *\n * Used where a burst of provisioning (e.g. forking N child boxes) must respect\n * the loop's concurrency bound instead of firing all N at once.\n */\nexport async function mapWithConcurrency<T, R>(\n items: readonly T[],\n limit: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const bound = Math.max(1, Math.floor(limit))\n const results = new Array<R>(items.length)\n let next = 0\n let failed = false\n const worker = async (): Promise<void> => {\n while (!failed) {\n const i = next\n next += 1\n if (i >= items.length) return\n try {\n results[i] = await fn(items[i] as T, i)\n } catch (err) {\n failed = true\n throw err\n }\n }\n }\n const workerCount = Math.min(bound, items.length)\n await Promise.all(Array.from({ length: workerCount }, () => worker()))\n return results\n}\n"],"mappings":";;;;;;AAiBA,eAAsB,cAAc,KAAoD;CACtF,IAAI,CAAC,OAAO,OAAQ,IAA6B,WAAW,YAAY,OAAO;CAC/E,IAAI;EACF,MAAM,IAAI,OAAO;EACjB,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,SAAgB,aAAa,MAAM,GAAW;CAC5C,OAAO,KAAK,OAAO,CAAC,CACjB,SAAS,EAAE,CAAC,CACZ,MAAM,GAAG,IAAI,GAAG;AACrB;;AAGA,SAAgB,aAAqB;CACnC,OAAO,OAAO,WAAW;AAC3B;;AAGA,SAAgB,aAAoB;CAClC,MAAM,sBAAM,IAAI,MAAM,SAAS;CAC/B,IAAI,OAAO;CACX,OAAO;AACT;;AAGA,SAAgB,aAAoB;CAClC,MAAM,WAAW;AACnB;;AAGA,SAAgB,eAAe,QAAuC;CACpE,IAAI,QAAQ,SAAS,MAAM,WAAW;AACxC;;AAGA,SAAgB,aAAa,KAAuB;CAClD,OAAO,eAAe,SAAS,IAAI,SAAS;AAC9C;;;;;;AAOA,SAAgB,MAAM,IAAY,QAAqC;CACrE,OAAO,IAAI,SAAS,YAAY;EAC9B,IAAI,QAAQ,SAAS;GACnB,QAAQ;GACR;EACF;EACA,IAAI;EACJ,MAAM,QAAQ,iBAAiB;GAC7B,IAAI,WAAW,QAAQ,OAAO,oBAAoB,SAAS,OAAO;GAClE,QAAQ;EACV,GAAG,EAAE;EACL,IAAI,QAAQ;GACV,gBAAgB;IACd,aAAa,KAAK;IAClB,QAAQ;GACV;GACA,OAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;EAC1D;CACF,CAAC;AACH;;;;;AAMA,SAAgB,YAAe,SAAqB,IAAoC;CACtF,OAAO,IAAI,SAAwB,YAAY;EAC7C,MAAM,QAAQ,iBAAiB,QAAQ,K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