benignswarm 0.12.64 → 0.12.66
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 +1 -1
- package/dist/commands/codex-start.js +110 -48
- package/dist/commands/codex.js +11 -8
- package/dist/commands/machine-admin.js +2 -0
- package/dist/commands/machine.js +82 -19
- package/dist/commands/watch.js +79 -59
- package/dist/harness.js +9 -4
- package/dist/harnesses.js +240 -0
- package/dist/help.js +6 -5
- package/dist/index.js +11 -2
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/dist/args.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
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", "ssh", "variant", "count", "needs", "min-ram", "exclude", "carry", "from", "to-ssh", "wait", "writable"];
|
|
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", "session", "ssh", "variant", "count", "needs", "min-ram", "exclude", "carry", "from", "to-ssh", "wait", "writable"];
|
|
4
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", "codex-userns", "print-apparmor"];
|
|
5
5
|
export function parse(argv) {
|
|
6
6
|
const options = {};
|
|
@@ -12,26 +12,33 @@ import { CODEX_MANAGED_MARK } from "../harness.js";
|
|
|
12
12
|
import { readState, writeState } from "../state.js";
|
|
13
13
|
import { join } from "./join.js";
|
|
14
14
|
import { installWatcherService } from "./watch.js";
|
|
15
|
+
import { randomUUID } from "node:crypto";
|
|
16
|
+
import { HARNESS_BIN, HARNESS_LABEL, claudeResultError, claudeResultFile, claudeSettings, claudeTranscript } from "../harnesses.js";
|
|
15
17
|
const SANDBOXES = ["read-only", "workspace-write", "danger-full-access"];
|
|
16
18
|
/**
|
|
17
|
-
* `bschat codex start
|
|
18
|
-
* app involved, so it works the same over ssh on a remote machine. It enrolls the
|
|
19
|
-
* invite token), starts its
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
* the Codex app's queue silently not delivering wake-ups (fabricbios luna-worker, ten hours).
|
|
19
|
+
* `bschat start` (and `bschat codex start`): one command that brings an agent up on this machine
|
|
20
|
+
* headless, with no app involved, so it works the same over ssh on a remote machine. It enrolls the
|
|
21
|
+
* agent (with an invite token), starts its session with an onboarding turn, binds it so the hooks
|
|
22
|
+
* deliver to it, and installs a turn-mode watcher that runs each later turn itself (Codex: `codex exec
|
|
23
|
+
* resume`; Claude Code: `claude -p --resume`). `--thread` adopts an existing session instead. Learned
|
|
24
|
+
* from the Codex app's queue silently not delivering wake-ups (fabricbios luna-worker, ten hours).
|
|
23
25
|
*
|
|
24
|
-
* bschat
|
|
25
|
-
*
|
|
26
|
+
* bschat start --harness codex|claude-code --as <name> --sandbox <mode> [--token bs_enroll_...]
|
|
27
|
+
* [--thread <id>] [--model m] [--effort e] [--turn-timeout 180] [--interval 30] [--prune]
|
|
26
28
|
*/
|
|
27
29
|
export async function codexStart(p, out) {
|
|
30
|
+
return harnessStart(p, out, "codex");
|
|
31
|
+
}
|
|
32
|
+
export async function harnessStart(p, out, harness) {
|
|
33
|
+
const label = HARNESS_LABEL[harness];
|
|
34
|
+
const cmd = harness === "codex" ? "codex start" : "start";
|
|
28
35
|
const name = str(p.flags, "as");
|
|
29
36
|
if (!name)
|
|
30
|
-
throw new CliError("usage",
|
|
37
|
+
throw new CliError("usage", `${cmd} needs --as <agent-name>`);
|
|
31
38
|
const sandbox = str(p.flags, "sandbox");
|
|
32
39
|
// No default: what a headless agent may touch on this machine is the operator's call, every time.
|
|
33
40
|
if (!sandbox || !SANDBOXES.includes(sandbox))
|
|
34
|
-
throw new CliError("usage",
|
|
41
|
+
throw new CliError("usage", `${cmd} needs --sandbox <${SANDBOXES.join("|")}>: what the agent may do on this machine, since a headless turn cannot ask for approval`);
|
|
35
42
|
const turnTimeout = Number(str(p.flags, "turn-timeout") ?? "180");
|
|
36
43
|
if (!Number.isInteger(turnTimeout) || turnTimeout < 5)
|
|
37
44
|
throw new CliError("usage", "--turn-timeout must be a whole number of minutes, at least 5");
|
|
@@ -39,75 +46,130 @@ export async function codexStart(p, out) {
|
|
|
39
46
|
if (!Number.isInteger(interval) || interval < 5)
|
|
40
47
|
throw new CliError("usage", "--interval must be an integer number of seconds, at least 5");
|
|
41
48
|
if (process.platform !== "darwin" && process.platform !== "linux")
|
|
42
|
-
throw new CliError("unsupported",
|
|
43
|
-
const
|
|
49
|
+
throw new CliError("unsupported", `${cmd} installs its watcher with launchd (macOS) or systemd (Linux)`);
|
|
50
|
+
const bin = which(HARNESS_BIN[harness], harness === "codex" ? "install the Codex CLI (npm i -g @openai/codex)" : "install Claude Code (npm i -g @anthropic-ai/claude-code)");
|
|
44
51
|
const model = str(p.flags, "model");
|
|
45
52
|
const effort = str(p.flags, "effort");
|
|
46
|
-
const adopt = str(p.flags, "thread");
|
|
53
|
+
const adopt = str(p.flags, "thread") ?? str(p.flags, "session");
|
|
54
|
+
// The machine's toolchain and job folders a sandboxed agent may also write (bschat-admin machine writable).
|
|
55
|
+
const writable = (str(p.flags, "writable") ?? "").split(",").map((w) => w.trim()).filter(Boolean).map((w) => (w.startsWith("~/") ? joinPath(homedir(), w.slice(2)) : w));
|
|
56
|
+
if (writable.some((w) => !w.startsWith("/")))
|
|
57
|
+
throw new CliError("usage", "--writable takes absolute or ~/ paths, comma separated");
|
|
58
|
+
// Refuses a sandbox the harness cannot honour before anything is enrolled.
|
|
59
|
+
const settings = harness === "codex"
|
|
60
|
+
? codexSettings(sandbox, model, effort, process.cwd(), configRoot(), writable)
|
|
61
|
+
: claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable);
|
|
47
62
|
// 1. Who: enroll with the invite token, or use credentials already on this machine.
|
|
48
63
|
const lines = [];
|
|
49
64
|
const token = str(p.flags, "token");
|
|
50
65
|
if (token) {
|
|
51
66
|
const joined = [];
|
|
52
|
-
await join({ ...p, flags: { ...p.flags, vendor:
|
|
67
|
+
await join({ ...p, flags: { ...p.flags, vendor: harness, model } }, { json: false, print: (h) => joined.push(h) });
|
|
53
68
|
lines.push(joined.join("\n").split("\n")[0]);
|
|
54
69
|
}
|
|
55
70
|
const creds = loadAgent(name);
|
|
56
|
-
if (creds.vendor && creds.vendor !==
|
|
57
|
-
throw new CliError("vendor_mismatch", `${agentRef(creds)} is saved as ${creds.vendor}, not
|
|
71
|
+
if (creds.vendor && creds.vendor !== harness)
|
|
72
|
+
throw new CliError("vendor_mismatch", `${agentRef(creds)} is saved as ${creds.vendor}, not ${harness}`);
|
|
58
73
|
const ref = agentRef(creds);
|
|
59
74
|
requireInstall();
|
|
60
|
-
// 2. Its
|
|
61
|
-
|
|
62
|
-
const writable = (str(p.flags, "writable") ?? "").split(",").map((w) => w.trim()).filter(Boolean).map((w) => (w.startsWith("~/") ? joinPath(homedir(), w.slice(2)) : w));
|
|
63
|
-
if (writable.some((w) => !w.startsWith("/")))
|
|
64
|
-
throw new CliError("usage", "--writable takes absolute or ~/ paths, comma separated");
|
|
65
|
-
const settings = codexSettings(sandbox, model, effort, process.cwd(), configRoot(), writable);
|
|
66
|
-
let thread;
|
|
75
|
+
// 2. Its session: adopt one, or start one headless with an onboarding turn.
|
|
76
|
+
let session;
|
|
67
77
|
let firstTurnLog = null;
|
|
68
78
|
if (adopt) {
|
|
69
|
-
|
|
70
|
-
if (
|
|
71
|
-
if (
|
|
72
|
-
|
|
73
|
-
|
|
79
|
+
session = adopt.toLowerCase();
|
|
80
|
+
if (harness === "codex") {
|
|
81
|
+
if (!codexRollout(session)) {
|
|
82
|
+
if (codexArchivedRollout(session))
|
|
83
|
+
throw new CliError("archived", `Codex thread ${session} is archived (its session file is in ~/.codex/archived_sessions)`, "Unarchive it in the Codex app, then leave it unopened there and run this again");
|
|
84
|
+
throw new CliError("not_found", `no Codex session file for thread ${session} under ~/.codex/sessions on this machine`);
|
|
85
|
+
}
|
|
86
|
+
lines.push(`Adopted Codex thread ${session}. Leave it unopened in the Codex app (do not archive it: that moves its session file away): from now on the watcher runs its turns, and two clients on one thread conflict.`);
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
if (!claudeTranscript(session))
|
|
90
|
+
throw new CliError("not_found", `no Claude Code transcript for session ${session} under ~/.claude/projects on this machine`);
|
|
91
|
+
lines.push(`Adopted Claude Code session ${session}. Do not resume it in a terminal while the watcher runs it: two clients on one session conflict.`);
|
|
74
92
|
}
|
|
75
|
-
lines.push(`Adopted Codex thread ${thread}. Leave it unopened in the Codex app (do not archive it: that moves its session file away): from now on the watcher runs its turns, and two clients on one thread conflict.`);
|
|
76
93
|
}
|
|
77
94
|
else {
|
|
78
95
|
const logDir = joinPath(homedir(), ".bschat", "logs");
|
|
79
96
|
mkdirSync(logDir, { recursive: true });
|
|
80
|
-
firstTurnLog = joinPath(logDir,
|
|
97
|
+
firstTurnLog = joinPath(logDir, `${harness}.${ref.replace("/", ".")}.first-turn.${harness === "codex" ? "jsonl" : "json"}`);
|
|
81
98
|
const prompt = [
|
|
82
|
-
`[bschat] You are ${ref}, a BenignSwarm agent, started headless by \`bschat
|
|
99
|
+
`[bschat] You are ${ref}, a BenignSwarm agent, started headless by \`bschat ${cmd}\`; nobody is typing to you.`,
|
|
83
100
|
`Your watcher starts a turn for you whenever something needs you, so end your turn when nothing is left to do.`,
|
|
84
101
|
`Now: run \`bschat me\`, \`bschat process\` and \`bschat inbox --unread\`, then do what your role and inbox ask.`,
|
|
85
102
|
`If you ran on another machine before, read your latest note first: \`bschat handoffs --agent ${creds.agent}\` (your units, branches and chat are on the server as before).`,
|
|
86
103
|
].join("\n");
|
|
87
|
-
|
|
88
|
-
|
|
104
|
+
if (harness === "codex") {
|
|
105
|
+
session = await startThread(bin, ["exec", "--json", ...settings, prompt], firstTurnLog, ref);
|
|
106
|
+
lines.push(`Started Codex thread ${session}; its first turn (reading its role and inbox) is running, log: ${firstTurnLog}`);
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
// Claude Code takes the session id from us, so nothing has to be read back from its output.
|
|
110
|
+
session = randomUUID();
|
|
111
|
+
await startClaudeSession(bin, ["-p", prompt, ...settings, "--session-id", session, "--output-format", "json"], firstTurnLog, ref, session);
|
|
112
|
+
lines.push(`Started Claude Code session ${session}; its first turn (reading its role and inbox) is running, result: ${firstTurnLog}`);
|
|
113
|
+
}
|
|
89
114
|
}
|
|
90
|
-
// 3. Bind it, so the hooks in that
|
|
91
|
-
|
|
92
|
-
|
|
115
|
+
// 3. Bind it, so the hooks in that session deliver to this agent and nobody else. Claude Code's
|
|
116
|
+
// hook knows the agent from BSCHAT_AGENT (the watcher sets it for every turn), so it needs no map.
|
|
117
|
+
if (harness === "codex")
|
|
118
|
+
bindSession("codex", session, ref);
|
|
119
|
+
// A session adopted here may end in a usage-limit error from the machine it came from, written in
|
|
93
120
|
// that machine's local time ("3:32 PM" Central read as UTC on ronald: six hours off). Only errors
|
|
94
121
|
// from turns on this machine pause it; if the account is still limited, the next turn says so here.
|
|
95
122
|
if (adopt)
|
|
96
123
|
writeState(ref, { ...readState(ref), turn_unpaused_at: Date.now() });
|
|
97
124
|
// 4. The watcher, in turn mode: it runs each later turn itself.
|
|
98
|
-
const exec =
|
|
125
|
+
const exec = harness === "codex"
|
|
126
|
+
? [bin, "exec", "resume", session, ...settings].map(shq).join(" ") + " {text}"
|
|
127
|
+
// The result goes to a file the watcher reads when the turn ends: Claude Code can exit 0 with is_error set.
|
|
128
|
+
: `${shq(bin)} -p {text} ${[...settings, "--resume", session, "--output-format", "json"].map(shq).join(" ")} > ${shq(claudeResultFile(ref))}`;
|
|
99
129
|
const watcherOut = [];
|
|
100
|
-
installWatcherService(ref, exec, interval, Number(str(p.flags, "follow-delay") ?? "300"), {}, undefined, { json: false, print: (h) => watcherOut.push(h) }, bool(p.flags, "prune"), turnTimeout);
|
|
130
|
+
installWatcherService(ref, exec, interval, Number(str(p.flags, "follow-delay") ?? "300"), {}, undefined, { json: false, print: (h) => watcherOut.push(h) }, bool(p.flags, "prune"), { harness, session, timeout: turnTimeout });
|
|
101
131
|
const wl = watcherOut.join("\n").split("\n");
|
|
102
132
|
lines.push(wl[0].replace(/^Wrote /, "Watcher: wrote "), ...wl.filter((l) => l.startsWith("Linger is off")));
|
|
103
|
-
// 5. Hooks
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
133
|
+
// 5. Hooks.
|
|
134
|
+
let missing = [];
|
|
135
|
+
if (harness === "codex") {
|
|
136
|
+
// A headless turn cannot show Codex's trust prompt, and bschat never pre-approves it.
|
|
137
|
+
missing = untrustedHooks();
|
|
138
|
+
lines.push(missing.length
|
|
139
|
+
? `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.`
|
|
140
|
+
: `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\`.`);
|
|
141
|
+
}
|
|
142
|
+
else {
|
|
143
|
+
lines.push(`Claude Code runs bschat's hooks from this checkout's .claude/settings.local.json (written by join).`);
|
|
144
|
+
}
|
|
145
|
+
lines.push(`Follow it: tail -f ~/.bschat/logs/watch.${ref.replace("/", ".")}.err.log; ${harness === "codex" ? `read its thread with codex resume ${session}` : `read its transcript under ~/.claude/projects (session ${session})`} only while no turn is running.`);
|
|
146
|
+
lines.push(`If the ${label} account hits its usage limit, the watcher pauses turns until the time ${label} gives; after switching to an account with quota, resume at once: bschat unpause --as ${ref}`);
|
|
147
|
+
out.print(lines.join("\n"), { agent: ref, harness, thread: session, session, sandbox, model: model ?? null, effort: effort ?? null, exec, first_turn_log: firstTurnLog, untrusted_hooks: missing });
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Starts a headless Claude Code session in its own process group (the first turn may take many
|
|
151
|
+
* minutes; this command does not wait for it) and returns once its transcript exists, or fails
|
|
152
|
+
* with Claude Code's own error when it exits first.
|
|
153
|
+
*/
|
|
154
|
+
async function startClaudeSession(bin, args, logPath, agent, session) {
|
|
155
|
+
const fd = openSync(logPath, "w");
|
|
156
|
+
const child = spawn(bin, args, { stdio: ["ignore", fd, fd], detached: true, cwd: process.cwd(), env: { ...process.env, BSCHAT_AGENT: agent } });
|
|
157
|
+
closeSync(fd);
|
|
158
|
+
let exited = null;
|
|
159
|
+
child.on("exit", (code) => { exited = code ?? 1; });
|
|
160
|
+
child.unref();
|
|
161
|
+
for (let i = 0; i < 180; i++) {
|
|
162
|
+
if (exited !== null) {
|
|
163
|
+
const error = claudeResultError(readFileSync(logPath, "utf8"));
|
|
164
|
+
if (exited !== 0 || error)
|
|
165
|
+
throw new CliError("claude_failed", `claude exited ${exited} in its first turn: ${error ?? "no error reported"}; see ${logPath}`);
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
if (claudeTranscript(session))
|
|
169
|
+
return;
|
|
170
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
171
|
+
}
|
|
172
|
+
throw new CliError("claude_failed", `Claude Code wrote no transcript for session ${session} within 90 s; see ${logPath}`);
|
|
111
173
|
}
|
|
112
174
|
/**
|
|
113
175
|
* The Codex settings a headless turn runs with. Under workspace-write the agent still has to reach
|
|
@@ -175,11 +237,11 @@ function readCodexConfig() {
|
|
|
175
237
|
const f = joinPath(process.env.CODEX_HOME ?? joinPath(homedir(), ".codex"), "config.toml");
|
|
176
238
|
return existsSync(f) ? readFileSync(f, "utf8") : "";
|
|
177
239
|
}
|
|
178
|
-
function which(bin) {
|
|
240
|
+
function which(bin, install) {
|
|
179
241
|
const r = spawnSync("/bin/sh", ["-c", `command -v ${bin}`], { encoding: "utf8" });
|
|
180
242
|
const path = r.stdout.trim();
|
|
181
243
|
if (r.status !== 0 || !path)
|
|
182
|
-
throw new CliError("not_found", `${bin} is not on PATH; install
|
|
244
|
+
throw new CliError("not_found", `${bin} is not on PATH; ${install} first`);
|
|
183
245
|
return path;
|
|
184
246
|
}
|
|
185
247
|
const shq = (s) => (/^[\w./=:@-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
|
package/dist/commands/codex.js
CHANGED
|
@@ -51,14 +51,17 @@ export async function codex(p, out) {
|
|
|
51
51
|
}
|
|
52
52
|
if (sub === "start")
|
|
53
53
|
return codexStart(p, out);
|
|
54
|
-
if (sub === "unpause")
|
|
55
|
-
|
|
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
|
-
}
|
|
54
|
+
if (sub === "unpause")
|
|
55
|
+
return unpause(p, out);
|
|
62
56
|
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>]");
|
|
63
57
|
}
|
|
58
|
+
/**
|
|
59
|
+
* After a usage limit the watcher waits for the reset time the harness gave. When the operator has
|
|
60
|
+
* switched the harness to an account with quota, this lets the next poll start a turn instead.
|
|
61
|
+
*/
|
|
62
|
+
export async function unpause(p, out) {
|
|
63
|
+
const name = resolveAgentName(str(p.flags, "as"));
|
|
64
|
+
writeState(name, { ...readState(name), turn_unpaused_at: Date.now() });
|
|
65
|
+
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 });
|
|
66
|
+
}
|
|
64
67
|
export const codexHooksPath = () => join(process.env.CODEX_HOME ?? join(homedir(), ".codex"), "hooks.json");
|
|
@@ -330,6 +330,8 @@ export async function agentMove(rest, p, out) {
|
|
|
330
330
|
throw new CliError("usage", "agent move <project>/<agent> --to <machine> --sandbox <mode> [--dir <path>|auto] [--carry note|thread] [--from local|<ssh host>] [--model m] [--effort e] [--wait min] [--force]");
|
|
331
331
|
if (carry !== "note" && carry !== "thread")
|
|
332
332
|
throw new CliError("usage", "--carry note (a resume note it writes now) or thread (its Codex thread, copied)");
|
|
333
|
+
if (carry === "thread" && (str(p.flags, "harness") ?? "codex") !== "codex")
|
|
334
|
+
throw new CliError("usage", "--carry thread copies a Codex thread; a Claude Code agent moves with --carry note (its resume note), and its new machine starts a fresh session");
|
|
333
335
|
if (carry === "thread" && !from)
|
|
334
336
|
throw new CliError("usage", "--carry thread needs --from local|<ssh host>: the machine whose ~/.codex holds its thread");
|
|
335
337
|
const c = adminClient(p);
|
package/dist/commands/machine.js
CHANGED
|
@@ -8,9 +8,8 @@ import { configRoot, loadAgent, saveAgent } from "../config.js";
|
|
|
8
8
|
import { CliError } from "../errors.js";
|
|
9
9
|
import { CODEX_APPARMOR_PATH, CODEX_MANAGED_DIR, CODEX_MANAGED_MARK, codexAppArmorProfile, codexManagedHooks } from "../harness.js";
|
|
10
10
|
import { applySparse } from "../git.js";
|
|
11
|
-
import {
|
|
11
|
+
import { TURN_HARNESSES, claudeFacts, claudeSandbox, probeFor, sessionProcesses } from "../harnesses.js";
|
|
12
12
|
import { readState, writeState } from "../state.js";
|
|
13
|
-
import { readTurnPhase, usageLimitUntil } from "../turn.js";
|
|
14
13
|
import { installService, lingerEnabled, MACHINE_LABEL, removeService, requireInstall, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
|
|
15
14
|
import { CLI_VERSION } from "../version.js";
|
|
16
15
|
export const machineFile = () => join(configRoot(), "machine.json");
|
|
@@ -29,10 +28,10 @@ function writeMachineState(s) {
|
|
|
29
28
|
/** What a session's watcher is started with; a change means re-running codex start. The thread is compared separately. */
|
|
30
29
|
export const sessionFingerprint = (s, writable = []) => JSON.stringify([s.harness, s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, ...(writable.length ? [writable] : [])]);
|
|
31
30
|
export const watchLabelOf = (ref) => `${WATCH_LABEL_PREFIX}${ref.replace("/", ".")}`;
|
|
32
|
-
/** The `bschat
|
|
31
|
+
/** The `bschat start` arguments that bring a session up (adopting its thread or session when known). */
|
|
33
32
|
export function startArgs(s, thread, writable = []) {
|
|
34
33
|
return [
|
|
35
|
-
"
|
|
34
|
+
"start", "--harness", s.harness, "--as", s.agent, "--sandbox", s.sandbox, "--turn-timeout", String(s.turn_timeout), "--json",
|
|
36
35
|
...(s.model ? ["--model", s.model] : []),
|
|
37
36
|
...(s.effort ? ["--effort", s.effort] : []),
|
|
38
37
|
...(thread ? ["--thread", thread] : []),
|
|
@@ -64,7 +63,7 @@ export async function reconcile(m, log) {
|
|
|
64
63
|
out.push({ id: s.id, state: "stopped" });
|
|
65
64
|
continue;
|
|
66
65
|
}
|
|
67
|
-
if (s.harness
|
|
66
|
+
if (!TURN_HARNESSES.includes(s.harness))
|
|
68
67
|
throw new Error(`harness ${s.harness} is not supported by this bschat ${CLI_VERSION}`);
|
|
69
68
|
if (!s.dir) {
|
|
70
69
|
// A pool session: the daemon makes the checkout (clone once per machine, a worktree per agent).
|
|
@@ -85,10 +84,10 @@ export async function reconcile(m, log) {
|
|
|
85
84
|
if (!svc() || !local || local.fingerprint !== fp || threadChanged) {
|
|
86
85
|
const r = spawnSync(bin, startArgs(s, thread, writable), { cwd: s.dir, encoding: "utf8", timeout: 180_000 });
|
|
87
86
|
if (r.status !== 0)
|
|
88
|
-
throw new Error(`
|
|
87
|
+
throw new Error(`bschat start failed: ${errorText(r.stderr || r.stdout)}`);
|
|
89
88
|
const started = JSON.parse(r.stdout);
|
|
90
89
|
state.sessions[s.id] = { label, fingerprint: fp, thread: started.thread, key_checked_at: state.sessions[s.id]?.key_checked_at ?? Date.now() };
|
|
91
|
-
log(`${s.agent}: ${thread ?
|
|
90
|
+
log(`${s.agent}: ${thread ? "adopted" : "started"} ${s.harness === "codex" ? "thread" : "session"} ${started.thread} in ${s.dir}`);
|
|
92
91
|
}
|
|
93
92
|
else {
|
|
94
93
|
const w = svc();
|
|
@@ -106,7 +105,7 @@ export async function reconcile(m, log) {
|
|
|
106
105
|
state.sessions[s.id].unpause_applied = s.unpause_at;
|
|
107
106
|
log(`${s.agent}: usage-limit pause lifted by the operator`);
|
|
108
107
|
}
|
|
109
|
-
out.push({ id: s.id, state: "running", dir: s.dir, thread: th, watcher: w && serviceActive(w) ? "active" : "inactive", last_turn: lastTurnLine(s.agent), ...turnFacts(s.agent, th) });
|
|
108
|
+
out.push({ id: s.id, state: "running", dir: s.dir, thread: th, watcher: w && serviceActive(w) ? "active" : "inactive", last_turn: lastTurnLine(s.agent), ...turnFacts(s.agent, s.harness, th) });
|
|
110
109
|
}
|
|
111
110
|
catch (e) {
|
|
112
111
|
const error = e.message.slice(0, 1000);
|
|
@@ -126,7 +125,8 @@ export async function reconcile(m, log) {
|
|
|
126
125
|
delete state.sessions[id];
|
|
127
126
|
}
|
|
128
127
|
writeMachineState(state);
|
|
129
|
-
const
|
|
128
|
+
const clones = refreshClones(workdir, [...new Set(desired.filter((s) => !s.dir && s.project && s.desired === "running").map((s) => s.project))], log);
|
|
129
|
+
const report = { ...machineFacts(), workdir: workdir ?? join(homedir(), "bschat"), workdir_free_bytes: freeBytes(workdir ?? homedir()), clones };
|
|
130
130
|
await client.call("POST", "/machines/me/report", { report, sessions: out });
|
|
131
131
|
return { sessions: out, report };
|
|
132
132
|
}
|
|
@@ -197,6 +197,48 @@ export function ensureCheckout(s, log, workdir = null) {
|
|
|
197
197
|
return { dir };
|
|
198
198
|
}
|
|
199
199
|
const shq = (x) => `'${x.replace(/'/g, `'\\''`)}'`;
|
|
200
|
+
const CLONE_REFRESH_MS = 10 * 60_000;
|
|
201
|
+
let clonesRefreshedAt = 0;
|
|
202
|
+
/** Tests reset the 10-minute throttle. */
|
|
203
|
+
export const resetCloneRefresh = () => { clonesRefreshedAt = 0; };
|
|
204
|
+
let lastClones = {};
|
|
205
|
+
/**
|
|
206
|
+
* Keeps each project clone's checked-out branch current: fetch, then fast-forward when it is clean.
|
|
207
|
+
* Unless a project requires pushed work, wu start branches from the clone's local target, so a
|
|
208
|
+
* clone made once went stale (ronald's benignswarm clone was 52 commits behind GitHub within a day).
|
|
209
|
+
* Anything it cannot fast-forward is reported, never forced.
|
|
210
|
+
*/
|
|
211
|
+
export function refreshClones(workdir, projects, log) {
|
|
212
|
+
if (Date.now() - clonesRefreshedAt < CLONE_REFRESH_MS)
|
|
213
|
+
return lastClones;
|
|
214
|
+
clonesRefreshedAt = Date.now();
|
|
215
|
+
const out = {};
|
|
216
|
+
for (const p of projects) {
|
|
217
|
+
const base = join(workdir ?? join(homedir(), "bschat"), p, "main");
|
|
218
|
+
if (!existsSync(join(base, ".git")))
|
|
219
|
+
continue;
|
|
220
|
+
const branch = (git(["rev-parse", "--abbrev-ref", "HEAD"], base).stdout ?? "").trim();
|
|
221
|
+
if (git(["fetch", "-q", "origin"], base).status !== 0) {
|
|
222
|
+
out[p] = { branch, behind: -1, note: "fetch failed" };
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
const behind = Number((git(["rev-list", "--count", `HEAD..origin/${branch}`], base).stdout ?? "0").trim()) || 0;
|
|
226
|
+
if (behind > 0) {
|
|
227
|
+
const dirty = (git(["status", "--porcelain"], base).stdout ?? "").trim() !== "";
|
|
228
|
+
const ff = dirty ? null : git(["merge", "-q", "--ff-only", `origin/${branch}`], base);
|
|
229
|
+
if (ff && ff.status === 0) {
|
|
230
|
+
log(`${p}: clone fast-forwarded ${behind} commit(s) to origin/${branch}`);
|
|
231
|
+
out[p] = { branch, behind: 0 };
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
out[p] = { branch, behind, note: dirty ? "clone has local changes; not fast-forwarded" : "not a fast-forward of origin" };
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
out[p] = { branch, behind: 0 };
|
|
238
|
+
}
|
|
239
|
+
lastClones = out;
|
|
240
|
+
return out;
|
|
241
|
+
}
|
|
200
242
|
/** Saves the agent's key on first use, and replaces it when the server no longer accepts it. */
|
|
201
243
|
async function ensureCredentials(client, m, s, local, log) {
|
|
202
244
|
let saved = true;
|
|
@@ -236,20 +278,23 @@ function errorText(s) {
|
|
|
236
278
|
return last.slice(0, 500);
|
|
237
279
|
}
|
|
238
280
|
}
|
|
239
|
-
/** Whether the
|
|
240
|
-
function turnFacts(agent, thread) {
|
|
241
|
-
const
|
|
242
|
-
if (!thread || !
|
|
281
|
+
/** Whether the session has a turn running, its process, and a usage-limit pause still in force. */
|
|
282
|
+
function turnFacts(agent, harness, thread) {
|
|
283
|
+
const ph = thread ? probeFor(harness, thread, agent).phase() : null;
|
|
284
|
+
if (!thread || !ph || "missing" in ph)
|
|
243
285
|
return { turn: { running: false, since: null }, process: null, paused_until: null };
|
|
244
|
-
const
|
|
245
|
-
const until = !ph.running ? usageLimitUntil(ph.lastError) : null;
|
|
286
|
+
const until = !ph.running ? probeFor(harness, thread, agent).limitUntil(ph.lastError) : null;
|
|
246
287
|
const unpausedAt = readState(agent).turn_unpaused_at ?? 0;
|
|
247
|
-
const paused = until && until > Date.now() && Date.parse(ph.
|
|
248
|
-
return { turn: { running: ph.running, since: ph.running ? ph.startedAt : ph.lastEventAt }, process: ph.running ? turnProcess(thread) : null, paused_until: paused };
|
|
288
|
+
const paused = until && until > Date.now() && Date.parse(ph.lastErrorAt ?? "") > unpausedAt ? new Date(until).toISOString() : null;
|
|
289
|
+
return { turn: { running: ph.running, since: ph.running ? ph.startedAt : ph.lastEventAt }, process: ph.running ? turnProcess(thread, harness) : null, paused_until: paused };
|
|
249
290
|
}
|
|
250
|
-
/** The
|
|
251
|
-
export function turnProcess(thread, psOutput) {
|
|
291
|
+
/** The harness process running a turn of this session (`codex exec resume <thread>`, `claude ... --resume <id>`), from ps. */
|
|
292
|
+
export function turnProcess(thread, harness = "codex", psOutput) {
|
|
252
293
|
const out = psOutput ?? (spawnSync("ps", ["-axo", "pid=,pcpu=,rss=,args="], { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 }).stdout ?? "");
|
|
294
|
+
if (harness === "claude-code") {
|
|
295
|
+
const p = sessionProcesses(thread, out)[0];
|
|
296
|
+
return p ? { pid: p.pid, cpu: p.cpu, rss_bytes: p.rss_bytes } : null;
|
|
297
|
+
}
|
|
253
298
|
for (const line of out.split("\n")) {
|
|
254
299
|
const m = /^\s*(\d+)\s+([\d.]+)\s+(\d+)\s+(.*)$/.exec(line);
|
|
255
300
|
if (m && /\bcodex\b/.test(m[4]) && m[4].includes(`exec resume ${thread}`) && !m[4].startsWith("/bin/sh"))
|
|
@@ -293,6 +338,16 @@ function memAvailable() {
|
|
|
293
338
|
}
|
|
294
339
|
return freemem();
|
|
295
340
|
}
|
|
341
|
+
/** Claude Code's version, login and sandbox; the sandbox check runs at most every 10 min. */
|
|
342
|
+
let claudeSandboxCache = null;
|
|
343
|
+
function claudeReport() {
|
|
344
|
+
const f = claudeFacts();
|
|
345
|
+
if (!f)
|
|
346
|
+
return null;
|
|
347
|
+
if (!claudeSandboxCache || Date.now() - claudeSandboxCache.at > 10 * 60_000)
|
|
348
|
+
claudeSandboxCache = { at: Date.now(), result: claudeSandbox() };
|
|
349
|
+
return { ...f, sandbox: claudeSandboxCache.result };
|
|
350
|
+
}
|
|
296
351
|
/** What the operator needs to know about this machine, reported with every pass. */
|
|
297
352
|
export function machineFacts() {
|
|
298
353
|
const codex = spawnSync("codex", ["--version"], { encoding: "utf8" });
|
|
@@ -311,6 +366,7 @@ export function machineFacts() {
|
|
|
311
366
|
load: loadavg().map((x) => Math.round(x * 100) / 100), mem_available_bytes: memAvailable(),
|
|
312
367
|
bschat: { version: CLI_VERSION, bin: requireInstall().bin },
|
|
313
368
|
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), sandbox: codexSandbox() } : null,
|
|
369
|
+
"claude-code": claudeReport(),
|
|
314
370
|
managed_hooks: existsSync(req) && readFileSync(req, "utf8").includes(CODEX_MANAGED_MARK),
|
|
315
371
|
linger: platform() === "linux" ? lingerEnabled() : null,
|
|
316
372
|
disk_free_bytes: diskFree,
|
|
@@ -362,6 +418,13 @@ export function prepare(opts = {}) {
|
|
|
362
418
|
: { step: "codex sandbox", result: "failed", detail: l.status !== 0 ? `installing ${CODEX_APPARMOR_PATH}: ${(l.stderr ?? "").trim()}` : `profile installed but the sandbox still fails: ${sb.error}` });
|
|
363
419
|
}
|
|
364
420
|
}
|
|
421
|
+
// Claude Code is optional on a machine; when it is there, say whether it can run agents.
|
|
422
|
+
const claude = claudeFacts();
|
|
423
|
+
if (claude) {
|
|
424
|
+
steps.push({ step: "claude code", result: claude.logged_in ? "ok" : "failed", detail: claude.logged_in ? `${claude.version}, ${claude.login}` : `${claude.version} is not logged in: run claude auth login on this machine (over ssh it prints a link to open in your browser and asks for the code)` });
|
|
425
|
+
const sb = claudeSandbox();
|
|
426
|
+
steps.push({ step: "claude code sandbox", result: sb.ok ? "ok" : "failed", detail: sb.ok ? "sandboxed (workspace-write) Claude Code agents can run here" : `${sb.error}; only danger-full-access Claude Code agents can run here` });
|
|
427
|
+
}
|
|
365
428
|
const req = "/etc/codex/requirements.toml";
|
|
366
429
|
const { requirements, wrapper } = codexManagedHooks(requireInstall().bin);
|
|
367
430
|
const current = existsSync(req) ? readFileSync(req, "utf8") : null;
|
package/dist/commands/watch.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { spawn, spawnSync } from "node:child_process";
|
|
2
|
-
import { bindSession,
|
|
3
|
-
import {
|
|
2
|
+
import { bindSession, sessionOfExec, threadOfExec } from "../sessions.js";
|
|
3
|
+
import { startTurn, stopTurn } from "../turn.js";
|
|
4
|
+
import { probeFor, turnHarness } from "../harnesses.js";
|
|
4
5
|
import { applyAck } from "./wake.js";
|
|
5
6
|
import { lingerEnabled, loadSystemdUnit, reloadLaunchAgent, removeService, requireInstall, systemdUnit, systemdUserDir, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
|
|
6
7
|
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
@@ -49,13 +50,24 @@ export async function watch(p, out) {
|
|
|
49
50
|
if (!Number.isInteger(turnTimeout) || turnTimeout < 5)
|
|
50
51
|
throw new CliError("usage", "--turn-timeout must be a whole number of minutes, at least 5");
|
|
51
52
|
const thread = exec ? threadOfExec(exec) : null;
|
|
53
|
+
// Which harness runs the turns and the session they continue. Codex watchers installed before
|
|
54
|
+
// 0.12.66 carry neither flag: their thread is in the exec command.
|
|
55
|
+
let turn = null;
|
|
52
56
|
if (turnMode) {
|
|
53
57
|
if (!exec)
|
|
54
|
-
throw new CliError("usage", '--turn needs --exec
|
|
58
|
+
throw new CliError("usage", '--turn needs --exec with the command that runs one turn, ending in {text}');
|
|
55
59
|
if (full)
|
|
56
60
|
throw new CliError("usage", "--turn and --full do not mix: a turn starts from one wake-up");
|
|
57
|
-
if (/\bcodex\s+queue\b/.test(exec)
|
|
61
|
+
if (/\bcodex\s+queue\b/.test(exec))
|
|
58
62
|
throw new CliError("usage", "--turn runs the turn itself: --exec must be codex exec resume <thread-id> ... {text}, not codex queue");
|
|
63
|
+
const named = str(p.flags, "harness") ?? (thread ? "codex" : undefined);
|
|
64
|
+
if (!named)
|
|
65
|
+
throw new CliError("usage", "--turn needs --harness <codex|claude-code> and --session <id> (a Codex exec resume command names its thread itself)");
|
|
66
|
+
const harness = turnHarness(named);
|
|
67
|
+
const session = (str(p.flags, "session") ?? (harness === "codex" ? thread : null))?.toLowerCase();
|
|
68
|
+
if (!session)
|
|
69
|
+
throw new CliError("usage", `--turn with --harness ${harness} needs --session <id>: the session its turns continue`);
|
|
70
|
+
turn = { harness, session, timeout: turnTimeout };
|
|
59
71
|
}
|
|
60
72
|
if (bool(p.flags, "launchd") || bool(p.flags, "service")) {
|
|
61
73
|
if (!exec)
|
|
@@ -68,7 +80,7 @@ export async function watch(p, out) {
|
|
|
68
80
|
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
81
|
extraEnv[n] = v;
|
|
70
82
|
}
|
|
71
|
-
return installWatcherService(name, exec, interval, followDelay, extraEnv, str(p.flags, "activity"), out, bool(p.flags, "prune"),
|
|
83
|
+
return installWatcherService(name, exec, interval, followDelay, extraEnv, str(p.flags, "activity"), out, bool(p.flags, "prune"), turn);
|
|
72
84
|
}
|
|
73
85
|
if (!exec && !once)
|
|
74
86
|
throw new CliError("usage", 'watch --exec "<command>" [--interval 30] | watch --once (print and exit) | watch --exec ... --service (launchd on macOS, systemd on Linux)');
|
|
@@ -101,6 +113,7 @@ export async function watch(p, out) {
|
|
|
101
113
|
// the key on its own clock.
|
|
102
114
|
let lastKeyCheck = 0;
|
|
103
115
|
const ctl = { turn: null, failedAt: 0, loggedRunning: null, pausedUntil: 0, pausedAt: 0 };
|
|
116
|
+
const probe = turn ? probeFor(turn.harness, turn.session, name) : null;
|
|
104
117
|
for (;;) {
|
|
105
118
|
if (activity && heartbeatClient)
|
|
106
119
|
lastSample = await heartbeatIfActive(heartbeatClient, activity, lastSample, interval, log);
|
|
@@ -153,8 +166,8 @@ export async function watch(p, out) {
|
|
|
153
166
|
}
|
|
154
167
|
if (!full) {
|
|
155
168
|
try {
|
|
156
|
-
if (
|
|
157
|
-
await turnStep(ctl,
|
|
169
|
+
if (probe)
|
|
170
|
+
await turnStep(ctl, probe, turnTimeout, log, (sink) => wakeOnce(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once, sink), name);
|
|
158
171
|
else
|
|
159
172
|
await wakeOnce(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once);
|
|
160
173
|
}
|
|
@@ -337,8 +350,12 @@ async function deliver(name, exec, wake, summary, tier, total, log, prefix, seq,
|
|
|
337
350
|
*/
|
|
338
351
|
function stopRevokedWatcher(name, log) {
|
|
339
352
|
const label = `${WATCH_LABEL_PREFIX}${name.replace("/", ".")}`;
|
|
340
|
-
|
|
341
|
-
|
|
353
|
+
// By label, else by the --as it runs with: watchers installed before 0.9 carry labels without the
|
|
354
|
+
// project (org.benignswarm.watch.visualizer-creator), and missing them left a restart loop.
|
|
355
|
+
const bare = name.split("/").pop();
|
|
356
|
+
const svc = watcherServices().find((s) => s.label === label)
|
|
357
|
+
?? watcherServices().find((s) => { const a = s.args ?? []; const i = a.indexOf("--as"); return a[1] === "watch" && i >= 0 && (a[i + 1] === name || a[i + 1] === bare); });
|
|
358
|
+
log(`this agent's key was revoked (moved to another machine, or retired): stopping and removing ${svc?.label ?? `${label} (no service found; exiting)`}`);
|
|
342
359
|
if (svc)
|
|
343
360
|
removeService(svc); // ends this process when it unloads the service
|
|
344
361
|
process.exit(0);
|
|
@@ -352,22 +369,20 @@ const KEY_CHECK_MS = 5 * 60_000;
|
|
|
352
369
|
* leaves the wake-up unacknowledged on the server, so a wake path that keeps failing shows as
|
|
353
370
|
* broken; one that runs past --turn-timeout is stopped and logged.
|
|
354
371
|
*/
|
|
355
|
-
async function turnStep(ctl,
|
|
356
|
-
const rollout = codexRollout(thread);
|
|
372
|
+
async function turnStep(ctl, probe, timeoutMin, log, wake, name) {
|
|
357
373
|
const turn = ctl.turn;
|
|
358
374
|
if (turn) {
|
|
359
|
-
if (!turn.confirmed &&
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
await ackTurn(name, turn.seq, log);
|
|
364
|
-
log(`turn #${turn.seq} started in the session; wake-up acknowledged`);
|
|
365
|
-
}
|
|
375
|
+
if (!turn.confirmed && probe.startedSince(turn.startedMs)) {
|
|
376
|
+
turn.confirmed = true;
|
|
377
|
+
await ackTurn(name, turn.seq, log);
|
|
378
|
+
log(`turn #${turn.seq} started in the session; wake-up acknowledged`);
|
|
366
379
|
}
|
|
367
380
|
if (turn.exit) {
|
|
368
381
|
const mins = Math.round((Date.now() - turn.startedMs) / 60_000);
|
|
369
382
|
const how = turn.exit.code !== null ? `exit ${turn.exit.code}` : `signal ${turn.exit.signal}`;
|
|
370
|
-
|
|
383
|
+
// A harness may exit 0 with an error in its result (Claude Code's is_error), so both count.
|
|
384
|
+
const error = turn.killedForTimeout ? null : probe.turnError();
|
|
385
|
+
if (turn.exit.code === 0 && !error) {
|
|
371
386
|
if (!turn.confirmed)
|
|
372
387
|
await ackTurn(name, turn.seq, log);
|
|
373
388
|
log(`turn #${turn.seq} finished after ${mins} min`);
|
|
@@ -377,16 +392,15 @@ async function turnStep(ctl, thread, timeoutMin, log, wake, name) {
|
|
|
377
392
|
}
|
|
378
393
|
else {
|
|
379
394
|
// Every failure waits before the next turn: a turn started right after one that failed
|
|
380
|
-
// usually fails the same way. A usage limit waits until the time
|
|
381
|
-
const
|
|
382
|
-
const until = usageLimitUntil(error);
|
|
395
|
+
// usually fails the same way. A usage limit waits until the time the harness names.
|
|
396
|
+
const until = probe.limitUntil(error);
|
|
383
397
|
if (until && until > Date.now()) {
|
|
384
398
|
ctl.pausedUntil = until;
|
|
385
399
|
ctl.pausedAt = Date.now();
|
|
386
|
-
log(`TURN #${turn.seq} FAILED: the
|
|
400
|
+
log(`TURN #${turn.seq} FAILED: the ${probe.label} account hit its usage limit; no turns until ${new Date(until).toISOString()} (${probe.label} said: ${error})`);
|
|
387
401
|
}
|
|
388
402
|
else {
|
|
389
|
-
log(`TURN #${turn.seq} FAILED (${how}) after ${mins} min${turn.confirmed ? "" : "; it never started in the session, so the wake-up stays unacknowledged"}${error ? `;
|
|
403
|
+
log(`TURN #${turn.seq} FAILED (${how}) after ${mins} min${turn.confirmed ? "" : "; it never started in the session, so the wake-up stays unacknowledged"}${error ? `; ${probe.label} said: ${error}` : ""}${probe.isLimit(error) ? ` (a usage limit with no reset time named)` : ""}. Next turn in 5 min at the earliest; its output is in this log.`);
|
|
390
404
|
}
|
|
391
405
|
if (!turn.confirmed)
|
|
392
406
|
writeState(name, { ...readState(name), watch_pending: undefined, watch_dormant_logged_at: undefined });
|
|
@@ -401,10 +415,10 @@ async function turnStep(ctl, thread, timeoutMin, log, wake, name) {
|
|
|
401
415
|
}
|
|
402
416
|
return;
|
|
403
417
|
}
|
|
404
|
-
// bschat
|
|
418
|
+
// bschat unpause: the operator switched the harness to an account with quota.
|
|
405
419
|
const unpausedAt = readState(name).turn_unpaused_at ?? 0;
|
|
406
420
|
if (ctl.pausedUntil > Date.now() && unpausedAt > ctl.pausedAt) {
|
|
407
|
-
log(`usage-limit pause lifted by bschat
|
|
421
|
+
log(`usage-limit pause lifted by bschat unpause`);
|
|
408
422
|
ctl.pausedUntil = 0;
|
|
409
423
|
ctl.failedAt = 0;
|
|
410
424
|
}
|
|
@@ -412,36 +426,41 @@ async function turnStep(ctl, thread, timeoutMin, log, wake, name) {
|
|
|
412
426
|
return;
|
|
413
427
|
if (ctl.pausedUntil > Date.now())
|
|
414
428
|
return;
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
}
|
|
429
|
+
// A turn this watcher did not start: an app or a terminal on the same session, or a turn left
|
|
430
|
+
// running by a watcher that restarted (turns run in their own process group and outlive it).
|
|
431
|
+
// Never start a second one.
|
|
432
|
+
const ph = probe.phase();
|
|
433
|
+
if ("missing" in ph) {
|
|
434
|
+
log(ph.missing);
|
|
435
|
+
return;
|
|
436
|
+
}
|
|
437
|
+
// A watcher that restarted after a usage-limit failure reads the pause from the session itself.
|
|
438
|
+
const until = !ph.running && Date.parse(ph.lastErrorAt ?? "") > unpausedAt ? probe.limitUntil(ph.lastError) : null;
|
|
439
|
+
if (until && until > Date.now()) {
|
|
440
|
+
ctl.pausedUntil = until;
|
|
441
|
+
ctl.pausedAt = Date.now();
|
|
442
|
+
log(`the last turn in ${probe.what} hit the ${probe.label} usage limit; no turns until ${new Date(until).toISOString()}`);
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
if (ph.running) {
|
|
446
|
+
const quietMs = Date.now() - Date.parse(ph.lastEventAt ?? ph.startedAt ?? "");
|
|
447
|
+
if (!(quietMs >= timeoutMin * 60_000)) {
|
|
435
448
|
if (ctl.loggedRunning !== ph.startedAt)
|
|
436
|
-
log(`
|
|
449
|
+
log(`a turn started at ${ph.startedAt} is still running in ${probe.what} (an app or terminal on it, or a turn from before a restart); waiting for it`);
|
|
437
450
|
ctl.loggedRunning = ph.startedAt;
|
|
451
|
+
return;
|
|
438
452
|
}
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
453
|
+
if (probe.label !== "Codex") {
|
|
454
|
+
// A live process still holds the session: a second turn on it would conflict. Say so once.
|
|
455
|
+
if (ctl.loggedRunning !== `stuck:${ph.startedAt}`)
|
|
456
|
+
log(`a process still holds ${probe.what} and has written nothing for ${Math.round(quietMs / 60_000)} min (over the ${timeoutMin}-min limit); starting no turn while it runs. End it to free the session.`);
|
|
457
|
+
ctl.loggedRunning = `stuck:${ph.startedAt}`;
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
// Codex: the rollout shows a turn that never closed; with nothing written for that long it is dead.
|
|
461
|
+
if (ctl.loggedRunning !== ph.startedAt)
|
|
462
|
+
log(`the turn started at ${ph.startedAt} has written nothing for ${Math.round(quietMs / 60_000)} min (over the ${timeoutMin}-min limit); treating it as dead`);
|
|
463
|
+
ctl.loggedRunning = ph.startedAt;
|
|
445
464
|
}
|
|
446
465
|
const st = readState(name);
|
|
447
466
|
if (st.watch_pending) {
|
|
@@ -499,9 +518,9 @@ function run(cmd, stdin, env) {
|
|
|
499
518
|
* Installs the watcher as a service that keeps it running for this identity: a LaunchAgent on macOS,
|
|
500
519
|
* a systemd user unit on Linux. Both run the machine's recorded install from this directory.
|
|
501
520
|
*/
|
|
502
|
-
export function installWatcherService(name, exec, interval, followDelay, extraEnv, activity, out, prune = false,
|
|
521
|
+
export function installWatcherService(name, exec, interval, followDelay, extraEnv, activity, out, prune = false, turn = null) {
|
|
503
522
|
if (process.platform === "darwin")
|
|
504
|
-
return installLaunchd(name, exec, interval, followDelay, extraEnv, activity, out, prune,
|
|
523
|
+
return installLaunchd(name, exec, interval, followDelay, extraEnv, activity, out, prune, turn);
|
|
505
524
|
if (process.platform !== "linux")
|
|
506
525
|
throw new CliError("unsupported", "--service runs watchers under launchd (macOS) or systemd (Linux); on this system run bschat watch under your own supervisor");
|
|
507
526
|
const slug = name.replace("/", ".");
|
|
@@ -509,7 +528,7 @@ export function installWatcherService(name, exec, interval, followDelay, extraEn
|
|
|
509
528
|
const logDir = join(homedir(), ".bschat", "logs");
|
|
510
529
|
mkdirSync(systemdUserDir(), { recursive: true });
|
|
511
530
|
mkdirSync(logDir, { recursive: true });
|
|
512
|
-
const args = [requireInstall().bin, "watch", "--as", name, "--exec", exec, "--interval", String(interval), "--follow-delay", String(followDelay), ...(activity ? ["--activity", activity] : []), ...(prune ? ["--prune"] : []), ...(
|
|
531
|
+
const args = [requireInstall().bin, "watch", "--as", name, "--exec", exec, "--interval", String(interval), "--follow-delay", String(followDelay), ...(activity ? ["--activity", activity] : []), ...(prune ? ["--prune"] : []), ...turnArgs(turn)];
|
|
513
532
|
const env = { PATH: process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin", HOME: homedir(), ...extraEnv };
|
|
514
533
|
const path = join(systemdUserDir(), `${label}.service`);
|
|
515
534
|
writeFileSync(path, systemdUnit(label, args, process.cwd(), env, logDir));
|
|
@@ -528,7 +547,7 @@ export function installWatcherService(name, exec, interval, followDelay, extraEn
|
|
|
528
547
|
].filter(Boolean).join("\n"), { unit: path, label, program: args[0], linger });
|
|
529
548
|
}
|
|
530
549
|
/** Writes a launchd agent that keeps `bschat watch` running for this identity on macOS. */
|
|
531
|
-
function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, out, prune = false,
|
|
550
|
+
function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, out, prune = false, turn = null) {
|
|
532
551
|
if (process.platform !== "darwin")
|
|
533
552
|
throw new CliError("unsupported", "--launchd is macOS only; on Linux run `bschat watch` under a systemd user service");
|
|
534
553
|
const slug = name.replace("/", ".");
|
|
@@ -551,8 +570,8 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
|
|
|
551
570
|
<string>--interval</string><string>${interval}</string>
|
|
552
571
|
<string>--follow-delay</string><string>${followDelay}</string>${activity ? `
|
|
553
572
|
<string>--activity</string><string>${escapeXml(activity)}</string>` : ""}${prune ? `
|
|
554
|
-
<string>--prune</string>` : ""}${
|
|
555
|
-
|
|
573
|
+
<string>--prune</string>` : ""}${turnArgs(turn).length ? `
|
|
574
|
+
${turnArgs(turn).map((a) => `<string>${escapeXml(a)}</string>`).join("")}` : ""}
|
|
556
575
|
</array>
|
|
557
576
|
<key>EnvironmentVariables</key><dict><key>PATH</key><string>${escapeXml(process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin")}</string><key>HOME</key><string>${homedir()}</string>${Object.entries(extraEnv).map(([k, v]) => `<key>${escapeXml(k)}</key><string>${escapeXml(v)}</string>`).join("")}</dict>
|
|
558
577
|
<key>WorkingDirectory</key><string>${escapeXml(process.cwd())}</string>
|
|
@@ -573,6 +592,7 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
|
|
|
573
592
|
bindSession(sess.kind, sess.id, name);
|
|
574
593
|
out.print(`Wrote ${path} and (re)loaded it: the watcher is running ${program[0]}.${Object.keys(extraEnv).length ? `\nCaptured env: ${Object.keys(extraEnv).join(", ")} (re-run this command if the harness restarts and these change)` : ""}\nStop it: launchctl bootout gui/$(id -u)/${label}\nLogs: ${logDir}/watch.${slug}.*.log\nCheck it: bschat doctor\nThe watcher runs from ${process.cwd()} so the repo identity file applies.`, { plist: path, label, program: program[0] });
|
|
575
594
|
}
|
|
595
|
+
const turnArgs = (t) => (t ? ["--turn", "--turn-timeout", String(t.timeout), "--harness", t.harness, "--session", t.session] : []);
|
|
576
596
|
function escapeXml(s) {
|
|
577
597
|
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
578
598
|
}
|
package/dist/harness.js
CHANGED
|
@@ -84,13 +84,18 @@ export function upsertBlock(path, body) {
|
|
|
84
84
|
else
|
|
85
85
|
writeFileSync(path, (cur.endsWith("\n") || cur === "" ? cur : cur + "\n") + "\n" + block);
|
|
86
86
|
}
|
|
87
|
-
|
|
87
|
+
/**
|
|
88
|
+
* The section join writes into AGENTS.md / GEMINI.md. Those files are usually committed and read on
|
|
89
|
+
* every machine, so it names no path: a Mac's /opt/homebrew/bin/bschat in a committed AGENTS.md
|
|
90
|
+
* pointed agents on a Linux machine at nothing. Each machine records its install in install.json.
|
|
91
|
+
*/
|
|
92
|
+
function pointer(_name, apiUrl, _bin) {
|
|
88
93
|
return [
|
|
89
94
|
`## bschat: agent chat for this project`,
|
|
90
95
|
``,
|
|
91
|
-
`This repo's agents coordinate on BenignSwarm with the \`bschat\` command, installed
|
|
92
|
-
`machine
|
|
93
|
-
`and do not use npx). Your identity for this repo is recorded in \`.bschat/identity.json\``,
|
|
96
|
+
`This repo's agents coordinate on BenignSwarm with the \`bschat\` command, installed once per`,
|
|
97
|
+
`machine (if \`bschat\` is not on your PATH, \`~/.bschat/install.json\` names this machine's copy;`,
|
|
98
|
+
`do not install another, and do not use npx). Your identity for this repo is recorded in \`.bschat/identity.json\``,
|
|
94
99
|
`(vendor -> agent name), so it works without env vars. If you are told you are a different agent,`,
|
|
95
100
|
`export BSCHAT_AGENT=<project>/<name>.`,
|
|
96
101
|
``,
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import { CliError } from "./errors.js";
|
|
6
|
+
import { codexArchivedRollout, codexRollout } from "./sessions.js";
|
|
7
|
+
import { codexTurnPhase, usageLimitUntil } from "./turn.js";
|
|
8
|
+
/**
|
|
9
|
+
* Harnesses a machine can run headless in turn mode (docs/REMOTE-MACHINES.md, "Harness adapters").
|
|
10
|
+
* Each adapter says how to start a session, what one turn's command is, whether a turn is running in
|
|
11
|
+
* that session (by anyone: an app, a terminal, a turn left by a watcher that restarted), and how the
|
|
12
|
+
* last turn ended. Antigravity is a desktop application with no headless turn and stays hand-run;
|
|
13
|
+
* Gemini CLI no longer accepts personal logins (Google moved individuals to Antigravity).
|
|
14
|
+
*/
|
|
15
|
+
export const TURN_HARNESSES = ["codex", "claude-code"];
|
|
16
|
+
export function turnHarness(h) {
|
|
17
|
+
if (TURN_HARNESSES.includes(h))
|
|
18
|
+
return h;
|
|
19
|
+
throw new CliError("unsupported", `harness ${h} cannot run headless turns; supported: ${TURN_HARNESSES.join(", ")}`);
|
|
20
|
+
}
|
|
21
|
+
export const HARNESS_LABEL = { codex: "Codex", "claude-code": "Claude Code" };
|
|
22
|
+
export const HARNESS_BIN = { codex: "codex", "claude-code": "claude" };
|
|
23
|
+
export function probeFor(harness, session, ref) {
|
|
24
|
+
return harness === "codex" ? codexProbe(session) : claudeProbe(session, ref);
|
|
25
|
+
}
|
|
26
|
+
function codexProbe(thread) {
|
|
27
|
+
const read = () => { const r = codexRollout(thread); return r ? codexTurnPhase(readFileSync(r, "utf8")) : null; };
|
|
28
|
+
return {
|
|
29
|
+
label: "Codex",
|
|
30
|
+
what: `thread ${thread}`,
|
|
31
|
+
phase() {
|
|
32
|
+
const ph = read();
|
|
33
|
+
if (ph)
|
|
34
|
+
return { ...ph, lastErrorAt: ph.lastEventAt };
|
|
35
|
+
return {
|
|
36
|
+
missing: codexArchivedRollout(thread)
|
|
37
|
+
? `thread ${thread} is archived in the Codex app (its session file is in ~/.codex/archived_sessions); starting no turn until it is unarchived`
|
|
38
|
+
: `no session file for thread ${thread} under ~/.codex/sessions; cannot tell whether a turn is running, so starting none`,
|
|
39
|
+
};
|
|
40
|
+
},
|
|
41
|
+
startedSince(ms) { const ph = read(); return !!ph?.startedAt && Date.parse(ph.startedAt) >= ms - 5_000; },
|
|
42
|
+
turnError() { return read()?.lastError ?? null; },
|
|
43
|
+
limitUntil: usageLimitUntil,
|
|
44
|
+
isLimit: (e) => !!e && /usage limit/i.test(e),
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
// ---- Claude Code ----
|
|
48
|
+
const claudeHome = () => process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude");
|
|
49
|
+
/** A Claude Code session's transcript (~/.claude/projects/<folder>/<id>.jsonl), wherever its folder is. */
|
|
50
|
+
export function claudeTranscript(session) {
|
|
51
|
+
const root = join(claudeHome(), "projects");
|
|
52
|
+
if (!existsSync(root))
|
|
53
|
+
return null;
|
|
54
|
+
for (const d of readdirSync(root, { withFileTypes: true })) {
|
|
55
|
+
if (!d.isDirectory())
|
|
56
|
+
continue;
|
|
57
|
+
const f = join(root, d.name, `${session}.jsonl`);
|
|
58
|
+
if (existsSync(f))
|
|
59
|
+
return f;
|
|
60
|
+
}
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
/** The last turn's output (`claude -p --output-format json`), written by the watcher's turn command. */
|
|
64
|
+
export const claudeResultFile = (ref) => join(homedir(), ".bschat", "logs", `turn.${ref.replace("/", ".")}.json`);
|
|
65
|
+
/** The latest timestamp in a transcript, and the latest user prompt's. */
|
|
66
|
+
export function claudeTranscriptTimes(text) {
|
|
67
|
+
let lastEventAt = null;
|
|
68
|
+
let promptAt = null;
|
|
69
|
+
for (const line of text.split("\n")) {
|
|
70
|
+
if (!line)
|
|
71
|
+
continue;
|
|
72
|
+
let j;
|
|
73
|
+
try {
|
|
74
|
+
j = JSON.parse(line);
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
continue;
|
|
78
|
+
} // a line still being written
|
|
79
|
+
if (!j.timestamp)
|
|
80
|
+
continue;
|
|
81
|
+
lastEventAt = j.timestamp;
|
|
82
|
+
if (j.type === "user" && typeof j.message?.content === "string")
|
|
83
|
+
promptAt = j.timestamp;
|
|
84
|
+
}
|
|
85
|
+
return { lastEventAt, promptAt };
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* The error a `claude -p --output-format json` run ended with, or null when it succeeded. Output
|
|
89
|
+
* that is not the result object (a missing session prints plain text) is returned as the error.
|
|
90
|
+
*/
|
|
91
|
+
export function claudeResultError(text) {
|
|
92
|
+
const t = text.trim();
|
|
93
|
+
if (!t)
|
|
94
|
+
return "the turn wrote no result";
|
|
95
|
+
let j;
|
|
96
|
+
try {
|
|
97
|
+
j = JSON.parse(t.split("\n").filter((l) => l.startsWith("{")).pop() ?? "");
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return t.split("\n").pop().slice(0, 500);
|
|
101
|
+
}
|
|
102
|
+
if (!j.is_error)
|
|
103
|
+
return null;
|
|
104
|
+
const parts = [j.result, ...(Array.isArray(j.errors) ? j.errors.map(String) : [])].filter((x) => typeof x === "string" && x.length > 0);
|
|
105
|
+
return `${parts.join("; ") || "error"}${j.terminal_reason ? ` (${j.terminal_reason}${j.api_error_status ? `, HTTP ${j.api_error_status}` : ""})` : ""}`.slice(0, 500);
|
|
106
|
+
}
|
|
107
|
+
export const claudeIsLimit = (e) => !!e && /usage limit|session limit|weekly limit|monthly limit|hit your .* limit|HTTP 429|rate_limit/i.test(e);
|
|
108
|
+
/**
|
|
109
|
+
* When a Claude usage-limit message says it resets ("resets 3pm", "resets at 3:30 PM"), in this
|
|
110
|
+
* machine's local time (the turn ran here), the next such moment after `now`; null when it names none.
|
|
111
|
+
*/
|
|
112
|
+
export function claudeLimitUntil(error, now = Date.now()) {
|
|
113
|
+
if (!claudeIsLimit(error))
|
|
114
|
+
return null;
|
|
115
|
+
const epoch = /\|(\d{10})\b/.exec(error);
|
|
116
|
+
if (epoch)
|
|
117
|
+
return Number(epoch[1]) * 1000;
|
|
118
|
+
const m = /resets?\s+(?:at\s+)?(\d{1,2})(?::(\d{2}))?\s*([ap]m)\b/i.exec(error);
|
|
119
|
+
if (!m)
|
|
120
|
+
return null;
|
|
121
|
+
let h = Number(m[1]) % 12;
|
|
122
|
+
if (m[3].toLowerCase() === "pm")
|
|
123
|
+
h += 12;
|
|
124
|
+
const d = new Date(now);
|
|
125
|
+
d.setHours(h, Number(m[2] ?? 0), 0, 0);
|
|
126
|
+
if (d.getTime() <= now)
|
|
127
|
+
d.setDate(d.getDate() + 1);
|
|
128
|
+
return d.getTime();
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* The command is Claude Code itself (its native binary, or node running its package), not a shell
|
|
132
|
+
* wrapping it and not a bschat watcher whose --exec names the session.
|
|
133
|
+
*/
|
|
134
|
+
export function isClaudeCommand(args) {
|
|
135
|
+
const [first, second = ""] = args.trim().split(/\s+/);
|
|
136
|
+
const base = first.split("/").pop();
|
|
137
|
+
if (base === "claude" || base === "claude.exe")
|
|
138
|
+
return true;
|
|
139
|
+
return /^node(js)?$/.test(base) && /claude-code\/|\/claude$/.test(second);
|
|
140
|
+
}
|
|
141
|
+
/** Processes whose arguments carry this session id (a turn, or someone's `claude --resume <id>`), not counting ps itself. */
|
|
142
|
+
export function sessionProcesses(session, psOutput) {
|
|
143
|
+
const out = psOutput ?? (spawnSync("ps", ["-axo", "pid=,pcpu=,rss=,args="], { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 }).stdout ?? "");
|
|
144
|
+
const found = [];
|
|
145
|
+
for (const line of out.split("\n")) {
|
|
146
|
+
const m = /^\s*(\d+)\s+([\d.]+)\s+(\d+)\s+(.*)$/.exec(line);
|
|
147
|
+
if (m && m[4].includes(session) && isClaudeCommand(m[4]) && Number(m[1]) !== process.pid)
|
|
148
|
+
found.push({ pid: Number(m[1]), cpu: Number(m[2]), rss_bytes: Number(m[3]) * 1024, args: m[4] });
|
|
149
|
+
}
|
|
150
|
+
return found;
|
|
151
|
+
}
|
|
152
|
+
function claudeProbe(session, ref) {
|
|
153
|
+
const resultFile = claudeResultFile(ref);
|
|
154
|
+
const lastResult = () => existsSync(resultFile) ? { error: claudeResultError(readFileSync(resultFile, "utf8")), at: statSync(resultFile).mtime.toISOString() } : null;
|
|
155
|
+
return {
|
|
156
|
+
label: "Claude Code",
|
|
157
|
+
what: `session ${session}`,
|
|
158
|
+
phase() {
|
|
159
|
+
const tr = claudeTranscript(session);
|
|
160
|
+
if (!tr)
|
|
161
|
+
return { missing: `no transcript for Claude Code session ${session} under ${join(claudeHome(), "projects")}; cannot tell whether a turn is running, so starting none` };
|
|
162
|
+
const times = claudeTranscriptTimes(readFileSync(tr, "utf8"));
|
|
163
|
+
// Claude Code writes no turn-ended marker, so a running turn is a process holding the session.
|
|
164
|
+
const running = sessionProcesses(session).length > 0;
|
|
165
|
+
const res = lastResult();
|
|
166
|
+
return { running, startedAt: times.promptAt, lastEventAt: times.lastEventAt, lastError: running ? null : res?.error ?? null, lastErrorAt: res?.at ?? null };
|
|
167
|
+
},
|
|
168
|
+
startedSince(ms) {
|
|
169
|
+
const tr = claudeTranscript(session);
|
|
170
|
+
const p = tr ? claudeTranscriptTimes(readFileSync(tr, "utf8")).promptAt : null;
|
|
171
|
+
return !!p && Date.parse(p) >= ms - 5_000;
|
|
172
|
+
},
|
|
173
|
+
turnError: () => lastResult()?.error ?? null,
|
|
174
|
+
limitUntil: (e) => claudeLimitUntil(e),
|
|
175
|
+
isLimit: claudeIsLimit,
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* The Claude Code flags a headless turn runs with. Claude Code's sandbox always lets the agent write
|
|
180
|
+
* its working folder, so read-only cannot be honoured and is refused. workspace-write is its sandbox
|
|
181
|
+
* (refusing to start when the sandbox is unavailable, never running a command outside it), every
|
|
182
|
+
* domain reachable as with Codex, edits allowed in the checkout and the folders `wu start` and bschat
|
|
183
|
+
* write (the checkout's parent, ~/.bschat) plus the machine's writable folders; anything that would
|
|
184
|
+
* need a prompt is denied, since nobody can answer one. danger-full-access skips permissions.
|
|
185
|
+
*/
|
|
186
|
+
export function claudeSettings(sandbox, model, effort, cwd, bschatHome, extraWritable = []) {
|
|
187
|
+
const common = [...(model ? ["--model", model] : []), ...(effort ? ["--effort", effort] : [])];
|
|
188
|
+
if (sandbox === "danger-full-access")
|
|
189
|
+
return [...common, "--permission-mode", "bypassPermissions"];
|
|
190
|
+
if (sandbox === "read-only")
|
|
191
|
+
throw new CliError("unsupported", "Claude Code has no read-only sandbox: its sandbox always lets the agent write its working folder. Use workspace-write (sandboxed; writes limited to the checkout, its unit worktrees, ~/.bschat and the machine's writable folders) or danger-full-access");
|
|
192
|
+
if (sandbox !== "workspace-write")
|
|
193
|
+
throw new CliError("usage", `unknown sandbox ${sandbox}`);
|
|
194
|
+
const dirs = [dirname(cwd), bschatHome, ...extraWritable];
|
|
195
|
+
const settings = {
|
|
196
|
+
sandbox: {
|
|
197
|
+
enabled: true,
|
|
198
|
+
failIfUnavailable: true,
|
|
199
|
+
autoAllowBashIfSandboxed: true,
|
|
200
|
+
allowUnsandboxedCommands: false,
|
|
201
|
+
filesystem: { allowWrite: dirs },
|
|
202
|
+
network: { allowedDomains: ["*"] },
|
|
203
|
+
},
|
|
204
|
+
};
|
|
205
|
+
return [...common, "--permission-mode", "acceptEdits", ...dirs.flatMap((d) => ["--add-dir", d]), "--settings", JSON.stringify(settings)];
|
|
206
|
+
}
|
|
207
|
+
/** Claude Code's version and login (`claude auth status`), for the machine report. */
|
|
208
|
+
export function claudeFacts() {
|
|
209
|
+
const v = spawnSync("claude", ["--version"], { encoding: "utf8", timeout: 30_000 });
|
|
210
|
+
if (v.status !== 0)
|
|
211
|
+
return null;
|
|
212
|
+
const s = spawnSync("claude", ["auth", "status"], { encoding: "utf8", timeout: 30_000 });
|
|
213
|
+
let logged = false;
|
|
214
|
+
let login = `${s.stdout ?? ""}${s.stderr ?? ""}`.trim();
|
|
215
|
+
try {
|
|
216
|
+
const j = JSON.parse(s.stdout);
|
|
217
|
+
logged = s.status === 0 && j.loggedIn === true;
|
|
218
|
+
login = logged ? `logged in (${j.authMethod ?? "unknown method"})` : "not logged in";
|
|
219
|
+
}
|
|
220
|
+
catch {
|
|
221
|
+
logged = false;
|
|
222
|
+
}
|
|
223
|
+
return { version: v.stdout.trim(), logged_in: logged, login: login.slice(0, 200) };
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Whether Claude Code's sandbox can run here. On macOS it uses the system's sandbox-exec; on Linux
|
|
227
|
+
* bubblewrap and socat, and bubblewrap needs unprivileged user namespaces (Ubuntu 24.04 restricts
|
|
228
|
+
* them with AppArmor), so this runs bubblewrap the way a sandboxed command would.
|
|
229
|
+
*/
|
|
230
|
+
export function claudeSandbox() {
|
|
231
|
+
if (process.platform === "darwin")
|
|
232
|
+
return existsSync("/usr/bin/sandbox-exec") ? { ok: true, error: null } : { ok: false, error: "sandbox-exec is missing" };
|
|
233
|
+
if (process.platform !== "linux")
|
|
234
|
+
return { ok: false, error: `no Claude Code sandbox on ${process.platform}` };
|
|
235
|
+
const missing = ["bwrap", "socat"].filter((b) => spawnSync("/bin/sh", ["-c", `command -v ${b}`]).status !== 0);
|
|
236
|
+
if (missing.length)
|
|
237
|
+
return { ok: false, error: `${missing.join(" and ")} not installed (sudo apt-get install bubblewrap socat)` };
|
|
238
|
+
const r = spawnSync("bwrap", ["--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--unshare-all", "--die-with-parent", "true"], { encoding: "utf8", timeout: 30_000 });
|
|
239
|
+
return r.status === 0 ? { ok: true, error: null } : { ok: false, error: `bubblewrap cannot start: ${`${r.stderr ?? ""}`.trim().split("\n")[0].slice(0, 250) || `exit ${r.status}`}` };
|
|
240
|
+
}
|
package/dist/help.js
CHANGED
|
@@ -99,8 +99,8 @@ Agent commands
|
|
|
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
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
|
|
103
|
-
|
|
102
|
+
--service (launchd on macOS, systemd on Linux; --launchd is the same). --turn runs each turn
|
|
103
|
+
itself (--harness codex|claude-code --session <id>); set up by bschat start.
|
|
104
104
|
Codex: bschat watch --exec "codex queue --thread <id> --message {summary}" --service
|
|
105
105
|
bschat update the same as install --latest: upgrade this machine's bschat and restart its watchers
|
|
106
106
|
bschat install [<version> | --latest] make or upgrade this machine's one bschat (join does it once) and restart
|
|
@@ -108,9 +108,10 @@ Agent commands
|
|
|
108
108
|
bschat doctor every bschat on this machine and who runs which (PATH, npx caches, this repo's
|
|
109
109
|
hook and instructions, each watcher's plist versus what launchd runs), with fixes
|
|
110
110
|
bschat codex hooks | bind <thread-id> | sync install bschat's Codex hooks (~/.codex/hooks.json) and say which thread is you
|
|
111
|
-
bschat
|
|
112
|
-
run
|
|
113
|
-
|
|
111
|
+
bschat start --harness codex|claude-code --as <a> --sandbox <mode> [--token t] [--thread id] [--model m] [--effort e]
|
|
112
|
+
run an agent headless: enroll, start or adopt its session, turn-mode watcher
|
|
113
|
+
(bschat codex start is the same with --harness codex)
|
|
114
|
+
bschat unpause [--as <a>] lift a usage-limit pause now (the harness was switched to an account with quota)
|
|
114
115
|
bschat machine run | once | status | prepare | service the machine daemon (set up by bschat-admin machine add)
|
|
115
116
|
bschat checkpoint "<title>" --body "..." a resume note without retiring: what you are doing, open threads, next steps;
|
|
116
117
|
your next session (after a move to another machine) reads it first
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { bool, parse } from "./args.js";
|
|
2
|
+
import { bool, parse, str } from "./args.js";
|
|
3
3
|
import * as a from "./commands/agent.js";
|
|
4
4
|
import { evidence } from "./commands/evidence.js";
|
|
5
5
|
import { join, setup } from "./commands/join.js";
|
|
@@ -11,7 +11,9 @@ import { feedback } from "./commands/feedback.js";
|
|
|
11
11
|
import { goal } from "./commands/goal.js";
|
|
12
12
|
import { wake } from "./commands/wake.js";
|
|
13
13
|
import { antigravity } from "./commands/antigravity.js";
|
|
14
|
-
import { codex } from "./commands/codex.js";
|
|
14
|
+
import { codex, unpause } from "./commands/codex.js";
|
|
15
|
+
import { harnessStart } from "./commands/codex-start.js";
|
|
16
|
+
import { turnHarness } from "./harnesses.js";
|
|
15
17
|
import { machine } from "./commands/machine.js";
|
|
16
18
|
import { doctor, install } from "./commands/install.js";
|
|
17
19
|
import { warnIfForeignCopy } from "./install.js";
|
|
@@ -54,6 +56,13 @@ const COMMANDS = {
|
|
|
54
56
|
wake,
|
|
55
57
|
antigravity,
|
|
56
58
|
codex,
|
|
59
|
+
start: async (p, out) => {
|
|
60
|
+
const h = str(p.flags, "harness");
|
|
61
|
+
if (!h)
|
|
62
|
+
throw new CliError("usage", "start needs --harness <codex|claude-code>");
|
|
63
|
+
return harnessStart(p, out, turnHarness(h));
|
|
64
|
+
},
|
|
65
|
+
unpause: async (p, out) => unpause(p, out),
|
|
57
66
|
machine,
|
|
58
67
|
checkpoint,
|
|
59
68
|
install,
|
package/dist/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const CLI_VERSION = "0.12.
|
|
1
|
+
export const CLI_VERSION = "0.12.66";
|