benignswarm 0.12.102 → 0.12.104
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/args.js +1 -1
- package/dist/commands/hook.js +12 -10
- package/dist/commands/image-admin.js +9 -1
- package/dist/commands/machine-admin.js +7 -4
- package/dist/commands/machine.js +279 -17
- package/dist/commands/watch.js +4 -4
- package/dist/commands/wu.js +49 -8
- package/dist/container.js +46 -1
- package/dist/harness.js +18 -0
- package/dist/help.js +13 -8
- package/dist/usage.js +21 -0
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/dist/args.js
CHANGED
|
@@ -41,7 +41,7 @@ export const BOOL_FLAGS = [
|
|
|
41
41
|
"read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "template", "scope-only", "unread",
|
|
42
42
|
"pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind",
|
|
43
43
|
"all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive",
|
|
44
|
-
"approve", "turn", "service", "print-hooks", "create", "rotate", "codex-userns", "bwrap-userns", "print-apparmor",
|
|
44
|
+
"approve", "turn", "service", "print-hooks", "create", "rotate", "codex-userns", "bwrap-userns", "agy-userns", "print-apparmor",
|
|
45
45
|
"cancel", "rerun", "confirmed", "refuted", "no-source", "confirm-bypass-signal", "in-container", "assessment-only", "retrieve-ec2", "no-wait-verify", "preview", "remove-empty", "dry-run", "stdin", "context-confirmed",
|
|
46
46
|
];
|
|
47
47
|
export function parse(argv) {
|
package/dist/commands/hook.js
CHANGED
|
@@ -193,17 +193,19 @@ export async function gatherUpdates(name, opts) {
|
|
|
193
193
|
] : [];
|
|
194
194
|
let measureLines = [];
|
|
195
195
|
let nextMeasureState = null;
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
196
|
+
if (opts.refreshMeasures) {
|
|
197
|
+
try {
|
|
198
|
+
const response = await client.call("GET", "/agents/me/brief");
|
|
199
|
+
const brief = response.brief;
|
|
200
|
+
if (!brief || !Array.isArray(brief.measures))
|
|
201
|
+
throw new Error("GET /agents/me/brief returned no measures array");
|
|
200
202
|
nextMeasureState = outcomeMeasureSnapshot(brief.measures, brief.measures_omitted ?? 0);
|
|
201
203
|
if (nextMeasureState !== state.measure_state)
|
|
202
204
|
measureLines = formatOutcomeMeasures(brief.measures, brief.measures_omitted ?? 0);
|
|
203
205
|
}
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
206
|
+
catch (e) {
|
|
207
|
+
process.stderr.write(`b9s: outcome measures: ${e.message}\n`);
|
|
208
|
+
}
|
|
207
209
|
}
|
|
208
210
|
const next = { ...state, last_check: Date.now() };
|
|
209
211
|
if (messages.length) {
|
|
@@ -450,7 +452,7 @@ export async function hook(p) {
|
|
|
450
452
|
}
|
|
451
453
|
}
|
|
452
454
|
}
|
|
453
|
-
const u = await gatherUpdates(name, { force: !!p.flags.force || (harness === "claude-code" && event === "SessionStart"), model: str(p.flags, "model") });
|
|
455
|
+
const u = await gatherUpdates(name, { force: !!p.flags.force || (harness === "claude-code" && event === "SessionStart"), model: str(p.flags, "model"), refreshMeasures: event === "SessionStart" && !compacted });
|
|
454
456
|
const formatted = formatHookDelivery(omitMeasuresAlreadyIn(standing?.text, u), standing);
|
|
455
457
|
const text = formatted.text;
|
|
456
458
|
if (!text)
|
|
@@ -605,7 +607,7 @@ async function antigravityHook(p) {
|
|
|
605
607
|
if (event !== "SessionStart" && event !== "PreInvocation")
|
|
606
608
|
return out({});
|
|
607
609
|
const standing = event === "SessionStart" ? await standingRules(name, input?.source === "compact") : null;
|
|
608
|
-
const u = await gatherUpdates(name, { force: event === "SessionStart", delivery: "hook" });
|
|
610
|
+
const u = await gatherUpdates(name, { force: event === "SessionStart", delivery: "hook", refreshMeasures: event === "SessionStart" });
|
|
609
611
|
const formatted = formatHookDelivery(omitMeasuresAlreadyIn(standing?.text, u), standing);
|
|
610
612
|
if (formatted.text)
|
|
611
613
|
await reportDelivery(name, formatted.text, formatted.by_kind);
|
|
@@ -680,7 +682,7 @@ async function codexHook(p) {
|
|
|
680
682
|
if (event !== "SessionStart" && event !== "UserPromptSubmit")
|
|
681
683
|
return;
|
|
682
684
|
const standing = event === "SessionStart" ? await standingRules(name, input?.source === "compact") : null;
|
|
683
|
-
const u = await gatherUpdates(name, { force: event === "SessionStart", delivery: "hook" });
|
|
685
|
+
const u = await gatherUpdates(name, { force: event === "SessionStart", delivery: "hook", refreshMeasures: event === "SessionStart" });
|
|
684
686
|
const formatted = formatHookDelivery(omitMeasuresAlreadyIn(standing?.text, u), standing);
|
|
685
687
|
if (formatted.text)
|
|
686
688
|
await reportDelivery(name, formatted.text, formatted.by_kind);
|
|
@@ -20,7 +20,7 @@ export async function projectImageAdmin(rest, p, out) {
|
|
|
20
20
|
}
|
|
21
21
|
const c = Client.forAdmin(loadAdmin(resolveAdminName(str(p.flags, "admin"))));
|
|
22
22
|
if (!sub || !project) {
|
|
23
|
-
throw new CliError("usage", "project image <validate --file f | config <p> [--path f] [--arch linux/amd64|linux/arm64] [--cache name...] | show <p> | build <p> --commit <sha> --file <devcontainer.json> [--dockerfile f] [--arch a] | rollback <p> (<sha256:...> | clear)>");
|
|
23
|
+
throw new CliError("usage", "project image <validate --file f | config <p> [--path f] [--arch linux/amd64|linux/arm64] [--cache name...] | show <p> | build <p> --commit <sha> --file <devcontainer.json> [--dockerfile f] [--arch a] | activate <p> <sha256:...> | rollback <p> (<sha256:...> | clear)>");
|
|
24
24
|
}
|
|
25
25
|
switch (sub) {
|
|
26
26
|
case "config": {
|
|
@@ -71,6 +71,14 @@ export async function projectImageAdmin(rest, p, out) {
|
|
|
71
71
|
out.print(`Project ${project} active digest is now ${r.image.active_digest ?? "(none)"}`, r);
|
|
72
72
|
return;
|
|
73
73
|
}
|
|
74
|
+
case "activate": {
|
|
75
|
+
const digest = rest[2];
|
|
76
|
+
if (!digest)
|
|
77
|
+
throw new CliError("usage", "project image activate <project> <sha256:...>");
|
|
78
|
+
const r = await c.call("POST", `/projects/${encodeURIComponent(project)}/image/select`, { image_digest: digest });
|
|
79
|
+
out.print(`Project ${project} active digest is now ${r.image.active_digest ?? "(none)"}`, r);
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
74
82
|
default:
|
|
75
83
|
throw new CliError("usage", "project image validate|config|show|build|rollback ...");
|
|
76
84
|
}
|
|
@@ -16,7 +16,7 @@ import { readState, stateFilePath, stateTransferContents } from "../state.js";
|
|
|
16
16
|
* sessions they run (docs/REMOTE-MACHINES.md). The server never sees an ssh credential: every ssh
|
|
17
17
|
* call here runs in the operator's terminal, and the machine key reaches the machine on ssh's stdin.
|
|
18
18
|
*
|
|
19
|
-
* machine add <name> --ssh <host> [--rotate] [--codex-userns] [--bwrap-userns]
|
|
19
|
+
* machine add <name> --ssh <host> [--rotate] [--codex-userns] [--bwrap-userns] [--agy-userns]
|
|
20
20
|
* machine list | show <name> | remove <name>
|
|
21
21
|
* machine session add <machine> <project>/<agent> --dir <path> --sandbox <mode> [--create --role r] [--model m] [--effort e] [--thread id] [--turn-timeout min]
|
|
22
22
|
* machine session stop|start|remove <machine> <project>/<agent>
|
|
@@ -111,6 +111,9 @@ function ssh(host, command, input) {
|
|
|
111
111
|
}
|
|
112
112
|
/** Runs a b9s command on the machine in a login shell (so ~/.local/bin and the harness CLIs are on PATH). */
|
|
113
113
|
const remoteBschat = (host, args, input) => ssh(host, `bash -lc ${JSON.stringify(`b9s ${args}`)}`, input);
|
|
114
|
+
export function machinePrepareCommand(options) {
|
|
115
|
+
return `machine prepare --json${options.codexUserns ? " --codex-userns" : ""}${options.bwrapUserns ? " --bwrap-userns" : ""}${options.agyUserns ? " --agy-userns" : ""}`;
|
|
116
|
+
}
|
|
114
117
|
export async function machineAdmin(action, rest, p, out) {
|
|
115
118
|
const c = adminClient(p);
|
|
116
119
|
if (action === "companion") {
|
|
@@ -123,7 +126,7 @@ export async function machineAdmin(action, rest, p, out) {
|
|
|
123
126
|
const name = rest[0];
|
|
124
127
|
const host = str(p.flags, "ssh");
|
|
125
128
|
if (!name || !host)
|
|
126
|
-
throw new CliError("usage", "machine add <name> --ssh <host> [--rotate] [--codex-userns] [--bwrap-userns] (the host as your ssh knows it: an alias, user@host)");
|
|
129
|
+
throw new CliError("usage", "machine add <name> --ssh <host> [--rotate] [--codex-userns] [--bwrap-userns] [--agy-userns] (the host as your ssh knows it: an alias, user@host)");
|
|
127
130
|
const lines = [];
|
|
128
131
|
const say = (l) => { lines.push(l); if (!out.json)
|
|
129
132
|
process.stderr.write(`${l}\n`); };
|
|
@@ -135,7 +138,7 @@ export async function machineAdmin(action, rest, p, out) {
|
|
|
135
138
|
if (boot.status !== 0)
|
|
136
139
|
throw new CliError("provision_failed", `bootstrapping ${host} failed${steps.length ? `: ${steps[steps.length - 1]}` : `: ${boot.stderr.trim().slice(-300)}`}`);
|
|
137
140
|
// 2. Linger, Codex, managed hooks: checked and fixed on the machine itself.
|
|
138
|
-
const prep = remoteBschat(host,
|
|
141
|
+
const prep = remoteBschat(host, machinePrepareCommand({ codexUserns: bool(p.flags, "codex-userns"), bwrapUserns: bool(p.flags, "bwrap-userns"), agyUserns: bool(p.flags, "agy-userns") }));
|
|
139
142
|
if (prep.status !== 0)
|
|
140
143
|
throw new CliError("provision_failed", `b9s machine prepare on ${host} failed: ${prep.stderr.trim().slice(-300)}`);
|
|
141
144
|
const prepared = JSON.parse(prep.stdout).steps;
|
|
@@ -553,7 +556,7 @@ async function runMachineCompanion(code, p, out) {
|
|
|
553
556
|
await report("bootstrap", "completed", "Node and b9s are ready on the target machine");
|
|
554
557
|
await checkCancel();
|
|
555
558
|
await report("prepare", "started", "Checking machine services and harness prerequisites");
|
|
556
|
-
const prep = remoteBschat(operation.ssh_host,
|
|
559
|
+
const prep = remoteBschat(operation.ssh_host, machinePrepareCommand({ codexUserns: operation.options.codex_userns, bwrapUserns: operation.options.bwrap_userns }));
|
|
557
560
|
if (prep.status !== 0)
|
|
558
561
|
throw new CliError("provision_failed", `b9s machine prepare on ${operation.ssh_host} failed: ${prep.stderr.trim().slice(-300)}`);
|
|
559
562
|
const prepared = JSON.parse(prep.stdout).steps;
|
package/dist/commands/machine.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { spawn, spawnSync } from "node:child_process";
|
|
2
2
|
import { createHash, createHmac } from "node:crypto";
|
|
3
|
-
import { chmodSync, closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, readSync, realpathSync, rmSync, statSync, statfsSync, unlinkSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { chmodSync, closeSync, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, readSync, realpathSync, rmSync, statSync, statfsSync, unlinkSync, writeFileSync } from "node:fs";
|
|
4
4
|
import { arch, cpus, freemem, homedir, hostname, loadavg, platform, tmpdir, totalmem, userInfo } from "node:os";
|
|
5
5
|
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
6
6
|
import { str } from "../args.js";
|
|
7
7
|
import { Client } from "../client.js";
|
|
8
8
|
import { configRoot, loadAgent, resolveAgentName, saveAgent } from "../config.js";
|
|
9
9
|
import { CliError } from "../errors.js";
|
|
10
|
-
import { BWRAP_APPARMOR_PATH, bwrapAppArmorProfile, CODEX_APPARMOR_PATH, CODEX_MANAGED_DIR, codexAppArmorProfile, codexManagedHooks, isCodexManagedRequirements } from "../harness.js";
|
|
10
|
+
import { AGY_APPARMOR_PATH, agyAppArmorProfile, BWRAP_APPARMOR_PATH, bwrapAppArmorProfile, CODEX_APPARMOR_PATH, CODEX_MANAGED_DIR, codexAppArmorProfile, codexManagedHooks, isCodexManagedRequirements } from "../harness.js";
|
|
11
11
|
import { applySparse } from "../git.js";
|
|
12
12
|
import { drainingUntil, writeMaintenance } from "../maintenance.js";
|
|
13
13
|
import { TURN_HARNESSES, claudeFacts, claudeSandbox, dshFacts, dshProcesses, probeFor, sessionProcesses } from "../harnesses.js";
|
|
@@ -22,7 +22,7 @@ import { defaultWorkspaceWritableRoots } from "../start-options.js";
|
|
|
22
22
|
import { antigravityPath, antigravitySandboxPermissions, antigravityTurnArgs, parseAntigravityJson } from "../antigravity.js";
|
|
23
23
|
import { bootTimeMs } from "../boot-time.js";
|
|
24
24
|
import { DEFAULT_CACHE_FLOOR_PCT, manageBuildCaches } from "../build-caches.js";
|
|
25
|
-
import { agentContainerName, agentContainerRunArgs, isolatedBuildCommand, isolatedDevcontainerBuildCommand, isolatedImagePullCommands, isolatedSubprocessEnv, probeImdsIsolation, probeNestedSandbox, readGitIdentity, resolveSessionSecretDelivery, validateDevcontainerSpec, } from "../container.js";
|
|
25
|
+
import { agentContainerName, agentContainerRunArgs, isolatedBuildCommand, isolatedDevcontainerBuildCommand, isolatedImagePullCommands, isolatedSubprocessEnv, networklessRuntimeWrapper, probeImdsIsolation, probeNestedSandbox, readGitIdentity, resolveSessionSecretDelivery, validateDevcontainerSpec, BUILD_SECRET_KEY_NAME_RE, BUILD_SECRET_CONTENT_RE, containsBuildSecretMaterial, sanitizeBuildDiagnosticText, } from "../container.js";
|
|
26
26
|
import { machineEnvironmentChecks } from "../environment-checks.js";
|
|
27
27
|
import { machineResourceTelemetry, parsePageSize } from "../machine-telemetry.js";
|
|
28
28
|
import { macReadiness, macReadinessSteps } from "../macos-readiness.js";
|
|
@@ -103,7 +103,7 @@ const MACHINE_REQUEST_TIMEOUT_MS = 45_000;
|
|
|
103
103
|
const MACHINE_PASS_BUDGET_MS = 4 * 60_000;
|
|
104
104
|
const MACHINE_WATCHDOG_MS = 5 * 60_000;
|
|
105
105
|
export function resolvePinnedImageRef(image) {
|
|
106
|
-
const raw =
|
|
106
|
+
const raw = image?.active_digest?.trim() ?? "";
|
|
107
107
|
if (!raw || /:latest\b/i.test(raw))
|
|
108
108
|
return null;
|
|
109
109
|
const normalized = raw.includes("@sha256:") ? raw : `${image?.registry_namespace ?? ""}@${raw}`;
|
|
@@ -120,6 +120,110 @@ function assertConfinedSnapshotPath(snapshotRealRoot, rawPath, label) {
|
|
|
120
120
|
return targetReal;
|
|
121
121
|
}
|
|
122
122
|
const LOCKFILE_CANDIDATES = ["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "Cargo.lock", "poetry.lock", "uv.lock"];
|
|
123
|
+
function runImageValidationCommand(runtime, imageRef, command, sourceDir) {
|
|
124
|
+
const args = ["run", "--rm", "--network", "none", "--read-only", "--cap-drop", "ALL", "--security-opt", "no-new-privileges", "--pids-limit", "256", "--memory", "4g", "--cpus", "2", "--tmpfs", "/tmp:rw,nosuid,nodev,noexec,size=512m"];
|
|
125
|
+
if (sourceDir)
|
|
126
|
+
args.push("--mount", `type=bind,source=${sourceDir},target=/workspace`, "--workdir", "/workspace");
|
|
127
|
+
args.push(imageRef, "/bin/sh", "-lc", command);
|
|
128
|
+
return { cmd: runtime, args };
|
|
129
|
+
}
|
|
130
|
+
const MAX_BUILD_CONTEXT_FILES = 20_000;
|
|
131
|
+
const MAX_BUILD_CONTEXT_BYTES = 512 * 1024 * 1024;
|
|
132
|
+
export function assertBuildContextHasNoSecrets(root) {
|
|
133
|
+
let files = 0;
|
|
134
|
+
let bytes = 0;
|
|
135
|
+
const visit = (dir) => {
|
|
136
|
+
for (const name of readdirSync(dir)) {
|
|
137
|
+
const path = join(dir, name);
|
|
138
|
+
const stat = lstatSync(path);
|
|
139
|
+
if (stat.isDirectory()) {
|
|
140
|
+
visit(path);
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
if (stat.isSymbolicLink())
|
|
144
|
+
throw new Error("build context contains a symlink; refusing an unbounded secret scan");
|
|
145
|
+
if (!stat.isFile())
|
|
146
|
+
continue;
|
|
147
|
+
files += 1;
|
|
148
|
+
bytes += stat.size;
|
|
149
|
+
if (files > MAX_BUILD_CONTEXT_FILES || bytes > MAX_BUILD_CONTEXT_BYTES) {
|
|
150
|
+
throw new Error("build context exceeds bounded secret scan limits; refusing build");
|
|
151
|
+
}
|
|
152
|
+
if (containsBuildSecretMaterial(readFileSync(path))) {
|
|
153
|
+
throw new Error("build context contains credential material; refusing to place secrets in image layers");
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
visit(root);
|
|
158
|
+
}
|
|
159
|
+
function scanImageArchiveEntry(archivePath, entryPath, runner, env) {
|
|
160
|
+
const quote = (value) => `'${value.replace(/'/g, "'\\''")}'`;
|
|
161
|
+
// Stream archive members through a bounded scanner. It never prints matched bytes or secret values.
|
|
162
|
+
const scanner = `let tail='';let total=0;const re=new RegExp(${JSON.stringify(BUILD_SECRET_CONTENT_RE.source)},'im');process.stdin.on('data',b=>{total+=b.length;if(total>536870912){process.exitCode=43;process.stdin.destroy();return}const s=tail+b.toString('latin1');if(re.test(s)){process.exitCode=42;process.stdin.destroy();return}tail=s.slice(-1024)});`;
|
|
163
|
+
const script = `tar -xOf ${quote(archivePath)} ${quote(entryPath)} | ${quote(process.execPath)} -e ${quote(scanner)}`;
|
|
164
|
+
const result = runner("bash", ["-o", "pipefail", "-c", script], { env, timeout: 900_000 });
|
|
165
|
+
if (result.status === 42)
|
|
166
|
+
throw new Error("exported image contains credential material in config or layer history");
|
|
167
|
+
if (result.status !== 0)
|
|
168
|
+
throw new Error(`could not complete bounded secret scan of exported image (status ${result.status}); refusing ready status`);
|
|
169
|
+
}
|
|
170
|
+
function scanImageArchiveConfig(archivePath, entryPath, runner, env) {
|
|
171
|
+
const quote = (value) => `'${value.replace(/'/g, "'\\''")}'`;
|
|
172
|
+
// Image config is JSON and may contain nested JSON in labels or environment values. Parse
|
|
173
|
+
// those strings recursively so escaped quotes cannot hide a credential assignment.
|
|
174
|
+
const scanner = `const chunks=[];let total=0;const re=new RegExp(${JSON.stringify(BUILD_SECRET_CONTENT_RE.source)},'im');const keyRe=new RegExp(${JSON.stringify(BUILD_SECRET_KEY_NAME_RE.source)},'i');process.stdin.on('data',b=>{total+=b.length;if(total>16777216){process.exitCode=43;process.stdin.destroy();return}chunks.push(b)});process.stdin.on('end',()=>{let root;try{root=JSON.parse(Buffer.concat(chunks).toString('utf8'))}catch{process.exitCode=44;return}let nodes=0;function secret(value,depth){if(++nodes>100000||depth>32)throw Error('scan limit');if(typeof value==='string'){if(re.test(value))return true;let nested;try{nested=JSON.parse(value)}catch{return false}return nested&&typeof nested==='object'?secret(nested,depth+1):false}if(Array.isArray(value))return value.some(v=>secret(v,depth+1));if(value&&typeof value==='object')return Object.entries(value).some(([k,v])=>keyRe.test(k)||re.test(k)||secret(v,depth+1));return false}try{process.exitCode=secret(root,0)?42:0}catch{process.exitCode=43}});`;
|
|
175
|
+
const script = `tar -xOf ${quote(archivePath)} ${quote(entryPath)} | ${quote(process.execPath)} -e ${quote(scanner)}`;
|
|
176
|
+
const result = runner("bash", ["-o", "pipefail", "-c", script], { env, timeout: 30_000 });
|
|
177
|
+
if (result.status === 42)
|
|
178
|
+
throw new Error("exported image contains credential material in config or layer history");
|
|
179
|
+
if (result.status !== 0)
|
|
180
|
+
throw new Error(`could not complete bounded secret scan of exported image config (status ${result.status}); refusing ready status`);
|
|
181
|
+
}
|
|
182
|
+
function measureCompressedImageBytes(runtime, imageRef, archivePath, runner, env) {
|
|
183
|
+
const imageSize = runner(runtime, ["image", "inspect", imageRef, "--format", "{{.Size}}"], { env, timeout: 30_000 });
|
|
184
|
+
const uncompressedBytes = Number((imageSize.stdout ?? "").trim());
|
|
185
|
+
if (imageSize.status !== 0 || !Number.isSafeInteger(uncompressedBytes) || uncompressedBytes < 1)
|
|
186
|
+
throw new Error("could not inspect uncompressed image size before archive measurement");
|
|
187
|
+
const disk = statfsSync(dirname(archivePath));
|
|
188
|
+
const freeBytes = Number(disk.bavail) * Number(disk.bsize);
|
|
189
|
+
if (!Number.isSafeInteger(freeBytes) || freeBytes < Math.ceil(uncompressedBytes * 1.2))
|
|
190
|
+
throw new Error("insufficient free space to safely measure compressed image layers");
|
|
191
|
+
const saved = runner(runtime, ["image", "save", "--output", archivePath, imageRef], { env, timeout: 900_000 });
|
|
192
|
+
if (saved.status !== 0)
|
|
193
|
+
throw new Error(`could not export image for size measurement: ${errorText(saved.stderr || saved.stdout)}`);
|
|
194
|
+
const quote = (value) => `'${value.replace(/'/g, "'\\''")}'`;
|
|
195
|
+
const manifestResult = runner("tar", ["-xOf", archivePath, "manifest.json"], { env, timeout: 30_000 });
|
|
196
|
+
if (manifestResult.status !== 0)
|
|
197
|
+
throw new Error("image archive has no Docker manifest for size measurement");
|
|
198
|
+
let manifest;
|
|
199
|
+
try {
|
|
200
|
+
manifest = JSON.parse(manifestResult.stdout ?? "");
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
throw new Error("image archive Docker manifest is invalid");
|
|
204
|
+
}
|
|
205
|
+
const layers = manifest[0]?.Layers;
|
|
206
|
+
const config = manifest[0]?.Config;
|
|
207
|
+
if (!Array.isArray(layers) || !layers.length || layers.some((layer) => typeof layer !== "string" || layer.startsWith("/") || layer.split("/").includes("..")) || typeof config !== "string" || config.startsWith("/") || config.split("/").includes("..")) {
|
|
208
|
+
throw new Error("image archive manifest has invalid layer paths");
|
|
209
|
+
}
|
|
210
|
+
let bytes = Buffer.byteLength(manifestResult.stdout ?? "");
|
|
211
|
+
const configResult = runner("bash", ["-o", "pipefail", "-c", `tar -xOf ${quote(archivePath)} ${quote(config)} | wc -c`], { env, timeout: 30_000 });
|
|
212
|
+
const configBytes = Number((configResult.stdout ?? "").trim());
|
|
213
|
+
if (configResult.status !== 0 || !Number.isSafeInteger(configBytes) || configBytes < 0)
|
|
214
|
+
throw new Error("could not measure image config metadata");
|
|
215
|
+
scanImageArchiveConfig(archivePath, config, runner, env);
|
|
216
|
+
bytes += configBytes;
|
|
217
|
+
for (const layer of layers) {
|
|
218
|
+
scanImageArchiveEntry(archivePath, layer, runner, env);
|
|
219
|
+
const result = runner("bash", ["-o", "pipefail", "-c", `tar -xOf ${quote(archivePath)} ${quote(layer)} | gzip -c | wc -c`], { env, timeout: 900_000 });
|
|
220
|
+
const layerBytes = Number((result.stdout ?? "").trim());
|
|
221
|
+
if (result.status !== 0 || !Number.isSafeInteger(layerBytes) || layerBytes < 1)
|
|
222
|
+
throw new Error(`could not measure compressed image layer ${layer}`);
|
|
223
|
+
bytes += layerBytes;
|
|
224
|
+
}
|
|
225
|
+
return bytes;
|
|
226
|
+
}
|
|
123
227
|
/**
|
|
124
228
|
* Materializes an isolated read-only-intent git worktree at `build.source_commit` (never reading
|
|
125
229
|
* mutable `<workdir>/<project>/main`), verifies `HEAD`, clean tree, `target_arch`, `recipe_hash`,
|
|
@@ -133,6 +237,13 @@ export async function reconcilePendingImageBuilds(client, projects, opts) {
|
|
|
133
237
|
const build = img?.latest_build;
|
|
134
238
|
if (!img || !build || build.status !== "pending")
|
|
135
239
|
continue;
|
|
240
|
+
if (img.hosted_build_blocked_reason) {
|
|
241
|
+
const error = `hosted image build refused: ${img.hosted_build_blocked_reason}`;
|
|
242
|
+
await client.call("POST", `/machines/me/image-builds/${build.id}`, { status: "failed", error }).catch(() => { });
|
|
243
|
+
opts.log(`${project.name}: ${error}`);
|
|
244
|
+
results.push({ project_id: project.id, build_id: build.id, status: "failed", error });
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
136
247
|
const nested = (opts.probeSandbox ?? probeNestedSandbox)({ runner });
|
|
137
248
|
if (!nested.runtime) {
|
|
138
249
|
if (process.env.B9S_CONTAINER_AGENTS === "1") {
|
|
@@ -252,6 +363,7 @@ export async function reconcilePendingImageBuilds(client, projects, opts) {
|
|
|
252
363
|
const declaredFeatures = matchedSpec.features ?? [];
|
|
253
364
|
let imageRef;
|
|
254
365
|
if (declaredFeatures.length > 0) {
|
|
366
|
+
assertBuildContextHasNoSecrets(snapshotRealRoot);
|
|
255
367
|
const dcCheck = runner("devcontainer", ["--version"], { env, timeout: 10_000 });
|
|
256
368
|
if (dcCheck.status !== 0) {
|
|
257
369
|
throw new Error(`devcontainer CLI is required to build devcontainer with features (${declaredFeatures.join(", ")}); refusing bare ${nested.runtime} build that would omit declared features`);
|
|
@@ -260,6 +372,7 @@ export async function reconcilePendingImageBuilds(client, projects, opts) {
|
|
|
260
372
|
...refPrefix,
|
|
261
373
|
workspaceFolder: snapshotRealRoot,
|
|
262
374
|
configPath: devcontainerReal,
|
|
375
|
+
dockerPath: networklessRuntimeWrapper(nested.runtime, buildTmpRoot),
|
|
263
376
|
});
|
|
264
377
|
imageRef = dcBuildSpec.imageRef;
|
|
265
378
|
const b = runner(dcBuildSpec.cmd, dcBuildSpec.args, { cwd: snapshotRealRoot, env, timeout: 600_000 });
|
|
@@ -272,6 +385,7 @@ export async function reconcilePendingImageBuilds(client, projects, opts) {
|
|
|
272
385
|
? resolve(dcDir, buildSection.context)
|
|
273
386
|
: snapshotRealRoot;
|
|
274
387
|
const contextReal = assertConfinedSnapshotPath(snapshotRealRoot, rawCtx, "build.context");
|
|
388
|
+
assertBuildContextHasNoSecrets(contextReal);
|
|
275
389
|
const buildSpec = isolatedBuildCommand({
|
|
276
390
|
...refPrefix,
|
|
277
391
|
dockerfilePath: dockerfileReal,
|
|
@@ -314,9 +428,54 @@ export async function reconcilePendingImageBuilds(client, projects, opts) {
|
|
|
314
428
|
throw new Error(`built image ${imageRef} did not yield an immutable @sha256 digest`);
|
|
315
429
|
}
|
|
316
430
|
const imageDigest = digestMatch[1].toLowerCase();
|
|
431
|
+
const validationResults = [];
|
|
432
|
+
for (const probe of build.declared_probes ?? []) {
|
|
433
|
+
if (probe.scope !== "image")
|
|
434
|
+
continue;
|
|
435
|
+
const probeSpec = runImageValidationCommand(nested.runtime, imageRef, probe.probe);
|
|
436
|
+
const result = runner(probeSpec.cmd, probeSpec.args, { env, timeout: 60_000 });
|
|
437
|
+
const output = (result.stdout ?? "").trim();
|
|
438
|
+
validationResults.push(result.status === 0
|
|
439
|
+
? { name: probe.name, scope: "image", ok: true, ...(output ? { version: sanitizeBuildDiagnosticText(output).slice(0, 120) } : {}) }
|
|
440
|
+
: { name: probe.name, scope: "image", ok: false, error: errorText(result.stderr || result.stdout || `${probe.name} probe exited ${result.status}`).slice(0, 300) });
|
|
441
|
+
}
|
|
442
|
+
const testCommand = typeof build.test_command === "string" ? build.test_command.trim() : "";
|
|
443
|
+
const projectTestDir = join(buildTmpRoot, "project-test");
|
|
444
|
+
let projectTest;
|
|
445
|
+
if (!testCommand) {
|
|
446
|
+
projectTest = { ok: false, error: "approved environment declaration is missing its project test command" };
|
|
447
|
+
}
|
|
448
|
+
else {
|
|
449
|
+
cpSync(snapshotRealRoot, projectTestDir, { recursive: true, dereference: false });
|
|
450
|
+
rmSync(join(projectTestDir, ".git"), { recursive: true, force: true });
|
|
451
|
+
const testSpec = runImageValidationCommand(nested.runtime, imageRef, testCommand, projectTestDir);
|
|
452
|
+
const testRun = runner(testSpec.cmd, testSpec.args, { env, cwd: buildTmpRoot, timeout: 1_800_000 });
|
|
453
|
+
projectTest = testRun.status === 0
|
|
454
|
+
? { ok: true }
|
|
455
|
+
: { ok: false, error: errorText(testRun.stderr || testRun.stdout || `project test exited ${testRun.status}`).slice(0, 300) };
|
|
456
|
+
}
|
|
457
|
+
const compressedSizeBytes = measureCompressedImageBytes(nested.runtime, imageRef, join(buildTmpRoot, "image-size.tar"), runner, env);
|
|
458
|
+
const provenance = {
|
|
459
|
+
source_commit: resolvedCommit,
|
|
460
|
+
recipe_hash: matchedSpec.recipe_hash,
|
|
461
|
+
target_arch: build.target_arch,
|
|
462
|
+
base_image_digest: matchedSpec.base_image_digest ?? null,
|
|
463
|
+
builder_runtime: nested.runtime,
|
|
464
|
+
};
|
|
465
|
+
const validationError = [
|
|
466
|
+
...validationResults.filter((r) => !r.ok).map((r) => `${r.name} probe failed: ${r.error}`),
|
|
467
|
+
...(!projectTest.ok ? [`project test failed: ${projectTest.error}`] : []),
|
|
468
|
+
...(compressedSizeBytes > 8 * 1024 * 1024 * 1024 ? ["compressed image exceeds the 8 GiB limit"] : []),
|
|
469
|
+
].join("; ");
|
|
317
470
|
await client.call("POST", `/machines/me/image-builds/${build.id}`, {
|
|
318
|
-
status: "ready",
|
|
471
|
+
status: validationError ? "failed" : "ready",
|
|
319
472
|
image_digest: imageDigest,
|
|
473
|
+
...(img.hosted_registry_repository ? { image_reference: `${imageRef}@${imageDigest}` } : {}),
|
|
474
|
+
probe_results: validationResults,
|
|
475
|
+
project_test: projectTest,
|
|
476
|
+
compressed_size_bytes: compressedSizeBytes,
|
|
477
|
+
provenance,
|
|
478
|
+
...(validationError ? { error: validationError } : {}),
|
|
320
479
|
tool_versions: {
|
|
321
480
|
source_commit: resolvedCommit,
|
|
322
481
|
recipe_hash: matchedSpec.recipe_hash,
|
|
@@ -325,11 +484,24 @@ export async function reconcilePendingImageBuilds(client, projects, opts) {
|
|
|
325
484
|
...(declaredFeatures.length ? { features: declaredFeatures.join(",") } : {}),
|
|
326
485
|
},
|
|
327
486
|
});
|
|
328
|
-
|
|
329
|
-
|
|
487
|
+
if (!validationError && validationResults.length) {
|
|
488
|
+
await client.call("POST", "/machines/me/image-probes", {
|
|
489
|
+
project_id: project.id,
|
|
490
|
+
image_digest: imageDigest,
|
|
491
|
+
probes: validationResults,
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
if (validationError) {
|
|
495
|
+
opts.log(`${project.name}: image candidate validation failed: ${validationError}`);
|
|
496
|
+
results.push({ project_id: project.id, build_id: build.id, status: "failed", error: validationError });
|
|
497
|
+
}
|
|
498
|
+
else {
|
|
499
|
+
opts.log(`${project.name}: built and validated project image ${imageRef}@${imageDigest}`);
|
|
500
|
+
results.push({ project_id: project.id, build_id: build.id, status: "ready", image_digest: imageDigest });
|
|
501
|
+
}
|
|
330
502
|
}
|
|
331
503
|
catch (e) {
|
|
332
|
-
const error = e.message.slice(0, 500);
|
|
504
|
+
const error = sanitizeBuildDiagnosticText(e.message).slice(0, 500);
|
|
333
505
|
await client.call("POST", `/machines/me/image-builds/${build.id}`, { status: "failed", error }).catch(() => { });
|
|
334
506
|
opts.log(`${project.name}: image build failed: ${error}`);
|
|
335
507
|
results.push({ project_id: project.id, build_id: build.id, status: "failed", error });
|
|
@@ -350,7 +522,10 @@ export function resolveContainerLaunchPrereqs(opts) {
|
|
|
350
522
|
throw new Error("container isolation required but neither podman nor docker is available; refusing unisolated host fallback");
|
|
351
523
|
}
|
|
352
524
|
if (opts.s.sandbox !== "danger-full-access" && !nested.nested_sandbox_ok) {
|
|
353
|
-
|
|
525
|
+
const error = new Error(`refusing sandboxed container session (${opts.s.sandbox}) without silently falling back to danger-full-access: ${nested.detail}`);
|
|
526
|
+
if (nested.missing.includes("unprivileged_userns"))
|
|
527
|
+
error.environment_check = "linux_user_namespaces";
|
|
528
|
+
throw error;
|
|
354
529
|
}
|
|
355
530
|
const imageDigest = resolvePinnedImageRef(opts.project?.image);
|
|
356
531
|
if (!imageDigest) {
|
|
@@ -739,7 +914,8 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
739
914
|
catch (e) {
|
|
740
915
|
const error = e.message.slice(0, 1000);
|
|
741
916
|
log(`${s.agent}: ${error}`);
|
|
742
|
-
|
|
917
|
+
const environmentCheck = e.environment_check;
|
|
918
|
+
out.push({ id: s.id, state: "error", thread: state.sessions[s.id]?.thread ?? null, error, ...(typeof environmentCheck === "string" ? { environment_check: environmentCheck } : {}) });
|
|
743
919
|
}
|
|
744
920
|
}
|
|
745
921
|
// Sessions the operator removed: their watchers go too.
|
|
@@ -1043,14 +1219,15 @@ async function ensureCredentials(client, m, s, local, log) {
|
|
|
1043
1219
|
}
|
|
1044
1220
|
export function errorText(s) {
|
|
1045
1221
|
const last = s.trim().split("\n").pop() ?? "";
|
|
1222
|
+
const redact = sanitizeBuildDiagnosticText;
|
|
1046
1223
|
try {
|
|
1047
1224
|
const parsed = JSON.parse(last);
|
|
1048
1225
|
if (parsed.error === "directory_conflict")
|
|
1049
|
-
return "directory_conflict: " + (parsed.message ?? last) + (parsed.hint ? "; " + parsed.hint : "");
|
|
1050
|
-
return parsed.message ?? last;
|
|
1226
|
+
return redact("directory_conflict: " + (parsed.message ?? last) + (parsed.hint ? "; " + parsed.hint : ""));
|
|
1227
|
+
return redact(parsed.message ?? last).slice(0, 500);
|
|
1051
1228
|
}
|
|
1052
1229
|
catch {
|
|
1053
|
-
return last.slice(0, 500);
|
|
1230
|
+
return redact(last).slice(0, 500);
|
|
1054
1231
|
}
|
|
1055
1232
|
}
|
|
1056
1233
|
/** Whether the session has a turn running, its process, and a usage-limit pause still in force. */
|
|
@@ -1233,6 +1410,43 @@ const AGY_SANDBOX_PROBE_MS = 10 * 60_000;
|
|
|
1233
1410
|
const AGY_SANDBOX_PROBE_MODEL = "gemini-4-hydrogen-low";
|
|
1234
1411
|
const AGY_SANDBOX_PROBE_RESPONSE = "B9S_SANDBOX_OK";
|
|
1235
1412
|
let agySandboxCache = null;
|
|
1413
|
+
const AGY_USERNS_ERROR = "Antigravity terminal sandbox unavailable (AppArmor restricts unprivileged user namespaces)";
|
|
1414
|
+
const AGY_USERNS_FIX = `${AGY_USERNS_ERROR}; run b9s machine prepare --agy-userns`;
|
|
1415
|
+
function antigravityUsernsDenied(parsed, output) {
|
|
1416
|
+
const value = parsed;
|
|
1417
|
+
const error = value?.error && typeof value.error === "object" ? value.error : null;
|
|
1418
|
+
const denied = value?.denied_actions ?? error?.denied_actions;
|
|
1419
|
+
return /Terminal sandbox unavailable/i.test(output) || (Array.isArray(denied) && denied.some((entry) => entry && typeof entry === "object" && entry.action === "command"));
|
|
1420
|
+
}
|
|
1421
|
+
/** Install only an absent or byte-identical b9s profile; leave every other owner untouched. */
|
|
1422
|
+
export function installAgyAppArmorProfile(binary, profilePath = AGY_APPARMOR_PATH, run = (args, input) => spawnSync("sudo", args, { input, encoding: "utf8", stdio: input === undefined ? "pipe" : ["pipe", "ignore", "pipe"] })) {
|
|
1423
|
+
const profile = agyAppArmorProfile(binary);
|
|
1424
|
+
let existing = null;
|
|
1425
|
+
try {
|
|
1426
|
+
existing = readFileSync(profilePath, "utf8");
|
|
1427
|
+
}
|
|
1428
|
+
catch (error) {
|
|
1429
|
+
if (error.code !== "ENOENT")
|
|
1430
|
+
return { ok: false, error: `reading ${profilePath}: ${error.message}` };
|
|
1431
|
+
}
|
|
1432
|
+
if (existing !== null && existing !== profile) {
|
|
1433
|
+
return { ok: false, error: `${profilePath} already exists and does not exactly match the b9s Antigravity profile; leaving it unchanged` };
|
|
1434
|
+
}
|
|
1435
|
+
if (existing === null) {
|
|
1436
|
+
const write = run(["-n", "sh", "-c", 'set -C; umask 022; cat > "$1"', "b9s", profilePath], profile);
|
|
1437
|
+
if (write.status !== 0)
|
|
1438
|
+
return { ok: false, error: `installing ${profilePath}: ${(write.stderr ?? "").trim() || `exit ${write.status ?? "unknown"}`}` };
|
|
1439
|
+
}
|
|
1440
|
+
const load = run(["-n", "apparmor_parser", "-r", profilePath]);
|
|
1441
|
+
return load.status === 0
|
|
1442
|
+
? { ok: true, error: null }
|
|
1443
|
+
: { ok: false, error: `loading ${profilePath}: ${(load.stderr ?? "").trim() || `exit ${load.status ?? "unknown"}`}` };
|
|
1444
|
+
}
|
|
1445
|
+
function resolvedAgyBinary(path) {
|
|
1446
|
+
const result = spawnSync("sh", ["-c", "command -v agy"], { encoding: "utf8", env: { ...process.env, PATH: path } });
|
|
1447
|
+
const binary = result.status === 0 ? (result.stdout ?? "").trim() : "";
|
|
1448
|
+
return isAbsolute(binary) ? binary : null;
|
|
1449
|
+
}
|
|
1236
1450
|
/** Runs one cached no-op turn through Antigravity's real workspace-write terminal sandbox. */
|
|
1237
1451
|
export function antigravitySandbox(force = false, path = process.env.PATH ?? "", b9sBin = readInstall()?.bin ?? null) {
|
|
1238
1452
|
if (!force && agySandboxCache && agySandboxCache.path === path && agySandboxCache.b9sBin === b9sBin && Date.now() - agySandboxCache.at < AGY_SANDBOX_PROBE_MS)
|
|
@@ -1259,9 +1473,12 @@ export function antigravitySandbox(force = false, path = process.env.PATH ?? "",
|
|
|
1259
1473
|
wroteMarker = readFileSync(marker, "utf8") === AGY_SANDBOX_PROBE_RESPONSE;
|
|
1260
1474
|
}
|
|
1261
1475
|
catch { /* a missing marker means the sandbox command did not run */ }
|
|
1476
|
+
const output = `${r.stdout ?? ""}\n${r.stderr ?? ""}`;
|
|
1262
1477
|
result = r.status === 0 && parsed?.status === "SUCCESS" && parsed.response?.trim() === AGY_SANDBOX_PROBE_RESPONSE && wroteMarker
|
|
1263
1478
|
? { ok: true, error: null }
|
|
1264
|
-
: { ok: false, error:
|
|
1479
|
+
: { ok: false, error: antigravityUsernsDenied(parsed, output)
|
|
1480
|
+
? AGY_USERNS_FIX
|
|
1481
|
+
: `sandbox could not run b9s --version and its no-op check (agy exit ${r.status ?? "unknown"}); verify recorded install ${b9sBin} and Node runtime ${process.execPath} are readable and executable inside the sandbox` };
|
|
1265
1482
|
}
|
|
1266
1483
|
catch (error) {
|
|
1267
1484
|
const detail = error instanceof Error ? error.message : String(error);
|
|
@@ -1521,6 +1738,45 @@ export function prepare(opts = {}) {
|
|
|
1521
1738
|
: agy.logged_in
|
|
1522
1739
|
? { step: "antigravity login", result: "ok", detail: `${agy.version ?? "agy"}; agy models succeeded` }
|
|
1523
1740
|
: { step: "antigravity login", result: "failed", detail: `${agy.version ?? "agy"}; agy models did not succeed; log in interactively with agy on this machine` });
|
|
1741
|
+
if (!agy.available || !agy.logged_in) {
|
|
1742
|
+
steps.push({ step: "antigravity sandbox", result: "skipped", detail: "agy must be installed and logged in before its terminal sandbox can be checked" });
|
|
1743
|
+
}
|
|
1744
|
+
else {
|
|
1745
|
+
let agySandboxResult = antigravitySandbox(true, daemonPath);
|
|
1746
|
+
if (agySandboxResult.ok) {
|
|
1747
|
+
steps.push({ step: "antigravity sandbox", result: "ok", detail: "workspace-write terminal sandbox works" });
|
|
1748
|
+
}
|
|
1749
|
+
else if (!agySandboxResult.error?.startsWith(AGY_USERNS_ERROR)) {
|
|
1750
|
+
steps.push({ step: "antigravity sandbox", result: "failed", detail: agySandboxResult.error ?? "agy sandbox no-op failed" });
|
|
1751
|
+
}
|
|
1752
|
+
else if (platform() !== "linux") {
|
|
1753
|
+
steps.push({ step: "antigravity sandbox", result: "failed", detail: `${AGY_USERNS_ERROR}; this opt-in AppArmor fix applies only on Linux` });
|
|
1754
|
+
}
|
|
1755
|
+
else if (!opts.agyUserns) {
|
|
1756
|
+
steps.push({ step: "antigravity sandbox", result: "failed", detail: `${agySandboxResult.error}; the profile targets the resolved agy binary at ${AGY_APPARMOR_PATH}` });
|
|
1757
|
+
}
|
|
1758
|
+
else if (!sudo) {
|
|
1759
|
+
steps.push({ step: "antigravity sandbox", result: "failed", detail: `--agy-userns needs passwordless sudo; install ${AGY_APPARMOR_PATH} by hand (b9s machine prepare --print-apparmor shows the profile) and run sudo apparmor_parser -r on it` });
|
|
1760
|
+
}
|
|
1761
|
+
else {
|
|
1762
|
+
const binary = resolvedAgyBinary(daemonPath);
|
|
1763
|
+
if (!binary) {
|
|
1764
|
+
steps.push({ step: "antigravity sandbox", result: "failed", detail: `--agy-userns could not resolve agy on the daemon PATH; cannot safely create ${AGY_APPARMOR_PATH}` });
|
|
1765
|
+
}
|
|
1766
|
+
else {
|
|
1767
|
+
const install = installAgyAppArmorProfile(binary);
|
|
1768
|
+
if (!install.ok) {
|
|
1769
|
+
steps.push({ step: "antigravity sandbox", result: "failed", detail: install.error ?? `could not install ${AGY_APPARMOR_PATH}` });
|
|
1770
|
+
}
|
|
1771
|
+
else {
|
|
1772
|
+
agySandboxResult = antigravitySandbox(true, daemonPath);
|
|
1773
|
+
steps.push(agySandboxResult.ok
|
|
1774
|
+
? { step: "antigravity sandbox", result: "done", detail: `installed ${AGY_APPARMOR_PATH} for ${binary}; workspace-write terminal sandbox works` }
|
|
1775
|
+
: { step: "antigravity sandbox", result: "failed", detail: `${AGY_APPARMOR_PATH} loaded but sandbox still fails: ${agySandboxResult.error}` });
|
|
1776
|
+
}
|
|
1777
|
+
}
|
|
1778
|
+
}
|
|
1779
|
+
}
|
|
1524
1780
|
const codex = spawnSync("codex", ["--version"], { encoding: "utf8", env: daemonEnv });
|
|
1525
1781
|
if (codex.status !== 0)
|
|
1526
1782
|
steps.push({ step: "codex", result: "failed", detail: "codex is not on PATH; install the Codex CLI (npm i -g @openai/codex) and log in (codex login --device-auth)" });
|
|
@@ -1918,9 +2174,15 @@ export async function machine(p, out) {
|
|
|
1918
2174
|
if (sub === "prepare") {
|
|
1919
2175
|
if (p.flags["print-hooks"])
|
|
1920
2176
|
return out.print(codexManagedHooks(requireInstall().bin).requirements, codexManagedHooks(requireInstall().bin));
|
|
1921
|
-
if (p.flags["print-apparmor"])
|
|
1922
|
-
|
|
1923
|
-
|
|
2177
|
+
if (p.flags["print-apparmor"]) {
|
|
2178
|
+
const agyBinary = resolvedAgyBinary(machineDaemonPath()) ?? join(homedir(), ".local", "bin", "agy");
|
|
2179
|
+
return out.print(`${CODEX_APPARMOR_PATH}:\n${codexAppArmorProfile()}\n${BWRAP_APPARMOR_PATH}:\n${bwrapAppArmorProfile()}\n${AGY_APPARMOR_PATH}:\n${agyAppArmorProfile(agyBinary)}`, {
|
|
2180
|
+
[CODEX_APPARMOR_PATH]: codexAppArmorProfile(),
|
|
2181
|
+
[BWRAP_APPARMOR_PATH]: bwrapAppArmorProfile(),
|
|
2182
|
+
[AGY_APPARMOR_PATH]: agyAppArmorProfile(agyBinary),
|
|
2183
|
+
});
|
|
2184
|
+
}
|
|
2185
|
+
const steps = prepare({ codexUserns: p.flags["codex-userns"] === true, bwrapUserns: p.flags["bwrap-userns"] === true, agyUserns: p.flags["agy-userns"] === true });
|
|
1924
2186
|
return out.print(steps.map((s) => `${s.result.padEnd(8)} ${s.step}: ${s.detail}`).join("\n"), { steps });
|
|
1925
2187
|
}
|
|
1926
2188
|
if (sub === "service") {
|
package/dist/commands/watch.js
CHANGED
|
@@ -325,8 +325,8 @@ export async function watch(p, out) {
|
|
|
325
325
|
return stoppingCode;
|
|
326
326
|
debugLog(`seen messages=${u?.counts.messages ?? 0} questions=${u?.counts.questions ?? 0} items=${u?.counts.items ?? 0} followed=${u?.counts.followed ?? 0} digest=${u?.counts.digest ?? 0} notices=${u?.counts.notices ?? 0}; tier=${u?.tier ?? "none"}; decision=${u ? "deliver" : "no updates"}`);
|
|
327
327
|
if (u) {
|
|
328
|
-
const recovery =
|
|
329
|
-
const update =
|
|
328
|
+
const recovery = await recoveryBriefText(name, log);
|
|
329
|
+
const update = formatUpdates(omitMeasuresAlreadyIn(recovery, u), [recovery ?? recoveryBriefUnavailableText]);
|
|
330
330
|
const total = update.counts.messages + update.counts.items + update.counts.followed + update.counts.digest + update.counts.notices;
|
|
331
331
|
const summary = update.text.split("\n")[0].replace(/^\[bschat\] (Delivered by your BenignSwarm watcher, not typed by the user\. )?/, "");
|
|
332
332
|
let delivered = true;
|
|
@@ -475,8 +475,8 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
|
|
|
475
475
|
}
|
|
476
476
|
}
|
|
477
477
|
const seq = (st.watch_seq ?? 0) + 1;
|
|
478
|
-
const recovery =
|
|
479
|
-
const recoveryPrompt =
|
|
478
|
+
const recovery = await recoveryBriefText(name, log);
|
|
479
|
+
const recoveryPrompt = recovery ?? recoveryBriefUnavailableText;
|
|
480
480
|
const wakePrefix = [
|
|
481
481
|
...(turnSink
|
|
482
482
|
? [`[b9s] Turn #${seq}, started by your BenignSwarm watcher because you were idle; not typed by the user. It is already acknowledged.`]
|
package/dist/commands/wu.js
CHANGED
|
@@ -5,7 +5,7 @@ import { Client } from "../client.js";
|
|
|
5
5
|
import { agentRef, loadAgent, resolveAgentName, resolveModel } from "../config.js";
|
|
6
6
|
import { readState } from "../state.js";
|
|
7
7
|
import { codexRollout, sessionsOf } from "../sessions.js";
|
|
8
|
-
import { claudeSessionWithHookMetadata, sessionCompactions, sessionContext, sessionUsage } from "../usage.js";
|
|
8
|
+
import { claudeSessionWithHookMetadata, sessionCompactions, sessionContext, sessionStart, sessionUsage } from "../usage.js";
|
|
9
9
|
import { CliError } from "../errors.js";
|
|
10
10
|
import { branchAndHead, commitAtTime, ensureReviewWorktree, ensureWorktree, fetchRef, fetchRemoteBranch, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, isAncestor, isShaBranchName, removeWorktreeIfClean, repoName, repoParent, symbolicBranch, verifyMergedCommit, verifyNoCommitsBeyondTarget, worktreeForBranch } from "../git.js";
|
|
11
11
|
import { join, resolve } from "node:path";
|
|
@@ -710,7 +710,7 @@ export async function wu(p, out) {
|
|
|
710
710
|
}
|
|
711
711
|
}
|
|
712
712
|
const pr = str(p.flags, "pr") ?? null;
|
|
713
|
-
const telemetry = await roundTelemetry(client, base, num(), name);
|
|
713
|
+
const telemetry = await roundTelemetry(client, base, num(), name, project);
|
|
714
714
|
let branchValueIds = [];
|
|
715
715
|
if (where.head) {
|
|
716
716
|
try {
|
|
@@ -763,7 +763,7 @@ export async function wu(p, out) {
|
|
|
763
763
|
const cause = str(p.flags, "cause");
|
|
764
764
|
if (sendBackEvent && (sub !== "rule" || !cause || !text))
|
|
765
765
|
throw new CliError("usage", 'wu rule <n> --send-back-event <event-id> --cause <cause> --ruling "decision"');
|
|
766
|
-
const r = await client.call("POST", `${base}/${num()}/${sub}`, sub === "ask" ? { question: text } : sendBackEvent ? { send_back_event_id: sendBackEvent, cause, ruling: text } : approve ? { approve: true, ruling: text } : { ruling: text });
|
|
766
|
+
const r = await client.call("POST", `${base}/${num()}/${sub}`, sub === "ask" ? { question: text, usage: await reviewUsage(client, project, name) } : sendBackEvent ? { send_back_event_id: sendBackEvent, cause, ruling: text } : approve ? { approve: true, ruling: text } : { ruling: text });
|
|
767
767
|
const q = r.unit.question;
|
|
768
768
|
out.print(`${fmt(r.unit)}\n${sendBackEvent ? "Retrospective ruling recorded on the unit; no chat message was added." : sub === "rule" ? "Ruled; the asker, owner and reviewers were told." : q.level === "expert" ? `Asked a ${q.roles.join(" or ")}; it goes to the operator if nobody rules in time.` : "Asked the operator."}`, r);
|
|
769
769
|
return;
|
|
@@ -830,7 +830,7 @@ export async function wu(p, out) {
|
|
|
830
830
|
const cause = str(p.flags, "cause");
|
|
831
831
|
if (sub === "changes" && !cause)
|
|
832
832
|
throw new CliError("usage", 'wu changes <n> --cause <scope_gap|missing_context|worker_error|reviewer_scope_growth|environment|stale_base> --unmet "<cited clause>" --note "what must change"');
|
|
833
|
-
const r = await client.call("POST", `${base}/${num()}/${sub}`, { note, ...(unmet ? { unmet } : {}), ...(cause ? { cause } : {}), ...(sub === "approve" && p.flags["confirm-causes"] !== undefined ? { confirmed_causes: list("confirm-causes") } : {}) });
|
|
833
|
+
const r = await client.call("POST", `${base}/${num()}/${sub}`, { note, usage: await reviewUsage(client, project, name), ...(unmet ? { unmet } : {}), ...(cause ? { cause } : {}), ...(sub === "approve" && p.flags["confirm-causes"] !== undefined ? { confirmed_causes: list("confirm-causes") } : {}) });
|
|
834
834
|
out.print(fmt(r.unit), r);
|
|
835
835
|
return;
|
|
836
836
|
}
|
|
@@ -954,7 +954,7 @@ export async function wu(p, out) {
|
|
|
954
954
|
}
|
|
955
955
|
case "note": {
|
|
956
956
|
const annotation = jsonFlag(p, "annotation", "an annotation object");
|
|
957
|
-
const r = await client.call("POST", `${base}/${num()}/note`, { note: str(p.flags, "note") ?? "", evidence: list("evidence"), ...(annotation ? { annotation } : {}) });
|
|
957
|
+
const r = await client.call("POST", `${base}/${num()}/note`, { note: str(p.flags, "note") ?? "", evidence: list("evidence"), usage: await reviewUsage(client, project, name), ...(annotation ? { annotation } : {}) });
|
|
958
958
|
out.print(fmt(r.unit), r);
|
|
959
959
|
return;
|
|
960
960
|
}
|
|
@@ -1541,6 +1541,35 @@ export async function askOperator(p, out) {
|
|
|
1541
1541
|
const r = await client.call("POST", `/projects/${project}/ask-operator`, { text, ...fields, proposal });
|
|
1542
1542
|
out.print(`Asked the operator${proposal ? " with your proposal (they can approve it as written)" : ""}; it is on their console banner and reported to them. You will be @mentioned with the decision. Carry on with what does not depend on it.`, r);
|
|
1543
1543
|
}
|
|
1544
|
+
async function reviewUsage(client, project, name) {
|
|
1545
|
+
const until = new Date().toISOString();
|
|
1546
|
+
const session = measurableSession(name);
|
|
1547
|
+
let since;
|
|
1548
|
+
try {
|
|
1549
|
+
const result = await client.call("GET", `/projects/${project}/agents/me/usage-cursor`);
|
|
1550
|
+
if (result.since === null)
|
|
1551
|
+
since = sessionStart(session);
|
|
1552
|
+
else {
|
|
1553
|
+
const cursor = typeof result.since === "string" ? Date.parse(result.since) : NaN;
|
|
1554
|
+
if (!Number.isFinite(cursor))
|
|
1555
|
+
throw new Error("invalid session usage cursor");
|
|
1556
|
+
since = new Date(cursor + 1).toISOString();
|
|
1557
|
+
}
|
|
1558
|
+
}
|
|
1559
|
+
catch (error) {
|
|
1560
|
+
return { harness: session?.harness ?? "unknown", source: "none", scope: "session", since: until, until, tokens: null, reason: `could not read session usage cursor: ${error.message}` };
|
|
1561
|
+
}
|
|
1562
|
+
if (!since)
|
|
1563
|
+
return { harness: session?.harness ?? "unknown", source: "none", scope: "session", since: until, until, tokens: null, reason: "no earlier usage boundary or timestamped session is available" };
|
|
1564
|
+
if (Date.parse(since) > Date.parse(until))
|
|
1565
|
+
return { harness: session?.harness ?? "unknown", source: "none", scope: "session", since: until, until, tokens: null, reason: "session usage cursor is later than the measurement time" };
|
|
1566
|
+
try {
|
|
1567
|
+
return sessionUsage(session, since, until);
|
|
1568
|
+
}
|
|
1569
|
+
catch (error) {
|
|
1570
|
+
return { harness: session?.harness ?? "unknown", source: "none", scope: "session", since, until, tokens: null, reason: `could not read session usage: ${error.message}` };
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1544
1573
|
function measurableSession(name) {
|
|
1545
1574
|
const sessionId = process.env.BSCHAT_SESSION_ID;
|
|
1546
1575
|
if (sessionId) {
|
|
@@ -1563,14 +1592,26 @@ function startTelemetry(name) {
|
|
|
1563
1592
|
const at = new Date().toISOString();
|
|
1564
1593
|
return { context: sessionContext(measurableSession(name), at), compactions_since_last: 0, compactions_reason: null };
|
|
1565
1594
|
}
|
|
1566
|
-
async function roundTelemetry(client, base, n, name) {
|
|
1595
|
+
async function roundTelemetry(client, base, n, name, project) {
|
|
1567
1596
|
try {
|
|
1568
1597
|
const events = (await client.call("GET", `${base}/${n}`)).events;
|
|
1569
|
-
|
|
1598
|
+
const telemetry = await telemetryFromEvents(name, events);
|
|
1599
|
+
const cursor = await client.call("GET", `/projects/${project}/agents/me/usage-cursor`);
|
|
1600
|
+
if (cursor.since !== null && cursor.since !== undefined) {
|
|
1601
|
+
const previous = Date.parse(cursor.since);
|
|
1602
|
+
const current = Date.parse(telemetry.usage.since);
|
|
1603
|
+
if (!Number.isFinite(previous) || !Number.isFinite(current))
|
|
1604
|
+
throw new Error("invalid session usage cursor");
|
|
1605
|
+
const since = new Date(Math.max(current, previous + 1)).toISOString();
|
|
1606
|
+
if (Date.parse(since) > Date.parse(telemetry.usage.until))
|
|
1607
|
+
throw new Error("session usage cursor is later than the measurement time");
|
|
1608
|
+
telemetry.usage = sessionUsage(measurableSession(name), since, telemetry.usage.until);
|
|
1609
|
+
}
|
|
1610
|
+
return telemetry;
|
|
1570
1611
|
}
|
|
1571
1612
|
catch (e) {
|
|
1572
1613
|
const until = new Date().toISOString();
|
|
1573
|
-
const reason = `could not read the unit
|
|
1614
|
+
const reason = `could not read the unit timeline or usage cursor: ${e.message}`;
|
|
1574
1615
|
const usage = { harness: "unknown", source: "none", scope: "session", since: until, until, tokens: null, reason };
|
|
1575
1616
|
return { usage, context: { pct: null, tokens: null, window: null, source: "unknown", measured_at: null, reason }, compactions: { count: null, reason } };
|
|
1576
1617
|
}
|
package/dist/container.js
CHANGED
|
@@ -15,6 +15,24 @@ const FORBIDDEN_MOUNT_RE = /(\/var\/run\/docker\.sock|\/\.ssh(?:\/|$)|\/\.aws(?:
|
|
|
15
15
|
const FORBIDDEN_FLAG_RE = /(--privileged|--cap-add(?:=|\s+)(?:SYS_ADMIN|ALL)|--net(?:work)?(?:=|\s+)host|--pid(?:=|\s+)host|--userns(?:=|\s+)host)/i;
|
|
16
16
|
const SECRET_KEY_RE = /(AWS_ACCESS_KEY_ID|AWS_SECRET_ACCESS_KEY|AWS_SESSION_TOKEN|OPENAI_API_KEY|ANTHROPIC_API_KEY|DEEPSEEK_API_KEY|GITHUB_TOKEN|GH_TOKEN|BSCHAT_KEY|B9S_KEY|BOT_TOKEN|PRIVATE_KEY)/i;
|
|
17
17
|
const SECRET_VALUE_RE = /(bs_(?:admin|agent|machine|enroll|boot)_[A-Za-z0-9]+|gh[pousr]_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]{12,}|AKIA[0-9A-Z]{16})/;
|
|
18
|
+
export const BUILD_SECRET_KEY_NAME_RE = /^(?:_authToken|_auth|password|passwd|token|secret|api[_-]?key|AWS_ACCESS_KEY_ID|AWS_SECRET_ACCESS_KEY|AWS_SESSION_TOKEN|OPENAI_API_KEY|ANTHROPIC_API_KEY|DEEPSEEK_API_KEY|GITHUB_TOKEN|GH_TOKEN|BSCHAT_KEY|B9S_KEY|BOT_TOKEN|PRIVATE_KEY)$/i;
|
|
19
|
+
export const BUILD_SECRET_CONTENT_RE = /(?:_authToken|(?:^|\s)_auth|(?:^|\s)(?:password|passwd|token|secret|api[_-]?key)\s*[:=]\s*[^\s#]{4,}|(?:^|[^A-Za-z0-9_])(?:AWS_ACCESS_KEY_ID|AWS_SECRET_ACCESS_KEY|AWS_SESSION_TOKEN|OPENAI_API_KEY|ANTHROPIC_API_KEY|DEEPSEEK_API_KEY|GITHUB_TOKEN|GH_TOKEN|BSCHAT_KEY|B9S_KEY|BOT_TOKEN|PRIVATE_KEY)["']?\s*[:=]\s*["']?[^\s"'#},]{4,}|-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|bs_(?:admin|agent|machine|enroll|boot)_[A-Za-z0-9]+|gh[pousr]_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]{12,}|AKIA[0-9A-Z]{16})/im;
|
|
20
|
+
const SECRET_BUILD_KEY_RE = /(AWS_ACCESS_KEY_ID|AWS_SECRET_ACCESS_KEY|AWS_SESSION_TOKEN|OPENAI_API_KEY|ANTHROPIC_API_KEY|DEEPSEEK_API_KEY|GITHUB_TOKEN|GH_TOKEN|BSCHAT_KEY|B9S_KEY|BOT_TOKEN|PRIVATE_KEY)/i;
|
|
21
|
+
/** Detect credential material in build contexts and exported image metadata/layers. */
|
|
22
|
+
export function containsBuildSecretMaterial(content) {
|
|
23
|
+
return BUILD_SECRET_CONTENT_RE.test(typeof content === "string" ? content : content.toString("latin1"));
|
|
24
|
+
}
|
|
25
|
+
const SECRET_DIAGNOSTIC_KEYS = "AWS_ACCESS_KEY_ID|AWS_SECRET_ACCESS_KEY|AWS_SESSION_TOKEN|OPENAI_API_KEY|ANTHROPIC_API_KEY|DEEPSEEK_API_KEY|GITHUB_TOKEN|GH_TOKEN|BSCHAT_KEY|B9S_KEY|BOT_TOKEN|PRIVATE_KEY";
|
|
26
|
+
const JSON_SECRET_DIAGNOSTIC_RE = new RegExp(`("(?:${SECRET_DIAGNOSTIC_KEYS})"\\s*:\\s*")[^"\\r\\n]*"`, "gi");
|
|
27
|
+
const BARE_SECRET_DIAGNOSTIC_RE = new RegExp(`\\b(${SECRET_DIAGNOSTIC_KEYS})\\b(\\s*[:=]\\s*)(?:"[^"\\r\\n]*"|'[^'\\r\\n]*'|[^\\s,;}\\]]+)`, "gi");
|
|
28
|
+
/** Redact known credentials before daemon diagnostics are logged, returned, or posted. */
|
|
29
|
+
export function sanitizeBuildDiagnosticText(text) {
|
|
30
|
+
return text
|
|
31
|
+
.replace(JSON_SECRET_DIAGNOSTIC_RE, '$1[REDACTED]"')
|
|
32
|
+
.replace(BARE_SECRET_DIAGNOSTIC_RE, "$1$2[REDACTED]")
|
|
33
|
+
.replace(/(_authToken\s*=\s*)[^\s#]+/gi, "$1[REDACTED]")
|
|
34
|
+
.replace(/(bs_(?:admin|agent|machine|enroll|boot)_[A-Za-z0-9]+|AKIA[0-9A-Z]{16}|sk-[A-Za-z0-9_-]{12,}|gh[pousr]_[A-Za-z0-9_]+)/g, "[REDACTED]");
|
|
35
|
+
}
|
|
18
36
|
function canonicalSort(v) {
|
|
19
37
|
if (Array.isArray(v))
|
|
20
38
|
return v.map(canonicalSort);
|
|
@@ -90,6 +108,21 @@ export function validateDevcontainerSpec(devcontainerRaw, opts = {}) {
|
|
|
90
108
|
const df = opts.dockerfileContent ?? "";
|
|
91
109
|
if (!df.trim())
|
|
92
110
|
return { ok: false, error: "dockerfileContent required to verify pinned FROM digests" };
|
|
111
|
+
if (SECRET_VALUE_RE.test(df))
|
|
112
|
+
return { ok: false, error: "Dockerfile contains token-like material; build-time secrets are not allowed" };
|
|
113
|
+
for (const raw of df.split(/\r?\n/)) {
|
|
114
|
+
const line = raw.trim();
|
|
115
|
+
const declaration = /^(ARG|ENV)\s+(.+)$/i.exec(line);
|
|
116
|
+
const keys = declaration ? (declaration[1].toUpperCase() === "ARG" ? [declaration[2].trim().split(/[=\s]/, 1)[0]] : declaration[2].trim().split(/\s+/).map((entry) => entry.split("=", 1)[0])) : [];
|
|
117
|
+
const secretKey = keys.find((key) => SECRET_BUILD_KEY_RE.test(key));
|
|
118
|
+
if (secretKey)
|
|
119
|
+
return { ok: false, error: `Dockerfile ${declaration?.[1]} references secret key ${secretKey}; build-time secrets are not allowed` };
|
|
120
|
+
if (/--mount\s*=\s*type=secret|(?:^|\s)--secret(?:=|\s)/i.test(line))
|
|
121
|
+
return { ok: false, error: "Dockerfile secret mounts and --secret options are not allowed" };
|
|
122
|
+
const runNetwork = /^RUN\b.*--network(?:=|\s+)(\S+)/i.exec(line);
|
|
123
|
+
if (runNetwork && runNetwork[1].toLowerCase() !== "none")
|
|
124
|
+
return { ok: false, error: "Dockerfile RUN network overrides are forbidden; build steps must use network=none" };
|
|
125
|
+
}
|
|
93
126
|
const fromMatches = [...df.matchAll(/^\s*FROM\s+(?:--platform=\S+\s+)?(\S+)/gim)];
|
|
94
127
|
if (!fromMatches.length)
|
|
95
128
|
return { ok: false, error: "Dockerfile must contain a pinned FROM instruction" };
|
|
@@ -276,6 +309,8 @@ export function isolatedBuildCommand(opts) {
|
|
|
276
309
|
const { imageRef, cacheKey } = isolatedImageMetadata(opts);
|
|
277
310
|
const args = [
|
|
278
311
|
"build",
|
|
312
|
+
"--network",
|
|
313
|
+
"none",
|
|
279
314
|
"--platform",
|
|
280
315
|
opts.arch,
|
|
281
316
|
"--no-cache=false",
|
|
@@ -326,7 +361,7 @@ export function isolatedDevcontainerBuildCommand(opts) {
|
|
|
326
361
|
"--config",
|
|
327
362
|
opts.configPath,
|
|
328
363
|
"--docker-path",
|
|
329
|
-
opts.runtime,
|
|
364
|
+
opts.dockerPath ?? opts.runtime,
|
|
330
365
|
"--platform",
|
|
331
366
|
opts.arch,
|
|
332
367
|
"--image-name",
|
|
@@ -336,6 +371,16 @@ export function isolatedDevcontainerBuildCommand(opts) {
|
|
|
336
371
|
cacheKey,
|
|
337
372
|
};
|
|
338
373
|
}
|
|
374
|
+
/**
|
|
375
|
+
* Dev Container CLI does not expose Docker build's network mode directly. Route its runtime calls
|
|
376
|
+
* through a small wrapper that forces --network=none on every `build`/`buildx build` invocation.
|
|
377
|
+
*/
|
|
378
|
+
export function networklessRuntimeWrapper(runtime, directory) {
|
|
379
|
+
const path = join(directory, `b9s-${runtime}-networkless.cjs`);
|
|
380
|
+
writeFileSync(path, `#!${process.execPath}\nconst { spawnSync } = require("node:child_process");\nconst args = process.argv.slice(2);\nconst isBuild = args[0] === "build" || (args[0] === "buildx" && args[1] === "build");\nif (isBuild) args.splice(Math.max(1, args.length - 1), 0, "--network=none");\nconst result = spawnSync(${JSON.stringify(runtime)}, args, { stdio: "inherit", env: process.env });\nprocess.exit(result.status ?? 1);\n`, { mode: 0o700 });
|
|
381
|
+
chmodSync(path, 0o700);
|
|
382
|
+
return path;
|
|
383
|
+
}
|
|
339
384
|
export function agentContainerName(accountSlug, project, agent) {
|
|
340
385
|
return `b9s-${accountSlug}-${project}-${agent}`.toLowerCase().replace(/[^a-z0-9_.-]/g, "-").slice(0, 60);
|
|
341
386
|
}
|
package/dist/harness.js
CHANGED
|
@@ -438,6 +438,7 @@ export function codexManagedHooks(bin) {
|
|
|
438
438
|
}
|
|
439
439
|
export const CODEX_APPARMOR_PATH = "/etc/apparmor.d/bschat-codex";
|
|
440
440
|
export const BWRAP_APPARMOR_PATH = "/etc/apparmor.d/bschat-bwrap";
|
|
441
|
+
export const AGY_APPARMOR_PATH = "/etc/apparmor.d/bschat-agy";
|
|
441
442
|
/**
|
|
442
443
|
* An AppArmor profile that lets the system's bubblewrap create user namespaces, which Claude Code's
|
|
443
444
|
* Linux sandbox runs commands in. Broader than the Codex profile: any local user may then use
|
|
@@ -480,3 +481,20 @@ export function codexAppArmorProfile() {
|
|
|
480
481
|
``,
|
|
481
482
|
].join("\n");
|
|
482
483
|
}
|
|
484
|
+
/** An opt-in AppArmor profile for the installed Antigravity CLI only. */
|
|
485
|
+
export function agyAppArmorProfile(binary) {
|
|
486
|
+
if (!binary.startsWith("/"))
|
|
487
|
+
throw new Error("Antigravity binary path must be absolute");
|
|
488
|
+
return [
|
|
489
|
+
`# b9s: let Antigravity create the user namespaces its workspace-write terminal sandbox needs (Ubuntu 24.04+ restricts them).`,
|
|
490
|
+
`# Written by b9s machine prepare --agy-userns; remove this file and run apparmor_parser -R on it to undo.`,
|
|
491
|
+
`abi <abi/4.0>,`,
|
|
492
|
+
`include <tunables/global>`,
|
|
493
|
+
``,
|
|
494
|
+
`profile bschat-agy ${binary} flags=(unconfined) {`,
|
|
495
|
+
` userns,`,
|
|
496
|
+
` include if exists <local/bschat-agy>`,
|
|
497
|
+
`}`,
|
|
498
|
+
``,
|
|
499
|
+
].join("\n");
|
|
500
|
+
}
|
package/dist/help.js
CHANGED
|
@@ -31,6 +31,7 @@ Environment problems: agents report bounded, redacted observations with b9s envi
|
|
|
31
31
|
|
|
32
32
|
Work-unit open, start, submit and close endpoints accept context fill and compaction metadata on lifecycle events. Report explicit unknown reasons when unavailable; never send prompt or response text as context. Context aggregation is grouped by the event owner and its stamped model/effort. Context policies (keep | compact | clear | agent-decides) resolve unit > role > project > system default keep, freeze on assignment/open, audit settings and action-metadata decisions via GET/PUT /projects/:p/context-policy, POST /projects/:p/work-units/:n/context-policy, and POST /projects/:p/work-units/:n/context-policy/decision, and fail closed until an assigner or operator updates a blocked unit. See packages/skill/references/api.md for field validation and response shapes.
|
|
33
33
|
GET /projects/:p/context-policy/comparison reports descriptive project-scoped policy aggregates by build/review mode, tag, and exact event-stamped class. Reviewer event counts are separate from replay-cluster uncertainty; turn token usage stays unknown. Clear-cohort units need their own server-verified clear event and a later start by the same actor. Results are not causal or paired; the console view is WU #299.
|
|
34
|
+
GET /projects/:p/work-units/:n/cost reports recorded worker, review and rework session tokens across superseded units; GET /projects/:p/stats includes finished-unit model costs. Incomplete or overlapping windows remain explicit, and token-weight prices are estimates. GET /projects/:p/agents/me/usage-cursor gives the caller's session boundary. See packages/skill/references/api.md.
|
|
34
35
|
Build dispatch checks role qualifications, capabilities, holds, reservations and operator-only required_class first, then ranks eligible workers by routing_policy weights, build quality guardrail, weakest-tag tie-break and build exploration budget, falling back when the preferred class is busy and recording route_decision / dispatch_reasons on units and events. Operators set/clear hard required_class with an audited reason via POST /projects/:p/work-units/:n/required-class (or tag definitions) and inspect cleared legacy min_tier rows via GET /projects/:p/routing/tier-migration (never guessing class mappings). Console routing controls are WU #244; CLI routing view/controls are WU #242.
|
|
35
36
|
Review routing ranks only independent qualified reviewers (excluding owner, prior builders, same-worktree occupants, and forbidden_dependent_roles), preserves trial/expert/mandatory_reviewer blockers, supports paired comparisons and head-to-head verdicts (POST /projects/:p/work-units/:n/compare, closing non-selected units as compared), and exposes GET /projects/:p/review-routing. Console routing controls are WU #244; CLI routing view/controls are WU #242. See packages/skill/references/api.md for field validation and response shapes.
|
|
36
37
|
|
|
@@ -216,16 +217,18 @@ Agent commands
|
|
|
216
217
|
Pressured or unknown telemetry holds heavy permits; ordinary turns remain available.
|
|
217
218
|
Claude Code workspace-write defaults to a $1 per-turn cap; configure it with --max-budget-usd
|
|
218
219
|
Account turn-spend caps are set by the account operator separately; token caps support subscriptions,
|
|
219
|
-
missing usage remains reserved.
|
|
220
|
+
missing usage remains reserved. Hard caps alone do not enable judgment capture; the account owner explicitly
|
|
221
|
+
toggles PUT /account/turn-budget/judgment-capture (enabled + reason), surfaced by console WU #238.
|
|
220
222
|
Admin-only account reads: GET /account/turn-spend/reservations and
|
|
221
223
|
GET /account/turn-spend/sessions/:session/reservations list unresolved reservations;
|
|
222
|
-
GET /account/turn-budget/audit lists
|
|
224
|
+
GET /account/turn-budget/audit lists budget and judgment activation changes. All three are paged and account-scoped.
|
|
223
225
|
(b9s codex start is the same with --harness codex)
|
|
224
226
|
b9s unpause [--as <a>] lift a usage-limit pause now (the harness was switched to an account with quota)
|
|
225
227
|
b9s turn note "<short progress summary>" [--as <a>] save a 300-character turn-end excerpt for an enabled managed session; it is labelled unverified
|
|
226
228
|
b9s machine bootstrap --url <api> [--retrieve-ec2 | --token-file <path> | --token <bs_boot_...>] [--name <m>] retrieve (over TLS+IMDSv2/STS) and exchange a single-use cloud bootstrap token once, scrub it, and write mode-0600 credentials
|
|
227
|
-
b9s machine run [--interval seconds] | once | build-images | status | prepare | service
|
|
228
|
-
default interval 30s, 1..3600; prepare checks
|
|
229
|
+
b9s machine run [--interval seconds] | once | build-images | status | prepare [--agy-userns] [--print-apparmor] | service
|
|
230
|
+
default interval 30s, 1..3600; prepare checks harnesses; --agy-userns opts into an AppArmor
|
|
231
|
+
profile for the resolved agy binary if Ubuntu blocks its workspace-write terminal sandbox (passwordless sudo)
|
|
229
232
|
b9s machine processes --worktree <path> [--as <project>/<agent>] [--json] read-only host process sample for a project-owned worktree
|
|
230
233
|
includes pid/parent, start/elapsed, command (120 chars), cwd, TCP listeners and sample time
|
|
231
234
|
project agents only; stale samples are labelled; command credentials are redacted; no environment values or signaling
|
|
@@ -366,12 +369,13 @@ the returned object and warning, then exits 3. Inspect the object and do not ret
|
|
|
366
369
|
|
|
367
370
|
Machines (provisioned over your own ssh; a daemon on each runs the agent sessions you declare)
|
|
368
371
|
Account Mac leases and trusted TestFlight signing approvals are managed in Console → Machines → Mac fleet and signing; there is no CLI signing or App Store release command.
|
|
369
|
-
b9s-admin machine add <name> --ssh <host> [--rotate] [--codex-userns] [--bwrap-userns] install Node and b9s (no sudo), linger, harness login checks,
|
|
372
|
+
b9s-admin machine add <name> --ssh <host> [--rotate] [--codex-userns] [--bwrap-userns] [--agy-userns] install Node and b9s (no sudo), linger, harness login checks,
|
|
370
373
|
on macOS also check selected Xcode/license/SDKs, actual simulator runtimes, and disk;
|
|
371
374
|
b9s's Codex hooks in /etc/codex (passwordless sudo only), register, start the daemon;
|
|
372
375
|
--codex-userns: where Linux restricts user namespaces (Ubuntu 24.04+), install a
|
|
373
376
|
Codex-only AppArmor profile so sandboxed agents can run; --bwrap-userns: the same
|
|
374
|
-
for /usr/bin/bwrap (Claude Code's sandbox; broader: any local user may use it)
|
|
377
|
+
for /usr/bin/bwrap (Claude Code's sandbox; broader: any local user may use it); --agy-userns:
|
|
378
|
+
install a profile only for the resolved ~/.local/bin/agy (Antigravity terminal sandbox)
|
|
375
379
|
b9s-admin machine list | show <name> | remove <name> [--preview] [--confirm <name> --impact-revision <revision>]
|
|
376
380
|
show includes host readiness, configured disk floors and named readiness refusals; removal previews sessions, work, keys, recovery blockers and replanned slots
|
|
377
381
|
the API requires a fresh revision for removal
|
|
@@ -418,8 +422,9 @@ Project devcontainer images & immutable registry builds (console controls in WU
|
|
|
418
422
|
b9s-admin project image validate --file <.devcontainer/devcontainer.json> [--dockerfile Dockerfile] [--arch linux/amd64|linux/arm64] validate @sha256 pins and reject secrets/host mounts/--privileged
|
|
419
423
|
b9s-admin project image config <project> [--path <path>] [--arch linux/amd64|linux/arm64] [--cache name,...] configure immutable per-account image registry & build cache allowlist
|
|
420
424
|
b9s-admin project image show <project> active digest, rollback target, latest build, and image capability probes
|
|
421
|
-
b9s-admin project image build <project> --commit <sha> --file <.devcontainer/devcontainer.json> [--dockerfile Dockerfile] [--arch <arch>]
|
|
422
|
-
b9s-admin project image
|
|
425
|
+
b9s-admin project image build <project> --commit <sha> --file <.devcontainer/devcontainer.json> [--dockerfile Dockerfile] [--arch <arch>] build only the reviewed declaration commit; machine validation runs its image probes and project test before ready
|
|
426
|
+
b9s-admin project image activate <project> <sha256:...> explicitly select a ready candidate for future or restarted sessions
|
|
427
|
+
b9s-admin project image rollback <project> (<sha256:...> | clear) select a prior ready digest or clear the active image selection without mutating tags
|
|
423
428
|
|
|
424
429
|
Pools (a role, variants and a count; the server names the agents and places them on machines)
|
|
425
430
|
b9s-admin project repo <project> <git url | none> what machines clone for the project's pool sessions
|
package/dist/usage.js
CHANGED
|
@@ -17,6 +17,27 @@ function lines(path) {
|
|
|
17
17
|
}
|
|
18
18
|
});
|
|
19
19
|
}
|
|
20
|
+
/** Earliest timestamp actually present in this session's supported metadata. */
|
|
21
|
+
export function sessionStart(session) {
|
|
22
|
+
if (!session)
|
|
23
|
+
return null;
|
|
24
|
+
const transcript = session.harness === "claude-code" && session.session_id
|
|
25
|
+
? (session.transcript && existsSync(session.transcript) ? session.transcript : claudeTranscript(session.session_id) ?? session.transcript)
|
|
26
|
+
: session.transcript;
|
|
27
|
+
if (!transcript || !existsSync(transcript))
|
|
28
|
+
return null;
|
|
29
|
+
let earliest = Infinity;
|
|
30
|
+
for (const row of lines(transcript)) {
|
|
31
|
+
const raw = session.harness === "dsh" ? (row.type === "b9s_invocation_start" ? row.at : null)
|
|
32
|
+
: session.harness === "antigravity" ? row.started_at : row.timestamp;
|
|
33
|
+
if (typeof raw === "string") {
|
|
34
|
+
const at = Date.parse(raw);
|
|
35
|
+
if (Number.isFinite(at))
|
|
36
|
+
earliest = Math.min(earliest, at);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return Number.isFinite(earliest) ? new Date(earliest).toISOString() : null;
|
|
40
|
+
}
|
|
20
41
|
const unknownContext = (reason) => ({ pct: null, tokens: null, window: null, source: "unknown", measured_at: null, reason });
|
|
21
42
|
const unknownCompactions = (reason) => ({ count: null, reason });
|
|
22
43
|
const positiveInt = (n) => typeof n === "number" && Number.isSafeInteger(n) && n > 0;
|
package/dist/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const CLI_VERSION = "0.12.
|
|
1
|
+
export const CLI_VERSION = "0.12.104";
|