trantor 0.18.129 → 0.18.131

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.
package/bin/sim.mjs ADDED
@@ -0,0 +1,235 @@
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from "node:child_process";
3
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { tmpdir } from "node:os";
6
+ import { createHash } from "node:crypto";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ const AXE_INSTALL = `bash ${join(dirname(fileURLToPath(import.meta.url)), "install-axe.sh")}`;
10
+ const [, , verb, ...args] = process.argv;
11
+ const owner = process.env.RELAY_SESSION || process.env.CLAUDE_SESSION_ID || process.cwd();
12
+ const ownerId = createHash("sha256").update(owner).digest("hex").slice(0, 16);
13
+ const registryPath = process.env.TRANTOR_SIM_REGISTRY || join(tmpdir(), "trantor-sim-registry.json");
14
+ const outputRoot = process.env.TRANTOR_SIM_OUTPUT || join(process.cwd(), ".agent-bus-out", "sim");
15
+
16
+ function fail(reason) {
17
+ console.error(String(reason).trim() || "simulator command failed");
18
+ process.exit(1);
19
+ }
20
+
21
+ function command(file, argv, { optional = false } = {}) {
22
+ const result = spawnSync(file, argv, { encoding: "utf8", maxBuffer: 32 * 1024 * 1024 });
23
+ if (result.error?.code === "ENOENT" && optional) return null;
24
+ if (result.error) fail(`${file} failed: ${result.error.message}`);
25
+ if (result.status !== 0) fail((result.stderr || result.stdout || `${file} exited ${result.status}`).trim());
26
+ return result.stdout || "";
27
+ }
28
+
29
+ function axe(args) {
30
+ const result = spawnSync("axe", args, { encoding: "utf8", maxBuffer: 32 * 1024 * 1024 });
31
+ if (result.error?.code === "ENOENT") fail(`AXe is missing. Install the pinned release with: ${AXE_INSTALL}`);
32
+ if (result.error) fail(`axe failed: ${result.error.message}`);
33
+ if (result.status !== 0) fail((result.stderr || result.stdout || `axe exited ${result.status}`).trim());
34
+ return result.stdout || "";
35
+ }
36
+
37
+ function registry() {
38
+ try { return JSON.parse(readFileSync(registryPath, "utf8")); }
39
+ catch (error) {
40
+ if (error.code === "ENOENT") return { owners: {} };
41
+ fail(`cannot read simulator registry: ${error.message}`);
42
+ }
43
+ }
44
+
45
+ function saveRegistry(value) {
46
+ mkdirSync(dirname(registryPath), { recursive: true });
47
+ const temp = `${registryPath}.${process.pid}.tmp`;
48
+ writeFileSync(temp, JSON.stringify(value));
49
+ renameSync(temp, registryPath);
50
+ }
51
+
52
+ function simulators() {
53
+ let list;
54
+ try { list = JSON.parse(command("xcrun", ["simctl", "list", "devices", "--json"])); }
55
+ catch (error) { fail(`could not read Simulator devices: ${error.message}`); }
56
+ return Object.values(list.devices || {}).flat();
57
+ }
58
+
59
+ function selected() {
60
+ const id = registry().owners[ownerId]?.udid;
61
+ if (!id) fail("this session has no simulator; run trantor sim boot <device> first");
62
+ const device = simulators().find((item) => item.udid === id);
63
+ if (!device || device.state !== "Booted") fail(`owned simulator ${id} is not booted; run trantor sim boot <device>`);
64
+ return device;
65
+ }
66
+
67
+ function emit(value) { process.stdout.write(`${JSON.stringify(value)}\n`); }
68
+
69
+ function resolveDevice(name, devices) {
70
+ const matches = devices.filter((device) => device.udid === name || device.name === name);
71
+ if (matches.length === 0) fail(`simulator not found: ${name}`);
72
+ if (matches.length > 1) fail(`simulator name is ambiguous: ${name}; pass its UDID`);
73
+ return matches[0];
74
+ }
75
+
76
+ function parseTree(raw) {
77
+ let tree;
78
+ try { tree = JSON.parse(raw); }
79
+ catch { fail("AXe returned invalid accessibility JSON"); }
80
+ if (tree?.didError) fail(tree.error?.message || "AXe accessibility read failed");
81
+ const root = tree?.data?.result ?? tree;
82
+ const elements = [];
83
+ let maxX = 0, maxY = 0;
84
+ const visit = (node) => {
85
+ if (Array.isArray(node)) { for (const child of node) visit(child); return; }
86
+ if (!node || Object.getPrototypeOf(node) !== Object.prototype) return;
87
+ const frame = node.frame || node.AXFrame;
88
+ if (frame && Object.getPrototypeOf(frame) === Object.prototype) {
89
+ const x = Number(frame.x ?? 0), y = Number(frame.y ?? 0);
90
+ const width = Number(frame.width ?? 0), height = Number(frame.height ?? 0);
91
+ if ([x, y, width, height].every(Number.isFinite)) {
92
+ maxX = Math.max(maxX, x + width); maxY = Math.max(maxY, y + height);
93
+ const label = node.AXLabel ?? node.label ?? node.title ?? node.AXValue ?? "";
94
+ const role = node.role_description ?? node.role ?? node.type ?? node.AXRole ?? "";
95
+ const id = node.AXUniqueId ?? node.identifier ?? node.id;
96
+ if (label || role || id) {
97
+ const element = { frame: { x, y, width, height }, enabled: node.enabled ?? node.isEnabled ?? true };
98
+ if (label) element.label = String(label);
99
+ if (id) element.id = String(id);
100
+ if (role) element.role = String(role);
101
+ elements.push({ ...element, _hasLabelOrId: Boolean(label || id), _scrollBarSlider:
102
+ /slider/i.test(String(node.role ?? node.type ?? node.AXRole ?? ""))
103
+ && /scroll.?bar/i.test([node.role_description, node.roleDescription, node.AXLabel, node.label].filter(Boolean).join(" ")) });
104
+ }
105
+ }
106
+ }
107
+ for (const [key, value] of Object.entries(node)) if (key === "children" || key === "AXChildren") visit(value);
108
+ };
109
+ visit(root);
110
+ if (maxX <= 0 || maxY <= 0) fail("AXe accessibility tree has no screen-sized frame");
111
+ const widthPoints = Math.round(maxX), heightPoints = Math.round(maxY);
112
+ const visible = elements.filter((element) => {
113
+ if (element._scrollBarSlider) return false;
114
+ if (element._hasLabelOrId) return true;
115
+ const { x, y, width, height } = element.frame;
116
+ if (width <= 0 || height <= 0) return false;
117
+ if (x <= 0 && y <= 0 && width >= widthPoints && height >= heightPoints) return false;
118
+ return true;
119
+ }).map(({ _hasLabelOrId, _scrollBarSlider, ...element }) => element);
120
+ return { elements: visible, widthPoints, heightPoints };
121
+ }
122
+
123
+ function point(value, name) {
124
+ const coords = String(value || "").split(",").map(Number);
125
+ if (coords.length !== 2 || coords.some((part) => !Number.isFinite(part) || part < 0)) fail(`${name} must be x,y in simulator points`);
126
+ return coords;
127
+ }
128
+
129
+ function pointDimensions(device) {
130
+ const shared = registry();
131
+ const owned = shared.owners[ownerId];
132
+ if (owned.dimensionsPoints?.width > 0 && owned.dimensionsPoints?.height > 0) return owned.dimensionsPoints;
133
+ const tree = parseTree(axe(["describe-ui", "--minimal-keys", "--udid", device.udid]));
134
+ owned.dimensionsPoints = { width: tree.widthPoints, height: tree.heightPoints };
135
+ saveRegistry(shared);
136
+ return owned.dimensionsPoints;
137
+ }
138
+
139
+ function checkOnScreen(coords, name, dimensions) {
140
+ if (coords[0] >= dimensions.width || coords[1] >= dimensions.height) {
141
+ fail(`${name} point ${coords.join(",")} is outside the simulator screen (${dimensions.width}x${dimensions.height} points)`);
142
+ }
143
+ }
144
+
145
+ try {
146
+ if (verb === "boot") {
147
+ if (args.length !== 1 || !args[0]) fail("usage: trantor sim boot <device-name-or-udid>");
148
+ const devices = simulators();
149
+ const target = resolveDevice(args[0], devices);
150
+ const shared = registry();
151
+ const anotherOwner = Object.entries(shared.owners).find(([key, value]) => key !== ownerId && value.udid === target.udid);
152
+ if (anotherOwner) fail(`simulator ${target.name} is owned by another agent session`);
153
+ const bootedElsewhere = devices.find((device) => device.state === "Booted" && device.udid !== target.udid);
154
+ if (bootedElsewhere) fail(`another simulator is already booted (${bootedElsewhere.name}, ${bootedElsewhere.udid}); shut it down before booting ${target.name}`);
155
+ if (target.state !== "Booted") {
156
+ command("xcrun", ["simctl", "boot", target.udid]);
157
+ command("xcrun", ["simctl", "bootstatus", target.udid, "-b"]);
158
+ }
159
+ shared.owners[ownerId] = { udid: target.udid, name: target.name, startedAt: new Date().toISOString() };
160
+ saveRegistry(shared);
161
+ emit({ verb, udid: target.udid, device: target.name, reused: target.state === "Booted", state: "Booted" });
162
+ } else if (verb === "install") {
163
+ if (args.length !== 1) fail("usage: trantor sim install <app-path>");
164
+ const device = selected(), app = resolve(args[0]);
165
+ command("xcrun", ["simctl", "install", device.udid, app]);
166
+ emit({ verb, udid: device.udid, app });
167
+ } else if (verb === "launch") {
168
+ if (args.length !== 1) fail("usage: trantor sim launch <bundle-id>");
169
+ const device = selected();
170
+ const result = command("xcrun", ["simctl", "launch", device.udid, args[0]]).trim();
171
+ emit({ verb, udid: device.udid, bundle: args[0], result });
172
+ } else if (verb === "screen") {
173
+ const device = selected();
174
+ const outAt = args.indexOf("--out");
175
+ if (args.length && (outAt !== 0 || args.length !== 2 || !args[1])) fail("usage: trantor sim screen [--out <png-path>]");
176
+ const path = resolve(outAt === 0 ? args[1] : join(outputRoot, `screen-${Date.now()}.png`));
177
+ mkdirSync(dirname(path), { recursive: true });
178
+ command("xcrun", ["simctl", "io", device.udid, "screenshot", path]);
179
+ const tree = parseTree(axe(["describe-ui", "--minimal-keys", "--udid", device.udid]));
180
+ const shared = registry();
181
+ shared.owners[ownerId].dimensionsPoints = { width: tree.widthPoints, height: tree.heightPoints };
182
+ saveRegistry(shared);
183
+ const dimensions = command("sips", ["-g", "pixelWidth", "-g", "pixelHeight", path]);
184
+ const pixelWidth = Number(dimensions.match(/pixelWidth:\s*(\d+)/)?.[1]);
185
+ const pixelHeight = Number(dimensions.match(/pixelHeight:\s*(\d+)/)?.[1]);
186
+ if (!pixelWidth || !pixelHeight) fail("could not read screenshot dimensions with sips");
187
+ const scaledPath = `${path}.scaled.png`;
188
+ command("sips", ["-z", String(tree.heightPoints), String(tree.widthPoints), path, "--out", scaledPath]);
189
+ rmSync(path, { force: true });
190
+ command("/bin/mv", [scaledPath, path]);
191
+ emit({ verb, udid: device.udid, screenshot: path, dimensionsPoints: { width: tree.widthPoints, height: tree.heightPoints }, elements: tree.elements });
192
+ } else if (verb === "tap") {
193
+ const device = selected();
194
+ const mode = args[0], value = args[1];
195
+ if (args.length !== 2 || !["--label", "--id", "--xy"].includes(mode) || !value) fail("usage: trantor sim tap --label <text> | --id <identifier> | --xy x,y");
196
+ let target;
197
+ if (mode === "--xy") {
198
+ const coords = point(value, "--xy");
199
+ checkOnScreen(coords, "--xy", pointDimensions(device));
200
+ target = ["-x", String(coords[0]), "-y", String(coords[1])];
201
+ } else target = [mode, value];
202
+ axe(["tap", ...target, "--udid", device.udid]);
203
+ emit({ verb, udid: device.udid, selector: mode, target: value });
204
+ } else if (verb === "swipe") {
205
+ const device = selected();
206
+ if (args.length !== 4 || args[0] !== "--from" || args[2] !== "--to") fail("usage: trantor sim swipe --from x,y --to x,y");
207
+ const from = point(args[1], "--from"), to = point(args[3], "--to");
208
+ const dimensions = pointDimensions(device);
209
+ checkOnScreen(from, "--from", dimensions);
210
+ checkOnScreen(to, "--to", dimensions);
211
+ axe(["swipe", "--start-x", String(from[0]), "--start-y", String(from[1]), "--end-x", String(to[0]), "--end-y", String(to[1]), "--udid", device.udid]);
212
+ emit({ verb, udid: device.udid, from, to });
213
+ } else if (verb === "type") {
214
+ const device = selected(), value = args.join(" ");
215
+ if (!value) fail("usage: trantor sim type <text>");
216
+ axe(["type", value, "--udid", device.udid]);
217
+ emit({ verb, udid: device.udid, characters: [...value].length });
218
+ } else if (verb === "shutdown") {
219
+ if (args.length) fail("usage: trantor sim shutdown");
220
+ const shared = registry(), owned = shared.owners[ownerId];
221
+ if (!owned) { emit({ verb, shutdown: false, reason: "this session owns no simulator" }); }
222
+ else {
223
+ const device = simulators().find((item) => item.udid === owned.udid);
224
+ if (device?.state === "Booted") command("xcrun", ["simctl", "shutdown", owned.udid]);
225
+ delete shared.owners[ownerId];
226
+ saveRegistry(shared);
227
+ emit({ verb, udid: owned.udid, shutdown: device?.state === "Booted", alreadyShutdown: device?.state !== "Booted" });
228
+ }
229
+ } else {
230
+ fail("usage: trantor sim <boot|install|launch|screen|tap|swipe|type|shutdown>");
231
+ }
232
+ } catch (error) {
233
+ if (error?.message) fail(error.message);
234
+ fail("simulator command failed");
235
+ }
package/hooks/lib/api.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  // Wraps lib/signed-fetch.mjs (#3916) with hub URL resolution per project (§12.1), session identity
3
3
  // (the same derivation mcp.mjs uses) and the Ed25519 keypair. FAIL-OPEN IS A CONTRACT (acceptance §9
