benignswarm 0.12.53 → 0.12.55

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": {
@@ -83,7 +83,7 @@ export async function codexStart(p, out) {
83
83
  `Your watcher starts a turn for you whenever something needs you, so end your turn when nothing is left to do.`,
84
84
  `Now: run \`bschat me\`, \`bschat process\` and \`bschat inbox --unread\`, then do what your role and inbox ask.`,
85
85
  ].join("\n");
86
- thread = await startThread(codexBin, ["exec", "--json", ...settings, prompt], firstTurnLog);
86
+ thread = await startThread(codexBin, ["exec", "--json", ...settings, prompt], firstTurnLog, ref);
87
87
  lines.push(`Started Codex thread ${thread}; its first turn (reading its role and inbox) is running, log: ${firstTurnLog}`);
88
88
  }
89
89
  // 3. Bind it, so the hooks in that thread deliver to this agent and nobody else.
@@ -104,9 +104,9 @@ export async function codexStart(p, out) {
104
104
  out.print(lines.join("\n"), { agent: ref, thread, sandbox, model: model ?? null, effort: effort ?? null, exec, first_turn_log: firstTurnLog, untrusted_hooks: missing });
105
105
  }
106
106
  /** 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) {
107
+ async function startThread(codexBin, args, logPath, agent) {
108
108
  const fd = openSync(logPath, "a");
109
- const child = spawn(codexBin, args, { stdio: ["ignore", fd, fd], detached: true, cwd: process.cwd() });
109
+ const child = spawn(codexBin, args, { stdio: ["ignore", fd, fd], detached: true, cwd: process.cwd(), env: { ...process.env, BSCHAT_AGENT: agent } });
110
110
  closeSync(fd);
111
111
  let exited = null;
112
112
  child.on("exit", (code) => { exited = code ?? 1; });
@@ -43,7 +43,8 @@ else
43
43
  for b in node npm npx; do ln -sf "$HOME/.local/node/bin/$b" "$HOME/.local/bin/$b"; done
44
44
  hash -r; step node done "$(node --version) in ~/.local/node"
45
45
  fi
46
- npx -y -p benignswarm@${version} bschat install ${version} >/tmp/bschat-install.$$ 2>&1 || fail bschat "$(tail -1 /tmp/bschat-install.$$)"
46
+ # --prefer-online: a cached package listing from before the publish says the version does not exist.
47
+ npx -y --prefer-online -p benignswarm@${version} bschat install ${version} >/tmp/bschat-install.$$ 2>&1 || fail bschat "$(grep -v 'complete log' /tmp/bschat-install.$$ | grep -m1 -iE 'error|failed' || tail -1 /tmp/bschat-install.$$)"
47
48
  rm -f /tmp/bschat-install.$$
48
49
  bin=$(node -p 'require(require("os").homedir()+"/.bschat/install.json").bin')
49
50
  for b in bschat bschat-admin; do [ -e "$HOME/.local/bin/$b" ] || ln -sf "$(dirname "$bin")/$b" "$HOME/.local/bin/$b"; done
@@ -122,11 +123,29 @@ export async function machineAdmin(action, rest, p, out) {
122
123
  const m = r.machine;
123
124
  const rep = m.report ?? {};
124
125
  const head = [
125
- `${m.name}: last report ${m.last_report_at ?? "never"}`,
126
- rep.os ? ` ${rep.os}/${rep.arch} ${rep.hostname} as ${rep.user}; bschat ${rep.bschat?.version}; codex ${rep.codex ? `${rep.codex.version}, ${rep.codex.logged_in ? "logged in" : "NOT logged in"}` : "missing"}; hooks ${rep.managed_hooks ? "managed by policy" : "user-level"}; linger ${rep.linger ?? "n/a"}; disk free ${rep.disk_free_bytes ? `${Math.round(rep.disk_free_bytes / 1e9)} GB` : "?"}` : " (no report yet: is its daemon running?)",
126
+ `${m.name}: last report ${m.last_report_at ?? "never"}; labels ${(m.labels ?? []).join(", ") || "(none)"}; slots ${m.slots ?? "auto"}`,
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?)",
127
128
  ];
128
- const rows = m.sessions.map((s) => ({ agent: s.agent, desired: s.desired, state: s.reported?.state ?? "-", thread: s.thread ?? "-", sandbox: s.sandbox, model: s.model ?? "-", dir: s.dir, error: s.reported?.error ?? "", last_turn: (s.reported?.last_turn ?? "").replace(/^\S+ bschat watch\[[^\]]+\]: /, "") }));
129
- return out.print([...head, rows.length ? table(rows, ["agent", "desired", "state", "thread", "sandbox", "model", "dir", "error", "last_turn"]) : " no sessions"].join("\n"), r);
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 === "label" || action === "slots") {
133
+ const name = rest[0];
134
+ if (!name)
135
+ throw new CliError("usage", "machine label <name> <label...> [--remove a,b] | machine slots <name> <n | auto>");
136
+ const cur = (await c.call("GET", `/machines/${name}`)).machine;
137
+ let body;
138
+ if (action === "label") {
139
+ const drop = (str(p.flags, "remove") ?? "").split(",").filter(Boolean);
140
+ body = { labels: [...new Set([...cur.labels, ...rest.slice(1)])].filter((l) => !drop.includes(l)) };
141
+ }
142
+ else {
143
+ if (!rest[1])
144
+ throw new CliError("usage", "machine slots <name> <n | auto> (auto: one per 4 GB of RAM)");
145
+ body = { slots: rest[1] === "auto" ? null : Number(rest[1]) };
146
+ }
147
+ const r = await c.call("PATCH", `/machines/${name}`, body);
148
+ return out.print(`${name}: labels ${r.machine.labels.join(", ") || "(none)"}; slots ${r.machine.slots ?? "auto"}. Pools were re-placed: bschat-admin pool list`, r);
130
149
  }
131
150
  if (action === "remove") {
132
151
  if (!rest[0])
@@ -161,3 +180,72 @@ export async function machineAdmin(action, rest, p, out) {
161
180
  }
162
181
  throw new CliError("usage", "machine add <name> --ssh <host> | list | show <name> | remove <name> | session add|stop|start|remove <machine> <project>/<agent>");
163
182
  }
183
+ /** `[tag=]harness:model[:effort][*weight]`, e.g. `luna=codex:gpt-6-luna:medium*2`. */
184
+ export function parseVariant(spec) {
185
+ const m = /^(?:([a-z0-9][a-z0-9-]*)=)?([a-z0-9-]+)(?::([^:*]+))?(?::([^:*]+))?(?:\*(\d+))?$/.exec(spec.trim());
186
+ if (!m)
187
+ throw new CliError("usage", `--variant ${spec}: expected [tag=]harness:model[:effort][*weight], e.g. luna=codex:gpt-6-luna:medium*2`);
188
+ 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]) } : {}) };
189
+ }
190
+ /** Every value of a repeatable flag (the parser keeps the last; read them from argv). */
191
+ export function repeated(argv, flag) {
192
+ const out = [];
193
+ argv.forEach((a, i) => {
194
+ if (a === `--${flag}` && argv[i + 1] !== undefined)
195
+ out.push(argv[i + 1]);
196
+ else if (a.startsWith(`--${flag}=`))
197
+ out.push(a.slice(flag.length + 3));
198
+ });
199
+ return out;
200
+ }
201
+ /**
202
+ * pool set <project>/<name> --role r --variant spec [--variant ...] --count n --sandbox mode [--needs a,b] [--min-ram GB] [--turn-timeout min]
203
+ * pool list [project] | show <project>/<name> | remove <project>/<name>
204
+ */
205
+ export async function poolAdmin(action, rest, p, out, argv) {
206
+ const c = adminClient(p);
207
+ const statusLines = (pool) => [
208
+ `${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` : ""}`,
209
+ ...(pool.status?.placed ?? []).map((x) => ` ${x.agent.padEnd(32)} on ${x.machine}`),
210
+ ...(pool.status?.unplaced ?? []).map((x) => ` ${x.agent.padEnd(32)} NOT PLACED: ${x.reason}`),
211
+ ];
212
+ if (action === "set") {
213
+ const [project, name] = (rest[0] ?? "").split("/");
214
+ const variants = repeated(argv, "variant").map(parseVariant);
215
+ const count = Number(str(p.flags, "count"));
216
+ if (!project || !name || !variants.length || !Number.isInteger(count))
217
+ 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]");
218
+ 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")) } : {}) };
219
+ const tt = str(p.flags, "turn-timeout");
220
+ 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) } : {}) });
221
+ return out.print([...statusLines(r.pool), "Their machines' daemons start them within 30 s: bschat-admin machine show <machine>"].join("\n"), r);
222
+ }
223
+ if (action === "list" || action === undefined) {
224
+ const r = await c.call("GET", rest[0] ? `/projects/${rest[0]}/pools` : "/pools");
225
+ 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);
226
+ }
227
+ if (action === "show") {
228
+ const [project, name] = (rest[0] ?? "").split("/");
229
+ const r = await c.call("GET", `/projects/${project}/pools`);
230
+ const pool = r.pools.find((x) => x.name === name);
231
+ if (!pool)
232
+ throw new CliError("not_found", `no pool ${rest[0]}`);
233
+ return out.print(statusLines(pool).join("\n"), { pool });
234
+ }
235
+ if (action === "remove") {
236
+ const [project, name] = (rest[0] ?? "").split("/");
237
+ if (!project || !name)
238
+ throw new CliError("usage", "pool remove <project>/<name> (retires its agents; their units go back to the queue)");
239
+ await c.call("DELETE", `/projects/${project}/pools/${name}`);
240
+ return out.print(`Removed pool ${rest[0]}: its agents are retired and their sessions removed.`, { removed: rest[0] });
241
+ }
242
+ throw new CliError("usage", "pool set <project>/<name> ... | list [project] | show <project>/<name> | remove <project>/<name>");
243
+ }
244
+ /** project repo <project> <git url | none>: what daemons clone for the project's pool sessions. */
245
+ export async function projectRepoAdmin(rest, p, out) {
246
+ const [project, url] = rest;
247
+ if (!project || !url)
248
+ throw new CliError("usage", "project repo <project> <git url | none> (cloned by machines for pool sessions, with each machine's git credentials)");
249
+ const r = await adminClient(p).call("PUT", `/projects/${project}/repo`, { url: url === "none" ? null : url });
250
+ out.print(`${project}: repository ${r.repo_url ?? "(none)"}`, r);
251
+ }
@@ -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";
@@ -58,6 +58,15 @@ export async function reconcile(m, log) {
58
58
  }
59
59
  if (s.harness !== "codex")
60
60
  throw new Error(`harness ${s.harness} is not supported by this bschat ${CLI_VERSION}`);
61
+ if (!s.dir) {
62
+ // A pool session: the daemon makes the checkout (clone once per machine, a worktree per agent).
63
+ const c = ensureCheckout(s, log);
64
+ if ("preparing" in c) {
65
+ out.push({ id: s.id, state: "preparing", detail: c.preparing });
66
+ continue;
67
+ }
68
+ s.dir = c.dir;
69
+ }
61
70
  if (!existsSync(s.dir))
62
71
  throw new Error(`checkout ${s.dir} does not exist on this machine`);
63
72
  const local = state.sessions[s.id];
@@ -82,7 +91,7 @@ export async function reconcile(m, log) {
82
91
  }
83
92
  }
84
93
  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) });
94
+ 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
95
  }
87
96
  catch (e) {
88
97
  const error = e.message.slice(0, 1000);
@@ -106,6 +115,68 @@ export async function reconcile(m, log) {
106
115
  await client.call("POST", "/machines/me/report", { report, sessions: out });
107
116
  return { sessions: out, report };
108
117
  }
118
+ const git = (args, cwd) => spawnSync("git", args, { cwd, encoding: "utf8", timeout: 600_000 });
119
+ /**
120
+ * The checkout of a pool session: the project's repository cloned once per machine under
121
+ * ~/bschat/<project>/main (in the background, since ester's is 20 GB; "preparing" until it is done),
122
+ * then a worktree per agent beside it, detached at origin's default branch (units branch from their
123
+ * target with wu start). An identity file makes plain `bschat` there the agent; `.bschat/` is ignored
124
+ * through the clone's info/exclude, so no tracked file changes.
125
+ */
126
+ export function ensureCheckout(s, log) {
127
+ if (!s.project)
128
+ throw new Error("an automatic checkout needs a project agent");
129
+ if (!s.repo_url)
130
+ throw new Error(`project ${s.project} has no repository URL: bschat-admin project repo ${s.project} <git url>`);
131
+ const root = join(homedir(), "bschat", s.project);
132
+ const base = join(root, "main");
133
+ const marker = join(root, ".cloning");
134
+ if (!existsSync(join(base, ".git"))) {
135
+ if (existsSync(marker)) {
136
+ const pid = Number(readFileSync(marker, "utf8"));
137
+ let alive = false;
138
+ try {
139
+ process.kill(pid, 0);
140
+ alive = true;
141
+ }
142
+ catch {
143
+ alive = false;
144
+ }
145
+ if (alive)
146
+ return { preparing: `cloning ${s.repo_url} into ${base} (log: ${root}/clone.log)` };
147
+ throw new Error(`cloning ${s.repo_url} into ${base} stopped without finishing; see ${root}/clone.log, fix it (git credentials?), then remove ${marker}`);
148
+ }
149
+ mkdirSync(root, { recursive: true });
150
+ 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" });
151
+ child.unref();
152
+ writeFileSync(marker, String(child.pid));
153
+ log(`${s.agent}: cloning ${s.repo_url} into ${base}`);
154
+ return { preparing: `cloning ${s.repo_url} into ${base}` };
155
+ }
156
+ const dir = join(root, s.agent_name);
157
+ if (!existsSync(dir)) {
158
+ const f = git(["fetch", "origin"], base);
159
+ if (f.status !== 0)
160
+ throw new Error(`git fetch in ${base} failed: ${(f.stderr ?? "").trim().slice(-300)}`);
161
+ const head = (git(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], base).stdout ?? "").trim() || "origin/main";
162
+ const w = git(["worktree", "add", "--detach", dir, head], base);
163
+ if (w.status !== 0)
164
+ throw new Error(`git worktree add ${dir} failed: ${(w.stderr ?? "").trim().slice(-300)}`);
165
+ log(`${s.agent}: worktree ${dir} at ${head}`);
166
+ }
167
+ const common = (git(["rev-parse", "--path-format=absolute", "--git-common-dir"], base).stdout ?? "").trim();
168
+ const exclude = join(common, "info", "exclude");
169
+ const ex = existsSync(exclude) ? readFileSync(exclude, "utf8") : "";
170
+ if (!ex.split("\n").includes(".bschat/")) {
171
+ mkdirSync(dirname(exclude), { recursive: true });
172
+ writeFileSync(exclude, `${ex}${ex && !ex.endsWith("\n") ? "\n" : ""}.bschat/\n`);
173
+ }
174
+ const id = join(dir, ".bschat", "identity.json");
175
+ mkdirSync(dirname(id), { recursive: true });
176
+ writeFileSync(id, JSON.stringify({ agents: { [s.harness]: { name: s.agent_name, project: s.project, ...(s.model ? { model: s.model } : {}) } } }, null, 2) + "\n");
177
+ return { dir };
178
+ }
179
+ const shq = (x) => `'${x.replace(/'/g, `'\\''`)}'`;
109
180
  /** Saves the agent's key on first use, and replaces it when the server no longer accepts it. */
