@mmerterden/multi-agent-pipeline 23.0.0 → 23.2.0

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 (26) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/docs/facts.json +1 -1
  3. package/manifest.json +29 -28
  4. package/package.json +1 -1
  5. package/pipeline/commands/multi-agent/clean-disk/SKILL.md +23 -6
  6. package/pipeline/commands/multi-agent/routines-import/SKILL.md +2 -0
  7. package/pipeline/commands/multi-agent/routines-share/SKILL.md +8 -4
  8. package/pipeline/commands/multi-agent/routines-update/SKILL.md +2 -0
  9. package/pipeline/contract/types/index.d.ts +2 -2
  10. package/pipeline/lib/routine-secret-scan.mjs +89 -4
  11. package/pipeline/multi-agent-refs/features/routine-sharing.md +84 -5
  12. package/pipeline/multi-agent-refs/features/usage-reporting.md +2 -0
  13. package/pipeline/schemas/disk-clean-request.schema.json +2 -0
  14. package/pipeline/schemas/disk-clean.schema.json +2 -0
  15. package/pipeline/scripts/disk-cleaner.mjs +417 -58
  16. package/pipeline/scripts/routine-registry.mjs +26 -1
  17. package/pipeline/scripts/routine-share.mjs +154 -12
  18. package/pipeline/scripts/usage-health.mjs +376 -0
  19. package/pipeline/scripts/usage-report.mjs +65 -3
  20. package/pipeline/skills/.skill-manifest.json +6 -6
  21. package/pipeline/skills/shared/core/multi-agent-clean-disk/SKILL.md +9 -4
  22. package/pipeline/skills/shared/core/multi-agent-routines-import/SKILL.md +2 -0
  23. package/pipeline/skills/shared/core/multi-agent-routines-share/SKILL.md +7 -3
  24. package/pipeline/skills/shared/core/multi-agent-routines-update/SKILL.md +2 -0
  25. package/pipeline/skills/shared/external/disk-cleaner/SKILL.md +21 -9
  26. package/pipeline/skills/shared/external/disk-cleaner/scripts/disk-cleaner.mjs +417 -58
@@ -74,7 +74,12 @@ import { prefsFileIn } from "../lib/prefs-value.mjs";
74
74
  import { parseArgs as parseArgv } from "../lib/args.mjs";
75
75
  import { exitOnHelp } from "../lib/cli-help.mjs";
76
76
  import { createHash } from "node:crypto";
77
- import { denyHostsFrom, scanSecrets } from "../lib/routine-secret-scan.mjs";
77
+ import {
78
+ SCANNED_FIELDS,
79
+ denyHostsFrom,
80
+ maskDeniedHosts,
81
+ scanSecrets,
82
+ } from "../lib/routine-secret-scan.mjs";
78
83
  import { isUnattended } from "../lib/unattended.mjs";
79
84
  import { lockTimeoutFrom, updateJsonFileSync } from "../lib/json-file-lock.mjs";
80
85
 
@@ -442,6 +447,26 @@ export function scanPayload(home, payload, env = process.env) {
442
447
  return scanSecrets(payload, { denyHosts: denyHostsFrom(readPrefs(home).global, env) });
443
448
  }
444
449
 
450
+ /**
451
+ * A copy of the payload with every hostname the internal-host rule would flag
452
+ * (with this machine's deny list) replaced by MASKED_HOST in each scanned
453
+ * field, and sha256 recomputed over the masked body. The saved routine is not
454
+ * touched. masked is the number of hostnames replaced.
455
+ */
456
+ export function maskPayloadHosts(home, payload, env = process.env) {
457
+ const denyHosts = denyHostsFrom(readPrefs(home).global, env);
458
+ const out = { ...payload };
459
+ let masked = 0;
460
+ for (const field of SCANNED_FIELDS) {
461
+ if (typeof out[field] !== "string") continue;
462
+ const { text, count } = maskDeniedHosts(out[field], denyHosts);
463
+ out[field] = text;
464
+ masked += count;
465
+ }
466
+ out.sha256 = bodySha256(out.body);
467
+ return { payload: out, masked };
468
+ }
469
+
445
470
  /**
446
471
  * Add a shared payload as a local routine. The sha256 is checked before
447
472
  * anything is written; the local name is `as` when given, else the payload's.
@@ -24,7 +24,8 @@
24
24
  // node routine-share.mjs browse [--q <text>]
25
25
  // node routine-share.mjs fetch --id <id>
26
26
  // node routine-share.mjs share --name <n> --visibility private|members|selected
27
- // [--logins a,b] [--base-version <n>] [--dry-run]
27
+ // [--logins a,b] [--base-version <n>] [--mask-hosts] [--dry-run]
28
+ // node routine-share.mjs share --all --visibility private [--mask-hosts] [--dry-run]
28
29
  // node routine-share.mjs import --id <id> --digest <digest> [--sha <sha256>] [--as <local name>]
29
30
  // node routine-share.mjs updates
30
31
  // node routine-share.mjs diff --name <local name>
@@ -37,6 +38,26 @@
37
38
  // must pass the host rule above; an override that does not is refused
38
39
  // (endpoint-not-allowed) before any request, never replaced by the default.
39
40
  //
41
+ // share --all publishes every saved routine this machine wrote, privately,
42
+ // in one run. It skips imported routines (source shared:...), every name this
43
+ // login already published (GET /api/routines, mine: true), so a bulk run never
44
+ // narrows a routine shared wider or bumps its version, and every routine whose
45
+ // payload or secret scan fails; the rest continue. It stops at the first 429
46
+ // (the server's hourly publish budget), leaving the remaining names
47
+ // not-attempted. results[] holds one row per saved routine: published,
48
+ // skipped (reason), failed (error), would-publish (dry run) or not-attempted.
49
+ // ok is false, error rate-limited or partial, when it stopped or a publish
50
+ // failed.
51
+ //
52
+ // --mask-hosts (share, one or --all) sends a copy in which every hostname the
53
+ // internal-host rule would flag is replaced by MASKED_HOST
54
+ // (internal-host.invalid), before the scan runs; sha256 is computed over the
55
+ // masked body, so the shared sha differs from the saved routine's, which is
56
+ // not touched. Each result carries masked: N (never the host text). Every
57
+ // other finding still refuses the routine. fetch, import, diff and update
58
+ // report placeholders: N and placeholderLines [{field, line, count}] for the
59
+ // importer to fill in with their own host; nothing fills them in.
60
+ //
40
61
  // Output: one JSON document on stdout. {ok:false, error, ...} on refusal.
41
62
  // share, import, update and delete refuse under MULTI_AGENT_UNATTENDED=1, and
42
63
  // the guard blocks the same subcommands by name (unattended-policy.json).
@@ -60,12 +81,14 @@ import {
60
81
  isValidLocalName,
61
82
  listRoutines,
62
83
  localNameTaken,
84
+ maskPayloadHosts,
63
85
  payloadDigest,
64
86
  payloadIssues,
65
87
  skillEdited,
66
88
  payloadProblems,
67
89
  scanPayload,
68
90
  } from "./routine-registry.mjs";
91
+ import { maskedHostsIn } from "../lib/routine-secret-scan.mjs";
69
92
 
70
93
  exitOnHelp(import.meta.url);
71
94
 
@@ -77,6 +100,7 @@ const SHA_RE = /^[0-9a-f]{64}$/;
77
100
  const MAX_LOGINS = 50;
78
101
  const UNATTENDED_REFUSED = new Set(["share", "import", "update", "delete"]);
79
102
  const DIFF_CELL_LIMIT = 4_000_000;
103
+ const SHARED_SOURCE = "shared:";
80
104
 
81
105
  class Refusal extends Error {
82
106
  constructor(error, extra = {}) {
@@ -199,6 +223,10 @@ function payloadOf(routine) {
199
223
  return p;
200
224
  }
201
225
 
226
+ function isImported(entry) {
227
+ return String(entry?.source || "").startsWith(SHARED_SOURCE);
228
+ }
229
+
202
230
  function localVersion(entry) {
203
231
  const m = /@(\d+)$/.exec(entry?.source || "");
204
232
  return m ? Number(m[1]) : null;
@@ -206,7 +234,7 @@ function localVersion(entry) {
206
234
 
207
235
  function importedEntry(home, name) {
208
236
  const entry = listRoutines(home).find((r) => r.name === name);
209
- if (!entry || !entry.sharedId || !String(entry.source || "").startsWith("shared:")) {
237
+ if (!entry || !entry.sharedId || !isImported(entry)) {
210
238
  throw new Refusal("not-imported", { name });
211
239
  }
212
240
  return entry;
@@ -261,6 +289,119 @@ function parseLogins(text) {
261
289
  return list;
262
290
  }
263
291
 
292
+ /**
293
+ * The payload share sends for one saved routine. With maskHosts, every
294
+ * hostname the internal-host rule would flag is replaced in the copy (the
295
+ * saved routine is untouched) and `masked` carries how many; the host text
296
+ * itself is never reported.
297
+ */
298
+ function sharePayload(home, name, env, maskHosts) {
299
+ const exported = exportRoutine(home, name);
300
+ if (!maskHosts) return { payload: exported, mask: {} };
301
+ const { payload, masked } = maskPayloadHosts(home, exported, env);
302
+ return { payload, mask: { masked } };
303
+ }
304
+
305
+ /** Where the masking placeholder sits in an incoming routine, for the importer to fill in. */
306
+ function placeholdersOf(routine) {
307
+ const { count, lines } = maskedHostsIn(routine);
308
+ return { placeholders: count, placeholderLines: lines };
309
+ }
310
+
311
+ /** The shareable payload of one routine, or the reason it may not be sent. */
312
+ function bulkCandidate(home, name, env, maskHosts) {
313
+ let payload;
314
+ let mask;
315
+ try {
316
+ ({ payload, mask } = sharePayload(home, name, env, maskHosts));
317
+ } catch (err) {
318
+ if (err instanceof RoutineError) return { skip: { reason: "invalid", detail: err.message } };
319
+ throw err;
320
+ }
321
+ const problems = payloadProblems(payload);
322
+ if (problems.length) return { skip: { reason: problems[0], problems, ...mask } };
323
+ const findings = scanPayload(home, payload, env);
324
+ if (findings.length) return { skip: { reason: "secret-detected", findings, ...mask } };
325
+ return { payload, mask };
326
+ }
327
+
328
+ async function shareAll(home, args, env) {
329
+ if (args.visibility !== "private")
330
+ throw new Refusal("invalid-visibility", { all: "private-only" });
331
+ for (const flag of ["name", "logins", "base-version"]) {
332
+ if (args[flag] !== undefined) throw new Refusal("invalid-flags", { flag });
333
+ }
334
+ const ctx = context(home, env);
335
+ const dryRun = Boolean(args["dry-run"]);
336
+ const maskHosts = args["mask-hosts"] === true;
337
+ // The skip list is what keeps a bulk run from narrowing a routine already
338
+ // shared wider, so a response that is not a list stops the run.
339
+ const listing = await call(ctx, "GET", "");
340
+ if (!Array.isArray(listing?.routines))
341
+ throw new Refusal("upstream-inconsistent", { reason: "routine list unreadable" });
342
+ const mine = new Set(listing.routines.filter((r) => r?.mine === true).map((r) => r.name));
343
+ const results = [];
344
+ let stopped = null;
345
+ for (const entry of listRoutines(home)) {
346
+ const name = entry.name;
347
+ if (stopped) {
348
+ results.push({ name, status: "not-attempted" });
349
+ continue;
350
+ }
351
+ if (isImported(entry)) {
352
+ results.push({ name, status: "skipped", reason: "imported" });
353
+ continue;
354
+ }
355
+ if (mine.has(name)) {
356
+ results.push({ name, status: "skipped", reason: "already-published" });
357
+ continue;
358
+ }
359
+ const { payload, mask, skip } = bulkCandidate(home, name, env, maskHosts);
360
+ if (skip) {
361
+ results.push({ name, status: "skipped", ...skip });
362
+ continue;
363
+ }
364
+ if (dryRun) {
365
+ results.push({
366
+ name,
367
+ status: "would-publish",
368
+ description: payload.description,
369
+ sha256: payload.sha256,
370
+ bytes: Buffer.byteLength(payload.body, "utf8"),
371
+ ...mask,
372
+ });
373
+ continue;
374
+ }
375
+ try {
376
+ const { routine } = await call(ctx, "POST", "", { ...payload, visibility: "private" });
377
+ results.push({
378
+ name,
379
+ status: "published",
380
+ id: routine?.id,
381
+ version: routine?.version,
382
+ ...mask,
383
+ });
384
+ } catch (err) {
385
+ if (!(err instanceof Refusal)) throw err;
386
+ if (err.extra.status === 429) {
387
+ stopped = { error: "rate-limited", ...err.extra };
388
+ results.push({ name, status: "not-attempted" });
389
+ } else {
390
+ const { status: httpStatus, ...detail } = err.extra;
391
+ results.push({ name, ...detail, status: "failed", error: err.message, httpStatus });
392
+ }
393
+ }
394
+ }
395
+ const counts = {};
396
+ for (const r of results) counts[r.status] = (counts[r.status] ?? 0) + 1;
397
+ const failed = counts.failed > 0;
398
+ const report = { all: true, visibility: "private", maskHosts, counts, results };
399
+ if (dryRun) return { ok: true, dryRun: true, url: ctx.base, ...report };
400
+ if (stopped) return { ok: false, error: "rate-limited", stopped, ...report };
401
+ if (failed) return { ok: false, error: "partial", ...report };
402
+ return { ok: true, ...report };
403
+ }
404
+
264
405
  const commands = {
265
406
  async browse(home, args, env) {
266
407
  const ctx = context(home, env);
@@ -281,19 +422,21 @@ const commands = {
281
422
  digest: payloadDigest(payload),
282
423
  localNameTaken: taken,
283
424
  issues,
425
+ ...placeholdersOf(routine),
284
426
  };
285
427
  },
286
428
 
287
429
  async share(home, args, env) {
430
+ if (args.all === true) return shareAll(home, args, env);
288
431
  const visibility = args.visibility;
289
432
  if (!VISIBILITIES.has(visibility)) throw new Refusal("invalid-visibility");
290
433
  const logins = parseLogins(args.logins);
291
434
  if (visibility === "selected" && logins.length === 0) throw new Refusal("invalid-logins");
292
- const payload = exportRoutine(home, args.name);
435
+ const { payload, mask } = sharePayload(home, args.name, env, args["mask-hosts"] === true);
293
436
  const problems = payloadProblems(payload);
294
- if (problems.length) throw new Refusal(problems[0], { problems });
437
+ if (problems.length) throw new Refusal(problems[0], { problems, ...mask });
295
438
  const findings = scanPayload(home, payload, env);
296
- if (findings.length) throw new Refusal("secret-detected", { findings });
439
+ if (findings.length) throw new Refusal("secret-detected", { findings, ...mask });
297
440
  const request = { ...payload, visibility };
298
441
  if (visibility === "selected") request.logins = logins;
299
442
  if (args["base-version"] !== undefined) {
@@ -302,9 +445,9 @@ const commands = {
302
445
  request.baseVersion = v;
303
446
  }
304
447
  const ctx = context(home, env);
305
- if (args["dry-run"]) return { ok: true, dryRun: true, url: ctx.base, request };
448
+ if (args["dry-run"]) return { ok: true, dryRun: true, url: ctx.base, request, ...mask };
306
449
  const { routine } = await call(ctx, "POST", "", request);
307
- return { ok: true, routine };
450
+ return { ok: true, routine, ...mask };
308
451
  },
309
452
 
310
453
  async import(home, args, env) {
@@ -317,13 +460,11 @@ const commands = {
317
460
  id: routine.id,
318
461
  as: typeof args.as === "string" ? args.as : undefined,
319
462
  });
320
- return { ok: true, imported: entry };
463
+ return { ok: true, imported: entry, ...placeholdersOf(routine) };
321
464
  },
322
465
 
323
466
  async updates(home, _args, env) {
324
- const imported = listRoutines(home).filter(
325
- (r) => r.sharedId && String(r.source || "").startsWith("shared:"),
326
- );
467
+ const imported = listRoutines(home).filter((r) => r.sharedId && isImported(r));
327
468
  if (imported.length === 0) return { ok: true, updates: [], unavailable: [] };
328
469
  const { routines = [] } = await call(context(home, env), "GET", "");
329
470
  const byId = new Map(routines.map((r) => [r.id, r]));
@@ -366,6 +507,7 @@ const commands = {
366
507
  descriptionChanged: local.description !== routine.description,
367
508
  localEdits: skillEdited(home, entry),
368
509
  diff: lineDiff(local.body, routine.body),
510
+ ...placeholdersOf(routine),
369
511
  };
370
512
  },
371
513
 
@@ -385,7 +527,7 @@ const commands = {
385
527
  replace: true,
386
528
  backup: edited !== false,
387
529
  });
388
- return { ok: true, updated };
530
+ return { ok: true, updated, ...placeholdersOf(routine) };
389
531
  },
390
532
 
391
533
  async delete(home, args, env) {
@@ -0,0 +1,376 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * usage-health.mjs - the machine-health summary a usage event may carry.
4
+ *
5
+ * health-report.mjs takes tens of seconds (it asks every credential and runs
6
+ * doctor), and a usage report must never wait on it. So the summary is cached
7
+ * on disk and the report only reads it:
8
+ *
9
+ * - a cached summary younger than CACHE_TTL_MS is used as it is;
10
+ * - otherwise the caller tries to take the refresh lock (`<cache>.lock`,
11
+ * created exclusively, holding a random owner token). Only the caller that
12
+ * takes it starts the detached refresher (this file with --refresh and
13
+ * that token) and waits at most WAIT_MS for the summary to land; a refresh
14
+ * that takes longer still fills the cache for the next event;
15
+ * - a caller that finds the lock held returns null at once, without waiting;
16
+ * - a lock older than LOCK_STALE_MS is taken over. A refresher removes its
17
+ * lock on success and rewrites it on failure, so a report that keeps
18
+ * failing is retried at most once per LOCK_STALE_MS;
19
+ * - the refresher exits at once when the lock is fresh and carries another
20
+ * owner's token;
21
+ * - anything that fails, times out or does not parse yields null, and the
22
+ * event goes out without the field. The receiving side keeps the last
23
+ * summary it had when the field is absent.
24
+ *
25
+ * Shape (the ingest contract):
26
+ * { generatedAt, overall: "green"|"yellow"|"red",
27
+ * items: [{ id, status, reason }] } at most MAX_ITEMS, ids from SECTION_IDS
28
+ *
29
+ * A reason is the section's message rendered in prefs outputLanguage. Before it
30
+ * is stored it is reduced to one plain line: the home directory becomes `~`,
31
+ * any other absolute path becomes `[path]`, anything shaped like a token
32
+ * becomes `[redacted]`, and it is cut to MAX_REASON characters. The cache is
33
+ * re-validated through the same filter when it is read, so a hand-edited file
34
+ * cannot smuggle anything past it. --probe is never used: no network.
35
+ *
36
+ * Env: MULTI_AGENT_USAGE_HEALTH=cache uses the cache and never starts a
37
+ * refresher; MULTI_AGENT_USAGE_HEALTH=off leaves the field out entirely.
38
+ *
39
+ * Usage:
40
+ * usage-health.mjs --refresh [--file <cache.json>] [--lang en|tr] [--token <owner>]
41
+ *
42
+ * @module pipeline/scripts/usage-health
43
+ */
44
+
45
+ import { spawn } from "node:child_process";
46
+ import { randomBytes } from "node:crypto";
47
+ import { mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
48
+ import { homedir } from "node:os";
49
+ import { dirname, join } from "node:path";
50
+ import { fileURLToPath } from "node:url";
51
+
52
+ import { exitOnHelp } from "../lib/cli-help.mjs";
53
+ import { renderHealthMessage } from "../lib/health-messages.mjs";
54
+ import { invokedDirectly } from "../lib/invoked-directly.mjs";
55
+ import { SECRET_PATTERNS } from "../lib/secret-patterns.generated.mjs";
56
+
57
+ exitOnHelp(import.meta.url);
58
+
59
+ export const HEALTH_FILE = "usage-health.json";
60
+ export const CACHE_TTL_MS = 30 * 60 * 1000;
61
+ export const WAIT_MS = 5000;
62
+ export const LOCK_STALE_MS = 3 * 60 * 1000;
63
+ export const REFRESH_LIMIT_MS = 150_000;
64
+ export const MAX_ITEMS = 30;
65
+ export const MAX_REASON = 200;
66
+ export const HEALTH_IDS = [
67
+ "services",
68
+ "toolkit",
69
+ "install",
70
+ "sessions",
71
+ "autopilot",
72
+ "office",
73
+ "disk",
74
+ "gate",
75
+ "errors",
76
+ ];
77
+ const STATUSES = ["green", "yellow", "red"];
78
+ const POLL_MS = 200;
79
+ const SELF = fileURLToPath(import.meta.url);
80
+
81
+ /** The cache file, beside the other usage-report state. */
82
+ export function healthFile(home = homedir()) {
83
+ return join(home, ".claude", "logs", "multi-agent", HEALTH_FILE);
84
+ }
85
+
86
+ // The shared credential list first, then looser shapes: a known prefix with a
87
+ // short tail, an email address, and a long run mixing letters and digits.
88
+ const TOKEN_SHAPES = [
89
+ ...SECRET_PATTERNS.map((p) => new RegExp(p.re.source, p.re.flags)),
90
+ /\b(?:gh[pousr]_|github_pat_|glpat-|figu_|figd_|xox[abprs]-|npm_|sk-|AKIA)[A-Za-z0-9_-]{6,}/g,
91
+ /\b[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,63}\b/g,
92
+ /\b(?=[A-Za-z0-9_+=-]*\d)(?=[A-Za-z0-9_+=-]*[A-Za-z])[A-Za-z0-9_+=-]{32,}/g,
93
+ ];
94
+ const ABSOLUTE_PATH = /(^|[\s(=:'"`,[])(\/[^\s'"`,)\]]+|[A-Za-z]:\\[^\s'"`,)\]]*)/g;
95
+
96
+ // The home directory only as a whole path component: followed by "/", the
97
+ // end, or a character that cannot continue a directory name. `/Users/ann2`
98
+ // is not under `/Users/ann`, so it is left to the absolute-path rule.
99
+ const homePattern = (home) =>
100
+ new RegExp(
101
+ `${home.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?=/|$|[^A-Za-z0-9._-]|\\.(?![A-Za-z0-9_-]))`,
102
+ "g",
103
+ );
104
+
105
+ /**
106
+ * One plain line safe to leave the machine, at most MAX_REASON characters.
107
+ *
108
+ * @param {unknown} text
109
+ * @param {string} [home]
110
+ * @returns {string}
111
+ */
112
+ export function scrubReason(text, home = homedir()) {
113
+ let s = String(text ?? "")
114
+ .replace(/\p{Cc}+/gu, " ")
115
+ .replace(/\s+/g, " ")
116
+ .trim();
117
+ if (home && home.length > 1) s = s.replace(homePattern(home), "~");
118
+ for (const shape of TOKEN_SHAPES) s = s.replace(shape, "[redacted]");
119
+ s = s.replace(ABSOLUTE_PATH, (_, lead) => `${lead}[path]`);
120
+ if (s.length > MAX_REASON) s = `${s.slice(0, MAX_REASON - 3).trimEnd()}...`;
121
+ return s;
122
+ }
123
+
124
+ const RANK = { green: 0, yellow: 1, red: 2 };
125
+ const worst = (items) => items.reduce((w, i) => (RANK[i.status] > RANK[w] ? i.status : w), "green");
126
+
127
+ function validDate(value) {
128
+ if (typeof value !== "string") return null;
129
+ const t = Date.parse(value);
130
+ return Number.isNaN(t) ? null : new Date(t).toISOString();
131
+ }
132
+
133
+ /**
134
+ * Brings anything shaped like a summary to the contract: known ids only, once
135
+ * each, a valid status, a scrubbed reason. Null when nothing usable is left.
136
+ */
137
+ export function normalizeSummary(raw, { home = homedir() } = {}) {
138
+ if (!raw || typeof raw !== "object" || !Array.isArray(raw.items)) return null;
139
+ const generatedAt = validDate(raw.generatedAt);
140
+ if (!generatedAt) return null;
141
+ const seen = new Set();
142
+ const items = [];
143
+ for (const it of raw.items) {
144
+ if (items.length >= MAX_ITEMS) break;
145
+ if (!it || typeof it !== "object") continue;
146
+ if (!HEALTH_IDS.includes(it.id) || seen.has(it.id) || !STATUSES.includes(it.status)) continue;
147
+ seen.add(it.id);
148
+ items.push({ id: it.id, status: it.status, reason: scrubReason(it.reason, home) });
149
+ }
150
+ if (items.length === 0) return null;
151
+ const overall = STATUSES.includes(raw.overall) ? raw.overall : worst(items);
152
+ return { generatedAt, overall, items };
153
+ }
154
+
155
+ /**
156
+ * health-report's document mapped to the contract: one item per section, the
157
+ * reason rendered from the section's message in `lang` (its English reason
158
+ * when it carries no message).
159
+ */
160
+ export function summaryFromReport(doc, { lang = "en", home = homedir() } = {}) {
161
+ if (!doc || typeof doc !== "object" || !Array.isArray(doc.sections)) return null;
162
+ const items = doc.sections.map((s) => ({
163
+ id: s?.id,
164
+ status: s?.status,
165
+ reason: s?.message ? renderHealthMessage(s.message, lang) : s?.reason,
166
+ }));
167
+ return normalizeSummary({ generatedAt: doc.generatedAt, overall: doc.status, items }, { home });
168
+ }
169
+
170
+ /**
171
+ * The cached summary when it is younger than `ttlMs`, else null. A missing,
172
+ * unreadable or malformed file is null, never an error.
173
+ */
174
+ export function readCachedHealth(file, { now = Date.now(), ttlMs = CACHE_TTL_MS, home } = {}) {
175
+ let raw;
176
+ try {
177
+ raw = JSON.parse(readFileSync(file, "utf8"));
178
+ } catch {
179
+ return null;
180
+ }
181
+ const summary = normalizeSummary(raw, { home });
182
+ if (!summary) return null;
183
+ const age = now - Date.parse(summary.generatedAt);
184
+ return age >= 0 && age < ttlMs ? summary : null;
185
+ }
186
+
187
+ /** Atomic, owner-only write of a summary. */
188
+ export function writeCachedHealth(file, summary) {
189
+ const tmp = `${file}.${process.pid}.tmp`;
190
+ mkdirSync(dirname(file), { recursive: true });
191
+ writeFileSync(tmp, JSON.stringify(summary) + "\n", { mode: 0o600 });
192
+ renameSync(tmp, file);
193
+ }
194
+
195
+ export const lockOf = (file) => `${file}.lock`;
196
+
197
+ const newToken = () => `${process.pid}-${randomBytes(8).toString("hex")}`;
198
+
199
+ function lockState(file, now = Date.now()) {
200
+ try {
201
+ const lock = lockOf(file);
202
+ const fresh = now - statSync(lock).mtimeMs < LOCK_STALE_MS;
203
+ return { exists: true, fresh, owner: readFileSync(lock, "utf8").trim() };
204
+ } catch {
205
+ return { exists: false, fresh: false, owner: null };
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Takes the refresh lock for `token`: created exclusively, or taken over when
211
+ * the existing lock is older than LOCK_STALE_MS. A takeover renames a private
212
+ * file over the stale lock and reads it back, so of two callers racing for
213
+ * the same stale lock only the one whose token is left in it proceeds.
214
+ *
215
+ * @returns {boolean} true when `token` now owns the lock
216
+ */
217
+ export function acquireLock(file, token, now = Date.now()) {
218
+ const lock = lockOf(file);
219
+ mkdirSync(dirname(file), { recursive: true });
220
+ try {
221
+ writeFileSync(lock, token, { flag: "wx", mode: 0o600 });
222
+ return true;
223
+ } catch (e) {
224
+ if (e?.code !== "EEXIST") return false;
225
+ }
226
+ if (lockState(file, now).fresh) return false;
227
+ try {
228
+ const tmp = `${lock}.${token}.tmp`;
229
+ writeFileSync(tmp, token, { mode: 0o600 });
230
+ renameSync(tmp, lock);
231
+ return lockState(file).owner === token;
232
+ } catch {
233
+ return false;
234
+ }
235
+ }
236
+
237
+ /** Starts the detached refresher for the lock `token` owns. */
238
+ function startRefresher({ file, lang, token }) {
239
+ const child = spawn(
240
+ process.execPath,
241
+ [SELF, "--refresh", "--file", file, "--token", token, ...(lang ? ["--lang", lang] : [])],
242
+ { detached: true, stdio: "ignore", env: process.env },
243
+ );
244
+ child.on("error", () => {});
245
+ child.unref();
246
+ }
247
+
248
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
249
+
250
+ /**
251
+ * Takes the refresh lock and, only then, starts the refresher and watches the
252
+ * cache until a fresh summary appears or `deadline` passes. A lock someone
253
+ * else holds means null at once: an event waits only when it starts the
254
+ * refresh. The refresher outlives this process.
255
+ */
256
+ export async function spawnRefresh({ file, lang, deadline, home, start = startRefresher }) {
257
+ const token = newToken();
258
+ if (!acquireLock(file, token)) return null;
259
+ try {
260
+ start({ file, lang, token });
261
+ } catch {
262
+ return null;
263
+ }
264
+ while (Date.now() < deadline) {
265
+ await sleep(Math.max(0, Math.min(POLL_MS, deadline - Date.now())));
266
+ const fresh = readCachedHealth(file, { home });
267
+ if (fresh) return fresh;
268
+ }
269
+ return null;
270
+ }
271
+
272
+ /**
273
+ * The summary for this event, or null. Never throws and never waits longer
274
+ * than `timeoutMs`. `refresh: null`, or MULTI_AGENT_USAGE_HEALTH set to
275
+ * `cache`, reads the cache only; `off` sends no summary at all.
276
+ *
277
+ * @param {{file?: string, now?: number, ttlMs?: number, timeoutMs?: number,
278
+ * lang?: string, home?: string, env?: Record<string, string | undefined>,
279
+ * refresh?: null | ((o: {file: string, lang?: string, deadline: number, home: string})
280
+ * => Promise<unknown>)}} [opts]
281
+ */
282
+ export async function machineHealth({
283
+ home = homedir(),
284
+ file = healthFile(home),
285
+ now = Date.now(),
286
+ ttlMs = CACHE_TTL_MS,
287
+ timeoutMs = WAIT_MS,
288
+ lang = "en",
289
+ env = process.env,
290
+ refresh = spawnRefresh,
291
+ } = {}) {
292
+ try {
293
+ const mode = env.MULTI_AGENT_USAGE_HEALTH;
294
+ if (mode === "off") return null;
295
+ const cached = readCachedHealth(file, { now, ttlMs, home });
296
+ if (cached || !refresh || mode === "cache") return cached;
297
+ let timer;
298
+ const timeout = new Promise((r) => {
299
+ timer = setTimeout(() => r(null), timeoutMs);
300
+ });
301
+ const fresh = await Promise.race([
302
+ Promise.resolve(refresh({ file, lang, deadline: Date.now() + timeoutMs, home })).catch(
303
+ () => null,
304
+ ),
305
+ timeout,
306
+ ]);
307
+ clearTimeout(timer);
308
+ return normalizeSummary(fresh, { home });
309
+ } catch {
310
+ return null;
311
+ }
312
+ }
313
+
314
+ /**
315
+ * Builds a report, maps it and stores it; used by the detached refresher.
316
+ * With `token` it runs only while that token owns the lock (or the lock is
317
+ * gone or stale); without one it takes the lock itself. A lock held by
318
+ * another owner means null at once, with the lock left as it is. Success
319
+ * removes the lock; failure rewrites it, which starts the backoff.
320
+ */
321
+ export async function refreshHealth({
322
+ file,
323
+ lang = "en",
324
+ home = homedir(),
325
+ report,
326
+ limitMs = REFRESH_LIMIT_MS,
327
+ token,
328
+ } = {}) {
329
+ const lock = lockOf(file);
330
+ const owner = token ?? newToken();
331
+ const held = lockState(file);
332
+ const mine = held.exists && held.owner === owner;
333
+ if (!mine && !acquireLock(file, owner)) return null;
334
+ let summary = null;
335
+ try {
336
+ const build = report ?? (await import("./health-report.mjs")).healthReport;
337
+ let timer;
338
+ const doc = await Promise.race([
339
+ build({ probe: false }),
340
+ new Promise((_, reject) => {
341
+ timer = setTimeout(() => reject(new Error("health report timed out")), limitMs);
342
+ }),
343
+ ]).finally(() => clearTimeout(timer));
344
+ summary = summaryFromReport(doc, { lang, home });
345
+ if (summary) writeCachedHealth(file, summary);
346
+ return summary;
347
+ } finally {
348
+ if (lockState(file).owner === owner || !lockState(file).exists) {
349
+ if (summary) rmSync(lock, { force: true });
350
+ else writeFileSync(lock, owner, { mode: 0o600 });
351
+ }
352
+ }
353
+ }
354
+
355
+ function flag(argv, name) {
356
+ const i = argv.indexOf(name);
357
+ return i >= 0 && typeof argv[i + 1] === "string" ? argv[i + 1] : undefined;
358
+ }
359
+
360
+ if (invokedDirectly(import.meta.url)) {
361
+ const argv = process.argv.slice(2);
362
+ if (!argv.includes("--refresh")) {
363
+ process.stderr.write(
364
+ "usage: usage-health.mjs --refresh [--file <cache.json>] [--lang <code>] [--token <owner>]\n",
365
+ );
366
+ process.exitCode = 2;
367
+ } else {
368
+ refreshHealth({
369
+ file: flag(argv, "--file") ?? healthFile(),
370
+ lang: flag(argv, "--lang"),
371
+ token: flag(argv, "--token"),
372
+ })
373
+ .then(() => process.exit(0))
374
+ .catch(() => process.exit(0));
375
+ }
376
+ }