@mostra/runtime 0.2.0 → 0.4.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 (66) hide show
  1. package/dist/bin.js +23 -12
  2. package/dist/bin.js.map +1 -1
  3. package/dist/builder/child/main.js +20 -18
  4. package/dist/builder/child/main.js.map +1 -1
  5. package/dist/{child-xrHmytks.js → child-Chiavhdx.js} +7 -3
  6. package/dist/child-Chiavhdx.js.map +1 -0
  7. package/dist/deps/child/install.js +9 -6
  8. package/dist/deps/child/install.js.map +1 -1
  9. package/dist/directories-mJ1qlVht.js +322 -0
  10. package/dist/directories-mJ1qlVht.js.map +1 -0
  11. package/dist/files-FygSJIzK.js +388 -0
  12. package/dist/files-FygSJIzK.js.map +1 -0
  13. package/dist/index.d.ts +2 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +2 -2
  16. package/dist/{instance-CzBkUyHu.js → instance-DxcGEQj_.js} +1680 -934
  17. package/dist/instance-DxcGEQj_.js.map +1 -0
  18. package/package.json +5 -5
  19. package/src/bin.ts +18 -16
  20. package/src/builder/child/dev.ts +8 -4
  21. package/src/builder/child/plugins.ts +12 -7
  22. package/src/builder/child/spa.ts +15 -9
  23. package/src/builder/index.ts +3 -6
  24. package/src/deps/child/install.ts +3 -2
  25. package/src/deps/index.ts +21 -16
  26. package/src/deps/warm.ts +3 -16
  27. package/src/dev/index.ts +37 -19
  28. package/src/faults.ts +9 -2
  29. package/src/gateway/capabilities.ts +2 -2
  30. package/src/gateway/listener.ts +36 -0
  31. package/src/home/acquire.ts +27 -11
  32. package/src/home/index.ts +1 -1
  33. package/src/home/paths.ts +45 -135
  34. package/src/home/platform.ts +17 -9
  35. package/src/home/record.ts +3 -3
  36. package/src/home/settings.ts +5 -16
  37. package/src/instance/index.ts +41 -9
  38. package/src/ledger/index.ts +5 -27
  39. package/src/platform/control.ts +409 -0
  40. package/src/platform/directories.ts +212 -0
  41. package/src/platform/environment.ts +64 -0
  42. package/src/platform/files.ts +386 -0
  43. package/src/platform/helper.ts +178 -0
  44. package/src/{processes → platform}/identity.ts +40 -8
  45. package/src/platform/index.ts +53 -0
  46. package/src/platform/launch.ts +373 -0
  47. package/src/processes/child.ts +11 -5
  48. package/src/processes/environment.ts +22 -3
  49. package/src/processes/index.ts +2 -1
  50. package/src/processes/manager.ts +76 -179
  51. package/src/protocol-server/client.ts +19 -18
  52. package/src/protocol-server/server.ts +75 -54
  53. package/src/publish/index.ts +2 -1
  54. package/src/publish/publisher.ts +17 -10
  55. package/src/publish/source.ts +7 -4
  56. package/src/registry/store.ts +7 -65
  57. package/src/secrets/index.ts +2 -2
  58. package/src/service/unit.ts +353 -33
  59. package/src/verify/index.ts +5 -3
  60. package/src/verify/typecheck.ts +3 -2
  61. package/src/workers/launcher.ts +3 -1
  62. package/src/workers/pool.ts +14 -1
  63. package/dist/child-xrHmytks.js.map +0 -1
  64. package/dist/instance-CzBkUyHu.js.map +0 -1
  65. package/dist/types-NjNy7gXX.js +0 -57
  66. package/dist/types-NjNy7gXX.js.map +0 -1
@@ -56,6 +56,41 @@ function writeRaw(
56
56
  ...(extra.headers ?? []),
57
57
  ];
58
58
  socket.end(`${headers.join("\r\n")}\r\n\r\n${body}`);
59
+ lingerAfterRefusal(socket);
60
+ }
61
+
62
+ /** Connections already answered with a refusal: a later parse error on them changes nothing. */
63
+ const refusedSockets = new WeakSet<Duplex>();
64
+
65
+ /** How long a refused connection is read before it is closed regardless. */
66
+ const LINGER_MS = 5000;
67
+ /** How much of a refused request is read and dropped before the connection is closed. */
68
+ const LINGER_BYTES = 16 * 1024 * 1024;
69
+
70
+ /**
71
+ * Reads and drops what the client is still sending after its refusal, until it closes the
72
+ * connection, for at most {@link LINGER_MS} and {@link LINGER_BYTES}. A socket closed with unread
73
+ * bytes is reset, and a reset can reach the client before it read the answer, which it then never
74
+ * sees: on Windows a browser sending a megabyte of cookies got a reset instead of the page that
75
+ * clears them (WP-W2). The answer is already written; this only keeps the connection open long
76
+ * enough for it to be read, as HTTP servers do for a "lingering close".
77
+ */
78
+ function lingerAfterRefusal(socket: Duplex): void {
79
+ refusedSockets.add(socket);
80
+ // Node's HTTP server keeps feeding what arrives to the request parser that just failed, which
81
+ // fails again (a second `clientError`) and ends the connection: from here on this reads alone.
82
+ socket.removeAllListeners("data");
83
+ socket.once("end", () => socket.destroy());
84
+ let read = 0;
85
+ const timer = setTimeout(() => socket.destroy(), LINGER_MS);
86
+ timer.unref();
87
+ socket.once("close", () => clearTimeout(timer));
88
+ socket.on("error", () => socket.destroy());
89
+ socket.on("data", (chunk: Buffer) => {
90
+ read += chunk.length;
91
+ if (read > LINGER_BYTES) socket.destroy();
92
+ });
93
+ socket.resume();
59
94
  }
60
95
 
61
96
  /**
@@ -161,6 +196,7 @@ export function createListener(options: {
161
196
  });
162
197
  // A client that sends something Node can't parse gets a 400 and its connection closed.
163
198
  server.on("clientError", (error: NodeJS.ErrnoException, socket) => {
199
+ if (refusedSockets.has(socket)) return;
164
200
  if (!socket.writable) {
165
201
  socket.destroy();
166
202
  return;
@@ -57,8 +57,13 @@ export interface AcquireHomeOptions {
57
57
  export interface OwnedHome {
58
58
  /** The home's real path. */
59
59
  readonly path: string;
60
+ /**
61
+ * The control endpoint's base: the socket path on POSIX; on Windows the pipe name each bind
62
+ * completes. `instance.json` records the endpoint actually bound.
63
+ */
60
64
  readonly socketPath: string;
61
- readonly runtimeDir: RuntimeDirChoice;
65
+ /** The runtime directory; `undefined` on Windows, which has none. */
66
+ readonly runtimeDir: RuntimeDirChoice | undefined;
62
67
  readonly ledger: Ledger;
63
68
  readonly log: Log;
64
69
  /** Removes secrets and capability material from everything the instance logs or reports. */
