@mostra/runtime 0.0.0-stage → 0.2.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.
- package/LICENSE +202 -0
- package/README.md +39 -2
- package/dist/bin.d.ts +1 -0
- package/dist/bin.js +236 -0
- package/dist/bin.js.map +1 -0
- package/dist/builder/child/main.d.ts +1 -0
- package/dist/builder/child/main.js +1408 -0
- package/dist/builder/child/main.js.map +1 -0
- package/dist/child-xrHmytks.js +49 -0
- package/dist/child-xrHmytks.js.map +1 -0
- package/dist/deps/child/install.d.ts +1 -0
- package/dist/deps/child/install.js +33 -0
- package/dist/deps/child/install.js.map +1 -0
- package/dist/index.d.ts +221 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/instance-CzBkUyHu.js +15920 -0
- package/dist/instance-CzBkUyHu.js.map +1 -0
- package/dist/types-NjNy7gXX.js +57 -0
- package/dist/types-NjNy7gXX.js.map +1 -0
- package/package.json +87 -3
- package/src/actions/index.ts +622 -0
- package/src/addressing/index.ts +281 -0
- package/src/bin.ts +240 -0
- package/src/builder/child/dev.ts +383 -0
- package/src/builder/child/fields.ts +363 -0
- package/src/builder/child/main.ts +47 -0
- package/src/builder/child/plugins.ts +195 -0
- package/src/builder/child/scan.ts +459 -0
- package/src/builder/child/spa.ts +348 -0
- package/src/builder/coverage.ts +72 -0
- package/src/builder/index.ts +406 -0
- package/src/builder/types.ts +180 -0
- package/src/deps/child/install.ts +30 -0
- package/src/deps/index.ts +918 -0
- package/src/deps/installer.ts +321 -0
- package/src/deps/lock.ts +82 -0
- package/src/deps/scan.ts +266 -0
- package/src/deps/specifier.ts +64 -0
- package/src/deps/warm.ts +57 -0
- package/src/dev/index.ts +518 -0
- package/src/faults.ts +65 -0
- package/src/gate.ts +55 -0
- package/src/gateway/actions.ts +268 -0
- package/src/gateway/browser.ts +650 -0
- package/src/gateway/capabilities.ts +760 -0
- package/src/gateway/controls.ts +91 -0
- package/src/gateway/dev.ts +119 -0
- package/src/gateway/http.ts +229 -0
- package/src/gateway/identity.ts +101 -0
- package/src/gateway/index.ts +1299 -0
- package/src/gateway/integrity.ts +117 -0
- package/src/gateway/listener.ts +217 -0
- package/src/gateway/routes.ts +197 -0
- package/src/gateway/serve.ts +138 -0
- package/src/gc/index.ts +451 -0
- package/src/home/acquire.ts +276 -0
- package/src/home/index.ts +16 -0
- package/src/home/paths.ts +192 -0
- package/src/home/platform.ts +34 -0
- package/src/home/record.ts +76 -0
- package/src/home/settings.ts +113 -0
- package/src/index.ts +30 -0
- package/src/instance/index.ts +979 -0
- package/src/interaction/ephemeral.ts +300 -0
- package/src/interaction/events.ts +355 -0
- package/src/interaction/fields.ts +392 -0
- package/src/interaction/index.ts +1013 -0
- package/src/interaction/outbox.ts +493 -0
- package/src/interaction/policy.ts +26 -0
- package/src/interaction/results.ts +341 -0
- package/src/interaction/runs.ts +313 -0
- package/src/interaction/signals.ts +120 -0
- package/src/interaction/submissions.ts +585 -0
- package/src/interaction/subscriptions.ts +258 -0
- package/src/interaction/viewers.ts +187 -0
- package/src/interaction/wait.ts +201 -0
- package/src/ledger/index.ts +442 -0
- package/src/ledger/migrations.ts +596 -0
- package/src/ledger/requests.ts +105 -0
- package/src/ledger/types.ts +28 -0
- package/src/live/index.ts +573 -0
- package/src/log.ts +316 -0
- package/src/processes/child.ts +67 -0
- package/src/processes/environment.ts +64 -0
- package/src/processes/identity.ts +191 -0
- package/src/processes/index.ts +19 -0
- package/src/processes/manager.ts +543 -0
- package/src/protocol-server/client.ts +94 -0
- package/src/protocol-server/index.ts +91 -0
- package/src/protocol-server/server.ts +518 -0
- package/src/protocol-server/streams.ts +81 -0
- package/src/publish/checks.ts +92 -0
- package/src/publish/digest.ts +87 -0
- package/src/publish/index.ts +23 -0
- package/src/publish/manifest.ts +409 -0
- package/src/publish/methods.ts +96 -0
- package/src/publish/publisher.ts +913 -0
- package/src/publish/source.ts +272 -0
- package/src/publish/tar.ts +110 -0
- package/src/registry/index.ts +481 -0
- package/src/registry/store.ts +136 -0
- package/src/secrets/index.ts +223 -0
- package/src/service/idle.ts +64 -0
- package/src/service/index.ts +3 -0
- package/src/service/unit.ts +250 -0
- package/src/verify/fields.ts +125 -0
- package/src/verify/index.ts +913 -0
- package/src/verify/regression.ts +157 -0
- package/src/verify/runner.ts +230 -0
- package/src/verify/sandbox.ts +407 -0
- package/src/verify/typecheck.ts +371 -0
- package/src/workers/index.ts +17 -0
- package/src/workers/launcher.ts +260 -0
- package/src/workers/pool.ts +708 -0
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Taking a home (D81, D82, D85; FAILURE_MODEL §2, §3). The ledger's exclusive lock decides who
|
|
3
|
+
* owns the home; the socket and `instance.json` are how everyone else finds the owner. A starter
|
|
4
|
+
* that doesn't get the lock attaches to the owner (a daemon starter) or reports
|
|
5
|
+
* `MOSTRA_HOME_LOCKED` (`mostra host`, or an owner it can't reach).
|
|
6
|
+
*/
|
|
7
|
+
import { statSync } from "node:fs";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import {
|
|
10
|
+
type ClientInfo,
|
|
11
|
+
createDiagnostic,
|
|
12
|
+
type Diagnostic,
|
|
13
|
+
HOST_PROTOCOL_REVISIONS,
|
|
14
|
+
type MostraInitializeResult,
|
|
15
|
+
RpcError,
|
|
16
|
+
} from "@mostra/protocol";
|
|
17
|
+
import { LEDGER_FILE, type Ledger, openLedger } from "../ledger/index.ts";
|
|
18
|
+
import { type Environment, type Log, openFileLog, Redactor } from "../log.ts";
|
|
19
|
+
import { readProcess } from "../processes/index.ts";
|
|
20
|
+
import { attach, type SocketClient } from "../protocol-server/index.ts";
|
|
21
|
+
import {
|
|
22
|
+
prepareOwnedDirectory,
|
|
23
|
+
type RuntimeDirChoice,
|
|
24
|
+
resolveRuntimeDir,
|
|
25
|
+
socketPathFor,
|
|
26
|
+
} from "./paths.ts";
|
|
27
|
+
import {
|
|
28
|
+
type InstanceRecord,
|
|
29
|
+
readInstanceRecord,
|
|
30
|
+
readLiveInstanceRecord,
|
|
31
|
+
removeInstanceRecord,
|
|
32
|
+
writeInstanceRecord,
|
|
33
|
+
} from "./record.ts";
|
|
34
|
+
|
|
35
|
+
/** How long a starter waits for the owner of a locked home to become reachable, by default. */
|
|
36
|
+
const DEFAULT_WAIT_MS = 20_000;
|
|
37
|
+
/** How often the owner checks that its home still exists, by default (at most 10 s, D81). */
|
|
38
|
+
const DEFAULT_WATCH_MS = 5000;
|
|
39
|
+
|
|
40
|
+
/** Options for {@link acquireHome}. */
|
|
41
|
+
export interface AcquireHomeOptions {
|
|
42
|
+
/** The resolved home path (`resolveHomePath`). */
|
|
43
|
+
readonly home: string;
|
|
44
|
+
readonly env: Environment;
|
|
45
|
+
/** `host` never attaches to another instance; `daemon` does. */
|
|
46
|
+
readonly mode: "host" | "daemon";
|
|
47
|
+
readonly runtimeVersion: string;
|
|
48
|
+
/** How a losing daemon starter introduces itself when it attaches. */
|
|
49
|
+
readonly client: ClientInfo;
|
|
50
|
+
/** How long to wait for a locked home's owner. Default 20 s. */
|
|
51
|
+
readonly waitMs?: number;
|
|
52
|
+
/** Where warnings and errors are mirrored besides the log file, such as stderr. */
|
|
53
|
+
readonly mirror?: (line: string) => void;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** A home this process owns. Holding it holds the home's ledger lock. */
|
|
57
|
+
export interface OwnedHome {
|
|
58
|
+
/** The home's real path. */
|
|
59
|
+
readonly path: string;
|
|
60
|
+
readonly socketPath: string;
|
|
61
|
+
readonly runtimeDir: RuntimeDirChoice;
|
|
62
|
+
readonly ledger: Ledger;
|
|
63
|
+
readonly log: Log;
|
|
64
|
+
/** Removes secrets and capability material from everything the instance logs or reports. */
|
|
65
|
+
readonly redactor: Redactor;
|
|
66
|
+
/** This process's identity, as recorded in `ledger_lock` and `instance.json`. */
|
|
67
|
+
readonly self: { readonly pid: number; readonly startTime: string };
|
|
68
|
+
/** When this process took the home (RFC 3339). */
|
|
69
|
+
readonly startedAt: string;
|
|
70
|
+
/** Writes `instance.json`; call it once the socket listens. */
|
|
71
|
+
publish(mode: "host" | "daemon"): void;
|
|
72
|
+
/**
|
|
73
|
+
* Calls `onGone` once with `MOSTRA_HOME_GONE` if the home or its ledger disappears or is
|
|
74
|
+
* replaced. Checks every `intervalMs`, at most 10 s.
|
|
75
|
+
*/
|
|
76
|
+
watch(onGone: (diagnostic: Diagnostic) => void, intervalMs?: number): void;
|
|
77
|
+
/** Removes `instance.json` if it is still this process's, and releases the lock. Idempotent. */
|
|
78
|
+
release(): void;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The outcome of {@link acquireHome}. */
|
|
82
|
+
export type HomeAcquisition =
|
|
83
|
+
| { readonly kind: "owner"; readonly home: OwnedHome }
|
|
84
|
+
| {
|
|
85
|
+
readonly kind: "attached";
|
|
86
|
+
/** The owner, as `instance.json` names it. */
|
|
87
|
+
readonly record: InstanceRecord;
|
|
88
|
+
/** An initialized session with the owner; the caller closes it. */
|
|
89
|
+
readonly connection: SocketClient;
|
|
90
|
+
readonly result: MostraInitializeResult;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const delay = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
|
|
94
|
+
|
|
95
|
+
function locked(message: string): RpcError {
|
|
96
|
+
return new RpcError(createDiagnostic("MOSTRA_HOME_LOCKED", { message }));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Takes the home, or finds its owner. Throws an `RpcError` with `MOSTRA_HOME_NOT_OWNED`,
|
|
101
|
+
* `MOSTRA_HOME_SOCKET_TOO_LONG`, `MOSTRA_HOME_LOCKED`, `MOSTRA_HOME_TOO_NEW`,
|
|
102
|
+
* `MOSTRA_HOME_LEDGER_UNREADABLE` or `MOSTRA_HOST_REVISION_UNSUPPORTED` when it can do neither.
|
|
103
|
+
* Call it only after the platform gate.
|
|
104
|
+
*/
|
|
105
|
+
export async function acquireHome(options: AcquireHomeOptions): Promise<HomeAcquisition> {
|
|
106
|
+
const prepared = prepareOwnedDirectory(options.home);
|
|
107
|
+
const home = prepared.realPath;
|
|
108
|
+
const runtimeDir = resolveRuntimeDir({ env: options.env });
|
|
109
|
+
// Check the length before creating anything in the runtime directory, then again with its real
|
|
110
|
+
// path, which is the one bound (on macOS, /tmp is /private/tmp).
|
|
111
|
+
socketPathFor(runtimeDir.dir, home);
|
|
112
|
+
const socketPath = socketPathFor(prepareOwnedDirectory(runtimeDir.dir).realPath, home);
|
|
113
|
+
const redactor = new Redactor();
|
|
114
|
+
redactor.protectEnvironment(options.env);
|
|
115
|
+
const log = openFileLog({
|
|
116
|
+
dir: join(home, "logs"),
|
|
117
|
+
redactor,
|
|
118
|
+
...(options.mirror ? { mirror: options.mirror } : {}),
|
|
119
|
+
});
|
|
120
|
+
if (prepared.tightenedFrom !== undefined) {
|
|
121
|
+
log.warn("home.tightened", { home, from: prepared.tightenedFrom.toString(8), to: "700" });
|
|
122
|
+
}
|
|
123
|
+
if (runtimeDir.rejected !== undefined) {
|
|
124
|
+
log.warn("home.xdg_runtime_dir_rejected", {
|
|
125
|
+
reason: runtimeDir.rejected,
|
|
126
|
+
using: runtimeDir.dir,
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const me = await readProcess(process.pid);
|
|
131
|
+
if (!me) throw new Error("Couldn't read this process's own start time.");
|
|
132
|
+
const self = { pid: me.pid, startTime: me.startTime };
|
|
133
|
+
const deadline = Date.now() + (options.waitMs ?? DEFAULT_WAIT_MS);
|
|
134
|
+
let seen: InstanceRecord | undefined;
|
|
135
|
+
|
|
136
|
+
for (;;) {
|
|
137
|
+
const opening = openLedger({
|
|
138
|
+
storeDir: join(home, "store"),
|
|
139
|
+
runtimeVersion: options.runtimeVersion,
|
|
140
|
+
owner: self,
|
|
141
|
+
log,
|
|
142
|
+
});
|
|
143
|
+
if (opening.ok) {
|
|
144
|
+
log.info("home.acquired", { home, socket: socketPath, pid: self.pid });
|
|
145
|
+
return {
|
|
146
|
+
kind: "owner",
|
|
147
|
+
home: own({
|
|
148
|
+
home,
|
|
149
|
+
socketPath,
|
|
150
|
+
runtimeDir,
|
|
151
|
+
ledger: opening.ledger,
|
|
152
|
+
log,
|
|
153
|
+
redactor,
|
|
154
|
+
self,
|
|
155
|
+
options,
|
|
156
|
+
}),
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const record = await readLiveInstanceRecord(home);
|
|
161
|
+
if (record) {
|
|
162
|
+
seen = record;
|
|
163
|
+
if (options.mode === "host") {
|
|
164
|
+
throw locked(
|
|
165
|
+
`The home ${home} is already owned by a Mostra ${record.mode} (PID ${record.pid}); \`mostra host\` needs a home no other instance owns.`,
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
try {
|
|
169
|
+
const { client, result } = await attach(record.socket, options.client, 2000);
|
|
170
|
+
log.info("home.attached", { home, owner: record.pid, socket: record.socket });
|
|
171
|
+
return { kind: "attached", record, connection: client, result };
|
|
172
|
+
} catch (error) {
|
|
173
|
+
// Only an unreachable socket is worth waiting for; a refusal is final.
|
|
174
|
+
if (
|
|
175
|
+
!(error instanceof RpcError) ||
|
|
176
|
+
error.diagnostic.code !== "MOSTRA_HOST_CONNECTION_CLOSED"
|
|
177
|
+
) {
|
|
178
|
+
throw error;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
if (Date.now() >= deadline) {
|
|
184
|
+
const owner = seen ?? readInstanceRecord(home);
|
|
185
|
+
throw locked(
|
|
186
|
+
owner
|
|
187
|
+
? `The home ${home} is owned by PID ${owner.pid}, but its socket ${owner.socket} can't be reached.`
|
|
188
|
+
: `Another process holds the ledger lock of the home ${home} and published no instance record.`,
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
await delay(100);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
interface OwnInputs {
|
|
196
|
+
readonly home: string;
|
|
197
|
+
readonly socketPath: string;
|
|
198
|
+
readonly runtimeDir: RuntimeDirChoice;
|
|
199
|
+
readonly ledger: Ledger;
|
|
200
|
+
readonly log: Log;
|
|
201
|
+
readonly redactor: Redactor;
|
|
202
|
+
readonly self: { readonly pid: number; readonly startTime: string };
|
|
203
|
+
readonly options: AcquireHomeOptions;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function identity(path: string): string | undefined {
|
|
207
|
+
try {
|
|
208
|
+
const stats = statSync(path);
|
|
209
|
+
return `${stats.dev}:${stats.ino}`;
|
|
210
|
+
} catch {
|
|
211
|
+
return undefined;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function own(inputs: OwnInputs): OwnedHome {
|
|
216
|
+
const { home, socketPath, runtimeDir, ledger, log, redactor, self } = inputs;
|
|
217
|
+
const startedAt = new Date().toISOString();
|
|
218
|
+
const homeId = identity(home);
|
|
219
|
+
const ledgerId = identity(join(home, "store", LEDGER_FILE));
|
|
220
|
+
let timer: ReturnType<typeof setInterval> | undefined;
|
|
221
|
+
let released = false;
|
|
222
|
+
return {
|
|
223
|
+
path: home,
|
|
224
|
+
socketPath,
|
|
225
|
+
runtimeDir,
|
|
226
|
+
ledger,
|
|
227
|
+
log,
|
|
228
|
+
redactor,
|
|
229
|
+
self,
|
|
230
|
+
startedAt,
|
|
231
|
+
publish(mode) {
|
|
232
|
+
writeInstanceRecord(home, {
|
|
233
|
+
pid: self.pid,
|
|
234
|
+
startTime: self.startTime,
|
|
235
|
+
socket: socketPath,
|
|
236
|
+
runtimeVersion: inputs.options.runtimeVersion,
|
|
237
|
+
revisions: [...HOST_PROTOCOL_REVISIONS],
|
|
238
|
+
mode,
|
|
239
|
+
startedAt,
|
|
240
|
+
});
|
|
241
|
+
},
|
|
242
|
+
watch(onGone, intervalMs = DEFAULT_WATCH_MS) {
|
|
243
|
+
if (timer) clearInterval(timer);
|
|
244
|
+
timer = setInterval(
|
|
245
|
+
() => {
|
|
246
|
+
const homeNow = identity(home);
|
|
247
|
+
const ledgerNow = identity(join(home, "store", LEDGER_FILE));
|
|
248
|
+
if (homeNow === homeId && ledgerNow === ledgerId) return;
|
|
249
|
+
if (timer) clearInterval(timer);
|
|
250
|
+
onGone(
|
|
251
|
+
createDiagnostic("MOSTRA_HOME_GONE", {
|
|
252
|
+
message:
|
|
253
|
+
homeNow === homeId
|
|
254
|
+
? `The ledger of the home ${home} was removed or replaced while the instance was running.`
|
|
255
|
+
: `The home ${home} was removed or replaced while the instance was running.`,
|
|
256
|
+
}),
|
|
257
|
+
);
|
|
258
|
+
},
|
|
259
|
+
Math.min(intervalMs, 10_000),
|
|
260
|
+
);
|
|
261
|
+
timer.unref();
|
|
262
|
+
},
|
|
263
|
+
release() {
|
|
264
|
+
if (released) return;
|
|
265
|
+
released = true;
|
|
266
|
+
if (timer) clearInterval(timer);
|
|
267
|
+
try {
|
|
268
|
+
removeInstanceRecord(home, self.pid, self.startTime);
|
|
269
|
+
} catch (error) {
|
|
270
|
+
log.warn("home.record_remove_failed", { error });
|
|
271
|
+
}
|
|
272
|
+
ledger.close();
|
|
273
|
+
log.info("home.released", { home });
|
|
274
|
+
},
|
|
275
|
+
};
|
|
276
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The home (DATA_MODEL §1; D81, D82, D84, D85; RT-06, RT-07): the platform gate, where a home and
|
|
3
|
+
* its socket live, and taking ownership of a home or finding its owner.
|
|
4
|
+
*/
|
|
5
|
+
export { acquireHome, type OwnedHome } from "./acquire.ts";
|
|
6
|
+
export {
|
|
7
|
+
homeHash,
|
|
8
|
+
prepareOwnedDirectory,
|
|
9
|
+
resolveHomePath,
|
|
10
|
+
resolveRuntimeDir,
|
|
11
|
+
socketPathFor,
|
|
12
|
+
socketPathLimit,
|
|
13
|
+
} from "./paths.ts";
|
|
14
|
+
export { checkPlatform, platformName } from "./platform.ts";
|
|
15
|
+
export type { InstanceRecord } from "./record.ts";
|
|
16
|
+
export { markHostConfigured, readHomeSettings, writeHomeSettings } from "./settings.ts";
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where a home and its control socket live (DATA_MODEL §1, D82, D84, D85). Resolving a path never
|
|
3
|
+
* touches the file system; preparing a directory creates it with mode 0700, tightens one the user
|
|
4
|
+
* owns, and refuses one owned by someone else.
|
|
5
|
+
*/
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
import { chmodSync, mkdirSync, realpathSync, statSync } from "node:fs";
|
|
8
|
+
import { homedir } from "node:os";
|
|
9
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
10
|
+
import { createDiagnostic, RpcError, VersionId } from "@mostra/protocol";
|
|
11
|
+
import type { Environment } from "../log.ts";
|
|
12
|
+
|
|
13
|
+
/** What path resolution reads: the flag, the environment and the platform. */
|
|
14
|
+
export interface PathInputs {
|
|
15
|
+
/** `--home`, when given. */
|
|
16
|
+
readonly home?: string | undefined;
|
|
17
|
+
readonly env: Environment;
|
|
18
|
+
readonly platform?: string;
|
|
19
|
+
/** The user's home directory. Default `os.homedir()`. */
|
|
20
|
+
readonly userHome?: string;
|
|
21
|
+
/** Resolves a relative `--home` or `MOSTRA_HOME`. Default `process.cwd()`. */
|
|
22
|
+
readonly cwd?: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const nonEmpty = (value: string | undefined): string | undefined =>
|
|
26
|
+
value === undefined || value === "" ? undefined : value;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The home path, resolved in D84's order: `--home`, then `MOSTRA_HOME`, then the platform default
|
|
30
|
+
* (`~/.mostra` on macOS, `${XDG_DATA_HOME:-~/.local/share}/mostra` on Linux). An SDK passes its
|
|
31
|
+
* `home` option as `--home`.
|
|
32
|
+
*/
|
|
33
|
+
export function resolveHomePath(inputs: PathInputs): string {
|
|
34
|
+
const cwd = inputs.cwd ?? process.cwd();
|
|
35
|
+
const chosen = nonEmpty(inputs.home) ?? nonEmpty(inputs.env["MOSTRA_HOME"]);
|
|
36
|
+
if (chosen !== undefined) return resolve(cwd, chosen);
|
|
37
|
+
const user = inputs.userHome ?? homedir();
|
|
38
|
+
if ((inputs.platform ?? process.platform) === "darwin") return join(user, ".mostra");
|
|
39
|
+
const data = nonEmpty(inputs.env["XDG_DATA_HOME"]);
|
|
40
|
+
return join(
|
|
41
|
+
data !== undefined && isAbsolute(data) ? data : join(user, ".local", "share"),
|
|
42
|
+
"mostra",
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** What the runtime directory resolution decided, and why. */
|
|
47
|
+
export interface RuntimeDirChoice {
|
|
48
|
+
readonly dir: string;
|
|
49
|
+
/** `override` (MOSTRA_RUNTIME_DIR), `xdg` (the safe XDG runtime directory) or `fallback`. */
|
|
50
|
+
readonly source: "override" | "xdg" | "fallback";
|
|
51
|
+
/** Why `$XDG_RUNTIME_DIR` wasn't used, when it was set. */
|
|
52
|
+
readonly rejected?: string;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The current user's ID. */
|
|
56
|
+
function uid(): number {
|
|
57
|
+
return process.getuid?.() ?? -1;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The runtime directory for control sockets (D82): `MOSTRA_RUNTIME_DIR`; else `~/.mostra/run` on
|
|
62
|
+
* macOS; on Linux `$XDG_RUNTIME_DIR/mostra` when `$XDG_RUNTIME_DIR` is a directory the user owns
|
|
63
|
+
* that nobody else can read or write, else `${XDG_STATE_HOME:-~/.local/state}/mostra/run`.
|
|
64
|
+
*/
|
|
65
|
+
export function resolveRuntimeDir(inputs: Omit<PathInputs, "home">): RuntimeDirChoice {
|
|
66
|
+
const override = nonEmpty(inputs.env["MOSTRA_RUNTIME_DIR"]);
|
|
67
|
+
if (override !== undefined) {
|
|
68
|
+
return { dir: resolve(inputs.cwd ?? process.cwd(), override), source: "override" };
|
|
69
|
+
}
|
|
70
|
+
const user = inputs.userHome ?? homedir();
|
|
71
|
+
if ((inputs.platform ?? process.platform) === "darwin") {
|
|
72
|
+
return { dir: join(user, ".mostra", "run"), source: "fallback" };
|
|
73
|
+
}
|
|
74
|
+
const xdg = nonEmpty(inputs.env["XDG_RUNTIME_DIR"]);
|
|
75
|
+
let rejected: string | undefined;
|
|
76
|
+
if (xdg !== undefined) {
|
|
77
|
+
rejected = unsafeXdgRuntimeDir(xdg);
|
|
78
|
+
if (rejected === undefined) return { dir: join(xdg, "mostra"), source: "xdg" };
|
|
79
|
+
}
|
|
80
|
+
const state = nonEmpty(inputs.env["XDG_STATE_HOME"]);
|
|
81
|
+
const base = state !== undefined && isAbsolute(state) ? state : join(user, ".local", "state");
|
|
82
|
+
const dir = join(base, "mostra", "run");
|
|
83
|
+
return rejected === undefined
|
|
84
|
+
? { dir, source: "fallback" }
|
|
85
|
+
: { dir, source: "fallback", rejected };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Why `$XDG_RUNTIME_DIR` can't be used, or `undefined` when it can (XDG Base Directory spec). */
|
|
89
|
+
function unsafeXdgRuntimeDir(dir: string): string | undefined {
|
|
90
|
+
if (!isAbsolute(dir)) return "it isn't an absolute path";
|
|
91
|
+
let stats: ReturnType<typeof statSync>;
|
|
92
|
+
try {
|
|
93
|
+
stats = statSync(dir);
|
|
94
|
+
} catch {
|
|
95
|
+
return "it doesn't exist";
|
|
96
|
+
}
|
|
97
|
+
if (!stats.isDirectory()) return "it isn't a directory";
|
|
98
|
+
if (stats.uid !== uid()) return "another user owns it";
|
|
99
|
+
if ((stats.mode & 0o077) !== 0) return "other users can access it";
|
|
100
|
+
return undefined;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The longest control socket path the operating system accepts, in bytes (VERIFIED_FACTS). */
|
|
104
|
+
export function socketPathLimit(platform: string = process.platform): number {
|
|
105
|
+
return platform === "darwin" ? 103 : 107;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* A home's hash (D82): 16 Crockford base32 characters of the SHA-256 of its real path, which
|
|
110
|
+
* names its socket and its login service.
|
|
111
|
+
*/
|
|
112
|
+
export function homeHash(realHome: string): string {
|
|
113
|
+
const digest = createHash("sha256").update(realHome, "utf8").digest();
|
|
114
|
+
// VersionId.fromSha256 is the one Crockford encoder (D77); its body starts with the same 16
|
|
115
|
+
// characters any encoding of this digest would.
|
|
116
|
+
return VersionId.fromSha256(new Uint8Array(digest)).slice("ver_".length, "ver_".length + 16);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* The control socket for a home (D82), named by its {@link homeHash}. Throws
|
|
121
|
+
* `MOSTRA_HOME_SOCKET_TOO_LONG` when the path exceeds the limit.
|
|
122
|
+
*/
|
|
123
|
+
export function socketPathFor(runtimeDir: string, realHome: string, platform?: string): string {
|
|
124
|
+
const hash = homeHash(realHome);
|
|
125
|
+
const path = join(runtimeDir, `${hash}.sock`);
|
|
126
|
+
const limit = socketPathLimit(platform);
|
|
127
|
+
const length = Buffer.byteLength(path);
|
|
128
|
+
if (length > limit) {
|
|
129
|
+
throw new RpcError(
|
|
130
|
+
createDiagnostic("MOSTRA_HOME_SOCKET_TOO_LONG", {
|
|
131
|
+
message: `The control socket path ${path} is ${length} bytes; this system allows ${limit}.`,
|
|
132
|
+
fix: { kind: "command", command: "export MOSTRA_RUNTIME_DIR=/tmp/mostra-$USER" },
|
|
133
|
+
}),
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
return path;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** The outcome of {@link prepareOwnedDirectory}. */
|
|
140
|
+
export interface PreparedDirectory {
|
|
141
|
+
/** The directory's real path. */
|
|
142
|
+
readonly realPath: string;
|
|
143
|
+
/** Whether Mostra created it. */
|
|
144
|
+
readonly created: boolean;
|
|
145
|
+
/** The mode it had when Mostra tightened it to 0700, when it did. */
|
|
146
|
+
readonly tightenedFrom?: number;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function notOwned(path: string, why: string): RpcError {
|
|
150
|
+
return new RpcError(
|
|
151
|
+
createDiagnostic("MOSTRA_HOME_NOT_OWNED", { message: `Mostra can't use ${path}: ${why}.` }),
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Makes `path` a directory only its owner can use (D85): creates it with mode 0700 when missing,
|
|
157
|
+
* tightens one the user owns to 0700, and throws `MOSTRA_HOME_NOT_OWNED` for one owned by
|
|
158
|
+
* another user or a path that isn't a directory. Symlinks are followed.
|
|
159
|
+
*/
|
|
160
|
+
export function prepareOwnedDirectory(path: string): PreparedDirectory {
|
|
161
|
+
try {
|
|
162
|
+
return prepare(path);
|
|
163
|
+
} catch (error) {
|
|
164
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
165
|
+
if (code === "ENOTDIR" || code === "EEXIST")
|
|
166
|
+
throw notOwned(path, "a part of the path isn't a directory");
|
|
167
|
+
if (code === "EACCES" || code === "EPERM")
|
|
168
|
+
throw notOwned(path, "you have no permission to use it");
|
|
169
|
+
throw error;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function prepare(path: string): PreparedDirectory {
|
|
174
|
+
let created = false;
|
|
175
|
+
try {
|
|
176
|
+
statSync(path);
|
|
177
|
+
} catch (error) {
|
|
178
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
179
|
+
mkdirSync(path, { recursive: true, mode: 0o700 });
|
|
180
|
+
created = true;
|
|
181
|
+
}
|
|
182
|
+
const realPath = realpathSync(path);
|
|
183
|
+
const stats = statSync(realPath);
|
|
184
|
+
if (!stats.isDirectory()) throw notOwned(path, "it isn't a directory");
|
|
185
|
+
if (stats.uid !== uid()) throw notOwned(path, `it belongs to user ${stats.uid}, not to you`);
|
|
186
|
+
const mode = stats.mode & 0o777;
|
|
187
|
+
if (mode !== 0o700) {
|
|
188
|
+
chmodSync(realPath, 0o700);
|
|
189
|
+
return created ? { realPath, created } : { realPath, created, tightenedFrom: mode };
|
|
190
|
+
}
|
|
191
|
+
return { realPath, created };
|
|
192
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The unsupported-platform gate (D35, RT-07). Every entry point calls it before it touches the
|
|
3
|
+
* home: Mostra 1.0 runs on macOS and Linux, on x64 and arm64, and fails closed elsewhere.
|
|
4
|
+
*/
|
|
5
|
+
import { createDiagnostic, type Diagnostic } from "@mostra/protocol";
|
|
6
|
+
|
|
7
|
+
const OPERATING_SYSTEMS: readonly string[] = ["darwin", "linux"];
|
|
8
|
+
const ARCHITECTURES: readonly string[] = ["x64", "arm64"];
|
|
9
|
+
|
|
10
|
+
/** The platform as `<os>-<arch>`, as `InstanceInfo.platform` reports it. */
|
|
11
|
+
export function platformName(
|
|
12
|
+
platform: string = process.platform,
|
|
13
|
+
arch: string = process.arch,
|
|
14
|
+
): string {
|
|
15
|
+
return `${platform}-${arch}`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Returns `MOSTRA_PLATFORM_UNSUPPORTED` for a platform Mostra doesn't run on, or `undefined` for
|
|
20
|
+
* a supported one.
|
|
21
|
+
*/
|
|
22
|
+
export function checkPlatform(
|
|
23
|
+
platform: string = process.platform,
|
|
24
|
+
arch: string = process.arch,
|
|
25
|
+
): Diagnostic | undefined {
|
|
26
|
+
if (OPERATING_SYSTEMS.includes(platform) && ARCHITECTURES.includes(arch)) return undefined;
|
|
27
|
+
const name =
|
|
28
|
+
platform === "win32"
|
|
29
|
+
? `Windows (${platformName(platform, arch)})`
|
|
30
|
+
: platformName(platform, arch);
|
|
31
|
+
return createDiagnostic("MOSTRA_PLATFORM_UNSUPPORTED", {
|
|
32
|
+
message: `Mostra doesn't run on ${name}; it supports macOS and Linux on x64 and arm64.`,
|
|
33
|
+
});
|
|
34
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `instance.json` (D81): how starters and clients find the supervisor that owns a home. It is a
|
|
3
|
+
* discovery record, never a lock: the ledger lock decides ownership. The owner writes it
|
|
4
|
+
* atomically after binding its socket and removes it on a clean exit; a record whose PID and
|
|
5
|
+
* start time match no live process is stale.
|
|
6
|
+
*/
|
|
7
|
+
import { readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import * as z from "zod";
|
|
10
|
+
import { isSameProcess } from "../processes/index.ts";
|
|
11
|
+
|
|
12
|
+
/** The record's file name in the home. */
|
|
13
|
+
export const INSTANCE_FILE = "instance.json";
|
|
14
|
+
|
|
15
|
+
/** What `instance.json` holds. */
|
|
16
|
+
export interface InstanceRecord {
|
|
17
|
+
/** The owner's process ID. */
|
|
18
|
+
readonly pid: number;
|
|
19
|
+
/** The owner's process start time (processes/identity.ts). */
|
|
20
|
+
readonly startTime: string;
|
|
21
|
+
/** The control socket clients attach to. */
|
|
22
|
+
readonly socket: string;
|
|
23
|
+
/** The owner's runtime release. */
|
|
24
|
+
readonly runtimeVersion: string;
|
|
25
|
+
/** The host protocol revisions the owner speaks. */
|
|
26
|
+
readonly revisions: readonly string[];
|
|
27
|
+
/** `host` or `daemon` (`InstanceInfo.mode`). */
|
|
28
|
+
readonly mode: "host" | "daemon";
|
|
29
|
+
/** When the owner took the home (RFC 3339). */
|
|
30
|
+
readonly startedAt: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const InstanceRecordSchema = z.object({
|
|
34
|
+
pid: z.int().min(1),
|
|
35
|
+
startTime: z.string(),
|
|
36
|
+
socket: z.string(),
|
|
37
|
+
runtimeVersion: z.string(),
|
|
38
|
+
revisions: z.array(z.string()),
|
|
39
|
+
mode: z.enum(["host", "daemon"]),
|
|
40
|
+
startedAt: z.string(),
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
/** Reads the record, or `undefined` when it is missing or unreadable. */
|
|
44
|
+
export function readInstanceRecord(home: string): InstanceRecord | undefined {
|
|
45
|
+
try {
|
|
46
|
+
const parsed = InstanceRecordSchema.safeParse(
|
|
47
|
+
JSON.parse(readFileSync(join(home, INSTANCE_FILE), "utf8")),
|
|
48
|
+
);
|
|
49
|
+
return parsed.success ? parsed.data : undefined;
|
|
50
|
+
} catch {
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Reads the record when it names a live process: the owner, or a starter's view of it. */
|
|
56
|
+
export async function readLiveInstanceRecord(home: string): Promise<InstanceRecord | undefined> {
|
|
57
|
+
const record = readInstanceRecord(home);
|
|
58
|
+
if (!record) return undefined;
|
|
59
|
+
return (await isSameProcess(record.pid, record.startTime)) ? record : undefined;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Writes the record atomically (a temporary file, then a rename), mode 0600. */
|
|
63
|
+
export function writeInstanceRecord(home: string, record: InstanceRecord): void {
|
|
64
|
+
const file = join(home, INSTANCE_FILE);
|
|
65
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
66
|
+
writeFileSync(temp, `${JSON.stringify(record, null, 2)}\n`, { mode: 0o600 });
|
|
67
|
+
renameSync(temp, file);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Removes the record when it is still this process's (a clean exit). */
|
|
71
|
+
export function removeInstanceRecord(home: string, pid: number, startTime: string): void {
|
|
72
|
+
const record = readInstanceRecord(home);
|
|
73
|
+
if (record && record.pid === pid && record.startTime === startTime) {
|
|
74
|
+
rmSync(join(home, INSTANCE_FILE), { force: true });
|
|
75
|
+
}
|
|
76
|
+
}
|