benignswarm 0.12.116 → 0.12.118

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,7 +1,7 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { appendFileSync, existsSync, mkdirSync, readFileSync, realpathSync, statSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
- import { basename, delimiter, dirname, join } from "node:path";
4
+ import { basename, delimiter, dirname, join, sep } from "node:path";
5
5
  import { configRoot } from "./config.js";
6
6
  import { repoDirectory } from "./directories.js";
7
7
  import { CliError } from "./errors.js";
@@ -60,11 +60,21 @@ export function antigravitySettings(sandbox, cwd, b9sHome, apiHost, extraWritabl
60
60
  throw new CliError("usage", "the BenignSwarm API host is invalid for Antigravity sandbox permissions");
61
61
  if (!b9sBin)
62
62
  throw new CliError("not_installed", "the recorded b9s install path is required for Antigravity workspace-write");
63
- const dirs = [...new Set([dirname(cwd), b9sHome, ...extraWritable])];
63
+ // Antigravity runs the agent's commands in the outermost workspace folder. A workspace folder
64
+ // that contains the checkout (its parent, where unit worktrees and the clone's git data live)
65
+ // therefore moved every command out of the checkout: `git` found no repository and the start's
66
+ // own check failed. Such folders are granted by permission instead, and only folders beside the
67
+ // checkout are added as workspaces. Verified with agy 1.5.11: pwd is the checkout, git reaches
68
+ // origin, and a sibling worktree can be created.
69
+ const wanted = [...new Set([dirname(cwd), b9sHome, ...extraWritable])];
70
+ const containsCheckout = (dir) => cwd === dir || cwd.startsWith(dir.endsWith(sep) ? dir : dir + sep);
71
+ const around = wanted.filter(containsCheckout);
72
+ const beside = wanted.filter((dir) => !containsCheckout(dir));
73
+ const allow = [...new Set([...antigravitySandboxPermissions(apiHost, b9sHome, b9sBin, nodeBin, repoDirectory(cwd)), ...around.map((dir) => `write_file(${dir})`)])];
64
74
  return [
65
75
  "--sandbox", "--settings",
66
- JSON.stringify({ enableTerminalSandbox: true, toolPermission: "proceed-in-sandbox", permissions: { allow: antigravitySandboxPermissions(apiHost, b9sHome, b9sBin, nodeBin, repoDirectory(cwd)) } }),
67
- ...dirs.flatMap((dir) => ["--add-dir", dir]),
76
+ JSON.stringify({ enableTerminalSandbox: true, toolPermission: "proceed-in-sandbox", permissions: { allow } }),
77
+ ...beside.flatMap((dir) => ["--add-dir", dir]),
68
78
  ];
69
79
  }
70
80
  export function antigravityTurnArgs(prompt, model, effort, timeoutSeconds, settings, conversation) {
package/dist/args.js CHANGED
@@ -10,7 +10,7 @@ export const LIST_FLAGS = [
10
10
  export const STRING_FLAGS = [
11
11
  "as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task",
12
12
  "state", "blocked-on", "tags", "custom", "vendor", "role", "description", "permissions",
13
- "cardinality", "assign-outside-qualifications", "machine", "idempotency-key", "dir", "confirm", "impact-revision", "type",
13
+ "cardinality", "assign-outside-qualifications", "judges", "machine", "idempotency-key", "dir", "confirm", "impact-revision", "type",
14
14
  "name", "out", "token", "token-file", "prefix", "uses", "expires-hours", "skill-dir", "harness", "provider", "reply-to",
15
15
  "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent",
16
16
  "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval",
@@ -22,6 +22,7 @@ export const STRING_FLAGS = [
22
22
  "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit",
23
23
  "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email",
24
24
  "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on",
25
+ "flow-summary", "flow-min-age", "flow-min-impact",
25
26
  "sandbox", "thread", "turn-timeout", "turns-per-hour", "unproductive-per-hour", "turn-coalesce-seconds", "session", "operation",
26
27
  "plain", "if-yes", "if-no", "ssh", "variant", "count", "min", "max", "needs", "min-ram", "exclude", "carry", "from",
27
28
  "to-ssh", "ssh-from", "wait", "writable", "writable-root", "dsh", "agy", "for", "until", "reason", "at", "requires",
@@ -11,7 +11,7 @@ import { milestoneWith, milestonesWith } from "./wu.js";
11
11
  import { awayUntil } from "./agent.js";
12
12
  import { agentMove, machineAdmin, poolAdmin, projectCheckoutAdmin, projectRepoAdmin } from "./machine-admin.js";
13
13
  import { routingAdmin, runRequiredClassUpdate } from "./routing-admin.js";
14
- import { accountAdmin, answerAdmin, explainAdmin, keysAdmin, needsAdmin, notifierAdmin, processAdmin, skillAdmin, tagList, textCheckAdmin, worktreeAdmin } from "./operator.js";
14
+ import { accountAdmin, answerAdmin, explainAdmin, keysAdmin, needsAdmin, notifierAdmin, processAdmin, skillAdmin, tagList, textCheckAdmin, turnJudgeAdmin, worktreeAdmin } from "./operator.js";
15
15
  import { adminNotice } from "./notices.js";
16
16
  import { cloudAdmin } from "./cloud-admin.js";
17
17
  import { projectImageAdmin } from "./image-admin.js";
@@ -128,6 +128,9 @@ export async function admin(p, out) {
128
128
  return notifierAdmin(p, out);
129
129
  case "account":
130
130
  return accountAdmin(p, out);
131
+ case "turn-judgment":
132
+ case "turn-judgments":
133
+ return turnJudgeAdmin(action, rest, p, out);
131
134
  case "text-check":
132
135
  return textCheckAdmin(action, p, out);
133
136
  case "worktree":
@@ -446,12 +449,15 @@ async function role(action, rest, p, out) {
446
449
  const base = proj ? `/projects/${proj}/roles` : "/roles";
447
450
  if (action === "list") {
448
451
  const r = await c.call("GET", base);
449
- const rows = r.roles.map((x) => ({ name: x.name, scope: x.project_id ? "project" : "account", reviews: (x.reviews ?? []).join(",") || "-", works: (x.works ?? []).join(",") || "-", trials: (x.trials ?? []).join(",") || "-", assign_outside_qualifications: !!x.assign_outside_qualifications, cardinality: x.cardinality, projects: x.project_id ? "(own)" : (x.permissions.projects ?? []).join(",") || "(none)", post: x.permissions.post_channels.join(","), broadcast: x.permissions.broadcast, create_channels: x.permissions.create_channels, read_account_status: x.permissions.read_account_status }));
450
- out.print(table(rows, ["name", "scope", "reviews", "works", "trials", "assign_outside_qualifications", "cardinality", "projects", "post", "broadcast", "create_channels", "read_account_status"]), r);
452
+ const rows = r.roles.map((x) => ({ name: x.name, scope: x.project_id ? "project" : "account", reviews: (x.reviews ?? []).join(",") || "-", works: (x.works ?? []).join(",") || "-", trials: (x.trials ?? []).join(",") || "-", assign_outside_qualifications: !!x.assign_outside_qualifications, judges: !!x.judges, cardinality: x.cardinality, projects: x.project_id ? "(own)" : (x.permissions.projects ?? []).join(",") || "(none)", post: x.permissions.post_channels.join(","), broadcast: x.permissions.broadcast, create_channels: x.permissions.create_channels, read_account_status: x.permissions.read_account_status }));
453
+ out.print(table(rows, ["name", "scope", "reviews", "works", "trials", "assign_outside_qualifications", "judges", "cardinality", "projects", "post", "broadcast", "create_channels", "read_account_status"]), r);
451
454
  }
452
455
  else if (action === "create" && rest[0]) {
453
456
  const permissions = permsFromFlags(p, !!proj) ?? { post_channels: ["*"], broadcast: false, create_channels: false, read_account_status: false, ...(proj ? {} : { projects: [] }) };
454
- const r = await c.call("POST", base, { name: rest[0], description: str(p.flags, "description") ?? "", permissions, cardinality: str(p.flags, "cardinality") ?? "many", reviews: tagList(str(p.flags, "reviews")) ?? [], works: tagList(str(p.flags, "works")) ?? [], trials: tagList(str(p.flags, "trials")) ?? [] });
457
+ const judgesFlag = str(p.flags, "judges");
458
+ if (judgesFlag !== undefined && judgesFlag !== "yes" && judgesFlag !== "no")
459
+ throw new CliError("usage", "--judges must be yes or no");
460
+ const r = await c.call("POST", base, { name: rest[0], description: str(p.flags, "description") ?? "", permissions, cardinality: str(p.flags, "cardinality") ?? "many", reviews: tagList(str(p.flags, "reviews")) ?? [], works: tagList(str(p.flags, "works")) ?? [], trials: tagList(str(p.flags, "trials")) ?? [], ...(judgesFlag !== undefined ? { judges: judgesFlag === "yes" } : {}) });
455
461
  out.print(`created ${proj ? "project" : "account"} role ${r.role.name}${!proj ? ` (projects: ${r.role.permissions.projects.join(",") || "none; set with: b9s-admin role edit ${r.role.name} --projects a,b or '*'"})` : ""}`, r);
456
462
  }
457
463
  else if (action === "edit" && rest[0]) {
@@ -471,13 +477,19 @@ async function role(action, rest, p, out) {
471
477
  const permissions = permsFromFlags(p, !!proj);
472
478
  if (permissions)
473
479
  body.permissions = permissions;
480
+ const judges = str(p.flags, "judges");
481
+ if (judges !== undefined) {
482
+ if (judges !== "yes" && judges !== "no")
483
+ throw new CliError("usage", "--judges must be yes or no");
484
+ body.judges = judges === "yes";
485
+ }
474
486
  for (const q of ["reviews", "works", "trials"]) {
475
487
  const v = tagList(str(p.flags, q));
476
488
  if (v !== undefined)
477
489
  body[q] = v;
478
490
  }
479
491
  if (!Object.keys(body).length)
480
- throw new CliError("usage", "role edit needs --description, --cardinality, --assign-outside-qualifications yes|no, --projects, --post, --broadcast, --create-channels, --read-account-status, --permissions, --reviews, --works or --trials");
492
+ throw new CliError("usage", "role edit needs --description, --cardinality, --assign-outside-qualifications yes|no, --judges yes|no, --projects, --post, --broadcast, --create-channels, --read-account-status, --permissions, --reviews, --works or --trials");
481
493
  const r = await c.call("PATCH", `${base}/${rest[0]}`, body);
482
494
  out.print(`updated role ${r.role.name}: reviews=${(r.role.reviews ?? []).join(",") || "-"} works=${(r.role.works ?? []).join(",") || "-"} trials=${(r.role.trials ?? []).join(",") || "-"} projects=${r.role.permissions.projects.join(",") || "(none)"} post=${r.role.permissions.post_channels.join(",")} broadcast=${r.role.permissions.broadcast}`, r);
483
495
  }
@@ -486,7 +498,7 @@ async function role(action, rest, p, out) {
486
498
  out.print(`deleted role ${rest[0]}`, r);
487
499
  }
488
500
  else
489
- throw new CliError("usage", "admin role create|edit|list|delete <name> [--project p] [--projects a,b|*] [--post ch1,ch2] [--broadcast] [--create-channels] [--read-account-status] [--assign-outside-qualifications yes|no] [--description d] [--cardinality one|many]");
501
+ throw new CliError("usage", "admin role create|edit|list|delete <name> [--project p] [--projects a,b|*] [--post ch1,ch2] [--broadcast] [--create-channels] [--read-account-status] [--assign-outside-qualifications yes|no] [--judges yes|no] [--description d] [--cardinality one|many]");
490
502
  }
491
503
  async function workUnitAdmin(action, rest, p, out) {
492
504
  if (action === "required-class" && rest[0] && /^\d+$/.test(rest[1] ?? "")) {
@@ -91,6 +91,9 @@ export async function who(p, out) {
91
91
  }
92
92
  export async function status(p, out) {
93
93
  const sub = p.positionals[1];
94
+ // Bare `b9s status` is about the machine, not an agent: it needs no agent identity.
95
+ if (sub === undefined)
96
+ return (await import("./machine-status.js")).machineStatus(out);
94
97
  const { client, creds } = agentClient(p);
95
98
  if (sub === "set") {
96
99
  const body = {};
@@ -55,7 +55,7 @@ function formatSettings(s) {
55
55
  ];
56
56
  return lines.join("\n");
57
57
  }
58
- const USAGE = "b9s-admin environment settings show | settings set [--stage disabled|report_only|staged|enabled] [--projects a,b] [--machines m1,m2] [--resolved-retention-days n] [--wont-fix-retention-days n] [--alerts on|off] [--alert-cooldown-minutes n] | retention run [--dry-run] | alerts [list|evaluate]";
58
+ const USAGE = "b9s-admin environment settings show | settings set [--stage disabled|report_only|staged|enabled] [--projects a,b] [--machines m1,m2] [--resolved-retention-days n] [--wont-fix-retention-days n] [--alerts on|off] [--alert-cooldown-minutes n] | retention run --dry-run | alerts [list|evaluate]";
59
59
  export async function environmentAdmin(c, action, rest, p, out) {
60
60
  if (action === "settings") {
61
61
  const sub = rest[0] ?? "show";
@@ -97,9 +97,11 @@ export async function environmentAdmin(c, action, rest, p, out) {
97
97
  }
98
98
  if (action === "retention" && rest[0] === "run" && rest.length === 1) {
99
99
  const dryRun = bool(p.flags, "dry-run");
100
- const r = await c.call("POST", "/account/environment/retention/run", { dry_run: dryRun });
100
+ if (!dryRun)
101
+ throw new CliError("review_required", "Manual retention deletion requires the reviewed batch in Account → Environment. Use retention run --dry-run to inspect candidates.");
102
+ const r = await c.call("POST", "/account/environment/retention/run", { dry_run: true });
101
103
  const res = r.result;
102
- out.print(`${res.dry_run ? "Retention dry run" : "Retention prune"} (${res.ran_at}): ${res.candidates_resolved} resolved + ${res.candidates_wont_fix} wont_fix candidate(s); deleted ${res.deleted_issues}.`, r);
104
+ out.print(`Retention candidate preview (${res.ran_at}): ${res.candidates_resolved} resolved + ${res.candidates_wont_fix} wont_fix candidate(s); deleted ${res.deleted_issues}. Confirm a reviewed batch in Account → Environment.`, r);
103
105
  return;
104
106
  }
105
107
  if (action === "alerts") {
@@ -0,0 +1,133 @@
1
+ import { existsSync, statSync } from "node:fs";
2
+ import { hostname } from "node:os";
3
+ import { join } from "node:path";
4
+ import { Client } from "../client.js";
5
+ import { DEFAULT_URL } from "../config.js";
6
+ import { configDirectory } from "../directories.js";
7
+ import { MACHINE_LABEL, readInstall, serviceActive, watcherServices } from "../install.js";
8
+ import { checkReachable, interfaceFacts, requiredHosts } from "../network.js";
9
+ import { CLI_VERSION } from "../version.js";
10
+ const firstLine = (text) => text.split("\n")[0].slice(0, 220);
11
+ /** How old the service's latest report may be before the machine counts as not heard from. */
12
+ export const staleAfterSeconds = (interval) => Math.max(90, 3 * (interval ?? 30));
13
+ /** Fixed rules, no guessing: every line of the verdict names the fact it comes from. */
14
+ export function statusVerdict(input) {
15
+ const problems = [];
16
+ const limits = [];
17
+ if (!input.interfaces.length)
18
+ problems.push("no network interface has an address");
19
+ for (const r of input.reach)
20
+ if (!r.ok)
21
+ problems.push(`cannot reach ${r.host} (${r.purpose}): ${r.error}`);
22
+ if (input.install.recorded && input.install.recorded.version !== input.install.running) {
23
+ limits.push(`this command is b9s ${input.install.running} but the machine's recorded install is ${input.install.recorded.version} at ${input.install.recorded.bin}`);
24
+ }
25
+ const m = input.machine;
26
+ if (!m)
27
+ return { state: "NOT A PROVISIONED MACHINE", problems, limits };
28
+ if (m.daemon !== "running")
29
+ problems.push(`the machine daemon is ${m.daemon}: b9s machine service`);
30
+ if (m.cloudError)
31
+ problems.push(`the service did not answer for this machine: ${m.cloudError}`);
32
+ const cloud = m.cloud;
33
+ if (cloud) {
34
+ if (cloud.machine.quarantined_at)
35
+ problems.push(`the service has quarantined this machine since ${cloud.machine.quarantined_at}`);
36
+ if (!cloud.received)
37
+ problems.push("the service has never received a report from this machine");
38
+ else if (cloud.received.age_seconds > staleAfterSeconds(cloud.received.report_interval_seconds)) {
39
+ problems.push(`the service last heard from this machine ${cloud.received.age_seconds} s ago (reports are due every ${cloud.received.report_interval_seconds ?? 30} s)`);
40
+ }
41
+ const reported = cloud.report?.install?.version;
42
+ if (reported && reported !== input.install.running)
43
+ limits.push(`the daemon last reported b9s ${reported}; this command is ${input.install.running} (the daemon reports the new version after its restart)`);
44
+ if (cloud.report?.git_identity && cloud.report.git_identity.ok === false)
45
+ limits.push("git has no user name and email here; agents cannot commit");
46
+ for (const name of ["codex", "claude-code", "antigravity"]) {
47
+ const h = cloud.report?.[name];
48
+ if (!h || h.available === false)
49
+ continue;
50
+ if (h.logged_in === false)
51
+ limits.push(`${name}: not logged in`);
52
+ else if (h.sandbox && h.sandbox.ok === false)
53
+ limits.push(`${name}: sandbox check failed: ${firstLine(h.sandbox.error ?? "no reason reported")}`);
54
+ }
55
+ for (const s of cloud.sessions)
56
+ if (s.state === "error")
57
+ problems.push(`session ${s.id ?? "?"} is in error: ${firstLine(s.error ?? "no reason reported")}`);
58
+ }
59
+ return { state: problems.length ? "NOT READY" : limits.length ? "READY WITH LIMITS" : "READY", problems, limits };
60
+ }
61
+ function harnessLine(name, h) {
62
+ if (!h || h.available === false)
63
+ return null;
64
+ if (h.logged_in === false)
65
+ return `${name}: not logged in`;
66
+ return `${name}: logged in, sandbox ${h.sandbox ? (h.sandbox.ok ? "ok" : "FAILED") : "not checked"}`;
67
+ }
68
+ export function renderStatus(input, verdict) {
69
+ const m = input.machine;
70
+ const cloud = m?.cloud ?? null;
71
+ const heard = cloud?.received ? ` · the service heard from it ${cloud.received.age_seconds} s ago` : "";
72
+ const lines = [`${m?.name ?? input.host}: ${verdict.state}${verdict.state.startsWith("READY") ? heard : ""}`];
73
+ const row = (label, value) => lines.push(`${label.padEnd(12)} ${value}`);
74
+ row("install", `b9s ${input.install.running}${input.install.recorded ? ` (recorded install ${input.install.recorded.version} at ${input.install.recorded.bin})` : " (no recorded install on this machine)"}`);
75
+ row("network", input.interfaces.length ? input.interfaces.map((i) => `${i.name} ${i.addresses.join(", ")}`).join(" · ") : "no interface has an address");
76
+ row("internet", input.reach.map((r) => `${r.host} ${r.ok ? `ok ${r.ms} ms` : `FAILED (${r.error})`}`).join(" · "));
77
+ if (!m) {
78
+ row("machine", "not provisioned: no machine registration here, so no daemon and no report to the service");
79
+ }
80
+ else {
81
+ row("daemon", m.daemon);
82
+ row("service", cloud ? (cloud.received ? `last report received ${cloud.received.at} (${cloud.received.age_seconds} s ago)` : "no report received yet") : `no answer: ${m.cloudError}`);
83
+ if (cloud) {
84
+ const harnesses = [harnessLine("codex", cloud.report?.codex), harnessLine("claude-code", cloud.report?.["claude-code"]), harnessLine("antigravity", cloud.report?.antigravity)].filter((x) => x !== null);
85
+ row("harnesses", harnesses.length ? harnesses.join(" · ") : "none reported");
86
+ const errors = cloud.sessions.filter((s) => s.state === "error").length;
87
+ row("sessions", `${cloud.sessions.length} reported, ${errors} in error`);
88
+ row("labels", cloud.machine.labels.length ? cloud.machine.labels.join(", ") : "none");
89
+ }
90
+ }
91
+ if (verdict.problems.length) {
92
+ lines.push("problems");
93
+ for (const p of verdict.problems)
94
+ lines.push(` - ${p}`);
95
+ }
96
+ if (verdict.limits.length) {
97
+ lines.push("limits");
98
+ for (const l of verdict.limits)
99
+ lines.push(` - ${l}`);
100
+ }
101
+ if (!verdict.problems.length && !verdict.limits.length)
102
+ lines.push("problems none");
103
+ return lines.join("\n");
104
+ }
105
+ /** `b9s status`: this machine's own checks next to what the service holds about it. */
106
+ export async function machineStatus(out) {
107
+ const file = join(configDirectory(), "machine.json");
108
+ const creds = existsSync(file) && statSync(file).isFile()
109
+ ? (await import("./machine.js")).loadMachine()
110
+ : null;
111
+ const url = creds?.url ?? process.env.BSCHAT_URL ?? process.env.B9S_URL ?? DEFAULT_URL;
112
+ const recorded = readInstall();
113
+ const reach = await checkReachable(requiredHosts(url));
114
+ let machine = null;
115
+ if (creds) {
116
+ const service = watcherServices().find((s) => s.label === MACHINE_LABEL);
117
+ const daemon = service ? (serviceActive(service) ? "running" : "stopped") : "not installed";
118
+ let cloud = null;
119
+ let cloudError = null;
120
+ try {
121
+ cloud = await Client.raw(creds.url, creds.key).call("GET", "/machines/me/status");
122
+ }
123
+ catch (error) {
124
+ cloudError = firstLine(error.message);
125
+ }
126
+ machine = { name: creds.name, url: creds.url, daemon, cloud, cloudError };
127
+ }
128
+ const input = { host: hostname(), install: { running: CLI_VERSION, recorded: recorded ? { version: recorded.version, bin: recorded.bin } : null }, interfaces: interfaceFacts(), reach, machine };
129
+ const verdict = statusVerdict(input);
130
+ out.print(renderStatus(input, verdict), { ...input, machine: machine ? { ...machine } : null, verdict });
131
+ if (verdict.state === "NOT READY")
132
+ process.exitCode = 1;
133
+ }
@@ -6,6 +6,7 @@ import { chmodSync, closeSync, cpSync, existsSync, lstatSync, mkdirSync, mkdtemp
6
6
  import { arch, cpus, freemem, homedir, hostname, loadavg, platform, tmpdir, totalmem, userInfo } from "node:os";
7
7
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
8
8
  import { str } from "../args.js";
9
+ import { interfaceFacts } from "../network.js";
9
10
  import { Client } from "../client.js";
10
11
  import { agentRef, configRoot, loadAgent, resolveAgentName, saveAgent } from "../config.js";
11
12
  import { CliError } from "../errors.js";
@@ -18,7 +19,7 @@ import { installService, launchdFacts, launchdFactsLine, launchdGuidance, launch
18
19
  import { CLI_VERSION } from "../version.js";
19
20
  import { probeCapabilities } from "../capabilities.js";
20
21
  import { diskSpaceNotice } from "../notices.js";
21
- import { verifyClaudeProvider } from "../providers.js";
22
+ import { deepSeekKeyPath, verifyClaudeProvider } from "../providers.js";
22
23
  import { busyTurnPause, DEFAULT_TURNS_PER_HOUR, DEFAULT_UNPRODUCTIVE_PER_HOUR, resumeTurnGuard, verificationUnavailable } from "../turn-guard.js";
23
24
  import { defaultWorkspaceWritableRoots } from "../start-options.js";
24
25
  import { antigravityPath, antigravitySandboxPermissions, antigravityTurnArgs, antigravityTurnEnv, parseAntigravityJson } from "../antigravity.js";
@@ -29,6 +30,7 @@ import { agentContainerName, agentContainerRunArgs, detectEc2Host, ensurePinnedI
29
30
  import { machineEnvironmentChecks } from "../environment-checks.js";
30
31
  import { machineResourceTelemetry, measuredWatcherServiceMemoryLimits, parsePageSize } from "../machine-telemetry.js";
31
32
  import { macReadiness, macReadinessSteps } from "../macos-readiness.js";
33
+ import { collectModelChecksQueued, modelCheckRuntimeTuple, probeModelRunAsync } from "../model-checks.js";
32
34
  import { authorizeWorktreeScope, redactProcessCommand, scanWorktreeProcesses } from "../machine-processes.js";
33
35
  import { collectPruneProtection } from "../prune-protection.js";
34
36
  import { runMachineDaemonLoop } from "../machine-daemon.js";
@@ -1665,6 +1667,8 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1665
1667
  const workSpace = volumeSpace(actualWorkdir, "workdir");
1666
1668
  const facts = machineFacts([...providerChecks], {
1667
1669
  workdir: actualWorkdir,
1670
+ modelsToCheck: me.models_to_check ?? [],
1671
+ modelRunProbe: deps?.modelRunProbe,
1668
1672
  ec2Probe: () => onEc2,
1669
1673
  ...(imdsContainerProbe ? { containerImdsProbe: () => imdsContainerProbe } : {}),
1670
1674
  ...(hostContainerProbe ? { probes: { container: () => hostContainerProbe } } : {}),
@@ -2442,6 +2446,135 @@ function claudeReport(path = process.env.PATH ?? "", providersInUse = ["anthropi
2442
2446
  }
2443
2447
  return { ...f, sandbox: claudeSandboxCache.result, providers };
2444
2448
  }
2449
+ const modelCheckCacheFile = () => join(configRoot(), "state", "model-checks.json");
2450
+ function readModelCheckCache() {
2451
+ try {
2452
+ const parsed = JSON.parse(readFileSync(modelCheckCacheFile(), "utf8"));
2453
+ return Object.fromEntries(Object.entries(parsed).filter((entry) => {
2454
+ const value = entry[1];
2455
+ return !!value && (value.status === "ok" || value.status === "unsupported" || value.status === "unknown")
2456
+ && typeof value.harness === "string" && typeof value.model === "string" && typeof value.cache_key === "string"
2457
+ // Legacy unknown entries may represent an unavailable login rather than a model run.
2458
+ // Do not let those suppress the first real probe after readiness recovers.
2459
+ && (value.status !== "unknown" || value.probe_attempted === true);
2460
+ }));
2461
+ }
2462
+ catch {
2463
+ return {};
2464
+ }
2465
+ }
2466
+ function writeModelCheckCache(cache) {
2467
+ mkdirSync(dirname(modelCheckCacheFile()), { recursive: true });
2468
+ writeFileSync(modelCheckCacheFile(), JSON.stringify(cache, null, 2) + "\n", { mode: 0o600 });
2469
+ }
2470
+ function jsonRecord(path) {
2471
+ try {
2472
+ const value = JSON.parse(readFileSync(path, "utf8"));
2473
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
2474
+ }
2475
+ catch {
2476
+ return null;
2477
+ }
2478
+ }
2479
+ function recordAt(value, key) {
2480
+ const nested = value?.[key];
2481
+ return nested && typeof nested === "object" && !Array.isArray(nested) ? nested : null;
2482
+ }
2483
+ function stableIdAt(value, keys) {
2484
+ for (const key of keys) {
2485
+ const id = value?.[key];
2486
+ if (typeof id === "string" && id.trim())
2487
+ return id.trim();
2488
+ }
2489
+ return null;
2490
+ }
2491
+ function jwtAccountSubject(token) {
2492
+ if (typeof token !== "string")
2493
+ return null;
2494
+ const parts = token.split(".");
2495
+ if (parts.length !== 3 || !parts[1])
2496
+ return null;
2497
+ try {
2498
+ const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
2499
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
2500
+ return null;
2501
+ return stableIdAt(payload, ["sub", "account_id", "accountUuid", "user_id"]);
2502
+ }
2503
+ catch {
2504
+ return null;
2505
+ }
2506
+ }
2507
+ function accountIdentityFingerprint(namespace, identifiers) {
2508
+ const stable = [...new Set(identifiers.filter((value) => !!value))];
2509
+ return stable.length ? createHash("sha256").update(JSON.stringify([namespace, ...stable])).digest("hex") : null;
2510
+ }
2511
+ /** Hash stable OAuth account identifiers only; rotating access/refresh tokens are never identity. */
2512
+ export function claudeAccountFingerprintForModelCheck(credentialsFile = join(claudeHome(), ".credentials.json"), configFile = join(homedir(), ".claude.json")) {
2513
+ const credentials = jsonRecord(credentialsFile);
2514
+ const oauth = recordAt(credentials, "claudeAiOauth");
2515
+ const config = jsonRecord(configFile);
2516
+ const account = recordAt(config, "oauthAccount");
2517
+ const tokenAccount = recordAt(oauth, "oauthAccount");
2518
+ return accountIdentityFingerprint("claude-code", [
2519
+ jwtAccountSubject(oauth?.accessToken),
2520
+ stableIdAt(oauth, ["accountUuid", "account_id", "user_id"]),
2521
+ stableIdAt(tokenAccount, ["accountUuid", "account_id", "user_id"]),
2522
+ stableIdAt(account, ["accountUuid", "account_id", "user_id"]),
2523
+ stableIdAt(oauth, ["organizationUuid", "organization_id"]) ?? stableIdAt(account, ["organizationUuid", "organization_id"]),
2524
+ ]);
2525
+ }
2526
+ /** Gemini's OAuth ID token subject is stable across access-token refreshes and never reported. */
2527
+ export function antigravityAccountFingerprintForModelCheck(credentialsFile = join(homedir(), ".gemini", "oauth_creds.json")) {
2528
+ const credentials = jsonRecord(credentialsFile);
2529
+ return accountIdentityFingerprint("antigravity", [
2530
+ jwtAccountSubject(credentials?.id_token),
2531
+ // The agy command's own token file names the signed-in account as `id_token_email`.
2532
+ stableIdAt(credentials, ["account_id", "accountId", "user_id", "id_token_email"]),
2533
+ ]);
2534
+ }
2535
+ function accountFingerprintForModelCheck(harness, provider) {
2536
+ if (harness === "codex")
2537
+ return codexAccountFingerprint();
2538
+ if (harness === "claude-code" && provider === "deepseek") {
2539
+ try {
2540
+ return createHash("sha256").update(readFileSync(deepSeekKeyPath())).digest("hex");
2541
+ }
2542
+ catch {
2543
+ return null;
2544
+ }
2545
+ }
2546
+ if (harness === "claude-code") {
2547
+ const credentialsFile = join(claudeHome(), ".credentials.json");
2548
+ const configFiles = [...new Set([join(claudeHome(), ".claude.json"), join(homedir(), ".claude.json")])];
2549
+ for (const configFile of configFiles) {
2550
+ const fingerprint = claudeAccountFingerprintForModelCheck(credentialsFile, configFile);
2551
+ if (fingerprint)
2552
+ return fingerprint;
2553
+ }
2554
+ return null;
2555
+ }
2556
+ if (harness === "antigravity") {
2557
+ // agy keeps its login in ~/.gemini/antigravity-cli/antigravity-oauth-token (the only file on a
2558
+ // Linux host that never ran another client); without it every Antigravity model read "not verified".
2559
+ for (const credentialsFile of [join(homedir(), ".gemini", "antigravity-cli", "antigravity-oauth-token"), join(homedir(), ".gemini", "oauth_creds.json"), join(homedir(), ".gemini", "antigravity", "oauth_creds.json")]) {
2560
+ const fingerprint = antigravityAccountFingerprintForModelCheck(credentialsFile);
2561
+ if (fingerprint)
2562
+ return fingerprint;
2563
+ }
2564
+ return null;
2565
+ }
2566
+ const candidates = harness === "dsh"
2567
+ ? [join(homedir(), ".config", "deepseek-harness", "auth.json"), join(homedir(), ".deepseek-harness", "auth.json")]
2568
+ : [];
2569
+ for (const path of candidates) {
2570
+ try {
2571
+ return createHash("sha256").update(readFileSync(path)).digest("hex");
2572
+ }
2573
+ catch { /* try the next supported credential location */ }
2574
+ }
2575
+ const envCredential = harness === "dsh" ? process.env.DEEPSEEK_API_KEY ?? process.env.DSH_API_KEY : undefined;
2576
+ return envCredential ? createHash("sha256").update(envCredential).digest("hex") : null;
2577
+ }
2445
2578
  /** What the operator needs to know about this machine, reported with every pass. */
2446
2579
  export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sessions = [], diskFloorPct = DEFAULT_CACHE_FLOOR_PCT) {
2447
2580
  const opts = typeof workdirOrOpts === "object" && workdirOrOpts !== null ? workdirOrOpts : {};
@@ -2449,16 +2582,19 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
2449
2582
  const probes = opts.probes;
2450
2583
  const path = process.env.PATH ?? "";
2451
2584
  const env = { ...process.env, PATH: path };
2452
- const codexFactsValue = probes?.codex
2585
+ const readCodexFacts = () => probes?.codex
2453
2586
  ? probes.codex()
2454
2587
  : (() => {
2455
2588
  const codex = spawnSync("codex", ["--version"], { encoding: "utf8", env });
2456
2589
  const login = codex.status === 0 ? spawnSync("codex", ["login", "status"], { encoding: "utf8", env }) : null;
2457
2590
  return codex.status === 0 ? { version: codex.stdout.trim(), logged_in: login?.status === 0 && /logged in/i.test(`${login.stdout}${login.stderr}`), login: `${login?.stdout ?? ""}${login?.stderr ?? ""}`.trim().slice(0, 200), account_fingerprint: codexAccountFingerprint(), sandbox: codexSandbox(false, path) } : null;
2458
2591
  })();
2459
- const dsh = (probes?.dsh ?? (() => dshFacts(platform(), path)))();
2592
+ const codexFactsValue = readCodexFacts();
2593
+ const readDshFacts = () => (probes?.dsh ?? (() => dshFacts(platform(), path)))();
2594
+ const dsh = readDshFacts();
2460
2595
  const probeAgent = antigravityProbeAgent(sessions);
2461
- const antigravity = probes?.antigravity ? probes.antigravity(probeAgent) : antigravityFacts(path, readInstall()?.bin ?? null, probeAgent);
2596
+ const readAntigravityFacts = () => probes?.antigravity ? probes.antigravity(probeAgent) : antigravityFacts(path, readInstall()?.bin ?? null, probeAgent);
2597
+ const antigravity = readAntigravityFacts();
2462
2598
  const homeSpace = volumeSpace(homedir(), "home");
2463
2599
  const readTelemetryFile = (path) => { try {
2464
2600
  return readFileSync(path, "utf8");
@@ -2488,7 +2624,23 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
2488
2624
  const telemetryAvailability = telemetry.metric_availability;
2489
2625
  const volumeFloorPct = diskFloorPct;
2490
2626
  const req = "/etc/codex/requirements.toml";
2491
- const claude = (probes?.claude ?? (() => claudeReport(path, providersInUse)))();
2627
+ const fingerprint = (harness, provider) => accountFingerprintForModelCheck(harness, provider);
2628
+ const readClaudeFacts = () => (probes?.claude ?? (() => claudeReport(path, providersInUse)))();
2629
+ const withClaudeIdentity = (value) => {
2630
+ if (!value)
2631
+ return null;
2632
+ const providerReports = value.providers;
2633
+ return {
2634
+ ...value,
2635
+ account_fingerprint: fingerprint("claude-code", "anthropic"),
2636
+ ...(providerReports ? { providers: Object.fromEntries(Object.entries(providerReports).map(([provider, report]) => [
2637
+ provider, { ...report, account_fingerprint: fingerprint("claude-code", provider) },
2638
+ ])) } : {}),
2639
+ };
2640
+ };
2641
+ const claude = withClaudeIdentity(readClaudeFacts());
2642
+ const dshWithIdentity = { ...dsh, account_fingerprint: fingerprint("dsh") };
2643
+ const antigravityWithIdentity = { ...antigravity, account_fingerprint: fingerprint("antigravity") };
2492
2644
  const bootedAt = (opts.bootTime ?? bootTimeMs)();
2493
2645
  const gitIdentity = (probes?.gitIdentity ?? (() => readGitIdentity()))();
2494
2646
  const container = (probes?.container ?? (() => probeNestedSandbox()))();
@@ -2511,6 +2663,8 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
2511
2663
  // macOS: which launchd domain the services use, so a headless Mac is visible, never silent (WU #478).
2512
2664
  ...(platform() === "darwin" ? { launchd: (probes?.launchd ?? launchdFacts)() } : {}),
2513
2665
  bschat: { version: CLI_VERSION, bin: requireInstall().bin },
2666
+ // IPv4 only: temporary IPv6 addresses rotate, and this report is compared for change.
2667
+ network: { interfaces: interfaceFacts(true) },
2514
2668
  git_identity: gitIdentity,
2515
2669
  on_ec2: onEc2,
2516
2670
  imds_blocked: imds.ok,
@@ -2521,8 +2675,8 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
2521
2675
  codex: codexFactsValue,
2522
2676
  "claude-code": claude,
2523
2677
  claude_code: claude,
2524
- dsh,
2525
- antigravity,
2678
+ dsh: dshWithIdentity,
2679
+ antigravity: antigravityWithIdentity,
2526
2680
  managed_hooks: managedHooks,
2527
2681
  linger: platform() === "linux" ? lingerEnabled() : null,
2528
2682
  disk_free_bytes: homeSpace?.freeBytes ?? null,
@@ -2541,6 +2695,29 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
2541
2695
  };
2542
2696
  }))();
2543
2697
  }
2698
+ const modelCache = readModelCheckCache();
2699
+ const readCurrentModelTuple = (request) => {
2700
+ if (request.harness === "codex")
2701
+ return modelCheckRuntimeTuple({ codex: readCodexFacts() }, request);
2702
+ if (request.harness === "claude-code") {
2703
+ const currentClaude = withClaudeIdentity(readClaudeFacts());
2704
+ return modelCheckRuntimeTuple({ "claude-code": currentClaude, claude_code: currentClaude }, request);
2705
+ }
2706
+ if (request.harness === "dsh") {
2707
+ return modelCheckRuntimeTuple({ dsh: { ...readDshFacts(), account_fingerprint: fingerprint("dsh") } }, request);
2708
+ }
2709
+ if (request.harness === "antigravity") {
2710
+ return modelCheckRuntimeTuple({ antigravity: { ...readAntigravityFacts(), account_fingerprint: fingerprint("antigravity") } }, request);
2711
+ }
2712
+ return { version: null, account: null, ready: false };
2713
+ };
2714
+ facts.model_checks = collectModelChecksQueued(opts.modelsToCheck ?? [], facts, modelCache, path, opts.modelRunProbe ?? probeModelRunAsync, (entry) => {
2715
+ const latest = readModelCheckCache();
2716
+ latest[entry.cache_key] = entry;
2717
+ writeModelCheckCache(latest);
2718
+ }, new Date(), readCurrentModelTuple);
2719
+ if ((opts.modelsToCheck ?? []).length)
2720
+ writeModelCheckCache(modelCache);
2544
2721
  return facts;
2545
2722
  }
2546
2723
  /** Parse root (`/`) mount specification from `/etc/fstab` (or kernel cmdline fallback) for UUID/PARTUUID safety. */