@tangle-network/agent-runtime 0.134.7 → 0.134.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 (54) hide show
  1. package/dist/{activation-CG9bkirD.js → activation-CAexDnXt.js} +2 -2
  2. package/dist/{activation-CG9bkirD.js.map → activation-CAexDnXt.js.map} +1 -1
  3. package/dist/agent.d.ts +1 -1
  4. package/dist/agent.js +2 -2
  5. package/dist/{authoring-CK6iXftK.js → authoring-DHVHhbJO.js} +2 -2
  6. package/dist/{authoring-CK6iXftK.js.map → authoring-DHVHhbJO.js.map} +1 -1
  7. package/dist/{graph-9KF7mJM3.js → graph-BWsEZmDL.js} +2 -2
  8. package/dist/{graph-9KF7mJM3.js.map → graph-BWsEZmDL.js.map} +1 -1
  9. package/dist/{improvement-cycle-5XDmxqzr.js → improvement-cycle-DN0QhoCi.js} +3 -3
  10. package/dist/{improvement-cycle-5XDmxqzr.js.map → improvement-cycle-DN0QhoCi.js.map} +1 -1
  11. package/dist/{index-0qU8jNOJ.d.ts → index-CRauzLFH.d.ts} +116 -35
  12. package/dist/{index-DJ9qeOi3.d.ts → index-DC7CNU9n.d.ts} +2 -2
  13. package/dist/index.d.ts +3 -3
  14. package/dist/index.js +7 -7
  15. package/dist/intelligence.js +3 -3
  16. package/dist/kernel.d.ts +2 -2
  17. package/dist/kernel.js +8 -8
  18. package/dist/{knowledge-DWTOug6a.js → knowledge-DDhcxfdu.js} +3 -3
  19. package/dist/{knowledge-DWTOug6a.js.map → knowledge-DDhcxfdu.js.map} +1 -1
  20. package/dist/knowledge.d.ts +1 -1
  21. package/dist/knowledge.js +1 -1
  22. package/dist/{loop-runner-bin-W7MjoHUk.d.ts → loop-runner-bin-Yp4T-tUJ.d.ts} +2 -2
  23. package/dist/{loop-runner-bin-BCvwX9rk.js → loop-runner-bin-gw418CFH.js} +3 -3
  24. package/dist/{loop-runner-bin-BCvwX9rk.js.map → loop-runner-bin-gw418CFH.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/{openai-tools-ClNr92Bx.js → openai-tools-ne97uXo0.js} +2 -2
  31. package/dist/{openai-tools-ClNr92Bx.js.map → openai-tools-ne97uXo0.js.map} +1 -1
  32. package/dist/run-layout-Be_Z0dF8.js +288 -0
  33. package/dist/run-layout-Be_Z0dF8.js.map +1 -0
  34. package/dist/{runtime-CnQ_-DF_.js → runtime-BZsDYscs.js} +6 -6
  35. package/dist/{runtime-CnQ_-DF_.js.map → runtime-BZsDYscs.js.map} +1 -1
  36. package/dist/{structural-rollout-CbQjaMwW.js → structural-rollout-BMnPPcJP.js} +2 -2
  37. package/dist/{structural-rollout-CbQjaMwW.js.map → structural-rollout-BMnPPcJP.js.map} +1 -1
  38. package/dist/{supervise-B8Ykk8GO.js → supervise-B-nTWUCK.js} +168 -5
  39. package/dist/supervise-B-nTWUCK.js.map +1 -0
  40. package/dist/{supervisor-BU01azdt.js → supervisor-Dl9Fk7g5.js} +14 -11
  41. package/dist/supervisor-Dl9Fk7g5.js.map +1 -0
  42. package/dist/testing.d.ts +1 -1
  43. package/dist/testing.js +11 -11
  44. package/dist/{top-app-G4M18b6i.js → top-app-CH4cUgpo.js} +28 -8
  45. package/dist/top-app-CH4cUgpo.js.map +1 -0
  46. package/dist/tui/bin.js +1 -1
  47. package/dist/tui/index.d.ts +7 -5
  48. package/dist/tui/index.js +1 -1
  49. package/package.json +1 -1
  50. package/dist/run-layout-CeJsEAom.js +0 -158
  51. package/dist/run-layout-CeJsEAom.js.map +0 -1
  52. package/dist/supervise-B8Ykk8GO.js.map +0 -1
  53. package/dist/supervisor-BU01azdt.js.map +0 -1
  54. package/dist/top-app-G4M18b6i.js.map +0 -1
package/dist/testing.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Lt as RunGraphTestOptions, Vt as runGraphWithTestBrain, Ya as superviseWithTestBrain, ao as SupervisorAgentTestDeps, gn as driverAgent, hn as DriverAgentOptions, mo as supervisorAgentWithTestBrain, qa as SuperviseTestOptions } from "./index-0qU8jNOJ.js";
1
+ import { Cn as DriverAgentOptions, Gt as RunGraphTestOptions, So as supervisorAgentWithTestBrain, Yt as runGraphWithTestBrain, po as SupervisorAgentTestDeps, ro as superviseWithTestBrain, to as SuperviseTestOptions, wn as driverAgent } from "./index-CRauzLFH.js";
2
2
  import { it as ToolLoopChat, rt as ToolLoopCallContext } from "./runtime-DHrzFy2v.js";
3
3
  import { AgentImprovementProposal, AgentProfile, AgentProfileImprovementMeasuredComparison, SandboxSizePreset } from "@tangle-network/agent-interface";
4
4
  //#region src/testing/index.d.ts
package/dist/testing.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import { $ as parseExactAgentProfile, K as applyExactAgentProfileDiff, rt as canonicalCandidateDigest$1, st as immutableCandidateValue } from "./prepare-Czki1LBy.js";
2
- import { f as verifyAgentImprovementProposal } from "./improvement-cycle-5XDmxqzr.js";
3
- import { c as supervisorAgentWithTestBrain, dt as driverAgent, r as superviseWithTestBrain } from "./supervise-B8Ykk8GO.js";
4
- import { i as runGraphWithTestBrain } from "./graph-9KF7mJM3.js";
2
+ import { f as verifyAgentImprovementProposal } from "./improvement-cycle-DN0QhoCi.js";
3
+ import { c as supervisorAgentWithTestBrain, dt as driverAgent, r as superviseWithTestBrain } from "./supervise-B-nTWUCK.js";
4
+ import { i as runGraphWithTestBrain } from "./graph-BWsEZmDL.js";
5
5
  import { SANDBOX_SIZE_PRESET_NAMES } from "@tangle-network/agent-interface";
6
6
  //#region src/testing/fixtures/agent-improvement-proposal.json
7
7
  var agent_improvement_proposal_default = {
8
8
  changedSurfaces: ["prompt"],
9
- digest: "sha256:f093f45bec21855f60bf2a74a405ac893e454bdc77439975f9ae9ddd536729fa",
9
+ digest: "sha256:1799d9520a67e6376169ba14bc8b706b4dea039bc6d313c642454a463aaf12db",
10
10
  evaluation: {
11
11
  "decision": {
12
12
  "contributingChecks": [
@@ -4577,7 +4577,7 @@ var agent_improvement_proposal_default = {
4577
4577
  ],
4578
4578
  "metadata": {
4579
4579
  "fixture": "agent-improvement-proposal",
4580
- "runtimeVersion": "0.134.7"
4580
+ "runtimeVersion": "0.134.8"
4581
4581
  },
4582
4582
  "objectives": [
4583
4583
  {
@@ -4688,8 +4688,8 @@ var agent_improvement_proposal_default = {
4688
4688
  "baselineContentHash": "sha256:5c21ee53e513fc604cb09754e21c392b24a424da0ef37dbf8f1ee4a8a0b08f09",
4689
4689
  "candidateContentHash": "sha256:60fcbb1c728194bd51d7d19cb732d1c3f1881dce7e0a6266b41c8b98cfd65693",
4690
4690
  "kind": "agent-eval-loop",
4691
- "recordDigest": "sha256:33ebff3cc78a0ca9b05cfc2f8189beb927a932564987dc2492bb82daf771fee7",
4692
- "runId": "agent-runtime-0.134.7-proposal-fixture",
4691
+ "recordDigest": "sha256:317285eea808e779bbdd266d5455cfe13222eae4b7772b8ae7bdc68ff6aaf3ed",
4692
+ "runId": "agent-runtime-0.134.8-proposal-fixture",
4693
4693
  "schema": "agent-candidate-experiment"
4694
4694
  }
4695
4695
  },
@@ -4712,13 +4712,13 @@ var agent_improvement_proposal_default = {
4712
4712
  }],
4713
4713
  kind: "agent-improvement-proposal",
4714
4714
  proposedAt: "2026-07-10T01:00:00.000Z",
4715
- runId: "agent-runtime-0.134.7-proposal-fixture"
4715
+ runId: "agent-runtime-0.134.8-proposal-fixture"
4716
4716
  };
4717
4717
  //#endregion
4718
4718
  //#region src/testing/fixtures/agent-profile-improvement-proposal.json
4719
4719
  var agent_profile_improvement_proposal_default = {
4720
4720
  changedSurfaces: ["prompt", "skills"],
4721
- digest: "sha256:52f08498aa1fd2f4c1ca54f32c5d5f8a9569bb61ee232e105e8934fe7296350f",
4721
+ digest: "sha256:4f17e8554bb99261a5323084be2980d86e47758cf9adcd67567d777ec7eaef31",
4722
4722
  evaluation: {
4723
4723
  "decision": {
4724
4724
  "contributingChecks": [
@@ -6352,7 +6352,7 @@ var agent_profile_improvement_proposal_default = {
6352
6352
  ],
6353
6353
  "metadata": {
6354
6354
  "fixture": "agent-profile-improvement-proposal",
6355
- "runtimeVersion": "0.134.7"
6355
+ "runtimeVersion": "0.134.8"
6356
6356
  },
6357
6357
  "objectives": [
6358
6358
  {
@@ -6463,7 +6463,7 @@ var agent_profile_improvement_proposal_default = {
6463
6463
  "baselineContentHash": "sha256:21c495a37c418c10bde64fbaa188beddeed31f1f051ea60a6a6582a9ee0db704",
6464
6464
  "candidateContentHash": "sha256:103f77bc8481601eef1ad5fe6ba84a40dffabc3a44f421f8c8559121edab84e9",
6465
6465
  "kind": "agent-eval-loop",
6466
- "recordDigest": "sha256:9f42e89a9e3bf4486227556bb2fed21d9d0b64aba60c5e4565201acbbec8d01c",
6466
+ "recordDigest": "sha256:2f69c7ceaf56c57d152db474e32b3cd1ec641d1dd5f2d66ae6550d3af11a6ee0",
6467
6467
  "runId": "profile-improvement-1",
6468
6468
  "schema": "agent-profile-improvement-experiment"
6469
6469
  }
@@ -1,4 +1,5 @@
1
- import { d as writeWorkerSteer, i as safeWorkerFile, n as legacySupervisorRunsRoot, o as supervisorRunsRoot, s as supervisorWorkersDir } from "./run-layout-CeJsEAom.js";
1
+ import { l as supervisorRunsRoot, r as legacySupervisorRunsRoot, s as safeWorkerFile, t as cancelWorker, u as supervisorWorkersDir, v as writeWorkerSteer } from "./run-layout-Be_Z0dF8.js";
2
+ import { randomUUID } from "node:crypto";
2
3
  import { join, resolve } from "node:path";
3
4
  import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
4
5
  import { spawnSync } from "node:child_process";
@@ -751,12 +752,14 @@ function fitAnsi(value, width) {
751
752
  //#region src/tui/top-app.ts
752
753
  /**
753
754
  * The interactive side of the supervisor-run TUI: a keypress/mouse loop over the frames
754
- * `./top-model` renders, plus the two operator controls that write back to the run — steer a live
755
- * worker, and request cancellation of a run.
755
+ * `./top-model` renders, plus the operator controls that write back to the run — steer a live
756
+ * worker, cancel one worker, and request cancellation of a whole run.
756
757
  *
757
- * Both controls go through the owned run layout: steers via `writeWorkerSteer` (the durable inbox
758
- * append), cancellation via a file inside the run directory the snapshot reported. Nothing here
759
- * joins a path from the workspace root.
758
+ * The controls go through the owned run layout: steers via `writeWorkerSteer` (the durable inbox
759
+ * append) and worker cancellation via `cancelWorker` (the acknowledged operation the runtime's
760
+ * turn loop applies). Run-level cancellation targets the ROOT, which has no acknowledged runtime
761
+ * path yet for a non-retained tree — it stays a `cancel.request.json` write inside the run
762
+ * directory for a host process to honor. Nothing here joins a path from the workspace root.
760
763
  *
761
764
  * Extracted from the `loops` repo (`src/top.ts`). The module-level singletons are the origin's
762
765
  * shape and are kept: this drives one terminal, and `runTopApp` is its one entry point.
@@ -1067,6 +1070,23 @@ function requestCancel() {
1067
1070
  state.notice = `${supervisor.id} is ${supervisor.status}; no cancel request written`;
1068
1071
  return;
1069
1072
  }
1073
+ const worker = state.focus === "workers" ? selectedWorker() : void 0;
1074
+ if (worker) {
1075
+ if (worker.status !== "running") {
1076
+ state.notice = `${worker.label} is ${worker.status}; nothing to cancel`;
1077
+ return;
1078
+ }
1079
+ try {
1080
+ const record = cancelWorker(supervisor.stateDir, worker.id, randomUUID(), {
1081
+ reason: "operator requested cancel from TUI",
1082
+ source: "agent-runtime-top"
1083
+ });
1084
+ state.notice = `cancel ${record.effect} for ${supervisor.id}/${worker.label} (op ${record.operationId})`;
1085
+ } catch (err) {
1086
+ state.notice = `cancel request failed: ${err instanceof Error ? err.message : String(err)}`;
1087
+ }
1088
+ return;
1089
+ }
1070
1090
  try {
1071
1091
  mkdirSync(supervisor.stateDir, { recursive: true });
1072
1092
  writeFileSync(join(supervisor.stateDir, "cancel.request.json"), `${JSON.stringify({
@@ -1074,7 +1094,7 @@ function requestCancel() {
1074
1094
  source: "agent-runtime-top",
1075
1095
  reason: "operator requested cancel from TUI"
1076
1096
  }, null, 2)}\n`, "utf8");
1077
- state.notice = `cancel requested for ${supervisor.id}`;
1097
+ state.notice = `run cancel requested for ${supervisor.id} (host-honored; not runtime-acknowledged)`;
1078
1098
  } catch (err) {
1079
1099
  state.notice = `cancel request failed: ${err instanceof Error ? err.message : String(err)}`;
1080
1100
  }
@@ -1085,4 +1105,4 @@ function wrap(value, size) {
1085
1105
  //#endregion
1086
1106
  export { renderTopFrameWithLayout as a, renderTopFrame as i, runTopApp as n, loadTopSnapshot as r, renderTopOnce as t };
1087
1107
 
1088
- //# sourceMappingURL=top-app-G4M18b6i.js.map
1108
+ //# sourceMappingURL=top-app-CH4cUgpo.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"top-app-CH4cUgpo.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 * @experimental\n */\n\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'\nimport { 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}\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\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 every unreadable or half-written file is\n * skipped rather than thrown on — an operator view must survive a writer mid-append. `now` is\n * injectable so elapsed time is deterministic under test.\n */\nexport function loadTopSnapshot(rootDir: string, now = Date.now()): TopSnapshot {\n const root = resolve(rootDir)\n // `.loops` is the pre-rename state dir; runs already on disk there stay visible.\n const supervisors = [supervisorRunsRoot(root), legacySupervisorRunsRoot(root)]\n .filter((runsRoot) => existsSync(runsRoot))\n .flatMap((runsRoot) =>\n readdirSync(runsRoot)\n .filter((entry) => isDirectory(join(runsRoot, entry)))\n .map((entry) => {\n const dir = join(runsRoot, entry)\n const state = readJson<Partial<SupervisorState>>(join(dir, 'state.json'))\n if (!isSupervisorState(state)) return undefined\n const events = readJournal(dir)\n const progressTail = readTail(join(dir, 'progress.ndjson'), 8)\n const workerEvents = readWorkerEventTails(supervisorWorkersDir(dir), 8)\n return buildSupervisorView(state, dir, events, progressTail, now, workerEvents)\n }),\n )\n .filter((view): view is SupervisorView => view !== undefined)\n .sort((a, b) => String(b.startedAt ?? '').localeCompare(String(a.startedAt ?? '')))\n\n return { root, generatedAt: now, supervisors }\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): TopJournalEvent[] {\n const file = journalFileNames\n .map((name) => join(eventDir, name))\n .find((candidate) => existsSync(candidate))\n if (!file) return []\n const out: TopJournalEvent[] = []\n let raw = ''\n try {\n raw = readFileSync(file, 'utf8')\n } catch {\n return out\n }\n for (const line of raw.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 // Corrupt journal lines should not take down the operator view.\n }\n }\n return out\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 (options.steerInput?.active) push(renderSteerInput(options.steerInput, width, color))\n push(rule(width, color))\n\n if (snapshot.supervisors.length === 0) {\n push(paint('NO SUPERVISORS', 'yellow', color))\n push(`No run state under ${supervisorRunsRoot(snapshot.root)}`)\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\nfunction readTail(file: string, maxLines: number): string[] {\n if (!existsSync(file)) return []\n try {\n const lines = readFileSync(file, 'utf8').trim().split('\\n').filter(Boolean)\n return lines.slice(-maxLines)\n } catch {\n return []\n }\n}\n\nfunction readWorkerEventTails(dir: string, maxLines: number): Map<string, WorkerEventTail> {\n const out = new Map<string, WorkerEventTail>()\n if (!existsSync(dir)) return out\n for (const entry of readdirSync(dir)) {\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 label = entry.slice(0, -'.ndjson'.length)\n const file = join(dir, entry)\n const lines = readTail(file, maxLines)\n const cwd = workerCwd(lines)\n out.set(label, { file, lines, ...(cwd ? { cwd } : {}) })\n }\n return out\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 readJson<T>(file: string): T | undefined {\n try {\n return JSON.parse(readFileSync(file, 'utf8')) as T\n } catch {\n return undefined\n }\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, mkdirSync, writeFileSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { emitKeypressEvents } from 'node:readline'\nimport { 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 = { root: state.root, generatedAt: 0, supervisors: [] }\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 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 = `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 — a root-scoped intent, which is out of the\n // worker-scoped acknowledgement contract: a non-retained supervisor tree exposes no root\n // handle to acknowledge with, so the request stays a file the run's HOST process may honor.\n try {\n mkdirSync(supervisor.stateDir, { recursive: true })\n writeFileSync(\n join(supervisor.stateDir, 'cancel.request.json'),\n `${JSON.stringify(\n {\n at: new Date().toISOString(),\n source: 'agent-runtime-top',\n reason: 'operator requested cancel from TUI',\n },\n null,\n 2,\n )}\\n`,\n 'utf8',\n )\n state.notice = `run cancel requested for ${supervisor.id} (host-honored; not runtime-acknowledged)`\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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAyNA,MAAM,aAAyB;CAAE,YAAY;CAAG,aAAa;CAAG,cAAc;CAAG,KAAK;CAAG,IAAI;AAAE;AAI/F,MAAM,cAAc;AAEpB,MAAM,SAAS;CACb,OAAO;CACP,KAAK;CACL,MAAM;CACN,KAAK;CACL,OAAO;CACP,QAAQ;CACR,MAAM;CACN,SAAS;CACT,MAAM;CACN,OAAO;CACP,SAAS;AACX;;;;;;;;AASA,SAAgB,gBAAgB,SAAiB,MAAM,KAAK,IAAI,GAAgB;CAC9E,MAAM,OAAO,QAAQ,OAAO;CAoB5B,OAAO;EAAE;EAAM,aAAa;EAAK,aAlBb,CAAC,mBAAmB,IAAI,GAAG,yBAAyB,IAAI,CAAC,CAAC,CAC3E,QAAQ,aAAa,WAAW,QAAQ,CAAC,CA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,MAAM,OAAO,OAAO,YAAY;EACxG,SAAS,KAAK;GACZ,MAAM,SAAS,0BAA0B,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;EAC1F;EACA;CACF;CAIA,IAAI;EACF,UAAU,WAAW,UAAU,EAAE,WAAW,KAAK,CAAC;EAClD,cACE,KAAK,WAAW,UAAU,qBAAqB,GAC/C,GAAG,KAAK,UACN;GACE,qBAAI,IAAI,KAAK,EAAA,CAAE,YAAY;GAC3B,QAAQ;GACR,QAAQ;EACV,GACA,MACA,CACF,EAAE,KACF,MACF;EACA,MAAM,SAAS,4BAA4B,WAAW,GAAG;CAC3D,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"}
package/dist/tui/bin.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { n as runTopApp } from "../top-app-G4M18b6i.js";
2
+ import { n as runTopApp } from "../top-app-CH4cUgpo.js";
3
3
  //#region src/tui/bin.ts
4
4
  /**
5
5
  * `agent-runtime-top` — watch the supervisor runs of one workspace.
@@ -1,12 +1,14 @@
1
1
  //#region src/tui/top-app.d.ts
2
2
  /**
3
3
  * The interactive side of the supervisor-run TUI: a keypress/mouse loop over the frames
4
- * `./top-model` renders, plus the two operator controls that write back to the run — steer a live
5
- * worker, and request cancellation of a run.
4
+ * `./top-model` renders, plus the operator controls that write back to the run — steer a live
5
+ * worker, cancel one worker, and request cancellation of a whole run.
6
6
  *
7
- * Both controls go through the owned run layout: steers via `writeWorkerSteer` (the durable inbox
8
- * append), cancellation via a file inside the run directory the snapshot reported. Nothing here
9
- * joins a path from the workspace root.
7
+ * The controls go through the owned run layout: steers via `writeWorkerSteer` (the durable inbox
8
+ * append) and worker cancellation via `cancelWorker` (the acknowledged operation the runtime's
9
+ * turn loop applies). Run-level cancellation targets the ROOT, which has no acknowledged runtime
10
+ * path yet for a non-retained tree — it stays a `cancel.request.json` write inside the run
11
+ * directory for a host process to honor. Nothing here joins a path from the workspace root.
10
12
  *
11
13
  * Extracted from the `loops` repo (`src/top.ts`). The module-level singletons are the origin's
12
14
  * shape and are kept: this drives one terminal, and `runTopApp` is its one entry point.
package/dist/tui/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import { a as renderTopFrameWithLayout, i as renderTopFrame, n as runTopApp, r as loadTopSnapshot, t as renderTopOnce } from "../top-app-G4M18b6i.js";
1
+ import { a as renderTopFrameWithLayout, i as renderTopFrame, n as runTopApp, r as loadTopSnapshot, t as renderTopOnce } from "../top-app-CH4cUgpo.js";
2
2
  export { loadTopSnapshot, renderTopFrame, renderTopFrameWithLayout, renderTopOnce, runTopApp };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-runtime",
3
- "version": "0.134.7",
3
+ "version": "0.134.8",
4
4
  "description": "Shared task-lifecycle skeleton for agents: a recursive loop kernel for chat turns, one-shot tasks, and multi-attempt loops, with trace capture and eval-gated self-improvement. Domain behavior lives in adapters; scoring and ship-gates in @tangle-network/agent-eval.",
5
5
  "homepage": "https://github.com/tangle-network/agent-runtime#readme",
6
6
  "repository": {
@@ -1,158 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import { join, resolve } from "node:path";
3
- import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
4
- //#region src/runtime/supervise/run-layout.ts
5
- /**
6
- * The on-disk supervisor-run layout: `<root>/.agent/supervisor/<id>`.
7
- *
8
- * This is the durable, cross-process face of a supervisor run — the counterpart to the in-process
9
- * `Inbox` seam in `./inbox`. A run persists its state under one directory so that any OTHER process
10
- * can find it after the fact: `@tangle-network/traces` reads exactly this layout via
11
- * `traces analyze --supervisor-run-dir`, a restarted host can rehydrate a run it no longer holds
12
- * handles to, and a human can steer a live worker by appending one NDJSON line. Until now the
13
- * layout was defined only in the unpublished `loops` repo (`src/supervisor-control.ts`) — a
14
- * published reader depending on an unpublished writer's convention — so the contract is promoted
15
- * here, names preserved.
16
- *
17
- * `.agent` is the one dot-dir for ALL agent-owned state (skills already write
18
- * `.agent/hypotheses/`, `.agent/skill-runs.jsonl`); supervisor runs live beside them rather than
19
- * under a product-branded dir. Runs written by older writers used `.loops/supervisor/<id>` —
20
- * readers that must see those keep a legacy fallback; this writer never creates `.loops` again.
21
- *
22
- * Layout, relative to `supervisorRunDir(root, id)`:
23
- *
24
- * workers/<label>.inbox.ndjson down-leg steer/answer requests for one worker (durable inbox);
25
- * each line is a {@link WorkerSteerRequest}
26
- * workers/<label>.ndjson best-effort per-worker control-event log (delivery bookkeeping)
27
- *
28
- * Reads are tolerant by contract: a partial trailing line (a writer mid-append) or a corrupt line
29
- * never poisons the rest of the file — later valid lines still matter.
30
- *
31
- * Promoted from `loops/src/supervisor-control.ts`. The one deliberate difference: the loops version
32
- * resolved a worker id to its label through the run journal before writing a steer; that resolution
33
- * stays with the caller (it is journal-format-specific), so `writeWorkerSteer` here takes the worker
34
- * LABEL directly.
35
- *
36
- * @experimental
37
- */
38
- /** The root every supervisor run of one workspace lives under. */
39
- function supervisorRunsRoot(rootDir) {
40
- return join(resolve(rootDir), ".agent", "supervisor");
41
- }
42
- /** The run directory every artifact of one supervisor run lives under. */
43
- function supervisorRunDir(rootDir, id) {
44
- return join(supervisorRunsRoot(rootDir), id);
45
- }
46
- /**
47
- * Where a pre-rename writer put the same run (`<root>/.loops/supervisor/<id>`). Readers that must
48
- * see historical runs check {@link supervisorRunDir} first and fall back to this; nothing writes
49
- * here anymore.
50
- */
51
- function legacySupervisorRunDir(rootDir, id) {
52
- return join(legacySupervisorRunsRoot(rootDir), id);
53
- }
54
- /**
55
- * The pre-rename runs root (`<root>/.loops/supervisor`). Only readers that ENUMERATE historical
56
- * runs need this — the per-id form is {@link legacySupervisorRunDir}. Nothing writes here.
57
- */
58
- function legacySupervisorRunsRoot(rootDir) {
59
- return join(resolve(rootDir), ".loops", "supervisor");
60
- }
61
- /** A worker label reduced to a safe filename stem. Empty labels get a stable fallback. */
62
- function safeWorkerFile(label) {
63
- const safe = label.replace(/[^A-Za-z0-9._-]/g, "_");
64
- return safe.length > 0 ? safe : "worker";
65
- }
66
- /** The directory holding every per-worker file of one run (inboxes and control-event logs). */
67
- function supervisorWorkersDir(eventDir) {
68
- return join(eventDir, "workers");
69
- }
70
- /** The durable inbox file for one worker of one run. */
71
- function workerInboxFile(rootDir, supervisorId, worker) {
72
- return workerInboxFileFromEventDir(supervisorRunDir(rootDir, supervisorId), worker);
73
- }
74
- /** Same, addressed from an already-known run directory (the reader's usual entry point). */
75
- function workerInboxFileFromEventDir(eventDir, worker) {
76
- return join(supervisorWorkersDir(eventDir), `${safeWorkerFile(worker)}.inbox.ndjson`);
77
- }
78
- /**
79
- * The best-effort control-event log for one worker (`workers/<label>.ndjson`) — delivery
80
- * bookkeeping for steers, plus whatever lifecycle events a writer chooses to append. Distinct from
81
- * the inbox: the inbox is the durable down-leg queue, this is the record of what happened to it.
82
- */
83
- function workerControlLogFile(eventDir, worker) {
84
- return join(supervisorWorkersDir(eventDir), `${safeWorkerFile(worker)}.ndjson`);
85
- }
86
- /**
87
- * Durably append one steer request to a worker's inbox and log the delivery attempt.
88
- *
89
- * The inbox append is the durable act; the control-event log is best-effort bookkeeping and may
90
- * silently fail without voiding the steer.
91
- */
92
- function writeWorkerSteer(rootDir, supervisorId, worker, message, source = "human") {
93
- const trimmed = message.trim();
94
- if (!trimmed) throw new Error("steer message is empty");
95
- const dir = supervisorRunDir(rootDir, supervisorId);
96
- mkdirSync(supervisorWorkersDir(dir), { recursive: true });
97
- const request = {
98
- id: randomUUID(),
99
- at: (/* @__PURE__ */ new Date()).toISOString(),
100
- source,
101
- worker,
102
- message: trimmed
103
- };
104
- const file = workerInboxFile(rootDir, supervisorId, worker);
105
- appendFileSync(file, `${JSON.stringify(request)}\n`, "utf8");
106
- appendWorkerControlEvent(dir, worker, {
107
- kind: "message",
108
- direction: "down",
109
- source,
110
- requestId: request.id,
111
- message: trimmed,
112
- queued: true,
113
- delivered: false
114
- });
115
- return {
116
- worker,
117
- file,
118
- request
119
- };
120
- }
121
- /** Read every valid steer request in a worker's inbox. Corrupt or partial lines are skipped. */
122
- function readWorkerSteerRequests(eventDir, worker) {
123
- const file = workerInboxFileFromEventDir(eventDir, worker);
124
- if (!existsSync(file)) return [];
125
- const out = [];
126
- let raw = "";
127
- try {
128
- raw = readFileSync(file, "utf8");
129
- } catch {
130
- return out;
131
- }
132
- for (const line of raw.split("\n")) {
133
- const trimmed = line.trim();
134
- if (!trimmed) continue;
135
- try {
136
- const parsed = JSON.parse(trimmed);
137
- if (isWorkerSteerRequest(parsed)) out.push(parsed);
138
- } catch {}
139
- }
140
- return out;
141
- }
142
- function appendWorkerControlEvent(eventDir, label, event) {
143
- try {
144
- mkdirSync(supervisorWorkersDir(eventDir), { recursive: true });
145
- appendFileSync(workerControlLogFile(eventDir, label), `${JSON.stringify({
146
- at: (/* @__PURE__ */ new Date()).toISOString(),
147
- label,
148
- ...event
149
- })}\n`, "utf8");
150
- } catch {}
151
- }
152
- function isWorkerSteerRequest(value) {
153
- return typeof value.id === "string" && typeof value.at === "string" && typeof value.source === "string" && typeof value.worker === "string" && typeof value.message === "string" && value.message.trim().length > 0;
154
- }
155
- //#endregion
156
- export { supervisorRunDir as a, workerControlLogFile as c, writeWorkerSteer as d, safeWorkerFile as i, workerInboxFile as l, legacySupervisorRunsRoot as n, supervisorRunsRoot as o, readWorkerSteerRequests as r, supervisorWorkersDir as s, legacySupervisorRunDir as t, workerInboxFileFromEventDir as u };
157
-
158
- //# sourceMappingURL=run-layout-CeJsEAom.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"run-layout-CeJsEAom.js","names":[],"sources":["../src/runtime/supervise/run-layout.ts"],"sourcesContent":["/**\n * The on-disk supervisor-run layout: `<root>/.agent/supervisor/<id>`.\n *\n * This is the durable, cross-process face of a supervisor run — the counterpart to the in-process\n * `Inbox` seam in `./inbox`. A run persists its state under one directory so that any OTHER process\n * can find it after the fact: `@tangle-network/traces` reads exactly this layout via\n * `traces analyze --supervisor-run-dir`, a restarted host can rehydrate a run it no longer holds\n * handles to, and a human can steer a live worker by appending one NDJSON line. Until now the\n * layout was defined only in the unpublished `loops` repo (`src/supervisor-control.ts`) — a\n * published reader depending on an unpublished writer's convention — so the contract is promoted\n * here, names preserved.\n *\n * `.agent` is the one dot-dir for ALL agent-owned state (skills already write\n * `.agent/hypotheses/`, `.agent/skill-runs.jsonl`); supervisor runs live beside them rather than\n * under a product-branded dir. Runs written by older writers used `.loops/supervisor/<id>` —\n * readers that must see those keep a legacy fallback; this writer never creates `.loops` again.\n *\n * Layout, relative to `supervisorRunDir(root, id)`:\n *\n * workers/<label>.inbox.ndjson down-leg steer/answer requests for one worker (durable inbox);\n * each line is a {@link WorkerSteerRequest}\n * workers/<label>.ndjson best-effort per-worker control-event log (delivery bookkeeping)\n *\n * Reads are tolerant by contract: a partial trailing line (a writer mid-append) or a corrupt line\n * never poisons the rest of the file — later valid lines still matter.\n *\n * Promoted from `loops/src/supervisor-control.ts`. The one deliberate difference: the loops version\n * resolved a worker id to its label through the run journal before writing a steer; that resolution\n * stays with the caller (it is journal-format-specific), so `writeWorkerSteer` here takes the worker\n * LABEL directly.\n *\n * @experimental\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\n\n/** One durable down-leg request appended to a worker's inbox file. */\nexport interface WorkerSteerRequest {\n readonly id: string\n /** ISO timestamp of the append. */\n readonly at: string\n /** Who asked — 'human', a brain label, a tool name. Provenance, not authorization. */\n readonly source: string\n /** The worker LABEL the request targets (already resolved by the caller). */\n readonly worker: string\n readonly message: string\n}\n\n/** The root every supervisor run of one workspace lives under. */\nexport function supervisorRunsRoot(rootDir: string): string {\n return join(resolve(rootDir), '.agent', 'supervisor')\n}\n\n/** The run directory every artifact of one supervisor run lives under. */\nexport function supervisorRunDir(rootDir: string, id: string): string {\n return join(supervisorRunsRoot(rootDir), id)\n}\n\n/**\n * Where a pre-rename writer put the same run (`<root>/.loops/supervisor/<id>`). Readers that must\n * see historical runs check {@link supervisorRunDir} first and fall back to this; nothing writes\n * here anymore.\n */\nexport function legacySupervisorRunDir(rootDir: string, id: string): string {\n return join(legacySupervisorRunsRoot(rootDir), id)\n}\n\n/**\n * The pre-rename runs root (`<root>/.loops/supervisor`). Only readers that ENUMERATE historical\n * runs need this — the per-id form is {@link legacySupervisorRunDir}. Nothing writes here.\n */\nexport function legacySupervisorRunsRoot(rootDir: string): string {\n return join(resolve(rootDir), '.loops', 'supervisor')\n}\n\n/** A worker label reduced to a safe filename stem. Empty labels get a stable fallback. */\nexport function safeWorkerFile(label: string): string {\n const safe = label.replace(/[^A-Za-z0-9._-]/g, '_')\n return safe.length > 0 ? safe : 'worker'\n}\n\n/** The directory holding every per-worker file of one run (inboxes and control-event logs). */\nexport function supervisorWorkersDir(eventDir: string): string {\n return join(eventDir, 'workers')\n}\n\n/** The durable inbox file for one worker of one run. */\nexport function workerInboxFile(rootDir: string, supervisorId: string, worker: string): string {\n return workerInboxFileFromEventDir(supervisorRunDir(rootDir, supervisorId), worker)\n}\n\n/** Same, addressed from an already-known run directory (the reader's usual entry point). */\nexport function workerInboxFileFromEventDir(eventDir: string, worker: string): string {\n return join(supervisorWorkersDir(eventDir), `${safeWorkerFile(worker)}.inbox.ndjson`)\n}\n\n/**\n * The best-effort control-event log for one worker (`workers/<label>.ndjson`) — delivery\n * bookkeeping for steers, plus whatever lifecycle events a writer chooses to append. Distinct from\n * the inbox: the inbox is the durable down-leg queue, this is the record of what happened to it.\n */\nexport function workerControlLogFile(eventDir: string, worker: string): string {\n return join(supervisorWorkersDir(eventDir), `${safeWorkerFile(worker)}.ndjson`)\n}\n\n/**\n * Durably append one steer request to a worker's inbox and log the delivery attempt.\n *\n * The inbox append is the durable act; the control-event log is best-effort bookkeeping and may\n * silently fail without voiding the steer.\n */\nexport function writeWorkerSteer(\n rootDir: string,\n supervisorId: string,\n worker: string,\n message: string,\n source = 'human',\n): { worker: string; file: string; request: WorkerSteerRequest } {\n const trimmed = message.trim()\n if (!trimmed) throw new Error('steer message is empty')\n const dir = supervisorRunDir(rootDir, supervisorId)\n mkdirSync(supervisorWorkersDir(dir), { recursive: true })\n const request: WorkerSteerRequest = {\n id: randomUUID(),\n at: new Date().toISOString(),\n source,\n worker,\n message: trimmed,\n }\n const file = workerInboxFile(rootDir, supervisorId, worker)\n appendFileSync(file, `${JSON.stringify(request)}\\n`, 'utf8')\n appendWorkerControlEvent(dir, worker, {\n kind: 'message',\n direction: 'down',\n source,\n requestId: request.id,\n message: trimmed,\n queued: true,\n delivered: false,\n })\n return { worker, file, request }\n}\n\n/** Read every valid steer request in a worker's inbox. Corrupt or partial lines are skipped. */\nexport function readWorkerSteerRequests(eventDir: string, worker: string): WorkerSteerRequest[] {\n const file = workerInboxFileFromEventDir(eventDir, worker)\n if (!existsSync(file)) return []\n const out: WorkerSteerRequest[] = []\n let raw = ''\n try {\n raw = readFileSync(file, 'utf8')\n } catch {\n return out\n }\n for (const line of raw.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed) continue\n try {\n const parsed = JSON.parse(trimmed) as Partial<WorkerSteerRequest>\n if (isWorkerSteerRequest(parsed)) out.push(parsed)\n } catch {\n // Ignore partial or corrupt input lines; later valid lines still matter.\n }\n }\n return out\n}\n\nfunction appendWorkerControlEvent(\n eventDir: string,\n label: string,\n event: Record<string, unknown>,\n): void {\n try {\n mkdirSync(supervisorWorkersDir(eventDir), { recursive: true })\n appendFileSync(\n workerControlLogFile(eventDir, label),\n `${JSON.stringify({ at: new Date().toISOString(), label, ...event })}\\n`,\n 'utf8',\n )\n } catch {\n // Control logging is best-effort; the inbox write above is the durable part.\n }\n}\n\nfunction isWorkerSteerRequest(value: Partial<WorkerSteerRequest>): value is WorkerSteerRequest {\n return (\n typeof value.id === 'string' &&\n typeof value.at === 'string' &&\n typeof value.source === 'string' &&\n typeof value.worker === 'string' &&\n typeof value.message === 'string' &&\n value.message.trim().length > 0\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,SAAgB,mBAAmB,SAAyB;CAC1D,OAAO,KAAK,QAAQ,OAAO,GAAG,UAAU,YAAY;AACtD;;AAGA,SAAgB,iBAAiB,SAAiB,IAAoB;CACpE,OAAO,KAAK,mBAAmB,OAAO,GAAG,EAAE;AAC7C;;;;;;AAOA,SAAgB,uBAAuB,SAAiB,IAAoB;CAC1E,OAAO,KAAK,yBAAyB,OAAO,GAAG,EAAE;AACnD;;;;;AAMA,SAAgB,yBAAyB,SAAyB;CAChE,OAAO,KAAK,QAAQ,OAAO,GAAG,UAAU,YAAY;AACtD;;AAGA,SAAgB,eAAe,OAAuB;CACpD,MAAM,OAAO,MAAM,QAAQ,oBAAoB,GAAG;CAClD,OAAO,KAAK,SAAS,IAAI,OAAO;AAClC;;AAGA,SAAgB,qBAAqB,UAA0B;CAC7D,OAAO,KAAK,UAAU,SAAS;AACjC;;AAGA,SAAgB,gBAAgB,SAAiB,cAAsB,QAAwB;CAC7F,OAAO,4BAA4B,iBAAiB,SAAS,YAAY,GAAG,MAAM;AACpF;;AAGA,SAAgB,4BAA4B,UAAkB,QAAwB;CACpF,OAAO,KAAK,qBAAqB,QAAQ,GAAG,GAAG,eAAe,MAAM,EAAE,cAAc;AACtF;;;;;;AAOA,SAAgB,qBAAqB,UAAkB,QAAwB;CAC7E,OAAO,KAAK,qBAAqB,QAAQ,GAAG,GAAG,eAAe,MAAM,EAAE,QAAQ;AAChF;;;;;;;AAQA,SAAgB,iBACd,SACA,cACA,QACA,SACA,SAAS,SACsD;CAC/D,MAAM,UAAU,QAAQ,KAAK;CAC7B,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,wBAAwB;CACtD,MAAM,MAAM,iBAAiB,SAAS,YAAY;CAClD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