@50arms/platform-mcp 0.1.464 → 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 (66) 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 +6 -2
  15. package/dist/handlers.js +66 -14
  16. package/dist/heartbeat-reporter.js +8 -3
  17. package/dist/http-client.js +4 -2
  18. package/dist/index.js +242 -80
  19. package/dist/job-key.js +3 -1
  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.js +6 -2
  52. package/dist/session-access.js +110 -32
  53. package/dist/session-connection.js +23 -7
  54. package/dist/session-control-file.js +1 -1
  55. package/dist/session-key.js +12 -4
  56. package/dist/session-options.js +6 -2
  57. package/dist/session-stats.js +2 -1
  58. package/dist/session-stream.js +81 -20
  59. package/dist/shutdown.js +3 -1
  60. package/dist/subagents-live.js +8 -2
  61. package/dist/terms-halt.js +4 -2
  62. package/dist/tool-access.js +17 -4
  63. package/dist/tool-surface.js +9 -2
  64. package/dist/transcript-lineage.js +5 -2
  65. package/dist/urgent-records.js +1 -0
  66. package/package.json +1 -1
@@ -15,13 +15,22 @@ var EXIT = {
15
15
  /** `sweep` / `maintain` refused to start because a compaction window is open (the only refusal today). */
16
16
  refused: 3
17
17
  };
18
- var REQUIRED_METRICS = ["docker_data_disk_bytes", "unowned_docker_resource_count", "orphan_process_count"];
18
+ var REQUIRED_METRICS = [
19
+ "docker_data_disk_bytes",
20
+ "unowned_docker_resource_count",
21
+ "orphan_process_count"
22
+ ];
19
23
  var PROCESS_START_METRIC = "process_start_ms";
20
24
  var KERNEL_TOKEN_METRIC = "kernel_token_count";
21
- var HEALTH_ITEM_LISTS = ["unowned_docker_resources", "orphan_processes"];
25
+ var HEALTH_ITEM_LISTS = [
26
+ "unowned_docker_resources",
27
+ "orphan_processes"
28
+ ];
22
29
  var ContractViolation = class extends Error {
23
30
  constructor(command, path, what) {
24
- super(`${command} output does not match machine-toolkit contract v${CONTRACT_VERSION}: ${path} ${what}`);
31
+ super(
32
+ `${command} output does not match machine-toolkit contract v${CONTRACT_VERSION}: ${path} ${what}`
33
+ );
25
34
  this.name = "ContractViolation";
26
35
  }
27
36
  };
@@ -33,11 +42,13 @@ function objectAt(v, path, fail2) {
33
42
  }
34
43
  function exactKeys(o, path, keys, fail2) {
35
44
  for (const k of keys) if (!(k in o)) fail2(join(path, k), "is required");
36
- for (const k of Object.keys(o)) if (!keys.includes(k)) fail2(join(path, k), "is not part of the contract");
45
+ for (const k of Object.keys(o))
46
+ if (!keys.includes(k)) fail2(join(path, k), "is not part of the contract");
37
47
  }
38
48
  function stringAt(o, key, path, fail2) {
39
49
  const v = o[key];
40
- if (typeof v !== "string" || v === "") return fail2(join(path, key), "must be a non-empty string");
50
+ if (typeof v !== "string" || v === "")
51
+ return fail2(join(path, key), "must be a non-empty string");
41
52
  return v;
42
53
  }
