@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.
- package/CHANGELOG.md +93 -0
- package/assets/scaffold/core/scripts/hq-delegate-verify.sh +5 -2
- package/dist/command-catalog.generated.d.ts +180 -13
- package/dist/command-catalog.generated.js +221 -13
- 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 +231 -55
- package/dist/commands/capacity.d.ts +4 -1
- package/dist/commands/capacity.js +46 -10
- package/dist/commands/cloud.d.ts +66 -13
- package/dist/commands/cloud.js +121 -40
- 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/core-delegate-w1b.js +15 -1
- package/dist/commands/core-policy.js +67 -8
- package/dist/commands/daemon.js +5 -0
- package/dist/commands/files-browse.d.ts +11 -4
- package/dist/commands/files-browse.js +21 -4
- package/dist/commands/files.d.ts +1 -1
- package/dist/commands/files.js +25 -11
- package/dist/commands/integrations-auth-rules.d.ts +27 -0
- package/dist/commands/integrations-auth-rules.js +79 -0
- package/dist/commands/integrations-connect.d.ts +10 -3
- package/dist/commands/integrations-connect.js +87 -13
- package/dist/commands/integrations-import.js +124 -12
- package/dist/commands/lanes.js +28 -11
- package/dist/commands/mesh.d.ts +2 -0
- package/dist/commands/mesh.js +60 -35
- 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-held.js +5 -2
- package/dist/commands/sync-mode.js +5 -0
- package/dist/commands/whoami.js +4 -0
- package/dist/lazy-commands.js +3 -5
- 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-cron.d.ts +8 -0
- package/dist/lib/bot/fleet-cron.js +35 -3
- package/dist/lib/bot/fleet-daemon.d.ts +46 -0
- package/dist/lib/bot/fleet-daemon.js +99 -1
- 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/probe.js +7 -1
- 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/run.js +20 -1
- package/dist/lib/bot/runtime/codex.js +1 -1
- package/dist/lib/bot/runtime/grok-acp.d.ts +5 -1
- package/dist/lib/bot/runtime/grok-acp.js +6 -3
- package/dist/lib/bot/runtime/index.js +19 -9
- package/dist/lib/bot/runtime/messages-stream.js +2 -2
- package/dist/lib/bot/runtime/types.d.ts +15 -0
- package/dist/lib/bot/runtime/types.js +9 -0
- package/dist/lib/bot/runtime-auth.d.ts +30 -0
- package/dist/lib/bot/runtime-auth.js +94 -3
- package/dist/lib/bot/runtime-failure.d.ts +23 -0
- package/dist/lib/bot/runtime-failure.js +43 -1
- package/dist/lib/bot/status.d.ts +2 -0
- package/dist/lib/capacity/accounts.d.ts +8 -0
- package/dist/lib/capacity/accounts.js +19 -0
- package/dist/lib/capacity/available.d.ts +154 -0
- package/dist/lib/capacity/available.js +905 -0
- package/dist/lib/capacity/codex-availability.d.ts +14 -1
- package/dist/lib/capacity/codex-availability.js +26 -1
- package/dist/lib/capacity/collectors/claude-oauth.d.ts +29 -2
- package/dist/lib/capacity/collectors/claude-oauth.js +104 -7
- package/dist/lib/capacity/collectors/codex.js +10 -7
- 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/capacity/ledger.d.ts +37 -1
- package/dist/lib/capacity/ledger.js +207 -30
- package/dist/lib/capacity/project.d.ts +26 -0
- package/dist/lib/capacity/project.js +137 -8
- package/dist/lib/capacity/refusal-rows.d.ts +31 -0
- package/dist/lib/capacity/refusal-rows.js +61 -0
- package/dist/lib/capacity/refusal.d.ts +53 -2
- package/dist/lib/capacity/refusal.js +284 -65
- package/dist/lib/capacity/route.js +46 -11
- package/dist/lib/capacity/widget.d.ts +12 -1
- package/dist/lib/capacity/widget.js +91 -3
- package/dist/lib/daemon/catalog.js +11 -1
- package/dist/lib/daemon/resolver.d.ts +2 -0
- package/dist/lib/daemon/resolver.js +3 -0
- package/dist/lib/daemon/run.d.ts +9 -0
- package/dist/lib/daemon/run.js +54 -1
- package/dist/lib/daemon/server.d.ts +2 -0
- package/dist/lib/daemon/server.js +10 -1
- package/dist/lib/daemon/tcc-eperm.d.ts +153 -0
- package/dist/lib/daemon/tcc-eperm.js +310 -0
- package/dist/lib/db/sqlite-binding.d.ts +1 -0
- package/dist/lib/db/sqlite-binding.js +1 -1
- package/dist/lib/delivery/admission.d.ts +86 -0
- package/dist/lib/delivery/admission.js +148 -0
- package/dist/lib/delivery/artifacts.d.ts +105 -0
- package/dist/lib/delivery/artifacts.js +567 -0
- package/dist/lib/delivery/attempt-id.d.ts +13 -0
- package/dist/lib/delivery/attempt-id.js +16 -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/disposable-target.d.ts +42 -0
- package/dist/lib/delivery/disposable-target.js +111 -0
- package/dist/lib/delivery/effects.d.ts +136 -0
- package/dist/lib/delivery/effects.js +541 -0
- package/dist/lib/delivery/enrollment.d.ts +146 -0
- package/dist/lib/delivery/enrollment.js +460 -0
- package/dist/lib/delivery/escalations.d.ts +51 -0
- package/dist/lib/delivery/escalations.js +60 -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/lease.d.ts +80 -0
- package/dist/lib/delivery/lease.js +134 -0
- package/dist/lib/delivery/migrations.d.ts +255 -0
- package/dist/lib/delivery/migrations.js +823 -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 +63 -0
- package/dist/lib/delivery/mqtt.js +119 -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 +215 -0
- package/dist/lib/delivery/reconciler.js +703 -0
- package/dist/lib/delivery/restore.d.ts +35 -0
- package/dist/lib/delivery/restore.js +134 -0
- package/dist/lib/delivery/rpc/client.d.ts +22 -0
- package/dist/lib/delivery/rpc/client.js +159 -0
- package/dist/lib/delivery/rpc/port.d.ts +40 -0
- package/dist/lib/delivery/rpc/port.js +16 -0
- package/dist/lib/delivery/rpc/server.d.ts +30 -0
- package/dist/lib/delivery/rpc/server.js +205 -0
- package/dist/lib/delivery/rpc/wire.d.ts +85 -0
- package/dist/lib/delivery/rpc/wire.js +143 -0
- package/dist/lib/delivery/store.d.ts +163 -0
- package/dist/lib/delivery/store.js +944 -0
- package/dist/lib/delivery/windows-service-install.d.ts +262 -0
- package/dist/lib/delivery/windows-service-install.js +892 -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 +191 -0
- package/dist/lib/delivery/workers/macos.js +943 -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-service-live.d.ts +121 -0
- package/dist/lib/delivery/workers/windows-service-live.js +711 -0
- package/dist/lib/delivery/workers/windows-service-runner.d.ts +33 -0
- package/dist/lib/delivery/workers/windows-service-runner.js +82 -0
- package/dist/lib/delivery/workers/windows-service.d.ts +140 -0
- package/dist/lib/delivery/workers/windows-service.js +584 -0
- package/dist/lib/delivery/workers/windows.d.ts +251 -0
- package/dist/lib/delivery/workers/windows.js +594 -0
- package/dist/lib/hot-channels/adapters/meetings.d.ts +15 -0
- package/dist/lib/hot-channels/adapters/meetings.js +36 -3
- package/dist/lib/hot-channels/signals-pass.d.ts +10 -0
- package/dist/lib/hot-channels/signals-pass.js +71 -2
- package/dist/lib/hot-channels/signals-redo.js +10 -2
- package/dist/lib/install/provider-wrappers.d.ts +2 -0
- package/dist/lib/install/provider-wrappers.js +68 -3
- package/dist/lib/lanes/watcher.js +35 -0
- package/dist/lib/signals/steps/extract.js +40 -4
- package/dist/schemas/hq-available-ai.v1.schema.json +76 -0
- package/dist/utils/catalog-runtime-paths.d.ts +34 -0
- package/dist/utils/catalog-runtime-paths.js +53 -0
- 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/files-browse-acl.js +1 -1
- 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,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
|