@wasit-dev/cli 0.7.0 → 0.8.0-beta.1

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/dist/run.js ADDED
@@ -0,0 +1,443 @@
1
+ /**
2
+ * `wasit run`: the endpoints of a `wasit.config.json`, one after another, with
3
+ * one report (spec A2, A8).
4
+ *
5
+ * Three tiers. `--read-only`: an x402 endpoint gets its unpaid challenge checks
6
+ * (X402-01..05); its payment checks, and every MPP check, are reported as
7
+ * skipped for the tier, so the report says which checks need a payer.
8
+ * `--dry-run` (spec B5): L0 and L1 only, the plan of the payment checks
9
+ * printed; no key, no payment, no signature. Neither flag: the payment tier.
10
+ *
11
+ * The payment tier pays only when every one of these holds (D-022a, B3, A1):
12
+ * the GitHub event may pay (push to the default branch, schedule,
13
+ * workflow_dispatch on it; outside GitHub Actions always), the network is a
14
+ * test network (L0; the mainnet opt-in is not part of this version), the
15
+ * environment has `operatedByMe: true`, the chain's key variable is set, and
16
+ * the plan (L1) fits the caps. Then one budget is shared by every endpoint, each
17
+ * endpoint's checks get its entry of the plan, and the pin and `maxRunUsd` come
18
+ * from the config; L2 and L3 hold every signature in core. On a pull request the
19
+ * run is the read-only tier and says so. A key variable that is set on a run that
20
+ * may not pay is refused before the service starts (Najmi, 2026-11-16).
21
+ *
22
+ * `--mainnet` asks for the mainnet opt-in, which this version does not have:
23
+ * the run is refused at once, exit 2, before the config is read (spec B12).
24
+ *
25
+ * `executeRun` does not call `process.exit` and does not read the process: the
26
+ * environment and the output are passed in, so it can be tested in-process.
27
+ */
28
+ import { readFileSync, statSync, writeFileSync } from "node:fs";
29
+ import { ConfigError, ConfigurationError, MAX_BASELINE_BYTES, PER_PAYMENT_CAP_USD, RunBudget, assertPaymentNetworkAllowed, buildEndpointReport, buildRunReport, deniedEnvValues, describePlan, describeRun, errored, formatUsd, inGithubActions, isLoopbackUrl, payerKeyVariables, paymentChainFor, paymentChecksSkipped, paymentEventGate, planX402Run, readBaseline, readConfigFile, readBuildCommit, readGithubEvent, readToolVersions, redactReport, refuseMainnetSwitch, resolveRun, runExitCode, runX402PaymentChecks, runX402ReadChecks, sanitizeText, selectBaseline, skippedPaymentChecks, urlOrigin, MainnetOptInRefusedError, RpcIdentityError, UnsupportedPaymentNetworkError, assertRpcServesNetwork, } from "@wasit-dev/core";
30
+ import { formatRun } from "./run-format.js";
31
+ import { ServiceError, serviceUserFor, startService } from "./service.js";
32
+ import { CLI_VERSION } from "./version.js";
33
+ const TIER_NOTE = "Tier: read-only. The payment checks were not run, and nothing was signed.";
34
+ const MPP_NOT_IN_RUN = "wasit run does not pay MPP in this version: run wasit mpp-charge or wasit mpp-channel against this endpoint";
35
+ function skippedFor(protocol, step) {
36
+ if (step.reason === undefined && (step.kind === "read-only" || step.kind === "needs-payer")) {
37
+ return skippedPaymentChecks(protocol, step.kind);
38
+ }
39
+ return paymentChecksSkipped(protocol, step.kind, step.reason ?? "the payment checks were not run");
40
+ }
41
+ /** What the run does for one endpoint. */
42
+ async function runEndpoint(endpoint, step) {
43
+ try {
44
+ if (endpoint.protocol === "x402") {
45
+ const shape = {
46
+ method: endpoint.method,
47
+ ...(endpoint.body === undefined ? {} : { body: endpoint.body }),
48
+ ...(Object.keys(endpoint.headers).length === 0 ? {} : { headers: endpoint.headers }),
49
+ };
50
+ const challenge = await runX402ReadChecks({ target: endpoint.url, ...shape });
51
+ if (!step.pay)
52
+ return [...challenge, ...skippedFor("x402", step)];
53
+ // Every endpoint of the run was planned; one that is not in the plan is not paid.
54
+ const plan = step.plan.endpoints.find((entry) => entry.name === endpoint.name);
55
+ if (plan === undefined)
56
+ throw new Error(`the plan of this run has no entry for ${endpoint.name}`);
57
+ const payment = await runX402PaymentChecks({
58
+ target: endpoint.url,
59
+ network: step.network,
60
+ payerSecretKey: step.key,
61
+ ...(step.rpcUrl === undefined ? {} : { rpcUrl: step.rpcUrl }),
62
+ budget: step.budget,
63
+ ...(step.pin === undefined ? {} : { pin: step.pin }),
64
+ plan,
65
+ ...shape,
66
+ // X402-11 sends a payment with the request the config says the service must refuse.
67
+ ...(endpoint.reject === undefined ? {} : { reject: endpoint.reject }),
68
+ ...(step.progress === undefined ? {} : { onProgress: step.progress }),
69
+ });
70
+ return [...challenge, ...payment];
71
+ }
72
+ // Every MPP check pays or signs. The read-only tier has none to run, and the
73
+ // payment tier of wasit run does not run them in this version.
74
+ if (step.pay)
75
+ return paymentChecksSkipped(endpoint.protocol, "not-applicable", MPP_NOT_IN_RUN);
76
+ return skippedFor(endpoint.protocol, step);
77
+ }
78
+ catch (error) {
79
+ // A check that throws is a defect in Wasit, not a finding about the service.
80
+ return [errored("PREFLIGHT", "Run Preflight", error)];
81
+ }
82
+ }
83
+ /** The x402 endpoints of a run, as the plan reads them. */
84
+ function planEndpoints(resolved) {
85
+ return resolved.endpoints
86
+ .filter((endpoint) => endpoint.protocol === "x402")
87
+ .map((endpoint) => ({
88
+ name: endpoint.name,
89
+ target: endpoint.url,
90
+ method: endpoint.method,
91
+ ...(endpoint.body === undefined ? {} : { body: endpoint.body }),
92
+ ...(Object.keys(endpoint.headers).length === 0 ? {} : { headers: endpoint.headers }),
93
+ ...(endpoint.reject === undefined ? {} : { reject: endpoint.reject }),
94
+ }));
95
+ }
96
+ /**
97
+ * A key variable is set on a run that may not pay (Najmi, 2026-11-16): refused
98
+ * before the service starts, because the service would run in the same job as
99
+ * the key. A fork's pull request has empty secrets and is not refused.
100
+ */
101
+ function keyOnRefusedEvent(keys, reason) {
102
+ const why = reason.replace(/^payment checks not run: /, "");
103
+ const first = keys[0] ?? "STELLAR_PRIVATE_KEY";
104
+ return (`wasit run: ${keys.join(", ")} ${keys.length === 1 ? "is" : "are"} set, and this run may not pay (${why}). ` +
105
+ `Nothing was started or sent: the service of this run would run in the same job as the key. ` +
106
+ `Give the key only to runs that may pay (push to the default branch, schedule, workflow_dispatch), ` +
107
+ `for example in the env: of the Wasit step:\n` +
108
+ ` ${first}: \${{ github.event_name != 'pull_request' && secrets.WASIT_TESTNET_PAYER || '' }}`);
109
+ }
110
+ /** Why `wasit run` stops in a CI that is not GitHub Actions. */
111
+ function otherCiRefusal(keys) {
112
+ const key = keys.length === 0
113
+ ? ""
114
+ : ` ${keys.join(", ")} ${keys.length === 1 ? "is" : "are"} set: remove ${keys.length === 1 ? "it" : "them"} from ` +
115
+ `this job, since the service of this run would run in the same job as the key.`;
116
+ return (`wasit run: CI is set, and this is not GitHub Actions. In this version the payment tier runs outside CI, or in ` +
117
+ `GitHub Actions, where it pays only on a push to the default branch, a schedule and workflow_dispatch. ` +
118
+ `In this CI, run wasit run --read-only, with no payer key in the job.${key} Nothing was started, sent or signed.`);
119
+ }
120
+ /** The payer's address for the first line of a paying run; the checks report a key that is not valid. */
121
+ function payerAddress(chain, key) {
122
+ try {
123
+ return chain.payerAddress(key);
124
+ }
125
+ catch {
126
+ return "(the key is not valid: see the results)";
127
+ }
128
+ }
129
+ /** The baseline file, read; the reason when it cannot be. A file that is not there is the first run on main: no reason. */
130
+ function readBaselineFile(path) {
131
+ try {
132
+ if (statSync(path).size > MAX_BASELINE_BYTES) {
133
+ return { ok: false, reason: `the baseline is larger than ${MAX_BASELINE_BYTES / 1024} KiB` };
134
+ }
135
+ return readBaseline(readFileSync(path, "utf-8"));
136
+ }
137
+ catch (error) {
138
+ const code = error.code;
139
+ return { ok: false, reason: `the baseline file cannot be read${typeof code === "string" ? ` (${code})` : ""}` };
140
+ }
141
+ }
142
+ /**
143
+ * The dry run: the plan of the x402 payment checks (L0, L1), printed. Exit 0
144
+ * when a paying run could start as planned, 2 when it would be refused.
145
+ */
146
+ async function printPlan(resolved, stdout, clean, fail) {
147
+ let plan;
148
+ try {
149
+ plan = await planX402Run({
150
+ network: resolved.network,
151
+ ...(resolved.pinned === undefined ? {} : { pin: resolved.pinned }),
152
+ ...(resolved.maxRunUsd === undefined ? {} : { maxRunUsd: resolved.maxRunUsd }),
153
+ endpoints: planEndpoints(resolved),
154
+ });
155
+ }
156
+ catch (error) {
157
+ // L0: a network that is not a test network, refused before any request.
158
+ if (error instanceof ConfigurationError)
159
+ return fail(`wasit run --dry-run: ${error.message}`);
160
+ throw error;
161
+ }
162
+ const lines = [...describeRun(resolved).split("\n"), ...describePlan(plan)];
163
+ for (const endpoint of resolved.endpoints) {
164
+ if (endpoint.protocol !== "x402") {
165
+ lines.push(` ${endpoint.name}: not planned: the dry run plans the x402 payment checks; ${endpoint.protocol} is not planned in this version.`);
166
+ }
167
+ }
168
+ const refused = plan.refusal !== undefined || plan.endpoints.some((endpoint) => endpoint.status === "refused");
169
+ if (!resolved.operatedByMe) {
170
+ lines.push(`Refused: operatedByMe is not true for environment ${resolved.environment}, so a paying run would be ` +
171
+ `refused: Wasit pays only a service its operator runs. Nothing was signed.`);
172
+ }
173
+ for (const line of lines)
174
+ stdout(clean(line));
175
+ return refused || !resolved.operatedByMe ? 2 : 0;
176
+ }
177
+ export async function executeRun(options, context) {
178
+ const secrets = deniedEnvValues(context.env);
179
+ const clean = (text) => sanitizeText(text, { redact: secrets });
180
+ const stderr = (text) => context.stderr(clean(text));
181
+ const fail = (message) => {
182
+ stderr(message);
183
+ return 2;
184
+ };
185
+ // B12: the switch exists only to refuse. First, so nothing is read, started, sent or signed.
186
+ if (options.mainnet === true) {
187
+ try {
188
+ refuseMainnetSwitch("--mainnet", inGithubActions(context.env) ? { event: context.env["GITHUB_EVENT_NAME"] ?? "" } : {});
189
+ }
190
+ catch (error) {
191
+ if (error instanceof MainnetOptInRefusedError)
192
+ return fail(`wasit run ${error.message}`);
193
+ throw error;
194
+ }
195
+ }
196
+ const dryRun = options.dryRun === true;
197
+ if (dryRun && options.readOnly) {
198
+ return fail("wasit run: choose --dry-run or --read-only, not both.");
199
+ }
200
+ if (dryRun && (options.json || options.out !== undefined || options.baseline !== undefined)) {
201
+ return fail("wasit run --dry-run prints a plan and writes no report: it takes no --json, --out or --baseline.");
202
+ }
203
+ if (options.start && options.startIfLocal === true) {
204
+ return fail("wasit run: choose --start or --start-if-local, not both.");
205
+ }
206
+ let resolved;
207
+ try {
208
+ resolved = resolveRun(readConfigFile(options.config), {
209
+ ...(options.env === undefined ? {} : { environment: options.env }),
210
+ ...(options.endpoint === undefined || options.endpoint.length === 0 ? {} : { endpoints: options.endpoint }),
211
+ }, context.env);
212
+ }
213
+ catch (error) {
214
+ if (error instanceof ConfigError)
215
+ return fail(error.message);
216
+ throw error;
217
+ }
218
+ // D-022a: which GitHub events may pay. A key given to a run that may not pay is
219
+ // refused here, before the service of this run (code that may not be reviewed
220
+ // yet) starts in the same job as the key. Every tier, the read-only one too.
221
+ const gate = paymentEventGate(context.env, readGithubEvent(context.env));
222
+ if (gate.ciOutsideGithub === true) {
223
+ // In a CI that is not GitHub Actions the payment tier does not run at all, and
224
+ // no tier runs beside a payer key (Najmi, 2026-11-17, review R9 a).
225
+ const keys = payerKeyVariables(context.env);
226
+ if (keys.length > 0 || (!options.readOnly && options.dryRun !== true))
227
+ return fail(otherCiRefusal(keys));
228
+ }
229
+ else if (!gate.allowed) {
230
+ const keys = payerKeyVariables(context.env);
231
+ if (keys.length > 0)
232
+ return fail(keyOnRefusedEvent(keys, gate.reason ?? "this event"));
233
+ }
234
+ // The payment tier: neither --read-only nor --dry-run. On an event that may not
235
+ // pay it is the read-only tier, and the report says why.
236
+ const paymentAsked = !options.readOnly && !dryRun;
237
+ const paying = paymentAsked && gate.allowed;
238
+ const chain = paying ? paymentChainFor(resolved.network) : undefined;
239
+ if (paying && (chain !== undefined || resolved.networkClass !== "unknown")) {
240
+ // L0, before the service starts or anything is sent: a test network only.
241
+ try {
242
+ assertPaymentNetworkAllowed("x402", resolved.network);
243
+ }
244
+ catch (error) {
245
+ if (error instanceof ConfigurationError)
246
+ return fail(`wasit run: ${error.message} Nothing was started, sent or signed.`);
247
+ throw error;
248
+ }
249
+ }
250
+ const keyEnv = chain?.payerKeyEnv;
251
+ const keyValue = keyEnv === undefined ? undefined : context.env[keyEnv];
252
+ const key = keyValue === undefined || keyValue.trim() === "" ? undefined : keyValue;
253
+ const hasX402 = resolved.endpoints.some((endpoint) => endpoint.protocol === "x402");
254
+ /** Why the payment tier that was asked for does not pay, on an event that may pay. */
255
+ const notPaid = !paying
256
+ ? undefined
257
+ : !resolved.operatedByMe
258
+ ? `operatedByMe is not true for environment ${resolved.environment}: Wasit pays only a service its operator runs`
259
+ : chain !== undefined && key === undefined
260
+ ? `no payer key: set ${keyEnv} on the Wasit step`
261
+ : undefined;
262
+ // D-023a+b: a run that will pay checks its RPC before the service starts or
263
+ // anything is sent to it: the payments are built and their settlements read
264
+ // through it, so it must serve the run's own network.
265
+ if (paying && notPaid === undefined && chain !== undefined && key !== undefined && hasX402) {
266
+ try {
267
+ await assertRpcServesNetwork(resolved.network, chain.resolveRpcUrl(resolved.network, resolved.rpcUrl));
268
+ }
269
+ catch (error) {
270
+ if (error instanceof RpcIdentityError)
271
+ return fail(`wasit run: ${error.message} The service was not started.`);
272
+ throw error;
273
+ }
274
+ }
275
+ // The decision is the CLI's, in one place: --start always starts, --start-if-local starts only
276
+ // when service.start is set and the environment is on this machine, and says which it did.
277
+ let shouldStart = options.start;
278
+ if (options.startIfLocal === true) {
279
+ const origin = urlOrigin(resolved.baseUrl);
280
+ if (resolved.service?.start === undefined) {
281
+ stderr(`wasit run: service.start is not set, so ${origin} is read as it is.`);
282
+ }
283
+ else if (!isLoopbackUrl(resolved.baseUrl)) {
284
+ stderr(`wasit run: environment ${resolved.environment} is at ${origin}, not on this machine, ` +
285
+ `so service.start is not used and ${origin} is read as it is.`);
286
+ }
287
+ else {
288
+ shouldStart = true;
289
+ }
290
+ }
291
+ let service;
292
+ // D-022a option 2: on a GitHub-hosted runner, a service started while a payer key is set runs as its own user.
293
+ const serviceUser = serviceUserFor(context.env);
294
+ if (shouldStart) {
295
+ const { start, ready } = resolved.service ?? {};
296
+ if (start === undefined) {
297
+ return fail("wasit run --start needs service.start in the config: the command that starts the service.");
298
+ }
299
+ if (ready === undefined) {
300
+ return fail("wasit run --start needs service.ready in the config: the url on this machine to wait for, " +
301
+ 'for example { "url": "http://127.0.0.1:3000/", "timeoutSeconds": 60 }.');
302
+ }
303
+ try {
304
+ service = await startService({
305
+ command: start,
306
+ ready,
307
+ env: context.env,
308
+ log: (line) => context.stderr(line),
309
+ ...(context.cwd === undefined ? {} : { cwd: context.cwd }),
310
+ ...(serviceUser === undefined ? {} : { separateUser: { name: serviceUser, ...(context.sudo === undefined ? {} : { sudo: context.sudo }) } }),
311
+ });
312
+ }
313
+ catch (error) {
314
+ if (error instanceof ServiceError)
315
+ return fail(error.message);
316
+ throw error;
317
+ }
318
+ }
319
+ if (dryRun) {
320
+ try {
321
+ return await printPlan(resolved, context.stdout, clean, fail);
322
+ }
323
+ finally {
324
+ await service?.stop();
325
+ }
326
+ }
327
+ const startedAt = (context.now?.() ?? new Date()).toISOString();
328
+ // Lines about money go where the report is not: stderr with --json, else stdout.
329
+ const say = (line) => (options.json ? stderr(line) : context.stdout(clean(line)));
330
+ try {
331
+ let step;
332
+ let tierNote;
333
+ let budget;
334
+ if (!paymentAsked) {
335
+ step = { pay: false, kind: "read-only" };
336
+ tierNote = TIER_NOTE;
337
+ }
338
+ else if (!gate.allowed) {
339
+ const reason = gate.reason ?? "payment checks not run";
340
+ step = { pay: false, kind: "read-only", reason };
341
+ tierNote = `Tier: read-only (${reason}). Nothing was signed.`;
342
+ }
343
+ else if (notPaid !== undefined) {
344
+ step = { pay: false, kind: resolved.operatedByMe ? "needs-payer" : "read-only", reason: `payment checks not run: ${notPaid}` };
345
+ tierNote = `Tier: payment on ${resolved.network}, and the payment checks were not run: ${notPaid}. Nothing was signed.`;
346
+ }
347
+ else if (chain === undefined || key === undefined) {
348
+ // No payment adapter for this network: the payment group is unsupported (spec A3), so the
349
+ // endpoint has no verdict (Najmi, 2026-11-15). Nothing is fetched for it beyond the challenge.
350
+ step = { pay: false, kind: "unsupported", reason: new UnsupportedPaymentNetworkError(resolved.network).message };
351
+ tierNote = `Tier: payment on ${resolved.network}, a network Wasit does not pay on. Nothing was signed.`;
352
+ }
353
+ else {
354
+ // L1: the plan, read before anything is signed. A run above its cap does not start.
355
+ const plan = await planX402Run({
356
+ network: resolved.network,
357
+ ...(resolved.pinned === undefined ? {} : { pin: resolved.pinned }),
358
+ ...(resolved.maxRunUsd === undefined ? {} : { maxRunUsd: resolved.maxRunUsd }),
359
+ endpoints: planEndpoints(resolved),
360
+ });
361
+ if (plan.refusal !== undefined) {
362
+ for (const line of describePlan(plan))
363
+ stderr(line);
364
+ return fail(`wasit run: ${plan.refusal}`);
365
+ }
366
+ budget = new RunBudget(resolved.maxRunUsd === undefined ? {} : { maxRunUsd: resolved.maxRunUsd });
367
+ say(`Payment tier on ${resolved.network} (test network): test funds. Payer ${payerAddress(chain, key)}; ` +
368
+ `at most ${formatUsd(plan.perPaymentCapUsd)} per payment; this run could spend up to ` +
369
+ `${formatUsd(plan.worstCaseUsd)} of the ${formatUsd(budget.capUsd)} cap.`);
370
+ for (const line of describePlan(plan).slice(1))
371
+ say(line);
372
+ step = {
373
+ pay: true,
374
+ network: resolved.network,
375
+ key,
376
+ ...(resolved.rpcUrl === undefined ? {} : { rpcUrl: resolved.rpcUrl }),
377
+ budget,
378
+ ...(resolved.pinned === undefined ? {} : { pin: resolved.pinned }),
379
+ plan,
380
+ progress: say,
381
+ };
382
+ tierNote = "";
383
+ }
384
+ const endpoints = [];
385
+ for (const endpoint of resolved.endpoints) {
386
+ const results = await runEndpoint(endpoint, step);
387
+ endpoints.push(buildEndpointReport({
388
+ name: endpoint.name,
389
+ protocol: endpoint.protocol,
390
+ method: endpoint.method,
391
+ path: endpoint.path,
392
+ results,
393
+ }));
394
+ }
395
+ if (budget !== undefined) {
396
+ // Charged before each signature and never credited back: what the run may have spent.
397
+ tierNote =
398
+ `Tier: payment on ${resolved.network}. The run charged ${formatUsd(budget.spentUsd)} of the ` +
399
+ `${formatUsd(budget.capUsd)} cap, at most $${PER_PAYMENT_CAP_USD}.00 a payment; every signature is counted as if it settled.`;
400
+ }
401
+ const input = {
402
+ environment: resolved.environment,
403
+ network: resolved.network,
404
+ startedAt,
405
+ versions: readToolVersions(CLI_VERSION, readBuildCommit(context.env)),
406
+ endpoints,
407
+ };
408
+ const preliminary = buildRunReport({ ...input, notes: [tierNote] });
409
+ const selected = selectBaseline(preliminary, options.baseline === undefined ? undefined : readBaselineFile(options.baseline));
410
+ const report = redactReport(selected.note === undefined
411
+ ? preliminary
412
+ : buildRunReport({ ...input, notes: [tierNote, `Baseline not used: ${selected.note}.`] }), secrets);
413
+ let verdict = runExitCode(report, selected.baseline?.report);
414
+ // The payment tier was asked for on an event that may pay and did not pay:
415
+ // not green (a FAIL still outranks it).
416
+ if (notPaid !== undefined && hasX402 && verdict.code === 0) {
417
+ verdict = { ...verdict, code: 2, reason: `the payment tier was asked for and its payment checks were not run: ${notPaid}` };
418
+ }
419
+ const json = `${JSON.stringify(report, null, 2)}\n`;
420
+ if (options.out !== undefined) {
421
+ try {
422
+ writeFileSync(options.out, json);
423
+ }
424
+ catch (error) {
425
+ const code = error.code;
426
+ return fail(`wasit run: cannot write ${options.out}${typeof code === "string" ? ` (${code})` : ""}`);
427
+ }
428
+ }
429
+ if (options.json) {
430
+ context.stdout(json.trimEnd());
431
+ // The JSON says what was found; this line says what the exit code is and why, for a log.
432
+ context.stderr(clean(`Result: ${verdict.reason} (exit ${verdict.code}).`));
433
+ }
434
+ else {
435
+ for (const line of formatRun(resolved, report, verdict))
436
+ context.stdout(clean(line));
437
+ }
438
+ return verdict.code;
439
+ }
440
+ finally {
441
+ await service?.stop();
442
+ }
443
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * `wasit run --start`: start the builder's service, wait until it answers, and
3
+ * stop it again (spec A8 #1, A-A02).
4
+ *
5
+ * Why this lives in the CLI and not in the Action: a composite action is one
6
+ * step for the workflow that uses it, so a variable set on the action reaches
7
+ * every step inside, the one that starts the service included. Here the
8
+ * child's environment is built in one place, from the parent's with the
9
+ * variables Wasit keeps away from a service removed (see `denied-env.ts` in
10
+ * core), and the same code runs on a laptop and in CI.
11
+ *
12
+ * Stopping is the part that must not fail quietly. A service is a shell command
13
+ * (`npm start`), so the process that starts is a shell and the service is its
14
+ * child or grandchild. On POSIX the command is started in a process group of
15
+ * its own and the whole group is signalled: SIGTERM first, SIGKILL after a grace
16
+ * period. The service is stopped when a run ends normally, when it fails, on
17
+ * SIGINT, SIGTERM and SIGHUP, and, as a last synchronous resort, when the Node
18
+ * process exits. A SIGKILL of Wasit itself cannot be caught.
19
+ *
20
+ * Windows: the group kill is `taskkill /pid <pid> /T /F`. That path has NOT been
21
+ * run on Windows; no Windows machine was available.
22
+ */
23
+ /**
24
+ * The OS user a service runs as when it must not share a user with the payer
25
+ * key (D-022a option 2). Fixed in code: a config or a variable never chooses it.
26
+ */
27
+ export declare const SERVICE_USER = "wasit-service";
28
+ /**
29
+ * The user to run the service as, or undefined for the runner's own user.
30
+ *
31
+ * Najmi, 2026-11-16: a separate user only when a payer key variable is set AND
32
+ * the runner is GitHub-hosted (`RUNNER_ENVIRONMENT`, which GitHub documents as
33
+ * `github-hosted` or `self-hosted`; not re-read on the day). A hosted runner's
34
+ * user has passwordless sudo, which makes the user; a self-hosted runner or a
35
+ * laptop may not, and there the service runs as today. What this separates is
36
+ * the service's own processes from the Wasit process that holds the key: on
37
+ * Linux the environment of a process (`/proc/<pid>/environ`) is readable by its
38
+ * own user and root only. It does NOT separate code that ran earlier in the job
39
+ * as the runner's user (install scripts), which the guide says.
40
+ */
41
+ export declare function serviceUserFor(env: Readonly<Record<string, string | undefined>>): string | undefined;
42
+ /** The service runs as `name`, through `sudo -n`. `sudo` is the program to run: a test passes a stand-in. */
43
+ export interface SeparateUser {
44
+ readonly name: string;
45
+ readonly sudo?: string;
46
+ }
47
+ /** The service did not start, did not answer, or exited. Nothing was learned about the target: exit 2. */
48
+ export declare class ServiceError extends Error {
49
+ constructor(message: string);
50
+ }
51
+ export interface ServiceOptions {
52
+ /** `service.start`: one shell command, as trusted as the repository's own code. */
53
+ readonly command: string;
54
+ /** `service.ready`: any HTTP answer counts. Held to this machine. */
55
+ readonly ready: {
56
+ readonly url: string;
57
+ readonly timeoutSeconds: number;
58
+ };
59
+ /** The environment to derive the child's from. The denied variables are removed. */
60
+ readonly env: Readonly<Record<string, string | undefined>>;
61
+ readonly cwd?: string;
62
+ /** Where the service's output goes, one line at a time. Default `console.error`: stdout stays for `--json`. */
63
+ readonly log?: (line: string) => void;
64
+ /** How long SIGTERM gets before SIGKILL. Default 5000. */
65
+ readonly stopGraceMs?: number;
66
+ /** After this many bytes of output, the rest is not printed (the service is not blocked). Default 256 KiB. */
67
+ readonly maxLogBytes?: number;
68
+ /** Default 250. */
69
+ readonly pollIntervalMs?: number;
70
+ /** Run the service as this user (see {@link serviceUserFor}). POSIX only; no fallback when it cannot be had. */
71
+ readonly separateUser?: SeparateUser;
72
+ }
73
+ export interface StartedService {
74
+ readonly pid: number;
75
+ /** Stops the service and everything it started. Safe to call twice. */
76
+ readonly stop: () => Promise<void>;
77
+ }
78
+ export declare function startService(options: ServiceOptions): Promise<StartedService>;