benignswarm 0.12.104 → 0.12.106

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.
@@ -17,12 +17,12 @@ import { CLI_VERSION } from "../version.js";
17
17
  import { probeCapabilities } from "../capabilities.js";
18
18
  import { diskSpaceNotice } from "../notices.js";
19
19
  import { verifyClaudeProvider } from "../providers.js";
20
- import { busyTurnPause, DEFAULT_TURNS_PER_HOUR, DEFAULT_UNPRODUCTIVE_PER_HOUR, resumeTurnGuard } from "../turn-guard.js";
20
+ import { busyTurnPause, DEFAULT_TURNS_PER_HOUR, DEFAULT_UNPRODUCTIVE_PER_HOUR, resumeTurnGuard, verificationUnavailable } from "../turn-guard.js";
21
21
  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, networklessRuntimeWrapper, probeImdsIsolation, probeNestedSandbox, readGitIdentity, resolveSessionSecretDelivery, validateDevcontainerSpec, BUILD_SECRET_KEY_NAME_RE, BUILD_SECRET_CONTENT_RE, containsBuildSecretMaterial, sanitizeBuildDiagnosticText, } from "../container.js";
25
+ import { agentContainerName, agentContainerRunArgs, detectEc2Host, ensurePinnedImagePulled, isolatedBuildCommand, isolatedDevcontainerBuildCommand, isolatedImagePullCommands, isolatedSubprocessEnv, probeContainerImdsIsolation, networklessRuntimeWrapper, probeImdsIsolation, probeNestedSandbox, readGitIdentity, resolveSessionSecretDelivery, resolveWritableMounts, 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";
@@ -30,6 +30,11 @@ import { authorizeWorktreeScope, redactProcessCommand, scanWorktreeProcesses } f
30
30
  import { collectPruneProtection } from "../prune-protection.js";
31
31
  import { runMachineDaemonLoop } from "../machine-daemon.js";
32
32
  import { pruneProjectWorktrees } from "./worktrees.js";
33
+ import { ECRClient } from "@aws-sdk/client-ecr";
34
+ import { EcrHostedRegistry } from "../hosted-registry-ecr.js";
35
+ import { publishHostedImage } from "../hosted-registry.js";
36
+ import { assumeHostedBuilder } from "../hosted-registry-session.js";
37
+ import { pushHostedImage } from "../hosted-registry-push.js";
33
38
  export const machineFile = () => join(configRoot(), "machine.json");
34
39
  export function loadMachine() {
35
40
  const f = machineFile();
@@ -99,6 +104,13 @@ export function turnFaultSessionFields(fault) {
99
104
  return { turn_fault_at: new Date(fault.at).toISOString() };
100
105
  }
101
106
  const syncRunner = (cmd, args, opts) => spawnSync(cmd, args, { encoding: "utf8", timeout: opts?.timeout ?? 180_000, cwd: opts?.cwd, env: opts?.env });
107
+ export function bareDigestOf(imageRef) {
108
+ if (!imageRef)
109
+ return null;
110
+ const idx = imageRef.indexOf("@sha256:");
111
+ const candidate = idx >= 0 ? imageRef.slice(idx + 1) : imageRef;
112
+ return /^sha256:[a-f0-9]{64}$/i.test(candidate.trim()) ? candidate.trim().toLowerCase() : null;
113
+ }
102
114
  const MACHINE_REQUEST_TIMEOUT_MS = 45_000;
103
115
  const MACHINE_PASS_BUDGET_MS = 4 * 60_000;
104
116
  const MACHINE_WATCHDOG_MS = 5 * 60_000;
@@ -427,7 +439,7 @@ export async function reconcilePendingImageBuilds(client, projects, opts) {
427
439
  if (insp.status !== 0 || !digestMatch) {
428
440
  throw new Error(`built image ${imageRef} did not yield an immutable @sha256 digest`);
429
441
  }
430
- const imageDigest = digestMatch[1].toLowerCase();
442
+ let imageDigest = digestMatch[1].toLowerCase();
431
443
  const validationResults = [];
432
444
  for (const probe of build.declared_probes ?? []) {
433
445
  if (probe.scope !== "image")
@@ -467,10 +479,40 @@ export async function reconcilePendingImageBuilds(client, projects, opts) {
467
479
  ...(!projectTest.ok ? [`project test failed: ${projectTest.error}`] : []),
468
480
  ...(compressedSizeBytes > 8 * 1024 * 1024 * 1024 ? ["compressed image exceeds the 8 GiB limit"] : []),
469
481
  ].join("; ");
482
+ let hostedImageReference;
483
+ if (!validationError && img.hosted_registry) {
484
+ const registry = img.hosted_registry;
485
+ let ecr;
486
+ try {
487
+ let port;
488
+ if (opts.hostedPort) {
489
+ port = await opts.hostedPort(registry, imageRef, nested.runtime, buildTmpRoot, env);
490
+ }
491
+ else {
492
+ const session = await assumeHostedBuilder(opts.accountId, project.id, registry);
493
+ ecr = new ECRClient(session);
494
+ const ecrClient = ecr;
495
+ const registryId = registry.registry_endpoint.split(".")[0];
496
+ port = new EcrHostedRegistry(ecrClient, registryId, async (source, target) => {
497
+ const prefix = `${registry.registry_endpoint}/`;
498
+ if (!target.startsWith(prefix))
499
+ throw new Error("hosted registry target mismatch");
500
+ const lastColon = target.lastIndexOf(":");
501
+ return pushHostedImage({ ecr: ecrClient, registryId, endpoint: registry.registry_endpoint, repository: target.slice(prefix.length, lastColon), tag: target.slice(lastColon + 1), source, runtime: nested.runtime, directory: buildTmpRoot, runner, env });
502
+ });
503
+ }
504
+ const pushed = await publishHostedImage({ accountId: opts.accountId, projectId: project.id, registry, sourceImage: imageRef, tag: build.id }, port);
505
+ imageDigest = pushed.digest;
506
+ hostedImageReference = pushed.imageReference;
507
+ }
508
+ finally {
509
+ ecr?.destroy();
510
+ }
511
+ }
470
512
  await client.call("POST", `/machines/me/image-builds/${build.id}`, {
471
513
  status: validationError ? "failed" : "ready",
472
514
  image_digest: imageDigest,
473
- ...(img.hosted_registry_repository ? { image_reference: `${imageRef}@${imageDigest}` } : {}),
515
+ ...(hostedImageReference ? { image_reference: hostedImageReference } : {}),
474
516
  probe_results: validationResults,
475
517
  project_test: projectTest,
476
518
  compressed_size_bytes: compressedSizeBytes,
@@ -517,21 +559,92 @@ export async function reconcilePendingImageBuilds(client, projects, opts) {
517
559
  return results;
518
560
  }
519
561
  export function resolveContainerLaunchPrereqs(opts) {
520
- const nested = (opts.probeSandbox ?? probeNestedSandbox)({ runner: opts.runner });
562
+ const nested = opts.sandboxReport ?? (opts.probeSandbox ?? probeNestedSandbox)({ runner: opts.runner });
521
563
  if (!nested.runtime) {
522
564
  throw new Error("container isolation required but neither podman nor docker is available; refusing unisolated host fallback");
523
565
  }
566
+ if (nested.usable_without_root === false) {
567
+ throw new Error(`refusing container session: ${nested.runtime} is not usable without root (${nested.detail})`);
568
+ }
524
569
  if (opts.s.sandbox !== "danger-full-access" && !nested.nested_sandbox_ok) {
525
570
  const error = new Error(`refusing sandboxed container session (${opts.s.sandbox}) without silently falling back to danger-full-access: ${nested.detail}`);
526
571
  if (nested.missing.includes("unprivileged_userns"))
527
572
  error.environment_check = "linux_user_namespaces";
528
573
  throw error;
529
574
  }
575
+ const targetArch = opts.project?.image?.target_arch;
576
+ const supportedArches = Array.isArray(nested.architectures) ? nested.architectures : [];
577
+ if (targetArch && supportedArches.length > 0 && !supportedArches.includes(targetArch)) {
578
+ throw new Error(`container runtime (${nested.runtime}) supports ${supportedArches.join(", ")}, project image requires ${targetArch}`);
579
+ }
580
+ if (opts.onEc2 && opts.containerImdsBlocked === false) {
581
+ throw new Error("refusing container session on EC2: metadata endpoints (169.254.169.254 / fd00:ec2::254) are not blocked from project containers");
582
+ }
530
583
  const imageDigest = resolvePinnedImageRef(opts.project?.image);
531
- if (!imageDigest) {
584
+ const bareDigest = bareDigestOf(imageDigest);
585
+ if (!imageDigest || !bareDigest) {
532
586
  throw new Error(`container session for ${opts.s.agent} has no ready pinned @sha256 project image digest; refusing unisolated host fallback`);
533
587
  }
534
- return { runtime: nested.runtime, imageDigest };
588
+ return { runtime: nested.runtime, imageDigest, bareDigest };
589
+ }
590
+ export function resolveContainerImageProbePrereqs(opts) {
591
+ const pinnedRef = resolvePinnedImageRef(opts.project.image);
592
+ const bare = bareDigestOf(pinnedRef);
593
+ const nested = opts.sandboxReport;
594
+ if (!nested?.runtime) {
595
+ return {
596
+ ok: false,
597
+ bareDigest: bare,
598
+ reason: "container isolation required for image capability probe but neither podman nor docker is available",
599
+ };
600
+ }
601
+ if (nested.usable_without_root === false) {
602
+ return {
603
+ ok: false,
604
+ bareDigest: bare,
605
+ reason: `refusing container image probe: ${nested.runtime} is not usable without root (${nested.detail})`,
606
+ };
607
+ }
608
+ if (!nested.nested_sandbox_ok) {
609
+ return {
610
+ ok: false,
611
+ bareDigest: bare,
612
+ reason: `refusing container image probe without nested container sandbox: ${nested.detail}`,
613
+ };
614
+ }
615
+ const targetArch = opts.project.image?.target_arch;
616
+ const supportedArches = Array.isArray(nested.architectures) ? nested.architectures : [];
617
+ if (targetArch && supportedArches.length > 0 && !supportedArches.includes(targetArch)) {
618
+ return {
619
+ ok: false,
620
+ bareDigest: bare,
621
+ reason: `container runtime (${nested.runtime}) supports ${supportedArches.join(", ")}, project image requires ${targetArch}`,
622
+ };
623
+ }
624
+ if (opts.onEc2 && opts.containerImdsBlocked !== true) {
625
+ return {
626
+ ok: false,
627
+ bareDigest: bare,
628
+ reason: "refusing container image probe on EC2: metadata endpoints (169.254.169.254 / fd00:ec2::254) are not blocked from project containers",
629
+ };
630
+ }
631
+ if (!pinnedRef || !bare) {
632
+ return {
633
+ ok: false,
634
+ bareDigest: null,
635
+ reason: "image capability probe requires a ready pinned @sha256 project image digest",
636
+ };
637
+ }
638
+ return {
639
+ ok: true,
640
+ bareDigest: bare,
641
+ context: {
642
+ runtime: nested.runtime,
643
+ imageDigest: pinnedRef,
644
+ arch: targetArch,
645
+ runner: opts.runner,
646
+ },
647
+ };
535
648
  }
536
649
  export function agentHomeDirOf(s) {
537
650
  return join(configRoot(), "agent-homes", s.project ?? "account", s.agent_name);
@@ -609,7 +722,18 @@ export async function launchDesiredSession(opts) {
609
722
  project: opts.project,
610
723
  runner,
611
724
  probeSandbox: opts.probeSandbox,
725
+ sandboxReport: opts.sandboxReport,
726
+ onEc2: opts.onEc2,
727
+ containerImdsBlocked: opts.containerImdsBlocked,
612
728
  });
729
+ if (opts.pullImage) {
730
+ ensurePinnedImagePulled({
731
+ runtime,
732
+ imageDigest,
733
+ arch: opts.project?.image?.target_arch,
734
+ runner,
735
+ });
736
+ }
613
737
  const agentHomeDir = agentHomeDirOf(opts.s);
614
738
  const isolatedB9sDir = join(agentHomeDir, ".b9s");
615
739
  const logsDir = join(isolatedB9sDir, "logs");
@@ -630,6 +754,14 @@ export async function launchDesiredSession(opts) {
630
754
  }
631
755
  const containerName = agentContainerName(opts.accountId, opts.s.project ?? "account", opts.s.agent_name);
632
756
  removeAgentContainer(runtime, containerName, runner);
757
+ const rawWritable = opts.machineWritable ?? [];
758
+ const writableMounts = resolveWritableMounts(rawWritable, {
759
+ worktreeDir: opts.s.dir,
760
+ agentHomeDir,
761
+ project: opts.s.project ?? "account",
762
+ agent: opts.s.agent_name,
763
+ });
764
+ const containerWritablePaths = ["/workspace", ...writableMounts.map((w) => w.containerPath)];
633
765
  const runArgs = agentContainerRunArgs({
634
766
  runtime,
635
767
  accountSlug: opts.accountId,
@@ -638,6 +770,8 @@ export async function launchDesiredSession(opts) {
638
770
  imageDigest,
639
771
  worktreeDir: opts.s.dir,
640
772
  agentHomeDir,
773
+ writableFolders: rawWritable,
774
+ platform: opts.project?.image?.target_arch,
641
775
  allowedCaches: opts.project?.image?.allowed_caches ?? [],
642
776
  cacheRootDir: join(opts.workdir ?? join(homedir(), "bschat"), ".caches", opts.accountId),
643
777
  detach: true,
@@ -647,7 +781,7 @@ export async function launchDesiredSession(opts) {
647
781
  B9S_AGENT: opts.s.agent,
648
782
  B9S_HOME: "/home/agent/.b9s",
649
783
  },
650
- command: ["b9s", ...startArgs(opts.s, opts.thread, opts.s.sandbox === "workspace-write" ? ["/workspace"] : [], opts.startupJitterSeconds), "--in-container"],
784
+ command: ["b9s", ...startArgs(opts.s, opts.thread, opts.s.sandbox === "workspace-write" ? containerWritablePaths : [], opts.startupJitterSeconds), "--in-container"],
651
785
  });
652
786
  const launchRes = runner(runtime, runArgs, {
653
787
  cwd: opts.s.dir,
@@ -722,6 +856,23 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
722
856
  const state = readMachineState();
723
857
  const bin = deps?.bin ?? requireInstall().bin;
724
858
  const runner = deps?.runner ?? syncRunner;
859
+ const hasPoolImageProject = projects.some((p) => Boolean(p.image?.pool_sessions_enabled));
860
+ const hasImageCapabilityProject = projects.some((p) => p.capabilities.some((cap) => cap.scope === "image"));
861
+ const isCloudHost = Boolean(m.container_agents) || Boolean(me.machine?.container_agents) || process.env.B9S_CONTAINER_AGENTS === "1";
862
+ const needsContainerEnv = isCloudHost || hasPoolImageProject || hasImageCapabilityProject;
863
+ const hostContainerProbe = (deps?.probeSandbox ?? probeNestedSandbox)({ runner });
864
+ const onEc2 = deps?.onEc2 ?? (() => {
865
+ try {
866
+ return deps?.detectEc2 ? deps.detectEc2() : detectEc2Host();
867
+ }
868
+ catch {
869
+ return true;
870
+ }
871
+ })();
872
+ const imdsContainerProbe = hostContainerProbe?.runtime && onEc2
873
+ ? (deps?.probeImdsContainer ? deps.probeImdsContainer({ runner }) : probeContainerImdsIsolation({ runner }))
874
+ : null;
875
+ const containerImdsOk = imdsContainerProbe ? imdsContainerProbe.ok : deps?.containerImdsBlocked;
725
876
  const out = [];
726
877
  for (const s of desired) {
727
878
  const label = watchLabelOf(s.agent);
@@ -753,8 +904,16 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
753
904
  removeAgentContainer(local.container_runtime, local.container_name, runner);
754
905
  log(`${s.agent}: stopped (container ${local.container_name} removed)`);
755
906
  }
756
- delete state.sessions[s.id];
757
- out.push({ id: s.id, state: "stopped" });
907
+ const persisted = readState(s.agent).harness_session;
908
+ const thread = local?.thread ?? s.thread ?? (persisted?.harness === s.harness ? persisted.session_id : null);
909
+ const dir = s.dir || (s.project ? join(workdir ?? join(homedir(), "bschat"), s.project, s.agent_name) : "");
910
+ const facts = stoppedSessionFacts(dir, thread, undefined, undefined, () => {
911
+ if (!thread || !TURN_HARNESSES.includes(s.harness))
912
+ return null;
913
+ const phase = probeFor(s.harness, thread, s.agent).phase();
914
+ return "missing" in phase ? null : phase.running;
915
+ });
916
+ out.push({ id: s.id, state: "stopped", ...facts });
758
917
  continue;
759
918
  }
760
919
  if (!TURN_HARNESSES.includes(s.harness))
@@ -764,9 +923,18 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
764
923
  if ((s.provider ?? "anthropic") === "deepseek" && s.harness !== "claude-code")
765
924
  throw new Error("provider deepseek requires harness claude-code");
766
925
  const projectEntry = projects.find((p) => p.id === s.project_id || p.name === s.project);
767
- const containerMode = Boolean(m.container_agents) || process.env.B9S_CONTAINER_AGENTS === "1" || Boolean(projectEntry?.image);
926
+ const isPoolImageOptIn = Boolean(s.pool) && !s.hardware_bound && Boolean(projectEntry?.image?.pool_sessions_enabled);
927
+ const containerMode = isCloudHost || (isPoolImageOptIn && hostContainerProbe?.runtime !== null);
768
928
  const containerPrereqs = containerMode
769
- ? resolveContainerLaunchPrereqs({ s, project: projectEntry, runner, probeSandbox: deps?.probeSandbox })
929
+ ? resolveContainerLaunchPrereqs({
930
+ s,
931
+ project: projectEntry,
932
+ runner,
933
+ probeSandbox: deps?.probeSandbox,
934
+ sandboxReport: hostContainerProbe ?? undefined,
935
+ onEc2,
936
+ containerImdsBlocked: containerImdsOk,
937
+ })
770
938
  : null;
771
939
  const pinnedImageRef = containerPrereqs?.imageDigest ?? null;
772
940
  const containerName = containerMode ? agentContainerName(accountId, s.project ?? "account", s.agent_name) : null;
@@ -829,6 +997,10 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
829
997
  removeService(hostSvc);
830
998
  log(`${s.agent}: removed host watcher service before container supervision`);
831
999
  }
1000
+ else if (!containerMode && local?.container_name && local.container_runtime) {
1001
+ removeAgentContainer(local.container_runtime, local.container_name, runner);
1002
+ log(`${s.agent}: removed stale container ${local.container_name} before host run`);
1003
+ }
832
1004
  const containerActive = containerMode && containerPrereqs && containerName
833
1005
  ? isContainerRunning(containerPrereqs.runtime, containerName, runner)
834
1006
  : false;
@@ -859,12 +1031,17 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
859
1031
  project: projectEntry,
860
1032
  thread,
861
1033
  sessionWritable,
1034
+ machineWritable: writable,
862
1035
  bin,
863
1036
  secretEnv: secretDelivery.env,
864
1037
  containerMode,
1038
+ pullImage: isPoolImageOptIn,
865
1039
  workdir,
866
1040
  runner,
867
1041
  probeSandbox: deps?.probeSandbox,
1042
+ sandboxReport: hostContainerProbe ?? undefined,
1043
+ onEc2,
1044
+ containerImdsBlocked: containerImdsOk,
868
1045
  startupJitterSeconds: deps?.startupJitterSeconds,
869
1046
  });
870
1047
  }
@@ -880,7 +1057,9 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
880
1057
  thread: started.thread,
881
1058
  thread_override_at: s.thread_override_at ?? null,
882
1059
  key_checked_at: state.sessions[s.id]?.key_checked_at ?? Date.now(),
883
- ...(containerMode && containerPrereqs && containerName ? { container_name: containerName, container_runtime: containerPrereqs.runtime } : {}),
1060
+ ...(containerMode && containerPrereqs && containerName
1061
+ ? { container_name: containerName, container_runtime: containerPrereqs.runtime, image_digest: containerPrereqs.bareDigest }
1062
+ : {}),
884
1063
  };
885
1064
  log(`${s.agent}: ${thread ? "adopted" : "started"} ${s.harness === "codex" ? "thread" : "session"} ${started.thread} in ${s.dir}`);
886
1065
  }
@@ -909,7 +1088,26 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
909
1088
  state.sessions[s.id].unpause_applied = s.unpause_at;
910
1089
  log(`${s.agent}: usage-limit pause lifted by the operator`);
911
1090
  }
912
- out.push({ id: s.id, state: "running", dir: s.dir, thread: th, watcher: watcherState, last_turn: lastTurnLine(s.agent), turn_judgment: s.turn_judgment ?? null, ...turnFacts(s.agent, s.harness, th, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR) });
1091
+ // A turn whose BenignSwarm activity cannot be sampled stays unverified and starts no further turn;
1092
+ // past one turn timeout that is a fault of its own, not an unproductive-turn fault. The watcher keeps
1093
+ // sampling, so the report clears by itself once the server answers.
1094
+ const unverified = verificationUnavailable(readState(s.agent).turn_guard, s.turn_timeout, Date.now());
1095
+ if (unverified) {
1096
+ out.push({ id: s.id, state: "error", dir: s.dir, thread: th, watcher: w && serviceActive(w) ? "active" : "inactive", error: `turn verification unavailable: ${unverified.last_error} (unverified since ${new Date(unverified.since).toISOString()}, ${unverified.attempts} failed samples); no new turns start until it is verified`.slice(0, 1000) });
1097
+ continue;
1098
+ }
1099
+ out.push({
1100
+ id: s.id,
1101
+ state: "running",
1102
+ dir: s.dir,
1103
+ thread: th,
1104
+ watcher: watcherState,
1105
+ last_turn: lastTurnLine(s.agent),
1106
+ turn_judgment: s.turn_judgment ?? null,
1107
+ image_digest: containerMode && containerPrereqs ? containerPrereqs.bareDigest : null,
1108
+ container_runtime: containerMode && containerPrereqs ? containerPrereqs.runtime : null,
1109
+ ...turnFacts(s.agent, s.harness, th, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR),
1110
+ });
913
1111
  }
914
1112
  catch (e) {
915
1113
  const error = e.message.slice(0, 1000);
@@ -998,7 +1196,12 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
998
1196
  }
999
1197
  }
1000
1198
  const workSpace = volumeSpace(actualWorkdir, "workdir");
1001
- const facts = machineFacts([...providerChecks], actualWorkdir, desired, me.machine?.cache_floor_pct ?? DEFAULT_CACHE_FLOOR_PCT);
1199
+ const facts = machineFacts([...providerChecks], {
1200
+ workdir: actualWorkdir,
1201
+ ec2Probe: () => onEc2,
1202
+ ...(imdsContainerProbe ? { containerImdsProbe: () => imdsContainerProbe } : {}),
1203
+ ...(hostContainerProbe ? { probes: { container: () => hostContainerProbe } } : {}),
1204
+ }, desired, me.machine?.cache_floor_pct ?? DEFAULT_CACHE_FLOOR_PCT);
1002
1205
  const environmentChecks = machineEnvironmentChecks({ ...facts, workdir_free_bytes: workSpace?.freeBytes ?? null, workdir_total_bytes: workSpace?.totalBytes ?? null }, writable)
1003
1206
  .map(({ check, status, observation, remedy, recovery_verified }) => ({ check, status, diagnosis: observation, remedy, recovery_verified, observed_at: new Date().toISOString() }));
1004
1207
  const dirtyClosedWorktrees = worktreePrune.flatMap((result) => Array.isArray(result.dirty_closed) ? result.dirty_closed.filter((item) => typeof item === "string") : []);
@@ -1024,23 +1227,87 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1024
1227
  maintenance: maintenanceReport(drainingUntil(), out),
1025
1228
  };
1026
1229
  const capabilities = {};
1230
+ const imageProbes = [];
1027
1231
  const probedProjects = [];
1028
1232
  for (const project of projects) {
1029
- const signature = JSON.stringify(project.capabilities);
1233
+ if (!project.capabilities.length)
1234
+ continue;
1235
+ const rawSessionDir = desired.find((s) => s.project_id === project.id && typeof s.dir === "string" && s.dir.trim().length > 0)?.dir?.trim() ?? "";
1236
+ const hostCaps = project.capabilities.filter((cap) => cap.scope !== "image");
1237
+ const imageCaps = project.capabilities.filter((cap) => cap.scope === "image");
1238
+ const hasImageCaps = imageCaps.length > 0;
1239
+ const imageGate = hasImageCaps
1240
+ ? resolveContainerImageProbePrereqs({
1241
+ project,
1242
+ sandboxReport: hostContainerProbe,
1243
+ onEc2,
1244
+ containerImdsBlocked: containerImdsOk,
1245
+ runner,
1246
+ })
1247
+ : null;
1248
+ const bare = imageGate?.bareDigest ?? bareDigestOf(resolvePinnedImageRef(project.image));
1249
+ const signature = JSON.stringify([
1250
+ project.capabilities,
1251
+ hasImageCaps ? bare : null,
1252
+ hasImageCaps ? hostContainerProbe?.runtime ?? null : null,
1253
+ imageGate ? (imageGate.ok ? "ok" : imageGate.reason) : null,
1254
+ hasImageCaps ? rawSessionDir : null,
1255
+ ]);
1030
1256
  const last = lastCapabilityProbe.get(project.id);
1031
1257
  if (last?.signature === signature && Date.now() - last.at < CAPABILITY_PROBE_MS)
1032
1258
  continue;
1033
- const projectDir = desired.find((s) => s.project_id === project.id && s.dir)?.dir ?? homedir();
1034
- if (!project.capabilities.length)
1035
- continue;
1036
- capabilities[project.id] = await probeCapabilities(project.capabilities, projectDir);
1037
- probedProjects.push(project.id);
1259
+ const byName = new Map();
1260
+ if (hostCaps.length) {
1261
+ for (const res of await probeCapabilities(hostCaps, rawSessionDir)) {
1262
+ byName.set(res.name, res);
1263
+ }
1264
+ }
1265
+ if (hasImageCaps && imageGate) {
1266
+ if (!imageGate.ok) {
1267
+ for (const cap of imageCaps) {
1268
+ byName.set(cap.name, { name: cap.name, ok: false, version: null, error: imageGate.reason });
1269
+ }
1270
+ }
1271
+ else {
1272
+ for (const res of await probeCapabilities(imageCaps, rawSessionDir, { container: imageGate.context })) {
1273
+ byName.set(res.name, res);
1274
+ }
1275
+ }
1276
+ }
1277
+ const probeResults = project.capabilities
1278
+ .map((cap) => byName.get(cap.name))
1279
+ .filter((res) => Boolean(res));
1280
+ capabilities[project.id] = probeResults;
1281
+ if (hasImageCaps && bare) {
1282
+ const imageScoped = imageCaps
1283
+ .map((cap) => byName.get(cap.name))
1284
+ .filter((res) => Boolean(res));
1285
+ if (imageScoped.length) {
1286
+ imageProbes.push({
1287
+ project_id: project.id,
1288
+ image_digest: bare,
1289
+ probes: imageScoped.map((res) => ({
1290
+ name: res.name,
1291
+ scope: "image",
1292
+ ok: res.ok,
1293
+ ...(res.version ? { version: res.version } : {}),
1294
+ ...(res.error ? { error: res.error } : {}),
1295
+ })),
1296
+ });
1297
+ }
1298
+ }
1299
+ probedProjects.push({ id: project.id, signature });
1038
1300
  log(`${project.name}: probed ${capabilities[project.id].length} declared capabilities`);
1039
1301
  }
1040
- await client.call("POST", "/machines/me/report", { report, report_interval_seconds: reportIntervalSeconds, sessions: out, capabilities });
1041
- for (const projectId of probedProjects) {
1042
- const declaration = projects.find((p) => p.id === projectId);
1043
- lastCapabilityProbe.set(projectId, { at: Date.now(), signature: JSON.stringify(declaration.capabilities) });
1302
+ await client.call("POST", "/machines/me/report", {
1303
+ report,
1304
+ report_interval_seconds: reportIntervalSeconds,
1305
+ sessions: out,
1306
+ capabilities,
1307
+ ...(imageProbes.length ? { image_probes: imageProbes } : {}),
1308
+ });
1309
+ for (const item of probedProjects) {
1310
+ lastCapabilityProbe.set(item.id, { at: Date.now(), signature: item.signature });
1044
1311
  }
1045
1312
  const warning = diskSpaceNotice(volumeSpace(homedir(), "home"), volumeSpace(workdir ?? join(homedir(), "bschat"), "workdir"));
1046
1313
  if (warning !== undefined)
@@ -1230,6 +1497,50 @@ export function errorText(s) {
1230
1497
  return redact(last).slice(0, 500);
1231
1498
  }
1232
1499
  }
1500
+ /** Unknown checks remain unknown: the scheduler must not infer a safe drain from missing evidence. */
1501
+ export function stoppedSessionFacts(dir, thread, gitStatus = (path) => {
1502
+ const result = spawnSync("git", ["-C", path, "status", "--porcelain", "--untracked-files=all"], { encoding: "utf8", timeout: 15_000 });
1503
+ return { status: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "" };
1504
+ }, processes = (path) => scanWorktreeProcesses(path, { project_roots: [path], foreign_roots: [] }), threadProbe, statPath = lstatSync) {
1505
+ let clean = null;
1506
+ let running = null;
1507
+ let absent = false;
1508
+ let error;
1509
+ if (dir) {
1510
+ let exists = false;
1511
+ try {
1512
+ statPath(dir);
1513
+ exists = true;
1514
+ }
1515
+ catch (e) {
1516
+ if (e.code === "ENOENT")
1517
+ absent = true;
1518
+ else
1519
+ error = `checkout lstat failed: ${e.code ?? "unknown error"}`;
1520
+ }
1521
+ if (exists) {
1522
+ try {
1523
+ const result = gitStatus(dir);
1524
+ if (result.status === 0)
1525
+ clean = result.stdout.trim().length === 0;
1526
+ else
1527
+ error = `git status failed: ${result.stderr.trim().slice(0, 200) || `exit ${result.status ?? "unknown"}`}`;
1528
+ }
1529
+ catch (e) {
1530
+ error = `git status failed: ${e.code ?? "unknown error"}`;
1531
+ }
1532
+ }
1533
+ try {
1534
+ const worktreeRunning = processes(absent ? dirname(dir) : dir).length > 0;
1535
+ running = worktreeRunning ? true : thread ? (threadProbe?.() ?? null) : false;
1536
+ }
1537
+ catch { /* Unknown stays unknown. */ }
1538
+ }
1539
+ // Pool moves start a fresh session: only a verified stopped turn and clean
1540
+ // checkout establish that the old thread may be left on this machine.
1541
+ const thread_ended = (clean === true || absent) && running === false ? true : running === true ? false : null;
1542
+ return { thread, checkout: { clean, ...(absent ? { state: "absent" } : error ? { state: "unknown", error } : {}) }, turn: { running, since: null }, thread_ended };
1543
+ }
1233
1544
  /** Whether the session has a turn running, its process, and a usage-limit pause still in force. */
1234
1545
  function turnFacts(agent, harness, thread, turnCap = DEFAULT_TURNS_PER_HOUR) {
1235
1546
  const ph = thread ? probeFor(harness, thread, agent).phase() : null;
@@ -1540,8 +1851,8 @@ function claudeReport(path = process.env.PATH ?? "", providersInUse = ["anthropi
1540
1851
  }
1541
1852
  /** What the operator needs to know about this machine, reported with every pass. */
1542
1853
  export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sessions = [], diskFloorPct = DEFAULT_CACHE_FLOOR_PCT) {
1543
- const workdir = typeof workdirOrOpts === "string" ? workdirOrOpts : undefined;
1544
1854
  const opts = typeof workdirOrOpts === "object" && workdirOrOpts !== null ? workdirOrOpts : {};
1855
+ const workdir = typeof workdirOrOpts === "string" ? workdirOrOpts : opts.workdir;
1545
1856
  const probes = opts.probes;
1546
1857
  const path = process.env.PATH ?? "";
1547
1858
  const env = { ...process.env, PATH: path };
@@ -1572,6 +1883,10 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
1572
1883
  const gitIdentity = (probes?.gitIdentity ?? (() => readGitIdentity()))();
1573
1884
  const container = (probes?.container ?? (() => probeNestedSandbox()))();
1574
1885
  const imds = (opts.imdsProbe ?? probeImdsIsolation)();
1886
+ const onEc2 = (opts.ec2Probe ?? detectEc2Host)();
1887
+ const containerImds = opts.containerImdsProbe
1888
+ ? opts.containerImdsProbe()
1889
+ : (container.runtime && onEc2 ? probeContainerImdsIsolation() : null);
1575
1890
  const managedHooks = (probes?.managedHooks ?? (() => existsSync(req) && isCodexManagedRequirements(readFileSync(req, "utf8"))))();
1576
1891
  const facts = {
1577
1892
  os: platform(), arch: arch(), hostname: hostname(), user: userInfo().username, cpus: cpus().length, mem_total_bytes: totalmem(),
@@ -1585,8 +1900,11 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
1585
1900
  daemon_path: path,
1586
1901
  bschat: { version: CLI_VERSION, bin: requireInstall().bin },
1587
1902
  git_identity: gitIdentity,
1903
+ on_ec2: onEc2,
1588
1904
  imds_blocked: imds.ok,
1589
1905
  imds_isolation: imds,
1906
+ container_imds_blocked: containerImds ? containerImds.ok : null,
1907
+ ...(containerImds ? { container_imds_isolation: containerImds } : {}),
1590
1908
  ...(container.runtime !== null || process.env.B9S_CLOUD_MACHINE === "1" ? { container_runtime: container } : {}),
1591
1909
  codex: codexFactsValue,
1592
1910
  "claude-code": claude,
@@ -1869,6 +2187,20 @@ export function prepare(opts = {}) {
1869
2187
  steps.push({ step: "codex hooks", result: "failed", detail: e.message });
1870
2188
  }
1871
2189
  }
2190
+ const cr = (opts.probeSandbox ?? probeNestedSandbox)();
2191
+ if (!cr.runtime) {
2192
+ steps.push({ step: "container runtime", result: "skipped", detail: "docker/podman not installed; project image pool sessions stay on host" });
2193
+ }
2194
+ else {
2195
+ const ec2 = (opts.detectEc2 ?? detectEc2Host)();
2196
+ const imds = ec2 ? (opts.probeImdsContainer ?? probeContainerImdsIsolation)() : { ok: true, detail: "not on EC2" };
2197
+ const archList = cr.architectures?.length ? cr.architectures.join(", ") : arch();
2198
+ const ok = cr.usable_without_root !== false && cr.nested_sandbox_ok && (!ec2 || imds.ok);
2199
+ const detail = !ok
2200
+ ? `${cr.runtime}${cr.usable_without_root === false ? " is not usable without root" : ""}${!cr.nested_sandbox_ok ? `; nested sandbox failed: ${cr.detail}` : ""}${ec2 && !imds.ok ? `; container IMDS not blocked: ${imds.detail}` : ""}`
2201
+ : `${cr.runtime} (${cr.rootless ? "rootless" : "daemon"}, non-root ok, arch ${archList}${ec2 ? ", EC2 container IMDS blocked" : ""})`;
2202
+ steps.push({ step: "container runtime", result: ok ? "ok" : "failed", detail });
2203
+ }
1872
2204
  return steps;
1873
2205
  }
1874
2206
  function sha256HexSync(data) {
@@ -121,7 +121,7 @@ export async function measure(p, out) {
121
121
  const target = str(p.flags, "target") ?? process.process.definition.merge.target_branch;
122
122
  if (!sha)
123
123
  throw new CliError("usage", "measure run <name> --sha <commit> [--target branch] [--rerun]");
124
- const result = await client.call("POST", `/projects/${project}/measures/${def.id}/runs`, { tested_sha: sha, target_branch: target, rerun: bool(p.flags, "rerun") });
124
+ const result = await client.call("POST", `/projects/${project}/measures/${def.id}/runs`, { client_id: randomUUID(), tested_sha: sha, target_branch: target, rerun: bool(p.flags, "rerun") }, { retries: 3 });
125
125
  out.print(result.run ? `queued ${name} as WU #${result.run.unit_number}` : result.queued ? `already queued ${name} as WU #${result.unit_number}` : `reusing value ${result.value_id}`, result);
126
126
  return;
127
127
  }