@mostra/runtime 0.2.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 (58) 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-CzBkUyHu.js → instance-DiKSe7s6.js} +1148 -737
  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/capabilities.ts +2 -2
  27. package/src/home/acquire.ts +27 -11
  28. package/src/home/paths.ts +45 -135
  29. package/src/home/platform.ts +17 -9
  30. package/src/home/record.ts +3 -3
  31. package/src/home/settings.ts +5 -16
  32. package/src/instance/index.ts +31 -7
  33. package/src/ledger/index.ts +5 -27
  34. package/src/platform/control.ts +409 -0
  35. package/src/platform/directories.ts +212 -0
  36. package/src/platform/environment.ts +64 -0
  37. package/src/platform/files.ts +368 -0
  38. package/src/platform/helper.ts +152 -0
  39. package/src/{processes → platform}/identity.ts +40 -8
  40. package/src/platform/index.ts +46 -0
  41. package/src/platform/launch.ts +373 -0
  42. package/src/processes/child.ts +4 -1
  43. package/src/processes/environment.ts +22 -3
  44. package/src/processes/index.ts +2 -1
  45. package/src/processes/manager.ts +76 -179
  46. package/src/protocol-server/client.ts +19 -18
  47. package/src/protocol-server/server.ts +75 -54
  48. package/src/publish/publisher.ts +16 -9
  49. package/src/publish/source.ts +7 -4
  50. package/src/registry/store.ts +7 -65
  51. package/src/secrets/index.ts +2 -2
  52. package/src/service/unit.ts +3 -2
  53. package/src/verify/index.ts +5 -3
  54. package/src/verify/typecheck.ts +3 -2
  55. package/src/workers/launcher.ts +3 -1
  56. package/dist/instance-CzBkUyHu.js.map +0 -1
  57. package/dist/types-NjNy7gXX.js +0 -57
  58. package/dist/types-NjNy7gXX.js.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mostra/runtime",
3
- "version": "0.2.0",
3
+ "version": "0.3.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.3",
38
38
  "@mdx-js/mdx": "3.1.1",
39
- "@mostra/protocol": "0.2.0",
39
+ "@mostra/protocol": "0.3.0",
40
40
  "@tailwindcss/vite": "4.3.3",
41
41
  "@vitejs/plugin-react": "6.1.1",
42
42
  "better-sqlite3": "13.0.3",
@@ -54,11 +54,11 @@
54
54
  "zod": "4.6.5"
55
55
  },
56
56
  "devDependencies": {
57
- "@mostra/shell": "0.2.0",
57
+ "@mostra/shell": "0.3.0",
58
58
  "@mostra/tools": "0.0.0",
59
- "@mostra/verify": "0.2.0",
59
+ "@mostra/verify": "0.3.0",
60
60
  "@mostra/warm": "0.0.0",
61
- "@mostra/worker": "0.2.0",
61
+ "@mostra/worker": "0.3.0",
62
62
  "@types/better-sqlite3": "9.6.0",
63
63
  "@types/node": "24.19.1",
64
64
  "@types/semver": "7.8.0",
package/src/bin.ts CHANGED
@@ -92,20 +92,14 @@ function refuseOverStdio(diagnostic: Diagnostic, exitCode: number): void {
92
92
  }
93
93
 
94
94
  function handleSignals(instance: Instance): void {
95
- for (const signal of ["SIGTERM", "SIGINT"] as const) {
95
+ // SIGTERM and SIGINT on POSIX; on Windows Ctrl+C and Ctrl+Break reach a console process as
96
+ // SIGINT and SIGBREAK, and everything else stops it over the protocol (`mostra/shutdown`, D87).
97
+ for (const signal of ["SIGTERM", "SIGINT", "SIGBREAK"] as const) {
96
98
  process.on(signal, () => void instance.stop(signal, EXIT.ok));
97
99
  }
98
100
  process.on("SIGPIPE", () => {});
99
101
  // 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
- });
102
+ process.on("exit", () => instance.processes.killAll());
109
103
  process.on("uncaughtException", (error) => {
110
104
  mirror(`${JSON.stringify({ level: "error", event: "uncaught", message: error.message })}\n`);
111
105
  void instance.stop("uncaught exception", EXIT.failure);
@@ -13,7 +13,7 @@
13
13
  * When `pages/`, `"use server"` modules or `live.ts` change, the generated entry is written again.
14
14
  */
15
15
  import { createHash, timingSafeEqual } from "node:crypto";
16
- import { mkdir, readdir, readFile, rm, symlink, writeFile } from "node:fs/promises";
16
+ import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
17
17
  import {
18
18
  createServer as createHttpServer,
19
19
  type IncomingMessage,
@@ -25,6 +25,7 @@ import tailwind from "@tailwindcss/vite";
25
25
  import react from "@vitejs/plugin-react";
26
26
  import { parseSync } from "oxc-parser";
27
27
  import { build, createServer, type Plugin, type ViteDevServer } from "vite";
28
+ import { linkDirectory, pathKey } from "../../platform/index.ts";
28
29
  import type { SupervisorConnection } from "../../processes/index.ts";
29
30
  import {
30
31
  DEV_SECRET_HEADER,
@@ -95,7 +96,7 @@ export async function startDev(
95
96
  await mkdir(generated, { recursive: true });
96
97
  for (const [name, text] of Object.entries(STAGING_FILES)) await writeFile(join(root, name), text);
97
98
  await rm(join(root, "node_modules"), { force: true, recursive: true });
98
- await symlink(request.nodeModules, join(root, "node_modules"), "dir");
99
+ await linkDirectory(request.nodeModules, join(root, "node_modules"));
99
100
  await writeFile(join(generated, "styles.css"), `@import "tailwindcss" source("../source");\n`);
100
101
  await mkdir(request.outDir, { recursive: true });
101
102
  // Vite's pre-bundled dependencies live in the session's root (`cacheDir` below); they are
@@ -114,7 +115,7 @@ export async function startDev(
114
115
  const refreshServerModules = (): void => {
115
116
  serverModules.clear();
116
117
  for (const [module, entries] of scan.serverModules)
117
- serverModules.set(join(sourceDir, module), entries);
118
+ serverModules.set(pathKey(join(sourceDir, module)), entries);
118
119
  };
119
120
  refreshServerModules();
120
121
  const writeEntry = async (): Promise<void> => {
@@ -10,6 +10,7 @@ import { compile } from "@mdx-js/mdx";
10
10
  import remarkFrontmatter from "remark-frontmatter";
11
11
  import remarkGfm from "remark-gfm";
12
12
  import type { Plugin } from "vite";
13
+ import { isUnder, pathKey } from "../../platform/index.ts";
13
14
  import type { ServerFunctionEntry } from "../types.ts";
14
15
  import { SCRIPT, startsWithUseServer } from "./scan.ts";
15
16
 
@@ -54,7 +55,7 @@ export function fieldHookUsePlugin(
54
55
  uses: FieldHookUse[],
55
56
  ): Plugin {
56
57
  const inside = (file: string, dir: string | undefined): boolean =>
57
- dir !== undefined && (file === dir || file.startsWith(`${dir}/`));
58
+ dir !== undefined && isUnder(file, dir);
58
59
  return {
59
60
  name: "mostra:field-hook-use",
60
61
  enforce: "pre",
@@ -68,7 +69,8 @@ export function fieldHookUsePlugin(
68
69
  inside(file, roots.runtimeDir)
69
70
  )
70
71
  return null;
71
- if (!uses.some((use) => use.importer === file)) uses.push({ importer: file });
72
+ if (!uses.some((use) => pathKey(use.importer) === pathKey(file)))
73
+ uses.push({ importer: file });
72
74
  return null;
73
75
  },
74
76
  };
@@ -92,7 +94,8 @@ const STUB_PREFIX = "\0mostra-server-reference:";
92
94
 
93
95
  /**
94
96
  * Replaces `"use server"` modules with their client stubs. `modules` maps each module's absolute
95
- * path to its exports, from the scan.
97
+ * path, as its {@link pathKey}, to its exports, from the scan: bundlers spell Windows paths with
98
+ * `/`, the file system with `\\`.
96
99
  */
97
100
  export function serverClientStubPlugin(
98
101
  modules: ReadonlyMap<string, readonly ServerFunctionEntry[]>,
@@ -107,7 +110,9 @@ export function serverClientStubPlugin(
107
110
  if (source.startsWith(STUB_PREFIX)) return source;
108
111
  const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });
109
112
  const file = resolved?.id.split("?")[0];
110
- return file !== undefined && modules.has(file) ? `${STUB_PREFIX}${file}.mjs` : null;
113
+ return file !== undefined && modules.has(pathKey(file))
114
+ ? `${STUB_PREFIX}${pathKey(file)}.mjs`
115
+ : null;
111
116
  },
112
117
  load(id) {
113
118
  if (!id.startsWith(STUB_PREFIX)) return null;
@@ -118,7 +123,7 @@ export function serverClientStubPlugin(
118
123
  // directive, but without a stub, would ship its server code to every viewer.
119
124
  transform(code, id) {
120
125
  const file = id.split("?")[0] ?? id;
121
- if (!file.startsWith(`${sourceDir}/`) || modules.has(file)) return null;
126
+ if (!isUnder(file, sourceDir) || modules.has(pathKey(file))) return null;
122
127
  if (!SCRIPT.has(extname(file))) return null;
123
128
  if (startsWithUseServer(file, code) !== true) return null;
124
129
  return this.error(
@@ -149,7 +154,7 @@ export interface BuildInputs {
149
154
  * later change to them would go unnoticed.
150
155
  */
151
156
  export function confinePlugin(inputs: BuildInputs): Plugin {
152
- const under = (file: string, dir: string): boolean => file.startsWith(`${dir}/`);
157
+ const under = (file: string, dir: string): boolean => isUnder(file, dir);
153
158
  const ours = (file: string): boolean =>
154
159
  under(file, inputs.sourceDir) || under(file, inputs.generatedDir);
155
160
  const packaged = (file: string): boolean => inputs.packageRoots.some((root) => under(file, root));
@@ -168,7 +173,7 @@ export function confinePlugin(inputs: BuildInputs): Plugin {
168
173
  if (from === undefined || source.startsWith("\0")) return null;
169
174
  const fromPackage = !ours(from);
170
175
  if (fromPackage && !packaged(from)) return null;
171
- const bare = !source.startsWith(".") && !source.startsWith("/");
176
+ const bare = !source.startsWith(".") && !source.startsWith("/") && !isAbsolute(source);
172
177
  const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });
173
178
  if (!resolved || resolved.external) return resolved;
174
179
  const id = resolved.id.split("?")[0] ?? resolved.id;
@@ -6,13 +6,14 @@
6
6
  * Nothing in the artifact runs.
7
7
  */
8
8
  import type { Dirent } from "node:fs";
9
- import { mkdir, readdir, realpath, rm, symlink, writeFile } from "node:fs/promises";
9
+ import { mkdir, readdir, realpath, rm, writeFile } from "node:fs/promises";
10
10
  import { join, relative } from "node:path";
11
11
  import { stripVTControlCharacters } from "node:util";
12
12
  import { createDiagnostic, type Diagnostic } from "@mostra/protocol";
13
13
  import tailwind from "@tailwindcss/vite";
14
14
  import react from "@vitejs/plugin-react";
15
15
  import { build, type InlineConfig, type PluginOption } from "vite";
16
+ import { isUnder, linkDirectory, pathKey } from "../../platform/index.ts";
16
17
  import type { FieldCoverage } from "../coverage.ts";
17
18
  import {
18
19
  type BuildRequest,
@@ -140,12 +141,16 @@ export function diagnose(error: unknown, sourceDir: string): Diagnostic {
140
141
  };
141
142
  const first = failure.errors?.[0] ?? failure;
142
143
  // Bundler messages carry terminal colours; diagnostics are plain text.
143
- const rawMessage = stripVTControlCharacters(first.message ?? String(error)).replaceAll(
144
- `${sourceDir}/`,
145
- "",
146
- );
144
+ // Paths in the message as the bundler spells them (`/`-separated on Windows too).
145
+ const rawMessage = stripVTControlCharacters(first.message ?? String(error))
146
+ .replaceAll(`${sourceDir}/`, "")
147
+ .replaceAll(`${sourceDir.replaceAll("\\", "/")}/`, "")
148
+ .replaceAll(`${sourceDir}\\`, "");
147
149
  const file = first.loc?.file ?? first.id;
148
- const inSource = file?.startsWith(sourceDir) ? relative(sourceDir, file) : undefined;
150
+ const inSource =
151
+ file !== undefined && isUnder(file, sourceDir)
152
+ ? relative(sourceDir, file).replaceAll("\\", "/")
153
+ : undefined;
149
154
  const location =
150
155
  inSource !== undefined
151
156
  ? { file: inSource, line: first.loc?.line ?? 1, column: (first.loc?.column ?? 0) + 1 }
@@ -216,7 +221,8 @@ export async function packageRoots(nodeModules: string): Promise<string[]> {
216
221
  } catch {
217
222
  continue; // A dangling link brings nothing in.
218
223
  }
219
- const store = dir.lastIndexOf("/.pnpm/");
224
+ // pnpm's store, found however the platform spells separators (the key keeps the length).
225
+ const store = pathKey(dir).lastIndexOf("/.pnpm/");
220
226
  const root = store === -1 ? dir : dir.slice(0, store + "/.pnpm".length);
221
227
  if (roots.has(root)) continue;
222
228
  roots.add(root);
@@ -257,7 +263,7 @@ export async function buildSpa(input: BuildRequest): Promise<BuildResponse> {
257
263
  packageRoots: await packageRoots(request.nodeModules),
258
264
  };
259
265
  await rm(join(request.stagingDir, "node_modules"), { force: true, recursive: true });
260
- await symlink(request.nodeModules, join(request.stagingDir, "node_modules"), "dir");
266
+ await linkDirectory(request.nodeModules, join(request.stagingDir, "node_modules"));
261
267
  await writeFile(
262
268
  join(request.stagingDir, "index.html"),
263
269
  html(request.manifest.title, request.versionId),
@@ -267,7 +273,7 @@ export async function buildSpa(input: BuildRequest): Promise<BuildResponse> {
267
273
  if (scan.hasLive) await writeFile(join(generated, "mostra-env.d.ts"), LIVE_DECLARATION);
268
274
 
269
275
  const serverModules = new Map<string, readonly ServerFunctionEntry[]>(
270
- [...scan.serverModules].map(([module, entries]) => [join(sourceDir, module), entries]),
276
+ [...scan.serverModules].map(([module, entries]) => [pathKey(join(sourceDir, module)), entries]),
271
277
  );
272
278
  // Packages that use the field hooks themselves open the version's coverage (D109).
273
279
  const hookUses: FieldHookUse[] = [];
@@ -48,6 +48,8 @@ export {
48
48
  type VersionRegistry,
49
49
  } from "./types.ts";
50
50
 
51
+ import { baseEnvironment } from "../platform/index.ts";
52
+
51
53
  /** How long one build may take (FAILURE_MODEL §9). */
52
54
  export const BUILD_TIMEOUT_MS = 180_000;
53
55
 
@@ -187,12 +189,7 @@ export function createSpaRenderMode(options: SpaRenderModeOptions): RenderMode {
187
189
  const timeoutMs = options.timeoutMs ?? BUILD_TIMEOUT_MS;
188
190
  const env = options.env ?? process.env;
189
191
  // The builder gets only what it needs: no secrets, nothing that could reach a bundle.
190
- const childEnv: Environment = {
191
- PATH: env["PATH"] ?? "/usr/bin:/bin",
192
- HOME: env["HOME"] ?? "/",
193
- NODE_ENV: "production",
194
- ...(env["TMPDIR"] ? { TMPDIR: env["TMPDIR"] } : {}),
195
- };
192
+ const childEnv: Environment = { ...baseEnvironment(env), NODE_ENV: "production" };
196
193
 
197
194
  return {
198
195
  id: "spa",
@@ -16,10 +16,11 @@ if (entry === undefined) {
16
16
  console.error("The install child needs the installer's entry as its first argument.");
17
17
  process.exit(2);
18
18
  }
19
- // Not detached: pnpm stays in this child's process group, which the supervisor and the disconnect
20
- // rule both end as a whole.
19
+ // Not detached: pnpm stays in this child's process group (on Windows its Job Object), which the
20
+ // supervisor and the disconnect rule both end as a whole. No console window opens on Windows.
21
21
  const installer = spawn(process.execPath, [entry, ...args], {
22
22
  stdio: ["ignore", "inherit", "inherit"],
23
+ windowsHide: true,
23
24
  });
24
25
  installer.on("error", (error) => {
25
26
  console.error(`The installer couldn't start: ${error.message}`);
package/src/deps/index.ts CHANGED
@@ -20,8 +20,8 @@
20
20
  * ```
21
21
  */
22
22
  import { randomBytes } from "node:crypto";
23
- import { existsSync, readlinkSync } from "node:fs";
24
- import { lstat, mkdir, readdir, readFile, rename, rm, symlink, writeFile } from "node:fs/promises";
23
+ import { existsSync } from "node:fs";
24
+ import { lstat, mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
25
25
  import { networkInterfaces } from "node:os";
26
26
  import { join } from "node:path";
27
27
  import {
@@ -43,6 +43,13 @@ import {
43
43
  recordResult,
44
44
  } from "../ledger/index.ts";
45
45
  import type { Environment, Log } from "../log.ts";
46
+ import {
47
+ linkDirectory,
48
+ linkTarget,
49
+ replaceDirectoryLink,
50
+ samePath,
51
+ WINDOWS,
52
+ } from "../platform/index.ts";
46
53
  import type { ProcessManager } from "../processes/index.ts";
47
54
  import { createInstaller, INSTALL_TIMEOUT_MS, type Installer } from "./installer.ts";
48
55
  import { type Lock, lockDigest, lockText, parseLock, pinnedPackages } from "./lock.ts";
@@ -223,8 +230,13 @@ export function isOffline(env: Environment): boolean {
223
230
  );
224
231
  }
225
232
 
226
- /** A shell-safe rendering of `value`, for the commands in diagnostics. */
233
+ /**
234
+ * A shell-safe rendering of `value`, for the commands in diagnostics: POSIX shell quoting, or on
235
+ * Windows the double quotes PowerShell and `cmd` both read (a Windows path holds no `"`), and a
236
+ * plain path with backslashes as it is.
237
+ */
227
238
  function shellQuote(value: string): string {
239
+ if (WINDOWS) return /^[\w@%+=:,./\\-]+$/.test(value) ? value : `"${value}"`;
228
240
  return /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
229
241
  }
230
242
 
@@ -369,7 +381,7 @@ export function createDependencies(options: DependenciesOptions): Dependencies {
369
381
  const work = join(dirs.tmp, `resolve-${randomBytes(6).toString("hex")}`);
370
382
  await mkdir(work);
371
383
  try {
372
- await symlink(warm.nodeModules, join(work, "warm"), "dir");
384
+ await linkDirectory(warm.nodeModules, join(work, "warm"));
373
385
  await writeFile(join(work, "package.json"), manifestOf(input.pins));
374
386
  if (input.previous !== undefined)
375
387
  await writeFile(join(work, "pnpm-lock.yaml"), input.previous);
@@ -412,16 +424,9 @@ export function createDependencies(options: DependenciesOptions): Dependencies {
412
424
  /** Points a layout's `warm` symlink at the current warm set (the runtime may have moved). */
413
425
  const relinkWarm = async (dir: string): Promise<void> => {
414
426
  const link = join(dir, "warm");
415
- let target: string | undefined;
416
- try {
417
- target = readlinkSync(link);
418
- } catch {
419
- target = undefined;
420
- }
421
- if (target === warm.nodeModules) return;
422
- const fresh = `${link}.${randomBytes(4).toString("hex")}`;
423
- await symlink(warm.nodeModules, fresh, "dir");
424
- await rename(fresh, link);
427
+ const target = await linkTarget(link);
428
+ if (target !== undefined && samePath(target, warm.nodeModules)) return;
429
+ await replaceDirectoryLink(warm.nodeModules, link);
425
430
  };
426
431
 
427
432
  /**
@@ -456,7 +461,7 @@ export function createDependencies(options: DependenciesOptions): Dependencies {
456
461
  await rm(dir, { recursive: true, force: true });
457
462
  await mkdir(dir, { recursive: true });
458
463
  try {
459
- await symlink(warm.nodeModules, join(dir, "warm"), "dir");
464
+ await linkDirectory(warm.nodeModules, join(dir, "warm"));
460
465
  await writeFile(join(dir, "package.json"), manifestOf(lock.packages));
461
466
  await writeFile(join(dir, "pnpm-lock.yaml"), pnpm);
462
467
  const outcome = await install().run({
@@ -536,7 +541,7 @@ export function createDependencies(options: DependenciesOptions): Dependencies {
536
541
  await rm(dir, { recursive: true, force: true });
537
542
  await mkdir(dir, { recursive: true });
538
543
  try {
539
- await symlink(warm.nodeModules, join(dir, "warm"), "dir");
544
+ await linkDirectory(warm.nodeModules, join(dir, "warm"));
540
545
  await writeFile(
541
546
  join(dir, "package.json"),
542
547
  `${JSON.stringify(
package/src/deps/warm.ts CHANGED
@@ -3,10 +3,10 @@
3
3
  * install. `@mostra/warm`'s `dependencies` are the warm packages; its `node_modules` is the layout.
4
4
  */
5
5
  import { existsSync, readFileSync, realpathSync } from "node:fs";
6
- import { dirname, join, resolve } from "node:path";
7
- import { fileURLToPath } from "node:url";
6
+ import { join, resolve } from "node:path";
8
7
  import { createDiagnostic, RpcError } from "@mostra/protocol";
9
8
  import type { Environment } from "../log.ts";
9
+ import { runtimeRoot } from "../platform/index.ts";
10
10
 
11
11
  /** The warm set: where its layout is and what versions it holds. */
12
12
  export interface WarmSet {
@@ -16,20 +16,7 @@ export interface WarmSet {
16
16
  readonly packages: Readonly<Record<string, string>>;
17
17
  }
18
18
 
19
- /** The directory of `@mostra/runtime`'s package.json. */
20
- export function runtimeRoot(): string {
21
- let dir = dirname(fileURLToPath(import.meta.url));
22
- for (;;) {
23
- const manifest = join(dir, "package.json");
24
- if (existsSync(manifest)) {
25
- const { name } = JSON.parse(readFileSync(manifest, "utf8")) as { name?: string };
26
- if (name === "@mostra/runtime") return dir;
27
- }
28
- const parent = dirname(dir);
29
- if (parent === dir) throw new Error("Couldn't find @mostra/runtime's package.json.");
30
- dir = parent;
31
- }
32
- }
19
+ export { runtimeRoot };
33
20
 
34
21
  function warmMissing(message: string): RpcError {
35
22
  return new RpcError(createDiagnostic("MOSTRA_ENV_WARM_MISSING", { message }));
package/src/faults.ts CHANGED
@@ -14,7 +14,7 @@
14
14
  import type { Environment } from "./log.ts";
15
15
 
16
16
  /** What a fault point does. */
17
- export type FaultAction = "throw" | "crash" | "hang";
17
+ export type FaultAction = "throw" | "throw-once" | "crash" | "hang";
18
18
 
19
19
  /** The test fault points of one instance. */
20
20
  export interface Faults {
@@ -47,7 +47,10 @@ export function faultsFrom(env: Environment): Faults {
47
47
  const separator = entry.lastIndexOf(":");
48
48
  const point = entry.slice(0, separator).trim();
49
49
  const action = entry.slice(separator + 1).trim();
50
- if (point && (action === "throw" || action === "crash" || action === "hang"))
50
+ if (
51
+ point &&
52
+ (action === "throw" || action === "throw-once" || action === "crash" || action === "hang")
53
+ )
51
54
  configured.set(point, action);
52
55
  }
53
56
  return {
@@ -55,6 +58,10 @@ export function faultsFrom(env: Environment): Faults {
55
58
  at(point) {
56
59
  const action = configured.get(point);
57
60
  if (action === "throw") throw new InjectedFault(point);
61
+ if (action === "throw-once") {
62
+ configured.delete(point);
63
+ throw new InjectedFault(point);
64
+ }
58
65
  if (action === "crash") {
59
66
  process.kill(process.pid, "SIGKILL");
60
67
  // The signal is delivered at once; block until it lands so no later step runs.
@@ -14,7 +14,6 @@ import {
14
14
  mkdirSync,
15
15
  openSync,
16
16
  readFileSync,
17
- renameSync,
18
17
  writeSync,
19
18
  } from "node:fs";
20
19
  import { join } from "node:path";
@@ -30,6 +29,7 @@ import {
30
29
  import { appendEvent } from "../interaction/index.ts";
31
30
  import type { Ledger, LedgerDb } from "../ledger/index.ts";
32
31
  import type { Log } from "../log.ts";
32
+ import { renamePathSync } from "../platform/index.ts";
33
33
 
34
34
  /** Crockford base32, the alphabet of every Mostra ID body (D77). */
35
35
  const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
@@ -127,7 +127,7 @@ export function capabilityKey(home: string, log: Log): Buffer {
127
127
  } finally {
128
128
  closeSync(fd);
129
129
  }
130
- renameSync(aside, file);
130
+ renamePathSync(aside, file);
131
131
  chmodSync(file, 0o600);
132
132
  return key;
133
133
  }
@@ -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,