@50arms/platform-mcp 0.1.463 → 0.1.465

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 (67) hide show
  1. package/dist/access-request.js +19 -6
  2. package/dist/agent-gate.js +19 -5
  3. package/dist/board-id.js +8 -2
  4. package/dist/checkout-docs-root.js +10 -2
  5. package/dist/clear-control.js +18 -4
  6. package/dist/compaction-control.js +30 -7
  7. package/dist/credential.js +10 -2
  8. package/dist/danxbot-api-examples.js +20 -3
  9. package/dist/design-screenshot.js +22 -5
  10. package/dist/digest-hold.js +14 -3
  11. package/dist/docs-tools.js +46 -12
  12. package/dist/durable-write.js +10 -2
  13. package/dist/forbidden-hint.js +13 -2
  14. package/dist/guarded-calls.js +7 -2
  15. package/dist/handlers.js +70 -15
  16. package/dist/heartbeat-reporter.js +8 -3
  17. package/dist/http-client.js +5 -3
  18. package/dist/index.js +252 -82
  19. package/dist/job-key.js +47 -0
  20. package/dist/json-body.js +3 -1
  21. package/dist/key-revoked-halt.js +2 -1
  22. package/dist/leftover-wire.js +17 -4
  23. package/dist/lifecycle.js +11 -3
  24. package/dist/listen.js +242 -64
  25. package/dist/listener-reminder.js +8 -2
  26. package/dist/machine-daemon/autostart.js +16 -4
  27. package/dist/machine-daemon/beat.js +18 -4
  28. package/dist/machine-daemon/cli.js +15 -4
  29. package/dist/machine-daemon/install.js +33 -9
  30. package/dist/machine-daemon/leftovers.js +134 -30
  31. package/dist/machine-daemon/state.js +9 -3
  32. package/dist/machine-daemon.js +531 -128
  33. package/dist/machine-registration.js +27 -6
  34. package/dist/machine-secret.js +8 -3
  35. package/dist/machine-toolkit.js +377 -81
  36. package/dist/mini-app-build.js +19 -5
  37. package/dist/mini-app-checkout.js +38 -10
  38. package/dist/mini-app-output.js +22 -5
  39. package/dist/mini-app-publish.js +34 -11
  40. package/dist/mini-app-restore.js +30 -9
  41. package/dist/one-line.js +3 -1
  42. package/dist/permission-request.js +14 -3
  43. package/dist/permission-watch.js +10 -3
  44. package/dist/plan-events-relay.js +96 -19
  45. package/dist/plan-events-tool.js +9 -2
  46. package/dist/plugin-publish.js +23 -6
  47. package/dist/plugin-screenshot.js +18 -6
  48. package/dist/restart-notice.js +47 -15
  49. package/dist/result-limit.js +6 -1
  50. package/dist/role-instruction-file.js +16 -4
  51. package/dist/route-board-scope.generated.js +5 -0
  52. package/dist/route-board-scope.js +6 -2
  53. package/dist/session-access.js +114 -33
  54. package/dist/session-connection.js +23 -7
  55. package/dist/session-control-file.js +1 -1
  56. package/dist/session-key.js +12 -4
  57. package/dist/session-options.js +6 -2
  58. package/dist/session-stats.js +2 -1
  59. package/dist/session-stream.js +81 -20
  60. package/dist/shutdown.js +3 -1
  61. package/dist/subagents-live.js +8 -2
  62. package/dist/terms-halt.js +4 -2
  63. package/dist/tool-access.js +17 -4
  64. package/dist/tool-surface.js +9 -2
  65. package/dist/transcript-lineage.js +5 -2
  66. package/dist/urgent-records.js +1 -0
  67. package/package.json +1 -1
@@ -5,7 +5,12 @@ import { homedir as homedir3 } from "node:os";
5
5
 
6
6
  // ../machine-vitals/src/probes.ts
7
7
  import { statfsSync, readFileSync } from "node:fs";
8
- import { cpus as osCpus, freemem, totalmem, platform as osPlatform } from "node:os";
8
+ import {
9
+ cpus as osCpus,
10
+ freemem,
11
+ totalmem,
12
+ platform as osPlatform
13
+ } from "node:os";
9
14
  import { execFileSync } from "node:child_process";
