@mostra/runtime 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +39 -2
  3. package/dist/bin.d.ts +1 -0
  4. package/dist/bin.js +236 -0
  5. package/dist/bin.js.map +1 -0
  6. package/dist/builder/child/main.d.ts +1 -0
  7. package/dist/builder/child/main.js +1408 -0
  8. package/dist/builder/child/main.js.map +1 -0
  9. package/dist/child-xrHmytks.js +49 -0
  10. package/dist/child-xrHmytks.js.map +1 -0
  11. package/dist/deps/child/install.d.ts +1 -0
  12. package/dist/deps/child/install.js +33 -0
  13. package/dist/deps/child/install.js.map +1 -0
  14. package/dist/index.d.ts +221 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +3 -0
  17. package/dist/instance-CzBkUyHu.js +15920 -0
  18. package/dist/instance-CzBkUyHu.js.map +1 -0
  19. package/dist/types-NjNy7gXX.js +57 -0
  20. package/dist/types-NjNy7gXX.js.map +1 -0
  21. package/package.json +87 -3
  22. package/src/actions/index.ts +622 -0
  23. package/src/addressing/index.ts +281 -0
  24. package/src/bin.ts +240 -0
  25. package/src/builder/child/dev.ts +383 -0
  26. package/src/builder/child/fields.ts +363 -0
  27. package/src/builder/child/main.ts +47 -0
  28. package/src/builder/child/plugins.ts +195 -0
  29. package/src/builder/child/scan.ts +459 -0
  30. package/src/builder/child/spa.ts +348 -0
  31. package/src/builder/coverage.ts +72 -0
  32. package/src/builder/index.ts +406 -0
  33. package/src/builder/types.ts +180 -0
  34. package/src/deps/child/install.ts +30 -0
  35. package/src/deps/index.ts +918 -0
  36. package/src/deps/installer.ts +321 -0
  37. package/src/deps/lock.ts +82 -0
  38. package/src/deps/scan.ts +266 -0
  39. package/src/deps/specifier.ts +64 -0
  40. package/src/deps/warm.ts +57 -0
  41. package/src/dev/index.ts +518 -0
  42. package/src/faults.ts +65 -0
  43. package/src/gate.ts +55 -0
  44. package/src/gateway/actions.ts +268 -0
  45. package/src/gateway/browser.ts +650 -0
  46. package/src/gateway/capabilities.ts +760 -0
  47. package/src/gateway/controls.ts +91 -0
  48. package/src/gateway/dev.ts +119 -0
  49. package/src/gateway/http.ts +229 -0
  50. package/src/gateway/identity.ts +101 -0
  51. package/src/gateway/index.ts +1299 -0
  52. package/src/gateway/integrity.ts +117 -0
  53. package/src/gateway/listener.ts +217 -0
  54. package/src/gateway/routes.ts +197 -0
  55. package/src/gateway/serve.ts +138 -0
  56. package/src/gc/index.ts +451 -0
  57. package/src/home/acquire.ts +276 -0
  58. package/src/home/index.ts +16 -0
  59. package/src/home/paths.ts +192 -0
  60. package/src/home/platform.ts +34 -0
  61. package/src/home/record.ts +76 -0
  62. package/src/home/settings.ts +113 -0
  63. package/src/index.ts +30 -0
  64. package/src/instance/index.ts +979 -0
  65. package/src/interaction/ephemeral.ts +300 -0
  66. package/src/interaction/events.ts +355 -0
  67. package/src/interaction/fields.ts +392 -0
  68. package/src/interaction/index.ts +1013 -0
  69. package/src/interaction/outbox.ts +493 -0
  70. package/src/interaction/policy.ts +26 -0
  71. package/src/interaction/results.ts +341 -0
  72. package/src/interaction/runs.ts +313 -0
  73. package/src/interaction/signals.ts +120 -0
  74. package/src/interaction/submissions.ts +585 -0
  75. package/src/interaction/subscriptions.ts +258 -0
  76. package/src/interaction/viewers.ts +187 -0
  77. package/src/interaction/wait.ts +201 -0
  78. package/src/ledger/index.ts +442 -0
  79. package/src/ledger/migrations.ts +596 -0
  80. package/src/ledger/requests.ts +105 -0
  81. package/src/ledger/types.ts +28 -0
  82. package/src/live/index.ts +573 -0
  83. package/src/log.ts +316 -0
  84. package/src/processes/child.ts +67 -0
  85. package/src/processes/environment.ts +64 -0
  86. package/src/processes/identity.ts +191 -0
  87. package/src/processes/index.ts +19 -0
  88. package/src/processes/manager.ts +543 -0
  89. package/src/protocol-server/client.ts +94 -0
  90. package/src/protocol-server/index.ts +91 -0
  91. package/src/protocol-server/server.ts +518 -0
  92. package/src/protocol-server/streams.ts +81 -0
  93. package/src/publish/checks.ts +92 -0
  94. package/src/publish/digest.ts +87 -0
  95. package/src/publish/index.ts +23 -0
  96. package/src/publish/manifest.ts +409 -0
  97. package/src/publish/methods.ts +96 -0
  98. package/src/publish/publisher.ts +913 -0
  99. package/src/publish/source.ts +272 -0
  100. package/src/publish/tar.ts +110 -0
  101. package/src/registry/index.ts +481 -0
  102. package/src/registry/store.ts +136 -0
  103. package/src/secrets/index.ts +223 -0
  104. package/src/service/idle.ts +64 -0
  105. package/src/service/index.ts +3 -0
  106. package/src/service/unit.ts +250 -0
  107. package/src/verify/fields.ts +125 -0
  108. package/src/verify/index.ts +913 -0
  109. package/src/verify/regression.ts +157 -0
  110. package/src/verify/runner.ts +230 -0
  111. package/src/verify/sandbox.ts +407 -0
  112. package/src/verify/typecheck.ts +371 -0
  113. package/src/workers/index.ts +17 -0
  114. package/src/workers/launcher.ts +260 -0
  115. package/src/workers/pool.ts +708 -0
