@indigoai-us/hq-cli 5.345.214 → 5.345.215

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