@mostra/runtime 0.1.0 → 0.3.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 +7 -7
  2. package/dist/bin.js.map +1 -1
  3. package/dist/builder/child/main.js +18 -17
  4. package/dist/builder/child/main.js.map +1 -1
  5. package/dist/{child-xrHmytks.js → child-BQc3arf7.js} +5 -2
  6. package/dist/{child-xrHmytks.js.map → child-BQc3arf7.js.map} +1 -1
  7. package/dist/deps/child/install.js +9 -6
  8. package/dist/deps/child/install.js.map +1 -1
  9. package/dist/files-KxzOxckl.js +674 -0
  10. package/dist/files-KxzOxckl.js.map +1 -0
  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-D7_UVdoN.js → instance-DiKSe7s6.js} +1331 -752
  15. package/dist/instance-DiKSe7s6.js.map +1 -0
  16. package/package.json +5 -5
  17. package/src/bin.ts +4 -10
  18. package/src/builder/child/dev.ts +4 -3
  19. package/src/builder/child/plugins.ts +12 -7
  20. package/src/builder/child/spa.ts +15 -9
  21. package/src/builder/index.ts +3 -6
  22. package/src/deps/child/install.ts +3 -2
  23. package/src/deps/index.ts +21 -16
  24. package/src/deps/warm.ts +3 -16
  25. package/src/faults.ts +9 -2
  26. package/src/gateway/actions.ts +1 -1
  27. package/src/gateway/browser.ts +1 -1
  28. package/src/gateway/capabilities.ts +28 -7
  29. package/src/gateway/identity.ts +101 -0
  30. package/src/gateway/index.ts +96 -6
  31. package/src/home/acquire.ts +27 -11
  32. package/src/home/paths.ts +45 -135
  33. package/src/home/platform.ts +17 -9
  34. package/src/home/record.ts +3 -3
  35. package/src/home/settings.ts +5 -16
  36. package/src/instance/index.ts +73 -12
  37. package/src/interaction/index.ts +4 -0
  38. package/src/interaction/viewers.ts +16 -2
  39. package/src/ledger/index.ts +5 -27
  40. package/src/ledger/migrations.ts +13 -0
  41. package/src/platform/control.ts +409 -0
  42. package/src/platform/directories.ts +212 -0
  43. package/src/platform/environment.ts +64 -0
  44. package/src/platform/files.ts +368 -0
  45. package/src/platform/helper.ts +152 -0
  46. package/src/{processes → platform}/identity.ts +40 -8
  47. package/src/platform/index.ts +46 -0
  48. package/src/platform/launch.ts +373 -0
  49. package/src/processes/child.ts +4 -1
  50. package/src/processes/environment.ts +22 -3
  51. package/src/processes/index.ts +2 -1
  52. package/src/processes/manager.ts +76 -179
  53. package/src/protocol-server/client.ts +19 -18
  54. package/src/protocol-server/server.ts +84 -54
  55. package/src/publish/publisher.ts +16 -9
  56. package/src/publish/source.ts +7 -4
  57. package/src/registry/store.ts +7 -65
  58. package/src/secrets/index.ts +3 -3
  59. package/src/service/unit.ts +3 -2
  60. package/src/verify/index.ts +5 -3
  61. package/src/verify/typecheck.ts +3 -2
  62. package/src/workers/launcher.ts +3 -1
  63. package/dist/instance-D7_UVdoN.js.map +0 -1
  64. package/dist/types-NjNy7gXX.js +0 -57
  65. package/dist/types-NjNy7gXX.js.map +0 -1
@@ -24,6 +24,7 @@ import {
24
24
  type JsonRpcParams,
25
25
  type MostraInitializeResult,
26
26
  type PortTrustedControlsActivatedParams,
27
+ portIdentityResolveMethod,
27
28
  portSecretsGetMethod,
28
29
  portTrustedControlsActivatedMethod,
29
30
  portTrustedControlsPolicyMethod,
@@ -56,7 +57,9 @@ import {
56
57
  controlsPolicy,
57
58
  createGateway,
58
59
  type Gateway,
60
+ IDENTITY_TIMEOUT_MS,
59
61
  locateShell,
62
+ resolveIdentity,
60
63
  } from "../gateway/index.ts";
61
64
  import { createGc, gcMethods } from "../gc/index.ts";
62
65
  import {
@@ -78,6 +81,7 @@ import {
78
81
  } from "../interaction/index.ts";
79
82
  import { createLive, type LatestLive, liveMethods } from "../live/index.ts";
80
83
  import type { Environment, Log } from "../log.ts";
84
+ import { helperPath, type LaunchPipe } from "../platform/index.ts";
81
85
  import {
82
86
  artifactEnvironment,
83
87
  openProcessManager,
@@ -205,6 +209,15 @@ export function runtimeVersion(): string {
205
209
 
206
210
  const CLIENT: ClientInfo = { name: "mostra-runtime", version: "" };
207
211
 
212
+ /** Every port this instance calls when a client registers it (`capabilities.ports`). */
213
+ export const SUPPORTED_PORTS: readonly string[] = [
214
+ "identity",
215
+ "submissions",
216
+ "drafts",
217
+ "trustedControls",
218
+ "secrets",
219
+ ];
220
+
208
221
  /**
209
222
  * Starts an instance for a home (RT-06): the platform gate, then the home's lock, migrations,
210
223
  * reaping, the socket and `instance.json`. A daemon starter that finds the home owned attaches
@@ -383,6 +396,11 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
383
396
  });
384
397
  return verifier;
385
398
  };
399
+ // The hosts that always provide a port (`HomeConfig.ports`, D105), by client name.
400
+ const expectedOwners = (port: string): string[] =>
401
+ Object.entries(readHomeSettings(home.path).expectedPorts ?? {})
402
+ .filter(([, ports]) => ports.includes(port))
403
+ .map(([owner]) => owner);
386
404
  // The gateway (WP-05): leased ports, capability links and sessions, static versions.
387
405
  const clockOffset = testClockOffset(environment["MOSTRA_TEST_CLOCK_OFFSET_MS"], log);
388
406
  const addressing = createAddressing({
@@ -608,10 +626,7 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
608
626
  artifact,
609
627
  log,
610
628
  home: () => readHomeSettings(home.path).submitChannels,
611
- expected: () =>
612
- Object.entries(readHomeSettings(home.path).expectedPorts ?? {})
613
- .filter(([, ports]) => ports.includes("trustedControls"))
614
- .map(([owner]) => owner),
629
+ expected: () => expectedOwners("trustedControls"),
615
630
  registrant: () => server.registrants("trustedControls").at(-1),
616
631
  call: (session, params) =>
617
632
  server.callSession(
@@ -621,6 +636,27 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
621
636
  CONTROLS_POLICY_TIMEOUT_MS,
622
637
  ),
623
638
  }),
639
+ // Who a browser is, for links without a viewer (D143 item 2).
640
+ identity: (input) =>
641
+ resolveIdentity({
642
+ ...input,
643
+ log,
644
+ // A host that is connected but serves no identity port (it stopped serving one, and its
645
+ // record says it still does) isn't away: the home's default holds (Opus review of
646
+ // WP-12, finding 7).
647
+ expected: () => {
648
+ const connected = server.connectedClients();
649
+ return expectedOwners("identity").filter((owner) => !connected.has(owner));
650
+ },
651
+ registrant: () => server.registrants("identity").at(-1),
652
+ call: (session, params) =>
653
+ server.callSession(
654
+ session,
655
+ portIdentityResolveMethod.method,
656
+ params as JsonRpcParams,
657
+ IDENTITY_TIMEOUT_MS,
658
+ ),
659
+ }),
624
660
  activated: (event) => {
625
661
  // Best effort and never retried, like draft mirrors (D105, D108): the change is durable.
626
662
  for (const registrant of server.registrants("trustedControls")) {
@@ -713,7 +749,9 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
713
749
  if (markHostConfigured(home.path, client.name))
714
750
  log.info("home.host_configured", { client: client.name });
715
751
  },
716
- supportedPorts: ["submissions", "drafts", "trustedControls", "secrets"],
752
+ // The ports this instance calls (D143 item 1); `addressing` arrives with WP-13, `reviews` and
753
+ // `capture` with WP-20, `pty` with WP-23.
754
+ supportedPorts: SUPPORTED_PORTS,
717
755
  notifications: [EVENTS_NOTIFY, ARTIFACT_PROGRESS, DEV_NOTIFY],
718
756
  onInitialized: (session) => interaction.connected(session),
719
757
  onClosed: (session) => interaction.disconnected(session),
@@ -758,7 +796,7 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
758
796
  ...sessionMethods({
759
797
  describe: () => info,
760
798
  startedAt: home.startedAt,
761
- socketPath: () => home.socketPath,
799
+ socketPath: () => server.socketPath ?? home.socketPath,
762
800
  connections: () => server.connections,
763
801
  processes: () => manager.list(),
764
802
  gateway: () =>
@@ -790,7 +828,9 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
790
828
 
791
829
  const instance: Instance = {
792
830
  info,
793
- socketPath: home.socketPath,
831
+ get socketPath() {
832
+ return server.socketPath ?? home.socketPath;
833
+ },
794
834
  processes: manager,
795
835
  reaped,
796
836
  stopped,
@@ -801,7 +841,9 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
801
841
  stopWatchingPublishes();
802
842
  live.stop();
803
843
  interaction.stop();
804
- server.close();
844
+ // Before any child stops: on Windows the pipe's helper is a child, and it hands clients
845
+ // the answers already sent (the `mostra/shutdown` reply among them) before it exits.
846
+ await server.close();
805
847
  await dev.stopAll();
806
848
  await gateway.close();
807
849
  await pool.stopAll();
@@ -828,12 +870,31 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
828
870
  try {
829
871
  await gateway.start();
830
872
  gatewayStarted = true;
831
- await server.listen(home.socketPath, options.checkIntervalMs);
873
+ // On Windows the helper serves the owner-only pipe, as a child like any other (RT-10).
874
+ const launchPipe: LaunchPipe = async (name) => {
875
+ const child = await manager.spawn({
876
+ kind: "control-pipe",
877
+ ownerRef: home.path,
878
+ command: helperPath(),
879
+ args: ["pipe", name],
880
+ channel: true,
881
+ });
882
+ if (!child.channel) throw new Error("The control pipe's helper has no channel.");
883
+ return { channel: child.channel, exited: child.exited, stop: () => child.stop(2000) };
884
+ };
885
+ await server.listen(home.socketPath, options.checkIntervalMs, {
886
+ launchPipe,
887
+ onMoved: (path) => {
888
+ faults.at("endpoint:moved");
889
+ home.publish(options.mode, path);
890
+ log.warn("home.endpoint_moved", { socket: path });
891
+ },
892
+ });
832
893
  // Deliveries pending from before a restart go out again (FAILURE_MODEL §4).
833
894
  interaction.start();
834
895
  // Producers that `always` run, and those hosts subscribe to, start now (LL-04).
835
896
  live.start();
836
- home.publish(options.mode);
897
+ home.publish(options.mode, server.socketPath ?? home.socketPath);
837
898
  // A host-spawned instance marks its home as a host's (D140 item 4).
838
899
  if (options.mode === "host" && markHostConfigured(home.path, "mostra-runtime host"))
839
900
  log.info("home.host_configured", { client: "mostra-runtime host" });
@@ -841,7 +902,7 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
841
902
  // Undo what started before the home is released, so no listener or child outlives it.
842
903
  live.stop();
843
904
  interaction.stop();
844
- server.close();
905
+ await server.close();
845
906
  await gateway.close();
846
907
  await pool.stopAll();
847
908
  await manager.stopAll();
@@ -885,7 +946,7 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
885
946
  log.info("instance.started", {
886
947
  mode: options.mode,
887
948
  pid: process.pid,
888
- socket: home.socketPath,
949
+ socket: server.socketPath ?? home.socketPath,
889
950
  shell: gateway.shellOrigin(),
890
951
  });
891
952
  return instance;
@@ -90,6 +90,7 @@ import {
90
90
  openView,
91
91
  viewControls,
92
92
  viewer,
93
+ viewerForHost,
93
94
  viewerForSpec,
94
95
  viewFor,
95
96
  } from "./viewers.ts";
@@ -154,6 +155,8 @@ export interface Interaction {
154
155
  viewer(viewerId: string): Viewer;
155
156
  /** The viewer for `view/url`'s `viewer`, inside the caller's transaction. */
156
157
  viewerForSpec(db: LedgerDb, spec: ViewerSpec): string;
158
+ /** The viewer a host's identity port named (D143 item 2), in a transaction of its own. */
159
+ viewerForHost(spec: ViewerSpec): string;
157
160
  /** Records a frame load of a version (D104), with the controls in force (D108); returns its ID. */
158
161
  openView(input: {
159
162
  readonly artifactId: string;
@@ -500,6 +503,7 @@ export function createInteraction(options: InteractionOptions): Interaction {
500
503
  },
501
504
  viewer: (viewerId) => ledger.read((db) => viewer(db, viewerId)),
502
505
  viewerForSpec,
506
+ viewerForHost: (spec) => ledger.write((db) => viewerForHost(db, spec)),
503
507
  openView(input) {
504
508
  return ledger.write((db) => openView(db, input));
505
509
  },
@@ -80,8 +80,21 @@ export function localViewerId(db: LedgerDb): string {
80
80
  * a `name` given again replaces the stored one.
81
81
  */
82
82
  export function viewerForSpec(db: LedgerDb, spec: ViewerSpec): string {
83
+ return viewerByRef(db, "token", spec);
84
+ }
85
+
86
+ /**
87
+ * The viewer a host's identity port named (D143 item 2): one viewer of kind `host` per `ref`,
88
+ * kept apart from `view/url`'s viewers, which a host names for links it mints.
89
+ */
90
+ export function viewerForHost(db: LedgerDb, spec: ViewerSpec): string {
91
+ return viewerByRef(db, "host", spec);
92
+ }
93
+
94
+ function viewerByRef(db: LedgerDb, kind: "token" | "host", spec: ViewerSpec): string {
83
95
  const found = db.get<ViewerRow>(
84
- "SELECT * FROM viewer WHERE kind = 'token' AND external_ref = ?",
96
+ "SELECT * FROM viewer WHERE kind = ? AND external_ref = ?",
97
+ kind,
85
98
  spec.ref,
86
99
  );
87
100
  if (found) {
@@ -92,8 +105,9 @@ export function viewerForSpec(db: LedgerDb, spec: ViewerSpec): string {
92
105
  }
93
106
  const id = ViewerId.create();
94
107
  db.run(
95
- "INSERT INTO viewer (id, kind, external_ref, name, created_at) VALUES (?, 'token', ?, ?, ?)",
108
+ "INSERT INTO viewer (id, kind, external_ref, name, created_at) VALUES (?, ?, ?, ?, ?)",
96
109
  id,
110
+ kind,
97
111
  spec.ref,
98
112
  spec.name ?? null,
99
113
  new Date().toISOString(),
@@ -11,22 +11,13 @@
11
11
  * opened.ledger.write((db) => db.run("INSERT INTO child …", …));
12
12
  * ```
13
13
  */
14
- import {
15
- closeSync,
16
- existsSync,
17
- fsyncSync,
18
- linkSync,
19
- mkdirSync,
20
- openSync,
21
- readdirSync,
22
- rmSync,
23
- statSync,
24
- } from "node:fs";
14
+ import { existsSync, linkSync, mkdirSync, readdirSync, rmSync, statSync } from "node:fs";
25
15
  import { createRequire } from "node:module";
26
16
  import { join } from "node:path";
27
17
  import { createDiagnostic, RpcError } from "@mostra/protocol";
28
18
  import type BetterSqlite3 from "better-sqlite3";
29
19
  import type { Log } from "../log.ts";
20
+ import { fsyncPath } from "../platform/index.ts";
30
21
  import { BOOTSTRAP_SQL, MIGRATIONS, type Migration } from "./migrations.ts";
31
22
  import type { LedgerDb, MigrationDb, RunResult, SqlValue } from "./types.ts";
32
23
 
@@ -166,12 +157,7 @@ function createLedgerFile(storeDir: string, file: string, log: Log): void {
166
157
  } finally {
167
158
  db.close();
168
159
  }
169
- const fd = openSync(temp, "r");
170
- try {
171
- fsyncSync(fd);
172
- } finally {
173
- closeSync(fd);
174
- }
160
+ fsyncPath(temp);
175
161
  try {
176
162
  linkSync(temp, file);
177
163
  log.info("ledger.created", { file });
@@ -185,16 +171,8 @@ function createLedgerFile(storeDir: string, file: string, log: Log): void {
185
171
  }
186
172
 
187
173
  function syncDirectory(dir: string): void {
188
- try {
189
- const fd = openSync(dir, "r");
190
- try {
191
- fsyncSync(fd);
192
- } finally {
193
- closeSync(fd);
194
- }
195
- } catch {
196
- // Some file systems can't fsync a directory; the data itself is synced.
197
- }
174
+ // Some file systems can't fsync a directory; the data itself is synced.
175
+ fsyncPath(dir, true);
198
176
  }
199
177
 
200
178
  /**
@@ -580,4 +580,17 @@ export const MIGRATIONS: readonly Migration[] = [
580
580
  `);
581
581
  },
582
582
  },
583
+ {
584
+ version: 10,
585
+ name: "session viewers",
586
+ up(db) {
587
+ // D143 item 2: a link minted without a viewer acts as the person a host's identity port
588
+ // names, decided once when the browser exchanges the link. The session keeps that viewer,
589
+ // and a frame session made from its tickets keeps the same one. NULL: the link's own viewer,
590
+ // or the home's local user.
591
+ db.exec(`
592
+ ALTER TABLE session ADD COLUMN viewer_id TEXT REFERENCES viewer(id);
593
+ `);
594
+ },
595
+ },
583
596
  ];