benignswarm 0.12.103 → 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.
@@ -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
  }
@@ -1,6 +1,6 @@
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";
@@ -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 = (image?.rollback_digest ?? image?.active_digest)?.trim() ?? "";
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
- opts.log(`${project.name}: built project image ${imageRef}@${imageDigest}`);
329
- results.push({ project_id: project.id, build_id: build.id, status: "ready", image_digest: imageDigest });
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 });
@@ -1047,14 +1219,15 @@ async function ensureCredentials(client, m, s, local, log) {
1047
1219
  }
1048
1220
  export function errorText(s) {
1049
1221
  const last = s.trim().split("\n").pop() ?? "";
1222
+ const redact = sanitizeBuildDiagnosticText;
1050
1223
  try {
1051
1224
  const parsed = JSON.parse(last);
1052
1225
  if (parsed.error === "directory_conflict")
1053
- return "directory_conflict: " + (parsed.message ?? last) + (parsed.hint ? "; " + parsed.hint : "");
1054
- 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);
1055
1228
  }
1056
1229
  catch {
1057
- return last.slice(0, 500);
1230
+ return redact(last).slice(0, 500);
1058
1231
  }
1059
1232
  }
1060
1233
  /** Whether the session has a turn running, its process, and a usage-limit pause still in force. */
@@ -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
- return telemetryFromEvents(name, events);
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's timeline: ${e.message}`;
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/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,10 +217,11 @@ 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. Judgment capture has a separate default-off activation in console WU #238.
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 policy changes. All three are paged and account-scoped.
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
@@ -420,8 +422,9 @@ Project devcontainer images & immutable registry builds (console controls in WU
420
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
421
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
422
424
  b9s-admin project image show <project> active digest, rollback target, latest build, and image capability probes
423
- b9s-admin project image build <project> --commit <sha> --file <.devcontainer/devcontainer.json> [--dockerfile Dockerfile] [--arch <arch>] validate recipe and record immutable build request
424
- b9s-admin project image rollback <project> (<sha256:...> | clear) select a previously ready digest in the same account/project without mutating tags
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
425
428
 
426
429
  Pools (a role, variants and a count; the server names the agents and places them on machines)
427
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.103";
1
+ export const CLI_VERSION = "0.12.104";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.103",
3
+ "version": "0.12.104",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {