benignswarm 0.12.49 → 0.12.51

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  import { parseArgs } from "node:util";
2
2
  import { CliError } from "./errors.js";
3
3
  export const STRING_FLAGS = ["as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task", "state", "blocked-on", "tags", "custom", "vendor", "role", "description", "permissions", "cardinality", "machine", "dir", "confirm", "type", "name", "out", "token", "prefix", "uses", "expires-hours", "skill-dir", "harness", "reply-to", "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent", "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval", "requeue-after", "unacked-after", "category", "command", "follow-delay", "env", "scope", "pr", "note", "add", "remove", "merged", "tag", "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "by", "target", "milestone", "file", "exit", "depends-on", "source", "by", "on", "question", "ruling", "gaps", "unit", "units", "blocks", "sla", "takeover", "max-open", "max-in-progress", "require-scope", "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit", "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email", "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on", "sandbox", "thread", "turn-timeout"];
4
- export const BOOL_FLAGS = ["latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels", "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "unread", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive", "approve", "turn"];
4
+ export const BOOL_FLAGS = ["latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels", "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "unread", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive", "approve", "turn", "service"];
5
5
  export function parse(argv) {
6
6
  const options = {};
7
7
  for (const f of STRING_FLAGS)
@@ -9,7 +9,7 @@ import { requireInstall } from "../install.js";
9
9
  import { bindSession, codexArchivedRollout, codexRollout } from "../sessions.js";
10
10
  import { codexHooksPath } from "./codex.js";
11
11
  import { join } from "./join.js";
12
- import { installLaunchd } from "./watch.js";
12
+ import { installWatcherService } from "./watch.js";
13
13
  const SANDBOXES = ["read-only", "workspace-write", "danger-full-access"];
14
14
  /**
15
15
  * `bschat codex start`: one command that brings a Codex agent up on this machine with no Codex
@@ -36,8 +36,8 @@ export async function codexStart(p, out) {
36
36
  const interval = Number(str(p.flags, "interval") ?? "30");
37
37
  if (!Number.isInteger(interval) || interval < 5)
38
38
  throw new CliError("usage", "--interval must be an integer number of seconds, at least 5");
39
- if (process.platform !== "darwin")
40
- throw new CliError("unsupported", "codex start installs a launchd watcher and is macOS only for now");
39
+ if (process.platform !== "darwin" && process.platform !== "linux")
40
+ throw new CliError("unsupported", "codex start installs its watcher with launchd (macOS) or systemd (Linux)");
41
41
  const codexBin = which("codex");
42
42
  const model = str(p.flags, "model");
43
43
  const effort = str(p.flags, "effort");
@@ -90,14 +90,16 @@ export async function codexStart(p, out) {
90
90
  // 4. The watcher, in turn mode: it runs each later turn itself.
91
91
  const exec = [codexBin, "exec", "resume", thread, ...settings].map(shq).join(" ") + " {text}";
92
92
  const watcherOut = [];
93
- installLaunchd(ref, exec, interval, Number(str(p.flags, "follow-delay") ?? "300"), {}, undefined, { json: false, print: (h) => watcherOut.push(h) }, bool(p.flags, "prune"), turnTimeout);
94
- lines.push(watcherOut.join("\n").split("\n")[0].replace(/^Wrote /, "Watcher: wrote "));
93
+ installWatcherService(ref, exec, interval, Number(str(p.flags, "follow-delay") ?? "300"), {}, undefined, { json: false, print: (h) => watcherOut.push(h) }, bool(p.flags, "prune"), turnTimeout);
94
+ const wl = watcherOut.join("\n").split("\n");
95
+ lines.push(wl[0].replace(/^Wrote /, "Watcher: wrote "), ...wl.filter((l) => l.startsWith("Linger is off")));
95
96
  // 5. Hooks: a headless turn cannot show Codex's trust prompt, and bschat never pre-approves it.
96
97
  const missing = untrustedHooks();
97
98
  lines.push(missing.length
98
99
  ? `Codex has not trusted bschat's hooks (${missing.join(", ")}) on this machine, so turns run without them: no standing rules at session start, no continuing when work arrives mid-turn. Wake-ups still work. To trust them, run \`codex\` once in a terminal here and approve the hooks when it asks.`
99
100
  : `Codex has trust entries for bschat's hooks here. If they changed since they were trusted, Codex skips them until approved again in an interactive \`codex\`.`);
100
101
  lines.push(`Follow it: tail -f ~/.bschat/logs/watch.${ref.replace("/", ".")}.err.log; read its thread with codex resume ${thread} only while no turn is running.`);
102
+ lines.push(`If the Codex account hits its usage limit, the watcher pauses turns until the time Codex gives; after switching to an account with quota, resume at once: bschat codex unpause --as ${ref}`);
101
103
  out.print(lines.join("\n"), { agent: ref, thread, sandbox, model: model ?? null, effort: effort ?? null, exec, first_turn_log: firstTurnLog, untrusted_hooks: missing });
102
104
  }
103
105
  /** Starts a headless Codex session in its own process group and returns its thread id from the JSON event stream. */
@@ -8,11 +8,13 @@ import { withCodexHooks } from "../harness.js";
8
8
  import { requireInstall } from "../install.js";
9
9
  import { bindSession, syncFromWatchers } from "../sessions.js";
10
10
  import { codexStart } from "./codex-start.js";
11
+ import { readState, writeState } from "../state.js";
11
12
  /**
12
13
  * bschat codex hooks install bschat's hooks in ~/.codex/hooks.json (this machine's Codex)
13
14
  * bschat codex bind <thread-id> [--as a] this Codex thread is you: its hooks deliver to you
14
15
  * bschat codex sync bind every thread an installed watcher wakes
15
16
  * bschat codex start --as a --sandbox m run the agent headless: enroll, start or adopt its thread, turn-mode watcher
17
+ * bschat codex unpause [--as a] lift a usage-limit pause now (Codex switched to an account with quota)
16
18
  */
17
19
  export async function codex(p, out) {
18
20
  const sub = p.positionals[1];
@@ -49,6 +51,14 @@ export async function codex(p, out) {
49
51
  }
50
52
  if (sub === "start")
51
53
  return codexStart(p, out);
52
- throw new CliError("usage", "codex hooks | codex bind <thread-id> [--as <agent>] | codex sync | codex start --as <name> --sandbox <mode> [--token ...] [--thread <id>]");
54
+ if (sub === "unpause") {
55
+ // After a usage limit the watcher waits for the reset time Codex gave. When the operator has
56
+ // switched Codex to an account with quota, this lets the next poll start a turn instead.
57
+ const name = resolveAgentName(str(p.flags, "as"));
58
+ writeState(name, { ...readState(name), turn_unpaused_at: Date.now() });
59
+ out.print(`Turns for ${name} may start again: its watcher lifts the usage-limit pause on its next poll (within its --interval).`, { agent: name, unpaused: true });
60
+ return;
61
+ }
62
+ throw new CliError("usage", "codex hooks | codex bind <thread-id> [--as <agent>] | codex sync | codex start --as <name> --sandbox <mode> [--token ...] [--thread <id>] | codex unpause [--as <agent>]");
53
63
  }
54
64
  export const codexHooksPath = () => join(process.env.CODEX_HOME ?? join(homedir(), ".codex"), "hooks.json");
@@ -3,7 +3,7 @@ import { accessSync, constants, existsSync, readFileSync, readdirSync, realpathS
3
3
  import { delimiter, join } from "node:path";
4
4
  import { bool } from "../args.js";
5
5
  import { CliError } from "../errors.js";
6
- import { binVersion, ensureInstall, latestPublished, readInstall, restartLaunchAgent, watcherPlists } from "../install.js";
6
+ import { binVersion, ensureInstall, latestPublished, lingerEnabled, readInstall, restartWatcher, watcherServices } from "../install.js";
7
7
  import { CLI_VERSION } from "../version.js";
8
8
  /**
9
9
  * bschat install [<version> | --latest] make or upgrade this machine's one bschat install and
@@ -23,13 +23,13 @@ export async function install(p, out) {
23
23
  const restarted = [];
24
24
  const elsewhere = [];
25
25
  if (!bool(p.flags, "no-restart")) {
26
- for (const w of watcherPlists()) {
27
- const program = plistJson(w.path)?.ProgramArguments?.[0];
26
+ for (const w of watcherServices()) {
27
+ const program = w.args?.[0];
28
28
  if (program !== rec.bin) {
29
- elsewhere.push(`${w.label} runs ${program ?? "(unreadable plist)"}`);
29
+ elsewhere.push(`${w.label} runs ${program ?? "(unreadable definition)"}`);
30
30
  continue;
31
31
  }
32
- if (restartLaunchAgent(w.label))
32
+ if (restartWatcher(w))
33
33
  restarted.push(w.label);
34
34
  else
35
35
  elsewhere.push(`${w.label} is not loaded (bschat doctor shows how to load it)`);
@@ -100,11 +100,26 @@ export async function doctor(_p, out) {
100
100
  if (existsSync(fp) && readFileSync(fp, "utf8").includes("npx -y benignswarm"))
101
101
  checks.push({ ok: false, what: `${fp} tells agents to use npx`, fix: "bschat setup --as <the agent of that harness> (rewrites it to the recorded install)" });
102
102
  }
103
- // Watchers: what the plist says versus what launchd is running.
103
+ // Watchers: what the definition says versus what is running.
104
104
  const uid = process.getuid?.();
105
- for (const w of watcherPlists()) {
106
- const pj = plistJson(w.path);
107
- const args = pj?.ProgramArguments ?? [];
105
+ const services = watcherServices();
106
+ if (services.some((s) => s.kind === "systemd") && lingerEnabled() === false)
107
+ 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" });
108
+ for (const w of services) {
109
+ const args = w.args ?? [];
110
+ if (w.kind === "systemd") {
111
+ const short = w.label.replace("org.benignswarm.watch.", "");
112
+ if (!args.length) {
113
+ checks.push({ ok: false, what: `watcher ${short}: unreadable unit ${w.path}` });
114
+ continue;
115
+ }
116
+ const ver = binVersion(args[0]);
117
+ if (rec && args[0] !== rec.bin)
118
+ checks.push({ ok: false, what: `watcher ${short} runs ${args[0]} (${ver ?? "does not run"}), not the recorded install`, fix: "re-run its bschat watch ... --service (it uses the recorded install and reloads)" });
119
+ const active = (spawnSync("systemctl", ["--user", "is-active", `${w.label}.service`], { encoding: "utf8" }).stdout ?? "").trim();
120
+ checks.push(active === "active" ? { ok: true, what: `watcher ${short}: running ${args[0]} (${ver ?? "?"})` } : { ok: false, what: `watcher ${short} is ${active || "unknown"}; see ~/.bschat/logs/watch.${short}.err.log`, fix: `systemctl --user daemon-reload && systemctl --user restart ${w.label}.service` });
121
+ continue;
122
+ }
108
123
  const short = w.label.replace("org.benignswarm.watch.", "");
109
124
  const reload = `launchctl bootout gui/${uid}/${w.label}; launchctl bootstrap gui/${uid} ${w.path}`;
110
125
  if (!args.length) {
@@ -137,7 +152,3 @@ export async function doctor(_p, out) {
137
152
  if (problems.length)
138
153
  process.exitCode = 1;
139
154
  }
140
- function plistJson(path) {
141
- const r = spawnSync("plutil", ["-convert", "json", "-o", "-", path], { encoding: "utf8" });
142
- return r.status === 0 ? JSON.parse(r.stdout) : null;
143
- }
@@ -6,7 +6,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
6
  import { dirname, join as pathJoin } from "node:path";
7
7
  import { CliError } from "../errors.js";
8
8
  import { defaultMachine } from "../git.js";
9
- import { ensureInstall } from "../install.js";
9
+ import { ensureInstall, readInstall } from "../install.js";
10
10
  import { codexHooksPath } from "./codex.js";
11
11
  import { claudeCheckoutOwner, claudeCheckoutTaken, withCodexHooks, HARNESSES, findIdentityFile, installForHarness, normalizeVendor, readIdentityFile, writeIdentity } from "../harness.js";
12
12
  import { detectVendor } from "../vendor.js";
@@ -167,8 +167,16 @@ export function assertVendorMatchesRepo(root, name, vendor, replace) {
167
167
  throw new CliError("vendor_mismatch", `${p} says ${name} runs in ${mapped.join(" and ")} here, but this command detected ${vendor}`, `If ${name} runs in ${mapped[0]}, run this from that harness or pass --vendor ${mapped[0]}. If the file is wrong, pass --replace.`);
168
168
  }
169
169
  /** This machine's one install, at least this CLI's version (installed or upgraded when needed). */
170
+ /**
171
+ * The machine's install, upgraded to this version if older. An existing record keeps its npm, so a
172
+ * join run from another Node (an nvm shell, an npx cache) upgrades the machine's install in place
173
+ * instead of moving it there and leaving every watcher on the old copy. Only a first install uses
174
+ * the npm next to the running Node.
175
+ */
170
176
  function machineInstall() {
171
- return ensureInstall(CLI_VERSION, (m) => process.stderr.write(`bschat: ${m}\n`));
177
+ const prev = readInstall();
178
+ const npm = prev?.npm && existsSync(prev.npm) ? prev.npm : undefined;
179
+ return ensureInstall(CLI_VERSION, (m) => process.stderr.write(`bschat: ${m}\n`), npm);
172
180
  }
173
181
  function writeIdentityDryRun(root, vendor, name, replace) {
174
182
  const p = findIdentityFile(root);
@@ -1,11 +1,11 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
2
  import { bindSession, codexArchivedRollout, codexRollout, sessionOfExec, threadOfExec } from "../sessions.js";
3
- import { readTurnPhase, startTurn, stopTurn } from "../turn.js";
3
+ import { readTurnPhase, startTurn, stopTurn, usageLimitUntil } from "../turn.js";
4
4
  import { applyAck } from "./wake.js";
5
- import { reloadLaunchAgent, requireInstall } from "../install.js";
5
+ import { lingerEnabled, loadSystemdUnit, reloadLaunchAgent, requireInstall, systemdUnit, systemdUserDir, WATCH_LABEL_PREFIX } from "../install.js";
6
6
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
7
7
  import { createHash } from "node:crypto";
8
- import { homedir } from "node:os";
8
+ import { homedir, userInfo } from "node:os";
9
9
  import { basename, dirname, join } from "node:path";
10
10
  import { bool, str } from "../args.js";
11
11
  import { configRoot, loadAgent, resolveAgentName } from "../config.js";
@@ -57,9 +57,9 @@ export async function watch(p, out) {
57
57
  if (/\bcodex\s+queue\b/.test(exec) || !thread)
58
58
  throw new CliError("usage", "--turn runs the turn itself: --exec must be codex exec resume <thread-id> ... {text}, not codex queue");
59
59
  }
60
- if (bool(p.flags, "launchd")) {
60
+ if (bool(p.flags, "launchd") || bool(p.flags, "service")) {
61
61
  if (!exec)
62
- throw new CliError("usage", "--launchd needs --exec so the agent knows what to run");
62
+ throw new CliError("usage", "--service needs --exec so the agent knows what to run");
63
63
  const envNames = (str(p.flags, "env") ?? "").split(",").map((x) => x.trim()).filter(Boolean);
64
64
  const extraEnv = {};
65
65
  for (const n of envNames) {
@@ -68,10 +68,10 @@ export async function watch(p, out) {
68
68
  throw new CliError("usage", `--env ${n}: not set in this shell; run this from a terminal inside the harness (Antigravity's terminal has ANTIGRAVITY_LS_ADDRESS and ANTIGRAVITY_CSRF_TOKEN)`);
69
69
  extraEnv[n] = v;
70
70
  }
71
- return installLaunchd(name, exec, interval, followDelay, extraEnv, str(p.flags, "activity"), out, bool(p.flags, "prune"), turnMode ? turnTimeout : null);
71
+ return installWatcherService(name, exec, interval, followDelay, extraEnv, str(p.flags, "activity"), out, bool(p.flags, "prune"), turnMode ? turnTimeout : null);
72
72
  }
73
73
  if (!exec && !once)
74
- throw new CliError("usage", 'watch --exec "<command>" [--interval 30] | watch --once (print and exit) | watch --exec ... --launchd');
74
+ throw new CliError("usage", 'watch --exec "<command>" [--interval 30] | watch --once (print and exit) | watch --exec ... --service (launchd on macOS, systemd on Linux)');
75
75
  const log = (m) => process.stderr.write(`${new Date().toISOString()} bschat watch[${name}]: ${m}\n`);
76
76
  if (!once) {
77
77
  // Only one long-running watcher per identity on this machine; a second one exits here.
@@ -96,7 +96,7 @@ export async function watch(p, out) {
96
96
  // scan on start and then hourly reports worktrees nobody is touching, which agent calls never would.
97
97
  const scanCreds = loadAgent(name);
98
98
  let lastScan = 0;
99
- const ctl = { turn: null, failedAt: 0, loggedRunning: null };
99
+ const ctl = { turn: null, failedAt: 0, loggedRunning: null, pausedUntil: 0, pausedAt: 0 };
100
100
  for (;;) {
101
101
  if (activity && heartbeatClient)
102
102
  lastSample = await heartbeatIfActive(heartbeatClient, activity, lastSample, interval, log);
@@ -338,11 +338,21 @@ async function turnStep(ctl, thread, timeoutMin, log, wake, name) {
338
338
  log(`TURN #${turn.seq} STOPPED after the ${timeoutMin}-min limit (${how}); its work so far is in the session`);
339
339
  }
340
340
  else {
341
- log(`TURN #${turn.seq} FAILED (${how}) after ${mins} min${turn.confirmed ? "" : "; it never started in the session, so the wake-up stays unacknowledged; retrying in 5 min"}. Its output is in this log.`);
342
- if (!turn.confirmed) {
343
- writeState(name, { ...readState(name), watch_pending: undefined, watch_dormant_logged_at: undefined });
344
- ctl.failedAt = Date.now();
341
+ // Every failure waits before the next turn: a turn started right after one that failed
342
+ // usually fails the same way. A usage limit waits until the time Codex names.
343
+ const error = rollout ? readTurnPhase(rollout).lastError : null;
344
+ const until = usageLimitUntil(error);
345
+ if (until && until > Date.now()) {
346
+ ctl.pausedUntil = until;
347
+ ctl.pausedAt = Date.now();
348
+ log(`TURN #${turn.seq} FAILED: the Codex account hit its usage limit; no turns until ${new Date(until).toISOString()} (Codex said: ${error})`);
349
+ }
350
+ else {
351
+ log(`TURN #${turn.seq} FAILED (${how}) after ${mins} min${turn.confirmed ? "" : "; it never started in the session, so the wake-up stays unacknowledged"}${error ? `; Codex said: ${error}` : ""}. Next turn in 5 min at the earliest; its output is in this log.`);
345
352
  }
353
+ if (!turn.confirmed)
354
+ writeState(name, { ...readState(name), watch_pending: undefined, watch_dormant_logged_at: undefined });
355
+ ctl.failedAt = Date.now();
346
356
  }
347
357
  ctl.turn = null;
348
358
  return;
@@ -353,12 +363,29 @@ async function turnStep(ctl, thread, timeoutMin, log, wake, name) {
353
363
  }
354
364
  return;
355
365
  }
366
+ // bschat codex unpause: the operator switched Codex to an account with quota.
367
+ const unpausedAt = readState(name).turn_unpaused_at ?? 0;
368
+ if (ctl.pausedUntil > Date.now() && unpausedAt > ctl.pausedAt) {
369
+ log(`usage-limit pause lifted by bschat codex unpause`);
370
+ ctl.pausedUntil = 0;
371
+ ctl.failedAt = 0;
372
+ }
356
373
  if (Date.now() - ctl.failedAt < TURN_RETRY_MS)
357
374
  return;
375
+ if (ctl.pausedUntil > Date.now())
376
+ return;
358
377
  if (rollout) {
359
378
  // A turn this watcher did not start: the Codex app, or a turn left running by a watcher that
360
379
  // restarted (turns run in their own process group and outlive it). Never start a second one.
361
380
  const ph = readTurnPhase(rollout);
381
+ // A watcher that restarted after a usage-limit failure reads the pause from the session itself.
382
+ const until = !ph.running && Date.parse(ph.lastEventAt ?? "") > unpausedAt ? usageLimitUntil(ph.lastError) : null;
383
+ if (until && until > Date.now()) {
384
+ ctl.pausedUntil = until;
385
+ ctl.pausedAt = Date.now();
386
+ log(`the last turn in thread ${thread} hit the Codex usage limit; no turns until ${new Date(until).toISOString()}`);
387
+ return;
388
+ }
362
389
  if (ph.running) {
363
390
  const quietMs = Date.now() - Date.parse(ph.lastEventAt ?? ph.startedAt);
364
391
  if (quietMs < timeoutMin * 60_000) {
@@ -430,8 +457,40 @@ function run(cmd, stdin, env) {
430
457
  child.on("error", () => resolve(1));
431
458
  });
432
459
  }
460
+ /**
461
+ * Installs the watcher as a service that keeps it running for this identity: a LaunchAgent on macOS,
462
+ * a systemd user unit on Linux. Both run the machine's recorded install from this directory.
463
+ */
464
+ export function installWatcherService(name, exec, interval, followDelay, extraEnv, activity, out, prune = false, turnTimeout = null) {
465
+ if (process.platform === "darwin")
466
+ return installLaunchd(name, exec, interval, followDelay, extraEnv, activity, out, prune, turnTimeout);
467
+ if (process.platform !== "linux")
468
+ throw new CliError("unsupported", "--service runs watchers under launchd (macOS) or systemd (Linux); on this system run bschat watch under your own supervisor");
469
+ const slug = name.replace("/", ".");
470
+ const label = `${WATCH_LABEL_PREFIX}${slug}`;
471
+ const logDir = join(homedir(), ".bschat", "logs");
472
+ mkdirSync(systemdUserDir(), { recursive: true });
473
+ mkdirSync(logDir, { recursive: true });
474
+ const args = [requireInstall().bin, "watch", "--as", name, "--exec", exec, "--interval", String(interval), "--follow-delay", String(followDelay), ...(activity ? ["--activity", activity] : []), ...(prune ? ["--prune"] : []), ...(turnTimeout !== null ? ["--turn", "--turn-timeout", String(turnTimeout)] : [])];
475
+ const env = { PATH: process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin", HOME: homedir(), ...extraEnv };
476
+ const path = join(systemdUserDir(), `${label}.service`);
477
+ writeFileSync(path, systemdUnit(label, args, process.cwd(), env, logDir));
478
+ loadSystemdUnit(label);
479
+ const sess = sessionOfExec(exec);
480
+ if (sess)
481
+ bindSession(sess.kind, sess.id, name);
482
+ const linger = lingerEnabled();
483
+ out.print([
484
+ `Wrote ${path} and (re)started it: the watcher is running ${args[0]}.`,
485
+ linger === false ? `Linger is off for ${userInfo().username}: systemd stops this watcher when your last login session on this machine ends. To keep it running: loginctl enable-linger ${userInfo().username}` : null,
486
+ `Stop it: systemctl --user disable --now ${label}.service`,
487
+ `Logs: ${logDir}/watch.${slug}.*.log`,
488
+ `Check it: bschat doctor`,
489
+ `The watcher runs from ${process.cwd()} so the repo identity file applies.`,
490
+ ].filter(Boolean).join("\n"), { unit: path, label, program: args[0], linger });
491
+ }
433
492
  /** Writes a launchd agent that keeps `bschat watch` running for this identity on macOS. */
434
- export function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, out, prune = false, turnTimeout = null) {
493
+ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, out, prune = false, turnTimeout = null) {
435
494
  if (process.platform !== "darwin")
436
495
  throw new CliError("unsupported", "--launchd is macOS only; on Linux run `bschat watch` under a systemd user service");
437
496
  const slug = name.replace("/", ".");
package/dist/install.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, writeFileSync } from "node:fs";
3
- import { homedir } from "node:os";
3
+ import { homedir, userInfo } from "node:os";
4
4
  import { dirname, join } from "node:path";
5
5
  import { configRoot } from "./config.js";
6
6
  import { CliError } from "./errors.js";
@@ -97,6 +97,14 @@ export function reloadLaunchAgent(label, path) {
97
97
  const out = spawnSync("launchctl", ["bootout", `${domain}/${label}`], { encoding: "utf8" });
98
98
  if (out.status !== 0)
99
99
  throw new CliError("launchctl_failed", `launchctl bootout ${domain}/${label} failed`, (out.stderr ?? "").trim());
100
+ // bootout returns before launchd has finished removing the job, and a bootstrap in that window
101
+ // fails, leaving the watcher unloaded (luna-worker's, after codex start). Wait until it is gone.
102
+ const until = Date.now() + 15_000;
103
+ while (spawnSync("launchctl", ["print", `${domain}/${label}`], { stdio: "ignore" }).status === 0) {
104
+ if (Date.now() > until)
105
+ throw new CliError("launchctl_failed", `launchd still lists ${domain}/${label} 15 s after bootout; nothing was loaded`, `Load it yourself: launchctl bootstrap ${domain} ${path}`);
106
+ spawnSync("sleep", ["0.2"]);
107
+ }
100
108
  }
101
109
  const r = spawnSync("launchctl", ["bootstrap", domain, path], { encoding: "utf8" });
102
110
  if (r.status !== 0)
@@ -106,6 +114,79 @@ export function reloadLaunchAgent(label, path) {
106
114
  export function restartLaunchAgent(label) {
107
115
  return spawnSync("launchctl", ["kickstart", "-k", `gui/${process.getuid()}/${label}`], { stdio: "ignore" }).status === 0;
108
116
  }
117
+ export const systemdUserDir = () => join(process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "systemd", "user");
118
+ /** Every watcher service on this machine. */
119
+ export function watcherServices() {
120
+ if (process.platform === "darwin")
121
+ return watcherPlists().map((w) => ({ kind: "launchd", ...w, args: plistArgs(w.path) }));
122
+ const dir = systemdUserDir();
123
+ if (process.platform !== "linux" || !existsSync(dir))
124
+ return [];
125
+ return readdirSync(dir)
126
+ .filter((f) => f.startsWith(WATCH_LABEL_PREFIX) && f.endsWith(".service"))
127
+ .map((f) => ({ kind: "systemd", label: f.slice(0, -".service".length), path: join(dir, f), args: unitArgs(readFileSync(join(dir, f), "utf8")) }));
128
+ }
129
+ export function plistArgs(path) {
130
+ const r = spawnSync("plutil", ["-convert", "json", "-o", "-", path], { encoding: "utf8" });
131
+ return r.status === 0 ? (JSON.parse(r.stdout).ProgramArguments ?? null) : null;
132
+ }
133
+ /** The command line a unit written by `systemdUnit` runs, from its `# bschat-args:` line. */
134
+ export function unitArgs(text) {
135
+ const m = /^# bschat-args: (.*)$/m.exec(text);
136
+ if (!m)
137
+ return null;
138
+ const a = JSON.parse(m[1]);
139
+ return Array.isArray(a) && a.every((x) => typeof x === "string") ? a : null;
140
+ }
141
+ /** systemd's quoting for one ExecStart word or Environment assignment: double quotes, with %, $, \ and " escaped. */
142
+ const sdq = (s) => `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%").replace(/\$/g, "$$$$")}"`;
143
+ /**
144
+ * A systemd user unit that keeps a watcher running. KillMode=process: a restart or upgrade stops the
145
+ * watcher only, never a Codex turn it started (turns run in their own process group, like on macOS).
146
+ */
147
+ export function systemdUnit(label, args, cwd, env, logDir) {
148
+ const slug = label.slice(WATCH_LABEL_PREFIX.length);
149
+ return [
150
+ `# Written by bschat; re-run its bschat watch ... --service (or bschat codex start) to change it.`,
151
+ `# bschat-args: ${JSON.stringify(args)}`,
152
+ `[Unit]`,
153
+ `Description=bschat watcher for ${slug}`,
154
+ `After=network-online.target`,
155
+ ``,
156
+ `[Service]`,
157
+ `ExecStart=${args.map(sdq).join(" ")}`,
158
+ `WorkingDirectory=${sdq(cwd)}`,
159
+ ...Object.entries(env).map(([k, v]) => `Environment=${sdq(`${k}=${v}`)}`),
160
+ `Restart=always`,
161
+ `RestartSec=5`,
162
+ `KillMode=process`,
163
+ `StandardOutput=append:${join(logDir, `watch.${slug}.out.log`)}`,
164
+ `StandardError=append:${join(logDir, `watch.${slug}.err.log`)}`,
165
+ ``,
166
+ `[Install]`,
167
+ `WantedBy=default.target`,
168
+ ``,
169
+ ].join("\n");
170
+ }
171
+ /** Loads (or reloads) a systemd user unit from its file and (re)starts it; throws when systemd refuses. */
172
+ export function loadSystemdUnit(label) {
173
+ for (const args of [["daemon-reload"], ["enable", `${label}.service`], ["restart", `${label}.service`]]) {
174
+ const r = spawnSync("systemctl", ["--user", ...args], { encoding: "utf8" });
175
+ if (r.status !== 0)
176
+ throw new CliError("systemctl_failed", `systemctl --user ${args.join(" ")} failed`, (r.stderr ?? "").trim());
177
+ }
178
+ }
179
+ /** Restarts a watcher service in place (new code, same definition); false when it is not loaded. */
180
+ export function restartWatcher(s) {
181
+ if (s.kind === "launchd")
182
+ return restartLaunchAgent(s.label);
183
+ return spawnSync("systemctl", ["--user", "restart", `${s.label}.service`], { stdio: "ignore" }).status === 0;
184
+ }
185
+ /** Whether this user's systemd services run while nobody is logged in (null when it cannot be told). */
186
+ export function lingerEnabled() {
187
+ const r = spawnSync("loginctl", ["show-user", userInfo().username, "-p", "Linger", "--value"], { encoding: "utf8" });
188
+ return r.status === 0 ? r.stdout.trim() === "yes" : null;
189
+ }
109
190
  /** Commands that legitimately run from a copy other than the recorded install (npx join, old npx hooks). */
110
191
  const GUARD_EXEMPT = new Set(["join", "setup", "install", "doctor", "hook", "watch"]);
111
192
  /**
package/dist/sessions.js CHANGED
@@ -1,10 +1,9 @@
1
- import { spawnSync } from "node:child_process";
2
1
  import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
3
2
  import { homedir } from "node:os";
4
3
  import { dirname, join } from "node:path";
5
4
  import { configRoot } from "./config.js";
6
5
  import { CliError } from "./errors.js";
7
- import { watcherPlists } from "./install.js";
6
+ import { watcherServices } from "./install.js";
8
7
  const file = (kind) => join(configRoot(), `${kind}.json`);
9
8
  const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
10
9
  function read(kind) {
@@ -54,11 +53,8 @@ export function conversationOfExec(exec) {
54
53
  /** Binds every session an installed watcher wakes (Antigravity conversation, Codex thread) to the agent it runs as. */
55
54
  export function syncFromWatchers() {
56
55
  const out = [];
57
- for (const w of watcherPlists()) {
58
- const r = spawnSync("plutil", ["-convert", "json", "-o", "-", w.path], { encoding: "utf8" });
59
- if (r.status !== 0)
60
- continue;
61
- const args = JSON.parse(r.stdout).ProgramArguments ?? [];
56
+ for (const w of watcherServices()) {
57
+ const args = w.args ?? [];
62
58
  const exec = args[args.indexOf("--exec") + 1] ?? "";
63
59
  const as = args[args.indexOf("--as") + 1];
64
60
  const sess = sessionOfExec(exec);
package/dist/turn.js CHANGED
@@ -5,6 +5,7 @@ export function codexTurnPhase(rolloutText) {
5
5
  let open = null;
6
6
  let startedAt = null;
7
7
  let lastEventAt = null;
8
+ let lastError = null;
8
9
  for (const line of rolloutText.split("\n")) {
9
10
  if (!line)
10
11
  continue;
@@ -23,11 +24,28 @@ export function codexTurnPhase(rolloutText) {
23
24
  if (t === "task_started") {
24
25
  open = j.timestamp ?? null;
25
26
  startedAt = open;
27
+ lastError = null;
26
28
  }
27
- else if (t === "task_complete" || t === "turn_aborted")
29
+ else if (t === "task_complete" || t === "turn_aborted") {
28
30
  open = null;
31
+ lastError = j.payload?.error?.message ?? null;
32
+ }
29
33
  }
30
- return { running: open !== null, startedAt, lastEventAt };
34
+ return { running: open !== null, startedAt, lastEventAt, lastError };
35
+ }
36
+ /**
37
+ * When a Codex usage-limit error says turns may resume ("You've hit your usage limit. ... try again
38
+ * at Nov 11th, 2026 3:32 PM", local time), or null when the error is something else. Every Codex
39
+ * agent on that ChatGPT account is out until then, so starting turns before it only fails again.
40
+ */
41
+ export function usageLimitUntil(error) {
42
+ if (!error || !/usage limit/i.test(error))
43
+ return null;
44
+ const m = /try again at ([A-Z][a-z]{2,8} \d{1,2})(?:st|nd|rd|th)?, (\d{4}) (\d{1,2}:\d{2} ?[AP]M)/.exec(error);
45
+ if (!m)
46
+ return null;
47
+ const t = Date.parse(`${m[1]}, ${m[2]} ${m[3]}`);
48
+ return Number.isNaN(t) ? null : t;
31
49
  }
32
50
  export function readTurnPhase(rollout) {
33
51
  return codexTurnPhase(readFileSync(rollout, "utf8"));
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.49";
1
+ export const CLI_VERSION = "0.12.51";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.49",
3
+ "version": "0.12.51",
4
4
  "description": "bschat: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -16,6 +16,7 @@
16
16
  ],
17
17
  "type": "module",
18
18
  "bin": {
19
+ "benignswarm": "dist/index.js",
19
20
  "bschat": "dist/index.js",
20
21
  "bschat-admin": "dist/admin-index.js"
21
22
  },