@mostra/runtime 0.8.0 → 0.10.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 (65) hide show
  1. package/dist/bin.js +2879 -8
  2. package/dist/bin.js.map +1 -1
  3. package/dist/builder/child/main.js +2 -2
  4. package/dist/{child-Chiavhdx.js → child-BmNZ4a70.js} +2 -2
  5. package/dist/{child-Chiavhdx.js.map → child-BmNZ4a70.js.map} +1 -1
  6. package/dist/deps/child/install.js +1 -1
  7. package/dist/{directories-mJ1qlVht.js → directories-BLJjeSPD.js} +5 -5
  8. package/dist/directories-BLJjeSPD.js.map +1 -0
  9. package/dist/{files-FygSJIzK.js → files-DGeWuE4I.js} +2 -2
  10. package/dist/{files-FygSJIzK.js.map → files-DGeWuE4I.js.map} +1 -1
  11. package/dist/index.d.ts +2 -0
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +2 -2
  14. package/dist/{instance-BRfg27Rg.js → instance-FExcyENK.js} +3346 -395
  15. package/dist/instance-FExcyENK.js.map +1 -0
  16. package/package.json +7 -5
  17. package/src/actions/index.ts +163 -10
  18. package/src/bin.ts +78 -1
  19. package/src/gateway/actions.ts +20 -4
  20. package/src/gateway/browser.ts +118 -95
  21. package/src/gateway/capabilities.ts +15 -6
  22. package/src/gateway/index.ts +112 -15
  23. package/src/gateway/routes.ts +15 -7
  24. package/src/gc/index.ts +14 -0
  25. package/src/instance/index.ts +41 -2
  26. package/src/interaction/ephemeral.ts +32 -23
  27. package/src/interaction/events.ts +21 -1
  28. package/src/interaction/imports.ts +317 -0
  29. package/src/interaction/index.ts +172 -19
  30. package/src/interaction/outbox.ts +9 -0
  31. package/src/interaction/results.ts +22 -1
  32. package/src/interaction/runs.ts +52 -2
  33. package/src/interaction/submissions.ts +17 -1
  34. package/src/interaction/tally.ts +129 -0
  35. package/src/ledger/index.ts +104 -9
  36. package/src/ledger/migrations.ts +183 -0
  37. package/src/ledger/types.ts +8 -0
  38. package/src/link/binding.ts +289 -0
  39. package/src/link/hosted.ts +65 -0
  40. package/src/link/http.ts +136 -0
  41. package/src/link/index.ts +8 -0
  42. package/src/link/manager.ts +1385 -0
  43. package/src/link/relay.ts +512 -0
  44. package/src/live/index.ts +112 -2
  45. package/src/platform/filesystems.ts +78 -0
  46. package/src/platform/index.ts +1 -0
  47. package/src/protocol-server/index.ts +18 -1
  48. package/src/protocol-server/server.ts +38 -7
  49. package/src/protocol-server/websocket.ts +161 -0
  50. package/src/publish/bundle.ts +398 -0
  51. package/src/publish/manifest.ts +9 -0
  52. package/src/publish/methods.ts +12 -1
  53. package/src/publish/publisher.ts +127 -0
  54. package/src/registry/index.ts +35 -14
  55. package/src/server/api.ts +439 -0
  56. package/src/server/auth.ts +613 -0
  57. package/src/server/config.ts +221 -0
  58. package/src/server/data.ts +369 -0
  59. package/src/server/directory.ts +141 -0
  60. package/src/server/hosted.ts +822 -0
  61. package/src/server/index.ts +368 -0
  62. package/src/server/relay.ts +1163 -0
  63. package/src/share/index.ts +110 -6
  64. package/dist/directories-mJ1qlVht.js.map +0 -1
  65. package/dist/instance-BRfg27Rg.js.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mostra/runtime",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "description": "The Mostra runtime: the supervisor that owns a home, its ledger, its child processes and the host protocol server (mostra-runtime host|daemon).",
5
5
  "license": "Apache-2.0",
6
6
  "author": "The Mostra Authors",
@@ -36,7 +36,7 @@
36
36
  "dependencies": {
37
37
  "@hono/node-server": "2.1.5",
38
38
  "@mdx-js/mdx": "3.1.1",
39
- "@mostra/protocol": "0.8.0",
39
+ "@mostra/protocol": "0.10.0",
40
40
  "@tailwindcss/vite": "4.3.3",
41
41
  "@vitejs/plugin-react": "6.1.2",
42
42
  "better-sqlite3": "13.0.3",
@@ -50,18 +50,20 @@
50
50
  "tailwindcss": "4.3.3",
51
51
  "typescript": "7.0.2",
52
52
  "vite": "8.3.4",
53
+ "ws": "8.22.0",
53
54
  "yaml": "2.9.1",
54
55
  "zod": "4.6.7"
55
56
  },
56
57
  "devDependencies": {
57
- "@mostra/shell": "0.8.0",
58
+ "@mostra/shell": "0.10.0",
58
59
  "@mostra/tools": "0.0.0",
59
- "@mostra/verify": "0.8.0",
60
+ "@mostra/verify": "0.10.0",
60
61
  "@mostra/warm": "0.0.0",
61
- "@mostra/worker": "0.8.0",
62
+ "@mostra/worker": "0.10.0",
62
63
  "@types/better-sqlite3": "9.6.0",
63
64
  "@types/node": "24.19.2",
64
65
  "@types/semver": "7.8.0",
66
+ "@types/ws": "8.18.2",
65
67
  "fast-check": "4.10.2",
66
68
  "playwright": "1.64.1",
67
69
  "tsdown": "0.23.1",
@@ -62,8 +62,32 @@ export interface ActionsOptions {
62
62
  /** Told about each refused function, for the verdict's `skippedActions`. */
63
63
  readonly skipped: (fnId: string) => void;
64
64
  };
65
+ /**
66
+ * A hosted artifact's shared state, which lives on its hosted home (D165 item 1): server code's
67
+ * `state` reads and writes it there, refused with `MOSTRA_REMOTE_UNREACHABLE` when it can't be
68
+ * reached, never applied here alone. `undefined` for an artifact that isn't hosted.
69
+ */
70
+ readonly hostedState?: (artifactId: string) => HostedState | undefined;
65
71
  }
66
72
 
73
+ /** A hosted artifact's shared state on its hosted home. */
74
+ export interface HostedState {
75
+ get(ids: readonly string[] | undefined): Promise<unknown>;
76
+ patch(input: {
77
+ readonly ops: unknown;
78
+ readonly mutationId?: string | undefined;
79
+ readonly baseRevision?: string | undefined;
80
+ readonly runId?: string | undefined;
81
+ }): Promise<unknown>;
82
+ }
83
+
84
+ /** Where a relayed run's or call's signals and host events go: its hosted home (D165 item 4). */
85
+ export type RelayedEffect = (
86
+ kind: "signal" | "emit",
87
+ name: string,
88
+ payload: unknown,
89
+ ) => Promise<string>;
90
+
67
91
  /** Plain calls and action runs, and the bridge workers ask through. */
68
92
  export interface Actions {
69
93
  /**
@@ -105,6 +129,51 @@ export interface Actions {
105
129
  recover(): void;
106
130
  /** How many runs and calls are in flight: the daemon stays while any are (D62). */
107
131
  activity(): number;
132
+ /**
133
+ * Runs a relayed run a hosted home recorded and this instance recorded under the same ID
134
+ * (D165 item 4), in this instance's pool with its secrets, telling `observer` what it does so
135
+ * the owner's link reports it back. Starts nothing for a run that is running or has ended.
136
+ */
137
+ runRelayed(runId: string, extra: RelayedRun): void;
138
+ /** Cancels a relayed run: its `abortSignal` fires if it runs (AC-04). */
139
+ cancelRelayed(runId: string): void;
140
+ /** A relayed plain call (D165 item 4): no record, its lines as they come. */
141
+ callRelayed(
142
+ input: {
143
+ readonly versionId: string;
144
+ readonly fnId: string;
145
+ readonly args: Batches;
146
+ readonly viewer?: { readonly id: string; readonly name?: string } | undefined;
147
+ readonly viewId?: string | undefined;
148
+ readonly effect?: RelayedEffect | undefined;
149
+ },
150
+ signal: AbortSignal,
151
+ ): Promise<AsyncIterable<CallLine>>;
152
+ }
153
+
154
+ /** What a relayed run's execution tells the owner's link (D165 item 4). */
155
+ export interface RunObserver {
156
+ /** Its worker has it. */
157
+ running(): void;
158
+ /** What it produced since the last flush, as kept. */
159
+ output(flush: {
160
+ readonly logFrom: number;
161
+ readonly log: readonly string[];
162
+ readonly batchFrom: number;
163
+ readonly batches: Batches;
164
+ readonly progress?: RunProgress;
165
+ }): void;
166
+ /** How it ended. */
167
+ ended(state: RunState): void;
168
+ }
169
+
170
+ /** A relayed run's context: the hosted viewer server code sees, and who hears of its output. */
171
+ export interface RelayedRun {
172
+ readonly viewer?: { readonly id: string; readonly name?: string } | undefined;
173
+ readonly viewId?: string | undefined;
174
+ readonly observer: RunObserver;
175
+ /** Where its signals and host events go. */
176
+ readonly effect?: RelayedEffect;
108
177
  }
109
178
 
110
179
  /** A run this instance is executing. */
@@ -129,6 +198,9 @@ export function createActions(options: ActionsOptions): Actions {
129
198
  const callRuns = new Map<string, string>();
130
199
  /** Why a run's worker stopped under it, until its `execute` ends it. */
131
200
  const crashCauses = new Map<string, string>();
201
+ /** Where relayed runs' and calls' effects go: by run ID, and by worker call ID. */
202
+ const runEffects = new Map<string, RelayedEffect>();
203
+ const callEffects = new Map<string, RelayedEffect>();
132
204
  let calls = 0;
133
205
 
134
206
  const redact = (text: string): string => options.redactor.redact(text);
@@ -191,7 +263,9 @@ export function createActions(options: ActionsOptions): Actions {
191
263
  bus.publishRun(artifactId, { kind: "run", run });
192
264
 
193
265
  /** Runs a recorded run in its version's worker, writing its output as it comes. */
194
- const execute = async (row: RunRow): Promise<void> => {
266
+ const execute = async (row: RunRow, relayed?: RelayedRun): Promise<void> => {
267
+ const observer = relayed?.observer;
268
+ if (relayed?.effect) runEffects.set(row.id, relayed.effect);
195
269
  const entry: Executing = { cancelled: false };
196
270
  executing.set(row.id, entry);
197
271
  let pendingLines: string[] = [];
@@ -217,6 +291,13 @@ export function createActions(options: ActionsOptions): Actions {
217
291
  pendingProgress = undefined;
218
292
  const written = interaction.runOutput(row.id, output);
219
293
  if (!written) return;
294
+ observer?.output({
295
+ logFrom: written.logFrom,
296
+ log: written.log,
297
+ batchFrom: written.batchFrom,
298
+ batches: written.batches,
299
+ ...(progress ? { progress } : {}),
300
+ });
220
301
  publish(row.artifact_id, {
221
302
  runId: row.id,
222
303
  status: "running",
@@ -242,6 +323,7 @@ export function createActions(options: ActionsOptions): Actions {
242
323
  ...(error ? { error: redactError(error) } : {}),
243
324
  });
244
325
  if (state) {
326
+ observer?.ended(state);
245
327
  publish(row.artifact_id, {
246
328
  runId: row.id,
247
329
  status: state.status,
@@ -283,6 +365,7 @@ export function createActions(options: ActionsOptions): Actions {
283
365
  return;
284
366
  }
285
367
  interaction.runRunning(row.id);
368
+ observer?.running();
286
369
  publish(row.artifact_id, {
287
370
  runId: row.id,
288
371
  status: "running",
@@ -291,7 +374,10 @@ export function createActions(options: ActionsOptions): Actions {
291
374
  batchFrom: 0,
292
375
  batches: [],
293
376
  });
294
- const viewer = row.viewer_id ? interaction.viewer(row.viewer_id) : undefined;
377
+ // A relayed run acts for the hosted home's viewer, who has no row here (D165 item 4).
378
+ const viewer =
379
+ relayed?.viewer ?? (row.viewer_id ? interaction.viewer(row.viewer_id) : undefined);
380
+ const viewId = relayed?.viewId ?? row.view_id ?? undefined;
295
381
  const { callId, outcome } = handle.call(
296
382
  {
297
383
  fnId: row.action,
@@ -299,7 +385,7 @@ export function createActions(options: ActionsOptions): Actions {
299
385
  context: {
300
386
  kind: "run",
301
387
  runId: row.id,
302
- ...(row.view_id ? { viewId: row.view_id } : {}),
388
+ ...(viewId ? { viewId } : {}),
303
389
  ...(viewer
304
390
  ? { viewer: { id: viewer.id, ...(viewer.name ? { name: viewer.name } : {}) } }
305
391
  : {}),
@@ -376,17 +462,24 @@ export function createActions(options: ActionsOptions): Actions {
376
462
  });
377
463
  } finally {
378
464
  executing.delete(row.id);
465
+ runEffects.delete(row.id);
379
466
  }
380
467
  };
381
468
 
382
469
  /** A plain call's lines, from a worker that has it. */
383
470
  async function* stream(
384
- page: PageIdentity,
385
- input: { readonly viewId: string; readonly fnId: string; readonly args: Batches },
471
+ caller: {
472
+ readonly viewer?: { readonly id: string; readonly name?: string } | undefined;
473
+ /** The local viewer whose call raises its signals, if it is one of this home's. */
474
+ readonly viewerId?: string | undefined;
475
+ /** A relayed call's effects go to its hosted home. */
476
+ readonly effect?: RelayedEffect | undefined;
477
+ },
478
+ input: { readonly viewId?: string | undefined; readonly fnId: string; readonly args: Batches },
386
479
  signal: AbortSignal,
387
480
  handle: WorkerHandle,
388
481
  ): AsyncGenerator<CallLine> {
389
- const viewer = interaction.viewer(page.viewerId);
482
+ const viewer = caller.viewer;
390
483
  const queue: CallLine[] = [];
391
484
  let wake: (() => void) | undefined;
392
485
  let size = 0;
@@ -397,11 +490,13 @@ export function createActions(options: ActionsOptions): Actions {
397
490
  args: input.args,
398
491
  context: {
399
492
  kind: "call",
400
- viewId: input.viewId,
401
- viewer: { id: viewer.id, ...(viewer.name ? { name: viewer.name } : {}) },
493
+ ...(input.viewId !== undefined ? { viewId: input.viewId } : {}),
494
+ ...(viewer
495
+ ? { viewer: { id: viewer.id, ...(viewer.name ? { name: viewer.name } : {}) } }
496
+ : {}),
402
497
  dryRun: options.dryRun !== undefined,
403
498
  },
404
- viewerId: page.viewerId,
499
+ ...(caller.viewerId !== undefined ? { viewerId: caller.viewerId } : {}),
405
500
  },
406
501
  {
407
502
  onBatch(batch) {
@@ -419,6 +514,7 @@ export function createActions(options: ActionsOptions): Actions {
419
514
  },
420
515
  );
421
516
  calls += 1;
517
+ if (caller.effect) callEffects.set(callId, caller.effect);
422
518
  const abort = (): void => handle.cancel(callId, "The page went away.");
423
519
  signal.addEventListener("abort", abort, { once: true });
424
520
  let ended: CallLine | undefined;
@@ -485,6 +581,7 @@ export function createActions(options: ActionsOptions): Actions {
485
581
  }
486
582
  } finally {
487
583
  calls -= 1;
584
+ callEffects.delete(callId);
488
585
  signal.removeEventListener("abort", abort);
489
586
  // A reader that stopped early (the response failed) leaves nothing running.
490
587
  if (!ended) handle.cancel(callId, "The page went away.");
@@ -494,6 +591,10 @@ export function createActions(options: ActionsOptions): Actions {
494
591
  const bridge: Actions["bridge"] = {
495
592
  async request(worker, method, params, call) {
496
593
  const runId = call?.context.runId;
594
+ const relayedEffect =
595
+ (runId !== undefined ? runEffects.get(runId) : undefined) ??
596
+ (call ? callEffects.get(call.callId) : undefined);
597
+ const hosted = options.hostedState?.(worker.artifactId);
497
598
  switch (method) {
498
599
  case WORKER_METHODS.secret: {
499
600
  const { name } = ServerSecretParams.parse(params);
@@ -501,6 +602,16 @@ export function createActions(options: ActionsOptions): Actions {
501
602
  }
502
603
  case WORKER_METHODS.signal: {
503
604
  const parsed = ServerSignalParams.parse(params);
605
+ // A relayed run's signal goes to its hosted home, without a secret (AC-06).
606
+ if (relayedEffect) {
607
+ return {
608
+ cursor: await relayedEffect(
609
+ "signal",
610
+ parsed.name,
611
+ redactValue(parsed.payload, options.redactor),
612
+ ),
613
+ };
614
+ }
504
615
  return {
505
616
  cursor: interaction.serverSignal(worker.artifactId, {
506
617
  name: parsed.name,
@@ -518,6 +629,15 @@ export function createActions(options: ActionsOptions): Actions {
518
629
  `${parsed.type.slice(0, 80)} isn't a host event type.`,
519
630
  );
520
631
  }
632
+ if (relayedEffect) {
633
+ return {
634
+ cursor: await relayedEffect(
635
+ "emit",
636
+ parsed.type,
637
+ redactValue(parsed.payload, options.redactor),
638
+ ),
639
+ };
640
+ }
521
641
  return {
522
642
  cursor: interaction.serverEmit(worker.artifactId, {
523
643
  type: parsed.type,
@@ -529,10 +649,19 @@ export function createActions(options: ActionsOptions): Actions {
529
649
  }
530
650
  case WORKER_METHODS.stateGet: {
531
651
  const parsed = ServerStateGetParams.parse(params);
652
+ if (hosted) return hosted.get(parsed.ids);
532
653
  return interaction.serverState(worker.artifactId, parsed.ids);
533
654
  }
534
655
  case WORKER_METHODS.statePatch: {
535
656
  const parsed = ServerStatePatchParams.parse(params);
657
+ if (hosted) {
658
+ return hosted.patch({
659
+ ops: redactValue(parsed.ops, options.redactor),
660
+ mutationId: parsed.mutationId,
661
+ baseRevision: parsed.baseRevision,
662
+ runId,
663
+ });
664
+ }
536
665
  return interaction.serverPatch(worker.artifactId, {
537
666
  ops: redactValue(parsed.ops, options.redactor),
538
667
  ...(parsed.mutationId !== undefined ? { mutationId: parsed.mutationId } : {}),
@@ -554,7 +683,8 @@ export function createActions(options: ActionsOptions): Actions {
554
683
  checkArgs(input.args);
555
684
  const versionId = interaction.viewVersion(page, input.viewId);
556
685
  const handle = await pool.acquire(functionOf(versionId, input.fnId));
557
- return stream(page, input, signal, handle);
686
+ const viewer = interaction.viewer(page.viewerId);
687
+ return stream({ viewer, viewerId: page.viewerId }, input, signal, handle);
558
688
  },
559
689
 
560
690
  startRun(page, input) {
@@ -618,5 +748,28 @@ export function createActions(options: ActionsOptions): Actions {
618
748
  activity() {
619
749
  return executing.size + calls;
620
750
  },
751
+
752
+ runRelayed(runId, relayed) {
753
+ if (executing.has(runId)) return;
754
+ const state = interaction.runState(runId);
755
+ if (!state || (state.status !== "queued" && state.status !== "waiting")) return;
756
+ const row = interaction.runRow(runId);
757
+ if (row) void execute(row, relayed);
758
+ },
759
+
760
+ cancelRelayed(runId) {
761
+ const running = executing.get(runId);
762
+ if (!running) return;
763
+ running.cancelled = true;
764
+ if (running.handle && running.callId) {
765
+ running.handle.cancel(running.callId, "Cancelled from a hosted page.");
766
+ } else running.endNow?.();
767
+ },
768
+
769
+ async callRelayed(input, signal) {
770
+ checkArgs(input.args);
771
+ const handle = await pool.acquire(functionOf(input.versionId, input.fnId));
772
+ return stream({ viewer: input.viewer, effect: input.effect }, input, signal, handle);
773
+ },
621
774
  };
622
775
  }
package/src/bin.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { mkdirSync } from "node:fs";
3
+ import { join } from "node:path";
3
4
  import { fileURLToPath } from "node:url";
4
5
  /**
5
6
  * `mostra-runtime`, the runtime bundle's entry point (D85).
@@ -33,7 +34,10 @@ import {
33
34
  } from "@mostra/protocol";
34
35
  import { checkPlatform, resolveHomePath } from "./home/index.ts";
35
36
  import { type Instance, runtimeVersion, startInstance } from "./instance/index.ts";
36
- import { realPath } from "./platform/index.ts";
37
+ import { openFileLog } from "./log.ts";
38
+ import { readProcess, realPath } from "./platform/index.ts";
39
+
40
+ import { readServerConfig, startServer } from "./server/index.ts";
37
41
  import { installService, serviceStatus, uninstallService } from "./service/index.ts";
38
42
 
39
43
  /** Exit codes, as INTERFACES §9 defines them for the CLI. */
@@ -42,6 +46,7 @@ const EXIT = { ok: 0, failure: 1, usage: 2, environment: 3 } as const;
42
46
  const USAGE = [
43
47
  "usage: mostra-runtime <host|daemon> [--home <dir>] [--bind <address> [--url-host <name>]] [--always-on]",
44
48
  " mostra-runtime service <install|uninstall|status> [--home <dir>] [--no-start]",
49
+ " mostra-runtime server --data <dir> [--config <file>] [--listen <host:port>] [--restored <homeId|all>]",
45
50
  ].join("\n");
46
51
 
47
52
  // A closed stdout or stderr (a starter that read the ready line and left) must not crash the
@@ -135,6 +140,14 @@ async function main(argv: readonly string[]): Promise<number> {
135
140
  const [mode, ...rest] = positionals;
136
141
  if (mode === "service" && !values.help)
137
142
  return await service(rest, values.home, values["no-start"] === true);
143
+ if (mode === "server" && !values.help && rest.length === 0) {
144
+ return await remoteServer({
145
+ data: values.data,
146
+ config: values.config,
147
+ listen: values.listen,
148
+ restored: values.restored ?? [],
149
+ });
150
+ }
138
151
  if (values.help || (mode !== "host" && mode !== "daemon") || rest.length > 0) {
139
152
  (values.help ? process.stdout : process.stderr).write(`${USAGE}\n`);
140
153
  return values.help ? EXIT.ok : EXIT.usage;
@@ -190,6 +203,66 @@ async function main(argv: readonly string[]): Promise<number> {
190
203
  }
191
204
  }
192
205
 
206
+ /**
207
+ * `mostra-runtime server`: the remote server (INTERFACES §18.1). Prints one JSON line on stdout
208
+ * (`{"status":"started","address",…}` or `{"status":"failed","diagnostic"}` with exit 3), then
209
+ * serves until SIGTERM, SIGINT or Ctrl+Break, and stops cleanly: every hosted home is closed and
210
+ * every lock released. Logs go to the data directory's `logs/`.
211
+ */
212
+ async function remoteServer(args: {
213
+ readonly data: string | undefined;
214
+ readonly config: string | undefined;
215
+ readonly listen: string | undefined;
216
+ readonly restored: readonly string[];
217
+ }): Promise<number> {
218
+ if (args.data === undefined) {
219
+ process.stderr.write(`mostra-runtime server needs --data <dir>.\n${USAGE}\n`);
220
+ return EXIT.usage;
221
+ }
222
+ try {
223
+ checkPlatform();
224
+ mkdirSync(args.data, { recursive: true, mode: 0o700 });
225
+ const data = realPath(args.data);
226
+ const config = readServerConfig(args.config, process.env);
227
+ const me = await readProcess(process.pid);
228
+ if (!me) throw new Error("Couldn't read this process's own start time.");
229
+ const log = openFileLog({ dir: join(data, "logs"), mirror });
230
+ const server = await startServer({
231
+ data,
232
+ config,
233
+ ...(args.listen !== undefined ? { listen: args.listen } : {}),
234
+ restored: args.restored,
235
+ runtimeVersion: runtimeVersion(),
236
+ owner: { pid: me.pid, startTime: me.startTime },
237
+ log,
238
+ env: process.env,
239
+ });
240
+ process.stdout.write(
241
+ `${JSON.stringify({ status: "started", pid: process.pid, address: server.address, data })}\n`,
242
+ );
243
+ return await new Promise<number>((resolve) => {
244
+ let stopping = false;
245
+ const stop = (): void => {
246
+ if (stopping) return;
247
+ stopping = true;
248
+ void server.close().then(
249
+ () => resolve(EXIT.ok),
250
+ (error: unknown) => {
251
+ log.error("server.stop_failed", { error });
252
+ resolve(EXIT.failure);
253
+ },
254
+ );
255
+ };
256
+ for (const signal of ["SIGTERM", "SIGINT", "SIGBREAK"] as const) process.on(signal, stop);
257
+ });
258
+ } catch (error) {
259
+ const diagnostic = diagnosticOf(error);
260
+ process.stdout.write(`${JSON.stringify({ status: "failed", diagnostic })}\n`);
261
+ mirror(`${JSON.stringify({ level: "error", diagnostic })}\n`);
262
+ return error instanceof RpcError ? EXIT.environment : EXIT.failure;
263
+ }
264
+ }
265
+
193
266
  /** `mostra-runtime service …`: the home's login service, as one JSON line (D62, RT-08). */
194
267
  async function service(
195
268
  args: readonly string[],
@@ -244,6 +317,10 @@ function parse(argv: readonly string[]) {
244
317
  "no-start": { type: "boolean" },
245
318
  help: { type: "boolean", short: "h" },
246
319
  version: { type: "boolean" },
320
+ data: { type: "string" },
321
+ config: { type: "string" },
322
+ listen: { type: "string" },
323
+ restored: { type: "string", multiple: true },
247
324
  },
248
325
  });
249
326
  }
@@ -45,6 +45,12 @@ const STATUS: Readonly<Record<string, number>> = {
45
45
  MOSTRA_VERIFY_ACTION_SKIPPED: 409,
46
46
  MOSTRA_HOME_DISK_FULL: 507,
47
47
  MOSTRA_HOME_GONE: 503,
48
+ // A hosted page's relay (D165 item 4, INTERFACES §4).
49
+ MOSTRA_REMOTE_OWNER_OFFLINE: 503,
50
+ MOSTRA_REMOTE_QUEUE_FULL: 503,
51
+ MOSTRA_REMOTE_SIGN_IN_REQUIRED: 403,
52
+ MOSTRA_REMOTE_RATE_LIMITED: 429,
53
+ MOSTRA_ACTION_PAUSED: 423,
48
54
  };
49
55
 
50
56
  type Handler = (context: RouteContext) => Response | Promise<Response>;
@@ -61,8 +67,8 @@ export interface ActionRoutes {
61
67
  /** Options for {@link actionRoutes}. */
62
68
  export interface ActionRoutesOptions {
63
69
  readonly interaction: Interaction;
64
- readonly actions: Actions;
65
- readonly live: Live;
70
+ readonly actions: Pick<Actions, "call" | "startRun" | "attach" | "cancel">;
71
+ readonly live: Pick<Live, "read">;
66
72
  readonly log: Log;
67
73
  /** The browser-protocol revisions served. */
68
74
  readonly revisions: readonly string[];
@@ -73,8 +79,18 @@ function answer(diagnostic: Diagnostic, status: number): Response {
73
79
  }
74
80
 
75
81
  function failure(error: unknown): Response {
76
- if (error instanceof RpcError)
77
- return answer(error.diagnostic, STATUS[error.diagnostic.code] ?? 500);
82
+ if (error instanceof RpcError) {
83
+ const status = STATUS[error.diagnostic.code] ?? 500;
84
+ // A refusal that says when to try again (a rate limit) says so in `Retry-After` too.
85
+ const retryAfter = (error as { retryAfter?: unknown }).retryAfter;
86
+ if (typeof retryAfter === "number") {
87
+ return jsonResponse(
88
+ { ...error.diagnostic },
89
+ { status, headers: { "retry-after": String(retryAfter) } },
90
+ );
91
+ }
92
+ return answer(error.diagnostic, status);
93
+ }
78
94
  throw error;
79
95
  }
80
96