bridex-worker 0.1.4 → 0.1.5

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.
Files changed (3) hide show
  1. package/README.md +81 -3
  2. package/dist/cli.js +977 -193
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -326,18 +326,21 @@ import path2 from "path";
326
326
  var JWT_ENV = "BRIDEX_RUN_JWT";
327
327
  var CODEX_APPROVE = `default_tools_approval_mode = "approve"`;
328
328
  function writeCodexMcpConfig(home, servers, bridex, opts = {}) {
329
- return writeTomlMcpConfig(home, servers, bridex, opts, { dir: ".codex", headersKey: "http_headers", extra: CODEX_APPROVE });
329
+ return writeTomlMcpConfig(home, servers, bridex, opts, { dir: ".codex", headersKey: "http_headers", extra: CODEX_APPROVE, forward: "env_vars" });
330
330
  }
331
331
  function writeGrokMcpConfig(home, servers, bridex, opts = {}) {
332
332
  const dir = grokHomeOf(home, (typeof opts === "function" ? void 0 : opts.env) ?? {});
333
- return writeTomlMcpConfig(home, servers, bridex, opts, { dir, headersKey: "headers" });
333
+ return writeTomlMcpConfig(home, servers, bridex, opts, { dir, headersKey: "headers", forward: "expand" });
334
334
  }
335
+ var expanded = (names) => Object.fromEntries(names.map((n) => [n, `\${${n}}`]));
335
336
  function writeTomlMcpConfig(home, servers, bridex, opts, dialect) {
336
- const { warn = console.warn, preserveOthers = false } = typeof opts === "function" ? { warn: opts } : opts;
337
+ const { warn = console.warn, preserveOthers = false, fromEnv = [] } = typeof opts === "function" ? { warn: opts } : opts;
337
338
  const owned = !preserveOthers;
338
339
  const file = configFile(home, dialect.dir, "config.toml", owned);
339
340
  const extra = dialect.extra ? `
340
341
  ${dialect.extra}` : "";
342
+ const envVars = fromEnv.length && dialect.forward === "env_vars" ? `
343
+ env_vars = [${fromEnv.map(tomlStr).join(", ")}]` : "";
341
344
  const existing = readConfig(file, owned);
342
345
  const ownNames = ["bridex", ...Object.keys(servers)].map((n) => n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
343
346
  const kept = stripTomlTables(
@@ -359,11 +362,14 @@ url = ${tomlStr(cfg.url)}${headers ? `
359
362
  ${dialect.headersKey} = { ${headers} }` : ""}${extra}`
360
363
  );
361
364
  } else {
362
- const env = Object.entries(cfg.env);
365
+ const env = Object.entries({
366
+ ...Object.fromEntries(Object.entries(cfg.env).filter(([k]) => !fromEnv.includes(k))),
367
+ ...dialect.forward === "expand" ? expanded(fromEnv) : {}
368
+ });
363
369
  blocks.push(
364
370
  `[mcp_servers.${name}]
365
371
  command = ${tomlStr(cfg.command)}
366
- args = [${cfg.args.map(tomlStr).join(", ")}]${extra}` + // a table's own keys must precede its sub-tables, so the key goes above .env
372
+ args = [${cfg.args.map(tomlStr).join(", ")}]${envVars}${extra}` + // a table's own keys must precede its sub-tables, so the key goes above .env
367
373
  (env.length ? `
368
374
 
369
375
  [mcp_servers.${name}.env]
@@ -377,7 +383,7 @@ ${env.map(([k, v]) => `${tomlStr(k)} = ${tomlStr(v)}`).join("\n")}` : "")
377
383
  return { env: {} };
378
384
  }
379
385
  function writeGeminiMcpConfig(home, servers, bridex, opts = {}) {
380
- const { warn = console.warn, preserveOthers = false } = typeof opts === "function" ? { warn: opts } : opts;
386
+ const { warn = console.warn, preserveOthers = false, fromEnv = [] } = typeof opts === "function" ? { warn: opts } : opts;
381
387
  const owned = !preserveOthers;
382
388
  const file = configFile(home, ".gemini", "settings.json", owned);
383
389
  const existing = readConfig(file, owned);
@@ -395,7 +401,12 @@ function writeGeminiMcpConfig(home, servers, bridex, opts = {}) {
395
401
  mcpServers.bridex = { httpUrl: bridex.url, headers: { Authorization: `Bearer $${JWT_ENV}` } };
396
402
  }
397
403
  for (const [name, cfg] of Object.entries(servers)) {
398
- mcpServers[name] = cfg.type === "http" ? { httpUrl: cfg.url, ...Object.keys(cfg.headers).length ? { headers: cfg.headers } : {} } : { command: cfg.command, args: cfg.args, ...Object.keys(cfg.env).length ? { env: cfg.env } : {} };
404
+ if (cfg.type === "http") {
405
+ mcpServers[name] = { httpUrl: cfg.url, ...Object.keys(cfg.headers).length ? { headers: cfg.headers } : {} };
406
+ continue;
407
+ }
408
+ const env = { ...cfg.env, ...expanded(fromEnv) };
409
+ mcpServers[name] = { command: cfg.command, args: cfg.args, ...Object.keys(env).length ? { env } : {} };
399
410
  }
400
411
  settings.mcpServers = mcpServers;
401
412
  writeIfChanged(file, `${JSON.stringify(settings, null, 2)}
@@ -5007,9 +5018,9 @@ function createCpClient(deps) {
5007
5018
  const doFetch = deps.fetch ?? globalThis.fetch;
5008
5019
  const base = `${deps.url.replace(/\/+$/, "")}/api/v1/workers/${encodeURIComponent(deps.id)}`;
5009
5020
  const timeoutMs = deps.timeoutMs ?? 1e4;
5010
- async function call(path24, init = {}) {
5021
+ async function call(path25, init = {}) {
5011
5022
  try {
5012
- return await doFetch(`${base}${path24}`, {
5023
+ return await doFetch(`${base}${path25}`, {
5013
5024
  ...init,
5014
5025
  headers: { ...init.headers, Authorization: `Bearer ${deps.key}` },
5015
5026
  signal: AbortSignal.timeout(timeoutMs)
@@ -6296,7 +6307,7 @@ async function joinCp(url, id, key, deps = defaultJoinDeps(), opts = {}) {
6296
6307
 
6297
6308
  // src/run.ts
6298
6309
  import os7 from "os";
6299
- import path23 from "path";
6310
+ import path24 from "path";
6300
6311
  import WebSocket from "ws";
6301
6312
 
6302
6313
  // src/admission.ts
@@ -6502,8 +6513,388 @@ function heartbeat(cfg, running, host, warm = [], quota) {
6502
6513
  }
6503
6514
 
6504
6515
  // src/engines/cli.ts
6516
+ import fs17 from "fs";
6517
+ import path14 from "path";
6518
+
6519
+ // src/leftovers.ts
6520
+ import { execFile as execFile3, execFileSync as execFileSync4 } from "child_process";
6521
+ import { createHash as createHash3 } from "crypto";
6505
6522
  import fs16 from "fs";
6506
6523
  import path13 from "path";
6524
+ var UNIT_VAR = "BRIDEX_WORKER_UNIT";
6525
+ var INSTALL_RE = /^[0-9a-f]{12}$/;
6526
+ var PID_RE = /^[1-9]\d*$/;
6527
+ var ID_RE = /^[^\s:]+$/;
6528
+ function tagOf(install2, workerPid, kind, id) {
6529
+ const tag = `${install2}:${workerPid}:${kind}:${id}`;
6530
+ if (!parseTag(tag)) throw new Error(`cannot tag ${kind} ${JSON.stringify(id)}`);
6531
+ return tag;
6532
+ }
6533
+ function tryTagOf(install2, workerPid, kind, id) {
6534
+ try {
6535
+ return tagOf(install2, workerPid, kind, id);
6536
+ } catch {
6537
+ return null;
6538
+ }
6539
+ }
6540
+ function parseTag(value) {
6541
+ const parts = value.split(":");
6542
+ if (parts.length !== 4) return null;
6543
+ const [install2, pid, kind, id] = parts;
6544
+ if (!INSTALL_RE.test(install2) || !PID_RE.test(pid) || !ID_RE.test(id)) return null;
6545
+ if (kind !== "run" && kind !== "job") return null;
6546
+ const workerPid = Number(pid);
6547
+ if (!Number.isSafeInteger(workerPid)) return null;
6548
+ return { install: install2, workerPid, kind, id };
6549
+ }
6550
+ function installIdOf(cacheDir) {
6551
+ let real;
6552
+ try {
6553
+ real = fs16.realpathSync(cacheDir);
6554
+ } catch {
6555
+ real = path13.resolve(cacheDir);
6556
+ }
6557
+ return createHash3("sha256").update(real).digest("hex").slice(0, 12);
6558
+ }
6559
+ var PS_MAX_BUFFER = 64 * 1024 * 1024;
6560
+ var PS_TIMEOUT_MS = 5e3;
6561
+ function psRunner(args, exec = execFile3) {
6562
+ return () => new Promise((resolve, reject) => {
6563
+ exec("ps", args, { encoding: "utf8", timeout: PS_TIMEOUT_MS, maxBuffer: PS_MAX_BUFFER }, (err, out) => err ? reject(err) : resolve(String(out)));
6564
+ });
6565
+ }
6566
+ function startOfStat(stat) {
6567
+ const close = stat.lastIndexOf(")");
6568
+ if (close < 0) return null;
6569
+ const start = stat.slice(close + 2).split(" ")[19];
6570
+ return start && /^\d+$/.test(start) ? start : null;
6571
+ }
6572
+ var PROC_SCAN = `
6573
+ const fs = require("fs"), path = require("path");
6574
+ const [root, prefix] = process.argv.slice(1);
6575
+ const startOf = (stat) => {
6576
+ const close = stat.lastIndexOf(")");
6577
+ if (close < 0) return null;
6578
+ const start = stat.slice(close + 2).split(" ")[19];
6579
+ return start && /^\\d+$/.test(start) ? start : null;
6580
+ };
6581
+ const passed = new Set(["ENOENT", "ESRCH", "EACCES", "EPERM"]);
6582
+ const readOf = (e, file) => {
6583
+ try { return fs.readFileSync(path.join(root, e, file), "utf8"); }
6584
+ catch (err) { if (passed.has(err && err.code)) return null; throw err; }
6585
+ };
6586
+ const out = [];
6587
+ for (const e of fs.readdirSync(root)) {
6588
+ if (!/^\\d+$/.test(e)) continue;
6589
+ const stat = readOf(e, "stat");
6590
+ if (stat === null) continue;
6591
+ const start = startOf(stat);
6592
+ if (!start) continue;
6593
+ const env = readOf(e, "environ");
6594
+ if (env === null) continue;
6595
+ const values = env.split("\\0").filter((v) => v.startsWith(prefix)).map((v) => v.slice(prefix.length));
6596
+ if (values.length === 0) continue;
6597
+ let name = "?";
6598
+ try { name = fs.readFileSync(path.join(root, e, "comm"), "utf8").trim() || "?"; } catch {}
6599
+ out.push([Number(e), values, name, start]);
6600
+ }
6601
+ process.stdout.write(JSON.stringify(out));
6602
+ `;
6603
+ function procScanner(procRoot, timeoutMs = PS_TIMEOUT_MS) {
6604
+ return () => new Promise((resolve, reject) => {
6605
+ execFile3(
6606
+ process.execPath,
6607
+ ["-e", PROC_SCAN, procRoot, `${UNIT_VAR}=`],
6608
+ { encoding: "utf8", timeout: timeoutMs, killSignal: "SIGKILL", maxBuffer: PS_MAX_BUFFER },
6609
+ (err, out) => err ? reject(err) : resolve(String(out))
6610
+ );
6611
+ });
6612
+ }
6613
+ var defaultReadDeps = {
6614
+ platform: process.platform,
6615
+ psStart: psRunner(["-A", "-o", "pid=,lstart="]),
6616
+ psPlain: psRunner(["-A", "-ww", "-o", "pid=,command="]),
6617
+ psEnv: psRunner(["-A", "-E", "-ww", "-o", "pid=,command="]),
6618
+ psComm: psRunner(["-A", "-ww", "-o", "pid=,comm="]),
6619
+ procScan: procScanner("/proc")
6620
+ };
6621
+ function oneTag(values) {
6622
+ const distinct = [...new Set(values)];
6623
+ return distinct.length === 1 ? distinct[0] : null;
6624
+ }
6625
+ async function readTagged(install2, deps = defaultReadDeps) {
6626
+ const found = deps.platform === "linux" ? await readProc(deps.procScan) : await readPs(deps);
6627
+ if (!found) return null;
6628
+ const out = [];
6629
+ for (const f of found) {
6630
+ const unit = parseTag(f.tag);
6631
+ if (unit && unit.install === install2) out.push({ ...f, unit });
6632
+ }
6633
+ return out;
6634
+ }
6635
+ async function readProc(scan) {
6636
+ let rows;
6637
+ try {
6638
+ rows = JSON.parse(await scan());
6639
+ } catch {
6640
+ return null;
6641
+ }
6642
+ if (!Array.isArray(rows)) return null;
6643
+ const out = [];
6644
+ for (const row of rows) {
6645
+ if (!Array.isArray(row)) continue;
6646
+ const [pid, values, name, start] = row;
6647
+ if (typeof pid !== "number" || !Array.isArray(values) || !values.every((v) => typeof v === "string")) continue;
6648
+ if (typeof start !== "string" || !start) continue;
6649
+ const tag = oneTag(values);
6650
+ if (!tag) continue;
6651
+ out.push({ pid, tag, name: typeof name === "string" && name ? name : "?", start });
6652
+ }
6653
+ return out;
6654
+ }
6655
+ function psLines(listing) {
6656
+ const out = /* @__PURE__ */ new Map();
6657
+ for (const line of listing.split("\n")) {
6658
+ const m = /^\s*(\d+) ?(.*)$/.exec(line);
6659
+ if (m) out.set(Number(m[1]), m[2]);
6660
+ }
6661
+ return out;
6662
+ }
6663
+ async function readPs(deps) {
6664
+ let starts, plain, withEnv, comm;
6665
+ try {
6666
+ starts = psLines(await deps.psStart());
6667
+ [plain, withEnv, comm] = await Promise.all([deps.psPlain(), deps.psEnv(), deps.psComm().catch(() => "")]);
6668
+ } catch {
6669
+ return null;
6670
+ }
6671
+ const commands = psLines(plain);
6672
+ const executables = psLines(comm);
6673
+ const prefix = `${UNIT_VAR}=`;
6674
+ const out = [];
6675
+ for (const [pid, line] of psLines(withEnv)) {
6676
+ const start = starts.get(pid)?.trim();
6677
+ if (!start) continue;
6678
+ const command = commands.get(pid)?.trimEnd();
6679
+ if (command === void 0) continue;
6680
+ if (!line.startsWith(command)) continue;
6681
+ const rest2 = line.slice(command.length);
6682
+ if (rest2 !== "" && !/^\s/.test(rest2)) continue;
6683
+ const tag = oneTag(rest2.split(/\s+/).filter((t) => t.startsWith(prefix)).map((t) => t.slice(prefix.length)));
6684
+ if (!tag) continue;
6685
+ out.push({ pid, tag, name: shortName(executables.get(pid) ?? ""), start });
6686
+ }
6687
+ return out;
6688
+ }
6689
+ var defaultSameDeps = {
6690
+ platform: process.platform,
6691
+ statOf: (pid) => fs16.readFileSync(`/proc/${pid}/stat`, "utf8"),
6692
+ startsOf: (pids) => {
6693
+ try {
6694
+ return execFileSync4("ps", ["-o", "pid=,lstart=", "-p", pids.join(",")], {
6695
+ encoding: "utf8",
6696
+ stdio: ["ignore", "pipe", "ignore"],
6697
+ timeout: PS_TIMEOUT_MS,
6698
+ maxBuffer: PS_MAX_BUFFER
6699
+ });
6700
+ } catch (err) {
6701
+ const e = err;
6702
+ if (e.status === 1) return String(e.stdout ?? "");
6703
+ throw err;
6704
+ }
6705
+ }
6706
+ };
6707
+ function sameAsListed(procs, deps = defaultSameDeps) {
6708
+ const checked = procs.filter((p) => p.start !== void 0);
6709
+ if (checked.length === 0) return procs;
6710
+ const now = /* @__PURE__ */ new Map();
6711
+ if (deps.platform === "linux") {
6712
+ for (const p of checked) {
6713
+ let stat;
6714
+ try {
6715
+ stat = deps.statOf(p.pid);
6716
+ } catch (err) {
6717
+ const code = err?.code;
6718
+ if (code === "ENOENT" || code === "ESRCH") continue;
6719
+ return null;
6720
+ }
6721
+ const start = startOfStat(stat);
6722
+ if (!start) return null;
6723
+ now.set(p.pid, start);
6724
+ }
6725
+ } else {
6726
+ try {
6727
+ for (const [pid, start] of psLines(deps.startsOf(checked.map((p) => p.pid)))) now.set(pid, start.trim());
6728
+ } catch {
6729
+ return null;
6730
+ }
6731
+ }
6732
+ return procs.filter((p) => p.start === void 0 || now.get(p.pid) === p.start);
6733
+ }
6734
+ function stillRunning(procs, deps = defaultSameDeps) {
6735
+ if (deps.platform !== "linux") return [];
6736
+ const out = [];
6737
+ for (const p of procs) {
6738
+ if (p.start === void 0) continue;
6739
+ let stat;
6740
+ try {
6741
+ stat = deps.statOf(p.pid);
6742
+ } catch (err) {
6743
+ const code = err?.code;
6744
+ if (code === "ENOENT" || code === "ESRCH") continue;
6745
+ return null;
6746
+ }
6747
+ const start = startOfStat(stat);
6748
+ const state2 = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[0];
6749
+ if (!start || !state2) return null;
6750
+ if (start === p.start && !/^[ZXx]$/.test(state2)) out.push(p);
6751
+ }
6752
+ return out;
6753
+ }
6754
+ function shortName(executable) {
6755
+ return (path13.basename(executable.trim()) || "?").slice(0, 64);
6756
+ }
6757
+ function matchTag(tag) {
6758
+ const unit = parseTag(tag);
6759
+ if (!unit) throw new Error(`not a unit tag: ${JSON.stringify(tag)}`);
6760
+ return { install: unit.install, tag, accept: (u) => u.kind === unit.kind && u.id === unit.id && u.workerPid === unit.workerPid };
6761
+ }
6762
+ function describeEnded(ended, cap = 5) {
6763
+ const names = [...new Set(ended.map((e) => e.name))];
6764
+ const shown = names.slice(0, cap).join(", ") + (names.length > cap ? `, \u2026 (${names.length - cap} more)` : "");
6765
+ return `${ended.length} process${ended.length === 1 ? "" : "es"} (${shown})`;
6766
+ }
6767
+ var END_GRACE_MS = 5e3;
6768
+ var END_POLL_MS = 200;
6769
+ var END_KILL_DELAYS = [50, 200, 750, 1500];
6770
+ var realSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
6771
+ async function endTagged(match, opts = {}) {
6772
+ const read = opts.read ?? (() => readTagged(match.install));
6773
+ const kill = opts.kill ?? ((pid, signal2) => process.kill(pid, signal2));
6774
+ const same = opts.same ?? ((procs) => sameAsListed(procs));
6775
+ const sameEach = opts.sameEach ?? (opts.same === void 0 && defaultSameDeps.platform === "linux");
6776
+ const unlisted = opts.unlisted ?? ((procs) => stillRunning(procs));
6777
+ const sleep = opts.sleep ?? realSleep;
6778
+ const now = opts.now ?? (() => performance.now());
6779
+ const graceMs = Math.max(0, opts.graceMs ?? END_GRACE_MS);
6780
+ const pollMs = Math.max(1, opts.pollMs ?? END_POLL_MS);
6781
+ const killDelays = opts.killDelays ?? END_KILL_DELAYS;
6782
+ const readNow = async () => {
6783
+ try {
6784
+ return await read() ?? null;
6785
+ } catch {
6786
+ return null;
6787
+ }
6788
+ };
6789
+ const unitsIn = (all) => new Set(all.filter((p) => p.unit.install === match.install && match.accept(p.unit)).map((p) => p.tag));
6790
+ let first = await readNow();
6791
+ if (!first) return { ended: [], refused: [], readFailed: true, done: Promise.resolve() };
6792
+ let units = unitsIn(first);
6793
+ if (units.size === 0 && match.tag !== void 0) {
6794
+ first = await readNow();
6795
+ if (!first) return { ended: [], refused: [], readFailed: true, done: Promise.resolve() };
6796
+ units = unitsIn(first);
6797
+ }
6798
+ if (units.size === 0) return { ended: [], refused: [], readFailed: false, done: Promise.resolve() };
6799
+ const members = (all) => all.filter((p) => units.has(p.tag) && p.pid > 1 && p.pid !== process.pid);
6800
+ let last = [];
6801
+ const membersNow = async () => {
6802
+ const all = await readNow();
6803
+ if (!all) return null;
6804
+ const now2 = members(all);
6805
+ const listed = new Set(now2.map((p) => p.pid));
6806
+ const missing = last.filter((p) => !listed.has(p.pid));
6807
+ if (missing.length > 0) {
6808
+ let running;
6809
+ try {
6810
+ running = unlisted(missing);
6811
+ } catch {
6812
+ running = null;
6813
+ }
6814
+ if (!running) return null;
6815
+ now2.push(...running);
6816
+ }
6817
+ last = now2;
6818
+ return now2;
6819
+ };
6820
+ const ended = /* @__PURE__ */ new Map();
6821
+ const refused = /* @__PURE__ */ new Map();
6822
+ const killed = /* @__PURE__ */ new Set();
6823
+ let seen = /* @__PURE__ */ new Set();
6824
+ const signal = (procs, sig) => {
6825
+ for (const batch of sameEach ? procs.map((p) => [p]) : procs.length ? [procs] : []) {
6826
+ let still;
6827
+ try {
6828
+ still = same(batch);
6829
+ } catch {
6830
+ still = null;
6831
+ }
6832
+ if (!still) return false;
6833
+ const kept = new Set(still.map((p) => p.pid));
6834
+ for (const p of batch) {
6835
+ const one = { pid: p.pid, unit: p.unit, name: p.name };
6836
+ if (!kept.has(p.pid)) {
6837
+ refused.delete(p.pid);
6838
+ seen.delete(p.pid);
6839
+ continue;
6840
+ }
6841
+ try {
6842
+ kill(p.pid, sig);
6843
+ } catch (err) {
6844
+ if (err?.code === "ESRCH") {
6845
+ refused.delete(p.pid);
6846
+ seen.delete(p.pid);
6847
+ } else {
6848
+ ended.delete(p.pid);
6849
+ refused.set(p.pid, one);
6850
+ }
6851
+ continue;
6852
+ }
6853
+ refused.delete(p.pid);
6854
+ if (!ended.has(p.pid)) ended.set(p.pid, one);
6855
+ if (sig === "SIGKILL") killed.add(p.pid);
6856
+ }
6857
+ }
6858
+ return true;
6859
+ };
6860
+ let left = members(first);
6861
+ last = left;
6862
+ seen = new Set(left.map((p) => p.pid));
6863
+ if (graceMs > 0) {
6864
+ signal(left, "SIGTERM");
6865
+ const start = now();
6866
+ while (left === null || left.length > 0) {
6867
+ const remaining = graceMs - (now() - start);
6868
+ if (remaining <= 0) break;
6869
+ await sleep(Math.min(pollMs, remaining));
6870
+ left = await membersNow();
6871
+ if (left) seen = new Set(left.map((p) => p.pid));
6872
+ }
6873
+ if (left === null) {
6874
+ left = await membersNow();
6875
+ if (left) seen = new Set(left.map((p) => p.pid));
6876
+ }
6877
+ }
6878
+ if (left && !signal(left, "SIGKILL")) left = null;
6879
+ for (const pid of [...refused.keys()]) if (!seen.has(pid)) refused.delete(pid);
6880
+ const readFailed = left === null;
6881
+ const result = [...ended.values()].filter((e) => !(readFailed && seen.has(e.pid) && !killed.has(e.pid)));
6882
+ const notReached = [...refused.values()];
6883
+ const later = async () => {
6884
+ for (const delay of killDelays) {
6885
+ await sleep(delay);
6886
+ const rest2 = await membersNow();
6887
+ if (!rest2) continue;
6888
+ if (rest2.length === 0) return;
6889
+ signal(rest2, "SIGKILL");
6890
+ }
6891
+ };
6892
+ const done = later().catch(() => {
6893
+ });
6894
+ return { ended: result, refused: notReached, readFailed, done };
6895
+ }
6896
+
6897
+ // src/engines/cli.ts
6507
6898
  function presetOf(needs) {
6508
6899
  const need = needs.find((n) => n.startsWith("cli:"));
6509
6900
  return need ? need.slice("cli:".length) : null;
@@ -6579,57 +6970,67 @@ function composeEnv(grant, o) {
6579
6970
  BRIDEX_RUN_JWT: grant.runJwt,
6580
6971
  BRIDEX_RUN_ID: grant.runId
6581
6972
  });
6973
+ if (o.unit === null) delete env[UNIT_VAR];
6974
+ else env[UNIT_VAR] = o.unit;
6582
6975
  return env;
6583
6976
  }
6584
- function mcpServersOf(grant) {
6977
+ function mcpServersOf(grant, unit) {
6585
6978
  const out = {};
6586
- for (const s of grant.mcp)
6587
- out[s.name] = s.type === "http" ? { type: "http", url: s.url, headers: s.headers } : { type: "stdio", command: s.command, args: s.args, env: s.env };
6979
+ for (const s of grant.mcp) {
6980
+ if (s.type === "http") {
6981
+ out[s.name] = { type: "http", url: s.url, headers: s.headers };
6982
+ continue;
6983
+ }
6984
+ const env = { ...s.env };
6985
+ if (unit === null) delete env[UNIT_VAR];
6986
+ else env[UNIT_VAR] = unit;
6987
+ out[s.name] = { type: "stdio", command: s.command, args: s.args, env };
6988
+ }
6588
6989
  return out;
6589
6990
  }
6590
6991
  function writeMcpFiles(presetId, home, servers, instance, warn = () => {
6591
- }) {
6992
+ }, fromEnv = []) {
6592
6993
  const bridex = { url: `${instance}/mcp` };
6593
6994
  const via = CLI_PRESETS[presetId]?.mcpVia;
6594
- if (via === "codex-config") writeCodexMcpConfig(home, servers, bridex, { warn });
6595
- else if (via === "grok-config") writeGrokMcpConfig(home, servers, bridex, { warn });
6596
- else if (via === "gemini-settings") writeGeminiMcpConfig(home, servers, bridex, { warn });
6995
+ if (via === "codex-config") writeCodexMcpConfig(home, servers, bridex, { warn, fromEnv });
6996
+ else if (via === "grok-config") writeGrokMcpConfig(home, servers, bridex, { warn, fromEnv });
6997
+ else if (via === "gemini-settings") writeGeminiMcpConfig(home, servers, bridex, { warn, fromEnv });
6597
6998
  }
6598
6999
  function resolveBin(bin, pathEnv) {
6599
- const candidates = bin.includes("/") ? [bin] : pathEnv.split(path13.delimiter).filter(Boolean).map((d) => path13.join(d, bin));
7000
+ const candidates = bin.includes("/") ? [bin] : pathEnv.split(path14.delimiter).filter(Boolean).map((d) => path14.join(d, bin));
6600
7001
  for (const c of candidates) {
6601
7002
  try {
6602
- return fs16.realpathSync(c);
7003
+ return fs17.realpathSync(c);
6603
7004
  } catch {
6604
7005
  }
6605
7006
  }
6606
7007
  return null;
6607
7008
  }
6608
7009
  var CLI_LOGIN_DIRS = [".claude", ".codex", ".gemini", ".grok"];
6609
- var under = (p, dir) => p === dir || p.startsWith(dir.endsWith(path13.sep) ? dir : dir + path13.sep);
7010
+ var under = (p, dir) => p === dir || p.startsWith(dir.endsWith(path14.sep) ? dir : dir + path14.sep);
6610
7011
  function toolchainRoots(bin, pathEnv, ownerHome) {
6611
7012
  let realHome = ownerHome;
6612
7013
  try {
6613
- realHome = fs16.realpathSync(ownerHome);
7014
+ realHome = fs17.realpathSync(ownerHome);
6614
7015
  } catch {
6615
7016
  }
6616
- const loginDir = (p) => CLI_LOGIN_DIRS.some((d) => p === path13.join(ownerHome, d) || p === path13.join(realHome, d));
7017
+ const loginDir = (p) => CLI_LOGIN_DIRS.some((d) => p === path14.join(ownerHome, d) || p === path14.join(realHome, d));
6617
7018
  const out = /* @__PURE__ */ new Set();
6618
7019
  const add = (p) => {
6619
7020
  if (!loginDir(p)) out.add(p);
6620
7021
  };
6621
- for (const dir of pathEnv.split(path13.delimiter).filter(Boolean)) {
7022
+ for (const dir of pathEnv.split(path14.delimiter).filter(Boolean)) {
6622
7023
  if (!under(dir, ownerHome) || dir === ownerHome) continue;
6623
7024
  add(dir);
6624
- const prefix = path13.dirname(dir);
6625
- if (path13.basename(dir) === "bin" && prefix !== ownerHome && (path13.dirname(prefix) !== ownerHome || fs16.existsSync(path13.join(prefix, "lib", "node_modules"))))
7025
+ const prefix = path14.dirname(dir);
7026
+ if (path14.basename(dir) === "bin" && prefix !== ownerHome && (path14.dirname(prefix) !== ownerHome || fs17.existsSync(path14.join(prefix, "lib", "node_modules"))))
6626
7027
  add(prefix);
6627
7028
  }
6628
7029
  const real = resolveBin(bin, pathEnv);
6629
7030
  const home = real && under(real, realHome) ? realHome : real && under(real, ownerHome) ? ownerHome : null;
6630
7031
  if (real && home) {
6631
- const prefix = path13.dirname(path13.dirname(real));
6632
- const root = loginDir(prefix) ? path13.dirname(real) : prefix;
7032
+ const prefix = path14.dirname(path14.dirname(real));
7033
+ const root = loginDir(prefix) ? path14.dirname(real) : prefix;
6633
7034
  if (root !== home && under(root, home)) add(root);
6634
7035
  }
6635
7036
  return [...out];
@@ -6643,7 +7044,7 @@ function runJail(ctx, readOnly = []) {
6643
7044
  readOnly: [ctx.skillsDir, ctx.templateHome, ctx.browsersDir, ...readOnly].filter((p) => Boolean(p)),
6644
7045
  // the MCP files this worker writes into the HOME, outside the jail: a
6645
7046
  // job left running (or a run beside it) could swap one for a link to write through
6646
- protect: [...protectedGitPaths(ctx.repoDir, ctx.cwd), ...MCP_CONFIG_FILES.map(([rel]) => path13.join(ctx.home, rel))],
7047
+ protect: [...protectedGitPaths(ctx.repoDir, ctx.cwd), ...MCP_CONFIG_FILES.map(([rel]) => path14.join(ctx.home, rel))],
6647
7048
  home: ctx.ownerHome,
6648
7049
  homeAccess: "hidden",
6649
7050
  hidden: ctx.hidden ?? []
@@ -6658,10 +7059,10 @@ var MCP_CONFIG_FILES = [
6658
7059
  function seedMcpFiles(home) {
6659
7060
  unlinkLinks(home, MCP_CONFIG_PATHS);
6660
7061
  for (const [rel, empty] of MCP_CONFIG_FILES) {
6661
- const file = path13.join(home, rel);
6662
- fs16.mkdirSync(path13.dirname(file), { recursive: true });
7062
+ const file = path14.join(home, rel);
7063
+ fs17.mkdirSync(path14.dirname(file), { recursive: true });
6663
7064
  try {
6664
- fs16.writeFileSync(file, empty, { flag: "wx" });
7065
+ fs17.writeFileSync(file, empty, { flag: "wx" });
6665
7066
  } catch {
6666
7067
  }
6667
7068
  }
@@ -6671,12 +7072,19 @@ async function runCliEngine(grant, ctx) {
6671
7072
  const presetId = presetOf(grant.needs);
6672
7073
  const preset = presetId ? CLI_PRESETS[presetId] : void 0;
6673
7074
  if (!presetId || !preset) return { ok: false, resultText: "", error: `no cli preset in the grant's needs (${grant.needs.join(", ") || "none"})` };
6674
- fs16.mkdirSync(ctx.home, { recursive: true });
6675
- fs16.mkdirSync(ctx.artifactsDir, { recursive: true });
6676
- const servers = mcpServersOf(grant);
7075
+ fs17.mkdirSync(ctx.home, { recursive: true });
7076
+ fs17.mkdirSync(ctx.artifactsDir, { recursive: true });
7077
+ const servers = mcpServersOf(grant, ctx.unit);
6677
7078
  unlinkLinks(ctx.home, MCP_CONFIG_PATHS);
6678
- writeMcpFiles(presetId, ctx.home, servers, ctx.instance, (m) => ctx.events.onTranscript({ role: "assistant", content: `(worker) ${m}` }));
6679
- const env = composeEnv(grant, { instance: ctx.instance, home: ctx.home, ...ctx.hostEnv ? { hostEnv: ctx.hostEnv } : {} });
7079
+ writeMcpFiles(
7080
+ presetId,
7081
+ ctx.home,
7082
+ mcpServersOf(grant, null),
7083
+ ctx.instance,
7084
+ (m) => ctx.events.onTranscript({ role: "assistant", content: `(worker) ${m}` }),
7085
+ [UNIT_VAR]
7086
+ );
7087
+ const env = composeEnv(grant, { instance: ctx.instance, home: ctx.home, unit: ctx.unit, ...ctx.hostEnv ? { hostEnv: ctx.hostEnv } : {} });
6680
7088
  const jailed = ctx.jail !== "none";
6681
7089
  const runCli = ctx.runCli ?? runCliOnce;
6682
7090
  const killer = killTreeOnAbort(ctx.abort, ctx.kill, ctx.killGraceMs, ctx.onKillSweep);
@@ -6731,20 +7139,20 @@ async function runCliEngine(grant, ctx) {
6731
7139
  }
6732
7140
 
6733
7141
  // src/runs.ts
6734
- import fs20 from "fs";
7142
+ import fs21 from "fs";
6735
7143
  import os6 from "os";
6736
- import path17 from "path";
7144
+ import path18 from "path";
6737
7145
 
6738
7146
  // src/engines/plan.ts
6739
- import fs17 from "fs";
6740
- import path14 from "path";
7147
+ import fs18 from "fs";
7148
+ import path15 from "path";
6741
7149
  var PLAN_TOOLCHAIN = ["claude", "codex"];
6742
7150
  async function runPlanEngine(grant, ctx) {
6743
7151
  if (!grant.plan) return { ok: false, resultText: "", error: "plan run without a plan: the grant carries none", noRetry: true };
6744
7152
  const { spec, codexArgs } = grant.plan;
6745
- fs17.mkdirSync(ctx.home, { recursive: true });
6746
- fs17.mkdirSync(ctx.artifactsDir, { recursive: true });
6747
- const env = composeEnv(grant, { instance: ctx.instance, home: ctx.home, ...ctx.hostEnv ? { hostEnv: ctx.hostEnv } : {} });
7153
+ fs18.mkdirSync(ctx.home, { recursive: true });
7154
+ fs18.mkdirSync(ctx.artifactsDir, { recursive: true });
7155
+ const env = composeEnv(grant, { instance: ctx.instance, home: ctx.home, unit: ctx.unit, ...ctx.hostEnv ? { hostEnv: ctx.hostEnv } : {} });
6748
7156
  const command = ctx.planCommand ?? { bin: PLAN_BIN, argv: [] };
6749
7157
  const pathEnv = env.PATH ?? "";
6750
7158
  const roots = [...new Set([command.bin, ...PLAN_TOOLCHAIN].flatMap((bin) => toolchainRoots(bin, pathEnv, ctx.ownerHome)))];
@@ -6755,7 +7163,7 @@ async function runPlanEngine(grant, ctx) {
6755
7163
  spec,
6756
7164
  cwd: ctx.cwd,
6757
7165
  env,
6758
- journalRoot: path14.join(ctx.home, PLAN_JOURNAL_DIR),
7166
+ journalRoot: path15.join(ctx.home, PLAN_JOURNAL_DIR),
6759
7167
  runId: grant.runId,
6760
7168
  command,
6761
7169
  wrapSpawn: (bin, argv) => wrapJailed(runJail(ctx, roots), bin, argv),
@@ -6783,7 +7191,7 @@ async function runPlanEngine(grant, ctx) {
6783
7191
 
6784
7192
  // src/engines/sdk.ts
6785
7193
  import { spawn as nodeSpawn2 } from "child_process";
6786
- import fs18 from "fs";
7194
+ import fs19 from "fs";
6787
7195
 
6788
7196
  // ../packages/shared/src/providerLimit.ts
6789
7197
  var MAX_RESET_DAYS = 8;
@@ -6887,7 +7295,7 @@ function turnAnswers(deliver) {
6887
7295
  }
6888
7296
 
6889
7297
  // ../packages/shared/src/toolGate.ts
6890
- import path15 from "path";
7298
+ import path16 from "path";
6891
7299
  var RUN_OUTLIVING_TOOLS = ["Monitor", "CronCreate", "CronDelete", "CronList", "ScheduleWakeup", "RemoteTrigger"];
6892
7300
  function permissionClassOf(toolName) {
6893
7301
  if (toolName === "Bash") return "terminal";
@@ -6905,8 +7313,8 @@ function fileToolPath(toolInput) {
6905
7313
  return typeof p === "string" ? p : null;
6906
7314
  }
6907
7315
  function insideRoots(p, base, roots) {
6908
- const abs = path15.resolve(base, p);
6909
- return roots.some((root) => abs === root || abs.startsWith(root + path15.sep));
7316
+ const abs = path16.resolve(base, p);
7317
+ return roots.some((root) => abs === root || abs.startsWith(root + path16.sep));
6910
7318
  }
6911
7319
  function backgroundTimerRefusal(toolName, toolInput) {
6912
7320
  if (toolName !== "Bash" || !toolInput.run_in_background || typeof toolInput.command !== "string") return null;
@@ -7032,10 +7440,10 @@ function messageEvents(m, toolCalls, events) {
7032
7440
  }
7033
7441
  }
7034
7442
  async function runSdkEngine(grant, ctx) {
7035
- fs18.mkdirSync(ctx.home, { recursive: true });
7036
- fs18.mkdirSync(ctx.artifactsDir, { recursive: true });
7443
+ fs19.mkdirSync(ctx.home, { recursive: true });
7444
+ fs19.mkdirSync(ctx.artifactsDir, { recursive: true });
7037
7445
  const query = ctx.query ?? await loadQuery();
7038
- const env = composeEnv(grant, { instance: ctx.instance, home: ctx.home, ...ctx.hostEnv ? { hostEnv: ctx.hostEnv } : {} });
7446
+ const env = composeEnv(grant, { instance: ctx.instance, home: ctx.home, unit: ctx.unit, ...ctx.hostEnv ? { hostEnv: ctx.hostEnv } : {} });
7039
7447
  const killer = killTreeOnAbort(ctx.abort, ctx.kill, ctx.killGraceMs, ctx.onKillSweep);
7040
7448
  const stderrTail = [];
7041
7449
  const { canUseTool, notes } = createToolGate(grant, ctx);
@@ -7079,7 +7487,7 @@ async function runSdkEngine(grant, ctx) {
7079
7487
  const onAbort = () => sdkAbort.abort();
7080
7488
  if (ctx.abort.aborted) sdkAbort.abort();
7081
7489
  else ctx.abort.addEventListener("abort", onAbort, { once: true });
7082
- const servers = mcpServersOf(grant);
7490
+ const servers = mcpServersOf(grant, ctx.unit);
7083
7491
  const options = {
7084
7492
  cwd: ctx.cwd,
7085
7493
  model: grant.model,
@@ -7180,12 +7588,16 @@ async function runSdkEngine(grant, ctx) {
7180
7588
  }
7181
7589
 
7182
7590
  // src/jobs.ts
7183
- import { execFileSync as execFileSync4, spawn as nodeSpawn3 } from "child_process";
7184
- import fs19 from "fs";
7185
- import path16 from "path";
7591
+ import { execFileSync as execFileSync5, spawn as nodeSpawn3 } from "child_process";
7592
+ import fs20 from "fs";
7593
+ import path17 from "path";
7186
7594
  var NO_SUCH_JOB = "(this machine has no such job any more)";
7187
7595
  var TAIL_BYTES = 64 * 1024;
7596
+ var LAUNCH_WAIT_MS = 6e4;
7188
7597
  var shq = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
7598
+ function isJobFileName(id) {
7599
+ return id !== "" && id !== "." && id !== ".." && !id.includes("\0") && path17.basename(id) === id;
7600
+ }
7189
7601
  function jobSecrets(grant) {
7190
7602
  const values = [grant.runJwt, grant.creds.git.token, ...grant.secretEnv.map((name) => grant.creds.env[name])];
7191
7603
  return [...new Set(values.filter((v) => !!v))];
@@ -7198,14 +7610,14 @@ var defaultSpawn = (bin, argv, o) => nodeSpawn3(bin, argv, { cwd: o.cwd, env: o.
7198
7610
  function commandLineOf(pid, opts = {}) {
7199
7611
  if (opts.proc !== false) {
7200
7612
  try {
7201
- return fs19.readFileSync(`/proc/${pid}/cmdline`, "utf8");
7613
+ return fs20.readFileSync(`/proc/${pid}/cmdline`, "utf8");
7202
7614
  } catch (err) {
7203
7615
  if (err.code !== "ENOENT") return void 0;
7204
- if (fs19.existsSync("/proc/self")) return null;
7616
+ if (fs20.existsSync("/proc/self")) return null;
7205
7617
  }
7206
7618
  }
7207
7619
  try {
7208
- const out = execFileSync4(opts.ps ?? "ps", ["-ww", "-o", "command=", "-p", String(pid)], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5e3 });
7620
+ const out = execFileSync5(opts.ps ?? "ps", ["-ww", "-o", "command=", "-p", String(pid)], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5e3 });
7209
7621
  return out.trim() || null;
7210
7622
  } catch (err) {
7211
7623
  return err.status === 1 ? null : void 0;
@@ -7221,14 +7633,49 @@ function jobAlive(pid, jobId, opts = {}) {
7221
7633
  return false;
7222
7634
  }
7223
7635
  }
7224
- function killGroup(pgid, delays = [50, 200, 750, 1500]) {
7636
+ function killGroup(pgid, delays = [50, 200, 750, 1500], still = () => true) {
7637
+ if (!still()) return;
7225
7638
  try {
7226
7639
  process.kill(-pgid, "SIGKILL");
7227
7640
  } catch {
7228
7641
  return;
7229
7642
  }
7230
7643
  const [delay, ...rest2] = delays;
7231
- if (delay !== void 0) setTimeout(() => killGroup(pgid, rest2), delay).unref();
7644
+ if (delay !== void 0) setTimeout(() => killGroup(pgid, rest2, still), delay).unref();
7645
+ }
7646
+ function reaches(target) {
7647
+ try {
7648
+ process.kill(target, 0);
7649
+ return true;
7650
+ } catch (err) {
7651
+ return err.code === "EPERM";
7652
+ }
7653
+ }
7654
+ function jobGroupLeft(pgid) {
7655
+ return !reaches(pgid) && reaches(-pgid);
7656
+ }
7657
+ var GROUP_WATCH_MS = 25;
7658
+ var GROUP_GAP_MS = 250;
7659
+ var GROUP_WATCH_LIMIT_MS = 3e4;
7660
+ function watchGroup(left, o = {}) {
7661
+ if (!left()) return null;
7662
+ const now = o.now ?? (() => performance.now());
7663
+ const gapMs = o.gapMs ?? GROUP_GAP_MS;
7664
+ const limitMs = o.limitMs ?? GROUP_WATCH_LIMIT_MS;
7665
+ const start = now();
7666
+ let seen = start;
7667
+ let ok = true;
7668
+ const look = () => {
7669
+ if (!ok) return false;
7670
+ const t = now();
7671
+ ok = t - seen <= gapMs && t - start <= limitMs && left();
7672
+ if (ok) seen = t;
7673
+ else clearInterval(timer);
7674
+ return ok;
7675
+ };
7676
+ const timer = setInterval(look, o.everyMs ?? GROUP_WATCH_MS);
7677
+ timer.unref();
7678
+ return look;
7232
7679
  }
7233
7680
  function defaultKill(pid) {
7234
7681
  killTree(pid, "SIGKILL");
@@ -7236,15 +7683,15 @@ function defaultKill(pid) {
7236
7683
  }
7237
7684
  function tailOf(file, maxBytes) {
7238
7685
  try {
7239
- const size = fs19.statSync(file).size;
7686
+ const size = fs20.statSync(file).size;
7240
7687
  const start = Math.max(0, size - maxBytes);
7241
- const fd = fs19.openSync(file, "r");
7688
+ const fd = fs20.openSync(file, "r");
7242
7689
  try {
7243
7690
  const buf = Buffer.alloc(Math.min(size, maxBytes));
7244
- fs19.readSync(fd, buf, 0, buf.length, start);
7691
+ fs20.readSync(fd, buf, 0, buf.length, start);
7245
7692
  return { text: (start > 0 ? "\u2026[earlier output trimmed]\n" : "") + buf.toString("utf8"), truncated: start > 0 };
7246
7693
  } finally {
7247
- fs19.closeSync(fd);
7694
+ fs20.closeSync(fd);
7248
7695
  }
7249
7696
  } catch {
7250
7697
  return { text: "", truncated: false };
@@ -7258,19 +7705,117 @@ function createJobs(deps) {
7258
7705
  const now = deps.now ?? Date.now;
7259
7706
  const slack = deps.timeoutSlackMs ?? 2 * 6e4;
7260
7707
  const keepSent = deps.keepSentMs ?? (() => 7 * 6e4);
7708
+ const sweepUnit = deps.sweep ?? ((tag, graceMs) => endTagged(matchTag(tag), { graceMs }));
7709
+ const endGrace = deps.endGraceMs ?? END_GRACE_MS;
7710
+ const killJobGroup = deps.killGroup ?? ((pgid, still) => killGroup(pgid, void 0, still));
7711
+ const groupLeft = deps.groupLeft ?? jobGroupLeft;
7712
+ let recoveryComplete = false;
7713
+ const unreadable = /* @__PURE__ */ new Set();
7261
7714
  const files = (id) => ({
7262
- meta: path16.join(deps.dir, `${id}.json`),
7263
- log: path16.join(deps.dir, `${id}.log`),
7264
- exit: path16.join(deps.dir, `${id}.exit`),
7265
- outer: path16.join(deps.dir, `${id}.outer.log`)
7715
+ meta: path17.join(deps.dir, `${id}.json`),
7716
+ log: path17.join(deps.dir, `${id}.log`),
7717
+ exit: path17.join(deps.dir, `${id}.exit`),
7718
+ outer: path17.join(deps.dir, `${id}.outer.log`),
7719
+ pid: path17.join(deps.dir, `${id}.pid`),
7720
+ /** the record being rewritten, whole, kept beside it until the rewrite is done (`writeMeta`) */
7721
+ next: path17.join(deps.dir, `${id}.json.next`),
7722
+ /** where `next` is written before it is renamed into place: `next` is never cut */
7723
+ nextTmp: path17.join(deps.dir, `${id}.json.next.tmp`)
7266
7724
  });
7267
- const writeMeta = (meta) => fs19.writeFileSync(files(meta.jobId).meta, JSON.stringify(meta), { mode: 384 });
7725
+ const writeNext = (f, text) => {
7726
+ try {
7727
+ fs20.writeFileSync(f.nextTmp, text, { mode: 384 });
7728
+ fs20.renameSync(f.nextTmp, f.next);
7729
+ } catch (err) {
7730
+ try {
7731
+ fs20.rmSync(f.nextTmp, { force: true });
7732
+ } catch {
7733
+ }
7734
+ throw err;
7735
+ }
7736
+ };
7737
+ const writeMeta = (meta, create = false) => {
7738
+ const f = files(meta.jobId);
7739
+ let fd;
7740
+ try {
7741
+ fd = fs20.openSync(f.meta, create ? "w" : "r+", 384);
7742
+ } catch (err) {
7743
+ if (!create && err.code === "ENOENT") return false;
7744
+ throw err;
7745
+ }
7746
+ let kept = true;
7747
+ try {
7748
+ const text = JSON.stringify(meta);
7749
+ const json = Buffer.from(text);
7750
+ const old = create ? 0 : fs20.fstatSync(fd).size;
7751
+ if (!create) writeNext(f, text);
7752
+ const out = json.length >= old ? json : Buffer.concat([json, Buffer.alloc(old - json.length, " ")]);
7753
+ for (let at = 0; at < out.length; ) at += fs20.writeSync(fd, out, at, out.length - at, at);
7754
+ if (out.length > json.length) fs20.ftruncateSync(fd, json.length);
7755
+ if (!create && fs20.fstatSync(fd).nlink === 0) kept = false;
7756
+ } finally {
7757
+ fs20.closeSync(fd);
7758
+ }
7759
+ if (!create) fs20.rmSync(f.next, { force: true });
7760
+ return kept;
7761
+ };
7762
+ const readRecord = (id) => {
7763
+ const f = files(id);
7764
+ const read = (file) => {
7765
+ try {
7766
+ return fs20.readFileSync(file, "utf8");
7767
+ } catch {
7768
+ return null;
7769
+ }
7770
+ };
7771
+ const parse2 = (text) => {
7772
+ if (text === null) return null;
7773
+ try {
7774
+ const meta = JSON.parse(text);
7775
+ return meta?.jobId ? meta : null;
7776
+ } catch {
7777
+ return null;
7778
+ }
7779
+ };
7780
+ let raw = read(f.meta);
7781
+ for (let tries = 0; raw !== null && tries < 3; tries++) {
7782
+ const next = parse2(read(f.next));
7783
+ if (next) return next;
7784
+ const again = read(f.meta);
7785
+ if (again === raw) return parse2(raw);
7786
+ raw = again;
7787
+ }
7788
+ return null;
7789
+ };
7268
7790
  const removeFiles = (id) => {
7269
- for (const f of Object.values(files(id))) fs19.rmSync(f, { force: true });
7791
+ for (const f of Object.values(files(id))) {
7792
+ try {
7793
+ fs20.rmSync(f, { force: true });
7794
+ } catch (err) {
7795
+ deps.log(`job ${id}: could not remove ${path17.basename(f)}: ${err.message}`, "warn");
7796
+ }
7797
+ }
7798
+ };
7799
+ const launcherPid = (id) => {
7800
+ try {
7801
+ const raw = fs20.readFileSync(files(id).pid, "utf8").trim();
7802
+ const pid = /^\d+$/.test(raw) ? Number(raw) : NaN;
7803
+ return Number.isSafeInteger(pid) && pid > 1 ? pid : null;
7804
+ } catch {
7805
+ return null;
7806
+ }
7807
+ };
7808
+ const recordPid = (id) => {
7809
+ const pid = readRecord(id)?.pid;
7810
+ return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 1 ? pid : null;
7811
+ };
7812
+ const starting = (meta) => {
7813
+ const age = now() - meta.startedAt;
7814
+ return age > -LAUNCH_WAIT_MS && age < LAUNCH_WAIT_MS;
7270
7815
  };
7271
7816
  const readExit = (id) => {
7272
7817
  try {
7273
- const raw = fs19.readFileSync(files(id).exit, "utf8").trim();
7818
+ const raw = fs20.readFileSync(files(id).exit, "utf8").trim();
7274
7819
  if (raw === "") return void 0;
7275
7820
  const code = Number.parseInt(raw, 10);
7276
7821
  return Number.isNaN(code) ? null : code;
@@ -7317,7 +7862,7 @@ function createJobs(deps) {
7317
7862
  const spec = job.meta.settle;
7318
7863
  if (!spec || job.meta.settled || !deps.settle) return report(id);
7319
7864
  job.settling = true;
7320
- const dropped = () => jobs.get(id) !== job || job.meta.settle !== spec;
7865
+ const dropped = () => jobs.get(id) !== job || job.meta.settle !== spec || !fs20.existsSync(files(id).meta);
7321
7866
  const before = job.meta.delivering;
7322
7867
  const keep = (going) => {
7323
7868
  if (dropped()) return;
@@ -7342,25 +7887,58 @@ function createJobs(deps) {
7342
7887
  report(id);
7343
7888
  });
7344
7889
  }
7345
- function finish(id, outcome) {
7890
+ function sweepOf(id, unit, graceMs) {
7891
+ let swept;
7892
+ try {
7893
+ swept = Promise.resolve(sweepUnit(unit, graceMs));
7894
+ } catch (err) {
7895
+ swept = Promise.reject(err);
7896
+ }
7897
+ deps.onSweep?.(swept);
7898
+ return swept.catch(() => ({ ended: [], refused: [], readFailed: true })).then(({ ended, refused, readFailed }) => {
7899
+ if (readFailed) deps.log(`job ${id}: could not list this machine's processes \u2014 what the job left running may not be ended`, "warn");
7900
+ if (ended.length) deps.log(`job ${id}: ended ${describeEnded(ended)} the job left running`, "warn");
7901
+ if (refused.length) deps.log(`job ${id}: could not end ${describeEnded(refused)} the job left running \u2014 not permitted to signal them`, "warn");
7902
+ });
7903
+ }
7904
+ function finish(id, outcome, graceMs = endGrace) {
7346
7905
  const job = jobs.get(id);
7347
7906
  if (!job || job.outcome) return;
7348
7907
  job.outcome = outcome;
7349
- letGo(job);
7350
7908
  deps.log(`job ${id} (${job.meta.label}): ${outcome.code === 0 ? "succeeded" : `failed \u2014 ${outcome.error ?? `exit ${outcome.code}`}`}`, outcome.code === 0 ? "ok" : "err");
7351
- settleThenReport(id);
7909
+ const unit = job.meta.unit;
7910
+ if (!unit || job.meta.pid === null) {
7911
+ letGo(job);
7912
+ return settleThenReport(id);
7913
+ }
7914
+ job.settling = true;
7915
+ job.swept = sweepOf(id, unit, graceMs);
7916
+ void job.swept.then(() => {
7917
+ job.settling = false;
7918
+ if (jobs.get(id) !== job) return;
7919
+ letGo(job);
7920
+ settleThenReport(id);
7921
+ });
7352
7922
  }
7353
7923
  function check2(id) {
7354
7924
  const job = jobs.get(id);
7355
7925
  if (!job || job.outcome) return;
7926
+ const { meta } = job;
7927
+ if (!meta.pid) meta.pid = launcherPid(id) ?? recordPid(id);
7356
7928
  const code = readExit(id);
7357
7929
  if (code !== void 0) return finish(id, { code });
7358
- const { meta } = job;
7359
7930
  if (meta.timeoutMinutes && meta.startedAt + meta.timeoutMinutes * 6e4 + slack < now()) {
7360
- if (meta.pid && alive(meta.pid, id)) kill(meta.pid);
7361
- return finish(id, { code: null, error: `ran past its ${meta.timeoutMinutes}-minute timeout` });
7931
+ if (meta.pid && alive(meta.pid, id)) {
7932
+ kill(meta.pid);
7933
+ job.groupKilled = true;
7934
+ }
7935
+ return finish(id, { code: null, error: `ran past its ${meta.timeoutMinutes}-minute timeout` }, 0);
7936
+ }
7937
+ if (!meta.pid) {
7938
+ if (!starting(meta)) finish(id, { code: null, error: "the job never started \u2014 the worker that started it stopped as it did (no process was named)" });
7939
+ return;
7362
7940
  }
7363
- if (meta.pid && !alive(meta.pid, id)) {
7941
+ if (!alive(meta.pid, id)) {
7364
7942
  const late = readExit(id);
7365
7943
  finish(id, late !== void 0 ? { code: late } : { code: null, error: "the process is gone and left no exit code \u2014 it was killed (out of memory?)" });
7366
7944
  }
@@ -7382,7 +7960,12 @@ function createJobs(deps) {
7382
7960
  */
7383
7961
  start(frame, ctx, instance) {
7384
7962
  if (jobs.has(frame.jobId)) return;
7385
- fs19.mkdirSync(deps.dir, { recursive: true });
7963
+ if (!isJobFileName(frame.jobId)) {
7964
+ deps.log(`job ${JSON.stringify(frame.jobId)}: refused \u2014 its id is not a file name of the jobs folder`, "err");
7965
+ deps.send({ type: "jobExit", jobId: frame.jobId, code: null, tail: "", error: "refused: the job's id cannot name a file of this machine's jobs folder" }, instance);
7966
+ return;
7967
+ }
7968
+ fs20.mkdirSync(deps.dir, { recursive: true });
7386
7969
  const meta = {
7387
7970
  jobId: frame.jobId,
7388
7971
  runId: frame.runId,
@@ -7395,35 +7978,72 @@ function createJobs(deps) {
7395
7978
  ...ctx?.settle ? { settle: { ...ctx.settle } } : {},
7396
7979
  ...ctx?.secrets?.length ? { secrets: [...ctx.secrets] } : {}
7397
7980
  };
7981
+ const unit = deps.tagOf?.(frame.jobId) ?? null;
7982
+ if (unit !== null) meta.unit = unit;
7398
7983
  const job = { meta, release: null, outcome: null, reportedAt: null };
7399
7984
  jobs.set(frame.jobId, job);
7400
- writeMeta(meta);
7985
+ writeMeta(meta, true);
7401
7986
  if (!ctx) return finish(frame.jobId, { code: null, error: `run ${frame.runId} is not executing on this machine any more` });
7402
7987
  const f = files(frame.jobId);
7403
7988
  const inner = wrapJailed(ctx.jail, "/bin/bash", ["-c", frame.command]);
7404
- const script = `( ${[inner.bin, ...inner.argv].map(shq).join(" ")} ) > ${shq(f.log)} 2>&1 ; printf %s $? > ${shq(f.exit)}`;
7989
+ const script = `printf %s $$ > ${shq(f.pid)} || { /bin/rm -f ${shq(f.pid)} ; exit 1 ; } ; [ -e ${shq(f.meta)} ] || { /bin/rm -f ${shq(f.pid)} ; exit 0 ; } ; ( ${[inner.bin, ...inner.argv].map(shq).join(" ")} ) > ${shq(f.log)} 2>&1 ; printf %s $? > ${shq(f.exit)}`;
7405
7990
  let outFd = null;
7991
+ let child;
7406
7992
  try {
7407
- outFd = fs19.openSync(f.outer, "a");
7408
- const child = spawn7("/bin/bash", ["-c", script], { cwd: ctx.cwd, env: { ...ctx.env, ...frame.env }, outFd });
7993
+ outFd = fs20.openSync(f.outer, "a");
7994
+ const env = { ...ctx.env, ...frame.env };
7995
+ if (unit === null) delete env[UNIT_VAR];
7996
+ else env[UNIT_VAR] = unit;
7997
+ child = spawn7("/bin/bash", ["-c", script], { cwd: ctx.cwd, env, outFd });
7409
7998
  child.on("error", (err) => finish(frame.jobId, { code: null, error: `could not start: ${err.message}` }));
7410
- child.on("exit", () => check2(frame.jobId));
7999
+ child.on("exit", () => {
8000
+ const pgid = child.pid;
8001
+ const still = pgid && !job.groupKilled ? watchGroup(() => groupLeft(pgid)) : null;
8002
+ setImmediate(() => {
8003
+ check2(frame.jobId);
8004
+ if (!pgid || !still || job.groupKilled) return;
8005
+ const end = () => killJobGroup(pgid, still);
8006
+ if (job.swept) void job.swept.then(end);
8007
+ else end();
8008
+ });
8009
+ });
7411
8010
  child.unref();
7412
- meta.pid = child.pid ?? null;
7413
- writeMeta(meta);
7414
8011
  } catch (err) {
7415
8012
  return finish(frame.jobId, { code: null, error: `could not start: ${err.message}` });
7416
8013
  } finally {
7417
- if (outFd !== null) fs19.closeSync(outFd);
8014
+ if (outFd !== null) fs20.closeSync(outFd);
8015
+ }
8016
+ meta.pid = child.pid ?? null;
8017
+ let recorded = true;
8018
+ try {
8019
+ recorded = writeMeta(meta);
8020
+ } catch (err) {
8021
+ deps.log(`job ${frame.jobId}: recording its process failed: ${err.message} \u2014 it runs on, watched by its pid`, "warn");
8022
+ }
8023
+ if (!recorded) {
8024
+ delete meta.settle;
8025
+ return finish(frame.jobId, { code: null, error: "cancelled as it started \u2014 another worker process on this cache dir removed its record" }, 0);
7418
8026
  }
7419
8027
  job.release = deps.hold(ctx.checkout, `job:${frame.jobId}`);
7420
8028
  deps.log(`job ${frame.jobId} started for run ${frame.runId}: ${frame.label}`, "info");
7421
8029
  },
7422
- /** The instance stopped the job (or no longer has it — an end it got): kill it and forget it, no report. */
8030
+ /**
8031
+ * The instance stopped the job (or no longer has it — an end it got): kill
8032
+ * it, end what is left of its tag with no grace, and forget it, no report.
8033
+ */
7423
8034
  cancel(jobId) {
7424
8035
  const job = jobs.get(jobId);
7425
8036
  if (!job) return false;
7426
- if (!job.outcome && job.meta.pid && alive(job.meta.pid, jobId)) kill(job.meta.pid);
8037
+ if (!job.outcome && !job.meta.pid) {
8038
+ const recorded = recordPid(jobId);
8039
+ fs20.rmSync(files(jobId).meta, { force: true });
8040
+ job.meta.pid = launcherPid(jobId) ?? recorded;
8041
+ }
8042
+ if (!job.outcome && job.meta.pid && alive(job.meta.pid, jobId)) {
8043
+ kill(job.meta.pid);
8044
+ job.groupKilled = true;
8045
+ }
8046
+ if (job.meta.unit && job.meta.pid !== null) job.swept = sweepOf(jobId, job.meta.unit, 0);
7427
8047
  letGo(job);
7428
8048
  forget(jobId);
7429
8049
  if (!job.outcome) deps.log(`job ${jobId}: cancelled from the instance`, "warn");
@@ -7450,7 +8070,11 @@ function createJobs(deps) {
7450
8070
  for (const job of jobs.values()) {
7451
8071
  if (job.meta.runId !== runId || !job.meta.settle) continue;
7452
8072
  delete job.meta.settle;
7453
- writeMeta(job.meta);
8073
+ try {
8074
+ writeMeta(job.meta);
8075
+ } catch (err) {
8076
+ deps.log(`job ${job.meta.jobId}: recording that its folder is not to be sent failed: ${err.message}`, "warn");
8077
+ }
7454
8078
  }
7455
8079
  },
7456
8080
  /** A connection is up: send every end again, the unreported and the lately sent — of the jobs `of` its instance (`Meta.instance`). */
@@ -7468,35 +8092,85 @@ function createJobs(deps) {
7468
8092
  * first if that had not been; one still running is watched again and
7469
8093
  * holds its checkout. `onEach` is called before each job is looked at:
7470
8094
  * the worker puts its lifeline off with it, as the scan grows with the
7471
- * jobs left and may take seconds for each.
8095
+ * jobs left and may take seconds for each. `late`: taken after the start
8096
+ * sweep (runs.ts `sweepAtStart`), which ended nothing of a job not known
8097
+ * then — one found ended has its tag swept before its checkout is let go
8098
+ * and its folder goes up, as a watched job's end does (`finish`). `late`
8099
+ * takes no job with no tag, nor one whose tag `peer` says names another
8100
+ * worker process still running: that one has the job as its own. Without
8101
+ * `late`, `peer` keeps out only a job being started (no pid in its record
8102
+ * yet, whatever its launcher's pid file says) by such a process.
7472
8103
  */
7473
- recover(onEach) {
8104
+ recover(onEach, o = {}) {
8105
+ recoveryComplete = true;
8106
+ unreadable.clear();
7474
8107
  let names = [];
7475
8108
  try {
7476
- names = fs19.readdirSync(deps.dir).filter((n) => n.endsWith(".json"));
7477
- } catch {
8109
+ names = fs20.readdirSync(deps.dir).filter((n) => n.endsWith(".json"));
8110
+ } catch (err) {
8111
+ if (err.code !== "ENOENT") recoveryComplete = false;
7478
8112
  return [];
7479
8113
  }
7480
8114
  for (const name of names) {
7481
8115
  onEach?.();
7482
- let meta;
7483
- try {
7484
- meta = JSON.parse(fs19.readFileSync(path16.join(deps.dir, name), "utf8"));
7485
- } catch {
8116
+ const meta = readRecord(name.slice(0, -".json".length));
8117
+ if (!meta) {
8118
+ unreadable.add(name.slice(0, -".json".length));
7486
8119
  continue;
7487
8120
  }
7488
- if (!meta.jobId || jobs.has(meta.jobId)) continue;
8121
+ if (jobs.has(meta.jobId)) continue;
8122
+ if (o.late && (!meta.unit || o.peer?.(meta.unit))) continue;
8123
+ if (!meta.pid && meta.unit && starting(meta) && o.peer?.(meta.unit)) continue;
8124
+ if (!meta.pid) meta.pid = launcherPid(meta.jobId);
7489
8125
  const job = { meta, release: null, outcome: null, reportedAt: null };
7490
8126
  jobs.set(meta.jobId, job);
7491
8127
  const code = readExit(meta.jobId);
7492
- if (code !== void 0) job.outcome = { code };
7493
- else if (meta.pid && alive(meta.pid, meta.jobId)) {
8128
+ let outcome = null;
8129
+ if (code !== void 0) outcome = { code };
8130
+ else if (meta.pid ? alive(meta.pid, meta.jobId) : starting(meta)) {
8131
+ if (meta.checkout) job.release = deps.hold(meta.checkout, `job:${meta.jobId}`);
8132
+ } else {
8133
+ const late = readExit(meta.jobId);
8134
+ outcome = late !== void 0 ? { code: late } : { code: null, error: "the process is gone and left no exit code \u2014 this worker restarted while it ran (machine reboot?)" };
8135
+ }
8136
+ if (!outcome) continue;
8137
+ if (o.late) {
7494
8138
  if (meta.checkout) job.release = deps.hold(meta.checkout, `job:${meta.jobId}`);
7495
- } else job.outcome = { code: null, error: "the process is gone and left no exit code \u2014 this worker restarted while it ran (machine reboot?)" };
7496
- if (job.outcome) settleThenReport(meta.jobId);
8139
+ finish(meta.jobId, outcome);
8140
+ } else {
8141
+ job.outcome = outcome;
8142
+ settleThenReport(meta.jobId);
8143
+ }
7497
8144
  }
7498
8145
  return [...jobs.keys()].sort();
7499
8146
  },
8147
+ /**
8148
+ * What the last `recover` found: `complete` when it listed the jobs folder
8149
+ * (one it could not list leaves jobs it does not know of — and their
8150
+ * processes may still run); `unended` the jobs not known to have ended:
8151
+ * those with no outcome now, and those whose record it could not read,
8152
+ * named by their file. Before any `recover`: incomplete.
8153
+ */
8154
+ recovery() {
8155
+ const running = [...jobs].filter(([, job]) => !job.outcome).map(([id]) => id);
8156
+ return { complete: recoveryComplete, unended: [.../* @__PURE__ */ new Set([...running, ...unreadable])].sort() };
8157
+ },
8158
+ /**
8159
+ * Job `id` has a record now that the last `recover` did not take: another
8160
+ * worker process on this cache dir started it after the folder was listed,
8161
+ * or was starting it as it was (`peer`) — and may have stopped since,
8162
+ * leaving it running. Asked of each job unit
8163
+ * the start sweep finds; one this cannot tell about counts as such.
8164
+ */
8165
+ recordedSince(id) {
8166
+ if (jobs.has(id) || unreadable.has(id) || !isJobFileName(id)) return false;
8167
+ try {
8168
+ fs20.statSync(files(id).meta);
8169
+ return true;
8170
+ } catch (err) {
8171
+ return err.code !== "ENOENT";
8172
+ }
8173
+ },
7500
8174
  /** jobs running here, or ended and not confirmed by the instance — `hello.jobs` */
7501
8175
  liveIds() {
7502
8176
  return [...jobs.keys()].sort();
@@ -7608,7 +8282,7 @@ function memo(make) {
7608
8282
  }
7609
8283
  function runHomeOf(cacheDir, instanceSegment, workspace, agent) {
7610
8284
  const safe2 = (s) => s.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 60) || "_";
7611
- return path17.join(cacheDir, "homes", instanceSegment, `${safe2(workspace)}-${hashKey(workspace).slice(0, 8)}`, safe2(agent));
8285
+ return path18.join(cacheDir, "homes", instanceSegment, `${safe2(workspace)}-${hashKey(workspace).slice(0, 8)}`, safe2(agent));
7612
8286
  }
7613
8287
  async function pushTaskBranch(git2, checkout, runId, auth, repoUrl, capBytes = WIP_FILE_CAP_MB * 1024 ** 2, givenUp = () => false) {
7614
8288
  if (!checkout.branch) return { pushed: false, error: "the checkout has no task branch" };
@@ -7635,7 +8309,7 @@ async function commitLeftovers(git2, cwd, runId, local, capBytes) {
7635
8309
  if (!dirty.trim() && !merging.length) return [];
7636
8310
  await git2(cwd, ["add", "-A"], local);
7637
8311
  const staged = (await git2(cwd, ["diff", "--cached", "--name-only", "-z", "--no-renames", "--diff-filter=d"], local)).split("\0").filter(Boolean);
7638
- const uncommitted = staged.filter((rel) => sizeOf(path17.join(cwd, rel)) >= capBytes);
8312
+ const uncommitted = staged.filter((rel) => sizeOf(path18.join(cwd, rel)) >= capBytes);
7639
8313
  if (uncommitted.length) await git2(cwd, ["reset", "-q", "--", ...uncommitted], { ...local, GIT_LITERAL_PATHSPECS: "1" });
7640
8314
  const left = (await git2(cwd, ["diff", "--cached", "--name-only", "-z"], local)).trim();
7641
8315
  if (left || merging.length) {
@@ -7649,10 +8323,10 @@ async function commitLeftovers(git2, cwd, runId, local, capBytes) {
7649
8323
  return uncommitted;
7650
8324
  }
7651
8325
  async function mergeHeads(git2, cwd, local) {
7652
- const file = path17.resolve(cwd, (await git2(cwd, ["rev-parse", "--git-path", "MERGE_HEAD"], local)).trim());
8326
+ const file = path18.resolve(cwd, (await git2(cwd, ["rev-parse", "--git-path", "MERGE_HEAD"], local)).trim());
7653
8327
  let text;
7654
8328
  try {
7655
- const fh = await fs20.promises.open(file, fs20.constants.O_RDONLY | (fs20.constants.O_NOFOLLOW ?? 0) | (fs20.constants.O_NONBLOCK ?? 0));
8329
+ const fh = await fs21.promises.open(file, fs21.constants.O_RDONLY | (fs21.constants.O_NOFOLLOW ?? 0) | (fs21.constants.O_NONBLOCK ?? 0));
7656
8330
  try {
7657
8331
  const st = await fh.stat();
7658
8332
  if (!st.isFile() || st.size > 64 * 1024) return [];
@@ -7694,7 +8368,7 @@ async function setAsideTaskBranch(git2, checkout, runId, baseBranch, capBytes =
7694
8368
  }
7695
8369
  function sizeOf(p) {
7696
8370
  try {
7697
- return fs20.lstatSync(p).size;
8371
+ return fs21.lstatSync(p).size;
7698
8372
  } catch {
7699
8373
  return 0;
7700
8374
  }
@@ -7710,6 +8384,14 @@ function engineOf(needs) {
7710
8384
  const preset = presetOf(needs);
7711
8385
  return preset ? { kind: "cli", preset } : null;
7712
8386
  }
8387
+ function pidAlive(pid) {
8388
+ try {
8389
+ process.kill(pid, 0);
8390
+ return true;
8391
+ } catch (err) {
8392
+ return err.code === "EPERM";
8393
+ }
8394
+ }
7713
8395
  function createRunner(deps) {
7714
8396
  const live = /* @__PURE__ */ new Map();
7715
8397
  const running = /* @__PURE__ */ new Map();
@@ -7728,6 +8410,25 @@ function createRunner(deps) {
7728
8410
  const cli = deps.cli ?? runCliEngine;
7729
8411
  const sdk = deps.sdk ?? runSdkEngine;
7730
8412
  const plan = deps.plan ?? runPlanEngine;
8413
+ const install2 = installIdOf(deps.cfg.cache_dir);
8414
+ const sweep = deps.sweep ?? endTagged;
8415
+ const workerAlive = deps.workerAlive ?? pidAlive;
8416
+ const peerJob = (tag) => {
8417
+ const u = parseTag(tag);
8418
+ return !u || u.install !== install2 || u.workerPid !== process.pid && workerAlive(u.workerPid);
8419
+ };
8420
+ const sweepTag = async (tag, graceMs) => {
8421
+ let r;
8422
+ try {
8423
+ r = await sweep(matchTag(tag), { graceMs });
8424
+ } catch {
8425
+ return { ended: [], refused: [], readFailed: true, done: Promise.resolve() };
8426
+ }
8427
+ noteSweep(Promise.resolve(r.done).then(() => {
8428
+ }, () => {
8429
+ }));
8430
+ return r;
8431
+ };
7731
8432
  const conns = /* @__PURE__ */ new Map();
7732
8433
  const connOf = (instance) => {
7733
8434
  let c = conns.get(instance);
@@ -7741,7 +8442,7 @@ function createRunner(deps) {
7741
8442
  const artifactsFor = memo((instance) => deps.artifactsFor ? deps.artifactsFor(instance) : deps.artifacts);
7742
8443
  const skillsFor = memo((instance) => deps.skillsFor ? deps.skillsFor(instance) : deps.skills);
7743
8444
  const jobs = createJobs({
7744
- dir: path17.join(deps.cfg.cache_dir, "jobs"),
8445
+ dir: path18.join(deps.cfg.cache_dir, "jobs"),
7745
8446
  send: (frame, instance) => {
7746
8447
  const link = conns.get(instance ?? deps.cfg.instance)?.link;
7747
8448
  if (!link) return false;
@@ -7754,6 +8455,14 @@ function createRunner(deps) {
7754
8455
  settle: (spec, job, hooks) => settleJob(spec, job, hooks),
7755
8456
  // as a run's sent result: the grace, and then some
7756
8457
  keepSentMs: () => longestGraceS() * 1e3 + 5 * 6e4,
8458
+ tagOf: (jobId) => tryTagOf(install2, process.pid, "job", jobId),
8459
+ // what a job left running ends with it, as a run's does
8460
+ sweep: sweepTag,
8461
+ endGraceMs: deps.killGraceMs ?? END_GRACE_MS,
8462
+ // a shutdown waits for a job's sweep from its start: a cancelled job's kill pass, and the passes after it
8463
+ onSweep: (swept) => noteSweep(swept.then((r) => r.done).then(() => {
8464
+ }, () => {
8465
+ })),
7757
8466
  ...deps.jobDeps
7758
8467
  });
7759
8468
  const jobInstance = (jobId) => {
@@ -7944,6 +8653,7 @@ function createRunner(deps) {
7944
8653
  deps.log(`run ${runId}: ${o.ok && !stopped ? "finished" : `failed \u2014 ${error ?? "no reason"}`}${push.pushed ? ", branch pushed" : push.error ? ` (${push.error})` : ""}`, o.ok && !stopped ? "ok" : "err");
7945
8654
  if (push.uncommitted) deps.log(`run ${runId}: left out of the commit (${WIP_FILE_CAP_MB} MB or more), still in the checkout: ${push.uncommitted.join(", ")}`, "warn");
7946
8655
  };
8656
+ let tagged = null;
7947
8657
  let checkout;
7948
8658
  try {
7949
8659
  checkout = await deps.cache.checkoutForRun(instance, grant.project, grant.creds.git, runId);
@@ -7967,7 +8677,7 @@ function createRunner(deps) {
7967
8677
  }
7968
8678
  const runGrant = {
7969
8679
  ...grant,
7970
- systemPrompt: grant.systemPrompt.replaceAll(WORKER_ARTIFACTS_ROOT, path17.dirname(artifactsDir)).replaceAll(WORKER_SKILLS_ROOT, slice?.dir ?? "(skill files are not on this machine \u2014 read them with skill_view)")
8680
+ systemPrompt: grant.systemPrompt.replaceAll(WORKER_ARTIFACTS_ROOT, path18.dirname(artifactsDir)).replaceAll(WORKER_SKILLS_ROOT, slice?.dir ?? "(skill files are not on this machine \u2014 read them with skill_view)")
7971
8681
  };
7972
8682
  if (artifacts && !ctl.signal.aborted) {
7973
8683
  await settling.get(`${instance}\0${grant.project.taskId}`);
@@ -7985,14 +8695,17 @@ function createRunner(deps) {
7985
8695
  const browsersDir = templateBrowsers ? null : playwrightBrowsers(ownerHome);
7986
8696
  const browsersPath = templateBrowsers ? "0" : browsersDir;
7987
8697
  const hostEnv = browsersPath ? { ...process.env, PLAYWRIGHT_BROWSERS_PATH: browsersPath } : void 0;
8698
+ const unit = tryTagOf(install2, process.pid, "run", runId);
8699
+ if (unit === null) deps.log(`run ${runId}: its id cannot be put into a process tag \u2014 what it leaves behind is not ended`, "warn");
7988
8700
  const ctx = {
7989
8701
  instance,
8702
+ unit,
7990
8703
  cwd: checkout.cwd,
7991
8704
  repoDir: checkout.repoDir,
7992
8705
  home: runHomeOf(deps.cfg.cache_dir, deps.cache.instanceSegment(instance), grant.workspace, grant.agent),
7993
8706
  artifactsDir,
7994
8707
  ...slice?.dir ? { skillsDir: slice.dir } : {},
7995
- ...templateHome && fs20.existsSync(templateHome) ? { templateHome } : {},
8708
+ ...templateHome && fs21.existsSync(templateHome) ? { templateHome } : {},
7996
8709
  ...browsersDir ? { browsersDir } : {},
7997
8710
  ...hostEnv ? { hostEnv } : {},
7998
8711
  jail: deps.jail,
@@ -8009,7 +8722,7 @@ function createRunner(deps) {
8009
8722
  seedMcpFiles(ctx.home);
8010
8723
  const noKey = (m) => ({ ...m, key: "", baseUrl: null });
8011
8724
  const jobGrant = { ...grant, creds: { ...grant.creds, model: noKey(grant.creds.model), extraModels: grant.creds.extraModels.map(noKey) } };
8012
- const env = composeEnv(jobGrant, { instance: ctx.instance, home: ctx.home, ...hostEnv ? { hostEnv } : {} });
8725
+ const env = composeEnv(jobGrant, { instance: ctx.instance, home: ctx.home, unit, ...hostEnv ? { hostEnv } : {} });
8013
8726
  entry.jobs = {
8014
8727
  cwd: checkout.cwd,
8015
8728
  env,
@@ -8019,6 +8732,7 @@ function createRunner(deps) {
8019
8732
  ...artifacts ? { settle: { workspace: grant.workspace, taskId: grant.project.taskId, runJwt: grant.runJwt, dir: artifactsDir, mounted: mounted !== null } } : {}
8020
8733
  };
8021
8734
  entry.inEngine = true;
8735
+ tagged = unit;
8022
8736
  const kind = engineOf(grant.needs)?.kind;
8023
8737
  outcome = kind === "plan" ? await plan(runGrant, ctx) : kind === "sdk" ? await sdk(runGrant, ctx) : await cli(runGrant, ctx);
8024
8738
  } catch (err) {
@@ -8028,8 +8742,28 @@ function createRunner(deps) {
8028
8742
  }
8029
8743
  }
8030
8744
  clearTimeout(timeout);
8745
+ const swept = tagged === null ? null : sweepTag(tagged, deps.killGraceMs ?? END_GRACE_MS);
8031
8746
  entry.relay.close();
8032
8747
  await entry.relay.acked();
8748
+ if (swept) {
8749
+ const { ended, refused, readFailed } = await swept;
8750
+ if (readFailed) deps.log(`run ${runId}: could not list this machine's processes \u2014 what the run left running may not be ended`, "warn");
8751
+ if (ended.length) {
8752
+ const what = describeEnded(ended);
8753
+ deps.log(`run ${runId}: ended ${what} the run left running`, "warn");
8754
+ emit({
8755
+ type: "transcript",
8756
+ runId,
8757
+ role: "assistant",
8758
+ content: `(worker) ended ${what} the run left running in the background \u2014 what must outlive a run is started with job_start`
8759
+ });
8760
+ }
8761
+ if (refused.length) {
8762
+ const what = describeEnded(refused);
8763
+ deps.log(`run ${runId}: could not end ${what} the run left running \u2014 not permitted to signal them`, "warn");
8764
+ emit({ type: "transcript", runId, role: "assistant", content: `(worker) could not end ${what} the run left running in the background: this worker may not signal them` });
8765
+ }
8766
+ }
8033
8767
  const givenUp = () => entry.discard;
8034
8768
  let push = givenUp() ? null : await pushTaskBranch(git2, checkout, runId, grant.creds.git, grant.project.repoUrl, void 0, givenUp);
8035
8769
  if (!push || !push.pushed && givenUp()) push = await setAsideTaskBranch(git2, checkout, runId, grant.project.baseBranch);
@@ -8186,8 +8920,56 @@ function createRunner(deps) {
8186
8920
  },
8187
8921
  /** jobs of `instance` running here or with an end it has not confirmed — its `hello.jobs` */
8188
8922
  jobIds: (instance = deps.cfg.instance) => jobs.liveIds().filter((id) => jobInstance(id) === instance),
8189
- /** After a restart: take back the jobs a previous process left (jobs.ts `recover`); `onEach` before each job. */
8190
- recoverJobs: (onEach) => jobs.recover(onEach),
8923
+ /**
8924
+ * After a restart: take back the jobs a previous process left (jobs.ts
8925
+ * `recover`); `onEach` before each job. One another worker process still
8926
+ * running is starting right now is left to it (`peer`).
8927
+ */
8928
+ recoverJobs: (onEach) => jobs.recover(onEach, { peer: peerJob }),
8929
+ /**
8930
+ * After `recoverJobs`, before any connection: end what earlier worker
8931
+ * processes of this install left tagged — their runs' leftovers and what
8932
+ * ended jobs left — and wait for every pass. A job still running is left
8933
+ * alone, and so is a job whose record could not be read, one recorded
8934
+ * after `recoverJobs` listed the folder (another worker process on this
8935
+ * cache dir started it, and may have stopped since), and every unit
8936
+ * of another worker process still alive (two may share a cache dir). When
8937
+ * the jobs folder could not be listed, only run units are ended: any job
8938
+ * may be one still running. Then the folder is read again: what was
8939
+ * recorded meanwhile by a worker process gone since is taken as
8940
+ * `recoverJobs` took the rest (`onEach` before each), so the first hello
8941
+ * names it — a job the instance hears nothing of is failed there while it
8942
+ * runs on. What one still running recorded is its own. One of those that has
8943
+ * ended by then has its tag swept at that end (jobs.ts `recover`, `late`):
8944
+ * this sweep left it alone.
8945
+ * Never rejects; a failed read is a warning.
8946
+ */
8947
+ async sweepAtStart(onEach) {
8948
+ const { complete, unended } = jobs.recovery();
8949
+ if (!complete) deps.log("start: the jobs folder could not be listed \u2014 only what earlier runs left running is ended, no job's processes", "warn");
8950
+ const running2 = new Set(unended);
8951
+ const since = /* @__PURE__ */ new Map();
8952
+ const recordedSince = (id) => since.get(id) ?? since.set(id, jobs.recordedSince(id)).get(id);
8953
+ const accept = (u) => {
8954
+ if (u.workerPid !== process.pid && workerAlive(u.workerPid)) return false;
8955
+ if (u.kind === "run") return true;
8956
+ return complete && !running2.has(u.id) && !recordedSince(u.id);
8957
+ };
8958
+ let r;
8959
+ try {
8960
+ r = await sweep({ install: install2, accept }, { graceMs: deps.killGraceMs ?? END_GRACE_MS });
8961
+ } catch {
8962
+ r = { ended: [], refused: [], readFailed: true, done: Promise.resolve() };
8963
+ }
8964
+ if (r.readFailed) deps.log("start: could not list this machine's processes \u2014 what earlier runs and jobs left running may not be ended", "warn");
8965
+ if (r.ended.length) deps.log(`start: ended ${describeEnded(r.ended)} that an earlier worker process left running`, "warn");
8966
+ if (r.refused.length) deps.log(`start: could not end ${describeEnded(r.refused)} that an earlier worker process left running \u2014 not permitted to signal them`, "warn");
8967
+ await Promise.resolve(r.done).catch(() => {
8968
+ });
8969
+ const known = new Set(jobs.liveIds());
8970
+ const taken = jobs.recover(onEach, { late: true, peer: peerJob }).filter((id) => !known.has(id));
8971
+ if (taken.length) deps.log(`jobs recorded since this start began: ${taken.join(", ")}`, "info");
8972
+ },
8191
8973
  /**
8192
8974
  * Watch the jobs, a round `ms` after the last one ended; returns the stop. A round looks
8193
8975
  * at one job per turn of the loop: a look may take seconds (`ps` on macOS, cut at 5 s), so
@@ -8346,27 +9128,27 @@ function createRunner(deps) {
8346
9128
  }
8347
9129
 
8348
9130
  // src/skills.ts
8349
- import fs22 from "fs";
8350
- import path19 from "path";
9131
+ import fs23 from "fs";
9132
+ import path20 from "path";
8351
9133
  import { Readable as Readable2 } from "stream";
8352
9134
  import { pipeline as pipeline3 } from "stream/promises";
8353
9135
 
8354
9136
  // ../packages/shared/src/tar.ts
8355
- import fs21 from "fs";
8356
- import path18 from "path";
9137
+ import fs22 from "fs";
9138
+ import path19 from "path";
8357
9139
  var BLOCK = 512;
8358
9140
  function str2(buf, off, len) {
8359
9141
  const end = buf.indexOf(0, off);
8360
9142
  return buf.toString("utf8", off, end >= off && end < off + len ? end : off + len);
8361
9143
  }
8362
9144
  function insideDest(dest, name) {
8363
- if (!name || path18.isAbsolute(name) || name.split(/[\\/]/).includes("..")) return null;
8364
- const abs = path18.resolve(dest, name);
8365
- return abs.startsWith(path18.resolve(dest) + path18.sep) ? abs : null;
9145
+ if (!name || path19.isAbsolute(name) || name.split(/[\\/]/).includes("..")) return null;
9146
+ const abs = path19.resolve(dest, name);
9147
+ return abs.startsWith(path19.resolve(dest) + path19.sep) ? abs : null;
8366
9148
  }
8367
9149
  function extractTar(file, dest) {
8368
- fs21.mkdirSync(dest, { recursive: true });
8369
- const fd = fs21.openSync(file, "r");
9150
+ fs22.mkdirSync(dest, { recursive: true });
9151
+ const fd = fs22.openSync(file, "r");
8370
9152
  const out = { files: 0, skipped: [] };
8371
9153
  try {
8372
9154
  let pos = 0;
@@ -8375,7 +9157,7 @@ function extractTar(file, dest) {
8375
9157
  const buf = Buffer.alloc(len);
8376
9158
  let got = 0;
8377
9159
  while (got < len) {
8378
- const n = fs21.readSync(fd, buf, got, len - got, pos + got);
9160
+ const n = fs22.readSync(fd, buf, got, len - got, pos + got);
8379
9161
  if (n === 0) throw new Error("the archive is truncated");
8380
9162
  got += n;
8381
9163
  }
@@ -8406,26 +9188,26 @@ function extractTar(file, dest) {
8406
9188
  continue;
8407
9189
  }
8408
9190
  if (type === "5") {
8409
- fs21.mkdirSync(abs, { recursive: true });
9191
+ fs22.mkdirSync(abs, { recursive: true });
8410
9192
  continue;
8411
9193
  }
8412
- fs21.mkdirSync(path18.dirname(abs), { recursive: true });
9194
+ fs22.mkdirSync(path19.dirname(abs), { recursive: true });
8413
9195
  const mode = parseInt(str2(h, 100, 8).trim() || "644", 8) & 73 ? 493 : 420;
8414
- const wfd = fs21.openSync(abs, "w", mode);
9196
+ const wfd = fs22.openSync(abs, "w", mode);
8415
9197
  try {
8416
9198
  for (let left = size; left > 0; ) {
8417
9199
  const chunk = read(Math.min(left, 1024 * 1024));
8418
- fs21.writeSync(wfd, chunk);
9200
+ fs22.writeSync(wfd, chunk);
8419
9201
  left -= chunk.length;
8420
9202
  }
8421
9203
  } finally {
8422
- fs21.closeSync(wfd);
9204
+ fs22.closeSync(wfd);
8423
9205
  }
8424
9206
  pos += padded - size;
8425
9207
  out.files++;
8426
9208
  }
8427
9209
  } finally {
8428
- fs21.closeSync(fd);
9210
+ fs22.closeSync(fd);
8429
9211
  }
8430
9212
  }
8431
9213
 
@@ -8434,24 +9216,24 @@ var HASH = /^[0-9a-f]{64}$/;
8434
9216
  var safe = (s) => s.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 80) || "_";
8435
9217
  function createSkills(o) {
8436
9218
  const fetchFn = o.fetch ?? globalThis.fetch;
8437
- const root = path19.join(o.cacheDir, "skills", o.instanceSegment);
9219
+ const root = path20.join(o.cacheDir, "skills", o.instanceSegment);
8438
9220
  const current = /* @__PURE__ */ new Map();
8439
9221
  const inUse = /* @__PURE__ */ new Map();
8440
9222
  let seq = 0;
8441
- const wsDir = (ws) => path19.join(root, safe(ws));
9223
+ const wsDir = (ws) => path20.join(root, safe(ws));
8442
9224
  function prune(ws) {
8443
9225
  const dir = wsDir(ws);
8444
9226
  const keep = new Set([...current].filter(([k]) => k.startsWith(`${ws}\0`)).map(([, h]) => h));
8445
9227
  let entries;
8446
9228
  try {
8447
- entries = fs22.readdirSync(dir);
9229
+ entries = fs23.readdirSync(dir);
8448
9230
  } catch {
8449
9231
  return;
8450
9232
  }
8451
9233
  for (const name of entries) {
8452
- const abs = path19.join(dir, name);
9234
+ const abs = path20.join(dir, name);
8453
9235
  const stale = name.startsWith(".") ? !name.includes(`-${process.pid}-`) : !keep.has(name) && !inUse.get(abs);
8454
- if (stale) fs22.rmSync(abs, { recursive: true, force: true });
9236
+ if (stale) fs23.rmSync(abs, { recursive: true, force: true });
8455
9237
  }
8456
9238
  }
8457
9239
  function hold(ws, dir) {
@@ -8468,30 +9250,30 @@ function createSkills(o) {
8468
9250
  }
8469
9251
  async function unpack(ws, hash, body) {
8470
9252
  const base = wsDir(ws);
8471
- const dir = path19.join(base, hash);
9253
+ const dir = path20.join(base, hash);
8472
9254
  const tag = `-${process.pid}-${++seq}`;
8473
- const tar = path19.join(base, `.${hash}${tag}.tar`);
8474
- const tmp = path19.join(base, `.${hash}${tag}`);
8475
- fs22.mkdirSync(base, { recursive: true });
9255
+ const tar = path20.join(base, `.${hash}${tag}.tar`);
9256
+ const tmp = path20.join(base, `.${hash}${tag}`);
9257
+ fs23.mkdirSync(base, { recursive: true });
8476
9258
  try {
8477
- await pipeline3(Readable2.fromWeb(body), fs22.createWriteStream(tar));
9259
+ await pipeline3(Readable2.fromWeb(body), fs23.createWriteStream(tar));
8478
9260
  extractTar(tar, tmp);
8479
9261
  try {
8480
- fs22.renameSync(tmp, dir);
9262
+ fs23.renameSync(tmp, dir);
8481
9263
  } catch (err) {
8482
- if (!fs22.existsSync(dir)) throw err;
9264
+ if (!fs23.existsSync(dir)) throw err;
8483
9265
  }
8484
9266
  return dir;
8485
9267
  } finally {
8486
- fs22.rmSync(tar, { force: true });
8487
- fs22.rmSync(tmp, { recursive: true, force: true });
9268
+ fs23.rmSync(tar, { force: true });
9269
+ fs23.rmSync(tmp, { recursive: true, force: true });
8488
9270
  }
8489
9271
  }
8490
9272
  async function acquire(grant) {
8491
9273
  const ws = grant.workspace;
8492
9274
  const key = `${ws}\0${grant.agent}`;
8493
9275
  const known = current.get(key);
8494
- const knownDir = known && fs22.existsSync(path19.join(wsDir(ws), known)) ? path19.join(wsDir(ws), known) : null;
9276
+ const knownDir = known && fs23.existsSync(path20.join(wsDir(ws), known)) ? path20.join(wsDir(ws), known) : null;
8495
9277
  const url = `${o.instance}/api/v1/workspaces/${encodeURIComponent(ws)}/skills/slice.tar?agent=${encodeURIComponent(grant.agent)}`;
8496
9278
  const settle = (dir, hash, fetched, error) => {
8497
9279
  if (hash) current.set(key, hash);
@@ -8513,8 +9295,8 @@ function createSkills(o) {
8513
9295
  });
8514
9296
  throw new Error(`the instance sent no valid ${SKILLS_SLICE_HASH_HEADER}`);
8515
9297
  }
8516
- const have = path19.join(wsDir(ws), hash);
8517
- if (fs22.existsSync(have)) {
9298
+ const have = path20.join(wsDir(ws), hash);
9299
+ if (fs23.existsSync(have)) {
8518
9300
  await res.body.cancel().catch(() => {
8519
9301
  });
8520
9302
  return settle(have, hash, false);
@@ -8529,9 +9311,9 @@ function createSkills(o) {
8529
9311
 
8530
9312
  // src/warm.ts
8531
9313
  import { spawn as spawn4 } from "child_process";
8532
- import { createHash as createHash3 } from "crypto";
8533
- import fs23 from "fs";
8534
- import path20 from "path";
9314
+ import { createHash as createHash4 } from "crypto";
9315
+ import fs24 from "fs";
9316
+ import path21 from "path";
8535
9317
  var TEMPLATE_INPUTS = ["package.json", "pnpm-lock.yaml", "package-lock.json", "yarn.lock", "pyproject.toml", "uv.lock"];
8536
9318
  var PLAYWRIGHT_NODE = ["playwright", "@playwright/test", "playwright-core"];
8537
9319
  function nodeDeps(packageJson) {
@@ -8590,7 +9372,7 @@ function templatePlan(files, has) {
8590
9372
  }
8591
9373
  var stepText = (s) => [s.bin, ...s.args].join(" ");
8592
9374
  function templateFingerprint(inputs, plan) {
8593
- const h = createHash3("sha1");
9375
+ const h = createHash4("sha1");
8594
9376
  for (const name of [...inputs.keys()].sort()) h.update(`${name}\0${inputs.get(name)}\0`);
8595
9377
  for (const s of plan.steps) h.update(`${stepText(s)}\0`);
8596
9378
  return h.digest("hex");
@@ -8614,12 +9396,12 @@ function createWarmer(deps) {
8614
9396
  async function dropTemplate(cacheKey) {
8615
9397
  const tpl = deps.cache.templateDir(cacheKey);
8616
9398
  const old = `${tpl}.old`;
8617
- fs23.rmSync(deps.cache.templateStampFile(cacheKey), { force: true });
8618
- await fs23.promises.rm(old, { recursive: true, force: true });
9399
+ fs24.rmSync(deps.cache.templateStampFile(cacheKey), { force: true });
9400
+ await fs24.promises.rm(old, { recursive: true, force: true });
8619
9401
  await deps.cache.replaceTemplate(cacheKey, () => {
8620
- if (fs23.existsSync(tpl)) fs23.renameSync(tpl, old);
9402
+ if (fs24.existsSync(tpl)) fs24.renameSync(tpl, old);
8621
9403
  });
8622
- await fs23.promises.rm(old, { recursive: true, force: true });
9404
+ await fs24.promises.rm(old, { recursive: true, force: true });
8623
9405
  }
8624
9406
  async function build(frame, repo, ref, plan, fingerprint) {
8625
9407
  const final = deps.cache.templateDir(frame.cacheKey);
@@ -8627,9 +9409,9 @@ function createWarmer(deps) {
8627
9409
  const home = deps.cache.templateHome(frame.cacheKey);
8628
9410
  const clearBuild = async () => {
8629
9411
  try {
8630
- await removeWorktreeAsync((cwd, args) => deps.runGitAsync(cwd, args, {}, [path20.dirname(buildDir)]), repo, buildDir, { force: true });
9412
+ await removeWorktreeAsync((cwd, args) => deps.runGitAsync(cwd, args, {}, [path21.dirname(buildDir)]), repo, buildDir, { force: true });
8631
9413
  } catch {
8632
- await fs23.promises.rm(buildDir, { recursive: true, force: true });
9414
+ await fs24.promises.rm(buildDir, { recursive: true, force: true });
8633
9415
  try {
8634
9416
  await deps.runGitAsync(repo, ["worktree", "prune"], {});
8635
9417
  } catch {
@@ -8637,8 +9419,8 @@ function createWarmer(deps) {
8637
9419
  }
8638
9420
  };
8639
9421
  await clearBuild();
8640
- fs23.mkdirSync(home, { recursive: true });
8641
- await deps.runGitAsync(repo, ["worktree", "add", "--lock", "--detach", buildDir, ref], {}, [path20.dirname(buildDir)]);
9422
+ fs24.mkdirSync(home, { recursive: true });
9423
+ await deps.runGitAsync(repo, ["worktree", "add", "--lock", "--detach", buildDir, ref], {}, [path21.dirname(buildDir)]);
8642
9424
  try {
8643
9425
  const env = {
8644
9426
  ...hostEnvOf(deps.hostEnv ?? process.env),
@@ -8670,18 +9452,18 @@ ${tail2}` : ""}` };
8670
9452
  }
8671
9453
  const next = `${final}.next`;
8672
9454
  const old = `${final}.old`;
8673
- await fs23.promises.rm(next, { recursive: true, force: true });
8674
- await fs23.promises.rm(old, { recursive: true, force: true });
8675
- fs23.mkdirSync(next, { recursive: true });
8676
- const kept = plan.keep.filter((entry) => fs23.existsSync(path20.join(buildDir, entry)));
8677
- for (const entry of kept) fs23.renameSync(path20.join(buildDir, entry), path20.join(next, entry));
9455
+ await fs24.promises.rm(next, { recursive: true, force: true });
9456
+ await fs24.promises.rm(old, { recursive: true, force: true });
9457
+ fs24.mkdirSync(next, { recursive: true });
9458
+ const kept = plan.keep.filter((entry) => fs24.existsSync(path21.join(buildDir, entry)));
9459
+ for (const entry of kept) fs24.renameSync(path21.join(buildDir, entry), path21.join(next, entry));
8678
9460
  await deps.cache.replaceTemplate(frame.cacheKey, () => {
8679
- if (fs23.existsSync(final)) fs23.renameSync(final, old);
8680
- fs23.renameSync(next, final);
9461
+ if (fs24.existsSync(final)) fs24.renameSync(final, old);
9462
+ fs24.renameSync(next, final);
8681
9463
  });
8682
- await fs23.promises.rm(old, { recursive: true, force: true });
9464
+ await fs24.promises.rm(old, { recursive: true, force: true });
8683
9465
  const stamp = { fingerprint, builtAt: deps.now(), steps: plan.steps.map(stepText), keep: kept, playwright: plan.playwright };
8684
- fs23.writeFileSync(deps.cache.templateStampFile(frame.cacheKey), JSON.stringify(stamp, null, 2));
9466
+ fs24.writeFileSync(deps.cache.templateStampFile(frame.cacheKey), JSON.stringify(stamp, null, 2));
8685
9467
  return { fetched: true, template: "built", detail: kept.join(", ") || "nothing to keep" };
8686
9468
  } finally {
8687
9469
  await clearBuild();
@@ -8711,7 +9493,7 @@ ${tail2}` : ""}` };
8711
9493
  return { fetched: true, template: "none" };
8712
9494
  }
8713
9495
  const fingerprint = templateFingerprint(inputs, plan);
8714
- if (deps.cache.templateStamp(frame.cacheKey)?.fingerprint === fingerprint && fs23.existsSync(deps.cache.templateDir(frame.cacheKey)) && fs23.existsSync(deps.cache.templateHome(frame.cacheKey)))
9496
+ if (deps.cache.templateStamp(frame.cacheKey)?.fingerprint === fingerprint && fs24.existsSync(deps.cache.templateDir(frame.cacheKey)) && fs24.existsSync(deps.cache.templateHome(frame.cacheKey)))
8715
9497
  return { fetched: true, template: "current" };
8716
9498
  if (await overBudget()) return { fetched: true, template: "skipped", detail: `the cache is at its cache_gb (${deps.cacheGb} GB)` };
8717
9499
  const out = await build(frame, repo, ref, plan, fingerprint);
@@ -8766,13 +9548,13 @@ function execStep(bin, args, o) {
8766
9548
  }
8767
9549
 
8768
9550
  // src/version.ts
8769
- var VERSION = "0.1.4";
9551
+ var VERSION = "0.1.5";
8770
9552
 
8771
9553
  // src/update.ts
8772
9554
  import { spawn as spawn5 } from "child_process";
8773
9555
  import { constants as fsConstants } from "fs";
8774
- import fs24 from "fs/promises";
8775
- import path21 from "path";
9556
+ import fs25 from "fs/promises";
9557
+ import path22 from "path";
8776
9558
  var PROBE_TIMEOUT_MS = 1e4;
8777
9559
  var OUTPUT_KEPT = 64 * 1024;
8778
9560
  var keepTail = (s) => s.length > OUTPUT_KEPT ? s.slice(s.length - OUTPUT_KEPT) : s;
@@ -8788,7 +9570,7 @@ function runUpdateChild(cmd2, args, o, start = spawn5) {
8788
9570
  clearTimeout(timer);
8789
9571
  resolve(out);
8790
9572
  };
8791
- const env = o.pathDirs?.length ? { ...process.env, PATH: [...o.pathDirs, process.env.PATH].filter(Boolean).join(path21.delimiter) } : process.env;
9573
+ const env = o.pathDirs?.length ? { ...process.env, PATH: [...o.pathDirs, process.env.PATH].filter(Boolean).join(path22.delimiter) } : process.env;
8792
9574
  let child;
8793
9575
  try {
8794
9576
  child = start(cmd2, args, { stdio: ["ignore", "pipe", "pipe"], detached: true, env });
@@ -8828,10 +9610,10 @@ async function check(o) {
8828
9610
  }
8829
9611
  const platform = o.platform ?? process.platform;
8830
9612
  if (platform === "win32") return { allowed: false, reason: "remote update is not supported on native Windows" };
8831
- const realpath2 = o.realpath ?? ((p) => fs24.realpath(p));
8832
- const access = o.access ?? ((p) => fs24.access(p, fsConstants.W_OK | fsConstants.X_OK));
8833
- const lstat = o.lstat ?? ((p) => fs24.lstat(p));
8834
- const stat = o.stat ?? ((p) => fs24.stat(p));
9613
+ const realpath2 = o.realpath ?? ((p) => fs25.realpath(p));
9614
+ const access = o.access ?? ((p) => fs25.access(p, fsConstants.W_OK | fsConstants.X_OK));
9615
+ const lstat = o.lstat ?? ((p) => fs25.lstat(p));
9616
+ const stat = o.stat ?? ((p) => fs25.stat(p));
8835
9617
  const run = o.run ?? runUpdateChild;
8836
9618
  const execPath = o.execPath ?? process.execPath;
8837
9619
  const script = o.script ?? process.argv[1];
@@ -8847,14 +9629,14 @@ async function check(o) {
8847
9629
  } catch (err) {
8848
9630
  return notGlobal(`${script}: ${errText(err)}`);
8849
9631
  }
8850
- const marker = `${path21.sep}lib${path21.sep}node_modules${path21.sep}bridex-worker${path21.sep}`;
9632
+ const marker = `${path22.sep}lib${path22.sep}node_modules${path22.sep}bridex-worker${path22.sep}`;
8851
9633
  const at = real.lastIndexOf(marker);
8852
9634
  if (at < 0) return notGlobal(real);
8853
- const prefix = real.slice(0, at) || path21.sep;
8854
- const globalDir = path21.join(prefix, "lib", "node_modules");
9635
+ const prefix = real.slice(0, at) || path22.sep;
9636
+ const globalDir = path22.join(prefix, "lib", "node_modules");
8855
9637
  const globalReal = await realpath2(globalDir).catch(() => globalDir);
8856
- const pathDir = path21.dirname(execPath);
8857
- const candidates = [.../* @__PURE__ */ new Set([path21.join(prefix, "bin", "npm"), path21.join(pathDir, "npm")])];
9638
+ const pathDir = path22.dirname(execPath);
9639
+ const candidates = [.../* @__PURE__ */ new Set([path22.join(prefix, "bin", "npm"), path22.join(pathDir, "npm")])];
8858
9640
  const misses = [];
8859
9641
  let npm = null;
8860
9642
  let npmPrefix = prefix;
@@ -8876,14 +9658,14 @@ async function check(o) {
8876
9658
  const rootReal = root ? await realpath2(root).catch(() => root) : "";
8877
9659
  if (rootReal === globalReal) {
8878
9660
  npm = cand;
8879
- if (path21.basename(root) === "node_modules" && path21.basename(path21.dirname(root)) === "lib") {
8880
- const named = path21.dirname(path21.dirname(root));
9661
+ if (path22.basename(root) === "node_modules" && path22.basename(path22.dirname(root)) === "lib") {
9662
+ const named = path22.dirname(path22.dirname(root));
8881
9663
  npmPrefix = await realpath2(named).catch(() => prefix);
8882
9664
  }
8883
9665
  if (npmPrefix !== prefix) {
8884
9666
  return {
8885
9667
  allowed: false,
8886
- reason: `npm's global folder ${root} is a symlink to ${globalReal}: an install would go wherever it points by then; remote update needs ${path21.join(npmPrefix, "lib", "node_modules")} to be a folder`
9668
+ reason: `npm's global folder ${root} is a symlink to ${globalReal}: an install would go wherever it points by then; remote update needs ${path22.join(npmPrefix, "lib", "node_modules")} to be a folder`
8887
9669
  };
8888
9670
  }
8889
9671
  break;
@@ -8901,7 +9683,7 @@ async function check(o) {
8901
9683
  } catch {
8902
9684
  return { allowed: false, reason: `the global npm folder ${globalReal} is not writable by this user` };
8903
9685
  }
8904
- const binDir = path21.join(prefix, "bin");
9686
+ const binDir = path22.join(prefix, "bin");
8905
9687
  try {
8906
9688
  await access(binDir);
8907
9689
  if (!(await stat(binDir)).isDirectory()) {
@@ -8920,7 +9702,7 @@ async function check(o) {
8920
9702
  };
8921
9703
  }
8922
9704
  }
8923
- const interpreter = path21.isAbsolute(argv0) ? argv0 : null;
9705
+ const interpreter = path22.isAbsolute(argv0) ? argv0 : null;
8924
9706
  return {
8925
9707
  allowed: true,
8926
9708
  npm,
@@ -8959,9 +9741,9 @@ async function install(o) {
8959
9741
  const execPath = o.execPath ?? process.execPath;
8960
9742
  const script = o.script ?? process.argv[1] ?? "";
8961
9743
  const timeoutMs = o.timeoutMs ?? INSTALL_TIMEOUT_MS;
8962
- const pathDir = path21.dirname(execPath);
9744
+ const pathDir = path22.dirname(execPath);
8963
9745
  const spec = `bridex-worker@${o.version}`;
8964
- const npmPath = [.../* @__PURE__ */ new Set([pathDir, ...o.interpreter ? [path21.dirname(o.interpreter)] : []])];
9746
+ const npmPath = [.../* @__PURE__ */ new Set([pathDir, ...o.interpreter ? [path22.dirname(o.interpreter)] : []])];
8965
9747
  const npm = await run(o.npm, ["i", "-g", "--prefix", o.prefix, spec], { timeoutMs, pathDirs: npmPath });
8966
9748
  const fallbackNodes = [.../* @__PURE__ */ new Set([o.interpreter, "node"])].filter((n) => !!n && n !== execPath);
8967
9749
  const probe = async (as) => {
@@ -9170,7 +9952,7 @@ function createUpdater(deps) {
9170
9952
  // src/watchdog.ts
9171
9953
  import { spawn as spawn6 } from "child_process";
9172
9954
  import { randomBytes as randomBytes2 } from "crypto";
9173
- import path22 from "path";
9955
+ import path23 from "path";
9174
9956
  import { Worker } from "worker_threads";
9175
9957
  var POOL_PROBE_MS = 3e4;
9176
9958
  var POOL_STUCK_MS = 12e4;
@@ -9309,7 +10091,7 @@ function skippedReason(o, c) {
9309
10091
  async function captureStacks(o) {
9310
10092
  const platform = o.platform ?? process.platform;
9311
10093
  if (platform !== "darwin") return { skipped: `stacks are taken on macOS only, not on ${platform}` };
9312
- const file = path22.join(o.dir, stackFileName(o.at ?? /* @__PURE__ */ new Date()));
10094
+ const file = path23.join(o.dir, stackFileName(o.at ?? /* @__PURE__ */ new Date()));
9313
10095
  const timeoutMs = o.timeoutMs ?? SAMPLE_TIMEOUT_MS;
9314
10096
  const args = [
9315
10097
  "-c",
@@ -9867,7 +10649,7 @@ var STUCK_STOP_REASON = "the worker went away: its thread pool was stuck, so it
9867
10649
  function stuckActions(o) {
9868
10650
  const capture = o.captureStacks ?? captureStacks;
9869
10651
  return {
9870
- capture: () => capture({ dir: path23.join(o.configDir, "diag") }),
10652
+ capture: () => capture({ dir: path24.join(o.configDir, "diag") }),
9871
10653
  stop: async (ms) => {
9872
10654
  o.poller()?.stop();
9873
10655
  o.reporter()?.stop();
@@ -9996,6 +10778,8 @@ async function runWorker(cfg, deps) {
9996
10778
  });
9997
10779
  const recovered = runner.recoverJobs(() => life?.arm(LIFELINE_MS));
9998
10780
  if (recovered.length) deps.log(`jobs from before this start: ${recovered.join(", ")}`, "info");
10781
+ life?.arm(LIFELINE_MS);
10782
+ await runner.sweepAtStart(() => life?.arm(LIFELINE_MS));
9999
10783
  runner.watchJobs();
10000
10784
  const connections = createConnections({
10001
10785
  connect: (url, token) => connectInstance(url, token),