benignswarm 0.12.113 → 0.12.115

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
2
  import { FileFactsCache, scanLinesBackward, TAIL_CHUNK_BYTES, TAIL_MAX_BYTES } from "../tail-lines.js";
3
3
  import { rotateLogs } from "../log-rotation.js";
4
- import { createHash, createHmac } from "node:crypto";
5
- import { chmodSync, closeSync, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, readSync, realpathSync, rmSync, statSync, statfsSync, unlinkSync, writeFileSync } from "node:fs";
4
+ import { createHash, createHmac, randomBytes } from "node:crypto";
5
+ import { chmodSync, closeSync, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, statfsSync, unlinkSync, writeFileSync } from "node:fs";
6
6
  import { arch, cpus, freemem, homedir, hostname, loadavg, platform, tmpdir, totalmem, userInfo } from "node:os";
7
7
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
8
8
  import { str } from "../args.js";
@@ -24,9 +24,10 @@ import { defaultWorkspaceWritableRoots } from "../start-options.js";
24
24
  import { antigravityPath, antigravitySandboxPermissions, antigravityTurnArgs, antigravityTurnEnv, parseAntigravityJson } from "../antigravity.js";
25
25
  import { bootTimeMs } from "../boot-time.js";
26
26
  import { DEFAULT_CACHE_FLOOR_PCT, manageBuildCaches } from "../build-caches.js";
27
+ import { imageCacheBaseDir, imageCacheProjectRoot, projectsWithImageCaches } from "../image-caches.js";
27
28
  import { agentContainerName, agentContainerRunArgs, detectEc2Host, ensurePinnedImagePulled, isolatedBuildCommand, isolatedDevcontainerBuildCommand, isolatedImagePullCommands, isolatedSubprocessEnv, probeContainerImdsIsolation, networklessRuntimeWrapper, parseContainerRuntimeVersion, probeImdsIsolation, probeNestedSandbox, readGitIdentity, resolveSessionSecretDelivery, resolveWritableMounts, validateDevcontainerSpec, BUILD_SECRET_KEY_NAME_RE, BUILD_SECRET_CONTENT_RE, containsBuildSecretMaterial, sanitizeBuildDiagnosticText, } from "../container.js";
28
29
  import { machineEnvironmentChecks } from "../environment-checks.js";
29
- import { machineResourceTelemetry, parsePageSize } from "../machine-telemetry.js";
30
+ import { machineResourceTelemetry, measuredWatcherServiceMemoryLimits, parsePageSize } from "../machine-telemetry.js";
30
31
  import { macReadiness, macReadinessSteps } from "../macos-readiness.js";
31
32
  import { authorizeWorktreeScope, redactProcessCommand, scanWorktreeProcesses } from "../machine-processes.js";
32
33
  import { collectPruneProtection } from "../prune-protection.js";
@@ -45,10 +46,18 @@ export function loadMachine() {
45
46
  return JSON.parse(readFileSync(f, "utf8"));
46
47
  }
47
48
  const stateFile = () => join(configRoot(), "state", "machine.json");
48
- const readMachineState = () => (existsSync(stateFile()) ? JSON.parse(readFileSync(stateFile(), "utf8")) : { sessions: {} });
49
+ const readMachineState = () => {
50
+ const state = existsSync(stateFile()) ? JSON.parse(readFileSync(stateFile(), "utf8")) : { sessions: {} };
51
+ state.starting_sessions ??= {};
52
+ state.unsettled_turns ??= {};
53
+ return state;
54
+ };
49
55
  function writeMachineState(s) {
56
+ // Beside the file, then renamed: a daemon stopped mid-write leaves the previous state whole.
50
57
  mkdirSync(dirname(stateFile()), { recursive: true });
51
- writeFileSync(stateFile(), JSON.stringify(s, null, 2) + "\n");
58
+ const temp = `${stateFile()}.${process.pid}.tmp`;
59
+ writeFileSync(temp, JSON.stringify(s, null, 2) + "\n");
60
+ renameSync(temp, stateFile());
52
61
  }
53
62
  /** What a session's watcher is started with; a change means re-running codex start. */
54
63
  /**
@@ -733,19 +742,221 @@ function readContainerStart(logsDir, agentRef) {
733
742
  }
734
743
  return null;
735
744
  }
745
+ function writeJsonAtomically(file, value) {
746
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
747
+ const temp = `${file}.${process.pid}.tmp`;
748
+ writeFileSync(temp, `${JSON.stringify(value)}\n`, { mode: 0o600 });
749
+ renameSync(temp, file);
750
+ }
751
+ function readMachineStartResult(file) {
752
+ try {
753
+ const result = JSON.parse(readFileSync(file, "utf8"));
754
+ if (Number.isInteger(result.status) && typeof result.stdout === "string" && typeof result.stderr === "string")
755
+ return result;
756
+ }
757
+ catch { /* child has not atomically published a result yet */ }
758
+ return null;
759
+ }
760
+ /**
761
+ * How long a start may take: `b9s start` runs the first turn (for Antigravity to its end) and, for
762
+ * harnesses that check their sandbox in a turn of its own, that turn too. A fixed three minutes
763
+ * ended slow first turns and the retry started a second one beside the first.
764
+ */
765
+ export const startWaitMs = (s) => (2 * s.turn_timeout + 10) * 60_000;
766
+ /** A start whose child never identified itself within this long was never launched. */
767
+ const START_INTENT_GRACE_MS = 30_000;
768
+ const HARNESS_PROCESS_RE = /(^|[\/\s])(codex|claude|agy|antigravity|dsh)(\s|$)/;
769
+ function pidAlive(pid) {
770
+ if (!Number.isInteger(pid) || pid <= 1)
771
+ return false;
772
+ try {
773
+ process.kill(pid, 0);
774
+ return true;
775
+ }
776
+ catch {
777
+ return false;
778
+ }
779
+ }
780
+ /** The start time of a process as ps prints it, or null when there is no such process. */
781
+ export function processStartStamp(pid) {
782
+ if (!Number.isInteger(pid) || pid <= 1)
783
+ return null;
784
+ const r = spawnSync("ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", timeout: 5_000 });
785
+ const stamp = r.status === 0 ? (r.stdout ?? "").trim() : "";
786
+ return stamp || null;
787
+ }
788
+ /**
789
+ * Whether the start child this record names still runs. "unknown" is a live pid whose identity
790
+ * cannot be established (its start time was never read, or cannot be read now): it is not signalled,
791
+ * since it may be another process, and not treated as gone, since it may be the child about to
792
+ * begin a first turn. A record from before the start time was kept is judged by pid alone.
793
+ */
794
+ function startChildState(pending) {
795
+ if (!pidAlive(pending.pid))
796
+ return "gone";
797
+ if (pending.pid_started === undefined)
798
+ return "alive";
799
+ if (pending.pid_started === null)
800
+ return "unknown";
801
+ const stamp = processStartStamp(pending.pid);
802
+ if (stamp === null)
803
+ return pidAlive(pending.pid) ? "unknown" : "gone";
804
+ return stamp === pending.pid_started ? "alive" : "gone";
805
+ }
806
+ function startProgressState(pending) {
807
+ try {
808
+ const progress = JSON.parse(readFileSync(pending.progress_file, "utf8"));
809
+ return typeof progress.state === "string" ? progress.state : null;
810
+ }
811
+ catch {
812
+ return null;
813
+ }
814
+ }
815
+ function cleanupMachineStart(pending) {
816
+ for (const file of [pending.progress_file, pending.result_file, ...(pending.child_file ? [pending.child_file] : []), ...(pending.secret_files ?? [])])
817
+ rmSync(file, { force: true });
818
+ }
819
+ function adoptStartChild(pending) {
820
+ if (pending.pid !== 0)
821
+ return;
822
+ let childPid = 0;
823
+ try {
824
+ childPid = Number(JSON.parse(readFileSync(pending.child_file ?? "", "utf8")).pid) || 0;
825
+ }
826
+ catch { /* not launched, or not yet */ }
827
+ if (childPid > 1) {
828
+ pending.pid = childPid;
829
+ pending.pid_started = processStartStamp(childPid);
830
+ }
831
+ }
832
+ /**
833
+ * Takes a pending start down: its child, the watcher and container it may have made, then its
834
+ * files, then its record. The intent is saved first and the record stays until every part is
835
+ * confirmed gone, so a daemon stopped midway, a child slow to exit or a failed removal is taken up
836
+ * again on the next pass; nothing is started for the session meanwhile. It waits at most a second
837
+ * for the child, so several endings cannot hold up the machine report. Throws while incomplete.
838
+ */
839
+ async function endPendingStart(state, id, pending, reason, runner, log) {
840
+ if (!pending.ending) {
841
+ // A first turn that had begun may outlive its start; nothing new starts beside it.
842
+ if (startProgressState(pending) === "onboarding_turn_running" && pending.desired?.dir)
843
+ state.unsettled_turns[pending.desired.dir] = { since: pending.started_at };
844
+ pending.ending = { reason, since: new Date().toISOString() };
845
+ writeMachineState(state);
846
+ }
847
+ adoptStartChild(pending);
848
+ if (pending.pid === 0 && Date.now() - Date.parse(pending.started_at) <= START_INTENT_GRACE_MS) {
849
+ throw new Error(`${pending.ending.reason}; waiting to learn whether its start process was launched`);
850
+ }
851
+ // Only the process this record names is signalled: a pid that now belongs to something else is left alone.
852
+ const child = pending.pid > 1 && pending.pid !== process.pid ? startChildState(pending) : "gone";
853
+ if (child === "unknown")
854
+ throw new Error(`${pending.ending.reason}; process ${pending.pid} cannot be identified as its start process, so it is not signalled and nothing is started in its place until it has exited`);
855
+ if (child === "alive") {
856
+ const again = pending.ending.signalled_at !== undefined && Date.now() - Date.parse(pending.ending.signalled_at) >= 5_000;
857
+ const signal = again ? "SIGKILL" : "SIGTERM";
858
+ if (again || pending.ending.signalled_at === undefined) {
859
+ try {
860
+ process.kill(process.platform === "win32" ? pending.pid : -pending.pid, signal);
861
+ }
862
+ catch {
863
+ try {
864
+ process.kill(pending.pid, signal);
865
+ }
866
+ catch { /* already exited */ }
867
+ }
868
+ if (pending.ending.signalled_at === undefined) {
869
+ pending.ending.signalled_at = new Date().toISOString();
870
+ writeMachineState(state);
871
+ }
872
+ }
873
+ const until = Date.now() + 1_000;
874
+ while (startChildState(pending) !== "gone" && Date.now() < until)
875
+ await new Promise((resolve) => setTimeout(resolve, 50));
876
+ if (startChildState(pending) !== "gone")
877
+ throw new Error(`${pending.ending.reason}; its start process ${pending.pid} has not exited yet`);
878
+ }
879
+ const agent = pending.desired?.agent;
880
+ if (agent) {
881
+ const label = watchLabelOf(agent);
882
+ const watcher = watcherServices().find((service) => service.label === label);
883
+ if (watcher) {
884
+ removeService(watcher);
885
+ log(`${agent}: ${reason} (watcher removed)`);
886
+ }
887
+ }
888
+ if (pending.container_name && pending.container_runtime) {
889
+ const removed = removeAgentContainer(pending.container_runtime, pending.container_name, runner);
890
+ if (removed.status !== 0)
891
+ throw new Error(`${pending.ending.reason}; container ${pending.container_name} could not be removed: ${errorText(removed.stderr || removed.stdout || "the runtime gave no reason")}`);
892
+ log(`${agent ?? pending.container_name}: ${reason} (container ${pending.container_name} removed)`);
893
+ }
894
+ cleanupMachineStart(pending);
895
+ delete state.starting_sessions[id];
896
+ writeMachineState(state);
897
+ }
898
+ const startChildFile = (resultFile) => `${resultFile}.child`;
899
+ function startSessionChild(bin, cwd, options, resultFile) {
900
+ const ownGroup = process.platform !== "win32";
901
+ const child = spawn(bin, ["machine", "_start-session"], {
902
+ cwd,
903
+ env: { ...process.env, B9S_MACHINE_START_RESULT_FILE: resultFile, B9S_MACHINE_START_CHILD_FILE: startChildFile(resultFile), ...(ownGroup ? { B9S_MACHINE_START_OWN_GROUP: "1" } : {}) },
904
+ detached: ownGroup,
905
+ stdio: ["pipe", "ignore", "ignore"],
906
+ });
907
+ child.on("error", (error) => writeJsonAtomically(resultFile, { status: 1, stdout: "", stderr: `could not start session child: ${error.message}` }));
908
+ child.stdin?.on("error", () => { });
909
+ child.stdin?.end(JSON.stringify({ ...options, runner: undefined, probeSandbox: undefined }));
910
+ return child.pid ?? -1;
911
+ }
912
+ async function launchSessionChildCommand() {
913
+ const resultFile = process.env.B9S_MACHINE_START_RESULT_FILE;
914
+ if (!resultFile)
915
+ throw new CliError("usage", "internal machine start child requires its result path");
916
+ const childFile = process.env.B9S_MACHINE_START_CHILD_FILE;
917
+ if (childFile)
918
+ writeJsonAtomically(childFile, { pid: process.pid });
919
+ const chunks = [];
920
+ for await (const chunk of process.stdin)
921
+ chunks.push(Buffer.from(chunk));
922
+ let result;
923
+ try {
924
+ const options = JSON.parse(Buffer.concat(chunks).toString("utf8"));
925
+ const launched = await launchDesiredSession({ ...options, runner: syncRunner });
926
+ result = { status: launched.status ?? 1, stdout: launched.stdout ?? "", stderr: launched.stderr || (launched.status === null ? `b9s start did not finish within ${Math.round(startWaitMs(options.s) / 60_000)} minutes and was stopped` : "") };
927
+ }
928
+ catch (error) {
929
+ result = { status: 1, stdout: "", stderr: error.message || String(error) };
930
+ }
931
+ if (result.status !== 0)
932
+ await endOwnProcessGroup();
933
+ writeJsonAtomically(resultFile, result);
934
+ }
736
935
  /**
737
- * Launches a desired session either inside an isolated per-agent container (using
738
- * `agentContainerRunArgs` + pinned `@sha256:` project image + fail-closed nested sandbox check
739
- * + `--in-container` detached watcher supervision) or directly on the host when container
740
- * isolation is not active for owned local machines.
936
+ * A failed or timed-out start must not leave a harness turn running behind it: the turn a harness
937
+ * runs inside `b9s start` shares this child's process group, and the next start would run a second
938
+ * one beside it. Turns that a harness detaches into their own group are found by the daemon's
939
+ * unsettled-turn check instead.
741
940
  */
941
+ async function endOwnProcessGroup() {
942
+ if (process.env.B9S_MACHINE_START_OWN_GROUP !== "1")
943
+ return;
944
+ const ignore = () => { };
945
+ process.on("SIGTERM", ignore);
946
+ try {
947
+ process.kill(-process.pid, "SIGTERM");
948
+ }
949
+ catch { /* no other member is left */ }
950
+ await new Promise((resolve) => setTimeout(resolve, 1_500));
951
+ process.off("SIGTERM", ignore);
952
+ }
742
953
  export async function launchDesiredSession(opts) {
743
954
  const runner = opts.runner ?? syncRunner;
744
955
  if (!opts.containerMode) {
745
956
  return runner(opts.bin, startArgs(opts.s, opts.thread, opts.sessionWritable, opts.startupJitterSeconds), {
746
957
  cwd: opts.s.dir,
747
- timeout: 180_000,
748
- env: { ...process.env, ...opts.secretEnv },
958
+ timeout: startWaitMs(opts.s),
959
+ env: { ...process.env, ...opts.secretEnv, ...(opts.progressFile ? { BSCHAT_MACHINE_START_PROGRESS_FILE: opts.progressFile } : {}) },
749
960
  });
750
961
  }
751
962
  const { runtime, imageDigest } = resolveContainerLaunchPrereqs({
@@ -804,13 +1015,14 @@ export async function launchDesiredSession(opts) {
804
1015
  writableFolders: rawWritable,
805
1016
  platform: opts.project?.image?.target_arch,
806
1017
  allowedCaches: opts.project?.image?.allowed_caches ?? [],
807
- cacheRootDir: join(opts.workdir ?? join(homedir(), "bschat"), ".caches", opts.accountId),
1018
+ cacheRootDir: imageCacheProjectRoot(opts.accountId, opts.project?.id ?? opts.s.project ?? "account"),
808
1019
  detach: true,
809
1020
  extraEnv: {
810
1021
  ...opts.secretEnv,
811
1022
  B9S_URL: opts.m.url,
812
1023
  B9S_AGENT: opts.s.agent,
813
1024
  B9S_HOME: "/home/agent/.b9s",
1025
+ ...(opts.containerProgressFile ? { BSCHAT_MACHINE_START_PROGRESS_FILE: opts.containerProgressFile } : {}),
814
1026
  },
815
1027
  command: ["b9s", ...startArgs(opts.s, opts.thread, opts.s.sandbox === "workspace-write" ? containerWritablePaths : [], opts.startupJitterSeconds), "--in-container"],
816
1028
  });
@@ -821,7 +1033,7 @@ export async function launchDesiredSession(opts) {
821
1033
  });
822
1034
  if (launchRes.status !== 0)
823
1035
  return launchRes;
824
- const deadline = Date.now() + (Number(process.env.B9S_CONTAINER_START_TIMEOUT_MS) || 120_000);
1036
+ const deadline = Date.now() + (Number(process.env.B9S_CONTAINER_START_TIMEOUT_MS) || startWaitMs(opts.s));
825
1037
  while (Date.now() < deadline) {
826
1038
  const err = readContainerError(logsDir, opts.s.agent);
827
1039
  if (err) {
@@ -917,16 +1129,20 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
917
1129
  for (const s of desired) {
918
1130
  const label = watchLabelOf(s.agent);
919
1131
  const svc = () => watcherServices().find((w) => w.label === label);
1132
+ let preflightDone = false;
920
1133
  try {
921
1134
  if (s.desired === "benched") {
922
1135
  const local = state.sessions[s.id];
1136
+ const pending = state.starting_sessions?.[s.id];
1137
+ if (pending)
1138
+ await endPendingStart(state, s.id, pending, "benched", runner, log);
923
1139
  const w = svc();
924
1140
  const reason = `benched by ${s.benched_by ?? "the operator"}${s.benched_at ? ` at ${s.benched_at}` : ""}${s.bench_note ? `: ${s.bench_note}` : ""}`;
925
1141
  if (w) {
926
1142
  removeService(w);
927
1143
  log(`${s.agent}: ${reason}; watcher removed`);
928
1144
  }
929
- if (local?.container_name && local.container_runtime) {
1145
+ if (local?.container_name && local.container_runtime && !(pending?.container_name === local.container_name && pending.container_runtime === local.container_runtime)) {
930
1146
  removeAgentContainer(local.container_runtime, local.container_name, runner);
931
1147
  log(`${s.agent}: ${reason}; container ${local.container_name} removed`);
932
1148
  }
@@ -935,12 +1151,15 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
935
1151
  }
936
1152
  if (s.desired === "stopped") {
937
1153
  const local = state.sessions[s.id];
1154
+ const pending = state.starting_sessions?.[s.id];
1155
+ if (pending)
1156
+ await endPendingStart(state, s.id, pending, "stopped", runner, log);
938
1157
  const w = svc();
939
1158
  if (w) {
940
1159
  removeService(w);
941
1160
  log(`${s.agent}: stopped (watcher removed)`);
942
1161
  }
943
- if (local?.container_name && local.container_runtime) {
1162
+ if (local?.container_name && local.container_runtime && !(pending?.container_name === local.container_name && pending.container_runtime === local.container_runtime)) {
944
1163
  removeAgentContainer(local.container_runtime, local.container_name, runner);
945
1164
  log(`${s.agent}: stopped (container ${local.container_name} removed)`);
946
1165
  }
@@ -992,7 +1211,102 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
992
1211
  }
993
1212
  if (!existsSync(s.dir))
994
1213
  throw new Error(`checkout ${s.dir} does not exist on this machine`);
995
- const local = state.sessions[s.id];
1214
+ let local = state.sessions[s.id];
1215
+ const pendingStart = state.starting_sessions?.[s.id];
1216
+ preflightDone = true;
1217
+ let neverLaunched = false;
1218
+ if (pendingStart) {
1219
+ let result = readMachineStartResult(pendingStart.result_file);
1220
+ const ageMs = Date.now() - Date.parse(pendingStart.started_at);
1221
+ const endPending = async (reason) => {
1222
+ await endPendingStart(state, s.id, pendingStart, reason, runner, log);
1223
+ throw new Error(reason);
1224
+ };
1225
+ if (pendingStart.ending) {
1226
+ // An ending begun on an earlier pass: finish it (it throws while incomplete), then start afresh.
1227
+ await endPendingStart(state, s.id, pendingStart, pendingStart.ending.reason, runner, log);
1228
+ neverLaunched = true;
1229
+ result = null;
1230
+ }
1231
+ else if (!result && pendingStart.pid === 0) {
1232
+ // The daemon stopped between recording the intent and recording the child. The child
1233
+ // names itself in its own file as its first act, so it is found here if it was launched.
1234
+ adoptStartChild(pendingStart);
1235
+ if (pendingStart.pid !== 0)
1236
+ writeMachineState(state);
1237
+ else if (ageMs > START_INTENT_GRACE_MS) {
1238
+ delete state.starting_sessions[s.id];
1239
+ writeMachineState(state);
1240
+ cleanupMachineStart(pendingStart);
1241
+ neverLaunched = true;
1242
+ log(`${s.agent}: a recorded start was never launched (the daemon stopped first); starting it now`);
1243
+ }
1244
+ }
1245
+ if (neverLaunched) {
1246
+ // Falls through to the ordinary launch decision below.
1247
+ }
1248
+ else if (!result) {
1249
+ if (pendingStart.pid !== 0 && startChildState(pendingStart) === "gone")
1250
+ await endPending("tracked b9s start process exited before returning a session or failure reason");
1251
+ const limitMs = startWaitMs(pendingStart.desired ?? s) + 120_000;
1252
+ if (ageMs > limitMs)
1253
+ await endPending(`b9s start did not finish within ${Math.round(limitMs / 60_000)} minutes and was stopped`);
1254
+ const detail = startProgressState(pendingStart) === "onboarding_turn_running" ? "onboarding turn running" : "starting";
1255
+ out.push({
1256
+ id: s.id, state: "preparing", dir: s.dir, thread: pendingStart.thread, detail,
1257
+ image_digest: pendingStart.image_digest ?? extractPinnedImageDigest(pendingStart.image_reference),
1258
+ image_reference: pendingStart.image_reference ?? null,
1259
+ container_runtime: pendingStart.container_runtime
1260
+ ? { runtime: pendingStart.container_runtime, version: pendingStart.container_runtime_version ?? null }
1261
+ : null,
1262
+ });
1263
+ continue;
1264
+ }
1265
+ else {
1266
+ // The child writes this result only after launchDesiredSession has returned, so its
1267
+ // file-based credentials have already been consumed. The outcome is saved before the
1268
+ // result file goes: a daemon that stops in between must find one of the two.
1269
+ if (result.status !== 0)
1270
+ await endPending(`b9s start failed: ${errorText(result.stderr || result.stdout)}`);
1271
+ let started;
1272
+ try {
1273
+ const parsed = JSON.parse(result.stdout);
1274
+ if (typeof parsed.thread !== "string" || !parsed.thread)
1275
+ throw new Error("no session id in it");
1276
+ started = { thread: parsed.thread };
1277
+ }
1278
+ catch (error) {
1279
+ // A success that names no session cannot be promoted; it ends like any failed start.
1280
+ started = await endPending(`b9s start reported success without a usable result (${error.message})`);
1281
+ }
1282
+ const startedWritable = s.sandbox === "workspace-write" ? [...new Set([...defaultWorkspaceWritableRoots(), ...writable])] : writable;
1283
+ const completedDesired = pendingStart.desired ?? s;
1284
+ state.sessions[s.id] = {
1285
+ label,
1286
+ fingerprint: sessionFingerprint({ ...completedDesired, thread: started.thread }, pendingStart.writable ?? startedWritable, pendingStart.image_reference !== undefined ? pendingStart.image_reference : pinnedImageRef),
1287
+ thread: started.thread,
1288
+ thread_override_at: completedDesired.thread_override_at ?? null,
1289
+ key_checked_at: local?.key_checked_at ?? Date.now(),
1290
+ ...(pendingStart.container_name && pendingStart.container_runtime ? {
1291
+ container_name: pendingStart.container_name,
1292
+ container_runtime: pendingStart.container_runtime,
1293
+ container_runtime_version: pendingStart.container_runtime_version ?? null,
1294
+ image_digest: pendingStart.image_digest ?? extractPinnedImageDigest(pendingStart.image_reference),
1295
+ image_reference: pendingStart.image_reference ?? null,
1296
+ } : {}),
1297
+ };
1298
+ local = state.sessions[s.id];
1299
+ delete state.starting_sessions[s.id];
1300
+ // Codex and Claude Code report a started session while its first turn still runs on its
1301
+ // own. That turn stays on record past this point, so a stop or removal followed by a fresh
1302
+ // start in this checkout waits for it instead of running beside it.
1303
+ if (startProgressState(pendingStart) === "onboarding_turn_running")
1304
+ state.unsettled_turns[s.dir] = { since: pendingStart.started_at };
1305
+ writeMachineState(state);
1306
+ cleanupMachineStart(pendingStart);
1307
+ log(`${s.agent}: ${pendingStart.thread ? "adopted" : "started"} ${s.harness === "codex" ? "thread" : "session"} ${started.thread} in ${s.dir}`);
1308
+ }
1309
+ }
996
1310
  let agentState = readState(s.agent, agentStateEnv);
997
1311
  if (s.turn_resume_at && agentState.turn_resume_applied_at !== s.turn_resume_at) {
998
1312
  agentState = { ...agentState, turn_guard: resumeTurnGuard(agentState.turn_guard), turn_resume_applied_at: s.turn_resume_at };
@@ -1059,46 +1373,52 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1059
1373
  out.push(held);
1060
1374
  continue;
1061
1375
  }
1376
+ const unsettled = state.unsettled_turns?.[s.dir];
1377
+ if (unsettled) {
1378
+ // An earlier start ended after its first turn began. While that turn's process still
1379
+ // runs in this checkout, a new session would put a second first turn beside it.
1380
+ const since = Date.parse(unsettled.since) - 60_000;
1381
+ const survivors = containerMode ? [] : processScanner(s.dir, { project_roots: [s.dir], foreign_roots: [] })
1382
+ .filter((proc) => HARNESS_PROCESS_RE.test(proc.command) && Date.parse(proc.started_at) >= since);
1383
+ if (thread === null && survivors.length) {
1384
+ out.push({ id: s.id, state: "preparing", dir: s.dir, thread: null, detail: `the first turn of an earlier start is still running here (pid ${survivors.map((proc) => proc.pid).join(", ")}); no second one starts until it ends` });
1385
+ continue;
1386
+ }
1387
+ delete state.unsettled_turns[s.dir];
1388
+ }
1062
1389
  const secretDelivery = resolveSessionSecretDelivery({
1063
1390
  session: s,
1064
1391
  secrets: me.harness_secrets ?? [],
1065
1392
  targetDir: join(configRoot(), "providers", "ephemeral"),
1393
+ runner: deps?.runner,
1066
1394
  });
1067
- let r;
1068
- try {
1069
- r = await launchDesiredSession({
1070
- m,
1071
- accountId,
1072
- s,
1073
- project: projectEntry,
1074
- thread,
1075
- sessionWritable,
1076
- machineWritable: writable,
1077
- bin,
1078
- secretEnv: secretDelivery.env,
1079
- containerMode,
1080
- pullImage: isPoolImageOptIn,
1081
- workdir,
1082
- runner,
1083
- probeSandbox: deps?.probeSandbox,
1084
- sandboxReport: hostContainerProbe ?? undefined,
1085
- onEc2,
1086
- containerImdsBlocked: containerImdsOk,
1087
- startupJitterSeconds: deps?.startupJitterSeconds,
1088
- });
1089
- }
1090
- finally {
1091
- secretDelivery.cleanup();
1092
- }
1093
- if (r.status !== 0)
1094
- throw new Error(`b9s start failed: ${errorText(r.stderr || r.stdout)}`);
1095
- const started = JSON.parse(r.stdout);
1096
- state.sessions[s.id] = {
1097
- label,
1098
- fingerprint: sessionFingerprint({ ...s, thread: started.thread }, s.sandbox === "workspace-write" ? sessionWritable : [], pinnedImageRef),
1099
- thread: started.thread,
1100
- thread_override_at: s.thread_override_at ?? null,
1101
- key_checked_at: state.sessions[s.id]?.key_checked_at ?? Date.now(),
1395
+ const startId = createHash("sha256").update(s.id).digest("hex").slice(0, 24);
1396
+ const progressDir = containerMode ? join(agentHomeDirOf(s), ".b9s", "logs") : join(configRoot(), "state", "machine-start");
1397
+ mkdirSync(progressDir, { recursive: true, mode: 0o700 });
1398
+ const progressFile = join(progressDir, `start-${startId}.json`);
1399
+ // What the daemon trusts (the child's identity, the outcome) stays in host-private state:
1400
+ // a containerised session can write its own home, and only the progress note lives there.
1401
+ // The name is per attempt, so nothing an earlier child wrote is read as this one's.
1402
+ const privateDir = join(configRoot(), "state", "machine-start");
1403
+ mkdirSync(privateDir, { recursive: true, mode: 0o700 });
1404
+ const resultFile = join(privateDir, `result-${startId}-${randomBytes(6).toString("hex")}.json`);
1405
+ writeJsonAtomically(progressFile, { state: "starting", at: new Date().toISOString() });
1406
+ const launchOptions = {
1407
+ m, accountId, s, project: projectEntry, thread, sessionWritable, machineWritable: writable,
1408
+ bin, secretEnv: secretDelivery.env, containerMode, pullImage: isPoolImageOptIn, workdir,
1409
+ sandboxReport: hostContainerProbe ?? undefined, onEc2, containerImdsBlocked: containerImdsOk,
1410
+ startupJitterSeconds: deps?.startupJitterSeconds,
1411
+ progressFile: containerMode ? undefined : progressFile,
1412
+ containerProgressFile: containerMode ? `/home/agent/.b9s/logs/start-${startId}.json` : undefined,
1413
+ };
1414
+ rmSync(startChildFile(resultFile), { force: true });
1415
+ // The intent is on disk before anything is launched, so a daemon that stops at any point
1416
+ // from here finds either this record, the child's own file, or the result: never nothing.
1417
+ const pending = {
1418
+ pid: 0, pid_started: null, started_at: new Date().toISOString(), progress_file: progressFile, result_file: resultFile,
1419
+ child_file: startChildFile(resultFile),
1420
+ secret_files: secretDelivery.files, fingerprint: fp, thread, desired: s,
1421
+ writable: sessionWritable, image_digest: pinnedImageRef,
1102
1422
  ...(containerMode && containerPrereqs && containerName
1103
1423
  ? {
1104
1424
  container_name: containerName,
@@ -1109,7 +1429,41 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1109
1429
  }
1110
1430
  : {}),
1111
1431
  };
1112
- log(`${s.agent}: ${thread ? "adopted" : "started"} ${s.harness === "codex" ? "thread" : "session"} ${started.thread} in ${s.dir}`);
1432
+ state.starting_sessions[s.id] = pending;
1433
+ try {
1434
+ writeMachineState(state);
1435
+ }
1436
+ catch (error) {
1437
+ delete state.starting_sessions[s.id];
1438
+ secretDelivery.cleanup();
1439
+ throw error;
1440
+ }
1441
+ try {
1442
+ pending.pid = (deps?.startTrackedSession ?? ((childBin, options, result) => startSessionChild(childBin, s.dir, options, result)))(bin, launchOptions, resultFile);
1443
+ }
1444
+ catch (error) {
1445
+ delete state.starting_sessions[s.id];
1446
+ writeMachineState(state);
1447
+ cleanupMachineStart(pending);
1448
+ throw error;
1449
+ }
1450
+ pending.pid_started = processStartStamp(pending.pid);
1451
+ try {
1452
+ writeMachineState(state);
1453
+ }
1454
+ catch (error) {
1455
+ // The record on disk still says pid 0; the child's own file lets the next pass find and end or adopt it.
1456
+ throw error;
1457
+ }
1458
+ out.push({
1459
+ id: s.id, state: "preparing", dir: s.dir, thread: thread ?? null, detail: "starting",
1460
+ image_digest: extractPinnedImageDigest(pinnedImageRef),
1461
+ image_reference: pinnedImageRef ?? null,
1462
+ container_runtime: containerPrereqs
1463
+ ? { runtime: containerPrereqs.runtime, version: containerPrereqs.version }
1464
+ : null,
1465
+ });
1466
+ continue;
1113
1467
  }
1114
1468
  else if (containerMode && state.sessions[s.id] && state.sessions[s.id].image_reference === undefined) {
1115
1469
  const localSession = state.sessions[s.id];
@@ -1200,7 +1554,18 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1200
1554
  });
1201
1555
  }
1202
1556
  catch (e) {
1203
- const error = e.message.slice(0, 1000);
1557
+ let error = e.message.slice(0, 1000);
1558
+ const stranded = preflightDone ? undefined : state.starting_sessions?.[s.id];
1559
+ if (stranded && !stranded.ending) {
1560
+ // The session as now asked for cannot run here, and a start made for its earlier form is
1561
+ // still pending: that start is ended, not left running behind the error.
1562
+ try {
1563
+ await endPendingStart(state, s.id, stranded, "the session can no longer start as it was asked", runner, log);
1564
+ }
1565
+ catch (ending) {
1566
+ error = `${error}; ${ending.message}`.slice(0, 1000);
1567
+ }
1568
+ }
1204
1569
  log(`${s.agent}: ${error}`);
1205
1570
  const environmentCheck = e.environment_check;
1206
1571
  out.push({ id: s.id, state: "error", thread: state.sessions[s.id]?.thread ?? null, error, ...(typeof environmentCheck === "string" ? { environment_check: environmentCheck } : {}) });
@@ -1210,24 +1575,36 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1210
1575
  for (const [id, local] of Object.entries(state.sessions)) {
1211
1576
  if (desired.some((s) => s.id === id))
1212
1577
  continue;
1578
+ const pending = state.starting_sessions?.[id];
1213
1579
  const w = watcherServices().find((x) => x.label === local.label);
1214
1580
  if (w) {
1215
1581
  removeService(w);
1216
1582
  log(`${local.label}: session removed by the operator; watcher removed`);
1217
1583
  }
1218
- if (local.container_name && local.container_runtime) {
1584
+ if (local.container_name && local.container_runtime && !(pending?.container_name === local.container_name && pending.container_runtime === local.container_runtime)) {
1219
1585
  removeAgentContainer(local.container_runtime, local.container_name, runner);
1220
1586
  log(`${local.label}: session removed by the operator; container ${local.container_name} removed`);
1221
1587
  }
1222
1588
  delete state.sessions[id];
1223
1589
  }
1590
+ for (const [id, pending] of Object.entries(state.starting_sessions ?? {})) {
1591
+ if (desired.some((s) => s.id === id))
1592
+ continue;
1593
+ // One ending that cannot finish yet must not cost the other sessions their report; it is taken up again next pass.
1594
+ try {
1595
+ await endPendingStart(state, id, pending, "session removed by the operator", runner, log);
1596
+ }
1597
+ catch (error) {
1598
+ log(`${pending.desired?.agent ?? id}: ${error.message}`);
1599
+ }
1600
+ }
1224
1601
  writeMachineState(state);
1225
1602
  const protectedWorktrees = [...new Set(desired.map((s) => s.dir).filter((d) => Boolean(d)))];
1226
1603
  const buildCaches = manageBuildCaches({
1227
1604
  budgetGb: me.machine?.cache_budget_gb ?? null,
1228
1605
  floorPct: me.machine?.cache_floor_pct ?? null,
1229
1606
  machineCaches: me.machine?.build_caches ?? [],
1230
- projects,
1607
+ projects: projectsWithImageCaches(accountId, projects, imageCacheBaseDir()),
1231
1608
  workdir,
1232
1609
  protectedWorktrees,
1233
1610
  });
@@ -2100,6 +2477,14 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
2100
2477
  const macSwap = macSwapResult?.status === 0 ? macSwapResult.stdout ?? null : null;
2101
2478
  const macVmStat = macVmStatResult?.status === 0 ? macVmStatResult.stdout ?? null : null;
2102
2479
  const telemetry = machineResourceTelemetry(hostPlatform, readTelemetryFile, pageSize, macSwap, macVmStat);
2480
+ if (hostPlatform === "linux") {
2481
+ const watcherUnits = watcherServices().filter((service) => service.kind === "systemd" && service.label.startsWith(WATCH_LABEL_PREFIX)).map((service) => `${service.label}.service`);
2482
+ const limits = watcherUnits.length
2483
+ ? spawnSync("systemctl", ["--user", "show", "--property=Id", "--property=ControlGroup", "--property=MemoryMax", "--no-pager", ...watcherUnits], { encoding: "utf8", timeout: 3_000 })
2484
+ : { status: 0, stdout: "" };
2485
+ const group = telemetry.agent_cgroup_pressure;
2486
+ group.watcher_service_memory_limits = measuredWatcherServiceMemoryLimits(watcherUnits, limits.status === 0 ? limits.stdout ?? "" : null, readTelemetryFile);
2487
+ }
2103
2488
  const telemetryAvailability = telemetry.metric_availability;
2104
2489
  const volumeFloorPct = diskFloorPct;
2105
2490
  const req = "/etc/codex/requirements.toml";
@@ -2687,6 +3072,8 @@ export function handleDeviceLoginRequests(client, requests, log, inFlight = defa
2687
3072
  }
2688
3073
  export async function machine(p, out) {
2689
3074
  const sub = p.positionals[1];
3075
+ if (sub === "_start-session")
3076
+ return launchSessionChildCommand();
2690
3077
  if (sub === "processes") {
2691
3078
  const creds = loadAgent(resolveAgentName(str(p.flags, "as")));
2692
3079
  if (!creds.project)