@50arms/platform-mcp 0.1.456 → 0.1.457

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.
@@ -538,6 +538,7 @@ function createSystemLeftoverTracker(run = runCommand, platform = process.platfo
538
538
  // src/machine-toolkit/contract.ts
539
539
  var CONTRACT_VERSION = 2;
540
540
  var REQUIRED_METRICS = ["docker_data_disk_bytes", "unowned_docker_resource_count", "orphan_process_count"];
541
+ var KERNEL_TOKEN_METRIC = "kernel_token_count";
541
542
  var HEALTH_ITEM_LISTS = ["unowned_docker_resources", "orphan_processes"];
542
543
  var ContractViolation = class extends Error {
543
544
  constructor(command, path, what) {
@@ -602,6 +603,8 @@ var VALIDATORS = {
602
603
  const metrics = objectAt(o.metrics, "metrics", fail);
603
604
  for (const name of REQUIRED_METRICS) if (!(name in metrics)) fail(`metrics.${name}`, "is required");
604
605
  for (const [name, metric] of Object.entries(metrics)) checkMetric(metric, `metrics.${name}`, fail);
606
+ const tokens = metrics[KERNEL_TOKEN_METRIC]?.value;
607
+ if (typeof tokens === "number" && !Number.isInteger(tokens)) fail(`metrics.${KERNEL_TOKEN_METRIC}.value`, "must be a whole number");
605
608
  const items = objectAt(o.items, "items", fail);
606
609
  exactKeys(items, "items", HEALTH_ITEM_LISTS, fail);
607
610
  for (const list of HEALTH_ITEM_LISTS) checkItems(items[list], `items.${list}`, [], fail);
@@ -1,4 +1,5 @@
1
1
  // src/machine-toolkit/cli.ts
2
+ import { spawn } from "node:child_process";
2
3
  import { realpathSync } from "node:fs";
3
4
  import { pathToFileURL } from "node:url";
4
5
 
@@ -15,6 +16,8 @@ var EXIT = {
15
16
  refused: 3
16
17
  };
17
18
  var REQUIRED_METRICS = ["docker_data_disk_bytes", "unowned_docker_resource_count", "orphan_process_count"];
19
+ var PROCESS_START_METRIC = "process_start_ms";
20
+ var KERNEL_TOKEN_METRIC = "kernel_token_count";
18
21
  var HEALTH_ITEM_LISTS = ["unowned_docker_resources", "orphan_processes"];
19
22
  var ContractViolation = class extends Error {
20
23
  constructor(command, path, what) {
@@ -79,6 +82,8 @@ var VALIDATORS = {
79
82
  const metrics = objectAt(o.metrics, "metrics", fail2);
80
83
  for (const name of REQUIRED_METRICS) if (!(name in metrics)) fail2(`metrics.${name}`, "is required");
81
84
  for (const [name, metric] of Object.entries(metrics)) checkMetric(metric, `metrics.${name}`, fail2);
85
+ 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");
82
87
  const items = objectAt(o.items, "items", fail2);
83
88
  exactKeys(items, "items", HEALTH_ITEM_LISTS, fail2);
84
89
  for (const list of HEALTH_ITEM_LISTS) checkItems(items[list], `items.${list}`, [], fail2);
@@ -243,77 +248,11 @@ function errMessage(err) {
243
248
  return err instanceof Error ? err.message : String(err);
244
249
  }
245
250
 
246
- // src/machine-toolkit/toolkit.ts
247
- import { readFileSync as readFileSync2 } from "node:fs";
248
- var PROFILE = "windows-wsl-docker";
249
- function resolveToolkitVersion(stamped, readManifest) {
250
- return stamped ?? readManifest();
251
- }
252
- var readOwnManifest = () => JSON.parse(readFileSync2(new URL("../../package.json", import.meta.url), "utf8")).version;
253
- var TOOLKIT_VERSION = resolveToolkitVersion(false ? void 0 : "0.1.456", readOwnManifest);
254
- function envelope(now) {
255
- return { contract_version: CONTRACT_VERSION, toolkit_version: TOOLKIT_VERSION, profile: PROFILE, measured_at: now.toISOString() };
256
- }
257
-
258
- // src/machine-toolkit/health.ts
259
- var HEALTH_BUDGET_MS = 1e4;
260
- var HEALTH_MARGIN_MS = 1500;
261
- var MIN_ORPHAN_DEADLINE_MS = 500;
262
- function orphanDeadlineMs(uptimeSeconds) {
263
- return Math.max(MIN_ORPHAN_DEADLINE_MS, Math.floor(HEALTH_BUDGET_MS - uptimeSeconds * 1e3 - HEALTH_MARGIN_MS));
264
- }
265
- var unread = (reason) => ({ metric: metricUnread(reason), items: [] });
266
- async function read(reader, what) {
267
- try {
268
- return await reader();
269
- } catch (err) {
270
- return unread(err instanceof DeadlineExceeded ? err.message : `${what} failed (${errorCode(err)})`);
271
- }
272
- }
273
- async function collectHealth(src, opts = {}) {
274
- const now = src.now();
275
- const deadlineMs = opts.deadlineMs ?? orphanDeadlineMs(process.uptime());
276
- const [dataDisk, unowned, orphans] = await Promise.all([
277
- read(() => {
278
- const disk = src.dataDisk();
279
- return disk.bytes === null ? unread(disk.unavailableReason) : { metric: metricRead(disk.bytes), items: [] };
280
- }, "reading docker_data.vhdx"),
281
- read(() => {
282
- const flags = src.flags();
283
- if (flags === null) return unread("no real Docker sweep has written docker-flags.json on this machine yet");
284
- const ageMs = Math.max(0, now.getTime() - new Date(flags.at).getTime());
285
- 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`);
286
- const ageSeconds = Math.round(ageMs / 1e3);
287
- 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) }));
288
- return { metric: metricRead(flags.unowned, "cached", ageSeconds), items };
289
- }, "reading the Docker flags file"),
290
- read(async () => {
291
- if (src.compactionWindowOpen()) return unread("a compaction window is open, so processes are not listed until it closes");
292
- const abort = new AbortController();
293
- let report2;
294
- try {
295
- report2 = await withDeadline(src.orphans(now, abort.signal), deadlineMs, opts.schedule ?? realScheduler, "the process listing");
296
- } catch (err) {
297
- abort.abort();
298
- throw err;
299
- }
300
- if (report2.unavailable.length > 0) return unread(report2.unavailable.map((u) => `${u.source} processes not listed (${u.code})`).join("; "));
301
- const items = report2.findings.map((f) => ({ id: `${f.source}:${f.pid}`, detail: `${f.kind} started ${f.startedAt.toISOString()}: ${f.commandLine}` }));
302
- return { metric: metricRead(items.length), items };
303
- }, "listing processes")
304
- ]);
305
- const report = {
306
- ...envelope(now),
307
- metrics: {
308
- docker_data_disk_bytes: dataDisk.metric,
309
- unowned_docker_resource_count: unowned.metric,
310
- orphan_process_count: orphans.metric
311
- },
312
- items: { unowned_docker_resources: unowned.items, orphan_processes: orphans.items }
313
- };
314
- assertContract("health", report);
315
- return report;
316
- }
251
+ // src/machine-toolkit/probe.ts
252
+ import { createHash } from "node:crypto";
253
+ import { existsSync as existsSync2, mkdirSync, renameSync, writeFileSync } from "node:fs";
254
+ import { join as join5 } from "node:path";
255
+ import { performance } from "node:perf_hooks";
317
256
 
318
257
  // src/machine-toolkit/processes.ts
319
258
  import { execFile } from "node:child_process";
@@ -412,6 +351,173 @@ async function reportOrphanProcesses(now = /* @__PURE__ */ new Date(), run = run
412
351
  return { findings: findOrphans(rows, now), unavailable };
413
352
  }
414
353
 
354
+ // src/machine-toolkit/probe.ts
355
+ var PROBE_START_TIMEOUT_MS = 15e3;
356
+ var TOKEN_QUERY_TIMEOUT_MS = 2e4;
357
+ var TOKEN_COUNT_UNSUPPORTED = "the kernel token count exists on Windows only";
358
+ function probeCommand(platform) {
359
+ return platform === "win32" ? { file: "cmd.exe", args: ["/c", "exit"] } : { file: "true", args: [] };
360
+ }
361
+ function probeProcessStart(opts) {
362
+ const { file, args } = probeCommand(opts.platform ?? process.platform);
363
+ const nowMs = opts.nowMs ?? (() => performance.now());
364
+ return new Promise((resolve, reject) => {
365
+ const startedAt = nowMs();
366
+ const child = opts.spawnFn(file, args, { windowsHide: true, stdio: "ignore", signal: opts.signal });
367
+ child.on("error", reject);
368
+ child.on("close", (code) => {
369
+ if (code !== 0) reject(Object.assign(new Error(`${file} exited ${code ?? "on a signal"}`), { code: "probe exit" }));
370
+ else resolve(Math.round(nowMs() - startedAt));
371
+ });
372
+ });
373
+ }
374
+ var TOKEN_PROBE_SOURCE = `using System;
375
+ using System.Runtime.InteropServices;
376
+ public static class DxTokeProbe {
377
+ [DllImport("ntdll.dll")] static extern int NtQuerySystemInformation(int cls, IntPtr buf, int len, out int ret);
378
+ public static int Main() {
379
+ int ret = 0; int size = 1 << 20; IntPtr buf; int st;
380
+ while (true) {
381
+ buf = Marshal.AllocHGlobal(size);
382
+ st = NtQuerySystemInformation(22, buf, size, out ret);
383
+ if (st == unchecked((int)0xC0000004)) { Marshal.FreeHGlobal(buf); size = ret + (1 << 16); continue; }
384
+ break;
385
+ }
386
+ try {
387
+ if (st != 0) { Console.Error.Write("NtQuerySystemInformation status " + st); return 2; }
388
+ int count = Marshal.ReadInt32(buf); long off = 8;
389
+ for (int i = 0; i < count; i++) {
390
+ IntPtr p = new IntPtr(buf.ToInt64() + off);
391
+ if (Marshal.ReadInt32(p) == 0x656B6F54) { Console.Out.Write((long)(uint)Marshal.ReadInt32(p, 4) - (long)(uint)Marshal.ReadInt32(p, 8)); return 0; }
392
+ off += 40;
393
+ }
394
+ Console.Error.Write("no Toke pool tag"); return 3;
395
+ } finally { Marshal.FreeHGlobal(buf); }
396
+ }
397
+ }
398
+ `;
399
+ var TOKEN_COMPILE_TIMEOUT_MS = 15e3;
400
+ function cscPath(windir) {
401
+ return join5(windir ?? String.raw`C:\Windows`, "Microsoft.NET", "Framework64", "v4.0.30319", "csc.exe");
402
+ }
403
+ function tokenProbeExeName(source = TOKEN_PROBE_SOURCE) {
404
+ return `token-probe-${createHash("sha256").update(source).digest("hex").slice(0, 12)}.exe`;
405
+ }
406
+ var realTokenProbeFiles = {
407
+ exists: (path) => existsSync2(path),
408
+ mkdir: (dir) => void mkdirSync(dir, { recursive: true }),
409
+ write: (path, text) => writeFileSync(path, text, "utf-8"),
410
+ rename: (from, to) => renameSync(from, to)
411
+ };
412
+ async function ensureTokenProbeExe(opts) {
413
+ const files = opts.files ?? realTokenProbeFiles;
414
+ const exe = join5(opts.dir, tokenProbeExeName());
415
+ if (files.exists(exe)) return exe;
416
+ files.mkdir(opts.dir);
417
+ const tag = String(opts.pid ?? process.pid);
418
+ const source = exe.replace(/\.exe$/, ".cs");
419
+ const temp = join5(opts.dir, `token-probe-${tag}.tmp.exe`);
420
+ 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);
422
+ files.rename(temp, exe);
423
+ return exe;
424
+ }
425
+ function parseTokenCount(stdout) {
426
+ 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" });
428
+ const n = Number(text);
429
+ if (!Number.isSafeInteger(n) || n < 0) throw Object.assign(new Error(`the token query printed ${text}`), { code: "token output" });
430
+ return n;
431
+ }
432
+ async function readKernelTokenCount(opts = {}) {
433
+ if ((opts.platform ?? process.platform) !== "win32") return { kind: "unsupported", reason: TOKEN_COUNT_UNSUPPORTED };
434
+ 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)) };
437
+ }
438
+
439
+ // src/machine-toolkit/toolkit.ts
440
+ import { readFileSync as readFileSync2 } from "node:fs";
441
+ var PROFILE = "windows-wsl-docker";
442
+ function resolveToolkitVersion(stamped, readManifest) {
443
+ return stamped ?? readManifest();
444
+ }
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.457", readOwnManifest);
447
+ function envelope(now) {
448
+ return { contract_version: CONTRACT_VERSION, toolkit_version: TOOLKIT_VERSION, profile: PROFILE, measured_at: now.toISOString() };
449
+ }
450
+
451
+ // src/machine-toolkit/health.ts
452
+ var HEALTH_BUDGET_MS = 1e4;
453
+ var HEALTH_MARGIN_MS = 1500;
454
+ var MIN_ORPHAN_DEADLINE_MS = 500;
455
+ function orphanDeadlineMs(uptimeSeconds) {
456
+ return Math.max(MIN_ORPHAN_DEADLINE_MS, Math.floor(HEALTH_BUDGET_MS - uptimeSeconds * 1e3 - HEALTH_MARGIN_MS));
457
+ }
458
+ var unread = (reason) => ({ metric: metricUnread(reason), items: [] });
459
+ async function read(reader, what) {
460
+ try {
461
+ return await reader();
462
+ } catch (err) {
463
+ return unread(err instanceof DeadlineExceeded ? err.message : `${what} failed (${errorCode(err)})`);
464
+ }
465
+ }
466
+ async function probe(work, ms, schedule, what) {
467
+ const abort = new AbortController();
468
+ try {
469
+ return await withDeadline(work(abort.signal), ms, schedule, what);
470
+ } catch (err) {
471
+ abort.abort();
472
+ throw err;
473
+ }
474
+ }
475
+ async function collectHealth(src, opts = {}) {
476
+ const now = src.now();
477
+ const deadlineMs = opts.deadlineMs ?? orphanDeadlineMs(process.uptime());
478
+ 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");
480
+ const [dataDisk, unowned, orphans, tokens] = await Promise.all([
481
+ read(() => {
482
+ const disk = src.dataDisk();
483
+ return disk.bytes === null ? unread(disk.unavailableReason) : { metric: metricRead(disk.bytes), items: [] };
484
+ }, "reading docker_data.vhdx"),
485
+ read(() => {
486
+ const flags = src.flags();
487
+ if (flags === null) return unread("no real Docker sweep has written docker-flags.json on this machine yet");
488
+ 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`);
490
+ 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) }));
492
+ return { metric: metricRead(flags.unowned, "cached", ageSeconds), items };
493
+ }, "reading the Docker flags file"),
494
+ 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}` }));
499
+ return { metric: metricRead(items.length), items };
500
+ }, "listing processes"),
501
+ read(async () => {
502
+ const reading = await probe(src.kernelTokenCount, TOKEN_QUERY_TIMEOUT_MS, schedule, "the kernel token query");
503
+ return reading.kind === "read" ? { metric: metricRead(reading.count), items: [] } : unread(reading.reason);
504
+ }, "reading the kernel token count")
505
+ ]);
506
+ const report = {
507
+ ...envelope(now),
508
+ metrics: {
509
+ docker_data_disk_bytes: dataDisk.metric,
510
+ unowned_docker_resource_count: unowned.metric,
511
+ orphan_process_count: orphans.metric,
512
+ [PROCESS_START_METRIC]: processStart.metric,
513
+ [KERNEL_TOKEN_METRIC]: tokens.metric
514
+ },
515
+ items: { unowned_docker_resources: unowned.items, orphan_processes: orphans.items }
516
+ };
517
+ assertContract("health", report);
518
+ return report;
519
+ }
520
+
415
521
  // src/machine-toolkit/cli.ts
416
522
  async function runToolkitCli(args, io) {
417
523
  const [command, ...rest] = args;
@@ -435,7 +541,9 @@ function collectFromThisMachine() {
435
541
  dataDisk: () => readDockerDataDisk(),
436
542
  flags: () => readFlags(),
437
543
  orphans: (now, signal) => reportOrphanProcesses(now, void 0, void 0, signal, "when-running"),
438
- compactionWindowOpen: () => compactionWindowOpen()
544
+ compactionWindowOpen: () => compactionWindowOpen(),
545
+ processStartMs: (signal) => probeProcessStart({ spawnFn: spawn, signal }),
546
+ kernelTokenCount: (signal) => readKernelTokenCount({ signal })
439
547
  });
440
548
  }
441
549
  function isMainModule() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@50arms/platform-mcp",
3
- "version": "0.1.456",
3
+ "version": "0.1.457",
4
4
  "description": "Stdio MCP server fronting the 50 Arms dashboard API for agents (operator sessions and dispatched workers alike): the generic 50arms_api/50arms_api_list/50arms_api_spec tools reach any route the caller's credential may call, plus dedicated agent-specific tools (session_connect, request_permission, attach_file, and 50arms_slack_reply) (DX-3465, PLN-11 R-25).",
5
5
  "license": "MIT",
6
6
  "type": "module",