benignswarm 0.12.47 → 0.12.48

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/args.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { parseArgs } from "node:util";
2
2
  import { CliError } from "./errors.js";
3
- 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,149 @@
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, 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
+ throw new CliError("not_found", `no Codex session file for thread ${thread} under ~/.codex/sessions on this machine`);
71
+ lines.push(`Adopted Codex thread ${thread}. Close it in the Codex app: from now on the watcher runs its turns, and two clients on one thread conflict.`);
72
+ }
73
+ else {
74
+ const logDir = joinPath(homedir(), ".bschat", "logs");
75
+ mkdirSync(logDir, { recursive: true });
76
+ firstTurnLog = joinPath(logDir, `codex.${ref.replace("/", ".")}.first-turn.jsonl`);
77
+ const prompt = [
78
+ `[bschat] You are ${ref}, a BenignSwarm agent, started headless by \`bschat codex start\`; nobody is typing to you.`,
79
+ `Your watcher starts a turn for you whenever something needs you, so end your turn when nothing is left to do.`,
80
+ `Now: run \`bschat me\`, \`bschat process\` and \`bschat inbox --unread\`, then do what your role and inbox ask.`,
81
+ ].join("\n");
82
+ thread = await startThread(codexBin, ["exec", "--json", ...settings, prompt], firstTurnLog);
83
+ lines.push(`Started Codex thread ${thread}; its first turn (reading its role and inbox) is running, log: ${firstTurnLog}`);
84
+ }
85
+ // 3. Bind it, so the hooks in that thread deliver to this agent and nobody else.
86
+ bindSession("codex", thread, ref);
87
+ // 4. The watcher, in turn mode: it runs each later turn itself.
88
+ const exec = [codexBin, "exec", "resume", thread, ...settings].map(shq).join(" ") + " {text}";
89
+ const watcherOut = [];
90
+ installLaunchd(ref, exec, interval, Number(str(p.flags, "follow-delay") ?? "300"), {}, undefined, { json: false, print: (h) => watcherOut.push(h) }, bool(p.flags, "prune"), turnTimeout);
91
+ lines.push(watcherOut.join("\n").split("\n")[0].replace(/^Wrote /, "Watcher: wrote "));
92
+ // 5. Hooks: a headless turn cannot show Codex's trust prompt, and bschat never pre-approves it.
93
+ const missing = untrustedHooks();
94
+ lines.push(missing.length
95
+ ? `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.`
96
+ : `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\`.`);
97
+ 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.`);
98
+ out.print(lines.join("\n"), { agent: ref, thread, sandbox, model: model ?? null, effort: effort ?? null, exec, first_turn_log: firstTurnLog, untrusted_hooks: missing });
99
+ }
100
+ /** Starts a headless Codex session in its own process group and returns its thread id from the JSON event stream. */
101
+ async function startThread(codexBin, args, logPath) {
102
+ const fd = openSync(logPath, "a");
103
+ const child = spawn(codexBin, args, { stdio: ["ignore", fd, fd], detached: true, cwd: process.cwd() });
104
+ closeSync(fd);
105
+ let exited = null;
106
+ child.on("exit", (code) => { exited = code ?? 1; });
107
+ child.unref();
108
+ for (let i = 0; i < 180; i++) {
109
+ const id = threadFromExecJson(readFileSync(logPath, "utf8"));
110
+ if (id)
111
+ return id;
112
+ if (exited !== null)
113
+ throw new CliError("codex_failed", `codex exec exited ${exited} before starting a thread; see ${logPath}`);
114
+ await new Promise((r) => setTimeout(r, 500));
115
+ }
116
+ throw new CliError("codex_failed", `codex exec reported no thread within 90 s; see ${logPath}`);
117
+ }
118
+ /** The thread id from `codex exec --json` output: its `thread.started` event. */
119
+ export function threadFromExecJson(text) {
120
+ for (const line of text.split("\n")) {
121
+ if (!line.startsWith("{"))
122
+ continue;
123
+ try {
124
+ const j = JSON.parse(line);
125
+ if (j.type === "thread.started" && typeof j.thread_id === "string")
126
+ return j.thread_id.toLowerCase();
127
+ }
128
+ catch {
129
+ // not an event line (codex logs plain text to the same file)
130
+ }
131
+ }
132
+ return null;
133
+ }
134
+ /** bschat's hook events with no trust entry in Codex's config.toml (`[hooks.state."<hooks.json>:<event>:0:0"]`). */
135
+ export function untrustedHooks(configText = readCodexConfig(), hooksPath = codexHooksPath()) {
136
+ return ["session_start", "user_prompt_submit", "post_tool_use", "stop"].filter((e) => !configText.includes(`[hooks.state."${hooksPath}:${e}:0:0"]`));
137
+ }
138
+ function readCodexConfig() {
139
+ const f = joinPath(process.env.CODEX_HOME ?? joinPath(homedir(), ".codex"), "config.toml");
140
+ return existsSync(f) ? readFileSync(f, "utf8") : "";
141
+ }
142
+ function which(bin) {
143
+ const r = spawnSync("/bin/sh", ["-c", `command -v ${bin}`], { encoding: "utf8" });
144
+ const path = r.stdout.trim();
145
+ if (r.status !== 0 || !path)
146
+ throw new CliError("not_found", `${bin} is not on PATH; install the Codex CLI (npm i -g @openai/codex) first`);
147
+ return path;
148
+ }
149
+ const shq = (s) => (/^[\w./=:@-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
@@ -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
- throw new CliError("usage", "codex hooks | codex bind <thread-id> [--as <agent>] | codex sync");
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");
@@ -1,5 +1,7 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
- import { bindSession, sessionOfExec } from "../sessions.js";
2
+ import { bindSession, 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
- await wakeOnce(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once);
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
- `[bschat] Wake-up #${seq} from your BenignSwarm watcher, not typed by the user.`,
228
- `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.`,
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 = `Wake-up #${seq} from your BenignSwarm watcher: run bschat wake ack ${seq} first, then read. ${operatorNew ? "A human operator wrote to you. " : ""}${summary}`;
239
- if (!(await deliver(name, exec, wake, line, u ? u.tier : "process", total, log, operatorNew ? "operator message; " : "", seq)))
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
- log(`${prefix}[${tier}] queueing wake-up: ${summary}`);
259
- const code = await run(cmd, wake, { BSCHAT_TEXT: wake, BSCHAT_SUMMARY: summary, BSCHAT_COUNT: String(total) });
260
- if (code !== 0) {
261
- // The agent was NOT woken. Leave nothing pending so the next poll tries again.
262
- log(`wake command exited ${code}; will retry next poll. If this repeats, the harness needs environment the LaunchAgent lacks (see --env).`);
263
- return false;
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,94 @@ 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(`no session file for thread ${thread} under ~/.codex/sessions; cannot tell whether a turn is running, so starting none`);
377
+ return;
378
+ }
379
+ const st = readState(name);
380
+ if (st.watch_pending) {
381
+ // Queued by a queue-mode watcher and never delivered, or failed: no turn is running, so the agent is not going to answer it.
382
+ log(`wake-up ${st.watch_pending.seq !== undefined ? `#${st.watch_pending.seq} ` : ""}was never answered and no turn is running; a turn replaces it`);
383
+ writeState(name, { ...st, watch_pending: undefined, watch_dormant_logged_at: undefined });
384
+ }
385
+ await wake((t) => { ctl.turn = t; });
386
+ }
387
+ /** The watcher acknowledges a turn it started: the session shows the agent has the prompt. */
388
+ async function ackTurn(name, seq, log) {
389
+ writeState(name, applyAck(readState(name), seq).next);
390
+ try {
391
+ await Client.forAgent(loadAgent(name), undefined, { presence: false }).call("POST", "/agents/me/wake/ack", { seq });
392
+ }
393
+ catch (e) {
394
+ log(`could not report the acknowledgement of turn #${seq} to the server: ${e.message}`);
395
+ }
396
+ }
275
397
  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
398
  const PROCESS_CHECK_MS = 5 * 60_000;
277
399
  /**
@@ -307,7 +429,7 @@ function run(cmd, stdin, env) {
307
429
  });
308
430
  }
309
431
  /** 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) {
432
+ export function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, out, prune = false, turnTimeout = null) {
311
433
  if (process.platform !== "darwin")
312
434
  throw new CliError("unsupported", "--launchd is macOS only; on Linux run `bschat watch` under a systemd user service");
313
435
  const slug = name.replace("/", ".");
@@ -330,7 +452,8 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
330
452
  <string>--interval</string><string>${interval}</string>
331
453
  <string>--follow-delay</string><string>${followDelay}</string>${activity ? `
332
454
  <string>--activity</string><string>${escapeXml(activity)}</string>` : ""}${prune ? `
333
- <string>--prune</string>` : ""}
455
+ <string>--prune</string>` : ""}${turnTimeout !== null ? `
456
+ <string>--turn</string><string>--turn-timeout</string><string>${turnTimeout}</string>` : ""}
334
457
  </array>
335
458
  <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
459
  <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
- return /\bcodex\b/.test(exec) && /--thread\b/.test(exec) ? UUID.exec(exec.slice(exec.indexOf("--thread")))?.[0]?.toLowerCase() ?? null : null;
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) {
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.47";
1
+ export const CLI_VERSION = "0.12.48";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.47",
3
+ "version": "0.12.48",
4
4
  "description": "bschat: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {