benignswarm 0.12.146 → 0.12.147

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,7 +1,9 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { constants } from "node:os";
3
+ import { fileURLToPath } from "node:url";
3
4
  import { CliError } from "../errors.js";
4
5
  import { forgetLockJob, rememberLockJob } from "../lock-jobs.js";
6
+ import { redactProcessCommand } from "../machine-processes.js";
5
7
  /**
6
8
  * How many times a lock-run call is repeated after a network failure or a 5xx. Every call carries
7
9
  * the job's token, so a repeat is the same request. A release that failed once during a database
@@ -29,6 +31,9 @@ function unlockCommand(o) {
29
31
  }
30
32
  export async function runUnderLock(o, deps) {
31
33
  const now = deps.now ?? Date.now;
34
+ const seconds = Number(process.env.B9S_LOCK_SILENCE_SECONDS ?? '300');
35
+ if (!Number.isInteger(seconds) || seconds < 1 || seconds > 86400)
36
+ throw new CliError('usage', 'B9S_LOCK_SILENCE_SECONDS must be an integer from 1 to 86400');
32
37
  const label = commandLabel(o.command);
33
38
  const base = `/projects/${o.project}/locks/${o.lock}`;
34
39
  const acquireBody = { unit: o.unit, note: o.note ?? label, shared: o.shared, machine: o.machine, job_token: o.token, lock_run: true };
@@ -62,13 +67,36 @@ export async function runUnderLock(o, deps) {
62
67
  r = await deps.call("POST", `${base}/acquire`, acquireBody);
63
68
  }
64
69
  const startedMs = now();
70
+ const slot = Number.isInteger(r.slot) ? Number(r.slot) : undefined;
71
+ if (o.lock === "ux-browser" && (slot === undefined || slot < 1 || slot > 3)) {
72
+ await release();
73
+ throw new CliError("lock_protocol_mismatch", "The server did not assign a valid ux-browser slot; the command was not started. Inspect the lock state: b9s locks");
74
+ }
65
75
  let code;
66
76
  try {
67
- await deps.call("POST", `${base}/running`, { shared: o.shared, machine: o.machine, job_token: o.token, command: label });
68
- deps.log(`job ${o.jobId} holds ${o.lock}; running: ${label}`);
69
- const result = await deps.run(o.command);
77
+ await deps.call("POST", `${base}/running`, { shared: o.shared, machine: o.machine, job_token: o.token, command: label, silence_seconds: seconds });
78
+ deps.log(`job ${o.jobId} holds ${o.lock}${slot === undefined ? "" : ` slot ${slot}`}; running: ${label}`);
79
+ let latest;
80
+ let pending;
81
+ const flush = () => {
82
+ if (latest === undefined || pending)
83
+ return;
84
+ const line = latest;
85
+ latest = undefined;
86
+ pending = deps.call('POST', `${base}/output`, { shared: o.shared, machine: o.machine, job_token: o.token, line }).then(() => { }, error => { deps.log(`job ${o.jobId} output report could not be confirmed: ${error instanceof Error ? error.message : String(error)}`); }).finally(() => { pending = undefined; });
87
+ };
88
+ const timer = setInterval(flush, Math.min(30000, Math.max(250, seconds * 1000 / 4)));
89
+ let result;
90
+ try {
91
+ result = await deps.run(o.command, { lock: o.lock, jobId: o.jobId, ...(slot === undefined ? {} : { slot }), ...(o.lock === "ux-browser" ? { heartbeat: () => deps.call("POST", `${base}/running`, { shared: o.shared, machine: o.machine, job_token: o.token, command: label }) } : {}), onOutput: line => { latest = redactProcessCommand(line).replace(/\bb9sjob_[A-Za-z0-9]{32,80}\b/g, '[redacted]').replace(/\b(Bearer\s+)[A-Za-z0-9._~+\/-]+=*/gi, '$1[redacted]').replace(/[\x00-\x1f\x7f]/g, ' ').slice(0, 200); } });
92
+ }
93
+ finally {
94
+ clearInterval(timer);
95
+ if (pending)
96
+ await pending;
97
+ }
70
98
  code = typeof result === "number" ? result : result.exit_code;
71
- const released = await release(typeof result === "number" ? { exit_code: code } : { exit_code: code, ...(result.gate_output ? { gate_output: true } : {}), ...(result.verified_baseline_sha ? { verified_baseline_sha: result.verified_baseline_sha } : {}), ...(result.tested_tree_sha ? { tested_tree_sha: result.tested_tree_sha } : {}) });
99
+ const released = await release(typeof result === "number" ? { exit_code: code } : { exit_code: code, ...(result.gate_output ? { gate_output: true } : {}), ...(result.verified_baseline_sha ? { verified_baseline_sha: result.verified_baseline_sha } : {}), ...(result.tested_tree_sha ? { tested_tree_sha: result.tested_tree_sha } : {}), ...(result.timeout_reason ? { timeout_reason: result.timeout_reason } : {}) });
72
100
  if (released.gate_receipt?.recorded === false) {
73
101
  const configured = released.gate_receipt.configured_command;
74
102
  deps.log(`Gate receipt not recorded: ${released.gate_receipt.reason ?? "the reported gate result was refused"}.${configured ? ` Use the configured command: ${configured}` : " No complete gate command is configured."}`);
@@ -79,11 +107,56 @@ export async function runUnderLock(o, deps) {
79
107
  await release();
80
108
  throw error;
81
109
  }
82
- deps.log(`${o.lock} released after ${Math.round((now() - startedMs) / 1000)} s; the command exited ${code}.`);
110
+ deps.log(`${o.lock}${slot === undefined ? "" : ` slot ${slot}`} released after ${Math.round((now() - startedMs) / 1000)} s; the command exited ${code}.`);
83
111
  return code;
84
112
  }
113
+ /** Captures gate receipt baseline and tree markers across streamed stdout chunks. */
114
+ export function createGateMarkerScanner() {
115
+ let tail = "";
116
+ let gateOutput = false;
117
+ let baseline;
118
+ let testedTree;
119
+ let timeoutReason;
120
+ return {
121
+ push(text, final = false) {
122
+ const lines = (tail + text).split(/\r?\n/);
123
+ const incomplete = lines.pop() ?? "";
124
+ if (final) {
125
+ tail = "";
126
+ if (incomplete)
127
+ lines.push(incomplete);
128
+ }
129
+ else {
130
+ tail = incomplete.slice(-2048);
131
+ }
132
+ for (const line of lines) {
133
+ if (/^gate:/i.test(line))
134
+ gateOutput = true;
135
+ const timeoutMatch = line.match(/^gate: timed out in (.+)$/);
136
+ if (timeoutMatch && !timeoutReason)
137
+ timeoutReason = `timed out in ${timeoutMatch[1]}`;
138
+ const baselineMatch = line.match(/^gate: verified baseline ([0-9a-f]{40})\s*$/i);
139
+ // The gate's header is authoritative. Tests run later in the same process
140
+ // may print fixture marker lines; they must not replace the real SHAs.
141
+ if (baselineMatch && !baseline)
142
+ baseline = baselineMatch[1].toLowerCase();
143
+ const treeMatch = line.match(/^gate: tested tree ([0-9a-f]{40})\s*$/i);
144
+ if (treeMatch && !testedTree)
145
+ testedTree = treeMatch[1].toLowerCase();
146
+ }
147
+ },
148
+ result() {
149
+ return {
150
+ ...(gateOutput ? { gate_output: true } : {}),
151
+ ...(baseline ? { verified_baseline_sha: baseline } : {}),
152
+ ...(testedTree ? { tested_tree_sha: testedTree } : {}),
153
+ ...(timeoutReason ? { timeout_reason: timeoutReason } : {}),
154
+ };
155
+ },
156
+ };
157
+ }
85
158
  /** The process-level pieces: the child with the terminal's streams, and signals passed on to it. */
86
- export function processDeps(call, log) {
159
+ export function processDeps(call, log, heartbeatIntervalMs = 15_000) {
87
160
  let interrupted = false;
88
161
  let wake;
89
162
  let forward;
@@ -100,12 +173,41 @@ export function processDeps(call, log) {
100
173
  const timer = setTimeout(() => { wake = undefined; resolve(); }, ms);
101
174
  wake = () => { clearTimeout(timer); wake = undefined; resolve(); };
102
175
  }),
103
- run: (command) => new Promise((resolve, reject) => {
104
- const child = spawn(command[0], command.slice(1), { stdio: ["inherit", "pipe", "inherit"] });
176
+ run: (command, context) => new Promise((resolve, reject) => {
177
+ const env = { ...process.env };
178
+ if (context) {
179
+ env.B9S_LOCK_JOB_ID = context.jobId;
180
+ if (context.slot !== undefined)
181
+ env.B9S_LOCK_SLOT = String(context.slot);
182
+ else
183
+ delete env.B9S_LOCK_SLOT;
184
+ }
185
+ // A lock-run process can be SIGKILLed, so it cannot rely on its own signal
186
+ // handlers to stop the command. Keep the command under a small supervisor
187
+ // and give it a private pipe whose EOF means its lock owner disappeared.
188
+ // The command runs in a separate process group so the supervisor can stop
189
+ // Wrangler/Vite/browser descendants before the lease expires and is reused.
190
+ const supervisor = fileURLToPath(new URL("../../dist/commands/lock-run-supervisor.js", import.meta.url));
191
+ const child = spawn(process.execPath, [supervisor, JSON.stringify(command)], { stdio: ["inherit", "pipe", "pipe", "pipe", "pipe"], env });
192
+ const supervisorControl = child.stdio[3];
193
+ child.once("exit", () => { supervisorControl?.end(); });
194
+ child.once("error", () => { supervisorControl?.end(); });
195
+ const onOutput = context?.onOutput;
105
196
  let tail = "";
106
197
  let gateOutput = false;
107
198
  let baseline;
108
199
  let testedTree;
200
+ let timeoutReason;
201
+ let heartbeatTimer;
202
+ let heartbeatInFlight;
203
+ let heartbeatFailure;
204
+ let commandStartFailure;
205
+ let commandExitCode;
206
+ let childClosed = false;
207
+ const stopHeartbeat = () => {
208
+ if (heartbeatTimer)
209
+ clearInterval(heartbeatTimer);
210
+ };
109
211
  const consumeLines = (text, final = false) => {
110
212
  const lines = (tail + text).split(/\r?\n/);
111
213
  const incomplete = lines.pop() ?? "";
@@ -115,11 +217,18 @@ export function processDeps(call, log) {
115
217
  lines.push(incomplete);
116
218
  }
117
219
  else {
118
- tail = incomplete.slice(-2048);
220
+ tail = incomplete.slice(-32768);
221
+ if (tail.trim())
222
+ onOutput?.(tail);
119
223
  }
120
224
  for (const line of lines) {
225
+ if (line.trim())
226
+ onOutput?.(line);
121
227
  if (/^gate:/i.test(line))
122
228
  gateOutput = true;
229
+ const timeoutMatch = line.match(/^gate: timed out in (.+)$/);
230
+ if (timeoutMatch && !timeoutReason)
231
+ timeoutReason = `timed out in ${timeoutMatch[1]}`;
123
232
  const baselineMatch = line.match(/^gate: verified baseline ([0-9a-f]{40})\s*$/i);
124
233
  // The gate's header is authoritative. Tests run later in the same process
125
234
  // may print fixture marker lines; they must not replace the real SHAs.
@@ -134,15 +243,73 @@ export function processDeps(call, log) {
134
243
  process.stdout.write(chunk);
135
244
  consumeLines(chunk.toString("utf8"));
136
245
  });
246
+ let errorTail = '';
247
+ child.stderr?.on('data', (chunk) => {
248
+ process.stderr.write(chunk);
249
+ const lines = (errorTail + chunk.toString('utf8')).split(/\r?\n/);
250
+ errorTail = (lines.pop() ?? '').slice(-2048);
251
+ for (const line of lines)
252
+ if (line.trim())
253
+ onOutput?.(line);
254
+ if (errorTail.trim())
255
+ onOutput?.(errorTail);
256
+ });
257
+ child.stdio[3]?.on("error", (error) => {
258
+ if (error.code !== "EPIPE")
259
+ log(`job ${context?.jobId ?? "unknown"} supervisor control pipe failed: ${error.message}`);
260
+ });
261
+ child.stdio[4]?.on("data", (chunk) => {
262
+ for (const line of chunk.toString("utf8").split(/\r?\n/)) {
263
+ if (!line)
264
+ continue;
265
+ try {
266
+ const message = JSON.parse(line);
267
+ if (message.type === "spawn_error")
268
+ commandStartFailure = message.message ?? "unknown spawn error";
269
+ if (message.type === "done") {
270
+ commandExitCode = message.exit_code;
271
+ if (message.spawn_error)
272
+ commandStartFailure = message.spawn_error;
273
+ }
274
+ }
275
+ catch {
276
+ log(`job ${context?.jobId ?? "unknown"} supervisor sent an invalid status record`);
277
+ }
278
+ }
279
+ });
137
280
  forward = (signal) => { child.kill(signal); };
138
- child.once("error", (error) => { forward = undefined; reject(new CliError("command_not_started", `could not start ${command[0]}: ${error.message}`)); });
281
+ if (context?.heartbeat) {
282
+ heartbeatTimer = setInterval(() => {
283
+ if (heartbeatInFlight)
284
+ return;
285
+ heartbeatInFlight = context.heartbeat().then(() => undefined, (error) => {
286
+ heartbeatFailure = error;
287
+ log(`job ${context.jobId} could not refresh its lock heartbeat; stopping the command to avoid running without the lock`);
288
+ if (!childClosed)
289
+ child.kill("SIGTERM");
290
+ }).finally(() => { heartbeatInFlight = undefined; });
291
+ }, heartbeatIntervalMs);
292
+ heartbeatTimer.unref?.();
293
+ }
294
+ child.once("error", (error) => { childClosed = true; stopHeartbeat(); forward = undefined; reject(new CliError("command_not_started", `could not start ${command[0]}: ${error.message}`)); });
139
295
  // `close` follows stdout's `end`, so the final marker lines have been
140
296
  // consumed before we construct the receipt sent with the lock release.
141
- child.once("close", (code, signal) => {
297
+ child.once("close", async (code, signal) => {
298
+ childClosed = true;
299
+ stopHeartbeat();
300
+ await heartbeatInFlight;
142
301
  forward = undefined;
302
+ if (heartbeatFailure) {
303
+ reject(new CliError("lock_heartbeat_failed", `job ${context?.jobId ?? "unknown"} stopped because its lock heartbeat failed: ${heartbeatFailure instanceof Error ? heartbeatFailure.message : String(heartbeatFailure)}`));
304
+ return;
305
+ }
306
+ if (commandStartFailure) {
307
+ reject(new CliError("command_not_started", `could not start ${command[0]}: ${commandStartFailure}`));
308
+ return;
309
+ }
143
310
  consumeLines("", true);
144
- const exit_code = code ?? 128 + (signal ? constants.signals[signal] ?? 0 : 0);
145
- resolve({ exit_code, ...(gateOutput ? { gate_output: true } : {}), ...(baseline ? { verified_baseline_sha: baseline } : {}), ...(testedTree ? { tested_tree_sha: testedTree } : {}) });
311
+ const exit_code = commandExitCode ?? code ?? 128 + (signal ? constants.signals[signal] ?? 0 : 0);
312
+ resolve({ exit_code, ...(gateOutput ? { gate_output: true } : {}), ...(baseline ? { verified_baseline_sha: baseline } : {}), ...(testedTree ? { tested_tree_sha: testedTree } : {}), ...(timeoutReason ? { timeout_reason: timeoutReason } : {}) });
146
313
  });
147
314
  }),
148
315
  dispose: () => { for (const signal of signals)
@@ -105,6 +105,9 @@ export function machineGitLines(gitFacts) {
105
105
  return [
106
106
  ` Git identity: ${gitFacts.identity_configured === true ? "configured" : "MISSING"}`,
107
107
  ...repositories.map((repo) => ` Git access ${repo.project}: ${repo.accessible === true ? "ok" : repo.accessible === false ? `FAILED (${repo.error ?? "access check failed"})` : `unknown (${repo.error ?? "not checked"})`}`),
108
+ ...(typeof gitFacts.repositories_omitted_count === "number" && gitFacts.repositories_omitted_count > 0
109
+ ? [` Git access checks omitted: ${gitFacts.repositories_omitted_count} of ${gitFacts.repositories_count ?? repositories.length} repository facts; refresh the machine report for the full list`]
110
+ : []),
108
111
  ];
109
112
  }
110
113
  /**
@@ -13,7 +13,8 @@ import { CliError } from "../errors.js";
13
13
  import { AGY_APPARMOR_PATH, agyAppArmorProfile, BWRAP_APPARMOR_PATH, bwrapAppArmorProfile, CODEX_APPARMOR_PATH, CODEX_MANAGED_DIR, codexAppArmorProfile, codexManagedHooks, isCodexManagedRequirements } from "../harness.js";
14
14
  import { applySparse, sessionCheckoutFacts } from "../git.js";
15
15
  import { drainingUntil, writeMaintenance } from "../maintenance.js";
16
- import { TURN_HARNESSES, cachedClaudeLogin, claudeFacts, claudeHome, claudeSandbox, dshFacts, dshProcesses, probeFor, sessionProcesses } from "../harnesses.js";
16
+ import { TURN_HARNESSES, cachedClaudeEgressVerification, cachedClaudeLogin, claudeCodePath, claudeFacts, claudeHome, claudeSandbox, claudeSandboxCacheIdentity, claudeSecretEgressCapability, dshFacts, dshProcesses, inspectCurrentClaudeEgressCapability, probeFor, queueClaudeEgressProbe, sessionProcesses, shouldQueueClaudeEgressProbe, terminateClaudeSessionProcesses } from "../harnesses.js";
17
+ import { clearSessionSecrets, SECRET_DECLARED_HOSTS_VAR, SECRET_EGRESS_ENV_KEYS_VAR, } from "../session-secrets.js";
17
18
  import { writeFileAtomic } from "../shared-file.js";
18
19
  import { readState, updateState } from "../state.js";
19
20
  import { installService, launchdFacts, launchdFactsLine, launchdGuidance, launchdSessionNow, lingerEnabled, MACHINE_LABEL, machineDaemonPath, readInstall, removeService, requireInstall, restartServicesInBatches, restartWatcher, serviceActive, serviceUsesInstall, serviceUsesNode, WATCH_LABEL_PREFIX, watcherServices, INSTALL_RESTART_BATCH_SIZE, INSTALL_RESTART_BATCH_PAUSE_MS } from "../install.js";
@@ -37,11 +38,13 @@ import { authorizeWorktreeScope, redactProcessCommand, scanWorktreeProcesses } f
37
38
  import { collectPruneProtection } from "../prune-protection.js";
38
39
  import { runMachineDaemonLoop } from "../machine-daemon.js";
39
40
  import { pruneProjectWorktrees } from "./worktrees.js";
41
+ import { boundMachineReport } from "../machine-report.js";
40
42
  import { ECRClient } from "@aws-sdk/client-ecr";
41
43
  import { EcrHostedRegistry } from "../hosted-registry-ecr.js";
42
44
  import { publishHostedImage } from "../hosted-registry.js";
43
45
  import { assumeHostedBuilder } from "../hosted-registry-session.js";
44
46
  import { pushHostedImage } from "../hosted-registry-push.js";
47
+ import { reconcilePendingUxJobs } from "../ux-jobs.js";
45
48
  export const machineFile = () => join(configRoot(), "machine.json");
46
49
  export function loadMachine() {
47
50
  const f = machineFile();
@@ -824,7 +827,9 @@ function startProgressState(pending) {
824
827
  return null;
825
828
  }
826
829
  }
827
- function cleanupMachineStart(pending) {
830
+ function cleanupMachineStart(pending, sessionId) {
831
+ if (sessionId)
832
+ clearSessionSecrets(sessionId);
828
833
  for (const file of [pending.progress_file, pending.result_file, ...(pending.child_file ? [pending.child_file] : []), ...(pending.secret_files ?? [])])
829
834
  rmSync(file, { force: true });
830
835
  }
@@ -903,7 +908,10 @@ async function endPendingStart(state, id, pending, reason, runner, log, readStar
903
908
  throw new Error(`${pending.ending.reason}; container ${pending.container_name} could not be removed: ${errorText(removed.stderr || removed.stdout || "the runtime gave no reason")}`);
904
909
  log(`${agent ?? pending.container_name}: ${reason} (container ${pending.container_name} removed)`);
905
910
  }
906
- cleanupMachineStart(pending);
911
+ cleanupMachineStart(pending, id);
912
+ if (pending.desired?.harness === "claude-code" && pending.has_project_secrets && pending.thread) {
913
+ terminateClaudeSessionProcesses(pending.thread);
914
+ }
907
915
  delete state.starting_sessions[id];
908
916
  writeMachineState(state);
909
917
  }
@@ -964,6 +972,11 @@ async function endOwnProcessGroup() {
964
972
  }
965
973
  export async function launchDesiredSession(opts) {
966
974
  const runner = opts.runner ?? syncRunner;
975
+ if (opts.s.harness === "claude-code" &&
976
+ (opts.s.secret_grant_required || (opts.projectSecretEnvKeys?.length ?? 0) > 0 || (opts.secretDeclaredHosts?.length ?? 0) > 0) &&
977
+ opts.s.sandbox !== "workspace-write") {
978
+ throw new CliError("secret_egress_unenforced_claude-code", "Claude Code project secret delivery requires workspace-write sandbox with enforced domain egress");
979
+ }
967
980
  if (!opts.containerMode) {
968
981
  return runner(opts.bin, startArgs(opts.s, opts.thread, opts.sessionWritable, opts.startupJitterSeconds), {
969
982
  cwd: opts.s.dir,
@@ -971,7 +984,8 @@ export async function launchDesiredSession(opts) {
971
984
  env: {
972
985
  ...process.env,
973
986
  ...opts.secretEnv,
974
- ...(opts.secretDeclaredHosts?.length ? { B9S_SECRET_DECLARED_HOSTS: JSON.stringify(opts.secretDeclaredHosts) } : {}),
987
+ ...(opts.projectSecretEnvKeys?.length ? { [SECRET_EGRESS_ENV_KEYS_VAR]: JSON.stringify(opts.projectSecretEnvKeys) } : {}),
988
+ ...(opts.secretDeclaredHosts?.length ? { [SECRET_DECLARED_HOSTS_VAR]: JSON.stringify(opts.secretDeclaredHosts) } : {}),
975
989
  ...(opts.progressFile ? { BSCHAT_MACHINE_START_PROGRESS_FILE: opts.progressFile } : {}),
976
990
  },
977
991
  });
@@ -1039,7 +1053,8 @@ export async function launchDesiredSession(opts) {
1039
1053
  B9S_URL: opts.m.url,
1040
1054
  B9S_AGENT: opts.s.agent,
1041
1055
  B9S_HOME: "/home/agent/.b9s",
1042
- ...(opts.secretDeclaredHosts?.length ? { B9S_SECRET_DECLARED_HOSTS: JSON.stringify(opts.secretDeclaredHosts) } : {}),
1056
+ ...(opts.projectSecretEnvKeys?.length ? { [SECRET_EGRESS_ENV_KEYS_VAR]: JSON.stringify(opts.projectSecretEnvKeys) } : {}),
1057
+ ...(opts.secretDeclaredHosts?.length ? { [SECRET_DECLARED_HOSTS_VAR]: JSON.stringify(opts.secretDeclaredHosts) } : {}),
1043
1058
  ...(opts.containerProgressFile ? { BSCHAT_MACHINE_START_PROGRESS_FILE: opts.containerProgressFile } : {}),
1044
1059
  },
1045
1060
  secretEnvKeys: opts.projectSecretEnvKeys,
@@ -1218,6 +1233,12 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1218
1233
  removeService(w);
1219
1234
  log(`${s.agent}: ${reason}; watcher removed`);
1220
1235
  }
1236
+ clearSessionSecrets(s.id);
1237
+ if (s.harness === "claude-code" && local?.has_project_secrets && local.thread) {
1238
+ terminateClaudeSessionProcesses(local.thread);
1239
+ }
1240
+ if (local)
1241
+ local.has_project_secrets = false;
1221
1242
  if (local?.container_name && local.container_runtime && !(pending?.container_name === local.container_name && pending.container_runtime === local.container_runtime)) {
1222
1243
  removeAgentContainer(local.container_runtime, local.container_name, runner);
1223
1244
  log(`${s.agent}: ${reason}; container ${local.container_name} removed`);
@@ -1235,6 +1256,12 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1235
1256
  removeService(w);
1236
1257
  log(`${s.agent}: stopped (watcher removed)`);
1237
1258
  }
1259
+ clearSessionSecrets(s.id);
1260
+ if (s.harness === "claude-code" && local?.has_project_secrets && local.thread) {
1261
+ terminateClaudeSessionProcesses(local.thread);
1262
+ }
1263
+ if (local)
1264
+ local.has_project_secrets = false;
1238
1265
  if (local?.container_name && local.container_runtime && !(pending?.container_name === local.container_name && pending.container_runtime === local.container_runtime)) {
1239
1266
  removeAgentContainer(local.container_runtime, local.container_name, runner);
1240
1267
  log(`${s.agent}: stopped (container ${local.container_name} removed)`);
@@ -1339,6 +1366,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1339
1366
  delete state.starting_sessions[s.id];
1340
1367
  writeMachineState(state);
1341
1368
  cleanupMachineStart(pendingStart);
1369
+ clearSessionSecrets(s.id);
1342
1370
  neverLaunched = true;
1343
1371
  log(`${s.agent}: a recorded start was never launched (the daemon stopped first); starting it now`);
1344
1372
  }
@@ -1385,6 +1413,8 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1385
1413
  state.sessions[s.id] = {
1386
1414
  label,
1387
1415
  fingerprint: sessionFingerprint({ ...completedDesired, thread: started.thread }, pendingStart.writable ?? startedWritable, pendingStart.image_reference !== undefined ? pendingStart.image_reference : pinnedImageRef),
1416
+ harness: completedDesired.harness,
1417
+ has_project_secrets: Boolean(pendingStart.has_project_secrets ?? completedDesired.secret_grant_required),
1388
1418
  thread: started.thread,
1389
1419
  thread_override_at: completedDesired.thread_override_at ?? null,
1390
1420
  key_checked_at: local?.key_checked_at ?? Date.now(),
@@ -1462,10 +1492,28 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1462
1492
  const containerActive = containerMode && activeContainerRuntime && activeContainerName
1463
1493
  ? isContainerRunning(activeContainerRuntime, activeContainerName, runner)
1464
1494
  : false;
1495
+ if (!s.secret_grant_required) {
1496
+ clearSessionSecrets(s.id);
1497
+ }
1465
1498
  const needsLaunch = containerMode
1466
1499
  ? (configChanged || !containerActive)
1467
1500
  : (!hostSvc || configChanged);
1468
1501
  if (needsLaunch) {
1502
+ if (local?.has_project_secrets && configChanged) {
1503
+ if (!containerMode && hostSvc) {
1504
+ removeService(hostSvc);
1505
+ log(`${s.agent}: removed watcher service before refreshing secret-bearing session`);
1506
+ }
1507
+ if (containerMode && local.container_name && local.container_runtime) {
1508
+ removeAgentContainer(local.container_runtime, local.container_name, runner);
1509
+ log(`${s.agent}: removed container ${local.container_name} before refreshing secret-bearing session`);
1510
+ }
1511
+ clearSessionSecrets(s.id);
1512
+ if ((!local.harness || local.harness === "claude-code") && local.thread) {
1513
+ terminateClaudeSessionProcesses(local.thread);
1514
+ }
1515
+ local.has_project_secrets = false;
1516
+ }
1469
1517
  // A new session's start runs its first turn at once, past the watchers' check: during a
1470
1518
  // maintenance window it waits. (Adopting a known thread starts no turn, so that proceeds.)
1471
1519
  // The phase is read at the launch decision itself: credential checks and checkouts before
@@ -1502,6 +1550,15 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1502
1550
  runner: deps?.runner,
1503
1551
  });
1504
1552
  if (s.secret_grant_required) {
1553
+ if (s.harness === "claude-code") {
1554
+ if (s.sandbox !== "workspace-write") {
1555
+ throw new CliError("secret_egress_unenforced_claude-code", "Claude Code project secret delivery requires workspace-write sandbox with enforced domain egress");
1556
+ }
1557
+ const localEgress = inspectCurrentClaudeEgressCapability(process.env.PATH ?? "", platform());
1558
+ if (!localEgress.enforced) {
1559
+ throw new CliError("secret_egress_unenforced_claude-code", localEgress.reason ?? "Claude Code project secret egress domain policy is not verified for this runtime");
1560
+ }
1561
+ }
1505
1562
  const grant = await client.call("POST", `/machines/me/sessions/${encodeURIComponent(s.id)}/secret-grant`, {});
1506
1563
  const redeemed = await Client.raw(m.url, grant.grant_token).call("POST", "/secret-broker/redeem", {});
1507
1564
  if (!redeemed.secrets || typeof redeemed.secrets !== "object" || Array.isArray(redeemed.secrets)) {
@@ -1532,7 +1589,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1532
1589
  pending = {
1533
1590
  pid: 0, pid_started: null, started_at: new Date().toISOString(), progress_file: progressFile, result_file: resultFile,
1534
1591
  child_file: startChildFile(resultFile),
1535
- secret_files: secretDelivery.files, fingerprint: fp, thread, desired: s,
1592
+ secret_files: secretDelivery.files, has_project_secrets: Boolean(s.secret_grant_required), fingerprint: fp, thread, desired: s,
1536
1593
  writable: sessionWritable, image_digest: pinnedImageRef,
1537
1594
  ...(containerMode && containerPrereqs && containerName
1538
1595
  ? {
@@ -1569,9 +1626,12 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1569
1626
  writeMachineState(state);
1570
1627
  }
1571
1628
  finally {
1572
- cleanupMachineStart(pending);
1629
+ cleanupMachineStart(pending, s.id);
1573
1630
  }
1574
1631
  }
1632
+ else if (s.secret_grant_required) {
1633
+ clearSessionSecrets(s.id);
1634
+ }
1575
1635
  throw error;
1576
1636
  }
1577
1637
  finally {
@@ -1744,6 +1804,10 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1744
1804
  removeAgentContainer(local.container_runtime, local.container_name, runner);
1745
1805
  log(`${local.label}: session removed by the operator; container ${local.container_name} removed`);
1746
1806
  }
1807
+ clearSessionSecrets(id);
1808
+ if (local.has_project_secrets && (!local.harness || local.harness === "claude-code") && local.thread) {
1809
+ terminateClaudeSessionProcesses(local.thread);
1810
+ }
1747
1811
  delete state.sessions[id];
1748
1812
  }
1749
1813
  for (const [id, pending] of Object.entries(state.starting_sessions ?? {})) {
@@ -1826,6 +1890,8 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1826
1890
  workdir: actualWorkdir,
1827
1891
  modelsToCheck: me.models_to_check ?? [],
1828
1892
  modelRunProbe: deps?.modelRunProbe,
1893
+ verifyClaudeEgress: true,
1894
+ apiUrl: m.url,
1829
1895
  ec2Probe: () => onEc2,
1830
1896
  ...(imdsContainerProbe ? { containerImdsProbe: () => imdsContainerProbe } : {}),
1831
1897
  ...(hostContainerProbe ? { probes: { container: () => hostContainerProbe } } : {}),
@@ -1836,7 +1902,8 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1836
1902
  const pruneUnavailable = worktreePrune.some((result) => result.status === "error" || result.status === "skipped");
1837
1903
  const pruneStatus = dirtyClosedWorktrees.length ? "failed" : pruneUnavailable ? "unknown" : "healthy";
1838
1904
  const pruneDiagnosis = [
1839
- ...dirtyClosedWorktrees,
1905
+ ...dirtyClosedWorktrees.slice(-5),
1906
+ ...(dirtyClosedWorktrees.length > 5 ? [`${dirtyClosedWorktrees.length - 5} additional dirty closed-unit worktrees omitted from this report.`] : []),
1840
1907
  ...(pruneUnavailable ? ["Closed-unit worktree pruning could not inspect every project clone on this machine."] : []),
1841
1908
  ...(!dirtyClosedWorktrees.length && !pruneUnavailable ? ["No dirty closed-unit worktrees were found."] : []),
1842
1909
  ].join("; ");
@@ -1845,7 +1912,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1845
1912
  remedy: pruneStatus === "failed" ? "Review the listed worktrees and preserve or remove their uncommitted changes before pruning." : null,
1846
1913
  recovery_verified: pruneStatus === "healthy", observed_at: new Date().toISOString(),
1847
1914
  });
1848
- const report = {
1915
+ const report = boundMachineReport({
1849
1916
  ...facts, environment_checks: environmentChecks,
1850
1917
  workdir: actualWorkdir, workdir_free_bytes: workSpace?.freeBytes ?? null, workdir_total_bytes: workSpace?.totalBytes ?? null, clones,
1851
1918
  metric_availability: { ...facts.metric_availability, work_volume: workSpace ? "available" : "unavailable" },
@@ -1853,7 +1920,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1853
1920
  build_caches: buildCaches,
1854
1921
  // The daemon's own confirmation that it is holding turns back, and how many are still running.
1855
1922
  maintenance: maintenanceReport(drainingUntil(), out),
1856
- };
1923
+ });
1857
1924
  const capabilities = {};
1858
1925
  const imageProbes = [];
1859
1926
  const probedProjects = [];
@@ -1927,6 +1994,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1927
1994
  probedProjects.push({ id: project.id, signature });
1928
1995
  log(`${project.name}: probed ${capabilities[project.id].length} declared capabilities`);
1929
1996
  }
1997
+ log(`machine report size: ${new TextEncoder().encode(JSON.stringify(report)).byteLength} UTF-8 bytes`);
1930
1998
  await client.call("POST", "/machines/me/report", {
1931
1999
  report,
1932
2000
  report_interval_seconds: reportIntervalSeconds,
@@ -1940,6 +2008,38 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1940
2008
  const warning = diskSpaceNotice(volumeSpace(homedir(), "home"), volumeSpace(workdir ?? join(homedir(), "bschat"), "workdir"));
1941
2009
  if (warning !== undefined)
1942
2010
  await client.call("PUT", "/machines/me/notices/disk", { text: warning });
2011
+ if (Array.isArray(me.ux_jobs) && me.ux_jobs.length) {
2012
+ const uxPromise = reconcilePendingUxJobs(client, me.ux_jobs, {
2013
+ accountId,
2014
+ machineName: m.name,
2015
+ workdir,
2016
+ sessions: desired.map((s) => ({
2017
+ id: s.id,
2018
+ agent: s.agent,
2019
+ agent_name: s.agent_name,
2020
+ project: s.project,
2021
+ project_id: s.project_id ?? null,
2022
+ dir: s.dir,
2023
+ desired: s.desired,
2024
+ benched_at: s.benched_at ?? null,
2025
+ retired_at: null,
2026
+ })),
2027
+ log,
2028
+ }, {
2029
+ inFlight: deps?.uxJobsInFlight,
2030
+ awaitCompletion: deps?.awaitUxJobs ?? false,
2031
+ deps: {
2032
+ ensureSessionKey: async (hint) => {
2033
+ const match = desired.find((s) => s.id === hint.id);
2034
+ if (match)
2035
+ await ensureCredentials(client, m, match, state.sessions[match.id], log);
2036
+ },
2037
+ ...deps?.uxJobDeps,
2038
+ },
2039
+ });
2040
+ if (deps?.awaitUxJobs)
2041
+ await uxPromise;
2042
+ }
1943
2043
  return { sessions: out, report };
1944
2044
  }
1945
2045
  export async function answerWorktreeProcessQueries(client, desired, queries, log, scan = scanWorktreeProcesses) {
@@ -2617,15 +2717,19 @@ export function claudeKeychainGap(f, headlessMac, fileCredentials) {
2617
2717
  return f;
2618
2718
  return { ...f, readiness_gap: "possible cause: this Mac has no desktop session, and a Claude Code sign-in kept in the login keychain can't be read without one. If Claude Code is signed in at the desktop, sign in there (or enable automatic sign-in), or store a file credential with 'claude setup-token'" };
2619
2719
  }
2620
- /** Claude Code's version, login and sandbox; the sandbox check runs at most every 10 min. */
2621
2720
  let claudeSandboxCache = null;
2622
- function claudeReport(path = process.env.PATH ?? "", providersInUse = ["anthropic"]) {
2721
+ export function claudeReport(path = process.env.PATH ?? "", providersInUse = ["anthropic"], options = {}) {
2623
2722
  const found = claudeFacts(undefined, path);
2624
2723
  if (!found)
2625
2724
  return null;
2626
2725
  const f = claudeKeychainGap(found, process.platform === "darwin" && launchdSessionNow() === "headless", existsSync(join(claudeHome(), ".credentials.json")));
2627
- if (!claudeSandboxCache || claudeSandboxCache.path !== path || Date.now() - claudeSandboxCache.at > 10 * 60_000)
2628
- claudeSandboxCache = { at: Date.now(), result: claudeSandbox(path), path };
2726
+ const hostOs = platform();
2727
+ const sandboxCwd = hostOs === "darwin" ? homedir() : undefined;
2728
+ const nowMs = options.nowMs ?? Date.now();
2729
+ const cacheKey = `${path}\0${claudeSandboxCacheIdentity(path)}`;
2730
+ if (!claudeSandboxCache || claudeSandboxCache.cacheKey !== cacheKey || nowMs - claudeSandboxCache.at > 10 * 60_000) {
2731
+ claudeSandboxCache = { at: nowMs, result: claudeSandbox(path, sandboxCwd), cacheKey };
2732
+ }
2629
2733
  const providers = {};
2630
2734
  for (const provider of providersInUse) {
2631
2735
  const check = provider === "anthropic"
@@ -2633,7 +2737,34 @@ function claudeReport(path = process.env.PATH ?? "", providersInUse = ["anthropi
2633
2737
  : verifyClaudeProvider(provider);
2634
2738
  providers[provider] = { ...check, sandbox: claudeSandboxCache.result };
2635
2739
  }
2636
- return { ...f, sandbox: claudeSandboxCache.result, providers };
2740
+ const binPath = claudeCodePath(path);
2741
+ const verification = cachedClaudeEgressVerification({ os: hostOs, runtimeVersion: f.version, binPath });
2742
+ const readyProvider = f.logged_in
2743
+ ? "anthropic"
2744
+ : providersInUse.find((provider) => providers[provider]?.logged_in === true) ?? null;
2745
+ if (options.verifyEgressInBackground === true
2746
+ && hostOs === "linux"
2747
+ && claudeSandboxCache.result.ok
2748
+ && f.version
2749
+ && readyProvider
2750
+ && shouldQueueClaudeEgressProbe(verification, nowMs)) {
2751
+ queueClaudeEgressProbe({
2752
+ path,
2753
+ os: hostOs,
2754
+ runtimeVersion: f.version,
2755
+ binPath,
2756
+ provider: readyProvider,
2757
+ apiUrl: options.apiUrl,
2758
+ trustedControlPlaneUrl: options.apiUrl ?? "https://api.benignswarm.org",
2759
+ env: process.env,
2760
+ });
2761
+ }
2762
+ return {
2763
+ ...f,
2764
+ sandbox: claudeSandboxCache.result,
2765
+ providers,
2766
+ secret_egress: claudeSecretEgressCapability(claudeSandboxCache.result, hostOs, f.version, verification, nowMs, binPath),
2767
+ };
2637
2768
  }
2638
2769
  /** Check a prepared target without starting a model turn or a watcher. */
2639
2770
  export function preparedTargetFacts(session) {
@@ -2841,7 +2972,7 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
2841
2972
  const volumeFloorPct = diskFloorPct;
2842
2973
  const req = "/etc/codex/requirements.toml";
2843
2974
  const fingerprint = (harness, provider) => accountFingerprintForModelCheck(harness, provider);
2844
- const readClaudeFacts = () => (probes?.claude ?? (() => claudeReport(path, providersInUse)))();
2975
+ const readClaudeFacts = () => (probes?.claude ?? (() => claudeReport(path, providersInUse, { verifyEgressInBackground: opts.verifyClaudeEgress === true, apiUrl: opts.apiUrl })))();
2845
2976
  const withClaudeIdentity = (value) => {
2846
2977
  if (!value)
2847
2978
  return null;
@@ -3556,7 +3687,7 @@ export async function machine(p, out) {
3556
3687
  return out.print([`machine ${m.name} (${m.url})`, ...(launchd ? [launchdFactsLine(launchd)] : []), ...rows, rows.length ? "" : "no sessions declared"].join("\n"), { machine: m.name, sessions: desired, local: state, ...(launchd ? { launchd } : {}) });
3557
3688
  }
3558
3689
  if (sub === "once") {
3559
- const r = await reconcile(m, log);
3690
+ const r = await reconcile(m, log, 30, { awaitUxJobs: true });
3560
3691
  return out.print(r.sessions.map((s) => `${s.state.padEnd(8)} ${desiredName(s.id)} ${s.thread ?? ""} ${s.error ?? ""}`).join("\n") || "no sessions declared", r);
3561
3692
  }
3562
3693
  if (sub === "build-images") {