@@ -0,0 +1,281 @@
1
+ /**
2
+ * Addressing (D21, D38, D70, D99): where the instance is reachable. It decides the bind address
3
+ * and the URL host, forms each listener's origin and its exact `Host` allowlist, leases a stable
4
+ * port per home for the shell and for each artifact, binds servers to their leased ports (leasing
5
+ * a new one when another program took it), and picks the frame-session mode for a shell and
6
+ * artifact origin pair. The gateway decides what is served on those ports.
7
+ *
8
+ * ```ts
9
+ * const addressing = createAddressing({ ledger, log, bind: { address: "127.0.0.1" } });
10
+ * const port = await addressing.listen(server, { purpose: "artifact", owner: artifactId });
11
+ * addressing.origin(port); // "http://127.0.0.1:23457"
12
+ * ```
13
+ */
14
+ import { randomInt } from "node:crypto";
15
+ import type { Server } from "node:net";
16
+ import { isIP } from "node:net";
17
+ import { createDiagnostic, RpcError } from "@mostra/protocol";
18
+ import type { Ledger } from "../ledger/index.ts";
19
+ import type { Log } from "../log.ts";
20
+
21
+ /** The lowest port Mostra leases: below every ephemeral range (D99). */
22
+ export const LEASE_FIRST_PORT = 20000;
23
+ /** The highest port Mostra leases: Linux's ephemeral range starts at 32768, macOS's at 49152. */
24
+ export const LEASE_LAST_PORT = 32767;
25
+ /** How many free ports to try before giving up on a lease. */
26
+ const LEASE_ATTEMPTS = 64;
27
+
28
+ /** What a lease is for (DATA_MODEL §3 `port_lease.purpose`). */
29
+ export type LeasePurpose = "shell" | "artifact" | "demo";
30
+
31
+ /** Who holds a lease: the shell, an artifact ID, or a demo. */
32
+ export interface LeaseOwner {
33
+ readonly purpose: LeasePurpose;
34
+ /** `shell` for the shell; the artifact ID for an artifact. */
35
+ readonly owner: string;
36
+ }
37
+
38
+ /** How the gateway binds (D99). */
39
+ export interface BindOptions {
40
+ /** The address to listen on; `127.0.0.1` unless `--bind` names another. */
41
+ readonly address: string;
42
+ /** The host name URLs use and the Host allowlist accepts; required for a wildcard address. */
43
+ readonly urlHost?: string;
44
+ }
45
+
46
+ /** How a frame authenticates for one shell and artifact origin pair (D70, D98). */
47
+ export type FrameMode = "cookie" | "worker";
48
+
49
+ /** Where the instance is reachable. */
50
+ export interface Addressing {
51
+ /** The address every listener binds. */
52
+ readonly bindAddress: string;
53
+ /** The host name in every URL, bracketed when it is an IPv6 literal. */
54
+ readonly urlHost: string;
55
+ /** The origin a listener on `port` serves: `http://<url host>:<port>`. */
56
+ origin(port: number): string;
57
+ /** The exact `Host` values a listener on `port` accepts, lowercase. */
58
+ hosts(port: number): readonly string[];
59
+ /** The leased port of an owner, if it has one. */
60
+ leased(owner: LeaseOwner): number | undefined;
61
+ /** Every lease, for binding them all at start. */
62
+ leases(): readonly (LeaseOwner & { readonly port: number })[];
63
+ /**
64
+ * Binds `server` to the owner's leased port, or to a newly leased one when it has none or
65
+ * another program holds it (`MOSTRA_ENV_PORT_TAKEN`). Resolves with the bound port.
66
+ */
67
+ listen(server: Server, owner: LeaseOwner): Promise<number>;
68
+ /**
69
+ * The frame-session mode for a shell and artifact origin pair: cookie mode when they share a
70
+ * host (same site, D38), worker mode otherwise (cross-site, D70).
71
+ */
72
+ frameMode(shellOrigin: string, artifactOrigin: string): FrameMode;
73
+ }
74
+
75
+ /** The unspecified addresses, as {@link authorityHost} writes them: each listens everywhere. */
76
+ const WILDCARDS = new Set(["0.0.0.0", "[::]", "[::ffff:0:0]"]);
77
+
78
+ function bindFailed(message: string): RpcError {
79
+ return new RpcError(createDiagnostic("MOSTRA_ENV_BIND_FAILED", { message }));
80
+ }
81
+
82
+ /**
83
+ * Validates the bind flags (D99) and returns the address and URL host. A wildcard address needs
84
+ * `urlHost`; `urlHost` alone, without a wider bind, is refused, so a URL never names a host the
85
+ * gateway doesn't listen on.
86
+ */
87
+ export function resolveBind(options: {
88
+ readonly bind?: string | undefined;
89
+ readonly urlHost?: string | undefined;
90
+ }): BindOptions {
91
+ const address = options.bind ?? "127.0.0.1";
92
+ const bare = address.replace(/^\[(.*)\]$/, "$1");
93
+ if (isIP(bare) === 0) {
94
+ throw bindFailed(`--bind takes an IP address, such as 127.0.0.1 or 0.0.0.0, not "${address}".`);
95
+ }
96
+ if (options.urlHost !== undefined && options.bind === undefined) {
97
+ throw bindFailed("--url-host needs --bind: without it the gateway listens on 127.0.0.1 only.");
98
+ }
99
+ // Compared in canonical form, so `0:0:0:0:0:0:0:0`, `::0` and `::ffff:0.0.0.0` count too.
100
+ if (WILDCARDS.has(authorityHost(bare)) && options.urlHost === undefined) {
101
+ throw bindFailed(
102
+ `--bind ${address} listens on every interface; name the host viewers use with --url-host.`,
103
+ );
104
+ }
105
+ if (
106
+ options.urlHost !== undefined &&
107
+ !/^(\[[0-9a-f:.]+\]|[a-z0-9.-]+|[0-9a-f:]+)$/i.test(options.urlHost)
108
+ ) {
109
+ throw bindFailed(`--url-host takes a host name or an IP address, not "${options.urlHost}".`);
110
+ }
111
+ if (options.urlHost !== undefined) {
112
+ try {
113
+ authorityHost(options.urlHost);
114
+ } catch {
115
+ throw bindFailed(`--url-host takes a host name or an IP address, not "${options.urlHost}".`);
116
+ }
117
+ }
118
+ return { address: bare, ...(options.urlHost !== undefined ? { urlHost: options.urlHost } : {}) };
119
+ }
120
+
121
+ /**
122
+ * A host as browsers write it in `Origin` and `Host`: lowercase, IPv6 compressed and bracketed
123
+ * (`0:0:0:0:0:0:0:1` is `[::1]`). Origins and the Host allowlist use this form, so the exact
124
+ * comparisons agree with what a browser sends however the flag spelled the address.
125
+ */
126
+ function authorityHost(host: string): string {
127
+ const bare = host.replace(/^\[(.*)\]$/, "$1");
128
+ return new URL(`http://${isIP(bare) === 6 ? `[${bare}]` : bare}/`).hostname;
129
+ }
130
+
131
+ /**
132
+ * Binds `server` to `port` on `address`; resolves `false` when that port is taken. Every other
133
+ * failure is about the address, so no port would do: it is `MOSTRA_ENV_BIND_FAILED`.
134
+ */
135
+ function tryListen(server: Server, port: number, address: string): Promise<boolean> {
136
+ return new Promise((resolve, reject) => {
137
+ const onError = (error: NodeJS.ErrnoException): void => {
138
+ server.off("listening", onListening);
139
+ if (error.code === "EADDRINUSE" || error.code === "EACCES") resolve(false);
140
+ else if (error.code === "EADDRNOTAVAIL") {
141
+ reject(bindFailed(`No network interface of this machine has the address ${address}.`));
142
+ } else if (error.code === "EAFNOSUPPORT") {
143
+ reject(
144
+ bindFailed(
145
+ `This machine has no ${isIP(address) === 6 ? "IPv6" : "IPv4"} support for ${address}.`,
146
+ ),
147
+ );
148
+ } else {
149
+ reject(
150
+ bindFailed(`The gateway can't listen on ${address}: ${error.code ?? error.message}.`),
151
+ );
152
+ }
153
+ };
154
+ const onListening = (): void => {
155
+ server.off("error", onError);
156
+ resolve(true);
157
+ };
158
+ server.once("error", onError);
159
+ server.once("listening", onListening);
160
+ server.listen({ port, host: address, exclusive: true });
161
+ });
162
+ }
163
+
164
+ /** Creates the addressing of one instance over its ledger's `port_lease` table. */
165
+ export function createAddressing(options: {
166
+ readonly ledger: Ledger;
167
+ readonly log: Log;
168
+ readonly bind: BindOptions;
169
+ /**
170
+ * Listen on ports the operating system assigns and lease none: a `verify` run's short-lived
171
+ * listeners (D138). Ephemeral ports lie above the lease range (D99), so they never take a port
172
+ * leased to an artifact whose listener isn't bound yet (D132).
173
+ */
174
+ readonly ephemeral?: boolean;
175
+ /** With `ephemeral`: the port the shell listens on instead of one assigned (`mostra dev --port`). */
176
+ readonly shellPort?: number;
177
+ }): Addressing {
178
+ const { ledger, log } = options;
179
+ const bindAddress = options.bind.address;
180
+ const urlHost = authorityHost(options.bind.urlHost ?? bindAddress).toLowerCase();
181
+
182
+ const leased = (owner: LeaseOwner): number | undefined =>
183
+ ledger.read((db) =>
184
+ db.get<{ port: number }>(
185
+ "SELECT port FROM port_lease WHERE purpose = ? AND owner_ref = ?",
186
+ owner.purpose,
187
+ owner.owner,
188
+ ),
189
+ )?.port;
190
+
191
+ const record = (owner: LeaseOwner, port: number): void => {
192
+ ledger.write((db) => {
193
+ db.run(
194
+ "DELETE FROM port_lease WHERE purpose = ? AND owner_ref = ?",
195
+ owner.purpose,
196
+ owner.owner,
197
+ );
198
+ // A port another owner once held, but that this process could bind, is no longer theirs.
199
+ db.run("DELETE FROM port_lease WHERE port = ?", port);
200
+ db.run(
201
+ "INSERT INTO port_lease (port, purpose, owner_ref, leased_at) VALUES (?, ?, ?, ?)",
202
+ port,
203
+ owner.purpose,
204
+ owner.owner,
205
+ new Date().toISOString(),
206
+ );
207
+ });
208
+ };
209
+
210
+ const taken = (): Set<number> =>
211
+ new Set(
212
+ ledger
213
+ .read((db) => db.all<{ port: number }>("SELECT port FROM port_lease"))
214
+ .map((row) => row.port),
215
+ );
216
+
217
+ return {
218
+ bindAddress,
219
+ urlHost,
220
+ origin: (port) => `http://${urlHost}:${port}`,
221
+ hosts: (port) => [`${urlHost}:${port}`],
222
+ leased,
223
+ leases: () =>
224
+ ledger
225
+ .read((db) =>
226
+ db.all<{ port: number; purpose: LeasePurpose; owner_ref: string }>(
227
+ "SELECT port, purpose, owner_ref FROM port_lease ORDER BY purpose DESC, port",
228
+ ),
229
+ )
230
+ .map((row) => ({ port: row.port, purpose: row.purpose, owner: row.owner_ref })),
231
+ async listen(server, owner) {
232
+ if (options.ephemeral) {
233
+ const wanted = owner.purpose === "shell" ? (options.shellPort ?? 0) : 0;
234
+ if (!(await tryListen(server, wanted, bindAddress))) {
235
+ throw bindFailed(
236
+ wanted === 0
237
+ ? `No ephemeral port is free on ${bindAddress}.`
238
+ : `The port ${wanted} on ${bindAddress} is taken.`,
239
+ );
240
+ }
241
+ const address = server.address();
242
+ if (address === null || typeof address === "string") throw new Error("not a TCP listener");
243
+ return address.port;
244
+ }
245
+ const previous = leased(owner);
246
+ if (previous !== undefined) {
247
+ if (await tryListen(server, previous, bindAddress)) return previous;
248
+ log.warn("addressing.port_taken", {
249
+ code: "MOSTRA_ENV_PORT_TAKEN",
250
+ purpose: owner.purpose,
251
+ owner: owner.owner,
252
+ port: previous,
253
+ });
254
+ }
255
+ const others = taken();
256
+ for (let attempt = 0; attempt < LEASE_ATTEMPTS; attempt++) {
257
+ const port = randomInt(LEASE_FIRST_PORT, LEASE_LAST_PORT + 1);
258
+ if (others.has(port)) continue;
259
+ if (!(await tryListen(server, port, bindAddress))) continue;
260
+ record(owner, port);
261
+ if (previous !== undefined) {
262
+ log.warn("addressing.port_released", {
263
+ purpose: owner.purpose,
264
+ owner: owner.owner,
265
+ from: previous,
266
+ to: port,
267
+ });
268
+ }
269
+ return port;
270
+ }
271
+ throw bindFailed(
272
+ `No free port between ${LEASE_FIRST_PORT} and ${LEASE_LAST_PORT} on ${bindAddress} after ${LEASE_ATTEMPTS} attempts.`,
273
+ );
274
+ },
275
+ frameMode(shellOrigin, artifactOrigin) {
276
+ return new URL(shellOrigin).hostname === new URL(artifactOrigin).hostname
277
+ ? "cookie"
278
+ : "worker";
279
+ },
280
+ };
281
+ }
package/src/bin.ts ADDED
@@ -0,0 +1,240 @@
1
+ #!/usr/bin/env node
2
+ import { mkdirSync, realpathSync } from "node:fs";
3
+ import { fileURLToPath } from "node:url";
4
+ /**
5
+ * `mostra-runtime`, the runtime bundle's entry point (D85).
6
+ *
7
+ * mostra-runtime host [--home <dir>] the host protocol over stdio (`mostra host`)
8
+ * mostra-runtime daemon [--home <dir>] [--always-on]
9
+ * the home's daemon on its socket (`mostra daemon start`);
10
+ * it exits after 30 idle minutes unless `--always-on`
11
+ * mostra-runtime service install|uninstall|status [--home <dir>] [--no-start]
12
+ * the home's login service (`mostra daemon install`, D62):
13
+ * one JSON line with the service's file and state
14
+ *
15
+ * Both take `--bind <address>` to serve viewers on an address other than 127.0.0.1, and
16
+ * `--url-host <name>`, the host name links use, which a wildcard address needs (D99). Neither is
17
+ * remembered: every wider start is explicit.
18
+ *
19
+ * `daemon` prints one JSON line on stdout: `{"status":"started",…}` when it took the home,
20
+ * `{"status":"attached",…}` when another daemon already owns it (then it exits 0), or
21
+ * `{"status":"failed","diagnostic":…}` (exit 3). `host` speaks only the protocol on stdout; when it
22
+ * can't start, it answers the host's first request with the diagnostic and exits 3. Logs go to
23
+ * `<home>/logs/supervisor.log`; warnings and errors are mirrored to stderr.
24
+ */
25
+ import { parseArgs } from "node:util";
26
+ import {
27
+ createDiagnostic,
28
+ type Diagnostic,
29
+ encodeLine,
30
+ LineSplitter,
31
+ RpcError,
32
+ RpcPeer,
33
+ } from "@mostra/protocol";
34
+ import { checkPlatform, resolveHomePath } from "./home/index.ts";
35
+ import { type Instance, runtimeVersion, startInstance } from "./instance/index.ts";
36
+ import { installService, serviceStatus, uninstallService } from "./service/index.ts";
37
+
38
+ /** Exit codes, as INTERFACES §9 defines them for the CLI. */
39
+ const EXIT = { ok: 0, failure: 1, usage: 2, environment: 3 } as const;
40
+
41
+ const USAGE = [
42
+ "usage: mostra-runtime <host|daemon> [--home <dir>] [--bind <address> [--url-host <name>]] [--always-on]",
43
+ " mostra-runtime service <install|uninstall|status> [--home <dir>] [--no-start]",
44
+ ].join("\n");
45
+
46
+ // A closed stdout or stderr (a starter that read the ready line and left) must not crash the
47
+ // supervisor.
48
+ process.stdout.on("error", () => {});
49
+ process.stderr.on("error", () => {});
50
+
51
+ const mirror = (line: string): void => {
52
+ process.stderr.write(line);
53
+ };
54
+
55
+ function diagnosticOf(error: unknown): Diagnostic {
56
+ if (error instanceof RpcError) return error.diagnostic;
57
+ return createDiagnostic("MOSTRA_HOST_INTERNAL_ERROR", {
58
+ message: `mostra-runtime failed unexpectedly: ${error instanceof Error ? error.message : String(error)}`,
59
+ });
60
+ }
61
+
62
+ /**
63
+ * In host mode, a supervisor that can't start still speaks the protocol: it answers the host's
64
+ * requests with the diagnostic, then exits once the first is answered or stdin ends.
65
+ */
66
+ function refuseOverStdio(diagnostic: Diagnostic, exitCode: number): void {
67
+ mirror(`${JSON.stringify({ level: "error", diagnostic })}\n`);
68
+ const splitter = new LineSplitter();
69
+ const exit = (): void => {
70
+ process.stdout.write("", () => process.exit(exitCode));
71
+ };
72
+ const peer = new RpcPeer({
73
+ send: (message) => {
74
+ process.stdout.write(encodeLine(message));
75
+ },
76
+ onRequest: () => {
77
+ setImmediate(exit);
78
+ throw new RpcError(diagnostic);
79
+ },
80
+ });
81
+ process.stdin.setEncoding("utf8");
82
+ process.stdin.on("data", (chunk: string) => {
83
+ try {
84
+ for (const line of splitter.push(chunk)) peer.receiveLine(line);
85
+ } catch {
86
+ exit();
87
+ }
88
+ });
89
+ process.stdin.on("end", exit);
90
+ process.stdin.on("error", exit);
91
+ setTimeout(exit, 30_000).unref();
92
+ }
93
+
94
+ function handleSignals(instance: Instance): void {
95
+ for (const signal of ["SIGTERM", "SIGINT"] as const) {
96
+ process.on(signal, () => void instance.stop(signal, EXIT.ok));
97
+ }
98
+ process.on("SIGPIPE", () => {});
99
+ // Last resort: children never outlive an exiting supervisor (FAILURE_MODEL §2).
100
+ process.on("exit", () => {
101
+ for (const child of instance.processes.list()) {
102
+ try {
103
+ process.kill(-child.pid, "SIGKILL");
104
+ } catch {
105
+ // Already gone.
106
+ }
107
+ }
108
+ });
109
+ process.on("uncaughtException", (error) => {
110
+ mirror(`${JSON.stringify({ level: "error", event: "uncaught", message: error.message })}\n`);
111
+ void instance.stop("uncaught exception", EXIT.failure);
112
+ setTimeout(() => process.exit(EXIT.failure), 15_000).unref();
113
+ });
114
+ }
115
+
116
+ async function main(argv: readonly string[]): Promise<number> {
117
+ let parsed: ReturnType<typeof parse>;
118
+ try {
119
+ parsed = parse(argv);
120
+ } catch (error) {
121
+ process.stderr.write(`${(error as Error).message}\n${USAGE}\n`);
122
+ return EXIT.usage;
123
+ }
124
+ const { values, positionals } = parsed;
125
+ if (values.version) {
126
+ process.stdout.write(`${runtimeVersion()}\n`);
127
+ return EXIT.ok;
128
+ }
129
+ const [mode, ...rest] = positionals;
130
+ if (mode === "service" && !values.help)
131
+ return service(rest, values.home, values["no-start"] === true);
132
+ if (values.help || (mode !== "host" && mode !== "daemon") || rest.length > 0) {
133
+ (values.help ? process.stdout : process.stderr).write(`${USAGE}\n`);
134
+ return values.help ? EXIT.ok : EXIT.usage;
135
+ }
136
+
137
+ try {
138
+ const started = await startInstance({
139
+ mode,
140
+ home: values.home,
141
+ bind: values.bind,
142
+ urlHost: values["url-host"],
143
+ alwaysOn: values["always-on"] === true,
144
+ mirror,
145
+ ...(mode === "host" ? { stdio: { input: process.stdin, output: process.stdout } } : {}),
146
+ });
147
+ if (started.kind === "attached") {
148
+ process.stdout.write(
149
+ `${JSON.stringify({
150
+ status: "attached",
151
+ pid: started.record.pid,
152
+ home: started.result.instance.home,
153
+ socket: started.record.socket,
154
+ revision: started.result.revision,
155
+ })}\n`,
156
+ );
157
+ return EXIT.ok;
158
+ }
159
+ const { instance } = started;
160
+ handleSignals(instance);
161
+ if (mode === "daemon") {
162
+ process.stdout.write(
163
+ `${JSON.stringify({
164
+ status: "started",
165
+ pid: instance.info.pid,
166
+ home: instance.info.home,
167
+ socket: instance.socketPath,
168
+ reaped: instance.reaped.filter((child) => child.signalled.length > 0).length,
169
+ })}\n`,
170
+ );
171
+ }
172
+ const stop = await instance.stopped;
173
+ return stop.exitCode;
174
+ } catch (error) {
175
+ const diagnostic = diagnosticOf(error);
176
+ const exitCode = error instanceof RpcError ? EXIT.environment : EXIT.failure;
177
+ if (mode === "host") {
178
+ refuseOverStdio(diagnostic, exitCode);
179
+ return new Promise<number>(() => {});
180
+ }
181
+ process.stdout.write(`${JSON.stringify({ status: "failed", diagnostic })}\n`);
182
+ mirror(`${JSON.stringify({ level: "error", diagnostic })}\n`);
183
+ return exitCode;
184
+ }
185
+ }
186
+
187
+ /** `mostra-runtime service …`: the home's login service, as one JSON line (D62, RT-08). */
188
+ function service(args: readonly string[], home: string | undefined, noStart: boolean): number {
189
+ const [action, ...extra] = args;
190
+ if ((action !== "install" && action !== "uninstall" && action !== "status") || extra.length > 0) {
191
+ process.stderr.write(`${USAGE}\n`);
192
+ return EXIT.usage;
193
+ }
194
+ const gate = checkPlatform();
195
+ if (gate) {
196
+ process.stdout.write(`${JSON.stringify({ status: "failed", diagnostic: gate })}\n`);
197
+ return EXIT.environment;
198
+ }
199
+ try {
200
+ const resolved = resolveHomePath({ home, env: process.env });
201
+ mkdirSync(resolved, { recursive: true, mode: 0o700 });
202
+ const spec = {
203
+ home: realpathSync(resolved),
204
+ node: process.execPath,
205
+ entry: fileURLToPath(import.meta.url),
206
+ };
207
+ const status =
208
+ action === "install"
209
+ ? installService(spec, { noStart })
210
+ : action === "uninstall"
211
+ ? uninstallService(spec, { noStart })
212
+ : serviceStatus(spec);
213
+ process.stdout.write(`${JSON.stringify({ status: "ok", action, service: status })}\n`);
214
+ return EXIT.ok;
215
+ } catch (error) {
216
+ const diagnostic = diagnosticOf(error);
217
+ process.stdout.write(`${JSON.stringify({ status: "failed", diagnostic })}\n`);
218
+ return EXIT.environment;
219
+ }
220
+ }
221
+
222
+ function parse(argv: readonly string[]) {
223
+ return parseArgs({
224
+ args: [...argv],
225
+ allowPositionals: true,
226
+ options: {
227
+ home: { type: "string" },
228
+ bind: { type: "string" },
229
+ "url-host": { type: "string" },
230
+ "always-on": { type: "boolean" },
231
+ "no-start": { type: "boolean" },
232
+ help: { type: "boolean", short: "h" },
233
+ version: { type: "boolean" },
234
+ },
235
+ });
236
+ }
237
+
238
+ const code = await main(process.argv.slice(2));
239
+ // Let stdout drain before exiting, so the status line is never cut off.
240
+ process.stdout.write("", () => process.exit(code));