10
15
  function readDisk(path, statfs = statfsSync) {
11
16
  const stats = statfs(path);
@@ -81,7 +86,9 @@ function parsePageFileJson(json) {
81
86
  }
82
87
  const r = row;
83
88
  if (typeof r.AllocatedBaseSize !== "number" || typeof r.CurrentUsage !== "number") {
84
- throw new Error("readSwap: Win32_PageFileUsage row lacks AllocatedBaseSize/CurrentUsage");
89
+ throw new Error(
90
+ "readSwap: Win32_PageFileUsage row lacks AllocatedBaseSize/CurrentUsage"
91
+ );
85
92
  }
86
93
  total += r.AllocatedBaseSize * 1024 * 1024;
87
94
  used += r.CurrentUsage * 1024 * 1024;
@@ -92,7 +99,9 @@ var PAGEFILE_SCRIPT = "Get-CimInstance Win32_PageFileUsage | Select-Object Alloc
92
99
  function readSwap(deps = {}) {
93
100
  const platform = deps.platform ?? osPlatform();
94
101
  if (platform === "linux") {
95
- return parseMeminfoSwap((deps.readFile ?? ((p) => readFileSync(p, "utf8")))("/proc/meminfo"));
102
+ return parseMeminfoSwap(
103
+ (deps.readFile ?? ((p) => readFileSync(p, "utf8")))("/proc/meminfo")
104
+ );
96
105
  }
97
106
  if (platform === "win32") {
98
107
  const run = deps.runPowerShell ?? ((script) => execFileSync(
@@ -107,7 +116,11 @@ function readSwap(deps = {}) {
107
116
  function createMachineVitalsCollector(deps) {
108
117
  const getCpus = deps.getCpus ?? osCpuTimes;
109
118
  const now = deps.now ?? Date.now;
110
- const cpuWindow = new CpuBusyWindow(deps.cpuWindowMs ?? 5 * 6e4, getCpus, now);
119
+ const cpuWindow = new CpuBusyWindow(
120
+ deps.cpuWindowMs ?? 5 * 6e4,
121
+ getCpus,
122
+ now
123
+ );
111
124
  return () => {
112
125
  const disk = readDisk(deps.diskPath, deps.statfs);
113
126
  const memory = readMemory(deps.getFree, deps.getTotal);
@@ -129,7 +142,11 @@ import { execFileSync as execFileSync2 } from "node:child_process";
129
142
  var TASK_NAME = "danxbot-machine-daemon";
130
143
  var UNIT_NAME = "danxbot-machine-daemon.service";
131
144
  function runHidden(file, args) {
132
- return execFileSync2(file, args, { encoding: "utf8", windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
145
+ return execFileSync2(file, args, {
146
+ encoding: "utf8",
147
+ windowsHide: true,
148
+ stdio: ["ignore", "pipe", "pipe"]
149
+ });
133
150
  }
134
151
  function disableAutostart(deps) {
135
152
  if (deps.platform === "win32") {
@@ -148,34 +165,60 @@ var BEAT_INTERVAL_MS = 6e4;
148
165
  function stopOnRefusal(deps) {
149
166
  const onDisk = deps.readBearer();
150
167
  if (onDisk !== null && onDisk !== deps.config.bearer) {
151
- deps.log("install-daemon replaced this machine's reporting bearer: this process is the old bundle, so it exits and the start entry runs the new one.");
168
+ deps.log(
169
+ "install-daemon replaced this machine's reporting bearer: this process is the old bundle, so it exits and the start entry runs the new one."
170
+ );
152
171
  return { reason: "replaced" };
153
172
  }
154
- deps.log("the dashboard refused this machine's reporting bearer (HTTP 401): re-run install-daemon. The daemon has stopped beating.");
173
+ deps.log(
174
+ "the dashboard refused this machine's reporting bearer (HTTP 401): re-run install-daemon. The daemon has stopped beating."
175
+ );
155
176
  return { reason: "refused" };
156
177
  }
157
178
  async function postAsMachine(config, fetchFn, route, payload) {
158
179
  try {
159
- const res = await fetchFn(`${config.dashboard_url.replace(/\/+$/, "")}${route}`, {
160
- method: "POST",
161
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${config.bearer}` },
162
- body: JSON.stringify({ machine_id: config.machine_id, ...payload })
163
- });
164
- return { status: res.status, error: res.status === 200 ? null : `HTTP ${res.status}`, text: await res.text() };
180
+ const res = await fetchFn(
181
+ `${config.dashboard_url.replace(/\/+$/, "")}${route}`,
182
+ {
183
+ method: "POST",
184
+ headers: {
185
+ "Content-Type": "application/json",
186
+ Authorization: `Bearer ${config.bearer}`
187
+ },
188
+ body: JSON.stringify({ machine_id: config.machine_id, ...payload })
189
+ }
190
+ );
191
+ return {
192
+ status: res.status,
193
+ error: res.status === 200 ? null : `HTTP ${res.status}`,
194
+ text: await res.text()
195
+ };
165
196
  } catch (err) {
166
- return { status: null, error: err instanceof Error ? err.message : String(err), text: "" };
197
+ return {
198
+ status: null,
199
+ error: err instanceof Error ? err.message : String(err),
200
+ text: ""
201
+ };
167
202
  }
168
203
  }
169
204
  async function sendBeat(deps, vitals) {
170
- const { status, error } = await postAsMachine(deps.config, deps.fetchFn, "/api/machines/heartbeat", { vitals });
205
+ const { status, error } = await postAsMachine(
206
+ deps.config,
207
+ deps.fetchFn,
208
+ "/api/machines/heartbeat",
209
+ { vitals }
210
+ );
171
211
  return { status, error };
172
212
  }
173
213
  async function runBeatLoop(deps) {
174
214
  let ticks = 0;
175
215
  for (; ; ) {
176
- if (deps.maxTicks !== void 0 && ticks >= deps.maxTicks) return { reason: "ticks-exhausted" };
216
+ if (deps.maxTicks !== void 0 && ticks >= deps.maxTicks)
217
+ return { reason: "ticks-exhausted" };
177
218
  if (!deps.installed()) {
178
- deps.log("the daemon's config is gone (uninstall-daemon removed it): stopping.");
219
+ deps.log(
220
+ "the daemon's config is gone (uninstall-daemon removed it): stopping."
221
+ );
179
222
  return { reason: "uninstalled" };
180
223
  }
181
224
  ticks += 1;
@@ -186,7 +229,10 @@ async function runBeatLoop(deps) {
186
229
  vitals = deps.collect();
187
230
  outcome = await sendBeat(deps, vitals);
188
231
  } catch (err) {
189
- outcome = { status: null, error: `vitals: ${err instanceof Error ? err.message : String(err)}` };
232
+ outcome = {
233
+ status: null,
234
+ error: `vitals: ${err instanceof Error ? err.message : String(err)}`
235
+ };
190
236
  }
191
237
  const next = new Date(beatAt.getTime() + BEAT_INTERVAL_MS);
192
238
  deps.writeStatus({
@@ -201,12 +247,15 @@ async function runBeatLoop(deps) {
201
247
  } else if (outcome.status === 401) {
202
248
  return stopOnRefusal(deps);
203
249
  } else {
204
- deps.log(`beat failed at ${beatAt.toISOString()}: ${outcome.error}; retrying on the next tick`);
250
+ deps.log(
251
+ `beat failed at ${beatAt.toISOString()}: ${outcome.error}; retrying on the next tick`
252
+ );
205
253
  }
206
254
  if (deps.reporter.refused()) return stopOnRefusal(deps);
207
255
  void deps.reporter.sample(beatAt);
208
256
  deps.reporter.tick(beatAt);
209
- if (deps.maxTicks !== void 0 && ticks >= deps.maxTicks) return { reason: "ticks-exhausted" };
257
+ if (deps.maxTicks !== void 0 && ticks >= deps.maxTicks)
258
+ return { reason: "ticks-exhausted" };
210
259
  await deps.sleep(Math.max(0, next.getTime() - deps.now().getTime()));
211
260
  }
212
261
  }
@@ -226,7 +275,8 @@ import { execFile } from "node:child_process";
226
275
  // src/machine-toolkit/errors.ts
227
276
  function errorCode(err) {
228
277
  const failure = err;
229
- if (typeof failure?.code === "string" || typeof failure?.code === "number") return String(failure.code);
278
+ if (typeof failure?.code === "string" || typeof failure?.code === "number")
279
+ return String(failure.code);
230
280
  return failure?.killed === true ? "timed out" : "unexpected error";
231
281
  }
232
282
  function errMessage(err) {
@@ -237,7 +287,10 @@ function errMessage(err) {
237
287
  var ORPHAN_MIN_AGE_MS = 10 * 60 * 1e3;
238
288
  var PROCESS_LISTING_TIMEOUT_MS = 2e4;
239
289
  var WSL_DISTRO = "Ubuntu";
240
- var DOCKER_DESKTOP_DISTROS = /* @__PURE__ */ new Set(["docker-desktop", "docker-desktop-data"]);
290
+ var DOCKER_DESKTOP_DISTROS = /* @__PURE__ */ new Set([
291
+ "docker-desktop",
292
+ "docker-desktop-data"
293
+ ]);
241
294
  var LISTING_MAX_BUFFER_BYTES = 64 * 1024 * 1024;
242
295
  var WINDOWS_LISTING_SCRIPT = "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; Get-CimInstance Win32_Process | ForEach-Object { [pscustomobject]@{ pid = $_.ProcessId; ppid = $_.ParentProcessId; started = $(if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString('o') } else { $null }); name = $_.Name; cmd = $_.CommandLine; exe = $_.ExecutablePath; cpu = ([uint64]$_.KernelModeTime + [uint64]$_.UserModeTime) } } | ConvertTo-Json -Compress";
243
296
  function parseWindowsListing(stdout) {
@@ -258,30 +311,103 @@ function parseWslListing(stdout, now) {
258
311
  for (const line of stdout.split("\n")) {
259
312
  if (line.trim() === "") continue;
260
313
  const m = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s*(.*)$/.exec(line);
261
- if (!m) throw new Error(`wsl ps printed a line this report cannot read: ${JSON.stringify(line)}`);
262
- rows.push({ source: "wsl", pid: Number(m[1]), ppid: Number(m[2]), startedAt: new Date(now.getTime() - Number(m[3]) * 1e3), name: m[4], commandLine: m[5], executablePath: "", cpuTime100ns: null });
314
+ if (!m)
315
+ throw new Error(
316
+ `wsl ps printed a line this report cannot read: ${JSON.stringify(line)}`
317
+ );
318
+ rows.push({
319
+ source: "wsl",
320
+ pid: Number(m[1]),
321
+ ppid: Number(m[2]),
322
+ startedAt: new Date(now.getTime() - Number(m[3]) * 1e3),
323
+ name: m[4],
324
+ commandLine: m[5],
325
+ executablePath: "",
326
+ cpuTime100ns: null
327
+ });
263
328
  }
264
329
  return rows;
265
330
  }
266
331
  var runCommand = (file, args, timeoutMs, signal) => new Promise((resolve, reject) => {
267
- execFile(file, args, { timeout: timeoutMs, maxBuffer: LISTING_MAX_BUFFER_BYTES, windowsHide: true, signal }, (err, stdout) => err ? reject(err) : resolve(stdout));
332
+ execFile(
333
+ file,
334
+ args,
335
+ {
336
+ timeout: timeoutMs,
337
+ maxBuffer: LISTING_MAX_BUFFER_BYTES,
338
+ windowsHide: true,
339
+ signal
340
+ },
341
+ (err, stdout) => err ? reject(err) : resolve(stdout)
342
+ );
268
343
  });
269
344
  async function wslDistroRunning(run, signal) {
270
- const stdout = await run("wsl.exe", ["--list", "--running", "--quiet"], PROCESS_LISTING_TIMEOUT_MS, signal);
345
+ const stdout = await run(
346
+ "wsl.exe",
347
+ ["--list", "--running", "--quiet"],
348
+ PROCESS_LISTING_TIMEOUT_MS,
349
+ signal
350
+ );
271
351
  const running = stdout.replace(/\0/g, "").split(/\r?\n/).map((line) => line.trim()).filter((line) => line !== "" && !DOCKER_DESKTOP_DISTROS.has(line));
272
352
  if (running.length === 0) return false;
273
353
  if (running.includes(WSL_DISTRO)) return true;
274
- throw Object.assign(new Error(`${WSL_DISTRO} is not among the running WSL distros: ${running.join(", ")}`), { code: "distro not running" });
354
+ throw Object.assign(
355
+ new Error(
356
+ `${WSL_DISTRO} is not among the running WSL distros: ${running.join(", ")}`
357
+ ),
358
+ { code: "distro not running" }
359
+ );
275
360
  }
276
361
  async function listProcesses(now = /* @__PURE__ */ new Date(), run = runCommand, platform = process.platform, signal, wsl = "always") {
277
- if (platform !== "win32") return { rows: [], unavailable: [{ source: "windows", reason: "orphan-process listing is implemented for the Windows dev machine only", code: "unsupported platform" }] };
362
+ if (platform !== "win32")
363
+ return {
364
+ rows: [],
365
+ unavailable: [
366
+ {
367
+ source: "windows",
368
+ reason: "orphan-process listing is implemented for the Windows dev machine only",
369
+ code: "unsupported platform"
370
+ }
371
+ ]
372
+ };
278
373
  const allListings = [
279
- { source: "windows", read: async () => parseWindowsListing(await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_LISTING_SCRIPT], PROCESS_LISTING_TIMEOUT_MS, signal)) },
374
+ {
375
+ source: "windows",
376
+ read: async () => parseWindowsListing(
377
+ await run(
378
+ "powershell.exe",
379
+ [
380
+ "-NoProfile",
381
+ "-NonInteractive",
382
+ "-Command",
383
+ WINDOWS_LISTING_SCRIPT
384
+ ],
385
+ PROCESS_LISTING_TIMEOUT_MS,
386
+ signal
387
+ )
388
+ )
389
+ },
280
390
  {
281
391
  source: "wsl",
282
392
  read: async () => {
283
- if (wsl === "when-running" && !await wslDistroRunning(run, signal)) return [];
284
- return parseWslListing(await run("wsl.exe", ["-d", WSL_DISTRO, "--", "ps", "-eo", "pid=,ppid=,etimes=,comm=,args="], PROCESS_LISTING_TIMEOUT_MS, signal), now);
393
+ if (wsl === "when-running" && !await wslDistroRunning(run, signal))
394
+ return [];
395
+ return parseWslListing(
396
+ await run(
397
+ "wsl.exe",
398
+ [
399
+ "-d",
400
+ WSL_DISTRO,
401
+ "--",
402
+ "ps",
403
+ "-eo",
404
+ "pid=,ppid=,etimes=,comm=,args="
405
+ ],
406
+ PROCESS_LISTING_TIMEOUT_MS,
407
+ signal
408
+ ),
409
+ now
410
+ );
285
411
  }
286
412
  }
287
413
  ];
@@ -291,7 +417,12 @@ async function listProcesses(now = /* @__PURE__ */ new Date(), run = runCommand,
291
417
  const unavailable = [];
292
418
  settled.forEach((s, i) => {
293
419
  if (s.status === "fulfilled") rows.push(...s.value);
294
- else unavailable.push({ source: listings[i].source, reason: errMessage(s.reason), code: errorCode(s.reason) });
420
+ else
421
+ unavailable.push({
422
+ source: listings[i].source,
423
+ reason: errMessage(s.reason),
424
+ code: errorCode(s.reason)
425
+ });
295
426
  });
296
427
  return { rows, unavailable };
297
428
  }
@@ -319,7 +450,11 @@ function readClaudeSessionFiles(dir = join(homedir(), ".claude", "sessions")) {
319
450
  if (!/^\d+\.json$/.test(file)) continue;
320
451
  try {
321
452
  const v = JSON.parse(readFileSync2(join(dir, file), "utf8"));
322
- if (typeof v.pid === "number" && typeof v.sessionId === "string" && typeof v.procStart === "string") sessions.set(v.pid, { sessionId: v.sessionId, startedAtMs: fileTimeToMs(v.procStart) });
453
+ if (typeof v.pid === "number" && typeof v.sessionId === "string" && typeof v.procStart === "string")
454
+ sessions.set(v.pid, {
455
+ sessionId: v.sessionId,
456
+ startedAtMs: fileTimeToMs(v.procStart)
457
+ });
323
458
  } catch {
324
459
  continue;
325
460
  }
@@ -327,10 +462,18 @@ function readClaudeSessionFiles(dir = join(homedir(), ".claude", "sessions")) {
327
462
  return sessions;
328
463
  }
329
464
  var FOLLOW_ARG = /(?:^|\s)(?:-[a-zA-Z]*[fF][a-zA-Z]*|--follow(?:=\S+)?)(?=\s|$)/;
330
- var FILTER_NAMES = /* @__PURE__ */ new Set(["grep.exe", "egrep.exe", "fgrep.exe", "sed.exe", "awk.exe", "gawk.exe"]);
465
+ var FILTER_NAMES = /* @__PURE__ */ new Set([
466
+ "grep.exe",
467
+ "egrep.exe",
468
+ "fgrep.exe",
469
+ "sed.exe",
470
+ "awk.exe",
471
+ "gawk.exe"
472
+ ]);
331
473
  function isFollowRow(row) {
332
474
  const name = row.name.toLowerCase();
333
- if (name === "tail.exe") return FOLLOW_ARG.test(row.commandLine.replace(/^"[^"]*"|^\S+/, ""));
475
+ if (name === "tail.exe")
476
+ return FOLLOW_ARG.test(row.commandLine.replace(/^"[^"]*"|^\S+/, ""));
334
477
  return FILTER_NAMES.has(name) && /(?:^|\s)--line-buffered(?=\s|$)/.test(row.commandLine);
335
478
  }
336
479
  function shortCommand(commandLine) {
@@ -369,7 +512,11 @@ var SESSION_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{1
369
512
  async function readSessionsFromEnvironment(pids, run = runCommand) {
370
513
  const found = /* @__PURE__ */ new Map();
371
514
  if (pids.length === 0) return found;
372
- const stdout = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", ENV_READ_SCRIPT(pids)], ENV_READ_TIMEOUT_MS);
515
+ const stdout = await run(
516
+ "powershell.exe",
517
+ ["-NoProfile", "-NonInteractive", "-Command", ENV_READ_SCRIPT(pids)],
518
+ ENV_READ_TIMEOUT_MS
519
+ );
373
520
  for (const line of stdout.split(/\r?\n/)) {
374
521
  const m = /^(\d+)=(\S+)$/.exec(line.trim());
375
522
  if (m && SESSION_ID_RE.test(m[2])) found.set(Number(m[1]), m[2]);
@@ -390,9 +537,16 @@ async function readMsysParents(processes, run = runCommand, exists = existsSync)
390
537
  const rows = [];
391
538
  for (const line of stdout.split(/\r?\n/)) {
392
539
  const m = /^[\sI]*(\d+)\s+(\d+)\s+\d+\s+(\d+)\s/.exec(line);
393
- if (m) rows.push({ pid: Number(m[1]), ppid: Number(m[2]), winpid: Number(m[3]) });
540
+ if (m)
541
+ rows.push({
542
+ pid: Number(m[1]),
543
+ ppid: Number(m[2]),
544
+ winpid: Number(m[3])
545
+ });
394
546
  }
395
- const winpidOfMsysPid = new Map(rows.filter((r) => r.pid !== r.winpid).map((r) => [r.pid, r.winpid]));
547
+ const winpidOfMsysPid = new Map(
548
+ rows.filter((r) => r.pid !== r.winpid).map((r) => [r.pid, r.winpid])
549
+ );
396
550
  const parents = /* @__PURE__ */ new Map();
397
551
  for (const r of rows) {
398
552
  const parent = r.pid === r.winpid ? void 0 : winpidOfMsysPid.get(r.ppid);
@@ -410,16 +564,25 @@ function createLeftoverTracker(deps) {
410
564
  const parentRowOf = (row, byPid, msys) => {
411
565
  const parent = byPid.get(msys.get(row.pid) ?? row.ppid);
412
566
  if (parent === void 0) return void 0;
413
- if (parent.startedAt !== null && row.startedAt !== null && parent.startedAt.getTime() > row.startedAt.getTime()) return void 0;
567
+ if (parent.startedAt !== null && row.startedAt !== null && parent.startedAt.getTime() > row.startedAt.getTime())
568
+ return void 0;
414
569
  return parent;
415
570
  };
416
571
  const traceOwner = (row, byPid, msys, sessions) => {
417
572
  let child = row;
418
573
  for (let hop = 0; hop < MAX_CHAIN_HOPS; hop++) {
419
574
  const parent = parentRowOf(child, byPid, msys);
420
- if (parent === void 0) return { owner: null, walk: `ends at pid ${child.pid} ${child.name}: its parent pid ${msys.get(child.pid) ?? child.ppid} is not running` };
575
+ if (parent === void 0)
576
+ return {
577
+ owner: null,
578
+ walk: `ends at pid ${child.pid} ${child.name}: its parent pid ${msys.get(child.pid) ?? child.ppid} is not running`
579
+ };
421
580
  const session = sessions.get(parent.pid);
422
- if (session !== void 0 && parent.name.toLowerCase() === "claude.exe" && parent.startedAt !== null && Math.abs(parent.startedAt.getTime() - session.startedAtMs) < 5e3) return { owner: session.sessionId, walk: `reaches claude.exe pid ${parent.pid} after ${hop + 1} hops` };
581
+ if (session !== void 0 && parent.name.toLowerCase() === "claude.exe" && parent.startedAt !== null && Math.abs(parent.startedAt.getTime() - session.startedAtMs) < 5e3)
582
+ return {
583
+ owner: session.sessionId,
584
+ walk: `reaches claude.exe pid ${parent.pid} after ${hop + 1} hops`
585
+ };
423
586
  child = parent;
424
587
  }
425
588
  return { owner: null, walk: `no claude.exe within ${MAX_CHAIN_HOPS} hops` };
@@ -427,12 +590,21 @@ function createLeftoverTracker(deps) {
427
590
  return {
428
591
  async sample(at) {
429
592
  const { rows, unavailable } = await deps.listing(at);
430
- if (unavailable.length > 0) throw new Error(`the process table is unavailable (${unavailable.map((u) => `${u.source}: ${u.reason}`).join("; ")}): the ledger is kept as it was`);
431
- const windows = rows.filter((r) => r.source === "windows" && r.startedAt !== null);
593
+ if (unavailable.length > 0)
594
+ throw new Error(
595
+ `the process table is unavailable (${unavailable.map((u) => `${u.source}: ${u.reason}`).join("; ")}): the ledger is kept as it was`
596
+ );
597
+ const windows = rows.filter(
598
+ (r) => r.source === "windows" && r.startedAt !== null
599
+ );
432
600
  const byPid = new Map(windows.map((r) => [r.pid, r]));
433
601
  const sessions = deps.claudeSessions();
434
602
  const msys = await deps.msysParents(windows);
435
- liveSessionIds = new Set(windows.filter((r) => r.name.toLowerCase() === "claude.exe" && sessions.get(r.pid) !== void 0).map((r) => sessions.get(r.pid).sessionId));
603
+ liveSessionIds = new Set(
604
+ windows.filter(
605
+ (r) => r.name.toLowerCase() === "claude.exe" && sessions.get(r.pid) !== void 0
606
+ ).map((r) => sessions.get(r.pid).sessionId)
607
+ );
436
608
  const nowLive = /* @__PURE__ */ new Map();
437
609
  const nowMs = at.getTime();
438
610
  for (const row of windows) {
@@ -444,12 +616,34 @@ function createLeftoverTracker(deps) {
444
616
  const follower = isFollowRow(row);
445
617
  if (entry === void 0) {
446
618
  const shell = parentRowOf(row, byPid, msys);
447
- if (follower) deps.log(`leftover: first sight of follower pid ${row.pid} ${row.name} (${shortCommand(row.commandLine)}), started ${row.startedAt.toISOString()}: launching shell ${shell === void 0 ? "not running" : `pid ${shell.pid} ${shell.name}`}; owner ${owner ?? "none"}, chain ${walk}`);
448
- entry = { pid: row.pid, startedAtMs, owner, envChecked: false, shellKey: shell?.startedAt ? keyOf(shell.pid, shell.startedAt.getTime()) : null, unreachable: false, awaiting: false, disposition: null, lastCpu100ns: null, lastSeenMs: nowMs, hotSinceMs: null, hotCpuStart100ns: null, hotStartWallMs: null, lastCpuPercent: null, remindedAtMs: null };
619
+ if (follower)
620
+ deps.log(
621
+ `leftover: first sight of follower pid ${row.pid} ${row.name} (${shortCommand(row.commandLine)}), started ${row.startedAt.toISOString()}: launching shell ${shell === void 0 ? "not running" : `pid ${shell.pid} ${shell.name}`}; owner ${owner ?? "none"}, chain ${walk}`
622
+ );
623
+ entry = {
624
+ pid: row.pid,
625
+ startedAtMs,
626
+ owner,
627
+ envChecked: false,
628
+ shellKey: shell?.startedAt ? keyOf(shell.pid, shell.startedAt.getTime()) : null,
629
+ unreachable: false,
630
+ awaiting: false,
631
+ disposition: null,
632
+ lastCpu100ns: null,
633
+ lastSeenMs: nowMs,
634
+ hotSinceMs: null,
635
+ hotCpuStart100ns: null,
636
+ hotStartWallMs: null,
637
+ lastCpuPercent: null,
638
+ remindedAtMs: null
639
+ };
449
640
  ledger.set(key, entry);
450
641
  } else if (entry.owner === null && owner !== null) {
451
642
  entry.owner = owner;
452
- if (follower) deps.log(`leftover: follower pid ${row.pid} now has owner ${owner} (chain ${walk})`);
643
+ if (follower)
644
+ deps.log(
645
+ `leftover: follower pid ${row.pid} now has owner ${owner} (chain ${walk})`
646
+ );
453
647
  }
454
648
  if (row.cpuTime100ns !== null && entry.lastCpu100ns !== null && nowMs > entry.lastSeenMs) {
455
649
  const fraction = (row.cpuTime100ns - entry.lastCpu100ns) / 1e4 / (nowMs - entry.lastSeenMs);
@@ -469,21 +663,30 @@ function createLeftoverTracker(deps) {
469
663
  }
470
664
  for (const [key, entry] of [...ledger]) {
471
665
  if (nowLive.has(key)) continue;
472
- if (live.has(key) && isFollowRow(live.get(key))) deps.log(`leftover: follower pid ${entry.pid} ended (owner ${entry.owner ?? "none"})`);
666
+ if (live.has(key) && isFollowRow(live.get(key)))
667
+ deps.log(
668
+ `leftover: follower pid ${entry.pid} ended (owner ${entry.owner ?? "none"})`
669
+ );
473
670
  ledger.delete(key);
474
671
  }
475
672
  live = nowLive;
476
673
  sampledAtMs = nowMs;
477
674
  const sessionIds = [...liveSessionIds].sort().join(",");
478
675
  if (sessionIds !== lastSessionIds) {
479
- deps.log(`leftover: watching ${liveSessionIds.size} claude sessions: ${sessionIds}`);
676
+ deps.log(
677
+ `leftover: watching ${liveSessionIds.size} claude sessions: ${sessionIds}`
678
+ );
480
679
  lastSessionIds = sessionIds;
481
680
  }
482
- const unknown = [...ledger.entries()].filter(([, e]) => e.owner === null && !e.envChecked && e.hotSinceMs !== null && nowMs - e.hotSinceMs >= HOT_MIN_MS);
681
+ const unknown = [...ledger.entries()].filter(
682
+ ([, e]) => e.owner === null && !e.envChecked && e.hotSinceMs !== null && nowMs - e.hotSinceMs >= HOT_MIN_MS
683
+ );
483
684
  if (unknown.length > 0 && nowMs >= envRetryAfterMs) {
484
685
  let fromEnv;
485
686
  try {
486
- fromEnv = await deps.sessionsFromEnvironment(unknown.map(([, e]) => e.pid));
687
+ fromEnv = await deps.sessionsFromEnvironment(
688
+ unknown.map(([, e]) => e.pid)
689
+ );
487
690
  } catch (err) {
488
691
  envRetryAfterMs = nowMs + ENV_RETRY_BACKOFF_MS;
489
692
  throw err;
@@ -491,7 +694,9 @@ function createLeftoverTracker(deps) {
491
694
  for (const [, e] of unknown) {
492
695
  e.envChecked = true;
493
696
  e.owner = fromEnv.get(e.pid) ?? null;
494
- deps.log(`leftover: hot process pid ${e.pid} has no claude.exe ancestor; its environment names ${e.owner ?? "no session"}`);
697
+ deps.log(
698
+ `leftover: hot process pid ${e.pid} has no claude.exe ancestor; its environment names ${e.owner ?? "no session"}`
699
+ );
495
700
  }
496
701
  }
497
702
  },
@@ -500,9 +705,18 @@ function createLeftoverTracker(deps) {
500
705
  const sessions = /* @__PURE__ */ new Map();
501
706
  const reminded = /* @__PURE__ */ new Map();
502
707
  const ownerless = [];
503
- const awaiting = [...new Set([...ledger.values()].flatMap((e) => e.awaiting && e.owner !== null ? [e.owner] : []))].sort();
708
+ const awaiting = [
709
+ ...new Set(
710
+ [...ledger.values()].flatMap(
711
+ (e) => e.awaiting && e.owner !== null ? [e.owner] : []
712
+ )
713
+ )
714
+ ].sort();
504
715
  if (sampledAtMs === null || nowMs - sampledAtMs > SAMPLE_MAX_AGE_MS) {
505
- if (sampledAtMs !== null) deps.log(`leftover: the process table was last read ${Math.floor((nowMs - sampledAtMs) / 6e4)} min ago, so this report flags nothing`);
716
+ if (sampledAtMs !== null)
717
+ deps.log(
718
+ `leftover: the process table was last read ${Math.floor((nowMs - sampledAtMs) / 6e4)} min ago, so this report flags nothing`
719
+ );
506
720
  return { sessions: [], ownerless, reminded, awaiting };
507
721
  }
508
722
  for (const [key, entry] of ledger) {
@@ -525,27 +739,54 @@ function createLeftoverTracker(deps) {
525
739
  why: readerGone ? "reader_gone" : follow ? "follow" : "cpu"
526
740
  };
527
741
  const note = (disposition, text, always = false) => {
528
- if (text !== null && (always || entry.disposition !== disposition)) deps.log(`leftover: flagged pid ${entry.pid} ${row.name} (${process2.why}, ${process2.age_seconds} s old, owner ${entry.owner ?? "none"}): ${text}`);
742
+ if (text !== null && (always || entry.disposition !== disposition))
743
+ deps.log(
744
+ `leftover: flagged pid ${entry.pid} ${row.name} (${process2.why}, ${process2.age_seconds} s old, owner ${entry.owner ?? "none"}): ${text}`
745
+ );
529
746
  entry.disposition = disposition;
530
747
  };
531
748
  if (entry.owner === null) {
532
749
  ownerless.push({ ...process2, reason: "no session found" });
533
- note("no session found", "no session found, so it goes to the orphan list");
750
+ note(
751
+ "no session found",
752
+ "no session found, so it goes to the orphan list"
753
+ );
534
754
  } else if (!liveSessionIds.has(entry.owner)) {
535
755
  ownerless.push({ ...process2, reason: "session ended" });
536
- note("session ended", "its session has ended, so it goes to the orphan list");
756
+ note(
757
+ "session ended",
758
+ "its session has ended, so it goes to the orphan list"
759
+ );
537
760
  } else {
538
- if (entry.unreachable) ownerless.push({ ...process2, reason: "session not on this dashboard" });
761
+ if (entry.unreachable)
762
+ ownerless.push({
763
+ ...process2,
764
+ reason: "session not on this dashboard"
765
+ });
539
766
  if (entry.remindedAtMs === null || nowMs - entry.remindedAtMs >= REMIND_INTERVAL_MS) {
540
- sessions.set(entry.owner, [...sessions.get(entry.owner) ?? [], process2]);
541
- reminded.set(entry.owner, [...reminded.get(entry.owner) ?? [], key]);
767
+ sessions.set(entry.owner, [
768
+ ...sessions.get(entry.owner) ?? [],
769
+ process2
770
+ ]);
771
+ reminded.set(entry.owner, [
772
+ ...reminded.get(entry.owner) ?? [],
773
+ key
774
+ ]);
542
775
  note("reminded", "the session is reminded in this report", true);
543
776
  } else {
544
777
  note("not yet", null);
545
778
  }
546
779
  }
547
780
  }
548
- return { sessions: [...sessions].map(([session_id, processes]) => ({ session_id, processes })), ownerless, reminded, awaiting };
781
+ return {
782
+ sessions: [...sessions].map(([session_id, processes]) => ({
783
+ session_id,
784
+ processes
785
+ })),
786
+ ownerless,
787
+ reminded,
788
+ awaiting
789
+ };
549
790
  },
550
791
  settle(collection, answer, at) {
551
792
  for (const sessionId of collection.awaiting) {
@@ -556,7 +797,9 @@ function createLeftoverTracker(deps) {
556
797
  entry.awaiting = false;
557
798
  if (expired) entry.remindedAtMs = null;
558
799
  }
559
- deps.log(expired ? `leftover: the reminder of session ${sessionId} expired on the dashboard before its stream took it, so it is sent again at the next report` : `leftover: the stream of session ${sessionId} took its reminder`);
800
+ deps.log(
801
+ expired ? `leftover: the reminder of session ${sessionId} expired on the dashboard before its stream took it, so it is sent again at the next report` : `leftover: the stream of session ${sessionId} took its reminder`
802
+ );
560
803
  }
561
804
  for (const [sessionId, keys] of collection.reminded) {
562
805
  const unreachable = answer.undelivered.includes(sessionId);
@@ -567,15 +810,27 @@ function createLeftoverTracker(deps) {
567
810
  entry.awaiting = !unreachable;
568
811
  if (!unreachable) entry.remindedAtMs = at.getTime();
569
812
  }
570
- deps.log(`leftover: the dashboard ${unreachable ? "has no stream row for" : "took the reminder for"} session ${sessionId} (${keys.length} processes)`);
813
+ deps.log(
814
+ `leftover: the dashboard ${unreachable ? "has no stream row for" : "took the reminder for"} session ${sessionId} (${keys.length} processes)`
815
+ );
571
816
  }
572
817
  }
573
818
  };
574
819
  }
575
820
  function createSystemLeftoverTracker(log, run = runCommand, platform = process.platform) {
576
- if (platform !== "win32") return { sample: async () => {
577
- }, collect: () => ({ sessions: [], ownerless: [], reminded: /* @__PURE__ */ new Map(), awaiting: [] }), settle: () => {
578
- } };
821
+ if (platform !== "win32")
822
+ return {
823
+ sample: async () => {
824
+ },
825
+ collect: () => ({
826
+ sessions: [],
827
+ ownerless: [],
828
+ reminded: /* @__PURE__ */ new Map(),
829
+ awaiting: []
830
+ }),
831
+ settle: () => {
832
+ }
833
+ };
579
834
  return createLeftoverTracker({
580
835
  log,
581
836
  listing: (now) => listProcesses(now, run, platform, void 0, "never"),
@@ -587,12 +842,21 @@ function createSystemLeftoverTracker(log, run = runCommand, platform = process.p
587
842
 
588
843
  // src/machine-toolkit/contract.ts
589
844
  var CONTRACT_VERSION = 2;
590
- var REQUIRED_METRICS = ["docker_data_disk_bytes", "unowned_docker_resource_count", "orphan_process_count"];
845
+ var REQUIRED_METRICS = [
846
+ "docker_data_disk_bytes",
847
+ "unowned_docker_resource_count",
848
+ "orphan_process_count"
849
+ ];
591
850
  var KERNEL_TOKEN_METRIC = "kernel_token_count";
592
- var HEALTH_ITEM_LISTS = ["unowned_docker_resources", "orphan_processes"];
851
+ var HEALTH_ITEM_LISTS = [
852
+ "unowned_docker_resources",
853
+ "orphan_processes"
854
+ ];
593
855
  var ContractViolation = class extends Error {
594
856
  constructor(command, path, what) {
595
- super(`${command} output does not match machine-toolkit contract v${CONTRACT_VERSION}: ${path} ${what}`);
857
+ super(
858
+ `${command} output does not match machine-toolkit contract v${CONTRACT_VERSION}: ${path} ${what}`
859
+ );
596
860
  this.name = "ContractViolation";
597
861
  }
598
862
  };
@@ -604,11 +868,13 @@ function objectAt(v, path, fail) {
604
868
  }
605
869
  function exactKeys(o, path, keys, fail) {
606
870
  for (const k of keys) if (!(k in o)) fail(join2(path, k), "is required");
607
- for (const k of Object.keys(o)) if (!keys.includes(k)) fail(join2(path, k), "is not part of the contract");
871
+ for (const k of Object.keys(o))
872
+ if (!keys.includes(k)) fail(join2(path, k), "is not part of the contract");
608
873
  }
609
874
  function stringAt(o, key, path, fail) {
610
875
  const v = o[key];
611
- if (typeof v !== "string" || v === "") return fail(join2(path, key), "must be a non-empty string");
876
+ if (typeof v !== "string" || v === "")
877
+ return fail(join2(path, key), "must be a non-empty string");
612
878
  return v;
613
879
  }
614
880
  function listAt(v, path, fail) {
@@ -619,54 +885,80 @@ function checkItem(v, path, extra, fail) {
619
885
  const o = objectAt(v, path, fail);
620
886
  exactKeys(o, path, ["id", "detail", ...extra], fail);
621
887
  stringAt(o, "id", path, fail);
622
- if (typeof o.detail !== "string") fail(join2(path, "detail"), "must be a string");
888
+ if (typeof o.detail !== "string")
889
+ fail(join2(path, "detail"), "must be a string");
623
890
  for (const k of extra) stringAt(o, k, path, fail);
624
891
  }
625
892
  function checkItems(v, path, extra, fail) {
626
- listAt(v, path, fail).forEach((item, i) => checkItem(item, `${path}[${i}]`, extra, fail));
893
+ listAt(v, path, fail).forEach(
894
+ (item, i) => checkItem(item, `${path}[${i}]`, extra, fail)
895
+ );
627
896
  }
628
897
  function checkMetric(v, path, fail) {
629
898
  const o = objectAt(v, path, fail);
630
899
  exactKeys(o, path, ["value", "reason", "source", "age_seconds"], fail);
631
900
  if (o.value === null) {
632
- if (typeof o.reason !== "string" || o.reason === "") fail(`${path}.reason`, "must say why the value is null");
901
+ if (typeof o.reason !== "string" || o.reason === "")
902
+ fail(`${path}.reason`, "must say why the value is null");
633
903
  } else {
634
- if (typeof o.value !== "number" || !Number.isFinite(o.value) || o.value < 0) fail(`${path}.value`, "must be null or a finite number of at least 0");
635
- if (o.reason !== null) fail(`${path}.reason`, "must be null when the value was read");
904
+ if (typeof o.value !== "number" || !Number.isFinite(o.value) || o.value < 0)
905
+ fail(`${path}.value`, "must be null or a finite number of at least 0");
906
+ if (o.reason !== null)
907
+ fail(`${path}.reason`, "must be null when the value was read");
636
908
  }
637
- if (o.source !== "fresh" && o.source !== "cached") fail(`${path}.source`, "must be 'fresh' or 'cached'");
638
- if (typeof o.age_seconds !== "number" || !Number.isFinite(o.age_seconds) || o.age_seconds < 0) fail(`${path}.age_seconds`, "must be a number of at least 0");
639
- if (o.source === "fresh" && o.age_seconds !== 0) fail(`${path}.age_seconds`, "must be 0 for a fresh reading");
909
+ if (o.source !== "fresh" && o.source !== "cached")
910
+ fail(`${path}.source`, "must be 'fresh' or 'cached'");
911
+ if (typeof o.age_seconds !== "number" || !Number.isFinite(o.age_seconds) || o.age_seconds < 0)
912
+ fail(`${path}.age_seconds`, "must be a number of at least 0");
913
+ if (o.source === "fresh" && o.age_seconds !== 0)
914
+ fail(`${path}.age_seconds`, "must be 0 for a fresh reading");
640
915
  }
641
916
  function checkEnvelope(o, fail) {
642
- if (o.contract_version !== CONTRACT_VERSION) fail("contract_version", `must be ${CONTRACT_VERSION}`);
917
+ if (o.contract_version !== CONTRACT_VERSION)
918
+ fail("contract_version", `must be ${CONTRACT_VERSION}`);
643
919
  stringAt(o, "toolkit_version", "", fail);
644
920
  stringAt(o, "profile", "", fail);
645
921
  const at = stringAt(o, "measured_at", "", fail);
646
- if (Number.isNaN(new Date(at).getTime())) fail("measured_at", "must be an ISO time");
922
+ if (Number.isNaN(new Date(at).getTime()))
923
+ fail("measured_at", "must be an ISO time");
647
924
  }
648
- var ENVELOPE_KEYS = ["contract_version", "toolkit_version", "profile", "measured_at"];
925
+ var ENVELOPE_KEYS = [
926
+ "contract_version",
927
+ "toolkit_version",
928
+ "profile",
929
+ "measured_at"
930
+ ];
649
931
  var VALIDATORS = {
650
932
  health(o, fail) {
651
933
  exactKeys(o, "", [...ENVELOPE_KEYS, "metrics", "items"], fail);
652
934
  checkEnvelope(o, fail);
653
935
  const metrics = objectAt(o.metrics, "metrics", fail);
654
- for (const name of REQUIRED_METRICS) if (!(name in metrics)) fail(`metrics.${name}`, "is required");
655
- for (const [name, metric] of Object.entries(metrics)) checkMetric(metric, `metrics.${name}`, fail);
936
+ for (const name of REQUIRED_METRICS)
937
+ if (!(name in metrics)) fail(`metrics.${name}`, "is required");
938
+ for (const [name, metric] of Object.entries(metrics))
939
+ checkMetric(metric, `metrics.${name}`, fail);
656
940
  const tokens = metrics[KERNEL_TOKEN_METRIC]?.value;
657
- if (typeof tokens === "number" && !Number.isInteger(tokens)) fail(`metrics.${KERNEL_TOKEN_METRIC}.value`, "must be a whole number");
941
+ if (typeof tokens === "number" && !Number.isInteger(tokens))
942
+ fail(`metrics.${KERNEL_TOKEN_METRIC}.value`, "must be a whole number");
658
943
  const items = objectAt(o.items, "items", fail);
659
944
  exactKeys(items, "items", HEALTH_ITEM_LISTS, fail);
660
- for (const list of HEALTH_ITEM_LISTS) checkItems(items[list], `items.${list}`, [], fail);
945
+ for (const list of HEALTH_ITEM_LISTS)
946
+ checkItems(items[list], `items.${list}`, [], fail);
661
947
  },
662
948
  sweep(o, fail) {
663
949
  exactKeys(o, "", [...ENVELOPE_KEYS, "dry_run", "kinds"], fail);
664
950
  checkEnvelope(o, fail);
665
- if (typeof o.dry_run !== "boolean") fail("dry_run", "must be true or false");
951
+ if (typeof o.dry_run !== "boolean")
952
+ fail("dry_run", "must be true or false");
666
953
  listAt(o.kinds, "kinds", fail).forEach((k, i) => {
667
954
  const path = `kinds[${i}]`;
668
955
  const kind = objectAt(k, path, fail);
669
- exactKeys(kind, path, ["kind", "removed", "kept", "failed", "flagged"], fail);
956
+ exactKeys(
957
+ kind,
958
+ path,
959
+ ["kind", "removed", "kept", "failed", "flagged"],
960
+ fail
961
+ );
670
962
  stringAt(kind, "kind", path, fail);
671
963
  checkItems(kind.removed, `${path}.removed`, [], fail);
672
964
  checkItems(kind.kept, `${path}.kept`, ["reason"], fail);
@@ -682,8 +974,10 @@ var VALIDATORS = {
682
974
  const step = objectAt(s, path, fail);
683
975
  exactKeys(step, path, ["name", "status", "detail"], fail);
684
976
  stringAt(step, "name", path, fail);
685
- if (step.status !== "done" && step.status !== "skipped" && step.status !== "failed") fail(`${path}.status`, "must be 'done', 'skipped' or 'failed'");
686
- if (typeof step.detail !== "string") fail(join2(path, "detail"), "must be a string");
977
+ if (step.status !== "done" && step.status !== "skipped" && step.status !== "failed")
978
+ fail(`${path}.status`, "must be 'done', 'skipped' or 'failed'");
979
+ if (typeof step.detail !== "string")
980
+ fail(join2(path, "detail"), "must be a string");
687
981
  });
688
982
  },
689
983
  "label-check"(o, fail) {
@@ -695,7 +989,11 @@ var VALIDATORS = {
695
989
  };
696
990
  function assertContract(command, report) {
697
991
  const fail = (path, what) => {
698
- throw new ContractViolation(command, path === "" ? "(document)" : path, what);
992
+ throw new ContractViolation(
993
+ command,
994
+ path === "" ? "(document)" : path,
995
+ what
996
+ );
699
997
  };
700
998
  VALIDATORS[command](objectAt(report, "", fail), fail);
701
999
  }
@@ -724,7 +1022,11 @@ function runHealthChild(opts) {
724
1022
  cancel();
725
1023
  resolve(run);
726
1024
  };
727
- const child = opts.spawnFn(opts.nodePath, [opts.toolkitPath, "health", "--json"], { windowsHide: true, stdio: ["ignore", "pipe", "ignore"] });
1025
+ const child = opts.spawnFn(
1026
+ opts.nodePath,
1027
+ [opts.toolkitPath, "health", "--json"],
1028
+ { windowsHide: true, stdio: ["ignore", "pipe", "ignore"] }
1029
+ );
728
1030
  cancel = schedule(() => {
729
1031
  child.kill();
730
1032
  finish({ kind: "timed-out" });
@@ -732,14 +1034,22 @@ function runHealthChild(opts) {
732
1034
  child.stdout?.on("data", (chunk) => {
733
1035
  stdout += chunk.toString();
734
1036
  });
735
- child.on("error", (err) => finish({ kind: "failed", reason: errorCode(err) }));
1037
+ child.on(
1038
+ "error",
1039
+ (err) => finish({ kind: "failed", reason: errorCode(err) })
1040
+ );
736
1041
  child.on("close", (code) => finish({ kind: "exited", code, stdout }));
737
1042
  });
738
1043
  }
739
1044
  function reportPayload(run) {
740
- if (run.kind === "timed-out") return { report_error: `health did not finish within ${REPORT_TIMEOUT_MS / 1e3} s: the machine is saturated` };
741
- if (run.kind === "failed") return { report_error: `health could not start (${run.reason})` };
742
- if (run.code !== 0 && run.code !== 2) return { report_error: `health exited ${run.code ?? "on a signal"}` };
1045
+ if (run.kind === "timed-out")
1046
+ return {
1047
+ report_error: `health did not finish within ${REPORT_TIMEOUT_MS / 1e3} s: the machine is saturated`
1048
+ };
1049
+ if (run.kind === "failed")
1050
+ return { report_error: `health could not start (${run.reason})` };
1051
+ if (run.code !== 0 && run.code !== 2)
1052
+ return { report_error: `health exited ${run.code ?? "on a signal"}` };
743
1053
  let parsed;
744
1054
  try {
745
1055
  parsed = JSON.parse(run.stdout);
@@ -754,27 +1064,50 @@ function reportPayload(run) {
754
1064
  }
755
1065
  return { report: parsed };
756
1066
  }
757
- var WHY_LABEL = { follow: "follower", reader_gone: "follower whose shell has exited,", cpu: "busy process" };
1067
+ var WHY_LABEL = {
1068
+ follow: "follower",
1069
+ reader_gone: "follower whose shell has exited,",
1070
+ cpu: "busy process"
1071
+ };
758
1072
  function foldOwnerless(payload, ownerless) {
759
1073
  if (!("report" in payload) || ownerless.length === 0) return payload;
760
1074
  const { report } = payload;
761
- const items = ownerless.map((p) => ({ id: `leftover:${p.pid}`, detail: `${WHY_LABEL[p.why]} pid ${p.pid}, running ${Math.floor(p.age_seconds / 3600)} h, no session to remind (${p.reason}): ${p.command}` }));
1075
+ const items = ownerless.map((p) => ({
1076
+ id: `leftover:${p.pid}`,
1077
+ detail: `${WHY_LABEL[p.why]} pid ${p.pid}, running ${Math.floor(p.age_seconds / 3600)} h, no session to remind (${p.reason}): ${p.command}`
1078
+ }));
762
1079
  const count = report.metrics.orphan_process_count;
763
- if (count === void 0) throw new Error("a validated health report carries orphan_process_count");
1080
+ if (count === void 0)
1081
+ throw new Error("a validated health report carries orphan_process_count");
764
1082
  return {
765
1083
  report: {
766
1084
  ...report,
767
- metrics: { ...report.metrics, orphan_process_count: count.value !== null ? { ...count, value: count.value + items.length } : count },
768
- items: { ...report.items, orphan_processes: [...report.items.orphan_processes, ...items] }
1085
+ metrics: {
1086
+ ...report.metrics,
1087
+ orphan_process_count: count.value !== null ? { ...count, value: count.value + items.length } : count
1088
+ },
1089
+ items: {
1090
+ ...report.items,
1091
+ orphan_processes: [...report.items.orphan_processes, ...items]
1092
+ }
769
1093
  }
770
1094
  };
771
1095
  }
772
1096
  function answerOf(text) {
773
1097
  try {
774
1098
  const answer = JSON.parse(text);
775
- const lists = ["undelivered", "pending", "expired"].map((name) => answer[name]);
776
- if (!lists.every((l) => Array.isArray(l) && l.every((id) => typeof id === "string"))) return null;
777
- return { undelivered: lists[0], pending: lists[1], expired: lists[2] };
1099
+ const lists = ["undelivered", "pending", "expired"].map(
1100
+ (name) => answer[name]
1101
+ );
1102
+ if (!lists.every(
1103
+ (l) => Array.isArray(l) && l.every((id) => typeof id === "string")
1104
+ ))
1105
+ return null;
1106
+ return {
1107
+ undelivered: lists[0],
1108
+ pending: lists[1],
1109
+ expired: lists[2]
1110
+ };
778
1111
  } catch {
779
1112
  return null;
780
1113
  }
@@ -794,10 +1127,24 @@ function createReporter(deps) {
794
1127
  let refused = false;
795
1128
  const run = async (startedAt) => {
796
1129
  const found = deps.leftovers.collect(startedAt);
797
- const payload = foldOwnerless(reportPayload(await deps.runHealth()), found.ownerless);
1130
+ const payload = foldOwnerless(
1131
+ reportPayload(await deps.runHealth()),
1132
+ found.ownerless
1133
+ );
798
1134
  const reportError = "report_error" in payload ? payload.report_error : null;
799
- if (found.sessions.length > 0 || found.ownerless.length > 0) deps.log(`report at ${startedAt.toISOString()} carries reminders for ${found.sessions.length} sessions and ${found.ownerless.length} ownerless processes`);
800
- const sent = await postAsMachine(deps.config, deps.fetchFn, "/api/machines/report", found.sessions.length === 0 && found.awaiting.length === 0 ? payload : { ...payload, leftovers: { sessions: found.sessions, awaiting: found.awaiting } });
1135
+ if (found.sessions.length > 0 || found.ownerless.length > 0)
1136
+ deps.log(
1137
+ `report at ${startedAt.toISOString()} carries reminders for ${found.sessions.length} sessions and ${found.ownerless.length} ownerless processes`
1138
+ );
1139
+ const sent = await postAsMachine(
1140
+ deps.config,
1141
+ deps.fetchFn,
1142
+ "/api/machines/report",
1143
+ found.sessions.length === 0 && found.awaiting.length === 0 ? payload : {
1144
+ ...payload,
1145
+ leftovers: { sessions: found.sessions, awaiting: found.awaiting }
1146
+ }
1147
+ );
801
1148
  let outcome;
802
1149
  let error = reportError ?? sent.error;
803
1150
  if (sent.status === 200) {
@@ -814,45 +1161,67 @@ function createReporter(deps) {
814
1161
  deps.log(`report refused at ${startedAt.toISOString()}: ${error}`);
815
1162
  } else {
816
1163
  outcome = reportError === null ? "sent" : "error-sent";
817
- deps.log(reportError === null ? `report sent at ${startedAt.toISOString()}` : `report error sent at ${startedAt.toISOString()}: ${reportError}`);
1164
+ deps.log(
1165
+ reportError === null ? `report sent at ${startedAt.toISOString()}` : `report error sent at ${startedAt.toISOString()}: ${reportError}`
1166
+ );
818
1167
  }
819
1168
  } else if (sent.status === 429) {
820
1169
  outcome = "throttled";
821
- deps.log("the dashboard refused this report as too soon (HTTP 429): the next due run tries again");
1170
+ deps.log(
1171
+ "the dashboard refused this report as too soon (HTTP 429): the next due run tries again"
1172
+ );
822
1173
  } else if (sent.status === 401) {
823
1174
  outcome = "refused";
824
1175
  refused = true;
825
- deps.log("the dashboard refused this machine's reporting bearer on a report (HTTP 401)");
1176
+ deps.log(
1177
+ "the dashboard refused this machine's reporting bearer on a report (HTTP 401)"
1178
+ );
826
1179
  } else {
827
1180
  outcome = "failed";
828
- deps.log(`report failed at ${startedAt.toISOString()}: ${sent.error}; the next due run tries again`);
1181
+ deps.log(
1182
+ `report failed at ${startedAt.toISOString()}: ${sent.error}; the next due run tries again`
1183
+ );
829
1184
  }
830
- if (deps.installed()) deps.writeStatus({ last_report_at: startedAt.toISOString(), last_report_outcome: outcome, last_report_error: error });
1185
+ if (deps.installed())
1186
+ deps.writeStatus({
1187
+ last_report_at: startedAt.toISOString(),
1188
+ last_report_outcome: outcome,
1189
+ last_report_error: error
1190
+ });
831
1191
  };
832
1192
  return {
833
1193
  async sample(at) {
834
1194
  if (sampling) {
835
- deps.log("the last leftover sample is still running: skipping this one");
1195
+ deps.log(
1196
+ "the last leftover sample is still running: skipping this one"
1197
+ );
836
1198
  return;
837
1199
  }
838
1200
  sampling = true;
839
1201
  try {
840
1202
  await deps.leftovers.sample(at);
841
1203
  } catch (err) {
842
- deps.log(`leftover sampling failed at ${at.toISOString()}: ${errMessage(err)}; the next beat tries again`);
1204
+ deps.log(
1205
+ `leftover sampling failed at ${at.toISOString()}: ${errMessage(err)}; the next beat tries again`
1206
+ );
843
1207
  } finally {
844
1208
  sampling = false;
845
1209
  }
846
1210
  },
847
1211
  tick(startedAt) {
848
- if (lastStartMs !== null && startedAt.getTime() - lastStartMs < REPORT_INTERVAL_MS - REPORT_TICK_TOLERANCE_MS) return null;
1212
+ if (lastStartMs !== null && startedAt.getTime() - lastStartMs < REPORT_INTERVAL_MS - REPORT_TICK_TOLERANCE_MS)
1213
+ return null;
849
1214
  if (running) {
850
1215
  deps.log("the last health report is still running: skipping this one");
851
1216
  return null;
852
1217
  }
853
1218
  lastStartMs = startedAt.getTime();
854
1219
  running = true;
855
- return run(startedAt).catch((err) => deps.log(`report failed at ${startedAt.toISOString()}: ${errMessage(err)}; the next due run tries again`)).finally(() => {
1220
+ return run(startedAt).catch(
1221
+ (err) => deps.log(
1222
+ `report failed at ${startedAt.toISOString()}: ${errMessage(err)}; the next due run tries again`
1223
+ )
1224
+ ).finally(() => {
856
1225
  running = false;
857
1226
  });
858
1227
  },
@@ -861,7 +1230,16 @@ function createReporter(deps) {
861
1230
  }
862
1231
 
863
1232
  // src/machine-daemon/state.ts
864
- import { appendFileSync, chmodSync, existsSync as existsSync2, mkdirSync, readFileSync as readFileSync3, renameSync, statSync, writeFileSync } from "node:fs";
1233
+ import {
1234
+ appendFileSync,
1235
+ chmodSync,
1236
+ existsSync as existsSync2,
1237
+ mkdirSync,
1238
+ readFileSync as readFileSync3,
1239
+ renameSync,
1240
+ statSync,
1241
+ writeFileSync
1242
+ } from "node:fs";
865
1243
  import { homedir as homedir2 } from "node:os";
866
1244
  import { dirname, join as join3 } from "node:path";
867
1245
  var MACHINE_DAEMON_DIR_NAME = ".danxbot";
@@ -904,7 +1282,10 @@ function writeOwnerOnlyJson(file, value) {
904
1282
  mkdirSync(dirname(file), { recursive: true });
905
1283
  const tmp = `${file}.${process.pid}.tmp`;
906
1284
  writeFileSync(tmp, `${JSON.stringify(value, null, 2)}
907
- `, { encoding: "utf8", mode: 384 });
1285
+ `, {
1286
+ encoding: "utf8",
1287
+ mode: 384
1288
+ });
908
1289
  if (process.platform !== "win32") chmodSync(tmp, 384);
909
1290
  renameSync(tmp, file);
910
1291
  }
@@ -918,13 +1299,20 @@ function createDaemonLog(file, now = () => /* @__PURE__ */ new Date(), maxBytes
918
1299
  return (line) => {
919
1300
  try {
920
1301
  mkdirSync(dirname(file), { recursive: true });
921
- if (!narrowed && existsSync2(file) && process.platform !== "win32") chmodSync(file, 384);
1302
+ if (!narrowed && existsSync2(file) && process.platform !== "win32")
1303
+ chmodSync(file, 384);
922
1304
  narrowed = true;
923
- if (existsSync2(file) && statSync(file).size >= maxBytes) renameSync(file, `${file}.1`);
1305
+ if (existsSync2(file) && statSync(file).size >= maxBytes)
1306
+ renameSync(file, `${file}.1`);
924
1307
  appendFileSync(file, `${now().toISOString()} ${line}
925
- `, { encoding: "utf8", mode: 384 });
1308
+ `, {
1309
+ encoding: "utf8",
1310
+ mode: 384
1311
+ });
926
1312
  } catch (err) {
927
- console.error(`[machine-daemon] cannot write ${file}: ${err instanceof Error ? err.message : String(err)}`);
1313
+ console.error(
1314
+ `[machine-daemon] cannot write ${file}: ${err instanceof Error ? err.message : String(err)}`
1315
+ );
928
1316
  }
929
1317
  };
930
1318
  }
@@ -944,7 +1332,9 @@ function readBearerOnDisk() {
944
1332
  async function runDaemonProcess() {
945
1333
  const config = readJsonIfPresent(daemonConfigPath());
946
1334
  if (config === null) {
947
- console.error("[machine-daemon] no config: run npx @50arms/platform-mcp install-daemon first");
1335
+ console.error(
1336
+ "[machine-daemon] no config: run npx @50arms/platform-mcp install-daemon first"
1337
+ );
948
1338
  return 2;
949
1339
  }
950
1340
  const fetchFn = fetch;
@@ -954,8 +1344,12 @@ async function runDaemonProcess() {
954
1344
  console.log(`[machine-daemon] ${line}`);
955
1345
  logToFile(line);
956
1346
  };
957
- log(`started: pid ${process.pid}, daemon ${config.daemon_version}, dashboard ${config.dashboard_url}`);
958
- const status = createStatusWriter((value) => writeOwnerOnlyJson(daemonStatusPath(), value));
1347
+ log(
1348
+ `started: pid ${process.pid}, daemon ${config.daemon_version}, dashboard ${config.dashboard_url}`
1349
+ );
1350
+ const status = createStatusWriter(
1351
+ (value) => writeOwnerOnlyJson(daemonStatusPath(), value)
1352
+ );
959
1353
  const stop = await runBeatLoop({
960
1354
  config,
961
1355
  collect: createMachineVitalsCollector({ diskPath: homedir3() }),
@@ -969,7 +1363,11 @@ async function runDaemonProcess() {
969
1363
  readBearer: readBearerOnDisk,
970
1364
  reporter: createReporter({
971
1365
  config,
972
- runHealth: () => runHealthChild({ spawnFn: spawn, nodePath: process.execPath, toolkitPath: toolkitBundlePath() }),
1366
+ runHealth: () => runHealthChild({
1367
+ spawnFn: spawn,
1368
+ nodePath: process.execPath,
1369
+ toolkitPath: toolkitBundlePath()
1370
+ }),
973
1371
  fetchFn,
974
1372
  leftovers: createSystemLeftoverTracker(log),
975
1373
  writeStatus: status.report,
@@ -977,14 +1375,19 @@ async function runDaemonProcess() {
977
1375
  installed: () => existsSync3(daemonConfigPath())
978
1376
  })
979
1377
  });
980
- return finishBeatStop(stop, () => disableAutostart({ platform: process.platform, run: runHidden }));
1378
+ return finishBeatStop(
1379
+ stop,
1380
+ () => disableAutostart({ platform: process.platform, run: runHidden })
1381
+ );
981
1382
  }
982
1383
 
983
1384
  // src/machine-daemon/entry.ts
984
1385
  runDaemonProcess().then(
985
1386
  (code) => process.exit(code),
986
1387
  (err) => {
987
- console.error(`[machine-daemon] fatal: ${err instanceof Error ? err.message : String(err)}`);
1388
+ console.error(
1389
+ `[machine-daemon] fatal: ${err instanceof Error ? err.message : String(err)}`
1390
+ );
988
1391
  process.exit(1);
989
1392
  }
990
1393
  );