110
181
  async function ensureCredentials(client, m, s, local, log) {
111
182
  let saved = true;
@@ -167,7 +238,7 @@ export function machineFacts() {
167
238
  }
168
239
  const req = "/etc/codex/requirements.toml";
169
240
  return {
170
- os: platform(), arch: arch(), hostname: hostname(), user: userInfo().username,
241
+ os: platform(), arch: arch(), hostname: hostname(), user: userInfo().username, cpus: cpus().length, mem_total_bytes: totalmem(),
171
242
  bschat: { version: CLI_VERSION, bin: requireInstall().bin },
172
243
  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
244
  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,14 @@ 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
+
210
+ Pools (a role, variants and a count; the server names the agents and places them on machines)
211
+ bschat-admin project repo <project> <git url | none> what machines clone for the project's pool sessions
212
+ bschat-admin pool set <project>/<name> --role <role> --variant [tag=]harness:model[:effort][*weight] [--variant ...]
213
+ --count <n> --sandbox <mode> [--needs label,label] [--min-ram GB] [--turn-timeout min]
214
+ slots are agents named <name>-<tag>-<n>; fewer retires the extra ones
215
+ bschat-admin pool list [project] | show <project>/<name> | remove <project>/<name>
207
216
  bschat-admin delete-account --confirm "delete everything"
208
217
  `;
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.53";
1
+ export const CLI_VERSION = "0.12.55";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.53",
3
+ "version": "0.12.55",
4
4
  "description": "bschat: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {