bridex-worker 0.1.3 → 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.
- package/README.md +90 -5
- package/dist/cli.js +1021 -196
- 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(
|
|
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
|
-
|
|
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(
|
|
5021
|
+
async function call(path25, init = {}) {
|
|
5011
5022
|
try {
|
|
5012
|
-
return await doFetch(`${base}${
|
|
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,10 +6307,11 @@ async function joinCp(url, id, key, deps = defaultJoinDeps(), opts = {}) {
|
|
|
6296
6307
|
|
|
6297
6308
|
// src/run.ts
|
|
6298
6309
|
import os7 from "os";
|
|
6299
|
-
import
|
|
6310
|
+
import path24 from "path";
|
|
6300
6311
|
import WebSocket from "ws";
|
|
6301
6312
|
|
|
6302
6313
|
// src/admission.ts
|
|
6314
|
+
import { execFileSync as execFileSync3 } from "child_process";
|
|
6303
6315
|
import fs15 from "fs";
|
|
6304
6316
|
import os5 from "os";
|
|
6305
6317
|
import path12 from "path";
|
|
@@ -6391,12 +6403,52 @@ var AUTO_SLOTS_MIN = 2;
|
|
|
6391
6403
|
var AUTO_SLOTS_MAX = 8;
|
|
6392
6404
|
var MAX_LOAD_PER_CORE = 1.5;
|
|
6393
6405
|
var DISK_RESERVE_BYTES = 3 * GB4;
|
|
6394
|
-
function
|
|
6395
|
-
const
|
|
6396
|
-
if (
|
|
6406
|
+
function parseVmStat(text) {
|
|
6407
|
+
const header = /\(page size of (\d+) bytes\)/.exec(text.split(/\r?\n/, 1)[0] ?? "");
|
|
6408
|
+
if (!header) return null;
|
|
6409
|
+
const pageSize = Number(header[1]);
|
|
6410
|
+
if (!Number.isSafeInteger(pageSize) || pageSize <= 0) return null;
|
|
6411
|
+
const count2 = (name, absent) => {
|
|
6412
|
+
const raw = new RegExp(`^${name}:(.*)$`, "m").exec(text)?.[1];
|
|
6413
|
+
if (raw === void 0) return absent;
|
|
6414
|
+
const m = /^(\d+)\.?$/.exec(raw.trim());
|
|
6415
|
+
return m ? Number(m[1]) : null;
|
|
6416
|
+
};
|
|
6417
|
+
let pages = 0;
|
|
6418
|
+
for (const n of [count2("Pages free", null), count2("Pages inactive", null), count2("Pages speculative", 0), count2("Pages purgeable", 0)]) {
|
|
6419
|
+
if (n === null) return null;
|
|
6420
|
+
pages += n;
|
|
6421
|
+
}
|
|
6422
|
+
const bytes = pages * pageSize;
|
|
6423
|
+
return Number.isSafeInteger(bytes) ? bytes : null;
|
|
6424
|
+
}
|
|
6425
|
+
function readVmStat() {
|
|
6426
|
+
try {
|
|
6427
|
+
return execFileSync3("/usr/bin/vm_stat", { encoding: "utf8", timeout: 2e3, stdio: ["ignore", "pipe", "ignore"] });
|
|
6428
|
+
} catch {
|
|
6429
|
+
return null;
|
|
6430
|
+
}
|
|
6431
|
+
}
|
|
6432
|
+
function availableMemory({ platform = process.platform, vmStat = readVmStat, linux = freeMemoryBytes } = {}) {
|
|
6433
|
+
if (platform === "darwin") {
|
|
6434
|
+
const mac = vmStatBytes(vmStat);
|
|
6435
|
+
if (mac !== null) return Math.min(mac, os5.totalmem());
|
|
6436
|
+
} else {
|
|
6437
|
+
const kernel = linux();
|
|
6438
|
+
if (kernel !== null) return kernel;
|
|
6439
|
+
}
|
|
6397
6440
|
const avail = process.availableMemory?.();
|
|
6398
6441
|
return typeof avail === "number" && avail > 0 ? avail : os5.freemem();
|
|
6399
6442
|
}
|
|
6443
|
+
function vmStatBytes(vmStat) {
|
|
6444
|
+
try {
|
|
6445
|
+
const text = vmStat();
|
|
6446
|
+
const bytes = text === null ? null : parseVmStat(text);
|
|
6447
|
+
return bytes !== null && bytes > 0 ? bytes : null;
|
|
6448
|
+
} catch {
|
|
6449
|
+
return null;
|
|
6450
|
+
}
|
|
6451
|
+
}
|
|
6400
6452
|
function existingAncestor(dir) {
|
|
6401
6453
|
let d = path12.resolve(dir);
|
|
6402
6454
|
while (!fs15.existsSync(d)) {
|
|
@@ -6461,8 +6513,388 @@ function heartbeat(cfg, running, host, warm = [], quota) {
|
|
|
6461
6513
|
}
|
|
6462
6514
|
|
|
6463
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";
|
|
6464
6522
|
import fs16 from "fs";
|
|
6465
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
|
|
6466
6898
|
function presetOf(needs) {
|
|
6467
6899
|
const need = needs.find((n) => n.startsWith("cli:"));
|
|
6468
6900
|
return need ? need.slice("cli:".length) : null;
|
|
@@ -6538,57 +6970,67 @@ function composeEnv(grant, o) {
|
|
|
6538
6970
|
BRIDEX_RUN_JWT: grant.runJwt,
|
|
6539
6971
|
BRIDEX_RUN_ID: grant.runId
|
|
6540
6972
|
});
|
|
6973
|
+
if (o.unit === null) delete env[UNIT_VAR];
|
|
6974
|
+
else env[UNIT_VAR] = o.unit;
|
|
6541
6975
|
return env;
|
|
6542
6976
|
}
|
|
6543
|
-
function mcpServersOf(grant) {
|
|
6977
|
+
function mcpServersOf(grant, unit) {
|
|
6544
6978
|
const out = {};
|
|
6545
|
-
for (const s of grant.mcp)
|
|
6546
|
-
|
|
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
|
+
}
|
|
6547
6989
|
return out;
|
|
6548
6990
|
}
|
|
6549
6991
|
function writeMcpFiles(presetId, home, servers, instance, warn = () => {
|
|
6550
|
-
}) {
|
|
6992
|
+
}, fromEnv = []) {
|
|
6551
6993
|
const bridex = { url: `${instance}/mcp` };
|
|
6552
6994
|
const via = CLI_PRESETS[presetId]?.mcpVia;
|
|
6553
|
-
if (via === "codex-config") writeCodexMcpConfig(home, servers, bridex, { warn });
|
|
6554
|
-
else if (via === "grok-config") writeGrokMcpConfig(home, servers, bridex, { warn });
|
|
6555
|
-
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 });
|
|
6556
6998
|
}
|
|
6557
6999
|
function resolveBin(bin, pathEnv) {
|
|
6558
|
-
const candidates = bin.includes("/") ? [bin] : pathEnv.split(
|
|
7000
|
+
const candidates = bin.includes("/") ? [bin] : pathEnv.split(path14.delimiter).filter(Boolean).map((d) => path14.join(d, bin));
|
|
6559
7001
|
for (const c of candidates) {
|
|
6560
7002
|
try {
|
|
6561
|
-
return
|
|
7003
|
+
return fs17.realpathSync(c);
|
|
6562
7004
|
} catch {
|
|
6563
7005
|
}
|
|
6564
7006
|
}
|
|
6565
7007
|
return null;
|
|
6566
7008
|
}
|
|
6567
7009
|
var CLI_LOGIN_DIRS = [".claude", ".codex", ".gemini", ".grok"];
|
|
6568
|
-
var under = (p, dir) => p === dir || p.startsWith(dir.endsWith(
|
|
7010
|
+
var under = (p, dir) => p === dir || p.startsWith(dir.endsWith(path14.sep) ? dir : dir + path14.sep);
|
|
6569
7011
|
function toolchainRoots(bin, pathEnv, ownerHome) {
|
|
6570
7012
|
let realHome = ownerHome;
|
|
6571
7013
|
try {
|
|
6572
|
-
realHome =
|
|
7014
|
+
realHome = fs17.realpathSync(ownerHome);
|
|
6573
7015
|
} catch {
|
|
6574
7016
|
}
|
|
6575
|
-
const loginDir = (p) => CLI_LOGIN_DIRS.some((d) => p ===
|
|
7017
|
+
const loginDir = (p) => CLI_LOGIN_DIRS.some((d) => p === path14.join(ownerHome, d) || p === path14.join(realHome, d));
|
|
6576
7018
|
const out = /* @__PURE__ */ new Set();
|
|
6577
7019
|
const add = (p) => {
|
|
6578
7020
|
if (!loginDir(p)) out.add(p);
|
|
6579
7021
|
};
|
|
6580
|
-
for (const dir of pathEnv.split(
|
|
7022
|
+
for (const dir of pathEnv.split(path14.delimiter).filter(Boolean)) {
|
|
6581
7023
|
if (!under(dir, ownerHome) || dir === ownerHome) continue;
|
|
6582
7024
|
add(dir);
|
|
6583
|
-
const prefix =
|
|
6584
|
-
if (
|
|
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"))))
|
|
6585
7027
|
add(prefix);
|
|
6586
7028
|
}
|
|
6587
7029
|
const real = resolveBin(bin, pathEnv);
|
|
6588
7030
|
const home = real && under(real, realHome) ? realHome : real && under(real, ownerHome) ? ownerHome : null;
|
|
6589
7031
|
if (real && home) {
|
|
6590
|
-
const prefix =
|
|
6591
|
-
const root = loginDir(prefix) ?
|
|
7032
|
+
const prefix = path14.dirname(path14.dirname(real));
|
|
7033
|
+
const root = loginDir(prefix) ? path14.dirname(real) : prefix;
|
|
6592
7034
|
if (root !== home && under(root, home)) add(root);
|
|
6593
7035
|
}
|
|
6594
7036
|
return [...out];
|
|
@@ -6602,7 +7044,7 @@ function runJail(ctx, readOnly = []) {
|
|
|
6602
7044
|
readOnly: [ctx.skillsDir, ctx.templateHome, ctx.browsersDir, ...readOnly].filter((p) => Boolean(p)),
|
|
6603
7045
|
// the MCP files this worker writes into the HOME, outside the jail: a
|
|
6604
7046
|
// job left running (or a run beside it) could swap one for a link to write through
|
|
6605
|
-
protect: [...protectedGitPaths(ctx.repoDir, ctx.cwd), ...MCP_CONFIG_FILES.map(([rel]) =>
|
|
7047
|
+
protect: [...protectedGitPaths(ctx.repoDir, ctx.cwd), ...MCP_CONFIG_FILES.map(([rel]) => path14.join(ctx.home, rel))],
|
|
6606
7048
|
home: ctx.ownerHome,
|
|
6607
7049
|
homeAccess: "hidden",
|
|
6608
7050
|
hidden: ctx.hidden ?? []
|
|
@@ -6617,10 +7059,10 @@ var MCP_CONFIG_FILES = [
|
|
|
6617
7059
|
function seedMcpFiles(home) {
|
|
6618
7060
|
unlinkLinks(home, MCP_CONFIG_PATHS);
|
|
6619
7061
|
for (const [rel, empty] of MCP_CONFIG_FILES) {
|
|
6620
|
-
const file =
|
|
6621
|
-
|
|
7062
|
+
const file = path14.join(home, rel);
|
|
7063
|
+
fs17.mkdirSync(path14.dirname(file), { recursive: true });
|
|
6622
7064
|
try {
|
|
6623
|
-
|
|
7065
|
+
fs17.writeFileSync(file, empty, { flag: "wx" });
|
|
6624
7066
|
} catch {
|
|
6625
7067
|
}
|
|
6626
7068
|
}
|
|
@@ -6630,12 +7072,19 @@ async function runCliEngine(grant, ctx) {
|
|
|
6630
7072
|
const presetId = presetOf(grant.needs);
|
|
6631
7073
|
const preset = presetId ? CLI_PRESETS[presetId] : void 0;
|
|
6632
7074
|
if (!presetId || !preset) return { ok: false, resultText: "", error: `no cli preset in the grant's needs (${grant.needs.join(", ") || "none"})` };
|
|
6633
|
-
|
|
6634
|
-
|
|
6635
|
-
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);
|
|
6636
7078
|
unlinkLinks(ctx.home, MCP_CONFIG_PATHS);
|
|
6637
|
-
writeMcpFiles(
|
|
6638
|
-
|
|
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 } : {} });
|
|
6639
7088
|
const jailed = ctx.jail !== "none";
|
|
6640
7089
|
const runCli = ctx.runCli ?? runCliOnce;
|
|
6641
7090
|
const killer = killTreeOnAbort(ctx.abort, ctx.kill, ctx.killGraceMs, ctx.onKillSweep);
|
|
@@ -6690,20 +7139,20 @@ async function runCliEngine(grant, ctx) {
|
|
|
6690
7139
|
}
|
|
6691
7140
|
|
|
6692
7141
|
// src/runs.ts
|
|
6693
|
-
import
|
|
7142
|
+
import fs21 from "fs";
|
|
6694
7143
|
import os6 from "os";
|
|
6695
|
-
import
|
|
7144
|
+
import path18 from "path";
|
|
6696
7145
|
|
|
6697
7146
|
// src/engines/plan.ts
|
|
6698
|
-
import
|
|
6699
|
-
import
|
|
7147
|
+
import fs18 from "fs";
|
|
7148
|
+
import path15 from "path";
|
|
6700
7149
|
var PLAN_TOOLCHAIN = ["claude", "codex"];
|
|
6701
7150
|
async function runPlanEngine(grant, ctx) {
|
|
6702
7151
|
if (!grant.plan) return { ok: false, resultText: "", error: "plan run without a plan: the grant carries none", noRetry: true };
|
|
6703
7152
|
const { spec, codexArgs } = grant.plan;
|
|
6704
|
-
|
|
6705
|
-
|
|
6706
|
-
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 } : {} });
|
|
6707
7156
|
const command = ctx.planCommand ?? { bin: PLAN_BIN, argv: [] };
|
|
6708
7157
|
const pathEnv = env.PATH ?? "";
|
|
6709
7158
|
const roots = [...new Set([command.bin, ...PLAN_TOOLCHAIN].flatMap((bin) => toolchainRoots(bin, pathEnv, ctx.ownerHome)))];
|
|
@@ -6714,7 +7163,7 @@ async function runPlanEngine(grant, ctx) {
|
|
|
6714
7163
|
spec,
|
|
6715
7164
|
cwd: ctx.cwd,
|
|
6716
7165
|
env,
|
|
6717
|
-
journalRoot:
|
|
7166
|
+
journalRoot: path15.join(ctx.home, PLAN_JOURNAL_DIR),
|
|
6718
7167
|
runId: grant.runId,
|
|
6719
7168
|
command,
|
|
6720
7169
|
wrapSpawn: (bin, argv) => wrapJailed(runJail(ctx, roots), bin, argv),
|
|
@@ -6742,7 +7191,7 @@ async function runPlanEngine(grant, ctx) {
|
|
|
6742
7191
|
|
|
6743
7192
|
// src/engines/sdk.ts
|
|
6744
7193
|
import { spawn as nodeSpawn2 } from "child_process";
|
|
6745
|
-
import
|
|
7194
|
+
import fs19 from "fs";
|
|
6746
7195
|
|
|
6747
7196
|
// ../packages/shared/src/providerLimit.ts
|
|
6748
7197
|
var MAX_RESET_DAYS = 8;
|
|
@@ -6846,7 +7295,7 @@ function turnAnswers(deliver) {
|
|
|
6846
7295
|
}
|
|
6847
7296
|
|
|
6848
7297
|
// ../packages/shared/src/toolGate.ts
|
|
6849
|
-
import
|
|
7298
|
+
import path16 from "path";
|
|
6850
7299
|
var RUN_OUTLIVING_TOOLS = ["Monitor", "CronCreate", "CronDelete", "CronList", "ScheduleWakeup", "RemoteTrigger"];
|
|
6851
7300
|
function permissionClassOf(toolName) {
|
|
6852
7301
|
if (toolName === "Bash") return "terminal";
|
|
@@ -6864,8 +7313,8 @@ function fileToolPath(toolInput) {
|
|
|
6864
7313
|
return typeof p === "string" ? p : null;
|
|
6865
7314
|
}
|
|
6866
7315
|
function insideRoots(p, base, roots) {
|
|
6867
|
-
const abs =
|
|
6868
|
-
return roots.some((root) => abs === root || abs.startsWith(root +
|
|
7316
|
+
const abs = path16.resolve(base, p);
|
|
7317
|
+
return roots.some((root) => abs === root || abs.startsWith(root + path16.sep));
|
|
6869
7318
|
}
|
|
6870
7319
|
function backgroundTimerRefusal(toolName, toolInput) {
|
|
6871
7320
|
if (toolName !== "Bash" || !toolInput.run_in_background || typeof toolInput.command !== "string") return null;
|
|
@@ -6991,10 +7440,10 @@ function messageEvents(m, toolCalls, events) {
|
|
|
6991
7440
|
}
|
|
6992
7441
|
}
|
|
6993
7442
|
async function runSdkEngine(grant, ctx) {
|
|
6994
|
-
|
|
6995
|
-
|
|
7443
|
+
fs19.mkdirSync(ctx.home, { recursive: true });
|
|
7444
|
+
fs19.mkdirSync(ctx.artifactsDir, { recursive: true });
|
|
6996
7445
|
const query = ctx.query ?? await loadQuery();
|
|
6997
|
-
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 } : {} });
|
|
6998
7447
|
const killer = killTreeOnAbort(ctx.abort, ctx.kill, ctx.killGraceMs, ctx.onKillSweep);
|
|
6999
7448
|
const stderrTail = [];
|
|
7000
7449
|
const { canUseTool, notes } = createToolGate(grant, ctx);
|
|
@@ -7038,7 +7487,7 @@ async function runSdkEngine(grant, ctx) {
|
|
|
7038
7487
|
const onAbort = () => sdkAbort.abort();
|
|
7039
7488
|
if (ctx.abort.aborted) sdkAbort.abort();
|
|
7040
7489
|
else ctx.abort.addEventListener("abort", onAbort, { once: true });
|
|
7041
|
-
const servers = mcpServersOf(grant);
|
|
7490
|
+
const servers = mcpServersOf(grant, ctx.unit);
|
|
7042
7491
|
const options = {
|
|
7043
7492
|
cwd: ctx.cwd,
|
|
7044
7493
|
model: grant.model,
|
|
@@ -7139,12 +7588,16 @@ async function runSdkEngine(grant, ctx) {
|
|
|
7139
7588
|
}
|
|
7140
7589
|
|
|
7141
7590
|
// src/jobs.ts
|
|
7142
|
-
import { execFileSync as
|
|
7143
|
-
import
|
|
7144
|
-
import
|
|
7591
|
+
import { execFileSync as execFileSync5, spawn as nodeSpawn3 } from "child_process";
|
|
7592
|
+
import fs20 from "fs";
|
|
7593
|
+
import path17 from "path";
|
|
7145
7594
|
var NO_SUCH_JOB = "(this machine has no such job any more)";
|
|
7146
7595
|
var TAIL_BYTES = 64 * 1024;
|
|
7596
|
+
var LAUNCH_WAIT_MS = 6e4;
|
|
7147
7597
|
var shq = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
|
|
7598
|
+
function isJobFileName(id) {
|
|
7599
|
+
return id !== "" && id !== "." && id !== ".." && !id.includes("\0") && path17.basename(id) === id;
|
|
7600
|
+
}
|
|
7148
7601
|
function jobSecrets(grant) {
|
|
7149
7602
|
const values = [grant.runJwt, grant.creds.git.token, ...grant.secretEnv.map((name) => grant.creds.env[name])];
|
|
7150
7603
|
return [...new Set(values.filter((v) => !!v))];
|
|
@@ -7157,14 +7610,14 @@ var defaultSpawn = (bin, argv, o) => nodeSpawn3(bin, argv, { cwd: o.cwd, env: o.
|
|
|
7157
7610
|
function commandLineOf(pid, opts = {}) {
|
|
7158
7611
|
if (opts.proc !== false) {
|
|
7159
7612
|
try {
|
|
7160
|
-
return
|
|
7613
|
+
return fs20.readFileSync(`/proc/${pid}/cmdline`, "utf8");
|
|
7161
7614
|
} catch (err) {
|
|
7162
7615
|
if (err.code !== "ENOENT") return void 0;
|
|
7163
|
-
if (
|
|
7616
|
+
if (fs20.existsSync("/proc/self")) return null;
|
|
7164
7617
|
}
|
|
7165
7618
|
}
|
|
7166
7619
|
try {
|
|
7167
|
-
const out =
|
|
7620
|
+
const out = execFileSync5(opts.ps ?? "ps", ["-ww", "-o", "command=", "-p", String(pid)], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5e3 });
|
|
7168
7621
|
return out.trim() || null;
|
|
7169
7622
|
} catch (err) {
|
|
7170
7623
|
return err.status === 1 ? null : void 0;
|
|
@@ -7180,14 +7633,49 @@ function jobAlive(pid, jobId, opts = {}) {
|
|
|
7180
7633
|
return false;
|
|
7181
7634
|
}
|
|
7182
7635
|
}
|
|
7183
|
-
function killGroup(pgid, delays = [50, 200, 750, 1500]) {
|
|
7636
|
+
function killGroup(pgid, delays = [50, 200, 750, 1500], still = () => true) {
|
|
7637
|
+
if (!still()) return;
|
|
7184
7638
|
try {
|
|
7185
7639
|
process.kill(-pgid, "SIGKILL");
|
|
7186
7640
|
} catch {
|
|
7187
7641
|
return;
|
|
7188
7642
|
}
|
|
7189
7643
|
const [delay, ...rest2] = delays;
|
|
7190
|
-
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;
|
|
7191
7679
|
}
|
|
7192
7680
|
function defaultKill(pid) {
|
|
7193
7681
|
killTree(pid, "SIGKILL");
|
|
@@ -7195,15 +7683,15 @@ function defaultKill(pid) {
|
|
|
7195
7683
|
}
|
|
7196
7684
|
function tailOf(file, maxBytes) {
|
|
7197
7685
|
try {
|
|
7198
|
-
const size =
|
|
7686
|
+
const size = fs20.statSync(file).size;
|
|
7199
7687
|
const start = Math.max(0, size - maxBytes);
|
|
7200
|
-
const fd =
|
|
7688
|
+
const fd = fs20.openSync(file, "r");
|
|
7201
7689
|
try {
|
|
7202
7690
|
const buf = Buffer.alloc(Math.min(size, maxBytes));
|
|
7203
|
-
|
|
7691
|
+
fs20.readSync(fd, buf, 0, buf.length, start);
|
|
7204
7692
|
return { text: (start > 0 ? "\u2026[earlier output trimmed]\n" : "") + buf.toString("utf8"), truncated: start > 0 };
|
|
7205
7693
|
} finally {
|
|
7206
|
-
|
|
7694
|
+
fs20.closeSync(fd);
|
|
7207
7695
|
}
|
|
7208
7696
|
} catch {
|
|
7209
7697
|
return { text: "", truncated: false };
|
|
@@ -7217,19 +7705,117 @@ function createJobs(deps) {
|
|
|
7217
7705
|
const now = deps.now ?? Date.now;
|
|
7218
7706
|
const slack = deps.timeoutSlackMs ?? 2 * 6e4;
|
|
7219
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();
|
|
7220
7714
|
const files = (id) => ({
|
|
7221
|
-
meta:
|
|
7222
|
-
log:
|
|
7223
|
-
exit:
|
|
7224
|
-
outer:
|
|
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`)
|
|
7225
7724
|
});
|
|
7226
|
-
const
|
|
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
|
+
};
|
|
7227
7790
|
const removeFiles = (id) => {
|
|
7228
|
-
for (const f of Object.values(files(id)))
|
|
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;
|
|
7229
7815
|
};
|
|
7230
7816
|
const readExit = (id) => {
|
|
7231
7817
|
try {
|
|
7232
|
-
const raw =
|
|
7818
|
+
const raw = fs20.readFileSync(files(id).exit, "utf8").trim();
|
|
7233
7819
|
if (raw === "") return void 0;
|
|
7234
7820
|
const code = Number.parseInt(raw, 10);
|
|
7235
7821
|
return Number.isNaN(code) ? null : code;
|
|
@@ -7276,7 +7862,7 @@ function createJobs(deps) {
|
|
|
7276
7862
|
const spec = job.meta.settle;
|
|
7277
7863
|
if (!spec || job.meta.settled || !deps.settle) return report(id);
|
|
7278
7864
|
job.settling = true;
|
|
7279
|
-
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);
|
|
7280
7866
|
const before = job.meta.delivering;
|
|
7281
7867
|
const keep = (going) => {
|
|
7282
7868
|
if (dropped()) return;
|
|
@@ -7301,25 +7887,58 @@ function createJobs(deps) {
|
|
|
7301
7887
|
report(id);
|
|
7302
7888
|
});
|
|
7303
7889
|
}
|
|
7304
|
-
function
|
|
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) {
|
|
7305
7905
|
const job = jobs.get(id);
|
|
7306
7906
|
if (!job || job.outcome) return;
|
|
7307
7907
|
job.outcome = outcome;
|
|
7308
|
-
letGo(job);
|
|
7309
7908
|
deps.log(`job ${id} (${job.meta.label}): ${outcome.code === 0 ? "succeeded" : `failed \u2014 ${outcome.error ?? `exit ${outcome.code}`}`}`, outcome.code === 0 ? "ok" : "err");
|
|
7310
|
-
|
|
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
|
+
});
|
|
7311
7922
|
}
|
|
7312
7923
|
function check2(id) {
|
|
7313
7924
|
const job = jobs.get(id);
|
|
7314
7925
|
if (!job || job.outcome) return;
|
|
7926
|
+
const { meta } = job;
|
|
7927
|
+
if (!meta.pid) meta.pid = launcherPid(id) ?? recordPid(id);
|
|
7315
7928
|
const code = readExit(id);
|
|
7316
7929
|
if (code !== void 0) return finish(id, { code });
|
|
7317
|
-
const { meta } = job;
|
|
7318
7930
|
if (meta.timeoutMinutes && meta.startedAt + meta.timeoutMinutes * 6e4 + slack < now()) {
|
|
7319
|
-
if (meta.pid && alive(meta.pid, id))
|
|
7320
|
-
|
|
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;
|
|
7321
7940
|
}
|
|
7322
|
-
if (
|
|
7941
|
+
if (!alive(meta.pid, id)) {
|
|
7323
7942
|
const late = readExit(id);
|
|
7324
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?)" });
|
|
7325
7944
|
}
|
|
@@ -7341,7 +7960,12 @@ function createJobs(deps) {
|
|
|
7341
7960
|
*/
|
|
7342
7961
|
start(frame, ctx, instance) {
|
|
7343
7962
|
if (jobs.has(frame.jobId)) return;
|
|
7344
|
-
|
|
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 });
|
|
7345
7969
|
const meta = {
|
|
7346
7970
|
jobId: frame.jobId,
|
|
7347
7971
|
runId: frame.runId,
|
|
@@ -7354,35 +7978,72 @@ function createJobs(deps) {
|
|
|
7354
7978
|
...ctx?.settle ? { settle: { ...ctx.settle } } : {},
|
|
7355
7979
|
...ctx?.secrets?.length ? { secrets: [...ctx.secrets] } : {}
|
|
7356
7980
|
};
|
|
7981
|
+
const unit = deps.tagOf?.(frame.jobId) ?? null;
|
|
7982
|
+
if (unit !== null) meta.unit = unit;
|
|
7357
7983
|
const job = { meta, release: null, outcome: null, reportedAt: null };
|
|
7358
7984
|
jobs.set(frame.jobId, job);
|
|
7359
|
-
writeMeta(meta);
|
|
7985
|
+
writeMeta(meta, true);
|
|
7360
7986
|
if (!ctx) return finish(frame.jobId, { code: null, error: `run ${frame.runId} is not executing on this machine any more` });
|
|
7361
7987
|
const f = files(frame.jobId);
|
|
7362
7988
|
const inner = wrapJailed(ctx.jail, "/bin/bash", ["-c", frame.command]);
|
|
7363
|
-
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)}`;
|
|
7364
7990
|
let outFd = null;
|
|
7991
|
+
let child;
|
|
7365
7992
|
try {
|
|
7366
|
-
outFd =
|
|
7367
|
-
const
|
|
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 });
|
|
7368
7998
|
child.on("error", (err) => finish(frame.jobId, { code: null, error: `could not start: ${err.message}` }));
|
|
7369
|
-
child.on("exit", () =>
|
|
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
|
+
});
|
|
7370
8010
|
child.unref();
|
|
7371
|
-
meta.pid = child.pid ?? null;
|
|
7372
|
-
writeMeta(meta);
|
|
7373
8011
|
} catch (err) {
|
|
7374
8012
|
return finish(frame.jobId, { code: null, error: `could not start: ${err.message}` });
|
|
7375
8013
|
} finally {
|
|
7376
|
-
if (outFd !== null)
|
|
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);
|
|
7377
8026
|
}
|
|
7378
8027
|
job.release = deps.hold(ctx.checkout, `job:${frame.jobId}`);
|
|
7379
8028
|
deps.log(`job ${frame.jobId} started for run ${frame.runId}: ${frame.label}`, "info");
|
|
7380
8029
|
},
|
|
7381
|
-
/**
|
|
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
|
+
*/
|
|
7382
8034
|
cancel(jobId) {
|
|
7383
8035
|
const job = jobs.get(jobId);
|
|
7384
8036
|
if (!job) return false;
|
|
7385
|
-
if (!job.outcome && 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);
|
|
7386
8047
|
letGo(job);
|
|
7387
8048
|
forget(jobId);
|
|
7388
8049
|
if (!job.outcome) deps.log(`job ${jobId}: cancelled from the instance`, "warn");
|
|
@@ -7409,7 +8070,11 @@ function createJobs(deps) {
|
|
|
7409
8070
|
for (const job of jobs.values()) {
|
|
7410
8071
|
if (job.meta.runId !== runId || !job.meta.settle) continue;
|
|
7411
8072
|
delete job.meta.settle;
|
|
7412
|
-
|
|
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
|
+
}
|
|
7413
8078
|
}
|
|
7414
8079
|
},
|
|
7415
8080
|
/** A connection is up: send every end again, the unreported and the lately sent — of the jobs `of` its instance (`Meta.instance`). */
|
|
@@ -7427,35 +8092,85 @@ function createJobs(deps) {
|
|
|
7427
8092
|
* first if that had not been; one still running is watched again and
|
|
7428
8093
|
* holds its checkout. `onEach` is called before each job is looked at:
|
|
7429
8094
|
* the worker puts its lifeline off with it, as the scan grows with the
|
|
7430
|
-
* 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.
|
|
7431
8103
|
*/
|
|
7432
|
-
recover(onEach) {
|
|
8104
|
+
recover(onEach, o = {}) {
|
|
8105
|
+
recoveryComplete = true;
|
|
8106
|
+
unreadable.clear();
|
|
7433
8107
|
let names = [];
|
|
7434
8108
|
try {
|
|
7435
|
-
names =
|
|
7436
|
-
} catch {
|
|
8109
|
+
names = fs20.readdirSync(deps.dir).filter((n) => n.endsWith(".json"));
|
|
8110
|
+
} catch (err) {
|
|
8111
|
+
if (err.code !== "ENOENT") recoveryComplete = false;
|
|
7437
8112
|
return [];
|
|
7438
8113
|
}
|
|
7439
8114
|
for (const name of names) {
|
|
7440
8115
|
onEach?.();
|
|
7441
|
-
|
|
7442
|
-
|
|
7443
|
-
|
|
7444
|
-
} catch {
|
|
8116
|
+
const meta = readRecord(name.slice(0, -".json".length));
|
|
8117
|
+
if (!meta) {
|
|
8118
|
+
unreadable.add(name.slice(0, -".json".length));
|
|
7445
8119
|
continue;
|
|
7446
8120
|
}
|
|
7447
|
-
if (
|
|
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);
|
|
7448
8125
|
const job = { meta, release: null, outcome: null, reportedAt: null };
|
|
7449
8126
|
jobs.set(meta.jobId, job);
|
|
7450
8127
|
const code = readExit(meta.jobId);
|
|
7451
|
-
|
|
7452
|
-
|
|
8128
|
+
let outcome = null;
|
|
8129
|
+
if (code !== void 0) outcome = { code };
|
|
8130
|
+
else if (meta.pid ? alive(meta.pid, meta.jobId) : starting(meta)) {
|
|
7453
8131
|
if (meta.checkout) job.release = deps.hold(meta.checkout, `job:${meta.jobId}`);
|
|
7454
|
-
} else
|
|
7455
|
-
|
|
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) {
|
|
8138
|
+
if (meta.checkout) job.release = deps.hold(meta.checkout, `job:${meta.jobId}`);
|
|
8139
|
+
finish(meta.jobId, outcome);
|
|
8140
|
+
} else {
|
|
8141
|
+
job.outcome = outcome;
|
|
8142
|
+
settleThenReport(meta.jobId);
|
|
8143
|
+
}
|
|
7456
8144
|
}
|
|
7457
8145
|
return [...jobs.keys()].sort();
|
|
7458
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
|
+
},
|
|
7459
8174
|
/** jobs running here, or ended and not confirmed by the instance — `hello.jobs` */
|
|
7460
8175
|
liveIds() {
|
|
7461
8176
|
return [...jobs.keys()].sort();
|
|
@@ -7567,7 +8282,7 @@ function memo(make) {
|
|
|
7567
8282
|
}
|
|
7568
8283
|
function runHomeOf(cacheDir, instanceSegment, workspace, agent) {
|
|
7569
8284
|
const safe2 = (s) => s.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 60) || "_";
|
|
7570
|
-
return
|
|
8285
|
+
return path18.join(cacheDir, "homes", instanceSegment, `${safe2(workspace)}-${hashKey(workspace).slice(0, 8)}`, safe2(agent));
|
|
7571
8286
|
}
|
|
7572
8287
|
async function pushTaskBranch(git2, checkout, runId, auth, repoUrl, capBytes = WIP_FILE_CAP_MB * 1024 ** 2, givenUp = () => false) {
|
|
7573
8288
|
if (!checkout.branch) return { pushed: false, error: "the checkout has no task branch" };
|
|
@@ -7594,7 +8309,7 @@ async function commitLeftovers(git2, cwd, runId, local, capBytes) {
|
|
|
7594
8309
|
if (!dirty.trim() && !merging.length) return [];
|
|
7595
8310
|
await git2(cwd, ["add", "-A"], local);
|
|
7596
8311
|
const staged = (await git2(cwd, ["diff", "--cached", "--name-only", "-z", "--no-renames", "--diff-filter=d"], local)).split("\0").filter(Boolean);
|
|
7597
|
-
const uncommitted = staged.filter((rel) => sizeOf(
|
|
8312
|
+
const uncommitted = staged.filter((rel) => sizeOf(path18.join(cwd, rel)) >= capBytes);
|
|
7598
8313
|
if (uncommitted.length) await git2(cwd, ["reset", "-q", "--", ...uncommitted], { ...local, GIT_LITERAL_PATHSPECS: "1" });
|
|
7599
8314
|
const left = (await git2(cwd, ["diff", "--cached", "--name-only", "-z"], local)).trim();
|
|
7600
8315
|
if (left || merging.length) {
|
|
@@ -7608,10 +8323,10 @@ async function commitLeftovers(git2, cwd, runId, local, capBytes) {
|
|
|
7608
8323
|
return uncommitted;
|
|
7609
8324
|
}
|
|
7610
8325
|
async function mergeHeads(git2, cwd, local) {
|
|
7611
|
-
const file =
|
|
8326
|
+
const file = path18.resolve(cwd, (await git2(cwd, ["rev-parse", "--git-path", "MERGE_HEAD"], local)).trim());
|
|
7612
8327
|
let text;
|
|
7613
8328
|
try {
|
|
7614
|
-
const fh = await
|
|
8329
|
+
const fh = await fs21.promises.open(file, fs21.constants.O_RDONLY | (fs21.constants.O_NOFOLLOW ?? 0) | (fs21.constants.O_NONBLOCK ?? 0));
|
|
7615
8330
|
try {
|
|
7616
8331
|
const st = await fh.stat();
|
|
7617
8332
|
if (!st.isFile() || st.size > 64 * 1024) return [];
|
|
@@ -7653,7 +8368,7 @@ async function setAsideTaskBranch(git2, checkout, runId, baseBranch, capBytes =
|
|
|
7653
8368
|
}
|
|
7654
8369
|
function sizeOf(p) {
|
|
7655
8370
|
try {
|
|
7656
|
-
return
|
|
8371
|
+
return fs21.lstatSync(p).size;
|
|
7657
8372
|
} catch {
|
|
7658
8373
|
return 0;
|
|
7659
8374
|
}
|
|
@@ -7669,6 +8384,14 @@ function engineOf(needs) {
|
|
|
7669
8384
|
const preset = presetOf(needs);
|
|
7670
8385
|
return preset ? { kind: "cli", preset } : null;
|
|
7671
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
|
+
}
|
|
7672
8395
|
function createRunner(deps) {
|
|
7673
8396
|
const live = /* @__PURE__ */ new Map();
|
|
7674
8397
|
const running = /* @__PURE__ */ new Map();
|
|
@@ -7687,6 +8410,25 @@ function createRunner(deps) {
|
|
|
7687
8410
|
const cli = deps.cli ?? runCliEngine;
|
|
7688
8411
|
const sdk = deps.sdk ?? runSdkEngine;
|
|
7689
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
|
+
};
|
|
7690
8432
|
const conns = /* @__PURE__ */ new Map();
|
|
7691
8433
|
const connOf = (instance) => {
|
|
7692
8434
|
let c = conns.get(instance);
|
|
@@ -7700,7 +8442,7 @@ function createRunner(deps) {
|
|
|
7700
8442
|
const artifactsFor = memo((instance) => deps.artifactsFor ? deps.artifactsFor(instance) : deps.artifacts);
|
|
7701
8443
|
const skillsFor = memo((instance) => deps.skillsFor ? deps.skillsFor(instance) : deps.skills);
|
|
7702
8444
|
const jobs = createJobs({
|
|
7703
|
-
dir:
|
|
8445
|
+
dir: path18.join(deps.cfg.cache_dir, "jobs"),
|
|
7704
8446
|
send: (frame, instance) => {
|
|
7705
8447
|
const link = conns.get(instance ?? deps.cfg.instance)?.link;
|
|
7706
8448
|
if (!link) return false;
|
|
@@ -7713,6 +8455,14 @@ function createRunner(deps) {
|
|
|
7713
8455
|
settle: (spec, job, hooks) => settleJob(spec, job, hooks),
|
|
7714
8456
|
// as a run's sent result: the grace, and then some
|
|
7715
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
|
+
})),
|
|
7716
8466
|
...deps.jobDeps
|
|
7717
8467
|
});
|
|
7718
8468
|
const jobInstance = (jobId) => {
|
|
@@ -7903,6 +8653,7 @@ function createRunner(deps) {
|
|
|
7903
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");
|
|
7904
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");
|
|
7905
8655
|
};
|
|
8656
|
+
let tagged = null;
|
|
7906
8657
|
let checkout;
|
|
7907
8658
|
try {
|
|
7908
8659
|
checkout = await deps.cache.checkoutForRun(instance, grant.project, grant.creds.git, runId);
|
|
@@ -7926,7 +8677,7 @@ function createRunner(deps) {
|
|
|
7926
8677
|
}
|
|
7927
8678
|
const runGrant = {
|
|
7928
8679
|
...grant,
|
|
7929
|
-
systemPrompt: grant.systemPrompt.replaceAll(WORKER_ARTIFACTS_ROOT,
|
|
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)")
|
|
7930
8681
|
};
|
|
7931
8682
|
if (artifacts && !ctl.signal.aborted) {
|
|
7932
8683
|
await settling.get(`${instance}\0${grant.project.taskId}`);
|
|
@@ -7944,14 +8695,17 @@ function createRunner(deps) {
|
|
|
7944
8695
|
const browsersDir = templateBrowsers ? null : playwrightBrowsers(ownerHome);
|
|
7945
8696
|
const browsersPath = templateBrowsers ? "0" : browsersDir;
|
|
7946
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");
|
|
7947
8700
|
const ctx = {
|
|
7948
8701
|
instance,
|
|
8702
|
+
unit,
|
|
7949
8703
|
cwd: checkout.cwd,
|
|
7950
8704
|
repoDir: checkout.repoDir,
|
|
7951
8705
|
home: runHomeOf(deps.cfg.cache_dir, deps.cache.instanceSegment(instance), grant.workspace, grant.agent),
|
|
7952
8706
|
artifactsDir,
|
|
7953
8707
|
...slice?.dir ? { skillsDir: slice.dir } : {},
|
|
7954
|
-
...templateHome &&
|
|
8708
|
+
...templateHome && fs21.existsSync(templateHome) ? { templateHome } : {},
|
|
7955
8709
|
...browsersDir ? { browsersDir } : {},
|
|
7956
8710
|
...hostEnv ? { hostEnv } : {},
|
|
7957
8711
|
jail: deps.jail,
|
|
@@ -7968,7 +8722,7 @@ function createRunner(deps) {
|
|
|
7968
8722
|
seedMcpFiles(ctx.home);
|
|
7969
8723
|
const noKey = (m) => ({ ...m, key: "", baseUrl: null });
|
|
7970
8724
|
const jobGrant = { ...grant, creds: { ...grant.creds, model: noKey(grant.creds.model), extraModels: grant.creds.extraModels.map(noKey) } };
|
|
7971
|
-
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 } : {} });
|
|
7972
8726
|
entry.jobs = {
|
|
7973
8727
|
cwd: checkout.cwd,
|
|
7974
8728
|
env,
|
|
@@ -7978,6 +8732,7 @@ function createRunner(deps) {
|
|
|
7978
8732
|
...artifacts ? { settle: { workspace: grant.workspace, taskId: grant.project.taskId, runJwt: grant.runJwt, dir: artifactsDir, mounted: mounted !== null } } : {}
|
|
7979
8733
|
};
|
|
7980
8734
|
entry.inEngine = true;
|
|
8735
|
+
tagged = unit;
|
|
7981
8736
|
const kind = engineOf(grant.needs)?.kind;
|
|
7982
8737
|
outcome = kind === "plan" ? await plan(runGrant, ctx) : kind === "sdk" ? await sdk(runGrant, ctx) : await cli(runGrant, ctx);
|
|
7983
8738
|
} catch (err) {
|
|
@@ -7987,8 +8742,28 @@ function createRunner(deps) {
|
|
|
7987
8742
|
}
|
|
7988
8743
|
}
|
|
7989
8744
|
clearTimeout(timeout);
|
|
8745
|
+
const swept = tagged === null ? null : sweepTag(tagged, deps.killGraceMs ?? END_GRACE_MS);
|
|
7990
8746
|
entry.relay.close();
|
|
7991
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
|
+
}
|
|
7992
8767
|
const givenUp = () => entry.discard;
|
|
7993
8768
|
let push = givenUp() ? null : await pushTaskBranch(git2, checkout, runId, grant.creds.git, grant.project.repoUrl, void 0, givenUp);
|
|
7994
8769
|
if (!push || !push.pushed && givenUp()) push = await setAsideTaskBranch(git2, checkout, runId, grant.project.baseBranch);
|
|
@@ -8145,8 +8920,56 @@ function createRunner(deps) {
|
|
|
8145
8920
|
},
|
|
8146
8921
|
/** jobs of `instance` running here or with an end it has not confirmed — its `hello.jobs` */
|
|
8147
8922
|
jobIds: (instance = deps.cfg.instance) => jobs.liveIds().filter((id) => jobInstance(id) === instance),
|
|
8148
|
-
/**
|
|
8149
|
-
|
|
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
|
+
},
|
|
8150
8973
|
/**
|
|
8151
8974
|
* Watch the jobs, a round `ms` after the last one ended; returns the stop. A round looks
|
|
8152
8975
|
* at one job per turn of the loop: a look may take seconds (`ps` on macOS, cut at 5 s), so
|
|
@@ -8305,27 +9128,27 @@ function createRunner(deps) {
|
|
|
8305
9128
|
}
|
|
8306
9129
|
|
|
8307
9130
|
// src/skills.ts
|
|
8308
|
-
import
|
|
8309
|
-
import
|
|
9131
|
+
import fs23 from "fs";
|
|
9132
|
+
import path20 from "path";
|
|
8310
9133
|
import { Readable as Readable2 } from "stream";
|
|
8311
9134
|
import { pipeline as pipeline3 } from "stream/promises";
|
|
8312
9135
|
|
|
8313
9136
|
// ../packages/shared/src/tar.ts
|
|
8314
|
-
import
|
|
8315
|
-
import
|
|
9137
|
+
import fs22 from "fs";
|
|
9138
|
+
import path19 from "path";
|
|
8316
9139
|
var BLOCK = 512;
|
|
8317
9140
|
function str2(buf, off, len) {
|
|
8318
9141
|
const end = buf.indexOf(0, off);
|
|
8319
9142
|
return buf.toString("utf8", off, end >= off && end < off + len ? end : off + len);
|
|
8320
9143
|
}
|
|
8321
9144
|
function insideDest(dest, name) {
|
|
8322
|
-
if (!name ||
|
|
8323
|
-
const abs =
|
|
8324
|
-
return abs.startsWith(
|
|
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;
|
|
8325
9148
|
}
|
|
8326
9149
|
function extractTar(file, dest) {
|
|
8327
|
-
|
|
8328
|
-
const fd =
|
|
9150
|
+
fs22.mkdirSync(dest, { recursive: true });
|
|
9151
|
+
const fd = fs22.openSync(file, "r");
|
|
8329
9152
|
const out = { files: 0, skipped: [] };
|
|
8330
9153
|
try {
|
|
8331
9154
|
let pos = 0;
|
|
@@ -8334,7 +9157,7 @@ function extractTar(file, dest) {
|
|
|
8334
9157
|
const buf = Buffer.alloc(len);
|
|
8335
9158
|
let got = 0;
|
|
8336
9159
|
while (got < len) {
|
|
8337
|
-
const n =
|
|
9160
|
+
const n = fs22.readSync(fd, buf, got, len - got, pos + got);
|
|
8338
9161
|
if (n === 0) throw new Error("the archive is truncated");
|
|
8339
9162
|
got += n;
|
|
8340
9163
|
}
|
|
@@ -8365,26 +9188,26 @@ function extractTar(file, dest) {
|
|
|
8365
9188
|
continue;
|
|
8366
9189
|
}
|
|
8367
9190
|
if (type === "5") {
|
|
8368
|
-
|
|
9191
|
+
fs22.mkdirSync(abs, { recursive: true });
|
|
8369
9192
|
continue;
|
|
8370
9193
|
}
|
|
8371
|
-
|
|
9194
|
+
fs22.mkdirSync(path19.dirname(abs), { recursive: true });
|
|
8372
9195
|
const mode = parseInt(str2(h, 100, 8).trim() || "644", 8) & 73 ? 493 : 420;
|
|
8373
|
-
const wfd =
|
|
9196
|
+
const wfd = fs22.openSync(abs, "w", mode);
|
|
8374
9197
|
try {
|
|
8375
9198
|
for (let left = size; left > 0; ) {
|
|
8376
9199
|
const chunk = read(Math.min(left, 1024 * 1024));
|
|
8377
|
-
|
|
9200
|
+
fs22.writeSync(wfd, chunk);
|
|
8378
9201
|
left -= chunk.length;
|
|
8379
9202
|
}
|
|
8380
9203
|
} finally {
|
|
8381
|
-
|
|
9204
|
+
fs22.closeSync(wfd);
|
|
8382
9205
|
}
|
|
8383
9206
|
pos += padded - size;
|
|
8384
9207
|
out.files++;
|
|
8385
9208
|
}
|
|
8386
9209
|
} finally {
|
|
8387
|
-
|
|
9210
|
+
fs22.closeSync(fd);
|
|
8388
9211
|
}
|
|
8389
9212
|
}
|
|
8390
9213
|
|
|
@@ -8393,24 +9216,24 @@ var HASH = /^[0-9a-f]{64}$/;
|
|
|
8393
9216
|
var safe = (s) => s.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 80) || "_";
|
|
8394
9217
|
function createSkills(o) {
|
|
8395
9218
|
const fetchFn = o.fetch ?? globalThis.fetch;
|
|
8396
|
-
const root =
|
|
9219
|
+
const root = path20.join(o.cacheDir, "skills", o.instanceSegment);
|
|
8397
9220
|
const current = /* @__PURE__ */ new Map();
|
|
8398
9221
|
const inUse = /* @__PURE__ */ new Map();
|
|
8399
9222
|
let seq = 0;
|
|
8400
|
-
const wsDir = (ws) =>
|
|
9223
|
+
const wsDir = (ws) => path20.join(root, safe(ws));
|
|
8401
9224
|
function prune(ws) {
|
|
8402
9225
|
const dir = wsDir(ws);
|
|
8403
9226
|
const keep = new Set([...current].filter(([k]) => k.startsWith(`${ws}\0`)).map(([, h]) => h));
|
|
8404
9227
|
let entries;
|
|
8405
9228
|
try {
|
|
8406
|
-
entries =
|
|
9229
|
+
entries = fs23.readdirSync(dir);
|
|
8407
9230
|
} catch {
|
|
8408
9231
|
return;
|
|
8409
9232
|
}
|
|
8410
9233
|
for (const name of entries) {
|
|
8411
|
-
const abs =
|
|
9234
|
+
const abs = path20.join(dir, name);
|
|
8412
9235
|
const stale = name.startsWith(".") ? !name.includes(`-${process.pid}-`) : !keep.has(name) && !inUse.get(abs);
|
|
8413
|
-
if (stale)
|
|
9236
|
+
if (stale) fs23.rmSync(abs, { recursive: true, force: true });
|
|
8414
9237
|
}
|
|
8415
9238
|
}
|
|
8416
9239
|
function hold(ws, dir) {
|
|
@@ -8427,30 +9250,30 @@ function createSkills(o) {
|
|
|
8427
9250
|
}
|
|
8428
9251
|
async function unpack(ws, hash, body) {
|
|
8429
9252
|
const base = wsDir(ws);
|
|
8430
|
-
const dir =
|
|
9253
|
+
const dir = path20.join(base, hash);
|
|
8431
9254
|
const tag = `-${process.pid}-${++seq}`;
|
|
8432
|
-
const tar =
|
|
8433
|
-
const tmp =
|
|
8434
|
-
|
|
9255
|
+
const tar = path20.join(base, `.${hash}${tag}.tar`);
|
|
9256
|
+
const tmp = path20.join(base, `.${hash}${tag}`);
|
|
9257
|
+
fs23.mkdirSync(base, { recursive: true });
|
|
8435
9258
|
try {
|
|
8436
|
-
await pipeline3(Readable2.fromWeb(body),
|
|
9259
|
+
await pipeline3(Readable2.fromWeb(body), fs23.createWriteStream(tar));
|
|
8437
9260
|
extractTar(tar, tmp);
|
|
8438
9261
|
try {
|
|
8439
|
-
|
|
9262
|
+
fs23.renameSync(tmp, dir);
|
|
8440
9263
|
} catch (err) {
|
|
8441
|
-
if (!
|
|
9264
|
+
if (!fs23.existsSync(dir)) throw err;
|
|
8442
9265
|
}
|
|
8443
9266
|
return dir;
|
|
8444
9267
|
} finally {
|
|
8445
|
-
|
|
8446
|
-
|
|
9268
|
+
fs23.rmSync(tar, { force: true });
|
|
9269
|
+
fs23.rmSync(tmp, { recursive: true, force: true });
|
|
8447
9270
|
}
|
|
8448
9271
|
}
|
|
8449
9272
|
async function acquire(grant) {
|
|
8450
9273
|
const ws = grant.workspace;
|
|
8451
9274
|
const key = `${ws}\0${grant.agent}`;
|
|
8452
9275
|
const known = current.get(key);
|
|
8453
|
-
const knownDir = known &&
|
|
9276
|
+
const knownDir = known && fs23.existsSync(path20.join(wsDir(ws), known)) ? path20.join(wsDir(ws), known) : null;
|
|
8454
9277
|
const url = `${o.instance}/api/v1/workspaces/${encodeURIComponent(ws)}/skills/slice.tar?agent=${encodeURIComponent(grant.agent)}`;
|
|
8455
9278
|
const settle = (dir, hash, fetched, error) => {
|
|
8456
9279
|
if (hash) current.set(key, hash);
|
|
@@ -8472,8 +9295,8 @@ function createSkills(o) {
|
|
|
8472
9295
|
});
|
|
8473
9296
|
throw new Error(`the instance sent no valid ${SKILLS_SLICE_HASH_HEADER}`);
|
|
8474
9297
|
}
|
|
8475
|
-
const have =
|
|
8476
|
-
if (
|
|
9298
|
+
const have = path20.join(wsDir(ws), hash);
|
|
9299
|
+
if (fs23.existsSync(have)) {
|
|
8477
9300
|
await res.body.cancel().catch(() => {
|
|
8478
9301
|
});
|
|
8479
9302
|
return settle(have, hash, false);
|
|
@@ -8488,9 +9311,9 @@ function createSkills(o) {
|
|
|
8488
9311
|
|
|
8489
9312
|
// src/warm.ts
|
|
8490
9313
|
import { spawn as spawn4 } from "child_process";
|
|
8491
|
-
import { createHash as
|
|
8492
|
-
import
|
|
8493
|
-
import
|
|
9314
|
+
import { createHash as createHash4 } from "crypto";
|
|
9315
|
+
import fs24 from "fs";
|
|
9316
|
+
import path21 from "path";
|
|
8494
9317
|
var TEMPLATE_INPUTS = ["package.json", "pnpm-lock.yaml", "package-lock.json", "yarn.lock", "pyproject.toml", "uv.lock"];
|
|
8495
9318
|
var PLAYWRIGHT_NODE = ["playwright", "@playwright/test", "playwright-core"];
|
|
8496
9319
|
function nodeDeps(packageJson) {
|
|
@@ -8549,7 +9372,7 @@ function templatePlan(files, has) {
|
|
|
8549
9372
|
}
|
|
8550
9373
|
var stepText = (s) => [s.bin, ...s.args].join(" ");
|
|
8551
9374
|
function templateFingerprint(inputs, plan) {
|
|
8552
|
-
const h =
|
|
9375
|
+
const h = createHash4("sha1");
|
|
8553
9376
|
for (const name of [...inputs.keys()].sort()) h.update(`${name}\0${inputs.get(name)}\0`);
|
|
8554
9377
|
for (const s of plan.steps) h.update(`${stepText(s)}\0`);
|
|
8555
9378
|
return h.digest("hex");
|
|
@@ -8573,12 +9396,12 @@ function createWarmer(deps) {
|
|
|
8573
9396
|
async function dropTemplate(cacheKey) {
|
|
8574
9397
|
const tpl = deps.cache.templateDir(cacheKey);
|
|
8575
9398
|
const old = `${tpl}.old`;
|
|
8576
|
-
|
|
8577
|
-
await
|
|
9399
|
+
fs24.rmSync(deps.cache.templateStampFile(cacheKey), { force: true });
|
|
9400
|
+
await fs24.promises.rm(old, { recursive: true, force: true });
|
|
8578
9401
|
await deps.cache.replaceTemplate(cacheKey, () => {
|
|
8579
|
-
if (
|
|
9402
|
+
if (fs24.existsSync(tpl)) fs24.renameSync(tpl, old);
|
|
8580
9403
|
});
|
|
8581
|
-
await
|
|
9404
|
+
await fs24.promises.rm(old, { recursive: true, force: true });
|
|
8582
9405
|
}
|
|
8583
9406
|
async function build(frame, repo, ref, plan, fingerprint) {
|
|
8584
9407
|
const final = deps.cache.templateDir(frame.cacheKey);
|
|
@@ -8586,9 +9409,9 @@ function createWarmer(deps) {
|
|
|
8586
9409
|
const home = deps.cache.templateHome(frame.cacheKey);
|
|
8587
9410
|
const clearBuild = async () => {
|
|
8588
9411
|
try {
|
|
8589
|
-
await removeWorktreeAsync((cwd, args) => deps.runGitAsync(cwd, args, {}, [
|
|
9412
|
+
await removeWorktreeAsync((cwd, args) => deps.runGitAsync(cwd, args, {}, [path21.dirname(buildDir)]), repo, buildDir, { force: true });
|
|
8590
9413
|
} catch {
|
|
8591
|
-
await
|
|
9414
|
+
await fs24.promises.rm(buildDir, { recursive: true, force: true });
|
|
8592
9415
|
try {
|
|
8593
9416
|
await deps.runGitAsync(repo, ["worktree", "prune"], {});
|
|
8594
9417
|
} catch {
|
|
@@ -8596,8 +9419,8 @@ function createWarmer(deps) {
|
|
|
8596
9419
|
}
|
|
8597
9420
|
};
|
|
8598
9421
|
await clearBuild();
|
|
8599
|
-
|
|
8600
|
-
await deps.runGitAsync(repo, ["worktree", "add", "--lock", "--detach", buildDir, ref], {}, [
|
|
9422
|
+
fs24.mkdirSync(home, { recursive: true });
|
|
9423
|
+
await deps.runGitAsync(repo, ["worktree", "add", "--lock", "--detach", buildDir, ref], {}, [path21.dirname(buildDir)]);
|
|
8601
9424
|
try {
|
|
8602
9425
|
const env = {
|
|
8603
9426
|
...hostEnvOf(deps.hostEnv ?? process.env),
|
|
@@ -8629,18 +9452,18 @@ ${tail2}` : ""}` };
|
|
|
8629
9452
|
}
|
|
8630
9453
|
const next = `${final}.next`;
|
|
8631
9454
|
const old = `${final}.old`;
|
|
8632
|
-
await
|
|
8633
|
-
await
|
|
8634
|
-
|
|
8635
|
-
const kept = plan.keep.filter((entry) =>
|
|
8636
|
-
for (const entry of kept)
|
|
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));
|
|
8637
9460
|
await deps.cache.replaceTemplate(frame.cacheKey, () => {
|
|
8638
|
-
if (
|
|
8639
|
-
|
|
9461
|
+
if (fs24.existsSync(final)) fs24.renameSync(final, old);
|
|
9462
|
+
fs24.renameSync(next, final);
|
|
8640
9463
|
});
|
|
8641
|
-
await
|
|
9464
|
+
await fs24.promises.rm(old, { recursive: true, force: true });
|
|
8642
9465
|
const stamp = { fingerprint, builtAt: deps.now(), steps: plan.steps.map(stepText), keep: kept, playwright: plan.playwright };
|
|
8643
|
-
|
|
9466
|
+
fs24.writeFileSync(deps.cache.templateStampFile(frame.cacheKey), JSON.stringify(stamp, null, 2));
|
|
8644
9467
|
return { fetched: true, template: "built", detail: kept.join(", ") || "nothing to keep" };
|
|
8645
9468
|
} finally {
|
|
8646
9469
|
await clearBuild();
|
|
@@ -8670,7 +9493,7 @@ ${tail2}` : ""}` };
|
|
|
8670
9493
|
return { fetched: true, template: "none" };
|
|
8671
9494
|
}
|
|
8672
9495
|
const fingerprint = templateFingerprint(inputs, plan);
|
|
8673
|
-
if (deps.cache.templateStamp(frame.cacheKey)?.fingerprint === fingerprint &&
|
|
9496
|
+
if (deps.cache.templateStamp(frame.cacheKey)?.fingerprint === fingerprint && fs24.existsSync(deps.cache.templateDir(frame.cacheKey)) && fs24.existsSync(deps.cache.templateHome(frame.cacheKey)))
|
|
8674
9497
|
return { fetched: true, template: "current" };
|
|
8675
9498
|
if (await overBudget()) return { fetched: true, template: "skipped", detail: `the cache is at its cache_gb (${deps.cacheGb} GB)` };
|
|
8676
9499
|
const out = await build(frame, repo, ref, plan, fingerprint);
|
|
@@ -8725,13 +9548,13 @@ function execStep(bin, args, o) {
|
|
|
8725
9548
|
}
|
|
8726
9549
|
|
|
8727
9550
|
// src/version.ts
|
|
8728
|
-
var VERSION = "0.1.
|
|
9551
|
+
var VERSION = "0.1.5";
|
|
8729
9552
|
|
|
8730
9553
|
// src/update.ts
|
|
8731
9554
|
import { spawn as spawn5 } from "child_process";
|
|
8732
9555
|
import { constants as fsConstants } from "fs";
|
|
8733
|
-
import
|
|
8734
|
-
import
|
|
9556
|
+
import fs25 from "fs/promises";
|
|
9557
|
+
import path22 from "path";
|
|
8735
9558
|
var PROBE_TIMEOUT_MS = 1e4;
|
|
8736
9559
|
var OUTPUT_KEPT = 64 * 1024;
|
|
8737
9560
|
var keepTail = (s) => s.length > OUTPUT_KEPT ? s.slice(s.length - OUTPUT_KEPT) : s;
|
|
@@ -8747,7 +9570,7 @@ function runUpdateChild(cmd2, args, o, start = spawn5) {
|
|
|
8747
9570
|
clearTimeout(timer);
|
|
8748
9571
|
resolve(out);
|
|
8749
9572
|
};
|
|
8750
|
-
const env = o.pathDirs?.length ? { ...process.env, PATH: [...o.pathDirs, process.env.PATH].filter(Boolean).join(
|
|
9573
|
+
const env = o.pathDirs?.length ? { ...process.env, PATH: [...o.pathDirs, process.env.PATH].filter(Boolean).join(path22.delimiter) } : process.env;
|
|
8751
9574
|
let child;
|
|
8752
9575
|
try {
|
|
8753
9576
|
child = start(cmd2, args, { stdio: ["ignore", "pipe", "pipe"], detached: true, env });
|
|
@@ -8787,10 +9610,10 @@ async function check(o) {
|
|
|
8787
9610
|
}
|
|
8788
9611
|
const platform = o.platform ?? process.platform;
|
|
8789
9612
|
if (platform === "win32") return { allowed: false, reason: "remote update is not supported on native Windows" };
|
|
8790
|
-
const realpath2 = o.realpath ?? ((p) =>
|
|
8791
|
-
const access = o.access ?? ((p) =>
|
|
8792
|
-
const lstat = o.lstat ?? ((p) =>
|
|
8793
|
-
const stat = o.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));
|
|
8794
9617
|
const run = o.run ?? runUpdateChild;
|
|
8795
9618
|
const execPath = o.execPath ?? process.execPath;
|
|
8796
9619
|
const script = o.script ?? process.argv[1];
|
|
@@ -8806,14 +9629,14 @@ async function check(o) {
|
|
|
8806
9629
|
} catch (err) {
|
|
8807
9630
|
return notGlobal(`${script}: ${errText(err)}`);
|
|
8808
9631
|
}
|
|
8809
|
-
const marker = `${
|
|
9632
|
+
const marker = `${path22.sep}lib${path22.sep}node_modules${path22.sep}bridex-worker${path22.sep}`;
|
|
8810
9633
|
const at = real.lastIndexOf(marker);
|
|
8811
9634
|
if (at < 0) return notGlobal(real);
|
|
8812
|
-
const prefix = real.slice(0, at) ||
|
|
8813
|
-
const globalDir =
|
|
9635
|
+
const prefix = real.slice(0, at) || path22.sep;
|
|
9636
|
+
const globalDir = path22.join(prefix, "lib", "node_modules");
|
|
8814
9637
|
const globalReal = await realpath2(globalDir).catch(() => globalDir);
|
|
8815
|
-
const pathDir =
|
|
8816
|
-
const candidates = [.../* @__PURE__ */ new Set([
|
|
9638
|
+
const pathDir = path22.dirname(execPath);
|
|
9639
|
+
const candidates = [.../* @__PURE__ */ new Set([path22.join(prefix, "bin", "npm"), path22.join(pathDir, "npm")])];
|
|
8817
9640
|
const misses = [];
|
|
8818
9641
|
let npm = null;
|
|
8819
9642
|
let npmPrefix = prefix;
|
|
@@ -8835,14 +9658,14 @@ async function check(o) {
|
|
|
8835
9658
|
const rootReal = root ? await realpath2(root).catch(() => root) : "";
|
|
8836
9659
|
if (rootReal === globalReal) {
|
|
8837
9660
|
npm = cand;
|
|
8838
|
-
if (
|
|
8839
|
-
const named =
|
|
9661
|
+
if (path22.basename(root) === "node_modules" && path22.basename(path22.dirname(root)) === "lib") {
|
|
9662
|
+
const named = path22.dirname(path22.dirname(root));
|
|
8840
9663
|
npmPrefix = await realpath2(named).catch(() => prefix);
|
|
8841
9664
|
}
|
|
8842
9665
|
if (npmPrefix !== prefix) {
|
|
8843
9666
|
return {
|
|
8844
9667
|
allowed: false,
|
|
8845
|
-
reason: `npm's global folder ${root} is a symlink to ${globalReal}: an install would go wherever it points by then; remote update needs ${
|
|
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`
|
|
8846
9669
|
};
|
|
8847
9670
|
}
|
|
8848
9671
|
break;
|
|
@@ -8860,7 +9683,7 @@ async function check(o) {
|
|
|
8860
9683
|
} catch {
|
|
8861
9684
|
return { allowed: false, reason: `the global npm folder ${globalReal} is not writable by this user` };
|
|
8862
9685
|
}
|
|
8863
|
-
const binDir =
|
|
9686
|
+
const binDir = path22.join(prefix, "bin");
|
|
8864
9687
|
try {
|
|
8865
9688
|
await access(binDir);
|
|
8866
9689
|
if (!(await stat(binDir)).isDirectory()) {
|
|
@@ -8879,7 +9702,7 @@ async function check(o) {
|
|
|
8879
9702
|
};
|
|
8880
9703
|
}
|
|
8881
9704
|
}
|
|
8882
|
-
const interpreter =
|
|
9705
|
+
const interpreter = path22.isAbsolute(argv0) ? argv0 : null;
|
|
8883
9706
|
return {
|
|
8884
9707
|
allowed: true,
|
|
8885
9708
|
npm,
|
|
@@ -8918,9 +9741,9 @@ async function install(o) {
|
|
|
8918
9741
|
const execPath = o.execPath ?? process.execPath;
|
|
8919
9742
|
const script = o.script ?? process.argv[1] ?? "";
|
|
8920
9743
|
const timeoutMs = o.timeoutMs ?? INSTALL_TIMEOUT_MS;
|
|
8921
|
-
const pathDir =
|
|
9744
|
+
const pathDir = path22.dirname(execPath);
|
|
8922
9745
|
const spec = `bridex-worker@${o.version}`;
|
|
8923
|
-
const npmPath = [.../* @__PURE__ */ new Set([pathDir, ...o.interpreter ? [
|
|
9746
|
+
const npmPath = [.../* @__PURE__ */ new Set([pathDir, ...o.interpreter ? [path22.dirname(o.interpreter)] : []])];
|
|
8924
9747
|
const npm = await run(o.npm, ["i", "-g", "--prefix", o.prefix, spec], { timeoutMs, pathDirs: npmPath });
|
|
8925
9748
|
const fallbackNodes = [.../* @__PURE__ */ new Set([o.interpreter, "node"])].filter((n) => !!n && n !== execPath);
|
|
8926
9749
|
const probe = async (as) => {
|
|
@@ -9129,7 +9952,7 @@ function createUpdater(deps) {
|
|
|
9129
9952
|
// src/watchdog.ts
|
|
9130
9953
|
import { spawn as spawn6 } from "child_process";
|
|
9131
9954
|
import { randomBytes as randomBytes2 } from "crypto";
|
|
9132
|
-
import
|
|
9955
|
+
import path23 from "path";
|
|
9133
9956
|
import { Worker } from "worker_threads";
|
|
9134
9957
|
var POOL_PROBE_MS = 3e4;
|
|
9135
9958
|
var POOL_STUCK_MS = 12e4;
|
|
@@ -9268,7 +10091,7 @@ function skippedReason(o, c) {
|
|
|
9268
10091
|
async function captureStacks(o) {
|
|
9269
10092
|
const platform = o.platform ?? process.platform;
|
|
9270
10093
|
if (platform !== "darwin") return { skipped: `stacks are taken on macOS only, not on ${platform}` };
|
|
9271
|
-
const file =
|
|
10094
|
+
const file = path23.join(o.dir, stackFileName(o.at ?? /* @__PURE__ */ new Date()));
|
|
9272
10095
|
const timeoutMs = o.timeoutMs ?? SAMPLE_TIMEOUT_MS;
|
|
9273
10096
|
const args = [
|
|
9274
10097
|
"-c",
|
|
@@ -9826,7 +10649,7 @@ var STUCK_STOP_REASON = "the worker went away: its thread pool was stuck, so it
|
|
|
9826
10649
|
function stuckActions(o) {
|
|
9827
10650
|
const capture = o.captureStacks ?? captureStacks;
|
|
9828
10651
|
return {
|
|
9829
|
-
capture: () => capture({ dir:
|
|
10652
|
+
capture: () => capture({ dir: path24.join(o.configDir, "diag") }),
|
|
9830
10653
|
stop: async (ms) => {
|
|
9831
10654
|
o.poller()?.stop();
|
|
9832
10655
|
o.reporter()?.stop();
|
|
@@ -9955,6 +10778,8 @@ async function runWorker(cfg, deps) {
|
|
|
9955
10778
|
});
|
|
9956
10779
|
const recovered = runner.recoverJobs(() => life?.arm(LIFELINE_MS));
|
|
9957
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));
|
|
9958
10783
|
runner.watchJobs();
|
|
9959
10784
|
const connections = createConnections({
|
|
9960
10785
|
connect: (url, token) => connectInstance(url, token),
|