benignswarm 0.12.51 → 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 +11 -2
- package/dist/commands/machine-admin.js +163 -0
- package/dist/commands/machine.js +284 -0
- package/dist/harness.js +41 -0
- package/dist/help.js +16 -2
- package/dist/index.js +2 -0
- package/dist/install.js +69 -6
- package/dist/version.js +1 -1
- package/package.json +1 -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", "service"];
|
|
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,6 +8,7 @@ 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
13
|
import { installWatcherService } from "./watch.js";
|
|
13
14
|
const SANDBOXES = ["read-only", "workspace-write", "danger-full-access"];
|
|
@@ -136,10 +137,18 @@ export function threadFromExecJson(text) {
|
|
|
136
137
|
}
|
|
137
138
|
return null;
|
|
138
139
|
}
|
|
139
|
-
/**
|
|
140
|
-
|
|
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 [];
|
|
141
147
|
return ["session_start", "user_prompt_submit", "post_tool_use", "stop"].filter((e) => !configText.includes(`[hooks.state."${hooksPath}:${e}:0:0"]`));
|
|
142
148
|
}
|
|
149
|
+
function readRequirements() {
|
|
150
|
+
return existsSync("/etc/codex/requirements.toml") ? readFileSync("/etc/codex/requirements.toml", "utf8") : "";
|
|
151
|
+
}
|
|
143
152
|
function readCodexConfig() {
|
|
144
153
|
const f = joinPath(process.env.CODEX_HOME ?? joinPath(homedir(), ".codex"), "config.toml");
|
|
145
154
|
return existsSync(f) ? readFileSync(f, "utf8") : "";
|
|
@@ -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/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,5 +1,5 @@
|
|
|
1
1
|
import { spawnSync } from "node:child_process";
|
|
2
|
-
import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { homedir, userInfo } from "node:os";
|
|
4
4
|
import { dirname, join } from "node:path";
|
|
5
5
|
import { configRoot } from "./config.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) {
|
|
@@ -123,7 +126,7 @@ export function watcherServices() {
|
|
|
123
126
|
if (process.platform !== "linux" || !existsSync(dir))
|
|
124
127
|
return [];
|
|
125
128
|
return readdirSync(dir)
|
|
126
|
-
.filter((f) => f.
|
|
129
|
+
.filter((f) => f.endsWith(".service") && isOurService(f.slice(0, -".service".length)))
|
|
127
130
|
.map((f) => ({ kind: "systemd", label: f.slice(0, -".service".length), path: join(dir, f), args: unitArgs(readFileSync(join(dir, f), "utf8")) }));
|
|
128
131
|
}
|
|
129
132
|
export function plistArgs(path) {
|
|
@@ -144,13 +147,12 @@ const sdq = (s) => `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/
|
|
|
144
147
|
* A systemd user unit that keeps a watcher running. KillMode=process: a restart or upgrade stops the
|
|
145
148
|
* watcher only, never a Codex turn it started (turns run in their own process group, like on macOS).
|
|
146
149
|
*/
|
|
147
|
-
export function systemdUnit(label, args, cwd, env, logDir) {
|
|
148
|
-
const slug = label.slice(WATCH_LABEL_PREFIX.length);
|
|
150
|
+
export function systemdUnit(label, args, cwd, env, logDir, slug = label.slice(WATCH_LABEL_PREFIX.length)) {
|
|
149
151
|
return [
|
|
150
152
|
`# Written by bschat; re-run its bschat watch ... --service (or bschat codex start) to change it.`,
|
|
151
153
|
`# bschat-args: ${JSON.stringify(args)}`,
|
|
152
154
|
`[Unit]`,
|
|
153
|
-
`Description=bschat watcher for ${slug}`,
|
|
155
|
+
`Description=bschat ${label === MACHINE_LABEL ? "machine daemon" : `watcher for ${slug}`}`,
|
|
154
156
|
`After=network-online.target`,
|
|
155
157
|
``,
|
|
156
158
|
`[Service]`,
|
|
@@ -176,6 +178,67 @@ export function loadSystemdUnit(label) {
|
|
|
176
178
|
throw new CliError("systemctl_failed", `systemctl --user ${args.join(" ")} failed`, (r.stderr ?? "").trim());
|
|
177
179
|
}
|
|
178
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
|
+
}
|
|
179
242
|
/** Restarts a watcher service in place (new code, same definition); false when it is not loaded. */
|
|
180
243
|
export function restartWatcher(s) {
|
|
181
244
|
if (s.kind === "launchd")
|
package/dist/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const CLI_VERSION = "0.12.
|
|
1
|
+
export const CLI_VERSION = "0.12.52";
|