benignswarm 0.12.145 → 0.12.147

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/help.js CHANGED
@@ -133,6 +133,7 @@ Agent commands
133
133
  save the returned job token; reuse --token to check/retry the same job
134
134
  b9s lock run <name> [--unit n] [--note ..] [--shared] [--token <job-token>] -- <command> poll until granted, run and release; gate receipt outcome is separate and does not change the command exit code
135
135
  polls every 15s; stale waiters are skipped after 60s with a process notice; later polls reap unreported holders idle 60s
136
+ output silence raises a Needs fault after B9S_LOCK_SILENCE_SECONDS (default 300); last output is redacted
136
137
  b9s locks shows waiter poll age; reported-command holders do not expire
137
138
  b9s unlock <name> [--job <id> | --token <job-token>] [--machine <label>|--shared] | b9s locks shows lock-run waiters' last-poll age; on this host the job token is kept for you
138
139
  b9s unlock <name> --remove-empty [--machine <label>|--shared]
@@ -154,6 +155,7 @@ Machine placement enforces configured session slots and reports machine pressure
154
155
  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
155
156
  b9s wu review <n> reviewer's checkout: fetch the submitted branch from origin and open
156
157
  ../<repo>-review-wu<n> detached at the submitted head (refused if origin differs)
158
+ b9s wu reviewer <n> --replace <agent> [--with <agent>] --note "why" assigner or operator: replace an owing reviewer with an available qualified reviewer; audited and announced (console control WU #733)
157
159
  b9s wu approve <n> --note ".." [--confirm-causes cause,cause] approval covers tags your role reviews (escalated or away-takeover reviewers cover only their handed-over tags); complete approval confirms classified send-back causes in timeline order
158
160
  a planned reviewer still owing may approve after coverage; status stays approved until merge
159
161
  b9s wu changes <n> --unmet ".." --cause <cause> --note ".." [--summary "..." | --plain-summary "..."] send back with a cited clause, cause and stored explanation (scope_gap, missing_context, worker_error, reviewer_scope_growth, environment, stale_base)
@@ -194,11 +196,12 @@ Machine placement enforces configured session slots and reports machine pressure
194
196
  Antigravity workspace-write queues the exact closed worktree for cleanup outside the sandbox at turn finalization; branches are kept
195
197
  b9s wu merge <n> [--note "..."] role-checked hosted merge through the API; never inspects local Git credentials or state
196
198
  b9s wu merge status <n> operation status and non-secret audit trail for a hosted merge
197
- b9s wu show <n> [--scope-only] show the full unit (including route/review explanation when recorded) or only its scope for scripts
199
+ b9s wu show <n> [--scope-only] show the full unit and its Console link (or only its scope for scripts)
198
200
  b9s wu recovery save <n> --reason "..." save a WIP branch commit and encrypted cutoff bundle; keep the source volume until safe_to_delete
199
201
  b9s wu recovery restore <n> next owner: verify and restore the restricted recovery bundle into the unit worktree
200
202
  b9s wu abandon <n> [--note ..] wu list [--all] [--json] for state and timeline (JSON keeps complete titles)
201
203
  b9s wu list [--all] [--status s] [--tag t] [--agent name] list visible work units; --all includes closed units
204
+ b9s wu stalled list stalled units with age and reason; exits 1 when any are stalled
202
205
  b9s worktrees prune [--yes] [--archive] remove clean, fully pushed worktrees whose work landed or whose unit is closed (dry run without --yes);
203
206
  --archive also saves a closed unit's uncommitted files to archive/wu<n>-leftovers and removes it;
204
207
  refused in Antigravity workspace-write: watcher processes queued wu done worktrees at turn finalization; prune retained or abandoned worktrees from an unrestricted checkout
@@ -297,7 +300,7 @@ Machine placement enforces configured session slots and reports machine pressure
297
300
  b9s channel create <name> [--topic t] needs create_channels permission
298
301
  b9s agents
299
302
  b9s roles
300
- b9s evidence post <file> [--label t] [--kind test|diagnosis|review|screenshot|log|other] [--claim "one line"] [--type ct] [--name fn] checksummed raw bytes; prints stored content type
303
+ b9s evidence post <file> [--label t] [--kind test|diagnosis|review|screenshot|log|other] [--claim "one line"] [--type ct] [--name fn] checksummed raw bytes; prints stored type and Console link
301
304
  b9s evidence list [--limit n] [--unit n] [--kind k]
302
305
  b9s evidence info <id|sha256>
303
306
  b9s evidence get <id|sha256> [--out path] verifies sha256 on download
@@ -306,6 +309,14 @@ Machine placement enforces configured session slots and reports machine pressure
306
309
  preserve the report as test evidence, validate/import schema v1, optionally attach to a unit
307
310
  JUnit requires context JSON (source, invocation, runner, run); JSON reports include those fields
308
311
  b9s test-results show <run-id> show the stored run, outcome counts, and original report evidence
312
+ b9s ux run [<task>] [--compare <screen>] --unit <n> [--on <machine>] [--head <sha>]
313
+ queue a remote seeded browser task or ux:compare on an account machine labeled ux-host or browser
314
+ b9s ux job <id> inspect a queued, running or finished remote browser job and its evidence
315
+ b9s ux jobs [--unit <n>] [--limit n] list remote browser jobs in this project
316
+ b9s gate run <n> [--merge-candidate <sha>] --on <machine>
317
+ queue a complete-suite gate run on a machine; records the receipt and posts the log as evidence
318
+ b9s gate job <id> inspect a queued, running or finished remote gate job and its evidence
319
+ b9s gate jobs [--unit <n>] [--limit n] list remote gate jobs in this project
309
320
  b9s retire --title t (--body b | --body-file f) [--handoff-to @x|@role:y] [--evidence id,id] --yes
310
321
  save a RESUME or HANDOFF note, revoke keys and remove machine sessions; revival does not restore sessions
311
322
  b9s handoffs [--open] [--agent a] notes left by retired agents (open = not yet picked up)
@@ -423,7 +434,8 @@ Use --admin <nickname> to select one of this machine's saved operator identities
423
434
  b9s-admin process tag add|edit|remove <project> <tag> [--meaning ..] [--require-evidence yes|no] [--require-rebased yes|no] [--expert-role r|none] [--requires name,name]
424
435
  legacy project-first order also accepted; for operation-first with a project named add, edit, or remove:
425
436
  b9s-admin process tag <op> <tag> --project <project>
426
- b9s-admin process timing <project> [--sla m] [--takeover m] [--max-open n] [--max-in-progress n] [--require-scope yes|no] [--require-evidence yes|no] [--require-cited-changes yes|no] [--default-approver r|none]
437
+ b9s-admin process timing <project> [--sla m] [--takeover m] [--stall <minutes|default>] [--max-open n] [--max-in-progress n] [--require-scope yes|no] [--require-evidence yes|no] [--require-cited-changes yes|no] [--default-approver r|none]
438
+ --stall sets the quiet-work threshold (1..525600 minutes); default uses twice the takeover window
427
439
  b9s-admin process merge <project> [--target b] [--merged-by owner|approver|integrator] [--integrator-role r] [--require-rebased|--require-merge-commit|--require-pushed yes|no] [--gate-command "<one command>"|none] [--require-gate-receipt yes|no]
428
440
  b9s-admin process assigners <project> role1,role2
429
441
  b9s-admin process agreements <project> --file agreements.md
@@ -447,14 +459,15 @@ Use --admin <nickname> to select one of this machine's saved operator identities
447
459
  b9s-admin role edit <name> [--project p] --reviews a,b --works c --trials d which tags a role reviews, works and trials ("*" all, "" none)
448
460
  --assign-outside-qualifications yes|no allow assigners in this role to make reasoned ownership exceptions; dispatch stays qualified
449
461
  --judges yes|no the turn-judge capability: this role may be chosen as the independent judge (docs/TURN-JUDGE.md)
450
- b9s-admin needs decisions waiting on you (asks, unit questions, broken wake paths, alert failures)
462
+ b9s-admin needs decisions waiting on you with decision/WU/fault IDs and Console links
451
463
  Browser conditional actions and retry receipts: docs/NEEDS-BROWSER-ACTIONS.md; console work #555/#556
452
- b9s-admin answer <key> "decision" answer one; the asker is @mentioned
453
- b9s-admin answer <key> --approve [--assign <agent>] [--note ".."] accept an ask proposal and name its action owner
454
- b9s-admin answer <key> --approve [--note ".."] accept a unit-question proposal as written
455
- b9s-admin explain <key> ask the agent to explain a decision in plain words (the console's Explain)
464
+ b9s-admin answer <id or key> "decision" answer one; the asker is @mentioned and a Console link is printed
465
+ b9s-admin answer <id or key> --approve [--assign <agent>] [--note ".."] accept an ask proposal and name its action owner
466
+ b9s-admin answer <id or key> --approve [--note ".."] accept a unit-question proposal as written
467
+ b9s-admin explain <id or key> ask the agent to explain a decision in plain words (the console's Explain)
456
468
  b9s-admin notifier [--agent name|none] [--email yes|no] [--repeat m] [--flow-summary yes|no] [--flow-min-age m] [--flow-min-impact n] how you are reached away from the console, and the last report
457
- b9s-admin account [--summary-minutes m] plan, usage and the account summary period
469
+ b9s-admin account [--summary-minutes m] [--quota-share-threshold fraction|default] account usage and quota concentration threshold
470
+ b9s-admin quota-pools harness account fingerprints, running-session share and recent usage limits
458
471
  b9s-admin account secrets-kms status
459
472
  b9s-admin account secrets-kms enable --region <aws-region> [--kms-key <arn-or-id>]
460
473
  dedicated per-account KMS key; foreign, shared, or untagged keys are refused
package/dist/index.js CHANGED
@@ -41,6 +41,7 @@ import { realpathSync } from "node:fs";
41
41
  import { fileURLToPath } from "node:url";
42
42
  import { standingRuleCommand } from "./commands/standing-rules.js";
43
43
  import { testResults } from "./commands/test-results.js";
44
+ import { gate, ux } from "./commands/ux.js";
44
45
  import { environment } from "./commands/environment.js";
45
46
  import { runCommandSafely } from "./command-runner.js";
46
47
  const COMMANDS = {
@@ -54,6 +55,8 @@ const COMMANDS = {
54
55
  "git-credential": async (p) => gitCredentialMain(p),
55
56
  templates,
56
57
  "test-results": testResults,
58
+ ux,
59
+ gate,
57
60
  environment,
58
61
  notice: agentNotice,
59
62
  who: a.who,
@@ -0,0 +1,239 @@
1
+ const MACHINE_REPORT_ENTRY_LIMIT = 20;
2
+ const PRUNE_PATH_LIMIT = 5;
3
+ const NESTED_LIST_LIMIT = 5;
4
+ const REPORT_TEXT_BYTE_LIMIT = 40;
5
+ const DIAGNOSTIC_FIELDS = new Set([
6
+ "error", "reason", "message", "diagnosis", "detail", "stderr", "stdout", "output", "log",
7
+ "path", "repo", "dirty_closed_paths", "paths", "skipped_protected", "cleaned_items",
8
+ "processes", "uninspected_processes", "active_processes", "readiness_refusals",
9
+ ]);
10
+ const record = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
11
+ function boundedEntries(items, limit = MACHINE_REPORT_ENTRY_LIMIT) {
12
+ // Keep the most recent facts, which are the ones from the daemon's current sweep.
13
+ return { items: items.slice(-limit), total: items.length, omitted: Math.max(0, items.length - limit) };
14
+ }
15
+ function boundedText(value) {
16
+ if (typeof value !== "string")
17
+ return null;
18
+ if (Buffer.byteLength(value, "utf8") <= REPORT_TEXT_BYTE_LIMIT)
19
+ return value;
20
+ const points = Array.from(value);
21
+ const ellipsisBytes = Buffer.byteLength("…", "utf8");
22
+ const sideBytes = Math.floor((REPORT_TEXT_BYTE_LIMIT - ellipsisBytes) / 2);
23
+ let head = "";
24
+ let headBytes = 0;
25
+ for (const point of points) {
26
+ const bytes = Buffer.byteLength(point, "utf8");
27
+ if (headBytes + bytes > sideBytes)
28
+ break;
29
+ head += point;
30
+ headBytes += bytes;
31
+ }
32
+ let tail = "";
33
+ let tailBytes = 0;
34
+ for (const point of points.reverse()) {
35
+ const bytes = Buffer.byteLength(point, "utf8");
36
+ if (tailBytes + bytes > sideBytes)
37
+ break;
38
+ tail = point + tail;
39
+ tailBytes += bytes;
40
+ }
41
+ return `${head}…${tail}`;
42
+ }
43
+ const shortText = (value) => boundedText(value);
44
+ const isDiagnosticField = (field) => field.split(".").some((part) => DIAGNOSTIC_FIELDS.has(part));
45
+ const boundFieldText = (field, value) => isDiagnosticField(field) ? shortText(value) : value;
46
+ function summarizePrune(value) {
47
+ const entries = Array.isArray(value) ? value.map(record) : [];
48
+ const volumes = new Map();
49
+ let removed = 0;
50
+ let dirtyClosed = 0;
51
+ let failed = 0;
52
+ let skipped = 0;
53
+ let removedPathCount = 0;
54
+ const dirtyPaths = [];
55
+ const removedPaths = [];
56
+ for (const entry of entries) {
57
+ if (typeof entry.removed === "number" && Number.isFinite(entry.removed))
58
+ removed += Math.max(0, entry.removed);
59
+ if (entry.status === "error")
60
+ failed++;
61
+ if (entry.status === "skipped")
62
+ skipped++;
63
+ const dirty = Array.isArray(entry.dirty_closed) ? entry.dirty_closed.filter((path) => typeof path === "string") : [];
64
+ dirtyClosed += dirty.length;
65
+ dirtyPaths.push(...dirty);
66
+ const paths = Array.isArray(entry.paths) ? entry.paths.filter((path) => typeof path === "string") : [];
67
+ removedPaths.push(...paths);
68
+ removedPathCount += typeof entry.paths_count === "number" && Number.isFinite(entry.paths_count)
69
+ ? Math.max(paths.length, entry.paths_count)
70
+ : paths.length;
71
+ const spaces = Array.isArray(entry.free_space) ? entry.free_space.map(record) : [];
72
+ for (const space of spaces) {
73
+ if (typeof space.volume !== "string")
74
+ continue;
75
+ const current = volumes.get(space.volume) ?? { freed_bytes: 0, free_bytes: null };
76
+ if (typeof space.freedBytes === "number" && Number.isFinite(space.freedBytes))
77
+ current.freed_bytes += Math.max(0, space.freedBytes);
78
+ if (typeof space.freeBytes === "number" && Number.isFinite(space.freeBytes))
79
+ current.free_bytes = space.freeBytes;
80
+ volumes.set(space.volume, current);
81
+ }
82
+ }
83
+ const projects = entries.map((entry, index) => ({
84
+ index,
85
+ priority: entry.status === "error" || entry.status === "skipped" ? 0 : Array.isArray(entry.dirty_closed) && entry.dirty_closed.length ? 1 : 2,
86
+ summary: {
87
+ project: boundedText(entry.project),
88
+ status: boundedText(entry.status),
89
+ reason: boundedText(entry.reason),
90
+ repo: boundedText(entry.repo),
91
+ removed: typeof entry.removed === "number" ? entry.removed : null,
92
+ dirty_closed_count: Array.isArray(entry.dirty_closed) ? entry.dirty_closed.length : 0,
93
+ },
94
+ }));
95
+ const selectedProjects = projects.sort((a, b) => a.priority - b.priority || a.index - b.index).slice(0, MACHINE_REPORT_ENTRY_LIMIT).map(({ summary }) => summary);
96
+ const retainedPaths = dirtyPaths.slice(-PRUNE_PATH_LIMIT).map(shortText);
97
+ return {
98
+ total_projects: entries.length,
99
+ omitted_projects: Math.max(0, entries.length - selectedProjects.length),
100
+ projects: selectedProjects,
101
+ removed_worktrees: removed,
102
+ dirty_closed_count: dirtyClosed,
103
+ failed_projects: failed,
104
+ skipped_projects: skipped,
105
+ volumes: [...volumes.entries()].slice(-MACHINE_REPORT_ENTRY_LIMIT).map(([volume, facts]) => ({ volume, ...facts })),
106
+ volume_count: volumes.size,
107
+ omitted_volumes: Math.max(0, volumes.size - MACHINE_REPORT_ENTRY_LIMIT),
108
+ dirty_closed_paths: retainedPaths,
109
+ omitted_dirty_closed_paths: Math.max(0, dirtyClosed - retainedPaths.length),
110
+ paths: removedPaths.slice(-PRUNE_PATH_LIMIT).map(shortText),
111
+ omitted_paths: Math.max(0, removedPathCount - Math.min(removedPathCount, PRUNE_PATH_LIMIT)),
112
+ };
113
+ }
114
+ function summarizeBuildCaches(value) {
115
+ const caches = record(value);
116
+ const bounded = (field) => {
117
+ const items = Array.isArray(field) ? field.map((item) => {
118
+ if (typeof item === "string")
119
+ return shortText(item);
120
+ const entry = record(item);
121
+ const shortened = Object.fromEntries(Object.entries(entry).map(([key, child]) => [
122
+ key,
123
+ typeof child === "string" ? boundFieldText(key, child)
124
+ : Array.isArray(child) ? boundedEntries(child.map((part) => typeof part === "string" ? boundFieldText(key, part) : part), NESTED_LIST_LIMIT).items
125
+ : child,
126
+ ]));
127
+ for (const [key, child] of Object.entries(entry)) {
128
+ if (Array.isArray(child)) {
129
+ const total = typeof entry[`${key}_count`] === "number" ? entry[`${key}_count`] : child.length;
130
+ shortened[`${key}_count`] = total;
131
+ shortened[`${key}_omitted_count`] = Math.max(0, total - shortened[key].length);
132
+ }
133
+ }
134
+ return shortened;
135
+ }) : [];
136
+ const priority = (item) => {
137
+ const entry = record(item);
138
+ if (entry.status === "error" || entry.status === "failed" || entry.kind === "inspection_incomplete")
139
+ return 0;
140
+ if (entry.status === "skipped_in_use" || entry.status === "skipped_protected" || entry.under_floor === true)
141
+ return 1;
142
+ return 2;
143
+ };
144
+ const selected = items.map((item, index) => ({ item, index, priority: priority(item) }))
145
+ .sort((a, b) => a.priority - b.priority || a.index - b.index).slice(0, MACHINE_REPORT_ENTRY_LIMIT).map(({ item }) => item);
146
+ return { items: selected, total: items.length, omitted: Math.max(0, items.length - selected.length) };
147
+ };
148
+ const result = { ...caches };
149
+ for (const field of ["volumes", "caches", "faults"]) {
150
+ const capped = bounded(caches[field]);
151
+ result[field] = capped.items;
152
+ result[`${field}_count`] = capped.total;
153
+ result[`${field}_omitted_count`] = capped.omitted;
154
+ }
155
+ return result;
156
+ }
157
+ /** Cap remaining nested machine-fact arrays (for example watcher services and SDK lists). */
158
+ function boundNestedArrays(value, field = "") {
159
+ if (typeof value === "string")
160
+ return isDiagnosticField(field) ? boundedText(value) : value;
161
+ if (Array.isArray(value))
162
+ return value.slice(-MACHINE_REPORT_ENTRY_LIMIT).map((item) => boundNestedArrays(item, field));
163
+ if (!value || typeof value !== "object")
164
+ return value;
165
+ const source = value;
166
+ const result = {};
167
+ for (const [key, child] of Object.entries(source)) {
168
+ const childField = field ? `${field}.${key}` : key;
169
+ if (Array.isArray(child)) {
170
+ const retained = child.slice(-MACHINE_REPORT_ENTRY_LIMIT).map((item) => boundNestedArrays(item, childField));
171
+ result[key] = retained;
172
+ if (child.length > MACHINE_REPORT_ENTRY_LIMIT) {
173
+ result[`${key}_count`] = child.length;
174
+ result[`${key}_omitted_count`] = child.length - MACHINE_REPORT_ENTRY_LIMIT;
175
+ }
176
+ }
177
+ else {
178
+ result[key] = boundNestedArrays(child, childField);
179
+ }
180
+ }
181
+ return result;
182
+ }
183
+ /** Keep daemon telemetry actionable while making every report list bounded and size predictable. */
184
+ export function boundMachineReport(report) {
185
+ const bounded = { ...report };
186
+ if (report.clones && typeof report.clones === "object" && !Array.isArray(report.clones)) {
187
+ const entries = Object.entries(report.clones);
188
+ const retained = entries.slice(-MACHINE_REPORT_ENTRY_LIMIT);
189
+ bounded.clones = Object.fromEntries(retained.map(([project, value]) => [
190
+ shortText(project),
191
+ Object.fromEntries(Object.entries(record(value)).map(([key, child]) => [key, typeof child === "string" ? boundFieldText(key, child) : child])),
192
+ ]));
193
+ bounded.clones_count = entries.length;
194
+ bounded.clones_omitted_count = Math.max(0, entries.length - retained.length);
195
+ }
196
+ if (Array.isArray(report.environment_checks)) {
197
+ const prioritized = report.environment_checks.map((item, index) => ({ item: record(item), index }))
198
+ .sort((a, b) => (a.item.status === "failed" ? 0 : a.item.status === "unknown" ? 1 : 2) - (b.item.status === "failed" ? 0 : b.item.status === "unknown" ? 1 : 2) || a.index - b.index);
199
+ const retained = prioritized.slice(0, MACHINE_REPORT_ENTRY_LIMIT).map(({ item }) => Object.fromEntries(Object.entries(item).map(([key, value]) => [key, typeof value === "string" ? boundFieldText(key, value) : value])));
200
+ bounded.environment_checks = retained;
201
+ bounded.environment_checks_count = report.environment_checks.length;
202
+ bounded.environment_checks_omitted_count = report.environment_checks.length - retained.length;
203
+ }
204
+ if (Array.isArray(report.model_checks)) {
205
+ // Keep the most recent queued model-check results. A missing retained check is
206
+ // not evidence that the model was verified; the omitted count lets placement
207
+ // explain that the report was truncated instead of implying a clean result.
208
+ const retained = report.model_checks.slice(-MACHINE_REPORT_ENTRY_LIMIT).map((value) => Object.fromEntries(Object.entries(record(value)).map(([key, child]) => [
209
+ key,
210
+ typeof child === "string" ? boundFieldText(key, child) : child,
211
+ ])));
212
+ bounded.model_checks = retained;
213
+ bounded.model_checks_count = report.model_checks.length;
214
+ bounded.model_checks_omitted_count = Math.max(0, report.model_checks.length - retained.length);
215
+ }
216
+ if (report.git && typeof report.git === "object" && !Array.isArray(report.git)) {
217
+ const git = record(report.git);
218
+ const repositories = Array.isArray(git.repositories) ? git.repositories.map(record) : [];
219
+ const ranked = repositories.map((repository, index) => ({ repository, index }))
220
+ .sort((a, b) => Number(a.repository.accessible === true) - Number(b.repository.accessible === true) || a.index - b.index);
221
+ const retained = ranked.slice(0, MACHINE_REPORT_ENTRY_LIMIT).map(({ repository }) => Object.fromEntries(Object.entries(repository).map(([key, child]) => [key, typeof child === "string" ? boundFieldText(key, child) : child])));
222
+ bounded.git = { ...git, repositories: retained };
223
+ bounded.git.repositories_count = repositories.length;
224
+ bounded.git.repositories_omitted_count = Math.max(0, repositories.length - retained.length);
225
+ }
226
+ if (Array.isArray(report.b9s_services)) {
227
+ const capped = boundedEntries(report.b9s_services);
228
+ bounded.b9s_services = capped.items.map((item) => Object.fromEntries(Object.entries(record(item)).map(([key, child]) => [
229
+ key, typeof child === "string" ? boundFieldText(key, child) : child,
230
+ ])));
231
+ bounded.b9s_services_count = capped.total;
232
+ bounded.b9s_services_omitted_count = capped.omitted;
233
+ }
234
+ if (Array.isArray(report.worktree_prune))
235
+ bounded.worktree_prune = summarizePrune(report.worktree_prune);
236
+ if (report.build_caches && typeof report.build_caches === "object")
237
+ bounded.build_caches = summarizeBuildCaches(report.build_caches);
238
+ return boundNestedArrays(bounded);
239
+ }
@@ -0,0 +1,214 @@
1
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, rmdirSync, rmSync, statfsSync, statSync } from "node:fs";
2
+ import { createHash } from "node:crypto";
3
+ import { join, resolve } from "node:path";
4
+ import { platform, tmpdir } from "node:os";
5
+ import { configRoot } from "./config.js";
6
+ import { CliError } from "./errors.js";
7
+ import { writeFileAtomic } from "./shared-file.js";
8
+ import { validateDeclaredSecretHosts } from "./claude-egress-proxy.js";
9
+ export const SECRET_EGRESS_ENV_KEYS_VAR = "B9S_SECRET_ENV_KEYS";
10
+ export const SECRET_DECLARED_HOSTS_VAR = "B9S_SECRET_DECLARED_HOSTS";
11
+ const TMPFS_MAGIC = 0x01021994;
12
+ const SECRET_ENV_KEY_RE = /^[A-Z_][A-Z0-9_]{0,63}$/;
13
+ /** Validate and normalize project-secret declared hostnames identically to the API contract. */
14
+ export function normalizeAndValidateSecretHosts(rawHosts, allowEmpty = false) {
15
+ try {
16
+ return validateDeclaredSecretHosts(rawHosts, allowEmpty);
17
+ }
18
+ catch (error) {
19
+ throw new CliError("secret_egress_invalid_hosts", error.message);
20
+ }
21
+ }
22
+ /** Parse env JSON carrying declared hostnames; non-empty strict hostnames required when present. */
23
+ export function parseSecretHostsJson(raw) {
24
+ if (raw === undefined)
25
+ return [];
26
+ let parsed;
27
+ try {
28
+ parsed = JSON.parse(raw);
29
+ }
30
+ catch {
31
+ throw new CliError("secret_egress_invalid_hosts", `${SECRET_DECLARED_HOSTS_VAR} must be a valid JSON hostname list`);
32
+ }
33
+ return normalizeAndValidateSecretHosts(parsed, false);
34
+ }
35
+ /** Parse env JSON carrying secret variable names (never values). */
36
+ export function parseSecretKeyNamesJson(raw) {
37
+ if (raw === undefined)
38
+ return [];
39
+ let parsed;
40
+ try {
41
+ parsed = JSON.parse(raw);
42
+ }
43
+ catch {
44
+ throw new CliError("secret_invalid_keys", `${SECRET_EGRESS_ENV_KEYS_VAR} must be a valid JSON array of environment variable names`);
45
+ }
46
+ if (!Array.isArray(parsed) || parsed.length < 1 || parsed.some((item) => typeof item !== "string" || !SECRET_ENV_KEY_RE.test(item))) {
47
+ throw new CliError("secret_invalid_keys", `${SECRET_EGRESS_ENV_KEYS_VAR} must contain valid uppercase environment variable names`);
48
+ }
49
+ return [...new Set(parsed)];
50
+ }
51
+ function isWritableTmpfs(dir) {
52
+ try {
53
+ const st = statfsSync(dir);
54
+ return Number(st.type) === TMPFS_MAGIC && existsSync(dir);
55
+ }
56
+ catch {
57
+ return false;
58
+ }
59
+ }
60
+ /**
61
+ * Private owner-only runtime directory for session-scoped project secrets, preferring Linux tmpfs
62
+ * and isolated by B9S/BSCHAT config root so tests and concurrent environments never collide.
63
+ */
64
+ export function sessionSecretsRootDir(env = process.env) {
65
+ const uid = typeof process.getuid === "function" ? process.getuid() : 0;
66
+ const configHash = createHash("sha256").update(resolve(configRoot(env))).digest("hex").slice(0, 16);
67
+ const os = platform();
68
+ if (os === "linux") {
69
+ const xdg = env.XDG_RUNTIME_DIR;
70
+ if (xdg && isWritableTmpfs(xdg)) {
71
+ return join(xdg, `b9s-session-secrets-${uid}`, configHash);
72
+ }
73
+ if (isWritableTmpfs("/dev/shm")) {
74
+ return join("/dev/shm", `b9s-session-secrets-${uid}`, configHash);
75
+ }
76
+ }
77
+ return join(tmpdir(), `b9s-session-secrets-${uid}`, configHash);
78
+ }
79
+ /** Deterministic session secret file path outside shared harness configs and daemon state. */
80
+ export function sessionSecretFilePath(sessionKey, env = process.env) {
81
+ const digest = createHash("sha256").update(sessionKey).digest("hex").slice(0, 32);
82
+ return join(sessionSecretsRootDir(env), `${digest}.json`);
83
+ }
84
+ function ensurePrivateSecretDirectory(dir) {
85
+ const parent = join(dir, "..");
86
+ mkdirSync(parent, { recursive: true, mode: 0o700 });
87
+ try {
88
+ chmodSync(parent, 0o700);
89
+ }
90
+ catch { /* ignore if parent root belongs to tmp */ }
91
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
92
+ chmodSync(dir, 0o700);
93
+ }
94
+ /** Persist one session's secret values in owner-only ephemeral runtime storage (never shared configs). */
95
+ export function writeSessionSecrets(params) {
96
+ const keys = Object.keys(params.secretEnv);
97
+ if (!params.sessionKey || !keys.length) {
98
+ throw new CliError("session_secrets_invalid", "session secret storage requires a session identifier and at least one secret key");
99
+ }
100
+ for (const key of keys) {
101
+ if (!SECRET_ENV_KEY_RE.test(key) || typeof params.secretEnv[key] !== "string") {
102
+ throw new CliError("session_secrets_invalid", `invalid project secret environment entry for ${key}`);
103
+ }
104
+ }
105
+ const hosts = normalizeAndValidateSecretHosts(params.declaredHosts, false);
106
+ const root = sessionSecretsRootDir(params.env);
107
+ ensurePrivateSecretDirectory(root);
108
+ const path = sessionSecretFilePath(params.sessionKey, params.env);
109
+ try {
110
+ if (lstatSync(path).isSymbolicLink()) {
111
+ throw new CliError("session_secrets_unsafe_path", `refusing to overwrite symlinked session secret file for ${params.agent}`);
112
+ }
113
+ }
114
+ catch (error) {
115
+ if (error.code !== "ENOENT")
116
+ throw error;
117
+ }
118
+ const payload = {
119
+ schema: 1,
120
+ session_id: params.sessionKey,
121
+ agent: params.agent,
122
+ harness: params.harness,
123
+ declared_hosts: hosts,
124
+ env: { ...params.secretEnv },
125
+ };
126
+ writeFileAtomic(path, JSON.stringify(payload), { mode: 0o600 });
127
+ chmodSync(path, 0o600);
128
+ return path;
129
+ }
130
+ /** Read and verify one session's scoped secret values immediately before spawning a harness turn. */
131
+ export function readSessionSecrets(params) {
132
+ if (!params.expectedKeys.length)
133
+ return {};
134
+ const expectedHosts = normalizeAndValidateSecretHosts(params.expectedDeclaredHosts, false);
135
+ const path = sessionSecretFilePath(params.sessionKey, params.env);
136
+ let st;
137
+ try {
138
+ st = lstatSync(path);
139
+ }
140
+ catch (error) {
141
+ if (error.code === "ENOENT") {
142
+ throw new CliError("session_secrets_unavailable", `session secret context for ${params.expectedAgent} is no longer active (secrets removed or revoked)`);
143
+ }
144
+ throw error;
145
+ }
146
+ if (st.isSymbolicLink() || !st.isFile()) {
147
+ throw new CliError("session_secrets_unsafe_path", `session secret file for ${params.expectedAgent} has an unsafe file type`);
148
+ }
149
+ if (typeof process.getuid === "function" && st.uid !== process.getuid()) {
150
+ throw new CliError("session_secrets_unsafe_path", `session secret file for ${params.expectedAgent} is not owned by the current user`);
151
+ }
152
+ if ((st.mode & 0o077) !== 0) {
153
+ throw new CliError("session_secrets_unsafe_permissions", `session secret file for ${params.expectedAgent} has overly broad permissions`);
154
+ }
155
+ let parsed;
156
+ try {
157
+ parsed = JSON.parse(readFileSync(path, "utf8"));
158
+ }
159
+ catch {
160
+ throw new CliError("session_secrets_unavailable", `session secret file for ${params.expectedAgent} is unreadable`);
161
+ }
162
+ if (parsed.schema !== 1 ||
163
+ parsed.session_id !== params.sessionKey ||
164
+ parsed.agent !== params.expectedAgent ||
165
+ parsed.harness !== params.expectedHarness ||
166
+ !parsed.env ||
167
+ typeof parsed.env !== "object" ||
168
+ Array.isArray(parsed.env) ||
169
+ !Array.isArray(parsed.declared_hosts)) {
170
+ throw new CliError("session_secrets_mismatch", `session secret context mismatch for ${params.expectedAgent}`);
171
+ }
172
+ const actualHosts = [...new Set(normalizeAndValidateSecretHosts(parsed.declared_hosts, false))].sort();
173
+ const wantHosts = [...new Set(expectedHosts)].sort();
174
+ if (actualHosts.length !== wantHosts.length || actualHosts.some((host, idx) => host !== wantHosts[idx])) {
175
+ throw new CliError("session_secrets_mismatch", `session declared hosts changed for ${params.expectedAgent}`);
176
+ }
177
+ const out = {};
178
+ for (const key of params.expectedKeys) {
179
+ const val = parsed.env[key];
180
+ if (typeof val !== "string") {
181
+ throw new CliError("session_secrets_unavailable", `required project secret ${key} is missing for ${params.expectedAgent}`);
182
+ }
183
+ out[key] = val;
184
+ }
185
+ return out;
186
+ }
187
+ /** Remove a session's ephemeral secret file cleanly at session end, revocation, or failure. */
188
+ export function clearSessionSecrets(sessionKey, env = process.env) {
189
+ if (!sessionKey)
190
+ return;
191
+ const path = sessionSecretFilePath(sessionKey, env);
192
+ try {
193
+ rmSync(path, { force: true });
194
+ }
195
+ catch {
196
+ /* best-effort cleanup */
197
+ }
198
+ const dir = sessionSecretsRootDir(env);
199
+ try {
200
+ const dirStat = statSync(dir);
201
+ if (dirStat.isDirectory())
202
+ rmdirSync(dir);
203
+ }
204
+ catch {
205
+ /* keep directory if other sessions still hold files or it does not exist */
206
+ }
207
+ }
208
+ /** Overwrite and delete in-memory secret map entries once forwarded to the session subprocess. */
209
+ export function wipeSecretMap(secrets) {
210
+ for (const key of Object.keys(secrets)) {
211
+ secrets[key] = "";
212
+ delete secrets[key];
213
+ }
214
+ }