benignswarm 0.12.111 → 0.12.112
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/antigravity.js +3 -1
- package/dist/client.js +2 -2
- package/dist/commands/install.js +77 -13
- package/dist/commands/join.js +3 -5
- package/dist/commands/lists.js +2 -2
- package/dist/commands/machine-admin.js +5 -2
- package/dist/commands/machine.js +175 -33
- package/dist/commands/watch.js +3 -3
- package/dist/commands/worktrees.js +1 -1
- package/dist/commands/wu.js +4 -2
- package/dist/git.js +57 -4
- package/dist/harnesses.js +1 -1
- package/dist/help.js +3 -0
- package/dist/install.js +122 -24
- package/dist/lock.js +2 -1
- package/dist/log-rotation.js +65 -0
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/dist/antigravity.js
CHANGED
|
@@ -110,7 +110,9 @@ export function antigravityTurnEnv(sandbox, b9sBin) {
|
|
|
110
110
|
if (sandbox !== "workspace-write")
|
|
111
111
|
return { BSCHAT_HARNESS: "antigravity", BSCHAT_ANTIGRAVITY_SANDBOX: sandbox };
|
|
112
112
|
const path = b9sBin ? antigravityPath(b9sBin) : [...new Set([dirname(process.execPath), ...(process.env.PATH ?? "").split(delimiter).filter(Boolean)])].join(delimiter);
|
|
113
|
-
|
|
113
|
+
// Antigravity supplies its restricted outbound proxy to sandboxed commands. Node's fetch
|
|
114
|
+
// ignores the proxy environment unless opted in; b9s uses fetch for authenticated API calls.
|
|
115
|
+
return { BSCHAT_HARNESS: "antigravity", BSCHAT_ANTIGRAVITY_SANDBOX: sandbox, NODE_USE_ENV_PROXY: "1", PATH: path };
|
|
114
116
|
}
|
|
115
117
|
export function runAntigravityTurn(bin, args, logPath, cwd, agent, expectedConversation, run = spawnSync, envOverride = {}) {
|
|
116
118
|
const started = new Date().toISOString();
|
package/dist/client.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { CliError, WrittenReceiptMismatchError } from "./errors.js";
|
|
3
|
-
import { collectAuto } from "./git.js";
|
|
3
|
+
import { collectAuto, machineIdentityForAgent } from "./git.js";
|
|
4
4
|
import { resolveEffort } from "./model.js";
|
|
5
5
|
import { cliUserAgent } from "./legacy-alias.js";
|
|
6
6
|
import { noteServerVersions } from "./update.js";
|
|
@@ -276,7 +276,7 @@ export class Client {
|
|
|
276
276
|
* by the hook or the watcher, which say nothing about whether the agent is alive.
|
|
277
277
|
*/
|
|
278
278
|
static forAgent(c, model, opts = {}) {
|
|
279
|
-
const auto = collectAuto({ model, machine: c.machine, effort: resolveEffort(opts.effort, process.env, c.vendor), provider: process.env.BSCHAT_PROVIDER });
|
|
279
|
+
const auto = collectAuto({ model, machine: machineIdentityForAgent(c.machine), effort: resolveEffort(opts.effort, process.env, c.vendor), provider: process.env.BSCHAT_PROVIDER });
|
|
280
280
|
return new Client(c.url, c.key, opts.presence === false ? null : { ...auto }, c.agent, opts.machineIdentity ? auto.machine : null);
|
|
281
281
|
}
|
|
282
282
|
static forAdmin(c) {
|
package/dist/commands/install.js
CHANGED
|
@@ -5,7 +5,7 @@ import { basename, delimiter, join } from "node:path";
|
|
|
5
5
|
import { homedir, platform } from "node:os";
|
|
6
6
|
import { bool } from "../args.js";
|
|
7
7
|
import { CliError } from "../errors.js";
|
|
8
|
-
import { binVersion, ensureCommandLinks, ensureInstall, latestPublished, lingerEnabled, readInstall, restartInstallServices, watcherServices } from "../install.js";
|
|
8
|
+
import { binVersion, ensureCommandLinks, ensureInstall, latestPublished, launchdLoadedIn, launchdPid, launchdSessionNow, lingerEnabled, ownNpm, plistLaunchdDomain, readInstall, restartInstallServices, watcherServices } from "../install.js";
|
|
9
9
|
import { CLI_VERSION } from "../version.js";
|
|
10
10
|
import { CODEX_REQUIREMENTS_PATH, codexHooksDuplicateWithManagedPolicy, reconcileCodexHooks, refreshInstalledHooks } from "../harness.js";
|
|
11
11
|
import { configRoot } from "../config.js";
|
|
@@ -20,8 +20,9 @@ export async function install(p, out) {
|
|
|
20
20
|
const want = p.positionals[1];
|
|
21
21
|
if (want && !/^\d+\.\d+\.\d+$/.test(want))
|
|
22
22
|
throw new CliError("usage", "install [<version> | --latest] e.g. b9s install --latest, b9s install 0.12.38");
|
|
23
|
-
|
|
24
|
-
const
|
|
23
|
+
// Explicit install is the only command that may move the machine record to this Node's npm.
|
|
24
|
+
const npm = ownNpm();
|
|
25
|
+
const version = want ?? (bool(p.flags, "latest") ? latestPublished(npm) : CLI_VERSION);
|
|
25
26
|
const rec = ensureInstall(version, (m) => process.stderr.write(`b9s: ${m}\n`), npm);
|
|
26
27
|
const lines = [`b9s ${rec.version} is this machine's install: ${rec.bin}`];
|
|
27
28
|
const aliases = ensureCommandLinks(rec.bin);
|
|
@@ -32,7 +33,7 @@ export async function install(p, out) {
|
|
|
32
33
|
const managedCodex = reconcileCodexHooks(rec.bin, false);
|
|
33
34
|
if (managedCodex.managed && managedCodex.changed && managedCodex.path)
|
|
34
35
|
lines.push(`Removed duplicate Codex hook registration from ${managedCodex.path}; ${CODEX_REQUIREMENTS_PATH} already registers it.`);
|
|
35
|
-
const refreshedHooks =
|
|
36
|
+
const refreshedHooks = refreshInstalledHooks(process.cwd(), rec.bin);
|
|
36
37
|
if (refreshedHooks.length)
|
|
37
38
|
lines.push(`Updated harness hooks: ${refreshedHooks.join(", ")}`);
|
|
38
39
|
if (prev && prev.bin !== rec.bin)
|
|
@@ -50,6 +51,28 @@ export async function install(p, out) {
|
|
|
50
51
|
lines.push(`Not restarted:\n ${elsewhere.join("\n ")}`);
|
|
51
52
|
out.print(lines.join("\n"), { install: rec, restarted, not_restarted: elsewhere });
|
|
52
53
|
}
|
|
54
|
+
export function embeddedHookCommands(value, marker) {
|
|
55
|
+
const found = [];
|
|
56
|
+
const visit = (item) => {
|
|
57
|
+
if (!item || typeof item !== "object")
|
|
58
|
+
return;
|
|
59
|
+
if (Array.isArray(item)) {
|
|
60
|
+
item.forEach(visit);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
for (const [key, child] of Object.entries(item)) {
|
|
64
|
+
if (key === "command" && typeof child === "string" && child.includes(marker))
|
|
65
|
+
found.push(child.replace(/ --event \w+$/, ""));
|
|
66
|
+
else
|
|
67
|
+
visit(child);
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
visit(value);
|
|
71
|
+
return [...new Set(found)];
|
|
72
|
+
}
|
|
73
|
+
export function hookUsesRecordedInstall(command, bin) {
|
|
74
|
+
return command === bin || command === `'${bin}'` || command.startsWith(`${bin} `) || command.startsWith(`'${bin}' `);
|
|
75
|
+
}
|
|
53
76
|
function diagnosticSpace(path) {
|
|
54
77
|
try {
|
|
55
78
|
const stat = statfsSync(path);
|
|
@@ -193,21 +216,59 @@ export async function doctor(_p, out) {
|
|
|
193
216
|
}
|
|
194
217
|
const sp = join(root, ".claude", "settings.local.json");
|
|
195
218
|
if (existsSync(sp)) {
|
|
196
|
-
const hooks = JSON.
|
|
197
|
-
const cmds =
|
|
219
|
+
const hooks = JSON.parse(readFileSync(sp, "utf8")).hooks ?? {};
|
|
220
|
+
const cmds = embeddedHookCommands(hooks, "hook claude-code");
|
|
198
221
|
for (const c of cmds) {
|
|
199
|
-
const good = !!rec && (c
|
|
222
|
+
const good = !!rec && hookUsesRecordedInstall(c, rec.bin);
|
|
200
223
|
checks.push({ ok: good, what: `Claude Code hook in ${sp}: ${c}`, fix: good ? undefined : "b9s setup --as <your agent> (rewrites the hook to the recorded install)" });
|
|
201
224
|
}
|
|
202
225
|
}
|
|
203
226
|
checks.push(...claudeSessionChecks());
|
|
227
|
+
const codexHooks = join(process.env.CODEX_HOME ?? join(homedir(), ".codex"), "hooks.json");
|
|
228
|
+
const antigravityHooks = join(root, ".agents", "hooks.json");
|
|
229
|
+
for (const [path, marker, label, fix] of [
|
|
230
|
+
[codexHooks, "hook codex", "Codex", "b9s codex hooks (rewrites the hook to the recorded install)"],
|
|
231
|
+
[antigravityHooks, "hook antigravity", "Antigravity", "b9s setup --as <your agent> --vendor antigravity (rewrites the hook to the recorded install)"],
|
|
232
|
+
])
|
|
233
|
+
if (existsSync(path)) {
|
|
234
|
+
let hooks;
|
|
235
|
+
try {
|
|
236
|
+
hooks = JSON.parse(readFileSync(path, "utf8"));
|
|
237
|
+
}
|
|
238
|
+
catch {
|
|
239
|
+
throw new CliError("bad_settings", `${path} is not valid JSON; fix it or remove it`);
|
|
240
|
+
}
|
|
241
|
+
for (const command of embeddedHookCommands(hooks, marker)) {
|
|
242
|
+
const good = !!rec && hookUsesRecordedInstall(command, rec.bin);
|
|
243
|
+
checks.push({ ok: good, what: `${label} hook in ${path}: ${command}`, fix: good ? undefined : fix });
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
if (existsSync(CODEX_REQUIREMENTS_PATH)) {
|
|
247
|
+
const policy = readFileSync(CODEX_REQUIREMENTS_PATH, "utf8");
|
|
248
|
+
const commands = [...new Set([...policy.matchAll(/command\s*=\s*"([^"]*hook codex[^"]*)"/g)].map((match) => match[1].replace(/ --event \w+$/, "")))];
|
|
249
|
+
for (const command of commands) {
|
|
250
|
+
const good = !!rec && hookUsesRecordedInstall(command, rec.bin);
|
|
251
|
+
checks.push({ ok: good, what: `managed Codex hook in ${CODEX_REQUIREMENTS_PATH}: ${command}`, fix: good ? undefined : `update the managed Codex hook to ${rec?.bin ?? "the recorded install"}` });
|
|
252
|
+
}
|
|
253
|
+
}
|
|
204
254
|
for (const f of ["AGENTS.md", "GEMINI.md", join(".agents", "rules", "bschat.md")]) {
|
|
205
255
|
const fp = join(root, f);
|
|
206
|
-
if (existsSync(fp)
|
|
207
|
-
|
|
256
|
+
if (existsSync(fp)) {
|
|
257
|
+
const text = readFileSync(fp, "utf8");
|
|
258
|
+
if (text.includes("npx -y benignswarm"))
|
|
259
|
+
checks.push({ ok: false, what: `${fp} tells agents to use npx`, fix: "b9s setup --as <the agent of that harness> (rewrites it to the recorded install)" });
|
|
260
|
+
const pointer = /recorded install at `([^`]+)`/.exec(text)?.[1];
|
|
261
|
+
if (pointer && rec && pointer !== rec.bin)
|
|
262
|
+
checks.push({ ok: false, what: `${fp} points at ${pointer}, not the recorded install ${rec.bin}`, fix: "b9s setup --as <the agent of that harness> (rewrites the pointer to the recorded install)" });
|
|
263
|
+
}
|
|
208
264
|
}
|
|
209
265
|
// Watchers: what the definition says versus what is running.
|
|
210
266
|
const uid = process.getuid?.();
|
|
267
|
+
if (process.platform === "darwin") {
|
|
268
|
+
checks.push(launchdSessionNow() === "gui"
|
|
269
|
+
? { ok: true, what: "launchd: desktop session (services in the gui domain)" }
|
|
270
|
+
: { ok: true, what: "launchd: headless Mac (no desktop session): services run as Background agents in the user domain; after a reboot an SSH login (FileVault unlock) is needed before they start" });
|
|
271
|
+
}
|
|
211
272
|
const services = watcherServices();
|
|
212
273
|
if (services.some((s) => s.kind === "systemd") && lingerEnabled() === false)
|
|
213
274
|
checks.push({ ok: false, what: "linger is off: systemd stops the watchers when your last login session on this machine ends", fix: "loginctl enable-linger $USER" });
|
|
@@ -227,18 +288,21 @@ export async function doctor(_p, out) {
|
|
|
227
288
|
continue;
|
|
228
289
|
}
|
|
229
290
|
const short = w.label.replace("org.benignswarm.watch.", "");
|
|
230
|
-
const
|
|
291
|
+
const domain = plistLaunchdDomain(w.path);
|
|
292
|
+
const reload = `launchctl bootout ${domain}/${w.label}; launchctl bootstrap ${domain} ${w.path}`;
|
|
231
293
|
if (!args.length) {
|
|
232
294
|
checks.push({ ok: false, what: `watcher ${short}: unreadable plist ${w.path}` });
|
|
233
295
|
continue;
|
|
234
296
|
}
|
|
235
|
-
const
|
|
236
|
-
const
|
|
297
|
+
const loadedIn = launchdLoadedIn(w.label);
|
|
298
|
+
const listed = { status: loadedIn.length ? 0 : 1 };
|
|
299
|
+
const pidNum = launchdPid(w.label);
|
|
300
|
+
const pid = pidNum === null ? undefined : String(pidNum);
|
|
237
301
|
const ver = binVersion(args[0]);
|
|
238
302
|
if (rec && args[0] !== rec.bin)
|
|
239
303
|
checks.push({ ok: false, what: `watcher ${short} runs ${args[0]} (${ver ?? "does not run"}), not the recorded install`, fix: "re-run its b9s watch ... --launchd (it uses the recorded install and reloads)" });
|
|
240
304
|
if (listed.status !== 0) {
|
|
241
|
-
checks.push({ ok: false, what: `watcher ${short} is not loaded (a login or reboot loads it)`, fix: `launchctl bootstrap
|
|
305
|
+
checks.push({ ok: false, what: `watcher ${short} is not loaded (a login or reboot loads it)`, fix: `launchctl bootstrap ${domain} ${w.path} (or delete the plist if the agent is gone)` });
|
|
242
306
|
continue;
|
|
243
307
|
}
|
|
244
308
|
if (!pid) {
|
package/dist/commands/join.js
CHANGED
|
@@ -2,11 +2,11 @@ import { cliUserAgent } from "../legacy-alias.js";
|
|
|
2
2
|
import { need, str, bool } from "../args.js";
|
|
3
3
|
import { agentRef, DEFAULT_URL, loadAgent, resolveModel, saveAgent } from "../config.js";
|
|
4
4
|
import { spawnSync } from "node:child_process";
|
|
5
|
-
import {
|
|
5
|
+
import { readFileSync } from "node:fs";
|
|
6
6
|
import { join as pathJoin } from "node:path";
|
|
7
7
|
import { CliError } from "../errors.js";
|
|
8
8
|
import { defaultMachine } from "../git.js";
|
|
9
|
-
import {
|
|
9
|
+
import { ensureMachineInstall } from "../install.js";
|
|
10
10
|
import { claudeCheckoutOwner, claudeCheckoutTaken, reconcileCodexHooks, HARNESSES, findIdentityFile, installForHarness, normalizeVendor, readIdentityFile, writeIdentity } from "../harness.js";
|
|
11
11
|
import { detectVendor } from "../vendor.js";
|
|
12
12
|
import { CLI_VERSION } from "../version.js";
|
|
@@ -196,9 +196,7 @@ export function assertVendorMatchesRepo(root, name, vendor, replace) {
|
|
|
196
196
|
* the npm next to the running Node.
|
|
197
197
|
*/
|
|
198
198
|
function machineInstall() {
|
|
199
|
-
|
|
200
|
-
const npm = prev?.npm && existsSync(prev.npm) ? prev.npm : undefined;
|
|
201
|
-
return ensureInstall(CLI_VERSION, (m) => process.stderr.write(`b9s: ${m}\n`), npm);
|
|
199
|
+
return ensureMachineInstall(CLI_VERSION, (m) => process.stderr.write(`b9s: ${m}\n`));
|
|
202
200
|
}
|
|
203
201
|
function writeIdentityDryRun(root, vendor, name, replace) {
|
|
204
202
|
const p = findIdentityFile(root);
|
package/dist/commands/lists.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { readFileSync } from "node:fs";
|
|
2
|
-
import { hostname } from "node:os";
|
|
3
2
|
import { spawnSync } from "node:child_process";
|
|
4
3
|
import { bool, str } from "../args.js";
|
|
5
4
|
import { Client } from "../client.js";
|
|
6
5
|
import { loadAgent, resolveAgentName, resolveModel } from "../config.js";
|
|
7
6
|
import { CliError } from "../errors.js";
|
|
8
7
|
import { table } from "../output.js";
|
|
8
|
+
import { defaultMachine } from "../git.js";
|
|
9
9
|
import { projectOf } from "./agent.js";
|
|
10
10
|
function client(p) {
|
|
11
11
|
const name = resolveAgentName(str(p.flags, "as"));
|
|
@@ -71,7 +71,7 @@ export async function list(p, out) {
|
|
|
71
71
|
assoc.branch = branch;
|
|
72
72
|
if (wt)
|
|
73
73
|
assoc.worktree = wt;
|
|
74
|
-
assoc.machine =
|
|
74
|
+
assoc.machine = defaultMachine();
|
|
75
75
|
if (!assoc.agent)
|
|
76
76
|
assoc.agent = creds.agent;
|
|
77
77
|
}
|
|
@@ -176,6 +176,8 @@ export async function machineAdmin(action, rest, p, out) {
|
|
|
176
176
|
throw new CliError("provision_failed", `installing the machine daemon on ${host} failed: ${svc.stderr.trim().slice(-300)}`);
|
|
177
177
|
const daemon = JSON.parse(svc.stdout);
|
|
178
178
|
say(` daemon: ${daemon.path} with PATH ${daemon.daemon_path}`);
|
|
179
|
+
if (daemon.launchd)
|
|
180
|
+
say(` ${daemon.launchd.guidance}`);
|
|
179
181
|
const failed = prepared.filter((s) => s.result === "failed");
|
|
180
182
|
return out.print([
|
|
181
183
|
`Machine ${name} (${host}) is provisioned and its daemon is running.`,
|
|
@@ -210,6 +212,7 @@ export async function machineAdmin(action, rest, p, out) {
|
|
|
210
212
|
rep.os ? ` ${rep.os}/${rep.arch} ${rep.hostname} as ${rep.user}; ${rep.cpus ?? "?"} CPUs, ${rep.mem_total_bytes ? `${Math.round(rep.mem_total_bytes / 1024 ** 3)} GB RAM` : "? RAM"}; b9s ${rep.bschat?.version}; codex ${rep.codex ? `${rep.codex.version}, ${rep.codex.logged_in ? "logged in" : "NOT logged in"}, sandbox ${rep.codex.sandbox ? (rep.codex.sandbox.ok ? "ok" : `FAILS (${rep.codex.sandbox.error})`) : "?"}` : "missing"}; hooks ${rep.managed_hooks ? "managed by policy" : "user-level"}; linger ${rep.linger ?? "n/a"}; disk free ${rep.disk_free_bytes ? `${Math.round(rep.disk_free_bytes / 1e9)} GB` : "?"}` : " (no report yet: is its daemon running?)",
|
|
211
213
|
rep.os ? ` Antigravity: ${rep.antigravity ? `${rep.antigravity.version ?? "agy"}, ${rep.antigravity.available ? "available" : "unavailable"}, ${rep.antigravity.logged_in ? "logged in" : "not logged in"}, sandbox ${rep.antigravity.sandbox ? (rep.antigravity.sandbox.ok ? "ok" : `FAILS (${rep.antigravity.sandbox.error})`) : "not checked"}` : "not installed"}` : null,
|
|
212
214
|
rep.container_runtime ? ` Container runtime: ${rep.container_runtime.runtime ?? "none"} (${rep.container_runtime.rootless ? "rootless" : "daemon"}, ${rep.container_runtime.usable_without_root === false ? "NO non-root access" : "non-root ok"}, arch ${(rep.container_runtime.architectures ?? []).join(",") || rep.arch || "?"}${rep.on_ec2 ? `, EC2 container IMDS ${rep.container_imds_blocked ? "blocked" : "NOT blocked"}` : ""})` : null,
|
|
215
|
+
rep.launchd ? ` launchd: ${rep.launchd.session === "headless" ? "headless Mac (no desktop session)" : "desktop session"}; daemon ${rep.launchd.daemon_domain ?? "not installed"}; watchers ${Object.entries(rep.launchd.watchers ?? {}).map(([d, n]) => `${n} in ${d}`).join(", ") || "none"}` : null,
|
|
213
216
|
m.quarantined ? ` QUARANTINED: ${m.quarantine?.reason ?? "operator containment"}${m.quarantine?.at ? ` (${m.quarantine.at})` : ""}` : null,
|
|
214
217
|
];
|
|
215
218
|
const cacheLines = [];
|
|
@@ -415,7 +418,7 @@ export async function machineAdmin(action, rest, p, out) {
|
|
|
415
418
|
throw new CliError("confirmation_required", `non-interactive removal requires a reviewed revision: run machine remove ${name} --preview, then pass --confirm ${name} --impact-revision <revision>`);
|
|
416
419
|
await confirmMachineName(name, p);
|
|
417
420
|
await c.call("DELETE", `/machines/${name}`, { source_revision: impact.source_revision, confirmation: name });
|
|
418
|
-
return out.print(`Removed machine ${name}; its machine key and machine-scoped agent keys are revoked. Agent identities remain. Stop its daemon on the machine with: systemctl --user disable --now org.benignswarm.machine (Linux) or launchctl bootout gui/$(id -u)/org.benignswarm.machine (macOS)`, { removed: name, impact });
|
|
421
|
+
return out.print(`Removed machine ${name}; its machine key and machine-scoped agent keys are revoked. Agent identities remain. Stop its daemon on the machine with: systemctl --user disable --now org.benignswarm.machine (Linux) or launchctl bootout gui/$(id -u)/org.benignswarm.machine (macOS with a desktop session; user/$(id -u)/org.benignswarm.machine on a headless Mac)`, { removed: name, impact });
|
|
419
422
|
}
|
|
420
423
|
if (action === "session") {
|
|
421
424
|
const [sub, machineName, ref] = rest;
|
|
@@ -592,7 +595,7 @@ async function runMachineCompanion(code, p, out) {
|
|
|
592
595
|
if (svc.status !== 0)
|
|
593
596
|
throw new CliError("provision_failed", `installing the machine daemon on ${operation.ssh_host} failed: ${svc.stderr.trim().slice(-300)}`);
|
|
594
597
|
const daemon = JSON.parse(svc.stdout);
|
|
595
|
-
await report("daemon", "completed", `Daemon installed at ${daemon.path}`);
|
|
598
|
+
await report("daemon", "completed", `Daemon installed at ${daemon.path}${daemon.launchd ? `; ${daemon.launchd.guidance}` : ""}`);
|
|
596
599
|
const outcome = operation.kind === "provision" ? "is provisioned" : "has its machine key rotated";
|
|
597
600
|
const completed = await companion.call("POST", `/machine-operations/${operation.id}/finish`, { status: "succeeded", result: `Machine ${operation.machine} ${outcome} and its daemon is running` });
|
|
598
601
|
const result = { operation: completed.operation, machine: operation.machine, ssh_host: operation.ssh_host, daemon_path: daemon.daemon_path, prepare: prepared };
|
package/dist/commands/machine.js
CHANGED
|
@@ -1,25 +1,27 @@
|
|
|
1
1
|
import { spawn, spawnSync } from "node:child_process";
|
|
2
|
+
import { FileFactsCache, scanLinesBackward, TAIL_CHUNK_BYTES, TAIL_MAX_BYTES } from "../tail-lines.js";
|
|
3
|
+
import { rotateLogs } from "../log-rotation.js";
|
|
2
4
|
import { createHash, createHmac } from "node:crypto";
|
|
3
5
|
import { chmodSync, closeSync, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, readSync, realpathSync, rmSync, statSync, statfsSync, unlinkSync, writeFileSync } from "node:fs";
|
|
4
6
|
import { arch, cpus, freemem, homedir, hostname, loadavg, platform, tmpdir, totalmem, userInfo } from "node:os";
|
|
5
7
|
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
6
8
|
import { str } from "../args.js";
|
|
7
9
|
import { Client } from "../client.js";
|
|
8
|
-
import { configRoot, loadAgent, resolveAgentName, saveAgent } from "../config.js";
|
|
10
|
+
import { agentRef, configRoot, loadAgent, resolveAgentName, saveAgent } from "../config.js";
|
|
9
11
|
import { CliError } from "../errors.js";
|
|
10
12
|
import { AGY_APPARMOR_PATH, agyAppArmorProfile, BWRAP_APPARMOR_PATH, bwrapAppArmorProfile, CODEX_APPARMOR_PATH, CODEX_MANAGED_DIR, codexAppArmorProfile, codexManagedHooks, isCodexManagedRequirements } from "../harness.js";
|
|
11
13
|
import { applySparse, sessionCheckoutFacts } from "../git.js";
|
|
12
14
|
import { drainingUntil, writeMaintenance } from "../maintenance.js";
|
|
13
|
-
import { TURN_HARNESSES, claudeFacts, claudeSandbox, dshFacts, dshProcesses, probeFor, sessionProcesses } from "../harnesses.js";
|
|
15
|
+
import { TURN_HARNESSES, claudeFacts, claudeHome, claudeSandbox, dshFacts, dshProcesses, probeFor, sessionProcesses } from "../harnesses.js";
|
|
14
16
|
import { readState, writeState } from "../state.js";
|
|
15
|
-
import { installService, lingerEnabled, MACHINE_LABEL, machineDaemonPath, readInstall, removeService, requireInstall, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
|
|
17
|
+
import { installService, launchdFacts, launchdFactsLine, launchdGuidance, launchdSessionNow, lingerEnabled, MACHINE_LABEL, machineDaemonPath, readInstall, removeService, requireInstall, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
|
|
16
18
|
import { CLI_VERSION } from "../version.js";
|
|
17
19
|
import { probeCapabilities } from "../capabilities.js";
|
|
18
20
|
import { diskSpaceNotice } from "../notices.js";
|
|
19
21
|
import { verifyClaudeProvider } from "../providers.js";
|
|
20
22
|
import { busyTurnPause, DEFAULT_TURNS_PER_HOUR, DEFAULT_UNPRODUCTIVE_PER_HOUR, resumeTurnGuard, verificationUnavailable } from "../turn-guard.js";
|
|
21
23
|
import { defaultWorkspaceWritableRoots } from "../start-options.js";
|
|
22
|
-
import { antigravityPath, antigravitySandboxPermissions, antigravityTurnArgs, parseAntigravityJson } from "../antigravity.js";
|
|
24
|
+
import { antigravityPath, antigravitySandboxPermissions, antigravityTurnArgs, antigravityTurnEnv, parseAntigravityJson } from "../antigravity.js";
|
|
23
25
|
import { bootTimeMs } from "../boot-time.js";
|
|
24
26
|
import { DEFAULT_CACHE_FLOOR_PCT, manageBuildCaches } from "../build-caches.js";
|
|
25
27
|
import { agentContainerName, agentContainerRunArgs, detectEc2Host, ensurePinnedImagePulled, isolatedBuildCommand, isolatedDevcontainerBuildCommand, isolatedImagePullCommands, isolatedSubprocessEnv, probeContainerImdsIsolation, networklessRuntimeWrapper, parseContainerRuntimeVersion, probeImdsIsolation, probeNestedSandbox, readGitIdentity, resolveSessionSecretDelivery, resolveWritableMounts, validateDevcontainerSpec, BUILD_SECRET_KEY_NAME_RE, BUILD_SECRET_CONTENT_RE, containsBuildSecretMaterial, sanitizeBuildDiagnosticText, } from "../container.js";
|
|
@@ -852,6 +854,9 @@ export async function launchDesiredSession(opts) {
|
|
|
852
854
|
return { status: 1, stdout: "", stderr: `timed out waiting for in-container b9s start (${containerName})` };
|
|
853
855
|
}
|
|
854
856
|
/** One pass: make what runs here match what the operator declared, then report. */
|
|
857
|
+
/** Service logs are rotated by the daemon (WU #481), checked at most this often. */
|
|
858
|
+
const LOG_ROTATION_EVERY_MS = 10 * 60_000;
|
|
859
|
+
let lastLogRotationAt = 0;
|
|
855
860
|
export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
856
861
|
const client = Client.raw(m.url, m.key, {
|
|
857
862
|
requestTimeoutMs: MACHINE_REQUEST_TIMEOUT_MS,
|
|
@@ -860,6 +865,11 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
860
865
|
? `request start ${event.method} ${event.path}`
|
|
861
866
|
: `request end ${event.method} ${event.path} in ${event.durationMs}ms${event.error ? ` (${event.error})` : ""}`),
|
|
862
867
|
});
|
|
868
|
+
if (Date.now() - lastLogRotationAt >= LOG_ROTATION_EVERY_MS) {
|
|
869
|
+
lastLogRotationAt = Date.now();
|
|
870
|
+
for (const r of rotateLogs(join(configRoot(), "logs")))
|
|
871
|
+
log(`rotated ${r.file}: ${Math.round(r.bytes_before / 1048576)} MB, kept the newest ${Math.round(r.kept_bytes / 1048576)} MB as ${r.file}.1`);
|
|
872
|
+
}
|
|
863
873
|
const me = await client.call("GET", "/machines/me");
|
|
864
874
|
const desired = me.sessions;
|
|
865
875
|
const processScanner = deps?.worktreeProcessScanner ?? scanWorktreeProcesses;
|
|
@@ -1182,7 +1192,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
1182
1192
|
dir: s.dir,
|
|
1183
1193
|
thread: th,
|
|
1184
1194
|
watcher: watcherState,
|
|
1185
|
-
last_turn:
|
|
1195
|
+
...((t) => ({ last_turn: t.line, ...(t.unknown_reason ? { last_turn_unknown: t.unknown_reason } : {}) }))(lastTurn(s.agent)),
|
|
1186
1196
|
turn_judgment: s.turn_judgment ?? null,
|
|
1187
1197
|
...(s.pool_move_pending ? { checkout: sessionCheckoutFacts(s.dir) } : {}),
|
|
1188
1198
|
...turnFacts(s.agent, s.harness, th, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR),
|
|
@@ -1661,16 +1671,37 @@ export function turnProcess(thread, harness = "codex", psOutput, agent) {
|
|
|
1661
1671
|
*/
|
|
1662
1672
|
const CRASH_STARTS = 5;
|
|
1663
1673
|
const CRASH_WINDOW_MS = 5 * 60_000;
|
|
1664
|
-
|
|
1674
|
+
/**
|
|
1675
|
+
* The last 64 KiB of a watcher's error log. Log rotation (WU #481) can empty the live file; then the
|
|
1676
|
+
* rotated <name>.1 supplies the rest of the window, from a line start, so a fault the guards look for
|
|
1677
|
+
* (a directory_conflict marker, a crash loop) is still seen on the pass right after a rotation.
|
|
1678
|
+
*/
|
|
1679
|
+
export function watcherLogText(ref) {
|
|
1665
1680
|
const f = join(configRoot(), "logs", `watch.${ref.replace("/", ".")}.err.log`);
|
|
1666
1681
|
if (!existsSync(f))
|
|
1667
1682
|
return null;
|
|
1668
|
-
const
|
|
1669
|
-
const
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1683
|
+
const WINDOW = 65_536;
|
|
1684
|
+
const tail = (path, max) => {
|
|
1685
|
+
const size = statSync(path).size;
|
|
1686
|
+
const fd = openSync(path, "r");
|
|
1687
|
+
try {
|
|
1688
|
+
const buf = Buffer.alloc(Math.min(size, max));
|
|
1689
|
+
readSync(fd, buf, 0, buf.length, size - buf.length);
|
|
1690
|
+
return buf;
|
|
1691
|
+
}
|
|
1692
|
+
finally {
|
|
1693
|
+
closeSync(fd);
|
|
1694
|
+
}
|
|
1695
|
+
};
|
|
1696
|
+
const live = tail(f, WINDOW);
|
|
1697
|
+
const rotated = `${f}.1`;
|
|
1698
|
+
if (live.length >= WINDOW || !existsSync(rotated))
|
|
1699
|
+
return live.toString("utf8");
|
|
1700
|
+
let earlier = tail(rotated, WINDOW - live.length);
|
|
1701
|
+
const nl = earlier.indexOf(0x0a);
|
|
1702
|
+
if (statSync(rotated).size > earlier.length && nl >= 0)
|
|
1703
|
+
earlier = earlier.subarray(nl + 1); // start at a whole line
|
|
1704
|
+
return Buffer.concat([earlier, live]).toString("utf8");
|
|
1674
1705
|
}
|
|
1675
1706
|
/** A marked startup failure is unambiguous even when it prevents the first watching banner. */
|
|
1676
1707
|
export function watcherDirectoryConflict(ref, logText) {
|
|
@@ -1736,12 +1767,44 @@ export function watcherFault(ref, logText, nowMs = Date.now()) {
|
|
|
1736
1767
|
}
|
|
1737
1768
|
}
|
|
1738
1769
|
/** The watcher's latest turn line (started, finished, FAILED, STOPPED, paused), for the report. */
|
|
1739
|
-
|
|
1770
|
+
const TURN_LINE = (l) => /b9s watch\[/.test(l) && /turn #|TURN #|usage limit|pause lifted/.test(l);
|
|
1771
|
+
const lastTurnCache = new FileFactsCache();
|
|
1772
|
+
/**
|
|
1773
|
+
* The latest turn line of a watcher log, read from the end (WU #481: the whole-file read ran per session
|
|
1774
|
+
* per pass over logs up to 190 MB). Within the cap it equals the whole-file answer; past it, line is null
|
|
1775
|
+
* and unknown_reason says why, so no diagnostic text is ever reported as a turn line.
|
|
1776
|
+
*/
|
|
1777
|
+
export function lastTurnFromFile(f, chunkBytes = TAIL_CHUNK_BYTES, maxBytes = TAIL_MAX_BYTES) {
|
|
1778
|
+
let found = null;
|
|
1779
|
+
const visit = (l) => { if (TURN_LINE(l)) {
|
|
1780
|
+
found = l.slice(0, 300);
|
|
1781
|
+
return true;
|
|
1782
|
+
} return false; };
|
|
1783
|
+
const scan = scanLinesBackward(f, visit, chunkBytes, maxBytes);
|
|
1784
|
+
let read = scan.bytesRead;
|
|
1785
|
+
let capped = scan.capped;
|
|
1786
|
+
// A rotation (WU #481) may have moved the latest turn line into <name>.1 and left the live log short:
|
|
1787
|
+
// continue there with what is left of the same cap, so rotation never hides the latest turn.
|
|
1788
|
+
const rotated = `${f}.1`;
|
|
1789
|
+
if (found === null && !capped && existsSync(rotated) && statSync(rotated).size > 0) {
|
|
1790
|
+
if (read < maxBytes) {
|
|
1791
|
+
const more = scanLinesBackward(rotated, visit, chunkBytes, maxBytes - read);
|
|
1792
|
+
read += more.bytesRead;
|
|
1793
|
+
capped = more.capped;
|
|
1794
|
+
}
|
|
1795
|
+
else {
|
|
1796
|
+
capped = true; // the budget ended exactly at the live log's start; the rotated bytes went unread
|
|
1797
|
+
}
|
|
1798
|
+
}
|
|
1799
|
+
if (found !== null)
|
|
1800
|
+
return { line: found };
|
|
1801
|
+
return capped ? { line: null, unknown_reason: `no turn line in the last ${Math.round(maxBytes / 1048576)} MB of the watcher log` } : { line: null };
|
|
1802
|
+
}
|
|
1803
|
+
export function lastTurn(ref) {
|
|
1740
1804
|
const f = join(configRoot(), "logs", `watch.${ref.replace("/", ".")}.err.log`);
|
|
1741
1805
|
if (!existsSync(f))
|
|
1742
|
-
return null;
|
|
1743
|
-
|
|
1744
|
-
return lines.length ? lines[lines.length - 1].slice(0, 300) : null;
|
|
1806
|
+
return { line: null };
|
|
1807
|
+
return lastTurnCache.get(f, (path) => lastTurnFromFile(path));
|
|
1745
1808
|
}
|
|
1746
1809
|
function volumeSpace(path, label) {
|
|
1747
1810
|
try {
|
|
@@ -1809,6 +1872,16 @@ function antigravityUsernsDenied(parsed, output) {
|
|
|
1809
1872
|
const denied = value?.denied_actions ?? error?.denied_actions;
|
|
1810
1873
|
return /Terminal sandbox unavailable/i.test(output) || (Array.isArray(denied) && denied.some((entry) => entry && typeof entry === "object" && entry.action === "command"));
|
|
1811
1874
|
}
|
|
1875
|
+
/** Resolve an authenticated identity before the probe moves into its fresh temporary cwd. */
|
|
1876
|
+
function antigravityProbeAgent(sessions = [], cwd = process.cwd()) {
|
|
1877
|
+
const session = sessions.find((item) => item.harness === "antigravity") ?? sessions[0];
|
|
1878
|
+
try {
|
|
1879
|
+
return resolveAgentName(session?.agent ?? process.env.BSCHAT_AGENT?.trim(), process.env, cwd);
|
|
1880
|
+
}
|
|
1881
|
+
catch {
|
|
1882
|
+
return null;
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1812
1885
|
/** Install only an absent or byte-identical b9s profile; leave every other owner untouched. */
|
|
1813
1886
|
export function installAgyAppArmorProfile(binary, profilePath = AGY_APPARMOR_PATH, run = (args, input) => spawnSync("sudo", args, { input, encoding: "utf8", stdio: input === undefined ? "pipe" : ["pipe", "ignore", "pipe"] })) {
|
|
1814
1887
|
const profile = agyAppArmorProfile(binary);
|
|
@@ -1838,13 +1911,38 @@ function resolvedAgyBinary(path) {
|
|
|
1838
1911
|
const binary = result.status === 0 ? (result.stdout ?? "").trim() : "";
|
|
1839
1912
|
return isAbsolute(binary) ? binary : null;
|
|
1840
1913
|
}
|
|
1841
|
-
/** Runs one cached
|
|
1842
|
-
export function antigravitySandbox(force = false, path = process.env.PATH ?? "", b9sBin = readInstall()?.bin ?? null) {
|
|
1843
|
-
if (
|
|
1914
|
+
/** Runs one cached authenticated API check through Antigravity's real workspace-write terminal sandbox. */
|
|
1915
|
+
export function antigravitySandbox(force = false, path = process.env.PATH ?? "", b9sBin = readInstall()?.bin ?? null, agent = antigravityProbeAgent()) {
|
|
1916
|
+
if (agent) {
|
|
1917
|
+
try {
|
|
1918
|
+
agent = resolveAgentName(agent, process.env, process.cwd());
|
|
1919
|
+
}
|
|
1920
|
+
catch {
|
|
1921
|
+
agent = null;
|
|
1922
|
+
}
|
|
1923
|
+
}
|
|
1924
|
+
if (!agent) {
|
|
1925
|
+
const result = { ok: false, error: "authenticated sandbox probe has no project-agent identity; set BSCHAT_AGENT or run from a checkout with a b9s identity" };
|
|
1926
|
+
agySandboxCache = { at: Date.now(), result, path, b9sBin, agent, credentialFingerprint: null };
|
|
1927
|
+
return result;
|
|
1928
|
+
}
|
|
1929
|
+
let credentialFingerprint;
|
|
1930
|
+
try {
|
|
1931
|
+
const credentials = loadAgent(agent);
|
|
1932
|
+
if (agentRef(credentials) !== agent)
|
|
1933
|
+
throw new Error("saved identity does not match the selected agent");
|
|
1934
|
+
credentialFingerprint = createHash("sha256").update(credentials.key).digest("hex");
|
|
1935
|
+
}
|
|
1936
|
+
catch {
|
|
1937
|
+
const result = { ok: false, error: `authenticated sandbox probe cannot resolve saved credentials for ${agent} from the machine's b9s home` };
|
|
1938
|
+
agySandboxCache = { at: Date.now(), result, path, b9sBin, agent, credentialFingerprint: null };
|
|
1939
|
+
return result;
|
|
1940
|
+
}
|
|
1941
|
+
if (!force && agySandboxCache && agySandboxCache.path === path && agySandboxCache.b9sBin === b9sBin && agySandboxCache.agent === agent && agySandboxCache.credentialFingerprint === credentialFingerprint && Date.now() - agySandboxCache.at < AGY_SANDBOX_PROBE_MS)
|
|
1844
1942
|
return agySandboxCache.result;
|
|
1845
1943
|
if (!b9sBin) {
|
|
1846
1944
|
const result = { ok: false, error: `recorded b9s install is unavailable; expected ${join(configRoot(), "install.json")}` };
|
|
1847
|
-
agySandboxCache = { at: Date.now(), result, path, b9sBin };
|
|
1945
|
+
agySandboxCache = { at: Date.now(), result, path, b9sBin, agent, credentialFingerprint };
|
|
1848
1946
|
return result;
|
|
1849
1947
|
}
|
|
1850
1948
|
let result;
|
|
@@ -1852,11 +1950,19 @@ export function antigravitySandbox(force = false, path = process.env.PATH ?? "",
|
|
|
1852
1950
|
try {
|
|
1853
1951
|
work = mkdtempSync(join(tmpdir(), "b9s-agy-sandbox-probe-"));
|
|
1854
1952
|
const marker = join(work, ".b9s-sandbox-probe");
|
|
1953
|
+
const meOutputPath = join(work, ".b9s-sandbox-probe-me");
|
|
1954
|
+
const meErrorPath = join(work, ".b9s-sandbox-probe-me-error");
|
|
1955
|
+
const meStatusPath = join(work, ".b9s-sandbox-probe-status");
|
|
1855
1956
|
const quotedMarker = `'${marker.replace(/'/g, `'\\''`)}'`;
|
|
1856
|
-
const
|
|
1957
|
+
const quotedMeOutput = `'${meOutputPath.replace(/'/g, `'\\''`)}'`;
|
|
1958
|
+
const quotedMeError = `'${meErrorPath.replace(/'/g, `'\\''`)}'`;
|
|
1959
|
+
const quotedMeStatus = `'${meStatusPath.replace(/'/g, `'\\''`)}'`;
|
|
1960
|
+
const command = `b9s me > ${quotedMeOutput} 2> ${quotedMeError}; me_status=$?; printf '%s' "$me_status" > ${quotedMeStatus}; if [ "$me_status" -eq 0 ]; then printf '${AGY_SANDBOX_PROBE_RESPONSE}' > ${quotedMarker}; fi`;
|
|
1961
|
+
const prompt = `Use your terminal tool once to run this exact command and do not replace or simulate its output: ${command}. Then reply with exactly ${AGY_SANDBOX_PROBE_RESPONSE}. Do not call any other tool.`;
|
|
1857
1962
|
const settings = ["--sandbox", "--settings", JSON.stringify({ enableTerminalSandbox: true, toolPermission: "proceed-in-sandbox", permissions: { allow: antigravitySandboxPermissions("api.benignswarm.org", configRoot(), b9sBin) } })];
|
|
1858
1963
|
const r = spawnSync("agy", antigravityTurnArgs(prompt, AGY_SANDBOX_PROBE_MODEL, undefined, 45, settings), {
|
|
1859
|
-
encoding: "utf8", timeout: 60_000, maxBuffer: 1024 * 1024, cwd: work,
|
|
1964
|
+
encoding: "utf8", timeout: 60_000, maxBuffer: 1024 * 1024, cwd: work,
|
|
1965
|
+
env: { ...process.env, ...antigravityTurnEnv("workspace-write", b9sBin), BSCHAT_AGENT: agent, PATH: antigravityPath(b9sBin, path) },
|
|
1860
1966
|
});
|
|
1861
1967
|
const parsed = parseAntigravityJson(r.stdout ?? "");
|
|
1862
1968
|
let wroteMarker = false;
|
|
@@ -1864,22 +1970,39 @@ export function antigravitySandbox(force = false, path = process.env.PATH ?? "",
|
|
|
1864
1970
|
wroteMarker = readFileSync(marker, "utf8") === AGY_SANDBOX_PROBE_RESPONSE;
|
|
1865
1971
|
}
|
|
1866
1972
|
catch { /* a missing marker means the sandbox command did not run */ }
|
|
1973
|
+
let meOutput = "";
|
|
1974
|
+
let meError = "";
|
|
1975
|
+
let meStatus = "";
|
|
1976
|
+
try {
|
|
1977
|
+
meOutput = readFileSync(meOutputPath, "utf8");
|
|
1978
|
+
}
|
|
1979
|
+
catch { /* missing output means b9s me did not run */ }
|
|
1980
|
+
try {
|
|
1981
|
+
meError = readFileSync(meErrorPath, "utf8");
|
|
1982
|
+
}
|
|
1983
|
+
catch { /* missing stderr means b9s me did not run */ }
|
|
1984
|
+
try {
|
|
1985
|
+
meStatus = readFileSync(meStatusPath, "utf8");
|
|
1986
|
+
}
|
|
1987
|
+
catch { /* missing status means b9s me did not run */ }
|
|
1988
|
+
const authenticatedMe = meStatus === "0" && /^agent:\s+\S+/m.test(meOutput);
|
|
1989
|
+
const meDiagnostic = meError.trim().replace(/Bearer\s+\S+/gi, "Bearer [redacted]").replace(/(https?:\/\/)[^/\s@]+@/gi, "$1[redacted]@").slice(0, 300);
|
|
1867
1990
|
const output = `${r.stdout ?? ""}\n${r.stderr ?? ""}`;
|
|
1868
|
-
result = r.status === 0 && parsed?.status === "SUCCESS" && parsed.response?.trim() === AGY_SANDBOX_PROBE_RESPONSE && wroteMarker
|
|
1991
|
+
result = r.status === 0 && parsed?.status === "SUCCESS" && parsed.response?.trim() === AGY_SANDBOX_PROBE_RESPONSE && wroteMarker && authenticatedMe
|
|
1869
1992
|
? { ok: true, error: null }
|
|
1870
1993
|
: { ok: false, error: antigravityUsernsDenied(parsed, output)
|
|
1871
1994
|
? AGY_USERNS_FIX
|
|
1872
|
-
: `sandbox
|
|
1995
|
+
: `sandbox authenticated API check failed (b9s me exit ${meStatus || "unknown"}; agy exit ${r.status ?? "unknown"})${meDiagnostic ? `: ${meDiagnostic}` : meOutput && !authenticatedMe ? `: ${meOutput.trim().slice(0, 300)}` : ""}; verify the API host is allowed and the recorded b9s install ${b9sBin} and Node runtime ${process.execPath} are usable inside the sandbox` };
|
|
1873
1996
|
}
|
|
1874
1997
|
catch (error) {
|
|
1875
1998
|
const detail = error instanceof Error ? error.message : String(error);
|
|
1876
|
-
result = { ok: false, error: `sandbox could not prepare b9s
|
|
1999
|
+
result = { ok: false, error: `sandbox could not prepare authenticated b9s me probe for recorded install ${b9sBin} with Node runtime ${process.execPath}: ${detail}` };
|
|
1877
2000
|
}
|
|
1878
2001
|
finally {
|
|
1879
2002
|
if (work)
|
|
1880
2003
|
rmSync(work, { recursive: true, force: true });
|
|
1881
2004
|
}
|
|
1882
|
-
agySandboxCache = { at: Date.now(), result, path, b9sBin };
|
|
2005
|
+
agySandboxCache = { at: Date.now(), result, path, b9sBin, agent, credentialFingerprint };
|
|
1883
2006
|
return result;
|
|
1884
2007
|
}
|
|
1885
2008
|
function antigravityLoginFacts(path) {
|
|
@@ -1896,11 +2019,11 @@ function antigravityLoginFacts(path) {
|
|
|
1896
2019
|
};
|
|
1897
2020
|
}
|
|
1898
2021
|
/** Machine facts used by placement; the daemon probes login cheaply and caches the sandbox turn. */
|
|
1899
|
-
export function antigravityFacts(path = process.env.PATH ?? "", b9sBin = readInstall()?.bin ?? null) {
|
|
2022
|
+
export function antigravityFacts(path = process.env.PATH ?? "", b9sBin = readInstall()?.bin ?? null, agent = antigravityProbeAgent()) {
|
|
1900
2023
|
const facts = antigravityLoginFacts(path);
|
|
1901
2024
|
return {
|
|
1902
2025
|
...facts,
|
|
1903
|
-
sandbox: facts.logged_in ? antigravitySandbox(false, path, b9sBin) : null,
|
|
2026
|
+
sandbox: facts.logged_in ? antigravitySandbox(false, path, b9sBin, agent) : null,
|
|
1904
2027
|
};
|
|
1905
2028
|
}
|
|
1906
2029
|
/** Linux's MemAvailable; Darwin is supplied by vm_stat, never approximated by free pages. */
|
|
@@ -1913,12 +2036,24 @@ function memAvailable() {
|
|
|
1913
2036
|
}
|
|
1914
2037
|
return platform() === "darwin" ? null : freemem();
|
|
1915
2038
|
}
|
|
2039
|
+
/**
|
|
2040
|
+
* On a headless Mac, a Claude Code sign-in kept in the login keychain can't be read, and 'claude auth status'
|
|
2041
|
+
* then reports no stored login, which looks the same as never having signed in. The observed status is kept;
|
|
2042
|
+
* when it is "not logged in" there, with no file credential, the report adds the keychain as a possible cause
|
|
2043
|
+
* and its fix as a readiness gap (WU #478). A rejected stored login or any other failure is left as observed.
|
|
2044
|
+
*/
|
|
2045
|
+
export function claudeKeychainGap(f, headlessMac, fileCredentials) {
|
|
2046
|
+
if (!headlessMac || fileCredentials || f.logged_in || f.login !== "not logged in")
|
|
2047
|
+
return f;
|
|
2048
|
+
return { ...f, readiness_gap: "possible cause: this Mac has no desktop session, and a Claude Code sign-in kept in the login keychain can't be read without one. If Claude Code is signed in at the desktop, sign in there (or enable automatic sign-in), or store a file credential with 'claude setup-token'" };
|
|
2049
|
+
}
|
|
1916
2050
|
/** Claude Code's version, login and sandbox; the sandbox check runs at most every 10 min. */
|
|
1917
2051
|
let claudeSandboxCache = null;
|
|
1918
2052
|
function claudeReport(path = process.env.PATH ?? "", providersInUse = ["anthropic"]) {
|
|
1919
|
-
const
|
|
1920
|
-
if (!
|
|
2053
|
+
const found = claudeFacts(undefined, path);
|
|
2054
|
+
if (!found)
|
|
1921
2055
|
return null;
|
|
2056
|
+
const f = claudeKeychainGap(found, process.platform === "darwin" && launchdSessionNow() === "headless", existsSync(join(claudeHome(), ".credentials.json")));
|
|
1922
2057
|
if (!claudeSandboxCache || claudeSandboxCache.path !== path || Date.now() - claudeSandboxCache.at > 10 * 60_000)
|
|
1923
2058
|
claudeSandboxCache = { at: Date.now(), result: claudeSandbox(path), path };
|
|
1924
2059
|
const providers = {};
|
|
@@ -1945,7 +2080,8 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
|
|
|
1945
2080
|
return codex.status === 0 ? { version: codex.stdout.trim(), logged_in: login?.status === 0 && /logged in/i.test(`${login.stdout}${login.stderr}`), login: `${login?.stdout ?? ""}${login?.stderr ?? ""}`.trim().slice(0, 200), account_fingerprint: codexAccountFingerprint(), sandbox: codexSandbox(false, path) } : null;
|
|
1946
2081
|
})();
|
|
1947
2082
|
const dsh = (probes?.dsh ?? (() => dshFacts(platform(), path)))();
|
|
1948
|
-
const
|
|
2083
|
+
const probeAgent = antigravityProbeAgent(sessions);
|
|
2084
|
+
const antigravity = probes?.antigravity ? probes.antigravity(probeAgent) : antigravityFacts(path, readInstall()?.bin ?? null, probeAgent);
|
|
1949
2085
|
const homeSpace = volumeSpace(homedir(), "home");
|
|
1950
2086
|
const readTelemetryFile = (path) => { try {
|
|
1951
2087
|
return readFileSync(path, "utf8");
|
|
@@ -1987,6 +2123,8 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
|
|
|
1987
2123
|
booted_at: bootedAt === null ? null : new Date(Math.floor(bootedAt / 60_000) * 60_000).toISOString(),
|
|
1988
2124
|
booted_at_exact: bootedAt === null ? null : new Date(bootedAt).toISOString(),
|
|
1989
2125
|
daemon_path: path,
|
|
2126
|
+
// macOS: which launchd domain the services use, so a headless Mac is visible, never silent (WU #478).
|
|
2127
|
+
...(platform() === "darwin" ? { launchd: (probes?.launchd ?? launchdFacts)() } : {}),
|
|
1990
2128
|
bschat: { version: CLI_VERSION, bin: requireInstall().bin },
|
|
1991
2129
|
git_identity: gitIdentity,
|
|
1992
2130
|
on_ec2: onEc2,
|
|
@@ -2122,6 +2260,8 @@ export function prepare(opts = {}) {
|
|
|
2122
2260
|
const daemonPath = machineDaemonPath();
|
|
2123
2261
|
const daemonEnv = { ...process.env, PATH: daemonPath };
|
|
2124
2262
|
steps.push({ step: "daemon PATH", result: "ok", detail: daemonPath });
|
|
2263
|
+
if (platform() === "darwin")
|
|
2264
|
+
steps.push({ step: "launchd", result: "ok", detail: launchdGuidance() });
|
|
2125
2265
|
if (platform() === "darwin")
|
|
2126
2266
|
steps.push(...macReadinessSteps(macReadiness({ path: daemonPath })).map((step) => ({ ...step, result: step.result })));
|
|
2127
2267
|
const sudo = spawnSync("sudo", ["-n", "true"], { stdio: "ignore" }).status === 0;
|
|
@@ -2611,7 +2751,8 @@ export async function machine(p, out) {
|
|
|
2611
2751
|
const bin = requireInstall().bin;
|
|
2612
2752
|
const daemonPath = machineDaemonPath();
|
|
2613
2753
|
const path = installService(MACHINE_LABEL, [bin, "machine", "run"], homedir(), { PATH: daemonPath, HOME: homedir() }, "machine");
|
|
2614
|
-
|
|
2754
|
+
const launchd = process.platform === "darwin" ? { ...launchdFacts(), guidance: launchdGuidance() } : null;
|
|
2755
|
+
return out.print([`Wrote ${path} and (re)started it: the machine daemon runs ${bin} machine run with PATH ${daemonPath}. Logs: ~/.b9s/logs/machine.*.log`, ...(launchd ? [launchd.guidance] : [])].join("\n"), { path, label: MACHINE_LABEL, daemon_path: daemonPath, ...(launchd ? { launchd } : {}) });
|
|
2615
2756
|
}
|
|
2616
2757
|
const m = loadMachine();
|
|
2617
2758
|
const log = (s) => process.stderr.write(`${new Date().toISOString()} b9s machine[${m.name}]: ${s}\n`);
|
|
@@ -2623,7 +2764,8 @@ export async function machine(p, out) {
|
|
|
2623
2764
|
const judgment = s.turn_judgment ? ` judgment ${s.turn_judgment.state}: ${s.turn_judgment.trigger_reasons.join(", ")}` : "";
|
|
2624
2765
|
return `${s.agent.padEnd(32)} desired ${s.desired.padEnd(8)} watcher ${w ? (serviceActive(w) ? "active" : "inactive") : "none"} ${s.harness}/${s.provider ?? "anthropic"} thread ${state.sessions[s.id]?.thread ?? s.thread ?? "-"}${judgment} ${s.dir}`;
|
|
2625
2766
|
});
|
|
2626
|
-
|
|
2767
|
+
const launchd = process.platform === "darwin" ? launchdFacts() : null;
|
|
2768
|
+
return out.print([`machine ${m.name} (${m.url})`, ...(launchd ? [launchdFactsLine(launchd)] : []), ...rows, rows.length ? "" : "no sessions declared"].join("\n"), { machine: m.name, sessions: desired, local: state, ...(launchd ? { launchd } : {}) });
|
|
2627
2769
|
}
|
|
2628
2770
|
if (sub === "once") {
|
|
2629
2771
|
const r = await reconcile(m, log);
|
package/dist/commands/watch.js
CHANGED
|
@@ -4,7 +4,7 @@ import { DEFAULT_TURN_COALESCE_SECONDS, MAX_TURN_COALESCE_SECONDS, shouldDeferTu
|
|
|
4
4
|
import { drainingUntil } from "../maintenance.js";
|
|
5
5
|
import { probeFor, turnHarness } from "../harnesses.js";
|
|
6
6
|
import { applyAck } from "./wake.js";
|
|
7
|
-
import { lingerEnabled, loadSystemdUnit, reloadLaunchAgent, removeService, requireInstall, systemdUnit, systemdUserDir, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
|
|
7
|
+
import { launchdSessionTypeXml, lingerEnabled, plistLaunchdDomain, loadSystemdUnit, reloadLaunchAgent, removeService, requireInstall, systemdUnit, systemdUserDir, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
|
|
8
8
|
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
9
9
|
import { createHash } from "node:crypto";
|
|
10
10
|
import { homedir, userInfo } from "node:os";
|
|
@@ -1369,7 +1369,7 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
|
|
|
1369
1369
|
<key>EnvironmentVariables</key><dict><key>PATH</key><string>${escapeXml(process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin")}</string><key>HOME</key><string>${homedir()}</string>${Object.entries(extraEnv).map(([k, v]) => `<key>${escapeXml(k)}</key><string>${escapeXml(v)}</string>`).join("")}</dict>
|
|
1370
1370
|
<key>WorkingDirectory</key><string>${escapeXml(process.cwd())}</string>
|
|
1371
1371
|
<key>RunAtLoad</key><true/>
|
|
1372
|
-
<key>KeepAlive</key><true
|
|
1372
|
+
<key>KeepAlive</key><true/>${launchdSessionTypeXml()}
|
|
1373
1373
|
<key>StandardOutPath</key><string>${join(logDir, `watch.${slug}.out.log`)}</string>
|
|
1374
1374
|
<key>StandardErrorPath</key><string>${join(logDir, `watch.${slug}.err.log`)}</string>
|
|
1375
1375
|
</dict></plist>
|
|
@@ -1383,7 +1383,7 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
|
|
|
1383
1383
|
const sess = sessionOfExec(exec);
|
|
1384
1384
|
if (sess)
|
|
1385
1385
|
bindSession(sess.kind, sess.id, name);
|
|
1386
|
-
out.print(`Wrote ${path} and (re)loaded it: the watcher is running ${program[0]}.${Object.keys(extraEnv).length ? `\nCaptured env: ${Object.keys(extraEnv).join(", ")} (re-run this command if the harness restarts and these change)` : ""}\nStop it: launchctl bootout
|
|
1386
|
+
out.print(`Wrote ${path} and (re)loaded it: the watcher is running ${program[0]}.${Object.keys(extraEnv).length ? `\nCaptured env: ${Object.keys(extraEnv).join(", ")} (re-run this command if the harness restarts and these change)` : ""}\nStop it: launchctl bootout ${plistLaunchdDomain(path)}/${label}\nLogs: ${logDir}/watch.${slug}.*.log\nCheck it: b9s doctor\nThe watcher runs from ${process.cwd()} so the repo identity file applies.`, { plist: path, label, program: program[0] });
|
|
1387
1387
|
}
|
|
1388
1388
|
export const turnArgs = (t) => (t ? ["--turn", "--turn-timeout", String(t.timeout), "--turns-per-hour", String(t.turnsPerHour), "--unproductive-per-hour", String(t.unproductivePerHour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR), "--turn-coalesce-seconds", String(t.coalesceSeconds), "--harness", t.harness, "--session", t.session, ...(t.machineSessionId ? ["--machine-session-id", t.machineSessionId] : []), ...(t.provider === "deepseek" ? ["--provider", t.provider] : []), ...(t.model ? ["--model", t.model] : [])] : []);
|
|
1389
1389
|
function escapeXml(s) {
|
|
@@ -204,7 +204,7 @@ export async function scanProject(creds, project, options = {}) {
|
|
|
204
204
|
const scan = scanWorktrees(options.cwd ?? process.cwd(), options);
|
|
205
205
|
if (!scan)
|
|
206
206
|
throw new CliError("not_a_repo", "the current directory is not inside a git repository", "Run b9s worktrees scan from a checkout of the project's repository.");
|
|
207
|
-
const machine =
|
|
207
|
+
const machine = defaultMachine();
|
|
208
208
|
const client = Client.forAgent(creds, undefined, { presence: false });
|
|
209
209
|
const timeoutMs = options.requestTimeoutMs ?? WORKTREE_SCAN_TIMEOUT_MS;
|
|
210
210
|
options.onProgress?.(`Reporting worktrees for project ${project} (timeout ${timeoutMs} ms)`);
|
package/dist/commands/wu.js
CHANGED
|
@@ -8,7 +8,7 @@ import { readState, writeState } from "../state.js";
|
|
|
8
8
|
import { codexRollout, sessionsOf } from "../sessions.js";
|
|
9
9
|
import { claudeSessionWithHookMetadata, sessionCompactions, sessionContext, sessionStart, sessionUsage } from "../usage.js";
|
|
10
10
|
import { CliError, WrittenReceiptMismatchError } from "../errors.js";
|
|
11
|
-
import { branchAndHead, commitAtTime, ensureReviewWorktree, ensureWorktree, fetchRef, fetchRemoteBranch, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, isAncestor, isShaBranchName, removeWorktreeIfClean, repoName, repoParent, symbolicBranch, verifyMergedCommit, verifyNoCommitsBeyondTarget, worktreeForBranch } from "../git.js";
|
|
11
|
+
import { branchAndHead, commitAtTime, defaultMachine, ensureReviewWorktree, ensureWorktree, fetchRef, fetchRemoteBranch, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, isAncestor, isShaBranchName, removeWorktreeIfClean, repoName, repoParent, symbolicBranch, verifyMergedCommit, verifyNoCommitsBeyondTarget, worktreeForBranch } from "../git.js";
|
|
12
12
|
import { join, resolve } from "node:path";
|
|
13
13
|
import { table } from "../output.js";
|
|
14
14
|
import { restoreRecoveryArchive, sha256 as recoverySha256 } from "../recovery-archive.js";
|
|
@@ -1608,9 +1608,11 @@ export async function lock(p, out) {
|
|
|
1608
1608
|
out.print(r.lock.holder_name ? `${lockName} released; now held by ${r.lock.holder_name}${r.lock.unit ? ` (WU #${r.lock.unit})` : ""}.` : `${lockName} released; free.`, r);
|
|
1609
1609
|
return;
|
|
1610
1610
|
}
|
|
1611
|
+
if (str(p.flags, "machine") !== undefined)
|
|
1612
|
+
throw new CliError("usage", "lock acquisition is scoped to the host running the CLI; --machine is only for unlock");
|
|
1611
1613
|
const unit = str(p.flags, "unit");
|
|
1612
1614
|
// Scoped to this machine unless --shared: the resource is this box's CPU and disk.
|
|
1613
|
-
const r = await client.call("POST", `/projects/${project}/locks/${lockName}/acquire`, { unit: unit ? Number(unit) : null, note: str(p.flags, "note") ?? "", shared: bool(p.flags, "shared"), machine:
|
|
1615
|
+
const r = await client.call("POST", `/projects/${project}/locks/${lockName}/acquire`, { unit: unit ? Number(unit) : null, note: str(p.flags, "note") ?? "", shared: bool(p.flags, "shared"), machine: defaultMachine() });
|
|
1614
1616
|
out.print(r.maintenance
|
|
1615
1617
|
? `${lockName} is not handed out now: ${r.maintenance}. You are #${r.position} in line and will be @mentioned when it is yours after the window; do not poll. Leave the queue: b9s unlock ${lockName}`
|
|
1616
1618
|
: r.acquired
|
package/dist/git.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { copyFileSync, existsSync, readdirSync, realpathSync, rmSync, statSync, statfsSync } from "node:fs";
|
|
1
|
+
import { copyFileSync, existsSync, lstatSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, statfsSync } from "node:fs";
|
|
2
2
|
import { spawnSync } from "node:child_process";
|
|
3
3
|
import { hostname } from "node:os";
|
|
4
4
|
import { dirname, isAbsolute, join, relative, sep } from "node:path";
|
|
5
5
|
import { CliError } from "./errors.js";
|
|
6
|
+
import { configDirectory } from "./directories.js";
|
|
6
7
|
export const PRUNE_STATUS_TIMEOUT_MS = 30_000;
|
|
7
8
|
function status(cwd, timeoutMs) {
|
|
8
9
|
const r = spawnSync("git", ["status", "--porcelain"], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 512 * 1024 * 1024, ...(timeoutMs === undefined ? {} : { timeout: timeoutMs }) });
|
|
@@ -108,9 +109,61 @@ export function scanWorktrees(cwd = process.cwd(), options = {}) {
|
|
|
108
109
|
});
|
|
109
110
|
return { repo, worktrees };
|
|
110
111
|
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
112
|
+
function registeredMachineLabel(env) {
|
|
113
|
+
let path;
|
|
114
|
+
try {
|
|
115
|
+
path = join(configDirectory(env), "machine.json");
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
const detail = error instanceof Error ? `: ${error.message}` : "";
|
|
119
|
+
throw new CliError("machine_identity_unavailable", `cannot resolve the machine registration directory${detail}; fix the .bschat/.b9s directory conflict before using host-scoped locks or status`);
|
|
120
|
+
}
|
|
121
|
+
let raw;
|
|
122
|
+
try {
|
|
123
|
+
raw = readFileSync(path, "utf8");
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
const code = error.code;
|
|
127
|
+
if (code === "ENOENT") {
|
|
128
|
+
try {
|
|
129
|
+
lstatSync(path);
|
|
130
|
+
}
|
|
131
|
+
catch (statError) {
|
|
132
|
+
if (statError.code === "ENOENT")
|
|
133
|
+
return undefined;
|
|
134
|
+
throw new CliError("machine_identity_unavailable", `cannot inspect machine registration ${path}; fix its permissions or path before using host-scoped locks or status`);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
throw new CliError("machine_identity_unavailable", `cannot read machine registration ${path} (${code ?? "unknown error"}); fix its permissions or registration before using host-scoped locks or status`);
|
|
138
|
+
}
|
|
139
|
+
let value;
|
|
140
|
+
try {
|
|
141
|
+
value = JSON.parse(raw);
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
throw new CliError("machine_identity_unavailable", `machine registration ${path} is malformed; repair or remove it only if this host is unregistered before using host-scoped locks or status`);
|
|
145
|
+
}
|
|
146
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || typeof value.name !== "string" || !value.name.trim()) {
|
|
147
|
+
throw new CliError("machine_identity_unavailable", `machine registration ${path} has no valid name; repair or remove it only if this host is unregistered before using host-scoped locks or status`);
|
|
148
|
+
}
|
|
149
|
+
return value.name.trim();
|
|
150
|
+
}
|
|
151
|
+
/** The machine shared by every CLI identity running on this host. Saved agent machine fields are not identity. */
|
|
152
|
+
export function defaultMachine(label, env = process.env, host = hostname()) {
|
|
153
|
+
const h = host.trim();
|
|
154
|
+
const registered = registeredMachineLabel(env);
|
|
155
|
+
const resolvedLabel = registered ?? label?.trim();
|
|
156
|
+
return resolvedLabel ? `${h}/${resolvedLabel}` : h;
|
|
157
|
+
}
|
|
158
|
+
/** Use the current host for status and locks; retain a copied identity's machine field only as a diagnostic label. */
|
|
159
|
+
const warnedMachineMismatches = new Set();
|
|
160
|
+
export function machineIdentityForAgent(savedMachine, env = process.env, host = hostname(), warn = (line) => process.stderr.write(`${line}\n`)) {
|
|
161
|
+
const current = defaultMachine(undefined, env, host);
|
|
162
|
+
if (savedMachine && savedMachine !== current && !warnedMachineMismatches.has(`${savedMachine}\0${current}`)) {
|
|
163
|
+
warnedMachineMismatches.add(`${savedMachine}\0${current}`);
|
|
164
|
+
warn(`[b9s] saved machine label "${savedMachine}" differs from this host "${current}"; using the host identity`);
|
|
165
|
+
}
|
|
166
|
+
return current;
|
|
114
167
|
}
|
|
115
168
|
/** True when `ancestor` is reachable from `ref` in the repo at cwd; null when either is unknown to git. */
|
|
116
169
|
export function isAncestor(ancestor, ref, cwd = process.cwd()) {
|
package/dist/harnesses.js
CHANGED
|
@@ -381,7 +381,7 @@ function codexProbe(thread) {
|
|
|
381
381
|
};
|
|
382
382
|
}
|
|
383
383
|
// ---- Claude Code ----
|
|
384
|
-
const claudeHome = () => process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude");
|
|
384
|
+
export const claudeHome = () => process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude");
|
|
385
385
|
/** A Claude Code session's transcript (~/.claude/projects/<folder>/<id>.jsonl), wherever its folder is. */
|
|
386
386
|
export function claudeTranscript(session) {
|
|
387
387
|
const root = join(claudeHome(), "projects");
|
package/dist/help.js
CHANGED
|
@@ -22,6 +22,7 @@ GET /account/usage reports used and allowed micro-dollars, uncertain calls and t
|
|
|
22
22
|
Session/admin clients can use GET /assistant/conversations, GET /assistant/conversations/:id/messages (paged history with saved tool notices), POST /assistant/conversations/:id/messages (SSE), and DELETE /assistant/conversations/:id. Old assistant messages report notices_available=false. The assistant can draft changes; POST /assistant/proposals/:id/apply or /discard is the operator's explicit action. See the agent/operator skill API reference for events and tools.
|
|
23
23
|
Free and paid accounts without a live Stripe subscription use the UTC calendar month; subscribed paid accounts reset at current_period_end.
|
|
24
24
|
|
|
25
|
+
Mac capacity/signing records and the hosted lease allocate/drain intents are documented in docs/MACOS-MACHINES-API.md. Allocation consumes WU #403's reviewed controller outputs; the API does not widen IAM. There is no CLI stop/release bypass. Operator controls are in the named hosted Mac lease console unit WU #381; signing remains a separate trusted worker.
|
|
25
26
|
Mac capacity/signing API (profiles, leases, signer-only references, TestFlight approvals, and the isolated signer job contract) is documented in docs/MACOS-MACHINES-API.md. There is no CLI command to issue signer-host credentials or trigger release; operator controls are WU #286, real host/provider integration is WU #288.
|
|
26
27
|
Standing rules are resolved by account, project, role, and exact-agent scope. GET /agents/me/standing-rules and GET /projects/:p/standing-rules return complete authorized sets and fingerprints; their separate ack endpoints accept only a current fingerprint after complete delivery. Operators and authorized assigners manage rules through the API; limits, compatibility confirmation, audit, and authorization are in packages/skill/references/api.md. Console management and chat promotion are planned in implementation unit 3 of docs/STANDING-RULES.md.
|
|
27
28
|
|
|
@@ -118,6 +119,7 @@ Agent commands
|
|
|
118
119
|
b9s milestone review <key> assigner or operator: request a closure review now (the steward does it when the last unit closes)
|
|
119
120
|
b9s lock <name> [--unit n] [--note ..] [--shared] take this machine's <name> (build slot, scratch) or queue; --shared for a project-wide resource (a test board)
|
|
120
121
|
acquisition queues through a machine maintenance drain/window and resumes after it
|
|
122
|
+
machine identity is this host's hostname plus its registered label, shared by all agents here
|
|
121
123
|
b9s unlock <name> [--machine <label>|--shared] [--remove-empty] | b9s locks
|
|
122
124
|
release it (also released when your unit closes); assigners/operators can remove an empty scoped lock with --remove-empty
|
|
123
125
|
lock names acquire/list/release/show/status are reserved: use lock <name>, locks, or unlock <name> as suggested
|
|
@@ -234,6 +236,7 @@ Machine placement shares capacity across the account's projects: session seats a
|
|
|
234
236
|
b9s machine run [--interval seconds] | once | build-images | status | prepare [--agy-userns] [--print-apparmor] | service
|
|
235
237
|
default interval 30s, 1..3600; prepare checks harnesses; --agy-userns opts into an AppArmor
|
|
236
238
|
profile for the resolved agy binary if Ubuntu blocks its workspace-write terminal sandbox (passwordless sudo)
|
|
239
|
+
Antigravity workspace-write readiness makes an authenticated b9s me call inside the sandbox
|
|
237
240
|
b9s machine processes --worktree <path> [--as <project>/<agent>] [--json] read-only host process sample for a project-owned worktree
|
|
238
241
|
includes pid/parent, start/elapsed, command (120 chars), cwd, TCP listeners and sample time
|
|
239
242
|
project agents only; stale samples are labelled; command credentials are redacted; no environment values or signaling
|
package/dist/install.js
CHANGED
|
@@ -134,14 +134,20 @@ export function binVersion(bin) {
|
|
|
134
134
|
return m ? m[1] : null;
|
|
135
135
|
}
|
|
136
136
|
/** The npm belonging to the Node running this process: the same runtime installs and runs b9s. */
|
|
137
|
-
function ownNpm() {
|
|
138
|
-
const npm = join(dirname(
|
|
137
|
+
export function ownNpm(execPath = process.execPath) {
|
|
138
|
+
const npm = join(dirname(execPath), "npm");
|
|
139
139
|
if (!existsSync(npm))
|
|
140
|
-
throw new CliError("no_npm", `no npm next to the Node running b9s (${
|
|
140
|
+
throw new CliError("no_npm", `no npm next to the Node running b9s (${execPath})`, "Install b9s with that Node's npm yourself (npm i -g benignswarm), then run: b9s install");
|
|
141
141
|
return npm;
|
|
142
142
|
}
|
|
143
|
+
/** npm scripts commonly use /usr/bin/env node, so PATH must select the Node beside this npm. */
|
|
144
|
+
function npmEnv(npm) {
|
|
145
|
+
const npmBin = dirname(resolve(npm));
|
|
146
|
+
const rest = (process.env.PATH ?? "").split(delimiter).filter((entry) => entry && resolve(entry) !== npmBin);
|
|
147
|
+
return { ...process.env, PATH: [npmBin, ...rest].join(delimiter) };
|
|
148
|
+
}
|
|
143
149
|
export function latestPublished(npm) {
|
|
144
|
-
const r = spawnSync(npm, ["view", "benignswarm", "version", "--prefer-online"], { encoding: "utf8", timeout: 60_000 });
|
|
150
|
+
const r = spawnSync(npm, ["view", "benignswarm", "version", "--prefer-online"], { encoding: "utf8", timeout: 60_000, env: npmEnv(npm) });
|
|
145
151
|
const v = (r.stdout ?? "").trim();
|
|
146
152
|
if (r.status !== 0 || !/^\d+\.\d+\.\d+$/.test(v))
|
|
147
153
|
throw new CliError("npm_view_failed", `could not ask npm for the latest benignswarm version (${npm})`, (r.stderr ?? "").trim().slice(0, 300));
|
|
@@ -154,7 +160,8 @@ export function latestPublished(npm) {
|
|
|
154
160
|
*/
|
|
155
161
|
export function ensureInstall(version, log, npmOverride) {
|
|
156
162
|
const npm = npmOverride ?? ownNpm();
|
|
157
|
-
const
|
|
163
|
+
const env = npmEnv(npm);
|
|
164
|
+
const pre = spawnSync(npm, ["prefix", "-g"], { encoding: "utf8", timeout: 30_000, env });
|
|
158
165
|
if (pre.status !== 0)
|
|
159
166
|
throw new CliError("npm_prefix_failed", `${npm} prefix -g failed`, (pre.stderr ?? "").trim().slice(0, 300));
|
|
160
167
|
const bin = join(pre.stdout.trim(), "bin", "b9s");
|
|
@@ -164,7 +171,7 @@ export function ensureInstall(version, log, npmOverride) {
|
|
|
164
171
|
}
|
|
165
172
|
else {
|
|
166
173
|
log(`${current ? `upgrading b9s ${current}` : "installing b9s"} to ${version} with ${npm}`);
|
|
167
|
-
const r = spawnSync(npm, ["i", "-g", `benignswarm@${version}`, "--prefer-online"], { stdio: ["ignore", 2, 2], timeout: 300_000 });
|
|
174
|
+
const r = spawnSync(npm, ["i", "-g", `benignswarm@${version}`, "--prefer-online"], { stdio: ["ignore", 2, 2], timeout: 300_000, env });
|
|
168
175
|
if (r.status !== 0)
|
|
169
176
|
throw new CliError("install_failed", `npm i -g benignswarm@${version} failed (exit ${r.status}) using ${npm}`, "Fix that npm's global prefix (permissions, network) or install it yourself, then run: b9s install");
|
|
170
177
|
const got = binVersion(bin);
|
|
@@ -179,6 +186,34 @@ export function ensureInstall(version, log, npmOverride) {
|
|
|
179
186
|
writeFileSync(installFile(), JSON.stringify(rec, null, 2) + "\n");
|
|
180
187
|
return rec;
|
|
181
188
|
}
|
|
189
|
+
/**
|
|
190
|
+
* Join/setup may refresh the machine install, but only within its recorded prefix. If the invoking
|
|
191
|
+
* CLI is older than the record, refuse before writing hooks instead of risking a downgrade. A first
|
|
192
|
+
* install uses this process's Node; changing the selected Node/npm is reserved for `b9s install`.
|
|
193
|
+
*/
|
|
194
|
+
export function ensureMachineInstall(version, log) {
|
|
195
|
+
const previous = readInstall();
|
|
196
|
+
if (!previous)
|
|
197
|
+
return ensureInstall(version, log, ownNpm());
|
|
198
|
+
if (!previous.npm || !existsSync(previous.npm)) {
|
|
199
|
+
throw new CliError("recorded_npm_missing", `the recorded install npm ${previous.npm || "(missing)"} is unavailable`, `Run ${previous.bin} install --latest from the Node installation you want this machine to use`);
|
|
200
|
+
}
|
|
201
|
+
const prefix = spawnSync(previous.npm, ["prefix", "-g"], { encoding: "utf8", timeout: 30_000, env: npmEnv(previous.npm) });
|
|
202
|
+
if (prefix.status !== 0)
|
|
203
|
+
throw new CliError("recorded_npm_prefix_failed", `${previous.npm} prefix -g failed`, (prefix.stderr ?? "").trim().slice(0, 300));
|
|
204
|
+
const expectedBin = join(dirname(previous.bin), "b9s");
|
|
205
|
+
const resolvedBin = join((prefix.stdout ?? "").trim(), "bin", "b9s");
|
|
206
|
+
if (resolve(expectedBin) !== resolve(resolvedBin)) {
|
|
207
|
+
throw new CliError("recorded_install_prefix_mismatch", `${previous.npm} resolves to ${resolvedBin}, but this machine records ${previous.bin}`, `Run ${previous.bin} install --latest from the Node installation you want this machine to use`);
|
|
208
|
+
}
|
|
209
|
+
// A join/setup invoked by an older npx or global copy must never write its own version back
|
|
210
|
+
// into a newer machine install. The operator can intentionally select or upgrade the install
|
|
211
|
+
// by invoking the explicit install command from the desired Node installation.
|
|
212
|
+
if (/^\d+\.\d+\.\d+$/.test(previous.version) && cmp(previous.version, version) > 0) {
|
|
213
|
+
throw new CliError("recorded_install_newer", `the recorded b9s ${previous.version} at ${previous.bin} is newer than this CLI ${version}`, `Run ${previous.bin} install --latest from the Node installation you want this machine to use`);
|
|
214
|
+
}
|
|
215
|
+
return ensureInstall(version, log, previous.npm);
|
|
216
|
+
}
|
|
182
217
|
/** Creates b9s-named shell links beside aliases of the same recorded install, without replacing another copy. */
|
|
183
218
|
export function ensureCommandLinks(installBin) {
|
|
184
219
|
const prefixBin = dirname(installBin);
|
|
@@ -245,11 +280,38 @@ export function watcherPlists() {
|
|
|
245
280
|
return [];
|
|
246
281
|
return readdirSync(dir).filter((f) => f.endsWith(".plist") && isOurService(f.slice(0, -".plist".length))).map((f) => ({ label: f.slice(0, -".plist".length), path: join(dir, f) }));
|
|
247
282
|
}
|
|
248
|
-
/**
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
283
|
+
/**
|
|
284
|
+
* The launchd domain for this user's services (WU #478). With a desktop session that is gui/<uid>, as
|
|
285
|
+
* always. A Mac with no one signed in at its desktop (FileVault unlocked over SSH, no auto-login) has no
|
|
286
|
+
* gui domain; there services are Background agents in user/<uid>, which load without a desktop session
|
|
287
|
+
* and keep running after the SSH session that loaded them ends. This is a deliberate mode, reported by
|
|
288
|
+
* doctor and machine status, never a silent substitute.
|
|
289
|
+
*/
|
|
290
|
+
export function launchdSessionNow() {
|
|
291
|
+
return spawnSync("launchctl", ["print", `gui/${process.getuid()}`], { stdio: "ignore" }).status === 0 ? "gui" : "headless";
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* The session-type key every LaunchAgent b9s writes carries on a Mac with no desktop session, so it loads
|
|
295
|
+
* as a Background agent in user/<uid> (WU #478). One function for every plist template: the watcher's
|
|
296
|
+
* own template in commands/watch.ts missed it at first, and mini1's first headless watcher was written for
|
|
297
|
+
* gui/<uid> and failed to load.
|
|
298
|
+
*/
|
|
299
|
+
export function launchdSessionTypeXml() {
|
|
300
|
+
return launchdSessionNow() === "headless" ? "\n <key>LimitLoadToSessionType</key><string>Background</string>" : "";
|
|
301
|
+
}
|
|
302
|
+
/** Which domain a written plist belongs to: a Background agent lives in user/<uid>, any other in gui/<uid>. */
|
|
303
|
+
export function plistLaunchdDomain(path) {
|
|
304
|
+
const r = spawnSync("plutil", ["-extract", "LimitLoadToSessionType", "raw", "-o", "-", path], { encoding: "utf8" });
|
|
305
|
+
const background = r.status === 0 && (r.stdout ?? "").trim() === "Background";
|
|
306
|
+
return `${background ? "user" : "gui"}/${process.getuid()}`;
|
|
307
|
+
}
|
|
308
|
+
export function launchdLoadedIn(label) {
|
|
309
|
+
const uid = process.getuid();
|
|
310
|
+
return [`gui/${uid}`, `user/${uid}`].filter((d) => spawnSync("launchctl", ["print", `${d}/${label}`], { stdio: "ignore" }).status === 0);
|
|
311
|
+
}
|
|
312
|
+
function launchdBootout(label, path) {
|
|
313
|
+
// A service may be loaded in either domain (a Mac that gained or lost a desktop session); unload it from each.
|
|
314
|
+
for (const domain of launchdLoadedIn(label)) {
|
|
253
315
|
const out = spawnSync("launchctl", ["bootout", `${domain}/${label}`], { encoding: "utf8" });
|
|
254
316
|
if (out.status !== 0)
|
|
255
317
|
throw new CliError("launchctl_failed", `launchctl bootout ${domain}/${label} failed`, (out.stderr ?? "").trim());
|
|
@@ -258,17 +320,60 @@ export function reloadLaunchAgent(label, path) {
|
|
|
258
320
|
const until = Date.now() + 15_000;
|
|
259
321
|
while (spawnSync("launchctl", ["print", `${domain}/${label}`], { stdio: "ignore" }).status === 0) {
|
|
260
322
|
if (Date.now() > until)
|
|
261
|
-
throw new CliError("launchctl_failed", `launchd still lists ${domain}/${label} 15 s after bootout; nothing was loaded`, `Load it yourself: launchctl bootstrap ${
|
|
323
|
+
throw new CliError("launchctl_failed", `launchd still lists ${domain}/${label} 15 s after bootout; nothing was loaded`, `Load it yourself: launchctl bootstrap ${plistLaunchdDomain(path)} ${path}`);
|
|
262
324
|
spawnSync("sleep", ["0.2"]);
|
|
263
325
|
}
|
|
264
326
|
}
|
|
327
|
+
}
|
|
328
|
+
/** The pid of a loaded LaunchAgent in whichever domain holds it, or null when it is not running. */
|
|
329
|
+
export function launchdPid(label) {
|
|
330
|
+
for (const domain of launchdLoadedIn(label)) {
|
|
331
|
+
const out = spawnSync("launchctl", ["print", `${domain}/${label}`], { encoding: "utf8" }).stdout ?? "";
|
|
332
|
+
const pid = Number(/^\s*pid = (\d+)$/m.exec(out)?.[1]);
|
|
333
|
+
if (Number.isInteger(pid) && pid > 0)
|
|
334
|
+
return pid;
|
|
335
|
+
}
|
|
336
|
+
return null;
|
|
337
|
+
}
|
|
338
|
+
/** What launchd mode this Mac's services use, for the machine report, machine status and doctor (WU #478). */
|
|
339
|
+
export function launchdFacts() {
|
|
340
|
+
const daemonPlist = join(launchAgentsDir(), `${MACHINE_LABEL}.plist`);
|
|
341
|
+
const watchers = {};
|
|
342
|
+
for (const w of watcherServices()) {
|
|
343
|
+
if (w.kind !== "launchd" || w.label === MACHINE_LABEL)
|
|
344
|
+
continue; // the daemon is reported on its own
|
|
345
|
+
const d = plistLaunchdDomain(w.path);
|
|
346
|
+
watchers[d] = (watchers[d] ?? 0) + 1;
|
|
347
|
+
}
|
|
348
|
+
return { session: launchdSessionNow(), daemon_domain: existsSync(daemonPlist) ? plistLaunchdDomain(daemonPlist) : null, watchers };
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* What an operator needs to know about this Mac's launchd mode when provisioning it (WU #478): which domain
|
|
352
|
+
* the services use and what a reboot or sign-out does to them.
|
|
353
|
+
*/
|
|
354
|
+
export function launchdGuidance(session = launchdSessionNow()) {
|
|
355
|
+
const uid = process.getuid();
|
|
356
|
+
return session === "headless"
|
|
357
|
+
? `launchd: headless Mac, services are Background agents in user/${uid}. After a reboot they start once someone logs in over SSH (that also unlocks FileVault); a desktop sign-in is not needed. Harness sign-ins kept in the login keychain (Claude Code's by default) are unreadable without a desktop session; Codex and Antigravity keep theirs in files. External volumes may be refused to processes started while no one is signed in at the desktop: keep the workdir on the internal disk.`
|
|
358
|
+
: `launchd: desktop session, services are LaunchAgents in gui/${uid}. They stop when that user signs out and start again at the next desktop sign-in; for a Mac meant to run unattended, use automatic sign-in, or install the services while no one is signed in so they run headless.`;
|
|
359
|
+
}
|
|
360
|
+
/** One line for status output. */
|
|
361
|
+
export function launchdFactsLine(f) {
|
|
362
|
+
const w = Object.entries(f.watchers).map(([d, n]) => `${n} in ${d}`).join(", ") || "none";
|
|
363
|
+
return `launchd: ${f.session === "headless" ? "headless Mac (no desktop session)" : "desktop session"}; daemon ${f.daemon_domain ?? "not installed"}; watchers ${w}`;
|
|
364
|
+
}
|
|
365
|
+
/** Loads (or reloads) a LaunchAgent from its plist, so what runs is what the file says. */
|
|
366
|
+
export function reloadLaunchAgent(label, path) {
|
|
367
|
+
launchdBootout(label, path);
|
|
368
|
+
const domain = plistLaunchdDomain(path);
|
|
265
369
|
const r = spawnSync("launchctl", ["bootstrap", domain, path], { encoding: "utf8" });
|
|
266
370
|
if (r.status !== 0)
|
|
267
371
|
throw new CliError("launchctl_failed", `launchctl bootstrap ${domain} ${path} failed`, (r.stderr ?? "").trim());
|
|
268
372
|
}
|
|
269
373
|
/** Restarts a loaded LaunchAgent in place (new code, same definition). */
|
|
270
374
|
export function restartLaunchAgent(label) {
|
|
271
|
-
|
|
375
|
+
const domain = launchdLoadedIn(label)[0];
|
|
376
|
+
return !!domain && spawnSync("launchctl", ["kickstart", "-k", `${domain}/${label}`], { stdio: "ignore" }).status === 0;
|
|
272
377
|
}
|
|
273
378
|
export const systemdUserDir = () => join(process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "systemd", "user");
|
|
274
379
|
/** Every watcher service on this machine. */
|
|
@@ -522,7 +627,7 @@ export function installService(label, args, cwd, env, logName) {
|
|
|
522
627
|
<key>WorkingDirectory</key><string>${esc(cwd)}</string>
|
|
523
628
|
<key>RunAtLoad</key><true/>
|
|
524
629
|
<key>KeepAlive</key><true/>
|
|
525
|
-
<key>AbandonProcessGroup</key><true
|
|
630
|
+
<key>AbandonProcessGroup</key><true/>${launchdSessionTypeXml()}
|
|
526
631
|
<key>StandardOutPath</key><string>${join(logDir, `${logName}.out.log`)}</string>
|
|
527
632
|
<key>StandardErrorPath</key><string>${join(logDir, `${logName}.err.log`)}</string>
|
|
528
633
|
</dict></plist>
|
|
@@ -540,19 +645,14 @@ export function removeService(s) {
|
|
|
540
645
|
spawnSync("systemctl", ["--user", "daemon-reload"], { stdio: "ignore" });
|
|
541
646
|
return;
|
|
542
647
|
}
|
|
543
|
-
|
|
544
|
-
if (spawnSync("launchctl", ["print", `${domain}/${s.label}`], { stdio: "ignore" }).status === 0) {
|
|
545
|
-
const r = spawnSync("launchctl", ["bootout", `${domain}/${s.label}`], { encoding: "utf8" });
|
|
546
|
-
if (r.status !== 0)
|
|
547
|
-
throw new CliError("launchctl_failed", `launchctl bootout ${domain}/${s.label} failed`, (r.stderr ?? "").trim());
|
|
548
|
-
}
|
|
648
|
+
launchdBootout(s.label, s.path);
|
|
549
649
|
rmSync(s.path, { force: true });
|
|
550
650
|
}
|
|
551
651
|
/** Whether a service's process is running now. */
|
|
552
652
|
export function serviceActive(s) {
|
|
553
653
|
if (s.kind === "systemd")
|
|
554
654
|
return (spawnSync("systemctl", ["--user", "is-active", `${s.label}.service`], { encoding: "utf8" }).stdout ?? "").trim() === "active";
|
|
555
|
-
return
|
|
655
|
+
return launchdPid(s.label) !== null;
|
|
556
656
|
}
|
|
557
657
|
/** Restarts a watcher service in place (new code, same definition); false when it is not loaded. */
|
|
558
658
|
export function restartWatcher(s) {
|
|
@@ -572,9 +672,7 @@ function watcherPid(service) {
|
|
|
572
672
|
const pid = Number((r.stdout ?? "").trim());
|
|
573
673
|
return r.status === 0 && Number.isInteger(pid) && pid > 0 ? pid : null;
|
|
574
674
|
}
|
|
575
|
-
|
|
576
|
-
const pid = Number(/"PID" = (\d+);/.exec(output)?.[1]);
|
|
577
|
-
return Number.isInteger(pid) && pid > 0 ? pid : null;
|
|
675
|
+
return launchdPid(service.label);
|
|
578
676
|
}
|
|
579
677
|
const watcherRestartDriver = {
|
|
580
678
|
pid: watcherPid,
|
package/dist/lock.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { launchdLoadedIn } from "./install.js";
|
|
1
2
|
import { mkdirSync, openSync, closeSync, readFileSync, unlinkSync, writeSync } from "node:fs";
|
|
2
3
|
import { join } from "node:path";
|
|
3
4
|
import { configRoot } from "./config.js";
|
|
@@ -44,7 +45,7 @@ export function acquireWatchLock(ref, env = process.env, pid = process.pid) {
|
|
|
44
45
|
throw e;
|
|
45
46
|
const holder = Number(readFileSync(p, "utf8").trim());
|
|
46
47
|
if (Number.isInteger(holder) && holder > 0 && alive(holder)) {
|
|
47
|
-
throw new CliError("watch_running", `a watcher for ${ref} is already running (pid ${holder})`, `Stop it first: kill ${holder}, or launchctl bootout gui/$(id -u)/org.benignswarm.watch.${ref.replace("/", ".")} if launchd started it. Lock file: ${p}`);
|
|
48
|
+
throw new CliError("watch_running", `a watcher for ${ref} is already running (pid ${holder})`, `Stop it first: kill ${holder}, or launchctl bootout ${process.platform === "darwin" ? (launchdLoadedIn(`org.benignswarm.watch.${ref.replace("/", ".")}`)[0] ?? `gui/$(id -u)`) : `gui/$(id -u)`}/org.benignswarm.watch.${ref.replace("/", ".")} if launchd started it. Lock file: ${p}`);
|
|
48
49
|
}
|
|
49
50
|
unlinkSync(p); // stale: the process that wrote it is gone
|
|
50
51
|
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { closeSync, fstatSync, openSync, readdirSync, readSync, renameSync, statSync, truncateSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
/**
|
|
4
|
+
* Bounded service logs (WU #481). launchd (StandardErrorPath) and systemd (StandardError=append:)
|
|
5
|
+
* keep the watcher and daemon logs open for the life of the service and nothing rotated them: on
|
|
6
|
+
* 2026-11-18 mbp held 594 MB of watcher logs, one 190 MB file, and the daemon read them every pass.
|
|
7
|
+
*
|
|
8
|
+
* Rotation is copy-and-truncate because the service manager holds the open file: renaming it would
|
|
9
|
+
* leave the service writing to the renamed file. Both managers open these files for append (systemd
|
|
10
|
+
* "append:", launchd's Standard*Path), so after the truncate the next write lands at the new end
|
|
11
|
+
* instead of leaving a hole. The newest `keepBytes` (from a line start) become `<name>.1`, replacing
|
|
12
|
+
* the previous one. A line written between the copy and the truncate is lost; that window is the
|
|
13
|
+
* copy of at most `keepBytes`, once per rotation.
|
|
14
|
+
*/
|
|
15
|
+
export const LOG_ROTATE_BYTES = 20 * 1024 * 1024;
|
|
16
|
+
/** Rotates every `*.log` in `dir` larger than `maxBytes`. Files it cannot read or truncate throw: a failed rotation is never silent. */
|
|
17
|
+
export function rotateLogs(dir, maxBytes = LOG_ROTATE_BYTES, keepBytes = maxBytes) {
|
|
18
|
+
const done = [];
|
|
19
|
+
let names;
|
|
20
|
+
try {
|
|
21
|
+
names = readdirSync(dir);
|
|
22
|
+
}
|
|
23
|
+
catch (e) {
|
|
24
|
+
if (e.code === "ENOENT")
|
|
25
|
+
return done;
|
|
26
|
+
throw e;
|
|
27
|
+
}
|
|
28
|
+
for (const name of names) {
|
|
29
|
+
if (!name.endsWith(".log"))
|
|
30
|
+
continue;
|
|
31
|
+
const path = join(dir, name);
|
|
32
|
+
const size = statSync(path).size;
|
|
33
|
+
if (size <= maxBytes)
|
|
34
|
+
continue;
|
|
35
|
+
done.push({ file: name, bytes_before: size, kept_bytes: rotateOne(path, keepBytes) });
|
|
36
|
+
}
|
|
37
|
+
return done;
|
|
38
|
+
}
|
|
39
|
+
function rotateOne(path, keepBytes) {
|
|
40
|
+
const fd = openSync(path, "r");
|
|
41
|
+
let tail;
|
|
42
|
+
try {
|
|
43
|
+
const size = fstatSync(fd).size;
|
|
44
|
+
const start = Math.max(0, size - keepBytes);
|
|
45
|
+
const buf = Buffer.alloc(size - start);
|
|
46
|
+
let got = 0;
|
|
47
|
+
while (got < buf.length) {
|
|
48
|
+
const n = readSync(fd, buf, got, buf.length - got, start + got);
|
|
49
|
+
if (n === 0)
|
|
50
|
+
break;
|
|
51
|
+
got += n;
|
|
52
|
+
}
|
|
53
|
+
// Start the kept copy at a line boundary unless the whole file fits.
|
|
54
|
+
const nl = start > 0 ? buf.indexOf(0x0a) : -1;
|
|
55
|
+
tail = buf.subarray(nl >= 0 ? nl + 1 : 0, got);
|
|
56
|
+
}
|
|
57
|
+
finally {
|
|
58
|
+
closeSync(fd);
|
|
59
|
+
}
|
|
60
|
+
const previous = `${path}.1`;
|
|
61
|
+
writeFileSync(`${previous}.tmp`, tail);
|
|
62
|
+
renameSync(`${previous}.tmp`, previous);
|
|
63
|
+
truncateSync(path, 0);
|
|
64
|
+
return tail.length;
|
|
65
|
+
}
|
package/dist/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const CLI_VERSION = "0.12.
|
|
1
|
+
export const CLI_VERSION = "0.12.112";
|