@@ -67,8 +72,8 @@ export interface OwnedHome {
67
72
  readonly self: { readonly pid: number; readonly startTime: string };
68
73
  /** When this process took the home (RFC 3339). */
69
74
  readonly startedAt: string;
70
- /** Writes `instance.json`; call it once the socket listens. */
71
- publish(mode: "host" | "daemon"): void;
75
+ /** Writes `instance.json` naming the bound endpoint; call it once it listens, and again when it moves. */
76
+ publish(mode: "host" | "daemon", socket: string): void;
72
77
  /**
73
78
  * Calls `onGone` once with `MOSTRA_HOME_GONE` if the home or its ledger disappears or is
74
79
  * replaced. Checks every `intervalMs`, at most 10 s.
@@ -107,9 +112,15 @@ export async function acquireHome(options: AcquireHomeOptions): Promise<HomeAcqu
107
112
  const home = prepared.realPath;
108
113
  const runtimeDir = resolveRuntimeDir({ env: options.env });
109
114
  // Check the length before creating anything in the runtime directory, then again with its real
110
- // path, which is the one bound (on macOS, /tmp is /private/tmp).
111
- socketPathFor(runtimeDir.dir, home);
112
- const socketPath = socketPathFor(prepareOwnedDirectory(runtimeDir.dir).realPath, home);
115
+ // path, which is the one bound (on macOS, /tmp is /private/tmp). Windows has no runtime
116
+ // directory: its control pipe lives in the system's pipe namespace.
117
+ let socketPath: string;
118
+ if (runtimeDir === undefined) {
119
+ socketPath = socketPathFor(undefined, home);
120
+ } else {
121
+ socketPathFor(runtimeDir.dir, home);
122
+ socketPath = socketPathFor(prepareOwnedDirectory(runtimeDir.dir).realPath, home);
123
+ }
113
124
  const redactor = new Redactor();
114
125
  redactor.protectEnvironment(options.env);
115
126
  const log = openFileLog({
@@ -118,9 +129,9 @@ export async function acquireHome(options: AcquireHomeOptions): Promise<HomeAcqu
118
129
  ...(options.mirror ? { mirror: options.mirror } : {}),
119
130
  });
120
131
  if (prepared.tightenedFrom !== undefined) {
121
- log.warn("home.tightened", { home, from: prepared.tightenedFrom.toString(8), to: "700" });
132
+ log.warn("home.tightened", { home, from: prepared.tightenedFrom, to: "owner only" });
122
133
  }
123
- if (runtimeDir.rejected !== undefined) {
134
+ if (runtimeDir?.rejected !== undefined) {
124
135
  log.warn("home.xdg_runtime_dir_rejected", {
125
136
  reason: runtimeDir.rejected,
126
137
  using: runtimeDir.dir,
@@ -194,8 +205,13 @@ export async function acquireHome(options: AcquireHomeOptions): Promise<HomeAcqu
194
205
 
195
206
  interface OwnInputs {
196
207
  readonly home: string;
208
+ /**
209
+ * The control endpoint's base: the socket path on POSIX; on Windows the pipe name each bind
210
+ * completes. `instance.json` records the endpoint actually bound.
211
+ */
197
212
  readonly socketPath: string;
198
- readonly runtimeDir: RuntimeDirChoice;
213
+ /** The runtime directory; `undefined` on Windows, which has none. */
214
+ readonly runtimeDir: RuntimeDirChoice | undefined;
199
215
  readonly ledger: Ledger;
200
216
  readonly log: Log;
201
217
  readonly redactor: Redactor;
@@ -228,11 +244,11 @@ function own(inputs: OwnInputs): OwnedHome {
228
244
  redactor,
229
245
  self,
230
246
  startedAt,
231
- publish(mode) {
247
+ publish(mode, socket) {
232
248
  writeInstanceRecord(home, {
233
249
  pid: self.pid,
234
250
  startTime: self.startTime,
235
- socket: socketPath,
251
+ socket,
236
252
  runtimeVersion: inputs.options.runtimeVersion,
237
253
  revisions: [...HOST_PROTOCOL_REVISIONS],
238
254
  mode,
package/src/home/index.ts CHANGED
@@ -12,5 +12,5 @@ export {
12
12
  socketPathLimit,
13
13
  } from "./paths.ts";
14
14
  export { checkPlatform, platformName } from "./platform.ts";
15
- export type { InstanceRecord } from "./record.ts";
15
+ export { type InstanceRecord, readLiveInstanceRecord } from "./record.ts";
16
16
  export { markHostConfigured, readHomeSettings, writeHomeSettings } from "./settings.ts";
package/src/home/paths.ts CHANGED
@@ -1,14 +1,25 @@
1
1
  /**
2
- * Where a home and its control socket live (DATA_MODEL §1, D82, D84, D85). Resolving a path never
3
- * touches the file system; preparing a directory creates it with mode 0700, tightens one the user
4
- * owns, and refuses one owned by someone else.
2
+ * Where a home and its control endpoint live (DATA_MODEL §1, D82, D84, D85). Resolving a path never
3
+ * touches the file system; preparing a directory creates it owner-only, tightens one the user
4
+ * owns, and refuses one owned by someone else. The per-system details are the platform layer's.
5
5
  */
6
6
  import { createHash } from "node:crypto";
7
- import { chmodSync, mkdirSync, realpathSync, statSync } from "node:fs";
8
7
  import { homedir } from "node:os";
9
- import { isAbsolute, join, resolve } from "node:path";
10
- import { createDiagnostic, RpcError, VersionId } from "@mostra/protocol";
8
+ import { VersionId } from "@mostra/protocol";
11
9
  import type { Environment } from "../log.ts";
10
+ import {
11
+ controlEndpoint,
12
+ defaultHome,
13
+ socketPathLimit as limitFor,
14
+ OS,
15
+ ownedDirectory,
16
+ type PreparedDirectory,
17
+ pathsOf,
18
+ type RuntimeDirChoice,
19
+ runtimeDirFor,
20
+ } from "../platform/index.ts";
21
+
22
+ export type { PreparedDirectory, RuntimeDirChoice };
12
23
 
13
24
  /** What path resolution reads: the flag, the environment and the platform. */
14
25
  export interface PathInputs {
@@ -27,82 +38,34 @@ const nonEmpty = (value: string | undefined): string | undefined =>
27
38
 
28
39
  /**
29
40
  * The home path, resolved in D84's order: `--home`, then `MOSTRA_HOME`, then the platform default
30
- * (`~/.mostra` on macOS, `${XDG_DATA_HOME:-~/.local/share}/mostra` on Linux). An SDK passes its
31
- * `home` option as `--home`.
41
+ * (`~/.mostra` on macOS, `${XDG_DATA_HOME:-~/.local/share}/mostra` on Linux,
42
+ * `%LOCALAPPDATA%\mostra` on Windows). An SDK passes its `home` option as `--home`.
32
43
  */
33
44
  export function resolveHomePath(inputs: PathInputs): string {
34
45
  const cwd = inputs.cwd ?? process.cwd();
35
46
  const chosen = nonEmpty(inputs.home) ?? nonEmpty(inputs.env["MOSTRA_HOME"]);
36
- if (chosen !== undefined) return resolve(cwd, chosen);
37
- const user = inputs.userHome ?? homedir();
38
- if ((inputs.platform ?? process.platform) === "darwin") return join(user, ".mostra");
39
- const data = nonEmpty(inputs.env["XDG_DATA_HOME"]);
40
- return join(
41
- data !== undefined && isAbsolute(data) ? data : join(user, ".local", "share"),
42
- "mostra",
43
- );
44
- }
45
-
46
- /** What the runtime directory resolution decided, and why. */
47
- export interface RuntimeDirChoice {
48
- readonly dir: string;
49
- /** `override` (MOSTRA_RUNTIME_DIR), `xdg` (the safe XDG runtime directory) or `fallback`. */
50
- readonly source: "override" | "xdg" | "fallback";
51
- /** Why `$XDG_RUNTIME_DIR` wasn't used, when it was set. */
52
- readonly rejected?: string;
53
- }
54
-
55
- /** The current user's ID. */
56
- function uid(): number {
57
- return process.getuid?.() ?? -1;
47
+ if (chosen !== undefined) return pathsOf(inputs.platform ?? OS).resolve(cwd, chosen);
48
+ return defaultHome(inputs.platform ?? OS, inputs.env, inputs.userHome ?? homedir());
58
49
  }
59
50
 
60
51
  /**
61
52
  * The runtime directory for control sockets (D82): `MOSTRA_RUNTIME_DIR`; else `~/.mostra/run` on
62
53
  * macOS; on Linux `$XDG_RUNTIME_DIR/mostra` when `$XDG_RUNTIME_DIR` is a directory the user owns
63
- * that nobody else can read or write, else `${XDG_STATE_HOME:-~/.local/state}/mostra/run`.
54
+ * that nobody else can read or write, else `${XDG_STATE_HOME:-~/.local/state}/mostra/run`. On
55
+ * Windows `undefined`: the control pipe lives in the system's pipe namespace.
64
56
  */
65
- export function resolveRuntimeDir(inputs: Omit<PathInputs, "home">): RuntimeDirChoice {
66
- const override = nonEmpty(inputs.env["MOSTRA_RUNTIME_DIR"]);
67
- if (override !== undefined) {
68
- return { dir: resolve(inputs.cwd ?? process.cwd(), override), source: "override" };
69
- }
70
- const user = inputs.userHome ?? homedir();
71
- if ((inputs.platform ?? process.platform) === "darwin") {
72
- return { dir: join(user, ".mostra", "run"), source: "fallback" };
73
- }
74
- const xdg = nonEmpty(inputs.env["XDG_RUNTIME_DIR"]);
75
- let rejected: string | undefined;
76
- if (xdg !== undefined) {
77
- rejected = unsafeXdgRuntimeDir(xdg);
78
- if (rejected === undefined) return { dir: join(xdg, "mostra"), source: "xdg" };
79
- }
80
- const state = nonEmpty(inputs.env["XDG_STATE_HOME"]);
81
- const base = state !== undefined && isAbsolute(state) ? state : join(user, ".local", "state");
82
- const dir = join(base, "mostra", "run");
83
- return rejected === undefined
84
- ? { dir, source: "fallback" }
85
- : { dir, source: "fallback", rejected };
86
- }
87
-
88
- /** Why `$XDG_RUNTIME_DIR` can't be used, or `undefined` when it can (XDG Base Directory spec). */
89
- function unsafeXdgRuntimeDir(dir: string): string | undefined {
90
- if (!isAbsolute(dir)) return "it isn't an absolute path";
91
- let stats: ReturnType<typeof statSync>;
92
- try {
93
- stats = statSync(dir);
94
- } catch {
95
- return "it doesn't exist";
96
- }
97
- if (!stats.isDirectory()) return "it isn't a directory";
98
- if (stats.uid !== uid()) return "another user owns it";
99
- if ((stats.mode & 0o077) !== 0) return "other users can access it";
100
- return undefined;
57
+ export function resolveRuntimeDir(inputs: Omit<PathInputs, "home">): RuntimeDirChoice | undefined {
58
+ return runtimeDirFor({
59
+ os: inputs.platform ?? OS,
60
+ env: inputs.env,
61
+ userHome: inputs.userHome ?? homedir(),
62
+ cwd: inputs.cwd ?? process.cwd(),
63
+ });
101
64
  }
102
65
 
103
66
  /** The longest control socket path the operating system accepts, in bytes (VERIFIED_FACTS). */
104
- export function socketPathLimit(platform: string = process.platform): number {
105
- return platform === "darwin" ? 103 : 107;
67
+ export function socketPathLimit(platform: string = OS): number {
68
+ return limitFor(platform);
106
69
  }
107
70
 
108
71
  /**
@@ -117,76 +80,23 @@ export function homeHash(realHome: string): string {
117
80
  }
118
81
 
119
82
  /**
120
- * The control socket for a home (D82), named by its {@link homeHash}. Throws
121
- * `MOSTRA_HOME_SOCKET_TOO_LONG` when the path exceeds the limit.
83
+ * The control endpoint for a home (D82), named by its {@link homeHash}: the socket in `runtimeDir`
84
+ * on POSIX, throwing `MOSTRA_HOME_SOCKET_TOO_LONG` past the system's limit; on Windows the pipe
85
+ * name that each bind completes with a random part.
122
86
  */
123
- export function socketPathFor(runtimeDir: string, realHome: string, platform?: string): string {
124
- const hash = homeHash(realHome);
125
- const path = join(runtimeDir, `${hash}.sock`);
126
- const limit = socketPathLimit(platform);
127
- const length = Buffer.byteLength(path);
128
- if (length > limit) {
129
- throw new RpcError(
130
- createDiagnostic("MOSTRA_HOME_SOCKET_TOO_LONG", {
131
- message: `The control socket path ${path} is ${length} bytes; this system allows ${limit}.`,
132
- fix: { kind: "command", command: "export MOSTRA_RUNTIME_DIR=/tmp/mostra-$USER" },
133
- }),
134
- );
135
- }
136
- return path;
137
- }
138
-
139
- /** The outcome of {@link prepareOwnedDirectory}. */
140
- export interface PreparedDirectory {
141
- /** The directory's real path. */
142
- readonly realPath: string;
143
- /** Whether Mostra created it. */
144
- readonly created: boolean;
145
- /** The mode it had when Mostra tightened it to 0700, when it did. */
146
- readonly tightenedFrom?: number;
147
- }
148
-
149
- function notOwned(path: string, why: string): RpcError {
150
- return new RpcError(
151
- createDiagnostic("MOSTRA_HOME_NOT_OWNED", { message: `Mostra can't use ${path}: ${why}.` }),
152
- );
87
+ export function socketPathFor(
88
+ runtimeDir: string | undefined,
89
+ realHome: string,
90
+ platform: string = OS,
91
+ ): string {
92
+ return controlEndpoint(runtimeDir, homeHash(realHome), platform);
153
93
  }
154
94
 
155
95
  /**
156
- * Makes `path` a directory only its owner can use (D85): creates it with mode 0700 when missing,
157
- * tightens one the user owns to 0700, and throws `MOSTRA_HOME_NOT_OWNED` for one owned by
158
- * another user or a path that isn't a directory. Symlinks are followed.
96
+ * Makes `path` a directory only its owner can use (D85): creates it owner-only when missing,
97
+ * tightens one the user owns (mode 0700, or an owner-only access list on Windows), and throws
98
+ * `MOSTRA_HOME_NOT_OWNED` for one owned by another user or a path that isn't a directory.
159
99
  */
160
100
  export function prepareOwnedDirectory(path: string): PreparedDirectory {
161
- try {
162
- return prepare(path);
163
- } catch (error) {
164
- const code = (error as NodeJS.ErrnoException).code;
165
- if (code === "ENOTDIR" || code === "EEXIST")
166
- throw notOwned(path, "a part of the path isn't a directory");
167
- if (code === "EACCES" || code === "EPERM")
168
- throw notOwned(path, "you have no permission to use it");
169
- throw error;
170
- }
171
- }
172
-
173
- function prepare(path: string): PreparedDirectory {
174
- let created = false;
175
- try {
176
- statSync(path);
177
- } catch (error) {
178
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
179
- mkdirSync(path, { recursive: true, mode: 0o700 });
180
- created = true;
181
- }
182
- const realPath = realpathSync(path);
183
- const stats = statSync(realPath);
184
- if (!stats.isDirectory()) throw notOwned(path, "it isn't a directory");
185
- if (stats.uid !== uid()) throw notOwned(path, `it belongs to user ${stats.uid}, not to you`);
186
- const mode = stats.mode & 0o777;
187
- if (mode !== 0o700) {
188
- chmodSync(realPath, 0o700);
189
- return created ? { realPath, created } : { realPath, created, tightenedFrom: mode };
190
- }
191
- return { realPath, created };
101
+ return ownedDirectory(path);
192
102
  }
@@ -1,29 +1,37 @@
1
1
  /**
2
- * The unsupported-platform gate (D35, RT-07). Every entry point calls it before it touches the
3
- * home: Mostra 1.0 runs on macOS and Linux, on x64 and arm64, and fails closed elsewhere.
2
+ * The unsupported-platform gate (D35, D146, RT-07). Every entry point calls it before it touches
3
+ * the home: Mostra runs on macOS and Linux, on x64 and arm64, and fails closed elsewhere. Windows
4
+ * (x64 and arm64) is being built (WP-W1 to WP-W3) and runs only behind the development switch
5
+ * `MOSTRA_DEV_WINDOWS=1`, which only Mostra's own CI sets, so no release exposes a partial port.
6
+ * WP-W3 removes the switch.
4
7
  */
5
8
  import { createDiagnostic, type Diagnostic } from "@mostra/protocol";
9
+ import { OS } from "../platform/index.ts";
6
10
 
7
11
  const OPERATING_SYSTEMS: readonly string[] = ["darwin", "linux"];
8
12
  const ARCHITECTURES: readonly string[] = ["x64", "arm64"];
9
13
 
14
+ /** The development switch that admits Windows until WP-W3 (D146). */
15
+ export const WINDOWS_DEV_SWITCH = "MOSTRA_DEV_WINDOWS";
16
+
10
17
  /** The platform as `<os>-<arch>`, as `InstanceInfo.platform` reports it. */
11
- export function platformName(
12
- platform: string = process.platform,
13
- arch: string = process.arch,
14
- ): string {
18
+ export function platformName(platform: string = OS, arch: string = process.arch): string {
15
19
  return `${platform}-${arch}`;
16
20
  }
17
21
 
18
22
  /**
19
23
  * Returns `MOSTRA_PLATFORM_UNSUPPORTED` for a platform Mostra doesn't run on, or `undefined` for
20
- * a supported one.
24
+ * a supported one. Windows is supported only while `env` sets the development switch to `1`.
21
25
  */
22
26
  export function checkPlatform(
23
- platform: string = process.platform,
27
+ platform: string = OS,
24
28
  arch: string = process.arch,
29
+ env: Readonly<Record<string, string | undefined>> = process.env,
25
30
  ): Diagnostic | undefined {
26
- if (OPERATING_SYSTEMS.includes(platform) && ARCHITECTURES.includes(arch)) return undefined;
31
+ if (ARCHITECTURES.includes(arch)) {
32
+ if (OPERATING_SYSTEMS.includes(platform)) return undefined;
33
+ if (platform === "win32" && env[WINDOWS_DEV_SWITCH] === "1") return undefined;
34
+ }
27
35
  const name =
28
36
  platform === "win32"
29
37
  ? `Windows (${platformName(platform, arch)})`
@@ -4,10 +4,10 @@
4
4
  * atomically after binding its socket and removes it on a clean exit; a record whose PID and
5
5
  * start time match no live process is stale.
6
6
  */
7
- import { readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
7
+ import { readFileSync, rmSync, writeFileSync } from "node:fs";
8
8
  import { join } from "node:path";
9
9
  import * as z from "zod";
10
- import { isSameProcess } from "../processes/index.ts";
10
+ import { isSameProcess, renamePathSync } from "../platform/index.ts";
11
11
 
12
12
  /** The record's file name in the home. */
13
13
  export const INSTANCE_FILE = "instance.json";
@@ -64,7 +64,7 @@ export function writeInstanceRecord(home: string, record: InstanceRecord): void
64
64
  const file = join(home, INSTANCE_FILE);
65
65
  const temp = `${file}.${process.pid}.tmp`;
66
66
  writeFileSync(temp, `${JSON.stringify(record, null, 2)}\n`, { mode: 0o600 });
67
- renameSync(temp, file);
67
+ renamePathSync(temp, file);
68
68
  }
69
69
 
70
70
  /** Removes the record when it is still this process's (a clean exit). */
@@ -6,7 +6,7 @@
6
6
  * Written atomically (a temporary file, then a rename); read fresh by whoever needs a setting, so
7
7
  * a host's change applies to the next request.
8
8
  */
9
- import { closeSync, fsyncSync, openSync, readFileSync, renameSync, writeFileSync } from "node:fs";
9
+ import { readFileSync, writeFileSync } from "node:fs";
10
10
  import { join } from "node:path";
11
11
  import {
12
12
  createDiagnostic,
@@ -15,6 +15,7 @@ import {
15
15
  SubmissionPolicy,
16
16
  } from "@mostra/protocol";
17
17
  import * as z from "zod";
18
+ import { fsyncPath, renamePathSync } from "../platform/index.ts";
18
19
 
19
20
  /** The settings `config.json` holds. Unknown keys are kept, so newer settings survive. */
20
21
  export interface HomeSettings {
@@ -85,21 +86,9 @@ export function writeHomeSettings(home: string, change: HomeSettings): void {
85
86
  const file = join(home, SETTINGS_FILE);
86
87
  const temporary = `${file}.${process.pid}.tmp`;
87
88
  writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
88
- const handle = openSync(temporary, "r");
89
- try {
90
- fsyncSync(handle);
91
- } finally {
92
- closeSync(handle);
93
- }
94
- renameSync(temporary, file);
95
- const dir = openSync(home, "r");
96
- try {
97
- fsyncSync(dir);
98
- } catch {
99
- // Some file systems can't sync a directory; the rename itself is atomic.
100
- } finally {
101
- closeSync(dir);
102
- }
89
+ fsyncPath(temporary);
90
+ renamePathSync(temporary, file);
91
+ fsyncPath(home, true);
103
92
  }
104
93
 
105
94
  /**
@@ -9,7 +9,7 @@
9
9
  * else await started.instance.stopped;
10
10
  * ```
11
11
  */
12
- import { readFileSync, realpathSync, statSync } from "node:fs";
12
+ import { readFileSync, statSync } from "node:fs";
13
13
  import { dirname, join, relative, resolve } from "node:path";
14
14
  import type { Readable, Writable } from "node:stream";
15
15
  import { fileURLToPath } from "node:url";
@@ -81,6 +81,7 @@ import {
81
81
  } from "../interaction/index.ts";
82
82
  import { createLive, type LatestLive, liveMethods } from "../live/index.ts";
83
83
  import type { Environment, Log } from "../log.ts";
84
+ import { helperPath, type LaunchPipe, realPath } from "../platform/index.ts";
84
85
  import {
85
86
  artifactEnvironment,
86
87
  openProcessManager,
@@ -251,9 +252,17 @@ export async function startInstance(options: StartInstanceOptions): Promise<Star
251
252
  }
252
253
 
253
254
  function sameHome(home: string, path: string): boolean {
255
+ // The client's spelling may differ from the instance's: a link, or on Windows a short (8.3)
256
+ // name or another case (the CLI's `%TEMP%` is often `C:\Users\RUNNER~1\…`, WP-W2). The home is
257
+ // its native real path, and so is the client's once resolved: the file system itself spells
258
+ // both, so they compare exactly. Folding case here would join directories the file system keeps
259
+ // apart: a case-sensitive directory's `Home` and `home`, or a name with the Kelvin sign and one
260
+ // with `k`, which NTFS tells apart and JavaScript's lower case doesn't (Opus review of WP-W2,
261
+ // finding 7).
254
262
  try {
255
- return realpathSync(path) === home;
263
+ return realPath(path) === home;
256
264
  } catch {
265
+ // A path that can't be resolved (it doesn't exist) is compared as written.
257
266
  return resolve(path) === home;
258
267
  }
259
268
  }
@@ -795,7 +804,7 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
795
804
  ...sessionMethods({
796
805
  describe: () => info,
797
806
  startedAt: home.startedAt,
798
- socketPath: () => home.socketPath,
807
+ socketPath: () => server.socketPath ?? home.socketPath,
799
808
  connections: () => server.connections,
800
809
  processes: () => manager.list(),
801
810
  gateway: () =>
@@ -827,7 +836,9 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
827
836
 
828
837
  const instance: Instance = {
829
838
  info,
830
- socketPath: home.socketPath,
839
+ get socketPath() {
840
+ return server.socketPath ?? home.socketPath;
841
+ },
831
842
  processes: manager,
832
843
  reaped,
833
844
  stopped,
@@ -838,7 +849,9 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
838
849
  stopWatchingPublishes();
839
850
  live.stop();
840
851
  interaction.stop();
841
- server.close();
852
+ // Before any child stops: on Windows the pipe's helper is a child, and it hands clients
853
+ // the answers already sent (the `mostra/shutdown` reply among them) before it exits.
854
+ await server.close();
842
855
  await dev.stopAll();
843
856
  await gateway.close();
844
857
  await pool.stopAll();
@@ -865,12 +878,31 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
865
878
  try {
866
879
  await gateway.start();
867
880
  gatewayStarted = true;
868
- await server.listen(home.socketPath, options.checkIntervalMs);
881
+ // On Windows the helper serves the owner-only pipe, as a child like any other (RT-10).
882
+ const launchPipe: LaunchPipe = async (name) => {
883
+ const child = await manager.spawn({
884
+ kind: "control-pipe",
885
+ ownerRef: home.path,
886
+ command: helperPath(),
887
+ args: ["pipe", name],
888
+ channel: true,
889
+ });
890
+ if (!child.channel) throw new Error("The control pipe's helper has no channel.");
891
+ return { channel: child.channel, exited: child.exited, stop: () => child.stop(2000) };
892
+ };
893
+ await server.listen(home.socketPath, options.checkIntervalMs, {
894
+ launchPipe,
895
+ onMoved: (path) => {
896
+ faults.at("endpoint:moved");
897
+ home.publish(options.mode, path);
898
+ log.warn("home.endpoint_moved", { socket: path });
899
+ },
900
+ });
869
901
  // Deliveries pending from before a restart go out again (FAILURE_MODEL §4).
870
902
  interaction.start();
871
903
  // Producers that `always` run, and those hosts subscribe to, start now (LL-04).
872
904
  live.start();
873
- home.publish(options.mode);
905
+ home.publish(options.mode, server.socketPath ?? home.socketPath);
874
906
  // A host-spawned instance marks its home as a host's (D140 item 4).
875
907
  if (options.mode === "host" && markHostConfigured(home.path, "mostra-runtime host"))
876
908
  log.info("home.host_configured", { client: "mostra-runtime host" });
@@ -878,7 +910,7 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
878
910
  // Undo what started before the home is released, so no listener or child outlives it.
879
911
  live.stop();
880
912
  interaction.stop();
881
- server.close();
913
+ await server.close();
882
914
  await gateway.close();
883
915
  await pool.stopAll();
884
916
  await manager.stopAll();
@@ -922,7 +954,7 @@ async function assemble(home: OwnedHome, options: StartInstanceOptions): Promise
922
954
  log.info("instance.started", {
923
955
  mode: options.mode,
924
956
  pid: process.pid,
925
- socket: home.socketPath,
957
+ socket: server.socketPath ?? home.socketPath,
926
958
  shell: gateway.shellOrigin(),
927
959
  });
928
960
  return instance;
@@ -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
  /**