@50arms/platform-mcp 0.1.467 → 0.1.469

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.
@@ -24,8 +24,12 @@
24
24
  import { homedir } from "node:os";
25
25
  import { prefixedLine } from "./one-line.js";
26
26
  import { sessionControlDir, sessionControlFilePath, sessionControlFilesIn, } from "./session-control-file.js";
27
- /** The longest request line relayed whole (the pacing line's bound): the dashboard's request is a few hundred characters. */
28
- export const COMPACTION_ASK_MAX_CODE_POINTS = 1000;
27
+ /**
28
+ * The longest request line relayed whole. DX-6605: a compaction recommendation states what compacting would save (the context after it, its cost,
29
+ * the break-even calls, whose figures they are) and each handover proposal states the same for its sub-agent, so the longest request, the session's own recommendation
30
+ * with three proposals and default figures, is about 1,700 characters; a longer line would cut the ready call off its tail.
31
+ */
32
+ export const COMPACTION_ASK_MAX_CODE_POINTS = 2000;
29
33
  const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
30
34
  const isCount = (v) => typeof v === "number" && Number.isInteger(v) && v >= 0;
31
35
  const isTime = (v) => typeof v === "number" && Number.isFinite(v);
package/dist/index.js CHANGED
@@ -89,7 +89,7 @@ import { SessionKeyUnusableError, deleteSessionKey } from "./session-key.js";
89
89
  import { SessionAccess } from "./session-access.js";
90
90
  import { PermissionRequests } from "./permission-request.js";
91
91
  import { makeGuardedCalls } from "./guarded-calls.js";
92
- import { JobKeyHolder } from "./job-key.js";
92
+ import { JobKeyHolder, sendWithJobKey } from "./job-key.js";
93
93
  import { readOwnVersion } from "./version-floor.js";
94
94
  import { createCheckoutDocsRootReporter, readCheckoutRepo, } from "./checkout-docs-root.js";
95
95
  import { isPickupConnect, projectKeyOf, recordSessionConnectionAfterConnect, removeSessionConnectionAfterLeave, } from "./session-connection.js";
@@ -671,14 +671,15 @@ renamedTool("50arms_api",
671
671
  if (refused)
672
672
  return haltResult(refused);
673
673
  // DX-7098: while a system job's key is held the model's calls go out on it (never the take, never a hook's background call).
674
- const bearer = jobKey.bearerFor(args);
675
- const guarded = await guardedCall(() => danxbotApi(client, args, {}, bearer ?? undefined), {
674
+ const guarded = await sendWithJobKey(jobKey, {
675
+ method: args.method,
676
+ path: args.path,
677
+ background: args.background,
676
678
  gateOpen: isAgentGateOpenCall(args.method, args.path),
677
- foreignKey: bearer !== null,
678
- });
679
+ }, (bearer) => danxbotApi(client, args, {}, bearer), guardedCall);
679
680
  if ("halt" in guarded)
680
681
  return haltResult(guarded.halt);
681
- const result = jobKey.afterCall(args, guarded.result, bearer !== null);
682
+ const result = guarded.result;
682
683
  const halt = termsHaltFor(result);
683
684
  if (halt)
684
685
  return haltResult(halt);
package/dist/job-key.js CHANGED
@@ -43,5 +43,20 @@ export class JobKeyHolder {
43
43
  return { ...result, body: { ...body, job_key: JOB_KEY_HELD_NOTE } };
44
44
  }
45
45
  }
46
+ /**
47
+ * One `50arms_api` call through the job-key holder (DX-7098): the bearer it goes out with (the job key while one is held), guarded like every
48
+ * tool's call, and the holder's answer rule applied to the result. `send` receives the bearer (`undefined` = the session's own key). The one
49
+ * wiring `index.ts` calls, so the tests drive the same code the tool does.
50
+ */
51
+ export async function sendWithJobKey(holder, call, send, guard) {
52
+ const bearer = holder.bearerFor(call);
53
+ const guarded = await guard(() => send(bearer ?? undefined), {
54
+ gateOpen: call.gateOpen === true,
55
+ foreignKey: bearer !== null,
56
+ });
57
+ if ("halt" in guarded)
58
+ return guarded;
59
+ return { result: holder.afterCall(call, guarded.result, bearer !== null) };
60
+ }
46
61
  const pathOf = (call) => call.path.split("?", 1)[0];
47
62
  const isTake = (call) => call.method === "POST" && TAKE_PATH.test(call.path);
package/dist/listen.js CHANGED
@@ -474,6 +474,14 @@ function isReviewableNudgeCardRefArray(value) {
474
474
  return (Array.isArray(value) &&
475
475
  value.every((c) => isNudgeCardRef(c) && typeof c.gate === "string"));
476
476
  }
477
+ function isBackgroundCommandArray(value) {
478
+ return (Array.isArray(value) &&
479
+ value.every((c) => isRecord(c) &&
480
+ typeof c.id === "string" &&
481
+ (typeof c.description === "string" || c.description === null) &&
482
+ typeof c.runningMinutes === "number" &&
483
+ Number.isFinite(c.runningMinutes)));
484
+ }
477
485
  function isNudgeCardRefArray(value) {
478
486
  return Array.isArray(value) && value.every(isNudgeCardRef);
479
487
  }
@@ -498,6 +506,8 @@ export function invalidNudgeReason(value) {
498
506
  return "unreadied is not a {id,title}[] array";
499
507
  if (!isReviewableNudgeCardRefArray(value.reviewable))
500
508
  return "reviewable is not a {id,title,gate}[] array";
509
+ if (!isBackgroundCommandArray(value.commands))
510
+ return "commands is not a {id,description,runningMinutes}[] array";
501
511
  if (value.freeSlots !== null &&
502
512
  !(typeof value.freeSlots === "number" &&
503
513
  Number.isInteger(value.freeSlots) &&
@@ -519,6 +529,14 @@ function freeSlotsSentence(freeSlots) {
519
529
  return "No agent slot is free now: start each review as a slot frees.";
520
530
  return `${freeSlots} agent slot${freeSlots === 1 ? " is" : "s are"} free now: start up to that many at once.`;
521
531
  }
532
+ /** DX-6707 (DEC-818) - the label the overdue background commands sit under, and what to do about them. */
533
+ const BACKGROUND_COMMAND_LABEL = "Background command past its 30-minute hold";
534
+ const BACKGROUND_COMMAND_INSTRUCTION = "check each is doing the right thing and not waiting in vain";
535
+ function backgroundCommandList(cmds) {
536
+ return cmds
537
+ .map((c) => `${c.id} "${c.description ?? "no description"}" (running ${c.runningMinutes}m)`)
538
+ .join(", ");
539
+ }
522
540
  function queuedCardList(cards) {
523
541
  return cards.map((c) => `${c.id} "${c.title}" [${c.queueState}]`).join(", ");
524
542
  }
@@ -562,6 +580,9 @@ export function formatNudgeLine(event) {
562
580
  // DX-7127 - the label and instruction come before the ids, like the filed part, so a cut never takes the instruction.
563
581
  if (event.reviewable.length > 0)
564
582
  parts.push(`${REVIEWABLE_LABEL} (${REVIEWABLE_INSTRUCTION}; ${freeSlotsSentence(event.freeSlots)}): ${reviewableCardList(event.reviewable)}`);
583
+ // DX-6707 (DEC-818) - named apart from the cards: the check is the session's own command, not a card it must work.
584
+ if (event.commands.length > 0)
585
+ parts.push(`${BACKGROUND_COMMAND_LABEL} (${BACKGROUND_COMMAND_INSTRUCTION}): ${backgroundCommandList(event.commands)}`);
565
586
  if (event.startable.length > 0)
566
587
  parts.push(`startable: ${queuedCardList(event.startable)}`);
567
588
  if (event.held.length > 0)
@@ -841,17 +841,13 @@ function createSystemLeftoverTracker(log, run = runCommand, platform = process.p
841
841
  }
842
842
 
843
843
  // src/machine-toolkit/contract.ts
844
- var CONTRACT_VERSION = 2;
844
+ var CONTRACT_VERSION = 3;
845
845
  var REQUIRED_METRICS = [
846
846
  "docker_data_disk_bytes",
847
- "unowned_docker_resource_count",
848
847
  "orphan_process_count"
849
848
  ];
850
849
  var KERNEL_TOKEN_METRIC = "kernel_token_count";
851
- var HEALTH_ITEM_LISTS = [
852
- "unowned_docker_resources",
853
- "orphan_processes"
854
- ];
850
+ var HEALTH_ITEM_LISTS = ["orphan_processes"];
855
851
  var ContractViolation = class extends Error {
856
852
  constructor(command, path, what) {
857
853
  super(
@@ -981,9 +977,8 @@ var VALIDATORS = {
981
977
  });
982
978
  },
983
979
  "label-check"(o, fail) {
984
- exactKeys(o, "", [...ENVELOPE_KEYS, "unowned", "malformed"], fail);
980
+ exactKeys(o, "", [...ENVELOPE_KEYS, "malformed"], fail);
985
981
  checkEnvelope(o, fail);
986
- checkItems(o.unowned, "unowned", ["reason"], fail);
987
982
  checkItems(o.malformed, "malformed", ["reason"], fail);
988
983
  }
989
984
  };
@@ -4,7 +4,7 @@ import { realpathSync } from "node:fs";
4
4
  import { pathToFileURL } from "node:url";
5
5
 
6
6
  // src/machine-toolkit/contract.ts
7
- var CONTRACT_VERSION = 2;
7
+ var CONTRACT_VERSION = 3;
8
8
  var EXIT = {
9
9
  /** The command ran and everything it reports was read or done. */
10
10
  ok: 0,
@@ -17,15 +17,11 @@ var EXIT = {
17
17
  };
18
18
  var REQUIRED_METRICS = [
19
19
  "docker_data_disk_bytes",
20
- "unowned_docker_resource_count",
21
20
  "orphan_process_count"
22
21
  ];
23
22
  var PROCESS_START_METRIC = "process_start_ms";
24
23
  var KERNEL_TOKEN_METRIC = "kernel_token_count";
25
- var HEALTH_ITEM_LISTS = [
26
- "unowned_docker_resources",
27
- "orphan_processes"
28
- ];
24
+ var HEALTH_ITEM_LISTS = ["orphan_processes"];
29
25
  var ContractViolation = class extends Error {
30
26
  constructor(command, path, what) {
31
27
  super(
@@ -36,65 +32,65 @@ var ContractViolation = class extends Error {
36
32
  };
37
33
  var isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
38
34
  var join = (path, key) => path === "" ? key : `${path}.${key}`;
39
- function objectAt(v, path, fail2) {
40
- if (!isObject(v)) return fail2(path, "must be an object");
35
+ function objectAt(v, path, fail) {
36
+ if (!isObject(v)) return fail(path, "must be an object");
41
37
  return v;
42
38
  }
43
- function exactKeys(o, path, keys, fail2) {
44
- for (const k of keys) if (!(k in o)) fail2(join(path, k), "is required");
39
+ function exactKeys(o, path, keys, fail) {
40
+ for (const k of keys) if (!(k in o)) fail(join(path, k), "is required");
45
41
  for (const k of Object.keys(o))
46
- if (!keys.includes(k)) fail2(join(path, k), "is not part of the contract");
42
+ if (!keys.includes(k)) fail(join(path, k), "is not part of the contract");
47
43
  }
48
- function stringAt(o, key, path, fail2) {
44
+ function stringAt(o, key, path, fail) {
49
45
  const v = o[key];
50
46
  if (typeof v !== "string" || v === "")
51
- return fail2(join(path, key), "must be a non-empty string");
47
+ return fail(join(path, key), "must be a non-empty string");
52
48
  return v;
53
49
  }
54
- function listAt(v, path, fail2) {
55
- if (!Array.isArray(v)) return fail2(path, "must be a list");
50
+ function listAt(v, path, fail) {
51
+ if (!Array.isArray(v)) return fail(path, "must be a list");
56
52
  return v;
57
53
  }
58
- function checkItem(v, path, extra, fail2) {
59
- const o = objectAt(v, path, fail2);
60
- exactKeys(o, path, ["id", "detail", ...extra], fail2);
61
- stringAt(o, "id", path, fail2);
54
+ function checkItem(v, path, extra, fail) {
55
+ const o = objectAt(v, path, fail);
56
+ exactKeys(o, path, ["id", "detail", ...extra], fail);
57
+ stringAt(o, "id", path, fail);
62
58
  if (typeof o.detail !== "string")
63
- fail2(join(path, "detail"), "must be a string");
64
- for (const k of extra) stringAt(o, k, path, fail2);
59
+ fail(join(path, "detail"), "must be a string");
60
+ for (const k of extra) stringAt(o, k, path, fail);
65
61
  }
66
- function checkItems(v, path, extra, fail2) {
67
- listAt(v, path, fail2).forEach(
68
- (item, i) => checkItem(item, `${path}[${i}]`, extra, fail2)
62
+ function checkItems(v, path, extra, fail) {
63
+ listAt(v, path, fail).forEach(
64
+ (item, i) => checkItem(item, `${path}[${i}]`, extra, fail)
69
65
  );
70
66
  }
71
- function checkMetric(v, path, fail2) {
72
- const o = objectAt(v, path, fail2);
73
- exactKeys(o, path, ["value", "reason", "source", "age_seconds"], fail2);
67
+ function checkMetric(v, path, fail) {
68
+ const o = objectAt(v, path, fail);
69
+ exactKeys(o, path, ["value", "reason", "source", "age_seconds"], fail);
74
70
  if (o.value === null) {
75
71
  if (typeof o.reason !== "string" || o.reason === "")
76
- fail2(`${path}.reason`, "must say why the value is null");
72
+ fail(`${path}.reason`, "must say why the value is null");
77
73
  } else {
78
74
  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");
75
+ fail(`${path}.value`, "must be null or a finite number of at least 0");
80
76
  if (o.reason !== null)
81
- fail2(`${path}.reason`, "must be null when the value was read");
77
+ fail(`${path}.reason`, "must be null when the value was read");
82
78
  }
83
79
  if (o.source !== "fresh" && o.source !== "cached")
84
- fail2(`${path}.source`, "must be 'fresh' or 'cached'");
80
+ fail(`${path}.source`, "must be 'fresh' or 'cached'");
85
81
  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");
82
+ fail(`${path}.age_seconds`, "must be a number of at least 0");
87
83
  if (o.source === "fresh" && o.age_seconds !== 0)
88
- fail2(`${path}.age_seconds`, "must be 0 for a fresh reading");
84
+ fail(`${path}.age_seconds`, "must be 0 for a fresh reading");
89
85
  }
90
- function checkEnvelope(o, fail2) {
86
+ function checkEnvelope(o, fail) {
91
87
  if (o.contract_version !== CONTRACT_VERSION)
92
- fail2("contract_version", `must be ${CONTRACT_VERSION}`);
93
- stringAt(o, "toolkit_version", "", fail2);
94
- stringAt(o, "profile", "", fail2);
95
- const at = stringAt(o, "measured_at", "", fail2);
88
+ fail("contract_version", `must be ${CONTRACT_VERSION}`);
89
+ stringAt(o, "toolkit_version", "", fail);
90
+ stringAt(o, "profile", "", fail);
91
+ const at = stringAt(o, "measured_at", "", fail);
96
92
  if (Number.isNaN(new Date(at).getTime()))
97
- fail2("measured_at", "must be an ISO time");
93
+ fail("measured_at", "must be an ISO time");
98
94
  }
99
95
  var ENVELOPE_KEYS = [
100
96
  "contract_version",
@@ -103,73 +99,72 @@ var ENVELOPE_KEYS = [
103
99
  "measured_at"
104
100
  ];
105
101
  var VALIDATORS = {
106
- health(o, fail2) {
107
- exactKeys(o, "", [...ENVELOPE_KEYS, "metrics", "items"], fail2);
108
- checkEnvelope(o, fail2);
109
- const metrics = objectAt(o.metrics, "metrics", fail2);
102
+ health(o, fail) {
103
+ exactKeys(o, "", [...ENVELOPE_KEYS, "metrics", "items"], fail);
104
+ checkEnvelope(o, fail);
105
+ const metrics = objectAt(o.metrics, "metrics", fail);
110
106
  for (const name of REQUIRED_METRICS)
111
- if (!(name in metrics)) fail2(`metrics.${name}`, "is required");
107
+ if (!(name in metrics)) fail(`metrics.${name}`, "is required");
112
108
  for (const [name, metric] of Object.entries(metrics))
113
- checkMetric(metric, `metrics.${name}`, fail2);
109
+ checkMetric(metric, `metrics.${name}`, fail);
114
110
  const tokens = metrics[KERNEL_TOKEN_METRIC]?.value;
115
111
  if (typeof tokens === "number" && !Number.isInteger(tokens))
116
- fail2(`metrics.${KERNEL_TOKEN_METRIC}.value`, "must be a whole number");
117
- const items = objectAt(o.items, "items", fail2);
118
- exactKeys(items, "items", HEALTH_ITEM_LISTS, fail2);
112
+ fail(`metrics.${KERNEL_TOKEN_METRIC}.value`, "must be a whole number");
113
+ const items = objectAt(o.items, "items", fail);
114
+ exactKeys(items, "items", HEALTH_ITEM_LISTS, fail);
119
115
  for (const list of HEALTH_ITEM_LISTS)
120
- checkItems(items[list], `items.${list}`, [], fail2);
116
+ checkItems(items[list], `items.${list}`, [], fail);
121
117
  },
122
- sweep(o, fail2) {
123
- exactKeys(o, "", [...ENVELOPE_KEYS, "dry_run", "kinds"], fail2);
124
- checkEnvelope(o, fail2);
118
+ sweep(o, fail) {
119
+ exactKeys(o, "", [...ENVELOPE_KEYS, "dry_run", "kinds"], fail);
120
+ checkEnvelope(o, fail);
125
121
  if (typeof o.dry_run !== "boolean")
126
- fail2("dry_run", "must be true or false");
127
- listAt(o.kinds, "kinds", fail2).forEach((k, i) => {
122
+ fail("dry_run", "must be true or false");
123
+ listAt(o.kinds, "kinds", fail).forEach((k, i) => {
128
124
  const path = `kinds[${i}]`;
129
- const kind = objectAt(k, path, fail2);
125
+ const kind = objectAt(k, path, fail);
130
126
  exactKeys(
131
127
  kind,
132
128
  path,
133
129
  ["kind", "removed", "kept", "failed", "flagged"],
134
- fail2
130
+ fail
135
131
  );
136
- stringAt(kind, "kind", path, fail2);
137
- checkItems(kind.removed, `${path}.removed`, [], fail2);
138
- checkItems(kind.kept, `${path}.kept`, ["reason"], fail2);
139
- checkItems(kind.failed, `${path}.failed`, ["error"], fail2);
140
- checkItems(kind.flagged, `${path}.flagged`, ["reason"], fail2);
132
+ stringAt(kind, "kind", path, fail);
133
+ checkItems(kind.removed, `${path}.removed`, [], fail);
134
+ checkItems(kind.kept, `${path}.kept`, ["reason"], fail);
135
+ checkItems(kind.failed, `${path}.failed`, ["error"], fail);
136
+ checkItems(kind.flagged, `${path}.flagged`, ["reason"], fail);
141
137
  });
142
138
  },
143
- maintain(o, fail2) {
144
- exactKeys(o, "", [...ENVELOPE_KEYS, "steps"], fail2);
145
- checkEnvelope(o, fail2);
146
- listAt(o.steps, "steps", fail2).forEach((s, i) => {
139
+ maintain(o, fail) {
140
+ exactKeys(o, "", [...ENVELOPE_KEYS, "steps"], fail);
141
+ checkEnvelope(o, fail);
142
+ listAt(o.steps, "steps", fail).forEach((s, i) => {
147
143
  const path = `steps[${i}]`;
148
- const step = objectAt(s, path, fail2);
149
- exactKeys(step, path, ["name", "status", "detail"], fail2);
150
- stringAt(step, "name", path, fail2);
144
+ const step = objectAt(s, path, fail);
145
+ exactKeys(step, path, ["name", "status", "detail"], fail);
146
+ stringAt(step, "name", path, fail);
151
147
  if (step.status !== "done" && step.status !== "skipped" && step.status !== "failed")
152
- fail2(`${path}.status`, "must be 'done', 'skipped' or 'failed'");
148
+ fail(`${path}.status`, "must be 'done', 'skipped' or 'failed'");
153
149
  if (typeof step.detail !== "string")
154
- fail2(join(path, "detail"), "must be a string");
150
+ fail(join(path, "detail"), "must be a string");
155
151
  });
156
152
  },
157
- "label-check"(o, fail2) {
158
- exactKeys(o, "", [...ENVELOPE_KEYS, "unowned", "malformed"], fail2);
159
- checkEnvelope(o, fail2);
160
- checkItems(o.unowned, "unowned", ["reason"], fail2);
161
- checkItems(o.malformed, "malformed", ["reason"], fail2);
153
+ "label-check"(o, fail) {
154
+ exactKeys(o, "", [...ENVELOPE_KEYS, "malformed"], fail);
155
+ checkEnvelope(o, fail);
156
+ checkItems(o.malformed, "malformed", ["reason"], fail);
162
157
  }
163
158
  };
164
159
  function assertContract(command, report) {
165
- const fail2 = (path, what) => {
160
+ const fail = (path, what) => {
166
161
  throw new ContractViolation(
167
162
  command,
168
163
  path === "" ? "(document)" : path,
169
164
  what
170
165
  );
171
166
  };
172
- VALIDATORS[command](objectAt(report, "", fail2), fail2);
167
+ VALIDATORS[command](objectAt(report, "", fail), fail);
173
168
  }
174
169
  var metricRead = (value, source = "fresh", ageSeconds = 0) => ({ value, reason: null, source, age_seconds: ageSeconds });
175
170
  var metricUnread = (reason) => ({
@@ -207,107 +202,6 @@ function readDockerDataDisk(localAppData = process.env.LOCALAPPDATA, stat = stat
207
202
  }
208
203
  }
209
204
 
210
- // src/machine-toolkit/docker-flags.mjs
211
- import { readFileSync } from "node:fs";
212
- import { join as join4 } from "node:path";
213
-
214
- // src/machine-toolkit/machine-home.mjs
215
- import { execFileSync } from "node:child_process";
216
- import { existsSync } from "node:fs";
217
- import { homedir, release } from "node:os";
218
- import { join as join3 } from "node:path";
219
- function isWsl(kernelRelease = release(), platform = process.platform, hasDrvFs = existsSync("/mnt/c/Users")) {
220
- return platform === "linux" && /microsoft/i.test(kernelRelease) && hasDrvFs;
221
- }
222
- var WSL_CALL_TIMEOUT_MS = 1e4;
223
- function windowsHomeFromWsl() {
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
- );
244
- return path;
245
- }
246
- var COMPACTION_WINDOW_FILE = "compaction-window";
247
- function compactionWindowOpen(home = machineHome()) {
248
- return existsSync(join3(home, ".danxbot", COMPACTION_WINDOW_FILE));
249
- }
250
- function machineHome() {
251
- return isWsl() ? windowsHomeFromWsl() : homedir();
252
- }
253
-
254
- // src/machine-toolkit/docker-flags.mjs
255
- var FLAGS_STALE_MS = 3 * 60 * 60 * 1e3;
256
- var UNOWNED_REASON_PREFIX = "UNOWNED: ";
257
- function flagsFile(home = machineHome()) {
258
- return join4(home, ".danxbot", "docker-flags.json");
259
- }
260
- function fail(path, what) {
261
- throw Object.assign(new Error(`${path} is malformed: ${what}`), {
262
- code: "EMALFORMED"
263
- });
264
- }
265
- function validateFlags(value, path) {
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
- );
275
- if (!Array.isArray(value.flagged)) fail(path, `"flagged" must be a list`);
276
- for (const f of value.flagged) {
277
- if (f === null || typeof f !== "object" || typeof f.id !== "string" || typeof f.reason !== "string" || !(f.card === null || typeof f.card === "string")) {
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
- );
282
- }
283
- }
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
- };
293
- }
294
- function readFlags(path = flagsFile()) {
295
- let text;
296
- try {
297
- text = readFileSync(path, "utf8");
298
- } catch (err) {
299
- if (err.code === "ENOENT") return null;
300
- throw err;
301
- }
302
- let value;
303
- try {
304
- value = JSON.parse(text);
305
- } catch (err) {
306
- fail(path, `not JSON (${err.message})`);
307
- }
308
- return validateFlags(value, path);
309
- }
310
-
311
205
  // src/machine-toolkit/deadline.ts
312
206
  var realScheduler = (fire, ms) => {
313
207
  const timer = setTimeout(fire, ms);
@@ -350,9 +244,49 @@ function errMessage(err) {
350
244
  // src/machine-toolkit/probe.ts
351
245
  import { createHash } from "node:crypto";
352
246
  import { existsSync as existsSync2, mkdirSync, renameSync, writeFileSync } from "node:fs";
353
- import { join as join5 } from "node:path";
247
+ import { join as join4 } from "node:path";
354
248
  import { performance } from "node:perf_hooks";
355
249
 
250
+ // src/machine-toolkit/machine-home.mjs
251
+ import { execFileSync } from "node:child_process";
252
+ import { existsSync } from "node:fs";
253
+ import { homedir, release } from "node:os";
254
+ import { join as join3 } from "node:path";
255
+ function isWsl(kernelRelease = release(), platform = process.platform, hasDrvFs = existsSync("/mnt/c/Users")) {
256
+ return platform === "linux" && /microsoft/i.test(kernelRelease) && hasDrvFs;
257
+ }
258
+ var WSL_CALL_TIMEOUT_MS = 1e4;
259
+ function windowsHomeFromWsl() {
260
+ const raw = execFileSync("cmd.exe", ["/c", "echo %USERPROFILE%"], {
261
+ windowsHide: true,
262
+ encoding: "utf8",
263
+ stdio: ["ignore", "pipe", "ignore"],
264
+ timeout: WSL_CALL_TIMEOUT_MS
265
+ }).replace(/\r/g, "").trim();
266
+ if (raw === "" || raw.includes("%"))
267
+ throw new Error(
268
+ `could not resolve the Windows home from cmd.exe (it said '${raw}')`
269
+ );
270
+ const path = execFileSync("wslpath", ["-u", raw], {
271
+ windowsHide: true,
272
+ encoding: "utf8",
273
+ stdio: ["ignore", "pipe", "ignore"],
274
+ timeout: WSL_CALL_TIMEOUT_MS
275
+ }).trim();
276
+ if (!existsSync(path))
277
+ throw new Error(
278
+ `the Windows home '${raw}' is not a directory under /mnt/c`
279
+ );
280
+ return path;
281
+ }
282
+ var COMPACTION_WINDOW_FILE = "compaction-window";
283
+ function compactionWindowOpen(home = machineHome()) {
284
+ return existsSync(join3(home, ".danxbot", COMPACTION_WINDOW_FILE));
285
+ }
286
+ function machineHome() {
287
+ return isWsl() ? windowsHomeFromWsl() : homedir();
288
+ }
289
+
356
290
  // src/machine-toolkit/processes.ts
357
291
  import { execFile } from "node:child_process";
358
292
  var ORPHAN_MIN_AGE_MS = 10 * 60 * 1e3;
@@ -600,7 +534,7 @@ public static class DxTokeProbe {
600
534
  `;
601
535
  var TOKEN_COMPILE_TIMEOUT_MS = 15e3;
602
536
  function cscPath(windir) {
603
- return join5(
537
+ return join4(
604
538
  windir ?? String.raw`C:\Windows`,
605
539
  "Microsoft.NET",
606
540
  "Framework64",
@@ -619,12 +553,12 @@ var realTokenProbeFiles = {
619
553
  };
620
554
  async function ensureTokenProbeExe(opts) {
621
555
  const files = opts.files ?? realTokenProbeFiles;
622
- const exe = join5(opts.dir, tokenProbeExeName());
556
+ const exe = join4(opts.dir, tokenProbeExeName());
623
557
  if (files.exists(exe)) return exe;
624
558
  files.mkdir(opts.dir);
625
559
  const tag = String(opts.pid ?? process.pid);
626
560
  const source = exe.replace(/\.exe$/, ".cs");
627
- const temp = join5(opts.dir, `token-probe-${tag}.tmp.exe`);
561
+ const temp = join4(opts.dir, `token-probe-${tag}.tmp.exe`);
628
562
  files.write(source, TOKEN_PROBE_SOURCE);
629
563
  await opts.run(
630
564
  cscPath(opts.windir),
@@ -654,7 +588,7 @@ async function readKernelTokenCount(opts = {}) {
654
588
  return { kind: "unsupported", reason: TOKEN_COUNT_UNSUPPORTED };
655
589
  const run = opts.run ?? runCommand;
656
590
  const exe = await ensureTokenProbeExe({
657
- dir: opts.dir ?? join5(machineHome(), ".danxbot"),
591
+ dir: opts.dir ?? join4(machineHome(), ".danxbot"),
658
592
  run,
659
593
  files: opts.files,
660
594
  windir: opts.windir ?? process.env.WINDIR,
@@ -669,16 +603,16 @@ async function readKernelTokenCount(opts = {}) {
669
603
  }
670
604
 
671
605
  // src/machine-toolkit/toolkit.ts
672
- import { readFileSync as readFileSync2 } from "node:fs";
606
+ import { readFileSync } from "node:fs";
673
607
  var PROFILE = "windows-wsl-docker";
674
608
  function resolveToolkitVersion(stamped, readManifest) {
675
609
  return stamped ?? readManifest();
676
610
  }
677
611
  var readOwnManifest = () => JSON.parse(
678
- readFileSync2(new URL("../../package.json", import.meta.url), "utf8")
612
+ readFileSync(new URL("../../package.json", import.meta.url), "utf8")
679
613
  ).version;
680
614
  var TOOLKIT_VERSION = resolveToolkitVersion(
681
- false ? void 0 : "0.1.467",
615
+ false ? void 0 : "0.1.469",
682
616
  readOwnManifest
683
617
  );
684
618
  function envelope(now) {
@@ -740,29 +674,11 @@ async function collectHealth(src, opts = {}) {
740
674
  }),
741
675
  "timing a process start"
742
676
  );
743
- const [dataDisk, unowned, orphans, tokens] = await Promise.all([
677
+ const [dataDisk, orphans, tokens] = await Promise.all([
744
678
  read(() => {
745
679
  const disk = src.dataDisk();
746
680
  return disk.bytes === null ? unread(disk.unavailableReason) : { metric: metricRead(disk.bytes), items: [] };
747
681
  }, "reading docker_data.vhdx"),
748
- read(() => {
749
- const flags = src.flags();
750
- if (flags === null)
751
- return unread(
752
- "no real Docker sweep has written docker-flags.json on this machine yet"
753
- );
754
- const ageMs = Math.max(0, now.getTime() - new Date(flags.at).getTime());
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
- );
759
- const ageSeconds = Math.round(ageMs / 1e3);
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
- }));
764
- return { metric: metricRead(flags.unowned, "cached", ageSeconds), items };
765
- }, "reading the Docker flags file"),
766
682
  read(async () => {
767
683
  if (src.compactionWindowOpen())
768
684
  return unread(
@@ -798,13 +714,11 @@ async function collectHealth(src, opts = {}) {
798
714
  ...envelope(now),
799
715
  metrics: {
800
716
  docker_data_disk_bytes: dataDisk.metric,
801
- unowned_docker_resource_count: unowned.metric,
802
717
  orphan_process_count: orphans.metric,
803
718
  [PROCESS_START_METRIC]: processStart.metric,
804
719
  [KERNEL_TOKEN_METRIC]: tokens.metric
805
720
  },
806
721
  items: {
807
- unowned_docker_resources: unowned.items,
808
722
  orphan_processes: orphans.items
809
723
  }
810
724
  };
@@ -835,7 +749,6 @@ function collectFromThisMachine() {
835
749
  return collectHealth({
836
750
  now: () => /* @__PURE__ */ new Date(),
837
751
  dataDisk: () => readDockerDataDisk(),
838
- flags: () => readFlags(),
839
752
  orphans: (now, signal) => reportOrphanProcesses(now, void 0, void 0, signal, "when-running"),
840
753
  compactionWindowOpen: () => compactionWindowOpen(),
841
754
  processStartMs: (signal) => probeProcessStart({ spawnFn: spawn, signal }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@50arms/platform-mcp",
3
- "version": "0.1.467",
3
+ "version": "0.1.469",
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",