43
54
  function listAt(v, path, fail2) {
@@ -48,54 +59,80 @@ function checkItem(v, path, extra, fail2) {
48
59
  const o = objectAt(v, path, fail2);
49
60
  exactKeys(o, path, ["id", "detail", ...extra], fail2);
50
61
  stringAt(o, "id", path, fail2);
51
- if (typeof o.detail !== "string") fail2(join(path, "detail"), "must be a string");
62
+ if (typeof o.detail !== "string")
63
+ fail2(join(path, "detail"), "must be a string");
52
64
  for (const k of extra) stringAt(o, k, path, fail2);
53
65
  }
54
66
  function checkItems(v, path, extra, fail2) {
55
- listAt(v, path, fail2).forEach((item, i) => checkItem(item, `${path}[${i}]`, extra, fail2));
67
+ listAt(v, path, fail2).forEach(
68
+ (item, i) => checkItem(item, `${path}[${i}]`, extra, fail2)
69
+ );
56
70
  }
57
71
  function checkMetric(v, path, fail2) {
58
72
  const o = objectAt(v, path, fail2);
59
73
  exactKeys(o, path, ["value", "reason", "source", "age_seconds"], fail2);
60
74
  if (o.value === null) {
61
- if (typeof o.reason !== "string" || o.reason === "") fail2(`${path}.reason`, "must say why the value is null");
75
+ if (typeof o.reason !== "string" || o.reason === "")
76
+ fail2(`${path}.reason`, "must say why the value is null");
62
77
  } else {
63
- if (typeof o.value !== "number" || !Number.isFinite(o.value) || o.value < 0) fail2(`${path}.value`, "must be null or a finite number of at least 0");
64
- if (o.reason !== null) fail2(`${path}.reason`, "must be null when the value was read");
78
+ if (typeof o.value !== "number" || !Number.isFinite(o.value) || o.value < 0)
79
+ fail2(`${path}.value`, "must be null or a finite number of at least 0");
80
+ if (o.reason !== null)
81
+ fail2(`${path}.reason`, "must be null when the value was read");
65
82
  }
66
- if (o.source !== "fresh" && o.source !== "cached") fail2(`${path}.source`, "must be 'fresh' or 'cached'");
67
- if (typeof o.age_seconds !== "number" || !Number.isFinite(o.age_seconds) || o.age_seconds < 0) fail2(`${path}.age_seconds`, "must be a number of at least 0");
68
- if (o.source === "fresh" && o.age_seconds !== 0) fail2(`${path}.age_seconds`, "must be 0 for a fresh reading");
83
+ if (o.source !== "fresh" && o.source !== "cached")
84
+ fail2(`${path}.source`, "must be 'fresh' or 'cached'");
85
+ if (typeof o.age_seconds !== "number" || !Number.isFinite(o.age_seconds) || o.age_seconds < 0)
86
+ fail2(`${path}.age_seconds`, "must be a number of at least 0");
87
+ if (o.source === "fresh" && o.age_seconds !== 0)
88
+ fail2(`${path}.age_seconds`, "must be 0 for a fresh reading");
69
89
  }
70
90
  function checkEnvelope(o, fail2) {
71
- if (o.contract_version !== CONTRACT_VERSION) fail2("contract_version", `must be ${CONTRACT_VERSION}`);
91
+ if (o.contract_version !== CONTRACT_VERSION)
92
+ fail2("contract_version", `must be ${CONTRACT_VERSION}`);
72
93
  stringAt(o, "toolkit_version", "", fail2);
73
94
  stringAt(o, "profile", "", fail2);
74
95
  const at = stringAt(o, "measured_at", "", fail2);
75
- if (Number.isNaN(new Date(at).getTime())) fail2("measured_at", "must be an ISO time");
76
- }
77
- var ENVELOPE_KEYS = ["contract_version", "toolkit_version", "profile", "measured_at"];
96
+ if (Number.isNaN(new Date(at).getTime()))
97
+ fail2("measured_at", "must be an ISO time");
98
+ }
99
+ var ENVELOPE_KEYS = [
100
+ "contract_version",
101
+ "toolkit_version",
102
+ "profile",
103
+ "measured_at"
104
+ ];
78
105
  var VALIDATORS = {
79
106
  health(o, fail2) {
80
107
  exactKeys(o, "", [...ENVELOPE_KEYS, "metrics", "items"], fail2);
81
108
  checkEnvelope(o, fail2);
82
109
  const metrics = objectAt(o.metrics, "metrics", fail2);
83
- for (const name of REQUIRED_METRICS) if (!(name in metrics)) fail2(`metrics.${name}`, "is required");
84
- for (const [name, metric] of Object.entries(metrics)) checkMetric(metric, `metrics.${name}`, fail2);
110
+ for (const name of REQUIRED_METRICS)
111
+ if (!(name in metrics)) fail2(`metrics.${name}`, "is required");
112
+ for (const [name, metric] of Object.entries(metrics))
113
+ checkMetric(metric, `metrics.${name}`, fail2);
85
114
  const tokens = metrics[KERNEL_TOKEN_METRIC]?.value;
86
- if (typeof tokens === "number" && !Number.isInteger(tokens)) fail2(`metrics.${KERNEL_TOKEN_METRIC}.value`, "must be a whole number");
115
+ if (typeof tokens === "number" && !Number.isInteger(tokens))
116
+ fail2(`metrics.${KERNEL_TOKEN_METRIC}.value`, "must be a whole number");
87
117
  const items = objectAt(o.items, "items", fail2);
88
118
  exactKeys(items, "items", HEALTH_ITEM_LISTS, fail2);
89
- for (const list of HEALTH_ITEM_LISTS) checkItems(items[list], `items.${list}`, [], fail2);
119
+ for (const list of HEALTH_ITEM_LISTS)
120
+ checkItems(items[list], `items.${list}`, [], fail2);
90
121
  },
91
122
  sweep(o, fail2) {
92
123
  exactKeys(o, "", [...ENVELOPE_KEYS, "dry_run", "kinds"], fail2);
93
124
  checkEnvelope(o, fail2);
94
- if (typeof o.dry_run !== "boolean") fail2("dry_run", "must be true or false");
125
+ if (typeof o.dry_run !== "boolean")
126
+ fail2("dry_run", "must be true or false");
95
127
  listAt(o.kinds, "kinds", fail2).forEach((k, i) => {
96
128
  const path = `kinds[${i}]`;
97
129
  const kind = objectAt(k, path, fail2);
98
- exactKeys(kind, path, ["kind", "removed", "kept", "failed", "flagged"], fail2);
130
+ exactKeys(
131
+ kind,
132
+ path,
133
+ ["kind", "removed", "kept", "failed", "flagged"],
134
+ fail2
135
+ );
99
136
  stringAt(kind, "kind", path, fail2);
100
137
  checkItems(kind.removed, `${path}.removed`, [], fail2);
101
138
  checkItems(kind.kept, `${path}.kept`, ["reason"], fail2);
@@ -111,8 +148,10 @@ var VALIDATORS = {
111
148
  const step = objectAt(s, path, fail2);
112
149
  exactKeys(step, path, ["name", "status", "detail"], fail2);
113
150
  stringAt(step, "name", path, fail2);
114
- if (step.status !== "done" && step.status !== "skipped" && step.status !== "failed") fail2(`${path}.status`, "must be 'done', 'skipped' or 'failed'");
115
- if (typeof step.detail !== "string") fail2(join(path, "detail"), "must be a string");
151
+ if (step.status !== "done" && step.status !== "skipped" && step.status !== "failed")
152
+ fail2(`${path}.status`, "must be 'done', 'skipped' or 'failed'");
153
+ if (typeof step.detail !== "string")
154
+ fail2(join(path, "detail"), "must be a string");
116
155
  });
117
156
  },
118
157
  "label-check"(o, fail2) {
@@ -124,12 +163,21 @@ var VALIDATORS = {
124
163
  };
125
164
  function assertContract(command, report) {
126
165
  const fail2 = (path, what) => {
127
- throw new ContractViolation(command, path === "" ? "(document)" : path, what);
166
+ throw new ContractViolation(
167
+ command,
168
+ path === "" ? "(document)" : path,
169
+ what
170
+ );
128
171
  };
129
172
  VALIDATORS[command](objectAt(report, "", fail2), fail2);
130
173
  }
131
174
  var metricRead = (value, source = "fresh", ageSeconds = 0) => ({ value, reason: null, source, age_seconds: ageSeconds });
132
- var metricUnread = (reason) => ({ value: null, reason, source: "fresh", age_seconds: 0 });
175
+ var metricUnread = (reason) => ({
176
+ value: null,
177
+ reason,
178
+ source: "fresh",
179
+ age_seconds: 0
180
+ });
133
181
  function healthExitCode(report) {
134
182
  return Object.values(report.metrics).some((m) => m.value === null) ? EXIT.degraded : EXIT.ok;
135
183
  }
@@ -139,12 +187,22 @@ import { statSync } from "node:fs";
139
187
  import { join as join2 } from "node:path";
140
188
  var DATA_DISK_RELATIVE = ["Docker", "wsl", "disk", "docker_data.vhdx"];
141
189
  function readDockerDataDisk(localAppData = process.env.LOCALAPPDATA, stat = statSync) {
142
- if (!localAppData) return { path: null, bytes: null, unavailableReason: "LOCALAPPDATA is not set (not a Windows session)" };
190
+ if (!localAppData)
191
+ return {
192
+ path: null,
193
+ bytes: null,
194
+ unavailableReason: "LOCALAPPDATA is not set (not a Windows session)"
195
+ };
143
196
  const path = join2(localAppData, ...DATA_DISK_RELATIVE);
144
197
  try {
145
198
  return { path, bytes: stat(path).size };
146
199
  } catch (err) {
147
- if (err.code === "ENOENT") return { path, bytes: null, unavailableReason: "the file does not exist (Docker Desktop's WSL2 backend is not in use here)" };
200
+ if (err.code === "ENOENT")
201
+ return {
202
+ path,
203
+ bytes: null,
204
+ unavailableReason: "the file does not exist (Docker Desktop's WSL2 backend is not in use here)"
205
+ };
148
206
  throw err;
149
207
  }
150
208
  }
@@ -163,10 +221,26 @@ function isWsl(kernelRelease = release(), platform = process.platform, hasDrvFs
163
221
  }
164
222
  var WSL_CALL_TIMEOUT_MS = 1e4;
165
223
  function windowsHomeFromWsl() {
166
- const raw = execFileSync("cmd.exe", ["/c", "echo %USERPROFILE%"], { windowsHide: true, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: WSL_CALL_TIMEOUT_MS }).replace(/\r/g, "").trim();
167
- if (raw === "" || raw.includes("%")) throw new Error(`could not resolve the Windows home from cmd.exe (it said '${raw}')`);
168
- const path = execFileSync("wslpath", ["-u", raw], { windowsHide: true, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: WSL_CALL_TIMEOUT_MS }).trim();
169
- if (!existsSync(path)) throw new Error(`the Windows home '${raw}' is not a directory under /mnt/c`);
224
+ const raw = execFileSync("cmd.exe", ["/c", "echo %USERPROFILE%"], {
225
+ windowsHide: true,
226
+ encoding: "utf8",
227
+ stdio: ["ignore", "pipe", "ignore"],
228
+ timeout: WSL_CALL_TIMEOUT_MS
229
+ }).replace(/\r/g, "").trim();
230
+ if (raw === "" || raw.includes("%"))
231
+ throw new Error(
232
+ `could not resolve the Windows home from cmd.exe (it said '${raw}')`
233
+ );
234
+ const path = execFileSync("wslpath", ["-u", raw], {
235
+ windowsHide: true,
236
+ encoding: "utf8",
237
+ stdio: ["ignore", "pipe", "ignore"],
238
+ timeout: WSL_CALL_TIMEOUT_MS
239
+ }).trim();
240
+ if (!existsSync(path))
241
+ throw new Error(
242
+ `the Windows home '${raw}' is not a directory under /mnt/c`
243
+ );
170
244
  return path;
171
245
  }
172
246
  var COMPACTION_WINDOW_FILE = "compaction-window";
@@ -184,19 +258,38 @@ function flagsFile(home = machineHome()) {
184
258
  return join4(home, ".danxbot", "docker-flags.json");
185
259
  }
186
260
  function fail(path, what) {
187
- throw Object.assign(new Error(`${path} is malformed: ${what}`), { code: "EMALFORMED" });
261
+ throw Object.assign(new Error(`${path} is malformed: ${what}`), {
262
+ code: "EMALFORMED"
263
+ });
188
264
  }
189
265
  function validateFlags(value, path) {
190
- if (value === null || typeof value !== "object" || Array.isArray(value)) fail(path, "not a JSON object");
191
- if (typeof value.at !== "string" || Number.isNaN(new Date(value.at).getTime())) fail(path, `"at" must be an ISO time, not ${JSON.stringify(value.at)}`);
192
- if (!Number.isInteger(value.unowned) || value.unowned < 0) fail(path, `"unowned" must be a whole number, not ${JSON.stringify(value.unowned)}`);
266
+ if (value === null || typeof value !== "object" || Array.isArray(value))
267
+ fail(path, "not a JSON object");
268
+ if (typeof value.at !== "string" || Number.isNaN(new Date(value.at).getTime()))
269
+ fail(path, `"at" must be an ISO time, not ${JSON.stringify(value.at)}`);
270
+ if (!Number.isInteger(value.unowned) || value.unowned < 0)
271
+ fail(
272
+ path,
273
+ `"unowned" must be a whole number, not ${JSON.stringify(value.unowned)}`
274
+ );
193
275
  if (!Array.isArray(value.flagged)) fail(path, `"flagged" must be a list`);
194
276
  for (const f of value.flagged) {
195
277
  if (f === null || typeof f !== "object" || typeof f.id !== "string" || typeof f.reason !== "string" || !(f.card === null || typeof f.card === "string")) {
196
- fail(path, `every "flagged" entry needs a string id and reason and a card (string or null), not ${JSON.stringify(f)}`);
278
+ fail(
279
+ path,
280
+ `every "flagged" entry needs a string id and reason and a card (string or null), not ${JSON.stringify(f)}`
281
+ );
197
282
  }
198
283
  }
199
- return { at: value.at, unowned: value.unowned, flagged: value.flagged.map((f) => ({ id: f.id, reason: f.reason, card: f.card })) };
284
+ return {
285
+ at: value.at,
286
+ unowned: value.unowned,
287
+ flagged: value.flagged.map((f) => ({
288
+ id: f.id,
289
+ reason: f.reason,
290
+ card: f.card
291
+ }))
292
+ };
200
293
  }
201
294
  function readFlags(path = flagsFile()) {
202
295
  let text;
@@ -224,7 +317,12 @@ var DeadlineExceeded = class extends Error {
224
317
  };
225
318
  function withDeadline(work, ms, schedule, what) {
226
319
  return new Promise((resolve, reject) => {
227
- const cancel = schedule(() => reject(new DeadlineExceeded(`${what} did not answer within ${ms / 1e3}s`)), ms);
320
+ const cancel = schedule(
321
+ () => reject(
322
+ new DeadlineExceeded(`${what} did not answer within ${ms / 1e3}s`)
323
+ ),
324
+ ms
325
+ );
228
326
  work.then(
229
327
  (v) => {
230
328
  cancel();
@@ -241,7 +339,8 @@ function withDeadline(work, ms, schedule, what) {
241
339
  // src/machine-toolkit/errors.ts
242
340
  function errorCode(err) {
243
341
  const failure = err;
244
- if (typeof failure?.code === "string" || typeof failure?.code === "number") return String(failure.code);
342
+ if (typeof failure?.code === "string" || typeof failure?.code === "number")
343
+ return String(failure.code);
245
344
  return failure?.killed === true ? "timed out" : "unexpected error";
246
345
  }
247
346
  function errMessage(err) {
@@ -264,12 +363,16 @@ var DOCKER_BUILD = /(?:^|[\\/"\s])docker(?:\.exe)?"?\s+(?:buildx\s+)?build\b/;
264
363
  var NODE_NAMES = /* @__PURE__ */ new Set(["node", "node.exe"]);
265
364
  var INIT_PID = 1;
266
365
  var WSL_DISTRO = "Ubuntu";
267
- var DOCKER_DESKTOP_DISTROS = /* @__PURE__ */ new Set(["docker-desktop", "docker-desktop-data"]);
366
+ var DOCKER_DESKTOP_DISTROS = /* @__PURE__ */ new Set([
367
+ "docker-desktop",
368
+ "docker-desktop-data"
369
+ ]);
268
370
  var LISTING_MAX_BUFFER_BYTES = 64 * 1024 * 1024;
269
371
  function kindOf(row) {
270
372
  if (DOCKER_BUILD.test(row.commandLine)) return "docker build";
271
373
  if (NODE_NAMES.has(row.name.toLowerCase())) return "node";
272
- if (row.source === "wsl" && WSL_SHELL_NAMES.has(row.name.toLowerCase())) return "shell";
374
+ if (row.source === "wsl" && WSL_SHELL_NAMES.has(row.name.toLowerCase()))
375
+ return "shell";
273
376
  return null;
274
377
  }
275
378
  function parentGone(row, bySourceAndPid) {
@@ -286,7 +389,13 @@ function findOrphans(rows, now) {
286
389
  if (kind === null || row.startedAt === null) continue;
287
390
  if (now.getTime() - row.startedAt.getTime() < ORPHAN_MIN_AGE_MS) continue;
288
391
  if (!parentGone(row, bySourceAndPid)) continue;
289
- found.push({ source: row.source, pid: row.pid, kind, startedAt: row.startedAt, commandLine: row.commandLine.slice(0, COMMAND_LINE_MAX_CHARS) });
392
+ found.push({
393
+ source: row.source,
394
+ pid: row.pid,
395
+ kind,
396
+ startedAt: row.startedAt,
397
+ commandLine: row.commandLine.slice(0, COMMAND_LINE_MAX_CHARS)
398
+ });
290
399
  }
291
400
  return found.sort((a, b) => a.startedAt.getTime() - b.startedAt.getTime());
292
401
  }
@@ -309,30 +418,103 @@ function parseWslListing(stdout, now) {
309
418
  for (const line of stdout.split("\n")) {
310
419
  if (line.trim() === "") continue;
311
420
  const m = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s*(.*)$/.exec(line);
312
- if (!m) throw new Error(`wsl ps printed a line this report cannot read: ${JSON.stringify(line)}`);
313
- 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 });
421
+ if (!m)
422
+ throw new Error(
423
+ `wsl ps printed a line this report cannot read: ${JSON.stringify(line)}`
424
+ );
425
+ rows.push({
426
+ source: "wsl",
427
+ pid: Number(m[1]),
428
+ ppid: Number(m[2]),
429
+ startedAt: new Date(now.getTime() - Number(m[3]) * 1e3),
430
+ name: m[4],
431
+ commandLine: m[5],
432
+ executablePath: "",
433
+ cpuTime100ns: null
434
+ });
314
435
  }
315
436
  return rows;
316
437
  }
317
438
  var runCommand = (file, args, timeoutMs, signal) => new Promise((resolve, reject) => {
318
- execFile(file, args, { timeout: timeoutMs, maxBuffer: LISTING_MAX_BUFFER_BYTES, windowsHide: true, signal }, (err, stdout) => err ? reject(err) : resolve(stdout));
439
+ execFile(
440
+ file,
441
+ args,
442
+ {
443
+ timeout: timeoutMs,
444
+ maxBuffer: LISTING_MAX_BUFFER_BYTES,
445
+ windowsHide: true,
446
+ signal
447
+ },
448
+ (err, stdout) => err ? reject(err) : resolve(stdout)
449
+ );
319
450
  });
320
451
  async function wslDistroRunning(run, signal) {
321
- const stdout = await run("wsl.exe", ["--list", "--running", "--quiet"], PROCESS_LISTING_TIMEOUT_MS, signal);
452
+ const stdout = await run(
453
+ "wsl.exe",
454
+ ["--list", "--running", "--quiet"],
455
+ PROCESS_LISTING_TIMEOUT_MS,
456
+ signal
457
+ );
322
458
  const running = stdout.replace(/\0/g, "").split(/\r?\n/).map((line) => line.trim()).filter((line) => line !== "" && !DOCKER_DESKTOP_DISTROS.has(line));
323
459
  if (running.length === 0) return false;
324
460
  if (running.includes(WSL_DISTRO)) return true;
325
- throw Object.assign(new Error(`${WSL_DISTRO} is not among the running WSL distros: ${running.join(", ")}`), { code: "distro not running" });
461
+ throw Object.assign(
462
+ new Error(
463
+ `${WSL_DISTRO} is not among the running WSL distros: ${running.join(", ")}`
464
+ ),
465
+ { code: "distro not running" }
466
+ );
326
467
  }
327
468
  async function listProcesses(now = /* @__PURE__ */ new Date(), run = runCommand, platform = process.platform, signal, wsl = "always") {
328
- if (platform !== "win32") return { rows: [], unavailable: [{ source: "windows", reason: "orphan-process listing is implemented for the Windows dev machine only", code: "unsupported platform" }] };
469
+ if (platform !== "win32")
470
+ return {
471
+ rows: [],
472
+ unavailable: [
473
+ {
474
+ source: "windows",
475
+ reason: "orphan-process listing is implemented for the Windows dev machine only",
476
+ code: "unsupported platform"
477
+ }
478
+ ]
479
+ };
329
480
  const allListings = [
330
- { source: "windows", read: async () => parseWindowsListing(await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_LISTING_SCRIPT], PROCESS_LISTING_TIMEOUT_MS, signal)) },
481
+ {
482
+ source: "windows",
483
+ read: async () => parseWindowsListing(
484
+ await run(
485
+ "powershell.exe",
486
+ [
487
+ "-NoProfile",
488
+ "-NonInteractive",
489
+ "-Command",
490
+ WINDOWS_LISTING_SCRIPT
491
+ ],
492
+ PROCESS_LISTING_TIMEOUT_MS,
493
+ signal
494
+ )
495
+ )
496
+ },
331
497
  {
332
498
  source: "wsl",
333
499
  read: async () => {
334
- if (wsl === "when-running" && !await wslDistroRunning(run, signal)) return [];
335
- return parseWslListing(await run("wsl.exe", ["-d", WSL_DISTRO, "--", "ps", "-eo", "pid=,ppid=,etimes=,comm=,args="], PROCESS_LISTING_TIMEOUT_MS, signal), now);
500
+ if (wsl === "when-running" && !await wslDistroRunning(run, signal))
501
+ return [];
502
+ return parseWslListing(
503
+ await run(
504
+ "wsl.exe",
505
+ [
506
+ "-d",
507
+ WSL_DISTRO,
508
+ "--",
509
+ "ps",
510
+ "-eo",
511
+ "pid=,ppid=,etimes=,comm=,args="
512
+ ],
513
+ PROCESS_LISTING_TIMEOUT_MS,
514
+ signal
515
+ ),
516
+ now
517
+ );
336
518
  }
337
519
  }
338
520
  ];
@@ -342,12 +524,23 @@ async function listProcesses(now = /* @__PURE__ */ new Date(), run = runCommand,
342
524
  const unavailable = [];
343
525
  settled.forEach((s, i) => {
344
526
  if (s.status === "fulfilled") rows.push(...s.value);
345
- else unavailable.push({ source: listings[i].source, reason: errMessage(s.reason), code: errorCode(s.reason) });
527
+ else
528
+ unavailable.push({
529
+ source: listings[i].source,
530
+ reason: errMessage(s.reason),
531
+ code: errorCode(s.reason)
532
+ });
346
533
  });
347
534
  return { rows, unavailable };
348
535
  }
349
536
  async function reportOrphanProcesses(now = /* @__PURE__ */ new Date(), run = runCommand, platform = process.platform, signal, wsl = "always") {
350
- const { rows, unavailable } = await listProcesses(now, run, platform, signal, wsl);
537
+ const { rows, unavailable } = await listProcesses(
538
+ now,
539
+ run,
540
+ platform,
541
+ signal,
542
+ wsl
543
+ );
351
544
  return { findings: findOrphans(rows, now), unavailable };
352
545
  }
353
546
 
@@ -363,10 +556,19 @@ function probeProcessStart(opts) {
363
556
  const nowMs = opts.nowMs ?? (() => performance.now());
364
557
  return new Promise((resolve, reject) => {
365
558
  const startedAt = nowMs();
366
- const child = opts.spawnFn(file, args, { windowsHide: true, stdio: "ignore", signal: opts.signal });
559
+ const child = opts.spawnFn(file, args, {
560
+ windowsHide: true,
561
+ stdio: "ignore",
562
+ signal: opts.signal
563
+ });
367
564
  child.on("error", reject);
368
565
  child.on("close", (code) => {
369
- if (code !== 0) reject(Object.assign(new Error(`${file} exited ${code ?? "on a signal"}`), { code: "probe exit" }));
566
+ if (code !== 0)
567
+ reject(
568
+ Object.assign(new Error(`${file} exited ${code ?? "on a signal"}`), {
569
+ code: "probe exit"
570
+ })
571
+ );
370
572
  else resolve(Math.round(nowMs() - startedAt));
371
573
  });
372
574
  });
@@ -398,7 +600,13 @@ public static class DxTokeProbe {
398
600
  `;
399
601
  var TOKEN_COMPILE_TIMEOUT_MS = 15e3;
400
602
  function cscPath(windir) {
401
- return join5(windir ?? String.raw`C:\Windows`, "Microsoft.NET", "Framework64", "v4.0.30319", "csc.exe");
603
+ return join5(
604
+ windir ?? String.raw`C:\Windows`,
605
+ "Microsoft.NET",
606
+ "Framework64",
607
+ "v4.0.30319",
608
+ "csc.exe"
609
+ );
402
610
  }
403
611
  function tokenProbeExeName(source = TOKEN_PROBE_SOURCE) {
404
612
  return `token-probe-${createHash("sha256").update(source).digest("hex").slice(0, 12)}.exe`;
@@ -418,22 +626,46 @@ async function ensureTokenProbeExe(opts) {
418
626
  const source = exe.replace(/\.exe$/, ".cs");
419
627
  const temp = join5(opts.dir, `token-probe-${tag}.tmp.exe`);
420
628
  files.write(source, TOKEN_PROBE_SOURCE);
421
- await opts.run(cscPath(opts.windir), ["-nologo", "-target:exe", `-out:${temp}`, source], TOKEN_COMPILE_TIMEOUT_MS, opts.signal);
629
+ await opts.run(
630
+ cscPath(opts.windir),
631
+ ["-nologo", "-target:exe", `-out:${temp}`, source],
632
+ TOKEN_COMPILE_TIMEOUT_MS,
633
+ opts.signal
634
+ );
422
635
  files.rename(temp, exe);
423
636
  return exe;
424
637
  }
425
638
  function parseTokenCount(stdout) {
426
639
  const text = stdout.trim();
427
- if (!/^-?\d+$/.test(text)) throw Object.assign(new Error(`the token query printed ${JSON.stringify(text.slice(0, 40))}`), { code: "token output" });
640
+ if (!/^-?\d+$/.test(text))
641
+ throw Object.assign(
642
+ new Error(`the token query printed ${JSON.stringify(text.slice(0, 40))}`),
643
+ { code: "token output" }
644
+ );
428
645
  const n = Number(text);
429
- if (!Number.isSafeInteger(n) || n < 0) throw Object.assign(new Error(`the token query printed ${text}`), { code: "token output" });
646
+ if (!Number.isSafeInteger(n) || n < 0)
647
+ throw Object.assign(new Error(`the token query printed ${text}`), {
648
+ code: "token output"
649
+ });
430
650
  return n;
431
651
  }
432
652
  async function readKernelTokenCount(opts = {}) {
433
- if ((opts.platform ?? process.platform) !== "win32") return { kind: "unsupported", reason: TOKEN_COUNT_UNSUPPORTED };
653
+ if ((opts.platform ?? process.platform) !== "win32")
654
+ return { kind: "unsupported", reason: TOKEN_COUNT_UNSUPPORTED };
434
655
  const run = opts.run ?? runCommand;
435
- const exe = await ensureTokenProbeExe({ dir: opts.dir ?? join5(machineHome(), ".danxbot"), run, files: opts.files, windir: opts.windir ?? process.env.WINDIR, signal: opts.signal });
436
- return { kind: "read", count: parseTokenCount(await run(exe, [], TOKEN_QUERY_TIMEOUT_MS, opts.signal)) };
656
+ const exe = await ensureTokenProbeExe({
657
+ dir: opts.dir ?? join5(machineHome(), ".danxbot"),
658
+ run,
659
+ files: opts.files,
660
+ windir: opts.windir ?? process.env.WINDIR,
661
+ signal: opts.signal
662
+ });
663
+ return {
664
+ kind: "read",
665
+ count: parseTokenCount(
666
+ await run(exe, [], TOKEN_QUERY_TIMEOUT_MS, opts.signal)
667
+ )
668
+ };
437
669
  }
438
670
 
439
671
  // src/machine-toolkit/toolkit.ts
@@ -442,10 +674,20 @@ var PROFILE = "windows-wsl-docker";
442
674
  function resolveToolkitVersion(stamped, readManifest) {
443
675
  return stamped ?? readManifest();
444
676
  }
445
- var readOwnManifest = () => JSON.parse(readFileSync2(new URL("../../package.json", import.meta.url), "utf8")).version;
446
- var TOOLKIT_VERSION = resolveToolkitVersion(false ? void 0 : "0.1.464", readOwnManifest);
677
+ var readOwnManifest = () => JSON.parse(
678
+ readFileSync2(new URL("../../package.json", import.meta.url), "utf8")
679
+ ).version;
680
+ var TOOLKIT_VERSION = resolveToolkitVersion(
681
+ false ? void 0 : "0.1.465",
682
+ readOwnManifest
683
+ );
447
684
  function envelope(now) {
448
- return { contract_version: CONTRACT_VERSION, toolkit_version: TOOLKIT_VERSION, profile: PROFILE, measured_at: now.toISOString() };
685
+ return {
686
+ contract_version: CONTRACT_VERSION,
687
+ toolkit_version: TOOLKIT_VERSION,
688
+ profile: PROFILE,
689
+ measured_at: now.toISOString()
690
+ };
449
691
  }
450
692
 
451
693
  // src/machine-toolkit/health.ts
@@ -453,14 +695,22 @@ var HEALTH_BUDGET_MS = 1e4;
453
695
  var HEALTH_MARGIN_MS = 1500;
454
696
  var MIN_ORPHAN_DEADLINE_MS = 500;
455
697
  function orphanDeadlineMs(uptimeSeconds) {
456
- return Math.max(MIN_ORPHAN_DEADLINE_MS, Math.floor(HEALTH_BUDGET_MS - uptimeSeconds * 1e3 - HEALTH_MARGIN_MS));
698
+ return Math.max(
699
+ MIN_ORPHAN_DEADLINE_MS,
700
+ Math.floor(HEALTH_BUDGET_MS - uptimeSeconds * 1e3 - HEALTH_MARGIN_MS)
701
+ );
457
702
  }
458
- var unread = (reason) => ({ metric: metricUnread(reason), items: [] });
703
+ var unread = (reason) => ({
704
+ metric: metricUnread(reason),
705
+ items: []
706
+ });
459
707
  async function read(reader, what) {
460
708
  try {
461
709
  return await reader();
462
710
  } catch (err) {
463
- return unread(err instanceof DeadlineExceeded ? err.message : `${what} failed (${errorCode(err)})`);
711
+ return unread(
712
+ err instanceof DeadlineExceeded ? err.message : `${what} failed (${errorCode(err)})`
713
+ );
464
714
  }
465
715
  }
466
716
  async function probe(work, ms, schedule, what) {
@@ -476,7 +726,20 @@ async function collectHealth(src, opts = {}) {
476
726
  const now = src.now();
477
727
  const deadlineMs = opts.deadlineMs ?? orphanDeadlineMs(process.uptime());
478
728
  const schedule = opts.schedule ?? realScheduler;
479
- const processStart = await read(async () => ({ metric: metricRead(await probe(src.processStartMs, PROBE_START_TIMEOUT_MS, schedule, "the process-start probe")), items: [] }), "timing a process start");
729
+ const processStart = await read(
730
+ async () => ({
731
+ metric: metricRead(
732
+ await probe(
733
+ src.processStartMs,
734
+ PROBE_START_TIMEOUT_MS,
735
+ schedule,
736
+ "the process-start probe"
737
+ )
738
+ ),
739
+ items: []
740
+ }),
741
+ "timing a process start"
742
+ );
480
743
  const [dataDisk, unowned, orphans, tokens] = await Promise.all([
481
744
  read(() => {
482
745
  const disk = src.dataDisk();
@@ -484,22 +747,50 @@ async function collectHealth(src, opts = {}) {
484
747
  }, "reading docker_data.vhdx"),
485
748
  read(() => {
486
749
  const flags = src.flags();
487
- if (flags === null) return unread("no real Docker sweep has written docker-flags.json on this machine yet");
750
+ if (flags === null)
751
+ return unread(
752
+ "no real Docker sweep has written docker-flags.json on this machine yet"
753
+ );
488
754
  const ageMs = Math.max(0, now.getTime() - new Date(flags.at).getTime());
489
- if (ageMs > FLAGS_STALE_MS) return unread(`the last Docker sweep result is ${(ageMs / 36e5).toFixed(1)} h old (older than ${FLAGS_STALE_MS / 36e5} h): the hourly sweep has stopped, so its count is stale`);
755
+ if (ageMs > FLAGS_STALE_MS)
756
+ return unread(
757
+ `the last Docker sweep result is ${(ageMs / 36e5).toFixed(1)} h old (older than ${FLAGS_STALE_MS / 36e5} h): the hourly sweep has stopped, so its count is stale`
758
+ );
490
759
  const ageSeconds = Math.round(ageMs / 1e3);
491
- const items = flags.flagged.filter((f) => f.reason.startsWith(UNOWNED_REASON_PREFIX)).map((f) => ({ id: f.id, detail: f.reason.slice(UNOWNED_REASON_PREFIX.length) }));
760
+ const items = flags.flagged.filter((f) => f.reason.startsWith(UNOWNED_REASON_PREFIX)).map((f) => ({
761
+ id: f.id,
762
+ detail: f.reason.slice(UNOWNED_REASON_PREFIX.length)
763
+ }));
492
764
  return { metric: metricRead(flags.unowned, "cached", ageSeconds), items };
493
765
  }, "reading the Docker flags file"),
494
766
  read(async () => {
495
- if (src.compactionWindowOpen()) return unread("a compaction window is open, so processes are not listed until it closes");
496
- const report2 = await probe((signal) => src.orphans(now, signal), deadlineMs, schedule, "the process listing");
497
- if (report2.unavailable.length > 0) return unread(report2.unavailable.map((u) => `${u.source} processes not listed (${u.code})`).join("; "));
498
- const items = report2.findings.map((f) => ({ id: `${f.source}:${f.pid}`, detail: `${f.kind} started ${f.startedAt.toISOString()}: ${f.commandLine}` }));
767
+ if (src.compactionWindowOpen())
768
+ return unread(
769
+ "a compaction window is open, so processes are not listed until it closes"
770
+ );
771
+ const report2 = await probe(
772
+ (signal) => src.orphans(now, signal),
773
+ deadlineMs,
774
+ schedule,
775
+ "the process listing"
776
+ );
777
+ if (report2.unavailable.length > 0)
778
+ return unread(
779
+ report2.unavailable.map((u) => `${u.source} processes not listed (${u.code})`).join("; ")
780
+ );
781
+ const items = report2.findings.map((f) => ({
782
+ id: `${f.source}:${f.pid}`,
783
+ detail: `${f.kind} started ${f.startedAt.toISOString()}: ${f.commandLine}`
784
+ }));
499
785
  return { metric: metricRead(items.length), items };
500
786
  }, "listing processes"),
501
787
  read(async () => {
502
- const reading = await probe(src.kernelTokenCount, TOKEN_QUERY_TIMEOUT_MS, schedule, "the kernel token query");
788
+ const reading = await probe(
789
+ src.kernelTokenCount,
790
+ TOKEN_QUERY_TIMEOUT_MS,
791
+ schedule,
792
+ "the kernel token query"
793
+ );
503
794
  return reading.kind === "read" ? { metric: metricRead(reading.count), items: [] } : unread(reading.reason);
504
795
  }, "reading the kernel token count")
505
796
  ]);
@@ -512,7 +803,10 @@ async function collectHealth(src, opts = {}) {
512
803
  [PROCESS_START_METRIC]: processStart.metric,
513
804
  [KERNEL_TOKEN_METRIC]: tokens.metric
514
805
  },
515
- items: { unowned_docker_resources: unowned.items, orphan_processes: orphans.items }
806
+ items: {
807
+ unowned_docker_resources: unowned.items,
808
+ orphan_processes: orphans.items
809
+ }
516
810
  };
517
811
  assertContract("health", report);
518
812
  return report;
@@ -523,7 +817,9 @@ async function runToolkitCli(args, io) {
523
817
  const [command, ...rest] = args;
524
818
  const extra = rest.filter((a) => a !== "--json");
525
819
  if (command !== "health" || extra.length > 0) {
526
- io.err(`machine-toolkit takes only: health --json (got '${args.join(" ")}')`);
820
+ io.err(
821
+ `machine-toolkit takes only: health --json (got '${args.join(" ")}')`
822
+ );
527
823
  return EXIT.failed;
528
824
  }
529
825
  try {