@indigoai-us/hq-cli 5.345.214 → 5.345.215-beta.0
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/CHANGELOG.md +29 -0
- package/dist/command-catalog.generated.d.ts +134 -7
- package/dist/command-catalog.generated.js +168 -7
- package/dist/commands/agents.d.ts +51 -1
- package/dist/commands/agents.js +154 -2
- package/dist/commands/bot-jobs.d.ts +2 -15
- package/dist/commands/bot-jobs.js +2 -94
- package/dist/commands/bot-runtime.d.ts +46 -5
- package/dist/commands/bot-runtime.js +228 -18
- package/dist/commands/bot.d.ts +16 -9
- package/dist/commands/bot.js +169 -51
- package/dist/commands/cloud.d.ts +66 -13
- package/dist/commands/cloud.js +120 -39
- package/dist/commands/company-restore.d.ts +23 -0
- package/dist/commands/company-restore.js +128 -0
- package/dist/commands/company.js +2 -0
- package/dist/commands/integrations-connect.d.ts +10 -3
- package/dist/commands/integrations-connect.js +87 -13
- package/dist/commands/lanes.js +26 -9
- package/dist/commands/sources.js +6 -0
- package/dist/commands/storage-offload.d.ts +12 -0
- package/dist/commands/storage-offload.js +41 -3
- package/dist/commands/sync-mode.js +5 -0
- package/dist/commands/whoami.js +4 -0
- package/dist/lib/bot/config.d.ts +1 -0
- package/dist/lib/bot/config.js +10 -0
- package/dist/lib/bot/eventbridge-cron.d.ts +22 -0
- package/dist/lib/bot/eventbridge-cron.js +104 -0
- package/dist/lib/bot/fleet-local.d.ts +33 -1
- package/dist/lib/bot/fleet-local.js +215 -31
- package/dist/lib/bot/fleet-python.d.ts +3 -0
- package/dist/lib/bot/fleet-python.js +34 -4
- package/dist/lib/bot/fleet-runtime-sources.d.ts +15 -0
- package/dist/lib/bot/fleet-runtime-sources.js +30 -0
- package/dist/lib/bot/legacy-provider-login.d.ts +8 -0
- package/dist/lib/bot/legacy-provider-login.js +19 -2
- package/dist/lib/bot/prompt.js +1 -1
- package/dist/lib/bot/readiness.d.ts +8 -0
- package/dist/lib/bot/readiness.js +17 -3
- package/dist/lib/bot/runtime-auth.d.ts +30 -0
- package/dist/lib/bot/runtime-auth.js +94 -3
- package/dist/lib/bot/status.d.ts +2 -0
- package/dist/lib/capacity/collectors/grok-refresh.d.ts +80 -0
- package/dist/lib/capacity/collectors/grok-refresh.js +189 -0
- package/dist/lib/capacity/collectors/grok.d.ts +5 -0
- package/dist/lib/capacity/collectors/grok.js +56 -5
- package/dist/lib/daemon/catalog.js +11 -1
- package/dist/lib/db/sqlite-binding.d.ts +1 -0
- package/dist/lib/db/sqlite-binding.js +1 -1
- package/dist/lib/delivery/artifacts.d.ts +99 -0
- package/dist/lib/delivery/artifacts.js +548 -0
- package/dist/lib/delivery/backup.d.ts +78 -0
- package/dist/lib/delivery/backup.js +343 -0
- package/dist/lib/delivery/cache.d.ts +29 -0
- package/dist/lib/delivery/cache.js +33 -0
- package/dist/lib/delivery/contracts.d.ts +142 -0
- package/dist/lib/delivery/contracts.js +289 -0
- package/dist/lib/delivery/credentials.d.ts +54 -0
- package/dist/lib/delivery/credentials.js +119 -0
- package/dist/lib/delivery/enrollment.d.ts +142 -0
- package/dist/lib/delivery/enrollment.js +382 -0
- package/dist/lib/delivery/identity.d.ts +25 -0
- package/dist/lib/delivery/identity.js +82 -0
- package/dist/lib/delivery/inbox.d.ts +116 -0
- package/dist/lib/delivery/inbox.js +260 -0
- package/dist/lib/delivery/migrations.d.ts +139 -0
- package/dist/lib/delivery/migrations.js +623 -0
- package/dist/lib/delivery/mqtt-adapter.d.ts +50 -0
- package/dist/lib/delivery/mqtt-adapter.js +242 -0
- package/dist/lib/delivery/mqtt.d.ts +61 -0
- package/dist/lib/delivery/mqtt.js +112 -0
- package/dist/lib/delivery/outbox.d.ts +95 -0
- package/dist/lib/delivery/outbox.js +187 -0
- package/dist/lib/delivery/provenance.d.ts +129 -0
- package/dist/lib/delivery/provenance.js +93 -0
- package/dist/lib/delivery/reconciler.d.ts +151 -0
- package/dist/lib/delivery/reconciler.js +492 -0
- package/dist/lib/delivery/restore.d.ts +35 -0
- package/dist/lib/delivery/restore.js +134 -0
- package/dist/lib/delivery/store.d.ts +161 -0
- package/dist/lib/delivery/store.js +940 -0
- package/dist/lib/delivery/workers/macos-job-helper.d.ts +103 -0
- package/dist/lib/delivery/workers/macos-job-helper.js +927 -0
- package/dist/lib/delivery/workers/macos.d.ts +176 -0
- package/dist/lib/delivery/workers/macos.js +901 -0
- package/dist/lib/delivery/workers/windows-boundary.d.ts +453 -0
- package/dist/lib/delivery/workers/windows-boundary.js +693 -0
- package/dist/lib/delivery/workers/windows-job-helper.d.ts +35 -0
- package/dist/lib/delivery/workers/windows-job-helper.js +264 -0
- package/dist/lib/delivery/workers/windows.d.ts +241 -0
- package/dist/lib/delivery/workers/windows.js +608 -0
- package/dist/lib/install/provider-wrappers.d.ts +2 -0
- package/dist/lib/install/provider-wrappers.js +68 -3
- package/dist/utils/cognito-callback-port.d.ts +14 -0
- package/dist/utils/cognito-callback-port.js +24 -0
- package/dist/utils/cognito-session.js +3 -3
- package/dist/utils/deleted-company-notice.d.ts +59 -0
- package/dist/utils/deleted-company-notice.js +156 -0
- package/dist/utils/login-browser.d.ts +1 -1
- package/dist/utils/login-browser.js +7 -5
- package/dist/utils/resident-package-preload.js +30 -15
- package/dist/utils/vault-api.js +7 -0
- package/package.json +7 -7
|
@@ -0,0 +1,901 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run and contain jobs on a macOS worker (US-007).
|
|
3
|
+
*
|
|
4
|
+
* The flow matches the Windows worker (windows.ts): the spec is validated, the
|
|
5
|
+
* run and job are read, the worker profile is matched, every input is
|
|
6
|
+
* verified and the launcher is prepared, all before the claim. A refusal
|
|
7
|
+
* claims nothing and is recorded as exactly one terminal result. After the
|
|
8
|
+
* claim the inputs are copied read-only into a fresh attempt directory and
|
|
9
|
+
* the command runs there with only the declared environment.
|
|
10
|
+
*
|
|
11
|
+
* Containment is a per-job Seatbelt profile applied by a small native
|
|
12
|
+
* supervisor (macos-job-helper.ts), compiled once on the worker with the
|
|
13
|
+
* system C compiler. The profile (jobProfile below):
|
|
14
|
+
* - denies reading the job's marker file, which is how the supervisor finds
|
|
15
|
+
* every process of the job, detached and reparented ones included;
|
|
16
|
+
* - denies every Mach service lookup except the directory service that
|
|
17
|
+
* user and group lookups need, so a job cannot reach launchd, the pasteboard,
|
|
18
|
+
* the window server or other system services;
|
|
19
|
+
* - denies file reads by default: the job reads the system runtime, node,
|
|
20
|
+
* the developer tools, the paths its spec declares in readPaths, and its own
|
|
21
|
+
* attempt directory; the helper directory, the delivery store, the work
|
|
22
|
+
* directory and other attempts are denied even when a declared path covers
|
|
23
|
+
* them;
|
|
24
|
+
* - denies the network unless the spec declares network: true;
|
|
25
|
+
* - denies inspecting processes outside the job's sandbox (process info,
|
|
26
|
+
* task ports and the kern.proc sysctls);
|
|
27
|
+
* - denies signals to processes outside the job's sandbox;
|
|
28
|
+
* - denies every file write outside the attempt directory;
|
|
29
|
+
* - denies exec of launchctl, open and osascript. This is defence in depth:
|
|
30
|
+
* the Mach lookup rule already stops what those tools would ask launchd,
|
|
31
|
+
* LaunchServices or Apple Events to do.
|
|
32
|
+
* Nothing is written under Library/LaunchAgents or any system location and
|
|
33
|
+
* nothing is registered with launchd. Without a compiler, off macOS, or when
|
|
34
|
+
* the helper fails its hash check or self test, the launcher refuses with
|
|
35
|
+
* CONTAINMENT_UNAVAILABLE before the claim.
|
|
36
|
+
*
|
|
37
|
+
* Cleanup. Each helper runs a reaper outside the sandbox that kills the tree
|
|
38
|
+
* within CLEANUP_WINDOW_MS when the helper dies, so no later prepare is needed.
|
|
39
|
+
* Each job also has a watchdog inside its own sandbox that kills the tree
|
|
40
|
+
* within CLEANUP_WINDOW_MS once the helper and the reaper are both gone, so a
|
|
41
|
+
* tree whose host, helper and reaper are all killed together does not wait
|
|
42
|
+
* for a later prepare either. Only a job that kills its own watchdog (it may
|
|
43
|
+
* signal its own sandbox) falls back to the periodic or next prepare sweep.
|
|
44
|
+
* A kill that runs out of the window is reported as failed KILL_INCOMPLETE and
|
|
45
|
+
* the job directory is left for the next sweep.
|
|
46
|
+
*
|
|
47
|
+
* Opt-out. optOut() stops admitting work at once. An active job that declared
|
|
48
|
+
* interruptible: true is killed with its whole tree and its attempt is
|
|
49
|
+
* returned to the ledger (abandoned, so the job is claimable again); every
|
|
50
|
+
* other active job runs to completion. A job that exits on its own before the
|
|
51
|
+
* kill lands is recorded as its exit. When the ledger return fails the result
|
|
52
|
+
* is failed RETURN_NOT_RECORDED and the attempt stays open.
|
|
53
|
+
*
|
|
54
|
+
* This module imports only node built-ins and sibling worker modules at
|
|
55
|
+
* runtime so it can be bundled without node_modules.
|
|
56
|
+
*/
|
|
57
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
58
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
59
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
60
|
+
import { basename, dirname, isAbsolute, join } from "node:path";
|
|
61
|
+
import { HELPER_SOURCE } from "./macos-job-helper.js";
|
|
62
|
+
import { WORKER_RESULT_VERSION, WorkerRefusal, helperOutcome, matchCapabilities, validateSpec, } from "./windows.js";
|
|
63
|
+
/**
|
|
64
|
+
* The memory and per-job process limits on macOS are sampled by the helper,
|
|
65
|
+
* not enforced by the kernel (RLIMIT_AS and RLIMIT_DATA return EINVAL, RLIMIT_RSS
|
|
66
|
+
* is not enforced, and RLIMIT_NPROC counts every process of the user), so they
|
|
67
|
+
* are advertised under their own names and a spec that requires the hard
|
|
68
|
+
* memory-limit or process-limit is not matched. The thresholds the G5
|
|
69
|
+
* acceptance probes hold on this host are an overshoot of at most 6 processes
|
|
70
|
+
* against a limit of 6, and of at most 512 MiB against a memory limit of
|
|
71
|
+
* 256 MiB, before the kill. Measured over six runs on 2026-10-28: 0 to 1
|
|
72
|
+
* process and 0 to 320 MiB of overshoot. These are test thresholds and
|
|
73
|
+
* measurements, not proven bounds; a faster forker or allocator can pass them. Memory is sampled every 10 ms;
|
|
74
|
+
* the process count is checked at every fork note and on the 50 ms discovery
|
|
75
|
+
* scan.
|
|
76
|
+
*/
|
|
77
|
+
export const MAC_SAMPLED_CAPABILITIES = ["memory-limit-sampled", "process-limit-sampled"];
|
|
78
|
+
/**
|
|
79
|
+
* Room above the job's maxProcesses in the RLIMIT_NPROC ceiling. That rlimit
|
|
80
|
+
* counts every process of the user, so the helper sets it to the user's
|
|
81
|
+
* process count at start plus maxProcesses plus this room: other processes of
|
|
82
|
+
* the user that start while the job runs eat into the room, not the job's
|
|
83
|
+
* limit.
|
|
84
|
+
*/
|
|
85
|
+
export const MAC_NPROC_HEADROOM = 128;
|
|
86
|
+
/**
|
|
87
|
+
* How each advertised limit is enforced. kernel: true means a kernel rlimit
|
|
88
|
+
* set before exec and inherited by every descendant; kernel: false means the
|
|
89
|
+
* helper samples it and kills the tree on a breach.
|
|
90
|
+
*/
|
|
91
|
+
export const MAC_LIMIT_ENFORCEMENT = {
|
|
92
|
+
"memory-limit-sampled": { kernel: false, detail: "resident memory of the tree, sampled every 10 ms" },
|
|
93
|
+
"process-limit-sampled": { kernel: false, detail: "live processes of the job, checked at every fork note and every 50 ms" },
|
|
94
|
+
"process-count-ceiling": {
|
|
95
|
+
kernel: true,
|
|
96
|
+
detail: `RLIMIT_NPROC: the user's process count at start + maxProcesses + ${MAC_NPROC_HEADROOM}; a fork past it fails with EAGAIN`,
|
|
97
|
+
},
|
|
98
|
+
"cpu-time-limit": { kernel: true, detail: "RLIMIT_CPU per process at ceil(cpuTimeMs / 1000) s (SIGXCPU, SIGKILL 1 s later); the tree's sum is also sampled" },
|
|
99
|
+
"file-size-limit": { kernel: true, detail: "RLIMIT_FSIZE at limits.fileSizeBytes when declared (SIGXFSZ, or EFBIG when the signal is ignored)" },
|
|
100
|
+
"open-files-limit": { kernel: true, detail: "RLIMIT_NOFILE per process at limits.openFiles when declared (EMFILE)" },
|
|
101
|
+
};
|
|
102
|
+
/** What the native macOS launcher contains. */
|
|
103
|
+
export const MAC_CAPABILITIES = [
|
|
104
|
+
"process-tree-kill",
|
|
105
|
+
...MAC_SAMPLED_CAPABILITIES,
|
|
106
|
+
"process-count-ceiling",
|
|
107
|
+
"cpu-time-limit",
|
|
108
|
+
"file-size-limit",
|
|
109
|
+
"open-files-limit",
|
|
110
|
+
"posix-signals",
|
|
111
|
+
];
|
|
112
|
+
/** The macOS-only capability names the US-006 matcher does not know. */
|
|
113
|
+
const MAC_ONLY_CAPABILITIES = [...MAC_SAMPLED_CAPABILITIES, "process-count-ceiling", "file-size-limit", "open-files-limit"];
|
|
114
|
+
/**
|
|
115
|
+
* The US-006 matcher, plus the macOS-only capabilities it does not know (the
|
|
116
|
+
* sampled limits and the kernel ceilings): those must be in the worker
|
|
117
|
+
* profile. A spec asking for the hard memory-limit or process-limit is
|
|
118
|
+
* refused CAPABILITY_MISSING, since no macOS profile has them.
|
|
119
|
+
*/
|
|
120
|
+
export function matchMacCapabilities(profile, req) {
|
|
121
|
+
const caps = req.capabilities ?? [];
|
|
122
|
+
const macOnly = caps.filter((c) => MAC_ONLY_CAPABILITIES.includes(c));
|
|
123
|
+
const match = matchCapabilities(profile, { ...req, capabilities: caps.filter((c) => !MAC_ONLY_CAPABILITIES.includes(c)) });
|
|
124
|
+
if (!match.ok)
|
|
125
|
+
return match;
|
|
126
|
+
const missing = macOnly.filter((c) => !profile.capabilities.includes(c));
|
|
127
|
+
if (missing.length > 0)
|
|
128
|
+
return { ok: false, code: "CAPABILITY_MISSING", detail: `worker lacks ${missing.join(", ")}` };
|
|
129
|
+
return { ok: true };
|
|
130
|
+
}
|
|
131
|
+
/** How long a kill, or the reaper after a helper dies, may take before the job is reported as not fully killed. */
|
|
132
|
+
export const CLEANUP_WINDOW_MS = 2000;
|
|
133
|
+
// ---------------------------------------------------------------------------
|
|
134
|
+
// Worker profile
|
|
135
|
+
let gitVersion;
|
|
136
|
+
/**
|
|
137
|
+
* The git a job runs: the developer directory's git, which works inside the
|
|
138
|
+
* sandbox. The /usr/bin/git shim does not (it exits 71 there), so the host's
|
|
139
|
+
* own `git` is never what is advertised. start() puts this git first on the
|
|
140
|
+
* job's PATH for a spec that requires git.
|
|
141
|
+
*/
|
|
142
|
+
function detectGit() {
|
|
143
|
+
if (gitVersion !== undefined)
|
|
144
|
+
return gitVersion;
|
|
145
|
+
const dev = detectDeveloperDir();
|
|
146
|
+
if (!dev)
|
|
147
|
+
return (gitVersion = null);
|
|
148
|
+
try {
|
|
149
|
+
const out = execFileSync(join(dev, "usr", "bin", "git"), ["--version"], { encoding: "utf8", timeout: 10_000, stdio: ["ignore", "pipe", "ignore"] });
|
|
150
|
+
gitVersion = /(\d+\.\d+\.\d+)/.exec(out)?.[1] ?? null;
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
gitVersion = null;
|
|
154
|
+
}
|
|
155
|
+
return gitVersion;
|
|
156
|
+
}
|
|
157
|
+
let cachedProfile;
|
|
158
|
+
/** The profile of this macOS host: node, git when present, and the macOS containment capabilities. */
|
|
159
|
+
export function detectMacProfile() {
|
|
160
|
+
if (cachedProfile)
|
|
161
|
+
return cachedProfile;
|
|
162
|
+
const platform = process.platform === "darwin" ? "macos" : process.platform === "win32" ? "windows" : process.platform;
|
|
163
|
+
const toolchains = { node: process.versions.node };
|
|
164
|
+
const git = detectGit();
|
|
165
|
+
if (git)
|
|
166
|
+
toolchains.git = git;
|
|
167
|
+
const capabilities = process.platform === "darwin" ? [...MAC_CAPABILITIES] : ["posix-signals"];
|
|
168
|
+
if (git)
|
|
169
|
+
capabilities.push("git");
|
|
170
|
+
cachedProfile = { platform, arch: process.arch, toolchains, capabilities };
|
|
171
|
+
return cachedProfile;
|
|
172
|
+
}
|
|
173
|
+
/** Characters a Seatbelt profile literal cannot hold without escaping. */
|
|
174
|
+
const UNPROFILABLE = /["\\\n\0]/;
|
|
175
|
+
/** True when the spec asks for git, by capability or by toolchain. */
|
|
176
|
+
function requiresGit(spec) {
|
|
177
|
+
return (spec.requires?.capabilities ?? []).includes("git") || spec.requires?.toolchains?.git !== undefined;
|
|
178
|
+
}
|
|
179
|
+
/** The US-006 checks plus the interruptible, readPaths and network fields, and a declared PATH when git is required. */
|
|
180
|
+
export function validateMacSpec(spec) {
|
|
181
|
+
const problem = validateSpec(spec);
|
|
182
|
+
if (problem)
|
|
183
|
+
return { ok: false, code: "INVALID_SPEC", detail: problem };
|
|
184
|
+
const s = spec;
|
|
185
|
+
if (s.interruptible !== undefined && typeof s.interruptible !== "boolean")
|
|
186
|
+
return { ok: false, code: "INVALID_SPEC", detail: "interruptible must be a boolean" };
|
|
187
|
+
if (s.network !== undefined && typeof s.network !== "boolean")
|
|
188
|
+
return { ok: false, code: "INVALID_SPEC", detail: "network must be a boolean" };
|
|
189
|
+
const lim = spec.limits;
|
|
190
|
+
for (const key of ["fileSizeBytes", "openFiles"]) {
|
|
191
|
+
const v = lim[key];
|
|
192
|
+
if (v !== undefined && !(Number.isSafeInteger(v) && v > 0))
|
|
193
|
+
return { ok: false, code: "INVALID_SPEC", detail: `limits.${key} must be a positive integer` };
|
|
194
|
+
}
|
|
195
|
+
if (requiresGit(spec) && typeof spec.env?.PATH !== "string") {
|
|
196
|
+
return { ok: false, code: "INVALID_SPEC", detail: "a spec that requires git must declare PATH; the worker puts its git first on it" };
|
|
197
|
+
}
|
|
198
|
+
if (s.readPaths !== undefined) {
|
|
199
|
+
if (!Array.isArray(s.readPaths) || !s.readPaths.every((p) => typeof p === "string"))
|
|
200
|
+
return { ok: false, code: "INVALID_SPEC", detail: "readPaths must be an array of strings" };
|
|
201
|
+
for (const p of s.readPaths) {
|
|
202
|
+
if (!isAbsolute(p))
|
|
203
|
+
return { ok: false, code: "INVALID_SPEC", detail: `read path ${JSON.stringify(p)} is not absolute` };
|
|
204
|
+
if (UNPROFILABLE.test(p))
|
|
205
|
+
return { ok: false, code: "INVALID_SPEC", detail: `read path ${JSON.stringify(p)} cannot be placed in a sandbox profile` };
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return { ok: true };
|
|
209
|
+
}
|
|
210
|
+
const HELPER_HASH = createHash("sha256").update(HELPER_SOURCE).digest("hex").slice(0, 16);
|
|
211
|
+
/** A token directory without a helper.pid this old is from a launch that never started its helper. */
|
|
212
|
+
const ORPHAN_DIR_MS = 30_000;
|
|
213
|
+
function sha256(bytes) {
|
|
214
|
+
return createHash("sha256").update(bytes).digest("hex");
|
|
215
|
+
}
|
|
216
|
+
function firstLine(err) {
|
|
217
|
+
return (err instanceof Error ? err.message : String(err)).split("\n")[0];
|
|
218
|
+
}
|
|
219
|
+
function unavailable(detail) {
|
|
220
|
+
return new WorkerRefusal("CONTAINMENT_UNAVAILABLE", detail);
|
|
221
|
+
}
|
|
222
|
+
/** Seatbelt profile strings are quoted literals; a path that needs escaping is refused rather than escaped. */
|
|
223
|
+
function profilePath(path) {
|
|
224
|
+
if (UNPROFILABLE.test(path))
|
|
225
|
+
throw unavailable(`path ${JSON.stringify(path)} cannot be placed in a sandbox profile`);
|
|
226
|
+
return path;
|
|
227
|
+
}
|
|
228
|
+
function real(path) {
|
|
229
|
+
try {
|
|
230
|
+
return realpathSync(path);
|
|
231
|
+
}
|
|
232
|
+
catch {
|
|
233
|
+
return path;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
function clamp(value, fallback, lo, hi) {
|
|
237
|
+
if (value === undefined || !Number.isFinite(value))
|
|
238
|
+
return fallback;
|
|
239
|
+
return Math.min(hi, Math.max(lo, Math.floor(value)));
|
|
240
|
+
}
|
|
241
|
+
let developerDir;
|
|
242
|
+
/** The active developer directory, so git and the other developer tools can run inside the sandbox. */
|
|
243
|
+
function detectDeveloperDir() {
|
|
244
|
+
if (developerDir !== undefined)
|
|
245
|
+
return developerDir;
|
|
246
|
+
try {
|
|
247
|
+
const out = execFileSync("/usr/bin/xcode-select", ["-p"], { encoding: "utf8", timeout: 10_000, stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
248
|
+
developerDir = out ? real(out) : null;
|
|
249
|
+
}
|
|
250
|
+
catch {
|
|
251
|
+
developerDir = null;
|
|
252
|
+
}
|
|
253
|
+
return developerDir;
|
|
254
|
+
}
|
|
255
|
+
/** The declared environment, with the developer directory's git first on PATH when the spec requires git. */
|
|
256
|
+
function jobEnv(spec) {
|
|
257
|
+
const env = { ...spec.env };
|
|
258
|
+
const dev = detectDeveloperDir();
|
|
259
|
+
if (dev && requiresGit(spec) && typeof env.PATH === "string")
|
|
260
|
+
env.PATH = `${join(dev, "usr", "bin")}:${env.PATH}`;
|
|
261
|
+
return env;
|
|
262
|
+
}
|
|
263
|
+
/** The install prefix of a node binary: bin/node's grandparent. */
|
|
264
|
+
function nodePrefix(file) {
|
|
265
|
+
return dirname(dirname(real(file)));
|
|
266
|
+
}
|
|
267
|
+
const subpaths = (paths) => paths.map((p) => `(subpath "${profilePath(p)}")`).join(" ");
|
|
268
|
+
const literals = (paths) => paths.map((p) => `(literal "${profilePath(p)}")`).join(" ");
|
|
269
|
+
/** What every job reads: the system runtime. */
|
|
270
|
+
const SYSTEM_READ = ["/usr", "/bin", "/sbin", "/System", "/Library/Apple", "/private/var/db/dyld", "/private/var/db/timezone", "/private/etc/localtime", "/dev"];
|
|
271
|
+
/** The command line tools and the developer directory selection. */
|
|
272
|
+
const TOOL_READ = ["/Library/Developer/CommandLineTools", "/private/var/select/developer_dir", "/private/var/db/xcode_select_link"];
|
|
273
|
+
/**
|
|
274
|
+
* Every directory above the given paths, and the /var, /tmp and /etc links
|
|
275
|
+
* into /private, so the paths can be resolved. The paths themselves are not
|
|
276
|
+
* included: their own rules decide them.
|
|
277
|
+
*/
|
|
278
|
+
function ancestors(paths) {
|
|
279
|
+
const out = new Set(["/var", "/tmp", "/etc"]);
|
|
280
|
+
for (const path of paths) {
|
|
281
|
+
for (let dir = dirname(path); dir !== "/" && !out.has(dir); dir = dirname(dir))
|
|
282
|
+
out.add(dir);
|
|
283
|
+
}
|
|
284
|
+
return [...out].sort();
|
|
285
|
+
}
|
|
286
|
+
/** The job's Seatbelt profile. Seatbelt applies the last rule that matches, so each deny after an allow narrows it. */
|
|
287
|
+
function jobProfile(p) {
|
|
288
|
+
const runtime = [nodePrefix(process.execPath)];
|
|
289
|
+
if (basename(p.file) === "node")
|
|
290
|
+
runtime.push(nodePrefix(p.file));
|
|
291
|
+
const dev = detectDeveloperDir();
|
|
292
|
+
if (dev)
|
|
293
|
+
runtime.push(dev);
|
|
294
|
+
const declared = p.readPaths.map(real);
|
|
295
|
+
const attemptDir = profilePath(p.attemptDir);
|
|
296
|
+
const readable = [...SYSTEM_READ, ...runtime, ...TOOL_READ, ...declared, p.control, attemptDir];
|
|
297
|
+
const lines = [
|
|
298
|
+
"(version 1)",
|
|
299
|
+
"(allow default)",
|
|
300
|
+
"(deny mach-lookup)",
|
|
301
|
+
'(allow mach-lookup (global-name "com.apple.system.opendirectoryd.libinfo"))',
|
|
302
|
+
"(deny file-read*)",
|
|
303
|
+
// Metadata only for the directories above each readable path, so a path can be resolved; a sibling cannot be stat'd.
|
|
304
|
+
`(allow file-read-metadata ${literals(ancestors(readable))})`,
|
|
305
|
+
`(allow file-read* (literal "/") ${subpaths(SYSTEM_READ.filter((s) => !s.endsWith("localtime")))} (literal "/private/etc/localtime"))`,
|
|
306
|
+
`(allow file-read* ${subpaths(runtime)} (subpath "/Library/Developer/CommandLineTools") (literal "/private/var/select/developer_dir") (literal "/private/var/db/xcode_select_link"))`,
|
|
307
|
+
];
|
|
308
|
+
if (declared.length > 0)
|
|
309
|
+
lines.push(`(allow file-read* ${subpaths(declared)})`);
|
|
310
|
+
lines.push(`(deny file-read* ${subpaths([p.helperRoot, ...p.protectedPaths.map(real)])})`, `(allow file-read* (literal "${profilePath(p.control)}"))`, `(allow file-read* (subpath "${attemptDir}"))`, `(deny file-read* (literal "${profilePath(p.marker)}"))`);
|
|
311
|
+
if (!p.network)
|
|
312
|
+
lines.push("(deny network*)");
|
|
313
|
+
lines.push("(deny process-info*)", "(allow process-info* (target same-sandbox))", "(deny mach-priv-task-port)", "(allow mach-priv-task-port (target same-sandbox))", "(deny mach-task-name)", "(allow mach-task-name (target same-sandbox))", '(deny sysctl-read (sysctl-name-prefix "kern.proc"))', "(deny signal)", "(allow signal (target same-sandbox))", "(deny file-write*)", `(allow file-write* (subpath "${profilePath(p.attemptDir)}") (literal "/dev/null") (literal "/dev/zero") (regex #"^/dev/fd/") (literal "/dev/tty"))`,
|
|
314
|
+
// Defence in depth: the mach-lookup rule already denies what these tools would ask of launchd and LaunchServices.
|
|
315
|
+
'(deny process-exec (literal "/bin/launchctl") (literal "/usr/bin/open") (literal "/usr/bin/osascript"))');
|
|
316
|
+
return lines.join("\n");
|
|
317
|
+
}
|
|
318
|
+
function pidAlive(pid) {
|
|
319
|
+
try {
|
|
320
|
+
process.kill(pid, 0);
|
|
321
|
+
return true;
|
|
322
|
+
}
|
|
323
|
+
catch (err) {
|
|
324
|
+
return err.code === "EPERM";
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
/** The helper's macOS-only exits, then the shared mapping. */
|
|
328
|
+
export function macHelperOutcome(h) {
|
|
329
|
+
if (h.exitLine?.startsWith("exit kill_incomplete"))
|
|
330
|
+
return { reason: "kill_incomplete", detail: `job helper could not kill every process within its cleanup window (${h.exitLine})` };
|
|
331
|
+
if (h.exitLine?.startsWith("exit protocol"))
|
|
332
|
+
return { reason: "supervisor_lost", detail: `job helper stopped the job on a malformed control line (${h.exitLine})` };
|
|
333
|
+
return helperOutcome(h);
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* The native macOS launcher. Each job gets its own helper process, which puts
|
|
337
|
+
* the root in the job's sandbox and supervises the tree; see
|
|
338
|
+
* macos-job-helper.ts for the protocol and the limits.
|
|
339
|
+
*/
|
|
340
|
+
export function nativeMacosLauncher(opts) {
|
|
341
|
+
const window = clamp(opts.cleanupWindowMs, CLEANUP_WINDOW_MS, 0, CLEANUP_WINDOW_MS);
|
|
342
|
+
const seenCap = clamp(opts.seenCapacity, 8192, 1, 8192);
|
|
343
|
+
let helper;
|
|
344
|
+
const paths = () => {
|
|
345
|
+
const root = realpathSync(mkdirAndReturn(opts.helperDir));
|
|
346
|
+
const dir = join(root, HELPER_HASH);
|
|
347
|
+
return { root, dir, exe: join(dir, "hqjob"), jobs: join(root, "jobs") };
|
|
348
|
+
};
|
|
349
|
+
const hashOk = (exe) => {
|
|
350
|
+
if (!existsSync(exe) || !existsSync(`${exe}.sha256`))
|
|
351
|
+
return null;
|
|
352
|
+
const sum = sha256(readFileSync(exe));
|
|
353
|
+
return sum === readFileSync(`${exe}.sha256`, "utf8").trim() ? sum : null;
|
|
354
|
+
};
|
|
355
|
+
const testedAs = (exe, sum) => existsSync(`${exe}.selftest`) && readFileSync(`${exe}.selftest`, "utf8").trim() === sum;
|
|
356
|
+
const selftest = (exe, jobs, sum) => {
|
|
357
|
+
let out;
|
|
358
|
+
try {
|
|
359
|
+
out = execFileSync(exe, ["--selftest", jobs], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 30_000, env: {} });
|
|
360
|
+
}
|
|
361
|
+
catch (err) {
|
|
362
|
+
const said = String(err.stdout ?? "").trim();
|
|
363
|
+
throw unavailable(`job helper self test failed: ${said.split("\n").join("; ") || firstLine(err)}`);
|
|
364
|
+
}
|
|
365
|
+
const lines = out.trim().split("\n");
|
|
366
|
+
if (lines[lines.length - 1] !== "selftest ok")
|
|
367
|
+
throw unavailable(`job helper self test said ${lines.join("; ") || "nothing"}`);
|
|
368
|
+
writeFileSync(`${exe}.selftest`, sum);
|
|
369
|
+
};
|
|
370
|
+
const build = (dir, exe) => {
|
|
371
|
+
const cc = opts.ccPath ?? "/usr/bin/cc";
|
|
372
|
+
if (!existsSync(cc))
|
|
373
|
+
throw unavailable(`no C compiler at ${cc}`);
|
|
374
|
+
const tag = `${process.pid}-${randomBytes(4).toString("hex")}`;
|
|
375
|
+
const src = join(dir, `hqjob-${tag}.c`);
|
|
376
|
+
const tmp = join(dir, `hqjob-${tag}`);
|
|
377
|
+
writeFileSync(src, HELPER_SOURCE);
|
|
378
|
+
try {
|
|
379
|
+
execFileSync(cc, ["-O2", "-Wno-deprecated-declarations", "-o", tmp, src], { stdio: ["ignore", "pipe", "pipe"], timeout: 120_000 });
|
|
380
|
+
}
|
|
381
|
+
finally {
|
|
382
|
+
rmSync(src, { force: true });
|
|
383
|
+
}
|
|
384
|
+
chmodSync(tmp, 0o555);
|
|
385
|
+
writeFileSync(`${tmp}.sha256`, sha256(readFileSync(tmp)));
|
|
386
|
+
rmSync(`${exe}.selftest`, { force: true });
|
|
387
|
+
renameSync(tmp, exe);
|
|
388
|
+
renameSync(`${tmp}.sha256`, `${exe}.sha256`);
|
|
389
|
+
};
|
|
390
|
+
/** Build once per source hash and self test once per binary. Used by prepare only. */
|
|
391
|
+
const ensure = () => {
|
|
392
|
+
if (process.platform !== "darwin")
|
|
393
|
+
throw unavailable(`native macOS containment needs macOS; this host is ${process.platform}`);
|
|
394
|
+
try {
|
|
395
|
+
const { dir, exe, jobs } = paths();
|
|
396
|
+
mkdirSync(dir, { recursive: true });
|
|
397
|
+
mkdirSync(jobs, { recursive: true });
|
|
398
|
+
let sum = hashOk(exe);
|
|
399
|
+
if (!sum) {
|
|
400
|
+
build(dir, exe);
|
|
401
|
+
sum = hashOk(exe);
|
|
402
|
+
if (!sum)
|
|
403
|
+
throw unavailable("job helper failed its hash check right after it was built");
|
|
404
|
+
}
|
|
405
|
+
if (!testedAs(exe, sum))
|
|
406
|
+
selftest(exe, jobs, sum);
|
|
407
|
+
helper = exe;
|
|
408
|
+
return { exe, jobs };
|
|
409
|
+
}
|
|
410
|
+
catch (err) {
|
|
411
|
+
if (err instanceof WorkerRefusal)
|
|
412
|
+
throw err;
|
|
413
|
+
throw unavailable(`job helper could not be built or checked: ${firstLine(err)}`);
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
/** Check the built helper against its recorded hash, and self test it if this binary never was. Never builds. */
|
|
417
|
+
const verify = () => {
|
|
418
|
+
if (process.platform !== "darwin")
|
|
419
|
+
throw unavailable(`native macOS containment needs macOS; this host is ${process.platform}`);
|
|
420
|
+
try {
|
|
421
|
+
const { exe, jobs } = paths();
|
|
422
|
+
const sum = hashOk(exe);
|
|
423
|
+
if (!sum)
|
|
424
|
+
throw unavailable("job helper is missing or does not match its recorded hash; prepare the launcher again");
|
|
425
|
+
mkdirSync(jobs, { recursive: true });
|
|
426
|
+
if (!testedAs(exe, sum))
|
|
427
|
+
selftest(exe, jobs, sum);
|
|
428
|
+
helper = exe;
|
|
429
|
+
return { exe, jobs };
|
|
430
|
+
}
|
|
431
|
+
catch (err) {
|
|
432
|
+
if (err instanceof WorkerRefusal)
|
|
433
|
+
throw err;
|
|
434
|
+
throw unavailable(`job helper could not be checked: ${firstLine(err)}`);
|
|
435
|
+
}
|
|
436
|
+
};
|
|
437
|
+
const reap = (exe, dir) => {
|
|
438
|
+
const marker = join(dir, "marker");
|
|
439
|
+
const control = join(dir, "control");
|
|
440
|
+
if (existsSync(marker) && existsSync(control))
|
|
441
|
+
execFileSync(exe, ["--reap", marker, control], { stdio: "ignore", timeout: 30_000, env: {} });
|
|
442
|
+
};
|
|
443
|
+
/** True when helper.pid names a live process with the recorded start time. */
|
|
444
|
+
const helperAlive = (exe, pidFile) => {
|
|
445
|
+
const parts = readFileSync(pidFile, "utf8").trim().split(" ");
|
|
446
|
+
if (parts.length !== 3 || !parts.every((p) => /^\d+$/.test(p)))
|
|
447
|
+
return false;
|
|
448
|
+
try {
|
|
449
|
+
execFileSync(exe, ["--alive", ...parts], { stdio: "ignore", timeout: 10_000, env: {} });
|
|
450
|
+
return true;
|
|
451
|
+
}
|
|
452
|
+
catch {
|
|
453
|
+
return false;
|
|
454
|
+
}
|
|
455
|
+
};
|
|
456
|
+
/** Kill and remove every job whose helper is gone. A live helper's job is never touched. */
|
|
457
|
+
const sweep = (exe, jobs) => {
|
|
458
|
+
for (const name of readdirSync(jobs)) {
|
|
459
|
+
const dir = join(jobs, name);
|
|
460
|
+
try {
|
|
461
|
+
const pidFile = join(dir, "helper.pid");
|
|
462
|
+
if (existsSync(pidFile)) {
|
|
463
|
+
if (helperAlive(exe, pidFile))
|
|
464
|
+
continue;
|
|
465
|
+
}
|
|
466
|
+
else if (Date.now() - statSync(dir).mtimeMs < ORPHAN_DIR_MS)
|
|
467
|
+
continue;
|
|
468
|
+
reap(exe, dir);
|
|
469
|
+
rmSync(dir, { recursive: true, force: true });
|
|
470
|
+
}
|
|
471
|
+
catch {
|
|
472
|
+
// Another launcher may be sweeping the same directory; the next prepare retries.
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
};
|
|
476
|
+
return {
|
|
477
|
+
prepare: () => {
|
|
478
|
+
const h = ensure();
|
|
479
|
+
sweep(h.exe, h.jobs);
|
|
480
|
+
},
|
|
481
|
+
helperPath: () => helper ?? ensure().exe,
|
|
482
|
+
launch(req) {
|
|
483
|
+
const { exe, jobs } = verify();
|
|
484
|
+
const helperRoot = dirname(dirname(exe));
|
|
485
|
+
const tokenDir = join(jobs, randomBytes(12).toString("hex"));
|
|
486
|
+
const marker = join(tokenDir, "marker");
|
|
487
|
+
const control = join(tokenDir, "control");
|
|
488
|
+
mkdirSync(tokenDir);
|
|
489
|
+
writeFileSync(marker, "");
|
|
490
|
+
writeFileSync(control, "");
|
|
491
|
+
let profile;
|
|
492
|
+
try {
|
|
493
|
+
profile = jobProfile({
|
|
494
|
+
marker,
|
|
495
|
+
control,
|
|
496
|
+
attemptDir: realpathSync(req.cwd),
|
|
497
|
+
helperRoot,
|
|
498
|
+
file: req.file,
|
|
499
|
+
readPaths: req.readPaths ?? [],
|
|
500
|
+
protectedPaths: req.protectedPaths ?? [],
|
|
501
|
+
network: req.network === true,
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
catch (err) {
|
|
505
|
+
rmSync(tokenDir, { recursive: true, force: true });
|
|
506
|
+
throw err;
|
|
507
|
+
}
|
|
508
|
+
const child = spawn(exe, [], { stdio: ["pipe", "pipe", "pipe"], env: {} });
|
|
509
|
+
// Without helper.pid a later sweep cannot tell this live helper from an orphan, so the launch fails
|
|
510
|
+
// before the helper reads its spec: the helper is killed and the token directory removed.
|
|
511
|
+
try {
|
|
512
|
+
if (!child.pid)
|
|
513
|
+
throw new Error("the helper did not start");
|
|
514
|
+
const start = execFileSync(exe, ["--start", String(child.pid)], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 10_000, env: {} }).trim();
|
|
515
|
+
if (!/^\d+ \d+$/.test(start))
|
|
516
|
+
throw new Error(`--start said ${start || "nothing"}`);
|
|
517
|
+
(opts.writeHelperPid ?? writeFileSync)(join(tokenDir, "helper.pid"), `${child.pid} ${start}`);
|
|
518
|
+
}
|
|
519
|
+
catch (err) {
|
|
520
|
+
child.stdin.on("error", () => { });
|
|
521
|
+
child.on("error", () => { });
|
|
522
|
+
child.kill("SIGKILL");
|
|
523
|
+
rmSync(tokenDir, { recursive: true, force: true });
|
|
524
|
+
throw unavailable(`job helper.pid could not be written: ${firstLine(err)}`);
|
|
525
|
+
}
|
|
526
|
+
const seen = [];
|
|
527
|
+
let rootPid = -1;
|
|
528
|
+
let reaperPid = null;
|
|
529
|
+
let watchdogPid = null;
|
|
530
|
+
let exitLine;
|
|
531
|
+
let errorLine;
|
|
532
|
+
let stderr = "";
|
|
533
|
+
let spawnError;
|
|
534
|
+
let cancelled = false;
|
|
535
|
+
let readyResolve;
|
|
536
|
+
const ready = new Promise((r) => (readyResolve = r));
|
|
537
|
+
child.stdin.on("error", () => { });
|
|
538
|
+
const field = (key, value) => `${key}\t${Buffer.from(value, "utf8").toString("base64")}\n`;
|
|
539
|
+
let input = field("app", req.file);
|
|
540
|
+
for (const a of [req.file, ...req.args])
|
|
541
|
+
input += field("arg", a);
|
|
542
|
+
input += field("cwd", req.cwd) + field("log", req.logPath);
|
|
543
|
+
for (const [k, v] of Object.entries(req.env))
|
|
544
|
+
input += field("env", `${k}=${v}`);
|
|
545
|
+
input += field("mem", String(req.limits.memoryBytes)) + field("procs", String(req.limits.maxProcesses)) + field("cpu", String(req.limits.cpuTimeMs));
|
|
546
|
+
input += field("win", String(window)) + field("seen", String(seenCap)) + field("room", String(MAC_NPROC_HEADROOM));
|
|
547
|
+
if (req.limits.fileSizeBytes !== undefined)
|
|
548
|
+
input += field("fsize", String(req.limits.fileSizeBytes));
|
|
549
|
+
if (req.limits.openFiles !== undefined)
|
|
550
|
+
input += field("nofile", String(req.limits.openFiles));
|
|
551
|
+
if (opts.limitSampling === false)
|
|
552
|
+
input += field("sample", "0");
|
|
553
|
+
input += field("profile", profile) + field("mark", marker) + field("ctrl", control) + "end\n";
|
|
554
|
+
child.stdin.write(input);
|
|
555
|
+
let buf = "";
|
|
556
|
+
child.stdout.setEncoding("utf8");
|
|
557
|
+
child.stdout.on("data", (chunk) => {
|
|
558
|
+
buf += chunk;
|
|
559
|
+
let nl;
|
|
560
|
+
while ((nl = buf.indexOf("\n")) >= 0) {
|
|
561
|
+
const line = buf.slice(0, nl).trim();
|
|
562
|
+
buf = buf.slice(nl + 1);
|
|
563
|
+
const [event, a] = line.split(" ");
|
|
564
|
+
if (event === "started") {
|
|
565
|
+
rootPid = Number(a);
|
|
566
|
+
readyResolve(rootPid);
|
|
567
|
+
}
|
|
568
|
+
else if (event === "reaper")
|
|
569
|
+
reaperPid = Number(a);
|
|
570
|
+
else if (event === "watchdog")
|
|
571
|
+
watchdogPid = Number(a);
|
|
572
|
+
else if (event === "process") {
|
|
573
|
+
const pid = Number(a);
|
|
574
|
+
if (!seen.includes(pid))
|
|
575
|
+
seen.push(pid);
|
|
576
|
+
}
|
|
577
|
+
else if (event === "exit")
|
|
578
|
+
exitLine = line;
|
|
579
|
+
else if (event === "error")
|
|
580
|
+
errorLine = line;
|
|
581
|
+
}
|
|
582
|
+
});
|
|
583
|
+
child.stderr.setEncoding("utf8");
|
|
584
|
+
child.stderr.on("data", (chunk) => {
|
|
585
|
+
if (stderr.length < 4096)
|
|
586
|
+
stderr += chunk;
|
|
587
|
+
});
|
|
588
|
+
/** After the helper is lost, give its reaper the cleanup window, then reap what is left. A reaper still alive keeps the directory for the sweep. */
|
|
589
|
+
const afterLost = async () => {
|
|
590
|
+
if (reaperPid && reaperPid > 0) {
|
|
591
|
+
const until = Date.now() + CLEANUP_WINDOW_MS + 1000;
|
|
592
|
+
while (pidAlive(reaperPid) && Date.now() < until)
|
|
593
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
594
|
+
if (pidAlive(reaperPid))
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
597
|
+
reap(exe, tokenDir);
|
|
598
|
+
rmSync(tokenDir, { recursive: true, force: true });
|
|
599
|
+
};
|
|
600
|
+
const done = new Promise((resolve) => {
|
|
601
|
+
child.on("error", (err) => {
|
|
602
|
+
spawnError = err.message;
|
|
603
|
+
});
|
|
604
|
+
child.on("close", (code) => {
|
|
605
|
+
readyResolve(-1);
|
|
606
|
+
const outcome = macHelperOutcome({ exitLine, errorLine, rootPid, code, spawnError, stderr });
|
|
607
|
+
if (outcome.reason === "kill_incomplete") {
|
|
608
|
+
// Members may still be alive: the directory stays so the next sweep can kill them.
|
|
609
|
+
resolve(outcome);
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
if (outcome.reason === "supervisor_lost") {
|
|
613
|
+
afterLost()
|
|
614
|
+
.catch(() => {
|
|
615
|
+
// The next prepare sweep retries this job's directory.
|
|
616
|
+
})
|
|
617
|
+
.finally(() => resolve(outcome));
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
rmSync(tokenDir, { recursive: true, force: true });
|
|
621
|
+
resolve(outcome);
|
|
622
|
+
});
|
|
623
|
+
});
|
|
624
|
+
return {
|
|
625
|
+
get pid() {
|
|
626
|
+
return rootPid > 0 ? rootPid : (child.pid ?? -1);
|
|
627
|
+
},
|
|
628
|
+
get reaperPid() {
|
|
629
|
+
return reaperPid;
|
|
630
|
+
},
|
|
631
|
+
get watchdogPid() {
|
|
632
|
+
return watchdogPid;
|
|
633
|
+
},
|
|
634
|
+
supervisorPid: child.pid ?? null,
|
|
635
|
+
ready,
|
|
636
|
+
processes: () => [...seen],
|
|
637
|
+
cancel: () => {
|
|
638
|
+
if (cancelled)
|
|
639
|
+
return;
|
|
640
|
+
cancelled = true;
|
|
641
|
+
child.stdin.end("cancel\n");
|
|
642
|
+
},
|
|
643
|
+
done,
|
|
644
|
+
};
|
|
645
|
+
},
|
|
646
|
+
};
|
|
647
|
+
}
|
|
648
|
+
function mkdirAndReturn(dir) {
|
|
649
|
+
mkdirSync(dir, { recursive: true });
|
|
650
|
+
return dir;
|
|
651
|
+
}
|
|
652
|
+
/**
|
|
653
|
+
* The periodic orphan sweep interval. A tree whose host, helper and reaper
|
|
654
|
+
* were all killed is ended by its own watchdog within CLEANUP_WINDOW_MS; the
|
|
655
|
+
* sweep is the fallback for a job that killed its watchdog, and removes the
|
|
656
|
+
* job directories the helpers left.
|
|
657
|
+
*/
|
|
658
|
+
export const SWEEP_INTERVAL_MS = 5000;
|
|
659
|
+
/** A store error carries a string code; checked by shape so no runtime import is needed. */
|
|
660
|
+
function storeCode(err) {
|
|
661
|
+
const code = err?.code;
|
|
662
|
+
return err instanceof Error && typeof code === "string" ? code : null;
|
|
663
|
+
}
|
|
664
|
+
function message(err) {
|
|
665
|
+
return (err instanceof Error ? err.message : String(err)).split("\n")[0];
|
|
666
|
+
}
|
|
667
|
+
function isRecord(x) {
|
|
668
|
+
return typeof x === "object" && x !== null && !Array.isArray(x);
|
|
669
|
+
}
|
|
670
|
+
export class MacosWorker {
|
|
671
|
+
opts;
|
|
672
|
+
clock;
|
|
673
|
+
active = new Map();
|
|
674
|
+
opted = false;
|
|
675
|
+
sweepTimer;
|
|
676
|
+
constructor(opts) {
|
|
677
|
+
this.opts = opts;
|
|
678
|
+
this.clock = opts.clock ?? (() => new Date());
|
|
679
|
+
const interval = opts.sweepIntervalMs ?? SWEEP_INTERVAL_MS;
|
|
680
|
+
const launcher = opts.launcher;
|
|
681
|
+
if (interval > 0 && launcher.prepare) {
|
|
682
|
+
this.sweepTimer = setInterval(() => {
|
|
683
|
+
try {
|
|
684
|
+
launcher.prepare?.();
|
|
685
|
+
}
|
|
686
|
+
catch {
|
|
687
|
+
// A failed sweep is retried on the next tick and on the next start.
|
|
688
|
+
}
|
|
689
|
+
}, interval);
|
|
690
|
+
this.sweepTimer.unref();
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
/** Stop the periodic orphan sweep. Active jobs are not touched. */
|
|
694
|
+
close() {
|
|
695
|
+
if (this.sweepTimer)
|
|
696
|
+
clearInterval(this.sweepTimer);
|
|
697
|
+
this.sweepTimer = undefined;
|
|
698
|
+
}
|
|
699
|
+
/** True once optOut has been called. No new job is admitted after that. */
|
|
700
|
+
get optedOut() {
|
|
701
|
+
return this.opted;
|
|
702
|
+
}
|
|
703
|
+
now() {
|
|
704
|
+
return this.clock().toISOString();
|
|
705
|
+
}
|
|
706
|
+
result(spec, fields) {
|
|
707
|
+
const env = isRecord(spec?.env) ? spec.env : {};
|
|
708
|
+
return {
|
|
709
|
+
schemaVersion: WORKER_RESULT_VERSION,
|
|
710
|
+
tenantId: String(spec?.tenantId ?? ""),
|
|
711
|
+
runId: String(spec?.runId ?? ""),
|
|
712
|
+
jobId: String(spec?.jobId ?? ""),
|
|
713
|
+
attemptId: null,
|
|
714
|
+
pid: null,
|
|
715
|
+
exitCode: null,
|
|
716
|
+
envKeys: Object.keys(env).sort(),
|
|
717
|
+
startedAt: null,
|
|
718
|
+
finishedAt: this.now(),
|
|
719
|
+
...fields,
|
|
720
|
+
};
|
|
721
|
+
}
|
|
722
|
+
refuse(spec, code, detail) {
|
|
723
|
+
const result = this.result(spec, { kind: "refused", code, detail });
|
|
724
|
+
try {
|
|
725
|
+
return { kind: "refused", result: this.opts.results.append(result) };
|
|
726
|
+
}
|
|
727
|
+
catch (err) {
|
|
728
|
+
return { kind: "refused", result: { ...result, detail: `${detail}; result not recorded: ${storeCode(err) ?? message(err)}` } };
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* Report the ledger outcome (or return the attempt), then append the one
|
|
733
|
+
* terminal result. A ledger or result-log failure is reported, never thrown.
|
|
734
|
+
* A failed return is recorded as failed RETURN_NOT_RECORDED and the attempt
|
|
735
|
+
* stays open in the ledger.
|
|
736
|
+
*/
|
|
737
|
+
finish(result, returning = false) {
|
|
738
|
+
let final = result;
|
|
739
|
+
if (result.attemptId !== null) {
|
|
740
|
+
if (returning) {
|
|
741
|
+
try {
|
|
742
|
+
this.opts.access.returnAttempt(this.opts.identity, result.attemptId);
|
|
743
|
+
}
|
|
744
|
+
catch (err) {
|
|
745
|
+
final = { ...result, kind: "failed", code: "RETURN_NOT_RECORDED", detail: `${result.detail}; ledger return not recorded: ${storeCode(err) ?? message(err)}` };
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
else {
|
|
749
|
+
try {
|
|
750
|
+
this.opts.access.recordOutcome(this.opts.identity, result.attemptId, result.kind === "succeeded" ? "passed" : "failed");
|
|
751
|
+
}
|
|
752
|
+
catch (err) {
|
|
753
|
+
final = { ...result, detail: `${result.detail}; ledger outcome not recorded: ${storeCode(err) ?? message(err)}` };
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
try {
|
|
758
|
+
return this.opts.results.append(final);
|
|
759
|
+
}
|
|
760
|
+
catch (err) {
|
|
761
|
+
return { ...final, kind: "failed", code: "RESULT_NOT_RECORDED", detail: `${final.kind} ${final.code}: ${final.detail}; result not recorded: ${storeCode(err) ?? message(err)}` };
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
async start(spec) {
|
|
765
|
+
if (this.opted)
|
|
766
|
+
return this.refuse(spec, "OPTED_OUT", "the worker has opted out and admits no new work");
|
|
767
|
+
const valid = validateMacSpec(spec);
|
|
768
|
+
if (!valid.ok)
|
|
769
|
+
return this.refuse(spec, valid.code, valid.detail);
|
|
770
|
+
try {
|
|
771
|
+
const { run, jobs } = this.opts.access.readRun(this.opts.identity, spec.runId);
|
|
772
|
+
if (run.tenantId !== spec.tenantId)
|
|
773
|
+
return this.refuse(spec, "INVALID_SPEC", `run ${spec.runId} belongs to another tenant`);
|
|
774
|
+
if (!jobs.some((j) => j.job.jobId === spec.jobId))
|
|
775
|
+
return this.refuse(spec, "UNKNOWN_JOB", `run ${spec.runId} has no job ${spec.jobId}`);
|
|
776
|
+
}
|
|
777
|
+
catch (err) {
|
|
778
|
+
return this.refuse(spec, storeCode(err) ?? "UNKNOWN_JOB", message(err));
|
|
779
|
+
}
|
|
780
|
+
const match = matchMacCapabilities(this.opts.profile, spec.requires);
|
|
781
|
+
if (!match.ok)
|
|
782
|
+
return this.refuse(spec, match.code, match.detail);
|
|
783
|
+
for (const ref of spec.inputs) {
|
|
784
|
+
const problem = this.opts.inputs.verify(ref);
|
|
785
|
+
if (problem)
|
|
786
|
+
return this.refuse(spec, problem, problem === "INPUT_MISSING" ? `input ${ref.name} is not admitted` : `input ${ref.name} changed after admission`);
|
|
787
|
+
}
|
|
788
|
+
try {
|
|
789
|
+
this.opts.launcher.prepare?.();
|
|
790
|
+
}
|
|
791
|
+
catch (err) {
|
|
792
|
+
return err instanceof WorkerRefusal ? this.refuse(spec, err.code, err.detail) : this.refuse(spec, "CONTAINMENT_UNAVAILABLE", message(err));
|
|
793
|
+
}
|
|
794
|
+
// Everything from here to the launch is synchronous, so an opt-out cannot
|
|
795
|
+
// land between this check and the claim.
|
|
796
|
+
if (this.opted)
|
|
797
|
+
return this.refuse(spec, "OPTED_OUT", "the worker has opted out and admits no new work");
|
|
798
|
+
let attemptId;
|
|
799
|
+
try {
|
|
800
|
+
attemptId = this.opts.access.claim(this.opts.identity, spec.jobId).attempt.attemptId;
|
|
801
|
+
}
|
|
802
|
+
catch (err) {
|
|
803
|
+
return this.refuse(spec, storeCode(err) ?? "CLAIM_FAILED", message(err));
|
|
804
|
+
}
|
|
805
|
+
const attemptDir = join(this.opts.workDir, attemptId);
|
|
806
|
+
const logPath = join(attemptDir, "output.log");
|
|
807
|
+
try {
|
|
808
|
+
mkdirSync(join(attemptDir, "inputs"), { recursive: true });
|
|
809
|
+
for (const ref of spec.inputs)
|
|
810
|
+
this.opts.inputs.materialize(ref, join(attemptDir, "inputs"));
|
|
811
|
+
}
|
|
812
|
+
catch (err) {
|
|
813
|
+
const code = err instanceof WorkerRefusal ? err.code : "INPUT_FAILED";
|
|
814
|
+
return { kind: "failed", result: this.finish(this.result(spec, { kind: "failed", code, detail: message(err), attemptId })) };
|
|
815
|
+
}
|
|
816
|
+
const startedAt = this.now();
|
|
817
|
+
let proc;
|
|
818
|
+
try {
|
|
819
|
+
const req = {
|
|
820
|
+
file: spec.command.file,
|
|
821
|
+
args: [...spec.command.args],
|
|
822
|
+
cwd: attemptDir,
|
|
823
|
+
env: jobEnv(spec),
|
|
824
|
+
logPath,
|
|
825
|
+
limits: { ...spec.limits },
|
|
826
|
+
readPaths: [...(spec.readPaths ?? [])],
|
|
827
|
+
network: spec.network === true,
|
|
828
|
+
protectedPaths: [...(this.opts.protectedPaths ?? []), this.opts.workDir],
|
|
829
|
+
};
|
|
830
|
+
proc = this.opts.launcher.launch(req);
|
|
831
|
+
}
|
|
832
|
+
catch (err) {
|
|
833
|
+
const code = err instanceof WorkerRefusal ? err.code : "SPAWN_FAILED";
|
|
834
|
+
return { kind: "failed", result: this.finish(this.result(spec, { kind: "failed", code, detail: message(err), attemptId, startedAt })) };
|
|
835
|
+
}
|
|
836
|
+
let rootPid = null;
|
|
837
|
+
const entry = { interruptible: spec.interruptible === true, proc, result: undefined, returning: false, cancelRequested: false };
|
|
838
|
+
entry.result = proc.done
|
|
839
|
+
.then((outcome) => {
|
|
840
|
+
const mapped = this.mapOutcome(outcome);
|
|
841
|
+
// Only a tree the helper reports as cancelled goes back to the ledger; a job that exited on its own is its exit.
|
|
842
|
+
if (entry.returning && outcome.reason === "cancelled") {
|
|
843
|
+
const fields = { kind: "cancelled", code: "RETURNED", detail: "returned on opt-out; the contained tree was terminated", exitCode: mapped.exitCode };
|
|
844
|
+
return this.finish(this.result(spec, { ...fields, attemptId, pid: rootPid, startedAt }), true);
|
|
845
|
+
}
|
|
846
|
+
return this.finish(this.result(spec, { ...mapped, attemptId, pid: rootPid, startedAt }));
|
|
847
|
+
}, (err) => this.finish(this.result(spec, { kind: "failed", code: "SUPERVISOR_LOST", detail: message(err), attemptId, pid: rootPid, startedAt })))
|
|
848
|
+
.finally(() => this.active.delete(attemptId));
|
|
849
|
+
this.active.set(attemptId, entry);
|
|
850
|
+
const pid = await proc.ready;
|
|
851
|
+
if (pid <= 0)
|
|
852
|
+
return { kind: "failed", result: await entry.result };
|
|
853
|
+
rootPid = pid;
|
|
854
|
+
const cancel = () => {
|
|
855
|
+
if (entry.cancelRequested)
|
|
856
|
+
return;
|
|
857
|
+
entry.cancelRequested = true;
|
|
858
|
+
proc.cancel();
|
|
859
|
+
};
|
|
860
|
+
return { kind: "started", attemptId, pid, process: proc, logPath, cancel, result: entry.result };
|
|
861
|
+
}
|
|
862
|
+
/**
|
|
863
|
+
* Stop admitting work. Interruptible active jobs are killed with their whole
|
|
864
|
+
* tree and returned to the ledger; the rest run to completion. Resolves when
|
|
865
|
+
* every job active at the call has its terminal result.
|
|
866
|
+
*/
|
|
867
|
+
async optOut() {
|
|
868
|
+
this.opted = true;
|
|
869
|
+
const jobs = [...this.active.values()];
|
|
870
|
+
for (const j of jobs) {
|
|
871
|
+
if (!j.interruptible || j.cancelRequested)
|
|
872
|
+
continue;
|
|
873
|
+
j.returning = true;
|
|
874
|
+
j.cancelRequested = true;
|
|
875
|
+
j.proc.cancel();
|
|
876
|
+
}
|
|
877
|
+
const results = await Promise.all(jobs.map((j) => j.result));
|
|
878
|
+
return { returned: results.filter((r) => r.code === "RETURNED"), completed: results.filter((r) => r.code !== "RETURNED") };
|
|
879
|
+
}
|
|
880
|
+
mapOutcome(o) {
|
|
881
|
+
switch (o.reason) {
|
|
882
|
+
case "cancelled":
|
|
883
|
+
return { kind: "cancelled", code: "CANCELLED", detail: "cancelled; the contained tree was terminated", exitCode: o.exitCode ?? null };
|
|
884
|
+
case "limit": {
|
|
885
|
+
const code = o.limit === "memory" ? "MEMORY_LIMIT" : o.limit === "processes" ? "PROCESS_LIMIT" : "CPU_LIMIT";
|
|
886
|
+
return { kind: "limit_exceeded", code, detail: `${o.limit} limit exceeded; the contained tree was terminated`, exitCode: o.exitCode ?? null };
|
|
887
|
+
}
|
|
888
|
+
case "exited":
|
|
889
|
+
return o.exitCode === 0
|
|
890
|
+
? { kind: "succeeded", code: "EXITED", detail: "exited 0", exitCode: 0 }
|
|
891
|
+
: { kind: "failed", code: "EXIT_NONZERO", detail: `exited ${o.exitCode}`, exitCode: o.exitCode };
|
|
892
|
+
case "kill_incomplete":
|
|
893
|
+
return { kind: "failed", code: "KILL_INCOMPLETE", detail: `${o.detail}; the job directory is left for the next sweep`, exitCode: null };
|
|
894
|
+
case "supervisor_lost":
|
|
895
|
+
return { kind: "failed", code: "SUPERVISOR_LOST", detail: o.detail, exitCode: null };
|
|
896
|
+
case "spawn_failed":
|
|
897
|
+
return { kind: "failed", code: "SPAWN_FAILED", detail: o.detail, exitCode: null };
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
//# sourceMappingURL=macos.js.map
|