benignswarm 0.12.154 → 0.12.156
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.
- package/dist/args.js +2 -2
- package/dist/claude-egress-proxy.js +26 -3
- package/dist/client.js +7 -1
- package/dist/commands/admin.js +32 -3
- package/dist/commands/agent.js +2 -2
- package/dist/commands/hook.js +2 -2
- package/dist/commands/lock-run.js +1 -0
- package/dist/commands/machine-admin.js +18 -0
- package/dist/commands/machine.js +49 -1
- package/dist/commands/operator.js +5 -4
- package/dist/commands/watch.js +15 -7
- package/dist/commands/wu.js +30 -7
- package/dist/help.js +10 -4
- package/dist/machine-diagnostics.js +200 -0
- package/dist/machine-telemetry.js +6 -1
- package/dist/ux-jobs.js +30 -4
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/dist/args.js
CHANGED
|
@@ -15,7 +15,7 @@ export const STRING_FLAGS = [
|
|
|
15
15
|
"event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent",
|
|
16
16
|
"parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval",
|
|
17
17
|
"requeue-after", "unacked-after", "category", "command", "command-pattern", "follow-delay", "startup-jitter-seconds", "env", "scope",
|
|
18
|
-
"scope-file", "scope-from", "append", "pr", "note", "note-file", "add", "remove", "merged", "tag",
|
|
18
|
+
"session-harness", "session-sandbox", "session-machine", "session-machine-label", "scope-file", "scope-from", "append", "pr", "note", "note-file", "add", "remove", "merged", "tag",
|
|
19
19
|
"activity", "max-unanswered", "to", "replay-of", "branch", "base", "effort", "max-budget-usd", "by", "target", "lands-with",
|
|
20
20
|
"milestone", "file", "exit", "depends-on", "default-tags", "source", "on", "partial", "question", "ruling",
|
|
21
21
|
"gaps", "unit", "units", "blocks", "sla", "takeover", "stall", "max-open", "max-in-progress", "require-scope",
|
|
@@ -42,7 +42,7 @@ export const STRING_FLAGS = [
|
|
|
42
42
|
export const BOOL_FLAGS = [
|
|
43
43
|
"latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels",
|
|
44
44
|
"read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "template", "scope-only", "unread",
|
|
45
|
-
"pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "log",
|
|
45
|
+
"clear-session", "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "log",
|
|
46
46
|
"all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive",
|
|
47
47
|
"approve", "turn", "service", "print-hooks", "create", "rotate", "drain", "codex-userns", "bwrap-userns", "agy-userns", "print-apparmor", "overdue",
|
|
48
48
|
"cancel", "rerun", "confirmed", "refuted", "no-source", "confirm-bypass-signal", "assessment-only", "continue",
|
|
@@ -10,6 +10,7 @@ import { domainToASCII, fileURLToPath } from "node:url";
|
|
|
10
10
|
export const CLAUDE_SECRET_EGRESS_OUTER_BOUNDARY = "bwrap-unshare-net-egress-proxy";
|
|
11
11
|
const EGRESS_RUNNER_CONFIG_ENV = "B9S_CLAUDE_EGRESS_RUNNER_CONFIG";
|
|
12
12
|
const DNS_HOSTNAME_RE = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;
|
|
13
|
+
const DARWIN_UNIX_SOCKET_PATH_MAX_BYTES = 103; // sockaddr_un.sun_path includes a trailing NUL byte.
|
|
13
14
|
export function isIpv4Literal(host) {
|
|
14
15
|
if (!/^\d{1,3}(?:\.\d{1,3}){3}$/.test(host))
|
|
15
16
|
return false;
|
|
@@ -40,6 +41,22 @@ export function normalizeEgressHostname(rawHost) {
|
|
|
40
41
|
export function isInternalOrLocalHostname(host) {
|
|
41
42
|
return host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal");
|
|
42
43
|
}
|
|
44
|
+
function unixSocketPathLimit() {
|
|
45
|
+
if (platform() === "darwin")
|
|
46
|
+
return DARWIN_UNIX_SOCKET_PATH_MAX_BYTES;
|
|
47
|
+
if (platform() === "linux")
|
|
48
|
+
return 107;
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
function assertUnixSocketPathFits(path) {
|
|
52
|
+
const limit = unixSocketPathLimit();
|
|
53
|
+
if (limit === null)
|
|
54
|
+
return;
|
|
55
|
+
const length = Buffer.byteLength(path);
|
|
56
|
+
if (length > limit) {
|
|
57
|
+
throw new Error(`Claude egress Unix socket path is ${length} bytes; this platform allows at most ${limit}. Choose a shorter runtime directory.`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
43
60
|
/** Strict host validation shared between project secret host declarations and the outer proxy. */
|
|
44
61
|
export function validateDeclaredSecretHosts(rawHosts, allowEmpty = false) {
|
|
45
62
|
if (!Array.isArray(rawHosts) || (!allowEmpty && rawHosts.length < 1) || rawHosts.length > 50 || rawHosts.some((h) => typeof h !== "string")) {
|
|
@@ -766,14 +783,20 @@ export async function startClaudeEgressProxy(opts) {
|
|
|
766
783
|
resolveFn: opts.resolve ?? ((host) => lookup(host, { all: true, verbatim: true })),
|
|
767
784
|
connectFn: opts.connect ?? ((address, port) => createConnection({ host: address, port })),
|
|
768
785
|
};
|
|
769
|
-
|
|
786
|
+
// Unix socket names have a small kernel limit. Keep these private sockets in
|
|
787
|
+
// the short, canonical system temp directory rather than inheriting an
|
|
788
|
+
// arbitrarily long TMPDIR from a user or test runner.
|
|
789
|
+
const socketBase = platform() === "darwin" || platform() === "linux" ? realpathSync("/tmp") : tmpdir();
|
|
790
|
+
const socketDir = opts.socketDir ?? join(socketBase, `b9s-egress-${process.pid}-${randomBytes(6).toString("hex")}`);
|
|
791
|
+
const httpSocketPath = join(socketDir, "http.sock");
|
|
792
|
+
const socksSocketPath = join(socketDir, "socks.sock");
|
|
793
|
+
assertUnixSocketPathFits(httpSocketPath);
|
|
794
|
+
assertUnixSocketPathFits(socksSocketPath);
|
|
770
795
|
mkdirSync(socketDir, { recursive: true, mode: 0o700 });
|
|
771
796
|
try {
|
|
772
797
|
chmodSync(socketDir, 0o700);
|
|
773
798
|
}
|
|
774
799
|
catch { /* ignore */ }
|
|
775
|
-
const httpSocketPath = join(socketDir, "http.sock");
|
|
776
|
-
const socksSocketPath = join(socketDir, "socks.sock");
|
|
777
800
|
const { httpProxyPort, socksProxyPort } = opts.httpPort && opts.socksPort
|
|
778
801
|
? { httpProxyPort: opts.httpPort, socksProxyPort: opts.socksPort }
|
|
779
802
|
: await allocateClaudeEgressPortPair();
|
package/dist/client.js
CHANGED
|
@@ -19,6 +19,8 @@ function expectedTextReceiptFields(method, path, body, response) {
|
|
|
19
19
|
return strings("text");
|
|
20
20
|
if (verb === "POST" && /^\/projects\/[^/]+\/channels$/.test(route))
|
|
21
21
|
return strings("topic");
|
|
22
|
+
if (verb === "POST" && /^\/projects\/[^/]+\/pause$/.test(route))
|
|
23
|
+
return strings("note");
|
|
22
24
|
if (verb === "POST" && route === "/machine-operations")
|
|
23
25
|
return strings("ssh_host");
|
|
24
26
|
if (verb === "POST" && /^\/projects\/[^/]+\/machines\/[^/]+\/jobs$/.test(route))
|
|
@@ -136,7 +138,7 @@ function expectedTextReceiptFields(method, path, body, response) {
|
|
|
136
138
|
}
|
|
137
139
|
if (["approve", "changes", "proceed"].includes(action))
|
|
138
140
|
return strings("note", "unmet");
|
|
139
|
-
if (["park", "requeue", "decline", "classify", "tags", "reopen", "supersede", "done", "abandon", "merge", "evidence/replace", "restore", "note", "hold", "hold/release", "question/escalate"].includes(action))
|
|
141
|
+
if (["park", "unpark", "requeue", "decline", "classify", "tags", "reopen", "supersede", "done", "abandon", "merge", "evidence/replace", "restore", "note", "hold", "hold/release", "question/escalate"].includes(action))
|
|
140
142
|
return strings("note");
|
|
141
143
|
}
|
|
142
144
|
if (verb === "POST" && milestone.test(route)) {
|
|
@@ -286,6 +288,10 @@ function expectedStoredText(method, path, body, response) {
|
|
|
286
288
|
const stored = {};
|
|
287
289
|
if (verb === "POST" && /^\/projects\/[^/]+\/work-units\/\d+\/head$/.test(route) && typeof fields.reason === "string")
|
|
288
290
|
stored.reason = fields.reason.trim();
|
|
291
|
+
if (verb === "POST" && /^\/projects\/[^/]+\/work-units\/\d+\/unpark$/.test(route) && typeof fields.note === "string")
|
|
292
|
+
stored.note = fields.note.trim();
|
|
293
|
+
if (verb === "POST" && /^\/projects\/[^/]+\/pause$/.test(route) && typeof fields.note === "string")
|
|
294
|
+
stored.note = fields.note.trim();
|
|
289
295
|
if (verb === "POST" && /^\/projects\/[^/]+\/asks\/[^/]+\/answer$/.test(route) && typeof fields.answer === "string" && fields.answer.trim()) {
|
|
290
296
|
const receipts = Array.isArray(response?.receipts) ? response.receipts : [];
|
|
291
297
|
if (!receipts.some((receipt) => receipt?.field === "answer"))
|
package/dist/commands/admin.js
CHANGED
|
@@ -129,7 +129,9 @@ export async function admin(p, out) {
|
|
|
129
129
|
return;
|
|
130
130
|
}
|
|
131
131
|
case "needs":
|
|
132
|
-
|
|
132
|
+
if (rest.length > 0)
|
|
133
|
+
throw new CliError("usage", "needs [project]");
|
|
134
|
+
return needsAdmin(p, out, action);
|
|
133
135
|
case "flow":
|
|
134
136
|
return flowAdmin(action, rest, p, out);
|
|
135
137
|
case "diag":
|
|
@@ -350,8 +352,23 @@ async function project(action, rest, p, out) {
|
|
|
350
352
|
const r = await c.call("DELETE", `/projects/${rest[0]}`);
|
|
351
353
|
out.print(`deleted project ${rest[0]} and all its data`, r);
|
|
352
354
|
}
|
|
355
|
+
else if ((action === "pause" || action === "resume") && rest.length === 1) {
|
|
356
|
+
const projectName = rest[0];
|
|
357
|
+
const base = `/projects/${encodeURIComponent(projectName)}`;
|
|
358
|
+
if (action === "pause") {
|
|
359
|
+
const note = need(p.flags, "note").trim();
|
|
360
|
+
if (!note)
|
|
361
|
+
throw new CliError("usage", "admin project pause <project> --note \"why it is paused\"");
|
|
362
|
+
const r = await c.call("POST", `${base}/pause`, { note });
|
|
363
|
+
out.print(`Paused project ${projectName} by ${r.paused.by}: ${r.paused.note}`, r);
|
|
364
|
+
}
|
|
365
|
+
else {
|
|
366
|
+
const r = await c.call("POST", `${base}/resume`, {});
|
|
367
|
+
out.print(`Resumed project ${projectName}; stall clocks restart at ${r.resumed_at}.`, r);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
353
370
|
else
|
|
354
|
-
throw new CliError("usage",
|
|
371
|
+
throw new CliError("usage", 'admin project create|list|delete <name> | pause <project> --note "why" | resume <project>');
|
|
355
372
|
}
|
|
356
373
|
async function agent(action, rest, p, out) {
|
|
357
374
|
const c = adminClient(p);
|
|
@@ -571,6 +588,18 @@ async function role(action, rest, p, out) {
|
|
|
571
588
|
throw new CliError("usage", "admin role create|edit|list|delete <name> [--project p] [--projects a,b|*] [--post ch1,ch2] [--broadcast] [--create-channels] [--read-account-status] [--assign-outside-qualifications yes|no] [--judges yes|no] [--description d] [--cardinality one|many]");
|
|
572
589
|
}
|
|
573
590
|
async function workUnitAdmin(action, rest, p, out) {
|
|
591
|
+
if ((action === "park" || action === "unpark") && rest.length === 2 && /^\d+$/.test(rest[1])) {
|
|
592
|
+
const [projectName, numberText] = rest;
|
|
593
|
+
const number = Number(numberText);
|
|
594
|
+
const path = `/projects/${encodeURIComponent(projectName)}/work-units/${number}/${action}`;
|
|
595
|
+
const note = need(p.flags, "note").trim();
|
|
596
|
+
const body = { note };
|
|
597
|
+
if (!note)
|
|
598
|
+
throw new CliError("usage", `admin wu ${action} <project> <n> --note "why ${action === "park" ? "it is parked" : "it is unparked"}"`);
|
|
599
|
+
const r = await adminClient(p).call("POST", path, body);
|
|
600
|
+
out.print(action === "park" ? `Parked WU #${number} in ${projectName}.` : `Unparked WU #${number} in ${projectName}.`, r);
|
|
601
|
+
return;
|
|
602
|
+
}
|
|
574
603
|
if (action === "head" && rest[0] && /^\d+$/.test(rest[1] ?? "")) {
|
|
575
604
|
const project = rest[0];
|
|
576
605
|
const number = Number(rest[1]);
|
|
@@ -632,7 +661,7 @@ async function workUnitAdmin(action, rest, p, out) {
|
|
|
632
661
|
return runRequiredClassUpdate(adminClient(p), rest[0], Number(rest[1]), p, out);
|
|
633
662
|
}
|
|
634
663
|
if (action !== "assign" || !rest[0] || !/^\d+$/.test(rest[1] ?? ""))
|
|
635
|
-
throw new CliError("usage", 'b9s-admin wu assign <project> <n> --to <agent> [--reason "why"] | b9s-admin wu done <project> <n> --merged <sha> [--gate-override-note "why"] | b9s-admin wu merged-sha <project> <n> --sha <full-sha> --reason "why" | b9s-admin wu required-class <project> <n> (--class p/h/m/e | --clear) --reason "why"');
|
|
664
|
+
throw new CliError("usage", 'b9s-admin wu assign <project> <n> --to <agent> [--reason "why"] | park|unpark <project> <n> --note "why" | b9s-admin wu done <project> <n> --merged <sha> [--gate-override-note "why"] | b9s-admin wu merged-sha <project> <n> --sha <full-sha> --reason "why" | b9s-admin wu required-class <project> <n> (--class p/h/m/e | --clear) --reason "why"');
|
|
636
665
|
const to = str(p.flags, "to");
|
|
637
666
|
if (!to)
|
|
638
667
|
throw new CliError("usage", 'b9s-admin wu assign <project> <n> --to <agent> [--reason "why"]');
|
package/dist/commands/agent.js
CHANGED
|
@@ -124,11 +124,11 @@ export async function who(p, out) {
|
|
|
124
124
|
const { client, creds } = agentClient(p);
|
|
125
125
|
const projectStalls = async (project) => {
|
|
126
126
|
const response = await client.call("GET", `/projects/${encodeURIComponent(project)}/work-units?all=1`);
|
|
127
|
-
return (response.units ?? []).filter((unit) => unit.stalled).map((unit) => ({ number: unit.number, owner_name: unit.owner_name,
|
|
127
|
+
return (response.units ?? []).filter((unit) => unit.stalled?.kind === "stalled").map((unit) => ({ number: unit.number, owner_name: unit.owner_name, label: unit.stalled.label, reason: unit.stalled.reason }));
|
|
128
128
|
};
|
|
129
129
|
const statusLines = (statuses, stalled) => statuses.map((status) => {
|
|
130
130
|
const owned = stalled.filter((unit) => unit.owner_name === status.agent_name);
|
|
131
|
-
return `${fmtStatus(status)}${owned.length ? `\n stalled work: ${owned.map((unit) => `WU #${unit.number} · ${unit.
|
|
131
|
+
return `${fmtStatus(status)}${owned.length ? `\n stalled work: ${owned.map((unit) => `WU #${unit.number} · ${unit.label} · ${unit.reason}`).join("; ")}` : ""}`;
|
|
132
132
|
});
|
|
133
133
|
if (bool(p.flags, "account") || (!creds.project && !str(p.flags, "project") && !process.env.BSCHAT_PROJECT)) {
|
|
134
134
|
const [r, me] = await Promise.all([client.call("GET", "/account/agents/status"), client.call("GET", "/me")]);
|
package/dist/commands/hook.js
CHANGED
|
@@ -234,7 +234,7 @@ export async function gatherUpdates(name, opts) {
|
|
|
234
234
|
try {
|
|
235
235
|
const work = await client.call("GET", `/projects/${encodeURIComponent(project)}/work-units?agent=${encodeURIComponent(creds.agent)}`);
|
|
236
236
|
const activeStalls = new Set();
|
|
237
|
-
for (const unit of (work.units ?? []).filter((item) => item.owner_name === creds.agent && item.stalled)) {
|
|
237
|
+
for (const unit of (work.units ?? []).filter((item) => item.owner_name === creds.agent && item.stalled?.kind === "stalled")) {
|
|
238
238
|
const key = `${project}/${unit.number}`;
|
|
239
239
|
activeStalls.add(key);
|
|
240
240
|
const episode = unit.stalled.since;
|
|
@@ -243,7 +243,7 @@ export async function gatherUpdates(name, opts) {
|
|
|
243
243
|
continue;
|
|
244
244
|
}
|
|
245
245
|
if (stalledNext[key] !== episode) {
|
|
246
|
-
stalledLines.push(` ${creds.project ? "" : `[${project}] `}WU #${unit.number}:
|
|
246
|
+
stalledLines.push(` ${creds.project ? "" : `[${project}] `}WU #${unit.number}: ${unit.stalled.label} · ${unit.stalled.reason} — b9s wu show ${creds.project ? "" : `--project ${project} `}${unit.number}`);
|
|
247
247
|
stalledNext[key] = episode;
|
|
248
248
|
}
|
|
249
249
|
}
|
|
@@ -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)");
|
package/dist/commands/machine.js
CHANGED
|
@@ -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
|
}
|
|
@@ -1721,6 +1740,15 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
1721
1740
|
out.push({ id: s.id, state: "error", dir: s.dir, thread: th, watcher: watcherState, error: `its watcher keeps exiting: ${fault}` });
|
|
1722
1741
|
continue;
|
|
1723
1742
|
}
|
|
1743
|
+
// WU #751: mirror the operator's project pause into the agent's state, so its watcher starts no new turn
|
|
1744
|
+
// while the project is paused (a running turn finishes). Written only when it changes.
|
|
1745
|
+
const pausedKey = s.project_paused ? s.project_paused.at : "";
|
|
1746
|
+
if ((state.sessions[s.id].project_paused_applied ?? "") !== pausedKey) {
|
|
1747
|
+
const paused = s.project_paused ?? undefined;
|
|
1748
|
+
updateState(s.agent, (onDisk) => ({ ...onDisk, project_paused: paused }), agentStateEnv);
|
|
1749
|
+
state.sessions[s.id].project_paused_applied = pausedKey;
|
|
1750
|
+
log(`${s.agent}: project ${paused ? `paused since ${paused.at}; no new turns` : "resumed; turns may start"}`);
|
|
1751
|
+
}
|
|
1724
1752
|
// The operator lifted a usage-limit pause: what b9s codex unpause does, here.
|
|
1725
1753
|
if (s.unpause_at && state.sessions[s.id].unpause_applied !== s.unpause_at) {
|
|
1726
1754
|
const unpausedAt = Date.parse(s.unpause_at);
|
|
@@ -2968,7 +2996,7 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
|
|
|
2968
2996
|
const isDarwin = hostPlatform === "darwin";
|
|
2969
2997
|
const pageSizeResult = hostPlatform === "linux"
|
|
2970
2998
|
? spawnSync("getconf", ["PAGESIZE"], { encoding: "utf8", timeout: 2_000 })
|
|
2971
|
-
:
|
|
2999
|
+
: null;
|
|
2972
3000
|
const pageSize = pageSizeResult?.status === 0 ? parsePageSize(pageSizeResult.stdout ?? "") : null;
|
|
2973
3001
|
const macSwapResult = isDarwin ? spawnSync("sysctl", ["-n", "vm.swapusage"], { encoding: "utf8", timeout: 2_000 }) : null;
|
|
2974
3002
|
const macVmStatResult = isDarwin ? spawnSync("vm_stat", [], { encoding: "utf8", timeout: 2_000 }) : null;
|
|
@@ -3690,6 +3718,26 @@ export async function machine(p, out) {
|
|
|
3690
3718
|
}
|
|
3691
3719
|
const m = loadMachine();
|
|
3692
3720
|
const log = (s) => process.stderr.write(`${new Date().toISOString()} b9s machine[${m.name}]: ${s}\n`);
|
|
3721
|
+
if (sub === "diag") {
|
|
3722
|
+
const target = p.positionals[2];
|
|
3723
|
+
if (!target || target !== m.name)
|
|
3724
|
+
throw new CliError("machine_scope", `this daemon is ${m.name}; agents may request diagnostics only from a machine they run on`);
|
|
3725
|
+
const agent = loadAgent(resolveAgentName(str(p.flags, "as"), process.env));
|
|
3726
|
+
const client = Client.forAgent(agent, undefined);
|
|
3727
|
+
const request = await client.call("POST", `/machines/${encodeURIComponent(target)}/diagnostics`, {});
|
|
3728
|
+
const deadline = Date.now() + 120_000;
|
|
3729
|
+
while (Date.now() < deadline) {
|
|
3730
|
+
const current = await client.call("GET", `/machines/${encodeURIComponent(target)}/diagnostics/${encodeURIComponent(request.id)}`);
|
|
3731
|
+
if (current.status === "complete" && current.evidence_id) {
|
|
3732
|
+
const result = { ...current, ref: `evidence:${current.evidence_id}` };
|
|
3733
|
+
return out.print(`Diagnostic evidence: evidence:${current.evidence_id}\nConsole: ${consoleLink("evidence", current.project, current.evidence_id)}`, result);
|
|
3734
|
+
}
|
|
3735
|
+
if (current.status === "expired")
|
|
3736
|
+
throw new CliError("diagnostic_expired", "machine did not return the diagnostic bundle within two minutes");
|
|
3737
|
+
await new Promise((resolve) => setTimeout(resolve, 1_000));
|
|
3738
|
+
}
|
|
3739
|
+
throw new CliError("diagnostic_timeout", `machine diagnostic request timed out; request ${request.id} may still complete`);
|
|
3740
|
+
}
|
|
3693
3741
|
if (sub === "status") {
|
|
3694
3742
|
const desired = (await Client.raw(m.url, m.key).call("GET", "/machines/me")).sessions;
|
|
3695
3743
|
const state = readMachineState();
|
|
@@ -321,17 +321,18 @@ function packetLines(j) {
|
|
|
321
321
|
lines.push("packet: expired or not retained");
|
|
322
322
|
return lines.join("\n");
|
|
323
323
|
}
|
|
324
|
-
export async function needsAdmin(p, out) {
|
|
325
|
-
const r = await adminClient(p).call("GET", "/account/needs");
|
|
324
|
+
export async function needsAdmin(p, out, project) {
|
|
325
|
+
const r = await adminClient(p).call("GET", project ? `/projects/${encodeURIComponent(project)}/needs` : "/account/needs");
|
|
326
326
|
if (!r.needs.length)
|
|
327
|
-
return out.print("Nothing is waiting on you.", r);
|
|
327
|
+
return out.print(project ? `Nothing waiting in ${r.project?.name ?? project}.` : "Nothing is waiting on you.", r);
|
|
328
328
|
const ind = (t) => t.replace(/\n/g, "\n ");
|
|
329
329
|
out.print(r.needs.map((n, i) => [
|
|
330
|
-
`${i + 1}. [${n.project || "Account"}] ${n.display_id ?? (n.kind === "unit_question" ? `WU #${n.unit} question` : "decision id unavailable")} · ${n.kind === "unit_question" ? "unit question" : n.kind === "wake_broken" || n.kind === "wake_unresponsive" ? "wake path" : n.kind === "notifier" ? "your alerts" : n.kind === "machine_report_refused" ? "machine report refused" : n.kind === "machine_session" ? "machine" : n.kind === "lock_silent" ? "silent lock job" : "decision"} · ${n.asked_by} · since ${n.since.slice(0, 16).replace("T", " ")} UTC`,
|
|
330
|
+
`${i + 1}. [${n.project || "Account"}] ${n.display_id ?? (n.kind === "unit_question" ? `WU #${n.unit} question` : n.kind === "sendback_reviewer_gap" ? "send-back reviewer gap" : "decision id unavailable")} · ${n.kind === "unit_question" ? "unit question" : n.kind === "wake_broken" || n.kind === "wake_unresponsive" ? "wake path" : n.kind === "sendback_reviewer_gap" ? "send-back reviewer gap" : n.kind === "notifier" ? "your alerts" : n.kind === "machine_report_refused" ? "machine report refused" : n.kind === "machine_session" ? "machine" : n.kind === "lock_silent" ? "silent lock job" : "decision"} · ${n.asked_by} · since ${n.since.slice(0, 16).replace("T", " ")} UTC`,
|
|
331
331
|
` Console: ${consoleLink("decision", n.project, n.key)}`,
|
|
332
332
|
n.plain ? ` In plain words: ${ind(n.plain)}` : n.unexplained ? ` In plain words: (${n.asked_by} did not explain this; b9s-admin explain ${n.key})` : null,
|
|
333
333
|
n.blocks ? ` What's stuck: ${ind(n.blocks)}` : null,
|
|
334
334
|
` ${n.kind === "ask" ? "What I need from you: " : ""}${ind(n.text)}`,
|
|
335
|
+
n.kind === "sendback_reviewer_gap" ? ` Next: staff ${n.required_role ?? "the send-back reviewer"} at ${n.required_model ?? "the required model"} in the project's Process settings.` : null,
|
|
335
336
|
n.if_yes ? ` If yes: ${ind(n.if_yes)}` : null,
|
|
336
337
|
n.if_no ? ` If no: ${ind(n.if_no)}` : null,
|
|
337
338
|
n.proposal ? ` Proposed by ${n.proposed_by}: ${ind(n.proposal)}` : null,
|
package/dist/commands/watch.js
CHANGED
|
@@ -34,7 +34,7 @@ import { collectPruneProtection } from "../prune-protection.js";
|
|
|
34
34
|
import { bootTimeMs } from "../boot-time.js";
|
|
35
35
|
import { DEFAULT_WATCH_STARTUP_JITTER_SECONDS, MAX_WATCH_STARTUP_JITTER_SECONDS, waitForWatcherStartup } from "../startup-jitter.js";
|
|
36
36
|
import { macMemoryFloorRefusal, parseMemoryEvents } from "../watcher-memory.js";
|
|
37
|
-
import { parseMacVmStat,
|
|
37
|
+
import { parseMacVmStat, parseMacVmStatPageSize } from "../machine-telemetry.js";
|
|
38
38
|
function omitMeasuresAlreadyIn(text, updates) {
|
|
39
39
|
if (!text)
|
|
40
40
|
return updates;
|
|
@@ -1313,12 +1313,11 @@ export function cgroupOomFailureReason(exit, before, after) {
|
|
|
1313
1313
|
? `systemd watcher cgroup OOM-killed the turn (memory.events oom_kill increased from ${before} to ${after})`
|
|
1314
1314
|
: null;
|
|
1315
1315
|
}
|
|
1316
|
-
function macTurnMemoryFloorRefusal() {
|
|
1317
|
-
const
|
|
1318
|
-
const
|
|
1319
|
-
const
|
|
1320
|
-
|
|
1321
|
-
return macMemoryFloorRefusal(totalmem(), memory?.available_bytes ?? null);
|
|
1316
|
+
export function macTurnMemoryFloorRefusal(run = spawnSync, totalMemoryBytes = totalmem()) {
|
|
1317
|
+
const vmStatResult = run("vm_stat", [], { encoding: "utf8", timeout: 2_000 });
|
|
1318
|
+
const vmStat = vmStatResult.status === 0 ? vmStatResult.stdout ?? "" : "";
|
|
1319
|
+
const memory = vmStatResult.status === 0 ? parseMacVmStat(vmStat, parseMacVmStatPageSize(vmStat)) : null;
|
|
1320
|
+
return macMemoryFloorRefusal(totalMemoryBytes, memory?.available_bytes ?? null);
|
|
1322
1321
|
}
|
|
1323
1322
|
function turnMemoryFloorAllows(log) {
|
|
1324
1323
|
if (process.platform !== "darwin")
|
|
@@ -1576,6 +1575,15 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
|
|
|
1576
1575
|
log(`the turn started at ${ph.startedAt} has written nothing for ${Math.round(quietMs / 60_000)} min (over the ${timeoutMin}-min limit); treating it as dead`);
|
|
1577
1576
|
ctl.loggedRunning = ph.startedAt;
|
|
1578
1577
|
}
|
|
1578
|
+
// WU #751: the operator paused this agent's project (the daemon records it from the session list): no new
|
|
1579
|
+
// turn until it is resumed. A running turn was already handled above and finishes on its own.
|
|
1580
|
+
const projectPaused = readState(name).project_paused;
|
|
1581
|
+
if (projectPaused) {
|
|
1582
|
+
if (ctl.loggedRunning !== `paused:${projectPaused.at}`)
|
|
1583
|
+
log(`project paused since ${projectPaused.at.slice(0, 16)}: starting no new turns until it is resumed`);
|
|
1584
|
+
ctl.loggedRunning = `paused:${projectPaused.at}`;
|
|
1585
|
+
return;
|
|
1586
|
+
}
|
|
1579
1587
|
// A maintenance window on this machine: no new turn from 15 min before it until it ends.
|
|
1580
1588
|
const maint = drainingUntil(undefined, undefined, env);
|
|
1581
1589
|
if (maint) {
|
package/dist/commands/wu.js
CHANGED
|
@@ -22,6 +22,7 @@ import { formatStandingRuleSet } from "../standing-rules.js";
|
|
|
22
22
|
import { projectOf } from "./agent.js";
|
|
23
23
|
import { consoleLink } from "../console-links.js";
|
|
24
24
|
import { isAntigravityWorkspaceWrite } from "../antigravity.js";
|
|
25
|
+
const waitAge = (minutes) => minutes < 60 ? `${minutes}m` : minutes < 24 * 60 ? `${Math.floor(minutes / 60)}h` : `${Math.floor(minutes / (24 * 60))}d`;
|
|
25
26
|
/** Only Claude's workspace-write sandbox needs SSH origins rewritten for its HTTP-only proxy. */
|
|
26
27
|
export function shouldInheritClaudeSandboxUrlRewrites(env = process.env) {
|
|
27
28
|
return env.CLAUDECODE === "1" && env.BSCHAT_CLAUDE_SANDBOX === "workspace-write";
|
|
@@ -630,7 +631,8 @@ export async function wu(p, out) {
|
|
|
630
631
|
const reviewers = u.reviewers.map((r) => `${r.name}${r.tags.length ? ` for ${r.tags.map((t) => `#${t}`).join(" ")}` : ""}`).join(", ");
|
|
631
632
|
const approvals = u.approvals.map((a) => a.name).join(", ");
|
|
632
633
|
return [
|
|
633
|
-
`WU #${u.number} [${u.status}]${u.stalled ? ` STALLED ${u.stalled.
|
|
634
|
+
`WU #${u.number} [${u.status}]${u.stalled ? ` ${u.stalled.kind === "stalled" ? "STALLED" : `WAITING ${u.stalled.kind}`} · ${u.stalled.label} · ${u.stalled.reason}` : ""} ${tags(u)} ${u.title}${flags ? ` (${flags})` : ""}${u.requires?.length ? `\n requires: ${u.requires.join(", ")}` : ""}`,
|
|
635
|
+
u.session_requirement ? ` session requirement: ${Object.entries(u.session_requirement).map(([key, value]) => `${key}=${value}`).join(", ")}` : null,
|
|
634
636
|
u.candidate_record?.tags?.length ? ` ${u.candidate_record.agent} first-round approval: ${u.candidate_record.tags.map((x) => `#${x.tag} ${x.approved_first_round}/${x.units} (${Math.round(x.rate * 100)}%)`).join(", ")}` : null,
|
|
635
637
|
` owner ${u.owner_name || "unassigned (queued)"}${reviewers ? ` · reviewers ${reviewers}` : ""}${approvals ? ` · approved by ${approvals}` : ""}${u.uncovered?.length ? ` · awaiting ${u.uncovered.map((t) => `#${t}`).join(" ")}` : ""}`,
|
|
636
638
|
Object.keys(u.tag_focus ?? {}).length ? ` review focus:\n${Object.entries(u.tag_focus).map(([tag, focus]) => ` #${tag}: ${focus}`).join("\n")}` : null,
|
|
@@ -678,6 +680,13 @@ export async function wu(p, out) {
|
|
|
678
680
|
// when require_scope is off and no tagged template requires sections.
|
|
679
681
|
return scope;
|
|
680
682
|
};
|
|
683
|
+
const sessionRequirement = () => {
|
|
684
|
+
const fields = { harness: str(p.flags, "session-harness"), sandbox: str(p.flags, "session-sandbox"), machine: str(p.flags, "session-machine"), machine_label: str(p.flags, "session-machine-label") };
|
|
685
|
+
const entries = Object.entries(fields).filter(([, value]) => value !== undefined);
|
|
686
|
+
if (bool(p.flags, "clear-session") && entries.length)
|
|
687
|
+
throw new CliError("usage", "--clear-session cannot be combined with session requirement flags");
|
|
688
|
+
return bool(p.flags, "clear-session") ? null : entries.length ? Object.fromEntries(entries) : undefined;
|
|
689
|
+
};
|
|
681
690
|
// The project's sparse-checkout exclusions (b9s-admin project checkout), for new worktrees.
|
|
682
691
|
const checkoutExclude = async () => (await client.call("GET", `/projects/${project}/process`)).checkout?.exclude ?? [];
|
|
683
692
|
switch (sub) {
|
|
@@ -694,7 +703,7 @@ export async function wu(p, out) {
|
|
|
694
703
|
const priority = str(p.flags, "priority");
|
|
695
704
|
if (priority !== undefined && priority !== "normal" && priority !== "urgent")
|
|
696
705
|
throw new CliError("usage", "--priority must be urgent or normal");
|
|
697
|
-
const r = await client.call("POST", base, { client_id: clientId, title, scope, ...(str(p.flags, "summary") === undefined ? {} : { plain_summary: str(p.flags, "summary") }), tags: unitTags, requires: list("requires"), evidence: list("evidence"), after: afterUnits(), reworks: list("reworks").map(Number), force: bool(p.flags, "force"), ...(priority ? { priority } : {}), ...symbolicBranchAndHead(), worktree: process.cwd(), target: str(p.flags, "target") ?? null, lands_with: parseLandsWith(str(p.flags, "lands-with")), milestone: str(p.flags, "milestone") ?? null, ...startTelemetry(name) }, { retries: 3 });
|
|
706
|
+
const r = await client.call("POST", base, { client_id: clientId, title, scope, ...(str(p.flags, "summary") === undefined ? {} : { plain_summary: str(p.flags, "summary") }), tags: unitTags, requires: list("requires"), ...(sessionRequirement() === undefined ? {} : { session_requirement: sessionRequirement() }), evidence: list("evidence"), after: afterUnits(), reworks: list("reworks").map(Number), force: bool(p.flags, "force"), ...(priority ? { priority } : {}), ...symbolicBranchAndHead(), worktree: process.cwd(), target: str(p.flags, "target") ?? null, lands_with: parseLandsWith(str(p.flags, "lands-with")), milestone: str(p.flags, "milestone") ?? null, ...startTelemetry(name) }, { retries: 3 });
|
|
698
707
|
const n = r.unit.number;
|
|
699
708
|
const created = createdReceipt(r.unit, r);
|
|
700
709
|
if (r.unit.waiting_on != null) {
|
|
@@ -735,6 +744,8 @@ export async function wu(p, out) {
|
|
|
735
744
|
throw new CliError("usage", 'wu assign "<title>" --to <agent|auto|queue> --scope "<what it covers and does not>" [--scope-file <path> | --scope-from <n>] [--tags a,b] [--after <n>[,<m>]] [--evidence id] [--replay-of <n>]');
|
|
736
745
|
const existingNumber = Number(p.positionals[2]);
|
|
737
746
|
if (Number.isInteger(existingNumber) && existingNumber > 0 && p.positionals.length === 3) {
|
|
747
|
+
if (sessionRequirement() !== undefined)
|
|
748
|
+
throw new CliError("usage", "amend an existing unit session requirement with wu scope before assigning it");
|
|
738
749
|
if (p.flags.after !== undefined)
|
|
739
750
|
throw new CliError("usage", "--after applies when creating a unit; use b9s wu wait to change an existing unit's wait");
|
|
740
751
|
const r = await client.call("POST", `${base}/${existingNumber}/assign`, { to, ...(reason === undefined ? {} : { reason }) });
|
|
@@ -753,7 +764,7 @@ export async function wu(p, out) {
|
|
|
753
764
|
const scope = await scopeText();
|
|
754
765
|
const replay = str(p.flags, "replay-of");
|
|
755
766
|
const clientId = randomUUID();
|
|
756
|
-
const r = await client.call("POST", `${base}/assign`, { client_id: clientId, to, title, scope, ...(str(p.flags, "summary") === undefined ? {} : { plain_summary: str(p.flags, "summary") }), tags: unitTags, requires: list("requires"), evidence: list("evidence"), after: afterUnits(), replay_of: replay ? Number(replay) : null, reworks: list("reworks").map(Number), branch: explicitBranch, ...(baseFlag !== undefined ? { base: baseFlag } : {}), ...(continueFlag ? { continue: true } : {}), target: str(p.flags, "target") ?? null, lands_with: parseLandsWith(str(p.flags, "lands-with")), milestone: str(p.flags, "milestone") ?? null, hold: !!p.flags.hold, force: bool(p.flags, "force"), ...(priority ? { priority } : {}), ...(reason === undefined ? {} : { reason }) }, { retries: 3 });
|
|
767
|
+
const r = await client.call("POST", `${base}/assign`, { client_id: clientId, to, title, scope, ...(str(p.flags, "summary") === undefined ? {} : { plain_summary: str(p.flags, "summary") }), tags: unitTags, requires: list("requires"), ...(sessionRequirement() === undefined ? {} : { session_requirement: sessionRequirement() }), evidence: list("evidence"), after: afterUnits(), replay_of: replay ? Number(replay) : null, reworks: list("reworks").map(Number), branch: explicitBranch, ...(baseFlag !== undefined ? { base: baseFlag } : {}), ...(continueFlag ? { continue: true } : {}), target: str(p.flags, "target") ?? null, lands_with: parseLandsWith(str(p.flags, "lands-with")), milestone: str(p.flags, "milestone") ?? null, hold: !!p.flags.hold, force: bool(p.flags, "force"), ...(priority ? { priority } : {}), ...(reason === undefined ? {} : { reason }) }, { retries: 3 });
|
|
757
768
|
const clientWarnings = [];
|
|
758
769
|
if (explicitBranch && baseFlag === undefined && repoName() && hasRemote("origin")) {
|
|
759
770
|
const remoteState = inspectRemoteBranch(explicitBranch);
|
|
@@ -1011,6 +1022,16 @@ export async function wu(p, out) {
|
|
|
1011
1022
|
}
|
|
1012
1023
|
case "scope": {
|
|
1013
1024
|
const note = str(p.flags, "note");
|
|
1025
|
+
const session = sessionRequirement();
|
|
1026
|
+
if (session !== undefined) {
|
|
1027
|
+
if (!note?.trim())
|
|
1028
|
+
throw new CliError("usage", "wu scope session requirement needs --note");
|
|
1029
|
+
if (str(p.flags, "scope") !== undefined || str(p.flags, "scope-file") !== undefined || str(p.flags, "scope-from") !== undefined || bool(p.flags, "replace") || str(p.flags, "append") !== undefined)
|
|
1030
|
+
throw new CliError("usage", "amend the session requirement separately from scope text");
|
|
1031
|
+
const r = await client.call("POST", `${base}/${num()}/scope`, { session_requirement: session, note });
|
|
1032
|
+
out.print(`${fmt(r.unit)}\nSession requirement amended.`, r);
|
|
1033
|
+
return;
|
|
1034
|
+
}
|
|
1014
1035
|
const hasScopeSource = str(p.flags, "scope") !== undefined || str(p.flags, "scope-file") !== undefined || str(p.flags, "scope-from") !== undefined;
|
|
1015
1036
|
const hasEditMode = bool(p.flags, "replace") || str(p.flags, "append") !== undefined;
|
|
1016
1037
|
if (Number(hasScopeSource) + Number(hasEditMode) !== 1)
|
|
@@ -1493,10 +1514,12 @@ export async function wu(p, out) {
|
|
|
1493
1514
|
}
|
|
1494
1515
|
case "stalled": {
|
|
1495
1516
|
const response = await client.call("GET", `${base}?all=1`);
|
|
1496
|
-
const
|
|
1497
|
-
const
|
|
1498
|
-
|
|
1499
|
-
|
|
1517
|
+
const includeAll = p.flags.all === true;
|
|
1518
|
+
const units = response.units.filter((unit) => unit.stalled && (includeAll || unit.stalled.kind === "stalled" || unit.stalled.overdue))
|
|
1519
|
+
.sort((a, b) => Number(b.stalled.kind === "stalled") - Number(a.stalled.kind === "stalled") || b.stalled.age_minutes - a.stalled.age_minutes || a.number - b.number);
|
|
1520
|
+
const rows = units.map((unit) => ({ n: `#${unit.number}`, kind: unit.stalled.kind, age: waitAge(unit.stalled.age_minutes), status: unit.status, owner: unit.owner_name || "unassigned", label: unit.stalled.label, reason: unit.stalled.reason, title: unit.title }));
|
|
1521
|
+
out.print(rows.length ? table(rows, ["n", "kind", "age", "status", "owner", "label", "reason", "title"]) : `(no ${includeAll ? "waiting or stalled" : "stalled or overdue"} work units)`, { project, units });
|
|
1522
|
+
if (units.some((unit) => unit.stalled.kind === "stalled"))
|
|
1500
1523
|
process.exitCode = 1;
|
|
1501
1524
|
return;
|
|
1502
1525
|
}
|
package/dist/help.js
CHANGED
|
@@ -73,10 +73,10 @@ Agent commands
|
|
|
73
73
|
b9s rule supersede <rule-id> --text "..." [--step cut|start|submit|verdict|merge|close] [--expires-at <UTC>] [--conflicts-with id,id] --confirm-compatible
|
|
74
74
|
b9s rule retire <rule-id> authorized assigner; project agent credentials restrict scope
|
|
75
75
|
review current charter/agreements before --confirm-compatible; no rule is inferred from chat
|
|
76
|
-
b9s wu open "<title>" --scope "..." [--summary "plain work summary"] [--scope-file <path> | --scope-from <n>] [--tags a,b] [--lands-with <n>] [--reworks n,m] [--after <n>[,<m>]] [--requires cap,cap] [--priority urgent|normal] [--milestone <key>] [--force] [--evidence id[,id...]] [--target <branch>] [--here] [--json] open a work unit in its own
|
|
76
|
+
b9s wu open "<title>" --scope "..." [--summary "plain work summary"] [--scope-file <path> | --scope-from <n>] [--tags a,b] [--lands-with <n>] [--reworks n,m] [--after <n>[,<m>]] [--requires cap,cap] [--session-harness h] [--session-sandbox mode] [--session-machine name] [--session-machine-label label] [--priority urgent|normal] [--milestone <key>] [--force] [--evidence id[,id...]] [--target <branch>] [--here] [--json] open a work unit in its own
|
|
77
77
|
worktree; tags come from the vocabulary; --target is the branch it lands in (default: the
|
|
78
78
|
process target), e.g. a lane branch; wu target <n> <branch|default> changes it before review
|
|
79
|
-
b9s wu assign "<title>" --to <agent|auto|queue> --scope ".." [--summary "plain work summary"] [--scope-file <path> | --scope-from <n>] [--tags a,b] [--lands-with <n>] [--reworks n,m] [--after <n>[,<m>]] [--requires cap,cap] [--priority urgent|normal] [--milestone <key>] [--branch <branch>] [--base <branch-or-sha>] [--continue] [--hold] [--evidence id[,id...]] [--force] [--replay-of n] [--template] [--reason "why"] [--json] hand out a unit (assigner roles);
|
|
79
|
+
b9s wu assign "<title>" --to <agent|auto|queue> --scope ".." [--summary "plain work summary"] [--scope-file <path> | --scope-from <n>] [--tags a,b] [--lands-with <n>] [--reworks n,m] [--after <n>[,<m>]] [--requires cap,cap] [--session-harness h] [--session-sandbox mode] [--session-machine name] [--session-machine-label label] [--priority urgent|normal] [--milestone <key>] [--branch <branch>] [--base <branch-or-sha>] [--continue] [--hold] [--evidence id[,id...]] [--force] [--replay-of n] [--template] [--reason "why"] [--json] hand out a unit (assigner roles);
|
|
80
80
|
--to auto picks the active qualified worker with the lightest load; it queues when nobody fits,
|
|
81
81
|
reports why candidates were passed over, and the sweep chases it;
|
|
82
82
|
--to queue waits deliberately; naming a busy worker reserves it for them (theirs when free,
|
|
@@ -178,6 +178,7 @@ Machine placement enforces configured session slots and reports machine pressure
|
|
|
178
178
|
owner, assigner or operator: wait for any non-closed unit; released when it closes
|
|
179
179
|
b9s wu wait <n> --on "evidence|unit #m|ask id|machine name|text blocker" --note "why" [--partial "verdict"] | --clear
|
|
180
180
|
owner or reviewer: pause review on a named blocker; reviewer may record a partial verdict
|
|
181
|
+
b9s wu scope <n> [--session-harness h] [--session-sandbox mode] [--session-machine name] [--session-machine-label label] [--clear-session] --note "why" amend the required session separately from scope text
|
|
181
182
|
b9s wu scope <n> --scope ".." | --scope-file <path> | --scope-from <n> --note ".." [--summary "..." | --plain-summary "..."] assigner or operator: replace the full scope; recorded and announced
|
|
182
183
|
b9s wu scope <n> --replace "<old>" "<new>" --note ".." replace one exact, unique substring of the scope
|
|
183
184
|
b9s wu scope <n> --append ".." --note ".." add a dated scope amendment (up to 2000 chars); the base scope stays capped at 4000
|
|
@@ -207,7 +208,7 @@ Machine placement enforces configured session slots and reports machine pressure
|
|
|
207
208
|
b9s wu recovery restore <n> next owner: verify and restore the restricted recovery bundle into the unit worktree
|
|
208
209
|
b9s wu abandon <n> [--note ..] wu list [--all] [--json] for state and timeline (JSON keeps complete titles)
|
|
209
210
|
b9s wu list [--all] [--status s] [--tag t] [--agent name] list visible work units; --all includes closed units
|
|
210
|
-
b9s wu stalled
|
|
211
|
+
b9s wu stalled [--all] list stalled and overdue waits (or all wait kinds); KIND column; exits 1 only for true stalls
|
|
211
212
|
b9s worktrees prune [--yes] [--archive] remove clean, fully pushed worktrees whose work landed or whose unit is closed (dry run without --yes);
|
|
212
213
|
--archive also saves a closed unit's uncommitted files to archive/wu<n>-leftovers and removes it;
|
|
213
214
|
refused in Antigravity workspace-write: watcher processes queued wu done worktrees at turn finalization; prune retained or abandoned worktrees from an unrestricted checkout
|
|
@@ -281,6 +282,7 @@ Machine placement enforces configured session slots and reports machine pressure
|
|
|
281
282
|
b9s machine once run one daemon cycle
|
|
282
283
|
b9s machine build-images run pending image builds
|
|
283
284
|
b9s machine status show daemon state
|
|
285
|
+
b9s machine diag <machine> [--as <project>/<agent>] request and wait for a safe machine diagnostic evidence bundle
|
|
284
286
|
b9s machine prepare [--codex-userns] [--bwrap-userns] [--agy-userns] [--print-hooks] [--print-apparmor] check machine readiness and required sandbox profiles
|
|
285
287
|
--agy-userns opts into an AppArmor
|
|
286
288
|
profile for the resolved agy binary if Ubuntu blocks its workspace-write terminal sandbox (passwordless sudo)
|
|
@@ -356,6 +358,7 @@ Successful writes verify stored-text receipts. If a 2xx write receipt mismatches
|
|
|
356
358
|
the returned object and warning, then exits 3. Inspect the object and do not retry that write.
|
|
357
359
|
Options are command-scoped; unsupported options are usage errors before command execution.
|
|
358
360
|
Use --admin <nickname> to select one of this machine's saved operator identities.
|
|
361
|
+
Project agents inspect work waits with b9s wu stalled [--all]; its default includes true stalls and overdue waits, while --all includes every recorded wait kind.
|
|
359
362
|
|
|
360
363
|
b9s-admin login [--as <nickname>] [--url <api>]
|
|
361
364
|
prints a link and a code and opens it: approve it in a browser already signed in to BenignSwarm
|
|
@@ -367,6 +370,7 @@ Use --admin <nickname> to select one of this machine's saved operator identities
|
|
|
367
370
|
b9s-admin text-check <project> find bschat mentions in working agreements, charter, tags, roles and open scopes
|
|
368
371
|
b9s-admin signup --url <api> --key <signup-code> <account-name> <email>
|
|
369
372
|
b9s-admin project create|list|delete <name>
|
|
373
|
+
b9s-admin project pause <project> --note "why" | resume <project> stop dispatch, steward actions, escalations, stall faults and new turns; queued and assigned work stays unchanged
|
|
370
374
|
b9s-admin github status | disconnect <installation-id>
|
|
371
375
|
b9s-admin project github <project> status | unlink
|
|
372
376
|
b9s-admin project hosted-merge <project> enable [--confirm-bypass-signal]
|
|
@@ -419,6 +423,7 @@ Use --admin <nickname> to select one of this machine's saved operator identities
|
|
|
419
423
|
b9s-admin role edit <name> [--project p] [--projects a,b|*] [--post c1,c2] [--broadcast] [--create-channels] [--read-account-status] [--assign-outside-qualifications yes|no] [--description d] [--cardinality one|many]
|
|
420
424
|
b9s-admin role list [--project p]
|
|
421
425
|
b9s-admin wu assign <project> <n> --to <agent> [--reason "why"] operator: reassign a unit in place
|
|
426
|
+
b9s-admin wu park|unpark <project> <n> --note "why" operator: park open or sent-back work, or return parked work to open
|
|
422
427
|
b9s-admin wu done <project> <n> --merged <sha> [--gate-override-note "why"] [--note "context"] operator: close approved work; missing receipt override requires a recorded reason
|
|
423
428
|
b9s-admin wu done <project> <n> --no-source --evidence id[,id...] --no-commits-beyond-target [--gate-override-note "why"] operator: close evidence-only work after confirming no commits beyond target
|
|
424
429
|
b9s-admin wu merged-sha <project> <n> --sha <full-40-character-lowercase-sha> --reason "why" operator: correct a legacy abbreviated merged SHA with an audited reason
|
|
@@ -470,7 +475,7 @@ Use --admin <nickname> to select one of this machine's saved operator identities
|
|
|
470
475
|
--assign-outside-qualifications yes|no allow assigners in this role to make reasoned ownership exceptions; dispatch stays qualified
|
|
471
476
|
--judges yes|no the turn-judge capability: this role may be chosen as the independent judge (docs/TURN-JUDGE.md)
|
|
472
477
|
b9s-admin obligations [--project p] [--overdue] who acts next and by when; unknown deadlines name their reason
|
|
473
|
-
b9s-admin needs
|
|
478
|
+
b9s-admin needs [project] needs for one project, or all projects with decision/WU/fault IDs and Console links
|
|
474
479
|
Browser conditional actions and retry receipts: docs/NEEDS-BROWSER-ACTIONS.md; console work #555/#556
|
|
475
480
|
b9s-admin answer <id or key> "decision" answer one; the asker is @mentioned and a Console link is printed
|
|
476
481
|
b9s-admin answer <id or key> --approve [--assign <agent>] [--note ".."] accept an ask proposal and name its action owner
|
|
@@ -501,6 +506,7 @@ Machines (provisioned over your own ssh; a daemon on each runs the agent session
|
|
|
501
506
|
install a profile only for the resolved ~/.local/bin/agy (Antigravity terminal sandbox)
|
|
502
507
|
b9s-admin machine list
|
|
503
508
|
b9s-admin machine show <name>
|
|
509
|
+
b9s-admin machine diag <name> request and wait for the daemon's redacted diagnostic evidence bundle
|
|
504
510
|
b9s-admin machine remove <name> [--preview] [--confirm <name> --impact-revision <revision>]
|
|
505
511
|
show includes host readiness, configured disk floors and named readiness refusals; removal previews sessions, work, keys, recovery blockers and replanned slots
|
|
506
512
|
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
|
+
}
|
|
@@ -157,7 +157,7 @@ export function machineResourceTelemetry(hostPlatform, readText, pageSizeBytes,
|
|
|
157
157
|
const memoryText = linux ? readText("/proc/meminfo") : null;
|
|
158
158
|
const linuxMemory = memoryText ? parseLinuxMemory(memoryText) : null;
|
|
159
159
|
const macSwap = darwin && macSwapUsage !== null ? parseMacSwapUsage(macSwapUsage) : null;
|
|
160
|
-
const macMemory = darwin && macVmStat !== null ? parseMacVmStat(macVmStat,
|
|
160
|
+
const macMemory = darwin && macVmStat !== null ? parseMacVmStat(macVmStat, parseMacVmStatPageSize(macVmStat)) : null;
|
|
161
161
|
const vmstat = linux ? parseLinuxSwapCounters(readText("/proc/vmstat") ?? "", pageSizeBytes) : { in_bytes_total: null, out_bytes_total: null };
|
|
162
162
|
const pressure = (kind) => linux ? parsePressureStall(readText(`/proc/pressure/${kind}`) ?? "") : null;
|
|
163
163
|
const memoryPressure = pressure("memory");
|
|
@@ -238,3 +238,8 @@ export function parsePageSize(content) {
|
|
|
238
238
|
const value = Number(content.trim());
|
|
239
239
|
return Number.isSafeInteger(value) && value > 0 ? value : null;
|
|
240
240
|
}
|
|
241
|
+
/** Read the kernel page size from vm_stat's own header so its page counts stay self-consistent. */
|
|
242
|
+
export function parseMacVmStatPageSize(content) {
|
|
243
|
+
const match = /^Mach Virtual Memory Statistics: \(page size of (\d+) bytes\)\s*$/m.exec(content);
|
|
244
|
+
return match ? parsePageSize(match[1]) : null;
|
|
245
|
+
}
|
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
|
-
|
|
367
|
-
|
|
368
|
-
|
|
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.
|
|
1
|
+
export const CLI_VERSION = "0.12.156";
|