benignswarm 0.12.92 → 0.12.94

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.
@@ -2,8 +2,9 @@ import { spawn, spawnSync } from "node:child_process";
2
2
  import { closeSync, existsSync, mkdirSync, openSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
4
  import { dirname, join as joinPath } from "node:path";
5
- import { bool, str } from "../args.js";
6
- import { agentRef, configRoot, loadAgent } from "../config.js";
5
+ import { bool, repeated, str } from "../args.js";
6
+ import { configRoot } from "../config.js";
7
+ import { startAgentIdentity, startEnrollmentIdentity, startWritableRoots } from "../start-options.js";
7
8
  import { CliError } from "../errors.js";
8
9
  import { requireInstall } from "../install.js";
9
10
  import { bindSession, codexArchivedRollout, codexRollout } from "../sessions.js";
@@ -15,7 +16,9 @@ import { beginTurnGuardAttempt, completePendingTurnGuard, installWatcherService
15
16
  import { randomUUID } from "node:crypto";
16
17
  import { HARNESS_BIN, HARNESS_LABEL, assertClaudeSelfCheck, claudeCodePath, claudeResultError, claudeResultFile, claudeSandboxEnv, claudeSettings, claudeTranscript, claudeTurnArgs, dshPath, dshResultError, dshSessionFromEvents, dshSettings, dshTurnLog, probeFor } from "../harnesses.js";
17
18
  import { claudeTurnEnv } from "../providers.js";
18
- import { DEFAULT_TURNS_PER_HOUR } from "../turn-guard.js";
19
+ import { DEFAULT_TURNS_PER_HOUR, MAX_TURNS_PER_HOUR } from "../turn-guard.js";
20
+ import { antigravityConversationDb, antigravityLog, antigravityResumeCommand, antigravitySettings, antigravityTotalTokens, antigravityTurnArgs, antigravityTurnEnv, runAntigravityTurn } from "../antigravity.js";
21
+ import { configureGitCredentialForWorktree } from "./git-credential.js";
19
22
  const SANDBOXES = ["read-only", "workspace-write", "danger-full-access"];
20
23
  export const DEFAULT_CLAUDE_MAX_BUDGET_USD = 1;
21
24
  /**
@@ -23,15 +26,31 @@ export const DEFAULT_CLAUDE_MAX_BUDGET_USD = 1;
23
26
  * headless, with no app involved, so it works the same over ssh on a remote machine. It enrolls the
24
27
  * agent (with an invite token), starts its session with an onboarding turn, binds it so the hooks
25
28
  * deliver to it, and installs a turn-mode watcher that runs each later turn itself (Codex: `codex exec
26
- * resume`; Claude Code: `claude -p --resume`). `--thread` adopts an existing session instead. Learned
29
+ * resume`; Claude Code: `claude -p --resume`; Antigravity: `agy -p --conversation`). `--thread` adopts an existing session instead. Learned
27
30
  * from the Codex app's queue silently not delivering wake-ups (fabricbios luna-worker, ten hours).
28
31
  *
29
- * b9s start --harness codex|claude-code|dsh --as <name> --sandbox <mode> [--token bs_enroll_...]
30
- * [--thread <id>] [--model m] [--effort e] [--turn-timeout 180] [--interval 30] [--prune] [--dsh <path>]
32
+ * b9s start --harness codex|claude-code|dsh|antigravity --as <name> --sandbox <mode> [--token bs_enroll_...]
33
+ * [--thread <id>] [--model m] [--effort e] [--turn-timeout 180] [--interval 30] [--prune] [--dsh <path>] [--agy <path>]
31
34
  */
32
35
  export async function codexStart(p, out) {
33
36
  return harnessStart(p, out, "codex");
34
37
  }
38
+ /** Builds the token enrollment call used by start; the token supplies project scope. */
39
+ export function startJoinArgs(p, harness, model) {
40
+ const identity = startEnrollmentIdentity(str(p.flags, "as") ?? "");
41
+ return {
42
+ parsed: {
43
+ ...p,
44
+ flags: {
45
+ ...p.flags,
46
+ as: identity.name,
47
+ vendor: harness,
48
+ model,
49
+ },
50
+ },
51
+ ...(identity.project ? { expectedProject: identity.project } : {}),
52
+ };
53
+ }
35
54
  export async function harnessStart(p, out, harness) {
36
55
  const label = HARNESS_LABEL[harness];
37
56
  const cmd = harness === "codex" ? "codex start" : "start";
@@ -42,12 +61,14 @@ export async function harnessStart(p, out, harness) {
42
61
  // No default: what a headless agent may touch on this machine is the operator's call, every time.
43
62
  if (!sandbox || !SANDBOXES.includes(sandbox))
44
63
  throw new CliError("usage", `${cmd} needs --sandbox <${SANDBOXES.join("|")}>: what the agent may do on this machine, since a headless turn cannot ask for approval`);
64
+ if (harness === "antigravity" && sandbox === "read-only")
65
+ throw new CliError("unsupported", "Antigravity has no read-only permission mode; use workspace-write or danger-full-access");
45
66
  const turnTimeout = Number(str(p.flags, "turn-timeout") ?? "180");
46
67
  if (!Number.isInteger(turnTimeout) || turnTimeout < 5)
47
68
  throw new CliError("usage", "--turn-timeout must be a whole number of minutes, at least 5");
48
69
  const turnsPerHour = Number(str(p.flags, "turns-per-hour") ?? String(DEFAULT_TURNS_PER_HOUR));
49
- if (!Number.isInteger(turnsPerHour) || turnsPerHour < 1 || turnsPerHour > DEFAULT_TURNS_PER_HOUR)
50
- throw new CliError("usage", `--turns-per-hour must be a whole number between 1 and ${DEFAULT_TURNS_PER_HOUR}`);
70
+ if (!Number.isInteger(turnsPerHour) || turnsPerHour < 1 || turnsPerHour > MAX_TURNS_PER_HOUR)
71
+ throw new CliError("usage", `--turns-per-hour must be a whole number between 1 and ${MAX_TURNS_PER_HOUR}`);
51
72
  const interval = Number(str(p.flags, "interval") ?? "30");
52
73
  if (!Number.isInteger(interval) || interval < 5)
53
74
  throw new CliError("usage", "--interval must be an integer number of seconds, at least 5");
@@ -56,54 +77,69 @@ export async function harnessStart(p, out, harness) {
56
77
  const dshOverride = str(p.flags, "dsh");
57
78
  if (harness !== "dsh" && dshOverride)
58
79
  throw new CliError("usage", "--dsh is only valid with --harness dsh");
80
+ const agyOverride = str(p.flags, "agy");
81
+ if (harness !== "antigravity" && agyOverride)
82
+ throw new CliError("usage", "--agy is only valid with --harness antigravity");
59
83
  const providerName = str(p.flags, "provider") ?? "anthropic";
60
84
  if (providerName !== "anthropic" && providerName !== "deepseek")
61
85
  throw new CliError("usage", "--provider must be anthropic or deepseek");
62
86
  const provider = providerName;
63
87
  if (provider === "deepseek" && harness !== "claude-code")
64
88
  throw new CliError("usage", "--provider deepseek requires --harness claude-code");
65
- const model = str(p.flags, "model") ?? (provider === "deepseek" ? "deepseek-flash" : undefined);
89
+ const providerModel = str(p.flags, "model") ?? (provider === "deepseek" ? "deepseek-flash" : undefined);
66
90
  const budgetFlag = str(p.flags, "max-budget-usd");
67
91
  if (budgetFlag !== undefined && (harness !== "claude-code" || sandbox !== "workspace-write"))
68
92
  throw new CliError("usage", "--max-budget-usd is only valid for Claude Code workspace-write sessions");
69
93
  const maxBudgetUsd = budgetFlag === undefined ? DEFAULT_CLAUDE_MAX_BUDGET_USD : Number(budgetFlag);
70
94
  if (harness === "claude-code" && sandbox === "workspace-write" && (!Number.isFinite(maxBudgetUsd) || maxBudgetUsd <= 0))
71
95
  throw new CliError("usage", "--max-budget-usd must be a positive dollar amount");
96
+ const model = providerModel;
97
+ if (harness === "antigravity" && !model)
98
+ throw new CliError("usage", "--model is required with --harness antigravity (for example gemini-4-hydrogen-low)");
72
99
  const bin = harness === "dsh"
73
100
  ? dshPath(dshOverride)
74
- : harness === "claude-code" && sandbox === "workspace-write"
75
- ? claudeCodePath() ?? (() => { throw new CliError("not_found", "Claude Code was not found on PATH or under ~/.local/share/claude/versions; add the native installer's active version to PATH or install Claude Code with `npm i -g @anthropic-ai/claude-code`"); })()
76
- : which(HARNESS_BIN[harness], harness === "codex" ? "install the Codex CLI (npm i -g @openai/codex)" : "install Claude Code (npm i -g @anthropic-ai/claude-code)");
101
+ : harness === "antigravity"
102
+ ? agyOverride ?? which(HARNESS_BIN[harness], "install Antigravity CLI (agy) and log in on this machine")
103
+ : harness === "claude-code" && sandbox === "workspace-write"
104
+ ? claudeCodePath() ?? (() => { throw new CliError("not_found", "Claude Code was not found on PATH or under ~/.local/share/claude/versions; add the native installer's active version to PATH or install Claude Code with `npm i -g @anthropic-ai/claude-code`"); })()
105
+ : which(HARNESS_BIN[harness], harness === "codex" ? "install the Codex CLI (npm i -g @openai/codex)" : "install Claude Code (npm i -g @anthropic-ai/claude-code)");
77
106
  if (!bin)
78
107
  throw new CliError("not_found", "DeepSeek Harness CLI dsh was not found; install DeepSeek Harness or pass --dsh <path>");
79
108
  if (harness === "dsh" && !existsSync(bin))
80
109
  throw new CliError("not_found", `DeepSeek Harness CLI ${bin} does not exist; pass --dsh <path> to its runtime/cli/bin/dsh`);
81
110
  const effort = str(p.flags, "effort");
82
- // The machine's toolchain and job folders a sandboxed agent may also write (b9s-admin machine writable).
83
- const writable = (str(p.flags, "writable") ?? "").split(",").map((w) => w.trim()).filter(Boolean).map((w) => (w.startsWith("~/") ? joinPath(homedir(), w.slice(2)) : w));
84
- if (writable.some((w) => !w.startsWith("/")))
85
- throw new CliError("usage", "--writable takes absolute or ~/ paths, comma separated");
111
+ const requestedAdopt = str(p.flags, "thread") ?? str(p.flags, "session");
112
+ // Machine-configured folders and explicit extra roots are combined with existing package caches
113
+ // only for workspace-write. Full-access sessions keep their previous root settings.
114
+ const machineWritable = (str(p.flags, "writable") ?? "").split(",").map((w) => w.trim()).filter(Boolean);
115
+ const explicitWritable = repeated(p, "writable-root").map((w) => w.trim());
116
+ const writable = startWritableRoots(sandbox, machineWritable, explicitWritable);
86
117
  // Refuses a sandbox the harness cannot honour before anything is enrolled.
87
- const settings = harness === "codex"
118
+ let settings = harness === "codex"
88
119
  ? codexSettings(sandbox, model, effort, process.cwd(), configRoot(), [...writable, ...ownWorktreeGitDir(process.cwd())])
89
120
  : harness === "dsh"
90
121
  ? dshSettings(sandbox, process.cwd(), configRoot(), [...writable, ...ownWorktreeGitDir(process.cwd())])
91
- : claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable);
122
+ : harness === "claude-code" ? claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable) : [];
92
123
  const providerEnv = { ...claudeTurnEnv(harness === "claude-code" ? provider : undefined, model), ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}) };
93
- if (harness === "claude-code" && sandbox === "workspace-write")
124
+ if ((harness === "claude-code" || harness === "antigravity") && sandbox === "workspace-write")
94
125
  configureHttpsOriginForWorktree(process.cwd());
95
126
  // 1. Who: enroll with the invite token, or use credentials already on this machine.
96
127
  const lines = [];
97
128
  const token = str(p.flags, "token");
98
129
  if (token) {
99
130
  const joined = [];
100
- await join({ ...p, flags: { ...p.flags, vendor: harness, model } }, { json: false, print: (h) => joined.push(h) });
131
+ const enrollment = startJoinArgs(p, harness, model);
132
+ await join(enrollment.parsed, { json: false, print: (h) => joined.push(h) }, enrollment.expectedProject);
101
133
  lines.push(joined.join("\n").split("\n")[0]);
102
134
  }
103
- const creds = loadAgent(name);
135
+ const { credentials: creds, ref } = startAgentIdentity(name);
136
+ if ((harness === "claude-code" || harness === "antigravity") && sandbox === "workspace-write")
137
+ configureHttpsOriginForWorktree(process.cwd());
138
+ await configureGitCredentialForWorktree(process.cwd(), creds);
104
139
  if (creds.vendor && creds.vendor !== harness)
105
- throw new CliError("vendor_mismatch", `${agentRef(creds)} is saved as ${creds.vendor}, not ${harness}`);
106
- const ref = agentRef(creds);
140
+ throw new CliError("vendor_mismatch", `${ref} is saved as ${creds.vendor}, not ${harness}`);
141
+ if (harness === "antigravity")
142
+ settings = antigravitySettings(sandbox, process.cwd(), configRoot(), new URL(creds.url).host, [...writable, ...ownWorktreeGitDir(process.cwd())]);
107
143
  const priorState = readState(ref);
108
144
  if (priorState.turn_guard?.fault) {
109
145
  const fault = priorState.turn_guard.fault;
@@ -111,7 +147,7 @@ export async function harnessStart(p, out, harness) {
111
147
  }
112
148
  const initialTurnPending = priorState.turn_guard?.turns.some((attempt) => attempt.productive === null) ?? false;
113
149
  const rememberedSession = initialTurnPending && priorState.harness_session?.harness === harness ? priorState.harness_session.session_id : null;
114
- const adopt = str(p.flags, "thread") ?? str(p.flags, "session") ?? rememberedSession ?? undefined;
150
+ const adopt = requestedAdopt ?? rememberedSession ?? undefined;
115
151
  requireInstall();
116
152
  // 2. Its session: adopt one, or start one headless with an onboarding turn.
117
153
  let session;
@@ -119,6 +155,8 @@ export async function harnessStart(p, out, harness) {
119
155
  let firstTurnLog = null;
120
156
  if (harness === "dsh")
121
157
  firstTurnLog = dshTurnLog(ref);
158
+ if (harness === "antigravity")
159
+ firstTurnLog = antigravityLog(ref);
122
160
  if (adopt) {
123
161
  session = adopt.toLowerCase();
124
162
  if (harness === "codex") {
@@ -138,11 +176,18 @@ export async function harnessStart(p, out, harness) {
138
176
  }
139
177
  lines.push(`Adopted Claude Code session ${session}. Do not resume it in a terminal while the watcher runs it: two clients on one session conflict.`);
140
178
  }
141
- else {
179
+ else if (harness === "dsh") {
142
180
  mkdirSync(joinPath(configRoot(), "logs"), { recursive: true });
143
181
  closeSync(openSync(dshTurnLog(ref), "a"));
144
182
  lines.push(`Adopted DeepSeek Harness session ${session}. Do not resume it elsewhere while the watcher runs it: two clients on one session conflict.`);
145
183
  }
184
+ else {
185
+ if (!existsSync(antigravityConversationDb(session)))
186
+ throw new CliError("not_found", `no Antigravity conversation database for ${session} under ~/.gemini/antigravity-cli/conversations`);
187
+ lines.push(`Adopted Antigravity conversation ${session}. Do not resume it elsewhere while the watcher runs it: two clients on one conversation conflict.`);
188
+ }
189
+ if (harness === "antigravity" && sandbox === "workspace-write")
190
+ await runAntigravitySandboxSelfCheck(ref, bin, settings, process.cwd(), session, model, effort, turnTimeout * 60, firstTurnLog, turnsPerHour);
146
191
  }
147
192
  }
148
193
  else {
@@ -154,7 +199,7 @@ export async function harnessStart(p, out, harness) {
154
199
  }
155
200
  const logDir = joinPath(configRoot(), "logs");
156
201
  mkdirSync(logDir, { recursive: true });
157
- firstTurnLog = harness === "dsh" ? dshTurnLog(ref) : harness === "claude-code" ? claudeResultFile(ref) : joinPath(logDir, `${harness}.${ref.replace("/", ".")}.first-turn.jsonl`);
202
+ firstTurnLog = harness === "dsh" ? dshTurnLog(ref) : harness === "claude-code" ? claudeResultFile(ref) : harness === "antigravity" ? antigravityLog(ref) : joinPath(logDir, `${harness}.${ref.replace("/", ".")}.first-turn.jsonl`);
158
203
  const prompt = [
159
204
  `[b9s] You are ${ref}, a BenignSwarm agent, started headless by \`b9s ${cmd}\`; nobody is typing to you.`,
160
205
  `Your watcher starts a turn for you whenever something needs you, so end your turn when nothing is left to do.`,
@@ -176,6 +221,14 @@ export async function harnessStart(p, out, harness) {
176
221
  initialPid = started.pid;
177
222
  lines.push(`Started DeepSeek Harness session ${session}; its first turn (reading its role and inbox) is running, event log: ${firstTurnLog}`);
178
223
  }
224
+ else if (harness === "antigravity") {
225
+ const started = runAntigravityTurn(bin, antigravityTurnArgs(prompt, model, effort, turnTimeout * 60, settings), firstTurnLog, process.cwd(), ref, undefined, undefined, antigravityTurnEnv(sandbox));
226
+ session = started.conversation;
227
+ await completePendingTurnGuard(ref, probeFor(harness, session, ref), (message) => diagnostic.push(message), started.output, antigravityTokenTotal(started.record.result?.usage));
228
+ lines.push(`Started Antigravity conversation ${session}; its first turn (reading its role and inbox) completed, JSON turn log: ${firstTurnLog}`);
229
+ if (sandbox === "workspace-write")
230
+ await runAntigravitySandboxSelfCheck(ref, bin, settings, process.cwd(), session, model, effort, turnTimeout * 60, firstTurnLog, turnsPerHour, antigravityTurnEnv(sandbox));
231
+ }
179
232
  else {
180
233
  // Claude Code takes the session id from us, so nothing has to be read back from its output.
181
234
  session ??= randomUUID();
@@ -198,8 +251,10 @@ export async function harnessStart(p, out, harness) {
198
251
  // hook knows the agent from BSCHAT_AGENT (the watcher sets it for every turn), so it needs no map.
199
252
  if (harness === "codex")
200
253
  bindSession("codex", session, ref);
201
- const transcript = harness === "dsh" ? dshTurnLog(ref) : harness === "claude-code" ? claudeTranscript(session) ?? firstTurnLog ?? "" : codexRollout(session) ?? firstTurnLog ?? "";
202
- writeState(ref, { ...readState(ref), harness_session: { harness, transcript, session_id: session, at: Date.now(), ...(harness === "claude-code" ? { provider } : {}), ...(initialPid ? { initial_pid: initialPid } : {}) } });
254
+ if (harness === "antigravity")
255
+ bindSession("antigravity", session, ref);
256
+ const transcript = harness === "dsh" ? dshTurnLog(ref) : harness === "antigravity" ? antigravityLog(ref) : harness === "claude-code" ? claudeTranscript(session) ?? firstTurnLog ?? "" : codexRollout(session) ?? firstTurnLog ?? "";
257
+ writeState(ref, { ...readState(ref), harness_session: { harness, transcript, session_id: session, at: Date.now(), ...(model ? { model } : {}), ...(harness === "claude-code" ? { provider } : {}), ...(initialPid ? { initial_pid: initialPid } : {}) } });
203
258
  // A session adopted here may end in a usage-limit error from the machine it came from, written in
204
259
  // that machine's local time ("3:32 PM" Central read as UTC on ronald: six hours off). Only errors
205
260
  // from turns on this machine pause it; if the account is still limited, the next turn says so here.
@@ -210,8 +265,10 @@ export async function harnessStart(p, out, harness) {
210
265
  ? [bin, "exec", "resume", session, ...settings].map(shq).join(" ") + " {text}"
211
266
  : harness === "dsh"
212
267
  ? dshResumeCommand(bin, session, settings, dshTurnLog(ref))
213
- // The result goes to a file the watcher reads when the turn ends: Claude Code can exit 0 with is_error set.
214
- : `${shq(bin)} -p {text} ${[...settings, ...(sandbox === "workspace-write" ? claudeTurnArgs(maxBudgetUsd) : []), "--resume", session, "--output-format", "json"].map(shq).join(" ")} > ${shq(claudeResultFile(ref))}`;
268
+ : harness === "antigravity"
269
+ ? antigravityResumeCommand(bin, session, model, effort, turnTimeout * 60, settings, antigravityLog(ref))
270
+ // The result goes to a file the watcher reads when the turn ends: Claude Code can exit 0 with is_error set.
271
+ : `${shq(bin)} -p {text} ${[...settings, ...(sandbox === "workspace-write" ? claudeTurnArgs(maxBudgetUsd) : []), "--resume", session, "--output-format", "json"].map(shq).join(" ")} > ${shq(claudeResultFile(ref))}`;
215
272
  const watcherOut = [];
216
273
  // Scratch space beside the checkout, not the system's /tmp: on a machine the checkout lives on the
217
274
  // work volume, the folder is inside what the sandbox may write, and it survives a reboot. Learned
@@ -219,7 +276,7 @@ export async function harnessStart(p, out, harness) {
219
276
  // volume had 750 GB free, and which empties /tmp at every boot.
220
277
  const tmp = sessionTmpDir(process.cwd(), creds.agent);
221
278
  mkdirSync(tmp, { recursive: true });
222
- installWatcherService(ref, exec, interval, Number(str(p.flags, "follow-delay") ?? "300"), { TMPDIR: tmp, ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}) }, undefined, { json: false, print: (h) => watcherOut.push(h) }, bool(p.flags, "prune"), { harness, session, timeout: turnTimeout, turnsPerHour, provider, model });
279
+ installWatcherService(ref, exec, interval, Number(str(p.flags, "follow-delay") ?? "300"), { TMPDIR: tmp, ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}), ...(harness === "antigravity" ? { BSCHAT_HARNESS: "antigravity", BSCHAT_ANTIGRAVITY_SANDBOX: sandbox, BSCHAT_MODEL: model, ...(effort ? { BSCHAT_EFFORT: effort } : {}) } : {}) }, undefined, { json: false, print: (h) => watcherOut.push(h) }, bool(p.flags, "prune"), { harness, session, timeout: turnTimeout, turnsPerHour, provider, model });
223
280
  const wl = watcherOut.join("\n").split("\n");
224
281
  lines.push(wl[0].replace(/^Wrote /, "Watcher: wrote "), ...wl.filter((l) => l.startsWith("Linger is off")));
225
282
  // 5. Hooks.
@@ -234,13 +291,17 @@ export async function harnessStart(p, out, harness) {
234
291
  else if (harness === "dsh") {
235
292
  lines.push("DeepSeek Harness runs the headless profile without an interactive approval prompt; b9s identifies this agent through BSCHAT_AGENT on each turn.");
236
293
  }
294
+ else if (harness === "antigravity") {
295
+ lines.push("Antigravity runs headless turns with the machine's cached agy login; b9s binds this conversation and records JSON token usage.");
296
+ }
237
297
  else {
238
298
  lines.push(`Claude Code runs b9s's hooks from this checkout's .claude/settings.local.json (written by join).`);
239
299
  }
240
- lines.push(`Follow it: tail -f ~/.b9s/logs/watch.${ref.replace("/", ".")}.err.log; ${harness === "codex" ? `read its thread with codex resume ${session}` : harness === "dsh" ? `read its events in ${dshTurnLog(ref)} or resume with dsh --profile headless --json --session-id ${session}` : `read its transcript under ~/.claude/projects (session ${session})`} only while no turn is running.`);
300
+ lines.push(`Follow it: tail -f ~/.b9s/logs/watch.${ref.replace("/", ".")}.err.log; ${harness === "codex" ? `read its thread with codex resume ${session}` : harness === "dsh" ? `read its events in ${dshTurnLog(ref)} or resume with dsh --profile headless --json --session-id ${session}` : harness === "antigravity" ? `inspect its recorded turns in ${antigravityLog(ref)}` : `read its transcript under ~/.claude/projects (session ${session})`} only while no turn is running.`);
241
301
  lines.push(harness === "dsh"
242
302
  ? `DeepSeek Harness failures, including balance or rate limits, are recorded and retried after the ordinary 5-minute backoff; no reset time is inferred from their text.`
243
- : `If the ${label} account hits its usage limit, the watcher pauses turns until the time ${label} gives; after switching to an account with quota, resume at once: b9s unpause --as ${ref}`);
303
+ : harness === "antigravity" ? `Antigravity failures, including quota errors, are recorded verbatim and retried after the ordinary 5-minute backoff; no reset time is inferred from their text.`
304
+ : `If the ${label} account hits its usage limit, the watcher pauses turns until the time ${label} gives; after switching to an account with quota, resume at once: b9s unpause --as ${ref}`);
244
305
  out.print(lines.join("\n"), { agent: ref, harness, provider, thread: session, session, sandbox, model: model ?? null, effort: effort ?? null, exec, first_turn_log: firstTurnLog, untrusted_hooks: missing });
245
306
  }
246
307
  export const dshStartArgs = (settings) => ["--profile", "headless", "--json", ...settings, "-"];
@@ -415,6 +476,63 @@ export async function runGuardedClaudeSandboxSelfCheck(ref, turnsPerHour, bin, s
415
476
  if (fault)
416
477
  throw new CliError("turn_mode_fault", `turn mode stopped after ${fault.consecutive_unproductive} consecutive turns without a BenignSwarm call; estimated tokens spent: ${fault.estimated_tokens}; last output: ${fault.output_tail || "(empty)"}`);
417
478
  }
479
+ function antigravityTokenTotal(usage) {
480
+ return antigravityTotalTokens(usage);
481
+ }
482
+ export function assertAntigravitySelfCheck(output) {
483
+ let outer;
484
+ try {
485
+ outer = JSON.parse(output);
486
+ }
487
+ catch {
488
+ throw new CliError("sandbox_self_check_failed", `Antigravity workspace-write self-check returned invalid JSON: ${output.trim().slice(-1500)}; watcher was not enabled`);
489
+ }
490
+ if (typeof outer.response !== "string")
491
+ throw new CliError("sandbox_self_check_failed", "Antigravity workspace-write self-check returned no response; watcher was not enabled");
492
+ let checks;
493
+ try {
494
+ checks = JSON.parse(outer.response);
495
+ }
496
+ catch {
497
+ throw new CliError("sandbox_self_check_failed", `Antigravity self-check response was not the required JSON: ${outer.response.slice(-1500)}; watcher was not enabled`);
498
+ }
499
+ if (checks.b9s_me?.status !== 0 || !checks.b9s_me.output?.includes("agent:")) {
500
+ throw new CliError("sandbox_self_check_failed", `Antigravity sandbox could not run b9s me${checks.b9s_me?.status === undefined ? "" : ` (exit ${checks.b9s_me.status})`}: ${checks.b9s_me?.output ?? "no output"}; watcher was not enabled`);
501
+ }
502
+ if (checks.git_ls_remote_origin?.status !== 0) {
503
+ throw new CliError("sandbox_self_check_failed", `Antigravity sandbox git ls-remote origin failed${checks.git_ls_remote_origin?.status === undefined ? "" : ` (exit ${checks.git_ls_remote_origin.status})`}: ${checks.git_ls_remote_origin?.output ?? "no output"}; watcher was not enabled`);
504
+ }
505
+ }
506
+ /** Run the two connectivity checks through the real model tools inside the per-turn sandbox. */
507
+ export async function runAntigravitySandboxSelfCheck(ref, bin, settings, cwd, session, model, effort, timeoutSeconds, logPath, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = antigravityTurnEnv("workspace-write")) {
508
+ const diagnostic = [];
509
+ if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (message) => diagnostic.push(message)))) {
510
+ throw new CliError("turn_mode_fault", diagnostic.at(-1) ?? "turn mode guard refused the Antigravity sandbox self-check");
511
+ }
512
+ const prompt = [
513
+ "BenignSwarm sandbox startup check. Use your terminal tool to execute these two commands separately, exactly as written:",
514
+ "1. b9s me",
515
+ "2. git ls-remote origin",
516
+ "Capture each real exit code and complete stdout/stderr. Do not infer or invent results.",
517
+ 'Return only one JSON object with this shape: {"b9s_me":{"status":0,"output":"..."},"git_ls_remote_origin":{"status":0,"output":"..."}}.',
518
+ ].join("\n");
519
+ let started;
520
+ try {
521
+ started = runAntigravityTurn(bin, antigravityTurnArgs(prompt, model, effort, timeoutSeconds, settings, session), logPath, cwd, ref, session, undefined, env);
522
+ }
523
+ catch (error) {
524
+ await completePendingTurnGuard(ref, probeFor("antigravity", session, ref), (message) => diagnostic.push(message), error.message, null);
525
+ const fault = readState(ref).turn_guard?.fault;
526
+ if (fault)
527
+ throw new CliError("turn_mode_fault", `turn mode stopped after ${fault.consecutive_unproductive} consecutive turns without a BenignSwarm call; estimated tokens spent: ${fault.estimated_tokens}; last output: ${fault.output_tail || "(empty)"}`);
528
+ throw error;
529
+ }
530
+ await completePendingTurnGuard(ref, probeFor("antigravity", session, ref), (message) => diagnostic.push(message), started.output, antigravityTokenTotal(started.record.result?.usage));
531
+ const fault = readState(ref).turn_guard?.fault;
532
+ if (fault)
533
+ throw new CliError("turn_mode_fault", `turn mode stopped after ${fault.consecutive_unproductive} consecutive turns without a BenignSwarm call; estimated tokens spent: ${fault.estimated_tokens}; last output: ${fault.output_tail || "(empty)"}`);
534
+ assertAntigravitySelfCheck(started.output);
535
+ }
418
536
  /**
419
537
  * The Codex settings a headless turn runs with. Under workspace-write the agent still has to reach
420
538
  * the API and write its own b9s state (~/.b9s), and `wu start` puts unit worktrees beside the
@@ -0,0 +1,128 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { Client } from "../client.js";
3
+ import { loadAgent, resolveAgentName } from "../config.js";
4
+ import { CliError } from "../errors.js";
5
+ import { requireInstall } from "../install.js";
6
+ function credentialInput(input) {
7
+ const result = {};
8
+ for (const line of input.split(/\r?\n/)) {
9
+ if (!line)
10
+ break;
11
+ const i = line.indexOf("=");
12
+ if (i < 0)
13
+ continue;
14
+ const key = line.slice(0, i);
15
+ if (key === "protocol" || key === "host" || key === "path")
16
+ result[key] = line.slice(i + 1);
17
+ }
18
+ return result;
19
+ }
20
+ function repositoryPath(path) {
21
+ if (!path)
22
+ return null;
23
+ const normalized = path.replace(/^\//, "").replace(/\.git$/i, "");
24
+ return /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(normalized) ? normalized.toLowerCase() : null;
25
+ }
26
+ export async function credentialResponse(input, api) {
27
+ const request = credentialInput(input);
28
+ if (request.protocol !== "https" || request.host?.toLowerCase() !== "github.com")
29
+ return "";
30
+ const wanted = repositoryPath(request.path);
31
+ if (!wanted)
32
+ return "";
33
+ const metadata = await api("GET", "");
34
+ if (!metadata.linked || !metadata.repository) {
35
+ throw new CliError("github_not_connected", "GitHub is not connected for this project. Connect GitHub in the console to enable repository access.");
36
+ }
37
+ const linked = `${metadata.repository.owner}/${metadata.repository.name}`.toLowerCase();
38
+ if (wanted !== linked)
39
+ return "";
40
+ const credential = await api("POST", "", {});
41
+ return `username=${credential.username}\npassword=${credential.password}\n\n`;
42
+ }
43
+ export async function gitCredentialOperation(operation, input, api) {
44
+ if (operation === "store" || operation === "erase")
45
+ return "";
46
+ if (operation !== "get")
47
+ throw new CliError("usage", "git-credential get|store|erase");
48
+ return credentialResponse(input, api);
49
+ }
50
+ export async function gitCredential(p) {
51
+ const operation = p.positionals[1];
52
+ const chunks = [];
53
+ for await (const chunk of process.stdin)
54
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
55
+ const input = Buffer.concat(chunks).toString("utf8");
56
+ if (operation === "store" || operation === "erase")
57
+ return;
58
+ if (operation !== "get")
59
+ throw new CliError("usage", "git-credential get|store|erase");
60
+ const agent = loadAgent(resolveAgentName(undefined));
61
+ if (!agent.project)
62
+ throw new CliError("github_not_connected", "GitHub credential helper requires a project-scoped agent identity.");
63
+ const client = Client.forAgent(agent, undefined, { presence: false });
64
+ const base = `/projects/${encodeURIComponent(agent.project)}/git-credentials`;
65
+ const result = await gitCredentialOperation(operation, input, (method, _path, body) => client.call(method, base, body));
66
+ if (result)
67
+ process.stdout.write(result);
68
+ }
69
+ function remoteRepository(url) {
70
+ const scp = /^git@github\.com:([^?#]+)$/i.exec(url);
71
+ const ssh = /^ssh:\/\/(?:git@)?github\.com\/([^?#]+)$/i.exec(url);
72
+ const https = /^https:\/\/github\.com\/([^?#]+)$/i.exec(url);
73
+ const match = scp ?? ssh ?? https;
74
+ if (!match)
75
+ return null;
76
+ const credentialPath = match[1].replace(/^\//, "");
77
+ const path = repositoryPath(credentialPath);
78
+ if (!path)
79
+ return null;
80
+ return { sshPrefix: scp ? "git@github.com:" : ssh ? "ssh://git@github.com/" : null, path, credentialPath };
81
+ }
82
+ function gitConfig(cwd, args) {
83
+ const result = spawnSync("git", ["config", ...args], { cwd, encoding: "utf8" });
84
+ if (result.status !== 0)
85
+ throw new CliError("git_credential_config", (result.stderr ?? "").trim() || "could not configure the worktree Git credential helper");
86
+ }
87
+ function shellQuote(value) { return `'${value.replace(/'/g, `'\\''`)}'`; }
88
+ /** Adds the exact repo helper only when origin is the repository linked to this project. */
89
+ export async function configureGitCredentialForWorktree(cwd, creds, lookup, installBin) {
90
+ if (!creds.project)
91
+ return;
92
+ const client = Client.forAgent(creds, undefined, { presence: false });
93
+ const metadata = lookup
94
+ ? await lookup()
95
+ : await client.call("GET", `/projects/${encodeURIComponent(creds.project)}/git-credentials`);
96
+ if (!metadata.linked || !metadata.repository)
97
+ return;
98
+ // Read the configured value, not `remote get-url`: that command expands existing insteadOf
99
+ // rewrites and would hide the SSH origin when this startup runs a second time.
100
+ const remote = spawnSync("git", ["config", "--get", "remote.origin.url"], { cwd, encoding: "utf8" });
101
+ if (remote.status !== 0)
102
+ throw new CliError("git_origin", `cannot read origin in ${cwd}: ${(remote.stderr ?? "").trim() || "git remote get-url origin failed"}`);
103
+ const parsed = remoteRepository(remote.stdout.trim());
104
+ if (!parsed)
105
+ return;
106
+ if (`${metadata.repository.owner}/${metadata.repository.name}`.toLowerCase() !== parsed.path)
107
+ return;
108
+ const enabled = spawnSync("git", ["config", "extensions.worktreeConfig", "true"], { cwd, encoding: "utf8" });
109
+ if (enabled.status !== 0)
110
+ throw new CliError("git_credential_config", (enabled.stderr ?? "").trim() || "could not enable per-worktree Git configuration");
111
+ if (parsed.sshPrefix) {
112
+ const rewriteKey = `url.https://github.com/${parsed.credentialPath}.insteadOf`;
113
+ const sshOrigin = `${parsed.sshPrefix}${parsed.credentialPath}`;
114
+ const existing = spawnSync("git", ["config", "--worktree", "--get-all", rewriteKey], { cwd, encoding: "utf8" });
115
+ if (!(existing.stdout ?? "").split(/\r?\n/).includes(sshOrigin))
116
+ gitConfig(cwd, ["--worktree", "--add", rewriteKey, sshOrigin]);
117
+ }
118
+ // useHttpPath makes Git send this exact remote path (including an optional .git suffix).
119
+ // Matching the remote spelling and suffix keeps this helper out of other repositories.
120
+ const repoUrl = `https://github.com/${parsed.credentialPath}`;
121
+ const helperKey = `credential.${repoUrl}.helper`;
122
+ gitConfig(cwd, ["--worktree", "--replace-all", helperKey, ""]);
123
+ gitConfig(cwd, ["--worktree", "--add", helperKey, `!${shellQuote(installBin ?? requireInstall().bin)} git-credential`]);
124
+ gitConfig(cwd, ["--worktree", "credential.https://github.com.useHttpPath", "true"]);
125
+ }
126
+ export async function gitCredentialMain(p) {
127
+ return gitCredential(p);
128
+ }
@@ -11,6 +11,7 @@ import { codexHooksPath } from "./codex.js";
11
11
  import { claudeCheckoutOwner, claudeCheckoutTaken, withCodexHooks, HARNESSES, findIdentityFile, installForHarness, normalizeVendor, readIdentityFile, writeIdentity } from "../harness.js";
12
12
  import { detectVendor } from "../vendor.js";
13
13
  import { CLI_VERSION } from "../version.js";
14
+ import { assertEnrolledStartProject } from "../start-options.js";
14
15
  function repoRoot() {
15
16
  const r = spawnSync("git", ["rev-parse", "--show-toplevel"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
16
17
  return r.status === 0 ? r.stdout.trim() : process.cwd();
@@ -64,7 +65,7 @@ export async function setup(p, out) {
64
65
  const selfTest = harnessList(p, vendor).includes("claude-code") ? verifyClaudeHook(root, ref) : null;
65
66
  out.print(`b9s ${inst.version} for this machine: ${inst.bin}\nRecorded ${vendor} -> ${ref} in ${idPath}\nWrote: ${uniq.join(", ")}${selfTest ? `\n${selfTest}` : ""}`, { install: inst, identity: idPath, written: uniq, hook_verified: !!selfTest });
66
67
  }
67
- export async function join(p, out) {
68
+ export async function join(p, out, expectedProject) {
68
69
  const name = str(p.flags, "as") ?? process.env.BSCHAT_AGENT;
69
70
  if (!name)
70
71
  throw new CliError("usage", "join needs --as <agent-name> (the name you were given)");
@@ -107,6 +108,9 @@ export async function join(p, out) {
107
108
  if (!res.ok)
108
109
  throw new CliError(json.error ?? `http_${res.status}`, json.message ?? "join failed");
109
110
  const project = json.project ? json.project.name : null;
111
+ // Used internally by `b9s start --as project/name --token ...`: enrollment always
112
+ // submits the bare name, then verifies the token was actually scoped to that project.
113
+ assertEnrolledStartProject(expectedProject, project);
110
114
  const ref = agentRef({ project, agent: name });
111
115
  const path = saveAgent({ url, key: json.key, account: json.project ? json.project.id : "", project, agent: name, vendor, machine });
112
116
  const idPath = noBind ? null : writeIdentity(root, vendor, name, model, bool(p.flags, "replace"), project);
@@ -211,8 +211,8 @@ export async function machineAdmin(action, rest, p, out) {
211
211
  if (sub === "add") {
212
212
  const turnTimeout = str(p.flags, "turn-timeout");
213
213
  const turnsPerHour = str(p.flags, "turns-per-hour");
214
- if (turnsPerHour !== undefined && (!/^\d+$/.test(turnsPerHour) || Number(turnsPerHour) < 1 || Number(turnsPerHour) > 20))
215
- throw new CliError("usage", "--turns-per-hour must be a whole number from 1 to 20");
214
+ if (turnsPerHour !== undefined && (!/^\d+$/.test(turnsPerHour) || Number(turnsPerHour) < 1 || Number(turnsPerHour) > 60))
215
+ throw new CliError("usage", "--turns-per-hour must be a whole number from 1 to 60");
216
216
  const body = {
217
217
  project, agent, harness: str(p.flags, "harness") ?? "codex", provider: str(p.flags, "provider") ?? "anthropic", dir: str(p.flags, "dir"), sandbox: str(p.flags, "sandbox"),
218
218
  model: str(p.flags, "model"), effort: str(p.flags, "effort"), thread: str(p.flags, "thread"),
@@ -231,9 +231,16 @@ export async function machineAdmin(action, rest, p, out) {
231
231
  const r = await c.call("PATCH", `/machines/${machineName}/sessions/${project}/${agent}`, { resume_turns: true });
232
232
  return out.print(`${ref} on ${machineName}: turn mode resumed explicitly; its daemon applies the request within 30 s.`, r);
233
233
  }
234
+ if (sub === "thread") {
235
+ const thread = rest[3];
236
+ if (thread === undefined)
237
+ throw new CliError("usage", "machine session thread <machine> <project>/<agent> <thread-id|none>");
238
+ const r = await c.call("PATCH", `/machines/${machineName}/sessions/${project}/${agent}`, { thread: thread === "none" ? null : thread });
239
+ return out.print(`${ref} on ${machineName}: ${thread === "none" ? "thread cleared" : `thread set to ${thread}`}; its daemon applies the change within 30 s.`, r);
240
+ }
234
241
  if (sub === "limit") {
235
242
  const value = str(p.flags, "turns-per-hour");
236
- if (!value || !/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 20)
243
+ if (!value || !/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 60)
237
244
  throw new CliError("usage", "machine session limit <machine> <project>/<agent> --turns-per-hour <1..20>");
238
245
  const r = await c.call("PATCH", `/machines/${machineName}/sessions/${project}/${agent}`, { turns_per_hour: Number(value) });
239
246
  return out.print(`${ref} on ${machineName}: turn limit set to ${value} per hour; the daemon applies it within 30 s.`, r);
@@ -243,7 +250,7 @@ export async function machineAdmin(action, rest, p, out) {
243
250
  return out.print(`Removed ${ref} from ${machineName}; the agent and its thread stay.`, { removed: ref });
244
251
  }
245
252
  }
246
- throw new CliError("usage", "machine add <name> --ssh <host> | list | show <name> | remove <name> | session add|stop|start|remove <machine> <project>/<agent>");
253
+ throw new CliError("usage", "machine add <name> --ssh <host> | list | show <name> | remove <name> | session add|stop|start|resume|limit|thread|remove <machine> <project>/<agent> [...]");
247
254
  }
248
255
  /** `[tag=]harness:model[:effort][*weight][@provider]`, e.g. `luna=claude-code:deepseek-flash@deepseek`. */
249
256
  export function parseVariant(spec) {
@@ -266,7 +273,7 @@ export function repeated(argv, flag) {
266
273
  return out;
267
274
  }
268
275
  /**
269
- * pool set <project>/<name> --role r --variant spec [--variant ...] --count n --sandbox mode [--needs a,b] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..20]
276
+ * pool set <project>/<name> --role r --variant spec [--variant ...] --count n --sandbox mode [--needs a,b] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..60]
270
277
  * pool list [project] | show <project>/<name> | remove <project>/<name>
271
278
  */
272
279
  export async function poolAdmin(action, rest, p, out, argv) {
@@ -281,12 +288,12 @@ export async function poolAdmin(action, rest, p, out, argv) {
281
288
  const variants = repeated(argv, "variant").map(parseVariant);
282
289
  const count = Number(str(p.flags, "count"));
283
290
  if (!project || !name || !variants.length || !Number.isInteger(count))
284
- throw new CliError("usage", "pool set <project>/<name> --role <role> --variant [tag=]harness:model[:effort][*weight][@anthropic|deepseek] [--variant ...] --count <n> --sandbox <read-only|workspace-write|danger-full-access> [--needs label,label] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..20]");
291
+ throw new CliError("usage", "pool set <project>/<name> --role <role> --variant [tag=]harness:model[:effort][*weight][@anthropic|deepseek] [--variant ...] --count <n> --sandbox <read-only|workspace-write|danger-full-access> [--needs label,label] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..60]");
285
292
  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")) } : {}) };
286
293
  const tt = str(p.flags, "turn-timeout");
287
294
  const tph = str(p.flags, "turns-per-hour");
288
- if (tph !== undefined && (!/^\d+$/.test(tph) || Number(tph) < 1 || Number(tph) > 20))
289
- throw new CliError("usage", "--turns-per-hour must be a whole number from 1 to 20");
295
+ if (tph !== undefined && (!/^\d+$/.test(tph) || Number(tph) < 1 || Number(tph) > 60))
296
+ throw new CliError("usage", "--turns-per-hour must be a whole number from 1 to 60");
290
297
  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) } : {}), ...(tph ? { turns_per_hour: Number(tph) } : {}) });
291
298
  return out.print([...statusLines(r.pool), "Their machines' daemons start them within 30 s: b9s-admin machine show <machine>"].join("\n"), r);
292
299
  }