benignswarm 0.12.93 → 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.
@@ -1,57 +1,178 @@
1
1
  import { spawnSync } from "node:child_process";
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
- import { dirname, join } from "node:path";
2
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { basename, dirname, join } from "node:path";
4
5
  import { configRoot } from "./config.js";
5
6
  import { CliError } from "./errors.js";
6
- import { watcherPlists } from "./install.js";
7
- /**
8
- * Which agent each Antigravity conversation belongs to, on this machine. Antigravity's hooks are
9
- * configured per workspace, and one workspace often hosts several Antigravity agents (ester has
10
- * four), so the hook cannot take its identity from the workspace: it looks up the conversationId
11
- * every event carries. A conversation nobody bound gets nothing, never another agent's messages.
12
- */
13
- const file = () => join(configRoot(), "antigravity.json");
14
- const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
15
- function read() {
16
- if (!existsSync(file()))
17
- return { conversations: {} };
7
+ export function antigravityTotalTokens(usage) {
8
+ if (!usage)
9
+ return null;
10
+ if (typeof usage.total_tokens === "number" && Number.isFinite(usage.total_tokens) && usage.total_tokens >= 0)
11
+ return usage.total_tokens;
12
+ return (usage.input_tokens ?? 0) + (usage.output_tokens ?? 0) + (usage.thinking_tokens ?? 0) + (usage.cache_read_tokens ?? 0);
13
+ }
14
+ export const antigravityLog = (ref) => join(configRoot(), "logs", `antigravity.${ref.replace("/", ".")}.jsonl`);
15
+ export const antigravityConversationDb = (id, home = homedir()) => join(home, ".gemini", "antigravity-cli", "conversations", `${id}.db`);
16
+ const shq = (s) => (/^[\w./=:@-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
17
+ export function antigravitySettings(sandbox, cwd, b9sHome, apiHost, extraWritable = []) {
18
+ if (sandbox === "read-only")
19
+ throw new CliError("unsupported", "Antigravity has no read-only permission mode; use workspace-write or danger-full-access");
20
+ if (sandbox === "danger-full-access")
21
+ return ["--dangerously-skip-permissions"];
22
+ if (sandbox !== "workspace-write")
23
+ throw new CliError("usage", `unknown sandbox ${sandbox}`);
24
+ if (!/^[a-z0-9.-]+(?::\d+)?$/i.test(apiHost))
25
+ throw new CliError("usage", "the BenignSwarm API host is invalid for Antigravity sandbox permissions");
26
+ const dirs = [...new Set([dirname(cwd), b9sHome, ...extraWritable])];
27
+ return [
28
+ "--sandbox", "--settings",
29
+ JSON.stringify({ enableTerminalSandbox: true, toolPermission: "proceed-in-sandbox", permissions: { allow: [`read_url(${apiHost})`, "read_url(github.com)"] } }),
30
+ ...dirs.flatMap((dir) => ["--add-dir", dir]),
31
+ ];
32
+ }
33
+ export function antigravityTurnArgs(prompt, model, effort, timeoutSeconds, settings, conversation) {
34
+ return ["-p", prompt, "--output-format", "json", "--model", model, ...(effort ? ["--effort", effort] : []), "--print-timeout", `${timeoutSeconds}s`, ...(conversation ? ["--conversation", conversation] : []), ...settings];
35
+ }
36
+ export function antigravityResultError(result, raw, exitCode, expectedConversation) {
37
+ if (!result)
38
+ return raw.trim().slice(-500) || `agy exited ${exitCode ?? "without a result"} and did not return JSON`;
39
+ if (expectedConversation && result.conversation_id !== expectedConversation) {
40
+ return `agy resumed conversation ${expectedConversation} but returned ${result.conversation_id ?? "no conversation id"}; refusing to adopt a new conversation`;
41
+ }
42
+ if (result.status !== "SUCCESS") {
43
+ const detail = typeof result.error === "string" ? result.error : result.error ? JSON.stringify(result.error) : "";
44
+ return `agy turn ended with status ${result.status ?? "missing"}${detail ? `: ${detail}` : ""}`.slice(0, 500);
45
+ }
46
+ if (exitCode !== null && exitCode !== 0)
47
+ return `agy exited ${exitCode}`;
48
+ if (!result.conversation_id)
49
+ return "agy returned SUCCESS without a conversation_id";
50
+ return null;
51
+ }
52
+ export function parseAntigravityJson(output) {
53
+ const text = output.trim();
54
+ if (!text)
55
+ return null;
18
56
  try {
19
- return JSON.parse(readFileSync(file(), "utf8"));
57
+ const value = JSON.parse(text);
58
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
20
59
  }
21
60
  catch {
22
- throw new CliError("bad_antigravity_map", `${file()} is not valid JSON`, "Remove it and run: bschat antigravity sync");
61
+ return null;
23
62
  }
24
63
  }
25
- export function bindConversation(conversationId, ref) {
26
- if (!UUID.test(conversationId))
27
- throw new CliError("usage", `"${conversationId}" is not an Antigravity conversation id (a UUID)`);
28
- const m = read();
29
- m.conversations[conversationId.toLowerCase()] = ref;
30
- mkdirSync(dirname(file()), { recursive: true });
31
- writeFileSync(file(), JSON.stringify(m, null, 2) + "\n");
32
- }
33
- export function conversationAgent(conversationId) {
34
- return read().conversations[conversationId.toLowerCase()] ?? null;
35
- }
36
- /** The conversation an Antigravity wake command addresses (`agentapi send-message ... <id>`), if any. */
37
- export function conversationOfExec(exec) {
38
- return /agentapi\b/.test(exec) ? UUID.exec(exec)?.[0]?.toLowerCase() ?? null : null;
39
- }
40
- /** Binds every conversation an installed Antigravity watcher wakes to the agent it runs as. */
41
- export function syncFromWatchers() {
42
- const out = [];
43
- for (const w of watcherPlists()) {
44
- const r = spawnSync("plutil", ["-convert", "json", "-o", "-", w.path], { encoding: "utf8" });
45
- if (r.status !== 0)
46
- continue;
47
- const args = JSON.parse(r.stdout).ProgramArguments ?? [];
48
- const exec = args[args.indexOf("--exec") + 1] ?? "";
49
- const as = args[args.indexOf("--as") + 1];
50
- const conv = conversationOfExec(exec);
51
- if (conv && as && args.includes("--as")) {
52
- bindConversation(conv, as);
53
- out.push({ conversation: conv, agent: as });
64
+ export function recordAntigravityTurn(path, record) {
65
+ mkdirSync(dirname(path), { recursive: true });
66
+ appendFileSync(path, `${JSON.stringify(record)}\n`, { mode: 0o600 });
67
+ }
68
+ /** 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 };
71
+ }
72
+ export function runAntigravityTurn(bin, args, logPath, cwd, agent, expectedConversation, run = spawnSync, envOverride = {}) {
73
+ const started = new Date().toISOString();
74
+ const model = args[args.indexOf("--model") + 1];
75
+ const effortIndex = args.indexOf("--effort");
76
+ const effort = effortIndex >= 0 ? args[effortIndex + 1] : undefined;
77
+ const result = run(bin, args, { encoding: "utf8", timeout: 24 * 60 * 60_000, maxBuffer: 8 * 1024 * 1024, cwd, env: { ...process.env, BSCHAT_AGENT: agent, ...(model ? { BSCHAT_MODEL: model } : {}), ...(effort ? { BSCHAT_EFFORT: effort } : {}), ...envOverride } });
78
+ const output = result.stdout ?? "";
79
+ const parsed = parseAntigravityJson(output);
80
+ const record = {
81
+ started_at: started,
82
+ finished_at: new Date().toISOString(),
83
+ exit_code: result.status,
84
+ ...(expectedConversation ? { expected_conversation: expectedConversation } : {}),
85
+ ...(model ? { model } : {}),
86
+ ...(parsed ? { result: parsed } : { raw: [output, result.stderr].filter(Boolean).join("\n").slice(-4000) }),
87
+ };
88
+ recordAntigravityTurn(logPath, record);
89
+ const error = antigravityResultError(parsed, output || result.stderr || "", result.status, expectedConversation);
90
+ if (result.error || error) {
91
+ const detail = result.error?.message ?? error;
92
+ throw new CliError("agy_failed", `agy turn failed${expectedConversation ? ` for conversation ${expectedConversation}` : ""}: ${detail}; output logged at ${logPath}`);
93
+ }
94
+ return { conversation: parsed.conversation_id, record, output };
95
+ }
96
+ export function antigravityResumeCommand(bin, session, model, effort, timeoutSeconds, settings, logPath) {
97
+ const tmp = `${logPath}.pending`;
98
+ const err = `${logPath}.stderr`;
99
+ const base = [bin, "-p", "{text}", "--output-format", "json", "--model", model, ...(effort ? ["--effort", effort] : []), "--print-timeout", `${timeoutSeconds}s`, "--conversation", session, ...settings].map((arg) => arg === "{text}" ? arg : shq(arg)).join(" ");
100
+ const script = `const fs=require('node:fs');const [tmp,err,log,status,started,expected,model]=process.argv.slice(1);const raw=fs.readFileSync(tmp,'utf8');const stderr=fs.readFileSync(err,'utf8');let result;try{result=JSON.parse(raw)}catch{}const record={started_at:started,finished_at:new Date().toISOString(),exit_code:Number(status),expected_conversation:expected,model,...(result?{result}:{raw:(raw+'\\n'+stderr).slice(-4000)})};fs.appendFileSync(log,JSON.stringify(record)+'\\n',{mode:0o600});fs.rmSync(tmp,{force:true});fs.rmSync(err,{force:true});`;
101
+ const node = `${shq(process.execPath)} -e ${shq(script)} ${shq(tmp)} ${shq(err)} ${shq(logPath)} "$agy_status" "$agy_started" ${shq(session)} ${shq(model)}`;
102
+ return `agy_started=$(date -u +%Y-%m-%dT%H:%M:%SZ); ${base} > ${shq(tmp)} 2> ${shq(err)}; agy_status=$?; ${node}; exit "$agy_status"`;
103
+ }
104
+ function agyRecords(path) {
105
+ if (!existsSync(path))
106
+ return [];
107
+ return readFileSync(path, "utf8").split("\n").flatMap((line) => {
108
+ try {
109
+ return [JSON.parse(line)];
110
+ }
111
+ catch {
112
+ return [];
54
113
  }
114
+ });
115
+ }
116
+ function antigravityError(record, session) {
117
+ if (!record)
118
+ return "agy has not recorded a completed turn";
119
+ return antigravityResultError(record.result ?? null, record.raw ?? "", record.exit_code, record.expected_conversation ?? session);
120
+ }
121
+ export function isAntigravityCommand(args) {
122
+ const first = /^(?:"([^"]+)"|'([^']+)'|(\S+))/.exec(args.trim());
123
+ const executable = first?.[1] ?? first?.[2] ?? first?.[3];
124
+ return executable !== undefined && basename(executable) === "agy";
125
+ }
126
+ export function antigravityProcesses(session, psOutput) {
127
+ const output = psOutput ?? spawnSync("ps", ["-axo", "pid=,args="], { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 }).stdout ?? "";
128
+ const found = [];
129
+ for (const line of output.split("\n")) {
130
+ const match = /^\s*(\d+)\s+(.*)$/.exec(line);
131
+ if (!match || Number(match[1]) === process.pid || !isAntigravityCommand(match[2]))
132
+ continue;
133
+ if (new RegExp(`(?:^|\\s)--conversation\\s+['\"]?${session.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&")}['\"]?(?:\\s|$)`).test(match[2]))
134
+ found.push({ pid: Number(match[1]), args: match[2] });
55
135
  }
56
- return out;
136
+ return found;
137
+ }
138
+ export function antigravityProbe(session, ref, logPath = antigravityLog(ref), conversationPath = antigravityConversationDb(session), processes = antigravityProcesses) {
139
+ const last = () => agyRecords(logPath).at(-1);
140
+ return {
141
+ label: "Antigravity", what: `conversation ${session}`,
142
+ phase() {
143
+ if (!existsSync(conversationPath))
144
+ return { missing: `no Antigravity conversation database ${conversationPath}; cannot tell whether conversation ${session} is running` };
145
+ const running = processes(session).length > 0;
146
+ const lastRecord = last();
147
+ const at = statSync(conversationPath).mtime.toISOString();
148
+ return { running, startedAt: at, lastEventAt: at, lastError: running ? null : antigravityError(lastRecord, session), lastErrorAt: lastRecord?.finished_at ?? null };
149
+ },
150
+ startedSince(ms) { return existsSync(conversationPath) && statSync(conversationPath).mtimeMs >= ms - 5_000; },
151
+ turnError() { return antigravityError(last(), session); },
152
+ turnOutput() { const result = last()?.result; return (result?.response ?? last()?.raw ?? "").slice(-800); },
153
+ turnTokens() { return antigravityTotalTokens(last()?.result?.usage); },
154
+ limitUntil: () => null,
155
+ isLimit: (error) => !!error && /usage limit|quota|resource exhausted/i.test(error),
156
+ };
157
+ }
158
+ export function antigravityUsage(path, since, until) {
159
+ const from = Date.parse(since), to = Date.parse(until);
160
+ const rows = agyRecords(path).filter((record) => Date.parse(record.started_at) >= from && Date.parse(record.started_at) <= to && record.result?.usage);
161
+ if (!rows.length)
162
+ return null;
163
+ const totals = { input: 0, cached_input: 0, output: 0, reasoning: 0, total: 0 };
164
+ for (const { result } of rows) {
165
+ const usage = result.usage;
166
+ const cached = usage.cache_read_tokens ?? 0;
167
+ totals.input += (usage.input_tokens ?? 0) + cached;
168
+ totals.cached_input += cached;
169
+ totals.output += usage.output_tokens ?? 0;
170
+ totals.reasoning += usage.thinking_tokens ?? 0;
171
+ totals.total += antigravityTotalTokens(usage) ?? 0;
172
+ }
173
+ return totals;
174
+ }
175
+ export function appendAntigravityRawResult(path, output, exitCode, expectedConversation) {
176
+ const result = parseAntigravityJson(output);
177
+ recordAntigravityTurn(path, { started_at: new Date().toISOString(), finished_at: new Date().toISOString(), exit_code: exitCode, ...(expectedConversation ? { expected_conversation: expectedConversation } : {}), ...(result ? { result } : { raw: output.slice(-4000) }) });
57
178
  }
package/dist/args.js CHANGED
@@ -3,7 +3,7 @@ import { CliError } from "./errors.js";
3
3
  // These options accept comma-separated collections, so repeating them should
4
4
  // append another collection instead of discarding earlier values.
5
5
  export const LIST_FLAGS = ["tags", "projects", "evidence", "statuses", "depends-on", "default-tags", "units", "waits-on", "writable-root", "needs", "exclude", "remove", "post", "harness", "variant", "requires", "reworks", "confirm-causes"];
6
- export const STRING_FLAGS = ["as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task", "state", "blocked-on", "tags", "custom", "vendor", "role", "tier", "description", "permissions", "cardinality", "assign-outside-qualifications", "machine", "dir", "confirm", "type", "name", "out", "token", "prefix", "uses", "expires-hours", "skill-dir", "harness", "provider", "reply-to", "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent", "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval", "requeue-after", "unacked-after", "category", "command", "command-pattern", "follow-delay", "env", "scope", "scope-file", "scope-from", "append", "pr", "note", "add", "remove", "merged", "tag", "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "max-budget-usd", "by", "target", "milestone", "file", "exit", "depends-on", "default-tags", "source", "on", "partial", "question", "ruling", "gaps", "unit", "units", "blocks", "sla", "takeover", "max-open", "max-in-progress", "require-scope", "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit", "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email", "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on", "sandbox", "thread", "turn-timeout", "turns-per-hour", "session", "plain", "if-yes", "if-no", "ssh", "variant", "count", "needs", "min-ram", "exclude", "carry", "from", "to-ssh", "wait", "writable", "writable-root", "dsh", "for", "until", "reason", "at", "requires", "priority", "informs", "amend", "waive-informs", "text", "kind", "claim", "decision", "sha", "value", "expect", "expectations", "reworks", "cause", "lesson", "disputes", "annotation", "send-back-event", "confirm-causes"];
6
+ export const STRING_FLAGS = ["as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task", "state", "blocked-on", "tags", "custom", "vendor", "role", "tier", "description", "permissions", "cardinality", "assign-outside-qualifications", "machine", "dir", "confirm", "type", "name", "out", "token", "prefix", "uses", "expires-hours", "skill-dir", "harness", "provider", "reply-to", "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent", "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval", "requeue-after", "unacked-after", "category", "command", "command-pattern", "follow-delay", "env", "scope", "scope-file", "scope-from", "append", "pr", "note", "add", "remove", "merged", "tag", "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "max-budget-usd", "by", "target", "milestone", "file", "exit", "depends-on", "default-tags", "source", "on", "partial", "question", "ruling", "gaps", "unit", "units", "blocks", "sla", "takeover", "max-open", "max-in-progress", "require-scope", "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit", "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email", "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on", "sandbox", "thread", "turn-timeout", "turns-per-hour", "session", "plain", "if-yes", "if-no", "ssh", "variant", "count", "needs", "min-ram", "exclude", "carry", "from", "to-ssh", "wait", "writable", "writable-root", "dsh", "agy", "for", "until", "reason", "at", "requires", "priority", "informs", "amend", "waive-informs", "text", "kind", "claim", "decision", "sha", "value", "expect", "expectations", "reworks", "cause", "lesson", "disputes", "annotation", "send-back-event", "confirm-causes"];
7
7
  export const BOOL_FLAGS = ["latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels", "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "template", "scope-only", "unread", "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive", "approve", "turn", "service", "print-hooks", "create", "rotate", "codex-userns", "bwrap-userns", "print-apparmor", "cancel", "rerun", "confirmed", "refuted", "no-source", "allow-lower-tier"];
8
8
  export function parse(argv) {
9
9
  const options = {};
package/dist/brief.js CHANGED
@@ -49,7 +49,7 @@ export function formatRecoveryBrief(brief) {
49
49
  lines.push("Questions waiting on you:");
50
50
  lines.push(...(brief.questions.length ? brief.questions.map((q) => ` ${q.project} WU #${q.number} (${q.age_minutes ?? 0} min ago): ${q.question} — ${q.next}`) : [" none"]));
51
51
  lines.push("Units:");
52
- lines.push(...(brief.units.length ? brief.units.map((u) => ` [${u.state}] ${u.project} WU #${u.number} ${u.title}${scope(u.base_scope, u.scope_amendments, u.scope_amendments_omitted)} — ${u.next}`) : [" none"]));
52
+ lines.push(...(brief.units.length ? brief.units.map((u) => ` [${u.state}] ${u.project} WU #${u.number} ${u.title}${scope(u.base_scope, u.scope_amendments, u.scope_amendments_omitted)}${u.recovery ? `\n Recovery: ${u.recovery.available ? `available (${u.recovery.size ?? "?"} bytes, sha256 ${u.recovery.sha256 ?? "?"})` : "not verified"}${u.recovery.expires_at ? `, expires ${u.recovery.expires_at}` : ""}${u.recovery.manifest?.skipped.length ? `, ${u.recovery.manifest.skipped.length} regenerable path(s) skipped` : ""}${u.recovery.manifest?.omitted.length ? `, ${u.recovery.manifest.omitted.length} file(s) remain uncaptured` : ""}; restore: b9s wu recovery restore ${u.number}` : ""} — ${u.next}`) : [" none"]));
53
53
  lines.push("Reviews waiting on you:");
54
54
  lines.push(...(brief.reviews.length ? brief.reviews.map((r) => ` ${r.project} ${r.slice ? `slice ${r.slice}` : `WU #${r.number}`} ${r.title}${scope(r.base_scope, r.scope_amendments, r.scope_amendments_omitted)} — ${r.next}`) : [" none"]));
55
55
  lines.push("Open asks:");
package/dist/client.js CHANGED
@@ -39,6 +39,26 @@ export class Client {
39
39
  h["x-bschat-machine"] = this.machineIdentity;
40
40
  return h;
41
41
  }
42
+ async raw(method, path, body, extraHeaders = {}) {
43
+ let response;
44
+ try {
45
+ response = await fetch(this.url + path, { method, headers: { ...this.headers(), ...extraHeaders }, body });
46
+ }
47
+ catch (e) {
48
+ throw new CliError("network", `could not reach ${this.url}: ${e.message}`);
49
+ }
50
+ noteServerVersions(response.headers, this.agentName);
51
+ if (!response.ok) {
52
+ const text = await response.text();
53
+ let json = { error: `http_${response.status}`, message: text.slice(0, 500) };
54
+ try {
55
+ json = JSON.parse(text);
56
+ }
57
+ catch { /* keep response text */ }
58
+ throw new CliError(json.error, json.message);
59
+ }
60
+ return response;
61
+ }
42
62
  /**
43
63
  * opts.retries: how many times to retry on a network failure or a 5xx. Only safe for calls
44
64
  * that are idempotent on the server (posts carry a client_id for exactly this reason).
@@ -16,7 +16,8 @@ import { beginTurnGuardAttempt, completePendingTurnGuard, installWatcherService
16
16
  import { randomUUID } from "node:crypto";
17
17
  import { HARNESS_BIN, HARNESS_LABEL, assertClaudeSelfCheck, claudeCodePath, claudeResultError, claudeResultFile, claudeSandboxEnv, claudeSettings, claudeTranscript, claudeTurnArgs, dshPath, dshResultError, dshSessionFromEvents, dshSettings, dshTurnLog, probeFor } from "../harnesses.js";
18
18
  import { claudeTurnEnv } from "../providers.js";
19
- 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";
20
21
  import { configureGitCredentialForWorktree } from "./git-credential.js";
21
22
  const SANDBOXES = ["read-only", "workspace-write", "danger-full-access"];
22
23
  export const DEFAULT_CLAUDE_MAX_BUDGET_USD = 1;
@@ -25,11 +26,11 @@ export const DEFAULT_CLAUDE_MAX_BUDGET_USD = 1;
25
26
  * headless, with no app involved, so it works the same over ssh on a remote machine. It enrolls the
26
27
  * agent (with an invite token), starts its session with an onboarding turn, binds it so the hooks
27
28
  * deliver to it, and installs a turn-mode watcher that runs each later turn itself (Codex: `codex exec
28
- * 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
29
30
  * from the Codex app's queue silently not delivering wake-ups (fabricbios luna-worker, ten hours).
30
31
  *
31
- * b9s start --harness codex|claude-code|dsh --as <name> --sandbox <mode> [--token bs_enroll_...]
32
- * [--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>]
33
34
  */
34
35
  export async function codexStart(p, out) {
35
36
  return harnessStart(p, out, "codex");
@@ -60,12 +61,14 @@ export async function harnessStart(p, out, harness) {
60
61
  // No default: what a headless agent may touch on this machine is the operator's call, every time.
61
62
  if (!sandbox || !SANDBOXES.includes(sandbox))
62
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");
63
66
  const turnTimeout = Number(str(p.flags, "turn-timeout") ?? "180");
64
67
  if (!Number.isInteger(turnTimeout) || turnTimeout < 5)
65
68
  throw new CliError("usage", "--turn-timeout must be a whole number of minutes, at least 5");
66
69
  const turnsPerHour = Number(str(p.flags, "turns-per-hour") ?? String(DEFAULT_TURNS_PER_HOUR));
67
- if (!Number.isInteger(turnsPerHour) || turnsPerHour < 1 || turnsPerHour > DEFAULT_TURNS_PER_HOUR)
68
- 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}`);
69
72
  const interval = Number(str(p.flags, "interval") ?? "30");
70
73
  if (!Number.isInteger(interval) || interval < 5)
71
74
  throw new CliError("usage", "--interval must be an integer number of seconds, at least 5");
@@ -74,24 +77,32 @@ export async function harnessStart(p, out, harness) {
74
77
  const dshOverride = str(p.flags, "dsh");
75
78
  if (harness !== "dsh" && dshOverride)
76
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");
77
83
  const providerName = str(p.flags, "provider") ?? "anthropic";
78
84
  if (providerName !== "anthropic" && providerName !== "deepseek")
79
85
  throw new CliError("usage", "--provider must be anthropic or deepseek");
80
86
  const provider = providerName;
81
87
  if (provider === "deepseek" && harness !== "claude-code")
82
88
  throw new CliError("usage", "--provider deepseek requires --harness claude-code");
83
- const model = str(p.flags, "model") ?? (provider === "deepseek" ? "deepseek-flash" : undefined);
89
+ const providerModel = str(p.flags, "model") ?? (provider === "deepseek" ? "deepseek-flash" : undefined);
84
90
  const budgetFlag = str(p.flags, "max-budget-usd");
85
91
  if (budgetFlag !== undefined && (harness !== "claude-code" || sandbox !== "workspace-write"))
86
92
  throw new CliError("usage", "--max-budget-usd is only valid for Claude Code workspace-write sessions");
87
93
  const maxBudgetUsd = budgetFlag === undefined ? DEFAULT_CLAUDE_MAX_BUDGET_USD : Number(budgetFlag);
88
94
  if (harness === "claude-code" && sandbox === "workspace-write" && (!Number.isFinite(maxBudgetUsd) || maxBudgetUsd <= 0))
89
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)");
90
99
  const bin = harness === "dsh"
91
100
  ? dshPath(dshOverride)
92
- : harness === "claude-code" && sandbox === "workspace-write"
93
- ? 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`"); })()
94
- : 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)");
95
106
  if (!bin)
96
107
  throw new CliError("not_found", "DeepSeek Harness CLI dsh was not found; install DeepSeek Harness or pass --dsh <path>");
97
108
  if (harness === "dsh" && !existsSync(bin))
@@ -104,12 +115,14 @@ export async function harnessStart(p, out, harness) {
104
115
  const explicitWritable = repeated(p, "writable-root").map((w) => w.trim());
105
116
  const writable = startWritableRoots(sandbox, machineWritable, explicitWritable);
106
117
  // Refuses a sandbox the harness cannot honour before anything is enrolled.
107
- const settings = harness === "codex"
118
+ let settings = harness === "codex"
108
119
  ? codexSettings(sandbox, model, effort, process.cwd(), configRoot(), [...writable, ...ownWorktreeGitDir(process.cwd())])
109
120
  : harness === "dsh"
110
121
  ? dshSettings(sandbox, process.cwd(), configRoot(), [...writable, ...ownWorktreeGitDir(process.cwd())])
111
- : claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable);
122
+ : harness === "claude-code" ? claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable) : [];
112
123
  const providerEnv = { ...claudeTurnEnv(harness === "claude-code" ? provider : undefined, model), ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}) };
124
+ if ((harness === "claude-code" || harness === "antigravity") && sandbox === "workspace-write")
125
+ configureHttpsOriginForWorktree(process.cwd());
113
126
  // 1. Who: enroll with the invite token, or use credentials already on this machine.
114
127
  const lines = [];
115
128
  const token = str(p.flags, "token");
@@ -120,11 +133,13 @@ export async function harnessStart(p, out, harness) {
120
133
  lines.push(joined.join("\n").split("\n")[0]);
121
134
  }
122
135
  const { credentials: creds, ref } = startAgentIdentity(name);
123
- if (harness === "claude-code" && sandbox === "workspace-write")
136
+ if ((harness === "claude-code" || harness === "antigravity") && sandbox === "workspace-write")
124
137
  configureHttpsOriginForWorktree(process.cwd());
125
138
  await configureGitCredentialForWorktree(process.cwd(), creds);
126
139
  if (creds.vendor && creds.vendor !== harness)
127
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())]);
128
143
  const priorState = readState(ref);
129
144
  if (priorState.turn_guard?.fault) {
130
145
  const fault = priorState.turn_guard.fault;
@@ -140,6 +155,8 @@ export async function harnessStart(p, out, harness) {
140
155
  let firstTurnLog = null;
141
156
  if (harness === "dsh")
142
157
  firstTurnLog = dshTurnLog(ref);
158
+ if (harness === "antigravity")
159
+ firstTurnLog = antigravityLog(ref);
143
160
  if (adopt) {
144
161
  session = adopt.toLowerCase();
145
162
  if (harness === "codex") {
@@ -159,11 +176,18 @@ export async function harnessStart(p, out, harness) {
159
176
  }
160
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.`);
161
178
  }
162
- else {
179
+ else if (harness === "dsh") {
163
180
  mkdirSync(joinPath(configRoot(), "logs"), { recursive: true });
164
181
  closeSync(openSync(dshTurnLog(ref), "a"));
165
182
  lines.push(`Adopted DeepSeek Harness session ${session}. Do not resume it elsewhere while the watcher runs it: two clients on one session conflict.`);
166
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);
167
191
  }
168
192
  }
169
193
  else {
@@ -175,7 +199,7 @@ export async function harnessStart(p, out, harness) {
175
199
  }
176
200
  const logDir = joinPath(configRoot(), "logs");
177
201
  mkdirSync(logDir, { recursive: true });
178
- 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`);
179
203
  const prompt = [
180
204
  `[b9s] You are ${ref}, a BenignSwarm agent, started headless by \`b9s ${cmd}\`; nobody is typing to you.`,
181
205
  `Your watcher starts a turn for you whenever something needs you, so end your turn when nothing is left to do.`,
@@ -197,6 +221,14 @@ export async function harnessStart(p, out, harness) {
197
221
  initialPid = started.pid;
198
222
  lines.push(`Started DeepSeek Harness session ${session}; its first turn (reading its role and inbox) is running, event log: ${firstTurnLog}`);
199
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
+ }
200
232
  else {
201
233
  // Claude Code takes the session id from us, so nothing has to be read back from its output.
202
234
  session ??= randomUUID();
@@ -219,8 +251,10 @@ export async function harnessStart(p, out, harness) {
219
251
  // hook knows the agent from BSCHAT_AGENT (the watcher sets it for every turn), so it needs no map.
220
252
  if (harness === "codex")
221
253
  bindSession("codex", session, ref);
222
- const transcript = harness === "dsh" ? dshTurnLog(ref) : harness === "claude-code" ? claudeTranscript(session) ?? firstTurnLog ?? "" : codexRollout(session) ?? firstTurnLog ?? "";
223
- 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 } : {}) } });
224
258
  // A session adopted here may end in a usage-limit error from the machine it came from, written in
225
259
  // that machine's local time ("3:32 PM" Central read as UTC on ronald: six hours off). Only errors
226
260
  // from turns on this machine pause it; if the account is still limited, the next turn says so here.
@@ -231,8 +265,10 @@ export async function harnessStart(p, out, harness) {
231
265
  ? [bin, "exec", "resume", session, ...settings].map(shq).join(" ") + " {text}"
232
266
  : harness === "dsh"
233
267
  ? dshResumeCommand(bin, session, settings, dshTurnLog(ref))
234
- // The result goes to a file the watcher reads when the turn ends: Claude Code can exit 0 with is_error set.
235
- : `${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))}`;
236
272
  const watcherOut = [];
237
273
  // Scratch space beside the checkout, not the system's /tmp: on a machine the checkout lives on the
238
274
  // work volume, the folder is inside what the sandbox may write, and it survives a reboot. Learned
@@ -240,7 +276,7 @@ export async function harnessStart(p, out, harness) {
240
276
  // volume had 750 GB free, and which empties /tmp at every boot.
241
277
  const tmp = sessionTmpDir(process.cwd(), creds.agent);
242
278
  mkdirSync(tmp, { recursive: true });
243
- 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 });
244
280
  const wl = watcherOut.join("\n").split("\n");
245
281
  lines.push(wl[0].replace(/^Wrote /, "Watcher: wrote "), ...wl.filter((l) => l.startsWith("Linger is off")));
246
282
  // 5. Hooks.
@@ -255,13 +291,17 @@ export async function harnessStart(p, out, harness) {
255
291
  else if (harness === "dsh") {
256
292
  lines.push("DeepSeek Harness runs the headless profile without an interactive approval prompt; b9s identifies this agent through BSCHAT_AGENT on each turn.");
257
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
+ }
258
297
  else {
259
298
  lines.push(`Claude Code runs b9s's hooks from this checkout's .claude/settings.local.json (written by join).`);
260
299
  }
261
- 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.`);
262
301
  lines.push(harness === "dsh"
263
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.`
264
- : `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}`);
265
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 });
266
306
  }
267
307
  export const dshStartArgs = (settings) => ["--profile", "headless", "--json", ...settings, "-"];
@@ -436,6 +476,63 @@ export async function runGuardedClaudeSandboxSelfCheck(ref, turnsPerHour, bin, s
436
476
  if (fault)
437
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)"}`);
438
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
+ }
439
536
  /**
440
537
  * The Codex settings a headless turn runs with. Under workspace-write the agent still has to reach
441
538
  * the API and write its own b9s state (~/.b9s), and `wu start` puts unit worktrees beside the