benignswarm 0.12.96 → 0.12.97

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.
@@ -1,8 +1,8 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
- import { createHash } from "node:crypto";
3
- import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, rmSync, statSync, statfsSync, writeFileSync } from "node:fs";
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";
4
4
  import { arch, cpus, freemem, homedir, hostname, loadavg, platform, tmpdir, totalmem, userInfo } from "node:os";
5
- import { dirname, join } from "node:path";
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, saveAgent } from "../config.js";
@@ -21,7 +21,10 @@ import { busyTurnPause, DEFAULT_TURNS_PER_HOUR, DEFAULT_UNPRODUCTIVE_PER_HOUR, r
21
21
  import { defaultWorkspaceWritableRoots } from "../start-options.js";
22
22
  import { antigravityTurnArgs, parseAntigravityJson } from "../antigravity.js";
23
23
  import { bootTimeMs } from "../boot-time.js";
24
- import { manageBuildCaches } from "../build-caches.js";
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";
26
+ import { machineEnvironmentChecks } from "../environment-checks.js";
27
+ import { macReadiness, macReadinessSteps } from "../macos-readiness.js";
25
28
  export const machineFile = () => join(configRoot(), "machine.json");
26
29
  export function loadMachine() {
27
30
  const f = machineFile();
@@ -42,7 +45,7 @@ function writeMachineState(s) {
42
45
  * 3: turns get TMPDIR beside the checkout instead of the system's /tmp.
43
46
  */
44
47
  const START_REV = 6;
45
- export const sessionFingerprint = (s, writable = []) => JSON.stringify([s.harness, ...(s.provider && s.provider !== "anthropic" ? [s.provider] : []), s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR, s.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR, s.thread, ...(writable.length ? [writable] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
48
+ export const sessionFingerprint = (s, writable = [], imageDigest = null) => JSON.stringify([s.harness, ...(s.provider && s.provider !== "anthropic" ? [s.provider] : []), s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR, s.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR, s.turn_coalesce_seconds ?? 180, s.thread, ...(writable.length ? [writable] : []), ...(imageDigest ? [imageDigest] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
46
49
  /** A clear is distinct from a thread that the server has not received from the machine yet. */
47
50
  export function reconcileThread(s, local) {
48
51
  const clearing = s.thread === null && !!s.thread_override_at && s.thread_override_at !== local?.thread_override_at;
@@ -66,7 +69,7 @@ export function maintenanceReport(drain, sessions) {
66
69
  /** The `b9s start` arguments that bring a session up (adopting its thread or session when known). */
67
70
  export function startArgs(s, thread, writable = []) {
68
71
  return [
69
- "start", "--harness", s.harness, "--as", s.agent, "--sandbox", s.sandbox, "--turn-timeout", String(s.turn_timeout), "--turns-per-hour", String(s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR), "--unproductive-per-hour", String(s.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR), "--json",
72
+ "start", "--harness", s.harness, "--as", s.agent, "--sandbox", s.sandbox, "--turn-timeout", String(s.turn_timeout), "--turns-per-hour", String(s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR), "--unproductive-per-hour", String(s.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR), "--turn-coalesce-seconds", String(s.turn_coalesce_seconds ?? 180), "--json",
70
73
  ...((s.provider ?? "anthropic") === "deepseek" ? ["--provider", "deepseek"] : []),
71
74
  ...(s.model ? ["--model", s.model] : []),
72
75
  ...(s.effort ? ["--effort", s.effort] : []),
@@ -80,11 +83,426 @@ const lastCapabilityProbe = new Map();
80
83
  export function turnFaultSessionFields(fault) {
81
84
  return { turn_fault_at: new Date(fault.at).toISOString() };
82
85
  }
86
+ const syncRunner = (cmd, args, opts) => spawnSync(cmd, args, { encoding: "utf8", timeout: opts?.timeout ?? 180_000, cwd: opts?.cwd, env: opts?.env });
87
+ export function resolvePinnedImageRef(image) {
88
+ const raw = (image?.rollback_digest ?? image?.active_digest)?.trim() ?? "";
89
+ if (!raw || /:latest\b/i.test(raw))
90
+ return null;
91
+ const normalized = raw.includes("@sha256:") ? raw : `${image?.registry_namespace ?? ""}@${raw}`;
92
+ return /^[a-z0-9][a-z0-9._/-]*@sha256:[a-f0-9]{64}$/i.test(normalized) ? normalized : null;
93
+ }
94
+ function assertConfinedSnapshotPath(snapshotRealRoot, rawPath, label) {
95
+ if (!existsSync(rawPath))
96
+ throw new Error(`${label} does not exist inside isolated commit snapshot`);
97
+ const targetReal = realpathSync(rawPath);
98
+ const rel = relative(snapshotRealRoot, targetReal);
99
+ if (rel.startsWith("..") || isAbsolute(rel)) {
100
+ throw new Error(`${label} escapes isolated commit snapshot (${rawPath})`);
101
+ }
102
+ return targetReal;
103
+ }
104
+ const LOCKFILE_CANDIDATES = ["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "Cargo.lock", "poetry.lock", "uv.lock"];
105
+ /**
106
+ * Materializes an isolated read-only-intent git worktree at `build.source_commit` (never reading
107
+ * mutable `<workdir>/<project>/main`), verifies `HEAD`, clean tree, `target_arch`, `recipe_hash`,
108
+ * and `base_image_digest`, and builds via `isolatedBuildCommand` without host secrets.
109
+ */
110
+ export async function reconcilePendingImageBuilds(client, projects, opts) {
111
+ const runner = opts.runner ?? syncRunner;
112
+ const results = [];
113
+ for (const project of projects) {
114
+ const img = project.image;
115
+ const build = img?.latest_build;
116
+ if (!img || !build || build.status !== "pending")
117
+ continue;
118
+ const nested = (opts.probeSandbox ?? probeNestedSandbox)({ runner });
119
+ if (!nested.runtime) {
120
+ if (process.env.B9S_CONTAINER_AGENTS === "1") {
121
+ const error = `cannot build image ${build.id} for ${project.name}: no container runtime available`;
122
+ await client.call("POST", `/machines/me/image-builds/${build.id}`, { status: "failed", error }).catch(() => { });
123
+ results.push({ project_id: project.id, build_id: build.id, status: "failed", error });
124
+ }
125
+ else {
126
+ results.push({ project_id: project.id, build_id: build.id, status: "skipped" });
127
+ }
128
+ continue;
129
+ }
130
+ const baseDir = join(opts.workdir ?? join(homedir(), "bschat"), project.name, "main");
131
+ const buildTmpRoot = mkdtempSync(join(tmpdir(), "b9s-build-"));
132
+ const buildHome = join(buildTmpRoot, "home");
133
+ const snapshotDir = join(buildTmpRoot, "snapshot");
134
+ mkdirSync(buildHome, { recursive: true, mode: 0o700 });
135
+ let snapshotCreated = false;
136
+ try {
137
+ await client.call("POST", `/machines/me/image-builds/${build.id}`, { status: "building" });
138
+ const requestedCommit = (build.source_commit ?? "").trim().toLowerCase();
139
+ if (!/^[0-9a-f]{7,64}$/.test(requestedCommit)) {
140
+ throw new Error(`invalid build source_commit: ${JSON.stringify(build.source_commit)}`);
141
+ }
142
+ if (!/^[a-f0-9]{64}$/i.test(build.recipe_hash ?? "")) {
143
+ throw new Error(`recorded build ${build.id} is missing a 64-hex recipe_hash`);
144
+ }
145
+ if (!["linux/amd64", "linux/arm64"].includes(build.target_arch)) {
146
+ throw new Error(`unsupported build target_arch: ${build.target_arch}`);
147
+ }
148
+ if (img.target_arch && build.target_arch !== img.target_arch) {
149
+ throw new Error(`target_arch mismatch: build=${build.target_arch} project=${img.target_arch}`);
150
+ }
151
+ const env = isolatedSubprocessEnv(process.env, { HOME: buildHome });
152
+ const gitCheck = runner("git", ["-C", baseDir, "rev-parse", "--git-dir"], { env, timeout: 15_000 });
153
+ if (gitCheck.status !== 0) {
154
+ throw new Error(`project ${project.name} checkout ${baseDir} is not a git repository; cannot isolate ${requestedCommit}`);
155
+ }
156
+ let hasCommit = runner("git", ["-C", baseDir, "cat-file", "-e", `${requestedCommit}^{commit}`], { env, timeout: 15_000 });
157
+ if (hasCommit.status !== 0 && project.repo_url) {
158
+ runner("git", ["-C", baseDir, "fetch", "--no-tags", "origin", requestedCommit], { env, timeout: 120_000 });
159
+ hasCommit = runner("git", ["-C", baseDir, "cat-file", "-e", `${requestedCommit}^{commit}`], { env, timeout: 15_000 });
160
+ }
161
+ if (hasCommit.status !== 0) {
162
+ throw new Error(`source_commit ${requestedCommit} is not present in ${baseDir}`);
163
+ }
164
+ const rev = runner("git", ["-C", baseDir, "rev-parse", "--verify", `${requestedCommit}^{commit}`], { env, timeout: 15_000 });
165
+ const resolvedCommit = (rev.stdout ?? "").trim().toLowerCase();
166
+ if (rev.status !== 0 || !/^[0-9a-f]{40,64}$/.test(resolvedCommit) || !resolvedCommit.startsWith(requestedCommit)) {
167
+ throw new Error(`source_commit ${requestedCommit} did not resolve deterministically`);
168
+ }
169
+ const wt = runner("git", ["-C", baseDir, "worktree", "add", "--detach", snapshotDir, resolvedCommit], { env, timeout: 60_000 });
170
+ if (wt.status !== 0) {
171
+ throw new Error(`failed to materialize isolated snapshot at ${resolvedCommit}: ${errorText(wt.stderr || wt.stdout)}`);
172
+ }
173
+ snapshotCreated = true;
174
+ const snapHead = runner("git", ["-C", snapshotDir, "rev-parse", "HEAD"], { env, timeout: 15_000 });
175
+ if (snapHead.status !== 0 || (snapHead.stdout ?? "").trim().toLowerCase() !== resolvedCommit) {
176
+ throw new Error(`isolated snapshot HEAD mismatch (expected ${resolvedCommit})`);
177
+ }
178
+ const snapDirty = runner("git", ["-C", snapshotDir, "status", "--porcelain", "--untracked-files=all"], { env, timeout: 15_000 });
179
+ if (snapDirty.status !== 0 || (snapDirty.stdout ?? "").trim() !== "") {
180
+ throw new Error(`isolated snapshot at ${resolvedCommit} is not clean`);
181
+ }
182
+ const snapshotRealRoot = realpathSync(snapshotDir);
183
+ const relDcPath = build.devcontainer_path || img.devcontainer_path || ".devcontainer/devcontainer.json";
184
+ if (relDcPath.startsWith("/") || relDcPath.split("/").includes("..")) {
185
+ throw new Error(`unsafe devcontainer_path: ${relDcPath}`);
186
+ }
187
+ const devcontainerReal = assertConfinedSnapshotPath(snapshotRealRoot, resolve(snapshotRealRoot, relDcPath), "devcontainer_path");
188
+ const dcDir = dirname(devcontainerReal);
189
+ const dcJson = JSON.parse(readFileSync(devcontainerReal, "utf8"));
190
+ const buildSection = dcJson.build && typeof dcJson.build === "object" && !Array.isArray(dcJson.build)
191
+ ? dcJson.build
192
+ : null;
193
+ const dockerfileReal = buildSection
194
+ ? assertConfinedSnapshotPath(snapshotRealRoot, resolve(dcDir, typeof buildSection.dockerfile === "string" ? buildSection.dockerfile : "Dockerfile"), "build.dockerfile")
195
+ : null;
196
+ const dockerfileContent = dockerfileReal ? readFileSync(dockerfileReal, "utf8") : null;
197
+ const expectedRecipe = build.recipe_hash.toLowerCase();
198
+ let matchedSpec = validateDevcontainerSpec(dcJson, { dockerfileContent, targetArch: build.target_arch, lockfileContent: null });
199
+ if (!matchedSpec.ok)
200
+ throw new Error(matchedSpec.error ?? "invalid devcontainer spec");
201
+ if (matchedSpec.recipe_hash !== expectedRecipe) {
202
+ let matched = false;
203
+ for (const candidate of LOCKFILE_CANDIDATES) {
204
+ const candPath = resolve(snapshotRealRoot, candidate);
205
+ if (!existsSync(candPath))
206
+ continue;
207
+ const candReal = assertConfinedSnapshotPath(snapshotRealRoot, candPath, candidate);
208
+ const candidateSpec = validateDevcontainerSpec(dcJson, {
209
+ dockerfileContent,
210
+ targetArch: build.target_arch,
211
+ lockfileContent: readFileSync(candReal, "utf8"),
212
+ });
213
+ if (candidateSpec.ok && candidateSpec.recipe_hash === expectedRecipe) {
214
+ matchedSpec = candidateSpec;
215
+ matched = true;
216
+ break;
217
+ }
218
+ }
219
+ if (!matched) {
220
+ throw new Error(`recipe_hash mismatch: expected ${expectedRecipe}, commit ${resolvedCommit} produced ${matchedSpec.recipe_hash}`);
221
+ }
222
+ }
223
+ if (build.base_image_digest && matchedSpec.base_image_digest !== build.base_image_digest.toLowerCase()) {
224
+ throw new Error(`base_image_digest mismatch: expected ${build.base_image_digest}, got ${matchedSpec.base_image_digest}`);
225
+ }
226
+ const refPrefix = {
227
+ runtime: nested.runtime,
228
+ accountId: opts.accountId,
229
+ projectId: project.id,
230
+ arch: build.target_arch,
231
+ registryNamespace: img.registry_namespace,
232
+ sourceCommit: resolvedCommit,
233
+ };
234
+ const declaredFeatures = matchedSpec.features ?? [];
235
+ let imageRef;
236
+ if (declaredFeatures.length > 0) {
237
+ const dcCheck = runner("devcontainer", ["--version"], { env, timeout: 10_000 });
238
+ if (dcCheck.status !== 0) {
239
+ throw new Error(`devcontainer CLI is required to build devcontainer with features (${declaredFeatures.join(", ")}); refusing bare ${nested.runtime} build that would omit declared features`);
240
+ }
241
+ const dcBuildSpec = isolatedDevcontainerBuildCommand({
242
+ ...refPrefix,
243
+ workspaceFolder: snapshotRealRoot,
244
+ configPath: devcontainerReal,
245
+ });
246
+ imageRef = dcBuildSpec.imageRef;
247
+ const b = runner(dcBuildSpec.cmd, dcBuildSpec.args, { cwd: snapshotRealRoot, env, timeout: 600_000 });
248
+ if (b.status !== 0) {
249
+ throw new Error(`devcontainer build failed: ${errorText(b.stderr || b.stdout)}`);
250
+ }
251
+ }
252
+ else if (dockerfileReal) {
253
+ const rawCtx = typeof buildSection?.context === "string"
254
+ ? resolve(dcDir, buildSection.context)
255
+ : snapshotRealRoot;
256
+ const contextReal = assertConfinedSnapshotPath(snapshotRealRoot, rawCtx, "build.context");
257
+ const buildSpec = isolatedBuildCommand({
258
+ ...refPrefix,
259
+ dockerfilePath: dockerfileReal,
260
+ contextDir: contextReal,
261
+ });
262
+ imageRef = buildSpec.imageRef;
263
+ const b = runner(buildSpec.cmd, buildSpec.args, { cwd: snapshotRealRoot, env, timeout: 600_000 });
264
+ if (b.status !== 0) {
265
+ throw new Error(`image build failed: ${errorText(b.stderr || b.stdout)}`);
266
+ }
267
+ }
268
+ else if (typeof dcJson.image === "string") {
269
+ const sourceImage = dcJson.image.trim();
270
+ const pullSpec = isolatedImagePullCommands({ ...refPrefix, sourceImage });
271
+ imageRef = pullSpec.imageRef;
272
+ const p = runner(pullSpec.cmd, pullSpec.pullArgs, { cwd: snapshotRealRoot, env, timeout: 600_000 });
273
+ if (p.status !== 0) {
274
+ throw new Error(`image pull failed: ${errorText(p.stderr || p.stdout)}`);
275
+ }
276
+ const pulledInsp = runner(nested.runtime, ["image", "inspect", sourceImage, "--format", "{{.Digest}}"], { env, timeout: 30_000 });
277
+ const pulledDigestMatch = /(sha256:[a-f0-9]{64})/i.exec((pulledInsp.stdout ?? "").trim());
278
+ if (pulledInsp.status !== 0 || !pulledDigestMatch) {
279
+ throw new Error(`pulled image ${sourceImage} did not yield an immutable @sha256 digest`);
280
+ }
281
+ if (matchedSpec.base_image_digest && pulledDigestMatch[1].toLowerCase() !== matchedSpec.base_image_digest.toLowerCase()) {
282
+ throw new Error(`pulled image digest mismatch: expected ${matchedSpec.base_image_digest}, got ${pulledDigestMatch[1].toLowerCase()}`);
283
+ }
284
+ const t = runner(pullSpec.cmd, pullSpec.tagArgs, { cwd: snapshotRealRoot, env, timeout: 30_000 });
285
+ if (t.status !== 0) {
286
+ throw new Error(`image tag failed: ${errorText(t.stderr || t.stdout)}`);
287
+ }
288
+ }
289
+ else {
290
+ throw new Error("devcontainer must specify a digest-pinned image or build.dockerfile");
291
+ }
292
+ const insp = runner(nested.runtime, ["image", "inspect", imageRef, "--format", "{{.Digest}}"], { env, timeout: 30_000 });
293
+ const rawDigest = (insp.stdout ?? "").trim();
294
+ const digestMatch = /(sha256:[a-f0-9]{64})/i.exec(rawDigest);
295
+ if (insp.status !== 0 || !digestMatch) {
296
+ throw new Error(`built image ${imageRef} did not yield an immutable @sha256 digest`);
297
+ }
298
+ const imageDigest = digestMatch[1].toLowerCase();
299
+ await client.call("POST", `/machines/me/image-builds/${build.id}`, {
300
+ status: "ready",
301
+ image_digest: imageDigest,
302
+ tool_versions: {
303
+ source_commit: resolvedCommit,
304
+ recipe_hash: matchedSpec.recipe_hash,
305
+ target_arch: build.target_arch,
306
+ base_image_digest: matchedSpec.base_image_digest ?? null,
307
+ ...(declaredFeatures.length ? { features: declaredFeatures.join(",") } : {}),
308
+ },
309
+ });
310
+ opts.log(`${project.name}: built project image ${imageRef}@${imageDigest}`);
311
+ results.push({ project_id: project.id, build_id: build.id, status: "ready", image_digest: imageDigest });
312
+ }
313
+ catch (e) {
314
+ const error = e.message.slice(0, 500);
315
+ await client.call("POST", `/machines/me/image-builds/${build.id}`, { status: "failed", error }).catch(() => { });
316
+ opts.log(`${project.name}: image build failed: ${error}`);
317
+ results.push({ project_id: project.id, build_id: build.id, status: "failed", error });
318
+ }
319
+ finally {
320
+ if (snapshotCreated) {
321
+ runner("git", ["-C", baseDir, "worktree", "remove", "--force", snapshotDir], { timeout: 15_000 });
322
+ runner("git", ["-C", baseDir, "worktree", "prune"], { timeout: 15_000 });
323
+ }
324
+ rmSync(buildTmpRoot, { recursive: true, force: true });
325
+ }
326
+ }
327
+ return results;
328
+ }
329
+ export function resolveContainerLaunchPrereqs(opts) {
330
+ const nested = (opts.probeSandbox ?? probeNestedSandbox)({ runner: opts.runner });
331
+ if (!nested.runtime) {
332
+ throw new Error("container isolation required but neither podman nor docker is available; refusing unisolated host fallback");
333
+ }
334
+ if (opts.s.sandbox !== "danger-full-access" && !nested.nested_sandbox_ok) {
335
+ throw new Error(`refusing sandboxed container session (${opts.s.sandbox}) without silently falling back to danger-full-access: ${nested.detail}`);
336
+ }
337
+ const imageDigest = resolvePinnedImageRef(opts.project?.image);
338
+ if (!imageDigest) {
339
+ throw new Error(`container session for ${opts.s.agent} has no ready pinned @sha256 project image digest; refusing unisolated host fallback`);
340
+ }
341
+ return { runtime: nested.runtime, imageDigest };
342
+ }
343
+ export function agentHomeDirOf(s) {
344
+ return join(configRoot(), "agent-homes", s.project ?? "account", s.agent_name);
345
+ }
346
+ export function isContainerRunning(runtime, containerName, runner = syncRunner) {
347
+ const res = runner(runtime, ["inspect", "-f", "{{.State.Running}}", containerName], {
348
+ timeout: 10_000,
349
+ env: isolatedSubprocessEnv(process.env),
350
+ });
351
+ return res.status === 0 && res.stdout.trim() === "true";
352
+ }
353
+ export function removeAgentContainer(runtime, containerName, runner = syncRunner) {
354
+ return runner(runtime, ["rm", "-f", containerName], {
355
+ timeout: 30_000,
356
+ env: isolatedSubprocessEnv(process.env),
357
+ });
358
+ }
359
+ function readContainerError(logsDir, agentRef) {
360
+ const exact = join(logsDir, `container-error.${agentRef.replace("/", ".")}.json`);
361
+ const candidates = existsSync(exact)
362
+ ? [exact]
363
+ : (existsSync(logsDir)
364
+ ? readdirSync(logsDir).filter((f) => f.startsWith("container-error.") && f.endsWith(".json")).map((f) => join(logsDir, f))
365
+ : []);
366
+ for (const file of candidates) {
367
+ try {
368
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
369
+ if (typeof parsed.error === "string" && parsed.error.trim()) {
370
+ return { error: parsed.error, ...(typeof parsed.code === "string" ? { code: parsed.code } : {}) };
371
+ }
372
+ }
373
+ catch {
374
+ // ignore partial or invalid file
375
+ }
376
+ }
377
+ return null;
378
+ }
379
+ function readContainerStart(logsDir, agentRef) {
380
+ const exact = join(logsDir, `container-start.${agentRef.replace("/", ".")}.json`);
381
+ const candidates = existsSync(exact)
382
+ ? [exact]
383
+ : (existsSync(logsDir)
384
+ ? readdirSync(logsDir).filter((f) => f.startsWith("container-start.") && f.endsWith(".json")).map((f) => join(logsDir, f))
385
+ : []);
386
+ for (const file of candidates) {
387
+ try {
388
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
389
+ if (typeof parsed.thread === "string" && parsed.thread.trim()) {
390
+ return parsed;
391
+ }
392
+ }
393
+ catch {
394
+ // ignore partial or invalid file
395
+ }
396
+ }
397
+ return null;
398
+ }
399
+ /**
400
+ * Launches a desired session either inside an isolated per-agent container (using
401
+ * `agentContainerRunArgs` + pinned `@sha256:` project image + fail-closed nested sandbox check
402
+ * + `--in-container` detached watcher supervision) or directly on the host when container
403
+ * isolation is not active for owned local machines.
404
+ */
405
+ export async function launchDesiredSession(opts) {
406
+ const runner = opts.runner ?? syncRunner;
407
+ if (!opts.containerMode) {
408
+ return runner(opts.bin, startArgs(opts.s, opts.thread, opts.sessionWritable), {
409
+ cwd: opts.s.dir,
410
+ timeout: 180_000,
411
+ env: { ...process.env, ...opts.secretEnv },
412
+ });
413
+ }
414
+ const { runtime, imageDigest } = resolveContainerLaunchPrereqs({
415
+ s: opts.s,
416
+ project: opts.project,
417
+ runner,
418
+ probeSandbox: opts.probeSandbox,
419
+ });
420
+ const agentHomeDir = agentHomeDirOf(opts.s);
421
+ const isolatedB9sDir = join(agentHomeDir, ".b9s");
422
+ const logsDir = join(isolatedB9sDir, "logs");
423
+ mkdirSync(logsDir, { recursive: true, mode: 0o700 });
424
+ chmodSync(agentHomeDir, 0o700);
425
+ for (const existing of readdirSync(logsDir)) {
426
+ if ((existing.startsWith("container-start.") || existing.startsWith("container-watcher.") || existing.startsWith("container-error."))
427
+ && existing.endsWith(".json")) {
428
+ rmSync(join(logsDir, existing), { force: true });
429
+ }
430
+ }
431
+ try {
432
+ const agentCreds = loadAgent(opts.s.agent);
433
+ saveAgent(agentCreds, { ...process.env, B9S_HOME: isolatedB9sDir, BSCHAT_HOME: isolatedB9sDir });
434
+ }
435
+ catch {
436
+ // Allow sessions with injected runtime credentials when no per-agent file exists on host yet.
437
+ }
438
+ const containerName = agentContainerName(opts.accountId, opts.s.project ?? "account", opts.s.agent_name);
439
+ removeAgentContainer(runtime, containerName, runner);
440
+ const runArgs = agentContainerRunArgs({
441
+ runtime,
442
+ accountSlug: opts.accountId,
443
+ project: opts.s.project ?? "account",
444
+ agent: opts.s.agent_name,
445
+ imageDigest,
446
+ worktreeDir: opts.s.dir,
447
+ agentHomeDir,
448
+ allowedCaches: opts.project?.image?.allowed_caches ?? [],
449
+ cacheRootDir: join(opts.workdir ?? join(homedir(), "bschat"), ".caches", opts.accountId),
450
+ detach: true,
451
+ extraEnv: {
452
+ ...opts.secretEnv,
453
+ B9S_URL: opts.m.url,
454
+ B9S_AGENT: opts.s.agent,
455
+ B9S_HOME: "/home/agent/.b9s",
456
+ },
457
+ command: ["b9s", ...startArgs(opts.s, opts.thread, opts.s.sandbox === "workspace-write" ? ["/workspace"] : []), "--in-container"],
458
+ });
459
+ const launchRes = runner(runtime, runArgs, {
460
+ cwd: opts.s.dir,
461
+ timeout: 60_000,
462
+ env: isolatedSubprocessEnv(process.env),
463
+ });
464
+ if (launchRes.status !== 0)
465
+ return launchRes;
466
+ const deadline = Date.now() + (Number(process.env.B9S_CONTAINER_START_TIMEOUT_MS) || 120_000);
467
+ while (Date.now() < deadline) {
468
+ const err = readContainerError(logsDir, opts.s.agent);
469
+ if (err) {
470
+ removeAgentContainer(runtime, containerName, runner);
471
+ return { status: 1, stdout: "", stderr: err.error };
472
+ }
473
+ const started = readContainerStart(logsDir, opts.s.agent);
474
+ if (started) {
475
+ if (!isContainerRunning(runtime, containerName, runner)) {
476
+ await new Promise((r) => setTimeout(r, 50));
477
+ const lateErr = readContainerError(logsDir, opts.s.agent);
478
+ return { status: 1, stdout: "", stderr: lateErr?.error ?? `container ${containerName} exited immediately after reporting start` };
479
+ }
480
+ return { status: 0, stdout: JSON.stringify(started), stderr: "" };
481
+ }
482
+ if (!isContainerRunning(runtime, containerName, runner)) {
483
+ await new Promise((r) => setTimeout(r, 50));
484
+ const lateErr = readContainerError(logsDir, opts.s.agent);
485
+ const lateStart = readContainerStart(logsDir, opts.s.agent);
486
+ if (lateErr)
487
+ return { status: 1, stdout: "", stderr: lateErr.error };
488
+ if (lateStart) {
489
+ return { status: 1, stdout: "", stderr: `container ${containerName} exited right after reporting b9s start` };
490
+ }
491
+ return { status: 1, stdout: "", stderr: `container ${containerName} exited before reporting b9s start` };
492
+ }
493
+ await new Promise((r) => setTimeout(r, 40));
494
+ }
495
+ removeAgentContainer(runtime, containerName, runner);
496
+ return { status: 1, stdout: "", stderr: `timed out waiting for in-container b9s start (${containerName})` };
497
+ }
83
498
  /** One pass: make what runs here match what the operator declared, then report. */
84
- export async function reconcile(m, log, reportIntervalSeconds = 30) {
499
+ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
85
500
  const client = Client.raw(m.url, m.key);
86
501
  const me = await client.call("GET", "/machines/me");
87
502
  const desired = me.sessions;
503
+ if (Array.isArray(me.device_logins)) {
504
+ handleDeviceLoginRequests(client, me.device_logins, log, deps?.deviceLoginInFlight ?? defaultDeviceLoginInFlight);
505
+ }
88
506
  const providerChecks = new Set(["anthropic"]);
89
507
  for (const provider of me.provider_checks ?? []) {
90
508
  if (provider === "anthropic" || provider === "deepseek")
@@ -94,34 +512,47 @@ export async function reconcile(m, log, reportIntervalSeconds = 30) {
94
512
  if (s.harness === "claude-code" && (s.provider === "anthropic" || s.provider === "deepseek"))
95
513
  providerChecks.add(s.provider);
96
514
  const projects = me.projects ?? [];
515
+ const accountId = me.machine?.account_id ?? me.account_id ?? "acct";
97
516
  const workdir = me.machine?.workdir ?? null;
98
517
  const writable = me.machine?.writable ?? [];
99
518
  // The maintenance window, for the watchers: they start no new turns while it drains or runs.
100
519
  const mw = me.machine?.maintenance;
101
520
  writeMaintenance(mw ? { start: mw.start, end: mw.end } : null);
521
+ await reconcilePendingImageBuilds(client, projects, { accountId, workdir, log, runner: deps?.runner, probeSandbox: deps?.probeSandbox });
102
522
  const state = readMachineState();
103
- const bin = requireInstall().bin;
523
+ const bin = deps?.bin ?? requireInstall().bin;
524
+ const runner = deps?.runner ?? syncRunner;
104
525
  const out = [];
105
526
  for (const s of desired) {
106
527
  const label = watchLabelOf(s.agent);
107
528
  const svc = () => watcherServices().find((w) => w.label === label);
108
529
  try {
109
530
  if (s.desired === "benched") {
531
+ const local = state.sessions[s.id];
110
532
  const w = svc();
111
533
  const reason = `benched by ${s.benched_by ?? "the operator"}${s.benched_at ? ` at ${s.benched_at}` : ""}${s.bench_note ? `: ${s.bench_note}` : ""}`;
112
534
  if (w) {
113
535
  removeService(w);
114
536
  log(`${s.agent}: ${reason}; watcher removed`);
115
537
  }
538
+ if (local?.container_name && local.container_runtime) {
539
+ removeAgentContainer(local.container_runtime, local.container_name, runner);
540
+ log(`${s.agent}: ${reason}; container ${local.container_name} removed`);
541
+ }
116
542
  out.push({ id: s.id, state: "benched", thread: state.sessions[s.id]?.thread ?? s.thread, detail: reason });
117
543
  continue;
118
544
  }
119
545
  if (s.desired === "stopped") {
546
+ const local = state.sessions[s.id];
120
547
  const w = svc();
121
548
  if (w) {
122
549
  removeService(w);
123
550
  log(`${s.agent}: stopped (watcher removed)`);
124
551
  }
552
+ if (local?.container_name && local.container_runtime) {
553
+ removeAgentContainer(local.container_runtime, local.container_name, runner);
554
+ log(`${s.agent}: stopped (container ${local.container_name} removed)`);
555
+ }
125
556
  delete state.sessions[s.id];
126
557
  out.push({ id: s.id, state: "stopped" });
127
558
  continue;
@@ -132,6 +563,16 @@ export async function reconcile(m, log, reportIntervalSeconds = 30) {
132
563
  throw new Error(`provider ${s.provider} is not supported by this b9s ${CLI_VERSION}`);
133
564
  if ((s.provider ?? "anthropic") === "deepseek" && s.harness !== "claude-code")
134
565
  throw new Error("provider deepseek requires harness claude-code");
566
+ const projectEntry = projects.find((p) => p.id === s.project_id || p.name === s.project);
567
+ const containerMode = Boolean(m.container_agents) || process.env.B9S_CONTAINER_AGENTS === "1" || Boolean(projectEntry?.image);
568
+ const containerPrereqs = containerMode
569
+ ? resolveContainerLaunchPrereqs({ s, project: projectEntry, runner, probeSandbox: deps?.probeSandbox })
570
+ : null;
571
+ const pinnedImageRef = containerPrereqs?.imageDigest ?? null;
572
+ const containerName = containerMode ? agentContainerName(accountId, s.project ?? "account", s.agent_name) : null;
573
+ const agentStateEnv = containerMode
574
+ ? { ...process.env, B9S_HOME: join(agentHomeDirOf(s), ".b9s"), BSCHAT_HOME: join(agentHomeDirOf(s), ".b9s") }
575
+ : process.env;
135
576
  if (!s.dir) {
136
577
  // A pool session: the daemon makes the checkout (clone once per machine, a worktree per agent).
137
578
  const c = ensureCheckout(s, log, workdir);
@@ -144,10 +585,10 @@ export async function reconcile(m, log, reportIntervalSeconds = 30) {
144
585
  if (!existsSync(s.dir))
145
586
  throw new Error(`checkout ${s.dir} does not exist on this machine`);
146
587
  const local = state.sessions[s.id];
147
- let agentState = readState(s.agent);
588
+ let agentState = readState(s.agent, agentStateEnv);
148
589
  if (s.turn_resume_at && agentState.turn_resume_applied_at !== s.turn_resume_at) {
149
590
  agentState = { ...agentState, turn_guard: resumeTurnGuard(agentState.turn_guard), turn_resume_applied_at: s.turn_resume_at };
150
- writeState(s.agent, agentState);
591
+ writeState(s.agent, agentState, agentStateEnv);
151
592
  log(`${s.agent}: operator/assigner resumed turn mode`);
152
593
  }
153
594
  if (agentState.turn_guard?.fault) {
@@ -161,6 +602,10 @@ export async function reconcile(m, log, reportIntervalSeconds = 30) {
161
602
  removeService(w);
162
603
  log(`${s.agent}: turn mode fault; watcher service stopped`);
163
604
  }
605
+ if (containerMode && containerPrereqs && containerName) {
606
+ removeAgentContainer(containerPrereqs.runtime, containerName, runner);
607
+ log(`${s.agent}: turn mode fault; container ${containerName} removed`);
608
+ }
164
609
  out.push({ id: s.id, state: "error", dir: s.dir, thread: local?.thread ?? s.thread, watcher: "inactive", error, ...turnFaultSessionFields(fault) });
165
610
  continue;
166
611
  }
@@ -177,9 +622,20 @@ export async function reconcile(m, log, reportIntervalSeconds = 30) {
177
622
  ? [...new Set([...defaultWorkspaceWritableRoots(), ...writable])]
178
623
  : writable;
179
624
  const thread = reconcileThread(s, local);
180
- const fp = sessionFingerprint({ ...s, thread }, s.sandbox === "workspace-write" ? sessionWritable : []);
625
+ const fp = sessionFingerprint({ ...s, thread }, s.sandbox === "workspace-write" ? sessionWritable : [], pinnedImageRef);
181
626
  const threadChanged = !!local?.thread && !!s.thread && s.thread !== local.thread;
182
- if (!svc() || !local || local.fingerprint !== fp || threadChanged) {
627
+ const hostSvc = svc();
628
+ if (containerMode && hostSvc) {
629
+ removeService(hostSvc);
630
+ log(`${s.agent}: removed host watcher service before container supervision`);
631
+ }
632
+ const containerActive = containerMode && containerPrereqs && containerName
633
+ ? isContainerRunning(containerPrereqs.runtime, containerName, runner)
634
+ : false;
635
+ const needsLaunch = containerMode
636
+ ? (!local || local.fingerprint !== fp || threadChanged || !containerActive)
637
+ : (!hostSvc || !local || local.fingerprint !== fp || threadChanged);
638
+ if (needsLaunch) {
183
639
  // A new session's start runs its first turn at once, past the watchers' check: during a
184
640
  // maintenance window it waits. (Adopting a known thread starts no turn, so that proceeds.)
185
641
  // The phase is read at the launch decision itself: credential checks and checkouts before
@@ -189,43 +645,70 @@ export async function reconcile(m, log, reportIntervalSeconds = 30) {
189
645
  out.push(held);
190
646
  continue;
191
647
  }
192
- const r = spawnSync(bin, startArgs(s, thread, sessionWritable), { cwd: s.dir, encoding: "utf8", timeout: 180_000 });
648
+ const secretDelivery = resolveSessionSecretDelivery({
649
+ session: s,
650
+ secrets: me.harness_secrets ?? [],
651
+ targetDir: join(configRoot(), "providers", "ephemeral"),
652
+ });
653
+ let r;
654
+ try {
655
+ r = await launchDesiredSession({
656
+ m,
657
+ accountId,
658
+ s,
659
+ project: projectEntry,
660
+ thread,
661
+ sessionWritable,
662
+ bin,
663
+ secretEnv: secretDelivery.env,
664
+ containerMode,
665
+ workdir,
666
+ runner,
667
+ probeSandbox: deps?.probeSandbox,
668
+ });
669
+ }
670
+ finally {
671
+ secretDelivery.cleanup();
672
+ }
193
673
  if (r.status !== 0)
194
674
  throw new Error(`b9s start failed: ${errorText(r.stderr || r.stdout)}`);
195
675
  const started = JSON.parse(r.stdout);
196
676
  state.sessions[s.id] = {
197
677
  label,
198
- fingerprint: sessionFingerprint({ ...s, thread: started.thread }, s.sandbox === "workspace-write" ? sessionWritable : []),
678
+ fingerprint: sessionFingerprint({ ...s, thread: started.thread }, s.sandbox === "workspace-write" ? sessionWritable : [], pinnedImageRef),
199
679
  thread: started.thread,
200
680
  thread_override_at: s.thread_override_at ?? null,
201
681
  key_checked_at: state.sessions[s.id]?.key_checked_at ?? Date.now(),
682
+ ...(containerMode && containerPrereqs && containerName ? { container_name: containerName, container_runtime: containerPrereqs.runtime } : {}),
202
683
  };
203
684
  log(`${s.agent}: ${thread ? "adopted" : "started"} ${s.harness === "codex" ? "thread" : "session"} ${started.thread} in ${s.dir}`);
204
685
  }
205
- else {
206
- const w = svc();
207
- if (!serviceActive(w)) {
208
- if (!restartWatcher(w))
686
+ else if (!containerMode && hostSvc) {
687
+ if (!serviceActive(hostSvc)) {
688
+ if (!restartWatcher(hostSvc))
209
689
  throw new Error(`its watcher ${label} is not loaded and could not be restarted`);
210
690
  log(`${s.agent}: watcher was not running; restarted`);
211
691
  }
212
692
  }
213
- const w = svc();
693
+ const w = containerMode ? undefined : svc();
694
+ const watcherState = containerMode && containerPrereqs && containerName
695
+ ? (isContainerRunning(containerPrereqs.runtime, containerName, runner) ? "active" : "inactive")
696
+ : (w && serviceActive(w) ? "active" : "inactive");
214
697
  const th = state.sessions[s.id].thread;
215
698
  // A watcher that exits at every start (a corrupt state file after the disk filled) is
216
699
  // restarted by systemd forever and looked "running" here; report it as the error it is.
217
- const fault = watcherFault(s.agent);
700
+ const fault = containerMode ? null : watcherFault(s.agent);
218
701
  if (fault) {
219
- out.push({ id: s.id, state: "error", dir: s.dir, thread: th, watcher: w && serviceActive(w) ? "active" : "inactive", error: `its watcher keeps exiting: ${fault}` });
702
+ out.push({ id: s.id, state: "error", dir: s.dir, thread: th, watcher: watcherState, error: `its watcher keeps exiting: ${fault}` });
220
703
  continue;
221
704
  }
222
705
  // The operator lifted a usage-limit pause: what b9s codex unpause does, here.
223
706
  if (s.unpause_at && state.sessions[s.id].unpause_applied !== s.unpause_at) {
224
- writeState(s.agent, { ...readState(s.agent), turn_unpaused_at: Date.parse(s.unpause_at) });
707
+ writeState(s.agent, { ...readState(s.agent, agentStateEnv), turn_unpaused_at: Date.parse(s.unpause_at) }, agentStateEnv);
225
708
  state.sessions[s.id].unpause_applied = s.unpause_at;
226
709
  log(`${s.agent}: usage-limit pause lifted by the operator`);
227
710
  }
228
- out.push({ id: s.id, state: "running", dir: s.dir, thread: th, watcher: w && serviceActive(w) ? "active" : "inactive", last_turn: lastTurnLine(s.agent), ...turnFacts(s.agent, s.harness, th, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR) });
711
+ out.push({ id: s.id, state: "running", dir: s.dir, thread: th, watcher: watcherState, last_turn: lastTurnLine(s.agent), ...turnFacts(s.agent, s.harness, th, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR) });
229
712
  }
230
713
  catch (e) {
231
714
  const error = e.message.slice(0, 1000);
@@ -242,6 +725,10 @@ export async function reconcile(m, log, reportIntervalSeconds = 30) {
242
725
  removeService(w);
243
726
  log(`${local.label}: session removed by the operator; watcher removed`);
244
727
  }
728
+ if (local.container_name && local.container_runtime) {
729
+ removeAgentContainer(local.container_runtime, local.container_name, runner);
730
+ log(`${local.label}: session removed by the operator; container ${local.container_name} removed`);
731
+ }
245
732
  delete state.sessions[id];
246
733
  }
247
734
  writeMachineState(state);
@@ -274,8 +761,12 @@ export async function reconcile(m, log, reportIntervalSeconds = 30) {
274
761
  const clones = refreshClones(workdir, [...new Set(desired.filter((s) => !s.dir && s.project && s.desired === "running").map((s) => s.project))], log);
275
762
  const actualWorkdir = workdir ?? join(homedir(), "bschat");
276
763
  const workSpace = volumeSpace(actualWorkdir, "workdir");
764
+ const facts = machineFacts([...providerChecks], actualWorkdir, desired, me.machine?.cache_floor_pct ?? DEFAULT_CACHE_FLOOR_PCT);
765
+ const environmentChecks = machineEnvironmentChecks({ ...facts, workdir_free_bytes: workSpace?.freeBytes ?? null, workdir_total_bytes: workSpace?.totalBytes ?? null }, writable)
766
+ .map(({ check, status, observation, remedy, recovery_verified }) => ({ check, status, diagnosis: observation, remedy, recovery_verified, observed_at: new Date().toISOString() }));
277
767
  const report = {
278
- ...machineFacts([...providerChecks]), workdir: actualWorkdir, workdir_free_bytes: workSpace?.freeBytes ?? null, workdir_total_bytes: workSpace?.totalBytes ?? null, clones,
768
+ ...facts, environment_checks: environmentChecks,
769
+ workdir: actualWorkdir, workdir_free_bytes: workSpace?.freeBytes ?? null, workdir_total_bytes: workSpace?.totalBytes ?? null, clones,
279
770
  build_caches: buildCaches,
280
771
  // The daemon's own confirmation that it is holding turns back, and how many are still running.
281
772
  maintenance: maintenanceReport(drainingUntil(), out),
@@ -459,12 +950,13 @@ export function errorText(s) {
459
950
  /** Whether the session has a turn running, its process, and a usage-limit pause still in force. */
460
951
  function turnFacts(agent, harness, thread, turnCap = DEFAULT_TURNS_PER_HOUR) {
461
952
  const ph = thread ? probeFor(harness, thread, agent).phase() : null;
953
+ const accountFingerprint = harness === "codex" ? codexAccountFingerprint() : null;
462
954
  if (!thread || !ph || "missing" in ph)
463
- return { turn: { running: false, since: null }, process: null, paused_until: null, pause_started_at: null, turn_guard: null };
955
+ return { turn: { running: false, since: null }, process: null, paused_until: null, pause_started_at: null, turn_guard: null, ...(harness === "codex" ? { usage_account_fingerprint: accountFingerprint } : {}) };
464
956
  const until = !ph.running ? probeFor(harness, thread, agent).limitUntil(ph.lastError) : null;
465
957
  const unpausedAt = readState(agent).turn_unpaused_at ?? 0;
466
958
  const paused = until && until > Date.now() && Date.parse(ph.lastErrorAt ?? "") > unpausedAt ? new Date(until).toISOString() : null;
467
- return { turn: { running: ph.running, since: ph.running ? ph.startedAt : ph.lastEventAt }, process: ph.running ? turnProcess(thread, harness, undefined, agent) : null, paused_until: paused, pause_started_at: paused ? ph.lastErrorAt : null, turn_guard: busyTurnPause(readState(agent).turn_guard, turnCap, Date.now()) };
959
+ return { turn: { running: ph.running, since: ph.running ? ph.startedAt : ph.lastEventAt }, process: ph.running ? turnProcess(thread, harness, undefined, agent) : null, paused_until: paused, pause_started_at: paused ? ph.lastErrorAt : null, turn_guard: busyTurnPause(readState(agent).turn_guard, turnCap, Date.now()), ...(harness === "codex" ? { usage_account_fingerprint: accountFingerprint } : {}) };
468
960
  }
469
961
  /** The harness process running a turn of this session (`codex exec resume <thread>`, `claude ... --resume <id>`), from ps. */
470
962
  export function turnProcess(thread, harness = "codex", psOutput, agent) {
@@ -614,6 +1106,41 @@ export function codexSandbox(force = false, path = process.env.PATH ?? "") {
614
1106
  sandboxCache = { at: Date.now(), result, path };
615
1107
  return result;
616
1108
  }
1109
+ /** Probe machine-managed project clones using the same Codex sandbox as agent turns. */
1110
+ export function checkProjectRepos(root = join(homedir(), "bschat"), run = (args, cwd) => spawnSync("codex", args, { cwd, encoding: "utf8", timeout: 30_000, env: process.env })) {
1111
+ if (!existsSync(root))
1112
+ return [];
1113
+ const steps = [];
1114
+ const projects = readdirSync(root, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
1115
+ for (const project of projects) {
1116
+ const cwd = join(root, project, "main");
1117
+ if (!existsSync(join(cwd, ".git")))
1118
+ continue;
1119
+ const remoteResult = spawnSync("git", ["remote", "get-url", "origin"], { cwd, encoding: "utf8", timeout: 10_000 });
1120
+ const remote = remoteResult.status === 0 ? (remoteResult.stdout ?? "").trim() : "";
1121
+ if (!remote) {
1122
+ steps.push({ step: `git repo ${project}`, result: "failed", detail: `could not read origin URL from ${cwd}` });
1123
+ continue;
1124
+ }
1125
+ const result = run(["sandbox", "--", "git", "ls-remote", remote, "HEAD"], cwd);
1126
+ if (result.status === 0) {
1127
+ steps.push({ step: `git repo ${project}`, result: "ok", detail: "sandboxed git ls-remote succeeded" });
1128
+ continue;
1129
+ }
1130
+ const output = `${result.stderr ?? ""}\n${result.stdout ?? ""}`.trim();
1131
+ if (/Bad owner or permissions on \/etc\/ssh\/ssh_config\.d\/20-systemd-ssh-proxy\.conf/i.test(output)) {
1132
+ steps.push({
1133
+ step: `git repo ${project}`,
1134
+ result: "failed",
1135
+ detail: "sandboxed git ls-remote failed: Bad owner or permissions on /etc/ssh/ssh_config.d/20-systemd-ssh-proxy.conf; set this repository's core.sshCommand to a local ~/.local/bin/git-ssh wrapper that selects this repo's key and runs ssh -F /dev/null (see docs/REMOTE-MACHINES.md)",
1136
+ });
1137
+ continue;
1138
+ }
1139
+ const safeOutput = output.replaceAll(remote, "<origin>").replace(/(https?:\/\/)[^/\s@]+@/gi, "$1[redacted]@");
1140
+ steps.push({ step: `git repo ${project}`, result: "failed", detail: `sandboxed git ls-remote failed: ${safeOutput.slice(0, 300) || `exit ${result.status ?? "unknown"}`}` });
1141
+ }
1142
+ return steps;
1143
+ }
617
1144
  const AGY_SANDBOX_PROBE_MS = 10 * 60_000;
618
1145
  const AGY_SANDBOX_PROBE_MODEL = "gemini-4-hydrogen-low";
619
1146
  const AGY_SANDBOX_PROBE_RESPONSE = "B9S_SANDBOX_OK";
@@ -696,36 +1223,113 @@ function claudeReport(path = process.env.PATH ?? "", providersInUse = ["anthropi
696
1223
  return { ...f, sandbox: claudeSandboxCache.result, providers };
697
1224
  }
698
1225
  /** What the operator needs to know about this machine, reported with every pass. */
699
- export function machineFacts(providersInUse = ["anthropic"]) {
1226
+ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sessions = [], diskFloorPct = DEFAULT_CACHE_FLOOR_PCT) {
1227
+ const workdir = typeof workdirOrOpts === "string" ? workdirOrOpts : undefined;
1228
+ const opts = typeof workdirOrOpts === "object" && workdirOrOpts !== null ? workdirOrOpts : {};
1229
+ const probes = opts.probes;
700
1230
  const path = process.env.PATH ?? "";
701
1231
  const env = { ...process.env, PATH: path };
702
- const codex = spawnSync("codex", ["--version"], { encoding: "utf8", env });
703
- const login = codex.status === 0 ? spawnSync("codex", ["login", "status"], { encoding: "utf8", env }) : null;
704
- const dsh = dshFacts(platform(), path);
705
- const antigravity = antigravityFacts(path);
1232
+ const codexFactsValue = probes?.codex
1233
+ ? probes.codex()
1234
+ : (() => {
1235
+ const codex = spawnSync("codex", ["--version"], { encoding: "utf8", env });
1236
+ const login = codex.status === 0 ? spawnSync("codex", ["login", "status"], { encoding: "utf8", env }) : null;
1237
+ return codex.status === 0 ? { version: codex.stdout.trim(), logged_in: login?.status === 0 && /logged in/i.test(`${login.stdout}${login.stderr}`), login: `${login?.stdout ?? ""}${login?.stderr ?? ""}`.trim().slice(0, 200), account_fingerprint: codexAccountFingerprint(), sandbox: codexSandbox(false, path) } : null;
1238
+ })();
1239
+ const dsh = (probes?.dsh ?? (() => dshFacts(platform(), path)))();
1240
+ const antigravity = (probes?.antigravity ?? (() => antigravityFacts(path)))();
706
1241
  const homeSpace = volumeSpace(homedir(), "home");
707
1242
  const req = "/etc/codex/requirements.toml";
708
- const claude = claudeReport(path, providersInUse);
1243
+ const claude = (probes?.claude ?? (() => claudeReport(path, providersInUse)))();
709
1244
  const bootedAt = bootTimeMs();
710
- return {
1245
+ const gitIdentity = (probes?.gitIdentity ?? (() => readGitIdentity()))();
1246
+ const container = (probes?.container ?? (() => probeNestedSandbox()))();
1247
+ const imds = (opts.imdsProbe ?? probeImdsIsolation)();
1248
+ const managedHooks = (probes?.managedHooks ?? (() => existsSync(req) && isCodexManagedRequirements(readFileSync(req, "utf8"))))();
1249
+ const facts = {
711
1250
  os: platform(), arch: arch(), hostname: hostname(), user: userInfo().username, cpus: cpus().length, mem_total_bytes: totalmem(),
712
1251
  load: loadavg().map((x) => Math.round(x * 100) / 100), mem_available_bytes: memAvailable(),
713
1252
  // When this machine last booted: the server ends a maintenance window once the machine is back.
714
1253
  booted_at: bootedAt === null ? null : new Date(Math.floor(bootedAt / 60_000) * 60_000).toISOString(),
715
1254
  daemon_path: path,
716
1255
  bschat: { version: CLI_VERSION, bin: requireInstall().bin },
717
- codex: codex.status === 0 ? { version: codex.stdout.trim(), logged_in: login?.status === 0 && /logged in/i.test(`${login.stdout}${login.stderr}`), login: `${login?.stdout ?? ""}${login?.stderr ?? ""}`.trim().slice(0, 200), account_fingerprint: codexAccountFingerprint(), sandbox: codexSandbox(false, path) } : null,
1256
+ git_identity: gitIdentity,
1257
+ imds_blocked: imds.ok,
1258
+ imds_isolation: imds,
1259
+ ...(container.runtime !== null || process.env.B9S_CLOUD_MACHINE === "1" ? { container_runtime: container } : {}),
1260
+ codex: codexFactsValue,
718
1261
  "claude-code": claude,
719
1262
  claude_code: claude,
720
1263
  dsh,
721
1264
  antigravity,
722
- managed_hooks: existsSync(req) && isCodexManagedRequirements(readFileSync(req, "utf8")),
1265
+ managed_hooks: managedHooks,
723
1266
  linger: platform() === "linux" ? lingerEnabled() : null,
724
1267
  disk_free_bytes: homeSpace?.freeBytes ?? null,
725
1268
  disk_total_bytes: homeSpace?.totalBytes ?? null,
726
1269
  io_pressure: ioPressure(),
1270
+ host_checks: platform() === "linux" ? collectLinuxHostChecks() : null,
727
1271
  at: new Date().toISOString(),
728
1272
  };
1273
+ if (platform() === "darwin") {
1274
+ facts.macos = (probes?.macos ?? (() => macReadiness({ path, checkout: workdir ?? join(homedir(), "bschat"), diskFloorPct })))();
1275
+ facts.git = (probes?.git ?? (() => {
1276
+ const gitName = spawnSync("git", ["config", "--global", "--get", "user.name"], { encoding: "utf8", env });
1277
+ const gitEmail = spawnSync("git", ["config", "--global", "--get", "user.email"], { encoding: "utf8", env });
1278
+ return {
1279
+ identity_configured: gitName.status === 0 && !!gitName.stdout?.trim() && gitEmail.status === 0 && !!gitEmail.stdout?.trim(),
1280
+ repositories: repositoryAccessFacts(sessions.filter((session) => session.project).map((session) => ({ project: session.project, project_id: session.project_id, repo_url: session.repo_url })), path),
1281
+ };
1282
+ }))();
1283
+ }
1284
+ return facts;
1285
+ }
1286
+ /** Parse root (`/`) mount specification from `/etc/fstab` (or kernel cmdline fallback) for UUID/PARTUUID safety. */
1287
+ export function parseFstabRootMount(fstabText, procCmdline) {
1288
+ if (typeof fstabText === "string") {
1289
+ for (const rawLine of fstabText.split(/\r?\n/)) {
1290
+ const line = rawLine.trim();
1291
+ if (!line || line.startsWith("#"))
1292
+ continue;
1293
+ const fields = line.split(/\s+/);
1294
+ if (fields.length >= 2 && fields[1] === "/") {
1295
+ const spec = fields[0];
1296
+ return { spec, by_uuid_or_partuuid: /^(UUID|PARTUUID)=/i.test(spec) };
1297
+ }
1298
+ }
1299
+ }
1300
+ if (typeof procCmdline === "string") {
1301
+ const m = /(?:^|\s)root=((?:UUID|PARTUUID)=[^\s]+|\/dev\/[^\s]+)/i.exec(procCmdline);
1302
+ if (m?.[1]) {
1303
+ const spec = m[1];
1304
+ return { spec, by_uuid_or_partuuid: /^(UUID|PARTUUID)=/i.test(spec) };
1305
+ }
1306
+ }
1307
+ return { spec: null, by_uuid_or_partuuid: false };
1308
+ }
1309
+ /** Evaluate ENA driver, NVMe driver, and root UUID/PARTUUID mount readiness from Linux host files. */
1310
+ export function parseLinuxHostChecks(opts) {
1311
+ const modules = typeof opts.procModulesText === "string" ? opts.procModulesText : "";
1312
+ const enaDriver = opts.enaSysfsPresent === true || /(?:^|\n)ena(?:\s|$)/m.test(modules);
1313
+ const nvmeDriver = opts.nvmeSysfsPresent === true || /(?:^|\n)(?:nvme|nvme_core|nvme_tcp)(?:\s|$)/m.test(modules);
1314
+ const rootMount = parseFstabRootMount(opts.fstabText, opts.procCmdline);
1315
+ return { ena_driver: enaDriver, nvme_driver: nvmeDriver, root_mount: rootMount };
1316
+ }
1317
+ function collectLinuxHostChecks() {
1318
+ const safeRead = (p) => {
1319
+ try {
1320
+ return readFileSync(p, "utf8");
1321
+ }
1322
+ catch {
1323
+ return null;
1324
+ }
1325
+ };
1326
+ return parseLinuxHostChecks({
1327
+ fstabText: safeRead("/etc/fstab"),
1328
+ procModulesText: safeRead("/proc/modules"),
1329
+ procCmdline: safeRead("/proc/cmdline"),
1330
+ enaSysfsPresent: existsSync("/sys/module/ena") || existsSync("/sys/bus/pci/drivers/ena"),
1331
+ nvmeSysfsPresent: existsSync("/sys/module/nvme") || existsSync("/sys/module/nvme_core") || existsSync("/sys/bus/pci/drivers/nvme"),
1332
+ });
729
1333
  }
730
1334
  /** Stable, non-reversible account identity for detecting a login switch without reporting its id. */
731
1335
  export function codexAccountFingerprint(authFile = join(process.env.CODEX_HOME ?? join(homedir(), ".codex"), "auth.json")) {
@@ -738,16 +1342,51 @@ export function codexAccountFingerprint(authFile = join(process.env.CODEX_HOME ?
738
1342
  return null;
739
1343
  }
740
1344
  }
1345
+ const REPO_ACCESS_REFRESH_MS = 10 * 60_000;
1346
+ const repoAccessCache = new Map();
1347
+ export function resetRepositoryAccessCache() { repoAccessCache.clear(); }
1348
+ /** Probe configured repo access using the machine owner's Git credentials; never report URLs or Git output. */
1349
+ export function repositoryAccessFacts(projects, path = process.env.PATH ?? "", nowMs = Date.now(), run = (url, machinePath) => spawnSync("git", ["ls-remote", "--heads", url], { encoding: "utf8", timeout: 60_000, env: { ...process.env, PATH: machinePath }, maxBuffer: 1024 * 1024 })) {
1350
+ const unique = new Map();
1351
+ for (const item of projects) {
1352
+ if (!item.project)
1353
+ continue;
1354
+ unique.set(item.project_id ?? item.project, { project: item.project, projectId: item.project_id ?? item.project, url: item.repo_url ?? null });
1355
+ }
1356
+ return [...unique.values()].map(({ project, projectId, url }) => {
1357
+ if (!url)
1358
+ return { project, accessible: null, error: "repository URL is not configured" };
1359
+ const key = `${projectId}\0${url}\0${path}`;
1360
+ const cached = repoAccessCache.get(key);
1361
+ if (cached && nowMs - cached.at < REPO_ACCESS_REFRESH_MS)
1362
+ return cached.result;
1363
+ let result;
1364
+ try {
1365
+ const probe = run(url, path);
1366
+ result = probe.status === 0
1367
+ ? { project, accessible: true, error: null }
1368
+ : { project, accessible: false, error: `git ls-remote failed (exit ${probe.status ?? "unknown"})` };
1369
+ }
1370
+ catch {
1371
+ result = { project, accessible: false, error: "git ls-remote could not run" };
1372
+ }
1373
+ repoAccessCache.set(key, { at: nowMs, result });
1374
+ return result;
1375
+ });
1376
+ }
741
1377
  /**
742
- * Provisioning steps that need this machine's own view, run by `machine add` over ssh: linger on
743
- * Linux, Codex present and logged in, and b9s's hooks in Codex's administrator layer when sudo
744
- * works without a password. Each step reports ok, done, skipped or failed; nothing is hidden.
1378
+ * Provisioning steps that need this machine's own view, run by `machine add` over ssh: read-only
1379
+ * Mac/Xcode readiness where relevant, linger on Linux, harness login, and b9s's hooks in Codex's
1380
+ * administrator layer when sudo works without a password. Each step reports ok, done, skipped or
1381
+ * failed; nothing is hidden.
745
1382
  */
746
1383
  export function prepare(opts = {}) {
747
1384
  const steps = [];
748
1385
  const daemonPath = machineDaemonPath();
749
1386
  const daemonEnv = { ...process.env, PATH: daemonPath };
750
1387
  steps.push({ step: "daemon PATH", result: "ok", detail: daemonPath });
1388
+ if (platform() === "darwin")
1389
+ steps.push(...macReadinessSteps(macReadiness({ path: daemonPath })).map((step) => ({ ...step, result: step.result })));
751
1390
  const sudo = spawnSync("sudo", ["-n", "true"], { stdio: "ignore" }).status === 0;
752
1391
  if (platform() === "linux") {
753
1392
  const l = lingerEnabled();
@@ -801,6 +1440,9 @@ export function prepare(opts = {}) {
801
1440
  ? { step: "codex sandbox", result: "done", detail: `installed ${CODEX_APPARMOR_PATH} (Codex only); the sandbox works` }
802
1441
  : { step: "codex sandbox", result: "failed", detail: l.status !== 0 ? `installing ${CODEX_APPARMOR_PATH}: ${(l.stderr ?? "").trim()}` : `profile installed but the sandbox still fails: ${sb.error}` });
803
1442
  }
1443
+ if (platform() === "linux" && sb.ok) {
1444
+ steps.push(...checkProjectRepos(join(homedir(), "bschat"), (args, cwd) => spawnSync("codex", args, { cwd, encoding: "utf8", timeout: 30_000, env: daemonEnv })));
1445
+ }
804
1446
  }
805
1447
  // Claude Code is optional on a machine; when it is there, say whether it can run agents.
806
1448
  const claude = claudeFacts(undefined, daemonPath);
@@ -860,8 +1502,276 @@ export function prepare(opts = {}) {
860
1502
  }
861
1503
  return steps;
862
1504
  }
1505
+ function sha256HexSync(data) {
1506
+ return createHash("sha256").update(data, "utf8").digest("hex");
1507
+ }
1508
+ function hmacSha256(key, data) {
1509
+ return createHmac("sha256", key).update(data, "utf8").digest();
1510
+ }
1511
+ export function signStsGetCallerIdentityProof(opts) {
1512
+ const dt = opts.now ?? new Date();
1513
+ const amzDate = dt.toISOString().replace(/[:-]|\.\d{3}/g, "");
1514
+ const dateStamp = amzDate.slice(0, 8);
1515
+ const host = `sts.${opts.region}.amazonaws.com`;
1516
+ const endpoint = `https://${host}/`;
1517
+ const body = "Action=GetCallerIdentity&Version=2011-06-15";
1518
+ const contentType = "application/x-www-form-urlencoded; charset=utf-8";
1519
+ const signedHeaders = "content-type;host;x-amz-date;x-amz-security-token";
1520
+ const canonicalHeaders = `content-type:${contentType}\n` +
1521
+ `host:${host}\n` +
1522
+ `x-amz-date:${amzDate}\n` +
1523
+ `x-amz-security-token:${opts.sessionToken}\n`;
1524
+ const canonicalRequest = [
1525
+ "POST",
1526
+ "/",
1527
+ "",
1528
+ canonicalHeaders,
1529
+ signedHeaders,
1530
+ sha256HexSync(body),
1531
+ ].join("\n");
1532
+ const credentialScope = `${dateStamp}/${opts.region}/sts/aws4_request`;
1533
+ const stringToSign = [
1534
+ "AWS4-HMAC-SHA256",
1535
+ amzDate,
1536
+ credentialScope,
1537
+ sha256HexSync(canonicalRequest),
1538
+ ].join("\n");
1539
+ const kDate = hmacSha256(`AWS4${opts.secretAccessKey}`, dateStamp);
1540
+ const kRegion = hmacSha256(kDate, opts.region);
1541
+ const kService = hmacSha256(kRegion, "sts");
1542
+ const kSigning = hmacSha256(kService, "aws4_request");
1543
+ const signature = createHmac("sha256", kSigning).update(stringToSign, "utf8").digest("hex");
1544
+ const authorization = `AWS4-HMAC-SHA256 Credential=${opts.accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
1545
+ return {
1546
+ region: opts.region,
1547
+ method: "POST",
1548
+ url: endpoint,
1549
+ headers: {
1550
+ host,
1551
+ "content-type": contentType,
1552
+ "x-amz-date": amzDate,
1553
+ "x-amz-security-token": opts.sessionToken,
1554
+ authorization,
1555
+ },
1556
+ body,
1557
+ };
1558
+ }
1559
+ async function retrieveEc2BootstrapToken(opts) {
1560
+ const imds = opts.imdsUrl.replace(/\/$/, "");
1561
+ const tokenRes = await opts.fetchImpl(`${imds}/latest/api/token`, {
1562
+ method: "PUT",
1563
+ headers: { "x-aws-ec2-metadata-token-ttl-seconds": "21600" },
1564
+ });
1565
+ if (!tokenRes.ok)
1566
+ throw new CliError("api", `IMDSv2 session token request failed (${tokenRes.status})`);
1567
+ const imdsToken = (await tokenRes.text()).trim();
1568
+ if (!imdsToken)
1569
+ throw new CliError("api", "IMDSv2 returned empty session token");
1570
+ const metaGet = async (path) => {
1571
+ const r = await opts.fetchImpl(`${imds}${path}`, {
1572
+ method: "GET",
1573
+ headers: { "x-aws-ec2-metadata-token": imdsToken },
1574
+ });
1575
+ if (!r.ok)
1576
+ throw new CliError("api", `IMDSv2 metadata ${path} failed (${r.status})`);
1577
+ return (await r.text()).trim();
1578
+ };
1579
+ const [instanceId, region, rolesRaw] = await Promise.all([
1580
+ metaGet("/latest/meta-data/instance-id"),
1581
+ metaGet("/latest/meta-data/placement/region"),
1582
+ metaGet("/latest/meta-data/iam/security-credentials/"),
1583
+ ]);
1584
+ const roleName = rolesRaw.split(/\r?\n/).find((l) => l.trim().length > 0)?.trim();
1585
+ if (!roleName)
1586
+ throw new CliError("api", "IMDSv2 reported no attached IAM instance role");
1587
+ const credsRaw = await metaGet(`/latest/meta-data/iam/security-credentials/${encodeURIComponent(roleName)}`);
1588
+ let creds;
1589
+ try {
1590
+ creds = JSON.parse(credsRaw);
1591
+ }
1592
+ catch {
1593
+ throw new CliError("api", "IMDSv2 IAM credentials response was not valid JSON");
1594
+ }
1595
+ if (!creds.AccessKeyId || !creds.SecretAccessKey || !creds.Token) {
1596
+ throw new CliError("api", "IMDSv2 IAM credentials missing AccessKeyId, SecretAccessKey, or Token");
1597
+ }
1598
+ const stsProof = signStsGetCallerIdentityProof({
1599
+ region,
1600
+ accessKeyId: creds.AccessKeyId,
1601
+ secretAccessKey: creds.SecretAccessKey,
1602
+ sessionToken: creds.Token,
1603
+ });
1604
+ const res = await opts.fetchImpl(`${opts.baseUrl}/cloud/bootstrap/retrieve`, {
1605
+ method: "POST",
1606
+ headers: { "content-type": "application/json" },
1607
+ body: JSON.stringify({ instance_id: instanceId, sts_identity: stsProof }),
1608
+ });
1609
+ const data = (await res.json().catch(() => ({})));
1610
+ if (!res.ok || typeof data?.token !== "string" || !data.token) {
1611
+ throw new CliError("api", data?.message ?? `bootstrap token retrieval failed (${res.status})`);
1612
+ }
1613
+ return {
1614
+ token: data.token,
1615
+ instanceId,
1616
+ machineId: typeof data.machine_id === "string" ? data.machine_id : undefined,
1617
+ machineName: typeof data.machine_name === "string" ? data.machine_name : undefined,
1618
+ };
1619
+ }
1620
+ export async function exchangeBootstrapToken(opts) {
1621
+ let parsedUrl;
1622
+ try {
1623
+ parsedUrl = new URL(opts.url);
1624
+ }
1625
+ catch {
1626
+ throw new CliError("usage", `invalid bootstrap URL ${JSON.stringify(opts.url)}`);
1627
+ }
1628
+ if (parsedUrl.protocol !== "https:") {
1629
+ throw new CliError("usage", "bootstrap URL must use https://");
1630
+ }
1631
+ const f = opts.fetchImpl ?? fetch;
1632
+ const baseUrl = opts.url.replace(/\/$/, "");
1633
+ let raw = "";
1634
+ let retrievedInstanceId = opts.instanceId;
1635
+ let retrievedMachineId = opts.machineId;
1636
+ let retrievedMachineName = opts.machineName;
1637
+ try {
1638
+ if (opts.retrieveEc2) {
1639
+ const retrieved = await retrieveEc2BootstrapToken({
1640
+ baseUrl,
1641
+ imdsUrl: opts.imdsUrl ?? "http://169.254.169.254",
1642
+ fetchImpl: f,
1643
+ });
1644
+ raw = retrieved.token;
1645
+ retrievedInstanceId = retrievedInstanceId ?? retrieved.instanceId;
1646
+ retrievedMachineId = retrievedMachineId ?? retrieved.machineId;
1647
+ retrievedMachineName = retrievedMachineName ?? retrieved.machineName;
1648
+ if (opts.tokenFile) {
1649
+ mkdirSync(dirname(opts.tokenFile), { recursive: true, mode: 0o700 });
1650
+ chmodSync(dirname(opts.tokenFile), 0o700);
1651
+ writeFileSync(opts.tokenFile, `${raw}\n`, { mode: 0o600 });
1652
+ chmodSync(opts.tokenFile, 0o600);
1653
+ raw = readFileSync(opts.tokenFile, "utf8").trim();
1654
+ }
1655
+ }
1656
+ else {
1657
+ raw = opts.token || (opts.tokenFile ? readFileSync(opts.tokenFile, "utf8").trim() : "") || process.env.B9S_BOOTSTRAP_TOKEN || process.env.BSCHAT_BOOTSTRAP_TOKEN || "";
1658
+ }
1659
+ if (!raw)
1660
+ throw new CliError("usage", "bootstrap token required (--retrieve-ec2, --token-file, --token, or B9S_BOOTSTRAP_TOKEN)");
1661
+ const res = await f(`${baseUrl}/cloud/bootstrap/exchange`, {
1662
+ method: "POST",
1663
+ headers: { "content-type": "application/json" },
1664
+ body: JSON.stringify({
1665
+ token: raw,
1666
+ ...(retrievedMachineName ? { machine_name: retrievedMachineName } : {}),
1667
+ ...(retrievedMachineId ? { machine_id: retrievedMachineId } : {}),
1668
+ ...(retrievedInstanceId ? { instance_id: retrievedInstanceId } : {}),
1669
+ }),
1670
+ });
1671
+ const data = (await res.json().catch(() => ({})));
1672
+ if (!res.ok)
1673
+ throw new CliError("api", data?.message ?? `bootstrap exchange failed (${res.status})`);
1674
+ const mf = machineFile();
1675
+ mkdirSync(dirname(mf), { recursive: true, mode: 0o700 });
1676
+ writeFileSync(mf, JSON.stringify({ url: baseUrl, name: data.machine.name, key: data.key, container_agents: true }, null, 2) + "\n", { mode: 0o600 });
1677
+ chmodSync(mf, 0o600);
1678
+ return { machine: data.machine, url: baseUrl, operation_id: data.operation_id, pinned: data.pinned ?? {} };
1679
+ }
1680
+ finally {
1681
+ raw = "";
1682
+ delete process.env.B9S_BOOTSTRAP_TOKEN;
1683
+ delete process.env.BSCHAT_BOOTSTRAP_TOKEN;
1684
+ if (opts.tokenFile) {
1685
+ try {
1686
+ writeFileSync(opts.tokenFile, "", { mode: 0o600 });
1687
+ }
1688
+ catch { /* best-effort wipe before unlink */ }
1689
+ try {
1690
+ unlinkSync(opts.tokenFile);
1691
+ }
1692
+ catch { /* best-effort immediate scrub */ }
1693
+ }
1694
+ }
1695
+ }
1696
+ const defaultDeviceLoginInFlight = new Set();
1697
+ export function handleDeviceLoginRequests(client, requests, log, inFlight = defaultDeviceLoginInFlight) {
1698
+ for (const req of requests) {
1699
+ if (req.status !== "requested")
1700
+ continue;
1701
+ if (inFlight.has(req.id))
1702
+ continue;
1703
+ const args = req.harness === "codex"
1704
+ ? ["login", "--device-auth"]
1705
+ : req.harness === "claude-code"
1706
+ ? ["auth", "login"]
1707
+ : null;
1708
+ if (!args)
1709
+ continue;
1710
+ const bin = req.harness === "codex" ? "codex" : "claude";
1711
+ inFlight.add(req.id);
1712
+ let settled = false;
1713
+ const reportTerminal = (payload) => {
1714
+ if (settled)
1715
+ return;
1716
+ settled = true;
1717
+ void client.call("POST", `/machines/me/device-login/${req.id}`, payload)
1718
+ .catch((e) => log(`device-login finish report failed: ${e.message}`))
1719
+ .finally(() => { inFlight.delete(req.id); });
1720
+ };
1721
+ let child;
1722
+ try {
1723
+ child = spawn(bin, args, { stdio: ["ignore", "pipe", "pipe"], detached: true });
1724
+ }
1725
+ catch (e) {
1726
+ reportTerminal({ status: "failed", error: `device auth spawn failed (${bin}): ${e.message}` });
1727
+ continue;
1728
+ }
1729
+ let combined = "";
1730
+ let postedPrompt = false;
1731
+ const checkOutput = () => {
1732
+ if (postedPrompt)
1733
+ return;
1734
+ const urlMatch = /(https:\/\/\S+)/.exec(combined);
1735
+ const codeMatch = /\b([A-Z0-9]{4,8}-[A-Z0-9]{4,8})\b/.exec(combined);
1736
+ if (urlMatch && codeMatch) {
1737
+ postedPrompt = true;
1738
+ client.call("POST", `/machines/me/device-login/${req.id}`, {
1739
+ status: "awaiting_user",
1740
+ verification_uri: urlMatch[1],
1741
+ user_code: codeMatch[1],
1742
+ }).catch((e) => log(`device-login report failed: ${e.message}`));
1743
+ }
1744
+ };
1745
+ child.on("error", (err) => {
1746
+ reportTerminal({ status: "failed", error: `device auth spawn failed (${bin}): ${err.message}` });
1747
+ });
1748
+ child.stdout?.on("data", (d) => { combined += String(d); checkOutput(); });
1749
+ child.stderr?.on("data", (d) => { combined += String(d); checkOutput(); });
1750
+ child.on("close", (code) => {
1751
+ reportTerminal(code === 0
1752
+ ? { status: "verified" }
1753
+ : { status: "failed", error: `device auth exited ${code ?? "null"}` });
1754
+ });
1755
+ child.unref();
1756
+ }
1757
+ }
863
1758
  export async function machine(p, out) {
864
1759
  const sub = p.positionals[1];
1760
+ if (sub === "bootstrap") {
1761
+ const url = str(p.flags, "url") ?? process.env.B9S_URL ?? process.env.BSCHAT_URL;
1762
+ if (!url)
1763
+ throw new CliError("usage", "machine bootstrap --url <api> [--retrieve-ec2 | --token-file <path> | --token <bs_boot_...>] [--name <name>]");
1764
+ const r = await exchangeBootstrapToken({
1765
+ url,
1766
+ token: str(p.flags, "token"),
1767
+ tokenFile: str(p.flags, "token-file"),
1768
+ retrieveEc2: p.flags["retrieve-ec2"] === true,
1769
+ machineName: str(p.flags, "name"),
1770
+ machineId: str(p.flags, "machine-id"),
1771
+ instanceId: str(p.flags, "instance-id"),
1772
+ });
1773
+ return out.print(`Enrolled machine ${r.machine.name} (${r.machine.id}) on ${r.url}; wrote mode-0600 credentials.`, r);
1774
+ }
865
1775
  if (sub === "prepare") {
866
1776
  if (p.flags["print-hooks"])
867
1777
  return out.print(codexManagedHooks(requireInstall().bin).requirements, codexManagedHooks(requireInstall().bin));
@@ -892,6 +1802,14 @@ export async function machine(p, out) {
892
1802
  const r = await reconcile(m, log);
893
1803
  return out.print(r.sessions.map((s) => `${s.state.padEnd(8)} ${desiredName(s.id)} ${s.thread ?? ""} ${s.error ?? ""}`).join("\n") || "no sessions declared", r);
894
1804
  }
1805
+ if (sub === "build-images") {
1806
+ const me = await Client.raw(m.url, m.key).call("GET", "/machines/me");
1807
+ const projects = me.projects ?? [];
1808
+ const accountId = me.machine?.account_id ?? "acct";
1809
+ const workdir = me.machine?.workdir ?? null;
1810
+ const results = await reconcilePendingImageBuilds(Client.raw(m.url, m.key), projects, { accountId, workdir, log });
1811
+ return out.print(results.map((r) => `${r.status.padEnd(8)} ${r.project_id} ${r.build_id} ${r.image_digest ?? r.error ?? ""}`).join("\n") || "no pending image builds", { results });
1812
+ }
895
1813
  if (sub === "run") {
896
1814
  const interval = Number(str(p.flags, "interval") ?? "30");
897
1815
  if (!Number.isFinite(interval) || interval < 1 || interval > 3600)
@@ -907,6 +1825,6 @@ export async function machine(p, out) {
907
1825
  await new Promise((r) => setTimeout(r, interval * 1000));
908
1826
  }
909
1827
  }
910
- throw new CliError("usage", "machine run | once | status | prepare | service");
1828
+ throw new CliError("usage", "machine bootstrap | run | once | status | prepare | service");
911
1829
  }
912
1830
  const desiredName = (id) => readMachineState().sessions[id]?.label.replace(WATCH_LABEL_PREFIX, "") ?? id;