benignswarm 0.12.154 → 0.12.155

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.
@@ -329,6 +329,7 @@ export function processDeps(call, log, heartbeatIntervalMs = 15_000) {
329
329
  return;
330
330
  heartbeatInFlight = context.heartbeat().then(() => undefined, (error) => {
331
331
  heartbeatFailure = error;
332
+ stopHeartbeat();
332
333
  log(`job ${context.jobId} could not refresh its lock heartbeat; stopping the command to avoid running without the lock`);
333
334
  if (!childClosed)
334
335
  child.kill("SIGTERM");
@@ -8,6 +8,7 @@ import { loadAdmin, resolveAdminName, splitRef } from "../config.js";
8
8
  import { CliError } from "../errors.js";
9
9
  import { table } from "../output.js";
10
10
  import { CLI_VERSION } from "../version.js";
11
+ import { consoleLink } from "../console-links.js";
11
12
  import { runMachineResize } from "./machine-resize.js";
12
13
  import { poolSuggestionsAdmin } from "./routing-admin.js";
13
14
  import { readState, stateFilePath, stateTransferContents } from "../state.js";
@@ -128,6 +129,23 @@ export function machinePrepareCommand(options) {
128
129
  }
129
130
  export async function machineAdmin(action, rest, p, out) {
130
131
  const c = adminClient(p);
132
+ if (action === "diag") {
133
+ if (!rest[0])
134
+ throw new CliError("usage", "machine diag <name>");
135
+ const machine = rest[0];
136
+ const request = await c.call("POST", `/machines/${encodeURIComponent(machine)}/diagnostics`, {});
137
+ const deadline = Date.now() + 120_000;
138
+ while (Date.now() < deadline) {
139
+ const current = await c.call("GET", `/machines/${encodeURIComponent(machine)}/diagnostics/${encodeURIComponent(request.id)}`);
140
+ if (current.status === "complete" && current.evidence_id) {
141
+ return out.print(`Diagnostic evidence: evidence:${current.evidence_id}\nConsole: ${consoleLink("evidence", current.project, current.evidence_id)}`, current);
142
+ }
143
+ if (current.status === "expired")
144
+ throw new CliError("diagnostic_expired", "machine did not return the diagnostic bundle within two minutes");
145
+ await new Promise((resolve) => setTimeout(resolve, 1_000));
146
+ }
147
+ throw new CliError("diagnostic_timeout", `machine diagnostic request timed out; request ${request.id} may still complete`);
148
+ }
131
149
  if (action === "companion") {
132
150
  if (rest[0] !== "run" || !rest[1] || !/^bs_handoff_[A-Za-z0-9_-]{20,}$/.test(rest[1])) {
133
151
  throw new CliError("usage", "machine companion run <handoff-code> [--confirm <machine-name>] (paste the short-lived code from the signed-in console)");
@@ -21,6 +21,8 @@ import { installService, launchdFacts, launchdFactsLine, launchdGuidance, launch
21
21
  import { CLI_VERSION } from "../version.js";
22
22
  import { probeCapabilities } from "../capabilities.js";
23
23
  import { diskSpaceNotice } from "../notices.js";
24
+ import { collectMachineDiagnosticBundle } from "../machine-diagnostics.js";
25
+ import { consoleLink } from "../console-links.js";
24
26
  import { cachedClaudeProviderCheck, deepSeekKeyPath, verifyClaudeProvider } from "../providers.js";
25
27
  import { busyTurnPause, DEFAULT_TURNS_PER_HOUR, DEFAULT_UNPRODUCTIVE_PER_HOUR, resumeTurnGuard, verificationUnavailable } from "../turn-guard.js";
26
28
  import { defaultWorkspaceWritableRoots } from "../start-options.js";
@@ -1122,6 +1124,23 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1122
1124
  const desired = me.sessions;
1123
1125
  const processScanner = deps?.worktreeProcessScanner ?? scanWorktreeProcesses;
1124
1126
  await answerWorktreeProcessQueries(client, desired, me.process_queries ?? [], log, processScanner);
1127
+ const diagnosticQueries = me.diagnostic_queries ?? [];
1128
+ if (diagnosticQueries.length) {
1129
+ const configuredWorkdir = me.machine?.workdir;
1130
+ const workdir = !configuredWorkdir ? join(homedir(), "bschat")
1131
+ : configuredWorkdir === "~" ? homedir()
1132
+ : configuredWorkdir.startsWith("~/") ? join(homedir(), configuredWorkdir.slice(2)) : configuredWorkdir;
1133
+ const bundle = collectMachineDiagnosticBundle(m.name, workdir, (me.projects ?? []).map((project) => project.name ?? "").filter(Boolean));
1134
+ for (const query of diagnosticQueries) {
1135
+ try {
1136
+ await client.call("POST", `/machines/me/diagnostics/${encodeURIComponent(query.id)}`, { bundle }, { retries: 2 });
1137
+ log(`uploaded diagnostic evidence for ${query.requester_name}`);
1138
+ }
1139
+ catch (error) {
1140
+ log(`diagnostic request ${query.id} failed: ${error.message}`);
1141
+ }
1142
+ }
1143
+ }
1125
1144
  if (Array.isArray(me.device_logins)) {
1126
1145
  handleDeviceLoginRequests(client, me.device_logins, log, deps?.deviceLoginInFlight ?? defaultDeviceLoginInFlight);
1127
1146
  }
@@ -3690,6 +3709,26 @@ export async function machine(p, out) {
3690
3709
  }
3691
3710
  const m = loadMachine();
3692
3711
  const log = (s) => process.stderr.write(`${new Date().toISOString()} b9s machine[${m.name}]: ${s}\n`);
3712
+ if (sub === "diag") {
3713
+ const target = p.positionals[2];
3714
+ if (!target || target !== m.name)
3715
+ throw new CliError("machine_scope", `this daemon is ${m.name}; agents may request diagnostics only from a machine they run on`);
3716
+ const agent = loadAgent(resolveAgentName(str(p.flags, "as"), process.env));
3717
+ const client = Client.forAgent(agent, undefined);
3718
+ const request = await client.call("POST", `/machines/${encodeURIComponent(target)}/diagnostics`, {});
3719
+ const deadline = Date.now() + 120_000;
3720
+ while (Date.now() < deadline) {
3721
+ const current = await client.call("GET", `/machines/${encodeURIComponent(target)}/diagnostics/${encodeURIComponent(request.id)}`);
3722
+ if (current.status === "complete" && current.evidence_id) {
3723
+ const result = { ...current, ref: `evidence:${current.evidence_id}` };
3724
+ return out.print(`Diagnostic evidence: evidence:${current.evidence_id}\nConsole: ${consoleLink("evidence", current.project, current.evidence_id)}`, result);
3725
+ }
3726
+ if (current.status === "expired")
3727
+ throw new CliError("diagnostic_expired", "machine did not return the diagnostic bundle within two minutes");
3728
+ await new Promise((resolve) => setTimeout(resolve, 1_000));
3729
+ }
3730
+ throw new CliError("diagnostic_timeout", `machine diagnostic request timed out; request ${request.id} may still complete`);
3731
+ }
3693
3732
  if (sub === "status") {
3694
3733
  const desired = (await Client.raw(m.url, m.key).call("GET", "/machines/me")).sessions;
3695
3734
  const state = readMachineState();
package/dist/help.js CHANGED
@@ -281,6 +281,7 @@ Machine placement enforces configured session slots and reports machine pressure
281
281
  b9s machine once run one daemon cycle
282
282
  b9s machine build-images run pending image builds
283
283
  b9s machine status show daemon state
284
+ b9s machine diag <machine> [--as <project>/<agent>] request and wait for a safe machine diagnostic evidence bundle
284
285
  b9s machine prepare [--codex-userns] [--bwrap-userns] [--agy-userns] [--print-hooks] [--print-apparmor] check machine readiness and required sandbox profiles
285
286
  --agy-userns opts into an AppArmor
286
287
  profile for the resolved agy binary if Ubuntu blocks its workspace-write terminal sandbox (passwordless sudo)
@@ -501,6 +502,7 @@ Machines (provisioned over your own ssh; a daemon on each runs the agent session
501
502
  install a profile only for the resolved ~/.local/bin/agy (Antigravity terminal sandbox)
502
503
  b9s-admin machine list
503
504
  b9s-admin machine show <name>
505
+ b9s-admin machine diag <name> request and wait for the daemon's redacted diagnostic evidence bundle
504
506
  b9s-admin machine remove <name> [--preview] [--confirm <name> --impact-revision <revision>]
505
507
  show includes host readiness, configured disk floors and named readiness refusals; removal previews sessions, work, keys, recovery blockers and replanned slots
506
508
  the API requires a fresh revision for removal
@@ -0,0 +1,200 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { readdirSync, readFileSync, statSync, statfsSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { delimiter, join, parse } from "node:path";
5
+ import { configRoot } from "./config.js";
6
+ import { MACHINE_LABEL, watcherServices } from "./install.js";
7
+ import { scanLinesBackward, TAIL_MAX_BYTES } from "./tail-lines.js";
8
+ const SECRET_PATTERNS = [
9
+ /\bBearer\s+[A-Za-z0-9._~+/=-]+/gi,
10
+ /\bbs_(?:admin|agent|machine|boot)_[A-Za-z0-9_-]+\b/g,
11
+ /((?:[A-Za-z_][A-Za-z0-9_]*(?:TOKEN|SECRET|PASSWORD|CREDENTIAL|API_KEY|PRIVATE_KEY|ACCESS_KEY|AUTHORIZATION|_KEY)|--?[\w-]*(?:token|secret|password|credential|api[_-]?key|private[_-]?key|access[_-]?key|auth(?:orization)?|key))\s*(?:[=:]|\s)\s*)("?)[^",}\s]+/gi,
12
+ /\b(?:gh[pousr]_[A-Za-z0-9_]{20,}|xox[baprs]-[A-Za-z0-9-]{10,}|glpat-[A-Za-z0-9_-]{20,})\b/g,
13
+ /([a-z][a-z0-9+.-]*:\/\/)[^/@\s]+:[^/@\s]+@/gi,
14
+ ];
15
+ export function redactDiagnosticText(input) {
16
+ let text = input.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, "");
17
+ for (const pattern of SECRET_PATTERNS)
18
+ text = text.replace(pattern, (match, prefix, quote) => typeof prefix === "string" ? `${prefix}${typeof quote === "string" ? quote : ""}[REDACTED]` : "[REDACTED]");
19
+ return text.slice(0, 4_000);
20
+ }
21
+ /** Keep only the known service entrypoint; arbitrary argv may contain credentials or private data. */
22
+ export function safeServiceArguments(args) {
23
+ const command = args.slice(1);
24
+ if (command[0] === "machine" && command[1] === "run")
25
+ return ["machine", "run"];
26
+ if (command[0] === "watch")
27
+ return ["watch"];
28
+ return [];
29
+ }
30
+ /** Return only a fixed process role; never upload the daemon's arbitrary argv text. */
31
+ export function diagnosticProcessLabel(command) {
32
+ if (/lock-run-supervisor/i.test(command))
33
+ return "b9s lock supervisor";
34
+ const cliCommand = /(?:^|\s)(?:\S*\/)?(?:b9s|bschat)(?:\s|$)/i.test(command)
35
+ || /\/(?:benignswarm|bschat)\/(?:packages\/cli\/)?dist\/index\.js(?:\s|$)/i.test(command);
36
+ if (!cliCommand)
37
+ return null;
38
+ if (/\bmachine\s+run\b/i.test(command))
39
+ return "b9s machine daemon";
40
+ if (/\bwatch\b/i.test(command))
41
+ return "b9s agent watcher";
42
+ return null;
43
+ }
44
+ function executable(pathValue, name) {
45
+ for (const dir of pathValue.split(delimiter)) {
46
+ const candidate = join(dir || ".", name);
47
+ try {
48
+ if (statSync(candidate).isFile())
49
+ return candidate;
50
+ }
51
+ catch { /* continue */ }
52
+ }
53
+ return null;
54
+ }
55
+ function treeSize(path, maxEntries = 500) {
56
+ let size = 0;
57
+ let visited = 0;
58
+ const walk = (dir, depth) => {
59
+ if (depth > 4 || visited >= maxEntries)
60
+ return;
61
+ let entries;
62
+ try {
63
+ entries = readdirSync(dir);
64
+ }
65
+ catch {
66
+ return;
67
+ }
68
+ for (const entry of entries) {
69
+ if (++visited > maxEntries)
70
+ break;
71
+ const child = join(dir, entry);
72
+ try {
73
+ const st = statSync(child);
74
+ if (st.isDirectory())
75
+ walk(child, depth + 1);
76
+ else if (st.isFile())
77
+ size += st.size;
78
+ }
79
+ catch { /* racing removal */ }
80
+ }
81
+ };
82
+ walk(path, 0);
83
+ return size;
84
+ }
85
+ /** Collect deliberately narrow host facts; never read arbitrary service environment variables. */
86
+ export function collectMachineDiagnosticBundle(machine, workdir, projectNames, env = process.env) {
87
+ const safePath = env.PATH ?? "/usr/local/bin:/usr/bin:/bin";
88
+ const home = homedir();
89
+ const service = watcherServices().find((entry) => entry.label === MACHINE_LABEL);
90
+ let serviceEnv = { PATH: safePath, HOME: home };
91
+ let workingDirectory = null;
92
+ let stdoutPath = null;
93
+ let stderrPath = null;
94
+ if (service?.kind === "launchd") {
95
+ const parsed = spawnSync("plutil", ["-convert", "json", "-o", "-", service.path], { encoding: "utf8", timeout: 2_000 });
96
+ if (parsed.status === 0)
97
+ try {
98
+ const plist = JSON.parse(parsed.stdout);
99
+ const allowed = plist.EnvironmentVariables ?? {};
100
+ serviceEnv = { PATH: typeof allowed.PATH === "string" ? allowed.PATH : safePath, HOME: typeof allowed.HOME === "string" ? allowed.HOME : home };
101
+ workingDirectory = typeof plist.WorkingDirectory === "string" ? plist.WorkingDirectory : null;
102
+ stdoutPath = typeof plist.StandardOutPath === "string" ? plist.StandardOutPath : null;
103
+ stderrPath = typeof plist.StandardErrorPath === "string" ? plist.StandardErrorPath : null;
104
+ }
105
+ catch { /* keep only the current process's safe defaults */ }
106
+ }
107
+ else if (service?.kind === "systemd") {
108
+ try {
109
+ const text = readFileSync(service.path, "utf8");
110
+ const envText = [...text.matchAll(/^Environment=(.*)$/gm)].map((match) => match[1]).join(" ");
111
+ const pathMatch = /(?:^|\s)"?PATH=([^"\s]*)"?/.exec(envText);
112
+ const homeMatch = /(?:^|\s)"?HOME=([^"\s]*)"?/.exec(envText);
113
+ serviceEnv = { PATH: pathMatch?.[1] ?? safePath, HOME: homeMatch?.[1] ?? home };
114
+ workingDirectory = /^WorkingDirectory=(.*)$/m.exec(text)?.[1]?.trim() ?? null;
115
+ stdoutPath = /^StandardOutput=append:(.*)$/m.exec(text)?.[1]?.trim() ?? null;
116
+ stderrPath = /^StandardError=append:(.*)$/m.exec(text)?.[1]?.trim() ?? null;
117
+ }
118
+ catch { /* keep only the current process's safe defaults */ }
119
+ }
120
+ const runtimes = {};
121
+ for (const [key, binary, args] of [["b9s", "b9s", ["--version"]], ["node", "node", ["--version"]], ["npm", "npm", ["--version"]]]) {
122
+ const path = executable(serviceEnv.PATH, binary);
123
+ const result = path ? spawnSync(path, [...args], { encoding: "utf8", timeout: 2_000, env: serviceEnv }) : null;
124
+ runtimes[key] = { path, version: result?.status === 0 ? redactDiagnosticText(result.stdout.trim()) : null };
125
+ }
126
+ const serviceInfo = service ? {
127
+ kind: service.kind, label: service.label, definition_path: service.path,
128
+ program: service.args?.[0] ? redactDiagnosticText(service.args[0]) : null,
129
+ args: safeServiceArguments(service.args ?? []),
130
+ working_directory: workingDirectory ? redactDiagnosticText(workingDirectory) : null,
131
+ stdout_path: stdoutPath ? redactDiagnosticText(stdoutPath) : null,
132
+ stderr_path: stderrPath ? redactDiagnosticText(stderrPath) : null,
133
+ environment: { PATH: redactDiagnosticText(serviceEnv.PATH), HOME: redactDiagnosticText(serviceEnv.HOME) }, runtimes,
134
+ } : null;
135
+ const logs = [];
136
+ for (const file of [join(configRoot(), "logs", "machine.out.log"), join(configRoot(), "logs", "machine.err.log")]) {
137
+ let lines = [];
138
+ try {
139
+ const newest = [];
140
+ scanLinesBackward(file, (line) => { if (line)
141
+ newest.push(line); return newest.length >= 250; }, undefined, TAIL_MAX_BYTES);
142
+ lines = newest.reverse().map(redactDiagnosticText);
143
+ }
144
+ catch { /* no log yet */ }
145
+ logs.push({ file: file.replace(home, "~"), lines });
146
+ }
147
+ const jobs = [];
148
+ for (const project of projectNames.slice(0, 30)) {
149
+ const root = join(workdir, project, ".ux-jobs");
150
+ let names;
151
+ try {
152
+ names = readdirSync(root).slice(-100);
153
+ }
154
+ catch {
155
+ continue;
156
+ }
157
+ for (const name of names) {
158
+ const path = join(root, name);
159
+ try {
160
+ const st = statSync(path);
161
+ if (st.isDirectory())
162
+ jobs.push({ name: `${project}/${name}`.slice(0, 200), age_seconds: Math.max(0, Math.floor((Date.now() - st.mtimeMs) / 1000)), size_bytes: treeSize(path) });
163
+ }
164
+ catch { /* job cleaned up concurrently */ }
165
+ }
166
+ }
167
+ jobs.sort((a, b) => a.age_seconds - b.age_seconds);
168
+ const disks = [];
169
+ const seen = new Set();
170
+ for (const path of [parse(home).root, home, workdir, ...projectNames.slice(0, 30).map((p) => join(workdir, p))]) {
171
+ try {
172
+ const st = statSync(path);
173
+ const key = String(st.dev);
174
+ if (seen.has(key))
175
+ continue;
176
+ seen.add(key);
177
+ const fs = statfsSync(path);
178
+ disks.push({ volume: path.replace(home, "~"), free_bytes: fs.bavail * fs.bsize, total_bytes: fs.blocks * fs.bsize });
179
+ }
180
+ catch { /* absent mount */ }
181
+ }
182
+ const ps = spawnSync("ps", process.platform === "darwin" ? ["-axo", "pid=,etime=,command="] : ["-eo", "pid=,etime=,args="], { encoding: "utf8", timeout: 2_000, env: { PATH: safePath, HOME: home } });
183
+ const processes = [];
184
+ if (ps.status === 0)
185
+ for (const line of ps.stdout.split(/\r?\n/)) {
186
+ const match = /^\s*(\d+)\s+(\S+)\s+(.+)$/.exec(line);
187
+ if (!match)
188
+ continue;
189
+ const command = diagnosticProcessLabel(match[3]);
190
+ if (!command)
191
+ continue;
192
+ const elapsed = match[2].split("-");
193
+ const parts = elapsed.pop().split(":").map(Number);
194
+ const seconds = parts.reduce((total, part) => total * 60 + part, 0) + (elapsed.length ? Number(elapsed[0]) * 86_400 : 0);
195
+ processes.push({ pid: Number(match[1]), command, age_seconds: seconds });
196
+ if (processes.length >= 100)
197
+ break;
198
+ }
199
+ return { collected_at: new Date().toISOString(), machine: redactDiagnosticText(machine), service: serviceInfo, logs, jobs: jobs.slice(0, 100), disks, processes };
200
+ }
package/dist/ux-jobs.js CHANGED
@@ -344,6 +344,7 @@ export const spawnAsyncCommand = (cmd, args, opts) => new Promise((resolve) => {
344
344
  env: opts.env,
345
345
  stdio: ["ignore", "pipe", "pipe"],
346
346
  shell: false,
347
+ detached: process.platform !== "win32",
347
348
  });
348
349
  let stdout = "";
349
350
  let stderr = "";
@@ -363,13 +364,36 @@ export const spawnAsyncCommand = (cmd, args, opts) => new Promise((resolve) => {
363
364
  });
364
365
  let timedOut = false;
365
366
  let aborted = false;
366
- const stopChild = () => {
367
- child.kill("SIGTERM");
368
- setTimeout(() => child.kill("SIGKILL"), 5_000).unref();
367
+ let stopping = false;
368
+ const signalTree = (signal) => {
369
+ if (!child.pid)
370
+ return;
371
+ if (process.platform === "win32") {
372
+ child.kill(signal);
373
+ return;
374
+ }
375
+ try {
376
+ process.kill(-child.pid, signal);
377
+ }
378
+ catch (error) {
379
+ if (error.code !== "ESRCH")
380
+ opts.onStderrChunk?.(`Could not signal command process group: ${error.message}\n`);
381
+ }
382
+ };
383
+ const stopChild = (immediate = false) => {
384
+ if (stopping)
385
+ return;
386
+ stopping = true;
387
+ if (immediate) {
388
+ signalTree("SIGKILL");
389
+ return;
390
+ }
391
+ signalTree("SIGTERM");
392
+ setTimeout(() => signalTree("SIGKILL"), 5_000).unref();
369
393
  };
370
394
  const onAbort = () => {
371
395
  aborted = true;
372
- stopChild();
396
+ stopChild(true);
373
397
  };
374
398
  opts.signal?.addEventListener("abort", onAbort, { once: true });
375
399
  const timer = setTimeout(() => {
@@ -1038,6 +1062,8 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1038
1062
  return;
1039
1063
  heartbeatInFlight = lockContext.heartbeat().then(() => undefined, (error) => {
1040
1064
  heartbeatFailure = error;
1065
+ if (heartbeatTimer)
1066
+ clearInterval(heartbeatTimer);
1041
1067
  ctx.log(`${jobKind} job ${job.id} (${lockContext.jobId}) could not refresh its lock heartbeat; stopping the command to avoid running without the lock`);
1042
1068
  heartbeatController.abort();
1043
1069
  }).finally(() => {
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.154";
1
+ export const CLI_VERSION = "0.12.155";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.154",
3
+ "version": "0.12.155",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {