benignswarm 0.12.164 → 0.12.166

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.
@@ -6,6 +6,57 @@ import { Client } from "../client.js";
6
6
  import { loadAgent, resolveAgentName } from "../config.js";
7
7
  import { CliError } from "../errors.js";
8
8
  import { githubCredentialForRepository, remoteRepository } from "./git-credential.js";
9
+ const GH_RERUN_USAGE = 'Usage: b9s gh run rerun <run-id> --failed [--job <job-id>] --reason "..."';
10
+ export function parseFailedRerunArgs(args) {
11
+ if (args[0] !== "run" || args[1] !== "rerun")
12
+ throw new CliError("usage", GH_RERUN_USAGE);
13
+ const runId = args[2];
14
+ if (!runId || !/^[1-9][0-9]{0,19}$/.test(runId))
15
+ throw new CliError("usage", `run-id must be a positive numeric GitHub Actions run id.\n${GH_RERUN_USAGE}`);
16
+ let failed = false;
17
+ let jobId;
18
+ let reason;
19
+ for (let index = 3; index < args.length; index += 1) {
20
+ const arg = args[index];
21
+ if (arg === "--failed") {
22
+ if (failed)
23
+ throw new CliError("usage", `--failed may be specified only once.\n${GH_RERUN_USAGE}`);
24
+ failed = true;
25
+ }
26
+ else if (arg === "--job") {
27
+ if (jobId !== undefined)
28
+ throw new CliError("usage", `--job may be specified only once.\n${GH_RERUN_USAGE}`);
29
+ const value = args[++index];
30
+ if (!value || !/^[1-9][0-9]{0,19}$/.test(value))
31
+ throw new CliError("usage", `--job requires a positive numeric GitHub job id.\n${GH_RERUN_USAGE}`);
32
+ jobId = value;
33
+ }
34
+ else if (arg === "--reason") {
35
+ if (reason !== undefined)
36
+ throw new CliError("usage", `--reason may be specified only once.\n${GH_RERUN_USAGE}`);
37
+ const value = args[++index];
38
+ if (!value)
39
+ throw new CliError("usage", `--reason requires a value.\n${GH_RERUN_USAGE}`);
40
+ reason = value.trim();
41
+ }
42
+ else {
43
+ throw new CliError("github_option_unsupported", `b9s gh run rerun does not support ${arg}; it never permits full-run or arbitrary GitHub commands.\n${GH_RERUN_USAGE}`);
44
+ }
45
+ }
46
+ if (!failed)
47
+ throw new CliError("usage", `--failed is required; full workflow-run reruns are not supported.\n${GH_RERUN_USAGE}`);
48
+ if (!reason || reason.length > 800)
49
+ throw new CliError("usage", `--reason must contain 1 to 800 non-whitespace characters.\n${GH_RERUN_USAGE}`);
50
+ return { runId, ...(jobId ? { jobId } : {}), reason };
51
+ }
52
+ export async function requestFailedRerun(args, project, api, parsed = parseFailedRerunArgs(args)) {
53
+ const request = parsed;
54
+ return api("POST", `/projects/${encodeURIComponent(project)}/github/runs/${encodeURIComponent(request.runId)}/rerun-failed`, {
55
+ failed: true,
56
+ ...(request.jobId ? { job_id: request.jobId } : {}),
57
+ reason: request.reason,
58
+ });
59
+ }
9
60
  const run = (command, args, options) => spawnSync(command, args, options);
10
61
  function repositoryArgument(value) {
11
62
  if (!value)
@@ -15,18 +66,24 @@ function repositoryArgument(value) {
15
66
  }
16
67
  const GH_COMMAND_OPTIONS = {
17
68
  "pr view": {
18
- values: new Set(["--repo", "-R", "--hostname", "-H", "--json", "--jq", "--template"]),
69
+ values: new Set(["--json", "--jq", "--template"]),
19
70
  booleans: new Set(["--comments"]),
20
71
  },
21
72
  "pr checks": {
22
- values: new Set(["--repo", "-R", "--hostname", "-H", "--interval", "--json", "--jq", "--template"]),
73
+ values: new Set(["--interval", "--json", "--jq", "--template"]),
23
74
  booleans: new Set(["--watch", "--required", "--fail-fast"]),
24
75
  },
25
76
  "pr status": {
26
- values: new Set(["--repo", "-R", "--hostname", "-H", "--json", "--jq", "--template"]),
77
+ values: new Set(["--json", "--jq", "--template"]),
27
78
  booleans: new Set(),
28
79
  },
80
+ "run view": { values: new Set(["--job", "--json"]), booleans: new Set(["--log-failed"]) },
81
+ "run download": { values: new Set(["-n", "-p", "-D"]), booleans: new Set() },
82
+ "run list": { values: new Set(["--branch", "--commit", "--limit", "--json"]), booleans: new Set() },
29
83
  };
84
+ function positiveGitHubId(value) {
85
+ return /^[1-9]\d{0,19}$/.test(value);
86
+ }
30
87
  function pullRequestTarget(value, linkedRepository) {
31
88
  if (/^\d+$/.test(value))
32
89
  return Number(value) > 0;
@@ -45,12 +102,13 @@ function validateGhOperation(args, linkedRepository, env) {
45
102
  const operation = `${args[0] ?? ""} ${args[1] ?? ""}`;
46
103
  const contract = GH_COMMAND_OPTIONS[operation];
47
104
  if (!contract) {
48
- throw new CliError("github_command_unsupported", "b9s gh supports only read-only gh pr view, gh pr checks, and gh pr status operations.");
105
+ throw new CliError("github_command_unsupported", "b9s gh supports only read-only gh pr view/checks/status and gh run view/download/list operations.");
49
106
  }
50
107
  if (env.GH_REPO && repositoryArgument(env.GH_REPO) !== linkedRepository) {
51
108
  throw new CliError("github_repository_mismatch", `GH_REPO points to ${env.GH_REPO}, not the linked project repository ${linkedRepository}.`);
52
109
  }
53
110
  const positional = [];
111
+ const seen = new Map();
54
112
  for (let index = 2; index < args.length; index += 1) {
55
113
  const arg = args[index];
56
114
  if (arg === "--")
@@ -63,23 +121,22 @@ function validateGhOperation(args, linkedRepository, env) {
63
121
  const flag = equal > 0 ? arg.slice(0, equal) : (arg.startsWith("-R") && arg !== "-R" ? "-R" : arg);
64
122
  const inlineValue = equal > 0 ? arg.slice(equal + 1) : (flag === "-R" && arg !== "-R" ? arg.slice(2) : undefined);
65
123
  if (contract.values.has(flag)) {
124
+ if (seen.has(flag))
125
+ throw new CliError("github_option_unsupported", `${flag} may be supplied only once.`);
66
126
  const value = inlineValue ?? args[index + 1];
67
127
  if (!value || value.startsWith("--"))
68
128
  throw new CliError("usage", `${flag} requires a value.`);
69
129
  if (inlineValue === undefined)
70
130
  index += 1;
71
- if (flag === "--repo" || flag === "-R") {
72
- if (repositoryArgument(value) !== linkedRepository) {
73
- throw new CliError("github_repository_mismatch", `gh target ${value} is not the linked project repository ${linkedRepository}.`);
74
- }
75
- }
76
- else if ((flag === "--hostname" || flag === "-H") && value.toLowerCase() !== "github.com") {
77
- throw new CliError("github_host_unsupported", "b9s gh is pinned to github.com.");
78
- }
131
+ seen.set(flag, value);
79
132
  continue;
80
133
  }
81
- if (contract.booleans.has(flag) && inlineValue === undefined)
134
+ if (contract.booleans.has(flag) && inlineValue === undefined) {
135
+ if (seen.has(flag))
136
+ throw new CliError("github_option_unsupported", `${flag} may be supplied only once.`);
137
+ seen.set(flag, true);
82
138
  continue;
139
+ }
83
140
  throw new CliError("github_option_unsupported", `b9s gh does not support ${arg}.`);
84
141
  }
85
142
  if (operation === "pr status" && positional.length > 0) {
@@ -91,6 +148,43 @@ function validateGhOperation(args, linkedRepository, env) {
91
148
  if (positional.length > 1 || (operation === "pr status" && positional.length !== 0)) {
92
149
  throw new CliError("github_target_unsupported", `b9s gh ${operation} accepts at most one pull request target.`);
93
150
  }
151
+ if (operation === "run view" || operation === "run download") {
152
+ if (positional.length !== 1 || !positiveGitHubId(positional[0])) {
153
+ throw new CliError("github_target_unsupported", `b9s gh ${operation} requires one positive numeric GitHub run ID.`);
154
+ }
155
+ }
156
+ if (operation === "run view") {
157
+ const logFailed = seen.has("--log-failed");
158
+ const job = seen.get("--job");
159
+ const json = seen.get("--json");
160
+ if (job !== undefined && !positiveGitHubId(String(job)))
161
+ throw new CliError("github_target_unsupported", "--job requires a positive numeric GitHub job ID.");
162
+ if (job !== undefined && !logFailed)
163
+ throw new CliError("github_option_unsupported", "--job is supported only with --log-failed.");
164
+ if (json !== undefined && (!/^[A-Za-z][A-Za-z0-9]*(,[A-Za-z][A-Za-z0-9]*)*$/.test(String(json)) || logFailed || job !== undefined)) {
165
+ throw new CliError("github_option_unsupported", "run view --json requires a comma-separated field list and cannot be combined with log options.");
166
+ }
167
+ }
168
+ if (operation === "run download" && seen.has("-n") && seen.has("-p")) {
169
+ throw new CliError("github_option_unsupported", "run download accepts either -n <name> or -p <pattern>, not both.");
170
+ }
171
+ if (operation === "run list") {
172
+ if (positional.length !== 0)
173
+ throw new CliError("github_target_unsupported", "b9s gh run list does not accept a run ID.");
174
+ if (seen.has("--branch") && seen.has("--commit"))
175
+ throw new CliError("github_option_unsupported", "run list accepts either --branch or --commit, not both.");
176
+ const commit = seen.get("--commit");
177
+ if (commit !== undefined && !/^[0-9a-f]{7,64}$/i.test(String(commit)))
178
+ throw new CliError("github_option_unsupported", "--commit requires a 7-64 character hexadecimal commit SHA.");
179
+ const limit = seen.get("--limit");
180
+ if (limit !== undefined && (!/^\d+$/.test(String(limit)) || Number(limit) < 1 || Number(limit) > 1000)) {
181
+ throw new CliError("github_option_unsupported", "--limit must be an integer from 1 to 1000.");
182
+ }
183
+ const json = seen.get("--json");
184
+ if (json !== undefined && !/^[A-Za-z][A-Za-z0-9]*(,[A-Za-z][A-Za-z0-9]*)*$/.test(String(json))) {
185
+ throw new CliError("github_option_unsupported", "--json requires a comma-separated field list.");
186
+ }
187
+ }
94
188
  }
95
189
  export async function runGhWithProjectCredential(args, cwd, api, runner = run, parentEnv = process.env) {
96
190
  if (args.length === 0)
@@ -104,7 +198,8 @@ export async function runGhWithProjectCredential(args, cwd, api, runner = run, p
104
198
  throw new CliError("github_repository_required", "b9s gh only supports GitHub HTTPS or SSH repository origins.");
105
199
  }
106
200
  validateGhOperation(args, repository.path, parentEnv);
107
- const credential = await githubCredentialForRepository(repository.path, api, true);
201
+ const needsActionsRead = args[0] === "run";
202
+ const credential = await githubCredentialForRepository(repository.path, api, true, needsActionsRead ? "actions:read" : undefined);
108
203
  if (!credential?.password)
109
204
  throw new CliError("github_credential_missing", "The linked repository did not return a GitHub credential.");
110
205
  // The scoped installation token exists only in the gh child's environment. It is never
@@ -132,6 +227,8 @@ export async function runGhWithProjectCredential(args, cwd, api, runner = run, p
132
227
  encoding: "utf8",
133
228
  env: childEnv,
134
229
  stdio: ["inherit", "pipe", "pipe"],
230
+ // Failed workflow logs can be much larger than the 1 MiB spawnSync default.
231
+ maxBuffer: 64 * 1024 * 1024,
135
232
  });
136
233
  }
137
234
  finally {
@@ -151,6 +248,12 @@ export async function gh(args) {
151
248
  if (!agent.project)
152
249
  throw new CliError("github_not_connected", "b9s gh requires a project-scoped agent identity.");
153
250
  const client = Client.forAgent(agent, undefined, { presence: false });
251
+ if (args[0] === "run" && args[1] === "rerun") {
252
+ const request = parseFailedRerunArgs(args);
253
+ const result = await requestFailedRerun(args, agent.project, (method, path, body) => client.call(method, path, body), request);
254
+ process.stdout.write(`Requested failed-job rerun for run ${request.runId}${request.jobId ? `, job ${request.jobId}` : ""}. Audit: ${typeof result === "object" && result !== null && "audit_id" in result ? String(result.audit_id) : "recorded"}.\n`);
255
+ return 0;
256
+ }
154
257
  const base = `/projects/${encodeURIComponent(agent.project)}/git-credentials`;
155
258
  return runGhWithProjectCredential(args, process.cwd(), (method, _path, body) => client.call(method, base, body));
156
259
  }
@@ -39,7 +39,7 @@ export async function credentialResponse(input, api) {
39
39
  return `username=${credential.username}\npassword=${credential.password}\n\n`;
40
40
  }
41
41
  /** Resolve a short-lived token through the same scoped credential endpoint used by Git. */
42
- export async function githubCredentialForRepository(wanted, api, refuseUnlinkedRepository = false) {
42
+ export async function githubCredentialForRepository(wanted, api, refuseUnlinkedRepository = false, requiredPermission) {
43
43
  const metadata = await api("GET", "");
44
44
  if (!metadata.linked || !metadata.repository) {
45
45
  throw new CliError("github_not_connected", "GitHub is not connected for this project. Connect GitHub in the console to enable repository access.");
@@ -51,7 +51,7 @@ export async function githubCredentialForRepository(wanted, api, refuseUnlinkedR
51
51
  }
52
52
  return null;
53
53
  }
54
- return api("POST", "", {});
54
+ return api("POST", "", requiredPermission ? { required_permission: requiredPermission } : {});
55
55
  }
56
56
  function missingRepositoryPathHint(input) {
57
57
  const request = credentialInput(input);
@@ -25,6 +25,28 @@ function readStdinJson() {
25
25
  }
26
26
  }
27
27
  const THROTTLE_MS = 20_000;
28
+ /** Store only values the Antigravity runtime explicitly reports in its hook payload. */
29
+ export function rememberAntigravityRuntime(ref, input, env = process.env) {
30
+ const state = readState(ref, env);
31
+ const observation = (value) => {
32
+ if (typeof value !== "string")
33
+ return null;
34
+ const normalized = value.trim();
35
+ return normalized && normalized.toLowerCase() !== "unknown" ? normalized : null;
36
+ };
37
+ const model = observation(input.modelName);
38
+ const effort = [input.reasoningEffort, input.reasoning_effort, input.effort]
39
+ .map(observation)
40
+ .find((value) => value !== null) ?? null;
41
+ if ((!model || state.model === model) && (!effort || state.effort === effort))
42
+ return;
43
+ const observedAt = Date.now();
44
+ updateState(ref, (onDisk) => ({
45
+ ...onDisk,
46
+ ...(model ? { model, model_observed_at: observedAt } : {}),
47
+ ...(effort ? { effort, effort_observed_at: observedAt } : {}),
48
+ }), env);
49
+ }
28
50
  function omitMeasuresAlreadyIn(text, updates) {
29
51
  if (!text || !updates)
30
52
  return updates;
@@ -716,11 +738,7 @@ async function antigravityHook(p, payload) {
716
738
  }
717
739
  if (typeof input?.transcriptPath === "string" && input.transcriptPath)
718
740
  noteSession(name, "antigravity", input.transcriptPath, conv, event === "SessionStart" && input?.source === "compact");
719
- if (typeof input?.modelName === "string" && input.modelName) {
720
- const observed = input.modelName;
721
- if (readState(name).model !== observed)
722
- updateState(name, (onDisk) => ({ ...onDisk, model: observed, model_observed_at: Date.now() }));
723
- }
741
+ rememberAntigravityRuntime(name, input ?? {});
724
742
  const st = readState(name);
725
743
  if (Date.now() - (st.heartbeat_at ?? 0) > HEARTBEAT_MS) {
726
744
  try {
@@ -4,9 +4,10 @@ import { agentRef, DEFAULT_URL, loadAgent, resolveModel, saveAgent } from "../co
4
4
  import { spawnSync } from "node:child_process";
5
5
  import { readFileSync } from "node:fs";
6
6
  import { join as pathJoin } from "node:path";
7
+ import { homedir } from "node:os";
7
8
  import { CliError } from "../errors.js";
8
9
  import { defaultMachine } from "../git.js";
9
- import { assertMachineInstallNotNewer, ensureMachineInstall } from "../install.js";
10
+ import { assertMachineInstallNotNewer, ensureInstall, isLiveExecutable, readInstall, requireInstall } from "../install.js";
10
11
  import { claudeCheckoutOwner, claudeCheckoutTaken, reconcileCodexHooks, HARNESSES, findIdentityFile, installForHarness, normalizeVendor, readIdentityFile, writeIdentity } from "../harness.js";
11
12
  import { detectVendor } from "../vendor.js";
12
13
  import { CLI_VERSION } from "../version.js";
@@ -103,6 +104,15 @@ export async function join(p, out, expectedProject) {
103
104
  // A newer recorded install must reject this copy before the single-use enrollment token is sent.
104
105
  // Otherwise wait to move/install the machine-wide CLI until credentials have been saved.
105
106
  assertMachineInstallNotNewer(CLI_VERSION);
107
+ // Validate the recorded binary (or canonical bootstrap runtime) before consuming a token.
108
+ if (readInstall()) {
109
+ const recorded = requireInstall();
110
+ if (!isLiveExecutable(recorded.bin))
111
+ throw new CliError("recorded_bin_unavailable", `the recorded b9s executable ${recorded.bin} is not executable`, "Ask the machine operator to repair the recorded install before joining");
112
+ }
113
+ else if (!isLiveExecutable(pathJoin(homedir(), ".local", "node", "bin", "npm")) || !isLiveExecutable(pathJoin(homedir(), ".local", "node", "bin", "node"))) {
114
+ throw new CliError("canonical_node_missing", "the canonical ~/.local/node npm is missing", `Follow ${url}/onboard to prepare Node before joining`);
115
+ }
106
116
  let res;
107
117
  try {
108
118
  res = await fetch(`${url}/enroll`, { method: "POST", headers: { "content-type": "application/json", "user-agent": cliUserAgent() }, body: JSON.stringify({ token, name, vendor, machine }) });
@@ -192,14 +202,16 @@ export function assertVendorMatchesRepo(root, name, vendor, replace) {
192
202
  throw new CliError("vendor_mismatch", `${p} says ${name} runs in ${mapped.join(" and ")} here, but this command detected ${vendor}`, `If ${name} runs in ${mapped[0]}, run this from that harness or pass --vendor ${mapped[0]}. If the file is wrong, pass --replace.`);
193
203
  }
194
204
  /** This machine's one install, at least this CLI's version (installed or upgraded when needed). */
195
- /**
196
- * The machine's install, upgraded to this version if older. An existing record keeps its npm, so a
197
- * join run from another Node (an nvm shell, an npx cache) upgrades the machine's install in place
198
- * instead of moving it there and leaving every watcher on the old copy. Only a first install uses
199
- * the npm next to the running Node.
200
- */
205
+ /** Reuse an existing machine install without rewriting it or restarting services. */
201
206
  function machineInstall() {
202
- return ensureMachineInstall(CLI_VERSION, (m) => process.stderr.write(`b9s: ${m}\n`));
207
+ assertMachineInstallNotNewer(CLI_VERSION);
208
+ if (readInstall())
209
+ return requireInstall();
210
+ const npm = pathJoin(homedir(), ".local", "node", "bin", "npm");
211
+ const node = pathJoin(homedir(), ".local", "node", "bin", "node");
212
+ if (!isLiveExecutable(npm) || !isLiveExecutable(node))
213
+ throw new CliError("canonical_node_missing", "the canonical ~/.local/node runtime is missing", "Follow the /onboard instructions before joining");
214
+ return ensureInstall(CLI_VERSION, (m) => process.stderr.write(`b9s: ${m}\n`), npm, true, false, node);
203
215
  }
204
216
  function writeIdentityDryRun(root, vendor, name, replace) {
205
217
  const p = findIdentityFile(root);
@@ -22,18 +22,8 @@ function processIsRunning(pid) {
22
22
  throw error;
23
23
  }
24
24
  }
25
- /**
26
- * How many times a lock-run call is repeated after a network failure or a 5xx. Every call carries
27
- * the job's token, so a repeat is the same request. A release that failed once during a database
28
- * overload left the lock held with no process behind it (two build hosts' suite locks sat held for
29
- * 45 minutes), and a failed poll ended a job that was only waiting its turn. The release keeps
30
- * trying for about two minutes, the others for about 40 seconds; after that the failure is
31
- * reported as before, naming the job. If a release was applied and only its answer was lost, the
32
- * repeat is refused (the job no longer holds the lock) and reported: the lock is free then.
33
- */
34
- export function lockRunRetries(path) {
35
- return path.endsWith("/release") ? 20 : 8;
36
- }
25
+ /** All lock-run reports carry the stable job token and may safely retry for the lease grace. */
26
+ export const LOCK_RUN_RETRY_WINDOW_MS = 5 * 60_000;
37
27
  export function createSupervisorRecordReader(onRecord, log) {
38
28
  let pending = "";
39
29
  const consume = (line) => {
@@ -111,7 +101,7 @@ export async function runUnderLock(o, deps) {
111
101
  return result;
112
102
  }
113
103
  catch (error) {
114
- throw new CliError("lock_release_failed", `job ${o.jobId} could not release ${o.lock} (${error instanceof Error ? error.message : String(error)})`, `Release it: ${unlockCommand(o)}`);
104
+ throw new CliError("lock_release_failed", `job ${o.jobId} could not release ${o.lock} (${error instanceof Error ? error.message : String(error)})`, `Release it: ${unlockCommand(o)}`, undefined, error);
115
105
  }
116
106
  };
117
107
  let r = await deps.call("POST", `${base}/acquire`, { ...acquireBody });
@@ -150,9 +140,11 @@ export async function runUnderLock(o, deps) {
150
140
  }
151
141
  const startedMs = now();
152
142
  const slot = Number.isInteger(r.slot) ? Number(r.slot) : undefined;
153
- if (o.lock === "ux-browser" && (slot === undefined || slot < 1 || slot > 3)) {
143
+ const countedLock = o.lock === "ux-browser" || o.lock === "complete-suite";
144
+ const capacity = Number.isSafeInteger(r.lock?.capacity) ? Number(r.lock.capacity) : undefined;
145
+ if (countedLock && (slot === undefined || slot < 1 || capacity === undefined || slot > capacity)) {
154
146
  await release();
155
- throw new CliError("lock_protocol_mismatch", "The server did not assign a valid ux-browser slot; the command was not started. Inspect the lock state: b9s locks");
147
+ throw new CliError("lock_protocol_mismatch", `The server did not assign a valid ${o.lock} slot; the command was not started. Inspect the lock state: b9s locks`);
156
148
  }
157
149
  let code;
158
150
  try {