benignswarm 0.12.47 → 0.12.49
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/codex-start.js +152 -0
- package/dist/commands/codex.js +5 -1
- package/dist/commands/watch.js +143 -18
- package/dist/sessions.js +15 -2
- package/dist/turn.js +59 -0
- 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"];
|
|
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"];
|
|
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"];
|
|
5
5
|
export function parse(argv) {
|
|
6
6
|
const options = {};
|
|
7
7
|
for (const f of STRING_FLAGS)
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
2
|
+
import { closeSync, existsSync, mkdirSync, openSync, readFileSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { join as joinPath } from "node:path";
|
|
5
|
+
import { bool, str } from "../args.js";
|
|
6
|
+
import { agentRef, loadAgent } from "../config.js";
|
|
7
|
+
import { CliError } from "../errors.js";
|
|
8
|
+
import { requireInstall } from "../install.js";
|
|
9
|
+
import { bindSession, codexArchivedRollout, codexRollout } from "../sessions.js";
|
|
10
|
+
import { codexHooksPath } from "./codex.js";
|
|
11
|
+
import { join } from "./join.js";
|
|
12
|
+
import { installLaunchd } from "./watch.js";
|
|
13
|
+
const SANDBOXES = ["read-only", "workspace-write", "danger-full-access"];
|
|
14
|
+
/**
|
|
15
|
+
* `bschat codex start`: one command that brings a Codex agent up on this machine with no Codex
|
|
16
|
+
* app involved, so it works the same over ssh on a remote machine. It enrolls the agent (with an
|
|
17
|
+
* invite token), starts its Codex thread headless (`codex exec`), binds the thread to the agent so
|
|
18
|
+
* the hooks deliver to it, and installs a turn-mode watcher that runs each later turn itself
|
|
19
|
+
* (`codex exec resume`). `--thread` adopts an existing thread instead of starting one. Learned from
|
|
20
|
+
* the Codex app's queue silently not delivering wake-ups (fabricbios luna-worker, ten hours).
|
|
21
|
+
*
|
|
22
|
+
* bschat codex start --as <name> --sandbox <mode> [--token bs_enroll_...] [--thread <id>]
|
|
23
|
+
* [--model m] [--effort e] [--turn-timeout 180] [--interval 30] [--prune]
|
|
24
|
+
*/
|
|
25
|
+
export async function codexStart(p, out) {
|
|
26
|
+
const name = str(p.flags, "as");
|
|
27
|
+
if (!name)
|
|
28
|
+
throw new CliError("usage", "codex start needs --as <agent-name>");
|
|
29
|
+
const sandbox = str(p.flags, "sandbox");
|
|
30
|
+
// No default: what a headless agent may touch on this machine is the operator's call, every time.
|
|
31
|
+
if (!sandbox || !SANDBOXES.includes(sandbox))
|
|
32
|
+
throw new CliError("usage", `codex start needs --sandbox <${SANDBOXES.join("|")}>: what the agent may do on this machine, since a headless turn cannot ask for approval`);
|
|
33
|
+
const turnTimeout = Number(str(p.flags, "turn-timeout") ?? "180");
|
|
34
|
+
if (!Number.isInteger(turnTimeout) || turnTimeout < 5)
|
|
35
|
+
throw new CliError("usage", "--turn-timeout must be a whole number of minutes, at least 5");
|
|
36
|
+
const interval = Number(str(p.flags, "interval") ?? "30");
|
|
37
|
+
if (!Number.isInteger(interval) || interval < 5)
|
|
38
|
+
throw new CliError("usage", "--interval must be an integer number of seconds, at least 5");
|
|
39
|
+
if (process.platform !== "darwin")
|
|
40
|
+
throw new CliError("unsupported", "codex start installs a launchd watcher and is macOS only for now");
|
|
41
|
+
const codexBin = which("codex");
|
|
42
|
+
const model = str(p.flags, "model");
|
|
43
|
+
const effort = str(p.flags, "effort");
|
|
44
|
+
const adopt = str(p.flags, "thread");
|
|
45
|
+
// 1. Who: enroll with the invite token, or use credentials already on this machine.
|
|
46
|
+
const lines = [];
|
|
47
|
+
const token = str(p.flags, "token");
|
|
48
|
+
if (token) {
|
|
49
|
+
const joined = [];
|
|
50
|
+
await join({ ...p, flags: { ...p.flags, vendor: "codex", model } }, { json: false, print: (h) => joined.push(h) });
|
|
51
|
+
lines.push(joined.join("\n").split("\n")[0]);
|
|
52
|
+
}
|
|
53
|
+
const creds = loadAgent(name);
|
|
54
|
+
if (creds.vendor && creds.vendor !== "codex")
|
|
55
|
+
throw new CliError("vendor_mismatch", `${agentRef(creds)} is saved as ${creds.vendor}, not codex`);
|
|
56
|
+
const ref = agentRef(creds);
|
|
57
|
+
requireInstall();
|
|
58
|
+
// 2. Its thread: adopt one, or start one headless with an onboarding turn.
|
|
59
|
+
const settings = [
|
|
60
|
+
...(model ? ["-m", model] : []),
|
|
61
|
+
...(effort ? ["-c", `model_reasoning_effort="${effort}"`] : []),
|
|
62
|
+
"-c", `sandbox_mode="${sandbox}"`,
|
|
63
|
+
"-c", `approval_policy="never"`,
|
|
64
|
+
];
|
|
65
|
+
let thread;
|
|
66
|
+
let firstTurnLog = null;
|
|
67
|
+
if (adopt) {
|
|
68
|
+
thread = adopt.toLowerCase();
|
|
69
|
+
if (!codexRollout(thread)) {
|
|
70
|
+
if (codexArchivedRollout(thread))
|
|
71
|
+
throw new CliError("archived", `Codex thread ${thread} 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");
|
|
72
|
+
throw new CliError("not_found", `no Codex session file for thread ${thread} under ~/.codex/sessions on this machine`);
|
|
73
|
+
}
|
|
74
|
+
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.`);
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
const logDir = joinPath(homedir(), ".bschat", "logs");
|
|
78
|
+
mkdirSync(logDir, { recursive: true });
|
|
79
|
+
firstTurnLog = joinPath(logDir, `codex.${ref.replace("/", ".")}.first-turn.jsonl`);
|
|
80
|
+
const prompt = [
|
|
81
|
+
`[bschat] You are ${ref}, a BenignSwarm agent, started headless by \`bschat codex start\`; nobody is typing to you.`,
|
|
82
|
+
`Your watcher starts a turn for you whenever something needs you, so end your turn when nothing is left to do.`,
|
|
83
|
+
`Now: run \`bschat me\`, \`bschat process\` and \`bschat inbox --unread\`, then do what your role and inbox ask.`,
|
|
84
|
+
].join("\n");
|
|
85
|
+
thread = await startThread(codexBin, ["exec", "--json", ...settings, prompt], firstTurnLog);
|
|
86
|
+
lines.push(`Started Codex thread ${thread}; its first turn (reading its role and inbox) is running, log: ${firstTurnLog}`);
|
|
87
|
+
}
|
|
88
|
+
// 3. Bind it, so the hooks in that thread deliver to this agent and nobody else.
|
|
89
|
+
bindSession("codex", thread, ref);
|
|
90
|
+
// 4. The watcher, in turn mode: it runs each later turn itself.
|
|
91
|
+
const exec = [codexBin, "exec", "resume", thread, ...settings].map(shq).join(" ") + " {text}";
|
|
92
|
+
const watcherOut = [];
|
|
93
|
+
installLaunchd(ref, exec, interval, Number(str(p.flags, "follow-delay") ?? "300"), {}, undefined, { json: false, print: (h) => watcherOut.push(h) }, bool(p.flags, "prune"), turnTimeout);
|
|
94
|
+
lines.push(watcherOut.join("\n").split("\n")[0].replace(/^Wrote /, "Watcher: wrote "));
|
|
95
|
+
// 5. Hooks: a headless turn cannot show Codex's trust prompt, and bschat never pre-approves it.
|
|
96
|
+
const missing = untrustedHooks();
|
|
97
|
+
lines.push(missing.length
|
|
98
|
+
? `Codex has not trusted bschat's hooks (${missing.join(", ")}) on this machine, so turns run without them: no standing rules at session start, no continuing when work arrives mid-turn. Wake-ups still work. To trust them, run \`codex\` once in a terminal here and approve the hooks when it asks.`
|
|
99
|
+
: `Codex has trust entries for bschat's hooks here. If they changed since they were trusted, Codex skips them until approved again in an interactive \`codex\`.`);
|
|
100
|
+
lines.push(`Follow it: tail -f ~/.bschat/logs/watch.${ref.replace("/", ".")}.err.log; read its thread with codex resume ${thread} only while no turn is running.`);
|
|
101
|
+
out.print(lines.join("\n"), { agent: ref, thread, sandbox, model: model ?? null, effort: effort ?? null, exec, first_turn_log: firstTurnLog, untrusted_hooks: missing });
|
|
102
|
+
}
|
|
103
|
+
/** Starts a headless Codex session in its own process group and returns its thread id from the JSON event stream. */
|
|
104
|
+
async function startThread(codexBin, args, logPath) {
|
|
105
|
+
const fd = openSync(logPath, "a");
|
|
106
|
+
const child = spawn(codexBin, args, { stdio: ["ignore", fd, fd], detached: true, cwd: process.cwd() });
|
|
107
|
+
closeSync(fd);
|
|
108
|
+
let exited = null;
|
|
109
|
+
child.on("exit", (code) => { exited = code ?? 1; });
|
|
110
|
+
child.unref();
|
|
111
|
+
for (let i = 0; i < 180; i++) {
|
|
112
|
+
const id = threadFromExecJson(readFileSync(logPath, "utf8"));
|
|
113
|
+
if (id)
|
|
114
|
+
return id;
|
|
115
|
+
if (exited !== null)
|
|
116
|
+
throw new CliError("codex_failed", `codex exec exited ${exited} before starting a thread; see ${logPath}`);
|
|
117
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
118
|
+
}
|
|
119
|
+
throw new CliError("codex_failed", `codex exec reported no thread within 90 s; see ${logPath}`);
|
|
120
|
+
}
|
|
121
|
+
/** The thread id from `codex exec --json` output: its `thread.started` event. */
|
|
122
|
+
export function threadFromExecJson(text) {
|
|
123
|
+
for (const line of text.split("\n")) {
|
|
124
|
+
if (!line.startsWith("{"))
|
|
125
|
+
continue;
|
|
126
|
+
try {
|
|
127
|
+
const j = JSON.parse(line);
|
|
128
|
+
if (j.type === "thread.started" && typeof j.thread_id === "string")
|
|
129
|
+
return j.thread_id.toLowerCase();
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
// not an event line (codex logs plain text to the same file)
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
/** bschat's hook events with no trust entry in Codex's config.toml (`[hooks.state."<hooks.json>:<event>:0:0"]`). */
|
|
138
|
+
export function untrustedHooks(configText = readCodexConfig(), hooksPath = codexHooksPath()) {
|
|
139
|
+
return ["session_start", "user_prompt_submit", "post_tool_use", "stop"].filter((e) => !configText.includes(`[hooks.state."${hooksPath}:${e}:0:0"]`));
|
|
140
|
+
}
|
|
141
|
+
function readCodexConfig() {
|
|
142
|
+
const f = joinPath(process.env.CODEX_HOME ?? joinPath(homedir(), ".codex"), "config.toml");
|
|
143
|
+
return existsSync(f) ? readFileSync(f, "utf8") : "";
|
|
144
|
+
}
|
|
145
|
+
function which(bin) {
|
|
146
|
+
const r = spawnSync("/bin/sh", ["-c", `command -v ${bin}`], { encoding: "utf8" });
|
|
147
|
+
const path = r.stdout.trim();
|
|
148
|
+
if (r.status !== 0 || !path)
|
|
149
|
+
throw new CliError("not_found", `${bin} is not on PATH; install the Codex CLI (npm i -g @openai/codex) first`);
|
|
150
|
+
return path;
|
|
151
|
+
}
|
|
152
|
+
const shq = (s) => (/^[\w./=:@-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
|
package/dist/commands/codex.js
CHANGED
|
@@ -7,10 +7,12 @@ import { CliError } from "../errors.js";
|
|
|
7
7
|
import { withCodexHooks } from "../harness.js";
|
|
8
8
|
import { requireInstall } from "../install.js";
|
|
9
9
|
import { bindSession, syncFromWatchers } from "../sessions.js";
|
|
10
|
+
import { codexStart } from "./codex-start.js";
|
|
10
11
|
/**
|
|
11
12
|
* bschat codex hooks install bschat's hooks in ~/.codex/hooks.json (this machine's Codex)
|
|
12
13
|
* bschat codex bind <thread-id> [--as a] this Codex thread is you: its hooks deliver to you
|
|
13
14
|
* bschat codex sync bind every thread an installed watcher wakes
|
|
15
|
+
* bschat codex start --as a --sandbox m run the agent headless: enroll, start or adopt its thread, turn-mode watcher
|
|
14
16
|
*/
|
|
15
17
|
export async function codex(p, out) {
|
|
16
18
|
const sub = p.positionals[1];
|
|
@@ -45,6 +47,8 @@ export async function codex(p, out) {
|
|
|
45
47
|
out.print(bound.length ? `Bound ${bound.length} thread(s) from watchers:\n${bound.map((b) => ` ${b.conversation} -> ${b.agent}`).join("\n")}` : "No Codex watcher found on this machine.", { bound });
|
|
46
48
|
return;
|
|
47
49
|
}
|
|
48
|
-
|
|
50
|
+
if (sub === "start")
|
|
51
|
+
return codexStart(p, out);
|
|
52
|
+
throw new CliError("usage", "codex hooks | codex bind <thread-id> [--as <agent>] | codex sync | codex start --as <name> --sandbox <mode> [--token ...] [--thread <id>]");
|
|
49
53
|
}
|
|
50
54
|
export const codexHooksPath = () => join(process.env.CODEX_HOME ?? join(homedir(), ".codex"), "hooks.json");
|
package/dist/commands/watch.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { spawn, spawnSync } from "node:child_process";
|
|
2
|
-
import { bindSession, sessionOfExec } from "../sessions.js";
|
|
2
|
+
import { bindSession, codexArchivedRollout, codexRollout, sessionOfExec, threadOfExec } from "../sessions.js";
|
|
3
|
+
import { readTurnPhase, startTurn, stopTurn } from "../turn.js";
|
|
4
|
+
import { applyAck } from "./wake.js";
|
|
3
5
|
import { reloadLaunchAgent, requireInstall } from "../install.js";
|
|
4
6
|
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
5
7
|
import { createHash } from "node:crypto";
|
|
@@ -42,6 +44,19 @@ export async function watch(p, out) {
|
|
|
42
44
|
const followDelay = Number(str(p.flags, "follow-delay") ?? "300");
|
|
43
45
|
if (!Number.isInteger(followDelay) || followDelay < 0)
|
|
44
46
|
throw new CliError("usage", "--follow-delay must be a non-negative number of seconds");
|
|
47
|
+
const turnMode = bool(p.flags, "turn");
|
|
48
|
+
const turnTimeout = Number(str(p.flags, "turn-timeout") ?? "180");
|
|
49
|
+
if (!Number.isInteger(turnTimeout) || turnTimeout < 5)
|
|
50
|
+
throw new CliError("usage", "--turn-timeout must be a whole number of minutes, at least 5");
|
|
51
|
+
const thread = exec ? threadOfExec(exec) : null;
|
|
52
|
+
if (turnMode) {
|
|
53
|
+
if (!exec)
|
|
54
|
+
throw new CliError("usage", '--turn needs --exec "codex exec resume <thread-id> ... {text}"');
|
|
55
|
+
if (full)
|
|
56
|
+
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) || !thread)
|
|
58
|
+
throw new CliError("usage", "--turn runs the turn itself: --exec must be codex exec resume <thread-id> ... {text}, not codex queue");
|
|
59
|
+
}
|
|
45
60
|
if (bool(p.flags, "launchd")) {
|
|
46
61
|
if (!exec)
|
|
47
62
|
throw new CliError("usage", "--launchd needs --exec so the agent knows what to run");
|
|
@@ -53,7 +68,7 @@ export async function watch(p, out) {
|
|
|
53
68
|
throw new CliError("usage", `--env ${n}: not set in this shell; run this from a terminal inside the harness (Antigravity's terminal has ANTIGRAVITY_LS_ADDRESS and ANTIGRAVITY_CSRF_TOKEN)`);
|
|
54
69
|
extraEnv[n] = v;
|
|
55
70
|
}
|
|
56
|
-
return installLaunchd(name, exec, interval, followDelay, extraEnv, str(p.flags, "activity"), out, bool(p.flags, "prune"));
|
|
71
|
+
return installLaunchd(name, exec, interval, followDelay, extraEnv, str(p.flags, "activity"), out, bool(p.flags, "prune"), turnMode ? turnTimeout : null);
|
|
57
72
|
}
|
|
58
73
|
if (!exec && !once)
|
|
59
74
|
throw new CliError("usage", 'watch --exec "<command>" [--interval 30] | watch --once (print and exit) | watch --exec ... --launchd');
|
|
@@ -66,7 +81,7 @@ export async function watch(p, out) {
|
|
|
66
81
|
process.on("SIGINT", () => bye(130));
|
|
67
82
|
process.on("SIGTERM", () => bye(143));
|
|
68
83
|
}
|
|
69
|
-
log(`watching${exec ? `, will run: ${exec}` : ""} every ${interval}s (${full ? "full text" : "single wake-up"} mode)`);
|
|
84
|
+
log(`watching${exec ? `, will run: ${exec}` : ""} every ${interval}s (${full ? "full text" : turnMode ? `turn mode, at most ${turnTimeout} min a turn` : "single wake-up"} mode)`);
|
|
70
85
|
// Harness liveness: the files the harness writes while it works, found from the wake command's
|
|
71
86
|
// session id or given with --activity. Without one the server shows this agent as "unknown"
|
|
72
87
|
// when it goes quiet, which is honest; say so once.
|
|
@@ -81,6 +96,7 @@ export async function watch(p, out) {
|
|
|
81
96
|
// scan on start and then hourly reports worktrees nobody is touching, which agent calls never would.
|
|
82
97
|
const scanCreds = loadAgent(name);
|
|
83
98
|
let lastScan = 0;
|
|
99
|
+
const ctl = { turn: null, failedAt: 0, loggedRunning: null };
|
|
84
100
|
for (;;) {
|
|
85
101
|
if (activity && heartbeatClient)
|
|
86
102
|
lastSample = await heartbeatIfActive(heartbeatClient, activity, lastSample, interval, log);
|
|
@@ -121,7 +137,10 @@ export async function watch(p, out) {
|
|
|
121
137
|
}
|
|
122
138
|
}
|
|
123
139
|
if (!full) {
|
|
124
|
-
|
|
140
|
+
if (turnMode)
|
|
141
|
+
await turnStep(ctl, thread, turnTimeout, log, (sink) => wakeOnce(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once, sink), name);
|
|
142
|
+
else
|
|
143
|
+
await wakeOnce(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once);
|
|
125
144
|
if (once)
|
|
126
145
|
return;
|
|
127
146
|
await new Promise((r) => setTimeout(r, interval * 1000));
|
|
@@ -159,7 +178,7 @@ export async function watch(p, out) {
|
|
|
159
178
|
* back, they pulled sol-architect off its task and it stopped with the task unfinished. The
|
|
160
179
|
* cursors moved because the agent was reading while it worked, not because it saw the wake-up.
|
|
161
180
|
*/
|
|
162
|
-
async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once) {
|
|
181
|
+
async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once, turnSink) {
|
|
163
182
|
const state = readState(name);
|
|
164
183
|
const pending = state.watch_pending;
|
|
165
184
|
if (pending) {
|
|
@@ -224,8 +243,12 @@ async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once)
|
|
|
224
243
|
const operatorNew = !!u && u.latestOperatorAt !== null && u.latestOperatorAt !== (st.watch_operator_at ?? null);
|
|
225
244
|
const summary = u ? u.text.split("\n")[0].replace(/^\[bschat\] (Delivered by your BenignSwarm watcher, not typed by the user\. )?/, "") : `process changed to v${lag.version}; read it: bschat process`;
|
|
226
245
|
const wake = [
|
|
227
|
-
|
|
228
|
-
|
|
246
|
+
...(turnSink
|
|
247
|
+
? [`[bschat] Turn #${seq}, started by your BenignSwarm watcher because you were idle; not typed by the user. It is already acknowledged.`]
|
|
248
|
+
: [
|
|
249
|
+
`[bschat] Wake-up #${seq} from your BenignSwarm watcher, not typed by the user.`,
|
|
250
|
+
`First acknowledge it: bschat wake ack ${seq} (no other wake-up comes until you do). If you are in the middle of a task, acknowledge, read, then carry on with the task.`,
|
|
251
|
+
]),
|
|
229
252
|
operatorNew ? `A human operator wrote to you directly.` : null,
|
|
230
253
|
processNews ? processLine(lag) : null,
|
|
231
254
|
u ? `New since you last looked: ${summary}` : `Nothing else is new.`,
|
|
@@ -235,8 +258,10 @@ async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once)
|
|
|
235
258
|
const total = u ? u.counts.messages + u.counts.items + u.counts.followed + u.counts.digest : 0;
|
|
236
259
|
// The one-line form ({summary}, what many Codex watchers send) must carry the number and the ack
|
|
237
260
|
// too, or an agent woken by it never acknowledges and is never woken again.
|
|
238
|
-
const line =
|
|
239
|
-
|
|
261
|
+
const line = turnSink
|
|
262
|
+
? `Turn #${seq} from your BenignSwarm watcher (already acknowledged): ${operatorNew ? "a human operator wrote to you. " : ""}${summary}`
|
|
263
|
+
: `Wake-up #${seq} from your BenignSwarm watcher: run bschat wake ack ${seq} first, then read. ${operatorNew ? "A human operator wrote to you. " : ""}${summary}`;
|
|
264
|
+
if (!(await deliver(name, exec, wake, line, u ? u.tier : "process", total, log, operatorNew ? "operator message; " : "", seq, turnSink)))
|
|
240
265
|
return;
|
|
241
266
|
writeState(name, {
|
|
242
267
|
...readState(name),
|
|
@@ -249,18 +274,27 @@ async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once)
|
|
|
249
274
|
});
|
|
250
275
|
}
|
|
251
276
|
/** Runs the wake command (or prints the wake-up without one). False when the command failed: nothing was delivered. */
|
|
252
|
-
async function deliver(name, exec, wake, summary, tier, total, log, prefix, seq) {
|
|
277
|
+
async function deliver(name, exec, wake, summary, tier, total, log, prefix, seq, turnSink) {
|
|
253
278
|
if (!exec) {
|
|
254
279
|
process.stdout.write(wake + "\n");
|
|
255
280
|
return true;
|
|
256
281
|
}
|
|
257
282
|
const cmd = exec.replaceAll("{count}", String(total)).replaceAll("{summary}", shellQuote(summary)).replaceAll("{text}", shellQuote(wake));
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
//
|
|
262
|
-
log(
|
|
263
|
-
|
|
283
|
+
const env = { BSCHAT_TEXT: wake, BSCHAT_SUMMARY: summary, BSCHAT_COUNT: String(total) };
|
|
284
|
+
if (turnSink) {
|
|
285
|
+
// The turn runs in the background; turnStep follows it, acknowledges it once the session shows
|
|
286
|
+
// it started, and reports how it ended.
|
|
287
|
+
log(`${prefix}[${tier}] starting turn #${seq}: ${summary}`);
|
|
288
|
+
turnSink(startTurn(cmd, env, seq));
|
|
289
|
+
}
|
|
290
|
+
else {
|
|
291
|
+
log(`${prefix}[${tier}] queueing wake-up: ${summary}`);
|
|
292
|
+
const code = await run(cmd, wake, env);
|
|
293
|
+
if (code !== 0) {
|
|
294
|
+
// The agent was NOT woken. Leave nothing pending so the next poll tries again.
|
|
295
|
+
log(`wake command exited ${code}; will retry next poll. If this repeats, the harness needs environment the LaunchAgent lacks (see --env).`);
|
|
296
|
+
return false;
|
|
297
|
+
}
|
|
264
298
|
}
|
|
265
299
|
// Tell the server a wake-up was queued, so it can tell a busy agent from a broken wake path
|
|
266
300
|
// (no harness activity long after). A failure here is logged; the agent was woken regardless.
|
|
@@ -272,6 +306,96 @@ async function deliver(name, exec, wake, summary, tier, total, log, prefix, seq)
|
|
|
272
306
|
}
|
|
273
307
|
return true;
|
|
274
308
|
}
|
|
309
|
+
const TURN_RETRY_MS = 5 * 60_000;
|
|
310
|
+
/**
|
|
311
|
+
* One poll in turn mode. While a turn runs nothing else starts: the turn's own hooks (Stop with new
|
|
312
|
+
* direct items) keep it going. The wake-up is acknowledged by the watcher once the session file
|
|
313
|
+
* shows the turn starting, which is proof the agent has the prompt. A turn that fails before that
|
|
314
|
+
* leaves the wake-up unacknowledged on the server, so a wake path that keeps failing shows as
|
|
315
|
+
* broken; one that runs past --turn-timeout is stopped and logged.
|
|
316
|
+
*/
|
|
317
|
+
async function turnStep(ctl, thread, timeoutMin, log, wake, name) {
|
|
318
|
+
const rollout = codexRollout(thread);
|
|
319
|
+
const turn = ctl.turn;
|
|
320
|
+
if (turn) {
|
|
321
|
+
if (!turn.confirmed && rollout) {
|
|
322
|
+
const ph = readTurnPhase(rollout);
|
|
323
|
+
if (ph.startedAt && Date.parse(ph.startedAt) >= turn.startedMs - 5_000) {
|
|
324
|
+
turn.confirmed = true;
|
|
325
|
+
await ackTurn(name, turn.seq, log);
|
|
326
|
+
log(`turn #${turn.seq} started in the session; wake-up acknowledged`);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
if (turn.exit) {
|
|
330
|
+
const mins = Math.round((Date.now() - turn.startedMs) / 60_000);
|
|
331
|
+
const how = turn.exit.code !== null ? `exit ${turn.exit.code}` : `signal ${turn.exit.signal}`;
|
|
332
|
+
if (turn.exit.code === 0) {
|
|
333
|
+
if (!turn.confirmed)
|
|
334
|
+
await ackTurn(name, turn.seq, log);
|
|
335
|
+
log(`turn #${turn.seq} finished after ${mins} min`);
|
|
336
|
+
}
|
|
337
|
+
else if (turn.killedForTimeout) {
|
|
338
|
+
log(`TURN #${turn.seq} STOPPED after the ${timeoutMin}-min limit (${how}); its work so far is in the session`);
|
|
339
|
+
}
|
|
340
|
+
else {
|
|
341
|
+
log(`TURN #${turn.seq} FAILED (${how}) after ${mins} min${turn.confirmed ? "" : "; it never started in the session, so the wake-up stays unacknowledged; retrying in 5 min"}. Its output is in this log.`);
|
|
342
|
+
if (!turn.confirmed) {
|
|
343
|
+
writeState(name, { ...readState(name), watch_pending: undefined, watch_dormant_logged_at: undefined });
|
|
344
|
+
ctl.failedAt = Date.now();
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
ctl.turn = null;
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
if (!turn.killedForTimeout && Date.now() - turn.startedMs > timeoutMin * 60_000) {
|
|
351
|
+
log(`turn #${turn.seq} has run ${timeoutMin} min; stopping it`);
|
|
352
|
+
stopTurn(turn);
|
|
353
|
+
}
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
if (Date.now() - ctl.failedAt < TURN_RETRY_MS)
|
|
357
|
+
return;
|
|
358
|
+
if (rollout) {
|
|
359
|
+
// A turn this watcher did not start: the Codex app, or a turn left running by a watcher that
|
|
360
|
+
// restarted (turns run in their own process group and outlive it). Never start a second one.
|
|
361
|
+
const ph = readTurnPhase(rollout);
|
|
362
|
+
if (ph.running) {
|
|
363
|
+
const quietMs = Date.now() - Date.parse(ph.lastEventAt ?? ph.startedAt);
|
|
364
|
+
if (quietMs < timeoutMin * 60_000) {
|
|
365
|
+
if (ctl.loggedRunning !== ph.startedAt)
|
|
366
|
+
log(`a turn started at ${ph.startedAt} is still running in thread ${thread} (the Codex app, or a turn from before a restart); waiting for it`);
|
|
367
|
+
ctl.loggedRunning = ph.startedAt;
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
if (ctl.loggedRunning !== ph.startedAt)
|
|
371
|
+
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`);
|
|
372
|
+
ctl.loggedRunning = ph.startedAt;
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
else {
|
|
376
|
+
log(codexArchivedRollout(thread)
|
|
377
|
+
? `thread ${thread} is archived in the Codex app (its session file is in ~/.codex/archived_sessions); starting no turn until it is unarchived`
|
|
378
|
+
: `no session file for thread ${thread} under ~/.codex/sessions; cannot tell whether a turn is running, so starting none`);
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
const st = readState(name);
|
|
382
|
+
if (st.watch_pending) {
|
|
383
|
+
// Queued by a queue-mode watcher and never delivered, or failed: no turn is running, so the agent is not going to answer it.
|
|
384
|
+
log(`wake-up ${st.watch_pending.seq !== undefined ? `#${st.watch_pending.seq} ` : ""}was never answered and no turn is running; a turn replaces it`);
|
|
385
|
+
writeState(name, { ...st, watch_pending: undefined, watch_dormant_logged_at: undefined });
|
|
386
|
+
}
|
|
387
|
+
await wake((t) => { ctl.turn = t; });
|
|
388
|
+
}
|
|
389
|
+
/** The watcher acknowledges a turn it started: the session shows the agent has the prompt. */
|
|
390
|
+
async function ackTurn(name, seq, log) {
|
|
391
|
+
writeState(name, applyAck(readState(name), seq).next);
|
|
392
|
+
try {
|
|
393
|
+
await Client.forAgent(loadAgent(name), undefined, { presence: false }).call("POST", "/agents/me/wake/ack", { seq });
|
|
394
|
+
}
|
|
395
|
+
catch (e) {
|
|
396
|
+
log(`could not report the acknowledgement of turn #${seq} to the server: ${e.message}`);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
275
399
|
const processLine = (lag) => `The project process changed: it is version ${lag.version} now and ${lag.seen ? `you last read version ${lag.seen}` : "you have not read it"}. Read it first: bschat process`;
|
|
276
400
|
const PROCESS_CHECK_MS = 5 * 60_000;
|
|
277
401
|
/**
|
|
@@ -307,7 +431,7 @@ function run(cmd, stdin, env) {
|
|
|
307
431
|
});
|
|
308
432
|
}
|
|
309
433
|
/** Writes a launchd agent that keeps `bschat watch` running for this identity on macOS. */
|
|
310
|
-
function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, out, prune = false) {
|
|
434
|
+
export function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, out, prune = false, turnTimeout = null) {
|
|
311
435
|
if (process.platform !== "darwin")
|
|
312
436
|
throw new CliError("unsupported", "--launchd is macOS only; on Linux run `bschat watch` under a systemd user service");
|
|
313
437
|
const slug = name.replace("/", ".");
|
|
@@ -330,7 +454,8 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
|
|
|
330
454
|
<string>--interval</string><string>${interval}</string>
|
|
331
455
|
<string>--follow-delay</string><string>${followDelay}</string>${activity ? `
|
|
332
456
|
<string>--activity</string><string>${escapeXml(activity)}</string>` : ""}${prune ? `
|
|
333
|
-
<string>--prune</string>` : ""}
|
|
457
|
+
<string>--prune</string>` : ""}${turnTimeout !== null ? `
|
|
458
|
+
<string>--turn</string><string>--turn-timeout</string><string>${turnTimeout}</string>` : ""}
|
|
334
459
|
</array>
|
|
335
460
|
<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>
|
|
336
461
|
<key>WorkingDirectory</key><string>${escapeXml(process.cwd())}</string>
|
package/dist/sessions.js
CHANGED
|
@@ -30,9 +30,14 @@ export function sessionAgent(kind, id) {
|
|
|
30
30
|
}
|
|
31
31
|
export const bindConversation = (id, ref) => bindSession("antigravity", id, ref);
|
|
32
32
|
export const conversationAgent = (id) => sessionAgent("antigravity", id);
|
|
33
|
-
/** The Codex thread a wake command addresses (`codex queue --thread <id>`), if any. */
|
|
33
|
+
/** The Codex thread a wake command addresses (`codex queue --thread <id>` or `codex exec resume <id>`), if any. */
|
|
34
34
|
export function threadOfExec(exec) {
|
|
35
|
-
|
|
35
|
+
if (!/\bcodex\b/.test(exec))
|
|
36
|
+
return null;
|
|
37
|
+
if (/--thread\b/.test(exec))
|
|
38
|
+
return UUID.exec(exec.slice(exec.indexOf("--thread")))?.[0]?.toLowerCase() ?? null;
|
|
39
|
+
const resume = /\bexec\s+resume\b/.exec(exec);
|
|
40
|
+
return resume ? UUID.exec(exec.slice(resume.index))?.[0]?.toLowerCase() ?? null : null;
|
|
36
41
|
}
|
|
37
42
|
/** The harness session a wake command addresses, if it names one. */
|
|
38
43
|
export function sessionOfExec(exec) {
|
|
@@ -69,6 +74,14 @@ export function sessionsOf(kind, ref) {
|
|
|
69
74
|
return Object.entries(read(kind).conversations).filter(([, r]) => r === ref).map(([id]) => id);
|
|
70
75
|
}
|
|
71
76
|
/** A Codex thread's rollout file (~/.codex/sessions/YYYY/MM/DD/rollout-*-<thread>.jsonl), newest first, or null. */
|
|
77
|
+
/** The thread's session file in Codex's archive (the app moves it there when a thread is archived), if it is there. */
|
|
78
|
+
export function codexArchivedRollout(thread) {
|
|
79
|
+
const dir = join(process.env.CODEX_HOME ?? join(homedir(), ".codex"), "archived_sessions");
|
|
80
|
+
if (!existsSync(dir))
|
|
81
|
+
return null;
|
|
82
|
+
const f = readdirSync(dir).find((n) => n.includes(thread) && n.endsWith(".jsonl"));
|
|
83
|
+
return f ? join(dir, f) : null;
|
|
84
|
+
}
|
|
72
85
|
export function codexRollout(thread) {
|
|
73
86
|
const root = join(process.env.CODEX_HOME ?? join(homedir(), ".codex"), "sessions");
|
|
74
87
|
if (!existsSync(root))
|
package/dist/turn.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
/** Where a Codex session stands, from its rollout: `task_started` opens a turn, `task_complete` or `turn_aborted` closes it. */
|
|
4
|
+
export function codexTurnPhase(rolloutText) {
|
|
5
|
+
let open = null;
|
|
6
|
+
let startedAt = null;
|
|
7
|
+
let lastEventAt = null;
|
|
8
|
+
for (const line of rolloutText.split("\n")) {
|
|
9
|
+
if (!line)
|
|
10
|
+
continue;
|
|
11
|
+
let j;
|
|
12
|
+
try {
|
|
13
|
+
j = JSON.parse(line);
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
continue; // a line still being written
|
|
17
|
+
}
|
|
18
|
+
if (j.timestamp)
|
|
19
|
+
lastEventAt = j.timestamp;
|
|
20
|
+
if (j.type !== "event_msg")
|
|
21
|
+
continue;
|
|
22
|
+
const t = j.payload?.type;
|
|
23
|
+
if (t === "task_started") {
|
|
24
|
+
open = j.timestamp ?? null;
|
|
25
|
+
startedAt = open;
|
|
26
|
+
}
|
|
27
|
+
else if (t === "task_complete" || t === "turn_aborted")
|
|
28
|
+
open = null;
|
|
29
|
+
}
|
|
30
|
+
return { running: open !== null, startedAt, lastEventAt };
|
|
31
|
+
}
|
|
32
|
+
export function readTurnPhase(rollout) {
|
|
33
|
+
return codexTurnPhase(readFileSync(rollout, "utf8"));
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Starts the turn command in its own process group, so a watcher restart (an upgrade reloads every
|
|
37
|
+
* LaunchAgent) does not kill a turn halfway through; the next watcher sees it running in the
|
|
38
|
+
* session file and waits. Output goes to the watcher's logs.
|
|
39
|
+
*/
|
|
40
|
+
export function startTurn(cmd, env, seq) {
|
|
41
|
+
const child = spawn("/bin/sh", ["-c", cmd], { stdio: ["ignore", "inherit", "inherit"], env: { ...process.env, ...env }, detached: true });
|
|
42
|
+
const turn = { seq, child, startedMs: Date.now(), confirmed: false };
|
|
43
|
+
child.on("close", (code, signal) => { turn.exit = { code, signal }; });
|
|
44
|
+
child.on("error", () => { turn.exit = { code: 127, signal: null }; });
|
|
45
|
+
return turn;
|
|
46
|
+
}
|
|
47
|
+
/** Ends a turn that ran past its limit: the whole process group, so codex goes too. */
|
|
48
|
+
export function stopTurn(turn) {
|
|
49
|
+
turn.killedForTimeout = true;
|
|
50
|
+
if (turn.child.pid) {
|
|
51
|
+
try {
|
|
52
|
+
process.kill(-turn.child.pid, "SIGTERM");
|
|
53
|
+
}
|
|
54
|
+
catch (e) {
|
|
55
|
+
if (e.code !== "ESRCH")
|
|
56
|
+
throw e;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
package/dist/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const CLI_VERSION = "0.12.
|
|
1
|
+
export const CLI_VERSION = "0.12.49";
|