benignswarm 0.12.114 → 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.
- package/dist/commands/codex-start.js +17 -3
- package/dist/commands/machine-admin.js +5 -0
- package/dist/commands/machine.js +439 -53
- package/dist/commands/watch.js +62 -4
- package/dist/container.js +4 -4
- package/dist/help.js +2 -2
- package/dist/install.js +39 -2
- package/dist/machine-telemetry.js +63 -0
- package/dist/version.js +1 -1
- package/dist/watcher-memory.js +32 -0
- package/package.json +1 -1
|
@@ -23,6 +23,19 @@ import { antigravityConversationDb, antigravityLog, antigravityResumeCommand, an
|
|
|
23
23
|
import { configureGitCredentialForWorktree } from "./git-credential.js";
|
|
24
24
|
const SANDBOXES = ["read-only", "workspace-write", "danger-full-access"];
|
|
25
25
|
export const DEFAULT_CLAUDE_MAX_BUDGET_USD = 1;
|
|
26
|
+
/** The guard states why it refuses. A refusal without a reason is still a refusal (no turn starts) and is reported as the defect it is. */
|
|
27
|
+
function refusalReason(diagnostic) {
|
|
28
|
+
return diagnostic.at(-1) ?? "the turn guard refused this turn without stating why; that is a CLI defect, report it with b9s feedback";
|
|
29
|
+
}
|
|
30
|
+
function reportMachineStartProgress(state) {
|
|
31
|
+
const file = process.env.BSCHAT_MACHINE_START_PROGRESS_FILE;
|
|
32
|
+
if (!file)
|
|
33
|
+
return;
|
|
34
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
35
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
36
|
+
writeFileSync(temp, `${JSON.stringify({ state, at: new Date().toISOString() })}\n`, { mode: 0o600 });
|
|
37
|
+
renameSync(temp, file);
|
|
38
|
+
}
|
|
26
39
|
/**
|
|
27
40
|
* `b9s start` (and `b9s codex start`): one command that brings an agent up on this machine
|
|
28
41
|
* headless, with no app involved, so it works the same over ssh on a remote machine. It enrolls the
|
|
@@ -246,8 +259,9 @@ export async function harnessStart(p, out, harness) {
|
|
|
246
259
|
].join("\n");
|
|
247
260
|
const diagnostic = [];
|
|
248
261
|
if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (m) => diagnostic.push(m), process.env, unproductivePerHour, process.env.BSCHAT_MACHINE_SESSION_ID, harness))) {
|
|
249
|
-
throw new CliError("turn_mode_fault", diagnostic
|
|
262
|
+
throw new CliError("turn_mode_fault", refusalReason(diagnostic));
|
|
250
263
|
}
|
|
264
|
+
reportMachineStartProgress("onboarding_turn_running");
|
|
251
265
|
try {
|
|
252
266
|
if (harness === "codex") {
|
|
253
267
|
session = await startThread(bin, ["exec", "--json", ...settings, prompt], firstTurnLog, ref);
|
|
@@ -569,7 +583,7 @@ export function runClaudeSandboxSelfCheck(bin, settings, maxBudgetUsd, env, cwd,
|
|
|
569
583
|
export async function runGuardedClaudeSandboxSelfCheck(ref, turnsPerHour, bin, settings, maxBudgetUsd, env, cwd, session, run = runClaudeSandboxSelfCheck, unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR) {
|
|
570
584
|
const diagnostic = [];
|
|
571
585
|
if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (message) => diagnostic.push(message), process.env, unproductivePerHour, process.env.BSCHAT_MACHINE_SESSION_ID, "claude-code"))) {
|
|
572
|
-
throw new CliError("turn_mode_fault", diagnostic
|
|
586
|
+
throw new CliError("turn_mode_fault", refusalReason(diagnostic));
|
|
573
587
|
}
|
|
574
588
|
const probe = probeFor("claude-code", session, ref);
|
|
575
589
|
let result;
|
|
@@ -620,7 +634,7 @@ export function assertAntigravitySelfCheck(output) {
|
|
|
620
634
|
export async function runAntigravitySandboxSelfCheck(ref, bin, settings, cwd, session, model, effort, timeoutSeconds, logPath, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = antigravityTurnEnv("workspace-write"), unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR) {
|
|
621
635
|
const diagnostic = [];
|
|
622
636
|
if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (message) => diagnostic.push(message), process.env, unproductivePerHour, process.env.BSCHAT_MACHINE_SESSION_ID, "antigravity"))) {
|
|
623
|
-
throw new CliError("turn_mode_fault", diagnostic
|
|
637
|
+
throw new CliError("turn_mode_fault", refusalReason(diagnostic));
|
|
624
638
|
}
|
|
625
639
|
const prompt = [
|
|
626
640
|
"BenignSwarm sandbox startup check. Use your terminal tool to execute these two commands separately, exactly as written:",
|
|
@@ -236,8 +236,13 @@ export async function machineAdmin(action, rest, p, out) {
|
|
|
236
236
|
const rep = liveReport ?? m.report ?? {};
|
|
237
237
|
const pressureText = (pressure) => `some ${pressure?.some_avg10 ?? "unknown"}% / full ${pressure?.full_avg10 ?? "unknown"}% (10s avg)`;
|
|
238
238
|
const agentPressure = rep.agent_cgroup_pressure;
|
|
239
|
+
const limitText = (value) => value === "max" ? "unlimited" : value === 0 ? "0 bytes" : typeof value === "number" ? `${(value / 1024 ** 3).toFixed(1)} GiB` : "unknown";
|
|
240
|
+
const cgroupMemory = agentPressure?.memory_limits;
|
|
241
|
+
const watcherMemory = agentPressure?.watcher_service_memory_limits;
|
|
239
242
|
const head = [
|
|
240
243
|
...[['I/O', 'io_pressure'], ['Memory', 'memory_pressure'], ['CPU', 'cpu_pressure']].map(([label, key]) => ` ${label} PSI host: ${pressureText(rep[key])}; agents: ${agentPressure?.status === "available" ? `${pressureText(agentPressure[key])} (${agentPressure.source})` : `${agentPressure?.status ?? "unknown"}; host PSI used when available`}${liveReport ? "" : "; live sample unavailable"}`),
|
|
244
|
+
cgroupMemory ? ` app.slice memory limits: ${cgroupMemory.status}; MemoryHigh ${limitText(cgroupMemory.memory_high_bytes)}; MemoryMax ${limitText(cgroupMemory.memory_max_bytes)}; MemorySwapMax ${limitText(cgroupMemory.memory_swap_max_bytes)}` : null,
|
|
245
|
+
...(Array.isArray(watcherMemory?.services) ? watcherMemory.services.map((service) => ` watcher ${String(service.unit ?? "unknown").replace(/^org\.benignswarm\.watch\./, "")}: ${service.status}; measured MemoryMax ${limitText(service.effective_memory_max_bytes)}; configured ${limitText(service.configured_memory_max_bytes)}; current ${limitText(service.memory_current_bytes)}`) : []),
|
|
241
246
|
`${m.name}: last report ${m.last_report_at ?? "never"}; labels ${(m.labels ?? []).join(", ") || "(none)"}; slots ${m.slots ?? "auto"}; writable ${(m.writable ?? []).join(", ") || "-"}; workdir ${rep.workdir ?? m.workdir ?? "~/bschat"}${rep.workdir_free_bytes ? ` (${Math.round(rep.workdir_free_bytes / 1e9)} GB free)` : ""}; cache budget ${m.cache_budget_gb ?? 40} GB (floor ${m.cache_floor_pct ?? 15}%)`,
|
|
242
247
|
rep.os ? ` ${rep.os}/${rep.arch} ${rep.hostname} as ${rep.user}; ${rep.cpus ?? "?"} CPUs, ${rep.mem_total_bytes ? `${Math.round(rep.mem_total_bytes / 1024 ** 3)} GB RAM` : "? RAM"}; b9s ${rep.bschat?.version}; codex ${rep.codex ? `${rep.codex.version}, ${rep.codex.logged_in ? "logged in" : "NOT logged in"}, sandbox ${rep.codex.sandbox ? (rep.codex.sandbox.ok ? "ok" : `FAILS (${rep.codex.sandbox.error})`) : "?"}` : "missing"}; hooks ${rep.managed_hooks ? "managed by policy" : "user-level"}; linger ${rep.linger ?? "n/a"}; disk free ${rep.disk_free_bytes ? `${Math.round(rep.disk_free_bytes / 1e9)} GB` : "?"}` : " (no report yet: is its daemon running?)",
|
|
243
248
|
rep.os ? ` Antigravity: ${rep.antigravity ? `${rep.antigravity.version ?? "agy"}, ${rep.antigravity.available ? "available" : "unavailable"}, ${rep.antigravity.logged_in ? "logged in" : "not logged in"}, sandbox ${rep.antigravity.sandbox ? (rep.antigravity.sandbox.ok ? "ok" : `FAILS (${rep.antigravity.sandbox.error})`) : "not checked"}` : "not installed"}` : null,
|
package/dist/commands/machine.js
CHANGED
|
@@ -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";
|
|
@@ -27,7 +27,7 @@ import { DEFAULT_CACHE_FLOOR_PCT, manageBuildCaches } from "../build-caches.js";
|
|
|
27
27
|
import { imageCacheBaseDir, imageCacheProjectRoot, projectsWithImageCaches } from "../image-caches.js";
|
|
28
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";
|
|
29
29
|
import { machineEnvironmentChecks } from "../environment-checks.js";
|
|
30
|
-
import { machineResourceTelemetry, parsePageSize } from "../machine-telemetry.js";
|
|
30
|
+
import { machineResourceTelemetry, measuredWatcherServiceMemoryLimits, parsePageSize } from "../machine-telemetry.js";
|
|
31
31
|
import { macReadiness, macReadinessSteps } from "../macos-readiness.js";
|
|
32
32
|
import { authorizeWorktreeScope, redactProcessCommand, scanWorktreeProcesses } from "../machine-processes.js";
|
|
33
33
|
import { collectPruneProtection } from "../prune-protection.js";
|
|
@@ -46,10 +46,18 @@ export function loadMachine() {
|
|
|
46
46
|
return JSON.parse(readFileSync(f, "utf8"));
|
|
47
47
|
}
|
|
48
48
|
const stateFile = () => join(configRoot(), "state", "machine.json");
|
|
49
|
-
const readMachineState = () =>
|
|
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
|
+
};
|
|
50
55
|
function writeMachineState(s) {
|
|
56
|
+
// Beside the file, then renamed: a daemon stopped mid-write leaves the previous state whole.
|
|
51
57
|
mkdirSync(dirname(stateFile()), { recursive: true });
|
|
52
|
-
|
|
58
|
+
const temp = `${stateFile()}.${process.pid}.tmp`;
|
|
59
|
+
writeFileSync(temp, JSON.stringify(s, null, 2) + "\n");
|
|
60
|
+
renameSync(temp, stateFile());
|
|
53
61
|
}
|
|
54
62
|
/** What a session's watcher is started with; a change means re-running codex start. */
|
|
55
63
|
/**
|
|
@@ -734,19 +742,221 @@ function readContainerStart(logsDir, agentRef) {
|
|
|
734
742
|
}
|
|
735
743
|
return null;
|
|
736
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
|
+
}
|
|
737
935
|
/**
|
|
738
|
-
*
|
|
739
|
-
* `
|
|
740
|
-
*
|
|
741
|
-
*
|
|
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.
|
|
742
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
|
+
}
|
|
743
953
|
export async function launchDesiredSession(opts) {
|
|
744
954
|
const runner = opts.runner ?? syncRunner;
|
|
745
955
|
if (!opts.containerMode) {
|
|
746
956
|
return runner(opts.bin, startArgs(opts.s, opts.thread, opts.sessionWritable, opts.startupJitterSeconds), {
|
|
747
957
|
cwd: opts.s.dir,
|
|
748
|
-
timeout:
|
|
749
|
-
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 } : {}) },
|
|
750
960
|
});
|
|
751
961
|
}
|
|
752
962
|
const { runtime, imageDigest } = resolveContainerLaunchPrereqs({
|
|
@@ -812,6 +1022,7 @@ export async function launchDesiredSession(opts) {
|
|
|
812
1022
|
B9S_URL: opts.m.url,
|
|
813
1023
|
B9S_AGENT: opts.s.agent,
|
|
814
1024
|
B9S_HOME: "/home/agent/.b9s",
|
|
1025
|
+
...(opts.containerProgressFile ? { BSCHAT_MACHINE_START_PROGRESS_FILE: opts.containerProgressFile } : {}),
|
|
815
1026
|
},
|
|
816
1027
|
command: ["b9s", ...startArgs(opts.s, opts.thread, opts.s.sandbox === "workspace-write" ? containerWritablePaths : [], opts.startupJitterSeconds), "--in-container"],
|
|
817
1028
|
});
|
|
@@ -822,7 +1033,7 @@ export async function launchDesiredSession(opts) {
|
|
|
822
1033
|
});
|
|
823
1034
|
if (launchRes.status !== 0)
|
|
824
1035
|
return launchRes;
|
|
825
|
-
const deadline = Date.now() + (Number(process.env.B9S_CONTAINER_START_TIMEOUT_MS) ||
|
|
1036
|
+
const deadline = Date.now() + (Number(process.env.B9S_CONTAINER_START_TIMEOUT_MS) || startWaitMs(opts.s));
|
|
826
1037
|
while (Date.now() < deadline) {
|
|
827
1038
|
const err = readContainerError(logsDir, opts.s.agent);
|
|
828
1039
|
if (err) {
|
|
@@ -918,16 +1129,20 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
918
1129
|
for (const s of desired) {
|
|
919
1130
|
const label = watchLabelOf(s.agent);
|
|
920
1131
|
const svc = () => watcherServices().find((w) => w.label === label);
|
|
1132
|
+
let preflightDone = false;
|
|
921
1133
|
try {
|
|
922
1134
|
if (s.desired === "benched") {
|
|
923
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);
|
|
924
1139
|
const w = svc();
|
|
925
1140
|
const reason = `benched by ${s.benched_by ?? "the operator"}${s.benched_at ? ` at ${s.benched_at}` : ""}${s.bench_note ? `: ${s.bench_note}` : ""}`;
|
|
926
1141
|
if (w) {
|
|
927
1142
|
removeService(w);
|
|
928
1143
|
log(`${s.agent}: ${reason}; watcher removed`);
|
|
929
1144
|
}
|
|
930
|
-
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)) {
|
|
931
1146
|
removeAgentContainer(local.container_runtime, local.container_name, runner);
|
|
932
1147
|
log(`${s.agent}: ${reason}; container ${local.container_name} removed`);
|
|
933
1148
|
}
|
|
@@ -936,12 +1151,15 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
936
1151
|
}
|
|
937
1152
|
if (s.desired === "stopped") {
|
|
938
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);
|
|
939
1157
|
const w = svc();
|
|
940
1158
|
if (w) {
|
|
941
1159
|
removeService(w);
|
|
942
1160
|
log(`${s.agent}: stopped (watcher removed)`);
|
|
943
1161
|
}
|
|
944
|
-
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)) {
|
|
945
1163
|
removeAgentContainer(local.container_runtime, local.container_name, runner);
|
|
946
1164
|
log(`${s.agent}: stopped (container ${local.container_name} removed)`);
|
|
947
1165
|
}
|
|
@@ -993,7 +1211,102 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
993
1211
|
}
|
|
994
1212
|
if (!existsSync(s.dir))
|
|
995
1213
|
throw new Error(`checkout ${s.dir} does not exist on this machine`);
|
|
996
|
-
|
|
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
|
+
}
|
|
997
1310
|
let agentState = readState(s.agent, agentStateEnv);
|
|
998
1311
|
if (s.turn_resume_at && agentState.turn_resume_applied_at !== s.turn_resume_at) {
|
|
999
1312
|
agentState = { ...agentState, turn_guard: resumeTurnGuard(agentState.turn_guard), turn_resume_applied_at: s.turn_resume_at };
|
|
@@ -1060,46 +1373,52 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
1060
1373
|
out.push(held);
|
|
1061
1374
|
continue;
|
|
1062
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
|
+
}
|
|
1063
1389
|
const secretDelivery = resolveSessionSecretDelivery({
|
|
1064
1390
|
session: s,
|
|
1065
1391
|
secrets: me.harness_secrets ?? [],
|
|
1066
1392
|
targetDir: join(configRoot(), "providers", "ephemeral"),
|
|
1393
|
+
runner: deps?.runner,
|
|
1067
1394
|
});
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
throw new Error(`b9s start failed: ${errorText(r.stderr || r.stdout)}`);
|
|
1096
|
-
const started = JSON.parse(r.stdout);
|
|
1097
|
-
state.sessions[s.id] = {
|
|
1098
|
-
label,
|
|
1099
|
-
fingerprint: sessionFingerprint({ ...s, thread: started.thread }, s.sandbox === "workspace-write" ? sessionWritable : [], pinnedImageRef),
|
|
1100
|
-
thread: started.thread,
|
|
1101
|
-
thread_override_at: s.thread_override_at ?? null,
|
|
1102
|
-
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,
|
|
1103
1422
|
...(containerMode && containerPrereqs && containerName
|
|
1104
1423
|
? {
|
|
1105
1424
|
container_name: containerName,
|
|
@@ -1110,7 +1429,41 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
1110
1429
|
}
|
|
1111
1430
|
: {}),
|
|
1112
1431
|
};
|
|
1113
|
-
|
|
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;
|
|
1114
1467
|
}
|
|
1115
1468
|
else if (containerMode && state.sessions[s.id] && state.sessions[s.id].image_reference === undefined) {
|
|
1116
1469
|
const localSession = state.sessions[s.id];
|
|
@@ -1201,7 +1554,18 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
1201
1554
|
});
|
|
1202
1555
|
}
|
|
1203
1556
|
catch (e) {
|
|
1204
|
-
|
|
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
|
+
}
|
|
1205
1569
|
log(`${s.agent}: ${error}`);
|
|
1206
1570
|
const environmentCheck = e.environment_check;
|
|
1207
1571
|
out.push({ id: s.id, state: "error", thread: state.sessions[s.id]?.thread ?? null, error, ...(typeof environmentCheck === "string" ? { environment_check: environmentCheck } : {}) });
|
|
@@ -1211,17 +1575,29 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
1211
1575
|
for (const [id, local] of Object.entries(state.sessions)) {
|
|
1212
1576
|
if (desired.some((s) => s.id === id))
|
|
1213
1577
|
continue;
|
|
1578
|
+
const pending = state.starting_sessions?.[id];
|
|
1214
1579
|
const w = watcherServices().find((x) => x.label === local.label);
|
|
1215
1580
|
if (w) {
|
|
1216
1581
|
removeService(w);
|
|
1217
1582
|
log(`${local.label}: session removed by the operator; watcher removed`);
|
|
1218
1583
|
}
|
|
1219
|
-
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)) {
|
|
1220
1585
|
removeAgentContainer(local.container_runtime, local.container_name, runner);
|
|
1221
1586
|
log(`${local.label}: session removed by the operator; container ${local.container_name} removed`);
|
|
1222
1587
|
}
|
|
1223
1588
|
delete state.sessions[id];
|
|
1224
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
|
+
}
|
|
1225
1601
|
writeMachineState(state);
|
|
1226
1602
|
const protectedWorktrees = [...new Set(desired.map((s) => s.dir).filter((d) => Boolean(d)))];
|
|
1227
1603
|
const buildCaches = manageBuildCaches({
|
|
@@ -2101,6 +2477,14 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
|
|
|
2101
2477
|
const macSwap = macSwapResult?.status === 0 ? macSwapResult.stdout ?? null : null;
|
|
2102
2478
|
const macVmStat = macVmStatResult?.status === 0 ? macVmStatResult.stdout ?? null : null;
|
|
2103
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
|
+
}
|
|
2104
2488
|
const telemetryAvailability = telemetry.metric_availability;
|
|
2105
2489
|
const volumeFloorPct = diskFloorPct;
|
|
2106
2490
|
const req = "/etc/codex/requirements.toml";
|
|
@@ -2688,6 +3072,8 @@ export function handleDeviceLoginRequests(client, requests, log, inFlight = defa
|
|
|
2688
3072
|
}
|
|
2689
3073
|
export async function machine(p, out) {
|
|
2690
3074
|
const sub = p.positionals[1];
|
|
3075
|
+
if (sub === "_start-session")
|
|
3076
|
+
return launchSessionChildCommand();
|
|
2691
3077
|
if (sub === "processes") {
|
|
2692
3078
|
const creds = loadAgent(resolveAgentName(str(p.flags, "as")));
|
|
2693
3079
|
if (!creds.project)
|
package/dist/commands/watch.js
CHANGED
|
@@ -7,7 +7,7 @@ import { applyAck } from "./wake.js";
|
|
|
7
7
|
import { launchdSessionTypeXml, lingerEnabled, plistLaunchdDomain, loadSystemdUnit, reloadLaunchAgent, removeService, requireInstall, systemdUnit, systemdUserDir, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
|
|
8
8
|
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statfsSync, writeFileSync } from "node:fs";
|
|
9
9
|
import { createHash } from "node:crypto";
|
|
10
|
-
import { homedir, userInfo } from "node:os";
|
|
10
|
+
import { homedir, totalmem, userInfo } from "node:os";
|
|
11
11
|
import { basename, dirname, join } from "node:path";
|
|
12
12
|
import { bool, str } from "../args.js";
|
|
13
13
|
import { configRoot, loadAgent, resolveAgentName } from "../config.js";
|
|
@@ -27,6 +27,8 @@ import { sessionUsage } from "../usage.js";
|
|
|
27
27
|
import { collectPruneProtection } from "../prune-protection.js";
|
|
28
28
|
import { bootTimeMs } from "../boot-time.js";
|
|
29
29
|
import { DEFAULT_WATCH_STARTUP_JITTER_SECONDS, MAX_WATCH_STARTUP_JITTER_SECONDS, waitForWatcherStartup } from "../startup-jitter.js";
|
|
30
|
+
import { macMemoryFloorRefusal, parseMemoryEvents } from "../watcher-memory.js";
|
|
31
|
+
import { parseMacVmStat, parsePageSize } from "../machine-telemetry.js";
|
|
30
32
|
function omitMeasuresAlreadyIn(text, updates) {
|
|
31
33
|
if (!text)
|
|
32
34
|
return updates;
|
|
@@ -754,6 +756,43 @@ export function diskFloorRefusal(paths, statfs = (p) => statfsSync(p)) {
|
|
|
754
756
|
}
|
|
755
757
|
return null;
|
|
756
758
|
}
|
|
759
|
+
/** cgroup-v2 OOM counter for this watcher service, if systemd placed it in a unified hierarchy. */
|
|
760
|
+
export function currentWatcherOomKillCount(readText = (path) => {
|
|
761
|
+
try {
|
|
762
|
+
return readFileSync(path, "utf8");
|
|
763
|
+
}
|
|
764
|
+
catch {
|
|
765
|
+
return null;
|
|
766
|
+
}
|
|
767
|
+
}) {
|
|
768
|
+
const cgroup = readText("/proc/self/cgroup");
|
|
769
|
+
const path = /^0::(\/[\w./@:-]+)$/m.exec(cgroup ?? "")?.[1];
|
|
770
|
+
if (!path || path.split("/").includes(".."))
|
|
771
|
+
return null;
|
|
772
|
+
const events = readText(`/sys/fs/cgroup${path}/memory.events`);
|
|
773
|
+
return events === null ? null : parseMemoryEvents(events)?.oomKill ?? null;
|
|
774
|
+
}
|
|
775
|
+
export function cgroupOomFailureReason(exit, before, after) {
|
|
776
|
+
const failed = exit.signal !== null || exit.code !== 0;
|
|
777
|
+
return failed && before !== undefined && after !== null && after > before
|
|
778
|
+
? `systemd watcher cgroup OOM-killed the turn (memory.events oom_kill increased from ${before} to ${after})`
|
|
779
|
+
: null;
|
|
780
|
+
}
|
|
781
|
+
function macTurnMemoryFloorRefusal() {
|
|
782
|
+
const pageSizeResult = spawnSync("sysctl", ["-n", "hw.pagesize"], { encoding: "utf8", timeout: 2_000 });
|
|
783
|
+
const vmStatResult = spawnSync("vm_stat", [], { encoding: "utf8", timeout: 2_000 });
|
|
784
|
+
const pageSize = pageSizeResult.status === 0 ? parsePageSize(pageSizeResult.stdout ?? "") : null;
|
|
785
|
+
const memory = vmStatResult.status === 0 ? parseMacVmStat(vmStatResult.stdout ?? "", pageSize) : null;
|
|
786
|
+
return macMemoryFloorRefusal(totalmem(), memory?.available_bytes ?? null);
|
|
787
|
+
}
|
|
788
|
+
function turnMemoryFloorAllows(log) {
|
|
789
|
+
if (process.platform !== "darwin")
|
|
790
|
+
return true;
|
|
791
|
+
const refusal = macTurnMemoryFloorRefusal();
|
|
792
|
+
if (refusal)
|
|
793
|
+
log(`no new turn starts: ${refusal}; turns are checked again on the next poll`);
|
|
794
|
+
return refusal === null;
|
|
795
|
+
}
|
|
757
796
|
function diskFloorAllowsTurn(log, env) {
|
|
758
797
|
const refusal = diskFloorRefusal([process.cwd(), configRoot(env)]);
|
|
759
798
|
if (refusal !== lastDiskRefusal) {
|
|
@@ -769,7 +808,7 @@ function diskFloorAllowsTurn(log, env) {
|
|
|
769
808
|
* leaves the wake-up unacknowledged on the server, so a wake path that keeps failing shows as
|
|
770
809
|
* broken; one that runs past --turn-timeout is stopped and logged.
|
|
771
810
|
*/
|
|
772
|
-
export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = process.env, unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR, harness) {
|
|
811
|
+
export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = process.env, unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR, harness, oomKillCounter = currentWatcherOomKillCount) {
|
|
773
812
|
const debug = (message) => { if (env.BSCHAT_WATCH_DEBUG === "1")
|
|
774
813
|
log(`debug poll: ${message}`); };
|
|
775
814
|
const turn = ctl.turn;
|
|
@@ -794,6 +833,9 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
|
|
|
794
833
|
error = `could not read the harness result: ${e.message}`;
|
|
795
834
|
}
|
|
796
835
|
}
|
|
836
|
+
const oomReason = cgroupOomFailureReason(turn.exit, turn.oomKillCountBefore, turn.exit.code !== 0 || turn.exit.signal !== null ? oomKillCounter() : null);
|
|
837
|
+
if (oomReason)
|
|
838
|
+
error = oomReason;
|
|
797
839
|
if (turn.exit.code === 0 && !error) {
|
|
798
840
|
if (!turn.confirmed)
|
|
799
841
|
await ackTurn(name, turn.seq, log, env);
|
|
@@ -950,6 +992,10 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
|
|
|
950
992
|
debug("no inbox poll: a volume is below its disk floor; session and pending wake are preserved");
|
|
951
993
|
return;
|
|
952
994
|
}
|
|
995
|
+
if (!turnMemoryFloorAllows(log)) {
|
|
996
|
+
debug("no inbox poll: the macOS available-memory floor is not met; session and pending wake are preserved");
|
|
997
|
+
return;
|
|
998
|
+
}
|
|
953
999
|
const st = readState(name, env);
|
|
954
1000
|
if (st.watch_pending) {
|
|
955
1001
|
debug(`no inbox poll: wake-up ${st.watch_pending.seq ?? "(legacy)"} is still pending`);
|
|
@@ -957,8 +1003,18 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
|
|
|
957
1003
|
log(`wake-up ${st.watch_pending.seq !== undefined ? `#${st.watch_pending.seq} ` : ""}was never answered and no turn is running; a turn replaces it`);
|
|
958
1004
|
writeState(name, { ...st, watch_pending: undefined, watch_dormant_logged_at: undefined }, env);
|
|
959
1005
|
}
|
|
960
|
-
|
|
961
|
-
|
|
1006
|
+
let oomKillCountBefore = null;
|
|
1007
|
+
await wake((t) => {
|
|
1008
|
+
if (oomKillCountBefore !== null)
|
|
1009
|
+
t.oomKillCountBefore = oomKillCountBefore;
|
|
1010
|
+
ctl.turn = t;
|
|
1011
|
+
}, async () => {
|
|
1012
|
+
if (!turnMemoryFloorAllows(log))
|
|
1013
|
+
return false;
|
|
1014
|
+
const allowed = await beginTurnGuardAttempt(name, turnsPerHour, log, env, unproductivePerHour, env.BSCHAT_MACHINE_SESSION_ID, harness);
|
|
1015
|
+
if (allowed)
|
|
1016
|
+
oomKillCountBefore = oomKillCounter();
|
|
1017
|
+
return allowed;
|
|
962
1018
|
});
|
|
963
1019
|
}
|
|
964
1020
|
async function turnActivity(name, env) {
|
|
@@ -1012,6 +1068,8 @@ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = proce
|
|
|
1012
1068
|
}
|
|
1013
1069
|
if (!diskFloorAllowsTurn(log, env))
|
|
1014
1070
|
return false;
|
|
1071
|
+
if (!turnMemoryFloorAllows(log))
|
|
1072
|
+
return false;
|
|
1015
1073
|
const before = await turnActivity(name, env);
|
|
1016
1074
|
current = readState(name, env);
|
|
1017
1075
|
if (current.turn_guard?.fault) {
|
package/dist/container.js
CHANGED
|
@@ -1039,8 +1039,8 @@ export function fetchAwsSecretToEphemeralFile(opts) {
|
|
|
1039
1039
|
}
|
|
1040
1040
|
/**
|
|
1041
1041
|
* Resolves the most specific Secrets Manager reference (project-scoped before account-wide,
|
|
1042
|
-
* matching provider before 'default') and materializes it into an ephemeral 0600 key file
|
|
1043
|
-
*
|
|
1042
|
+
* matching provider before 'default') and materializes it into an ephemeral 0600 key file.
|
|
1043
|
+
* Callers launching a tracked child retain that file until the child exits, then clean it up.
|
|
1044
1044
|
*/
|
|
1045
1045
|
export function resolveSessionSecretDelivery(opts) {
|
|
1046
1046
|
const provider = opts.session.provider ?? "anthropic";
|
|
@@ -1048,7 +1048,7 @@ export function resolveSessionSecretDelivery(opts) {
|
|
|
1048
1048
|
.filter((x) => x.harness === opts.session.harness && (x.provider === provider || x.provider === "default") && (!x.project_id || x.project_id === opts.session.project_id))
|
|
1049
1049
|
.sort((a, b) => (b.project_id ? 1 : 0) - (a.project_id ? 1 : 0) || (b.provider === provider ? 1 : 0) - (a.provider === provider ? 1 : 0))[0];
|
|
1050
1050
|
if (!match)
|
|
1051
|
-
return { env: {}, cleanup: () => { } };
|
|
1051
|
+
return { env: {}, files: [], cleanup: () => { } };
|
|
1052
1052
|
const fetched = fetchAwsSecretToEphemeralFile({
|
|
1053
1053
|
secretArn: match.secret_arn,
|
|
1054
1054
|
region: match.region,
|
|
@@ -1066,5 +1066,5 @@ export function resolveSessionSecretDelivery(opts) {
|
|
|
1066
1066
|
env.ANTHROPIC_API_KEY = value;
|
|
1067
1067
|
else
|
|
1068
1068
|
env.B9S_HARNESS_CREDENTIAL_FILE = fetched.path;
|
|
1069
|
-
return { env, cleanup: fetched.cleanup };
|
|
1069
|
+
return { env, files: [fetched.path], cleanup: fetched.cleanup };
|
|
1070
1070
|
}
|
package/dist/help.js
CHANGED
|
@@ -271,7 +271,7 @@ Machine placement shares capacity across the account's projects: session seats a
|
|
|
271
271
|
JUnit requires context JSON (source, invocation, runner, run); JSON reports include those fields
|
|
272
272
|
b9s test-results show <run-id> show the stored run, outcome counts, and original report evidence
|
|
273
273
|
b9s retire --title t (--body b | --body-file f) [--handoff-to @x|@role:y] [--evidence id,id] --yes
|
|
274
|
-
save a RESUME or HANDOFF note,
|
|
274
|
+
save a RESUME or HANDOFF note, revoke keys and remove machine sessions; revival does not restore sessions
|
|
275
275
|
b9s handoffs [--open] [--agent a] notes left by retired agents (open = not yet picked up)
|
|
276
276
|
b9s handoffs show <id> | pickup <id>
|
|
277
277
|
b9s lists [--account] shared lists (open/total, your unread count)
|
|
@@ -328,7 +328,7 @@ the returned object and warning, then exits 3. Inspect the object and do not ret
|
|
|
328
328
|
b9s-admin agent list <project>
|
|
329
329
|
b9s-admin agent bench <project>/<agent> [--note <text>] suspend keys and free an active seat
|
|
330
330
|
b9s-admin agent unbench <project>/<agent> restore keys if a seat is available
|
|
331
|
-
b9s-admin agent retire <project>/<agent> [--note <text> | --note-file <file>] --yes revoke keys, release
|
|
331
|
+
b9s-admin agent retire <project>/<agent> [--note <text> | --note-file <file>] --yes revoke keys, remove machine sessions, release units, optionally save a resume handoff
|
|
332
332
|
b9s-admin agent away <project>/<agent> (--for <minutes|hours> | --until <ISO timestamp>) --reason "why"
|
|
333
333
|
b9s-admin agent back <project>/<agent>
|
|
334
334
|
b9s-admin enroll create <project> [--name n | --prefix p] [--role r] [--uses n] [--expires-hours h] prints the invite text
|
package/dist/install.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { spawnSync } from "node:child_process";
|
|
2
2
|
import { accessSync, constants, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
|
|
3
|
-
import { homedir, userInfo } from "node:os";
|
|
3
|
+
import { homedir, totalmem, userInfo } from "node:os";
|
|
4
4
|
import { basename, delimiter, dirname, join, resolve } from "node:path";
|
|
5
5
|
import { configRoot } from "./config.js";
|
|
6
6
|
import { CliError } from "./errors.js";
|
|
7
7
|
import { cmp } from "./update.js";
|
|
8
8
|
import { CLI_VERSION } from "./version.js";
|
|
9
|
+
import { watcherMemoryLimits } from "./watcher-memory.js";
|
|
9
10
|
export const installFile = () => join(configRoot(), "install.json");
|
|
10
11
|
export function readInstall() {
|
|
11
12
|
const p = installFile();
|
|
@@ -465,9 +466,16 @@ export function rewriteServiceInstall(s, installBin) {
|
|
|
465
466
|
if (!/^# bschat-args: .*$/m.test(original) || !/^ExecStart=.*$/m.test(original)) {
|
|
466
467
|
throw new CliError("service_unreadable", `${s.label} has no recognized service command metadata`);
|
|
467
468
|
}
|
|
468
|
-
|
|
469
|
+
let updated = original
|
|
469
470
|
.replace(/^# bschat-args: .*$/m, `# bschat-args: ${JSON.stringify(nextArgs)}`)
|
|
470
471
|
.replace(/^ExecStart=.*$/m, `ExecStart=${nextArgs.map(systemdQuote).join(" ")}`);
|
|
472
|
+
if (s.label.startsWith(WATCH_LABEL_PREFIX)) {
|
|
473
|
+
const limits = watcherMemoryLimits(totalmem());
|
|
474
|
+
if (!limits)
|
|
475
|
+
throw new CliError("memory_limits_unavailable", "cannot determine physical RAM; refusing to leave an uncapped Linux watcher");
|
|
476
|
+
updated = updated.replace(/^Slice=.*\n/gm, "").replace(/^MemoryMax=.*\n/gm, "");
|
|
477
|
+
updated = updated.replace(/^\[Install\]$/m, `Slice=app.slice\nMemoryMax=${limits.unitMaxBytes}\n\n[Install]`);
|
|
478
|
+
}
|
|
471
479
|
writeFileSync(s.path, updated);
|
|
472
480
|
return original;
|
|
473
481
|
}
|
|
@@ -516,6 +524,15 @@ export async function restartInstallServices(installBin, services = watcherServi
|
|
|
516
524
|
else
|
|
517
525
|
matching.push(service);
|
|
518
526
|
}
|
|
527
|
+
if (matching.some((service) => service.kind === "systemd" && service.label.startsWith(WATCH_LABEL_PREFIX))) {
|
|
528
|
+
try {
|
|
529
|
+
ensureWatcherSliceMemoryLimits();
|
|
530
|
+
}
|
|
531
|
+
catch (error) {
|
|
532
|
+
notRestarted.push(`Linux watcher memory limits were not applied; services were not restarted: ${error.message}`);
|
|
533
|
+
return { restarted, not_restarted: notRestarted };
|
|
534
|
+
}
|
|
535
|
+
}
|
|
519
536
|
const rewritten = [];
|
|
520
537
|
for (const service of matching) {
|
|
521
538
|
try {
|
|
@@ -560,6 +577,7 @@ export async function restartInstallServices(installBin, services = watcherServi
|
|
|
560
577
|
* watcher only, never a Codex turn it started (turns run in their own process group, like on macOS).
|
|
561
578
|
*/
|
|
562
579
|
export function systemdUnit(label, args, cwd, env, logDir, slug = label.slice(WATCH_LABEL_PREFIX.length)) {
|
|
580
|
+
const memoryLimits = label.startsWith(WATCH_LABEL_PREFIX) ? watcherMemoryLimits(totalmem()) : null;
|
|
563
581
|
return [
|
|
564
582
|
`# Written by b9s; re-run its b9s watch ... --service (or b9s codex start) to change it.`,
|
|
565
583
|
`# bschat-args: ${JSON.stringify(args)}`,
|
|
@@ -576,6 +594,7 @@ export function systemdUnit(label, args, cwd, env, logDir, slug = label.slice(WA
|
|
|
576
594
|
`RestartPreventExitStatus=78`,
|
|
577
595
|
`RestartSec=5`,
|
|
578
596
|
`KillMode=process`,
|
|
597
|
+
...(memoryLimits ? [`Slice=app.slice`, `MemoryMax=${memoryLimits.unitMaxBytes}`] : []),
|
|
579
598
|
`StandardOutput=append:${join(logDir, `watch.${slug}.out.log`)}`,
|
|
580
599
|
`StandardError=append:${join(logDir, `watch.${slug}.err.log`)}`,
|
|
581
600
|
``,
|
|
@@ -589,6 +608,8 @@ export function loadSystemdUnit(label) {
|
|
|
589
608
|
// systemd's own checker first, where it exists: it names the bad line (a quoted WorkingDirectory
|
|
590
609
|
// once failed only at restart, as "bad unit file setting").
|
|
591
610
|
const path = join(systemdUserDir(), `${label}.service`);
|
|
611
|
+
if (label.startsWith(WATCH_LABEL_PREFIX))
|
|
612
|
+
ensureWatcherSliceMemoryLimits();
|
|
592
613
|
const v = spawnSync("systemd-analyze", ["--user", "verify", path], { encoding: "utf8" });
|
|
593
614
|
if (!v.error && v.status !== 0)
|
|
594
615
|
throw new CliError("bad_unit", `systemd rejects ${path}`, (v.stderr ?? "").trim().slice(0, 500));
|
|
@@ -598,6 +619,22 @@ export function loadSystemdUnit(label) {
|
|
|
598
619
|
throw new CliError("systemctl_failed", `systemctl --user ${args.join(" ")} failed`, (r.stderr ?? "").trim());
|
|
599
620
|
}
|
|
600
621
|
}
|
|
622
|
+
/** Apply a shared RAM-derived ceiling to all managed agent watcher services on this host. */
|
|
623
|
+
export function ensureWatcherSliceMemoryLimits(ramBytes = totalmem()) {
|
|
624
|
+
const limits = watcherMemoryLimits(ramBytes);
|
|
625
|
+
if (!limits)
|
|
626
|
+
throw new CliError("memory_limits_unavailable", "cannot determine physical RAM; refusing to install an uncapped Linux watcher");
|
|
627
|
+
const sliceDir = join(systemdUserDir(), "app.slice.d");
|
|
628
|
+
mkdirSync(sliceDir, { recursive: true });
|
|
629
|
+
const dropIn = join(sliceDir, "50-b9s-memory.conf");
|
|
630
|
+
writeFileSync(dropIn, `[Slice]\nMemoryHigh=${limits.sliceHighBytes}\nMemoryMax=${limits.sliceMaxBytes}\nMemorySwapMax=0\n`);
|
|
631
|
+
const reload = spawnSync("systemctl", ["--user", "daemon-reload"], { encoding: "utf8" });
|
|
632
|
+
if (reload.status !== 0)
|
|
633
|
+
throw new CliError("systemctl_failed", "systemctl --user daemon-reload failed while applying watcher memory limits", (reload.stderr ?? "").trim());
|
|
634
|
+
const apply = spawnSync("systemctl", ["--user", "set-property", "--runtime", "app.slice", `MemoryHigh=${limits.sliceHighBytes}`, `MemoryMax=${limits.sliceMaxBytes}`, "MemorySwapMax=0"], { encoding: "utf8" });
|
|
635
|
+
if (apply.status !== 0)
|
|
636
|
+
throw new CliError("systemctl_failed", "systemd could not apply MemoryHigh, MemoryMax, and MemorySwapMax to app.slice; Linux watcher installation is refused", (apply.stderr ?? "").trim());
|
|
637
|
+
}
|
|
601
638
|
/**
|
|
602
639
|
* Installs and (re)starts a service running `args` from `cwd`: a LaunchAgent on macOS, a systemd user
|
|
603
640
|
* unit on Linux. Logs go to ~/.b9s/logs/<logName>.{out,err}.log. Returns the definition's path.
|
|
@@ -1,3 +1,51 @@
|
|
|
1
|
+
/** Pair systemd's loaded unit state with the cgroup's measured memory cap and current use. */
|
|
2
|
+
export function measuredWatcherServiceMemoryLimits(units, systemdShow, readText) {
|
|
3
|
+
if (systemdShow === null)
|
|
4
|
+
return { status: "unavailable", services: units.map((unit) => ({ unit, status: "unavailable", control_group: null, configured_memory_max_bytes: null, effective_memory_max_bytes: null, memory_current_bytes: null })) };
|
|
5
|
+
const records = new Map();
|
|
6
|
+
for (const block of systemdShow.trim().split(/\r?\n\s*\r?\n/)) {
|
|
7
|
+
const values = {};
|
|
8
|
+
for (const line of block.split(/\r?\n/)) {
|
|
9
|
+
const at = line.indexOf("=");
|
|
10
|
+
if (at > 0)
|
|
11
|
+
values[line.slice(0, at)] = line.slice(at + 1);
|
|
12
|
+
}
|
|
13
|
+
if (values.Id)
|
|
14
|
+
records.set(values.Id, values);
|
|
15
|
+
}
|
|
16
|
+
const bytes = (raw) => {
|
|
17
|
+
if (raw === "max" || raw === "infinity")
|
|
18
|
+
return "max";
|
|
19
|
+
const parsed = Number(raw);
|
|
20
|
+
return raw && Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : null;
|
|
21
|
+
};
|
|
22
|
+
const services = units.map((unit) => {
|
|
23
|
+
const values = records.get(unit);
|
|
24
|
+
if (!values)
|
|
25
|
+
return { unit, status: "unavailable", control_group: null, configured_memory_max_bytes: null, effective_memory_max_bytes: null, memory_current_bytes: null };
|
|
26
|
+
const configured = bytes(values.MemoryMax);
|
|
27
|
+
const group = values.ControlGroup || null;
|
|
28
|
+
if (!group)
|
|
29
|
+
return { unit, status: "inactive", control_group: null, configured_memory_max_bytes: configured, effective_memory_max_bytes: null, memory_current_bytes: null };
|
|
30
|
+
const components = group.split("/").filter(Boolean);
|
|
31
|
+
if (!group.startsWith("/user.slice/") || !group.includes("/app.slice/") || components.includes("..") || components.at(-1) !== unit) {
|
|
32
|
+
return { unit, status: "unavailable", control_group: null, configured_memory_max_bytes: configured, effective_memory_max_bytes: null, memory_current_bytes: null };
|
|
33
|
+
}
|
|
34
|
+
const prefix = `/sys/fs/cgroup${group}`;
|
|
35
|
+
const effective = bytes(readText(`${prefix}/memory.max`)?.trim());
|
|
36
|
+
const current = bytes(readText(`${prefix}/memory.current`)?.trim());
|
|
37
|
+
return {
|
|
38
|
+
unit,
|
|
39
|
+
status: effective === null ? "unavailable" : "available",
|
|
40
|
+
control_group: group,
|
|
41
|
+
configured_memory_max_bytes: configured,
|
|
42
|
+
effective_memory_max_bytes: effective,
|
|
43
|
+
memory_current_bytes: typeof current === "number" ? current : null,
|
|
44
|
+
};
|
|
45
|
+
});
|
|
46
|
+
const status = services.some((service) => service.status === "unavailable") ? "partial" : "available";
|
|
47
|
+
return { status, services };
|
|
48
|
+
}
|
|
1
49
|
/** Parse one Linux PSI file without turning a missing some/full line into zero. */
|
|
2
50
|
export function parsePressureStall(content) {
|
|
3
51
|
const parseWindow = (kind) => {
|
|
@@ -126,6 +174,16 @@ export function machineResourceTelemetry(hostPlatform, readText, pageSizeBytes,
|
|
|
126
174
|
? "/" + components.slice(0, appSlice + 1).join("/") : null;
|
|
127
175
|
const groupPressure = (kind) => safePath ? parsePressureStall(readText(`/sys/fs/cgroup${safePath}/${kind}.pressure`) ?? "") : null;
|
|
128
176
|
const groupMemory = groupPressure("memory"), groupCpu = groupPressure("cpu"), groupIo = groupPressure("io");
|
|
177
|
+
const groupLimit = (name) => {
|
|
178
|
+
if (!safePath)
|
|
179
|
+
return null;
|
|
180
|
+
const raw = readText(`/sys/fs/cgroup${safePath}/${name}`)?.trim();
|
|
181
|
+
if (raw === "max")
|
|
182
|
+
return "max";
|
|
183
|
+
const value = Number(raw);
|
|
184
|
+
return raw && Number.isSafeInteger(value) && value >= 0 ? value : null;
|
|
185
|
+
};
|
|
186
|
+
const sliceMemoryLimits = { memory_high_bytes: groupLimit("memory.high"), memory_max_bytes: groupLimit("memory.max"), memory_swap_max_bytes: groupLimit("memory.swap.max") };
|
|
129
187
|
const groupAvailable = [groupMemory, groupCpu, groupIo].every((value) => value?.some?.avg10 != null) && groupIo?.full?.avg10 != null && groupMemory?.full?.avg10 != null;
|
|
130
188
|
const swapTotal = linuxMemory?.swap_total_bytes ?? macSwap?.total_bytes ?? null;
|
|
131
189
|
const swapUsed = linuxMemory?.swap_used_bytes ?? macSwap?.used_bytes ?? null;
|
|
@@ -157,6 +215,11 @@ export function machineResourceTelemetry(hostPlatform, readText, pageSizeBytes,
|
|
|
157
215
|
memory_pressure: flattenPressure(groupMemory),
|
|
158
216
|
cpu_pressure: flattenPressure(groupCpu),
|
|
159
217
|
io_pressure: flattenPressure(groupIo),
|
|
218
|
+
memory_limits: {
|
|
219
|
+
source: safePath,
|
|
220
|
+
status: !linux || legacyCgroup ? "unsupported" : Object.values(sliceMemoryLimits).every((value) => value !== null) ? "available" : "unavailable",
|
|
221
|
+
...sliceMemoryLimits,
|
|
222
|
+
},
|
|
160
223
|
},
|
|
161
224
|
metric_availability: {
|
|
162
225
|
memory: linux ? (typeof linuxMemory?.total_bytes === "number" && typeof linuxMemory?.available_bytes === "number" ? "available" : "unavailable") : darwin ? (typeof macMemory?.available_bytes === "number" ? "available" : "unavailable") : "unsupported",
|
package/dist/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const CLI_VERSION = "0.12.
|
|
1
|
+
export const CLI_VERSION = "0.12.115";
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export const GIB = 1024 ** 3;
|
|
2
|
+
/** Keep a machine-wide reserve while allowing one normal build-heavy turn. */
|
|
3
|
+
export function watcherMemoryLimits(totalBytes) {
|
|
4
|
+
if (!Number.isSafeInteger(totalBytes) || totalBytes <= 0)
|
|
5
|
+
return null;
|
|
6
|
+
return {
|
|
7
|
+
totalBytes,
|
|
8
|
+
sliceHighBytes: Math.floor(totalBytes * 0.75),
|
|
9
|
+
sliceMaxBytes: Math.floor(totalBytes * 0.85),
|
|
10
|
+
unitMaxBytes: Math.floor(totalBytes * 0.30),
|
|
11
|
+
swapMaxBytes: 0,
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
export function parseMemoryEvents(content) {
|
|
15
|
+
const values = new Map();
|
|
16
|
+
for (const line of content.split(/\r?\n/)) {
|
|
17
|
+
const match = /^(oom|oom_kill) (\d+)$/.exec(line.trim());
|
|
18
|
+
if (match)
|
|
19
|
+
values.set(match[1], Number(match[2]));
|
|
20
|
+
}
|
|
21
|
+
const oom = values.get("oom"), oomKill = values.get("oom_kill");
|
|
22
|
+
return Number.isSafeInteger(oom) && Number.isSafeInteger(oomKill) ? { oom: oom, oomKill: oomKill } : null;
|
|
23
|
+
}
|
|
24
|
+
export function macMemoryFloorRefusal(totalBytes, availableBytes) {
|
|
25
|
+
if (totalBytes === null || availableBytes === null || !Number.isFinite(totalBytes) || !Number.isFinite(availableBytes) || totalBytes <= 0 || availableBytes < 0) {
|
|
26
|
+
return "cannot read available memory on this Mac";
|
|
27
|
+
}
|
|
28
|
+
const floor = Math.max(2 * GIB, totalBytes * 0.10);
|
|
29
|
+
return availableBytes < floor
|
|
30
|
+
? `available memory is ${(availableBytes / GIB).toFixed(1)} GiB, below the turn-start floor of ${(floor / GIB).toFixed(1)} GiB (2 GiB or 10% of RAM)`
|
|
31
|
+
: null;
|
|
32
|
+
}
|