benignswarm 0.12.54 → 0.12.56

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,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"];
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"];
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"];
5
5
  export function parse(argv) {
6
6
  const options = {};
@@ -7,7 +7,7 @@ import { spawnSync } from "node:child_process";
7
7
  import { CliError } from "../errors.js";
8
8
  import { table } from "../output.js";
9
9
  import { milestoneWith, milestonesWith } from "./wu.js";
10
- import { machineAdmin } from "./machine-admin.js";
10
+ import { machineAdmin, poolAdmin, projectRepoAdmin } from "./machine-admin.js";
11
11
  import { accountAdmin, answerAdmin, keysAdmin, needsAdmin, notifierAdmin, processAdmin, skillAdmin, tagList, worktreeAdmin } from "./operator.js";
12
12
  function adminClient(p) {
13
13
  return Client.forAdmin(loadAdmin(resolveAdminName(str(p.flags, "admin"))));
@@ -55,6 +55,8 @@ export async function admin(p, out) {
55
55
  return;
56
56
  }
57
57
  case "project":
58
+ if (action === "repo")
59
+ return projectRepoAdmin(rest, p, out);
58
60
  return project(action, rest, p, out);
59
61
  case "agent":
60
62
  return agent(action, rest, p, out);
@@ -93,6 +95,9 @@ export async function admin(p, out) {
93
95
  case "machine":
94
96
  case "machines":
95
97
  return machineAdmin(action, rest, p, out);
98
+ case "pool":
99
+ case "pools":
100
+ return poolAdmin(action, rest, p, out, process.argv.slice(2));
96
101
  case "skill":
97
102
  return skillAdmin(action, p, out);
98
103
  case "delete-account": {
@@ -1,9 +1,9 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
2
  import { closeSync, existsSync, mkdirSync, openSync, readFileSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
- import { join as joinPath } from "node:path";
4
+ import { dirname, join as joinPath } from "node:path";
5
5
  import { bool, str } from "../args.js";
6
- import { agentRef, loadAgent } from "../config.js";
6
+ import { agentRef, configRoot, loadAgent } from "../config.js";
7
7
  import { CliError } from "../errors.js";
8
8
  import { requireInstall } from "../install.js";
9
9
  import { bindSession, codexArchivedRollout, codexRollout } from "../sessions.js";
@@ -57,12 +57,7 @@ export async function codexStart(p, out) {
57
57
  const ref = agentRef(creds);
58
58
  requireInstall();
59
59
  // 2. Its thread: adopt one, or start one headless with an onboarding turn.
60
- const settings = [
61
- ...(model ? ["-m", model] : []),
62
- ...(effort ? ["-c", `model_reasoning_effort="${effort}"`] : []),
63
- "-c", `sandbox_mode="${sandbox}"`,
64
- "-c", `approval_policy="never"`,
65
- ];
60
+ const settings = codexSettings(sandbox, model, effort, process.cwd(), configRoot());
66
61
  let thread;
67
62
  let firstTurnLog = null;
68
63
  if (adopt) {
@@ -83,7 +78,7 @@ export async function codexStart(p, out) {
83
78
  `Your watcher starts a turn for you whenever something needs you, so end your turn when nothing is left to do.`,
84
79
  `Now: run \`bschat me\`, \`bschat process\` and \`bschat inbox --unread\`, then do what your role and inbox ask.`,
85
80
  ].join("\n");
86
- thread = await startThread(codexBin, ["exec", "--json", ...settings, prompt], firstTurnLog);
81
+ thread = await startThread(codexBin, ["exec", "--json", ...settings, prompt], firstTurnLog, ref);
87
82
  lines.push(`Started Codex thread ${thread}; its first turn (reading its role and inbox) is running, log: ${firstTurnLog}`);
88
83
  }
89
84
  // 3. Bind it, so the hooks in that thread deliver to this agent and nobody else.
@@ -103,10 +98,26 @@ export async function codexStart(p, out) {
103
98
  lines.push(`If the Codex account hits its usage limit, the watcher pauses turns until the time Codex gives; after switching to an account with quota, resume at once: bschat codex unpause --as ${ref}`);
104
99
  out.print(lines.join("\n"), { agent: ref, thread, sandbox, model: model ?? null, effort: effort ?? null, exec, first_turn_log: firstTurnLog, untrusted_hooks: missing });
105
100
  }
101
+ /**
102
+ * The Codex settings a headless turn runs with. Under workspace-write the agent still has to reach
103
+ * the API and write its own bschat state (~/.bschat), and `wu start` puts unit worktrees beside the
104
+ * checkout, so those two places are writable and the network is on; nothing else is.
105
+ */
106
+ export function codexSettings(sandbox, model, effort, cwd, bschatHome) {
107
+ return [
108
+ ...(model ? ["-m", model] : []),
109
+ ...(effort ? ["-c", `model_reasoning_effort="${effort}"`] : []),
110
+ "-c", `sandbox_mode="${sandbox}"`,
111
+ "-c", `approval_policy="never"`,
112
+ ...(sandbox === "workspace-write"
113
+ ? ["-c", "sandbox_workspace_write.network_access=true", "-c", `sandbox_workspace_write.writable_roots=${JSON.stringify([bschatHome, dirname(cwd)])}`]
114
+ : []),
115
+ ];
116
+ }
106
117
  /** Starts a headless Codex session in its own process group and returns its thread id from the JSON event stream. */
107
- async function startThread(codexBin, args, logPath) {
118
+ async function startThread(codexBin, args, logPath, agent) {
108
119
  const fd = openSync(logPath, "a");
109
- const child = spawn(codexBin, args, { stdio: ["ignore", fd, fd], detached: true, cwd: process.cwd() });
120
+ const child = spawn(codexBin, args, { stdio: ["ignore", fd, fd], detached: true, cwd: process.cwd(), env: { ...process.env, BSCHAT_AGENT: agent } });
110
121
  closeSync(fd);
111
122
  let exited = null;
112
123
  child.on("exit", (code) => { exited = code ?? 1; });
@@ -123,11 +123,36 @@ export async function machineAdmin(action, rest, p, out) {
123
123
  const m = r.machine;
124
124
  const rep = m.report ?? {};
125
125
  const head = [
126
- `${m.name}: last report ${m.last_report_at ?? "never"}`,
127
- rep.os ? ` ${rep.os}/${rep.arch} ${rep.hostname} as ${rep.user}; bschat ${rep.bschat?.version}; codex ${rep.codex ? `${rep.codex.version}, ${rep.codex.logged_in ? "logged in" : "NOT logged in"}` : "missing"}; hooks ${rep.managed_hooks ? "managed by policy" : "user-level"}; linger ${rep.linger ?? "n/a"}; disk free ${rep.disk_free_bytes ? `${Math.round(rep.disk_free_bytes / 1e9)} GB` : "?"}` : " (no report yet: is its daemon running?)",
126
+ `${m.name}: last report ${m.last_report_at ?? "never"}; labels ${(m.labels ?? []).join(", ") || "(none)"}; slots ${m.slots ?? "auto"}; workdir ${rep.workdir ?? m.workdir ?? "~/bschat"}${rep.workdir_free_bytes ? ` (${Math.round(rep.workdir_free_bytes / 1e9)} GB free)` : ""}`,
127
+ rep.os ? ` ${rep.os}/${rep.arch} ${rep.hostname} as ${rep.user}; ${rep.cpus ?? "?"} CPUs, ${rep.mem_total_bytes ? `${Math.round(rep.mem_total_bytes / 1024 ** 3)} GB RAM` : "? RAM"}; bschat ${rep.bschat?.version}; codex ${rep.codex ? `${rep.codex.version}, ${rep.codex.logged_in ? "logged in" : "NOT logged in"}` : "missing"}; hooks ${rep.managed_hooks ? "managed by policy" : "user-level"}; linger ${rep.linger ?? "n/a"}; disk free ${rep.disk_free_bytes ? `${Math.round(rep.disk_free_bytes / 1e9)} GB` : "?"}` : " (no report yet: is its daemon running?)",
128
128
  ];
129
- const rows = m.sessions.map((s) => ({ agent: s.agent, desired: s.desired, state: s.reported?.state ?? "-", thread: s.thread ?? "-", sandbox: s.sandbox, model: s.model ?? "-", dir: s.dir, error: s.reported?.error ?? "", last_turn: (s.reported?.last_turn ?? "").replace(/^\S+ bschat watch\[[^\]]+\]: /, "") }));
130
- return out.print([...head, rows.length ? table(rows, ["agent", "desired", "state", "thread", "sandbox", "model", "dir", "error", "last_turn"]) : " no sessions"].join("\n"), r);
129
+ const rows = m.sessions.map((s) => ({ agent: s.agent, pool: s.pool ?? "-", desired: s.desired, state: s.reported?.state ?? "-", thread: s.thread ?? "-", sandbox: s.sandbox, model: s.model ?? "-", dir: s.dir || s.reported?.dir || "(auto)", error: s.reported?.error ?? s.reported?.detail ?? "", last_turn: (s.reported?.last_turn ?? "").replace(/^\S+ bschat watch\[[^\]]+\]: /, "") }));
130
+ return out.print([...head, rows.length ? table(rows, ["agent", "pool", "desired", "state", "thread", "sandbox", "model", "dir", "error", "last_turn"]) : " no sessions"].join("\n"), r);
131
+ }
132
+ if (action === "workdir") {
133
+ const [name, path] = rest;
134
+ if (!name || !path)
135
+ throw new CliError("usage", "machine workdir <name> <absolute path | default> (where its daemon clones projects and makes agent worktrees; default ~/bschat)");
136
+ const r = await c.call("PATCH", `/machines/${name}`, { workdir: path === "default" ? null : path });
137
+ return out.print(`${name}: pool checkouts go to ${r.machine.workdir ?? "~/bschat"} from its next pass (existing checkouts stay where they are).`, r);
138
+ }
139
+ if (action === "label" || action === "slots") {
140
+ const name = rest[0];
141
+ if (!name)
142
+ throw new CliError("usage", "machine label <name> <label...> [--remove a,b] | machine slots <name> <n | auto>");
143
+ const cur = (await c.call("GET", `/machines/${name}`)).machine;
144
+ let body;
145
+ if (action === "label") {
146
+ const drop = (str(p.flags, "remove") ?? "").split(",").filter(Boolean);
147
+ body = { labels: [...new Set([...cur.labels, ...rest.slice(1)])].filter((l) => !drop.includes(l)) };
148
+ }
149
+ else {
150
+ if (!rest[1])
151
+ throw new CliError("usage", "machine slots <name> <n | auto> (auto: one per 4 GB of RAM)");
152
+ body = { slots: rest[1] === "auto" ? null : Number(rest[1]) };
153
+ }
154
+ const r = await c.call("PATCH", `/machines/${name}`, body);
155
+ return out.print(`${name}: labels ${r.machine.labels.join(", ") || "(none)"}; slots ${r.machine.slots ?? "auto"}. Pools were re-placed: bschat-admin pool list`, r);
131
156
  }
132
157
  if (action === "remove") {
133
158
  if (!rest[0])
@@ -162,3 +187,72 @@ export async function machineAdmin(action, rest, p, out) {
162
187
  }
163
188
  throw new CliError("usage", "machine add <name> --ssh <host> | list | show <name> | remove <name> | session add|stop|start|remove <machine> <project>/<agent>");
164
189
  }
190
+ /** `[tag=]harness:model[:effort][*weight]`, e.g. `luna=codex:gpt-6-luna:medium*2`. */
191
+ export function parseVariant(spec) {
192
+ const m = /^(?:([a-z0-9][a-z0-9-]*)=)?([a-z0-9-]+)(?::([^:*]+))?(?::([^:*]+))?(?:\*(\d+))?$/.exec(spec.trim());
193
+ if (!m)
194
+ throw new CliError("usage", `--variant ${spec}: expected [tag=]harness:model[:effort][*weight], e.g. luna=codex:gpt-6-luna:medium*2`);
195
+ return { ...(m[1] ? { tag: m[1] } : {}), harness: m[2], ...(m[3] ? { model: m[3] } : {}), ...(m[4] ? { effort: m[4] } : {}), ...(m[5] ? { weight: Number(m[5]) } : {}) };
196
+ }
197
+ /** Every value of a repeatable flag (the parser keeps the last; read them from argv). */
198
+ export function repeated(argv, flag) {
199
+ const out = [];
200
+ argv.forEach((a, i) => {
201
+ if (a === `--${flag}` && argv[i + 1] !== undefined)
202
+ out.push(argv[i + 1]);
203
+ else if (a.startsWith(`--${flag}=`))
204
+ out.push(a.slice(flag.length + 3));
205
+ });
206
+ return out;
207
+ }
208
+ /**
209
+ * pool set <project>/<name> --role r --variant spec [--variant ...] --count n --sandbox mode [--needs a,b] [--min-ram GB] [--turn-timeout min]
210
+ * pool list [project] | show <project>/<name> | remove <project>/<name>
211
+ */
212
+ export async function poolAdmin(action, rest, p, out, argv) {
213
+ const c = adminClient(p);
214
+ const statusLines = (pool) => [
215
+ `${pool.project}/${pool.name}: ${pool.count} × role ${pool.role ?? "(none)"}, ${pool.sandbox}; variants ${pool.variants.map((v) => `${v.tag}=${v.harness}:${v.model ?? "default"}${v.effort ? `:${v.effort}` : ""}${v.weight > 1 ? `*${v.weight}` : ""}`).join(", ")}${pool.needs?.labels?.length ? `; needs ${pool.needs.labels.join(", ")}` : ""}${pool.needs?.min_ram_gb ? `; min ${pool.needs.min_ram_gb} GB` : ""}`,
216
+ ...(pool.status?.placed ?? []).map((x) => ` ${x.agent.padEnd(32)} on ${x.machine}`),
217
+ ...(pool.status?.unplaced ?? []).map((x) => ` ${x.agent.padEnd(32)} NOT PLACED: ${x.reason}`),
218
+ ];
219
+ if (action === "set") {
220
+ const [project, name] = (rest[0] ?? "").split("/");
221
+ const variants = repeated(argv, "variant").map(parseVariant);
222
+ const count = Number(str(p.flags, "count"));
223
+ if (!project || !name || !variants.length || !Number.isInteger(count))
224
+ throw new CliError("usage", "pool set <project>/<name> --role <role> --variant [tag=]harness:model[:effort][*weight] [--variant ...] --count <n> --sandbox <read-only|workspace-write|danger-full-access> [--needs label,label] [--min-ram GB] [--turn-timeout min]");
225
+ const needs = { ...(str(p.flags, "needs") ? { labels: str(p.flags, "needs").split(",").map((x) => x.trim()).filter(Boolean) } : {}), ...(str(p.flags, "min-ram") ? { min_ram_gb: Number(str(p.flags, "min-ram")) } : {}) };
226
+ const tt = str(p.flags, "turn-timeout");
227
+ const r = await c.call("PUT", `/projects/${project}/pools/${name}`, { role: str(p.flags, "role") ?? null, variants, count, sandbox: str(p.flags, "sandbox"), needs, ...(tt ? { turn_timeout: Number(tt) } : {}) });
228
+ return out.print([...statusLines(r.pool), "Their machines' daemons start them within 30 s: bschat-admin machine show <machine>"].join("\n"), r);
229
+ }
230
+ if (action === "list" || action === undefined) {
231
+ const r = await c.call("GET", rest[0] ? `/projects/${rest[0]}/pools` : "/pools");
232
+ return out.print(r.pools.flatMap(statusLines).join("\n") || "No pools. Make one: bschat-admin pool set <project>/<name> --role ... --variant ... --count n --sandbox ...", r);
233
+ }
234
+ if (action === "show") {
235
+ const [project, name] = (rest[0] ?? "").split("/");
236
+ const r = await c.call("GET", `/projects/${project}/pools`);
237
+ const pool = r.pools.find((x) => x.name === name);
238
+ if (!pool)
239
+ throw new CliError("not_found", `no pool ${rest[0]}`);
240
+ return out.print(statusLines(pool).join("\n"), { pool });
241
+ }
242
+ if (action === "remove") {
243
+ const [project, name] = (rest[0] ?? "").split("/");
244
+ if (!project || !name)
245
+ throw new CliError("usage", "pool remove <project>/<name> (retires its agents; their units go back to the queue)");
246
+ await c.call("DELETE", `/projects/${project}/pools/${name}`);
247
+ return out.print(`Removed pool ${rest[0]}: its agents are retired and their sessions removed.`, { removed: rest[0] });
248
+ }
249
+ throw new CliError("usage", "pool set <project>/<name> ... | list [project] | show <project>/<name> | remove <project>/<name>");
250
+ }
251
+ /** project repo <project> <git url | none>: what daemons clone for the project's pool sessions. */
252
+ export async function projectRepoAdmin(rest, p, out) {
253
+ const [project, url] = rest;
254
+ if (!project || !url)
255
+ throw new CliError("usage", "project repo <project> <git url | none> (cloned by machines for pool sessions, with each machine's git credentials)");
256
+ const r = await adminClient(p).call("PUT", `/projects/${project}/repo`, { url: url === "none" ? null : url });
257
+ out.print(`${project}: repository ${r.repo_url ?? "(none)"}`, r);
258
+ }
@@ -1,6 +1,6 @@
1
- import { spawnSync } from "node:child_process";
1
+ import { spawn, spawnSync } from "node:child_process";
2
2
  import { existsSync, mkdirSync, readFileSync, statfsSync, writeFileSync } from "node:fs";
3
- import { arch, homedir, hostname, platform, userInfo } from "node:os";
3
+ import { arch, cpus, homedir, hostname, platform, totalmem, userInfo } from "node:os";
4
4
  import { dirname, join } from "node:path";
5
5
  import { str } from "../args.js";
6
6
  import { Client } from "../client.js";
@@ -38,7 +38,9 @@ const KEY_CHECK_MS = 10 * 60_000;
38
38
  /** One pass: make what runs here match what the operator declared, then report. */
39
39
  export async function reconcile(m, log) {
40
40
  const client = Client.raw(m.url, m.key);
41
- const desired = (await client.call("GET", "/machines/me")).sessions;
41
+ const me = await client.call("GET", "/machines/me");
42
+ const desired = me.sessions;
43
+ const workdir = me.machine?.workdir ?? null;
42
44
  const state = readMachineState();
43
45
  const bin = requireInstall().bin;
44
46
  const out = [];
@@ -58,6 +60,15 @@ export async function reconcile(m, log) {
58
60
  }
59
61
  if (s.harness !== "codex")
60
62
  throw new Error(`harness ${s.harness} is not supported by this bschat ${CLI_VERSION}`);
63
+ if (!s.dir) {
64
+ // A pool session: the daemon makes the checkout (clone once per machine, a worktree per agent).
65
+ const c = ensureCheckout(s, log, workdir);
66
+ if ("preparing" in c) {
67
+ out.push({ id: s.id, state: "preparing", detail: c.preparing });
68
+ continue;
69
+ }
70
+ s.dir = c.dir;
71
+ }
61
72
  if (!existsSync(s.dir))
62
73
  throw new Error(`checkout ${s.dir} does not exist on this machine`);
63
74
  const local = state.sessions[s.id];
@@ -82,7 +93,7 @@ export async function reconcile(m, log) {
82
93
  }
83
94
  }
84
95
  const w = svc();
85
- out.push({ id: s.id, state: "running", thread: state.sessions[s.id].thread, watcher: w && serviceActive(w) ? "active" : "inactive", last_turn: lastTurnLine(s.agent) });
96
+ out.push({ id: s.id, state: "running", dir: s.dir, thread: state.sessions[s.id].thread, watcher: w && serviceActive(w) ? "active" : "inactive", last_turn: lastTurnLine(s.agent) });
86
97
  }
87
98
  catch (e) {
88
99
  const error = e.message.slice(0, 1000);
@@ -102,10 +113,74 @@ export async function reconcile(m, log) {
102
113
  delete state.sessions[id];
103
114
  }
104
115
  writeMachineState(state);
105
- const report = machineFacts();
116
+ const report = { ...machineFacts(), workdir: workdir ?? join(homedir(), "bschat"), workdir_free_bytes: freeBytes(workdir ?? homedir()) };
106
117
  await client.call("POST", "/machines/me/report", { report, sessions: out });
107
118
  return { sessions: out, report };
108
119
  }
120
+ const git = (args, cwd) => spawnSync("git", args, { cwd, encoding: "utf8", timeout: 600_000 });
121
+ /**
122
+ * The checkout of a pool session: the project's repository cloned once per machine under
123
+ * ~/bschat/<project>/main (in the background, since ester's is 20 GB; "preparing" until it is done),
124
+ * then a worktree per agent beside it, detached at origin's default branch (units branch from their
125
+ * target with wu start). An identity file makes plain `bschat` there the agent; `.bschat/` is ignored
126
+ * through the clone's info/exclude, so no tracked file changes.
127
+ */
128
+ export function ensureCheckout(s, log, workdir = null) {
129
+ if (!s.project)
130
+ throw new Error("an automatic checkout needs a project agent");
131
+ if (!s.repo_url)
132
+ throw new Error(`project ${s.project} has no repository URL: bschat-admin project repo ${s.project} <git url>`);
133
+ if (workdir && !existsSync(workdir))
134
+ mkdirSync(workdir, { recursive: true });
135
+ const root = join(workdir ?? join(homedir(), "bschat"), s.project);
136
+ const base = join(root, "main");
137
+ const marker = join(root, ".cloning");
138
+ if (!existsSync(join(base, ".git"))) {
139
+ if (existsSync(marker)) {
140
+ const pid = Number(readFileSync(marker, "utf8"));
141
+ let alive = false;
142
+ try {
143
+ process.kill(pid, 0);
144
+ alive = true;
145
+ }
146
+ catch {
147
+ alive = false;
148
+ }
149
+ if (alive)
150
+ return { preparing: `cloning ${s.repo_url} into ${base} (log: ${root}/clone.log)` };
151
+ throw new Error(`cloning ${s.repo_url} into ${base} stopped without finishing; see ${root}/clone.log, fix it (git credentials?), then remove ${marker}`);
152
+ }
153
+ mkdirSync(root, { recursive: true });
154
+ const child = spawn("/bin/sh", ["-c", `git clone ${shq(s.repo_url)} ${shq(base + ".partial")} >> ${shq(join(root, "clone.log"))} 2>&1 && mv ${shq(base + ".partial")} ${shq(base)} && rm -f ${shq(marker)}`], { detached: true, stdio: "ignore" });
155
+ child.unref();
156
+ writeFileSync(marker, String(child.pid));
157
+ log(`${s.agent}: cloning ${s.repo_url} into ${base}`);
158
+ return { preparing: `cloning ${s.repo_url} into ${base}` };
159
+ }
160
+ const dir = join(root, s.agent_name);
161
+ if (!existsSync(dir)) {
162
+ const f = git(["fetch", "origin"], base);
163
+ if (f.status !== 0)
164
+ throw new Error(`git fetch in ${base} failed: ${(f.stderr ?? "").trim().slice(-300)}`);
165
+ const head = (git(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], base).stdout ?? "").trim() || "origin/main";
166
+ const w = git(["worktree", "add", "--detach", dir, head], base);
167
+ if (w.status !== 0)
168
+ throw new Error(`git worktree add ${dir} failed: ${(w.stderr ?? "").trim().slice(-300)}`);
169
+ log(`${s.agent}: worktree ${dir} at ${head}`);
170
+ }
171
+ const common = (git(["rev-parse", "--path-format=absolute", "--git-common-dir"], base).stdout ?? "").trim();
172
+ const exclude = join(common, "info", "exclude");
173
+ const ex = existsSync(exclude) ? readFileSync(exclude, "utf8") : "";
174
+ if (!ex.split("\n").includes(".bschat/")) {
175
+ mkdirSync(dirname(exclude), { recursive: true });
176
+ writeFileSync(exclude, `${ex}${ex && !ex.endsWith("\n") ? "\n" : ""}.bschat/\n`);
177
+ }
178
+ const id = join(dir, ".bschat", "identity.json");
179
+ mkdirSync(dirname(id), { recursive: true });
180
+ writeFileSync(id, JSON.stringify({ agents: { [s.harness]: { name: s.agent_name, project: s.project, ...(s.model ? { model: s.model } : {}) } } }, null, 2) + "\n");
181
+ return { dir };
182
+ }
183
+ const shq = (x) => `'${x.replace(/'/g, `'\\''`)}'`;
109
184
  /** Saves the agent's key on first use, and replaces it when the server no longer accepts it. */
110
185
  async function ensureCredentials(client, m, s, local, log) {
111
186
  let saved = true;
@@ -153,6 +228,15 @@ function lastTurnLine(ref) {
153
228
  const lines = readFileSync(f, "utf8").split("\n").filter((l) => /bschat watch\[/.test(l) && /turn #|TURN #|usage limit|pause lifted/.test(l));
154
229
  return lines.length ? lines[lines.length - 1].slice(0, 300) : null;
155
230
  }
231
+ function freeBytes(path) {
232
+ try {
233
+ const st = statfsSync(existsSync(path) ? path : dirname(path));
234
+ return st.bavail * st.bsize;
235
+ }
236
+ catch {
237
+ return null;
238
+ }
239
+ }
156
240
  /** What the operator needs to know about this machine, reported with every pass. */
157
241
  export function machineFacts() {
158
242
  const codex = spawnSync("codex", ["--version"], { encoding: "utf8" });
@@ -167,7 +251,7 @@ export function machineFacts() {
167
251
  }
168
252
  const req = "/etc/codex/requirements.toml";
169
253
  return {
170
- os: platform(), arch: arch(), hostname: hostname(), user: userInfo().username,
254
+ os: platform(), arch: arch(), hostname: hostname(), user: userInfo().username, cpus: cpus().length, mem_total_bytes: totalmem(),
171
255
  bschat: { version: CLI_VERSION, bin: requireInstall().bin },
172
256
  codex: codex.status === 0 ? { version: codex.stdout.trim(), logged_in: login?.status === 0 && /logged in/i.test(`${login.stdout}${login.stderr}`), login: `${login?.stdout ?? ""}${login?.stderr ?? ""}`.trim().slice(0, 200) } : null,
173
257
  managed_hooks: existsSync(req) && readFileSync(req, "utf8").includes(CODEX_MANAGED_MARK),
@@ -285,7 +285,8 @@ async function deliver(name, exec, wake, summary, tier, total, log, prefix, seq,
285
285
  // The turn runs in the background; turnStep follows it, acknowledges it once the session shows
286
286
  // it started, and reports how it ended.
287
287
  log(`${prefix}[${tier}] starting turn #${seq}: ${summary}`);
288
- turnSink(startTurn(cmd, env, seq));
288
+ // The agent's own bschat calls in the turn know who they are without any repo file.
289
+ turnSink(startTurn(cmd, { ...env, BSCHAT_AGENT: name }, seq));
289
290
  }
290
291
  else {
291
292
  log(`${prefix}[${tier}] queueing wake-up: ${summary}`);
package/dist/help.js CHANGED
@@ -204,5 +204,15 @@ Machines (provisioned over your own ssh; a daemon on each runs the agent session
204
204
  bschat-admin machine session add <machine> <project>/<agent> --dir <checkout> --sandbox <read-only|workspace-write|danger-full-access>
205
205
  [--create --role <role>] [--model m] [--effort e] [--thread <id>] [--turn-timeout min]
206
206
  bschat-admin machine session stop|start|remove <machine> <project>/<agent>
207
+ bschat-admin machine label <name> <label...> [--remove a,b] what cannot be measured (lab-lan, builds); pools' --needs match it
208
+ bschat-admin machine slots <name> <n | auto> how many sessions it takes (auto: one per 4 GB of RAM)
209
+ bschat-admin machine workdir <name> <path | default> where its daemon clones projects for pool sessions (default ~/bschat)
210
+
211
+ Pools (a role, variants and a count; the server names the agents and places them on machines)
212
+ bschat-admin project repo <project> <git url | none> what machines clone for the project's pool sessions
213
+ bschat-admin pool set <project>/<name> --role <role> --variant [tag=]harness:model[:effort][*weight] [--variant ...]
214
+ --count <n> --sandbox <mode> [--needs label,label] [--min-ram GB] [--turn-timeout min]
215
+ slots are agents named <name>-<tag>-<n>; fewer retires the extra ones
216
+ bschat-admin pool list [project] | show <project>/<name> | remove <project>/<name>
207
217
  bschat-admin delete-account --confirm "delete everything"
208
218
  `;
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.54";
1
+ export const CLI_VERSION = "0.12.56";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.54",
3
+ "version": "0.12.56",
4
4
  "description": "bschat: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {