benignswarm 0.12.92 → 0.12.94

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/harnesses.js CHANGED
@@ -7,21 +7,22 @@ import { configRoot } from "./config.js";
7
7
  import { readState, writeState } from "./state.js";
8
8
  import { codexArchivedRollout, codexRollout } from "./sessions.js";
9
9
  import { codexTurnPhase, usageLimitUntil } from "./turn.js";
10
+ import { antigravityProbe } from "./antigravity.js";
10
11
  /**
11
12
  * Harnesses a machine can run headless in turn mode (docs/REMOTE-MACHINES.md, "Harness adapters").
12
13
  * Each adapter says how to start a session, what one turn's command is, whether a turn is running in
13
14
  * that session (by anyone: an app, a terminal, a turn left by a watcher that restarted), and how the
14
- * last turn ended. Antigravity is a desktop application with no headless turn and stays hand-run;
15
- * Gemini CLI no longer accepts personal logins (Google moved individuals to Antigravity).
15
+ * last turn ended. Antigravity uses its `agy` CLI and cached login; Gemini CLI no longer accepts
16
+ * personal logins (Google moved individuals to Antigravity).
16
17
  */
17
- export const TURN_HARNESSES = ["codex", "claude-code", "dsh"];
18
+ export const TURN_HARNESSES = ["codex", "claude-code", "dsh", "antigravity"];
18
19
  export function turnHarness(h) {
19
20
  if (TURN_HARNESSES.includes(h))
20
21
  return h;
21
22
  throw new CliError("unsupported", `harness ${h} cannot run headless turns; supported: ${TURN_HARNESSES.join(", ")}`);
22
23
  }
23
- export const HARNESS_LABEL = { codex: "Codex", "claude-code": "Claude Code", dsh: "DeepSeek Harness" };
24
- export const HARNESS_BIN = { codex: "codex", "claude-code": "claude", dsh: "dsh" };
24
+ export const HARNESS_LABEL = { codex: "Codex", "claude-code": "Claude Code", dsh: "DeepSeek Harness", antigravity: "Antigravity" };
25
+ export const HARNESS_BIN = { codex: "codex", "claude-code": "claude", dsh: "dsh", antigravity: "agy" };
25
26
  /** Node's fetch ignores the sandbox's HTTP(S)_PROXY unless this opt-in is present. */
26
27
  export function claudeSandboxEnv(sandbox) {
27
28
  return sandbox === "workspace-write" ? { NODE_USE_ENV_PROXY: "1", BSCHAT_CLAUDE_SANDBOX: "workspace-write" } : {};
@@ -117,7 +118,7 @@ export function assertClaudeSelfCheck(stdout) {
117
118
  throw new CliError("sandbox_self_check_failed", `Claude Code workspace-write self-check failed; watcher was not enabled.\n${error}`);
118
119
  }
119
120
  export function probeFor(harness, session, ref) {
120
- return harness === "codex" ? codexProbe(session) : harness === "claude-code" ? claudeProbe(session, ref) : dshProbe(session, ref);
121
+ return harness === "codex" ? codexProbe(session) : harness === "claude-code" ? claudeProbe(session, ref) : harness === "dsh" ? dshProbe(session, ref) : antigravityProbe(session, ref);
121
122
  }
122
123
  export const dshTurnLog = (ref) => join(configRoot(), "logs", `turn.${ref.replace("/", ".")}.jsonl`);
123
124
  /** The first session event identifies a newly-created DeepSeek Harness session. */
@@ -547,7 +548,7 @@ export function claudeSettings(sandbox, model, effort, cwd, bschatHome, extraWri
547
548
  autoAllowBashIfSandboxed: true,
548
549
  allowUnsandboxedCommands: false,
549
550
  filesystem: { allowWrite: dirs },
550
- network: { allowedDomains: ["*"] },
551
+ network: { allowedDomains: ["*", "api.benignswarm.org"] },
551
552
  },
552
553
  };
553
554
  return [...common, "--permission-mode", "acceptEdits", ...dirs.flatMap((d) => ["--add-dir", d]), "--settings", JSON.stringify(settings)];
package/dist/help.js CHANGED
@@ -20,13 +20,14 @@ GET /account/usage reports used and allowed micro-dollars, uncertain calls and t
20
20
  Session/admin clients can use GET /assistant/conversations, GET /assistant/conversations/:id/messages (paged history with saved tool notices), POST /assistant/conversations/:id/messages (SSE), and DELETE /assistant/conversations/:id. Old assistant messages report notices_available=false. The assistant can draft changes; POST /assistant/proposals/:id/apply or /discard is the operator's explicit action. See the agent/operator skill API reference for events and tools.
21
21
  Free and paid accounts without a live Stripe subscription use the UTC calendar month; subscribed paid accounts reset at current_period_end.
22
22
 
23
- GitHub repository links are managed by the account owner through the browser session API: POST /github/connect, GET /github/callback, GET /github/repositories, and POST/GET/DELETE /projects/:p/github-link. App setup steps are in the operator skill (packages/skill-admin/references/setup.md). Hosted merge remains disabled; this connection unit's stand-in ruleset test is accepted, and a separate live GitHub bypass-change check is required before enablement.
23
+ GitHub repository links are managed by the account owner through the browser session API: POST /github/connect, GET /github/callback, GET /github/repositories, and POST/GET/DELETE /projects/:p/github-link. Hosted merge execution and status are served at POST/GET /projects/:p/work-units/:n/merge (role-checked against merge.merged_by, operator-hold checked, target-serialized in MergeTargetDO, with idempotent reconciliation and manual wu done disabled for enabled linked targets). App setup steps are in the operator skill (packages/skill-admin/references/setup.md). Hosted merge remains disabled per project (hosted_merge_enabled = 0) until the live GitHub bypass-change check completes and the operator enables it.
24
24
 
25
25
  Agent commands
26
26
  b9s login --as <name> --key <bs_agent_...> [--url <api>] [--label <machine-label>]
27
27
  b9s logout --as <name>
28
28
  b9s identities list saved identities on this machine
29
29
  b9s me who am I, role, permissions, channels
30
+ b9s git-credential get|store|erase Git credential helper for the project's linked GitHub repository
30
31
  b9s resume compact recovery brief: units, reviews, asks, slices, decisions, outcomes, process and notices
31
32
  b9s notice add --project <p> "<text>" [--until <time>] [--command-pattern <regex>]
32
33
  assigner only: add a project notice; matching commands warn but continue
@@ -94,19 +95,20 @@ Agent commands
94
95
  b9s measure post <name> --sha <commit> --value <v> --evidence <id[,id...]> [--target branch]
95
96
  b9s measure check <name> run the command producer for the active matching unit at this clean worktree's HEAD and compare with its target's latest good value
96
97
  Global: --effort <high|medium|low|...> reasoning effort to report (else BSCHAT_EFFORT, CLAUDE_EFFORT, codex model_reasoning_effort)
97
- b9s wu submit <n> [--evidence id[,id...] ...] [--pr url] [--expect 'measure: effect'] ask for review; repeat --evidence or pass comma-separated ids; optional expected effect is shown to reviewers; verifies the commit on origin branches
98
+ b9s wu submit <n> [--evidence id[,id...] ...] [--pr url] [--expect 'measure: effect'] [--lesson "..."] [--disputes '<JSON list>'] ask for review; after a send-back give one lesson (max 280 chars); optional disputes cite send-back event IDs and exact clauses
98
99
  b9s wu review <n> reviewer's checkout: fetch the submitted branch from origin and open
99
100
  ../<repo>-review-wu<n> detached at the submitted head (refused if origin differs)
100
- b9s wu approve <n> --note ".." approval covers tags your role reviews
101
+ b9s wu approve <n> --note ".." [--confirm-causes cause,cause] approval covers tags your role reviews; complete approval confirms classified send-back causes in timeline order
101
102
  a planned reviewer still owing may approve after coverage; status stays approved until merge
102
- b9s wu changes <n> --unmet ".." --note ".." send back, quoting the failed scope, exit or agreement clause; a planned reviewer still owing may send an approved, unmerged unit back
103
+ b9s wu changes <n> --unmet ".." --cause <cause> --note ".." send back with a cited clause and cause (scope_gap, missing_context, worker_error, reviewer_scope_growth, environment, stale_base); a planned reviewer still owing may send an approved, unmerged unit back
103
104
  concerns outside those are notes (wu note) or questions (wu ask)
104
105
  b9s wu classify <n> --tags a,b classifier: confirm or change a new unit's tags before it routes for review
105
106
  b9s wu proceed <n> --note ".." reviewer: this step is good, carry on; back to the owner, NOT an approval
106
107
  b9s wu reopen <n> --note ".." owner or reviewer: withdraw an unmerged approval (verification failed); resubmit the same unit
107
108
  b9s wu supersede <n> --by <m> owner or assigner: this unit continues as #m; anyone blocked on #n now waits on #m
108
109
  b9s wu ask <n> "question" owner, reviewer or assigner: a decision this unit cannot move without, including queued units (tag expert first, then the operator)
109
- b9s wu rule <n> "decision" | --approve the tag's expert: answer an open question, or approve its proposal as written (operator questions are answered in the console)
110
+ b9s wu rule <n> "decision" | --approve the tag's expert: answer an open question, or approve its proposal as written (operator questions are answered in the console); --send-back-event <id> --cause <cause> records an explicit retrospective ruling
111
+ b9s wu note <n> --note ".." [--annotation '<JSON object>'] add a note; assigner annotation links a cited scope finding to a cause and one-line reason
110
112
  b9s wu propose <n> "answer" owner, reviewer, assigner or expert: recommend an answer to the unit's open question, approvable as written
111
113
  b9s wu escalate <n> [--note ..] the tag's expert: pass the question to the operator
112
114
  b9s wu wait <n> --on <m> --note "why" | --clear
@@ -131,6 +133,8 @@ Agent commands
131
133
  b9s wu evidence replace <n> <old> <new> [--note ".."] owner replaces attached evidence; old id is retained in the unit history
132
134
  b9s wu done <n> --merged <sha> | --no-source --evidence id[,id...] [--keep-worktree] after approval; no-source closes an evidence-only unit without a merge SHA and checks its branch has no commits beyond the target
133
135
  b9s wu show <n> [--scope-only] show the full unit or only its scope for scripts
136
+ b9s wu recovery save <n> --reason "..." save a WIP branch commit and encrypted cutoff bundle; keep the source volume until safe_to_delete
137
+ b9s wu recovery restore <n> next owner: verify and restore the restricted recovery bundle into the unit worktree
134
138
  b9s wu abandon <n> [--note ..] wu list [--all] for state and timeline
135
139
  b9s worktrees prune [--yes] [--archive] remove clean worktrees whose work landed or whose unit is closed (dry run without --yes);
136
140
  --archive also saves a closed unit's uncommitted files to archive/wu<n>-leftovers and removes it
@@ -148,9 +152,9 @@ Agent commands
148
152
  --env A,B copies those variables from this shell into the LaunchAgent (Antigravity needs
149
153
  ANTIGRAVITY_LS_ADDRESS,ANTIGRAVITY_CSRF_TOKEN). --full queues the text itself. --once /
150
154
  --service (launchd on macOS, systemd on Linux; --launchd is the same). --turn runs each turn
151
- itself (--harness codex|claude-code|dsh --session <id>); 3 consecutive turns without an
155
+ itself (--harness codex|claude-code|dsh|antigravity --session <id>); 3 consecutive turns without an
152
156
  agent-key call stop it and report a machine error; max 20 turns/hour (lower with
153
- --turns-per-hour 1..20). A fault persists across watcher restarts; an operator or
157
+ --turns-per-hour 1..60). A fault persists across watcher restarts; an operator or
154
158
  assigner resumes it with b9s-admin machine session resume.
155
159
  Codex: b9s watch --exec "codex queue --thread <id> --message {summary}" --service
156
160
  b9s update the same as install --latest: upgrade this machine's b9s, repair PATH aliases,
@@ -160,7 +164,7 @@ Agent commands
160
164
  b9s doctor every b9s on this machine and who runs which (PATH, npx caches, this repo's
161
165
  hook and instructions, each watcher's plist versus what launchd runs), with fixes
162
166
  b9s codex hooks | bind <thread-id> | sync install b9s's Codex hooks (~/.codex/hooks.json) and say which thread is you
163
- b9s start --harness codex|claude-code|dsh --as <a> --sandbox <mode> [--provider anthropic|deepseek] [--token t] [--thread id] [--model m] [--effort e] [--max-budget-usd n] [--turns-per-hour 1..20] [--dsh path]
167
+ b9s start --harness codex|claude-code|dsh|antigravity --as <project>/<name> --sandbox <mode> [--provider anthropic|deepseek] [--token t] [--thread id] [--model m] [--effort e] [--writable-root path]... [--max-budget-usd n] [--turns-per-hour 1..60] [--dsh path] [--agy path]
164
168
  run an agent headless: enroll, start or adopt its session, turn-mode watcher
165
169
  Claude Code workspace-write defaults to a $1 per-turn cap; configure it with --max-budget-usd
166
170
  (b9s codex start is the same with --harness codex)
@@ -286,7 +290,8 @@ Machines (provisioned over your own ssh; a daemon on each runs the agent session
286
290
  b9s-admin machine maintenance <name> --at <ISO | HH:MM> --for <30m | 2h> | --cancel a window: no new turns from
287
291
  15 min before, its agents away until the machine reports back after booting
288
292
  b9s-admin machine session add <machine> <project>/<agent> --dir <checkout> --sandbox <read-only|workspace-write|danger-full-access> [--harness codex|claude-code] [--provider anthropic|deepseek]
289
- [--create --role <role>] [--model m] [--effort e] [--thread <id>] [--turn-timeout min] [--turns-per-hour 1..20]
293
+ [--create --role <role>] [--model m] [--effort e] [--thread <id>] [--turn-timeout min] [--turns-per-hour 1..60]
294
+ b9s-admin machine session thread <machine> <project>/<agent> <thread-id|none> set or clear the thread a pool session adopts
290
295
  b9s-admin machine session stop|start|resume|limit|remove <machine> <project>/<agent> resume a latched turn fault or set a lower per-session hourly limit
291
296
  (change its count/settings, pause scaling, pin, or bench the agent)
292
297
  b9s-admin agent move <project>/<agent> --to <machine> --sandbox <mode> [--dir <path>|auto] [--harness codex|claude-code] [--provider anthropic|deepseek] [--carry note|thread]
@@ -302,7 +307,7 @@ Pools (a role, variants and a count; the server names the agents and places them
302
307
  b9s-admin project repo <project> <git url | none> what machines clone for the project's pool sessions
303
308
  b9s-admin project checkout <project> --exclude <path,path | none> paths new worktrees leave out (sparse checkout), e.g. logs/
304
309
  b9s-admin pool set <project>/<name> --role <role> --variant [tag=]harness:model[:effort][*weight][@anthropic|deepseek] [--variant ...]
305
- --count <n> --sandbox <mode> [--needs label,label] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..20]
310
+ --count <n> --sandbox <mode> [--needs label,label] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..60]
306
311
  slots are agents named <name>-<tag>-<n>; fewer retires the extra ones
307
312
  b9s-admin pool list [project] | show <project>/<name> | remove <project>/<name>
308
313
  b9s-admin delete-account --confirm "delete everything"
package/dist/index.js CHANGED
@@ -31,6 +31,7 @@ import { commandWarnings } from "./commands/hook.js";
31
31
  import { loadAgent, resolveAgentName } from "./config.js";
32
32
  import { agentNotice } from "./commands/notices.js";
33
33
  import { versionLine, warnLegacyAlias } from "./legacy-alias.js";
34
+ import { gitCredentialMain } from "./commands/git-credential.js";
34
35
  const COMMANDS = {
35
36
  join,
36
37
  setup,
@@ -39,6 +40,7 @@ const COMMANDS = {
39
40
  identities: a.identities,
40
41
  me: a.me,
41
42
  resume,
43
+ "git-credential": async (p) => gitCredentialMain(p),
42
44
  notice: agentNotice,
43
45
  who: a.who,
44
46
  status: a.status,
@@ -71,7 +73,7 @@ const COMMANDS = {
71
73
  start: async (p, out) => {
72
74
  const h = str(p.flags, "harness");
73
75
  if (!h)
74
- throw new CliError("usage", "start needs --harness <codex|claude-code>");
76
+ throw new CliError("usage", "start needs --harness <codex|claude-code|dsh|antigravity>");
75
77
  return harnessStart(p, out, turnHarness(h));
76
78
  },
77
79
  unpause: async (p, out) => unpause(p, out),
@@ -104,7 +106,7 @@ const COMMANDS = {
104
106
  // These commands establish identity, own their startup validation, or inspect/change only local
105
107
  // machine state. Their dispatch must run before any notice lookup attempts to load an agent.
106
108
  const NOTICE_PREFLIGHT_EXEMPT_COMMANDS = new Set([
107
- "join", "setup", "login", "logout", "identities", "skill", "hook", "machine", "install", "doctor", "update", "version", "admin", "start",
109
+ "join", "setup", "login", "logout", "identities", "skill", "hook", "machine", "install", "doctor", "update", "version", "admin", "start", "git-credential",
108
110
  ]);
109
111
  let invokedCommand;
110
112
  async function main(argv) {
package/dist/install.js CHANGED
@@ -240,6 +240,29 @@ export function watcherServices() {
240
240
  .filter((f) => f.endsWith(".service") && isOurService(f.slice(0, -".service".length)))
241
241
  .map((f) => ({ kind: "systemd", label: f.slice(0, -".service".length), path: join(dir, f), args: unitArgs(readFileSync(join(dir, f), "utf8")) }));
242
242
  }
243
+ /** Read the recorded working directory for a watcher; pruning must fail closed on an unreadable service. */
244
+ export function watcherWorkingDirectory(service) {
245
+ if (service.kind === "systemd") {
246
+ const text = readFileSync(service.path, "utf8");
247
+ const match = /^WorkingDirectory=(.+)$/m.exec(text);
248
+ if (!match)
249
+ throw new CliError("service_unreadable", `${service.label} has no recorded WorkingDirectory`);
250
+ return match[1].replace(/%%/g, "%");
251
+ }
252
+ const read = spawnSync("plutil", ["-convert", "json", "-o", "-", service.path], { encoding: "utf8" });
253
+ if (read.status !== 0)
254
+ throw new CliError("service_unreadable", `could not read ${service.path} as a launchd plist`, (read.stderr ?? "").trim());
255
+ let plist;
256
+ try {
257
+ plist = JSON.parse(read.stdout);
258
+ }
259
+ catch {
260
+ throw new CliError("service_unreadable", `${service.path} is not valid plist JSON`);
261
+ }
262
+ if (typeof plist.WorkingDirectory !== "string" || !plist.WorkingDirectory)
263
+ throw new CliError("service_unreadable", `${service.label} has no readable WorkingDirectory`);
264
+ return plist.WorkingDirectory;
265
+ }
243
266
  export function plistArgs(path) {
244
267
  const r = spawnSync("plutil", ["-convert", "json", "-o", "-", path], { encoding: "utf8" });
245
268
  return r.status === 0 ? (JSON.parse(r.stdout).ProgramArguments ?? null) : null;
@@ -0,0 +1,113 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { isAbsolute, join } from "node:path";
3
+ import { Client } from "./client.js";
4
+ import { configRoot } from "./config.js";
5
+ import { CliError } from "./errors.js";
6
+ import { WATCH_LABEL_PREFIX, watcherServices, watcherWorkingDirectory } from "./install.js";
7
+ function readMachineCredentials() {
8
+ const file = join(configRoot(), "machine.json");
9
+ if (!existsSync(file))
10
+ return null;
11
+ try {
12
+ const value = JSON.parse(readFileSync(file, "utf8"));
13
+ if (typeof value.url !== "string" || !value.url || typeof value.key !== "string" || !value.key)
14
+ throw new Error("url and key are required");
15
+ return { url: value.url, key: value.key };
16
+ }
17
+ catch (error) {
18
+ throw new CliError("machine_sessions_unreadable", `could not read this machine's session list from ${file}: ${error.message}`);
19
+ }
20
+ }
21
+ async function fetchMachineSessions() {
22
+ const machine = readMachineCredentials();
23
+ if (!machine)
24
+ return [];
25
+ const response = await Client.raw(machine.url, machine.key).call("GET", "/machines/me");
26
+ if (!Array.isArray(response.sessions))
27
+ throw new Error("GET /machines/me returned no sessions array");
28
+ return response.sessions;
29
+ }
30
+ async function fetchProjectAgents(creds, project) {
31
+ return Client.forAgent(creds, undefined, { presence: false }).call("GET", `/projects/${project}/agents`);
32
+ }
33
+ function argument(args, name) {
34
+ const index = args.indexOf(name);
35
+ if (index >= 0)
36
+ return args[index + 1] ?? null;
37
+ const inline = args.find((arg) => arg.startsWith(`${name}=`));
38
+ return inline ? inline.slice(name.length + 1) : null;
39
+ }
40
+ function watcherUses(services) {
41
+ return services.filter((service) => service.label.startsWith(WATCH_LABEL_PREFIX)).map((service) => {
42
+ if (!service.args?.length)
43
+ throw new CliError("watcher_unreadable", `${service.label} has no readable service arguments`);
44
+ const agent = argument(service.args, "--as");
45
+ if (!agent)
46
+ throw new CliError("watcher_unreadable", `${service.label} has no recorded --as agent`);
47
+ const dir = argument(service.args, "--dir") ?? watcherWorkingDirectory(service);
48
+ if (!isAbsolute(dir))
49
+ throw new CliError("watcher_unreadable", `${service.label} has no absolute working directory`);
50
+ return { path: dir, agent };
51
+ });
52
+ }
53
+ function sessionUses(value) {
54
+ if (!Array.isArray(value))
55
+ throw new Error("machine session list is not an array");
56
+ return value.flatMap((row, index) => {
57
+ if (!row || typeof row !== "object" || Array.isArray(row))
58
+ throw new Error(`machine session ${index + 1} is malformed`);
59
+ const session = row;
60
+ if (typeof session.agent !== "string" || !session.agent)
61
+ throw new Error(`machine session ${index + 1} has no agent`);
62
+ const reported = session.reported;
63
+ if (reported !== undefined && reported !== null && (typeof reported !== "object" || Array.isArray(reported)))
64
+ throw new Error(`machine session ${session.agent} has malformed reported state`);
65
+ const reportedDir = reported && typeof reported === "object" ? reported.dir : undefined;
66
+ const dir = typeof session.dir === "string" && session.dir ? session.dir : typeof reportedDir === "string" ? reportedDir : "";
67
+ if (!dir)
68
+ return [];
69
+ if (!isAbsolute(dir))
70
+ throw new Error(`machine session ${session.agent} has a non-absolute directory`);
71
+ return [{ path: dir, agent: session.agent }];
72
+ });
73
+ }
74
+ function retiredAgents(value) {
75
+ if (!value || typeof value !== "object" || !Array.isArray(value.agents))
76
+ throw new CliError("home_agents_unreadable", "project agent list has no agents array");
77
+ const result = new Set();
78
+ for (const [index, item] of (value.agents).entries()) {
79
+ if (!item || typeof item !== "object" || Array.isArray(item) || typeof item.name !== "string") {
80
+ throw new CliError("home_agents_unreadable", `project agent ${index + 1} is malformed`);
81
+ }
82
+ const agent = item;
83
+ if (agent.retired_at)
84
+ result.add(agent.name);
85
+ }
86
+ return result;
87
+ }
88
+ /** Read machine sessions, watcher services and retirement state before any worktree can be removed. */
89
+ export async function collectPruneProtection(creds, project, dependencies = {}) {
90
+ const services = (dependencies.watchers ?? watcherServices)();
91
+ const inUse = watcherUses(services);
92
+ let sessions;
93
+ try {
94
+ sessions = await (dependencies.machineSessions ?? fetchMachineSessions)();
95
+ }
96
+ catch (error) {
97
+ throw new CliError("machine_sessions_unreadable", `could not read this machine's session list: ${error.message}`);
98
+ }
99
+ try {
100
+ inUse.push(...sessionUses(sessions));
101
+ }
102
+ catch (error) {
103
+ throw new CliError("machine_sessions_unreadable", `could not read this machine's session list: ${error.message}`);
104
+ }
105
+ let agents;
106
+ try {
107
+ agents = await (dependencies.projectAgents ?? (() => fetchProjectAgents(creds, project)))();
108
+ }
109
+ catch (error) {
110
+ throw new CliError("home_agents_unreadable", `could not read project agents for home worktrees: ${error.message}`);
111
+ }
112
+ return { inUse, retiredHomeAgents: retiredAgents(agents) };
113
+ }
@@ -0,0 +1,149 @@
1
+ import { open, mkdir, lstat, realpath } from "node:fs/promises";
2
+ import { isAbsolute, resolve, sep } from "node:path";
3
+ import { createHash } from "node:crypto";
4
+ import { gunzipSync, gzipSync } from "node:zlib";
5
+ import { CliError } from "./errors.js";
6
+ const MAGIC = new TextEncoder().encode("BSRECOV1");
7
+ function safePath(root, path) {
8
+ if (!path || path.length > 4096 || isAbsolute(path) || path.includes("\\") || path.includes("\0") || path.split("/").some((part) => !part || part === "." || part === ".."))
9
+ throw new CliError("unsafe_recovery", `unsafe recovery path ${JSON.stringify(path)}`);
10
+ const target = resolve(root, path);
11
+ if (target !== root && !target.startsWith(root + sep))
12
+ throw new CliError("unsafe_recovery", `recovery path escapes worktree: ${path}`);
13
+ return target;
14
+ }
15
+ /** Restores the simple length-prefixed regular-file format emitted by b9s recovery save. */
16
+ export async function restoreRecoveryArchive(data, worktree) {
17
+ try {
18
+ data = gunzipSync(data, { maxOutputLength: 1024 * 1024 * 1024 + 16 * 1024 * 1024 + 12 });
19
+ }
20
+ catch {
21
+ throw new CliError("bad_recovery_archive", "recovery bundle is not valid gzip data or expands beyond the 1 GiB recovery limit");
22
+ }
23
+ if (data.length < 12 || !MAGIC.every((v, i) => data[i] === v))
24
+ throw new CliError("bad_recovery_archive", "recovery bundle has an unsupported archive format");
25
+ const manifestSize = new DataView(data.buffer, data.byteOffset, data.byteLength).getUint32(8);
26
+ if (manifestSize > 16 * 1024 * 1024 || 12 + manifestSize > data.length)
27
+ throw new CliError("bad_recovery_archive", "recovery archive manifest is truncated or too large");
28
+ let files;
29
+ try {
30
+ files = JSON.parse(new TextDecoder().decode(data.subarray(12, 12 + manifestSize)));
31
+ }
32
+ catch {
33
+ throw new CliError("bad_recovery_archive", "recovery archive manifest is invalid JSON");
34
+ }
35
+ if (!Array.isArray(files) || files.length > 100_000)
36
+ throw new CliError("bad_recovery_archive", "recovery archive file list is invalid");
37
+ let archiveSize = 0;
38
+ let archiveOffset = 12 + manifestSize;
39
+ const archivePaths = new Set();
40
+ for (const entry of files) {
41
+ if (!entry || typeof entry.path !== "string" || !Number.isSafeInteger(entry.size) || entry.size < 0 || archivePaths.has(entry.path))
42
+ throw new CliError("bad_recovery_archive", "recovery archive contains an invalid or duplicate file entry");
43
+ safePath(worktree, entry.path);
44
+ archivePaths.add(entry.path);
45
+ archiveSize += entry.size;
46
+ if (!Number.isSafeInteger(archiveSize) || archiveSize > 1024 * 1024 * 1024)
47
+ throw new CliError("bad_recovery_archive", "recovery archive file data exceeds the 1 GiB recovery limit");
48
+ archiveOffset += entry.size;
49
+ }
50
+ if (archiveOffset > data.length)
51
+ throw new CliError("bad_recovery_archive", "recovery archive file data is truncated");
52
+ if (archiveOffset !== data.length)
53
+ throw new CliError("bad_recovery_archive", "recovery archive has trailing bytes");
54
+ const root = await realpath(worktree);
55
+ let offset = 12 + manifestSize;
56
+ const restored = [];
57
+ const seen = new Set();
58
+ // Validate all existing paths first so a later symlink cannot cause a partial restore.
59
+ for (const entry of files) {
60
+ const target = safePath(root, entry.path);
61
+ let parent = root;
62
+ for (const part of entry.path.split("/").slice(0, -1)) {
63
+ parent = resolve(parent, part);
64
+ try {
65
+ const stat = await lstat(parent);
66
+ if (stat.isSymbolicLink() || !stat.isDirectory())
67
+ throw new CliError("unsafe_recovery", `recovery path crosses a symlink or non-directory: ${entry.path}`);
68
+ }
69
+ catch (error) {
70
+ if (error.code === "ENOENT")
71
+ break;
72
+ throw error;
73
+ }
74
+ }
75
+ try {
76
+ const stat = await lstat(target);
77
+ if (stat.isSymbolicLink() || !stat.isFile())
78
+ throw new CliError("unsafe_recovery", `refusing to replace a symlink or non-file: ${entry.path}`);
79
+ }
80
+ catch (error) {
81
+ if (error.code !== "ENOENT")
82
+ throw error;
83
+ }
84
+ }
85
+ for (const entry of files) {
86
+ if (!entry || typeof entry.path !== "string" || !Number.isSafeInteger(entry.size) || entry.size < 0 || seen.has(entry.path))
87
+ throw new CliError("bad_recovery_archive", "recovery archive contains an invalid or duplicate file entry");
88
+ seen.add(entry.path);
89
+ const target = safePath(root, entry.path);
90
+ if (offset + entry.size > data.length)
91
+ throw new CliError("bad_recovery_archive", `recovery archive is truncated at ${entry.path}`);
92
+ const parts = entry.path.split("/");
93
+ let parent = root;
94
+ for (const part of parts.slice(0, -1)) {
95
+ parent = resolve(parent, part);
96
+ try {
97
+ const stat = await lstat(parent);
98
+ if (stat.isSymbolicLink() || !stat.isDirectory())
99
+ throw new CliError("unsafe_recovery", `recovery path crosses a symlink or non-directory: ${entry.path}`);
100
+ }
101
+ catch (error) {
102
+ if (error.code !== "ENOENT")
103
+ throw error;
104
+ await mkdir(parent);
105
+ }
106
+ }
107
+ try {
108
+ const stat = await lstat(target);
109
+ if (stat.isSymbolicLink() || !stat.isFile())
110
+ throw new CliError("unsafe_recovery", `refusing to replace a symlink or non-file: ${entry.path}`);
111
+ }
112
+ catch (error) {
113
+ if (error.code !== "ENOENT")
114
+ throw error;
115
+ }
116
+ const file = await open(target, "w", 0o600);
117
+ try {
118
+ await file.write(data.subarray(offset, offset + entry.size));
119
+ }
120
+ finally {
121
+ await file.close();
122
+ }
123
+ offset += entry.size;
124
+ restored.push(entry.path);
125
+ }
126
+ if (offset !== data.length)
127
+ throw new CliError("bad_recovery_archive", "recovery archive has trailing bytes");
128
+ return restored;
129
+ }
130
+ export function sha256(data) { return createHash("sha256").update(data).digest("hex"); }
131
+ export function recoveryArchiveHeader(files) {
132
+ const json = new TextEncoder().encode(JSON.stringify(files));
133
+ const header = new Uint8Array(12 + json.length);
134
+ header.set(MAGIC);
135
+ new DataView(header.buffer).setUint32(8, json.length);
136
+ header.set(json, 12);
137
+ return header;
138
+ }
139
+ export function createRecoveryArchive(files) {
140
+ const header = recoveryArchiveHeader(files.map(({ path, bytes }) => ({ path, size: bytes.length })));
141
+ const raw = new Uint8Array(header.length + files.reduce((n, entry) => n + entry.bytes.length, 0));
142
+ raw.set(header);
143
+ let offset = header.length;
144
+ for (const entry of files) {
145
+ raw.set(entry.bytes, offset);
146
+ offset += entry.bytes.length;
147
+ }
148
+ return gzipSync(raw, { level: 6 });
149
+ }
@@ -0,0 +1,64 @@
1
+ import { existsSync, statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { agentRef, loadAgent } from "./config.js";
5
+ import { CliError } from "./errors.js";
6
+ /** Package-manager and build caches available to workspace-write sessions when present. */
7
+ export const WORKSPACE_WRITE_CACHE_PATHS = [
8
+ ".npm",
9
+ ".cache",
10
+ ".expo",
11
+ ".cargo/registry",
12
+ ".cargo/git",
13
+ ];
14
+ function directoryExists(path) {
15
+ try {
16
+ return existsSync(path) && statSync(path).isDirectory();
17
+ }
18
+ catch {
19
+ return false;
20
+ }
21
+ }
22
+ export function defaultWorkspaceWritableRoots(home = homedir(), isDirectory = directoryExists) {
23
+ return WORKSPACE_WRITE_CACHE_PATHS.map((path) => join(home, path)).filter(isDirectory);
24
+ }
25
+ function absoluteWritablePath(value, flag, home) {
26
+ const path = value.startsWith("~/") ? join(home, value.slice(2)) : value;
27
+ if (!path.startsWith("/"))
28
+ throw new CliError("usage", `--${flag} paths must be absolute or start with ~/`);
29
+ return path;
30
+ }
31
+ /** Defaults plus machine-configured roots and explicit `b9s start --writable-root` paths. */
32
+ export function startWritableRoots(sandbox, machineRoots, explicitRoots, home = homedir(), isDirectory = directoryExists) {
33
+ if (sandbox !== "workspace-write" && explicitRoots.length) {
34
+ throw new CliError("usage", "--writable-root only applies to --sandbox workspace-write");
35
+ }
36
+ const machine = machineRoots.map((path) => absoluteWritablePath(path, "writable", home));
37
+ if (sandbox !== "workspace-write")
38
+ return [...new Set(machine)];
39
+ const requested = explicitRoots.map((path) => absoluteWritablePath(path, "writable-root", home));
40
+ return [...new Set([...defaultWorkspaceWritableRoots(home, isDirectory), ...machine, ...requested])];
41
+ }
42
+ export function startAgentIdentity(name, env = process.env) {
43
+ const credentials = loadAgent(name, env);
44
+ return { credentials, ref: agentRef(credentials) };
45
+ }
46
+ /** Split b9s start's optional project/name identity from the bare name accepted by enrollment. */
47
+ export function startEnrollmentIdentity(identity) {
48
+ const parts = identity.split("/");
49
+ if (parts.length === 1 && parts[0])
50
+ return { name: parts[0] };
51
+ if (parts.length !== 2 || !parts[0] || !parts[1]) {
52
+ throw new CliError("usage", "--as must be <agent-name> or <project>/<agent-name>");
53
+ }
54
+ return { project: parts[0], name: parts[1] };
55
+ }
56
+ /** When a qualified start name accompanies an invite, the token must enroll in that project. */
57
+ export function assertEnrolledStartProject(expected, actual) {
58
+ if (!expected)
59
+ return;
60
+ if (actual !== expected) {
61
+ const actualText = actual === null ? "an account-wide agent, not a project" : `project "${actual}"`;
62
+ throw new CliError("project_mismatch", `--as requested project "${expected}", but the enrollment token belongs to ${actualText}`);
63
+ }
64
+ }
@@ -1,4 +1,6 @@
1
1
  export const DEFAULT_TURNS_PER_HOUR = 20;
2
+ /** The highest hourly turn ceiling a session may be given (operator decision 2026-11-14: busy reviewers ran into 20). */
3
+ export const MAX_TURNS_PER_HOUR = 60;
2
4
  export const MAX_UNPRODUCTIVE_TURNS = 3;
3
5
  const HOUR_MS = 60 * 60_000;
4
6
  const OUTPUT_TAIL_LIMIT = 800;
package/dist/usage.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import { claudeTranscript, dshUsage } from "./harnesses.js";
3
+ import { antigravityUsage } from "./antigravity.js";
3
4
  const zero = () => ({ input: 0, cached_input: 0, output: 0, reasoning: 0, total: 0 });
4
5
  function lines(path) {
5
6
  return readFileSync(path, "utf8").split("\n").filter(Boolean).flatMap((l) => {
@@ -90,6 +91,11 @@ export function sessionUsage(session, since, until) {
90
91
  const base = { harness: "dsh", source: "dsh-step-end-events", scope: "session", since, until, tokens: null };
91
92
  return tokens.total ? { ...base, tokens } : { ...base, reason: "no step_end usage events in the DeepSeek Harness turn log during this window" };
92
93
  }
94
+ if (session.harness === "antigravity") {
95
+ const tokens = antigravityUsage(session.transcript, since, until);
96
+ const base = { harness: "antigravity", source: "agy-json-turn-records", scope: "session", since, until, tokens };
97
+ return tokens ? base : { ...base, reason: "no Antigravity usage records in the window" };
98
+ }
93
99
  return none(session.harness, `${session.harness} keeps no readable token counts locally`);
94
100
  }
95
101
  /** Usage for a Claude Code session identified by the watcher, when no hook bound it to this agent. */
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.92";
1
+ export const CLI_VERSION = "0.12.94";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.92",
3
+ "version": "0.12.94",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -31,7 +31,7 @@
31
31
  "scripts": {
32
32
  "build": "tsc -p tsconfig.build.json",
33
33
  "typecheck": "tsc --noEmit",
34
- "test": "npm run build && vitest run",
34
+ "test": "npm run typecheck && npm run build && vitest run",
35
35
  "prepack": "npm run build"
36
36
  },
37
37
  "devDependencies": {