benignswarm 0.12.101 → 0.12.103

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.
@@ -1,8 +1,9 @@
1
1
  import { spawnSync } from "node:child_process";
2
- import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
2
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, realpathSync, statSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
- import { basename, dirname, join } from "node:path";
4
+ import { basename, delimiter, dirname, join } from "node:path";
5
5
  import { configRoot } from "./config.js";
6
+ import { repoDirectory } from "./directories.js";
6
7
  import { CliError } from "./errors.js";
7
8
  export function antigravityTotalTokens(usage) {
8
9
  if (!usage)
@@ -14,7 +15,41 @@ export function antigravityTotalTokens(usage) {
14
15
  export const antigravityLog = (ref) => join(configRoot(), "logs", `antigravity.${ref.replace("/", ".")}.jsonl`);
15
16
  export const antigravityConversationDb = (id, home = homedir()) => join(home, ".gemini", "antigravity-cli", "conversations", `${id}.db`);
16
17
  const shq = (s) => (/^[\w./=:@-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
17
- export function antigravitySettings(sandbox, cwd, b9sHome, apiHost, extraWritable = []) {
18
+ function b9sPackageRoot(bin) {
19
+ let dir = dirname(realpathSync(bin));
20
+ for (;;) {
21
+ const manifest = join(dir, "package.json");
22
+ if (existsSync(manifest)) {
23
+ try {
24
+ if (JSON.parse(readFileSync(manifest, "utf8")).name === "benignswarm")
25
+ return dir;
26
+ }
27
+ catch { /* continue up to the package root */ }
28
+ }
29
+ const parent = dirname(dir);
30
+ if (parent === dir)
31
+ break;
32
+ dir = parent;
33
+ }
34
+ throw new CliError("install_package_missing", `cannot find the benignswarm package containing recorded b9s install ${bin}`);
35
+ }
36
+ export function antigravitySandboxPermissions(apiHost, b9sHome, b9sBin, nodeBin = process.execPath, skillRoot) {
37
+ const packageRoot = b9sPackageRoot(b9sBin);
38
+ const allow = [
39
+ `read_url(${apiHost})`, "read_url(github.com)", "command(b9s)",
40
+ `read_file(${b9sBin})`, `read_file(${realpathSync(b9sBin)})`, `read_file(${nodeBin})`, `read_file(${packageRoot})`,
41
+ `write_file(${b9sHome})`,
42
+ ];
43
+ if (skillRoot) {
44
+ allow.push(`read_file(${join(skillRoot, "identity.json")})`);
45
+ for (const file of ["SKILL.md", "references/api.md", "references/watchers.md", "references/process.md", "references/continuity.md"]) {
46
+ allow.push(`read_file(${join(skillRoot, file)})`);
47
+ }
48
+ allow.push(`read_file(${join(dirname(skillRoot), ".agents", "rules", "bschat.md")})`);
49
+ }
50
+ return [...new Set(allow)];
51
+ }
52
+ export function antigravitySettings(sandbox, cwd, b9sHome, apiHost, extraWritable = [], b9sBin, nodeBin = process.execPath) {
18
53
  if (sandbox === "read-only")
19
54
  throw new CliError("unsupported", "Antigravity has no read-only permission mode; use workspace-write or danger-full-access");
20
55
  if (sandbox === "danger-full-access")
@@ -23,10 +58,12 @@ export function antigravitySettings(sandbox, cwd, b9sHome, apiHost, extraWritabl
23
58
  throw new CliError("usage", `unknown sandbox ${sandbox}`);
24
59
  if (!/^[a-z0-9.-]+(?::\d+)?$/i.test(apiHost))
25
60
  throw new CliError("usage", "the BenignSwarm API host is invalid for Antigravity sandbox permissions");
61
+ if (!b9sBin)
62
+ throw new CliError("not_installed", "the recorded b9s install path is required for Antigravity workspace-write");
26
63
  const dirs = [...new Set([dirname(cwd), b9sHome, ...extraWritable])];
27
64
  return [
28
65
  "--sandbox", "--settings",
29
- JSON.stringify({ enableTerminalSandbox: true, toolPermission: "proceed-in-sandbox", permissions: { allow: [`read_url(${apiHost})`, "read_url(github.com)"] } }),
66
+ JSON.stringify({ enableTerminalSandbox: true, toolPermission: "proceed-in-sandbox", permissions: { allow: antigravitySandboxPermissions(apiHost, b9sHome, b9sBin, nodeBin, repoDirectory(cwd)) } }),
30
67
  ...dirs.flatMap((dir) => ["--add-dir", dir]),
31
68
  ];
32
69
  }
@@ -66,8 +103,14 @@ export function recordAntigravityTurn(path, record) {
66
103
  appendFileSync(path, `${JSON.stringify(record)}\n`, { mode: 0o600 });
67
104
  }
68
105
  /** Explicit markers let commands launched by this turn inherit only this harness's sandbox workaround. */
69
- export function antigravityTurnEnv(sandbox) {
70
- return { BSCHAT_HARNESS: "antigravity", BSCHAT_ANTIGRAVITY_SANDBOX: sandbox };
106
+ export function antigravityPath(b9sBin, path = process.env.PATH ?? "") {
107
+ return [...new Set([dirname(b9sBin), dirname(process.execPath), ...path.split(delimiter).filter(Boolean)])].join(delimiter);
108
+ }
109
+ export function antigravityTurnEnv(sandbox, b9sBin) {
110
+ if (sandbox !== "workspace-write")
111
+ return { BSCHAT_HARNESS: "antigravity", BSCHAT_ANTIGRAVITY_SANDBOX: sandbox };
112
+ const path = b9sBin ? antigravityPath(b9sBin) : [...new Set([dirname(process.execPath), ...(process.env.PATH ?? "").split(delimiter).filter(Boolean)])].join(delimiter);
113
+ return { BSCHAT_HARNESS: "antigravity", BSCHAT_ANTIGRAVITY_SANDBOX: sandbox, PATH: path };
71
114
  }
72
115
  export function runAntigravityTurn(bin, args, logPath, cwd, agent, expectedConversation, run = spawnSync, envOverride = {}) {
73
116
  const started = new Date().toISOString();
package/dist/args.js CHANGED
@@ -22,7 +22,7 @@ export const STRING_FLAGS = [
22
22
  "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit",
23
23
  "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email",
24
24
  "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on",
25
- "sandbox", "thread", "turn-timeout", "turns-per-hour", "unproductive-per-hour", "turn-coalesce-seconds", "session",
25
+ "sandbox", "thread", "turn-timeout", "turns-per-hour", "unproductive-per-hour", "turn-coalesce-seconds", "session", "operation",
26
26
  "plain", "if-yes", "if-no", "ssh", "variant", "count", "needs", "min-ram", "exclude", "carry", "from",
27
27
  "to-ssh", "wait", "writable", "writable-root", "dsh", "agy", "for", "until", "reason", "at", "requires",
28
28
  "priority", "informs", "amend", "waive-informs", "text", "kind", "claim", "decision", "sha", "value", "expect",
@@ -41,7 +41,7 @@ export const BOOL_FLAGS = [
41
41
  "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "template", "scope-only", "unread",
42
42
  "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind",
43
43
  "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive",
44
- "approve", "turn", "service", "print-hooks", "create", "rotate", "codex-userns", "bwrap-userns", "print-apparmor",
44
+ "approve", "turn", "service", "print-hooks", "create", "rotate", "codex-userns", "bwrap-userns", "agy-userns", "print-apparmor",
45
45
  "cancel", "rerun", "confirmed", "refuted", "no-source", "confirm-bypass-signal", "in-container", "assessment-only", "retrieve-ec2", "no-wait-verify", "preview", "remove-empty", "dry-run", "stdin", "context-confirmed",
46
46
  ];
47
47
  export function parse(argv) {
@@ -171,8 +171,11 @@ export async function harnessStart(p, out, harness) {
171
171
  await configureGitCredentialForWorktree(process.cwd(), creds);
172
172
  if (creds.vendor && creds.vendor !== harness)
173
173
  throw new CliError("vendor_mismatch", `${ref} is saved as ${creds.vendor}, not ${harness}`);
174
- if (harness === "antigravity")
175
- settings = antigravitySettings(sandbox, process.cwd(), configRoot(), new URL(creds.url).host, [...writable, ...ownWorktreeGitDir(process.cwd())]);
174
+ if (harness === "antigravity") {
175
+ if (inContainer)
176
+ provisionContainerInstallRecord();
177
+ settings = antigravitySettings(sandbox, process.cwd(), configRoot(), new URL(creds.url).host, [...writable, ...ownWorktreeGitDir(process.cwd())], requireInstall().bin);
178
+ }
176
179
  const priorState = readState(ref);
177
180
  if (priorState.turn_guard?.fault) {
178
181
  const fault = priorState.turn_guard.fault;
@@ -222,7 +225,7 @@ export async function harnessStart(p, out, harness) {
222
225
  lines.push(`Adopted Antigravity conversation ${session}. Do not resume it elsewhere while the watcher runs it: two clients on one conversation conflict.`);
223
226
  }
224
227
  if (harness === "antigravity" && sandbox === "workspace-write")
225
- await runAntigravitySandboxSelfCheck(ref, bin, settings, process.cwd(), session, model, effort, turnTimeout * 60, firstTurnLog, turnsPerHour, antigravityTurnEnv(sandbox), unproductivePerHour);
228
+ await runAntigravitySandboxSelfCheck(ref, bin, settings, process.cwd(), session, model, effort, turnTimeout * 60, firstTurnLog, turnsPerHour, antigravityTurnEnv(sandbox, install.bin), unproductivePerHour);
226
229
  }
227
230
  }
228
231
  else {
@@ -257,12 +260,12 @@ export async function harnessStart(p, out, harness) {
257
260
  lines.push(`Started DeepSeek Harness session ${session}; its first turn (reading its role and inbox) is running, event log: ${firstTurnLog}`);
258
261
  }
259
262
  else if (harness === "antigravity") {
260
- const started = runAntigravityTurn(bin, antigravityTurnArgs(prompt, model, effort, turnTimeout * 60, settings), firstTurnLog, process.cwd(), ref, undefined, undefined, antigravityTurnEnv(sandbox));
263
+ const started = runAntigravityTurn(bin, antigravityTurnArgs(prompt, model, effort, turnTimeout * 60, settings), firstTurnLog, process.cwd(), ref, undefined, undefined, antigravityTurnEnv(sandbox, install.bin));
261
264
  session = started.conversation;
262
265
  await completePendingTurnGuard(ref, probeFor(harness, session, ref), (message) => diagnostic.push(message), started.output, antigravityTokenTotal(started.record.result?.usage));
263
266
  lines.push(`Started Antigravity conversation ${session}; its first turn (reading its role and inbox) completed, JSON turn log: ${firstTurnLog}`);
264
267
  if (sandbox === "workspace-write")
265
- await runAntigravitySandboxSelfCheck(ref, bin, settings, process.cwd(), session, model, effort, turnTimeout * 60, firstTurnLog, turnsPerHour, antigravityTurnEnv(sandbox), unproductivePerHour);
268
+ await runAntigravitySandboxSelfCheck(ref, bin, settings, process.cwd(), session, model, effort, turnTimeout * 60, firstTurnLog, turnsPerHour, antigravityTurnEnv(sandbox, install.bin), unproductivePerHour);
266
269
  }
267
270
  else {
268
271
  // Claude Code takes the session id from us, so nothing has to be read back from its output.
@@ -313,7 +316,7 @@ export async function harnessStart(p, out, harness) {
313
316
  mkdirSync(tmp, { recursive: true });
314
317
  const followDelay = Number(str(p.flags, "follow-delay") ?? "300");
315
318
  const prune = bool(p.flags, "prune");
316
- watcherEnv = { TMPDIR: tmp, ...(machineSessionId ? { BSCHAT_MACHINE_SESSION_ID: machineSessionId } : {}), ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}), ...(harness === "antigravity" ? { BSCHAT_HARNESS: "antigravity", BSCHAT_ANTIGRAVITY_SANDBOX: sandbox, BSCHAT_MODEL: model, ...(effort ? { BSCHAT_EFFORT: effort } : {}) } : {}) };
319
+ watcherEnv = { TMPDIR: tmp, ...(machineSessionId ? { BSCHAT_MACHINE_SESSION_ID: machineSessionId } : {}), ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}), ...(harness === "antigravity" ? { ...antigravityTurnEnv(sandbox, install.bin), BSCHAT_MODEL: model, ...(effort ? { BSCHAT_EFFORT: effort } : {}) } : {}) };
317
320
  const turnSpec = { harness, session, timeout: turnTimeout, turnsPerHour, unproductivePerHour, coalesceSeconds: turnCoalesceSeconds, provider, model, ...(machineSessionId ? { machineSessionId } : {}) };
318
321
  if (inContainer) {
319
322
  const sess = sessionOfExec(exec);
@@ -193,17 +193,19 @@ export async function gatherUpdates(name, opts) {
193
193
  ] : [];
194
194
  let measureLines = [];
195
195
  let nextMeasureState = null;
196
- try {
197
- const response = await client.call("GET", "/agents/me/brief");
198
- const brief = response.brief;
199
- if (brief && Array.isArray(brief.measures)) {
196
+ if (opts.refreshMeasures) {
197
+ try {
198
+ const response = await client.call("GET", "/agents/me/brief");
199
+ const brief = response.brief;
200
+ if (!brief || !Array.isArray(brief.measures))
201
+ throw new Error("GET /agents/me/brief returned no measures array");
200
202
  nextMeasureState = outcomeMeasureSnapshot(brief.measures, brief.measures_omitted ?? 0);
201
203
  if (nextMeasureState !== state.measure_state)
202
204
  measureLines = formatOutcomeMeasures(brief.measures, brief.measures_omitted ?? 0);
203
205
  }
204
- }
205
- catch (e) {
206
- process.stderr.write(`b9s: outcome measures: ${e.message}\n`);
206
+ catch (e) {
207
+ process.stderr.write(`b9s: outcome measures: ${e.message}\n`);
208
+ }
207
209
  }
208
210
  const next = { ...state, last_check: Date.now() };
209
211
  if (messages.length) {
@@ -450,7 +452,7 @@ export async function hook(p) {
450
452
  }
451
453
  }
452
454
  }
453
- const u = await gatherUpdates(name, { force: !!p.flags.force || (harness === "claude-code" && event === "SessionStart"), model: str(p.flags, "model") });
455
+ const u = await gatherUpdates(name, { force: !!p.flags.force || (harness === "claude-code" && event === "SessionStart"), model: str(p.flags, "model"), refreshMeasures: event === "SessionStart" && !compacted });
454
456
  const formatted = formatHookDelivery(omitMeasuresAlreadyIn(standing?.text, u), standing);
455
457
  const text = formatted.text;
456
458
  if (!text)
@@ -605,7 +607,7 @@ async function antigravityHook(p) {
605
607
  if (event !== "SessionStart" && event !== "PreInvocation")
606
608
  return out({});
607
609
  const standing = event === "SessionStart" ? await standingRules(name, input?.source === "compact") : null;
608
- const u = await gatherUpdates(name, { force: event === "SessionStart", delivery: "hook" });
610
+ const u = await gatherUpdates(name, { force: event === "SessionStart", delivery: "hook", refreshMeasures: event === "SessionStart" });
609
611
  const formatted = formatHookDelivery(omitMeasuresAlreadyIn(standing?.text, u), standing);
610
612
  if (formatted.text)
611
613
  await reportDelivery(name, formatted.text, formatted.by_kind);
@@ -680,7 +682,7 @@ async function codexHook(p) {
680
682
  if (event !== "SessionStart" && event !== "UserPromptSubmit")
681
683
  return;
682
684
  const standing = event === "SessionStart" ? await standingRules(name, input?.source === "compact") : null;
683
- const u = await gatherUpdates(name, { force: event === "SessionStart", delivery: "hook" });
685
+ const u = await gatherUpdates(name, { force: event === "SessionStart", delivery: "hook", refreshMeasures: event === "SessionStart" });
684
686
  const formatted = formatHookDelivery(omitMeasuresAlreadyIn(standing?.text, u), standing);
685
687
  if (formatted.text)
686
688
  await reportDelivery(name, formatted.text, formatted.by_kind);
@@ -16,7 +16,7 @@ import { readState, stateFilePath, stateTransferContents } from "../state.js";
16
16
  * sessions they run (docs/REMOTE-MACHINES.md). The server never sees an ssh credential: every ssh
17
17
  * call here runs in the operator's terminal, and the machine key reaches the machine on ssh's stdin.
18
18
  *
19
- * machine add <name> --ssh <host> [--rotate] [--codex-userns] [--bwrap-userns]
19
+ * machine add <name> --ssh <host> [--rotate] [--codex-userns] [--bwrap-userns] [--agy-userns]
20
20
  * machine list | show <name> | remove <name>
21
21
  * machine session add <machine> <project>/<agent> --dir <path> --sandbox <mode> [--create --role r] [--model m] [--effort e] [--thread id] [--turn-timeout min]
22
22
  * machine session stop|start|remove <machine> <project>/<agent>
@@ -111,6 +111,9 @@ function ssh(host, command, input) {
111
111
  }
112
112
  /** Runs a b9s command on the machine in a login shell (so ~/.local/bin and the harness CLIs are on PATH). */
113
113
  const remoteBschat = (host, args, input) => ssh(host, `bash -lc ${JSON.stringify(`b9s ${args}`)}`, input);
114
+ export function machinePrepareCommand(options) {
115
+ return `machine prepare --json${options.codexUserns ? " --codex-userns" : ""}${options.bwrapUserns ? " --bwrap-userns" : ""}${options.agyUserns ? " --agy-userns" : ""}`;
116
+ }
114
117
  export async function machineAdmin(action, rest, p, out) {
115
118
  const c = adminClient(p);
116
119
  if (action === "companion") {
@@ -123,7 +126,7 @@ export async function machineAdmin(action, rest, p, out) {
123
126
  const name = rest[0];
124
127
  const host = str(p.flags, "ssh");
125
128
  if (!name || !host)
126
- throw new CliError("usage", "machine add <name> --ssh <host> [--rotate] [--codex-userns] [--bwrap-userns] (the host as your ssh knows it: an alias, user@host)");
129
+ throw new CliError("usage", "machine add <name> --ssh <host> [--rotate] [--codex-userns] [--bwrap-userns] [--agy-userns] (the host as your ssh knows it: an alias, user@host)");
127
130
  const lines = [];
128
131
  const say = (l) => { lines.push(l); if (!out.json)
129
132
  process.stderr.write(`${l}\n`); };
@@ -135,7 +138,7 @@ export async function machineAdmin(action, rest, p, out) {
135
138
  if (boot.status !== 0)
136
139
  throw new CliError("provision_failed", `bootstrapping ${host} failed${steps.length ? `: ${steps[steps.length - 1]}` : `: ${boot.stderr.trim().slice(-300)}`}`);
137
140
  // 2. Linger, Codex, managed hooks: checked and fixed on the machine itself.
138
- const prep = remoteBschat(host, `machine prepare --json${bool(p.flags, "codex-userns") ? " --codex-userns" : ""}${bool(p.flags, "bwrap-userns") ? " --bwrap-userns" : ""}`);
141
+ const prep = remoteBschat(host, machinePrepareCommand({ codexUserns: bool(p.flags, "codex-userns"), bwrapUserns: bool(p.flags, "bwrap-userns"), agyUserns: bool(p.flags, "agy-userns") }));
139
142
  if (prep.status !== 0)
140
143
  throw new CliError("provision_failed", `b9s machine prepare on ${host} failed: ${prep.stderr.trim().slice(-300)}`);
141
144
  const prepared = JSON.parse(prep.stdout).steps;
@@ -553,7 +556,7 @@ async function runMachineCompanion(code, p, out) {
553
556
  await report("bootstrap", "completed", "Node and b9s are ready on the target machine");
554
557
  await checkCancel();
555
558
  await report("prepare", "started", "Checking machine services and harness prerequisites");
556
- const prep = remoteBschat(operation.ssh_host, `machine prepare --json${operation.options.codex_userns ? " --codex-userns" : ""}${operation.options.bwrap_userns ? " --bwrap-userns" : ""}`);
559
+ const prep = remoteBschat(operation.ssh_host, machinePrepareCommand({ codexUserns: operation.options.codex_userns, bwrapUserns: operation.options.bwrap_userns }));
557
560
  if (prep.status !== 0)
558
561
  throw new CliError("provision_failed", `b9s machine prepare on ${operation.ssh_host} failed: ${prep.stderr.trim().slice(-300)}`);
559
562
  const prepared = JSON.parse(prep.stdout).steps;
@@ -827,7 +830,7 @@ function machineMoveReadinessError(machine, harness, provider, sandbox, liveSamp
827
830
  return null;
828
831
  }
829
832
  /**
830
- * agent move <project>/<agent> --to <machine> --sandbox <mode> [--dir path|auto] [--harness codex|claude-code] [--provider anthropic|deepseek] [--model m] [--effort e]
833
+ * agent move <project>/<agent> (--to <machine> --sandbox <mode> | --operation <id>) [--dir path|auto] [--harness codex|claude-code] [--provider anthropic|deepseek] [--model m] [--effort e]
831
834
  * [--carry note|thread] [--from local|<ssh host>] [--to-ssh <host>] [--thread id] [--wait min]
832
835
  * [--force --confirm-force <project>/<agent>]
833
836
  *
@@ -839,19 +842,99 @@ function machineMoveReadinessError(machine, harness, provider, sandbox, liveSamp
839
842
  export async function agentMove(rest, p, out) {
840
843
  const ref = rest[0] ?? "";
841
844
  const [project, agent] = ref.split("/");
842
- const to = str(p.flags, "to");
843
- const sandbox = str(p.flags, "sandbox");
844
- const harness = str(p.flags, "harness") ?? "codex";
845
- const provider = str(p.flags, "provider") ?? "anthropic";
846
- const carry = str(p.flags, "carry") ?? "note";
845
+ const operationId = str(p.flags, "operation");
846
+ const requestedTo = str(p.flags, "to");
847
+ const requestedSandbox = str(p.flags, "sandbox");
848
+ const requestedHarness = str(p.flags, "harness");
849
+ const requestedProvider = str(p.flags, "provider");
850
+ const requestedCarry = str(p.flags, "carry");
851
+ const requestedDir = str(p.flags, "dir");
852
+ const requestedModel = str(p.flags, "model");
853
+ const requestedEffort = str(p.flags, "effort");
854
+ const requestedThread = str(p.flags, "thread");
847
855
  const from = str(p.flags, "from");
848
856
  const forceConfirmation = str(p.flags, "confirm-force");
849
- if (!project || !agent || !to || !sandbox)
850
- throw new CliError("usage", "agent move <project>/<agent> --to <machine> --sandbox <mode> [--dir <path>|auto] [--harness codex|claude-code] [--provider anthropic|deepseek] [--carry note|thread] [--from local|<ssh host>] [--model m] [--effort e] [--wait min] [--force --confirm-force <project>/<agent>]");
857
+ if (!project || !agent || (!operationId && (!requestedTo || !requestedSandbox)))
858
+ throw new CliError("usage", "agent move <project>/<agent> (--to <machine> --sandbox <mode> | --operation <id>) [--dir <path>|auto] [--harness codex|claude-code] [--provider anthropic|deepseek] [--carry note|thread] [--from local|<ssh host>] [--model m] [--effort e] [--wait min] [--force --confirm-force <project>/<agent>]");
851
859
  if (forceConfirmation && !bool(p.flags, "force"))
852
860
  throw new CliError("usage", "--confirm-force is valid only with --force");
853
861
  if (forceConfirmation && forceConfirmation !== ref)
854
862
  throw new CliError("confirmation_required", `--confirm-force must exactly match ${ref}`);
863
+ if (!from)
864
+ throw new CliError("usage", "--from local|<ssh host> is required so the trusted CLI can check the source before authorizing completion");
865
+ const c = adminClient(p);
866
+ const say = (l) => { if (!out.json)
867
+ process.stderr.write(`${l}\n`); };
868
+ const moveRoute = `/projects/${project}/agents/${agent}/moves`;
869
+ let move;
870
+ let to;
871
+ let sandbox;
872
+ let harness;
873
+ let provider;
874
+ let carry;
875
+ let dir;
876
+ let model = requestedModel;
877
+ let effort = requestedEffort;
878
+ let thread = requestedThread ?? null;
879
+ if (operationId) {
880
+ const loaded = await c.call("GET", `${moveRoute}/${encodeURIComponent(operationId)}`);
881
+ move = loaded.move;
882
+ if (move.status !== "requested")
883
+ throw new CliError("move_not_awaiting_execution", `move operation ${operationId} is ${move.status}; only a requested operation can be continued`);
884
+ const target = move.target;
885
+ const expected = [
886
+ ["--to", requestedTo, move.to], ["--sandbox", requestedSandbox, target.sandbox], ["--harness", requestedHarness, target.harness],
887
+ ["--provider", requestedProvider, target.provider], ["--carry", requestedCarry, move.carry], ["--dir", requestedDir, target.dir],
888
+ ["--model", requestedModel, target.model], ["--effort", requestedEffort, target.effort], ["--thread", requestedThread, target.thread],
889
+ ];
890
+ for (const [flag, supplied, stored] of expected) {
891
+ if (supplied !== undefined && supplied !== (stored == null ? undefined : String(stored))) {
892
+ throw new CliError("move_option_mismatch", `${flag}=${supplied} does not match move operation ${operationId}${stored == null ? " (not set on the operation)" : ` (${stored})`}`);
893
+ }
894
+ }
895
+ if (str(p.flags, "turn-timeout") !== undefined && Number(str(p.flags, "turn-timeout")) !== target.turn_timeout) {
896
+ throw new CliError("move_option_mismatch", `--turn-timeout=${str(p.flags, "turn-timeout")} does not match move operation ${operationId} (${target.turn_timeout})`);
897
+ }
898
+ to = String(move.to);
899
+ sandbox = String(target.sandbox);
900
+ harness = String(target.harness ?? "codex");
901
+ provider = String(target.provider ?? "anthropic");
902
+ carry = String(move.carry ?? "note");
903
+ dir = String(target.dir ?? "auto");
904
+ model ??= typeof target.model === "string" ? target.model : undefined;
905
+ effort ??= typeof target.effort === "string" ? target.effort : undefined;
906
+ thread ??= typeof target.thread === "string" ? target.thread : null;
907
+ }
908
+ else {
909
+ to = requestedTo;
910
+ sandbox = requestedSandbox;
911
+ harness = requestedHarness ?? "codex";
912
+ provider = requestedProvider ?? "anthropic";
913
+ carry = requestedCarry ?? "note";
914
+ dir = requestedDir ?? "auto";
915
+ if (harness !== "codex" && harness !== "claude-code")
916
+ throw new CliError("usage", "agent move currently supports codex and claude-code sessions; DSH and Antigravity session behavior is unchanged");
917
+ if (provider !== "anthropic" && provider !== "deepseek")
918
+ throw new CliError("usage", "--provider must be anthropic or deepseek");
919
+ if (provider === "deepseek" && harness !== "claude-code")
920
+ throw new CliError("usage", "--provider deepseek requires --harness claude-code");
921
+ if (carry !== "note" && carry !== "thread")
922
+ throw new CliError("usage", "--carry note (a resume note it writes now) or thread (its Codex thread, copied)");
923
+ if (carry !== "thread" && thread)
924
+ throw new CliError("usage", "--thread is valid only with --carry thread");
925
+ if (carry === "thread" && harness !== "codex")
926
+ throw new CliError("usage", "--carry thread copies a Codex thread; a Claude Code agent moves with --carry note (its resume note), and its new machine starts a fresh session");
927
+ if (carry === "thread" && !from)
928
+ throw new CliError("usage", "--carry thread needs --from local|<ssh host>: the machine whose ~/.codex holds its thread");
929
+ const requested = await c.call("POST", moveRoute, {
930
+ to, carry, harness, provider, dir, sandbox,
931
+ ...(model ? { model } : {}),
932
+ ...(effort ? { effort } : {}),
933
+ ...(thread ? { thread } : {}),
934
+ ...(str(p.flags, "turn-timeout") ? { turn_timeout: Number(str(p.flags, "turn-timeout")) } : {}),
935
+ });
936
+ move = requested.move;
937
+ }
855
938
  if (harness !== "codex" && harness !== "claude-code")
856
939
  throw new CliError("usage", "agent move currently supports codex and claude-code sessions; DSH and Antigravity session behavior is unchanged");
857
940
  if (provider !== "anthropic" && provider !== "deepseek")
@@ -860,33 +943,16 @@ export async function agentMove(rest, p, out) {
860
943
  throw new CliError("usage", "--provider deepseek requires --harness claude-code");
861
944
  if (carry !== "note" && carry !== "thread")
862
945
  throw new CliError("usage", "--carry note (a resume note it writes now) or thread (its Codex thread, copied)");
863
- if (carry !== "thread" && str(p.flags, "thread"))
946
+ if (carry !== "thread" && thread)
864
947
  throw new CliError("usage", "--thread is valid only with --carry thread");
865
- if (carry === "thread" && (str(p.flags, "harness") ?? "codex") !== "codex")
948
+ if (carry === "thread" && harness !== "codex")
866
949
  throw new CliError("usage", "--carry thread copies a Codex thread; a Claude Code agent moves with --carry note (its resume note), and its new machine starts a fresh session");
867
950
  if (carry === "thread" && !from)
868
951
  throw new CliError("usage", "--carry thread needs --from local|<ssh host>: the machine whose ~/.codex holds its thread");
869
- if (!from)
870
- throw new CliError("usage", "--from local|<ssh host> is required so the trusted CLI can check the source before authorizing completion");
871
- const c = adminClient(p);
872
- const say = (l) => { if (!out.json)
873
- process.stderr.write(`${l}\n`); };
874
- const moveRoute = `/projects/${project}/agents/${agent}/moves`;
875
- const requested = await c.call("POST", moveRoute, {
876
- to, carry, harness, provider, dir: str(p.flags, "dir") ?? "auto", sandbox,
877
- ...(str(p.flags, "model") ? { model: str(p.flags, "model") } : {}),
878
- ...(str(p.flags, "effort") ? { effort: str(p.flags, "effort") } : {}),
879
- ...(str(p.flags, "thread") ? { thread: str(p.flags, "thread") } : {}),
880
- ...(str(p.flags, "turn-timeout") ? { turn_timeout: Number(str(p.flags, "turn-timeout")) } : {}),
881
- });
882
- const move = requested.move;
883
952
  const progressRoute = `${moveRoute}/${move.id}`;
884
953
  if (!out.json)
885
954
  say(` move ${move.id}: ${move.from ?? "source"} → ${to}; other agent keys will be revoked only after completion`);
886
- await c.call("PATCH", progressRoute, { status: "checking", detail: "trusted CLI is checking local readiness and preparing the handoff" });
887
- let thread = str(p.flags, "thread") ?? null;
888
- let model = str(p.flags, "model");
889
- let effort = str(p.flags, "effort");
955
+ await c.call("PATCH", progressRoute, { status: "checking", expected_status: "requested", detail: "trusted CLI is checking local readiness and preparing the handoff" });
890
956
  let problems = [];
891
957
  const destinationHost = str(p.flags, "to-ssh") ?? to;
892
958
  try {
@@ -1012,7 +1078,8 @@ export async function agentMove(rest, p, out) {
1012
1078
  ? "source-only work was not explicitly confirmed"
1013
1079
  : "local source check or context handoff failed";
1014
1080
  try {
1015
- await c.call("PATCH", progressRoute, { status: "blocked", detail: recordedDetail });
1081
+ const refusalReason = error instanceof CliError ? `${error.code}: ${recordedDetail}` : recordedDetail;
1082
+ await c.call("PATCH", progressRoute, { status: "blocked", detail: recordedDetail, refusal_reason: refusalReason.slice(0, 1000) });
1016
1083
  }
1017
1084
  catch (recordError) {
1018
1085
  throw new CliError("move_progress_failed", `${detail}\nCould not record the blocked move operation: ${recordError instanceof Error ? recordError.message : String(recordError)}`);
@@ -1028,7 +1095,23 @@ export async function agentMove(rest, p, out) {
1028
1095
  ...(carry === "thread" && thread ? { thread } : {}),
1029
1096
  ...(model ? { model } : {}), ...(effort ? { effort } : {}),
1030
1097
  });
1031
- const r = await c.call("POST", `${progressRoute}/complete`, {});
1098
+ let r;
1099
+ try {
1100
+ r = await c.call("POST", `${progressRoute}/complete`, { carried_context_kind: carry });
1101
+ }
1102
+ catch (error) {
1103
+ const refusalReason = error instanceof CliError ? `${error.code}: server move completion failed` : "server move completion failed";
1104
+ try {
1105
+ const current = await c.call("GET", progressRoute);
1106
+ if (!current.move.completion_summary) {
1107
+ await c.call("PATCH", progressRoute, {
1108
+ status: "failed", detail: "server move completion failed", refusal_reason: refusalReason.slice(0, 1000),
1109
+ });
1110
+ }
1111
+ }
1112
+ catch { /* preserve the completion error; the server may already have recorded its failure summary */ }
1113
+ throw error;
1114
+ }
1032
1115
  return out.print([
1033
1116
  `Move ${move.id} completed: ${ref} now runs on ${to} (${r.session.harness}/${r.session.provider}, ${r.session.sandbox}, ${r.session.dir || "automatic checkout"}${thread ? `, thread ${thread}` : ", a fresh session"}); its daemon starts it within 30 s.`,
1034
1117
  r.moved_from.length ? `Its session on ${r.moved_from.join(", ")} was removed.` : null,
@@ -7,19 +7,19 @@ import { str } from "../args.js";
7
7
  import { Client } from "../client.js";
8
8
  import { configRoot, loadAgent, resolveAgentName, saveAgent } from "../config.js";
9
9
  import { CliError } from "../errors.js";
10
- import { BWRAP_APPARMOR_PATH, bwrapAppArmorProfile, CODEX_APPARMOR_PATH, CODEX_MANAGED_DIR, codexAppArmorProfile, codexManagedHooks, isCodexManagedRequirements } from "../harness.js";
10
+ import { AGY_APPARMOR_PATH, agyAppArmorProfile, BWRAP_APPARMOR_PATH, bwrapAppArmorProfile, CODEX_APPARMOR_PATH, CODEX_MANAGED_DIR, codexAppArmorProfile, codexManagedHooks, isCodexManagedRequirements } from "../harness.js";
11
11
  import { applySparse } from "../git.js";
12
12
  import { drainingUntil, writeMaintenance } from "../maintenance.js";
13
13
  import { TURN_HARNESSES, claudeFacts, claudeSandbox, dshFacts, dshProcesses, probeFor, sessionProcesses } from "../harnesses.js";
14
14
  import { readState, writeState } from "../state.js";
15
- import { installService, lingerEnabled, MACHINE_LABEL, machineDaemonPath, removeService, requireInstall, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
15
+ import { installService, lingerEnabled, MACHINE_LABEL, machineDaemonPath, readInstall, removeService, requireInstall, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
16
16
  import { CLI_VERSION } from "../version.js";
17
17
  import { probeCapabilities } from "../capabilities.js";
18
18
  import { diskSpaceNotice } from "../notices.js";
19
19
  import { verifyClaudeProvider } from "../providers.js";
20
20
  import { busyTurnPause, DEFAULT_TURNS_PER_HOUR, DEFAULT_UNPRODUCTIVE_PER_HOUR, resumeTurnGuard } from "../turn-guard.js";
21
21
  import { defaultWorkspaceWritableRoots } from "../start-options.js";
22
- import { antigravityTurnArgs, parseAntigravityJson } from "../antigravity.js";
22
+ import { antigravityPath, antigravitySandboxPermissions, antigravityTurnArgs, parseAntigravityJson } from "../antigravity.js";
23
23
  import { bootTimeMs } from "../boot-time.js";
24
24
  import { DEFAULT_CACHE_FLOOR_PCT, manageBuildCaches } from "../build-caches.js";
25
25
  import { agentContainerName, agentContainerRunArgs, isolatedBuildCommand, isolatedDevcontainerBuildCommand, isolatedImagePullCommands, isolatedSubprocessEnv, probeImdsIsolation, probeNestedSandbox, readGitIdentity, resolveSessionSecretDelivery, validateDevcontainerSpec, } from "../container.js";
@@ -350,7 +350,10 @@ export function resolveContainerLaunchPrereqs(opts) {
350
350
  throw new Error("container isolation required but neither podman nor docker is available; refusing unisolated host fallback");
351
351
  }
352
352
  if (opts.s.sandbox !== "danger-full-access" && !nested.nested_sandbox_ok) {
353
- throw new Error(`refusing sandboxed container session (${opts.s.sandbox}) without silently falling back to danger-full-access: ${nested.detail}`);
353
+ const error = new Error(`refusing sandboxed container session (${opts.s.sandbox}) without silently falling back to danger-full-access: ${nested.detail}`);
354
+ if (nested.missing.includes("unprivileged_userns"))
355
+ error.environment_check = "linux_user_namespaces";
356
+ throw error;
354
357
  }
355
358
  const imageDigest = resolvePinnedImageRef(opts.project?.image);
356
359
  if (!imageDigest) {
@@ -739,7 +742,8 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
739
742
  catch (e) {
740
743
  const error = e.message.slice(0, 1000);
741
744
  log(`${s.agent}: ${error}`);
742
- out.push({ id: s.id, state: "error", thread: state.sessions[s.id]?.thread ?? null, error });
745
+ const environmentCheck = e.environment_check;
746
+ out.push({ id: s.id, state: "error", thread: state.sessions[s.id]?.thread ?? null, error, ...(typeof environmentCheck === "string" ? { environment_check: environmentCheck } : {}) });
743
747
  }
744
748
  }
745
749
  // Sessions the operator removed: their watchers go too.
@@ -1233,19 +1237,62 @@ const AGY_SANDBOX_PROBE_MS = 10 * 60_000;
1233
1237
  const AGY_SANDBOX_PROBE_MODEL = "gemini-4-hydrogen-low";
1234
1238
  const AGY_SANDBOX_PROBE_RESPONSE = "B9S_SANDBOX_OK";
1235
1239
  let agySandboxCache = null;
1240
+ const AGY_USERNS_ERROR = "Antigravity terminal sandbox unavailable (AppArmor restricts unprivileged user namespaces)";
1241
+ const AGY_USERNS_FIX = `${AGY_USERNS_ERROR}; run b9s machine prepare --agy-userns`;
1242
+ function antigravityUsernsDenied(parsed, output) {
1243
+ const value = parsed;
1244
+ const error = value?.error && typeof value.error === "object" ? value.error : null;
1245
+ const denied = value?.denied_actions ?? error?.denied_actions;
1246
+ return /Terminal sandbox unavailable/i.test(output) || (Array.isArray(denied) && denied.some((entry) => entry && typeof entry === "object" && entry.action === "command"));
1247
+ }
1248
+ /** Install only an absent or byte-identical b9s profile; leave every other owner untouched. */
1249
+ export function installAgyAppArmorProfile(binary, profilePath = AGY_APPARMOR_PATH, run = (args, input) => spawnSync("sudo", args, { input, encoding: "utf8", stdio: input === undefined ? "pipe" : ["pipe", "ignore", "pipe"] })) {
1250
+ const profile = agyAppArmorProfile(binary);
1251
+ let existing = null;
1252
+ try {
1253
+ existing = readFileSync(profilePath, "utf8");
1254
+ }
1255
+ catch (error) {
1256
+ if (error.code !== "ENOENT")
1257
+ return { ok: false, error: `reading ${profilePath}: ${error.message}` };
1258
+ }
1259
+ if (existing !== null && existing !== profile) {
1260
+ return { ok: false, error: `${profilePath} already exists and does not exactly match the b9s Antigravity profile; leaving it unchanged` };
1261
+ }
1262
+ if (existing === null) {
1263
+ const write = run(["-n", "sh", "-c", 'set -C; umask 022; cat > "$1"', "b9s", profilePath], profile);
1264
+ if (write.status !== 0)
1265
+ return { ok: false, error: `installing ${profilePath}: ${(write.stderr ?? "").trim() || `exit ${write.status ?? "unknown"}`}` };
1266
+ }
1267
+ const load = run(["-n", "apparmor_parser", "-r", profilePath]);
1268
+ return load.status === 0
1269
+ ? { ok: true, error: null }
1270
+ : { ok: false, error: `loading ${profilePath}: ${(load.stderr ?? "").trim() || `exit ${load.status ?? "unknown"}`}` };
1271
+ }
1272
+ function resolvedAgyBinary(path) {
1273
+ const result = spawnSync("sh", ["-c", "command -v agy"], { encoding: "utf8", env: { ...process.env, PATH: path } });
1274
+ const binary = result.status === 0 ? (result.stdout ?? "").trim() : "";
1275
+ return isAbsolute(binary) ? binary : null;
1276
+ }
1236
1277
  /** Runs one cached no-op turn through Antigravity's real workspace-write terminal sandbox. */
1237
- export function antigravitySandbox(force = false, path = process.env.PATH ?? "") {
1238
- if (!force && agySandboxCache && agySandboxCache.path === path && Date.now() - agySandboxCache.at < AGY_SANDBOX_PROBE_MS)
1278
+ export function antigravitySandbox(force = false, path = process.env.PATH ?? "", b9sBin = readInstall()?.bin ?? null) {
1279
+ if (!force && agySandboxCache && agySandboxCache.path === path && agySandboxCache.b9sBin === b9sBin && Date.now() - agySandboxCache.at < AGY_SANDBOX_PROBE_MS)
1239
1280
  return agySandboxCache.result;
1240
- const work = mkdtempSync(join(tmpdir(), "b9s-agy-sandbox-probe-"));
1281
+ if (!b9sBin) {
1282
+ const result = { ok: false, error: `recorded b9s install is unavailable; expected ${join(configRoot(), "install.json")}` };
1283
+ agySandboxCache = { at: Date.now(), result, path, b9sBin };
1284
+ return result;
1285
+ }
1241
1286
  let result;
1287
+ let work = null;
1242
1288
  try {
1289
+ work = mkdtempSync(join(tmpdir(), "b9s-agy-sandbox-probe-"));
1243
1290
  const marker = join(work, ".b9s-sandbox-probe");
1244
1291
  const quotedMarker = `'${marker.replace(/'/g, `'\\''`)}'`;
1245
- const prompt = `Use your terminal tool once to run exactly: printf '${AGY_SANDBOX_PROBE_RESPONSE}' > ${quotedMarker}. Then reply with exactly ${AGY_SANDBOX_PROBE_RESPONSE}. Do not call any other tool.`;
1246
- const settings = ["--sandbox", "--settings", JSON.stringify({ enableTerminalSandbox: true, toolPermission: "proceed-in-sandbox", permissions: { allow: [] } })];
1292
+ const prompt = `Use your terminal tool once to run exactly: b9s --version && printf '${AGY_SANDBOX_PROBE_RESPONSE}' > ${quotedMarker}. Then reply with exactly ${AGY_SANDBOX_PROBE_RESPONSE}. Do not call any other tool.`;
1293
+ const settings = ["--sandbox", "--settings", JSON.stringify({ enableTerminalSandbox: true, toolPermission: "proceed-in-sandbox", permissions: { allow: antigravitySandboxPermissions("api.benignswarm.org", configRoot(), b9sBin) } })];
1247
1294
  const r = spawnSync("agy", antigravityTurnArgs(prompt, AGY_SANDBOX_PROBE_MODEL, undefined, 45, settings), {
1248
- encoding: "utf8", timeout: 60_000, maxBuffer: 1024 * 1024, cwd: work, env: { ...process.env, PATH: path },
1295
+ encoding: "utf8", timeout: 60_000, maxBuffer: 1024 * 1024, cwd: work, env: { ...process.env, PATH: antigravityPath(b9sBin, path) },
1249
1296
  });
1250
1297
  const parsed = parseAntigravityJson(r.stdout ?? "");
1251
1298
  let wroteMarker = false;
@@ -1253,14 +1300,22 @@ export function antigravitySandbox(force = false, path = process.env.PATH ?? "")
1253
1300
  wroteMarker = readFileSync(marker, "utf8") === AGY_SANDBOX_PROBE_RESPONSE;
1254
1301
  }
1255
1302
  catch { /* a missing marker means the sandbox command did not run */ }
1303
+ const output = `${r.stdout ?? ""}\n${r.stderr ?? ""}`;
1256
1304
  result = r.status === 0 && parsed?.status === "SUCCESS" && parsed.response?.trim() === AGY_SANDBOX_PROBE_RESPONSE && wroteMarker
1257
1305
  ? { ok: true, error: null }
1258
- : { ok: false, error: r.status !== 0 ? `agy sandbox no-op failed (exit ${r.status ?? "unknown"})` : "agy sandbox no-op did not return the required successful result" };
1306
+ : { ok: false, error: antigravityUsernsDenied(parsed, output)
1307
+ ? AGY_USERNS_FIX
1308
+ : `sandbox could not run b9s --version and its no-op check (agy exit ${r.status ?? "unknown"}); verify recorded install ${b9sBin} and Node runtime ${process.execPath} are readable and executable inside the sandbox` };
1309
+ }
1310
+ catch (error) {
1311
+ const detail = error instanceof Error ? error.message : String(error);
1312
+ result = { ok: false, error: `sandbox could not prepare b9s --version probe for recorded install ${b9sBin} with Node runtime ${process.execPath}: ${detail}` };
1259
1313
  }
1260
1314
  finally {
1261
- rmSync(work, { recursive: true, force: true });
1315
+ if (work)
1316
+ rmSync(work, { recursive: true, force: true });
1262
1317
  }
1263
- agySandboxCache = { at: Date.now(), result, path };
1318
+ agySandboxCache = { at: Date.now(), result, path, b9sBin };
1264
1319
  return result;
1265
1320
  }
1266
1321
  function antigravityLoginFacts(path) {
@@ -1277,11 +1332,11 @@ function antigravityLoginFacts(path) {
1277
1332
  };
1278
1333
  }
1279
1334
  /** Machine facts used by placement; the daemon probes login cheaply and caches the sandbox turn. */
1280
- export function antigravityFacts(path = process.env.PATH ?? "") {
1335
+ export function antigravityFacts(path = process.env.PATH ?? "", b9sBin = readInstall()?.bin ?? null) {
1281
1336
  const facts = antigravityLoginFacts(path);
1282
1337
  return {
1283
1338
  ...facts,
1284
- sandbox: facts.logged_in ? antigravitySandbox(false, path) : null,
1339
+ sandbox: facts.logged_in ? antigravitySandbox(false, path, b9sBin) : null,
1285
1340
  };
1286
1341
  }
1287
1342
  /** Memory a new process could use: Linux's MemAvailable (free alone undercounts the page cache), else free. */
@@ -1510,6 +1565,45 @@ export function prepare(opts = {}) {
1510
1565
  : agy.logged_in
1511
1566
  ? { step: "antigravity login", result: "ok", detail: `${agy.version ?? "agy"}; agy models succeeded` }
1512
1567
  : { step: "antigravity login", result: "failed", detail: `${agy.version ?? "agy"}; agy models did not succeed; log in interactively with agy on this machine` });
1568
+ if (!agy.available || !agy.logged_in) {
1569
+ steps.push({ step: "antigravity sandbox", result: "skipped", detail: "agy must be installed and logged in before its terminal sandbox can be checked" });
1570
+ }
1571
+ else {
1572
+ let agySandboxResult = antigravitySandbox(true, daemonPath);
1573
+ if (agySandboxResult.ok) {
1574
+ steps.push({ step: "antigravity sandbox", result: "ok", detail: "workspace-write terminal sandbox works" });
1575
+ }
1576
+ else if (!agySandboxResult.error?.startsWith(AGY_USERNS_ERROR)) {
1577
+ steps.push({ step: "antigravity sandbox", result: "failed", detail: agySandboxResult.error ?? "agy sandbox no-op failed" });
1578
+ }
1579
+ else if (platform() !== "linux") {
1580
+ steps.push({ step: "antigravity sandbox", result: "failed", detail: `${AGY_USERNS_ERROR}; this opt-in AppArmor fix applies only on Linux` });
1581
+ }
1582
+ else if (!opts.agyUserns) {
1583
+ steps.push({ step: "antigravity sandbox", result: "failed", detail: `${agySandboxResult.error}; the profile targets the resolved agy binary at ${AGY_APPARMOR_PATH}` });
1584
+ }
1585
+ else if (!sudo) {
1586
+ steps.push({ step: "antigravity sandbox", result: "failed", detail: `--agy-userns needs passwordless sudo; install ${AGY_APPARMOR_PATH} by hand (b9s machine prepare --print-apparmor shows the profile) and run sudo apparmor_parser -r on it` });
1587
+ }
1588
+ else {
1589
+ const binary = resolvedAgyBinary(daemonPath);
1590
+ if (!binary) {
1591
+ steps.push({ step: "antigravity sandbox", result: "failed", detail: `--agy-userns could not resolve agy on the daemon PATH; cannot safely create ${AGY_APPARMOR_PATH}` });
1592
+ }
1593
+ else {
1594
+ const install = installAgyAppArmorProfile(binary);
1595
+ if (!install.ok) {
1596
+ steps.push({ step: "antigravity sandbox", result: "failed", detail: install.error ?? `could not install ${AGY_APPARMOR_PATH}` });
1597
+ }
1598
+ else {
1599
+ agySandboxResult = antigravitySandbox(true, daemonPath);
1600
+ steps.push(agySandboxResult.ok
1601
+ ? { step: "antigravity sandbox", result: "done", detail: `installed ${AGY_APPARMOR_PATH} for ${binary}; workspace-write terminal sandbox works` }
1602
+ : { step: "antigravity sandbox", result: "failed", detail: `${AGY_APPARMOR_PATH} loaded but sandbox still fails: ${agySandboxResult.error}` });
1603
+ }
1604
+ }
1605
+ }
1606
+ }
1513
1607
  const codex = spawnSync("codex", ["--version"], { encoding: "utf8", env: daemonEnv });
1514
1608
  if (codex.status !== 0)
1515
1609
  steps.push({ step: "codex", result: "failed", detail: "codex is not on PATH; install the Codex CLI (npm i -g @openai/codex) and log in (codex login --device-auth)" });
@@ -1907,9 +2001,15 @@ export async function machine(p, out) {
1907
2001
  if (sub === "prepare") {
1908
2002
  if (p.flags["print-hooks"])
1909
2003
  return out.print(codexManagedHooks(requireInstall().bin).requirements, codexManagedHooks(requireInstall().bin));
1910
- if (p.flags["print-apparmor"])
1911
- return out.print(`${CODEX_APPARMOR_PATH}:\n${codexAppArmorProfile()}\n${BWRAP_APPARMOR_PATH}:\n${bwrapAppArmorProfile()}`, { [CODEX_APPARMOR_PATH]: codexAppArmorProfile(), [BWRAP_APPARMOR_PATH]: bwrapAppArmorProfile() });
1912
- const steps = prepare({ codexUserns: p.flags["codex-userns"] === true, bwrapUserns: p.flags["bwrap-userns"] === true });
2004
+ if (p.flags["print-apparmor"]) {
2005
+ const agyBinary = resolvedAgyBinary(machineDaemonPath()) ?? join(homedir(), ".local", "bin", "agy");
2006
+ return out.print(`${CODEX_APPARMOR_PATH}:\n${codexAppArmorProfile()}\n${BWRAP_APPARMOR_PATH}:\n${bwrapAppArmorProfile()}\n${AGY_APPARMOR_PATH}:\n${agyAppArmorProfile(agyBinary)}`, {
2007
+ [CODEX_APPARMOR_PATH]: codexAppArmorProfile(),
2008
+ [BWRAP_APPARMOR_PATH]: bwrapAppArmorProfile(),
2009
+ [AGY_APPARMOR_PATH]: agyAppArmorProfile(agyBinary),
2010
+ });
2011
+ }
2012
+ const steps = prepare({ codexUserns: p.flags["codex-userns"] === true, bwrapUserns: p.flags["bwrap-userns"] === true, agyUserns: p.flags["agy-userns"] === true });
1913
2013
  return out.print(steps.map((s) => `${s.result.padEnd(8)} ${s.step}: ${s.detail}`).join("\n"), { steps });
1914
2014
  }
1915
2015
  if (sub === "service") {
@@ -325,8 +325,8 @@ export async function watch(p, out) {
325
325
  return stoppingCode;
326
326
  debugLog(`seen messages=${u?.counts.messages ?? 0} questions=${u?.counts.questions ?? 0} items=${u?.counts.items ?? 0} followed=${u?.counts.followed ?? 0} digest=${u?.counts.digest ?? 0} notices=${u?.counts.notices ?? 0}; tier=${u?.tier ?? "none"}; decision=${u ? "deliver" : "no updates"}`);
327
327
  if (u) {
328
- const recovery = resumeBriefDelivered ? null : await recoveryBriefText(name, log);
329
- const update = resumeBriefDelivered ? u : formatUpdates(omitMeasuresAlreadyIn(recovery, u), [recovery ?? recoveryBriefUnavailableText]);
328
+ const recovery = await recoveryBriefText(name, log);
329
+ const update = formatUpdates(omitMeasuresAlreadyIn(recovery, u), [recovery ?? recoveryBriefUnavailableText]);
330
330
  const total = update.counts.messages + update.counts.items + update.counts.followed + update.counts.digest + update.counts.notices;
331
331
  const summary = update.text.split("\n")[0].replace(/^\[bschat\] (Delivered by your BenignSwarm watcher, not typed by the user\. )?/, "");
332
332
  let delivered = true;
@@ -475,8 +475,8 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
475
475
  }
476
476
  }
477
477
  const seq = (st.watch_seq ?? 0) + 1;
478
- const recovery = includeResumeBrief ? await recoveryBriefText(name, log) : null;
479
- const recoveryPrompt = includeResumeBrief ? recovery ?? recoveryBriefUnavailableText : null;
478
+ const recovery = await recoveryBriefText(name, log);
479
+ const recoveryPrompt = recovery ?? recoveryBriefUnavailableText;
480
480
  const wakePrefix = [
481
481
  ...(turnSink
482
482
  ? [`[b9s] Turn #${seq}, started by your BenignSwarm watcher because you were idle; not typed by the user. It is already acknowledged.`]
package/dist/harness.js CHANGED
@@ -438,6 +438,7 @@ export function codexManagedHooks(bin) {
438
438
  }
439
439
  export const CODEX_APPARMOR_PATH = "/etc/apparmor.d/bschat-codex";
440
440
  export const BWRAP_APPARMOR_PATH = "/etc/apparmor.d/bschat-bwrap";
441
+ export const AGY_APPARMOR_PATH = "/etc/apparmor.d/bschat-agy";
441
442
  /**
442
443
  * An AppArmor profile that lets the system's bubblewrap create user namespaces, which Claude Code's
443
444
  * Linux sandbox runs commands in. Broader than the Codex profile: any local user may then use
@@ -480,3 +481,20 @@ export function codexAppArmorProfile() {
480
481
  ``,
481
482
  ].join("\n");
482
483
  }
484
+ /** An opt-in AppArmor profile for the installed Antigravity CLI only. */
485
+ export function agyAppArmorProfile(binary) {
486
+ if (!binary.startsWith("/"))
487
+ throw new Error("Antigravity binary path must be absolute");
488
+ return [
489
+ `# b9s: let Antigravity create the user namespaces its workspace-write terminal sandbox needs (Ubuntu 24.04+ restricts them).`,
490
+ `# Written by b9s machine prepare --agy-userns; remove this file and run apparmor_parser -R on it to undo.`,
491
+ `abi <abi/4.0>,`,
492
+ `include <tunables/global>`,
493
+ ``,
494
+ `profile bschat-agy ${binary} flags=(unconfined) {`,
495
+ ` userns,`,
496
+ ` include if exists <local/bschat-agy>`,
497
+ `}`,
498
+ ``,
499
+ ].join("\n");
500
+ }
package/dist/help.js CHANGED
@@ -23,6 +23,7 @@ Session/admin clients can use GET /assistant/conversations, GET /assistant/conve
23
23
  Free and paid accounts without a live Stripe subscription use the UTC calendar month; subscribed paid accounts reset at current_period_end.
24
24
 
25
25
  Mac capacity/signing API (profiles, leases, signer-only references, TestFlight approvals, and the isolated signer job contract) is documented in docs/MACOS-MACHINES-API.md. There is no CLI command to issue signer-host credentials or trigger release; operator controls are WU #286, real host/provider integration is WU #288.
26
+ Standing rules are resolved by account, project, role, and exact-agent scope. GET /agents/me/standing-rules and GET /projects/:p/standing-rules return complete authorized sets and fingerprints; their separate ack endpoints accept only a current fingerprint after complete delivery. Operators and authorized assigners manage rules through the API; limits, compatibility confirmation, audit, and authorization are in packages/skill/references/api.md. Console management and chat promotion are planned in implementation unit 3 of docs/STANDING-RULES.md.
26
27
 
27
28
  GitHub connection and repository status are available in the console and through b9s-admin github status and b9s-admin project github <project> status|unlink. A repository link enables agent credentials without requiring a ruleset. An agent can inspect its effective repository permission with GET /projects/:p/git-credentials; a project admin can inspect a named agent with GET /projects/:p/git-credentials?agent=<name-or-id>. Each issuance records its permission reason without storing the token. Verify an exact target ruleset in Account -> GitHub connection before enabling hosted merge; the CLI cannot perform this owner OAuth step. Disconnect an installation with b9s-admin github disconnect <installation-id>. Hosted merge execution and status use b9s wu merge <n> and b9s wu merge status <n>; they call POST/GET /projects/:p/work-units/:n/merge and never inspect local Git state. API role checks use merge.merged_by and operator override; operator_hold is checked, merges serialize in MergeTargetDO, and retries reconcile idempotently. Manual wu done remains disabled for enabled linked targets. Enable with b9s-admin project hosted-merge <project> enable --confirm-bypass-signal only after ruleset verification and the live GitHub bypass-change check; disable with b9s-admin project hosted-merge <project> disable. The console control is WU #196. App setup steps are in packages/skill-admin/references/setup.md.
28
29
 
@@ -37,9 +38,9 @@ Agent commands
37
38
  b9s login --as <name> --key <bs_agent_...> [--url <api>] [--label <machine-label>]
38
39
  b9s logout --as <name>
39
40
  b9s identities list saved identities on this machine
40
- b9s me who am I, role, permissions, channels; --json includes your machine sessions
41
+ b9s me who am I, role, permissions, channels, standing rules and acknowledgment; --json includes your machine sessions
41
42
  b9s git-credential get|store|erase Git credential helper for the project's linked GitHub repository
42
- b9s resume compact recovery brief: units, reviews, asks, slices, decisions, outcomes, process and notices
43
+ b9s resume compact recovery brief: units, reviews, asks, slices, decisions, outcomes, process, standing rules and notices
43
44
  b9s notice add --project <p> "<text>" [--until <time>] [--command-pattern <regex>]
44
45
  assigner only: add a project notice; matching commands warn but continue
45
46
  b9s who [--account] agent status (--account: all projects); shows pressure for active machine sessions
@@ -56,7 +57,7 @@ Agent commands
56
57
  b9s inbox handle <project>/<channel>/<seq> mark an addressed question handled outside its thread
57
58
  b9s follow <channel> | unfollow <channel> | following followed channels' new messages are injected by the hook;
58
59
  other channels appear as a one-line unread digest
59
- b9s process the project's process: tag vocabulary, reviewers, wake-path warnings, scope templates, requirements, agreements
60
+ b9s process the project's process: tag vocabulary, reviewers, wake-path warnings, scope templates, agreements and active standing rules
60
61
  b9s wu open "<title>" --scope "..." [--scope-file <path> | --scope-from <n>] [--tags a,b] [--lands-with <n>] [--after <n>[,<m>]] [--requires cap,cap] [--force] [--evidence id[,id...]] [--target <branch>] [--here] open a work unit in its own
61
62
  worktree; tags come from the vocabulary; --target is the branch it lands in (default: the
62
63
  process target), e.g. a lane branch; wu target <n> <branch|default> changes it before review
@@ -223,8 +224,9 @@ Agent commands
223
224
  b9s unpause [--as <a>] lift a usage-limit pause now (the harness was switched to an account with quota)
224
225
  b9s turn note "<short progress summary>" [--as <a>] save a 300-character turn-end excerpt for an enabled managed session; it is labelled unverified
225
226
  b9s machine bootstrap --url <api> [--retrieve-ec2 | --token-file <path> | --token <bs_boot_...>] [--name <m>] retrieve (over TLS+IMDSv2/STS) and exchange a single-use cloud bootstrap token once, scrub it, and write mode-0600 credentials
226
- b9s machine run [--interval seconds] | once | build-images | status | prepare | service
227
- default interval 30s, 1..3600; prepare checks dsh availability/version (Linux has no DSH build)
227
+ b9s machine run [--interval seconds] | once | build-images | status | prepare [--agy-userns] [--print-apparmor] | service
228
+ default interval 30s, 1..3600; prepare checks harnesses; --agy-userns opts into an AppArmor
229
+ profile for the resolved agy binary if Ubuntu blocks its workspace-write terminal sandbox (passwordless sudo)
228
230
  b9s machine processes --worktree <path> [--as <project>/<agent>] [--json] read-only host process sample for a project-owned worktree
229
231
  includes pid/parent, start/elapsed, command (120 chars), cwd, TCP listeners and sample time
230
232
  project agents only; stale samples are labelled; command credentials are redacted; no environment values or signaling
@@ -365,12 +367,13 @@ the returned object and warning, then exits 3. Inspect the object and do not ret
365
367
 
366
368
  Machines (provisioned over your own ssh; a daemon on each runs the agent sessions you declare)
367
369
  Account Mac leases and trusted TestFlight signing approvals are managed in Console → Machines → Mac fleet and signing; there is no CLI signing or App Store release command.
368
- b9s-admin machine add <name> --ssh <host> [--rotate] [--codex-userns] [--bwrap-userns] install Node and b9s (no sudo), linger, harness login checks,
370
+ b9s-admin machine add <name> --ssh <host> [--rotate] [--codex-userns] [--bwrap-userns] [--agy-userns] install Node and b9s (no sudo), linger, harness login checks,
369
371
  on macOS also check selected Xcode/license/SDKs, actual simulator runtimes, and disk;
370
372
  b9s's Codex hooks in /etc/codex (passwordless sudo only), register, start the daemon;
371
373
  --codex-userns: where Linux restricts user namespaces (Ubuntu 24.04+), install a
372
374
  Codex-only AppArmor profile so sandboxed agents can run; --bwrap-userns: the same
373
- for /usr/bin/bwrap (Claude Code's sandbox; broader: any local user may use it)
375
+ for /usr/bin/bwrap (Claude Code's sandbox; broader: any local user may use it); --agy-userns:
376
+ install a profile only for the resolved ~/.local/bin/agy (Antigravity terminal sandbox)
374
377
  b9s-admin machine list | show <name> | remove <name> [--preview] [--confirm <name> --impact-revision <revision>]
375
378
  show includes host readiness, configured disk floors and named readiness refusals; removal previews sessions, work, keys, recovery blockers and replanned slots
376
379
  the API requires a fresh revision for removal
@@ -386,10 +389,11 @@ Machines (provisioned over your own ssh; a daemon on each runs the agent session
386
389
  b9s-admin machine session thread <machine> <project>/<agent> <thread-id|none> set or clear the thread a pool session adopts
387
390
  b9s-admin machine session stop|start|resume|limit|coalesce|remove <machine> <project>/<agent> set its busy, unproductive, or coalescing limit
388
391
  (change its count/settings, pause scaling, pin, or bench the agent)
389
- b9s-admin agent move <project>/<agent> --to <machine> --sandbox <mode> --from local|<ssh host> [--dir <path>|auto]
392
+ b9s-admin agent move <project>/<agent> (--to <machine> --sandbox <mode> | --operation <id>) --from local|<ssh host> [--dir <path>|auto]
390
393
  [--harness codex|claude-code] [--provider anthropic|deepseek] [--carry note|thread]
391
394
  [--model m] [--effort e] [--wait min] [--force --confirm-force <project>/<agent>]
392
- opens a server move operation, checks source worktrees, transfers thread/note plus local agent state over SSH,
395
+ creates a move or continues the requested operation from the console; stored options are loaded and explicit options must match
396
+ checks source worktrees, transfers thread/note plus local agent state over SSH,
393
397
  refuses newer destination state and avoids duplicate Codex hooks under managed policy,
394
398
  then commits the session only after handoff succeeds; work left on the source requires both flags
395
399
  b9s-admin machine label <name> <label...> [--remove a,b] what cannot be measured (lab-lan, builds); pools' --needs match it
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.101";
1
+ export const CLI_VERSION = "0.12.103";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.101",
3
+ "version": "0.12.103",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {