benignswarm 0.12.50 → 0.12.52
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/args.js +2 -2
- package/dist/commands/admin.js +4 -0
- package/dist/commands/codex-start.js +18 -7
- package/dist/commands/codex.js +11 -1
- package/dist/commands/install.js +24 -13
- package/dist/commands/machine-admin.js +163 -0
- package/dist/commands/machine.js +284 -0
- package/dist/commands/watch.js +50 -9
- package/dist/harness.js +41 -0
- package/dist/help.js +16 -2
- package/dist/index.js +2 -0
- package/dist/install.js +139 -3
- package/dist/sessions.js +3 -7
- package/dist/version.js +1 -1
- package/package.json +2 -1
package/dist/args.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { parseArgs } from "node:util";
|
|
2
2
|
import { CliError } from "./errors.js";
|
|
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"];
|
|
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", "ssh"];
|
|
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", "print-hooks", "create", "rotate"];
|
|
5
5
|
export function parse(argv) {
|
|
6
6
|
const options = {};
|
|
7
7
|
for (const f of STRING_FLAGS)
|
package/dist/commands/admin.js
CHANGED
|
@@ -7,6 +7,7 @@ import { spawnSync } from "node:child_process";
|
|
|
7
7
|
import { CliError } from "../errors.js";
|
|
8
8
|
import { table } from "../output.js";
|
|
9
9
|
import { milestoneWith, milestonesWith } from "./wu.js";
|
|
10
|
+
import { machineAdmin } from "./machine-admin.js";
|
|
10
11
|
import { accountAdmin, answerAdmin, keysAdmin, needsAdmin, notifierAdmin, processAdmin, skillAdmin, tagList, worktreeAdmin } from "./operator.js";
|
|
11
12
|
function adminClient(p) {
|
|
12
13
|
return Client.forAdmin(loadAdmin(resolveAdminName(str(p.flags, "admin"))));
|
|
@@ -89,6 +90,9 @@ export async function admin(p, out) {
|
|
|
89
90
|
return accountAdmin(p, out);
|
|
90
91
|
case "worktree":
|
|
91
92
|
return worktreeAdmin(action, rest, p, out);
|
|
93
|
+
case "machine":
|
|
94
|
+
case "machines":
|
|
95
|
+
return machineAdmin(action, rest, p, out);
|
|
92
96
|
case "skill":
|
|
93
97
|
return skillAdmin(action, p, out);
|
|
94
98
|
case "delete-account": {
|
|
@@ -8,8 +8,9 @@ import { CliError } from "../errors.js";
|
|
|
8
8
|
import { requireInstall } from "../install.js";
|
|
9
9
|
import { bindSession, codexArchivedRollout, codexRollout } from "../sessions.js";
|
|
10
10
|
import { codexHooksPath } from "./codex.js";
|
|
11
|
+
import { CODEX_MANAGED_MARK } from "../harness.js";
|
|
11
12
|
import { join } from "./join.js";
|
|
12
|
-
import {
|
|
13
|
+
import { installWatcherService } from "./watch.js";
|
|
13
14
|
const SANDBOXES = ["read-only", "workspace-write", "danger-full-access"];
|
|
14
15
|
/**
|
|
15
16
|
* `bschat codex start`: one command that brings a Codex agent up on this machine with no Codex
|
|
@@ -36,8 +37,8 @@ export async function codexStart(p, out) {
|
|
|
36
37
|
const interval = Number(str(p.flags, "interval") ?? "30");
|
|
37
38
|
if (!Number.isInteger(interval) || interval < 5)
|
|
38
39
|
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
|
|
40
|
+
if (process.platform !== "darwin" && process.platform !== "linux")
|
|
41
|
+
throw new CliError("unsupported", "codex start installs its watcher with launchd (macOS) or systemd (Linux)");
|
|
41
42
|
const codexBin = which("codex");
|
|
42
43
|
const model = str(p.flags, "model");
|
|
43
44
|
const effort = str(p.flags, "effort");
|
|
@@ -90,14 +91,16 @@ export async function codexStart(p, out) {
|
|
|
90
91
|
// 4. The watcher, in turn mode: it runs each later turn itself.
|
|
91
92
|
const exec = [codexBin, "exec", "resume", thread, ...settings].map(shq).join(" ") + " {text}";
|
|
92
93
|
const watcherOut = [];
|
|
93
|
-
|
|
94
|
-
|
|
94
|
+
installWatcherService(ref, exec, interval, Number(str(p.flags, "follow-delay") ?? "300"), {}, undefined, { json: false, print: (h) => watcherOut.push(h) }, bool(p.flags, "prune"), turnTimeout);
|
|
95
|
+
const wl = watcherOut.join("\n").split("\n");
|
|
96
|
+
lines.push(wl[0].replace(/^Wrote /, "Watcher: wrote "), ...wl.filter((l) => l.startsWith("Linger is off")));
|
|
95
97
|
// 5. Hooks: a headless turn cannot show Codex's trust prompt, and bschat never pre-approves it.
|
|
96
98
|
const missing = untrustedHooks();
|
|
97
99
|
lines.push(missing.length
|
|
98
100
|
? `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
101
|
: `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
102
|
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.`);
|
|
103
|
+
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
104
|
out.print(lines.join("\n"), { agent: ref, thread, sandbox, model: model ?? null, effort: effort ?? null, exec, first_turn_log: firstTurnLog, untrusted_hooks: missing });
|
|
102
105
|
}
|
|
103
106
|
/** Starts a headless Codex session in its own process group and returns its thread id from the JSON event stream. */
|
|
@@ -134,10 +137,18 @@ export function threadFromExecJson(text) {
|
|
|
134
137
|
}
|
|
135
138
|
return null;
|
|
136
139
|
}
|
|
137
|
-
/**
|
|
138
|
-
|
|
140
|
+
/**
|
|
141
|
+
* bschat's hook events with no trust entry in Codex's config.toml (`[hooks.state."<hooks.json>:<event>:0:0"]`),
|
|
142
|
+
* or none when they are in Codex's administrator layer (bschat-admin machine add), trusted by policy.
|
|
143
|
+
*/
|
|
144
|
+
export function untrustedHooks(configText = readCodexConfig(), hooksPath = codexHooksPath(), requirements = readRequirements()) {
|
|
145
|
+
if (requirements.startsWith(CODEX_MANAGED_MARK))
|
|
146
|
+
return [];
|
|
139
147
|
return ["session_start", "user_prompt_submit", "post_tool_use", "stop"].filter((e) => !configText.includes(`[hooks.state."${hooksPath}:${e}:0:0"]`));
|
|
140
148
|
}
|
|
149
|
+
function readRequirements() {
|
|
150
|
+
return existsSync("/etc/codex/requirements.toml") ? readFileSync("/etc/codex/requirements.toml", "utf8") : "";
|
|
151
|
+
}
|
|
141
152
|
function readCodexConfig() {
|
|
142
153
|
const f = joinPath(process.env.CODEX_HOME ?? joinPath(homedir(), ".codex"), "config.toml");
|
|
143
154
|
return existsSync(f) ? readFileSync(f, "utf8") : "";
|
package/dist/commands/codex.js
CHANGED
|
@@ -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
|
-
|
|
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");
|
package/dist/commands/install.js
CHANGED
|
@@ -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,
|
|
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
|
|
27
|
-
const program =
|
|
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
|
|
29
|
+
elsewhere.push(`${w.label} runs ${program ?? "(unreadable definition)"}`);
|
|
30
30
|
continue;
|
|
31
31
|
}
|
|
32
|
-
if (
|
|
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
|
|
103
|
+
// Watchers: what the definition says versus what is running.
|
|
104
104
|
const uid = process.getuid?.();
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
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
|
-
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { bool, str } from "../args.js";
|
|
3
|
+
import { Client } from "../client.js";
|
|
4
|
+
import { loadAdmin, resolveAdminName } from "../config.js";
|
|
5
|
+
import { CliError } from "../errors.js";
|
|
6
|
+
import { table } from "../output.js";
|
|
7
|
+
import { CLI_VERSION } from "../version.js";
|
|
8
|
+
/**
|
|
9
|
+
* bschat-admin machine: provision machines over the operator's own ssh and declare the agent
|
|
10
|
+
* sessions they run (docs/REMOTE-MACHINES.md). The server never sees an ssh credential: every ssh
|
|
11
|
+
* call here runs in the operator's terminal, and the machine key reaches the machine on ssh's stdin.
|
|
12
|
+
*
|
|
13
|
+
* machine add <name> --ssh <host> [--rotate]
|
|
14
|
+
* machine list | show <name> | remove <name>
|
|
15
|
+
* machine session add <machine> <project>/<agent> --dir <path> --sandbox <mode> [--create --role r] [--model m] [--effort e] [--thread id] [--turn-timeout min]
|
|
16
|
+
* machine session stop|start|remove <machine> <project>/<agent>
|
|
17
|
+
*/
|
|
18
|
+
const adminClient = (p) => Client.forAdmin(loadAdmin(resolveAdminName(str(p.flags, "admin"))));
|
|
19
|
+
/**
|
|
20
|
+
* Brings Node 22+ and bschat to the machine without sudo: Node's official tarball under
|
|
21
|
+
* ~/.local/node (checked against nodejs.org's SHASUMS256), bschat installed with that npm and
|
|
22
|
+
* recorded as the machine's install, both linked into ~/.local/bin. Prints one BSCHAT-STEP line per
|
|
23
|
+
* step; any failure stops it with a FAILED line.
|
|
24
|
+
*/
|
|
25
|
+
export function bootstrapScript(version) {
|
|
26
|
+
return `set -u
|
|
27
|
+
step() { echo "BSCHAT-STEP $1 $2 \${3:-}"; }
|
|
28
|
+
fail() { step "$1" failed "$2"; exit 1; }
|
|
29
|
+
mkdir -p "$HOME/.local/bin"
|
|
30
|
+
case ":$PATH:" in *":$HOME/.local/bin:"*) ;; *) export PATH="$HOME/.local/bin:$PATH"; printf '\\nexport PATH="$HOME/.local/bin:$PATH" # bschat\\n' >> "$HOME/.profile"; step path done "added ~/.local/bin to ~/.profile" ;; esac
|
|
31
|
+
major=0
|
|
32
|
+
if command -v node >/dev/null 2>&1; then major=$(node -p 'process.versions.node.split(".")[0]'); fi
|
|
33
|
+
if [ "$major" -ge 22 ]; then step node ok "$(node --version) $(command -v node)"
|
|
34
|
+
else
|
|
35
|
+
os=$(uname -s | tr A-Z a-z); case "$(uname -m)" in x86_64|amd64) a=x64 ;; aarch64|arm64) a=arm64 ;; *) fail node "unsupported CPU $(uname -m)" ;; esac
|
|
36
|
+
base=https://nodejs.org/dist/latest-v24.x
|
|
37
|
+
f=$(curl -fsSL $base/SHASUMS256.txt | awk -v want="node-v[0-9.]*-$os-$a.tar.xz" '$2 ~ "^"want"$" {print $2}') || fail node "cannot reach nodejs.org"
|
|
38
|
+
[ -n "$f" ] || fail node "no Node 24 build for $os-$a"
|
|
39
|
+
tmp=$(mktemp -d); curl -fsSL -o "$tmp/$f" "$base/$f" || fail node "download failed"
|
|
40
|
+
(cd "$tmp" && curl -fsSL $base/SHASUMS256.txt | grep " $f\\$" | (sha256sum -c - 2>/dev/null || shasum -a 256 -c -)) >/dev/null || fail node "checksum mismatch for $f"
|
|
41
|
+
rm -rf "$HOME/.local/node" && mkdir -p "$HOME/.local/node" && tar -xJf "$tmp/$f" -C "$HOME/.local/node" --strip-components=1 || fail node "unpack failed"
|
|
42
|
+
rm -rf "$tmp"
|
|
43
|
+
for b in node npm npx; do ln -sf "$HOME/.local/node/bin/$b" "$HOME/.local/bin/$b"; done
|
|
44
|
+
hash -r; step node done "$(node --version) in ~/.local/node"
|
|
45
|
+
fi
|
|
46
|
+
npx -y -p benignswarm@${version} bschat install ${version} >/tmp/bschat-install.$$ 2>&1 || fail bschat "$(tail -1 /tmp/bschat-install.$$)"
|
|
47
|
+
rm -f /tmp/bschat-install.$$
|
|
48
|
+
bin=$(node -p 'require(require("os").homedir()+"/.bschat/install.json").bin')
|
|
49
|
+
for b in bschat bschat-admin; do [ -e "$HOME/.local/bin/$b" ] || ln -sf "$(dirname "$bin")/$b" "$HOME/.local/bin/$b"; done
|
|
50
|
+
step bschat ok "$("$bin" --version) $bin"
|
|
51
|
+
`;
|
|
52
|
+
}
|
|
53
|
+
function ssh(host, command, input) {
|
|
54
|
+
const r = spawnSync("ssh", ["-o", "BatchMode=yes", host, command], { input, encoding: "utf8", timeout: 600_000, maxBuffer: 16 * 1024 * 1024 });
|
|
55
|
+
if (r.error)
|
|
56
|
+
throw new CliError("ssh_failed", `ssh ${host}: ${r.error.message}`);
|
|
57
|
+
return { status: r.status ?? 255, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
|
|
58
|
+
}
|
|
59
|
+
/** Runs a bschat command on the machine in a login shell (so ~/.local/bin and the harness CLIs are on PATH). */
|
|
60
|
+
const remoteBschat = (host, args, input) => ssh(host, `bash -lc ${JSON.stringify(`bschat ${args}`)}`, input);
|
|
61
|
+
export async function machineAdmin(action, rest, p, out) {
|
|
62
|
+
const c = adminClient(p);
|
|
63
|
+
if (action === "add") {
|
|
64
|
+
const name = rest[0];
|
|
65
|
+
const host = str(p.flags, "ssh");
|
|
66
|
+
if (!name || !host)
|
|
67
|
+
throw new CliError("usage", "machine add <name> --ssh <host> (the host as your ssh knows it: an alias, user@host)");
|
|
68
|
+
const lines = [];
|
|
69
|
+
const say = (l) => { lines.push(l); if (!out.json)
|
|
70
|
+
process.stderr.write(`${l}\n`); };
|
|
71
|
+
// 1. Node and bschat, over the operator's ssh.
|
|
72
|
+
const boot = ssh(host, "bash -l -s", bootstrapScript(CLI_VERSION));
|
|
73
|
+
const steps = boot.stdout.split("\n").filter((l) => l.startsWith("BSCHAT-STEP ")).map((l) => l.slice(12));
|
|
74
|
+
for (const s of steps)
|
|
75
|
+
say(` ${s}`);
|
|
76
|
+
if (boot.status !== 0)
|
|
77
|
+
throw new CliError("provision_failed", `bootstrapping ${host} failed${steps.length ? `: ${steps[steps.length - 1]}` : `: ${boot.stderr.trim().slice(-300)}`}`);
|
|
78
|
+
// 2. Linger, Codex, managed hooks: checked and fixed on the machine itself.
|
|
79
|
+
const prep = remoteBschat(host, "machine prepare --json");
|
|
80
|
+
if (prep.status !== 0)
|
|
81
|
+
throw new CliError("provision_failed", `bschat machine prepare on ${host} failed: ${prep.stderr.trim().slice(-300)}`);
|
|
82
|
+
const prepared = JSON.parse(prep.stdout).steps;
|
|
83
|
+
for (const s of prepared)
|
|
84
|
+
say(` ${s.step} ${s.result} ${s.detail}`);
|
|
85
|
+
// 3. Register (or re-key) and hand the key over on ssh's stdin, never on a command line.
|
|
86
|
+
let reg;
|
|
87
|
+
try {
|
|
88
|
+
reg = await c.call("POST", "/machines", { name });
|
|
89
|
+
}
|
|
90
|
+
catch (e) {
|
|
91
|
+
if (e.code !== "conflict" || !bool(p.flags, "rotate"))
|
|
92
|
+
throw e;
|
|
93
|
+
reg = await c.call("POST", `/machines/${name}/key`, {});
|
|
94
|
+
say(` registration: ${name} existed; its key was rotated`);
|
|
95
|
+
}
|
|
96
|
+
const admin = loadAdmin(resolveAdminName(str(p.flags, "admin")));
|
|
97
|
+
const wrote = ssh(host, `umask 077 && mkdir -p ~/.bschat && cat > ~/.bschat/machine.json`, JSON.stringify({ url: admin.url, key: reg.key, name }, null, 2) + "\n");
|
|
98
|
+
if (wrote.status !== 0)
|
|
99
|
+
throw new CliError("provision_failed", `writing ~/.bschat/machine.json on ${host} failed: ${wrote.stderr.trim()}`);
|
|
100
|
+
// 4. The daemon.
|
|
101
|
+
const svc = remoteBschat(host, "machine service");
|
|
102
|
+
if (svc.status !== 0)
|
|
103
|
+
throw new CliError("provision_failed", `installing the machine daemon on ${host} failed: ${svc.stderr.trim().slice(-300)}`);
|
|
104
|
+
say(` daemon: ${svc.stdout.trim().split("\n")[0]}`);
|
|
105
|
+
const failed = prepared.filter((s) => s.result === "failed");
|
|
106
|
+
return out.print([
|
|
107
|
+
`Machine ${name} (${host}) is provisioned and its daemon is running.`,
|
|
108
|
+
...lines,
|
|
109
|
+
failed.length ? `Still to do on the machine: ${failed.map((s) => `${s.step} (${s.detail})`).join("; ")}` : null,
|
|
110
|
+
`Declare what it runs: bschat-admin machine session add ${name} <project>/<agent> --dir <checkout on ${host}> --sandbox <mode> [--create --role <role>]`,
|
|
111
|
+
].filter(Boolean).join("\n"), { machine: name, host, bootstrap: steps, prepare: prepared });
|
|
112
|
+
}
|
|
113
|
+
if (action === "list" || action === undefined) {
|
|
114
|
+
const r = await c.call("GET", "/machines");
|
|
115
|
+
const rows = r.machines.map((m) => ({ name: m.name, os: m.report?.os ?? "-", bschat: m.report?.bschat?.version ?? "-", codex: m.report?.codex ? (m.report.codex.logged_in ? "logged in" : "NOT logged in") : "-", sessions: m.sessions.length, last_report: m.last_report_at ?? "never" }));
|
|
116
|
+
return out.print(rows.length ? table(rows, ["name", "os", "bschat", "codex", "sessions", "last_report"]) : "No machines. Add one: bschat-admin machine add <name> --ssh <host>", r);
|
|
117
|
+
}
|
|
118
|
+
if (action === "show") {
|
|
119
|
+
if (!rest[0])
|
|
120
|
+
throw new CliError("usage", "machine show <name>");
|
|
121
|
+
const r = await c.call("GET", `/machines/${rest[0]}`);
|
|
122
|
+
const m = r.machine;
|
|
123
|
+
const rep = m.report ?? {};
|
|
124
|
+
const head = [
|
|
125
|
+
`${m.name}: last report ${m.last_report_at ?? "never"}`,
|
|
126
|
+
rep.os ? ` ${rep.os}/${rep.arch} ${rep.hostname} as ${rep.user}; bschat ${rep.bschat?.version}; codex ${rep.codex ? `${rep.codex.version}, ${rep.codex.logged_in ? "logged in" : "NOT logged in"}` : "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?)",
|
|
127
|
+
];
|
|
128
|
+
const rows = m.sessions.map((s) => ({ agent: s.agent, desired: s.desired, state: s.reported?.state ?? "-", thread: s.thread ?? "-", sandbox: s.sandbox, model: s.model ?? "-", dir: s.dir, error: s.reported?.error ?? "", last_turn: (s.reported?.last_turn ?? "").replace(/^\S+ bschat watch\[[^\]]+\]: /, "") }));
|
|
129
|
+
return out.print([...head, rows.length ? table(rows, ["agent", "desired", "state", "thread", "sandbox", "model", "dir", "error", "last_turn"]) : " no sessions"].join("\n"), r);
|
|
130
|
+
}
|
|
131
|
+
if (action === "remove") {
|
|
132
|
+
if (!rest[0])
|
|
133
|
+
throw new CliError("usage", "machine remove <name> (forgets it and revokes its keys; stop its daemon on the machine with: systemctl --user disable --now org.benignswarm.machine)");
|
|
134
|
+
await c.call("DELETE", `/machines/${rest[0]}`);
|
|
135
|
+
return out.print(`Removed machine ${rest[0]}; its machine key and the agent keys minted for it are revoked. Its daemon stops reaching the API; stop it on the machine with: systemctl --user disable --now org.benignswarm.machine (Linux) or launchctl bootout gui/$(id -u)/org.benignswarm.machine (macOS)`, { removed: rest[0] });
|
|
136
|
+
}
|
|
137
|
+
if (action === "session") {
|
|
138
|
+
const [sub, machineName, ref] = rest;
|
|
139
|
+
const [project, agent] = (ref ?? "").split("/");
|
|
140
|
+
if (!sub || !machineName || !project || !agent)
|
|
141
|
+
throw new CliError("usage", "machine session add|stop|start|remove <machine> <project>/<agent> [...]");
|
|
142
|
+
if (sub === "add") {
|
|
143
|
+
const turnTimeout = str(p.flags, "turn-timeout");
|
|
144
|
+
const body = {
|
|
145
|
+
project, agent, harness: str(p.flags, "harness") ?? "codex", dir: str(p.flags, "dir"), sandbox: str(p.flags, "sandbox"),
|
|
146
|
+
model: str(p.flags, "model"), effort: str(p.flags, "effort"), thread: str(p.flags, "thread"),
|
|
147
|
+
...(turnTimeout ? { turn_timeout: Number(turnTimeout) } : {}),
|
|
148
|
+
create: bool(p.flags, "create"), role: str(p.flags, "role"),
|
|
149
|
+
};
|
|
150
|
+
const r = await c.call("POST", `/machines/${machineName}/sessions`, body);
|
|
151
|
+
return out.print(`Declared ${r.session.agent} on ${machineName} (${r.session.harness}, ${r.session.sandbox}, ${r.session.dir}). Its daemon starts it within 30 s: bschat-admin machine show ${machineName}`, r);
|
|
152
|
+
}
|
|
153
|
+
if (sub === "stop" || sub === "start") {
|
|
154
|
+
const r = await c.call("PATCH", `/machines/${machineName}/sessions/${project}/${agent}`, { desired: sub === "stop" ? "stopped" : "running" });
|
|
155
|
+
return out.print(`${ref} on ${machineName}: desired ${r.session.desired}; its daemon acts within 30 s.`, r);
|
|
156
|
+
}
|
|
157
|
+
if (sub === "remove") {
|
|
158
|
+
await c.call("DELETE", `/machines/${machineName}/sessions/${project}/${agent}`);
|
|
159
|
+
return out.print(`Removed ${ref} from ${machineName}; the agent and its thread stay.`, { removed: ref });
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
throw new CliError("usage", "machine add <name> --ssh <host> | list | show <name> | remove <name> | session add|stop|start|remove <machine> <project>/<agent>");
|
|
163
|
+
}
|
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, statfsSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { arch, homedir, hostname, platform, userInfo } from "node:os";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import { str } from "../args.js";
|
|
6
|
+
import { Client } from "../client.js";
|
|
7
|
+
import { configRoot, loadAgent, saveAgent } from "../config.js";
|
|
8
|
+
import { CliError } from "../errors.js";
|
|
9
|
+
import { CODEX_MANAGED_DIR, CODEX_MANAGED_MARK, codexManagedHooks } from "../harness.js";
|
|
10
|
+
import { installService, lingerEnabled, MACHINE_LABEL, removeService, requireInstall, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
|
|
11
|
+
import { CLI_VERSION } from "../version.js";
|
|
12
|
+
export const machineFile = () => join(configRoot(), "machine.json");
|
|
13
|
+
export function loadMachine() {
|
|
14
|
+
const f = machineFile();
|
|
15
|
+
if (!existsSync(f))
|
|
16
|
+
throw new CliError("no_machine", `${f} does not exist: this machine was not provisioned`, "Run bschat-admin machine add <name> --ssh <host> from the operator's terminal");
|
|
17
|
+
return JSON.parse(readFileSync(f, "utf8"));
|
|
18
|
+
}
|
|
19
|
+
const stateFile = () => join(configRoot(), "state", "machine.json");
|
|
20
|
+
const readMachineState = () => (existsSync(stateFile()) ? JSON.parse(readFileSync(stateFile(), "utf8")) : { sessions: {} });
|
|
21
|
+
function writeMachineState(s) {
|
|
22
|
+
mkdirSync(dirname(stateFile()), { recursive: true });
|
|
23
|
+
writeFileSync(stateFile(), JSON.stringify(s, null, 2) + "\n");
|
|
24
|
+
}
|
|
25
|
+
/** What a session's watcher is started with; a change means re-running codex start. The thread is compared separately. */
|
|
26
|
+
export const sessionFingerprint = (s) => JSON.stringify([s.harness, s.dir, s.sandbox, s.model, s.effort, s.turn_timeout]);
|
|
27
|
+
export const watchLabelOf = (ref) => `${WATCH_LABEL_PREFIX}${ref.replace("/", ".")}`;
|
|
28
|
+
/** The `bschat codex start` arguments that bring a session up (adopting its thread when known). */
|
|
29
|
+
export function startArgs(s, thread) {
|
|
30
|
+
return [
|
|
31
|
+
"codex", "start", "--as", s.agent, "--sandbox", s.sandbox, "--turn-timeout", String(s.turn_timeout), "--json",
|
|
32
|
+
...(s.model ? ["--model", s.model] : []),
|
|
33
|
+
...(s.effort ? ["--effort", s.effort] : []),
|
|
34
|
+
...(thread ? ["--thread", thread] : []),
|
|
35
|
+
];
|
|
36
|
+
}
|
|
37
|
+
const KEY_CHECK_MS = 10 * 60_000;
|
|
38
|
+
/** One pass: make what runs here match what the operator declared, then report. */
|
|
39
|
+
export async function reconcile(m, log) {
|
|
40
|
+
const client = Client.raw(m.url, m.key);
|
|
41
|
+
const desired = (await client.call("GET", "/machines/me")).sessions;
|
|
42
|
+
const state = readMachineState();
|
|
43
|
+
const bin = requireInstall().bin;
|
|
44
|
+
const out = [];
|
|
45
|
+
for (const s of desired) {
|
|
46
|
+
const label = watchLabelOf(s.agent);
|
|
47
|
+
const svc = () => watcherServices().find((w) => w.label === label);
|
|
48
|
+
try {
|
|
49
|
+
if (s.desired === "stopped") {
|
|
50
|
+
const w = svc();
|
|
51
|
+
if (w) {
|
|
52
|
+
removeService(w);
|
|
53
|
+
log(`${s.agent}: stopped (watcher removed)`);
|
|
54
|
+
}
|
|
55
|
+
delete state.sessions[s.id];
|
|
56
|
+
out.push({ id: s.id, state: "stopped" });
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
if (s.harness !== "codex")
|
|
60
|
+
throw new Error(`harness ${s.harness} is not supported by this bschat ${CLI_VERSION}`);
|
|
61
|
+
if (!existsSync(s.dir))
|
|
62
|
+
throw new Error(`checkout ${s.dir} does not exist on this machine`);
|
|
63
|
+
const local = state.sessions[s.id];
|
|
64
|
+
await ensureCredentials(client, m, s, local, log);
|
|
65
|
+
const fp = sessionFingerprint(s);
|
|
66
|
+
const thread = s.thread ?? local?.thread ?? null;
|
|
67
|
+
const threadChanged = !!local?.thread && !!s.thread && s.thread !== local.thread;
|
|
68
|
+
if (!svc() || !local || local.fingerprint !== fp || threadChanged) {
|
|
69
|
+
const r = spawnSync(bin, startArgs(s, thread), { cwd: s.dir, encoding: "utf8", timeout: 180_000 });
|
|
70
|
+
if (r.status !== 0)
|
|
71
|
+
throw new Error(`codex start failed: ${errorText(r.stderr || r.stdout)}`);
|
|
72
|
+
const started = JSON.parse(r.stdout);
|
|
73
|
+
state.sessions[s.id] = { label, fingerprint: fp, thread: started.thread, key_checked_at: state.sessions[s.id]?.key_checked_at ?? Date.now() };
|
|
74
|
+
log(`${s.agent}: ${thread ? `adopted thread ${started.thread}` : `started thread ${started.thread}`} in ${s.dir}`);
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
const w = svc();
|
|
78
|
+
if (!serviceActive(w)) {
|
|
79
|
+
if (!restartWatcher(w))
|
|
80
|
+
throw new Error(`its watcher ${label} is not loaded and could not be restarted`);
|
|
81
|
+
log(`${s.agent}: watcher was not running; restarted`);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
const w = svc();
|
|
85
|
+
out.push({ id: s.id, state: "running", thread: state.sessions[s.id].thread, watcher: w && serviceActive(w) ? "active" : "inactive", last_turn: lastTurnLine(s.agent) });
|
|
86
|
+
}
|
|
87
|
+
catch (e) {
|
|
88
|
+
const error = e.message.slice(0, 1000);
|
|
89
|
+
log(`${s.agent}: ${error}`);
|
|
90
|
+
out.push({ id: s.id, state: "error", thread: state.sessions[s.id]?.thread ?? null, error });
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
// Sessions the operator removed: their watchers go too.
|
|
94
|
+
for (const [id, local] of Object.entries(state.sessions)) {
|
|
95
|
+
if (desired.some((s) => s.id === id))
|
|
96
|
+
continue;
|
|
97
|
+
const w = watcherServices().find((x) => x.label === local.label);
|
|
98
|
+
if (w) {
|
|
99
|
+
removeService(w);
|
|
100
|
+
log(`${local.label}: session removed by the operator; watcher removed`);
|
|
101
|
+
}
|
|
102
|
+
delete state.sessions[id];
|
|
103
|
+
}
|
|
104
|
+
writeMachineState(state);
|
|
105
|
+
const report = machineFacts();
|
|
106
|
+
await client.call("POST", "/machines/me/report", { report, sessions: out });
|
|
107
|
+
return { sessions: out, report };
|
|
108
|
+
}
|
|
109
|
+
/** Saves the agent's key on first use, and replaces it when the server no longer accepts it. */
|
|
110
|
+
async function ensureCredentials(client, m, s, local, log) {
|
|
111
|
+
let saved = true;
|
|
112
|
+
try {
|
|
113
|
+
loadAgent(s.agent);
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
saved = false;
|
|
117
|
+
}
|
|
118
|
+
if (saved && local && Date.now() - local.key_checked_at < KEY_CHECK_MS)
|
|
119
|
+
return;
|
|
120
|
+
if (saved) {
|
|
121
|
+
try {
|
|
122
|
+
await Client.forAgent(loadAgent(s.agent), undefined, { presence: false }).call("GET", "/me");
|
|
123
|
+
if (local)
|
|
124
|
+
local.key_checked_at = Date.now();
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
catch (e) {
|
|
128
|
+
if (e.code !== "unauthorized")
|
|
129
|
+
throw e;
|
|
130
|
+
log(`${s.agent}: its saved key is no longer accepted; getting a new one`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
const r = await client.call("POST", `/machines/me/sessions/${s.id}/key`, {});
|
|
134
|
+
saveAgent({ url: m.url, key: r.key, account: r.agent.project_id ?? "", project: r.agent.project, agent: r.agent.name, vendor: r.agent.vendor, machine: `${hostname()}/${m.name}` });
|
|
135
|
+
if (local)
|
|
136
|
+
local.key_checked_at = Date.now();
|
|
137
|
+
log(`${s.agent}: key saved for this machine`);
|
|
138
|
+
}
|
|
139
|
+
function errorText(s) {
|
|
140
|
+
const last = s.trim().split("\n").pop() ?? "";
|
|
141
|
+
try {
|
|
142
|
+
return JSON.parse(last).message ?? last;
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
return last.slice(0, 500);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/** The watcher's latest turn line (started, finished, FAILED, STOPPED, paused), for the report. */
|
|
149
|
+
function lastTurnLine(ref) {
|
|
150
|
+
const f = join(homedir(), ".bschat", "logs", `watch.${ref.replace("/", ".")}.err.log`);
|
|
151
|
+
if (!existsSync(f))
|
|
152
|
+
return null;
|
|
153
|
+
const lines = readFileSync(f, "utf8").split("\n").filter((l) => /bschat watch\[/.test(l) && /turn #|TURN #|usage limit|pause lifted/.test(l));
|
|
154
|
+
return lines.length ? lines[lines.length - 1].slice(0, 300) : null;
|
|
155
|
+
}
|
|
156
|
+
/** What the operator needs to know about this machine, reported with every pass. */
|
|
157
|
+
export function machineFacts() {
|
|
158
|
+
const codex = spawnSync("codex", ["--version"], { encoding: "utf8" });
|
|
159
|
+
const login = codex.status === 0 ? spawnSync("codex", ["login", "status"], { encoding: "utf8" }) : null;
|
|
160
|
+
let diskFree = null;
|
|
161
|
+
try {
|
|
162
|
+
const st = statfsSync(homedir());
|
|
163
|
+
diskFree = st.bavail * st.bsize;
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
diskFree = null;
|
|
167
|
+
}
|
|
168
|
+
const req = "/etc/codex/requirements.toml";
|
|
169
|
+
return {
|
|
170
|
+
os: platform(), arch: arch(), hostname: hostname(), user: userInfo().username,
|
|
171
|
+
bschat: { version: CLI_VERSION, bin: requireInstall().bin },
|
|
172
|
+
codex: 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) } : null,
|
|
173
|
+
managed_hooks: existsSync(req) && readFileSync(req, "utf8").includes(CODEX_MANAGED_MARK),
|
|
174
|
+
linger: platform() === "linux" ? lingerEnabled() : null,
|
|
175
|
+
disk_free_bytes: diskFree,
|
|
176
|
+
at: new Date().toISOString(),
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Provisioning steps that need this machine's own view, run by `machine add` over ssh: linger on
|
|
181
|
+
* Linux, Codex present and logged in, and bschat's hooks in Codex's administrator layer when sudo
|
|
182
|
+
* works without a password. Each step reports ok, done, skipped or failed; nothing is hidden.
|
|
183
|
+
*/
|
|
184
|
+
export function prepare() {
|
|
185
|
+
const steps = [];
|
|
186
|
+
const sudo = spawnSync("sudo", ["-n", "true"], { stdio: "ignore" }).status === 0;
|
|
187
|
+
if (platform() === "linux") {
|
|
188
|
+
const l = lingerEnabled();
|
|
189
|
+
if (l)
|
|
190
|
+
steps.push({ step: "linger", result: "ok", detail: "services keep running after logout" });
|
|
191
|
+
else {
|
|
192
|
+
const r = spawnSync("loginctl", ["enable-linger", userInfo().username], { encoding: "utf8" });
|
|
193
|
+
const r2 = r.status === 0 ? r : sudo ? spawnSync("sudo", ["-n", "loginctl", "enable-linger", userInfo().username], { encoding: "utf8" }) : r;
|
|
194
|
+
steps.push(lingerEnabled() ? { step: "linger", result: "done", detail: "enabled" } : { step: "linger", result: "failed", detail: `${(r2.stderr ?? "").trim()} (run: sudo loginctl enable-linger ${userInfo().username})` });
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
const codex = spawnSync("codex", ["--version"], { encoding: "utf8" });
|
|
198
|
+
if (codex.status !== 0)
|
|
199
|
+
steps.push({ step: "codex", result: "failed", detail: "codex is not on PATH; install the Codex CLI (npm i -g @openai/codex) and log in (codex login --device-auth)" });
|
|
200
|
+
else {
|
|
201
|
+
const login = spawnSync("codex", ["login", "status"], { encoding: "utf8" });
|
|
202
|
+
const ok = login.status === 0 && /logged in/i.test(`${login.stdout}${login.stderr}`);
|
|
203
|
+
steps.push({ step: "codex", result: ok ? "ok" : "failed", detail: ok ? `${codex.stdout.trim()}, ${login.stdout.trim()}` : `${codex.stdout.trim()} is not logged in: run codex login --device-auth on this machine` });
|
|
204
|
+
}
|
|
205
|
+
const req = "/etc/codex/requirements.toml";
|
|
206
|
+
const { requirements, wrapper } = codexManagedHooks(requireInstall().bin);
|
|
207
|
+
const current = existsSync(req) ? readFileSync(req, "utf8") : null;
|
|
208
|
+
if (current !== null && !current.startsWith(CODEX_MANAGED_MARK)) {
|
|
209
|
+
steps.push({ step: "codex hooks", result: "skipped", detail: `${req} exists and was not written by bschat; add bschat's hooks to it by hand (bschat machine prepare --print-hooks shows them) or trust ~/.codex/hooks.json in an interactive codex` });
|
|
210
|
+
}
|
|
211
|
+
else if (current === requirements && existsSync(`${CODEX_MANAGED_DIR}/bschat`) && readFileSync(`${CODEX_MANAGED_DIR}/bschat`, "utf8") === wrapper) {
|
|
212
|
+
steps.push({ step: "codex hooks", result: "ok", detail: `managed by policy in ${req}` });
|
|
213
|
+
}
|
|
214
|
+
else if (!sudo) {
|
|
215
|
+
steps.push({ step: "codex hooks", result: "skipped", detail: `sudo needs a password here, so bschat's hooks are not in ${req}; trust ~/.codex/hooks.json in an interactive codex instead` });
|
|
216
|
+
}
|
|
217
|
+
else {
|
|
218
|
+
const write = (path, text, mode) => {
|
|
219
|
+
const t = spawnSync("sudo", ["-n", "tee", path], { input: text, stdio: ["pipe", "ignore", "pipe"], encoding: "utf8" });
|
|
220
|
+
if (t.status !== 0)
|
|
221
|
+
throw new Error(`sudo tee ${path}: ${(t.stderr ?? "").trim()}`);
|
|
222
|
+
const c = spawnSync("sudo", ["-n", "chmod", mode, path], { encoding: "utf8" });
|
|
223
|
+
if (c.status !== 0)
|
|
224
|
+
throw new Error(`sudo chmod ${path}: ${(c.stderr ?? "").trim()}`);
|
|
225
|
+
};
|
|
226
|
+
try {
|
|
227
|
+
const d = spawnSync("sudo", ["-n", "mkdir", "-p", CODEX_MANAGED_DIR], { encoding: "utf8" });
|
|
228
|
+
if (d.status !== 0)
|
|
229
|
+
throw new Error(`sudo mkdir ${CODEX_MANAGED_DIR}: ${(d.stderr ?? "").trim()}`);
|
|
230
|
+
write(`${CODEX_MANAGED_DIR}/bschat`, wrapper, "755");
|
|
231
|
+
write(req, requirements, "644");
|
|
232
|
+
steps.push({ step: "codex hooks", result: "done", detail: `bschat's hooks are in ${req}, trusted by policy` });
|
|
233
|
+
}
|
|
234
|
+
catch (e) {
|
|
235
|
+
steps.push({ step: "codex hooks", result: "failed", detail: e.message });
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
return steps;
|
|
239
|
+
}
|
|
240
|
+
export async function machine(p, out) {
|
|
241
|
+
const sub = p.positionals[1];
|
|
242
|
+
if (sub === "prepare") {
|
|
243
|
+
if (p.flags["print-hooks"])
|
|
244
|
+
return out.print(codexManagedHooks(requireInstall().bin).requirements, codexManagedHooks(requireInstall().bin));
|
|
245
|
+
const steps = prepare();
|
|
246
|
+
return out.print(steps.map((s) => `${s.result.padEnd(8)} ${s.step}: ${s.detail}`).join("\n"), { steps });
|
|
247
|
+
}
|
|
248
|
+
if (sub === "service") {
|
|
249
|
+
loadMachine();
|
|
250
|
+
const bin = requireInstall().bin;
|
|
251
|
+
const path = installService(MACHINE_LABEL, [bin, "machine", "run"], homedir(), { PATH: process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin", HOME: homedir() }, "machine");
|
|
252
|
+
return out.print(`Wrote ${path} and (re)started it: the machine daemon runs ${bin} machine run. Logs: ~/.bschat/logs/machine.*.log`, { path, label: MACHINE_LABEL });
|
|
253
|
+
}
|
|
254
|
+
const m = loadMachine();
|
|
255
|
+
const log = (s) => process.stderr.write(`${new Date().toISOString()} bschat machine[${m.name}]: ${s}\n`);
|
|
256
|
+
if (sub === "status") {
|
|
257
|
+
const desired = (await Client.raw(m.url, m.key).call("GET", "/machines/me")).sessions;
|
|
258
|
+
const state = readMachineState();
|
|
259
|
+
const rows = desired.map((s) => {
|
|
260
|
+
const w = watcherServices().find((x) => x.label === watchLabelOf(s.agent));
|
|
261
|
+
return `${s.agent.padEnd(32)} desired ${s.desired.padEnd(8)} watcher ${w ? (serviceActive(w) ? "active" : "inactive") : "none"} thread ${state.sessions[s.id]?.thread ?? s.thread ?? "-"} ${s.dir}`;
|
|
262
|
+
});
|
|
263
|
+
return out.print([`machine ${m.name} (${m.url})`, ...rows, rows.length ? "" : "no sessions declared"].join("\n"), { machine: m.name, sessions: desired, local: state });
|
|
264
|
+
}
|
|
265
|
+
if (sub === "once") {
|
|
266
|
+
const r = await reconcile(m, log);
|
|
267
|
+
return out.print(r.sessions.map((s) => `${s.state.padEnd(8)} ${desiredName(s.id)} ${s.thread ?? ""} ${s.error ?? ""}`).join("\n") || "no sessions declared", r);
|
|
268
|
+
}
|
|
269
|
+
if (sub === "run") {
|
|
270
|
+
const interval = Number(str(p.flags, "interval") ?? "30");
|
|
271
|
+
log(`running every ${interval}s against ${m.url}`);
|
|
272
|
+
for (;;) {
|
|
273
|
+
try {
|
|
274
|
+
await reconcile(m, log);
|
|
275
|
+
}
|
|
276
|
+
catch (e) {
|
|
277
|
+
log(`pass failed: ${e.message}`);
|
|
278
|
+
}
|
|
279
|
+
await new Promise((r) => setTimeout(r, interval * 1000));
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
throw new CliError("usage", "machine run | once | status | prepare | service");
|
|
283
|
+
}
|
|
284
|
+
const desiredName = (id) => readMachineState().sessions[id]?.label.replace(WATCH_LABEL_PREFIX, "") ?? id;
|
package/dist/commands/watch.js
CHANGED
|
@@ -2,10 +2,10 @@ import { spawn, spawnSync } from "node:child_process";
|
|
|
2
2
|
import { bindSession, codexArchivedRollout, codexRollout, sessionOfExec, threadOfExec } from "../sessions.js";
|
|
3
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", "--
|
|
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
|
|
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, pausedUntil: 0 };
|
|
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);
|
|
@@ -344,6 +344,7 @@ async function turnStep(ctl, thread, timeoutMin, log, wake, name) {
|
|
|
344
344
|
const until = usageLimitUntil(error);
|
|
345
345
|
if (until && until > Date.now()) {
|
|
346
346
|
ctl.pausedUntil = until;
|
|
347
|
+
ctl.pausedAt = Date.now();
|
|
347
348
|
log(`TURN #${turn.seq} FAILED: the Codex account hit its usage limit; no turns until ${new Date(until).toISOString()} (Codex said: ${error})`);
|
|
348
349
|
}
|
|
349
350
|
else {
|
|
@@ -362,6 +363,13 @@ async function turnStep(ctl, thread, timeoutMin, log, wake, name) {
|
|
|
362
363
|
}
|
|
363
364
|
return;
|
|
364
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
|
+
}
|
|
365
373
|
if (Date.now() - ctl.failedAt < TURN_RETRY_MS)
|
|
366
374
|
return;
|
|
367
375
|
if (ctl.pausedUntil > Date.now())
|
|
@@ -371,9 +379,10 @@ async function turnStep(ctl, thread, timeoutMin, log, wake, name) {
|
|
|
371
379
|
// restarted (turns run in their own process group and outlive it). Never start a second one.
|
|
372
380
|
const ph = readTurnPhase(rollout);
|
|
373
381
|
// A watcher that restarted after a usage-limit failure reads the pause from the session itself.
|
|
374
|
-
const until = !ph.running ? usageLimitUntil(ph.lastError) : null;
|
|
382
|
+
const until = !ph.running && Date.parse(ph.lastEventAt ?? "") > unpausedAt ? usageLimitUntil(ph.lastError) : null;
|
|
375
383
|
if (until && until > Date.now()) {
|
|
376
384
|
ctl.pausedUntil = until;
|
|
385
|
+
ctl.pausedAt = Date.now();
|
|
377
386
|
log(`the last turn in thread ${thread} hit the Codex usage limit; no turns until ${new Date(until).toISOString()}`);
|
|
378
387
|
return;
|
|
379
388
|
}
|
|
@@ -448,8 +457,40 @@ function run(cmd, stdin, env) {
|
|
|
448
457
|
child.on("error", () => resolve(1));
|
|
449
458
|
});
|
|
450
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
|
+
}
|
|
451
492
|
/** Writes a launchd agent that keeps `bschat watch` running for this identity on macOS. */
|
|
452
|
-
|
|
493
|
+
function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, out, prune = false, turnTimeout = null) {
|
|
453
494
|
if (process.platform !== "darwin")
|
|
454
495
|
throw new CliError("unsupported", "--launchd is macOS only; on Linux run `bschat watch` under a systemd user service");
|
|
455
496
|
const slug = name.replace("/", ".");
|
package/dist/harness.js
CHANGED
|
@@ -260,3 +260,44 @@ export function withCodexHooks(doc, bin) {
|
|
|
260
260
|
}
|
|
261
261
|
return { ...doc, hooks };
|
|
262
262
|
}
|
|
263
|
+
/** First line of the files `bschat-admin machine add` writes in Codex's administrator layer. */
|
|
264
|
+
export const CODEX_MANAGED_MARK = "# bschat managed hooks";
|
|
265
|
+
export const CODEX_MANAGED_DIR = "/etc/codex/hooks";
|
|
266
|
+
/**
|
|
267
|
+
* Codex's administrator layer for a provisioned machine (docs/REMOTE-MACHINES.md): bschat's hooks in
|
|
268
|
+
* /etc/codex/requirements.toml, which Codex trusts by policy, calling a wrapper in the managed dir
|
|
269
|
+
* that runs this machine's recorded install. `allow_managed_hooks_only` is deliberately not set: it
|
|
270
|
+
* would switch off the machine owner's own hooks. Returns the two files' contents.
|
|
271
|
+
*/
|
|
272
|
+
export function codexManagedHooks(bin) {
|
|
273
|
+
const events = [
|
|
274
|
+
{ event: "SessionStart", matcher: "startup|resume|clear|compact" },
|
|
275
|
+
{ event: "UserPromptSubmit" },
|
|
276
|
+
{ event: "PostToolUse", matcher: "*" },
|
|
277
|
+
{ event: "Stop" },
|
|
278
|
+
];
|
|
279
|
+
const requirements = [
|
|
280
|
+
`${CODEX_MANAGED_MARK} (written by bschat-admin machine add; trusted by policy, so headless turns run them)`,
|
|
281
|
+
`[hooks]`,
|
|
282
|
+
`managed_dir = "${CODEX_MANAGED_DIR}"`,
|
|
283
|
+
...events.flatMap(({ event, matcher }) => [
|
|
284
|
+
``,
|
|
285
|
+
`[[hooks.${event}]]`,
|
|
286
|
+
...(matcher ? [`matcher = "${matcher}"`] : []),
|
|
287
|
+
`[[hooks.${event}.hooks]]`,
|
|
288
|
+
`type = "command"`,
|
|
289
|
+
`command = "${CODEX_MANAGED_DIR}/bschat ${event}"`,
|
|
290
|
+
`timeout = 20`,
|
|
291
|
+
]),
|
|
292
|
+
``,
|
|
293
|
+
].join("\n");
|
|
294
|
+
// Runs for every user of the machine; one without this install has no bschat agent here.
|
|
295
|
+
const wrapper = [
|
|
296
|
+
`#!/bin/sh`,
|
|
297
|
+
`${CODEX_MANAGED_MARK}: Codex hook entry point for ${bin}`,
|
|
298
|
+
`[ -x ${shellPath(bin)} ] || exit 0`,
|
|
299
|
+
`exec ${shellPath(bin)} ${CODEX_HOOK_MARK} --event "$1"`,
|
|
300
|
+
``,
|
|
301
|
+
].join("\n");
|
|
302
|
+
return { requirements, wrapper };
|
|
303
|
+
}
|
package/dist/help.js
CHANGED
|
@@ -98,14 +98,20 @@ Agent commands
|
|
|
98
98
|
Tiers: direct (@you, replies, assignments, operator) wake now; @role wakes now;
|
|
99
99
|
followed-channel chatter waits --follow-delay 300 s and collapses; digest never wakes.
|
|
100
100
|
--env A,B copies those variables from this shell into the LaunchAgent (Antigravity needs
|
|
101
|
-
ANTIGRAVITY_LS_ADDRESS,ANTIGRAVITY_CSRF_TOKEN). --full queues the text itself. --once /
|
|
102
|
-
|
|
101
|
+
ANTIGRAVITY_LS_ADDRESS,ANTIGRAVITY_CSRF_TOKEN). --full queues the text itself. --once /
|
|
102
|
+
--service (launchd on macOS, systemd on Linux; --launchd is the same). --turn runs Codex
|
|
103
|
+
turns itself (codex exec resume); set up by bschat codex start.
|
|
104
|
+
Codex: bschat watch --exec "codex queue --thread <id> --message {summary}" --service
|
|
103
105
|
bschat update the same as install --latest: upgrade this machine's bschat and restart its watchers
|
|
104
106
|
bschat install [<version> | --latest] make or upgrade this machine's one bschat (join does it once) and restart
|
|
105
107
|
the watchers on it; hooks, repo instructions and watchers all run its path
|
|
106
108
|
bschat doctor every bschat on this machine and who runs which (PATH, npx caches, this repo's
|
|
107
109
|
hook and instructions, each watcher's plist versus what launchd runs), with fixes
|
|
108
110
|
bschat codex hooks | bind <thread-id> | sync install bschat's Codex hooks (~/.codex/hooks.json) and say which thread is you
|
|
111
|
+
bschat codex start --as <a> --sandbox <mode> [--token t] [--thread id] [--model m] [--effort e]
|
|
112
|
+
run a Codex agent headless: enroll, start or adopt its thread, turn-mode watcher
|
|
113
|
+
bschat codex unpause [--as <a>] lift a usage-limit pause now (Codex was switched to an account with quota)
|
|
114
|
+
bschat machine run | once | status | prepare | service the machine daemon (set up by bschat-admin machine add)
|
|
109
115
|
bschat antigravity bind <conversation-id> | sync which Antigravity conversation is you, for its hook (watchers bind theirs)
|
|
110
116
|
bschat wake ack [<n>] acknowledge your watcher's wake-up #n first thing (no n: the one pending here)
|
|
111
117
|
Liveness: the watcher reports harness activity (Codex rollout / Antigravity conversation
|
|
@@ -190,5 +196,13 @@ bschat-admin login (approve it in your signed-in browser); the session lasts 30
|
|
|
190
196
|
bschat-admin notifier [--agent name|none] [--email yes|no] [--repeat m] how you are reached away from the console, and the last report
|
|
191
197
|
bschat-admin account [--summary-minutes m] plan, usage and the account summary period
|
|
192
198
|
bschat-admin worktree forget <project> <id> delete a stale worktree record (never the directory)
|
|
199
|
+
|
|
200
|
+
Machines (provisioned over your own ssh; a daemon on each runs the agent sessions you declare)
|
|
201
|
+
bschat-admin machine add <name> --ssh <host> [--rotate] install Node and bschat (no sudo), linger, Codex check,
|
|
202
|
+
bschat's Codex hooks in /etc/codex (passwordless sudo only), register, start the daemon
|
|
203
|
+
bschat-admin machine list | show <name> | remove <name>
|
|
204
|
+
bschat-admin machine session add <machine> <project>/<agent> --dir <checkout> --sandbox <read-only|workspace-write|danger-full-access>
|
|
205
|
+
[--create --role <role>] [--model m] [--effort e] [--thread <id>] [--turn-timeout min]
|
|
206
|
+
bschat-admin machine session stop|start|remove <machine> <project>/<agent>
|
|
193
207
|
bschat-admin delete-account --confirm "delete everything"
|
|
194
208
|
`;
|
package/dist/index.js
CHANGED
|
@@ -12,6 +12,7 @@ import { goal } from "./commands/goal.js";
|
|
|
12
12
|
import { wake } from "./commands/wake.js";
|
|
13
13
|
import { antigravity } from "./commands/antigravity.js";
|
|
14
14
|
import { codex } from "./commands/codex.js";
|
|
15
|
+
import { machine } from "./commands/machine.js";
|
|
15
16
|
import { doctor, install } from "./commands/install.js";
|
|
16
17
|
import { warnIfForeignCopy } from "./install.js";
|
|
17
18
|
import { processCmd, record, wu, milestones, milestone, lock, askOperator } from "./commands/wu.js";
|
|
@@ -53,6 +54,7 @@ const COMMANDS = {
|
|
|
53
54
|
wake,
|
|
54
55
|
antigravity,
|
|
55
56
|
codex,
|
|
57
|
+
machine,
|
|
56
58
|
install,
|
|
57
59
|
// `update` is the word people reach for: the same as install, latest unless a version is named.
|
|
58
60
|
update: (p, out) => install(p.positionals[1] ? p : { ...p, flags: { ...p.flags, latest: true } }, out),
|
package/dist/install.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { spawnSync } from "node:child_process";
|
|
2
|
-
import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, writeFileSync } from "node:fs";
|
|
3
|
-
import { homedir } from "node:os";
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
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";
|
|
@@ -82,12 +82,15 @@ export function ensureInstall(version, log, npmOverride) {
|
|
|
82
82
|
export const shellPath = (p) => (/^[A-Za-z0-9_./-]+$/.test(p) ? p : `'${p.replace(/'/g, `'\\''`)}'`);
|
|
83
83
|
export const launchAgentsDir = () => join(homedir(), "Library", "LaunchAgents");
|
|
84
84
|
export const WATCH_LABEL_PREFIX = "org.benignswarm.watch.";
|
|
85
|
+
/** The machine daemon's service (bschat machine run), next to the watchers. */
|
|
86
|
+
export const MACHINE_LABEL = "org.benignswarm.machine";
|
|
87
|
+
const isOurService = (label) => label.startsWith(WATCH_LABEL_PREFIX) || label === MACHINE_LABEL;
|
|
85
88
|
/** This machine's watcher LaunchAgent plists (macOS). */
|
|
86
89
|
export function watcherPlists() {
|
|
87
90
|
const dir = launchAgentsDir();
|
|
88
91
|
if (!existsSync(dir))
|
|
89
92
|
return [];
|
|
90
|
-
return readdirSync(dir).filter((f) => f.
|
|
93
|
+
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) }));
|
|
91
94
|
}
|
|
92
95
|
/** Loads (or reloads) a LaunchAgent from its plist, so what runs is what the file says. */
|
|
93
96
|
export function reloadLaunchAgent(label, path) {
|
|
@@ -114,6 +117,139 @@ export function reloadLaunchAgent(label, path) {
|
|
|
114
117
|
export function restartLaunchAgent(label) {
|
|
115
118
|
return spawnSync("launchctl", ["kickstart", "-k", `gui/${process.getuid()}/${label}`], { stdio: "ignore" }).status === 0;
|
|
116
119
|
}
|
|
120
|
+
export const systemdUserDir = () => join(process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "systemd", "user");
|
|
121
|
+
/** Every watcher service on this machine. */
|
|
122
|
+
export function watcherServices() {
|
|
123
|
+
if (process.platform === "darwin")
|
|
124
|
+
return watcherPlists().map((w) => ({ kind: "launchd", ...w, args: plistArgs(w.path) }));
|
|
125
|
+
const dir = systemdUserDir();
|
|
126
|
+
if (process.platform !== "linux" || !existsSync(dir))
|
|
127
|
+
return [];
|
|
128
|
+
return readdirSync(dir)
|
|
129
|
+
.filter((f) => f.endsWith(".service") && isOurService(f.slice(0, -".service".length)))
|
|
130
|
+
.map((f) => ({ kind: "systemd", label: f.slice(0, -".service".length), path: join(dir, f), args: unitArgs(readFileSync(join(dir, f), "utf8")) }));
|
|
131
|
+
}
|
|
132
|
+
export function plistArgs(path) {
|
|
133
|
+
const r = spawnSync("plutil", ["-convert", "json", "-o", "-", path], { encoding: "utf8" });
|
|
134
|
+
return r.status === 0 ? (JSON.parse(r.stdout).ProgramArguments ?? null) : null;
|
|
135
|
+
}
|
|
136
|
+
/** The command line a unit written by `systemdUnit` runs, from its `# bschat-args:` line. */
|
|
137
|
+
export function unitArgs(text) {
|
|
138
|
+
const m = /^# bschat-args: (.*)$/m.exec(text);
|
|
139
|
+
if (!m)
|
|
140
|
+
return null;
|
|
141
|
+
const a = JSON.parse(m[1]);
|
|
142
|
+
return Array.isArray(a) && a.every((x) => typeof x === "string") ? a : null;
|
|
143
|
+
}
|
|
144
|
+
/** systemd's quoting for one ExecStart word or Environment assignment: double quotes, with %, $, \ and " escaped. */
|
|
145
|
+
const sdq = (s) => `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%").replace(/\$/g, "$$$$")}"`;
|
|
146
|
+
/**
|
|
147
|
+
* A systemd user unit that keeps a watcher running. KillMode=process: a restart or upgrade stops the
|
|
148
|
+
* watcher only, never a Codex turn it started (turns run in their own process group, like on macOS).
|
|
149
|
+
*/
|
|
150
|
+
export function systemdUnit(label, args, cwd, env, logDir, slug = label.slice(WATCH_LABEL_PREFIX.length)) {
|
|
151
|
+
return [
|
|
152
|
+
`# Written by bschat; re-run its bschat watch ... --service (or bschat codex start) to change it.`,
|
|
153
|
+
`# bschat-args: ${JSON.stringify(args)}`,
|
|
154
|
+
`[Unit]`,
|
|
155
|
+
`Description=bschat ${label === MACHINE_LABEL ? "machine daemon" : `watcher for ${slug}`}`,
|
|
156
|
+
`After=network-online.target`,
|
|
157
|
+
``,
|
|
158
|
+
`[Service]`,
|
|
159
|
+
`ExecStart=${args.map(sdq).join(" ")}`,
|
|
160
|
+
`WorkingDirectory=${sdq(cwd)}`,
|
|
161
|
+
...Object.entries(env).map(([k, v]) => `Environment=${sdq(`${k}=${v}`)}`),
|
|
162
|
+
`Restart=always`,
|
|
163
|
+
`RestartSec=5`,
|
|
164
|
+
`KillMode=process`,
|
|
165
|
+
`StandardOutput=append:${join(logDir, `watch.${slug}.out.log`)}`,
|
|
166
|
+
`StandardError=append:${join(logDir, `watch.${slug}.err.log`)}`,
|
|
167
|
+
``,
|
|
168
|
+
`[Install]`,
|
|
169
|
+
`WantedBy=default.target`,
|
|
170
|
+
``,
|
|
171
|
+
].join("\n");
|
|
172
|
+
}
|
|
173
|
+
/** Loads (or reloads) a systemd user unit from its file and (re)starts it; throws when systemd refuses. */
|
|
174
|
+
export function loadSystemdUnit(label) {
|
|
175
|
+
for (const args of [["daemon-reload"], ["enable", `${label}.service`], ["restart", `${label}.service`]]) {
|
|
176
|
+
const r = spawnSync("systemctl", ["--user", ...args], { encoding: "utf8" });
|
|
177
|
+
if (r.status !== 0)
|
|
178
|
+
throw new CliError("systemctl_failed", `systemctl --user ${args.join(" ")} failed`, (r.stderr ?? "").trim());
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Installs and (re)starts a service running `args` from `cwd`: a LaunchAgent on macOS, a systemd user
|
|
183
|
+
* unit on Linux. Logs go to ~/.bschat/logs/<logName>.{out,err}.log. Returns the definition's path.
|
|
184
|
+
*/
|
|
185
|
+
export function installService(label, args, cwd, env, logName) {
|
|
186
|
+
const logDir = join(homedir(), ".bschat", "logs");
|
|
187
|
+
mkdirSync(logDir, { recursive: true });
|
|
188
|
+
if (process.platform === "linux") {
|
|
189
|
+
mkdirSync(systemdUserDir(), { recursive: true });
|
|
190
|
+
const path = join(systemdUserDir(), `${label}.service`);
|
|
191
|
+
const unit = systemdUnit(label, args, cwd, env, logDir, logName).replace(`watch.${logName}.out.log`, `${logName}.out.log`).replace(`watch.${logName}.err.log`, `${logName}.err.log`);
|
|
192
|
+
writeFileSync(path, unit);
|
|
193
|
+
loadSystemdUnit(label);
|
|
194
|
+
return path;
|
|
195
|
+
}
|
|
196
|
+
if (process.platform !== "darwin")
|
|
197
|
+
throw new CliError("unsupported", "services run under launchd (macOS) or systemd (Linux)");
|
|
198
|
+
const esc = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
199
|
+
const path = join(launchAgentsDir(), `${label}.plist`);
|
|
200
|
+
mkdirSync(launchAgentsDir(), { recursive: true });
|
|
201
|
+
writeFileSync(path, `<?xml version="1.0" encoding="UTF-8"?>
|
|
202
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
203
|
+
<plist version="1.0"><dict>
|
|
204
|
+
<key>Label</key><string>${label}</string>
|
|
205
|
+
<key>ProgramArguments</key><array>${args.map((a) => `<string>${esc(a)}</string>`).join("")}</array>
|
|
206
|
+
<key>EnvironmentVariables</key><dict>${Object.entries(env).map(([k, v]) => `<key>${esc(k)}</key><string>${esc(v)}</string>`).join("")}</dict>
|
|
207
|
+
<key>WorkingDirectory</key><string>${esc(cwd)}</string>
|
|
208
|
+
<key>RunAtLoad</key><true/>
|
|
209
|
+
<key>KeepAlive</key><true/>
|
|
210
|
+
<key>AbandonProcessGroup</key><true/>
|
|
211
|
+
<key>StandardOutPath</key><string>${join(logDir, `${logName}.out.log`)}</string>
|
|
212
|
+
<key>StandardErrorPath</key><string>${join(logDir, `${logName}.err.log`)}</string>
|
|
213
|
+
</dict></plist>
|
|
214
|
+
`);
|
|
215
|
+
reloadLaunchAgent(label, path);
|
|
216
|
+
return path;
|
|
217
|
+
}
|
|
218
|
+
/** Stops a service and removes its definition, so nothing (install --latest, a reboot) starts it again. */
|
|
219
|
+
export function removeService(s) {
|
|
220
|
+
if (s.kind === "systemd") {
|
|
221
|
+
const r = spawnSync("systemctl", ["--user", "disable", "--now", `${s.label}.service`], { encoding: "utf8" });
|
|
222
|
+
if (r.status !== 0 && existsSync(s.path))
|
|
223
|
+
throw new CliError("systemctl_failed", `systemctl --user disable --now ${s.label}.service failed`, (r.stderr ?? "").trim());
|
|
224
|
+
rmSync(s.path, { force: true });
|
|
225
|
+
spawnSync("systemctl", ["--user", "daemon-reload"], { stdio: "ignore" });
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
const domain = `gui/${process.getuid()}`;
|
|
229
|
+
if (spawnSync("launchctl", ["print", `${domain}/${s.label}`], { stdio: "ignore" }).status === 0) {
|
|
230
|
+
const r = spawnSync("launchctl", ["bootout", `${domain}/${s.label}`], { encoding: "utf8" });
|
|
231
|
+
if (r.status !== 0)
|
|
232
|
+
throw new CliError("launchctl_failed", `launchctl bootout ${domain}/${s.label} failed`, (r.stderr ?? "").trim());
|
|
233
|
+
}
|
|
234
|
+
rmSync(s.path, { force: true });
|
|
235
|
+
}
|
|
236
|
+
/** Whether a service's process is running now. */
|
|
237
|
+
export function serviceActive(s) {
|
|
238
|
+
if (s.kind === "systemd")
|
|
239
|
+
return (spawnSync("systemctl", ["--user", "is-active", `${s.label}.service`], { encoding: "utf8" }).stdout ?? "").trim() === "active";
|
|
240
|
+
return /"PID" = \d+;/.test(spawnSync("launchctl", ["list", s.label], { encoding: "utf8" }).stdout ?? "");
|
|
241
|
+
}
|
|
242
|
+
/** Restarts a watcher service in place (new code, same definition); false when it is not loaded. */
|
|
243
|
+
export function restartWatcher(s) {
|
|
244
|
+
if (s.kind === "launchd")
|
|
245
|
+
return restartLaunchAgent(s.label);
|
|
246
|
+
return spawnSync("systemctl", ["--user", "restart", `${s.label}.service`], { stdio: "ignore" }).status === 0;
|
|
247
|
+
}
|
|
248
|
+
/** Whether this user's systemd services run while nobody is logged in (null when it cannot be told). */
|
|
249
|
+
export function lingerEnabled() {
|
|
250
|
+
const r = spawnSync("loginctl", ["show-user", userInfo().username, "-p", "Linger", "--value"], { encoding: "utf8" });
|
|
251
|
+
return r.status === 0 ? r.stdout.trim() === "yes" : null;
|
|
252
|
+
}
|
|
117
253
|
/** Commands that legitimately run from a copy other than the recorded install (npx join, old npx hooks). */
|
|
118
254
|
const GUARD_EXEMPT = new Set(["join", "setup", "install", "doctor", "hook", "watch"]);
|
|
119
255
|
/**
|
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 {
|
|
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
|
|
58
|
-
const
|
|
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/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const CLI_VERSION = "0.12.
|
|
1
|
+
export const CLI_VERSION = "0.12.52";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "benignswarm",
|
|
3
|
-
"version": "0.12.
|
|
3
|
+
"version": "0.12.52",
|
|
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
|
},
|