@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
@@ -1,19 +1,20 @@
1
- import { a as DEV_SECRET_HEADER, c as LIVE_DECLARATION, i as DEV_RELOAD_METHOD, l as STAGING_FILES, n as DEV_CHANGED_METHOD, r as DEV_METHOD, t as BUILD_METHOD } from "./types-NjNy7gXX.js";
1
+ import { C as STAGING_FILES, S as LIVE_DECLARATION, _ as DEV_METHOD, a as nameKey, c as removeTree, d as replaceDirectoryLink, f as samePath, g as DEV_CHANGED_METHOD, h as BUILD_METHOD, i as linkTarget, l as renamePath, m as sealTree, o as pathKey, p as sealPlaced, r as linkDirectory, s as realPath, t as fsyncPath, u as renamePathSync, v as DEV_RELOAD_METHOD, y as DEV_SECRET_HEADER } from "./files-FygSJIzK.js";
2
+ import { a as pathsOf, c as currentUserSid, d as runtimeRoot$1, f as serviceLauncherPath, i as ownedDirectory, l as helperPath, n as WINDOWS, o as runtimeDirFor, p as stopServiceLauncher, r as defaultHome, s as socketPathLimit, t as OS, u as runHelperAsync } from "./directories-mJ1qlVht.js";
2
3
  import { builtinModules, createRequire } from "node:module";
3
- import { appendFileSync, chmodSync, closeSync, constants, createReadStream, createWriteStream, existsSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, watch, writeFileSync, writeSync } from "node:fs";
4
- import { basename, delimiter, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { appendFileSync, chmodSync, closeSync, constants, createReadStream, createWriteStream, existsSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, watch, writeFileSync, writeSync } from "node:fs";
5
+ import { basename, delimiter, dirname, extname, join, relative, resolve, sep, win32 } from "node:path";
5
6
  import { fileURLToPath } from "node:url";
6
7
  import { ACTION_ARGS_MAX, ACTION_RESULT_MAX, ALL_SCOPES, ARTIFACT_MANIFEST_KEYS, ARTIFACT_PROGRESS, ArtifactId, ArtifactManifest, BROWSER_PROTOCOL_REVISION, BROWSER_PROTOCOL_REVISIONS, BUNDLE_NAME, CLI_CLIENT_NAME, CallRequest, ChooseRequest, DEFAULT_WORKER_LIMITS, DEV_NOTIFY, DeliveryId, EVENTS_NOTIFY, FieldsRequest, FollowRequest, HOST_PROTOCOL_REVISIONS, LIVE_RING_DEFAULT, LIVE_RING_MAX, LIVE_VALUE_MAX, LineSplitter, LiveRequest, MAX_LINE_LENGTH, MutationId, RUN_LOG_MAX, RUN_LOG_TRUNCATED, RpcError, RpcPeer, RunAttachRequest, RunCancelRequest, RunId, RunRequest, SECRET_NAME_PATTERN, SECRET_VALUE_MAX, SIGNAL_NAME_PATTERN, SIGNAL_PAYLOAD_MAX_BYTES, ServerEmitParams, ServerLiveValueParams, ServerSecretParams, ServerSignalParams, ServerStateGetParams, ServerStatePatchParams, ShellSubmitRequest, SignalRequest, SubmissionId, SubmissionPolicy, SubmitRequest, TokenId, VERIFY_RUNNER_METHODS, VerifyVerdict, VersionId, ViewId, ViewerId, WORKER_METHODS, WorkerBatchParams, WorkerCallOutcome, WorkerPingResult, WorkerStartResult, ariaSummary, artifactCreateMethod, artifactGetMethod, artifactListMethod, artifactPublishMethod, artifactVerifyMethod, canonicalJson, checkArgumentFrames, checkRequest, createDiagnostic, depsAddMethod, devStartMethod, devStopMethod, durationMs, encodeLine, estimateImageTokens, eventsAckMethod, eventsReadMethod, eventsSubscribeMethod, eventsUnsubscribeMethod, fromBase64, gcRunMethod, instanceCheckMethod, instanceStatusMethod, isFieldId, isFinalRunStatus, livePushMethod, mostraInitializeMethod, mostraShutdownMethod, negotiateRevision, normalizeScopes, parseParams, portDraftsMirrorMethod, portIdentityResolveMethod, portSecretsGetMethod, portSubmissionsDeliverMethod, portTrustedControlsActivatedMethod, portTrustedControlsPolicyMethod, refusal, resultsGetMethod, safeEqual, safePath, scopeAllows, secretDeleteMethod, secretListMethod, secretSetMethod, serializeAll, stateGetMethod, statePatchMethod, toBase64, viewDefaultMethod, viewLaunchMethod, viewRevokeMethod, viewRotateMethod, viewUrlMethod, viewportsFor, waitMethod } from "@mostra/protocol";
7
8
  import { createHash, createHmac, randomBytes, randomInt, randomUUID } from "node:crypto";
8
9
  import { connect, createConnection, createServer, isIP } from "node:net";
9
- import { access, chmod, copyFile, cp, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, stat, symlink, unlink, utimes, writeFile } from "node:fs/promises";
10
+ import { execFile, execFileSync, spawn } from "node:child_process";
11
+ import { Duplex, Readable } from "node:stream";
12
+ import { access, chmod, copyFile, cp, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rm, stat, unlink, utimes, writeFile } from "node:fs/promises";
10
13
  import { homedir, networkInterfaces } from "node:os";
11
14
  import semver from "semver";
12
- import { execFile, execFileSync, spawn } from "node:child_process";
13
15
  import { createInterface } from "node:readline";
14
16
  import * as z from "zod";
15
17
  import { parse, parseDocument } from "yaml";
16
- import { Readable } from "node:stream";
17
18
  import { pipeline } from "node:stream/promises";
18
19
  import { createZstdCompress } from "node:zlib";
19
20
  import { createServer as createServer$1, request } from "node:http";
@@ -859,80 +860,903 @@ function coverageMatcher(coverage) {
859
860
  }
860
861
  return (fieldId) => ids.has(fieldId) || templates.some((pattern) => pattern.test(fieldId));
861
862
  }
862
- /** Packages whose versions define the SPA build; they are part of `buildConfigDigest` (VR-01). */
863
- const BUILD_PACKAGES = [
864
- "vite",
865
- "@vitejs/plugin-react",
866
- "@mdx-js/mdx",
867
- "remark-frontmatter",
868
- "remark-gfm",
869
- "@tailwindcss/vite",
870
- "oxc-parser"
863
+ //#endregion
864
+ //#region src/platform/identity.ts
865
+ /**
866
+ * Process identity (DATA_MODEL §3 `child.start_time`, FAILURE_MODEL §2). A PID alone can be
867
+ * reused, so a process is identified by its PID plus an opaque start time: the boot it started in
868
+ * and when it started within that boot. Linux reads `/proc/<pid>/stat` (start ticks since boot)
869
+ * and the boot ID; macOS reads `ps -o lstart` (seconds) and `kern.boottime` (VERIFIED_FACTS,
870
+ * WP-02); Windows asks the helper for the creation time (`GetProcessTimes`, 100 ns units since
871
+ * 1601, so absolute across boots), written `win/<creation time>` (VERIFIED_FACTS, WP-W1). Zombies,
872
+ * and Windows processes that exited but whose object a handle still keeps, count as gone.
873
+ *
874
+ * Seconds are enough on macOS (issue #8): XNU hands out PIDs in order from the last one, up to
875
+ * 99,999, then from 100, skipping any PID still used as a process, process group or session
876
+ * (`forkproc` in `bsd/kern/kern_fork.c`). A PID comes back only after the whole range has been
877
+ * handed out, about 99,900 forks, which takes this machine about 100 s at its measured 1,000
878
+ * spawns a second, and never while its process group lives (VERIFIED_FACTS, WP-08).
879
+ */
880
+ /** The boot part of every Windows start time: creation times are absolute. */
881
+ const WINDOWS_BOOT = "win";
882
+ /** Splits a start time into its boot and its position within the boot. */
883
+ function parts(startTime) {
884
+ const slash = startTime.lastIndexOf("/");
885
+ if (slash <= 0) return void 0;
886
+ const text = startTime.slice(slash + 1);
887
+ if (!/^\d+$/.test(text)) return void 0;
888
+ return {
889
+ boot: startTime.slice(0, slash),
890
+ at: BigInt(text)
891
+ };
892
+ }
893
+ /** Whether two start times belong to the same boot of the machine. */
894
+ function sameBoot(a, b) {
895
+ const left = parts(a);
896
+ const right = parts(b);
897
+ return left !== void 0 && right !== void 0 && left.boot === right.boot;
898
+ }
899
+ /**
900
+ * Whether `candidate` started in the same boot as `reference` and no earlier. On macOS the
901
+ * resolution is one second, so a process started in the same second counts as no earlier.
902
+ */
903
+ function startedNoEarlier(candidate, reference) {
904
+ const c = parts(candidate);
905
+ const r = parts(reference);
906
+ return c !== void 0 && r !== void 0 && c.boot === r.boot && c.at >= r.at;
907
+ }
908
+ /** Parses one `/proc/<pid>/stat` line. `comm` may contain spaces and parentheses. */
909
+ function parseProcStat(line, boot) {
910
+ const open = line.indexOf("(");
911
+ const close = line.lastIndexOf(")");
912
+ if (open < 0 || close < open) return void 0;
913
+ const pid = Number(line.slice(0, open).trim());
914
+ const rest = line.slice(close + 1).trim().split(/\s+/);
915
+ if (rest[0] === "Z") return void 0;
916
+ const pgid = Number(rest[2]);
917
+ const start = rest[19];
918
+ if (!Number.isSafeInteger(pid) || !Number.isSafeInteger(pgid) || start === void 0) return;
919
+ if (!/^\d+$/.test(start)) return void 0;
920
+ return {
921
+ pid,
922
+ pgid,
923
+ startTime: `${boot}/${start}`
924
+ };
925
+ }
926
+ const MONTHS = [
927
+ "Jan",
928
+ "Feb",
929
+ "Mar",
930
+ "Apr",
931
+ "May",
932
+ "Jun",
933
+ "Jul",
934
+ "Aug",
935
+ "Sep",
936
+ "Oct",
937
+ "Nov",
938
+ "Dec"
871
939
  ];
872
- /** Bumped whenever the SPA build's settings change, so older versions aren't reused. */
873
- const SPA_CONFIG_REVISION = 7;
874
- /** The directory of `@mostra/runtime`'s package.json. */
875
- function runtimeRoot$1() {
876
- let dir = dirname(fileURLToPath(import.meta.url));
877
- for (;;) {
878
- const manifest = join(dir, "package.json");
879
- if (existsSync(manifest)) {
880
- const { name } = JSON.parse(readFileSync(manifest, "utf8"));
881
- if (name === "@mostra/runtime") return dir;
882
- }
883
- const parent = dirname(dir);
884
- if (parent === dir) throw new Error("Couldn't find @mostra/runtime's package.json.");
885
- dir = parent;
886
- }
940
+ /**
941
+ * Parses one line of `LC_ALL=C TZ=UTC ps -o pid=,pgid=,stat=,lstart=`, such as
942
+ * ` 214 99444 Ss Tue Oct 6 13:53:19 2026`. Zombies (`stat` starting with `Z`) are skipped.
943
+ */
944
+ function parsePsLine(line, boot) {
945
+ const fields = line.trim().split(/\s+/);
946
+ if (fields.length < 8) return void 0;
947
+ const [pidText, pgidText, stat, , monthText, dayText, timeText, yearText] = fields;
948
+ if (stat?.startsWith("Z")) return void 0;
949
+ const pid = Number(pidText);
950
+ const pgid = Number(pgidText);
951
+ const month = MONTHS.indexOf(monthText ?? "");
952
+ const [hours, minutes, seconds] = (timeText ?? "").split(":").map(Number);
953
+ const millis = Date.UTC(Number(yearText), month, Number(dayText), hours ?? NaN, minutes ?? NaN, seconds ?? NaN);
954
+ if (!Number.isSafeInteger(pid) || !Number.isSafeInteger(pgid) || month < 0 || Number.isNaN(millis)) return;
955
+ return {
956
+ pid,
957
+ pgid,
958
+ startTime: `${boot}/${millis / 1e3}`
959
+ };
887
960
  }
888
- /** Node's lookup of an installed package's directory, from `from` upwards. */
889
- function packageDir(name, from) {
890
- let dir = from;
891
- for (;;) {
892
- const candidate = join(dir, "node_modules", name);
893
- if (existsSync(join(candidate, "package.json"))) return realpathSync(candidate);
894
- const parent = dirname(dir);
895
- if (parent === dir) return void 0;
896
- dir = parent;
961
+ function run$1(file, args) {
962
+ return new Promise((resolve, reject) => {
963
+ execFile(file, args, {
964
+ env: {
965
+ LC_ALL: "C",
966
+ TZ: "UTC",
967
+ PATH: "/usr/bin:/bin:/usr/sbin:/sbin"
968
+ },
969
+ maxBuffer: 67108864
970
+ }, (error, stdout) => {
971
+ if (error && typeof error.code !== "number") {
972
+ reject(error);
973
+ return;
974
+ }
975
+ resolve({
976
+ code: typeof error?.code === "number" ? error.code : 0,
977
+ stdout
978
+ });
979
+ });
980
+ });
981
+ }
982
+ let cachedBoot;
983
+ /** The identity of the current boot of this machine (on Windows a constant: times are absolute). */
984
+ function bootId() {
985
+ cachedBoot ??= (async () => {
986
+ if (process.platform === "win32") return WINDOWS_BOOT;
987
+ if (process.platform === "linux") return (await readFile("/proc/sys/kernel/random/boot_id", "utf8")).trim();
988
+ const { stdout } = await run$1("/usr/sbin/sysctl", ["-n", "kern.boottime"]);
989
+ const match = /sec = (\d+), usec = (\d+)/.exec(stdout);
990
+ if (!match) throw new Error("Couldn't read kern.boottime.");
991
+ return `${match[1]}.${match[2]}`;
992
+ })();
993
+ return cachedBoot;
994
+ }
995
+ /** Reads one process, or `undefined` when no process has that PID. */
996
+ async function readProcess(pid) {
997
+ if (process.platform === "win32") {
998
+ const [entry] = await runHelperAsync(["identity", String(pid)]);
999
+ return entry?.startTime === void 0 ? void 0 : {
1000
+ pid,
1001
+ pgid: pid,
1002
+ startTime: entry.startTime
1003
+ };
1004
+ }
1005
+ const boot = await bootId();
1006
+ if (process.platform === "linux") try {
1007
+ return parseProcStat(await readFile(`/proc/${pid}/stat`, "utf8"), boot);
1008
+ } catch {
1009
+ return;
897
1010
  }
1011
+ const { code, stdout } = await run$1("/bin/ps", [
1012
+ "-o",
1013
+ "pid=,pgid=,stat=,lstart=",
1014
+ "-p",
1015
+ String(pid)
1016
+ ]);
1017
+ if (code !== 0) return void 0;
1018
+ const [line] = stdout.split("\n").filter((text) => text.trim() !== "");
1019
+ return line === void 0 ? void 0 : parsePsLine(line, boot);
898
1020
  }
899
- function versionOf(dir) {
900
- return JSON.parse(readFileSync(join(dir, "package.json"), "utf8")).version;
1021
+ /**
1022
+ * Lists every process the user can see. On Windows each carries its parent's PID (`ppid`), which
1023
+ * may name a process that has since exited and whose PID was reused.
1024
+ */
1025
+ async function listProcesses() {
1026
+ if (process.platform === "win32") return (await runHelperAsync(["processes"])).flatMap((entry) => entry.startTime === void 0 ? [] : [{
1027
+ pid: entry.pid,
1028
+ pgid: entry.pid,
1029
+ startTime: entry.startTime,
1030
+ ppid: entry.ppid ?? 0
1031
+ }]);
1032
+ const boot = await bootId();
1033
+ if (process.platform === "linux") {
1034
+ const entries = (await readdir("/proc")).filter((name) => /^\d+$/.test(name));
1035
+ return (await Promise.all(entries.map(async (name) => {
1036
+ try {
1037
+ return parseProcStat(await readFile(`/proc/${name}/stat`, "utf8"), boot);
1038
+ } catch {
1039
+ return;
1040
+ }
1041
+ }))).filter((info) => info !== void 0);
1042
+ }
1043
+ const { stdout } = await run$1("/bin/ps", [
1044
+ "-A",
1045
+ "-o",
1046
+ "pid=,pgid=,stat=,lstart="
1047
+ ]);
1048
+ return stdout.split("\n").map((line) => parsePsLine(line, boot)).filter((info) => info !== void 0);
901
1049
  }
902
- /** The builder child's entry: the compiled one beside the compiled supervisor, else the source. */
903
- function childEntry$1(root) {
904
- return fileURLToPath(import.meta.url).endsWith(".ts") ? join(root, "src/builder/child/main.ts") : join(root, "dist/builder/child/main.js");
1050
+ /** Whether the process recorded as `pid` and `startTime` is still the one running. */
1051
+ async function isSameProcess(pid, startTime) {
1052
+ const info = await readProcess(pid);
1053
+ return info !== void 0 && info.startTime === startTime;
905
1054
  }
906
- /** The SPA render mode (D19): every build in its own builder child. */
907
- function createSpaRenderMode(options) {
908
- const root = runtimeRoot$1();
909
- const buildPackages = {};
910
- for (const name of BUILD_PACKAGES) {
911
- const dir = packageDir(name, root);
912
- if (!dir) throw new Error(`The runtime is missing its build dependency ${name}.`);
913
- buildPackages[name] = versionOf(dir);
1055
+ //#endregion
1056
+ //#region src/platform/launch.ts
1057
+ /**
1058
+ * Starting, ending and reaping children on each operating system (RT-09, RT-10, issue #7, D93,
1059
+ * FAILURE_MODEL §2). The process manager keeps the policy (record a child before it runs, end its
1060
+ * descendants with it, reap what a crashed supervisor left); this module is how each system does
1061
+ * it.
1062
+ *
1063
+ * - **POSIX.** A child is started detached, as the leader of its own process group, behind a
1064
+ * `/bin/sh` gate that waits for "go" on descriptor 3 and then `exec`s the command, keeping its
1065
+ * PID, group and start time. It is ended by signalling its group (SIGTERM, then SIGKILL), and
1066
+ * the reaper signals a recorded group's members that started no earlier than its leader.
1067
+ * - **Windows.** A child is started behind `mostra-win gate`, which creates it suspended in a Job
1068
+ * Object of its own that ends every member when its last handle closes, reports its PID and
1069
+ * creation time on descriptor 3, and lets it run on "go". Descriptor 3 stays open as the
1070
+ * child's lifeline: closing it (a stop, or the supervisor's exit or crash) ends the job, child
1071
+ * and descendants at once. Windows has no signals to ask a process to stop, so a stop is that:
1072
+ * graceful work goes over the child's own channel first (D87). The reaper ends a recorded
1073
+ * child's job, which it opens by the name the gate gave it (`Local\mostra-job-<pid>-<creation>`),
1074
+ * and the child itself if it still runs as the recorded process.
1075
+ */
1076
+ /**
1077
+ * The POSIX gate (issue #7): `/bin/sh` waits for "go" on file descriptor 3 and only then replaces
1078
+ * itself with the real command. A supervisor killed in between leaves a gate that reads
1079
+ * end-of-file and exits 125 without running anything.
1080
+ */
1081
+ const GATE_SCRIPT = "IFS= read -r go <&3 && [ \"$go\" = go ] || exit 125; exec 3<&-; exec \"$@\"";
1082
+ /** How long reaping waits between SIGTERM and SIGKILL. */
1083
+ const REAP_GRACE_MS = 2e3;
1084
+ /** How long to wait for SIGKILLed processes to disappear before reporting them. */
1085
+ const KILL_WAIT_MS = 5e3;
1086
+ const delay$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1087
+ function signalGroup(pgid, signal) {
1088
+ try {
1089
+ process.kill(-pgid, signal);
1090
+ return true;
1091
+ } catch {
1092
+ return false;
914
1093
  }
915
- const buildConfig = {
916
- mode: "spa",
917
- revision: SPA_CONFIG_REVISION,
918
- base: "/",
919
- sourcemap: true,
920
- packages: buildPackages,
921
- stagingFiles: STAGING_FILES
922
- };
923
- const timeoutMs = options.timeoutMs ?? 18e4;
924
- const env = options.env ?? process.env;
925
- const childEnv = {
926
- PATH: env["PATH"] ?? "/usr/bin:/bin",
927
- HOME: env["HOME"] ?? "/",
928
- NODE_ENV: "production",
929
- ...env["TMPDIR"] ? { TMPDIR: env["TMPDIR"] } : {}
1094
+ }
1095
+ const groupAlive = (pgid) => signalGroup(pgid, 0);
1096
+ /** Starts `spec` behind its gate. */
1097
+ function launch(spec, warn) {
1098
+ return WINDOWS ? launchWindows(spec) : launchPosix(spec, warn);
1099
+ }
1100
+ function stdioFor(extra) {
1101
+ const base = [
1102
+ "ignore",
1103
+ "pipe",
1104
+ "pipe",
1105
+ "pipe"
1106
+ ];
1107
+ if (extra === "ipc") return [...base, "ipc"];
1108
+ if (extra === "channel") return [...base, "overlapped"];
1109
+ return base;
1110
+ }
1111
+ function launchPosix(spec, warn) {
1112
+ const child = spawn("/bin/sh", [
1113
+ "-c",
1114
+ GATE_SCRIPT,
1115
+ `mostra-${spec.kind}`,
1116
+ spec.command,
1117
+ ...spec.args
1118
+ ], {
1119
+ cwd: spec.cwd,
1120
+ env: spec.env,
1121
+ detached: true,
1122
+ stdio: stdioFor(spec.extra),
1123
+ serialization: "json"
1124
+ });
1125
+ const gate = child.stdio[3];
1126
+ gate?.on("error", () => {});
1127
+ const pid = () => child.pid ?? 0;
1128
+ const end = async (pgids, graceMs) => {
1129
+ for (const pgid of pgids) signalGroup(pgid, "SIGTERM");
1130
+ const deadline = Date.now() + graceMs;
1131
+ while (Date.now() < deadline && pgids.some(groupAlive)) await delay$1(25);
1132
+ for (const pgid of pgids) if (groupAlive(pgid)) signalGroup(pgid, "SIGKILL");
1133
+ const killDeadline = Date.now() + KILL_WAIT_MS;
1134
+ while (Date.now() < killDeadline && pgids.some(groupAlive)) await delay$1(10);
1135
+ const left = pgids.filter(groupAlive);
1136
+ if (left.length > 0) warn("process.group_survived_sigkill", { pgids: left });
930
1137
  };
931
1138
  return {
932
- id: "spa",
933
- buildConfig,
934
- capabilities: ({ hasServerCode }) => ({
935
- staticExport: !hasServerCode,
1139
+ process: child,
1140
+ async identify() {
1141
+ const info = await readProcess(pid());
1142
+ if (info) return {
1143
+ pid: info.pid,
1144
+ startTime: info.startTime
1145
+ };
1146
+ if (child.exitCode !== null || child.signalCode !== null) return void 0;
1147
+ throw new Error(`Couldn't read the process identity of ${spec.kind} ${pid()}.`);
1148
+ },
1149
+ release() {
1150
+ gate?.end("go\n");
1151
+ },
1152
+ running: () => child.exitCode === null && child.signalCode === null,
1153
+ end: (graceMs, extraGroups) => end([pid(), ...extraGroups], graceMs),
1154
+ sweep: (extraGroups) => end([pid(), ...extraGroups], 2e3),
1155
+ kill() {
1156
+ signalGroup(pid(), "SIGKILL");
1157
+ }
1158
+ };
1159
+ }
1160
+ function launchWindows(spec) {
1161
+ const hung = (spec.env["MOSTRA_TEST_GATE"] ?? "").split(",").includes("ignore-lifeline");
1162
+ const child = spawn(helperPath(), [
1163
+ "gate",
1164
+ "--",
1165
+ spec.command,
1166
+ ...spec.args
1167
+ ], {
1168
+ cwd: spec.cwd,
1169
+ env: spec.env,
1170
+ windowsHide: true,
1171
+ detached: hung,
1172
+ stdio: stdioFor(spec.extra),
1173
+ serialization: "json"
1174
+ });
1175
+ const lifeline = child.stdio[3];
1176
+ lifeline?.on("error", () => {});
1177
+ const report = new Promise((resolve, reject) => {
1178
+ let text = "";
1179
+ const onData = (chunk) => {
1180
+ text += chunk.toString("utf8");
1181
+ const end = text.indexOf("\n");
1182
+ if (end < 0) return;
1183
+ lifeline?.off("data", onData);
1184
+ try {
1185
+ const line = JSON.parse(text.slice(0, end));
1186
+ if (line.pid !== void 0 && line.startTime !== void 0) resolve({
1187
+ pid: line.pid,
1188
+ startTime: line.startTime
1189
+ });
1190
+ else reject(/* @__PURE__ */ new Error(`The gate couldn't start ${spec.kind}: ${line.error ?? text.slice(0, end)}`));
1191
+ } catch {
1192
+ reject(/* @__PURE__ */ new Error(`The gate of ${spec.kind} reported ${text.slice(0, 200)}`));
1193
+ }
1194
+ };
1195
+ lifeline?.on("data", onData);
1196
+ child.once("exit", () => resolve(void 0));
1197
+ child.once("error", reject);
1198
+ });
1199
+ const exited = new Promise((resolve) => {
1200
+ if (child.exitCode !== null) resolve();
1201
+ child.once("exit", () => resolve());
1202
+ });
1203
+ const running = () => child.exitCode === null && child.signalCode === null;
1204
+ return {
1205
+ process: child,
1206
+ identify: () => report,
1207
+ release() {
1208
+ lifeline?.write("go\n");
1209
+ },
1210
+ running,
1211
+ async end(graceMs) {
1212
+ lifeline?.end();
1213
+ if (!running()) return;
1214
+ let timer;
1215
+ await Promise.race([exited, new Promise((resolve) => timer = setTimeout(resolve, graceMs))]);
1216
+ clearTimeout(timer);
1217
+ if (running()) child.kill();
1218
+ await Promise.race([exited, delay$1(KILL_WAIT_MS)]);
1219
+ },
1220
+ async sweep() {},
1221
+ kill() {
1222
+ lifeline?.destroy();
1223
+ child.kill();
1224
+ }
1225
+ };
1226
+ }
1227
+ /**
1228
+ * Ends what a previous supervisor's children left running, by their recorded identities, and
1229
+ * leaves alone processes that only look like them (FAILURE_MODEL §2). Call it only while holding
1230
+ * the home's ledger lock.
1231
+ */
1232
+ function reapRecorded(rows, warn) {
1233
+ return WINDOWS ? reapWindows(rows, warn) : reapPosix(rows, warn);
1234
+ }
1235
+ async function reapWindows(rows, warn) {
1236
+ if (rows.length === 0) return [];
1237
+ const answers = await runHelperAsync(["reap", ...rows.map((row) => `${row.pid}:${row.start_time}`)]);
1238
+ return rows.map((row, index) => {
1239
+ const answer = answers[index];
1240
+ if (answer?.error !== void 0) warn("process.reap_incomplete", {
1241
+ pid: row.pid,
1242
+ error: answer.error
1243
+ });
1244
+ const ended = answer?.ended ?? [];
1245
+ if (ended.length > 0) return { ended };
1246
+ return {
1247
+ ended: [],
1248
+ skipped: answer?.reused ? "pid reused" : "gone"
1249
+ };
1250
+ });
1251
+ }
1252
+ /** The processes of a recorded group that are provably the recorded child's. */
1253
+ function targetsFor(row, processes) {
1254
+ const leader = processes.find((info) => info.pid === row.pid);
1255
+ if (leader && leader.startTime !== row.start_time) return "pid reused";
1256
+ if (!leader) {
1257
+ const boot = processes.find((info) => info.pid === process.pid)?.startTime;
1258
+ if (boot === void 0 || !sameBoot(boot, row.start_time)) return "other boot";
1259
+ }
1260
+ const members = processes.filter((info) => info.pgid === row.pgid && info.pid !== process.pid).filter((info) => startedNoEarlier(info.startTime, row.start_time)).map((info) => info.pid);
1261
+ return members.length > 0 ? members : "gone";
1262
+ }
1263
+ function signalAll(pids, signal) {
1264
+ for (const pid of pids) try {
1265
+ process.kill(pid, signal);
1266
+ } catch {}
1267
+ }
1268
+ async function reapPosix(rows, warn) {
1269
+ if (rows.length === 0) return [];
1270
+ const before = await listProcesses();
1271
+ const plan = rows.map((row) => ({
1272
+ row,
1273
+ targets: targetsFor(row, before)
1274
+ }));
1275
+ const owned = plan.filter((entry) => Array.isArray(entry.targets)).map((entry) => entry.row);
1276
+ const members = (processes) => [...new Set(owned.flatMap((row) => {
1277
+ const targets = targetsFor(row, processes);
1278
+ return Array.isArray(targets) ? targets : [];
1279
+ }))];
1280
+ const groupsLeft = () => owned.some((row) => groupAlive(row.pgid));
1281
+ signalAll(members(before), "SIGTERM");
1282
+ const deadline = Date.now() + REAP_GRACE_MS;
1283
+ let remaining = members(await listProcesses());
1284
+ while ((remaining.length > 0 || groupsLeft()) && Date.now() < deadline) {
1285
+ await delay$1(100);
1286
+ remaining = members(await listProcesses());
1287
+ }
1288
+ const killDeadline = Date.now() + KILL_WAIT_MS;
1289
+ while ((remaining.length > 0 || groupsLeft()) && Date.now() < killDeadline) {
1290
+ signalAll(remaining, "SIGKILL");
1291
+ await delay$1(50);
1292
+ remaining = members(await listProcesses());
1293
+ }
1294
+ if (remaining.length > 0 || groupsLeft()) warn("process.reap_incomplete", {
1295
+ pids: remaining,
1296
+ pgids: owned.map((row) => row.pgid)
1297
+ });
1298
+ return plan.map(({ targets }) => Array.isArray(targets) ? { ended: targets } : {
1299
+ ended: [],
1300
+ skipped: targets
1301
+ });
1302
+ }
1303
+ /**
1304
+ * Whether `pid` can be adopted by a child whose own group is `childPgid`: on POSIX a program the
1305
+ * child started in its own session (a PTY program), which only a group leader is; on Windows every
1306
+ * descendant is already in the child's job and ends with it, so a running process needs nothing
1307
+ * more (it isn't recorded again).
1308
+ */
1309
+ async function adoptable(pid) {
1310
+ const info = await readProcess(pid);
1311
+ if (!info) return void 0;
1312
+ if (WINDOWS) return {
1313
+ info,
1314
+ record: false
1315
+ };
1316
+ return info.pgid === info.pid ? {
1317
+ info,
1318
+ record: true
1319
+ } : void 0;
1320
+ }
1321
+ //#endregion
1322
+ //#region src/platform/control.ts
1323
+ /**
1324
+ * The home's control endpoint (D81, D82; RT-06, RT-10): how attached clients reach the
1325
+ * supervisor. On POSIX it is a Unix socket in the owner-only runtime directory; on Windows a named
1326
+ * pipe that only the user can open and that refuses remote clients, which the helper creates and
1327
+ * forwards to the supervisor over its descriptor 4 (`crates/mostra-win/src/win/pipe.rs`), because
1328
+ * Node.js's own pipes let any local user open them for reading (VERIFIED_FACTS, WP-W1).
1329
+ *
1330
+ * Either way the caller gets one stream per client and a listener it can check and replace: a
1331
+ * socket file that disappeared, or a pipe whose helper stopped, is bound again (D81 item 4).
1332
+ */
1333
+ /**
1334
+ * The endpoint for a home. POSIX: `<runtime dir>/<home hash>.sock`, refused with
1335
+ * `MOSTRA_HOME_SOCKET_TOO_LONG` past the system's limit. Windows: `\\.\pipe\mostra-<home hash>`,
1336
+ * to which each bind adds a random part, so no other program can create the name before the
1337
+ * supervisor does; clients learn the full name from `instance.json`.
1338
+ */
1339
+ function controlEndpoint(runtimeDir, hash, os = OS) {
1340
+ if (os === "win32" || runtimeDir === void 0) return `\\\\.\\pipe\\mostra-${hash}`;
1341
+ const path = pathsOf(os).join(runtimeDir, `${hash}.sock`);
1342
+ const limit = socketPathLimit(os);
1343
+ const length = Buffer.byteLength(path);
1344
+ if (length > limit) throw new RpcError(createDiagnostic("MOSTRA_HOME_SOCKET_TOO_LONG", {
1345
+ message: `The control socket path ${path} is ${length} bytes; this system allows ${limit}.`,
1346
+ fix: {
1347
+ kind: "command",
1348
+ command: "export MOSTRA_RUNTIME_DIR=/tmp/mostra-$USER"
1349
+ }
1350
+ }));
1351
+ return path;
1352
+ }
1353
+ /** Binds `endpoint` and calls `onConnection` for every client. */
1354
+ function listenControl(endpoint, onConnection, options = {}) {
1355
+ if (WINDOWS) return listenPipe(endpoint, onConnection, options.launchPipe ?? launchPipeDirectly);
1356
+ return listenSocket(endpoint, onConnection, options.onError ?? (() => {}));
1357
+ }
1358
+ const PIPE_PREFIX = "\\\\.\\pipe\\";
1359
+ /**
1360
+ * Starts the pipe's helper behind its gate without a process manager to record it: for a
1361
+ * protocol server outside an instance (the instance always records its helper).
1362
+ */
1363
+ const launchPipeDirectly = async (name) => {
1364
+ const launched = launch({
1365
+ kind: "control-pipe",
1366
+ command: helperPath(),
1367
+ args: ["pipe", name],
1368
+ env: process.env,
1369
+ extra: "channel"
1370
+ }, () => {});
1371
+ const exited = new Promise((resolve) => launched.process.once("exit", resolve));
1372
+ await launched.identify();
1373
+ launched.release();
1374
+ const channel = launched.process.stdio[4];
1375
+ if (!channel) throw new Error("The control pipe's helper has no channel.");
1376
+ return {
1377
+ channel,
1378
+ exited,
1379
+ stop: () => launched.end(2e3, [])
1380
+ };
1381
+ };
1382
+ async function listenSocket(path, onConnection, onError) {
1383
+ mkdirSync(dirname(path), {
1384
+ recursive: true,
1385
+ mode: 448
1386
+ });
1387
+ try {
1388
+ unlinkSync(path);
1389
+ } catch (error) {
1390
+ if (error.code !== "ENOENT") throw error;
1391
+ }
1392
+ const server = createServer((socket) => onConnection(socket));
1393
+ await new Promise((resolve, reject) => {
1394
+ server.once("error", reject);
1395
+ server.listen(path, () => {
1396
+ server.off("error", reject);
1397
+ resolve();
1398
+ });
1399
+ });
1400
+ chmodSync(path, 384);
1401
+ server.on("error", onError);
1402
+ const stats = statSync(path);
1403
+ const same = () => {
1404
+ try {
1405
+ const current = statSync(path);
1406
+ return current.ino === stats.ino && current.dev === stats.dev;
1407
+ } catch {
1408
+ return false;
1409
+ }
1410
+ };
1411
+ return {
1412
+ path,
1413
+ intact: same,
1414
+ async close() {
1415
+ const ours = same();
1416
+ server.close();
1417
+ if (ours) try {
1418
+ unlinkSync(path);
1419
+ } catch {}
1420
+ }
1421
+ };
1422
+ }
1423
+ const OPEN = 1;
1424
+ const DATA = 2;
1425
+ const CLOSE = 3;
1426
+ const READY = 4;
1427
+ const FATAL = 5;
1428
+ /** The largest payload the supervisor sends in one frame. */
1429
+ const MAX_FRAME = 1 << 20;
1430
+ /** How long the helper may take to create the pipe. */
1431
+ const READY_MS = 1e4;
1432
+ /** How long a closing listener waits for its helper to hand clients their bytes (its own 5 s). */
1433
+ const DRAIN_MS = 6e3;
1434
+ function frame(connection, kind, payload) {
1435
+ const header = Buffer.alloc(9);
1436
+ header.writeUInt32LE(connection, 0);
1437
+ header[4] = kind;
1438
+ header.writeUInt32LE(payload?.length ?? 0, 5);
1439
+ return payload ? Buffer.concat([header, payload]) : header;
1440
+ }
1441
+ async function listenPipe(base, onConnection, launchPipe) {
1442
+ const helper = await launchPipe(`${base.startsWith(PIPE_PREFIX) ? base.slice(9) : `mostra-${createHash("sha256").update(base).digest("hex").slice(0, 16)}`}-${randomBytes(8).toString("hex")}`);
1443
+ const streams = /* @__PURE__ */ new Map();
1444
+ let exited = false;
1445
+ let failed = false;
1446
+ let path;
1447
+ helper.exited.then(() => {
1448
+ exited = true;
1449
+ for (const stream of streams.values()) stream.destroy();
1450
+ streams.clear();
1451
+ });
1452
+ const send = (bytes) => {
1453
+ if (!exited && !helper.channel.destroyed) helper.channel.write(bytes);
1454
+ };
1455
+ const ready = new Promise((resolve, reject) => {
1456
+ const timer = setTimeout(() => reject(/* @__PURE__ */ new Error("The control pipe's helper didn't create the pipe in time.")), READY_MS);
1457
+ let pending = Buffer.alloc(0);
1458
+ helper.channel.on("data", (chunk) => {
1459
+ pending = pending.length === 0 ? chunk : Buffer.concat([pending, chunk]);
1460
+ while (pending.length >= 9) {
1461
+ const length = pending.readUInt32LE(5);
1462
+ if (pending.length < 9 + length) break;
1463
+ const id = pending.readUInt32LE(0);
1464
+ const kind = pending[4];
1465
+ const payload = pending.subarray(9, 9 + length);
1466
+ pending = pending.subarray(9 + length);
1467
+ if (kind === READY) {
1468
+ clearTimeout(timer);
1469
+ path = payload.toString("utf8");
1470
+ resolve(path);
1471
+ } else if (kind === FATAL) {
1472
+ clearTimeout(timer);
1473
+ const why = `The control pipe can't be served: ${payload.toString("utf8")}`;
1474
+ if (path === void 0) reject(new Error(why));
1475
+ else {
1476
+ failed = true;
1477
+ helper.stop();
1478
+ }
1479
+ } else if (kind === OPEN) {
1480
+ const stream = clientStream(id, send, () => streams.delete(id));
1481
+ streams.set(id, stream);
1482
+ onConnection(stream);
1483
+ } else if (kind === DATA) streams.get(id)?.push(Buffer.from(payload));
1484
+ else if (kind === CLOSE) {
1485
+ const stream = streams.get(id);
1486
+ streams.delete(id);
1487
+ if (stream) {
1488
+ stream.push(null);
1489
+ stream.end();
1490
+ }
1491
+ }
1492
+ }
1493
+ });
1494
+ helper.exited.then(() => {
1495
+ clearTimeout(timer);
1496
+ reject(/* @__PURE__ */ new Error("The control pipe's helper exited."));
1497
+ });
1498
+ });
1499
+ helper.channel.on("error", () => {});
1500
+ let bound;
1501
+ try {
1502
+ bound = await ready;
1503
+ } catch (error) {
1504
+ await helper.stop();
1505
+ throw error;
1506
+ }
1507
+ return {
1508
+ path: bound,
1509
+ intact: () => !exited && !failed,
1510
+ async close() {
1511
+ for (const stream of streams.values()) stream.end();
1512
+ if (!exited) send(frame(0, CLOSE));
1513
+ let timer;
1514
+ await Promise.race([helper.exited, new Promise((resolve) => {
1515
+ timer = setTimeout(resolve, DRAIN_MS);
1516
+ })]);
1517
+ clearTimeout(timer);
1518
+ for (const stream of streams.values()) stream.destroy();
1519
+ streams.clear();
1520
+ await helper.stop();
1521
+ }
1522
+ };
1523
+ }
1524
+ /** One client's stream over the helper's channel. */
1525
+ function clientStream(id, send, forget) {
1526
+ let closed = false;
1527
+ const close = () => {
1528
+ if (closed) return;
1529
+ closed = true;
1530
+ forget();
1531
+ send(frame(id, CLOSE));
1532
+ };
1533
+ return new Duplex({
1534
+ read() {},
1535
+ write(chunk, _encoding, callback) {
1536
+ for (let offset = 0; offset < chunk.length; offset += MAX_FRAME) send(frame(id, DATA, chunk.subarray(offset, offset + MAX_FRAME)));
1537
+ callback();
1538
+ },
1539
+ final(callback) {
1540
+ close();
1541
+ callback();
1542
+ },
1543
+ destroy(error, callback) {
1544
+ close();
1545
+ callback(error);
1546
+ }
1547
+ });
1548
+ }
1549
+ /** Why a client couldn't open a control endpoint. */
1550
+ var ControlConnectError = class extends Error {
1551
+ /** `unreachable` (nothing serves it, or it timed out) or `not-owned` (another user's pipe). */
1552
+ reason;
1553
+ constructor(reason, message) {
1554
+ super(message);
1555
+ this.name = "ControlConnectError";
1556
+ this.reason = reason;
1557
+ }
1558
+ };
1559
+ /**
1560
+ * Connects to a home's control endpoint as a client. On Windows through `mostra-win connect`,
1561
+ * which refuses a pipe another user created under the name (an old name `instance.json` still
1562
+ * names may be free for anyone to take), and never lets the server act as this process: Node.js
1563
+ * can check neither (Opus review of WP-W1). Rejects with a {@link ControlConnectError}.
1564
+ */
1565
+ function connectControl(endpoint, timeoutMs = 5e3) {
1566
+ return WINDOWS ? connectPipe(endpoint, timeoutMs) : connectSocket$1(endpoint, timeoutMs);
1567
+ }
1568
+ function connectSocket$1(path, timeoutMs) {
1569
+ return new Promise((resolve, reject) => {
1570
+ const socket = createConnection(path);
1571
+ const timer = setTimeout(() => {
1572
+ socket.destroy();
1573
+ reject(new ControlConnectError("unreachable", "timed out"));
1574
+ }, timeoutMs);
1575
+ socket.once("error", (error) => {
1576
+ clearTimeout(timer);
1577
+ reject(new ControlConnectError("unreachable", error.code ?? "failed"));
1578
+ });
1579
+ socket.once("connect", () => {
1580
+ clearTimeout(timer);
1581
+ resolve(socket);
1582
+ });
1583
+ });
1584
+ }
1585
+ function connectPipe(endpoint, timeoutMs) {
1586
+ const name = endpoint.startsWith(PIPE_PREFIX) ? endpoint.slice(9) : endpoint;
1587
+ return new Promise((resolve, reject) => {
1588
+ const child = spawn(helperPath(), ["connect", name], {
1589
+ stdio: [
1590
+ "pipe",
1591
+ "pipe",
1592
+ "pipe"
1593
+ ],
1594
+ windowsHide: true
1595
+ });
1596
+ let settled = false;
1597
+ const fail = (reason, message) => {
1598
+ if (settled) return;
1599
+ settled = true;
1600
+ clearTimeout(timer);
1601
+ child.kill();
1602
+ reject(new ControlConnectError(reason, message));
1603
+ };
1604
+ const timer = setTimeout(() => fail("unreachable", "timed out"), timeoutMs);
1605
+ child.once("error", (error) => fail("unreachable", error.message));
1606
+ child.once("exit", (code) => fail(code === 3 ? "not-owned" : "unreachable", `exit ${code}`));
1607
+ let text = "";
1608
+ child.stderr.setEncoding("utf8");
1609
+ child.stderr.on("data", (chunk) => {
1610
+ if (settled) return;
1611
+ text += chunk;
1612
+ const end = text.indexOf("\n");
1613
+ if (end < 0) return;
1614
+ let line = {};
1615
+ try {
1616
+ line = JSON.parse(text.slice(0, end));
1617
+ } catch {}
1618
+ if (line.connected !== true) {
1619
+ fail(line.code === "not-owned" ? "not-owned" : "unreachable", line.error ?? text.slice(0, end));
1620
+ return;
1621
+ }
1622
+ settled = true;
1623
+ clearTimeout(timer);
1624
+ resolve(Duplex.from({
1625
+ readable: child.stdout,
1626
+ writable: child.stdin
1627
+ }));
1628
+ });
1629
+ });
1630
+ }
1631
+ //#endregion
1632
+ //#region src/platform/environment.ts
1633
+ /**
1634
+ * The smallest environment a child can run in (the builder's): `PATH`, `HOME` and `TMPDIR` on
1635
+ * POSIX. Windows programs need more of what Windows itself gives every program (without
1636
+ * `SystemRoot` Node.js can't load its cryptography, without `TEMP` it has no temporary folder),
1637
+ * and Windows compares variable names without case, so they are found that way.
1638
+ */
1639
+ /**
1640
+ * What Windows itself gives every program and programs rely on, besides `Path`: the system's
1641
+ * directories, the user's profile folders, the shell and how it finds programs, who the user is
1642
+ * and the processor. None names a secret. The one list both the base and the artifact environment
1643
+ * pass on Windows (`processes/environment.ts`).
1644
+ */
1645
+ const WINDOWS_SYSTEM_VARIABLES = [
1646
+ "SystemRoot",
1647
+ "SystemDrive",
1648
+ "windir",
1649
+ "ComSpec",
1650
+ "PATHEXT",
1651
+ "TEMP",
1652
+ "TMP",
1653
+ "USERPROFILE",
1654
+ "HOMEDRIVE",
1655
+ "HOMEPATH",
1656
+ "APPDATA",
1657
+ "LOCALAPPDATA",
1658
+ "ProgramData",
1659
+ "ProgramFiles",
1660
+ "ProgramFiles(x86)",
1661
+ "ProgramW6432",
1662
+ "CommonProgramFiles",
1663
+ "CommonProgramFiles(x86)",
1664
+ "CommonProgramW6432",
1665
+ "USERNAME",
1666
+ "USERDOMAIN",
1667
+ "COMPUTERNAME",
1668
+ "OS",
1669
+ "NUMBER_OF_PROCESSORS",
1670
+ "PROCESSOR_ARCHITECTURE",
1671
+ "PROCESSOR_IDENTIFIER"
1672
+ ];
1673
+ const WINDOWS_BASE = ["Path", ...WINDOWS_SYSTEM_VARIABLES];
1674
+ /** The base environment of a child, from the supervisor's `env`. */
1675
+ function baseEnvironment(env) {
1676
+ if (!WINDOWS) return {
1677
+ PATH: env["PATH"] ?? "/usr/bin:/bin",
1678
+ HOME: env["HOME"] ?? "/",
1679
+ ...env["TMPDIR"] ? { TMPDIR: env["TMPDIR"] } : {}
1680
+ };
1681
+ const byName = new Map(Object.entries(env).map(([name, value]) => [name.toUpperCase(), value]));
1682
+ const result = {};
1683
+ for (const name of WINDOWS_BASE) {
1684
+ const value = byName.get(name.toUpperCase());
1685
+ if (value !== void 0) result[name] = value;
1686
+ }
1687
+ return result;
1688
+ }
1689
+ /** Packages whose versions define the SPA build; they are part of `buildConfigDigest` (VR-01). */
1690
+ const BUILD_PACKAGES = [
1691
+ "vite",
1692
+ "@vitejs/plugin-react",
1693
+ "@mdx-js/mdx",
1694
+ "remark-frontmatter",
1695
+ "remark-gfm",
1696
+ "@tailwindcss/vite",
1697
+ "oxc-parser"
1698
+ ];
1699
+ /** Bumped whenever the SPA build's settings change, so older versions aren't reused. */
1700
+ const SPA_CONFIG_REVISION = 7;
1701
+ /** The directory of `@mostra/runtime`'s package.json. */
1702
+ function runtimeRoot() {
1703
+ let dir = dirname(fileURLToPath(import.meta.url));
1704
+ for (;;) {
1705
+ const manifest = join(dir, "package.json");
1706
+ if (existsSync(manifest)) {
1707
+ const { name } = JSON.parse(readFileSync(manifest, "utf8"));
1708
+ if (name === "@mostra/runtime") return dir;
1709
+ }
1710
+ const parent = dirname(dir);
1711
+ if (parent === dir) throw new Error("Couldn't find @mostra/runtime's package.json.");
1712
+ dir = parent;
1713
+ }
1714
+ }
1715
+ /** Node's lookup of an installed package's directory, from `from` upwards. */
1716
+ function packageDir(name, from) {
1717
+ let dir = from;
1718
+ for (;;) {
1719
+ const candidate = join(dir, "node_modules", name);
1720
+ if (existsSync(join(candidate, "package.json"))) return realpathSync(candidate);
1721
+ const parent = dirname(dir);
1722
+ if (parent === dir) return void 0;
1723
+ dir = parent;
1724
+ }
1725
+ }
1726
+ function versionOf(dir) {
1727
+ return JSON.parse(readFileSync(join(dir, "package.json"), "utf8")).version;
1728
+ }
1729
+ /** The builder child's entry: the compiled one beside the compiled supervisor, else the source. */
1730
+ function childEntry$1(root) {
1731
+ return fileURLToPath(import.meta.url).endsWith(".ts") ? join(root, "src/builder/child/main.ts") : join(root, "dist/builder/child/main.js");
1732
+ }
1733
+ /** The SPA render mode (D19): every build in its own builder child. */
1734
+ function createSpaRenderMode(options) {
1735
+ const root = runtimeRoot();
1736
+ const buildPackages = {};
1737
+ for (const name of BUILD_PACKAGES) {
1738
+ const dir = packageDir(name, root);
1739
+ if (!dir) throw new Error(`The runtime is missing its build dependency ${name}.`);
1740
+ buildPackages[name] = versionOf(dir);
1741
+ }
1742
+ const buildConfig = {
1743
+ mode: "spa",
1744
+ revision: SPA_CONFIG_REVISION,
1745
+ base: "/",
1746
+ sourcemap: true,
1747
+ packages: buildPackages,
1748
+ stagingFiles: STAGING_FILES
1749
+ };
1750
+ const timeoutMs = options.timeoutMs ?? 18e4;
1751
+ const childEnv = {
1752
+ ...baseEnvironment(options.env ?? process.env),
1753
+ NODE_ENV: "production"
1754
+ };
1755
+ return {
1756
+ id: "spa",
1757
+ buildConfig,
1758
+ capabilities: ({ hasServerCode }) => ({
1759
+ staticExport: !hasServerCode,
936
1760
  mcpApp: true,
937
1761
  needsWorker: hasServerCode
938
1762
  }),
@@ -1114,13 +1938,17 @@ function faultsFrom(env) {
1114
1938
  const separator = entry.lastIndexOf(":");
1115
1939
  const point = entry.slice(0, separator).trim();
1116
1940
  const action = entry.slice(separator + 1).trim();
1117
- if (point && (action === "throw" || action === "crash" || action === "hang")) configured.set(point, action);
1941
+ if (point && (action === "throw" || action === "throw-once" || action === "crash" || action === "hang")) configured.set(point, action);
1118
1942
  }
1119
1943
  return {
1120
1944
  hangs: (point) => configured.get(point) === "hang",
1121
1945
  at(point) {
1122
1946
  const action = configured.get(point);
1123
1947
  if (action === "throw") throw new InjectedFault(point);
1948
+ if (action === "throw-once") {
1949
+ configured.delete(point);
1950
+ throw new InjectedFault(point);
1951
+ }
1124
1952
  if (action === "crash") {
1125
1953
  process.kill(process.pid, "SIGKILL");
1126
1954
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1e4);
@@ -1755,12 +2583,7 @@ function createLedgerFile(storeDir, file, log) {
1755
2583
  } finally {
1756
2584
  db.close();
1757
2585
  }
1758
- const fd = openSync(temp, "r");
1759
- try {
1760
- fsyncSync(fd);
1761
- } finally {
1762
- closeSync(fd);
1763
- }
2586
+ fsyncPath(temp);
1764
2587
  try {
1765
2588
  linkSync(temp, file);
1766
2589
  log.info("ledger.created", { file });
@@ -1772,14 +2595,7 @@ function createLedgerFile(storeDir, file, log) {
1772
2595
  syncDirectory(storeDir);
1773
2596
  }
1774
2597
  function syncDirectory(dir) {
1775
- try {
1776
- const fd = openSync(dir, "r");
1777
- try {
1778
- fsyncSync(fd);
1779
- } finally {
1780
- closeSync(fd);
1781
- }
1782
- } catch {}
2598
+ fsyncPath(dir, true);
1783
2599
  }
1784
2600
  /**
1785
2601
  * Removes `*.creating` files left by starters that died while building a ledger. A file whose
@@ -1935,313 +2751,144 @@ function migrate(db, file, storeDir, latest, migrations, options) {
1935
2751
  function inodeOf(file) {
1936
2752
  try {
1937
2753
  const stats = statSync(file);
1938
- return `${stats.dev}:${stats.ino}`;
1939
- } catch {
1940
- return;
1941
- }
1942
- }
1943
- function wrap(db, file, schemaVersion, migrated) {
1944
- const target = queries(db);
1945
- let open = true;
1946
- const listeners = /* @__PURE__ */ new Set();
1947
- const opened = inodeOf(file);
1948
- const assertInPlace = () => {
1949
- if (inodeOf(file) === opened) return;
1950
- throw new RpcError(createDiagnostic("MOSTRA_HOME_GONE", { message: `The ledger ${file} was moved or deleted while the instance was running.` }));
1951
- };
1952
- const guarded = (run) => {
1953
- try {
1954
- return run();
1955
- } catch (error) {
1956
- throw diagnose$1(error, file) ?? error;
1957
- }
1958
- };
1959
- return {
1960
- file,
1961
- schemaVersion,
1962
- migrated,
1963
- write(fn) {
1964
- assertInPlace();
1965
- const result = guarded(() => db.transaction(() => fn(target)).immediate());
1966
- assertInPlace();
1967
- if (db.inTransaction) return result;
1968
- for (const listener of listeners) try {
1969
- listener();
1970
- } catch {}
1971
- return result;
1972
- },
1973
- onCommit(listener) {
1974
- listeners.add(listener);
1975
- return () => listeners.delete(listener);
1976
- },
1977
- read(fn) {
1978
- return guarded(() => db.transaction(() => fn(target)).deferred());
1979
- },
1980
- checkIntegrity() {
1981
- const problems = db.pragma("integrity_check").map((row) => row.integrity_check).filter((text) => text !== "ok");
1982
- return {
1983
- ok: problems.length === 0,
1984
- problems
1985
- };
1986
- },
1987
- close() {
1988
- if (!open) return;
1989
- open = false;
1990
- db.close();
1991
- }
1992
- };
1993
- }
1994
- //#endregion
1995
- //#region src/processes/environment.ts
1996
- /**
1997
- * The artifact environment (D95, DP-05): what a child that runs an artifact's own code, or code
1998
- * the artifact chose such as a package's lifecycle script, receives from the supervisor's
1999
- * environment. It is an allowlist, so the supervisor's own settings and a host's credentials
2000
- * (anything a spawning host put into Mostra's environment) never reach artifact code by accident.
2001
- * Install children use it from WP-04 on; workers (WP-08) start from it too.
2002
- */
2003
- /** Variables an artifact's processes need to work like an ordinary shell's programs. */
2004
- const PASSED = /* @__PURE__ */ new Set([
2005
- "PATH",
2006
- "HOME",
2007
- "TMPDIR",
2008
- "LANG",
2009
- "LC_ALL",
2010
- "LC_CTYPE",
2011
- "TZ",
2012
- "USER",
2013
- "LOGNAME",
2014
- "SHELL",
2015
- "TERM",
2016
- "XDG_CACHE_HOME",
2017
- "XDG_CONFIG_HOME",
2018
- "XDG_DATA_HOME",
2019
- "CC",
2020
- "CXX",
2021
- "MAKE",
2022
- "PYTHON",
2023
- "DEVELOPER_DIR",
2024
- "SDKROOT",
2025
- "HTTP_PROXY",
2026
- "HTTPS_PROXY",
2027
- "NO_PROXY",
2028
- "http_proxy",
2029
- "https_proxy",
2030
- "no_proxy",
2031
- "NODE_EXTRA_CA_CERTS",
2032
- "SSL_CERT_FILE",
2033
- "SSL_CERT_DIR"
2034
- ]);
2035
- /** npm's own configuration channel: the user's registry, scopes and proxies for installs. */
2036
- const NPM_CONFIG = /^npm_config_/i;
2037
- /**
2038
- * The artifact environment derived from the supervisor's `env`. Its `PATH` starts with the
2039
- * directory of the Node.js the runtime runs on (D142): a lifecycle script or server code that runs
2040
- * `node` gets the runtime bundle's private Node.js, on a machine with no other Node.js too.
2041
- */
2042
- function artifactEnvironment(env) {
2043
- const result = {};
2044
- for (const [name, value] of Object.entries(env)) {
2045
- if (value === void 0) continue;
2046
- if (PASSED.has(name) || NPM_CONFIG.test(name)) result[name] = value;
2047
- }
2048
- const own = dirname(process.execPath);
2049
- const path = result["PATH"] ?? "/usr/bin:/bin";
2050
- result["PATH"] = path.split(delimiter)[0] === own ? path : `${own}${delimiter}${path}`;
2051
- return result;
2052
- }
2053
- //#endregion
2054
- //#region src/processes/identity.ts
2055
- /**
2056
- * Process identity (DATA_MODEL §3 `child.start_time`, FAILURE_MODEL §2). A PID alone can be
2057
- * reused, so a process is identified by its PID plus an opaque start time: the boot it started in
2058
- * and when it started within that boot. Linux reads `/proc/<pid>/stat` (start ticks since boot)
2059
- * and the boot ID; macOS reads `ps -o lstart` (seconds) and `kern.boottime` (VERIFIED_FACTS,
2060
- * WP-02). Zombies count as gone: they have exited and only wait for their parent.
2061
- *
2062
- * Seconds are enough on macOS (issue #8): XNU hands out PIDs in order from the last one, up to
2063
- * 99,999, then from 100, skipping any PID still used as a process, process group or session
2064
- * (`forkproc` in `bsd/kern/kern_fork.c`). A PID comes back only after the whole range has been
2065
- * handed out, about 99,900 forks, which takes this machine about 100 s at its measured 1,000
2066
- * spawns a second, and never while its process group lives (VERIFIED_FACTS, WP-08).
2067
- */
2068
- /** Splits a start time into its boot and its position within the boot. */
2069
- function parts(startTime) {
2070
- const slash = startTime.lastIndexOf("/");
2071
- if (slash <= 0) return void 0;
2072
- const at = Number(startTime.slice(slash + 1));
2073
- return Number.isSafeInteger(at) ? {
2074
- boot: startTime.slice(0, slash),
2075
- at
2076
- } : void 0;
2077
- }
2078
- /** Whether two start times belong to the same boot of the machine. */
2079
- function sameBoot(a, b) {
2080
- const left = parts(a);
2081
- const right = parts(b);
2082
- return left !== void 0 && right !== void 0 && left.boot === right.boot;
2083
- }
2084
- /**
2085
- * Whether `candidate` started in the same boot as `reference` and no earlier. On macOS the
2086
- * resolution is one second, so a process started in the same second counts as no earlier.
2087
- */
2088
- function startedNoEarlier(candidate, reference) {
2089
- const c = parts(candidate);
2090
- const r = parts(reference);
2091
- return c !== void 0 && r !== void 0 && c.boot === r.boot && c.at >= r.at;
2092
- }
2093
- /** Parses one `/proc/<pid>/stat` line. `comm` may contain spaces and parentheses. */
2094
- function parseProcStat(line, boot) {
2095
- const open = line.indexOf("(");
2096
- const close = line.lastIndexOf(")");
2097
- if (open < 0 || close < open) return void 0;
2098
- const pid = Number(line.slice(0, open).trim());
2099
- const rest = line.slice(close + 1).trim().split(/\s+/);
2100
- if (rest[0] === "Z") return void 0;
2101
- const pgid = Number(rest[2]);
2102
- const start = rest[19];
2103
- if (!Number.isSafeInteger(pid) || !Number.isSafeInteger(pgid) || start === void 0) return;
2104
- if (!/^\d+$/.test(start)) return void 0;
2105
- return {
2106
- pid,
2107
- pgid,
2108
- startTime: `${boot}/${start}`
2109
- };
2110
- }
2111
- const MONTHS = [
2112
- "Jan",
2113
- "Feb",
2114
- "Mar",
2115
- "Apr",
2116
- "May",
2117
- "Jun",
2118
- "Jul",
2119
- "Aug",
2120
- "Sep",
2121
- "Oct",
2122
- "Nov",
2123
- "Dec"
2124
- ];
2125
- /**
2126
- * Parses one line of `LC_ALL=C TZ=UTC ps -o pid=,pgid=,stat=,lstart=`, such as
2127
- * ` 214 99444 Ss Tue Oct 6 13:53:19 2026`. Zombies (`stat` starting with `Z`) are skipped.
2128
- */
2129
- function parsePsLine(line, boot) {
2130
- const fields = line.trim().split(/\s+/);
2131
- if (fields.length < 8) return void 0;
2132
- const [pidText, pgidText, stat, , monthText, dayText, timeText, yearText] = fields;
2133
- if (stat?.startsWith("Z")) return void 0;
2134
- const pid = Number(pidText);
2135
- const pgid = Number(pgidText);
2136
- const month = MONTHS.indexOf(monthText ?? "");
2137
- const [hours, minutes, seconds] = (timeText ?? "").split(":").map(Number);
2138
- const millis = Date.UTC(Number(yearText), month, Number(dayText), hours ?? NaN, minutes ?? NaN, seconds ?? NaN);
2139
- if (!Number.isSafeInteger(pid) || !Number.isSafeInteger(pgid) || month < 0 || Number.isNaN(millis)) return;
2140
- return {
2141
- pid,
2142
- pgid,
2143
- startTime: `${boot}/${millis / 1e3}`
2144
- };
2145
- }
2146
- function run$1(file, args) {
2147
- return new Promise((resolve, reject) => {
2148
- execFile(file, args, {
2149
- env: {
2150
- LC_ALL: "C",
2151
- TZ: "UTC",
2152
- PATH: "/usr/bin:/bin:/usr/sbin:/sbin"
2153
- },
2154
- maxBuffer: 67108864
2155
- }, (error, stdout) => {
2156
- if (error && typeof error.code !== "number") {
2157
- reject(error);
2158
- return;
2159
- }
2160
- resolve({
2161
- code: typeof error?.code === "number" ? error.code : 0,
2162
- stdout
2163
- });
2164
- });
2165
- });
2166
- }
2167
- let cachedBoot;
2168
- /** The identity of the current boot of this machine. */
2169
- function bootId() {
2170
- cachedBoot ??= (async () => {
2171
- if (process.platform === "linux") return (await readFile("/proc/sys/kernel/random/boot_id", "utf8")).trim();
2172
- const { stdout } = await run$1("/usr/sbin/sysctl", ["-n", "kern.boottime"]);
2173
- const match = /sec = (\d+), usec = (\d+)/.exec(stdout);
2174
- if (!match) throw new Error("Couldn't read kern.boottime.");
2175
- return `${match[1]}.${match[2]}`;
2176
- })();
2177
- return cachedBoot;
2178
- }
2179
- /** Reads one process, or `undefined` when no process has that PID. */
2180
- async function readProcess(pid) {
2181
- const boot = await bootId();
2182
- if (process.platform === "linux") try {
2183
- return parseProcStat(await readFile(`/proc/${pid}/stat`, "utf8"), boot);
2754
+ return `${stats.dev}:${stats.ino}`;
2184
2755
  } catch {
2185
2756
  return;
2186
2757
  }
2187
- const { code, stdout } = await run$1("/bin/ps", [
2188
- "-o",
2189
- "pid=,pgid=,stat=,lstart=",
2190
- "-p",
2191
- String(pid)
2192
- ]);
2193
- if (code !== 0) return void 0;
2194
- const [line] = stdout.split("\n").filter((text) => text.trim() !== "");
2195
- return line === void 0 ? void 0 : parsePsLine(line, boot);
2196
2758
  }
2197
- /** Lists every process the user can see. */
2198
- async function listProcesses() {
2199
- const boot = await bootId();
2200
- if (process.platform === "linux") {
2201
- const entries = (await readdir("/proc")).filter((name) => /^\d+$/.test(name));
2202
- return (await Promise.all(entries.map(async (name) => {
2203
- try {
2204
- return parseProcStat(await readFile(`/proc/${name}/stat`, "utf8"), boot);
2205
- } catch {
2206
- return;
2207
- }
2208
- }))).filter((info) => info !== void 0);
2209
- }
2210
- const { stdout } = await run$1("/bin/ps", [
2211
- "-A",
2212
- "-o",
2213
- "pid=,pgid=,stat=,lstart="
2214
- ]);
2215
- return stdout.split("\n").map((line) => parsePsLine(line, boot)).filter((info) => info !== void 0);
2759
+ function wrap(db, file, schemaVersion, migrated) {
2760
+ const target = queries(db);
2761
+ let open = true;
2762
+ const listeners = /* @__PURE__ */ new Set();
2763
+ const opened = inodeOf(file);
2764
+ const assertInPlace = () => {
2765
+ if (inodeOf(file) === opened) return;
2766
+ throw new RpcError(createDiagnostic("MOSTRA_HOME_GONE", { message: `The ledger ${file} was moved or deleted while the instance was running.` }));
2767
+ };
2768
+ const guarded = (run) => {
2769
+ try {
2770
+ return run();
2771
+ } catch (error) {
2772
+ throw diagnose$1(error, file) ?? error;
2773
+ }
2774
+ };
2775
+ return {
2776
+ file,
2777
+ schemaVersion,
2778
+ migrated,
2779
+ write(fn) {
2780
+ assertInPlace();
2781
+ const result = guarded(() => db.transaction(() => fn(target)).immediate());
2782
+ assertInPlace();
2783
+ if (db.inTransaction) return result;
2784
+ for (const listener of listeners) try {
2785
+ listener();
2786
+ } catch {}
2787
+ return result;
2788
+ },
2789
+ onCommit(listener) {
2790
+ listeners.add(listener);
2791
+ return () => listeners.delete(listener);
2792
+ },
2793
+ read(fn) {
2794
+ return guarded(() => db.transaction(() => fn(target)).deferred());
2795
+ },
2796
+ checkIntegrity() {
2797
+ const problems = db.pragma("integrity_check").map((row) => row.integrity_check).filter((text) => text !== "ok");
2798
+ return {
2799
+ ok: problems.length === 0,
2800
+ problems
2801
+ };
2802
+ },
2803
+ close() {
2804
+ if (!open) return;
2805
+ open = false;
2806
+ db.close();
2807
+ }
2808
+ };
2216
2809
  }
2217
- /** Whether the process recorded as `pid` and `startTime` is still the one running. */
2218
- async function isSameProcess(pid, startTime) {
2219
- const info = await readProcess(pid);
2220
- return info !== void 0 && info.startTime === startTime;
2810
+ //#endregion
2811
+ //#region src/processes/environment.ts
2812
+ /**
2813
+ * The artifact environment (D95, DP-05): what a child that runs an artifact's own code, or code
2814
+ * the artifact chose such as a package's lifecycle script, receives from the supervisor's
2815
+ * environment. It is an allowlist, so the supervisor's own settings and a host's credentials
2816
+ * (anything a spawning host put into Mostra's environment) never reach artifact code by accident.
2817
+ * Install children use it from WP-04 on; workers (WP-08) start from it too.
2818
+ */
2819
+ /** Variables an artifact's processes need to work like an ordinary shell's programs. */
2820
+ const PASSED = /* @__PURE__ */ new Set([
2821
+ "PATH",
2822
+ "HOME",
2823
+ "TMPDIR",
2824
+ "LANG",
2825
+ "LC_ALL",
2826
+ "LC_CTYPE",
2827
+ "TZ",
2828
+ "USER",
2829
+ "LOGNAME",
2830
+ "SHELL",
2831
+ "TERM",
2832
+ "XDG_CACHE_HOME",
2833
+ "XDG_CONFIG_HOME",
2834
+ "XDG_DATA_HOME",
2835
+ "CC",
2836
+ "CXX",
2837
+ "MAKE",
2838
+ "PYTHON",
2839
+ "DEVELOPER_DIR",
2840
+ "SDKROOT",
2841
+ "HTTP_PROXY",
2842
+ "HTTPS_PROXY",
2843
+ "NO_PROXY",
2844
+ "http_proxy",
2845
+ "https_proxy",
2846
+ "no_proxy",
2847
+ "NODE_EXTRA_CA_CERTS",
2848
+ "SSL_CERT_FILE",
2849
+ "SSL_CERT_DIR"
2850
+ ]);
2851
+ /** What Windows programs need besides the variables above (`platform`'s one list). */
2852
+ const PASSED_WINDOWS = new Set(WINDOWS_SYSTEM_VARIABLES.map((name) => name.toUpperCase()));
2853
+ const PASSED_UPPER = new Set([...PASSED].map((name) => name.toUpperCase()));
2854
+ /** npm's own configuration channel: the user's registry, scopes and proxies for installs. */
2855
+ const NPM_CONFIG = /^npm_config_/i;
2856
+ /**
2857
+ * The artifact environment derived from the supervisor's `env`. Its `PATH` starts with the
2858
+ * directory of the Node.js the runtime runs on (D142): a lifecycle script or server code that runs
2859
+ * `node` gets the runtime bundle's private Node.js, on a machine with no other Node.js too.
2860
+ */
2861
+ function artifactEnvironment(env) {
2862
+ const result = {};
2863
+ let pathName = "PATH";
2864
+ for (const [name, value] of Object.entries(env)) {
2865
+ if (value === void 0) continue;
2866
+ if (WINDOWS) {
2867
+ const upper = name.toUpperCase();
2868
+ if (upper === "PATH") pathName = name;
2869
+ if (PASSED_UPPER.has(upper) || PASSED_WINDOWS.has(upper) || NPM_CONFIG.test(name)) result[name] = value;
2870
+ } else if (PASSED.has(name) || NPM_CONFIG.test(name)) result[name] = value;
2871
+ }
2872
+ const own = dirname(process.execPath);
2873
+ const path = result[pathName] ?? (WINDOWS ? "" : "/usr/bin:/bin");
2874
+ const first = path.split(delimiter)[0] ?? "";
2875
+ const already = WINDOWS ? first.toLowerCase() === own.toLowerCase() : first === own;
2876
+ result[pathName] = already ? path : path === "" ? own : `${own}${delimiter}${path}`;
2877
+ return result;
2221
2878
  }
2222
2879
  //#endregion
2223
2880
  //#region src/processes/manager.ts
2224
2881
  /**
2225
- * The process manager (RT-09, ARCHITECTURE §4, FAILURE_MODEL §2). Every child runs as the leader
2226
- * of its own process group and is recorded in the ledger's `child` table with its PID and start
2227
- * time before anyone relies on it. A child's group dies with it, and a supervisor that starts
2228
- * after a crash reaps every recorded group that is still running.
2882
+ * The process manager (RT-09, RT-10, ARCHITECTURE §4, FAILURE_MODEL §2). Every child starts
2883
+ * behind a gate in a group of its own (a process group on POSIX, a Job Object on Windows,
2884
+ * `platform/launch.ts`) and is recorded in the ledger's `child` table with its PID and start
2885
+ * time before it may run. A child's group dies with it, and a supervisor that starts after a
2886
+ * crash reaps every recorded group that is still running.
2229
2887
  */
2230
2888
  /** How long a stopping child gets between SIGTERM and SIGKILL, by default. */
2231
2889
  const DEFAULT_GRACE_MS = 5e3;
2232
- /** How long reaping waits between SIGTERM and SIGKILL. */
2233
- const REAP_GRACE_MS = 2e3;
2234
- /** How long to wait for SIGKILLed processes to disappear before reporting them. */
2235
- const KILL_WAIT_MS = 5e3;
2236
2890
  /** How many stderr lines a child's exit report keeps. */
2237
2891
  const STDERR_TAIL = 50;
2238
- /**
2239
- * The gate every child starts behind (issue #7): `/bin/sh` waits for "go" on file descriptor 3 and
2240
- * only then replaces itself with the real command, keeping its PID, process group and start time.
2241
- * The supervisor writes "go" after it has recorded the child, so a supervisor killed in between
2242
- * leaves a gate that reads end-of-file and exits 125 without running anything.
2243
- */
2244
- const GATE_SCRIPT = "IFS= read -r go <&3 && [ \"$go\" = go ] || exit 125; exec 3<&-; exec \"$@\"";
2245
2892
  const AdoptParams = z.object({ pid: z.int().min(2) });
2246
2893
  /**
2247
2894
  * Opens the process manager: first reaps every child a previous supervisor of this home left
@@ -2249,28 +2896,12 @@ const AdoptParams = z.object({ pid: z.int().min(2) });
2249
2896
  * ledger lock, so no live supervisor's children are touched.
2250
2897
  */
2251
2898
  async function openProcessManager(options) {
2252
- const reaped = await reapRecorded(options.ledger, options.log);
2899
+ const reaped = await reap(options.ledger, options.log);
2253
2900
  return {
2254
2901
  manager: createManager(options),
2255
2902
  reaped
2256
2903
  };
2257
2904
  }
2258
- /** Signals `pids`, ignoring ones already gone. */
2259
- function signalAll(pids, signal) {
2260
- for (const pid of pids) try {
2261
- process.kill(pid, signal);
2262
- } catch {}
2263
- }
2264
- function signalGroup(pgid, signal) {
2265
- try {
2266
- process.kill(-pgid, signal);
2267
- return true;
2268
- } catch {
2269
- return false;
2270
- }
2271
- }
2272
- const groupAlive = (pgid) => signalGroup(pgid, 0);
2273
- const delay$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2274
2905
  /** Waits for `promise` to settle, or `ms` at most, leaving no timer behind. */
2275
2906
  async function settleWithin(promise, ms) {
2276
2907
  let timer;
@@ -2282,64 +2913,27 @@ async function settleWithin(promise, ms) {
2282
2913
  clearTimeout(timer);
2283
2914
  }
2284
2915
  }
2285
- /** The processes of a recorded group that are provably the recorded child's: see FAILURE_MODEL §2. */
2286
- function targetsFor(row, processes) {
2287
- const leader = processes.find((info) => info.pid === row.pid);
2288
- if (leader && leader.startTime !== row.start_time) return "pid reused";
2289
- if (!leader) {
2290
- const boot = processes.find((info) => info.pid === process.pid)?.startTime;
2291
- if (boot === void 0 || !sameBoot(boot, row.start_time)) return "other boot";
2292
- }
2293
- const members = processes.filter((info) => info.pgid === row.pgid && info.pid !== process.pid).filter((info) => startedNoEarlier(info.startTime, row.start_time)).map((info) => info.pid);
2294
- return members.length > 0 ? members : "gone";
2295
- }
2296
- async function reapRecorded(ledger, log) {
2916
+ async function reap(ledger, log) {
2297
2917
  const rows = ledger.read((db) => db.all("SELECT * FROM child ORDER BY started_at"));
2298
2918
  if (rows.length === 0) return [];
2299
- const before = await listProcesses();
2300
- const plan = rows.map((row) => ({
2301
- row,
2302
- targets: targetsFor(row, before)
2303
- }));
2304
- const owned = plan.filter((entry) => Array.isArray(entry.targets)).map((entry) => entry.row);
2305
- const members = (processes) => [...new Set(owned.flatMap((row) => {
2306
- const targets = targetsFor(row, processes);
2307
- return Array.isArray(targets) ? targets : [];
2308
- }))];
2309
- const groupsLeft = () => owned.some((row) => groupAlive(row.pgid));
2310
- signalAll(members(before), "SIGTERM");
2311
- const deadline = Date.now() + REAP_GRACE_MS;
2312
- let remaining = members(await listProcesses());
2313
- while ((remaining.length > 0 || groupsLeft()) && Date.now() < deadline) {
2314
- await delay$1(100);
2315
- remaining = members(await listProcesses());
2316
- }
2317
- const killDeadline = Date.now() + KILL_WAIT_MS;
2318
- while ((remaining.length > 0 || groupsLeft()) && Date.now() < killDeadline) {
2319
- signalAll(remaining, "SIGKILL");
2320
- await delay$1(50);
2321
- remaining = members(await listProcesses());
2322
- }
2323
- if (remaining.length > 0 || groupsLeft()) log.warn("process.reap_incomplete", {
2324
- pids: remaining,
2325
- pgids: owned.map((row) => row.pgid)
2326
- });
2919
+ const outcomes = await reapRecorded(rows, (event, fields) => log.warn(event, fields));
2327
2920
  ledger.write((db) => {
2328
- for (const { row } of plan) db.run("DELETE FROM child WHERE pid = ? AND start_time = ?", row.pid, row.start_time);
2921
+ for (const row of rows) db.run("DELETE FROM child WHERE pid = ? AND start_time = ?", row.pid, row.start_time);
2329
2922
  });
2330
- const report = plan.map(({ row, targets }) => {
2923
+ const report = rows.map((row, index) => {
2331
2924
  const base = {
2332
2925
  pid: row.pid,
2333
2926
  kind: row.kind,
2334
2927
  ownerRef: row.owner_ref
2335
2928
  };
2336
- return Array.isArray(targets) ? {
2929
+ const outcome = outcomes[index];
2930
+ return outcome?.skipped === void 0 ? {
2337
2931
  ...base,
2338
- signalled: targets
2932
+ signalled: outcome?.ended ?? []
2339
2933
  } : {
2340
2934
  ...base,
2341
2935
  signalled: [],
2342
- skipped: targets
2936
+ skipped: outcome.skipped
2343
2937
  };
2344
2938
  });
2345
2939
  for (const entry of report) log.info("process.reaped", { ...entry });
@@ -2354,62 +2948,27 @@ function createManager({ ledger, log, redactor, faults = noFaults }) {
2354
2948
  const forget = (pid) => {
2355
2949
  ledger.write((db) => db.run("DELETE FROM child WHERE pid = ? OR parent_pid = ?", pid, pid));
2356
2950
  };
2357
- /**
2358
- * Terminates groups: SIGTERM, then SIGKILL after `graceMs` to those still present, then waits
2359
- * (boundedly) until they are gone.
2360
- */
2361
- const endGroups = async (pgids, graceMs) => {
2362
- for (const pgid of pgids) signalGroup(pgid, "SIGTERM");
2363
- const deadline = Date.now() + graceMs;
2364
- while (Date.now() < deadline && pgids.some(groupAlive)) await delay$1(25);
2365
- for (const pgid of pgids) if (groupAlive(pgid)) signalGroup(pgid, "SIGKILL");
2366
- const killDeadline = Date.now() + KILL_WAIT_MS;
2367
- while (Date.now() < killDeadline && pgids.some(groupAlive)) await delay$1(10);
2368
- const left = pgids.filter(groupAlive);
2369
- if (left.length > 0) log.warn("process.group_survived_sigkill", { pgids: left });
2370
- };
2951
+ const warn = (event, fields) => log.warn(event, fields);
2371
2952
  const spawnChild = async (spec) => {
2372
2953
  if (stopping) throw new Error("The process manager is stopping.");
2373
2954
  if (spec.ipc && spec.channel) throw new Error("A child takes ipc or a channel, not both.");
2374
2955
  for (const value of spec.redact ?? []) redactor.protect(value);
2375
2956
  redactor.protectEnvironment(spec.env ?? process.env);
2376
- const child = spawn("/bin/sh", [
2377
- "-c",
2378
- GATE_SCRIPT,
2379
- `mostra-${spec.kind}`,
2380
- spec.command,
2381
- ...spec.args ?? []
2382
- ], {
2957
+ const launched = launch({
2958
+ kind: spec.kind,
2959
+ command: spec.command,
2960
+ args: spec.args ?? [],
2383
2961
  cwd: spec.cwd,
2384
2962
  env: spec.env ?? process.env,
2385
- detached: true,
2386
- stdio: spec.ipc ? [
2387
- "ignore",
2388
- "pipe",
2389
- "pipe",
2390
- "pipe",
2391
- "ipc"
2392
- ] : spec.channel ? [
2393
- "ignore",
2394
- "pipe",
2395
- "pipe",
2396
- "pipe",
2397
- "pipe"
2398
- ] : [
2399
- "ignore",
2400
- "pipe",
2401
- "pipe",
2402
- "pipe"
2403
- ],
2404
- serialization: "json"
2405
- });
2406
- const gate = child.stdio[3];
2407
- gate?.on("error", () => {});
2963
+ extra: spec.ipc ? "ipc" : spec.channel ? "channel" : void 0
2964
+ }, warn);
2965
+ const child = launched.process;
2408
2966
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
2409
- const pid = await new Promise((resolve, reject) => {
2410
- child.once("spawn", () => resolve(child.pid ?? 0));
2967
+ await new Promise((resolve, reject) => {
2968
+ child.once("spawn", () => resolve());
2411
2969
  child.once("error", reject);
2412
2970
  });
2971
+ let pid = child.pid ?? 0;
2413
2972
  child.on("error", (error) => log.warn("process.error", {
2414
2973
  kind: spec.kind,
2415
2974
  pid,
@@ -2466,15 +3025,16 @@ function createManager({ ledger, log, redactor, faults = noFaults }) {
2466
3025
  ledger.write((db) => db.run("DELETE FROM child WHERE pid = ? AND parent_pid = ?", parsed.data.pid, pid));
2467
3026
  return {};
2468
3027
  }
2469
- const info = await readProcess(parsed.data.pid);
2470
- if (!info || info.pgid !== info.pid) return { adopted: false };
2471
- adopted.set(info.pid, info.pgid);
3028
+ const found = await adoptable(parsed.data.pid);
3029
+ if (!found) return { adopted: false };
3030
+ if (!found.record) return { adopted: true };
3031
+ adopted.set(found.info.pid, found.info.pgid);
2472
3032
  record({
2473
- pid: info.pid,
2474
- start_time: info.startTime,
3033
+ pid: found.info.pid,
3034
+ start_time: found.info.startTime,
2475
3035
  kind: `${spec.kind}/adopted`,
2476
3036
  owner_ref: spec.ownerRef,
2477
- pgid: info.pgid,
3037
+ pgid: found.info.pgid,
2478
3038
  started_at: (/* @__PURE__ */ new Date()).toISOString(),
2479
3039
  parent_pid: pid
2480
3040
  });
@@ -2496,28 +3056,28 @@ function createManager({ ledger, log, redactor, faults = noFaults }) {
2496
3056
  child.on("disconnect", () => connected.close());
2497
3057
  }
2498
3058
  const registered = (async () => {
2499
- const info = await readProcess(pid);
3059
+ const info = await launched.identify();
2500
3060
  faults.at("spawn:before-record");
2501
- if (!info) {
2502
- if (child.exitCode !== null || child.signalCode !== null) return;
2503
- throw new Error(`Couldn't read the process identity of ${spec.kind} ${pid}.`);
2504
- }
3061
+ faults.at(`spawn:before-record:${spec.kind}`);
3062
+ if (faults.hangs(`spawn:before-record:${spec.kind}`)) await new Promise(() => {});
3063
+ if (!info) return;
3064
+ pid = info.pid;
2505
3065
  record({
2506
- pid,
3066
+ pid: info.pid,
2507
3067
  start_time: info.startTime,
2508
3068
  kind: spec.kind,
2509
3069
  owner_ref: spec.ownerRef,
2510
- pgid: pid,
3070
+ pgid: info.pid,
2511
3071
  started_at: startedAt,
2512
3072
  parent_pid: null
2513
3073
  });
2514
- gate?.end("go\n");
3074
+ launched.release();
2515
3075
  })();
2516
3076
  const exited = exit.then(async ({ code, signal }) => {
2517
- await endGroups([pid, ...adopted.values()], 2e3);
3077
+ await launched.sweep([...adopted.values()]);
2518
3078
  await settleWithin(Promise.all(drained), 2e3);
2519
3079
  await registered.catch(() => {});
2520
- running.delete(pid);
3080
+ running.delete(child.pid ?? 0);
2521
3081
  try {
2522
3082
  forget(pid);
2523
3083
  } catch (error) {
@@ -2544,8 +3104,14 @@ function createManager({ ledger, log, redactor, faults = noFaults }) {
2544
3104
  pid,
2545
3105
  error
2546
3106
  }));
3107
+ const stop = async (graceMs = DEFAULT_GRACE_MS) => {
3108
+ if (launched.running()) await launched.end(graceMs, [...adopted.values()]);
3109
+ return exited;
3110
+ };
2547
3111
  const handle = {
2548
- pid,
3112
+ get pid() {
3113
+ return pid;
3114
+ },
2549
3115
  kind: spec.kind,
2550
3116
  ownerRef: spec.ownerRef,
2551
3117
  startedAt,
@@ -2555,12 +3121,12 @@ function createManager({ ledger, log, redactor, faults = noFaults }) {
2555
3121
  if (!peer) return Promise.reject(/* @__PURE__ */ new Error(`${spec.kind} was started without IPC.`));
2556
3122
  return peer.request(method, params, options);
2557
3123
  },
2558
- async stop(graceMs = DEFAULT_GRACE_MS) {
2559
- if (child.exitCode === null && child.signalCode === null) await endGroups([pid, ...adopted.values()], graceMs);
2560
- return exited;
2561
- }
3124
+ stop
2562
3125
  };
2563
- running.set(pid, handle);
3126
+ running.set(child.pid ?? 0, {
3127
+ handle,
3128
+ kill: () => launched.kill()
3129
+ });
2564
3130
  try {
2565
3131
  await registered;
2566
3132
  } catch (error) {
@@ -2590,39 +3156,28 @@ function createManager({ ledger, log, redactor, faults = noFaults }) {
2590
3156
  };
2591
3157
  return {
2592
3158
  spawn: trackedSpawn,
2593
- list: () => [...running.values()].map((child) => ({
2594
- pid: child.pid,
2595
- kind: child.kind,
2596
- ownerRef: child.ownerRef,
2597
- startedAt: child.startedAt
3159
+ list: () => [...running.values()].map(({ handle }) => ({
3160
+ pid: handle.pid,
3161
+ kind: handle.kind,
3162
+ ownerRef: handle.ownerRef,
3163
+ startedAt: handle.startedAt
2598
3164
  })),
2599
3165
  async stopAll(graceMs = DEFAULT_GRACE_MS) {
2600
3166
  stopping = true;
2601
3167
  await Promise.all(inflight);
2602
- await Promise.all([...running.values()].map((child) => child.stop(graceMs)));
2603
- }
2604
- };
2605
- }
2606
- //#endregion
2607
- //#region src/deps/warm.ts
2608
- /**
2609
- * The warm set (D91, D95): the pre-built, read-only layout every artifact resolves without an
2610
- * install. `@mostra/warm`'s `dependencies` are the warm packages; its `node_modules` is the layout.
2611
- */
2612
- /** The directory of `@mostra/runtime`'s package.json. */
2613
- function runtimeRoot() {
2614
- let dir = dirname(fileURLToPath(import.meta.url));
2615
- for (;;) {
2616
- const manifest = join(dir, "package.json");
2617
- if (existsSync(manifest)) {
2618
- const { name } = JSON.parse(readFileSync(manifest, "utf8"));
2619
- if (name === "@mostra/runtime") return dir;
2620
- }
2621
- const parent = dirname(dir);
2622
- if (parent === dir) throw new Error("Couldn't find @mostra/runtime's package.json.");
2623
- dir = parent;
2624
- }
3168
+ await Promise.all([...running.values()].map(({ handle }) => handle.stop(graceMs)));
3169
+ },
3170
+ killAll() {
3171
+ for (const { kill } of running.values()) kill();
3172
+ }
3173
+ };
2625
3174
  }
3175
+ //#endregion
3176
+ //#region src/deps/warm.ts
3177
+ /**
3178
+ * The warm set (D91, D95): the pre-built, read-only layout every artifact resolves without an
3179
+ * install. `@mostra/warm`'s `dependencies` are the warm packages; its `node_modules` is the layout.
3180
+ */
2626
3181
  function warmMissing(message) {
2627
3182
  return new RpcError(createDiagnostic("MOSTRA_ENV_WARM_MISSING", { message }));
2628
3183
  }
@@ -2631,7 +3186,7 @@ function warmMissing(message) {
2631
3186
  * the runtime bundle and this repository lay it out. Every listed package must be installed.
2632
3187
  */
2633
3188
  function locateWarmSet(env) {
2634
- const dir = env["MOSTRA_WARM_DIR"] ?? resolve(runtimeRoot(), "..", "warm");
3189
+ const dir = env["MOSTRA_WARM_DIR"] ?? resolve(runtimeRoot$1(), "..", "warm");
2635
3190
  const manifestFile = join(dir, "package.json");
2636
3191
  if (!existsSync(manifestFile)) throw warmMissing(`No warm package set at ${dir}.`);
2637
3192
  const { dependencies = {} } = JSON.parse(readFileSync(manifestFile, "utf8"));
@@ -2661,11 +3216,11 @@ function packageNamed(record, message) {
2661
3216
  }
2662
3217
  /** The install child's entry: the compiled one beside the compiled supervisor, else the source. */
2663
3218
  function childEntry() {
2664
- return fileURLToPath(import.meta.url).endsWith(".ts") ? join(runtimeRoot(), "src/deps/child/install.ts") : join(runtimeRoot(), "dist/deps/child/install.js");
3219
+ return fileURLToPath(import.meta.url).endsWith(".ts") ? join(runtimeRoot$1(), "src/deps/child/install.ts") : join(runtimeRoot$1(), "dist/deps/child/install.js");
2665
3220
  }
2666
3221
  /** Finds pnpm 10 beside the runtime; anything else is refused (D94). */
2667
3222
  function locatePnpm() {
2668
- let dir = runtimeRoot();
3223
+ let dir = runtimeRoot$1();
2669
3224
  for (;;) {
2670
3225
  const candidate = join(dir, "node_modules", "pnpm");
2671
3226
  if (existsSync(join(candidate, "package.json"))) {
@@ -3239,8 +3794,13 @@ function isOffline(env) {
3239
3794
  if (flag !== void 0 && flag !== "" && !/^(?:0|false|no)$/i.test(flag)) return true;
3240
3795
  return !Object.values(networkInterfaces()).some((addresses) => (addresses ?? []).some((address) => !address.internal && !address.address.startsWith("169.254.") && !/^fe[89ab]/i.test(address.address)));
3241
3796
  }
3242
- /** A shell-safe rendering of `value`, for the commands in diagnostics. */
3797
+ /**
3798
+ * A shell-safe rendering of `value`, for the commands in diagnostics: POSIX shell quoting, or on
3799
+ * Windows the double quotes PowerShell and `cmd` both read (a Windows path holds no `"`), and a
3800
+ * plain path with backslashes as it is.
3801
+ */
3243
3802
  function shellQuote(value) {
3803
+ if (WINDOWS) return /^[\w@%+=:,./\\-]+$/.test(value) ? value : `"${value}"`;
3244
3804
  return /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
3245
3805
  }
3246
3806
  /** Serializes work per key; one supervisor, so in-process order is the order. */
@@ -3321,7 +3881,7 @@ function createDependencies(options) {
3321
3881
  const work = join(dirs.tmp, `resolve-${randomBytes(6).toString("hex")}`);
3322
3882
  await mkdir(work);
3323
3883
  try {
3324
- await symlink(warm.nodeModules, join(work, "warm"), "dir");
3884
+ await linkDirectory(warm.nodeModules, join(work, "warm"));
3325
3885
  await writeFile(join(work, "package.json"), manifestOf(input.pins));
3326
3886
  if (input.previous !== void 0) await writeFile(join(work, "pnpm-lock.yaml"), input.previous);
3327
3887
  const outcome = await install().run({
@@ -3363,16 +3923,9 @@ function createDependencies(options) {
3363
3923
  /** Points a layout's `warm` symlink at the current warm set (the runtime may have moved). */
3364
3924
  const relinkWarm = async (dir) => {
3365
3925
  const link = join(dir, "warm");
3366
- let target;
3367
- try {
3368
- target = readlinkSync(link);
3369
- } catch {
3370
- target = void 0;
3371
- }
3372
- if (target === warm.nodeModules) return;
3373
- const fresh = `${link}.${randomBytes(4).toString("hex")}`;
3374
- await symlink(warm.nodeModules, fresh, "dir");
3375
- await rename(fresh, link);
3926
+ const target = await linkTarget(link);
3927
+ if (target !== void 0 && samePath(target, warm.nodeModules)) return;
3928
+ await replaceDirectoryLink(warm.nodeModules, link);
3376
3929
  };
3377
3930
  /**
3378
3931
  * The layout of `lock`, installed from the store (and the registry for what the store lacks)
@@ -3397,7 +3950,7 @@ function createDependencies(options) {
3397
3950
  });
3398
3951
  await mkdir(dir, { recursive: true });
3399
3952
  try {
3400
- await symlink(warm.nodeModules, join(dir, "warm"), "dir");
3953
+ await linkDirectory(warm.nodeModules, join(dir, "warm"));
3401
3954
  await writeFile(join(dir, "package.json"), manifestOf(lock.packages));
3402
3955
  await writeFile(join(dir, "pnpm-lock.yaml"), pnpm);
3403
3956
  const outcome = await install().run({
@@ -3457,7 +4010,7 @@ function createDependencies(options) {
3457
4010
  });
3458
4011
  await mkdir(dir, { recursive: true });
3459
4012
  try {
3460
- await symlink(warm.nodeModules, join(dir, "warm"), "dir");
4013
+ await linkDirectory(warm.nodeModules, join(dir, "warm"));
3461
4014
  await writeFile(join(dir, "package.json"), `${JSON.stringify({
3462
4015
  name: "mostra-artifact-dependencies",
3463
4016
  private: true,
@@ -3808,12 +4361,6 @@ function writeLine(output, message) {
3808
4361
  }
3809
4362
  //#endregion
3810
4363
  //#region src/protocol-server/server.ts
3811
- /**
3812
- * The host protocol server (D59, INTERFACES §6, HO-02): one dispatcher for every connection,
3813
- * whether `mostra-runtime host`'s stdio or an attached client's Unix socket. It owns the session
3814
- * rules (initialize first and once, revision negotiation, the home check, port registration on
3815
- * the registering connection) and routes every other method to the handler a module registered.
3816
- */
3817
4364
  /** Builds a handler with its types checked against the method definition. */
3818
4365
  function handler(definition, handle) {
3819
4366
  return {
@@ -3829,7 +4376,14 @@ var ProtocolServer = class {
3829
4376
  #nextId = 1;
3830
4377
  #refusal;
3831
4378
  #listener;
4379
+ #endpoint;
4380
+ #listenOptions = {};
3832
4381
  #healTimer;
4382
+ /** A heal under way: one at a time, and `close` waits for it (Opus review of WP-W1). */
4383
+ #healing;
4384
+ /** An endpoint that moved but whose `onMoved` failed: announced again by every heal until it holds. */
4385
+ #unannounced;
4386
+ #closed = false;
3833
4387
  constructor(options) {
3834
4388
  this.#options = options;
3835
4389
  this.#handlers = new Map(options.handlers.map((entry) => [entry.definition.method, entry]));
@@ -3907,62 +4461,52 @@ var ProtocolServer = class {
3907
4461
  return session;
3908
4462
  }
3909
4463
  /**
3910
- * Listens on the home's control socket (D81, D82): replaces any leftover socket file (only the
3911
- * lock holder calls this), makes the socket owner-only, and checks every `healMs` (at most
3912
- * 10 s) that the file still exists, re-creating it when it has disappeared.
4464
+ * Listens on the home's control endpoint (D81, D82): a Unix socket, replacing any leftover file
4465
+ * (only the lock holder calls this) and owner-only; on Windows the helper's owner-only pipe
4466
+ * (`launchPipe`). Every `healMs` (at most 10 s) it checks that the endpoint still serves and
4467
+ * binds it again when it doesn't, calling `onMoved` when the new endpoint has another name.
3913
4468
  */
3914
- async listen(path, healMs = 5e3) {
3915
- this.#listener = await this.#bind(path);
4469
+ async listen(path, healMs = 5e3, options = {}) {
4470
+ this.#endpoint = path;
4471
+ this.#listenOptions = options;
4472
+ this.#listener = await this.#bind();
3916
4473
  this.#healTimer = setInterval(() => void this.#heal(), Math.min(healMs, 1e4));
3917
4474
  this.#healTimer.unref();
3918
4475
  }
3919
- /** The socket the server listens on. */
4476
+ /** The endpoint the server listens on, as clients connect to it. */
3920
4477
  get socketPath() {
3921
4478
  return this.#listener?.path;
3922
4479
  }
3923
- async #bind(path) {
3924
- mkdirSync(dirname(path), {
3925
- recursive: true,
3926
- mode: 448
3927
- });
3928
- try {
3929
- unlinkSync(path);
3930
- } catch (error) {
3931
- if (error.code !== "ENOENT") throw error;
3932
- }
3933
- const server = createServer((socket) => {
3934
- this.serve("socket", socket, socket);
4480
+ #bind() {
4481
+ return listenControl(this.#endpoint ?? "", (stream) => {
4482
+ this.serve("socket", stream, stream);
4483
+ }, {
4484
+ ...this.#listenOptions.launchPipe ? { launchPipe: this.#listenOptions.launchPipe } : {},
4485
+ onError: (error) => this.#options.log.error("protocol.listener_error", { error })
3935
4486
  });
3936
- await new Promise((resolve, reject) => {
3937
- server.once("error", reject);
3938
- server.listen(path, () => {
3939
- server.off("error", reject);
3940
- resolve();
3941
- });
4487
+ }
4488
+ #heal() {
4489
+ if (this.#closed) return Promise.resolve();
4490
+ this.#healing ??= this.#healOnce().finally(() => {
4491
+ this.#healing = void 0;
3942
4492
  });
3943
- chmodSync(path, 384);
3944
- server.on("error", (error) => this.#options.log.error("protocol.listener_error", { error }));
3945
- return {
3946
- server,
3947
- path,
3948
- stats: statSync(path)
3949
- };
4493
+ return this.#healing;
3950
4494
  }
3951
- async #heal() {
4495
+ async #healOnce() {
4496
+ if (this.#unannounced !== void 0) this.#announce(this.#unannounced);
3952
4497
  const listener = this.#listener;
3953
- if (!listener) return;
3954
- let current;
3955
- try {
3956
- current = statSync(listener.path);
3957
- } catch {
3958
- current = void 0;
3959
- }
3960
- if (current && current.ino === listener.stats.ino && current.dev === listener.stats.dev) return;
3961
- listener.server.close();
4498
+ if (!listener || listener.intact()) return;
4499
+ await listener.close();
4500
+ if (this.#closed) return;
3962
4501
  try {
3963
- const replacement = await this.#bind(listener.path);
4502
+ const replacement = await this.#bind();
4503
+ if (this.#closed) {
4504
+ await replacement.close();
4505
+ return;
4506
+ }
3964
4507
  this.#listener = replacement;
3965
- this.#options.log.warn("protocol.socket_recreated", { path: listener.path });
4508
+ this.#options.log.warn("protocol.socket_recreated", { path: replacement.path });
4509
+ if (replacement.path !== listener.path) this.#announce(replacement.path);
3966
4510
  } catch (error) {
3967
4511
  this.#options.log.warn("protocol.socket_recreate_failed", {
3968
4512
  path: listener.path,
@@ -3971,6 +4515,22 @@ var ProtocolServer = class {
3971
4515
  }
3972
4516
  }
3973
4517
  /**
4518
+ * Tells the instance the endpoint moved (it rewrites `instance.json`); when that fails, every
4519
+ * later heal tries again, so starters are never left with a record naming a dead pipe.
4520
+ */
4521
+ #announce(path) {
4522
+ try {
4523
+ this.#listenOptions.onMoved?.(path);
4524
+ this.#unannounced = void 0;
4525
+ } catch (error) {
4526
+ this.#unannounced = path;
4527
+ this.#options.log.warn("protocol.endpoint_announce_failed", {
4528
+ path,
4529
+ error
4530
+ });
4531
+ }
4532
+ }
4533
+ /**
3974
4534
  * Answers every request from now on with `diagnostic`, for an instance that can no longer serve
3975
4535
  * (`MOSTRA_HOME_GONE`).
3976
4536
  */
@@ -4040,20 +4600,17 @@ var ProtocolServer = class {
4040
4600
  }
4041
4601
  /**
4042
4602
  * Stops listening, removes the socket file if it is still this server's, and closes every
4043
- * connection. Responses already sent are flushed first.
4603
+ * connection. Responses already sent are flushed first: the connections end before the
4604
+ * listener, which on Windows lets the pipe's helper hand them over before it exits.
4044
4605
  */
4045
- close() {
4606
+ async close() {
4607
+ this.#closed = true;
4046
4608
  if (this.#healTimer) clearInterval(this.#healTimer);
4609
+ await this.#healing;
4610
+ for (const connection of this.#connections) connection.close();
4047
4611
  const listener = this.#listener;
4048
4612
  this.#listener = void 0;
4049
- if (listener) {
4050
- listener.server.close();
4051
- try {
4052
- const current = statSync(listener.path);
4053
- if (current.ino === listener.stats.ino && current.dev === listener.stats.dev) unlinkSync(listener.path);
4054
- } catch {}
4055
- }
4056
- for (const connection of this.#connections) connection.close();
4613
+ await listener?.close();
4057
4614
  }
4058
4615
  async #dispatch(session, method, params) {
4059
4616
  try {
@@ -4146,43 +4703,34 @@ var ProtocolServer = class {
4146
4703
  */
4147
4704
  /**
4148
4705
  * Connects to a control socket. Rejects with `MOSTRA_HOST_CONNECTION_CLOSED` when nothing
4149
- * listens there (the file is missing or stale) or the connection doesn't open within `timeoutMs`.
4706
+ * listens there (the file is missing or stale), the connection doesn't open within `timeoutMs`,
4707
+ * or, on Windows, the pipe under that name is another user's.
4150
4708
  */
4151
4709
  function connectSocket(path, timeoutMs = 5e3) {
4152
- return new Promise((resolve, reject) => {
4153
- const socket = createConnection(path);
4154
- const timer = setTimeout(() => {
4155
- socket.destroy();
4156
- reject(refused(path, "timed out"));
4157
- }, timeoutMs);
4158
- socket.once("error", (error) => {
4159
- clearTimeout(timer);
4160
- reject(refused(path, error.code ?? "failed"));
4710
+ return connectControl(path, timeoutMs).then((socket) => {
4711
+ const peer = new RpcPeer({ send: (message) => void writeLine(socket, message) });
4712
+ let markClosed = () => {};
4713
+ const closed = new Promise((done) => {
4714
+ markClosed = done;
4161
4715
  });
4162
- socket.once("connect", () => {
4163
- clearTimeout(timer);
4164
- const peer = new RpcPeer({ send: (message) => void writeLine(socket, message) });
4165
- let markClosed = () => {};
4166
- const closed = new Promise((done) => {
4167
- markClosed = done;
4168
- });
4169
- socket.on("error", () => socket.destroy());
4170
- pump({
4171
- input: socket,
4172
- output: socket
4173
- }, () => peer, () => {
4174
- peer.close();
4175
- markClosed();
4176
- });
4177
- resolve({
4178
- peer,
4179
- closed,
4180
- close: () => {
4181
- peer.close();
4182
- socket.end();
4183
- }
4184
- });
4716
+ socket.on("error", () => socket.destroy());
4717
+ pump({
4718
+ input: socket,
4719
+ output: socket
4720
+ }, () => peer, () => {
4721
+ peer.close();
4722
+ markClosed();
4185
4723
  });
4724
+ return {
4725
+ peer,
4726
+ closed,
4727
+ close: () => {
4728
+ peer.close();
4729
+ socket.end();
4730
+ }
4731
+ };
4732
+ }, (error) => {
4733
+ throw refused(path, error instanceof ControlConnectError && error.reason === "not-owned" ? "it belongs to another user" : error instanceof Error ? error.message : "failed");
4186
4734
  });
4187
4735
  }
4188
4736
  function refused(path, why) {
@@ -6785,69 +7333,10 @@ function createInteraction(options) {
6785
7333
  /**
6786
7334
  * The content-addressed version store on disk (DATA_MODEL §1, FAILURE_MODEL §3): `versions/<id>/`
6787
7335
  * and `sources/<artifactId>/<sourceDigest>.tar.zst`. A version directory is assembled in staging,
6788
- * made read-only and synced, then renamed into place; it becomes visible only when its ledger row
7336
+ * synced and made read-only (`platform`: modes on POSIX, an access list on Windows), then renamed
7337
+ * into place; it becomes visible only when its ledger row
6789
7338
  * commits, and anything without a row is removed at the next start.
6790
7339
  */
6791
- /** Calls `visit` for every entry under `dir`, children before their directory. */
6792
- async function walk(dir, visit) {
6793
- for (const entry of await readdir(dir, { withFileTypes: true })) {
6794
- const path = join(dir, entry.name);
6795
- if (entry.isDirectory()) await walk(path, visit);
6796
- await visit(path, entry.isDirectory());
6797
- }
6798
- }
6799
- /**
6800
- * Syncs a file or a directory to disk. A file that can't be synced fails the caller (its bytes
6801
- * would not be durable); a directory may not support it on some file systems, and only that
6802
- * case is tolerated (EINVAL, ENOTSUP, EISDIR, EPERM, EACCES on `open`).
6803
- */
6804
- function fsyncPath(path, directory = false) {
6805
- let fd;
6806
- try {
6807
- fd = openSync(path, "r");
6808
- fsyncSync(fd);
6809
- } catch (error) {
6810
- const code = error.code;
6811
- if (!directory || ![
6812
- "EINVAL",
6813
- "ENOTSUP",
6814
- "EISDIR",
6815
- "EPERM",
6816
- "EACCES"
6817
- ].includes(code ?? "")) throw error;
6818
- } finally {
6819
- if (fd !== void 0) closeSync(fd);
6820
- }
6821
- }
6822
- /**
6823
- * Makes a tree read-only (files 0444, directories 0555) and syncs it to disk. The top directory is
6824
- * left writable when `keepTop` is set: renaming a directory needs write access to it, to update `..`.
6825
- */
6826
- async function sealTree(dir, keepTop = false) {
6827
- await walk(dir, async (path, isDirectory) => {
6828
- await chmod(path, isDirectory ? 365 : 292);
6829
- fsyncPath(path, isDirectory);
6830
- });
6831
- if (!keepTop) await chmod(dir, 365);
6832
- fsyncPath(dir, true);
6833
- }
6834
- /** Removes a tree, sealed or not. Missing trees are fine. */
6835
- async function removeTree(dir) {
6836
- try {
6837
- if ((await lstat(dir)).isDirectory()) {
6838
- await chmod(dir, 493);
6839
- await walk(dir, async (path, isDirectory) => {
6840
- if (isDirectory) await chmod(path, 493);
6841
- }).catch(() => {});
6842
- }
6843
- } catch {
6844
- return;
6845
- }
6846
- await rm(dir, {
6847
- recursive: true,
6848
- force: true
6849
- });
6850
- }
6851
7340
  /** Opens the version store of the home at `home`, creating its directories. */
6852
7341
  async function openVersionStore(home) {
6853
7342
  const versionsDir = join(home, "versions");
@@ -6872,9 +7361,8 @@ async function openVersionStore(home) {
6872
7361
  await sealTree(built, true);
6873
7362
  const target = versionDir(versionId);
6874
7363
  await removeTree(target);
6875
- await rename(built, target);
6876
- await chmod(target, 365);
6877
- fsyncPath(target, true);
7364
+ await renamePath(built, target);
7365
+ await sealPlaced(target);
6878
7366
  fsyncPath(versionsDir, true);
6879
7367
  },
6880
7368
  async sweep(known) {
@@ -8167,7 +8655,7 @@ function capabilityKey(home, log) {
8167
8655
  } finally {
8168
8656
  closeSync(fd);
8169
8657
  }
8170
- renameSync(aside, file);
8658
+ renamePathSync(aside, file);
8171
8659
  chmodSync(file, 384);
8172
8660
  return key;
8173
8661
  }
@@ -8861,6 +9349,36 @@ function writeRaw(socket, refused, extra = {}) {
8861
9349
  ...extra.headers ?? []
8862
9350
  ];
8863
9351
  socket.end(`${headers.join("\r\n")}\r\n\r\n${body}`);
9352
+ lingerAfterRefusal(socket);
9353
+ }
9354
+ /** Connections already answered with a refusal: a later parse error on them changes nothing. */
9355
+ const refusedSockets = /* @__PURE__ */ new WeakSet();
9356
+ /** How long a refused connection is read before it is closed regardless. */
9357
+ const LINGER_MS = 5e3;
9358
+ /** How much of a refused request is read and dropped before the connection is closed. */
9359
+ const LINGER_BYTES = 16777216;
9360
+ /**
9361
+ * Reads and drops what the client is still sending after its refusal, until it closes the
9362
+ * connection, for at most {@link LINGER_MS} and {@link LINGER_BYTES}. A socket closed with unread
9363
+ * bytes is reset, and a reset can reach the client before it read the answer, which it then never
9364
+ * sees: on Windows a browser sending a megabyte of cookies got a reset instead of the page that
9365
+ * clears them (WP-W2). The answer is already written; this only keeps the connection open long
9366
+ * enough for it to be read, as HTTP servers do for a "lingering close".
9367
+ */
9368
+ function lingerAfterRefusal(socket) {
9369
+ refusedSockets.add(socket);
9370
+ socket.removeAllListeners("data");
9371
+ socket.once("end", () => socket.destroy());
9372
+ let read = 0;
9373
+ const timer = setTimeout(() => socket.destroy(), LINGER_MS);
9374
+ timer.unref();
9375
+ socket.once("close", () => clearTimeout(timer));
9376
+ socket.on("error", () => socket.destroy());
9377
+ socket.on("data", (chunk) => {
9378
+ read += chunk.length;
9379
+ if (read > LINGER_BYTES) socket.destroy();
9380
+ });
9381
+ socket.resume();
8864
9382
  }
8865
9383
  /**
8866
9384
  * The answer to headers past {@link MAX_HEADER_SIZE}: a page that says what happened and clears
@@ -8927,6 +9445,7 @@ function createListener(options) {
8927
9445
  listener(incoming, outgoing);
8928
9446
  });
8929
9447
  server.on("clientError", (error, socket) => {
9448
+ if (refusedSockets.has(socket)) return;
8930
9449
  if (!socket.writable) {
8931
9450
  socket.destroy();
8932
9451
  return;
@@ -10107,7 +10626,7 @@ async function verifyDocument(path, request, headers) {
10107
10626
  * `MOSTRA_ENV_SHELL_MISSING`.
10108
10627
  */
10109
10628
  function locateShell(env) {
10110
- const dir = env["MOSTRA_SHELL_DIR"] ?? resolve(runtimeRoot(), "..", "shell", "dist");
10629
+ const dir = env["MOSTRA_SHELL_DIR"] ?? resolve(runtimeRoot$1(), "..", "shell", "dist");
10111
10630
  return existsSync(join(dir, "index.html")) ? dir : void 0;
10112
10631
  }
10113
10632
  //#endregion
@@ -10497,7 +11016,7 @@ function localLauncher(options) {
10497
11016
  resolve(options.home, "versions"),
10498
11017
  resolve(options.home, "cache", "builds"),
10499
11018
  resolve(options.home, "cache", "dev")
10500
- ].some((root) => versionDir.startsWith(`${root}/`))) throw new Error("A home: locator names a version directory, a verify build or a dev session of the home.");
11019
+ ].some((root) => pathKey(versionDir).startsWith(`${pathKey(root)}/`))) throw new Error("A home: locator names a version directory, a verify build or a dev session of the home.");
10501
11020
  const modules = await options.modules?.({
10502
11021
  artifactId: spec.artifactId,
10503
11022
  versionDir,
@@ -10640,6 +11159,16 @@ const PINGS_MISSED_BEFORE_STOP = 3;
10640
11159
  * to count as running out of memory rather than hanging.
10641
11160
  */
10642
11161
  const OOM_STALL_FRACTION = .8;
11162
+ /**
11163
+ * An exit code as people look it up: a Windows status (`0xC0000005`, an access violation) in
11164
+ * hexadecimal, any other code as a number. Node.js reports a Windows status as an unsigned
11165
+ * 32-bit number; on POSIX codes are below 256.
11166
+ */
11167
+ function exitCodeText(code) {
11168
+ if (code === null) return "?";
11169
+ if (code >= 2147483648 || code < 0) return `0x${(code >>> 0).toString(16).toUpperCase().padStart(8, "0")}`;
11170
+ return String(code);
11171
+ }
10643
11172
  function crashed(message) {
10644
11173
  return new RpcError(createDiagnostic("MOSTRA_RUNTIME_WORKER_CRASHED", { message }));
10645
11174
  }
@@ -10698,7 +11227,7 @@ function createWorkerPool(options) {
10698
11227
  }
10699
11228
  const lines = exit.stderrTail.filter((line) => line.trim() !== "" && !/^Node\.js v\d/.test(line.trim()));
10700
11229
  const last = lines.findLast((line) => /^[A-Za-z_$][\w$.]*(?:Error|Exception)\b.*:/.test(line.trim())) ?? lines.findLast((line) => !/^\s+at\s/.test(line)) ?? lines.at(-1);
10701
- const how = exit.signal !== null ? `it was ended by ${exit.signal}` : `it exited with code ${exit.code ?? "?"}`;
11230
+ const how = exit.signal !== null ? `it was ended by ${exit.signal}` : `it exited with code ${exitCodeText(exit.code)}`;
10702
11231
  return {
10703
11232
  kind: "crash",
10704
11233
  cause: last ? `${how}: ${last.slice(0, 300)}` : how
@@ -11491,7 +12020,7 @@ function parseTscOutput(lines, alreadyReported, ownConfig = false) {
11491
12020
  }
11492
12021
  /** Where `@mostra/server`'s declarations are: the worker provides the package, so no layout has it (D129). */
11493
12022
  function serverTypes() {
11494
- const root = runtimeRoot();
12023
+ const root = runtimeRoot$1();
11495
12024
  for (const candidate of [join(root, "..", "server", "dist", "index.d.ts"), join(root, "..", "server", "src", "index.ts")]) if (existsSync(candidate)) return candidate;
11496
12025
  }
11497
12026
  /** Runs the type check of the snapshot in `sourceDir` against `nodeModules`. */
@@ -11504,7 +12033,7 @@ async function typecheck(options) {
11504
12033
  await mkdir(join(workDir, ".mostra-check"), { recursive: true });
11505
12034
  try {
11506
12035
  await cp(options.sourceDir, join(workDir, "source"), { recursive: true });
11507
- await symlink(options.nodeModules, join(workDir, "node_modules"), "dir");
12036
+ await linkDirectory(options.nodeModules, join(workDir, "node_modules"));
11508
12037
  await writeFile(join(workDir, ".mostra-check", "assets.d.ts"), AMBIENT);
11509
12038
  if (options.hasLive) await writeFile(join(workDir, ".mostra-check", "mostra-env.d.ts"), LIVE_DECLARATION);
11510
12039
  const own = existsSync(join(workDir, "source", "tsconfig.json"));
@@ -11927,7 +12456,7 @@ function createVerifier(options) {
11927
12456
  recursive: true,
11928
12457
  force: true
11929
12458
  });
11930
- await rename(temporary, join(buildsDir, prepared.versionId));
12459
+ await renamePath(temporary, join(buildsDir, prepared.versionId));
11931
12460
  await pruneBuilds(prepared.versionId);
11932
12461
  return outcome;
11933
12462
  } finally {
@@ -12237,7 +12766,7 @@ function createVerifier(options) {
12237
12766
  verdict: checkedVerdict,
12238
12767
  built: built.ok
12239
12768
  }, null, 2)}\n`);
12240
- await rename(temporary, target);
12769
+ await renamePath(temporary, target);
12241
12770
  await pruneVerdicts();
12242
12771
  } else {
12243
12772
  await rm(join(cacheDir, `${key}.json`), { force: true });
@@ -12776,7 +13305,7 @@ async function listSource(source) {
12776
13305
  continue;
12777
13306
  }
12778
13307
  if (kind === "dir") {
12779
- if (IGNORED_DIRS.has(entry.name) || rules.ignores(`${path}/`)) continue;
13308
+ if (IGNORED_DIRS.has(nameKey(entry.name)) || rules.ignores(`${path}/`)) continue;
12780
13309
  let real;
12781
13310
  try {
12782
13311
  real = await realpath(absolute);
@@ -12787,9 +13316,9 @@ async function listSource(source) {
12787
13316
  await walk(absolute, path, /* @__PURE__ */ new Set([...ancestors, real]));
12788
13317
  } else if (kind === "file") {
12789
13318
  if (IGNORED_FILE.test(entry.name) || rules.ignores(path)) continue;
12790
- const clash = seen.get(path);
12791
- if (clash !== void 0) throw artifactError("MOSTRA_ARTIFACT_SOURCE_UNREADABLE", `${clash} and ${absolute} have the same name after Unicode normalization (NFC).`);
12792
- seen.set(path, absolute);
13319
+ const clash = seen.get(nameKey(path));
13320
+ if (clash !== void 0) throw artifactError("MOSTRA_ARTIFACT_SOURCE_UNREADABLE", `${clash} and ${absolute} have the same name after Unicode normalization (NFC)${WINDOWS ? " and ignoring case, as Windows compares names" : ""}.`);
13321
+ seen.set(nameKey(path), absolute);
12793
13322
  files.push({
12794
13323
  path,
12795
13324
  absolute
@@ -13037,15 +13566,15 @@ async function archiveSnapshot(source, files, target) {
13037
13566
  }
13038
13567
  yield TAR_END;
13039
13568
  }
13040
- const output = createWriteStream(temporary, { mode: 256 });
13041
- await pipeline(Readable.from(blocks()), createZstdCompress(), output);
13042
- const handle = await import("node:fs/promises").then((fs) => fs.open(temporary, "r"));
13043
13569
  try {
13044
- await handle.sync();
13045
- } finally {
13046
- await handle.close();
13570
+ await pipeline(Readable.from(blocks()), createZstdCompress(), createWriteStream(temporary, { mode: 384 }));
13571
+ fsyncPath(temporary);
13572
+ await chmod(temporary, 256);
13573
+ } catch (error) {
13574
+ await removeTree(temporary).catch(() => {});
13575
+ throw error;
13047
13576
  }
13048
- await rename(temporary, target);
13577
+ await renamePath(temporary, target);
13049
13578
  fsyncPath(dirname(target), true);
13050
13579
  return true;
13051
13580
  }
@@ -13404,7 +13933,7 @@ function createPublisher(options) {
13404
13933
  };
13405
13934
  const cachedBuild = verifier().builtVersion(versionId);
13406
13935
  if (cachedBuild && await versionDamage(cachedBuild) === void 0) {
13407
- await rename(cachedBuild, out);
13936
+ await renamePath(cachedBuild, out);
13408
13937
  outputDigest = JSON.parse(await readFile(join(out, "manifest.json"), "utf8")).outputDigest;
13409
13938
  } else {
13410
13939
  log.info("publish.rebuild", {
@@ -13671,10 +14200,7 @@ async function recoverDev(home, log) {
13671
14200
  } catch {
13672
14201
  return;
13673
14202
  }
13674
- for (const name of left) await rm(join(devRoot(home), name), {
13675
- recursive: true,
13676
- force: true
13677
- });
14203
+ for (const name of left) await removeTree(join(devRoot(home), name));
13678
14204
  if (left.length > 0) log.info("dev.sessions_removed", { count: left.length });
13679
14205
  }
13680
14206
  const LOOPBACK = /* @__PURE__ */ new Set([
@@ -13727,13 +14253,23 @@ function createDev(options) {
13727
14253
  let manifestKey = "";
13728
14254
  let artifactId = "";
13729
14255
  const mirrored = /* @__PURE__ */ new Map();
13730
- /** Copies changed files into the mirror and removes deleted ones; what changed. */
14256
+ /** When each mirrored file was first missed: a save that moves the old file aside first. */
14257
+ const missing = /* @__PURE__ */ new Map();
14258
+ /**
14259
+ * Copies changed files into the mirror and removes deleted ones; what changed. Editors save
14260
+ * in several ways (in place, a temporary file renamed over the old one, the old one renamed
14261
+ * to a backup first), and on Windows an editor may hold a file it is writing so that nothing
14262
+ * else can read it: a file that can't be read now is left for the next sync, never recorded,
14263
+ * and a file is removed from the mirror only once it has been missing for
14264
+ * {@link MISSING_GRACE_MS}, so a save never looks like a deletion (WP-W2).
14265
+ */
13731
14266
  const sync = async () => {
13732
14267
  const files = await listSource(source);
13733
14268
  const changed = [];
13734
14269
  const seen = /* @__PURE__ */ new Set();
13735
14270
  for (const file of files) {
13736
14271
  seen.add(file.path);
14272
+ missing.delete(file.path);
13737
14273
  let info;
13738
14274
  try {
13739
14275
  info = await stat(file.absolute);
@@ -13744,16 +14280,30 @@ function createDev(options) {
13744
14280
  const before = mirrored.get(file.path);
13745
14281
  if (before === key) continue;
13746
14282
  const target = join(root, "source", ...file.path.split("/"));
13747
- await mkdir(dirname(target), { recursive: true });
13748
- await copyFile(file.absolute, target);
14283
+ try {
14284
+ await mkdir(dirname(target), { recursive: true });
14285
+ await copyFile(file.absolute, target);
14286
+ } catch (error) {
14287
+ log.info("dev.sync_deferred", {
14288
+ sessionId,
14289
+ file: file.path,
14290
+ error
14291
+ });
14292
+ continue;
14293
+ }
13749
14294
  mirrored.set(file.path, key);
13750
14295
  changed.push({
13751
14296
  file: file.path,
13752
14297
  kind: before === void 0 ? "add" : "change"
13753
14298
  });
13754
14299
  }
14300
+ const now = Date.now();
13755
14301
  for (const path of [...mirrored.keys()]) {
13756
14302
  if (seen.has(path)) continue;
14303
+ const since = missing.get(path) ?? now;
14304
+ missing.set(path, since);
14305
+ if (now - since < MISSING_GRACE_MS) continue;
14306
+ missing.delete(path);
13757
14307
  mirrored.delete(path);
13758
14308
  await unlink(join(root, "source", ...path.split("/"))).catch(() => {});
13759
14309
  changed.push({
@@ -13766,7 +14316,7 @@ function createDev(options) {
13766
14316
  /** The manifest and identity of the mirrored source. */
13767
14317
  const describe = async () => {
13768
14318
  const extracted = extractManifest(source.entry, await readFile(join(root, "source", source.entry), "utf8"));
13769
- const manifest = extracted.manifest ?? { title: titleOf(source) };
14319
+ const manifest = extracted.manifest ?? { title: defaultTitle(source) };
13770
14320
  return {
13771
14321
  manifest,
13772
14322
  artifactId: manifest.id ?? options.registry.artifactAt(source.bindingPath) ?? stableId(source.bindingPath),
@@ -13886,10 +14436,7 @@ function createDev(options) {
13886
14436
  await child?.stop().catch(() => {});
13887
14437
  await sandbox?.close().catch(() => {});
13888
14438
  locksInUse.delete(sessionId);
13889
- await rm(dir, {
13890
- recursive: true,
13891
- force: true
13892
- });
14439
+ await removeTree(dir);
13893
14440
  };
13894
14441
  const stop = async () => {
13895
14442
  if (closed) return;
@@ -13994,10 +14541,12 @@ function createDev(options) {
13994
14541
  }
13995
14542
  };
13996
14543
  }
13997
- /** The title of a source without a manifest: its directory's or file's name (INTERFACES §2.2). */
13998
- function titleOf(source) {
13999
- return (source.kind === "dir" ? source.root.split("/").at(-1) : source.entry.replace(/\.[^.]+$/, "")) || "Untitled";
14000
- }
14544
+ /**
14545
+ * How long a mirrored file must stay missing before `mostra dev` removes it: an editor that moves
14546
+ * the old file aside before writing the new one leaves a gap of milliseconds, a deletion lasts.
14547
+ * The 1 s comparison notices the removal within this and a second more.
14548
+ */
14549
+ const MISSING_GRACE_MS = 1500;
14001
14550
  const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
14002
14551
  /** A stand-in artifact ID for a source no manifest `id` or binding names: stable per path. */
14003
14552
  function stableId(bindingPath) {
@@ -14324,82 +14873,35 @@ function gcMethods(gc) {
14324
14873
  //#endregion
14325
14874
  //#region src/home/paths.ts
14326
14875
  /**
14327
- * Where a home and its control socket live (DATA_MODEL §1, D82, D84, D85). Resolving a path never
14328
- * touches the file system; preparing a directory creates it with mode 0700, tightens one the user
14329
- * owns, and refuses one owned by someone else.
14876
+ * Where a home and its control endpoint live (DATA_MODEL §1, D82, D84, D85). Resolving a path never
14877
+ * touches the file system; preparing a directory creates it owner-only, tightens one the user
14878
+ * owns, and refuses one owned by someone else. The per-system details are the platform layer's.
14330
14879
  */
14331
14880
  const nonEmpty = (value) => value === void 0 || value === "" ? void 0 : value;
14332
14881
  /**
14333
14882
  * The home path, resolved in D84's order: `--home`, then `MOSTRA_HOME`, then the platform default
14334
- * (`~/.mostra` on macOS, `${XDG_DATA_HOME:-~/.local/share}/mostra` on Linux). An SDK passes its
14335
- * `home` option as `--home`.
14883
+ * (`~/.mostra` on macOS, `${XDG_DATA_HOME:-~/.local/share}/mostra` on Linux,
14884
+ * `%LOCALAPPDATA%\mostra` on Windows). An SDK passes its `home` option as `--home`.
14336
14885
  */
14337
14886
  function resolveHomePath(inputs) {
14338
14887
  const cwd = inputs.cwd ?? process.cwd();
14339
14888
  const chosen = nonEmpty(inputs.home) ?? nonEmpty(inputs.env["MOSTRA_HOME"]);
14340
- if (chosen !== void 0) return resolve(cwd, chosen);
14341
- const user = inputs.userHome ?? homedir();
14342
- if ((inputs.platform ?? process.platform) === "darwin") return join(user, ".mostra");
14343
- const data = nonEmpty(inputs.env["XDG_DATA_HOME"]);
14344
- return join(data !== void 0 && isAbsolute(data) ? data : join(user, ".local", "share"), "mostra");
14345
- }
14346
- /** The current user's ID. */
14347
- function uid$1() {
14348
- return process.getuid?.() ?? -1;
14889
+ if (chosen !== void 0) return pathsOf(inputs.platform ?? OS).resolve(cwd, chosen);
14890
+ return defaultHome(inputs.platform ?? OS, inputs.env, inputs.userHome ?? homedir());
14349
14891
  }
14350
14892
  /**
14351
14893
  * The runtime directory for control sockets (D82): `MOSTRA_RUNTIME_DIR`; else `~/.mostra/run` on
14352
14894
  * macOS; on Linux `$XDG_RUNTIME_DIR/mostra` when `$XDG_RUNTIME_DIR` is a directory the user owns
14353
- * that nobody else can read or write, else `${XDG_STATE_HOME:-~/.local/state}/mostra/run`.
14895
+ * that nobody else can read or write, else `${XDG_STATE_HOME:-~/.local/state}/mostra/run`. On
14896
+ * Windows `undefined`: the control pipe lives in the system's pipe namespace.
14354
14897
  */
14355
14898
  function resolveRuntimeDir(inputs) {
14356
- const override = nonEmpty(inputs.env["MOSTRA_RUNTIME_DIR"]);
14357
- if (override !== void 0) return {
14358
- dir: resolve(inputs.cwd ?? process.cwd(), override),
14359
- source: "override"
14360
- };
14361
- const user = inputs.userHome ?? homedir();
14362
- if ((inputs.platform ?? process.platform) === "darwin") return {
14363
- dir: join(user, ".mostra", "run"),
14364
- source: "fallback"
14365
- };
14366
- const xdg = nonEmpty(inputs.env["XDG_RUNTIME_DIR"]);
14367
- let rejected;
14368
- if (xdg !== void 0) {
14369
- rejected = unsafeXdgRuntimeDir(xdg);
14370
- if (rejected === void 0) return {
14371
- dir: join(xdg, "mostra"),
14372
- source: "xdg"
14373
- };
14374
- }
14375
- const state = nonEmpty(inputs.env["XDG_STATE_HOME"]);
14376
- const base = state !== void 0 && isAbsolute(state) ? state : join(user, ".local", "state");
14377
- const dir = join(base, "mostra", "run");
14378
- return rejected === void 0 ? {
14379
- dir,
14380
- source: "fallback"
14381
- } : {
14382
- dir,
14383
- source: "fallback",
14384
- rejected
14385
- };
14386
- }
14387
- /** Why `$XDG_RUNTIME_DIR` can't be used, or `undefined` when it can (XDG Base Directory spec). */
14388
- function unsafeXdgRuntimeDir(dir) {
14389
- if (!isAbsolute(dir)) return "it isn't an absolute path";
14390
- let stats;
14391
- try {
14392
- stats = statSync(dir);
14393
- } catch {
14394
- return "it doesn't exist";
14395
- }
14396
- if (!stats.isDirectory()) return "it isn't a directory";
14397
- if (stats.uid !== uid$1()) return "another user owns it";
14398
- if ((stats.mode & 63) !== 0) return "other users can access it";
14399
- }
14400
- /** The longest control socket path the operating system accepts, in bytes (VERIFIED_FACTS). */
14401
- function socketPathLimit(platform = process.platform) {
14402
- return platform === "darwin" ? 103 : 107;
14899
+ return runtimeDirFor({
14900
+ os: inputs.platform ?? OS,
14901
+ env: inputs.env,
14902
+ userHome: inputs.userHome ?? homedir(),
14903
+ cwd: inputs.cwd ?? process.cwd()
14904
+ });
14403
14905
  }
14404
14906
  /**
14405
14907
  * A home's hash (D82): 16 Crockford base32 characters of the SHA-256 of its real path, which
@@ -14410,73 +14912,20 @@ function homeHash(realHome) {
14410
14912
  return VersionId.fromSha256(new Uint8Array(digest)).slice(4, 20);
14411
14913
  }
14412
14914
  /**
14413
- * The control socket for a home (D82), named by its {@link homeHash}. Throws
14414
- * `MOSTRA_HOME_SOCKET_TOO_LONG` when the path exceeds the limit.
14915
+ * The control endpoint for a home (D82), named by its {@link homeHash}: the socket in `runtimeDir`
14916
+ * on POSIX, throwing `MOSTRA_HOME_SOCKET_TOO_LONG` past the system's limit; on Windows the pipe
14917
+ * name that each bind completes with a random part.
14415
14918
  */
14416
- function socketPathFor(runtimeDir, realHome, platform) {
14417
- const hash = homeHash(realHome);
14418
- const path = join(runtimeDir, `${hash}.sock`);
14419
- const limit = socketPathLimit(platform);
14420
- const length = Buffer.byteLength(path);
14421
- if (length > limit) throw new RpcError(createDiagnostic("MOSTRA_HOME_SOCKET_TOO_LONG", {
14422
- message: `The control socket path ${path} is ${length} bytes; this system allows ${limit}.`,
14423
- fix: {
14424
- kind: "command",
14425
- command: "export MOSTRA_RUNTIME_DIR=/tmp/mostra-$USER"
14426
- }
14427
- }));
14428
- return path;
14429
- }
14430
- function notOwned(path, why) {
14431
- return new RpcError(createDiagnostic("MOSTRA_HOME_NOT_OWNED", { message: `Mostra can't use ${path}: ${why}.` }));
14919
+ function socketPathFor(runtimeDir, realHome, platform = OS) {
14920
+ return controlEndpoint(runtimeDir, homeHash(realHome), platform);
14432
14921
  }
14433
14922
  /**
14434
- * Makes `path` a directory only its owner can use (D85): creates it with mode 0700 when missing,
14435
- * tightens one the user owns to 0700, and throws `MOSTRA_HOME_NOT_OWNED` for one owned by
14436
- * another user or a path that isn't a directory. Symlinks are followed.
14923
+ * Makes `path` a directory only its owner can use (D85): creates it owner-only when missing,
14924
+ * tightens one the user owns (mode 0700, or an owner-only access list on Windows), and throws
14925
+ * `MOSTRA_HOME_NOT_OWNED` for one owned by another user or a path that isn't a directory.
14437
14926
  */
14438
14927
  function prepareOwnedDirectory(path) {
14439
- try {
14440
- return prepare(path);
14441
- } catch (error) {
14442
- const code = error.code;
14443
- if (code === "ENOTDIR" || code === "EEXIST") throw notOwned(path, "a part of the path isn't a directory");
14444
- if (code === "EACCES" || code === "EPERM") throw notOwned(path, "you have no permission to use it");
14445
- throw error;
14446
- }
14447
- }
14448
- function prepare(path) {
14449
- let created = false;
14450
- try {
14451
- statSync(path);
14452
- } catch (error) {
14453
- if (error.code !== "ENOENT") throw error;
14454
- mkdirSync(path, {
14455
- recursive: true,
14456
- mode: 448
14457
- });
14458
- created = true;
14459
- }
14460
- const realPath = realpathSync(path);
14461
- const stats = statSync(realPath);
14462
- if (!stats.isDirectory()) throw notOwned(path, "it isn't a directory");
14463
- if (stats.uid !== uid$1()) throw notOwned(path, `it belongs to user ${stats.uid}, not to you`);
14464
- const mode = stats.mode & 511;
14465
- if (mode !== 448) {
14466
- chmodSync(realPath, 448);
14467
- return created ? {
14468
- realPath,
14469
- created
14470
- } : {
14471
- realPath,
14472
- created,
14473
- tightenedFrom: mode
14474
- };
14475
- }
14476
- return {
14477
- realPath,
14478
- created
14479
- };
14928
+ return ownedDirectory(path);
14480
14929
  }
14481
14930
  //#endregion
14482
14931
  //#region src/home/record.ts
@@ -14517,7 +14966,7 @@ function writeInstanceRecord(home, record) {
14517
14966
  const file = join(home, INSTANCE_FILE);
14518
14967
  const temp = `${file}.${process.pid}.tmp`;
14519
14968
  writeFileSync(temp, `${JSON.stringify(record, null, 2)}\n`, { mode: 384 });
14520
- renameSync(temp, file);
14969
+ renamePathSync(temp, file);
14521
14970
  }
14522
14971
  /** Removes the record when it is still this process's (a clean exit). */
14523
14972
  function removeInstanceRecord(home, pid, startTime) {
@@ -14550,8 +14999,12 @@ async function acquireHome(options) {
14550
14999
  const prepared = prepareOwnedDirectory(options.home);
14551
15000
  const home = prepared.realPath;
14552
15001
  const runtimeDir = resolveRuntimeDir({ env: options.env });
14553
- socketPathFor(runtimeDir.dir, home);
14554
- const socketPath = socketPathFor(prepareOwnedDirectory(runtimeDir.dir).realPath, home);
15002
+ let socketPath;
15003
+ if (runtimeDir === void 0) socketPath = socketPathFor(void 0, home);
15004
+ else {
15005
+ socketPathFor(runtimeDir.dir, home);
15006
+ socketPath = socketPathFor(prepareOwnedDirectory(runtimeDir.dir).realPath, home);
15007
+ }
14555
15008
  const redactor = new Redactor();
14556
15009
  redactor.protectEnvironment(options.env);
14557
15010
  const log = openFileLog({
@@ -14561,10 +15014,10 @@ async function acquireHome(options) {
14561
15014
  });
14562
15015
  if (prepared.tightenedFrom !== void 0) log.warn("home.tightened", {
14563
15016
  home,
14564
- from: prepared.tightenedFrom.toString(8),
14565
- to: "700"
15017
+ from: prepared.tightenedFrom,
15018
+ to: "owner only"
14566
15019
  });
14567
- if (runtimeDir.rejected !== void 0) log.warn("home.xdg_runtime_dir_rejected", {
15020
+ if (runtimeDir?.rejected !== void 0) log.warn("home.xdg_runtime_dir_rejected", {
14568
15021
  reason: runtimeDir.rejected,
14569
15022
  using: runtimeDir.dir
14570
15023
  });
@@ -14655,11 +15108,11 @@ function own(inputs) {
14655
15108
  redactor,
14656
15109
  self,
14657
15110
  startedAt,
14658
- publish(mode) {
15111
+ publish(mode, socket) {
14659
15112
  writeInstanceRecord(home, {
14660
15113
  pid: self.pid,
14661
15114
  startTime: self.startTime,
14662
- socket: socketPath,
15115
+ socket,
14663
15116
  runtimeVersion: inputs.options.runtimeVersion,
14664
15117
  revisions: [...HOST_PROTOCOL_REVISIONS],
14665
15118
  mode,
@@ -14694,21 +15147,27 @@ function own(inputs) {
14694
15147
  //#endregion
14695
15148
  //#region src/home/platform.ts
14696
15149
  /**
14697
- * The unsupported-platform gate (D35, RT-07). Every entry point calls it before it touches the
14698
- * home: Mostra 1.0 runs on macOS and Linux, on x64 and arm64, and fails closed elsewhere.
15150
+ * The unsupported-platform gate (D35, D146, RT-07). Every entry point calls it before it touches
15151
+ * the home: Mostra runs on macOS and Linux, on x64 and arm64, and fails closed elsewhere. Windows
15152
+ * (x64 and arm64) is being built (WP-W1 to WP-W3) and runs only behind the development switch
15153
+ * `MOSTRA_DEV_WINDOWS=1`, which only Mostra's own CI sets, so no release exposes a partial port.
15154
+ * WP-W3 removes the switch.
14699
15155
  */
14700
15156
  const OPERATING_SYSTEMS = ["darwin", "linux"];
14701
15157
  const ARCHITECTURES = ["x64", "arm64"];
14702
15158
  /** The platform as `<os>-<arch>`, as `InstanceInfo.platform` reports it. */
14703
- function platformName(platform = process.platform, arch = process.arch) {
15159
+ function platformName(platform = OS, arch = process.arch) {
14704
15160
  return `${platform}-${arch}`;
14705
15161
  }
14706
15162
  /**
14707
15163
  * Returns `MOSTRA_PLATFORM_UNSUPPORTED` for a platform Mostra doesn't run on, or `undefined` for
14708
- * a supported one.
15164
+ * a supported one. Windows is supported only while `env` sets the development switch to `1`.
14709
15165
  */
14710
- function checkPlatform(platform = process.platform, arch = process.arch) {
14711
- if (OPERATING_SYSTEMS.includes(platform) && ARCHITECTURES.includes(arch)) return void 0;
15166
+ function checkPlatform(platform = OS, arch = process.arch, env = process.env) {
15167
+ if (ARCHITECTURES.includes(arch)) {
15168
+ if (OPERATING_SYSTEMS.includes(platform)) return void 0;
15169
+ if (platform === "win32" && env["MOSTRA_DEV_WINDOWS"] === "1") return void 0;
15170
+ }
14712
15171
  const name = platform === "win32" ? `Windows (${platformName(platform, arch)})` : platformName(platform, arch);
14713
15172
  return createDiagnostic("MOSTRA_PLATFORM_UNSUPPORTED", { message: `Mostra doesn't run on ${name}; it supports macOS and Linux on x64 and arm64.` });
14714
15173
  }
@@ -14771,19 +15230,9 @@ function writeHomeSettings(home, change) {
14771
15230
  const file = join(home, SETTINGS_FILE);
14772
15231
  const temporary = `${file}.${process.pid}.tmp`;
14773
15232
  writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`, { mode: 384 });
14774
- const handle = openSync(temporary, "r");
14775
- try {
14776
- fsyncSync(handle);
14777
- } finally {
14778
- closeSync(handle);
14779
- }
14780
- renameSync(temporary, file);
14781
- const dir = openSync(home, "r");
14782
- try {
14783
- fsyncSync(dir);
14784
- } catch {} finally {
14785
- closeSync(dir);
14786
- }
15233
+ fsyncPath(temporary);
15234
+ renamePathSync(temporary, file);
15235
+ fsyncPath(home, true);
14787
15236
  }
14788
15237
  /**
14789
15238
  * Marks the home as configured by a host (D140 item 4), once: the first host's client name and
@@ -14873,7 +15322,7 @@ function openSecrets(options) {
14873
15322
  flag: "w"
14874
15323
  });
14875
15324
  chmodSync(temporary, 384);
14876
- renameSync(temporary, join(dir, name));
15325
+ renamePathSync(temporary, join(dir, name));
14877
15326
  options.log.info("secret.set", {
14878
15327
  name,
14879
15328
  scope: scope.kind
@@ -14974,11 +15423,14 @@ function watchIdle(options) {
14974
15423
  //#endregion
14975
15424
  //#region src/service/unit.ts
14976
15425
  /**
14977
- * The home's login service (D62, D63, RT-08): `mostra daemon install` registers the home's daemon
14978
- * with the user's service manager, so an artifact answers at any hour, even after a reboot. A
14979
- * launchd agent on macOS, a systemd user unit on Linux; either runs `mostra-runtime daemon
14980
- * --always-on --home <home>`, which never exits for lack of work, and restarts it when it ends
14981
- * unexpectedly. The unit carries no secret: the daemon reads them from the home (D44).
15426
+ * The home's login service (D62, D63, RT-08, RT-11): `mostra daemon install` registers the home's
15427
+ * daemon with the user's service manager, so an artifact answers at any hour, even after a reboot.
15428
+ * A launchd agent on macOS, a systemd user unit on Linux, a Task Scheduler task at the user's logon
15429
+ * on Windows (D151); each runs `mostra-runtime daemon --always-on --home <home>`, which never
15430
+ * exits for lack of work, and restarts it when it ends unexpectedly. On Windows the task runs the
15431
+ * daemon through `mostra-win-service`, a launcher without a console, so no window opens at logon,
15432
+ * which also does the restarting (Task Scheduler's own setting didn't, VERIFIED_FACTS WP-W2). The
15433
+ * definition carries no secret: the daemon reads them from the home (D44).
14982
15434
  */
14983
15435
  function failed(message) {
14984
15436
  return new RpcError(createDiagnostic("MOSTRA_ENV_SERVICE_FAILED", { message }));
@@ -14989,7 +15441,7 @@ function userHome(env) {
14989
15441
  /** The service a home's daemon would be, installed or not. */
14990
15442
  function serviceFor(spec) {
14991
15443
  const env = spec.env ?? process.env;
14992
- const platform = spec.platform ?? process.platform;
15444
+ const platform = spec.platform ?? OS;
14993
15445
  const hash = homeHash(spec.home);
14994
15446
  const command = [
14995
15447
  spec.node,
@@ -15021,24 +15473,182 @@ function serviceFor(spec) {
15021
15473
  command
15022
15474
  };
15023
15475
  }
15476
+ if (platform === "win32") {
15477
+ const file = win32.join(spec.home, "service", "task.xml");
15478
+ return {
15479
+ manager: "task-scheduler",
15480
+ name: `mostra-${hash.toLowerCase()}`,
15481
+ file,
15482
+ installed: existsSync(file),
15483
+ command: [
15484
+ spec.launcher ?? launcherOrName(),
15485
+ "--stop-event",
15486
+ stopEventOf(file) ?? newStopEvent(hash),
15487
+ "--log",
15488
+ win32.join(spec.home, "logs", "service.log"),
15489
+ ...windowsServiceVariables(env).flatMap(([name, value]) => ["--env", `${name}=${value}`]),
15490
+ "--",
15491
+ ...command
15492
+ ]
15493
+ };
15494
+ }
15024
15495
  throw new RpcError(createDiagnostic("MOSTRA_PLATFORM_UNSUPPORTED", { message: `Mostra can't install a login service on ${platform}.` }));
15025
15496
  }
15026
15497
  /**
15498
+ * What a Windows task passes on besides the user's logon environment, which Task Scheduler gives
15499
+ * it: the development switch while Windows needs it (D150 item 7, until WP-W3), the helper a
15500
+ * checkout names, and the locale and time zone, as the POSIX units carry theirs. Nothing secret.
15501
+ */
15502
+ function windowsServiceVariables(env) {
15503
+ return [
15504
+ "MOSTRA_DEV_WINDOWS",
15505
+ "MOSTRA_WIN_HELPER",
15506
+ "LANG",
15507
+ "TZ"
15508
+ ].flatMap((name) => {
15509
+ const value = env[name];
15510
+ return value ? [[name, value]] : [];
15511
+ });
15512
+ }
15513
+ /**
15514
+ * A new name for the event that asks a home's launcher to stop: in `Local\` (the logon session's
15515
+ * namespace, the only one an ordinary user may create names in), with a random part, so nobody who
15516
+ * can't read the task or the home can create it first (Opus review of WP-W2, finding 6).
15517
+ */
15518
+ const newStopEvent = (hash) => `Local\\mostra-service-${hash.toLowerCase()}-${randomBytes(8).toString("hex")}`;
15519
+ /** The stop event a definition Mostra wrote names, if the file is there. */
15520
+ function stopEventOf(file) {
15521
+ try {
15522
+ const text = readFileSync(file).toString("utf16le");
15523
+ return /--stop-event (Local\\mostra-service-[0-9a-z]+-[0-9a-f]{16})\b/.exec(text)?.[1];
15524
+ } catch {
15525
+ return;
15526
+ }
15527
+ }
15528
+ /** The launcher's path, or its bare name where it isn't installed (a status only reads it). */
15529
+ function launcherOrName() {
15530
+ try {
15531
+ return serviceLauncherPath();
15532
+ } catch {
15533
+ return "mostra-win-service.exe";
15534
+ }
15535
+ }
15536
+ /** One word of a Windows command line, quoted as the Microsoft C runtime parses it. */
15537
+ function windowsArgument(word) {
15538
+ if (word !== "" && !/[\s"]/.test(word)) return word;
15539
+ let out = "\"";
15540
+ let backslashes = 0;
15541
+ for (const char of word) {
15542
+ if (char === "\\") {
15543
+ backslashes += 1;
15544
+ continue;
15545
+ }
15546
+ out += "\\".repeat(char === "\"" ? backslashes * 2 + 1 : backslashes) + char;
15547
+ backslashes = 0;
15548
+ }
15549
+ return `${out}${"\\".repeat(backslashes * 2)}"`;
15550
+ }
15551
+ /** The Task Scheduler definition (schema 1.2) of a home's task. */
15552
+ function taskFile(spec, status) {
15553
+ const user = xml(spec.user ?? currentUserSid());
15554
+ const [program = "", ...args] = status.command;
15555
+ return `<?xml version="1.0" encoding="UTF-16"?>
15556
+ <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
15557
+ <RegistrationInfo>
15558
+ <Description>${xml(`Mostra daemon for ${spec.home}`)}</Description>
15559
+ </RegistrationInfo>
15560
+ <Triggers>
15561
+ <LogonTrigger>
15562
+ <Enabled>true</Enabled>
15563
+ <UserId>${user}</UserId>
15564
+ </LogonTrigger>
15565
+ </Triggers>
15566
+ <Principals>
15567
+ <Principal id="Author">
15568
+ <UserId>${user}</UserId>
15569
+ <LogonType>InteractiveToken</LogonType>
15570
+ <RunLevel>LeastPrivilege</RunLevel>
15571
+ </Principal>
15572
+ </Principals>
15573
+ <Settings>
15574
+ <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
15575
+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
15576
+ <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
15577
+ <AllowHardTerminate>true</AllowHardTerminate>
15578
+ <StartWhenAvailable>false</StartWhenAvailable>
15579
+ <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
15580
+ <IdleSettings>
15581
+ <StopOnIdleEnd>false</StopOnIdleEnd>
15582
+ <RestartOnIdle>false</RestartOnIdle>
15583
+ </IdleSettings>
15584
+ <AllowStartOnDemand>true</AllowStartOnDemand>
15585
+ <Enabled>true</Enabled>
15586
+ <Hidden>false</Hidden>
15587
+ <RunOnlyIfIdle>false</RunOnlyIfIdle>
15588
+ <WakeToRun>false</WakeToRun>
15589
+ <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
15590
+ <Priority>5</Priority>
15591
+ </Settings>
15592
+ <Actions Context="Author">
15593
+ <Exec>
15594
+ <Command>${xml(program)}</Command>
15595
+ <Arguments>${xml(args.map(windowsArgument).join(" "))}</Arguments>
15596
+ </Exec>
15597
+ </Actions>
15598
+ </Task>
15599
+ `;
15600
+ }
15601
+ /**
15027
15602
  * Whether `home` has a login service installed: its daemon then never exits for lack of work,
15028
15603
  * whoever started it, so a daemon started by hand before `install` keeps the artifacts answering.
15029
15604
  */
15030
15605
  function hasLoginService(home, env = process.env) {
15031
15606
  try {
15032
- return serviceFor({
15607
+ const status = serviceFor({
15033
15608
  home,
15034
15609
  node: "",
15035
15610
  entry: "",
15036
15611
  env
15037
- }).installed;
15612
+ });
15613
+ if (!status.installed) return false;
15614
+ return status.manager !== "task-scheduler" || registeredLately(status);
15038
15615
  } catch {
15039
15616
  return false;
15040
15617
  }
15041
15618
  }
15619
+ /** What the idle check last learnt of each task: whether Task Scheduler holds it, and when. */
15620
+ const registrations = /* @__PURE__ */ new Map();
15621
+ /**
15622
+ * Whether Task Scheduler held the task when last asked, asking again in the background at most
15623
+ * once a minute: the idle check runs every few seconds and must never wait for `schtasks`. A task
15624
+ * removed in Task Scheduler's own window then stops counting, so a daemon started by hand exits
15625
+ * when idle again (Opus review of WP-W2, finding 5). Until the first answer, the definition in the
15626
+ * home counts.
15627
+ */
15628
+ function registeredLately(status) {
15629
+ const interval = Number(process.env["MOSTRA_TEST_SERVICE_QUERY_MS"]) || 6e4;
15630
+ const entry = registrations.get(status.name) ?? {
15631
+ at: Number.NEGATIVE_INFINITY,
15632
+ asking: false
15633
+ };
15634
+ registrations.set(status.name, entry);
15635
+ if (!entry.asking && Date.now() - entry.at >= interval) {
15636
+ entry.asking = true;
15637
+ execFile("schtasks", [
15638
+ "/Query",
15639
+ "/TN",
15640
+ status.name
15641
+ ], {
15642
+ timeout: 3e4,
15643
+ windowsHide: true
15644
+ }, (error) => {
15645
+ entry.registered = error === null;
15646
+ entry.at = Date.now();
15647
+ entry.asking = false;
15648
+ });
15649
+ }
15650
+ return entry.registered ?? true;
15651
+ }
15042
15652
  const xml = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
15043
15653
  /** systemd's quoting for one `ExecStart` word. */
15044
15654
  const systemdWord = (word) => /^[A-Za-z0-9_./:@=+-]+$/.test(word) ? word : `"${word.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/%/g, "%%").replace(/\$/g, "$$$$")}"`;
@@ -15060,6 +15670,7 @@ function serviceEnvironment(env) {
15060
15670
  }
15061
15671
  /** The text of the service's file. */
15062
15672
  function serviceFile(spec, status) {
15673
+ if (status.manager === "task-scheduler") return taskFile(spec, status);
15063
15674
  const env = serviceEnvironment(spec.env ?? process.env);
15064
15675
  const log = join(spec.home, "logs", "service.log");
15065
15676
  if (status.manager === "launchd") {
@@ -15129,29 +15740,60 @@ function run(command, args) {
15129
15740
  }
15130
15741
  }
15131
15742
  const uid = () => process.getuid?.() ?? 0;
15743
+ /** The definition's bytes: Task Scheduler reads UTF-16 with its byte order mark. */
15744
+ function encoded(status, text) {
15745
+ return status.manager === "task-scheduler" ? Buffer.from(`\ufeff${text}`, "utf16le") : text;
15746
+ }
15747
+ /** The definition as written, decoded as {@link encoded} wrote it. */
15748
+ function readDefinition(status) {
15749
+ const bytes = readFileSync(status.file);
15750
+ if (status.manager !== "task-scheduler") return bytes.toString("utf8");
15751
+ return bytes.toString("utf16le").replace(/^\ufeff/, "");
15752
+ }
15132
15753
  /** Installs the home's daemon as a login service and starts it, replacing an earlier one. */
15133
- function installService(spec, options = {}) {
15134
- const status = serviceFor(spec);
15754
+ async function installService(spec, options = {}) {
15755
+ const status = serviceFor((spec.platform ?? OS) === "win32" && spec.launcher === void 0 ? {
15756
+ ...spec,
15757
+ launcher: serviceLauncherPath()
15758
+ } : spec);
15135
15759
  const text = serviceFile(spec, status);
15760
+ const registering = status.manager === "task-scheduler" && !options.noStart;
15761
+ const written = registering ? `${status.file}.new` : status.file;
15136
15762
  try {
15137
15763
  mkdirSync(dirname(status.file), { recursive: true });
15138
15764
  mkdirSync(join(spec.home, "logs"), {
15139
15765
  recursive: true,
15140
15766
  mode: 448
15141
15767
  });
15142
- if (status.installed && !options.noStart) stopService(status);
15143
- writeFileSync(status.file, text, { mode: 420 });
15768
+ if (status.installed && !options.noStart) await stopService(status, spec.home, options);
15769
+ writeFileSync(written, encoded(status, text), { mode: 420 });
15144
15770
  } catch (error) {
15145
15771
  if (error instanceof RpcError) throw error;
15146
15772
  throw failed(`Writing ${status.file} failed: ${error.message}`);
15147
15773
  }
15774
+ if (registering) {
15775
+ try {
15776
+ run("schtasks", [
15777
+ "/Create",
15778
+ "/TN",
15779
+ status.name,
15780
+ "/XML",
15781
+ written,
15782
+ "/F"
15783
+ ]);
15784
+ renameSync(written, status.file);
15785
+ } finally {
15786
+ rmSync(written, { force: true });
15787
+ }
15788
+ registrations.delete(status.name);
15789
+ }
15148
15790
  if (!options.noStart) {
15149
15791
  if (status.manager === "launchd") run("launchctl", [
15150
15792
  "bootstrap",
15151
15793
  `gui/${uid()}`,
15152
15794
  status.file
15153
15795
  ]);
15154
- else {
15796
+ else if (status.manager === "systemd") {
15155
15797
  run("systemctl", ["--user", "daemon-reload"]);
15156
15798
  run("systemctl", [
15157
15799
  "--user",
@@ -15159,29 +15801,104 @@ function installService(spec, options = {}) {
15159
15801
  "--now",
15160
15802
  status.name
15161
15803
  ]);
15162
- }
15804
+ } else run("schtasks", [
15805
+ "/Run",
15806
+ "/TN",
15807
+ status.name
15808
+ ]);
15163
15809
  }
15164
15810
  return {
15165
15811
  ...status,
15166
15812
  installed: true
15167
15813
  };
15168
15814
  }
15169
- function stopService(status) {
15815
+ async function stopService(status, home, options) {
15170
15816
  try {
15171
15817
  if (status.manager === "launchd") run("launchctl", ["bootout", `gui/${uid()}/${status.name}`]);
15172
- else run("systemctl", [
15818
+ else if (status.manager === "systemd") run("systemctl", [
15173
15819
  "--user",
15174
15820
  "disable",
15175
15821
  "--now",
15176
15822
  status.name
15177
15823
  ]);
15824
+ else await stopTask(status, home, options);
15825
+ } catch {}
15826
+ }
15827
+ /**
15828
+ * Stops and deletes a home's task, the daemon first and in order (D87), as launchd's `bootout`
15829
+ * and systemd's `disable --now` send it SIGTERM:
15830
+ * - through the launcher's stop event, when this logon session has it: the launcher gives the
15831
+ * daemon Ctrl+Break, which the runtime handles as `mostra/shutdown`;
15832
+ * - otherwise (the launcher runs in another session, as when the user is logged on at the console
15833
+ * and uninstalls over SSH, or the home lost the definition naming the event) with
15834
+ * `mostra/shutdown` over the home's pipe, which reaches the daemon from any session; its exit
15835
+ * with code 0 ends the launcher (Opus review of WP-W2, finding 4);
15836
+ *
15837
+ * then the task is ended, which ends whatever its job still holds, and deleted.
15838
+ */
15839
+ async function stopTask(status, home, options) {
15840
+ const event = status.installed ? status.command[status.command.indexOf("--stop-event") + 1] : void 0;
15841
+ let signalled = false;
15842
+ if (event !== void 0 && process.env["MOSTRA_TEST_SERVICE_STOP"] !== "pipe") try {
15843
+ signalled = stopServiceLauncher(event).signalled;
15844
+ } catch {}
15845
+ if (!signalled) await shutDownInstance(home, options.client);
15846
+ try {
15847
+ run("schtasks", [
15848
+ "/End",
15849
+ "/TN",
15850
+ status.name
15851
+ ]);
15178
15852
  } catch {}
15853
+ run("schtasks", [
15854
+ "/Delete",
15855
+ "/TN",
15856
+ status.name,
15857
+ "/F"
15858
+ ]);
15859
+ registrations.delete(status.name);
15860
+ }
15861
+ /** Asks the home's running daemon, if any, to stop (`mostra/shutdown`), and waits until it has. */
15862
+ async function shutDownInstance(home, client) {
15863
+ const record = await readLiveInstanceRecord(home);
15864
+ if (record === void 0 || record.mode !== "daemon") return;
15865
+ try {
15866
+ const session = await attach(record.socket, client ?? {
15867
+ name: "mostra-service",
15868
+ version: "0"
15869
+ });
15870
+ await session.client.peer.call(mostraShutdownMethod, {}, { timeoutMs: 1e4 }).catch(() => void 0);
15871
+ session.client.close();
15872
+ } catch {
15873
+ return;
15874
+ }
15875
+ const deadline = Date.now() + 2e4;
15876
+ while (Date.now() < deadline && await isSameProcess(record.pid, record.startTime)) await new Promise((resolve) => setTimeout(resolve, 100));
15877
+ }
15878
+ /** Whether Task Scheduler holds the home's task. */
15879
+ function taskRegistered(status) {
15880
+ try {
15881
+ run("schtasks", [
15882
+ "/Query",
15883
+ "/TN",
15884
+ status.name
15885
+ ]);
15886
+ return true;
15887
+ } catch {
15888
+ return false;
15889
+ }
15179
15890
  }
15180
- /** Stops and removes the home's login service; a home without one is left as it is. */
15181
- function uninstallService(spec, options = {}) {
15891
+ /**
15892
+ * Stops and removes the home's login service; a home without one is left as it is. On Windows a
15893
+ * task Task Scheduler still holds is removed though the home lost its definition (restored from a
15894
+ * backup, removed by hand), or the task would keep starting the daemon at every logon (Opus review
15895
+ * of WP-W2, finding 5).
15896
+ */
15897
+ async function uninstallService(spec, options = {}) {
15182
15898
  const status = serviceFor(spec);
15183
- if (!status.installed) return status;
15184
- if (!options.noStart) stopService(status);
15899
+ const orphaned = !status.installed && status.manager === "task-scheduler" && !options.noStart && taskRegistered(status);
15900
+ if (!status.installed && !orphaned) return status;
15901
+ if (!options.noStart) await stopService(status, spec.home, options);
15185
15902
  rmSync(status.file, { force: true });
15186
15903
  if (!options.noStart && status.manager === "systemd") try {
15187
15904
  run("systemctl", ["--user", "daemon-reload"]);
@@ -15191,17 +15908,22 @@ function uninstallService(spec, options = {}) {
15191
15908
  installed: false
15192
15909
  };
15193
15910
  }
15194
- /** Whether the home has a login service whose file runs this home's daemon (`mostra doctor`). */
15911
+ /**
15912
+ * Whether the home has a login service whose file runs this home's daemon (`mostra doctor`); on
15913
+ * Windows also whether Task Scheduler holds its task (`registered`).
15914
+ */
15195
15915
  function serviceStatus(spec) {
15196
15916
  const status = serviceFor(spec);
15917
+ const registered = status.manager === "task-scheduler" ? { registered: taskRegistered(status) } : {};
15197
15918
  if (!status.installed) return {
15198
15919
  ...status,
15199
- current: false
15920
+ current: false,
15921
+ ...registered
15200
15922
  };
15201
- const text = readFileSync(status.file, "utf8");
15202
15923
  return {
15203
15924
  ...status,
15204
- current: text === serviceFile(spec, status)
15925
+ current: readDefinition(status) === serviceFile(spec, status),
15926
+ ...registered
15205
15927
  };
15206
15928
  }
15207
15929
  //#endregion
@@ -15296,7 +16018,7 @@ async function startInstance(options) {
15296
16018
  }
15297
16019
  function sameHome(home, path) {
15298
16020
  try {
15299
- return realpathSync(path) === home;
16021
+ return realPath(path) === home;
15300
16022
  } catch {
15301
16023
  return resolve(path) === home;
15302
16024
  }
@@ -15372,7 +16094,7 @@ async function assemble(home, options) {
15372
16094
  let runner;
15373
16095
  let verifier;
15374
16096
  const sandboxOptions = () => {
15375
- const workerLocation = locateWorker(environment, runtimeRoot());
16097
+ const workerLocation = locateWorker(environment, runtimeRoot$1());
15376
16098
  return {
15377
16099
  home: home.path,
15378
16100
  log,
@@ -15394,7 +16116,7 @@ async function assemble(home, options) {
15394
16116
  };
15395
16117
  const getVerifier = () => {
15396
16118
  if (verifier) return verifier;
15397
- const located = locateRunner(environment, runtimeRoot());
16119
+ const located = locateRunner(environment, runtimeRoot$1());
15398
16120
  runner = createRunnerClient({
15399
16121
  processes: manager,
15400
16122
  log,
@@ -15482,7 +16204,7 @@ async function assemble(home, options) {
15482
16204
  const testLease = Number(environment["MOSTRA_TEST_INTEREST_LEASE_MS"]);
15483
16205
  const bus = createEphemeralBus(testLease > 0 ? { leaseMs: testLease } : {});
15484
16206
  const workerSocket = environment["MOSTRA_TEST_WORKER_HOST"];
15485
- const located = locateWorker(environment, runtimeRoot());
16207
+ const located = locateWorker(environment, runtimeRoot$1());
15486
16208
  const launcher = workerSocket ? socketLauncher(workerSocket) : localLauncher({
15487
16209
  processes: manager,
15488
16210
  home: home.path,
@@ -15742,7 +16464,7 @@ async function assemble(home, options) {
15742
16464
  ...sessionMethods({
15743
16465
  describe: () => info,
15744
16466
  startedAt: home.startedAt,
15745
- socketPath: () => home.socketPath,
16467
+ socketPath: () => server.socketPath ?? home.socketPath,
15746
16468
  connections: () => server.connections,
15747
16469
  processes: () => manager.list(),
15748
16470
  gateway: () => gatewayStarted ? {
@@ -15769,7 +16491,9 @@ async function assemble(home, options) {
15769
16491
  });
15770
16492
  const instance = {
15771
16493
  info,
15772
- socketPath: home.socketPath,
16494
+ get socketPath() {
16495
+ return server.socketPath ?? home.socketPath;
16496
+ },
15773
16497
  processes: manager,
15774
16498
  reaped,
15775
16499
  stopped,
@@ -15783,7 +16507,7 @@ async function assemble(home, options) {
15783
16507
  stopWatchingPublishes();
15784
16508
  live.stop();
15785
16509
  interaction.stop();
15786
- server.close();
16510
+ await server.close();
15787
16511
  await dev.stopAll();
15788
16512
  await gateway.close();
15789
16513
  await pool.stopAll();
@@ -15817,15 +16541,37 @@ async function assemble(home, options) {
15817
16541
  try {
15818
16542
  await gateway.start();
15819
16543
  gatewayStarted = true;
15820
- await server.listen(home.socketPath, options.checkIntervalMs);
16544
+ const launchPipe = async (name) => {
16545
+ const child = await manager.spawn({
16546
+ kind: "control-pipe",
16547
+ ownerRef: home.path,
16548
+ command: helperPath(),
16549
+ args: ["pipe", name],
16550
+ channel: true
16551
+ });
16552
+ if (!child.channel) throw new Error("The control pipe's helper has no channel.");
16553
+ return {
16554
+ channel: child.channel,
16555
+ exited: child.exited,
16556
+ stop: () => child.stop(2e3)
16557
+ };
16558
+ };
16559
+ await server.listen(home.socketPath, options.checkIntervalMs, {
16560
+ launchPipe,
16561
+ onMoved: (path) => {
16562
+ faults.at("endpoint:moved");
16563
+ home.publish(options.mode, path);
16564
+ log.warn("home.endpoint_moved", { socket: path });
16565
+ }
16566
+ });
15821
16567
  interaction.start();
15822
16568
  live.start();
15823
- home.publish(options.mode);
16569
+ home.publish(options.mode, server.socketPath ?? home.socketPath);
15824
16570
  if (options.mode === "host" && markHostConfigured(home.path, "mostra-runtime host")) log.info("home.host_configured", { client: "mostra-runtime host" });
15825
16571
  } catch (error) {
15826
16572
  live.stop();
15827
16573
  interaction.stop();
15828
- server.close();
16574
+ await server.close();
15829
16575
  await gateway.close();
15830
16576
  await pool.stopAll();
15831
16577
  await manager.stopAll();
@@ -15864,7 +16610,7 @@ async function assemble(home, options) {
15864
16610
  log.info("instance.started", {
15865
16611
  mode: options.mode,
15866
16612
  pid: process.pid,
15867
- socket: home.socketPath,
16613
+ socket: server.socketPath ?? home.socketPath,
15868
16614
  shell: gateway.shellOrigin()
15869
16615
  });
15870
16616
  return instance;
@@ -15917,4 +16663,4 @@ function sourceDirectory(path) {
15917
16663
  //#endregion
15918
16664
  export { uninstallService as a, serviceStatus as i, startInstance as n, checkPlatform as o, installService as r, resolveHomePath as s, runtimeVersion as t };
15919
16665
 
15920
- //# sourceMappingURL=instance-CzBkUyHu.js.map
16666
+ //# sourceMappingURL=instance-DxcGEQj_.js.map