@indigoai-us/hq-cli 5.345.215-beta.0 → 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 (124) hide show
  1. package/CHANGELOG.md +65 -1
  2. package/assets/scaffold/core/scripts/hq-delegate-verify.sh +5 -2
  3. package/dist/command-catalog.generated.d.ts +46 -6
  4. package/dist/command-catalog.generated.js +53 -6
  5. package/dist/commands/bot.js +64 -6
  6. package/dist/commands/capacity.d.ts +4 -1
  7. package/dist/commands/capacity.js +46 -10
  8. package/dist/commands/cloud.js +1 -1
  9. package/dist/commands/core-delegate-w1b.js +15 -1
  10. package/dist/commands/core-policy.js +67 -8
  11. package/dist/commands/daemon.js +5 -0
  12. package/dist/commands/files-browse.d.ts +11 -4
  13. package/dist/commands/files-browse.js +21 -4
  14. package/dist/commands/files.d.ts +1 -1
  15. package/dist/commands/files.js +25 -11
  16. package/dist/commands/integrations-auth-rules.d.ts +27 -0
  17. package/dist/commands/integrations-auth-rules.js +79 -0
  18. package/dist/commands/integrations-import.js +124 -12
  19. package/dist/commands/lanes.js +2 -2
  20. package/dist/commands/mesh.d.ts +2 -0
  21. package/dist/commands/mesh.js +60 -35
  22. package/dist/commands/sync-held.js +5 -2
  23. package/dist/lazy-commands.js +3 -5
  24. package/dist/lib/bot/fleet-cron.d.ts +8 -0
  25. package/dist/lib/bot/fleet-cron.js +35 -3
  26. package/dist/lib/bot/fleet-daemon.d.ts +46 -0
  27. package/dist/lib/bot/fleet-daemon.js +99 -1
  28. package/dist/lib/bot/probe.js +7 -1
  29. package/dist/lib/bot/run.js +20 -1
  30. package/dist/lib/bot/runtime/codex.js +1 -1
  31. package/dist/lib/bot/runtime/grok-acp.d.ts +5 -1
  32. package/dist/lib/bot/runtime/grok-acp.js +6 -3
  33. package/dist/lib/bot/runtime/index.js +19 -9
  34. package/dist/lib/bot/runtime/messages-stream.js +2 -2
  35. package/dist/lib/bot/runtime/types.d.ts +15 -0
  36. package/dist/lib/bot/runtime/types.js +9 -0
  37. package/dist/lib/bot/runtime-failure.d.ts +23 -0
  38. package/dist/lib/bot/runtime-failure.js +43 -1
  39. package/dist/lib/capacity/accounts.d.ts +8 -0
  40. package/dist/lib/capacity/accounts.js +19 -0
  41. package/dist/lib/capacity/available.d.ts +154 -0
  42. package/dist/lib/capacity/available.js +905 -0
  43. package/dist/lib/capacity/codex-availability.d.ts +14 -1
  44. package/dist/lib/capacity/codex-availability.js +26 -1
  45. package/dist/lib/capacity/collectors/claude-oauth.d.ts +29 -2
  46. package/dist/lib/capacity/collectors/claude-oauth.js +104 -7
  47. package/dist/lib/capacity/collectors/codex.js +10 -7
  48. package/dist/lib/capacity/ledger.d.ts +37 -1
  49. package/dist/lib/capacity/ledger.js +207 -30
  50. package/dist/lib/capacity/project.d.ts +26 -0
  51. package/dist/lib/capacity/project.js +137 -8
  52. package/dist/lib/capacity/refusal-rows.d.ts +31 -0
  53. package/dist/lib/capacity/refusal-rows.js +61 -0
  54. package/dist/lib/capacity/refusal.d.ts +53 -2
  55. package/dist/lib/capacity/refusal.js +284 -65
  56. package/dist/lib/capacity/route.js +46 -11
  57. package/dist/lib/capacity/widget.d.ts +12 -1
  58. package/dist/lib/capacity/widget.js +91 -3
  59. package/dist/lib/daemon/resolver.d.ts +2 -0
  60. package/dist/lib/daemon/resolver.js +3 -0
  61. package/dist/lib/daemon/run.d.ts +9 -0
  62. package/dist/lib/daemon/run.js +54 -1
  63. package/dist/lib/daemon/server.d.ts +2 -0
  64. package/dist/lib/daemon/server.js +10 -1
  65. package/dist/lib/daemon/tcc-eperm.d.ts +153 -0
  66. package/dist/lib/daemon/tcc-eperm.js +310 -0
  67. package/dist/lib/delivery/admission.d.ts +86 -0
  68. package/dist/lib/delivery/admission.js +148 -0
  69. package/dist/lib/delivery/artifacts.d.ts +7 -1
  70. package/dist/lib/delivery/artifacts.js +29 -10
  71. package/dist/lib/delivery/attempt-id.d.ts +13 -0
  72. package/dist/lib/delivery/attempt-id.js +16 -0
  73. package/dist/lib/delivery/disposable-target.d.ts +42 -0
  74. package/dist/lib/delivery/disposable-target.js +111 -0
  75. package/dist/lib/delivery/effects.d.ts +136 -0
  76. package/dist/lib/delivery/effects.js +541 -0
  77. package/dist/lib/delivery/enrollment.d.ts +21 -17
  78. package/dist/lib/delivery/enrollment.js +83 -5
  79. package/dist/lib/delivery/escalations.d.ts +51 -0
  80. package/dist/lib/delivery/escalations.js +60 -0
  81. package/dist/lib/delivery/lease.d.ts +80 -0
  82. package/dist/lib/delivery/lease.js +134 -0
  83. package/dist/lib/delivery/migrations.d.ts +120 -4
  84. package/dist/lib/delivery/migrations.js +215 -15
  85. package/dist/lib/delivery/mqtt.d.ts +2 -0
  86. package/dist/lib/delivery/mqtt.js +7 -0
  87. package/dist/lib/delivery/reconciler.d.ts +65 -1
  88. package/dist/lib/delivery/reconciler.js +224 -13
  89. package/dist/lib/delivery/rpc/client.d.ts +22 -0
  90. package/dist/lib/delivery/rpc/client.js +159 -0
  91. package/dist/lib/delivery/rpc/port.d.ts +40 -0
  92. package/dist/lib/delivery/rpc/port.js +16 -0
  93. package/dist/lib/delivery/rpc/server.d.ts +30 -0
  94. package/dist/lib/delivery/rpc/server.js +205 -0
  95. package/dist/lib/delivery/rpc/wire.d.ts +85 -0
  96. package/dist/lib/delivery/rpc/wire.js +143 -0
  97. package/dist/lib/delivery/store.d.ts +2 -0
  98. package/dist/lib/delivery/store.js +4 -0
  99. package/dist/lib/delivery/windows-service-install.d.ts +262 -0
  100. package/dist/lib/delivery/windows-service-install.js +892 -0
  101. package/dist/lib/delivery/workers/macos.d.ts +16 -1
  102. package/dist/lib/delivery/workers/macos.js +54 -12
  103. package/dist/lib/delivery/workers/windows-service-live.d.ts +121 -0
  104. package/dist/lib/delivery/workers/windows-service-live.js +711 -0
  105. package/dist/lib/delivery/workers/windows-service-runner.d.ts +33 -0
  106. package/dist/lib/delivery/workers/windows-service-runner.js +82 -0
  107. package/dist/lib/delivery/workers/windows-service.d.ts +140 -0
  108. package/dist/lib/delivery/workers/windows-service.js +584 -0
  109. package/dist/lib/delivery/workers/windows.d.ts +32 -22
  110. package/dist/lib/delivery/workers/windows.js +50 -64
  111. package/dist/lib/hot-channels/adapters/meetings.d.ts +15 -0
  112. package/dist/lib/hot-channels/adapters/meetings.js +36 -3
  113. package/dist/lib/hot-channels/signals-pass.d.ts +10 -0
  114. package/dist/lib/hot-channels/signals-pass.js +71 -2
  115. package/dist/lib/hot-channels/signals-redo.js +10 -2
  116. package/dist/lib/lanes/watcher.js +35 -0
  117. package/dist/lib/signals/steps/extract.js +40 -4
  118. package/dist/schemas/hq-available-ai.v1.schema.json +76 -0
  119. package/dist/utils/catalog-runtime-paths.d.ts +34 -0
  120. package/dist/utils/catalog-runtime-paths.js +53 -0
  121. package/dist/utils/files-browse-acl.js +1 -1
  122. package/package.json +7 -7
  123. package/dist/lib/delivery/workers/windows-boundary.d.ts +0 -453
  124. package/dist/lib/delivery/workers/windows-boundary.js +0 -693
@@ -0,0 +1,584 @@
1
+ /**
2
+ * Windows jobs through an existing service host (US-006, proposal 040).
3
+ *
4
+ * The worker's own Node runner runs as a manual-start Windows service under
5
+ * its virtual account, hosted by an established service wrapper. There is no
6
+ * logon, impersonation, token or credential code anywhere in this design: the
7
+ * job runs as the service's own identity, inside a Job Object.
8
+ *
9
+ * Three parts:
10
+ * - jobHelperLauncher: runs one job in a Job Object through the prebuilt
11
+ * helper (the reviewed HELPER_SOURCE, compiled once at install time by
12
+ * an Administrator into a protected directory). It checks the helper's
13
+ * pinned sha256 and self test and never compiles anything.
14
+ * - runSpoolService: the service loop. It reads job requests from the
15
+ * spool queue, runs each once, reports events, honours cancel files and
16
+ * writes a heartbeat.
17
+ * - SpoolTransport and serviceWindowsLauncher: the CLI side. The launcher
18
+ * refuses with CONTAINMENT_UNAVAILABLE before the claim unless the host is
19
+ * Windows and the runner's heartbeat is fresh, names the expected service
20
+ * and reports the expected manifest digest.
21
+ *
22
+ * Spool layout under the pilot root (ACLs are set by the installer):
23
+ * queue/<id>.json request, written by the CLI (Administrators only)
24
+ * control/<id>.cancel cancel marker, written by the CLI
25
+ * state/heartbeat.json runner liveness
26
+ * state/<id>.events one JSON object per line, appended by the runner
27
+ * Only node built-ins are imported at runtime.
28
+ */
29
+ import { spawn as nodeSpawn, execFileSync } from "node:child_process";
30
+ import { createHash, randomBytes } from "node:crypto";
31
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
32
+ import { basename, dirname, join } from "node:path";
33
+ import { helperOutcome, quoteWindowsArg, WorkerRefusal } from "./windows.js";
34
+ export const SPOOL_VERSION = "hq-delivery.windows-spool.v1";
35
+ /** The proposal 040 pilot names. */
36
+ export const PILOT040 = {
37
+ service: "HQNDUS006040",
38
+ account: "NT SERVICE\\HQNDUS006040",
39
+ root: "C:\\ProgramData\\HQNativeDelivery-US006-040",
40
+ };
41
+ export const SPOOL_DIRS = ["queue", "control", "state", "logs", "runs"];
42
+ const REQUEST_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
43
+ function sha256(bytes) {
44
+ return createHash("sha256").update(bytes).digest("hex");
45
+ }
46
+ function unavailable(detail, reason) {
47
+ return new WorkerRefusal("CONTAINMENT_UNAVAILABLE", `${detail}: ${reason}`);
48
+ }
49
+ function firstLine(err) {
50
+ return (err instanceof Error ? err.message : String(err)).split("\n")[0];
51
+ }
52
+ /**
53
+ * The virtual account SID Windows derives for a service name:
54
+ * S-1-5-80- followed by the SHA-1 of the upper-cased UTF-16LE name, read as
55
+ * five little-endian 32-bit values.
56
+ */
57
+ export function serviceSidFor(name) {
58
+ const digest = createHash("sha1").update(Buffer.from(name.toUpperCase(), "utf16le")).digest();
59
+ const parts = [];
60
+ for (let i = 0; i < 20; i += 4)
61
+ parts.push(digest.readUInt32LE(i));
62
+ return `S-1-5-80-${parts.join("-")}`;
63
+ }
64
+ /**
65
+ * Runs each job in its own Job Object through the installed helper; see
66
+ * the helper source for the limits and the line protocol. prepare checks
67
+ * the platform, the helper's digest and its self test, and refuses with
68
+ * CONTAINMENT_UNAVAILABLE on any failure. Nothing is compiled or written.
69
+ */
70
+ export function jobHelperLauncher(opts) {
71
+ const platform = opts.platform ?? process.platform;
72
+ const root = opts.systemRoot ?? process.env.SystemRoot ?? process.env.SYSTEMROOT ?? "C:\\Windows";
73
+ const helperEnv = { SystemRoot: root, windir: root };
74
+ let checked = false;
75
+ const check = () => {
76
+ if (platform !== "win32")
77
+ throw unavailable("BOUNDARY_SERVICE_UNAVAILABLE", `native Windows containment needs Windows; this host is ${platform}`);
78
+ if (checked)
79
+ return;
80
+ if (!existsSync(opts.helperExe))
81
+ throw unavailable("BOUNDARY_MANIFEST", `no job helper at ${opts.helperExe}`);
82
+ const actual = sha256(readFileSync(opts.helperExe));
83
+ if (actual !== opts.sha256)
84
+ throw unavailable("BOUNDARY_MANIFEST", `job helper sha256 ${actual} does not match the manifest`);
85
+ let out;
86
+ try {
87
+ out = execFileSync(opts.helperExe, ["--selftest"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], windowsHide: true, timeout: 30_000, env: helperEnv });
88
+ }
89
+ catch (err) {
90
+ throw unavailable("BOUNDARY_RUN_SETUP", `job helper self test failed: ${firstLine(err)}`);
91
+ }
92
+ if (out.trim() !== "selftest ok")
93
+ throw unavailable("BOUNDARY_RUN_SETUP", `job helper self test said ${out.trim() || "nothing"}`);
94
+ checked = true;
95
+ };
96
+ return {
97
+ prepare: () => check(),
98
+ launch(req) {
99
+ check();
100
+ const child = nodeSpawn(opts.helperExe, [], { stdio: ["pipe", "pipe", "pipe"], windowsHide: true, env: helperEnv });
101
+ const seen = [];
102
+ let rootPid = -1;
103
+ let exitLine;
104
+ let errorLine;
105
+ let stderr = "";
106
+ let spawnError;
107
+ let cancelled = false;
108
+ let readyResolve;
109
+ const ready = new Promise((r) => (readyResolve = r));
110
+ child.stdin.on("error", () => { });
111
+ const field = (key, value) => `${key}\t${Buffer.from(value, "utf8").toString("base64")}\n`;
112
+ let input = field("app", req.file) + field("cmd", [req.file, ...req.args].map(quoteWindowsArg).join(" ")) + field("cwd", req.cwd) + field("log", req.logPath);
113
+ for (const [k, v] of Object.entries(req.env))
114
+ input += field("env", `${k}=${v}`);
115
+ input += field("mem", String(req.limits.memoryBytes)) + field("procs", String(req.limits.maxProcesses)) + field("cpu", String(req.limits.cpuTimeMs)) + "end\n";
116
+ child.stdin.write(input);
117
+ let buf = "";
118
+ child.stdout.setEncoding("utf8");
119
+ child.stdout.on("data", (chunk) => {
120
+ buf += chunk;
121
+ let nl;
122
+ while ((nl = buf.indexOf("\n")) >= 0) {
123
+ const line = buf.slice(0, nl).trim();
124
+ buf = buf.slice(nl + 1);
125
+ const [event, a] = line.split(" ");
126
+ if (event === "started") {
127
+ rootPid = Number(a);
128
+ readyResolve(rootPid);
129
+ }
130
+ else if (event === "process") {
131
+ const pid = Number(a);
132
+ if (!seen.includes(pid))
133
+ seen.push(pid);
134
+ }
135
+ else if (event === "exit")
136
+ exitLine = line;
137
+ else if (event === "error")
138
+ errorLine = line;
139
+ }
140
+ });
141
+ child.stderr.setEncoding("utf8");
142
+ child.stderr.on("data", (chunk) => {
143
+ if (stderr.length < 4096)
144
+ stderr += chunk;
145
+ });
146
+ const done = new Promise((resolve) => {
147
+ child.on("error", (err) => {
148
+ spawnError = err.message;
149
+ });
150
+ child.on("close", (code) => {
151
+ readyResolve(-1);
152
+ resolve(helperOutcome({ exitLine, errorLine, rootPid, code, spawnError, stderr }));
153
+ });
154
+ });
155
+ return {
156
+ get pid() {
157
+ return rootPid > 0 ? rootPid : (child.pid ?? -1);
158
+ },
159
+ supervisorPid: child.pid ?? null,
160
+ ready,
161
+ processes: () => [...seen],
162
+ cancel: () => {
163
+ if (cancelled)
164
+ return;
165
+ cancelled = true;
166
+ child.stdin.end("cancel\n");
167
+ },
168
+ done,
169
+ };
170
+ },
171
+ };
172
+ }
173
+ export function spoolPaths(root) {
174
+ return {
175
+ queue: join(root, "queue"),
176
+ control: join(root, "control"),
177
+ state: join(root, "state"),
178
+ heartbeat: join(root, "state", "heartbeat.json"),
179
+ request: (id) => join(root, "queue", `${id}.json`),
180
+ cancel: (id) => join(root, "control", `${id}.cancel`),
181
+ events: (id) => join(root, "state", `${id}.events`),
182
+ };
183
+ }
184
+ /** sha256 of the manifest file bytes, the identity the CLI and runner agree on. */
185
+ export function manifestDigest(manifestPath) {
186
+ return sha256(readFileSync(manifestPath));
187
+ }
188
+ /**
189
+ * Windows refuses to replace a file another process has open (the CLI reading
190
+ * the heartbeat) with EPERM, EACCES or EBUSY. On Beaker a writer replacing a
191
+ * file while one reader read it in a loop failed 17730 of 26871 renames. Those
192
+ * codes are retried on win32 only, after 5, 10, 20 and 40 ms (75 ms in all, under
193
+ * the runner's 200 ms beat). writeAtomic is synchronous, so the waits block with
194
+ * Atomics.wait rather than yielding to the event loop.
195
+ */
196
+ const WIN32_RENAME_BACKOFF_MS = [5, 10, 20, 40];
197
+ const WIN32_RENAME_RETRY = new Set(["EPERM", "EACCES", "EBUSY"]);
198
+ function sleepSync(ms) {
199
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
200
+ }
201
+ /**
202
+ * Replace `path` with `text` through a temp file and a rename. A final failure
203
+ * throws as before; the temp file is removed first, on every OS, so a failed
204
+ * write leaves nothing in the spool. Exported for its tests.
205
+ */
206
+ export function writeAtomic(path, text, platform = process.platform) {
207
+ const tmp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
208
+ writeFileSync(tmp, text);
209
+ const waits = platform === "win32" ? WIN32_RENAME_BACKOFF_MS : [];
210
+ for (let attempt = 0;; attempt++) {
211
+ try {
212
+ renameSync(tmp, path);
213
+ return;
214
+ }
215
+ catch (err) {
216
+ const code = err.code ?? "";
217
+ if (attempt < waits.length && WIN32_RENAME_RETRY.has(code)) {
218
+ sleepSync(waits[attempt]);
219
+ continue;
220
+ }
221
+ try {
222
+ rmSync(tmp, { force: true });
223
+ }
224
+ catch {
225
+ // The temp file may be held too (antivirus, a reader); the rename error is the one to report.
226
+ }
227
+ throw err;
228
+ }
229
+ }
230
+ }
231
+ function readJson(path) {
232
+ try {
233
+ return JSON.parse(readFileSync(path, "utf8"));
234
+ }
235
+ catch {
236
+ return undefined;
237
+ }
238
+ }
239
+ function readEvents(path) {
240
+ if (!existsSync(path))
241
+ return [];
242
+ const out = [];
243
+ for (const line of readFileSync(path, "utf8").split("\n")) {
244
+ if (line.trim() === "")
245
+ continue;
246
+ try {
247
+ out.push(JSON.parse(line));
248
+ }
249
+ catch {
250
+ // A torn last line is read again on the next poll.
251
+ }
252
+ }
253
+ return out;
254
+ }
255
+ function isRequest(x, id) {
256
+ const r = x;
257
+ return (typeof r === "object" &&
258
+ r !== null &&
259
+ r.schemaVersion === SPOOL_VERSION &&
260
+ r.id === id &&
261
+ typeof r.run?.tenantId === "string" &&
262
+ typeof r.run?.runId === "string" &&
263
+ typeof r.run?.jobId === "string" &&
264
+ typeof r.req?.file === "string" &&
265
+ Array.isArray(r.req?.args) &&
266
+ typeof r.req?.cwd === "string" &&
267
+ typeof r.req?.logPath === "string" &&
268
+ typeof r.req?.env === "object" &&
269
+ typeof r.req?.limits?.memoryBytes === "number" &&
270
+ typeof r.req?.limits?.maxProcesses === "number" &&
271
+ typeof r.req?.limits?.cpuTimeMs === "number");
272
+ }
273
+ function envFileName(id) {
274
+ return ".hq-env-" + id + ".json";
275
+ }
276
+ /**
277
+ * Read a request's env file once, check it, and delete it. The file must sit
278
+ * directly in the request's cwd under its expected name. Returns the env or a
279
+ * failure detail.
280
+ */
281
+ function takeEnv(r, id) {
282
+ const ref = r.envRef;
283
+ if (typeof ref.path !== "string" || dirname(ref.path) !== r.req.cwd || basename(ref.path) !== envFileName(id))
284
+ return "env file is not the request's own";
285
+ let bytes;
286
+ try {
287
+ bytes = readFileSync(ref.path);
288
+ }
289
+ catch {
290
+ return "env file is missing";
291
+ }
292
+ try {
293
+ rmSync(ref.path, { force: true });
294
+ }
295
+ catch {
296
+ // A leftover file holds only this job's own env.
297
+ }
298
+ if (sha256(bytes) !== ref.sha256)
299
+ return "env file does not match its queued sha256";
300
+ let env;
301
+ try {
302
+ env = JSON.parse(bytes.toString("utf8"));
303
+ }
304
+ catch {
305
+ return "env file is not JSON";
306
+ }
307
+ if (typeof env !== "object" || env === null || Array.isArray(env) || Object.values(env).some((v) => typeof v !== "string"))
308
+ return "env file is not a string map";
309
+ return env;
310
+ }
311
+ /**
312
+ * Run the spool until the signal aborts. Each queued request runs once: a
313
+ * request that already has an events file is never started again. A request
314
+ * that was accepted by an earlier runner but has no done event is closed as
315
+ * supervisor_lost, because that runner's helper and Job Object are gone.
316
+ * On abort every running job is cancelled and awaited before the promise
317
+ * resolves.
318
+ */
319
+ export async function runSpoolService(opts) {
320
+ const p = spoolPaths(opts.root);
321
+ const now = opts.now ?? (() => new Date());
322
+ const pollMs = opts.pollMs ?? 200;
323
+ const startedAt = now().toISOString();
324
+ const running = new Map();
325
+ const finished = [];
326
+ const append = (id, ev) => appendFileSync(p.events(id), JSON.stringify(ev) + "\n");
327
+ const beat = (stopping = false) => {
328
+ const hb = { schemaVersion: SPOOL_VERSION, service: opts.service, pid: process.pid, startedAt, at: now().toISOString(), manifestDigest: opts.manifestDigest };
329
+ if (stopping)
330
+ hb.stopping = true;
331
+ writeAtomic(p.heartbeat, JSON.stringify(hb));
332
+ };
333
+ for (const name of readdirSync(p.state)) {
334
+ if (!name.endsWith(".events"))
335
+ continue;
336
+ const id = name.slice(0, -".events".length);
337
+ const events = readEvents(p.events(id));
338
+ if (!events.some((e) => e.e === "done"))
339
+ append(id, { e: "done", outcome: { reason: "supervisor_lost", detail: "the runner restarted while the job was running" }, at: now().toISOString() });
340
+ }
341
+ const startOne = (id) => {
342
+ const raw = readJson(p.request(id));
343
+ append(id, { e: "accepted", at: now().toISOString() });
344
+ if (!isRequest(raw, id)) {
345
+ append(id, { e: "done", outcome: { reason: "spawn_failed", detail: "malformed spool request" }, at: now().toISOString() });
346
+ return;
347
+ }
348
+ let req = raw.req;
349
+ if (raw.envRef) {
350
+ const env = takeEnv(raw, id);
351
+ if (typeof env === "string") {
352
+ append(id, { e: "done", outcome: { reason: "spawn_failed", detail: env }, at: now().toISOString() });
353
+ return;
354
+ }
355
+ req = { ...raw.req, env };
356
+ }
357
+ let proc;
358
+ try {
359
+ opts.launcher.prepare?.(raw.run);
360
+ proc = opts.launcher.launch(req, raw.run);
361
+ }
362
+ catch (err) {
363
+ append(id, { e: "done", outcome: { reason: "spawn_failed", detail: err instanceof WorkerRefusal ? `${err.code}: ${err.detail}` : firstLine(err) }, at: now().toISOString() });
364
+ return;
365
+ }
366
+ const reported = new Set();
367
+ const report = () => {
368
+ for (const pid of proc.processes()) {
369
+ if (reported.has(pid))
370
+ continue;
371
+ reported.add(pid);
372
+ append(id, { e: "process", pid });
373
+ }
374
+ };
375
+ running.set(id, { proc, report });
376
+ void proc.ready.then((pid) => {
377
+ if (pid > 0)
378
+ append(id, { e: "started", pid, supervisorPid: proc.supervisorPid, at: now().toISOString() });
379
+ });
380
+ finished.push(proc.done.then((outcome) => {
381
+ report();
382
+ running.delete(id);
383
+ append(id, { e: "done", outcome, at: now().toISOString() });
384
+ }, (err) => {
385
+ running.delete(id);
386
+ append(id, { e: "done", outcome: { reason: "supervisor_lost", detail: firstLine(err) }, at: now().toISOString() });
387
+ }));
388
+ };
389
+ const tick = () => {
390
+ beat();
391
+ for (const name of readdirSync(p.queue).sort()) {
392
+ if (!name.endsWith(".json"))
393
+ continue;
394
+ const id = name.slice(0, -".json".length);
395
+ if (!REQUEST_ID.test(id) || existsSync(p.events(id)))
396
+ continue;
397
+ startOne(id);
398
+ }
399
+ for (const [id, { proc, report }] of running) {
400
+ report();
401
+ if (existsSync(p.cancel(id)))
402
+ proc.cancel();
403
+ }
404
+ };
405
+ await new Promise((resolve) => {
406
+ const stop = () => {
407
+ clearInterval(timer);
408
+ resolve();
409
+ };
410
+ const timer = setInterval(() => {
411
+ try {
412
+ tick();
413
+ }
414
+ catch {
415
+ // A transient filesystem error is retried on the next tick; a
416
+ // persistent one stops the heartbeat, which the CLI reports.
417
+ }
418
+ }, pollMs);
419
+ try {
420
+ tick();
421
+ }
422
+ catch {
423
+ // as above
424
+ }
425
+ if (opts.signal?.aborted)
426
+ stop();
427
+ opts.signal?.addEventListener("abort", stop, { once: true });
428
+ });
429
+ for (const { proc } of running.values())
430
+ proc.cancel();
431
+ await Promise.all(finished);
432
+ try {
433
+ beat(true);
434
+ }
435
+ catch {
436
+ // The spool is gone; there is nobody left to tell that the runner stopped.
437
+ }
438
+ }
439
+ export class SpoolTransport {
440
+ opts;
441
+ p;
442
+ now;
443
+ maxAge;
444
+ pollMs;
445
+ constructor(opts) {
446
+ this.opts = opts;
447
+ this.p = spoolPaths(opts.root);
448
+ this.now = opts.now ?? (() => new Date());
449
+ this.maxAge = opts.maxHeartbeatAgeMs ?? 10_000;
450
+ this.pollMs = opts.pollMs ?? 100;
451
+ }
452
+ /** The current heartbeat when it is live and for this installation; throws a WorkerRefusal otherwise. */
453
+ check() {
454
+ const hb = readJson(this.p.heartbeat);
455
+ if (!hb || hb.schemaVersion !== SPOOL_VERSION)
456
+ throw unavailable("BOUNDARY_SERVICE_UNAVAILABLE", "the runner has no heartbeat");
457
+ if (hb.stopping)
458
+ throw unavailable("BOUNDARY_SERVICE_UNAVAILABLE", "the runner is stopped");
459
+ const age = this.now().getTime() - Date.parse(hb.at);
460
+ if (!(age <= this.maxAge))
461
+ throw unavailable("BOUNDARY_SERVICE_UNAVAILABLE", `the runner heartbeat is ${Number.isFinite(age) ? `${age} ms` : "unreadably"} old`);
462
+ if (hb.service !== this.opts.service)
463
+ throw unavailable("BOUNDARY_SERVICE_IDENTITY", `the runner is ${hb.service}, expected ${this.opts.service}`);
464
+ if (hb.manifestDigest !== this.opts.manifestDigest)
465
+ throw unavailable("BOUNDARY_MANIFEST", "the runner's manifest digest does not match");
466
+ return hb;
467
+ }
468
+ submit(req, run) {
469
+ const hb = this.check();
470
+ const id = `${run.jobId.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 80)}-${randomBytes(8).toString("hex")}`;
471
+ // Env values never go into the queue, which every job can read. They go
472
+ // to a file in the request's own cwd that the runner deletes on read.
473
+ const envText = JSON.stringify(req.env);
474
+ const envPath = join(req.cwd, envFileName(id));
475
+ writeAtomic(envPath, envText);
476
+ const request = {
477
+ schemaVersion: SPOOL_VERSION,
478
+ id,
479
+ run: { ...run },
480
+ req: { ...req, env: {} },
481
+ envRef: { path: envPath, sha256: sha256(envText), keys: Object.keys(req.env).sort() },
482
+ submittedAt: this.now().toISOString(),
483
+ };
484
+ mkdirSync(this.p.queue, { recursive: true });
485
+ writeAtomic(this.p.request(id), JSON.stringify(request));
486
+ let rootPid = -1;
487
+ let supervisorPid = null;
488
+ const seen = [];
489
+ let consumed = 0;
490
+ let readyResolve;
491
+ const ready = new Promise((r) => (readyResolve = r));
492
+ let doneResolve;
493
+ const done = new Promise((r) => (doneResolve = r));
494
+ let settled = false;
495
+ const finish = (o) => {
496
+ if (settled)
497
+ return;
498
+ settled = true;
499
+ clearInterval(timer);
500
+ readyResolve(rootPid > 0 ? rootPid : -1);
501
+ doneResolve(o);
502
+ };
503
+ const poll = () => {
504
+ const events = readEvents(this.p.events(id));
505
+ for (const ev of events.slice(consumed)) {
506
+ consumed += 1;
507
+ if (ev.e === "started") {
508
+ rootPid = ev.pid;
509
+ supervisorPid = ev.supervisorPid;
510
+ proc.supervisorPid = supervisorPid;
511
+ readyResolve(rootPid);
512
+ }
513
+ else if (ev.e === "process") {
514
+ if (!seen.includes(ev.pid))
515
+ seen.push(ev.pid);
516
+ }
517
+ else if (ev.e === "done") {
518
+ finish(ev.outcome);
519
+ return;
520
+ }
521
+ }
522
+ const now = readJson(this.p.heartbeat);
523
+ const age = now ? this.now().getTime() - Date.parse(now.at) : Number.NaN;
524
+ if (!now || now.pid !== hb.pid || now.startedAt !== hb.startedAt || now.stopping || !(age <= this.maxAge)) {
525
+ // One last read: the runner may have written done just before stopping.
526
+ const last = readEvents(this.p.events(id)).find((e) => e.e === "done");
527
+ if (last && last.e === "done")
528
+ finish(last.outcome);
529
+ else
530
+ finish({ reason: "supervisor_lost", detail: "the runner stopped or restarted before the job finished" });
531
+ }
532
+ };
533
+ const timer = setInterval(poll, this.pollMs);
534
+ const proc = {
535
+ get pid() {
536
+ return rootPid;
537
+ },
538
+ supervisorPid,
539
+ ready,
540
+ processes: () => [...seen],
541
+ cancel: () => {
542
+ if (settled)
543
+ return;
544
+ mkdirSync(this.p.control, { recursive: true });
545
+ writeFileSync(this.p.cancel(id), "");
546
+ },
547
+ done,
548
+ };
549
+ return proc;
550
+ }
551
+ }
552
+ /**
553
+ * The CLI launcher for the service pilot. prepare refuses with
554
+ * CONTAINMENT_UNAVAILABLE before the claim unless the host is Windows and the
555
+ * runner is live, named and on the expected manifest. There is no other path
556
+ * to a process.
557
+ */
558
+ export function serviceWindowsLauncher(opts) {
559
+ const platform = opts.platform ?? process.platform;
560
+ let admitted;
561
+ const check = () => {
562
+ if (platform !== "win32")
563
+ throw unavailable("BOUNDARY_SERVICE_UNAVAILABLE", `native Windows containment needs Windows; this host is ${platform}`);
564
+ opts.transport.check();
565
+ };
566
+ return {
567
+ prepare(run) {
568
+ admitted = undefined;
569
+ check();
570
+ if (!run)
571
+ throw unavailable("BOUNDARY_RUN_SETUP", "no admitted run");
572
+ admitted = { ...run };
573
+ },
574
+ launch(req, run) {
575
+ const r = run ?? admitted;
576
+ admitted = undefined;
577
+ if (!r)
578
+ throw unavailable("BOUNDARY_RUN_SETUP", "no admitted run");
579
+ check();
580
+ return opts.transport.submit(req, r);
581
+ },
582
+ };
583
+ }
584
+ //# sourceMappingURL=windows-service.js.map
@@ -1,6 +1,6 @@
1
- import type { DeliveryAccess } from "../enrollment.js";
1
+ import type { AdminScope, DeliveryAccess, EnrollmentRequest, IssuedEnrollment } from "../enrollment.js";
2
2
  import type { WorkerIdentity } from "../identity.js";
3
- import { type BoundaryContext, type BoundaryProbe, type BoundaryRun } from "./windows-boundary.js";
3
+ import type { WorkerTrust } from "../migrations.js";
4
4
  export declare const EXECUTION_SPEC_VERSION = "hq-delivery.execution.v1";
5
5
  export declare const WORKER_RESULT_VERSION = "hq-delivery.worker-result.v1";
6
6
  export type Platform = "windows" | "macos" | "linux";
@@ -10,7 +10,29 @@ export interface WorkerProfile {
10
10
  /** Toolchain name -> installed version. */
11
11
  toolchains: Record<string, string>;
12
12
  capabilities: string[];
13
+ /** "untrusted" on Windows: see WINDOWS_TRUST_NOTE. */
14
+ resultTrust?: "untrusted";
13
15
  }
16
+ /**
17
+ * Owner decision 2026-10-28 ("Mark Windows untrusted"). Why Windows results
18
+ * are untrusted, as advertised in the profile and the docs.
19
+ */
20
+ export declare const WINDOWS_TRUST_NOTE = "Windows results are not trusted against a hostile job: under proposal 040 the job runs as the shared runner identity (the service's virtual account), so a job can write its own or another job's events and results. Workers are capped at standard trust and their results are never release-eligible. Closing this needs a separate job account (future work).";
21
+ /** The highest trust a Windows worker may hold. */
22
+ export declare const WINDOWS_MAX_TRUST: WorkerTrust;
23
+ /** Issue an enrollment ticket for a Windows worker. Release trust is refused with WINDOWS_TRUST_CAPPED; nothing is issued. */
24
+ export declare function issueWindowsEnrollment(access: DeliveryAccess, scope: AdminScope, request: EnrollmentRequest): IssuedEnrollment;
25
+ /** Redeem a Windows enrollment. Release trust is refused with WINDOWS_TRUST_CAPPED, whatever the ticket allows. */
26
+ export declare function enrollWindowsWorker(access: DeliveryAccess, input: EnrollmentRequest & {
27
+ ticket: string;
28
+ }): WorkerIdentity;
29
+ /**
30
+ * The promotion gate for Windows results. Every Windows result is untrusted,
31
+ * so this always refuses with WINDOWS_RESULT_UNTRUSTED. Merge point: US-008's
32
+ * shared release-eligibility check (assertJobTrust on the integration branch)
33
+ * should call this for Windows results; this base does not have it.
34
+ */
35
+ export declare function assertReleaseEligible(result: Pick<TerminalResult, "resultTrust" | "jobId" | "kind">): never;
14
36
  export interface Requirements {
15
37
  /** The job runs on any one of these platforms. */
16
38
  platforms: string[];
@@ -96,6 +118,10 @@ export interface TerminalResult {
96
118
  envKeys: string[];
97
119
  startedAt: string | null;
98
120
  finishedAt: string;
121
+ /** Set to "untrusted" on every Windows worker result (WINDOWS_TRUST_NOTE). Other workers sharing this type may omit it. */
122
+ resultTrust?: "untrusted";
123
+ /** false on every Windows worker result: never release-eligible. */
124
+ releaseEligible?: boolean;
99
125
  }
100
126
  /** Append-only JSON lines of terminal results. One result per attempt. */
101
127
  export declare class ResultLog {
@@ -178,28 +204,12 @@ export declare function helperOutcome(h: {
178
204
  spawnError?: string;
179
205
  stderr: string;
180
206
  }): LaunchOutcome;
181
- /** Submits an admitted job to the boundary service. Root's service binding implements this. */
207
+ /** Submits an admitted job to the service runner (windows-service.ts). */
182
208
  export interface ServiceTransport {
183
- submit(req: LaunchRequest, run: BoundaryRun): ContainedProcess;
184
- }
185
- export interface NativeWindowsLauncherOptions {
186
- /** Reports the seven boundary predicates for a run. Without one the launcher refuses. */
187
- probe?: BoundaryProbe;
188
- /** The installation, configuration and freshness a probe result must match. */
189
- context?: BoundaryContext;
190
- /** The authenticated channel to the service. Without one the launcher refuses. */
191
- transport?: ServiceTransport;
192
- /** Defaults to process.platform. */
193
- platform?: NodeJS.Platform;
209
+ submit(req: LaunchRequest, run: LaunchRun): ContainedProcess;
210
+ /** Throws a WorkerRefusal unless the runner can take a job now. */
211
+ check(): unknown;
194
212
  }
195
- /**
196
- * The native Windows launcher (proposal 039). A job runs only through the
197
- * boundary service: the probe must report all seven predicates as passing,
198
- * fresh and for this installation, and the job goes to the service over the
199
- * transport. There is no local compile and no same-user fallback; any missing
200
- * piece is CONTAINMENT_UNAVAILABLE before the claim.
201
- */
202
- export declare function nativeWindowsLauncher(opts?: NativeWindowsLauncherOptions): ContainedLauncher;
203
213
  export type StartResult = {
204
214
  kind: "refused";
205
215
  result: TerminalResult;