benignswarm 0.12.93 → 0.12.95
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/antigravity.js +167 -46
- package/dist/args.js +3 -3
- package/dist/boot-time.js +39 -0
- package/dist/brief.js +1 -1
- package/dist/build-caches.js +891 -0
- package/dist/client.js +20 -0
- package/dist/commands/admin.js +97 -2
- package/dist/commands/cloud-admin.js +74 -0
- package/dist/commands/codex-start.js +131 -31
- package/dist/commands/machine-admin.js +98 -14
- package/dist/commands/machine.js +130 -28
- package/dist/commands/watch.js +29 -23
- package/dist/commands/wu.js +215 -7
- package/dist/git.js +20 -6
- package/dist/harnesses.js +7 -6
- package/dist/help.js +35 -15
- package/dist/index.js +1 -1
- package/dist/recovery-archive.js +149 -0
- package/dist/turn-guard.js +32 -11
- package/dist/usage.js +6 -0
- package/dist/version.js +1 -1
- package/package.json +1 -1
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).
|
package/dist/commands/admin.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { cliUserAgent } from "../legacy-alias.js";
|
|
2
2
|
import { bool, need, str } from "../args.js";
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
3
4
|
import { Client } from "../client.js";
|
|
4
5
|
import { DEFAULT_URL, forgetAdmin, loadAdmin, resolveAdminName, saveAdmin } from "../config.js";
|
|
5
6
|
import { hostname } from "node:os";
|
|
@@ -11,6 +12,7 @@ import { awayUntil } from "./agent.js";
|
|
|
11
12
|
import { agentMove, machineAdmin, poolAdmin, projectCheckoutAdmin, projectRepoAdmin } from "./machine-admin.js";
|
|
12
13
|
import { accountAdmin, answerAdmin, explainAdmin, keysAdmin, needsAdmin, notifierAdmin, processAdmin, skillAdmin, tagList, textCheckAdmin, worktreeAdmin } from "./operator.js";
|
|
13
14
|
import { adminNotice } from "./notices.js";
|
|
15
|
+
import { cloudAdmin } from "./cloud-admin.js";
|
|
14
16
|
function adminClient(p) {
|
|
15
17
|
return Client.forAdmin(loadAdmin(resolveAdminName(str(p.flags, "admin"))));
|
|
16
18
|
}
|
|
@@ -61,7 +63,13 @@ export async function admin(p, out) {
|
|
|
61
63
|
return projectRepoAdmin(rest, p, out);
|
|
62
64
|
if (action === "checkout")
|
|
63
65
|
return projectCheckoutAdmin(rest, p, out);
|
|
66
|
+
if (action === "github")
|
|
67
|
+
return projectGitHubAdmin(rest, p, out);
|
|
68
|
+
if (action === "hosted-merge")
|
|
69
|
+
return projectHostedMergeAdmin(rest, p, out);
|
|
64
70
|
return project(action, rest, p, out);
|
|
71
|
+
case "github":
|
|
72
|
+
return githubAdmin(action, rest, p, out);
|
|
65
73
|
case "agent":
|
|
66
74
|
if (action === "move")
|
|
67
75
|
return agentMove(rest, p, out);
|
|
@@ -109,6 +117,8 @@ export async function admin(p, out) {
|
|
|
109
117
|
case "machine":
|
|
110
118
|
case "machines":
|
|
111
119
|
return machineAdmin(action, rest, p, out);
|
|
120
|
+
case "cloud":
|
|
121
|
+
return cloudAdmin(action, rest, p, out);
|
|
112
122
|
case "pool":
|
|
113
123
|
case "pools":
|
|
114
124
|
return poolAdmin(action, rest, p, out, process.argv.slice(2));
|
|
@@ -126,6 +136,51 @@ export async function admin(p, out) {
|
|
|
126
136
|
throw new CliError("usage", `unknown admin command ${group ?? ""}`, "Run: b9s --help");
|
|
127
137
|
}
|
|
128
138
|
}
|
|
139
|
+
async function githubAdmin(action, rest, p, out) {
|
|
140
|
+
const c = adminClient(p);
|
|
141
|
+
if (action === "status" && !rest.length) {
|
|
142
|
+
const r = await c.call("GET", "/github/repositories");
|
|
143
|
+
const rows = (r.installations ?? []).map((i) => ({ installation: i.installation_id, owner: i.owner_login, repositories: i.repositories?.length ?? 0, settings: i.settings_url }));
|
|
144
|
+
out.print(rows.length ? table(rows, ["installation", "owner", "repositories", "settings"]) : "No GitHub installations connected.", r);
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
if (action === "disconnect" && rest.length === 1 && /^\d{1,20}$/.test(rest[0])) {
|
|
148
|
+
const r = await c.call("DELETE", `/github/installations/${rest[0]}`);
|
|
149
|
+
out.print(`Disconnected GitHub installation ${rest[0]}; linked projects have hosted merge disabled.`, r);
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
throw new CliError("usage", "b9s-admin github status | disconnect <installation-id>");
|
|
153
|
+
}
|
|
154
|
+
async function projectGitHubAdmin(rest, p, out) {
|
|
155
|
+
const [project, action, ...extra] = rest;
|
|
156
|
+
if (!project || extra.length)
|
|
157
|
+
throw new CliError("usage", "b9s-admin project github <project> status | unlink");
|
|
158
|
+
const c = adminClient(p);
|
|
159
|
+
if (action === "status") {
|
|
160
|
+
const r = await c.call("GET", `/projects/${project}/github-link`);
|
|
161
|
+
const link = r.link;
|
|
162
|
+
out.print(`${project}: ${link.owner}/${link.name} -> ${link.target_branch}; hosted merge ${r.hosted_merge_enabled ? "enabled" : "disabled"}${link.ruleset_unverified_reason ? `; ruleset unverified: ${link.ruleset_unverified_reason}` : ""}`, r);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
if (action === "unlink") {
|
|
166
|
+
const r = await c.call("DELETE", `/projects/${project}/github-link`);
|
|
167
|
+
out.print(`Unlinked GitHub repository from ${project}; hosted merge disabled.`, r);
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
throw new CliError("usage", "b9s-admin project github <project> status | unlink");
|
|
171
|
+
}
|
|
172
|
+
async function projectHostedMergeAdmin(rest, p, out) {
|
|
173
|
+
const [project, action, ...extra] = rest;
|
|
174
|
+
if (!project || !["enable", "disable"].includes(action ?? "") || extra.length) {
|
|
175
|
+
throw new CliError("usage", "b9s-admin project hosted-merge <project> enable|disable [--confirm-bypass-signal]");
|
|
176
|
+
}
|
|
177
|
+
const enabled = action === "enable";
|
|
178
|
+
const confirmed = bool(p.flags, "confirm-bypass-signal");
|
|
179
|
+
if (enabled && !confirmed)
|
|
180
|
+
throw new CliError("usage", "enable only after the live GitHub bypass-change signal check; pass --confirm-bypass-signal after confirming it");
|
|
181
|
+
const r = await adminClient(p).call("PATCH", `/projects/${project}/github-link`, { hosted_merge_enabled: enabled, ...(enabled ? { bypass_signal_verified: true } : {}) });
|
|
182
|
+
out.print(`Hosted merge ${enabled ? "enabled" : "disabled"} for ${project}.`, r);
|
|
183
|
+
}
|
|
129
184
|
async function project(action, rest, p, out) {
|
|
130
185
|
const c = adminClient(p);
|
|
131
186
|
if (action === "list") {
|
|
@@ -147,6 +202,14 @@ async function agent(action, rest, p, out) {
|
|
|
147
202
|
const c = adminClient(p);
|
|
148
203
|
if (bool(p.flags, "account"))
|
|
149
204
|
return accountAgent(action, rest, p, out, c);
|
|
205
|
+
if (action === "retire") {
|
|
206
|
+
const [ref, extra] = rest;
|
|
207
|
+
const slash = ref?.indexOf("/") ?? -1;
|
|
208
|
+
if (!ref || extra || slash < 1 || slash === ref.length - 1 || ref.indexOf("/", slash + 1) !== -1) {
|
|
209
|
+
throw new CliError("usage", "admin agent retire <project>/<agent> [--note <text> | --note-file <file>] --yes");
|
|
210
|
+
}
|
|
211
|
+
return retireAdminAgent(c, ref, `/projects/${ref.slice(0, slash)}/agents/${ref.slice(slash + 1)}/retire`, p, out);
|
|
212
|
+
}
|
|
150
213
|
if ((action === "bench" || action === "unbench") && rest[0]) {
|
|
151
214
|
const ref = rest[0];
|
|
152
215
|
const slash = ref.indexOf("/");
|
|
@@ -205,10 +268,15 @@ async function agent(action, rest, p, out) {
|
|
|
205
268
|
out.print(`deleted agent ${name}`, r);
|
|
206
269
|
}
|
|
207
270
|
else
|
|
208
|
-
throw new CliError("usage", "admin agent create|list|role|tier <project>/<agent> <tier>|rotate-key|bench|unbench|delete ...", "Run: b9s --help");
|
|
271
|
+
throw new CliError("usage", "admin agent create|list|retire|role|tier <project>/<agent> <tier>|rotate-key|bench|unbench|delete ...", "Run: b9s --help");
|
|
209
272
|
}
|
|
210
273
|
async function accountAgent(action, rest, p, out, c) {
|
|
211
274
|
const [name, extra] = rest;
|
|
275
|
+
if (action === "retire" && name && !extra) {
|
|
276
|
+
if (name.includes("/"))
|
|
277
|
+
throw new CliError("usage", "admin agent --account retire <agent> [--note <text> | --note-file <file>] --yes");
|
|
278
|
+
return retireAdminAgent(c, `account/${name}`, `/agents/${name}/retire`, p, out);
|
|
279
|
+
}
|
|
212
280
|
if ((action === "bench" || action === "unbench") && name) {
|
|
213
281
|
if (name.includes("/"))
|
|
214
282
|
throw new CliError("usage", `agent ${action} --account <agent>${action === "bench" ? " [--note <text>]" : ""}`);
|
|
@@ -244,7 +312,34 @@ async function accountAgent(action, rest, p, out, c) {
|
|
|
244
312
|
out.print(`deleted account agent ${name}`, r);
|
|
245
313
|
}
|
|
246
314
|
else
|
|
247
|
-
throw new CliError("usage", "admin agent --account create <name> --vendor v --role r | list | role <name> <role> | tier <name> <tier> | rotate-key <name> | bench|unbench <name> | delete <name>");
|
|
315
|
+
throw new CliError("usage", "admin agent --account create <name> --vendor v --role r | list | retire <name> [--note <text> | --note-file <file>] --yes | role <name> <role> | tier <name> <tier> | rotate-key <name> | bench|unbench <name> | delete <name>");
|
|
316
|
+
}
|
|
317
|
+
async function retireAdminAgent(c, ref, path, p, out) {
|
|
318
|
+
const note = str(p.flags, "note");
|
|
319
|
+
const noteFile = str(p.flags, "note-file");
|
|
320
|
+
if (note !== undefined && noteFile !== undefined)
|
|
321
|
+
throw new CliError("usage", "use either --note or --note-file, not both");
|
|
322
|
+
let handoffNote = note;
|
|
323
|
+
if (noteFile !== undefined) {
|
|
324
|
+
try {
|
|
325
|
+
handoffNote = readFileSync(noteFile, "utf8");
|
|
326
|
+
}
|
|
327
|
+
catch (e) {
|
|
328
|
+
throw new CliError("bad_file", `${noteFile}: ${e.message}`);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
if (handoffNote !== undefined && !handoffNote.trim())
|
|
332
|
+
throw new CliError("usage", "a retirement note must not be empty");
|
|
333
|
+
if (handoffNote !== undefined && handoffNote.length > 60_000)
|
|
334
|
+
throw new CliError("usage", "a retirement note must be under 60000 chars");
|
|
335
|
+
if (!bool(p.flags, "yes")) {
|
|
336
|
+
out.print(`Would retire ${ref}, revoke its keys, and release its units to the queue.${handoffNote === undefined ? "" : " A resume handoff note will be saved."}\nRe-run with --yes to confirm.`, { would_retire: ref, confirmed: false });
|
|
337
|
+
throw new CliError("confirmation_required", "agent retirement requires --yes");
|
|
338
|
+
}
|
|
339
|
+
const result = await c.call("POST", path, handoffNote === undefined ? {} : { note: handoffNote });
|
|
340
|
+
const released = result.released_units?.length ? `; released units ${result.released_units.join(", ")}` : "";
|
|
341
|
+
const saved = result.handoff ? `; handoff note saved as handoff:${result.handoff.id}` : "";
|
|
342
|
+
out.print(`Retired ${ref}; keys revoked${released}${saved}.`, result);
|
|
248
343
|
}
|
|
249
344
|
function permsFromFlags(p, projectScoped) {
|
|
250
345
|
const raw = str(p.flags, "permissions");
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { CliError } from "../errors.js";
|
|
3
|
+
import { need, str } from "../args.js";
|
|
4
|
+
import { Client } from "../client.js";
|
|
5
|
+
import { loadAdmin, resolveAdminName } from "../config.js";
|
|
6
|
+
export async function cloudAdmin(action, rest, p, out) {
|
|
7
|
+
const creds = loadAdmin(resolveAdminName(str(p.flags, "admin")));
|
|
8
|
+
const c = Client.forAdmin(creds);
|
|
9
|
+
switch (action) {
|
|
10
|
+
case "connect": {
|
|
11
|
+
const file = need(p.flags, "file");
|
|
12
|
+
let value;
|
|
13
|
+
try {
|
|
14
|
+
value = JSON.parse(readFileSync(file, "utf8"));
|
|
15
|
+
}
|
|
16
|
+
catch (e) {
|
|
17
|
+
throw new CliError("usage", `could not read connection JSON from ${file}: ${e instanceof Error ? e.message : String(e)}`);
|
|
18
|
+
}
|
|
19
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
20
|
+
throw new CliError("usage", "connection file must contain a JSON object");
|
|
21
|
+
const r = await c.call("POST", "/cloud/connections", value);
|
|
22
|
+
out.print(`Connected AWS account ${r.connection.aws_account_id} in ${r.connection.region}. Save the external ID now; it is shown only in this response.\n\nExternal ID: ${r.external_id}\n\nReview and install this AWS role trust policy and permissions policy:\n\nTrust policy:\n${JSON.stringify(r.policy.trust_policy, null, 2)}\n\nPermissions policy:\n${JSON.stringify(r.policy.permissions_policy, null, 2)}\n\n${r.policy.read_scope_note}`, r);
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
case "show": {
|
|
26
|
+
const r = await c.call("GET", "/cloud/connections");
|
|
27
|
+
out.print(r.connection ? `BYO AWS ${r.connection.aws_account_id} / ${r.connection.region}; role ${r.connection.role_arn}; template ${r.connection.template_id}:${r.connection.template_version}; cap ${r.connection.daily_cap_cents} cents/day` : "No BYO AWS connection.", r);
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
case "policy": {
|
|
31
|
+
const r = await c.call("GET", "/cloud/connections/policy");
|
|
32
|
+
out.print(`${r.policy.read_scope_note}\n\n${JSON.stringify(r.policy, null, 2)}`, r);
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
case "test": {
|
|
36
|
+
const r = await c.call("POST", "/cloud/connections/test", {});
|
|
37
|
+
out.print(r.ok ? `AWS connection verified: ${r.aws_account_id} / ${r.region}; ${r.checks.join(", ")}` : `AWS permission test failed: ${r.reason}`, r);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
case "disconnect": {
|
|
41
|
+
const r = await c.call("DELETE", "/cloud/connections");
|
|
42
|
+
out.print("BYO AWS connection disabled.", r);
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
case "launch": {
|
|
46
|
+
const machine = need(p.flags, "machine"), idempotency = need(p.flags, "idempotency-key");
|
|
47
|
+
const r = await c.call("POST", "/cloud/operations", { machine_id: machine, idempotency_key: idempotency });
|
|
48
|
+
out.print(`Cloud operation ${r.operation.id}: ${r.operation.state} (${r.operation.idempotency_key})`, r);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
case "operations": {
|
|
52
|
+
const r = await c.call("GET", "/cloud/operations");
|
|
53
|
+
out.print(JSON.stringify(r.operations, null, 2), r);
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
case "inspect": {
|
|
57
|
+
const id = rest[0];
|
|
58
|
+
if (!id)
|
|
59
|
+
throw new CliError("usage", "cloud inspect <operation-id>");
|
|
60
|
+
const r = await c.call("GET", `/cloud/operations/${encodeURIComponent(id)}/provider`);
|
|
61
|
+
out.print(`Operation ${id}: provider ${r.provider_state ?? "not launched"}; ownership proof ${r.ownership_verified ? "verified" : "not verified"}`, r);
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
case "terminate": {
|
|
65
|
+
const id = rest[0];
|
|
66
|
+
if (!id)
|
|
67
|
+
throw new CliError("usage", "cloud terminate <operation-id>");
|
|
68
|
+
const r = await c.call("POST", `/cloud/operations/${encodeURIComponent(id)}/terminate`, { reason: need(p.flags, "reason") });
|
|
69
|
+
out.print(`Operation ${id}: ${r.state}`, r);
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
default: throw new CliError("usage", "cloud connect|show|policy|test|disconnect|launch|operations|inspect|terminate");
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -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, DEFAULT_UNPRODUCTIVE_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,17 @@ 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 >
|
|
68
|
-
throw new CliError("usage", `--turns-per-hour must be a whole number between 1 and ${
|
|
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}`);
|
|
72
|
+
const unproductivePerHour = Number(str(p.flags, "unproductive-per-hour") ?? String(DEFAULT_UNPRODUCTIVE_PER_HOUR));
|
|
73
|
+
if (!Number.isInteger(unproductivePerHour) || unproductivePerHour < 1 || unproductivePerHour > 60)
|
|
74
|
+
throw new CliError("usage", "--unproductive-per-hour must be a whole number between 1 and 60");
|
|
69
75
|
const interval = Number(str(p.flags, "interval") ?? "30");
|
|
70
76
|
if (!Number.isInteger(interval) || interval < 5)
|
|
71
77
|
throw new CliError("usage", "--interval must be an integer number of seconds, at least 5");
|
|
@@ -74,24 +80,32 @@ export async function harnessStart(p, out, harness) {
|
|
|
74
80
|
const dshOverride = str(p.flags, "dsh");
|
|
75
81
|
if (harness !== "dsh" && dshOverride)
|
|
76
82
|
throw new CliError("usage", "--dsh is only valid with --harness dsh");
|
|
83
|
+
const agyOverride = str(p.flags, "agy");
|
|
84
|
+
if (harness !== "antigravity" && agyOverride)
|
|
85
|
+
throw new CliError("usage", "--agy is only valid with --harness antigravity");
|
|
77
86
|
const providerName = str(p.flags, "provider") ?? "anthropic";
|
|
78
87
|
if (providerName !== "anthropic" && providerName !== "deepseek")
|
|
79
88
|
throw new CliError("usage", "--provider must be anthropic or deepseek");
|
|
80
89
|
const provider = providerName;
|
|
81
90
|
if (provider === "deepseek" && harness !== "claude-code")
|
|
82
91
|
throw new CliError("usage", "--provider deepseek requires --harness claude-code");
|
|
83
|
-
const
|
|
92
|
+
const providerModel = str(p.flags, "model") ?? (provider === "deepseek" ? "deepseek-flash" : undefined);
|
|
84
93
|
const budgetFlag = str(p.flags, "max-budget-usd");
|
|
85
94
|
if (budgetFlag !== undefined && (harness !== "claude-code" || sandbox !== "workspace-write"))
|
|
86
95
|
throw new CliError("usage", "--max-budget-usd is only valid for Claude Code workspace-write sessions");
|
|
87
96
|
const maxBudgetUsd = budgetFlag === undefined ? DEFAULT_CLAUDE_MAX_BUDGET_USD : Number(budgetFlag);
|
|
88
97
|
if (harness === "claude-code" && sandbox === "workspace-write" && (!Number.isFinite(maxBudgetUsd) || maxBudgetUsd <= 0))
|
|
89
98
|
throw new CliError("usage", "--max-budget-usd must be a positive dollar amount");
|
|
99
|
+
const model = providerModel;
|
|
100
|
+
if (harness === "antigravity" && !model)
|
|
101
|
+
throw new CliError("usage", "--model is required with --harness antigravity (for example gemini-4-hydrogen-low)");
|
|
90
102
|
const bin = harness === "dsh"
|
|
91
103
|
? dshPath(dshOverride)
|
|
92
|
-
: harness === "
|
|
93
|
-
?
|
|
94
|
-
:
|
|
104
|
+
: harness === "antigravity"
|
|
105
|
+
? agyOverride ?? which(HARNESS_BIN[harness], "install Antigravity CLI (agy) and log in on this machine")
|
|
106
|
+
: harness === "claude-code" && sandbox === "workspace-write"
|
|
107
|
+
? 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`"); })()
|
|
108
|
+
: 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
109
|
if (!bin)
|
|
96
110
|
throw new CliError("not_found", "DeepSeek Harness CLI dsh was not found; install DeepSeek Harness or pass --dsh <path>");
|
|
97
111
|
if (harness === "dsh" && !existsSync(bin))
|
|
@@ -104,12 +118,14 @@ export async function harnessStart(p, out, harness) {
|
|
|
104
118
|
const explicitWritable = repeated(p, "writable-root").map((w) => w.trim());
|
|
105
119
|
const writable = startWritableRoots(sandbox, machineWritable, explicitWritable);
|
|
106
120
|
// Refuses a sandbox the harness cannot honour before anything is enrolled.
|
|
107
|
-
|
|
121
|
+
let settings = harness === "codex"
|
|
108
122
|
? codexSettings(sandbox, model, effort, process.cwd(), configRoot(), [...writable, ...ownWorktreeGitDir(process.cwd())])
|
|
109
123
|
: harness === "dsh"
|
|
110
124
|
? dshSettings(sandbox, process.cwd(), configRoot(), [...writable, ...ownWorktreeGitDir(process.cwd())])
|
|
111
|
-
: claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable);
|
|
125
|
+
: harness === "claude-code" ? claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable) : [];
|
|
112
126
|
const providerEnv = { ...claudeTurnEnv(harness === "claude-code" ? provider : undefined, model), ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}) };
|
|
127
|
+
if ((harness === "claude-code" || harness === "antigravity") && sandbox === "workspace-write")
|
|
128
|
+
configureHttpsOriginForWorktree(process.cwd());
|
|
113
129
|
// 1. Who: enroll with the invite token, or use credentials already on this machine.
|
|
114
130
|
const lines = [];
|
|
115
131
|
const token = str(p.flags, "token");
|
|
@@ -120,15 +136,17 @@ export async function harnessStart(p, out, harness) {
|
|
|
120
136
|
lines.push(joined.join("\n").split("\n")[0]);
|
|
121
137
|
}
|
|
122
138
|
const { credentials: creds, ref } = startAgentIdentity(name);
|
|
123
|
-
if (harness === "claude-code" && sandbox === "workspace-write")
|
|
139
|
+
if ((harness === "claude-code" || harness === "antigravity") && sandbox === "workspace-write")
|
|
124
140
|
configureHttpsOriginForWorktree(process.cwd());
|
|
125
141
|
await configureGitCredentialForWorktree(process.cwd(), creds);
|
|
126
142
|
if (creds.vendor && creds.vendor !== harness)
|
|
127
143
|
throw new CliError("vendor_mismatch", `${ref} is saved as ${creds.vendor}, not ${harness}`);
|
|
144
|
+
if (harness === "antigravity")
|
|
145
|
+
settings = antigravitySettings(sandbox, process.cwd(), configRoot(), new URL(creds.url).host, [...writable, ...ownWorktreeGitDir(process.cwd())]);
|
|
128
146
|
const priorState = readState(ref);
|
|
129
147
|
if (priorState.turn_guard?.fault) {
|
|
130
148
|
const fault = priorState.turn_guard.fault;
|
|
131
|
-
throw new CliError("turn_mode_fault", `turn mode is stopped after ${fault.reason === "unproductive" ? `${fault.consecutive_unproductive} consecutive turns without a BenignSwarm call` : `${fault.
|
|
149
|
+
throw new CliError("turn_mode_fault", `turn mode is stopped after ${fault.reason === "unproductive" ? `${fault.consecutive_unproductive} consecutive turns without a BenignSwarm call` : `${fault.unproductive_last_hour} unproductive turns in the rolling hour`}; resume it with b9s-admin machine session resume; last output: ${fault.output_tail || "(empty)"}`);
|
|
132
150
|
}
|
|
133
151
|
const initialTurnPending = priorState.turn_guard?.turns.some((attempt) => attempt.productive === null) ?? false;
|
|
134
152
|
const rememberedSession = initialTurnPending && priorState.harness_session?.harness === harness ? priorState.harness_session.session_id : null;
|
|
@@ -140,6 +158,8 @@ export async function harnessStart(p, out, harness) {
|
|
|
140
158
|
let firstTurnLog = null;
|
|
141
159
|
if (harness === "dsh")
|
|
142
160
|
firstTurnLog = dshTurnLog(ref);
|
|
161
|
+
if (harness === "antigravity")
|
|
162
|
+
firstTurnLog = antigravityLog(ref);
|
|
143
163
|
if (adopt) {
|
|
144
164
|
session = adopt.toLowerCase();
|
|
145
165
|
if (harness === "codex") {
|
|
@@ -155,15 +175,22 @@ export async function harnessStart(p, out, harness) {
|
|
|
155
175
|
if (!claudeTranscript(session))
|
|
156
176
|
throw new CliError("not_found", `no Claude Code transcript for session ${session} under ~/.claude/projects on this machine`);
|
|
157
177
|
if (sandbox === "workspace-write") {
|
|
158
|
-
await runGuardedClaudeSandboxSelfCheck(ref, turnsPerHour, bin, settings, maxBudgetUsd, providerEnv, process.cwd(), randomUUID());
|
|
178
|
+
await runGuardedClaudeSandboxSelfCheck(ref, turnsPerHour, bin, settings, maxBudgetUsd, providerEnv, process.cwd(), randomUUID(), undefined, unproductivePerHour);
|
|
159
179
|
}
|
|
160
180
|
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
181
|
}
|
|
162
|
-
else {
|
|
182
|
+
else if (harness === "dsh") {
|
|
163
183
|
mkdirSync(joinPath(configRoot(), "logs"), { recursive: true });
|
|
164
184
|
closeSync(openSync(dshTurnLog(ref), "a"));
|
|
165
185
|
lines.push(`Adopted DeepSeek Harness session ${session}. Do not resume it elsewhere while the watcher runs it: two clients on one session conflict.`);
|
|
166
186
|
}
|
|
187
|
+
else {
|
|
188
|
+
if (!existsSync(antigravityConversationDb(session)))
|
|
189
|
+
throw new CliError("not_found", `no Antigravity conversation database for ${session} under ~/.gemini/antigravity-cli/conversations`);
|
|
190
|
+
lines.push(`Adopted Antigravity conversation ${session}. Do not resume it elsewhere while the watcher runs it: two clients on one conversation conflict.`);
|
|
191
|
+
}
|
|
192
|
+
if (harness === "antigravity" && sandbox === "workspace-write")
|
|
193
|
+
await runAntigravitySandboxSelfCheck(ref, bin, settings, process.cwd(), session, model, effort, turnTimeout * 60, firstTurnLog, turnsPerHour, antigravityTurnEnv(sandbox), unproductivePerHour);
|
|
167
194
|
}
|
|
168
195
|
}
|
|
169
196
|
else {
|
|
@@ -171,11 +198,11 @@ export async function harnessStart(p, out, harness) {
|
|
|
171
198
|
// first real turn resumes this same checked session and receives a separate reservation below.
|
|
172
199
|
if (harness === "claude-code" && sandbox === "workspace-write") {
|
|
173
200
|
session = randomUUID();
|
|
174
|
-
await runGuardedClaudeSandboxSelfCheck(ref, turnsPerHour, bin, settings, maxBudgetUsd, providerEnv, process.cwd(), session);
|
|
201
|
+
await runGuardedClaudeSandboxSelfCheck(ref, turnsPerHour, bin, settings, maxBudgetUsd, providerEnv, process.cwd(), session, undefined, unproductivePerHour);
|
|
175
202
|
}
|
|
176
203
|
const logDir = joinPath(configRoot(), "logs");
|
|
177
204
|
mkdirSync(logDir, { recursive: true });
|
|
178
|
-
firstTurnLog = harness === "dsh" ? dshTurnLog(ref) : harness === "claude-code" ? claudeResultFile(ref) : joinPath(logDir, `${harness}.${ref.replace("/", ".")}.first-turn.jsonl`);
|
|
205
|
+
firstTurnLog = harness === "dsh" ? dshTurnLog(ref) : harness === "claude-code" ? claudeResultFile(ref) : harness === "antigravity" ? antigravityLog(ref) : joinPath(logDir, `${harness}.${ref.replace("/", ".")}.first-turn.jsonl`);
|
|
179
206
|
const prompt = [
|
|
180
207
|
`[b9s] You are ${ref}, a BenignSwarm agent, started headless by \`b9s ${cmd}\`; nobody is typing to you.`,
|
|
181
208
|
`Your watcher starts a turn for you whenever something needs you, so end your turn when nothing is left to do.`,
|
|
@@ -183,7 +210,7 @@ export async function harnessStart(p, out, harness) {
|
|
|
183
210
|
`If you ran on another machine before, read your latest note first: \`b9s handoffs --agent ${creds.agent}\` (your units, branches and chat are on the server as before).`,
|
|
184
211
|
].join("\n");
|
|
185
212
|
const diagnostic = [];
|
|
186
|
-
if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (m) => diagnostic.push(m)))) {
|
|
213
|
+
if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (m) => diagnostic.push(m), process.env, unproductivePerHour))) {
|
|
187
214
|
throw new CliError("turn_mode_fault", diagnostic.at(-1) ?? "turn mode guard refused the onboarding turn");
|
|
188
215
|
}
|
|
189
216
|
try {
|
|
@@ -197,6 +224,14 @@ export async function harnessStart(p, out, harness) {
|
|
|
197
224
|
initialPid = started.pid;
|
|
198
225
|
lines.push(`Started DeepSeek Harness session ${session}; its first turn (reading its role and inbox) is running, event log: ${firstTurnLog}`);
|
|
199
226
|
}
|
|
227
|
+
else if (harness === "antigravity") {
|
|
228
|
+
const started = runAntigravityTurn(bin, antigravityTurnArgs(prompt, model, effort, turnTimeout * 60, settings), firstTurnLog, process.cwd(), ref, undefined, undefined, antigravityTurnEnv(sandbox));
|
|
229
|
+
session = started.conversation;
|
|
230
|
+
await completePendingTurnGuard(ref, probeFor(harness, session, ref), (message) => diagnostic.push(message), started.output, antigravityTokenTotal(started.record.result?.usage));
|
|
231
|
+
lines.push(`Started Antigravity conversation ${session}; its first turn (reading its role and inbox) completed, JSON turn log: ${firstTurnLog}`);
|
|
232
|
+
if (sandbox === "workspace-write")
|
|
233
|
+
await runAntigravitySandboxSelfCheck(ref, bin, settings, process.cwd(), session, model, effort, turnTimeout * 60, firstTurnLog, turnsPerHour, antigravityTurnEnv(sandbox), unproductivePerHour);
|
|
234
|
+
}
|
|
200
235
|
else {
|
|
201
236
|
// Claude Code takes the session id from us, so nothing has to be read back from its output.
|
|
202
237
|
session ??= randomUUID();
|
|
@@ -209,7 +244,7 @@ export async function harnessStart(p, out, harness) {
|
|
|
209
244
|
await completePendingTurnGuard(ref, probeFor(harness, session ?? "", ref), (m) => diagnostic.push(m), `${error.message}\n${raw}`.slice(-800));
|
|
210
245
|
const fault = readState(ref).turn_guard?.fault;
|
|
211
246
|
if (fault)
|
|
212
|
-
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)"}`);
|
|
247
|
+
throw new CliError("turn_mode_fault", `turn mode stopped after ${fault.reason === "unproductive" ? `${fault.consecutive_unproductive} consecutive turns without a BenignSwarm call` : `${fault.unproductive_last_hour} unproductive turns in the rolling hour`}; estimated tokens spent: ${fault.estimated_tokens}; last output: ${fault.output_tail || "(empty)"}`);
|
|
213
248
|
throw error;
|
|
214
249
|
}
|
|
215
250
|
}
|
|
@@ -219,8 +254,10 @@ export async function harnessStart(p, out, harness) {
|
|
|
219
254
|
// hook knows the agent from BSCHAT_AGENT (the watcher sets it for every turn), so it needs no map.
|
|
220
255
|
if (harness === "codex")
|
|
221
256
|
bindSession("codex", session, ref);
|
|
222
|
-
|
|
223
|
-
|
|
257
|
+
if (harness === "antigravity")
|
|
258
|
+
bindSession("antigravity", session, ref);
|
|
259
|
+
const transcript = harness === "dsh" ? dshTurnLog(ref) : harness === "antigravity" ? antigravityLog(ref) : harness === "claude-code" ? claudeTranscript(session) ?? firstTurnLog ?? "" : codexRollout(session) ?? firstTurnLog ?? "";
|
|
260
|
+
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
261
|
// A session adopted here may end in a usage-limit error from the machine it came from, written in
|
|
225
262
|
// that machine's local time ("3:32 PM" Central read as UTC on ronald: six hours off). Only errors
|
|
226
263
|
// from turns on this machine pause it; if the account is still limited, the next turn says so here.
|
|
@@ -231,8 +268,10 @@ export async function harnessStart(p, out, harness) {
|
|
|
231
268
|
? [bin, "exec", "resume", session, ...settings].map(shq).join(" ") + " {text}"
|
|
232
269
|
: harness === "dsh"
|
|
233
270
|
? dshResumeCommand(bin, session, settings, dshTurnLog(ref))
|
|
234
|
-
|
|
235
|
-
|
|
271
|
+
: harness === "antigravity"
|
|
272
|
+
? antigravityResumeCommand(bin, session, model, effort, turnTimeout * 60, settings, antigravityLog(ref))
|
|
273
|
+
// The result goes to a file the watcher reads when the turn ends: Claude Code can exit 0 with is_error set.
|
|
274
|
+
: `${shq(bin)} -p {text} ${[...settings, ...(sandbox === "workspace-write" ? claudeTurnArgs(maxBudgetUsd) : []), "--resume", session, "--output-format", "json"].map(shq).join(" ")} > ${shq(claudeResultFile(ref))}`;
|
|
236
275
|
const watcherOut = [];
|
|
237
276
|
// Scratch space beside the checkout, not the system's /tmp: on a machine the checkout lives on the
|
|
238
277
|
// work volume, the folder is inside what the sandbox may write, and it survives a reboot. Learned
|
|
@@ -240,7 +279,7 @@ export async function harnessStart(p, out, harness) {
|
|
|
240
279
|
// volume had 750 GB free, and which empties /tmp at every boot.
|
|
241
280
|
const tmp = sessionTmpDir(process.cwd(), creds.agent);
|
|
242
281
|
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 });
|
|
282
|
+
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, unproductivePerHour, provider, model });
|
|
244
283
|
const wl = watcherOut.join("\n").split("\n");
|
|
245
284
|
lines.push(wl[0].replace(/^Wrote /, "Watcher: wrote "), ...wl.filter((l) => l.startsWith("Linger is off")));
|
|
246
285
|
// 5. Hooks.
|
|
@@ -255,13 +294,17 @@ export async function harnessStart(p, out, harness) {
|
|
|
255
294
|
else if (harness === "dsh") {
|
|
256
295
|
lines.push("DeepSeek Harness runs the headless profile without an interactive approval prompt; b9s identifies this agent through BSCHAT_AGENT on each turn.");
|
|
257
296
|
}
|
|
297
|
+
else if (harness === "antigravity") {
|
|
298
|
+
lines.push("Antigravity runs headless turns with the machine's cached agy login; b9s binds this conversation and records JSON token usage.");
|
|
299
|
+
}
|
|
258
300
|
else {
|
|
259
301
|
lines.push(`Claude Code runs b9s's hooks from this checkout's .claude/settings.local.json (written by join).`);
|
|
260
302
|
}
|
|
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.`);
|
|
303
|
+
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
304
|
lines.push(harness === "dsh"
|
|
263
305
|
? `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
|
-
:
|
|
306
|
+
: 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.`
|
|
307
|
+
: `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
308
|
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
309
|
}
|
|
267
310
|
export const dshStartArgs = (settings) => ["--profile", "headless", "--json", ...settings, "-"];
|
|
@@ -413,9 +456,9 @@ export function runClaudeSandboxSelfCheck(bin, settings, maxBudgetUsd, env, cwd,
|
|
|
413
456
|
return { output, tokens };
|
|
414
457
|
}
|
|
415
458
|
/** Guard a model-spending connectivity preflight independently from the agent's real turn. */
|
|
416
|
-
export async function runGuardedClaudeSandboxSelfCheck(ref, turnsPerHour, bin, settings, maxBudgetUsd, env, cwd, session, run = runClaudeSandboxSelfCheck) {
|
|
459
|
+
export async function runGuardedClaudeSandboxSelfCheck(ref, turnsPerHour, bin, settings, maxBudgetUsd, env, cwd, session, run = runClaudeSandboxSelfCheck, unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR) {
|
|
417
460
|
const diagnostic = [];
|
|
418
|
-
if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (message) => diagnostic.push(message)))) {
|
|
461
|
+
if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (message) => diagnostic.push(message), process.env, unproductivePerHour))) {
|
|
419
462
|
throw new CliError("turn_mode_fault", diagnostic.at(-1) ?? "turn mode guard refused the sandbox self-check");
|
|
420
463
|
}
|
|
421
464
|
const probe = probeFor("claude-code", session, ref);
|
|
@@ -428,13 +471,70 @@ export async function runGuardedClaudeSandboxSelfCheck(ref, turnsPerHour, bin, s
|
|
|
428
471
|
await completePendingTurnGuard(ref, probe, (message) => diagnostic.push(message), output, null);
|
|
429
472
|
const fault = readState(ref).turn_guard?.fault;
|
|
430
473
|
if (fault)
|
|
431
|
-
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)"}`);
|
|
474
|
+
throw new CliError("turn_mode_fault", `turn mode stopped after ${fault.reason === "unproductive" ? `${fault.consecutive_unproductive} consecutive turns without a BenignSwarm call` : `${fault.unproductive_last_hour} unproductive turns in the rolling hour`}; estimated tokens spent: ${fault.estimated_tokens}; last output: ${fault.output_tail || "(empty)"}`);
|
|
432
475
|
throw error;
|
|
433
476
|
}
|
|
434
477
|
await completePendingTurnGuard(ref, probe, (message) => diagnostic.push(message), result.output, result.tokens);
|
|
435
478
|
const fault = readState(ref).turn_guard?.fault;
|
|
436
479
|
if (fault)
|
|
437
|
-
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)"}`);
|
|
480
|
+
throw new CliError("turn_mode_fault", `turn mode stopped after ${fault.reason === "unproductive" ? `${fault.consecutive_unproductive} consecutive turns without a BenignSwarm call` : `${fault.unproductive_last_hour} unproductive turns in the rolling hour`}; estimated tokens spent: ${fault.estimated_tokens}; last output: ${fault.output_tail || "(empty)"}`);
|
|
481
|
+
}
|
|
482
|
+
function antigravityTokenTotal(usage) {
|
|
483
|
+
return antigravityTotalTokens(usage);
|
|
484
|
+
}
|
|
485
|
+
export function assertAntigravitySelfCheck(output) {
|
|
486
|
+
let outer;
|
|
487
|
+
try {
|
|
488
|
+
outer = JSON.parse(output);
|
|
489
|
+
}
|
|
490
|
+
catch {
|
|
491
|
+
throw new CliError("sandbox_self_check_failed", `Antigravity workspace-write self-check returned invalid JSON: ${output.trim().slice(-1500)}; watcher was not enabled`);
|
|
492
|
+
}
|
|
493
|
+
if (typeof outer.response !== "string")
|
|
494
|
+
throw new CliError("sandbox_self_check_failed", "Antigravity workspace-write self-check returned no response; watcher was not enabled");
|
|
495
|
+
let checks;
|
|
496
|
+
try {
|
|
497
|
+
checks = JSON.parse(outer.response);
|
|
498
|
+
}
|
|
499
|
+
catch {
|
|
500
|
+
throw new CliError("sandbox_self_check_failed", `Antigravity self-check response was not the required JSON: ${outer.response.slice(-1500)}; watcher was not enabled`);
|
|
501
|
+
}
|
|
502
|
+
if (checks.b9s_me?.status !== 0 || !checks.b9s_me.output?.includes("agent:")) {
|
|
503
|
+
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`);
|
|
504
|
+
}
|
|
505
|
+
if (checks.git_ls_remote_origin?.status !== 0) {
|
|
506
|
+
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`);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
/** Run the two connectivity checks through the real model tools inside the per-turn sandbox. */
|
|
510
|
+
export async function runAntigravitySandboxSelfCheck(ref, bin, settings, cwd, session, model, effort, timeoutSeconds, logPath, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = antigravityTurnEnv("workspace-write"), unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR) {
|
|
511
|
+
const diagnostic = [];
|
|
512
|
+
if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (message) => diagnostic.push(message), process.env, unproductivePerHour))) {
|
|
513
|
+
throw new CliError("turn_mode_fault", diagnostic.at(-1) ?? "turn mode guard refused the Antigravity sandbox self-check");
|
|
514
|
+
}
|
|
515
|
+
const prompt = [
|
|
516
|
+
"BenignSwarm sandbox startup check. Use your terminal tool to execute these two commands separately, exactly as written:",
|
|
517
|
+
"1. b9s me",
|
|
518
|
+
"2. git ls-remote origin",
|
|
519
|
+
"Capture each real exit code and complete stdout/stderr. Do not infer or invent results.",
|
|
520
|
+
'Return only one JSON object with this shape: {"b9s_me":{"status":0,"output":"..."},"git_ls_remote_origin":{"status":0,"output":"..."}}.',
|
|
521
|
+
].join("\n");
|
|
522
|
+
let started;
|
|
523
|
+
try {
|
|
524
|
+
started = runAntigravityTurn(bin, antigravityTurnArgs(prompt, model, effort, timeoutSeconds, settings, session), logPath, cwd, ref, session, undefined, env);
|
|
525
|
+
}
|
|
526
|
+
catch (error) {
|
|
527
|
+
await completePendingTurnGuard(ref, probeFor("antigravity", session, ref), (message) => diagnostic.push(message), error.message, null);
|
|
528
|
+
const fault = readState(ref).turn_guard?.fault;
|
|
529
|
+
if (fault)
|
|
530
|
+
throw new CliError("turn_mode_fault", `turn mode stopped after ${fault.reason === "unproductive" ? `${fault.consecutive_unproductive} consecutive turns without a BenignSwarm call` : `${fault.unproductive_last_hour} unproductive turns in the rolling hour`}; estimated tokens spent: ${fault.estimated_tokens}; last output: ${fault.output_tail || "(empty)"}`);
|
|
531
|
+
throw error;
|
|
532
|
+
}
|
|
533
|
+
await completePendingTurnGuard(ref, probeFor("antigravity", session, ref), (message) => diagnostic.push(message), started.output, antigravityTokenTotal(started.record.result?.usage));
|
|
534
|
+
const fault = readState(ref).turn_guard?.fault;
|
|
535
|
+
if (fault)
|
|
536
|
+
throw new CliError("turn_mode_fault", `turn mode stopped after ${fault.reason === "unproductive" ? `${fault.consecutive_unproductive} consecutive turns without a BenignSwarm call` : `${fault.unproductive_last_hour} unproductive turns in the rolling hour`}; estimated tokens spent: ${fault.estimated_tokens}; last output: ${fault.output_tail || "(empty)"}`);
|
|
537
|
+
assertAntigravitySelfCheck(started.output);
|
|
438
538
|
}
|
|
439
539
|
/**
|
|
440
540
|
* The Codex settings a headless turn runs with. Under workspace-write the agent still has to reach
|