4
4
  // #10): getJSON/signedPost never throw; no key means unsigned, and only the hub knows its RELAY_AUTH policy.
5
- import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
5
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, appendFileSync } from "node:fs";
6
6
  import { join } from "node:path";
7
7
  import { homedir } from "node:os";
8
8
  import { resolveProject, hostId, resolveHub } from "../../lib/project.mjs";
@@ -12,6 +12,22 @@ import { sfetchJson } from "../../lib/signed-fetch.mjs";
12
12
  export const DEFAULT_TIMEOUT_MS = 1500;
13
13
  export const WRITE_TIMEOUT_MS = 8000; // #7755: writes get their own budget above the read default
14
14
 
15
+ function recordAmbiguousTimeout(pathOrUrl, op, elapsedMs, project) {
16
+ const busDir = process.env.AGENT_BUS_DIR || join(homedir(), ".agent-bus");
17
+ const file = join(busDir, "hub-timeouts.jsonl");
18
+ const row = {
19
+ ts: new Date().toISOString(),
20
+ route: String(pathOrUrl),
21
+ op,
22
+ elapsedMs,
23
+ hubUrl: relayUrl(project),
24
+ };
25
+ try {
26
+ mkdirSync(busDir, { recursive: true });
27
+ appendFileSync(file, `${JSON.stringify(row)}\n`, { mode: 0o600 });
28
+ } catch { /* timeout reporting must never change the fail-open result */ }
29
+ }
30
+
15
31
  // Hub URL, PER-PROJECT (TDD §12.1): env RELAY_URL, then config `hubs[project]`, then the legacy global
16
32
  // `url`, then the local default. Never throws, keeping hooks fail-open.
17
33
  export function relayUrl(project) {
@@ -180,6 +196,7 @@ export async function signedGet(pathOrUrl, { timeoutMs = DEFAULT_TIMEOUT_MS, ses
180
196
  // one GET /_op — committed returns the stored body as success, rejected returns the stored refusal,
181
197
  // unknown reads "ambiguous: timed out, outcome unknown". Never a bare failure for a write that landed.
182
198
  export async function signedPost(pathOrUrl, payload, { timeoutMs = WRITE_TIMEOUT_MS, session, instance, project } = {}) {
199
+ const startedAt = Date.now();
183
200
  const proj = projectOf(project, payload, pathOrUrl);
184
201
  const sess = session || sessionFor(proj);
185
202
  const durable = loadIdentity(sess);
@@ -193,6 +210,7 @@ export async function signedPost(pathOrUrl, payload, { timeoutMs = WRITE_TIMEOUT
193
210
  const st = q.ok ? q.json?.status : "unknown";
194
211
  if (st === "committed") return { ok: true, status: q.json.code || 200, json: q.json.body, resolved: "committed" };
195
212
  if (st === "rejected") return { ok: false, status: q.json.code || 400, json: q.json.body, resolved: "rejected" };
213
+ recordAmbiguousTimeout(pathOrUrl, op, Date.now() - startedAt, proj);
196
214
  return { ...f, ambiguous: true, reason: "ambiguous: timed out, outcome unknown" };
197
215
  };
198
216
  try {
package/hub/auth.mjs CHANGED
@@ -6,7 +6,7 @@ import { timingSafeEqual, randomBytes } from "node:crypto";
6
6
  import { publicView } from "../lib/identity.mjs";
7
7
  import { IDENTITY_KINDS } from "../lib/store-contract.mjs";
8
8
 
9
- export function createAuthRuntime({ state, markDirty, AUTH_MODE, SUPERSEDE_GRACE_MS, LOOPBACK_BIND, ENROLL_MODE, seenNonces = new Map() }) {
9
+ export function createAuthRuntime({ state, markDirty, AUTH_MODE, SUPERSEDE_GRACE_MS, LOOPBACK_BIND, ENROLL_MODE, seenNonces = new Map(), diagnostics = null }) {
10
10
  const now = () => Date.now();
11
11
  // Route measurements and supported envelopes: docs/REQUEST-BODY-LIMITS.md.
12
12
  const BODY_CAP_DEFAULT = 4 * 1024 * 1024;
@@ -61,7 +61,9 @@ async function body(req, maxBytes = BODY_CAP_DEFAULT) {
61
61
  function json(res, code, obj) {
62
62
  if (res.headersSent || res.writableEnded || res.destroyed) return false;
63
63
  res.writeHead(code, { "content-type": "application/json", "access-control-allow-origin": "*" });
64
- res.end(JSON.stringify(obj));
64
+ const payload = JSON.stringify(obj);
65
+ diagnostics?.recordStep("response.serialize", Buffer.byteLength(payload));
66
+ res.end(payload);
65
67
  return true;
66
68
  }
67
69
  // Canonical project name: follow the alias chain so historically-divergent keys
@@ -96,7 +98,7 @@ const AUTH_HEADERS = ["x-trantor-pubkey", "x-trantor-sig", "x-trantor-ts", "x-tr
96
98
  const PUBLIC_ENDPOINTS = new Set(["/", "/ui", "/health", "/enroll"]);
97
99
  const OWNER_ENDPOINTS = new Set(["/project/delete", "/sweep", "/reconcile", "/invite", "/import", "/policy", "/session/prompts", "/session/prompt/claim", "/session/prompt/ack", "/session/attachment"]);
98
100
  const DEVICE_ENDPOINTS = new Set(["/device/register", "/device/unregister", "/devices"]);
99
- const READ_ENDPOINTS = new Set(["/peers", "/tasks", "/events", "/inbox", "/peer", "/card", "/stream", "/history", "/projects", "/catchup", "/phases", "/recent", "/handoffs", "/verify-gates", "/claims", "/proposals", "/grants", "/overseer/context", "/overseer/status", "/session/chat", "/session/prompt", "/crew/roster"]);
101
+ const READ_ENDPOINTS = new Set(["/peers", "/tasks", "/events", "/inbox", "/peer", "/card", "/stream", "/history", "/projects", "/catchup", "/phases", "/recent", "/handoffs", "/verify-gates", "/claims", "/proposals", "/grants", "/overseer/context", "/overseer/status", "/session/chat", "/session/prompt", "/crew/roster", "/machines/health"]);
100
102
  const roleRank = { read: 1, write: 2, approver: 3, owner: 4 };
101
103
  const hasAuthHeaders = (req) => AUTH_HEADERS.some(h => !!req.headers[h]);
102
104
  const authPath = (u) => `${u.pathname}${u.search || ""}`;
package/hub/public.mjs CHANGED
@@ -4,7 +4,8 @@ import { HDR } from "../lib/identity.mjs";
4
4
  const ALLOWED = new Set([
5
5
  ...["/health", "/projects", "/catchup", "/tasks", "/card", "/events", "/stream",
6
6
  "/inbox", "/poll", "/recent", "/peers", "/holds", "/verify-gates", "/proposals",
7
- "/balances", "/economics", "/session/chat", "/session/prompt", "/crew/roster", "/_op"]
7
+ "/balances", "/economics", "/session/chat", "/session/prompt", "/crew/roster",
8
+ "/machines/health", "/_op"]
8
9
  .map(path => `GET ${path}`),
9
10
  ...["/enroll", "/task/update", "/task/checklist-toggle", "/send", "/delivered",
10
11
  "/verify-gate", "/hold/decide", "/proposal/decide", "/session/prompt", "/session/answer",
@@ -34,6 +34,12 @@ export async function routeMessages({ req, res, q, P, auth, ctx }) {
34
34
  // it (#6134). Stored only when false — absent means wake, so every older client is unchanged.
35
35
  const wake = b.wake === false ? { wake: false } : {};
36
36
  const msg = { id: ++state.seq, ts: now(), from: b.from || "anon", to: b.to || "all", text, project: String(b.project || fromProj || "").slice(0, 80), ...(re ? { re } : {}), ...(kind ? { kind } : {}), ...wake };
37
+ const peer = state.peers[msg.from];
38
+ if (msg.to === "all" && msg.kind === "status" && peer?.status === "crew member booting" && /^[A-Za-z0-9_.-]+ reporting — ready for a contract\b/.test(msg.text.trim())) {
39
+ peer.status = "idle";
40
+ peer.phase = "idle";
41
+ peer.phaseSince = msg.ts;
42
+ }
37
43
  state.messages.push(msg); if (state.messages.length > 5000) state.messages.splice(0, 1000);
38
44
  markDirty(); pushToStreams(msg); // <-- instant push to live watchers
39
45
  // Mirror onto the unified log. `refs` = the card ids this message cites (#3701), which is what
@@ -217,10 +217,23 @@ export function createSessionRuntime({ state, markDirty, appendEvent, pushEventT
217
217
  }
218
218
  }
219
219
 
220
- // #12140: the desktop publishes the seats its Mac can spawn (from `trantor provider status
221
- // --json`) at boot and every 10 minutes. Memory-only like the chat mirror — a restarted hub
222
- // has no roster until the desktop republishes.
223
- const roster = new Map(); // machine -> { machine, updatedAt, seats }
220
+ // #12140: the desktop publishes the seats its Mac can spawn (from `trantor provider status
221
+ // --json`) at boot and every 10 minutes. Memory-only like the chat mirror — a restarted hub
222
+ // has no roster until the desktop republishes.
223
+ const roster = new Map(); // machine -> { machine, updatedAt, seats }
224
+
225
+ // #13920: machine health heartbeat — the crew-runner on each seat-hosting machine POSTs its
226
+ // loadavg/memory every ~30s (config healthHeartbeat:true). Memory-only like the roster; the ts is
227
+ // the hub's RECEIVE time, never the sender's clock, so a skewed machine clock cannot poison the
228
+ // staleness math. Rows older than a day are pruned: a decommissioned machine must not read
229
+ // "stale" forever. State, not events — nothing here is appended to the audit log.
230
+ const machinesHealth = new Map(); // machine -> { machine, cpuPct, memUsed, memTotal, ts }
231
+ const HEALTH_STALE_MS = Number(process.env.RELAY_HEALTH_STALE_MS || 90_000);
232
+ const HEALTH_KEEP_MS = 24 * 60 * 60 * 1000;
233
+ function pruneMachinesHealth() {
234
+ const cut = now() - HEALTH_KEEP_MS;
235
+ for (const [m, h] of machinesHealth) if (h.ts < cut) machinesHealth.delete(m);
236
+ }
224
237
 
225
238
  async function route({ req, res, q, P, auth, ctx }) {
226
239
  const isChat = P === "/session/chat";
@@ -230,7 +243,8 @@ export function createSessionRuntime({ state, markDirty, appendEvent, pushEventT
230
243
  const isAnswer = P === "/session/answer";
231
244
  const isCrewCommand = P === "/crew/command";
232
245
  const isCrewRoster = P === "/crew/roster";
233
- if (!isChat && !isPrompts && !isPrompt && !isAttachment && !isAnswer && !isCrewCommand && !isCrewRoster) return false;
246
+ const isMachinesHealth = P === "/machines/health";
247
+ if (!isChat && !isPrompts && !isPrompt && !isAttachment && !isAnswer && !isCrewCommand && !isCrewRoster && !isMachinesHealth) return false;
234
248
  const { body, json, canon, scopeAllows } = ctx;
235
249
 
236
250
  // #12137: the phone's answer to an AskUserQuestion joins the SAME queue as a plain prompt,
@@ -346,6 +360,33 @@ export function createSessionRuntime({ state, markDirty, appendEvent, pushEventT
346
360
  return json(res, 200, { machines: [...roster.values()] });
347
361
  }
348
362
 
363
+ // #13920: a seat-signed POST (write on its own project, machine label from the body — the
364
+ // signer is a seat like "glm:trantor", not a machine, so the roster's signer-keying cannot
365
+ // apply). The label is held to the machineLabel grammar and every number is validated; the
366
+ // payload ts is ignored in favour of the hub's receive time.
367
+ if (req.method === "POST" && isMachinesHealth) {
368
+ const b = await body(req);
369
+ const machine = String(b.machine || "");
370
+ if (!/^[a-z0-9-]{1,24}$/.test(machine)) return json(res, 400, { error: "machine must match ^[a-z0-9-]{1,24}$" });
371
+ const cpuPct = Number(b.cpuPct);
372
+ if (!Number.isFinite(cpuPct) || cpuPct < 0 || cpuPct > 100000) return json(res, 400, { error: "cpuPct must be a finite percent (load can exceed 100)" });
373
+ const memUsed = Number(b.memUsed);
374
+ const memTotal = Number(b.memTotal);
375
+ if (!Number.isFinite(memUsed) || !Number.isFinite(memTotal) || memUsed < 0 || memTotal <= 0 || memUsed > memTotal) {
376
+ return json(res, 400, { error: "memUsed/memTotal must be bytes with used <= total" });
377
+ }
378
+ machinesHealth.set(machine, { machine, cpuPct: Math.round(cpuPct), memUsed: Math.round(memUsed), memTotal: Math.round(memTotal), ts: now() });
379
+ return json(res, 200, { ok: true, machine });
380
+ }
381
+
382
+ if (req.method === "GET" && isMachinesHealth) {
383
+ pruneMachinesHealth();
384
+ const machines = [...machinesHealth.values()]
385
+ .map(h => ({ ...h, stale: now() - h.ts > HEALTH_STALE_MS }))
386
+ .sort((a, b) => a.machine.localeCompare(b.machine));
387
+ return json(res, 200, { machines, staleAfterMs: HEALTH_STALE_MS });
388
+ }
389
+
349
390
  if (req.method === "POST" && isChat) {
350
391
  const b = await body(req);
351
392
  // the same canon the GET reads with, or a publish and a read could name two mirrors
package/hub/store.mjs CHANGED
@@ -4,7 +4,7 @@ import { randomBytes } from "node:crypto";
4
4
  import { createPersistHealth } from "../lib/persist-health.mjs";
5
5
  import { DEFAULT_ORG } from "../lib/store-contract.mjs";
6
6
 
7
- export async function createStoreRuntime({ STORE_KIND, PG_URL, ORG_ID, DATA }) {
7
+ export async function createStoreRuntime({ STORE_KIND, PG_URL, ORG_ID, DATA, diagnostics = null }) {
8
8
  function emptyState() {
9
9
  return { messages: [], peers: {}, seq: 0, tasks: [], taskSeq: 0, projectMeta: {}, lessons: [], events: [], cardEventsBackfilled: false, aliases: {}, phaseMeta: {}, verifyGates: [], verifyGateSeq: 0, proposals: [], proposalSeq: 0, balances: { ts: 0, by: "", entries: [] }, balancesByMachine: {}, subagentCostReset: false, handoffLog: [], identities: {}, devices: [], inviteTokens: {}, focus: {}, orgPolicy: {}, overseerState: {}, instances: {}, dutySession: "", contractReap: {}, eventSeq: 0, sessionPrompts: [], sessionPromptSeq: 0 };
10
10
  }
@@ -195,7 +195,9 @@ const snapshotState = () => {
195
195
  const cardEvents = events.filter(e => ["created", "moved", "updated"].includes(e?.type));
196
196
  const messages = state.messages.slice();
197
197
  const tasks = state.tasks.slice();
198
- const snapshot = JSON.parse(JSON.stringify({ ...state, events: [], cardEvents: [], messages: [], tasks: [] }));
198
+ const serialized = JSON.stringify({ ...state, events: [], cardEvents: [], messages: [], tasks: [] });
199
+ diagnostics?.recordStep("snapshot.serialize", Buffer.byteLength(serialized));
200
+ const snapshot = JSON.parse(serialized);
199
201
  snapshot.events = events;
200
202
  snapshot.cardEvents = cardEvents;
201
203
  snapshot.messages = messages;
@@ -233,7 +235,9 @@ const persist = () => {
233
235
  return;
234
236
  }
235
237
  try {
236
- writeFileSync(DATA, JSON.stringify(snapshotState()));
238
+ const serialized = JSON.stringify(snapshotState());
239
+ diagnostics?.recordStep("json.persist.serialize", Buffer.byteLength(serialized));
240
+ writeFileSync(DATA, serialized);
237
241
  dirty = false;
238
242
  persistHealth.succeeded();
239
243
  } catch (e) {
package/hub.mjs CHANGED
@@ -21,6 +21,7 @@ import { routeMessages } from "./hub/routes/messages.mjs";
21
21
  import { routeDevices } from "./hub/routes/devices.mjs";
22
22
  import { createSessionRuntime } from "./hub/routes/session.mjs";
23
23
  import { createNotifier } from "./hub/notifier.mjs";
24
+ import { createHubDiagnostics } from "./lib/hub-diagnostics.mjs";
24
25
 
25
26
  const PORT = Number(process.env.RELAY_PORT || 4477);
26
27
  const HOST = process.env.RELAY_HOST || "127.0.0.1";
@@ -65,11 +66,12 @@ if (!LOOPBACK_BIND && AUTH_MODE !== "enforce") {
65
66
  process.exit(1);
66
67
  }
67
68
 
68
- const store = await createStoreRuntime({ STORE_KIND, PG_URL, ORG_ID, DATA });
69
+ const diagnostics = createHubDiagnostics();
70
+ const store = await createStoreRuntime({ STORE_KIND, PG_URL, ORG_ID, DATA, diagnostics });
69
71
  const seenNonces = new Map();
70
72
  const authRuntime = createAuthRuntime({
71
73
  state: store.state, markDirty: store.markDirty, AUTH_MODE, SUPERSEDE_GRACE_MS,
72
- LOOPBACK_BIND, ENROLL_MODE, seenNonces,
74
+ LOOPBACK_BIND, ENROLL_MODE, seenNonces, diagnostics,
73
75
  });
74
76
  const notifier = createNotifier({ state: store.state, markDirty: store.markDirty, canRead: authRuntime.canRead });
75
77
  const events = createEventRuntime({ state: store.state, markDirty: store.markDirty, AUTH_MODE, ONLINE_MS, canon: authRuntime.canon, notifier });
@@ -140,12 +142,16 @@ const routes = [routeDevices, routeAdmin, routeCards, routeInsights, routeMessag
140
142
 
141
143
  const publicAuth = createAuthRuntime({
142
144
  state: store.state, markDirty: store.markDirty, AUTH_MODE: "enforce", SUPERSEDE_GRACE_MS,
143
- LOOPBACK_BIND: true, ENROLL_MODE: "invite", seenNonces,
145
+ LOOPBACK_BIND: true, ENROLL_MODE: "invite", seenNonces, diagnostics,
144
146
  });
145
147
  const publicContext = { ...context, ...publicAuth, AUTH_MODE: "enforce" };
146
148
 
147
149
  function requestHandler(runtime, ctx, gate = null) {
148
150
  return async (req, res) => {
151
+ diagnostics.beginRequest(req);
152
+ const finish = () => diagnostics.endRequest(req, res);
153
+ res.once("finish", finish);
154
+ res.once("close", finish);
149
155
  try {
150
156
  const u = new URL(req.url, "http://x");
151
157
  const q = Object.fromEntries(u.searchParams);
@@ -190,6 +196,7 @@ function requestHandler(runtime, ctx, gate = null) {
190
196
  };
191
197
  }
192
198
 
199
+ diagnostics.start();
193
200
  const server = http.createServer(requestHandler(authRuntime, context));
194
201
  server.listen(PORT, HOST, () => console.error(`[trantor] hub on http://${HOST}:${PORT} (auth: ${AUTH_MODE}; data: ${DATA})`));
195
202
 
package/lib/disk.mjs CHANGED
@@ -26,7 +26,7 @@ export const JUNK_DIRS = ["node_modules", ".next", "target", "dist", "build", ".
26
26
  export const DRILL_DIR = ".agent-bus-out";
27
27
  export const LOW_SPACE_BYTES = 50 * 1024 ** 3;
28
28
  export const ALARM_SPACE_BYTES = 15 * 1024 ** 3;
29
- const ON_DISK_TYPES = ["build-dir", "scratch-entry", "seat-worktree", "build-output", "build-junk", "drill-output"];
29
+ const ON_DISK_TYPES = ["build-dir", "scratch-entry", "seat-worktree", "build-output", "build-junk", "drill-output", "shared-cache"];
30
30
 
31
31
  const GB = 1024 ** 3;
32
32
  const KB = 1024;
@@ -84,6 +84,7 @@ function defaults(d = {}) {
84
84
  now: d.now || Date.now(),
85
85
  worktreesRoot: d.worktreesRoot || null,
86
86
  cwds: d.cwds || memoCwds(d.exec),
87
+ isPidAlive: d.isPidAlive,
87
88
  log: d.log || console.log,
88
89
  entryBudget: d.entryBudget || 400_000,
89
90
  };
@@ -95,6 +96,56 @@ export function worktreesRootFor(d) {
95
96
  return d.worktreesRoot || join(d.home || homedir(), ".agent-bus", "worktrees");
96
97
  }
97
98
 
99
+ export function cacheRootFor(d) {
100
+ return join(d.home || homedir(), ".agent-bus", "cache");
101
+ }
102
+
103
+ export function hasActiveHeavyGate({ fs = nodeFs, home = homedir(), isPidAlive = (pid) => {
104
+ try { process.kill(pid, 0); return true; } catch (error) { return error?.code !== "ESRCH"; }
105
+ } } = {}) {
106
+ const lockDir = join(home, ".agent-bus", "heavy-gate");
107
+ let entries;
108
+ try { entries = fs.readdirSync(lockDir, { withFileTypes: true }); } catch { return false; }
109
+ return entries.some((entry) => {
110
+ if (!entry.isFile() || !/^slot-\d+\.json$/.test(entry.name)) return false;
111
+ try {
112
+ const row = JSON.parse(fs.readFileSync(join(lockDir, entry.name), "utf8"));
113
+ return Number.isSafeInteger(row.pid) && isPidAlive(row.pid);
114
+ } catch { return false; }
115
+ });
116
+ }
117
+
118
+ // Shared cache output uses the same three-day idle window as per-seat build output. A gate
119
+ // can compile from any project's cache, so an active slot protects every shared cache.
120
+ export function scanSharedBuildCache(d) {
121
+ const dep = defaults(d);
122
+ const { fs, home, now } = dep;
123
+ if (hasActiveHeavyGate({ fs, home, isPidAlive: d.isPidAlive }))
124
+ return { plan: [], kept: [{ path: cacheRootFor(d), reason: "KEPT: a heavy-gate slot is active" }] };
125
+ const root = cacheRootFor(d), plan = [], kept = [];
126
+ let projects;
127
+ try { projects = fs.readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory()); }
128
+ catch { return { plan, kept }; }
129
+ for (const project of projects) {
130
+ const projectDir = join(root, project.name);
131
+ for (const name of ["cargo-target", "DerivedData"]) {
132
+ const path = join(projectDir, name);
133
+ let stat;
134
+ try { stat = fs.statSync(path); } catch { continue; }
135
+ if (!stat.isDirectory()) continue;
136
+ const size = dirSize(fs, path, d);
137
+ if (size.partial) { kept.push({ path, reason: "KEPT: size walk exceeded entry budget" }); continue; }
138
+ if (size.maxMtime > now - BUILD_OUTPUT_IDLE_MAX) {
139
+ kept.push({ path, reason: `KEPT: cache was touched within ${BUILD_OUTPUT_IDLE_MAX / DAY} days` });
140
+ continue;
141
+ }
142
+ plan.push({ type: "shared-cache", path, project: project.name, bytes: size.bytes });
143
+ }
144
+ }
145
+ plan.sort((a, b) => b.bytes - a.bytes);
146
+ return { plan, kept };
147
+ }
148
+
98
149
  // Recursive size walk. Skips symlinks entirely — a worktree symlink must not make
99
150
  // us measure (or later rm) outside its root. Budget caps pathological trees. Dirs are
100
151
  // statted too: a rename into an old tree updates the DIR mtime, not the file's, and
@@ -533,6 +584,7 @@ export function buildDiskReport(d) {
533
584
  const seats = scanSeatWorktrees({ ...dep, entryBudget: dep.entryBudget });
534
585
  const stale = scanStaleWorktrees({ ...dep, entryBudget: dep.entryBudget });
535
586
  const nested = scanNestedBuildOutput({ ...dep, entryBudget: dep.entryBudget });
587
+ const sharedCache = scanSharedBuildCache({ ...dep, entryBudget: dep.entryBudget });
536
588
  const junk = scanDeadWorktreeOutput({ ...dep, entryBudget: dep.entryBudget });
537
589
  const sessions = scanOpencodeSessions(dep);
538
590
  const sims = scanSimulators(dep);
@@ -549,8 +601,8 @@ export function buildDiskReport(d) {
549
601
  hf: reportHfCache(dep),
550
602
  claudeWorktrees: reportClaudeWorktrees(dep),
551
603
  bigFiles: collectBigFiles(dep),
552
- plan: mergePlans([...sims.plan, ...seats.plan, ...stale.plan, ...nested.plan], stale.plan, junk.plan).concat(sessions.plan),
553
- kept: [...seats.kept, ...stale.kept, ...nested.kept].filter((k) => !junk.plan.some((j) => isUnder(k.path, j.path))).concat(junk.kept, sessions.kept),
604
+ plan: mergePlans([...sims.plan, ...seats.plan, ...stale.plan, ...nested.plan, ...sharedCache.plan], stale.plan, junk.plan).concat(sessions.plan),
605
+ kept: [...seats.kept, ...stale.kept, ...nested.kept, ...sharedCache.kept].filter((k) => !junk.plan.some((j) => isUnder(k.path, j.path))).concat(junk.kept, sessions.kept),
554
606
  };
555
607
  return report;
556
608
  }
@@ -624,11 +676,19 @@ export async function runClean(r, d) {
624
676
  try {
625
677
  if (item.path) {
626
678
  const p = assertUnderHome(item.path, home);
627
- if (!isUnder(p, root)) throw new Error(`refused: ${p} is not under the seat worktrees root`);
628
- const [project, seat] = relative(root, p).split(sep);
629
- if (!project || !seat) throw new Error("refused: path does not identify a seat worktree");
630
- const reason = seatRetentionReason(dep, project, seat, join(root, project, seat));
631
- if (reason) throw new Error(reason);
679
+ if (item.type === "shared-cache") {
680
+ const cacheRoot = cacheRootFor(dep);
681
+ const cacheParts = relative(cacheRoot, p).split(sep);
682
+ if (!isUnder(p, cacheRoot) || cacheParts.length !== 2 || !["cargo-target", "DerivedData"].includes(cacheParts[1]))
683
+ throw new Error(`refused: ${p} is not a project cache directory`);
684
+ if (hasActiveHeavyGate({ fs: dep.fs, home, isPidAlive: dep.isPidAlive })) throw new Error("refused: a heavy-gate slot is active");
685
+ } else {
686
+ if (!isUnder(p, root)) throw new Error(`refused: ${p} is not under the seat worktrees root`);
687
+ const [project, seat] = relative(root, p).split(sep);
688
+ if (!project || !seat) throw new Error("refused: path does not identify a seat worktree");
689
+ const reason = seatRetentionReason(dep, project, seat, join(root, project, seat));
690
+ if (reason) throw new Error(reason);
691
+ }
632
692
  }
633
693
  if (item.type === "simulators") {
634
694
  exec("xcrun", ["simctl", "delete", "unavailable"]);
@@ -643,6 +703,12 @@ export async function runClean(r, d) {
643
703
  const g = exec("git", ["-C", p, "worktree", "remove", p]);
644
704
  if (g.status !== 0) throw new Error(String(g.stderr || "git worktree remove failed").trim().split("\n")[0] || "git worktree remove failed");
645
705
  results.push({ type: item.type, path: p, bytes: item.bytes || 0, ok: true });
706
+ } else if (item.type === "shared-cache") {
707
+ if (hasActiveHeavyGate({ fs: dep.fs, home, isPidAlive: dep.isPidAlive })) throw new Error("refused: a heavy-gate slot is active");
708
+ const stat = dirSize(dep.fs, item.path, dep);
709
+ if (stat.partial || stat.maxMtime > dep.now - BUILD_OUTPUT_IDLE_MAX) throw new Error("refused: cache changed or is too recent");
710
+ remove(item.path, { recursive: true, force: true });
711
+ results.push({ type: item.type, path: item.path, bytes: item.bytes || 0, ok: true });
646
712
  } else if (["build-dir", "build-output", "scratch-entry", "build-junk", "drill-output"].includes(item.type)) {
647
713
  const p = assertUnderHome(item.path, home);
648
714
  if (!isUnder(p, root)) throw new Error(`refused: ${p} is not under the seat worktrees root`);