@mostra/sdk 0.6.2 → 0.7.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/dist/bundles.json CHANGED
@@ -1,43 +1,43 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "version": "0.6.2",
4
- "release": "https://github.com/mostra-dev/mostra/releases/download/v0.6.2",
3
+ "version": "0.7.0",
4
+ "release": "https://github.com/mostra-dev/mostra/releases/download/v0.7.0",
5
5
  "assets": {
6
6
  "darwin-arm64": {
7
- "file": "mostra-0.6.2-darwin-arm64.tar.gz",
8
- "sha256": "97d35bd3f8dccc00d093db061ab6e029af2086f74ea87a5ea96fd76949c06e00",
9
- "size": 199800553,
10
- "unpackedSize": 786444001
7
+ "file": "mostra-0.7.0-darwin-arm64.tar.gz",
8
+ "sha256": "4a6d34db7497333403c2e2ccde1b1520f3ebb6fc6c2b3b1416052bc1abb56100",
9
+ "size": 199967965,
10
+ "unpackedSize": 787181663
11
11
  },
12
12
  "darwin-x64": {
13
- "file": "mostra-0.6.2-darwin-x64.tar.gz",
14
- "sha256": "772fc9ec246fe9322d159676b1b528e35a5d24ea8cb6c335c0f094f3bcd234cf",
15
- "size": 202876656,
16
- "unpackedSize": 794565665
13
+ "file": "mostra-0.7.0-darwin-x64.tar.gz",
14
+ "sha256": "ee2a393760b876f7bb7370364d9e1955303fe6d4503dc5cbc77bb1235debe223",
15
+ "size": 203052747,
16
+ "unpackedSize": 795303327
17
17
  },
18
18
  "linux-x64": {
19
- "file": "mostra-0.6.2-linux-x64.tar.gz",
20
- "sha256": "bcee47d7f85cb5b4472d90d9866e3d998aa9e8980f23f7a853f4083a080ff9a2",
21
- "size": 207122495,
22
- "unpackedSize": 797259557
19
+ "file": "mostra-0.7.0-linux-x64.tar.gz",
20
+ "sha256": "9e95f76074624168aad3fc94d7a0142497afb4fb8761c22c12218d5eaaab7915",
21
+ "size": 207302075,
22
+ "unpackedSize": 797997219
23
23
  },
24
24
  "linux-arm64": {
25
- "file": "mostra-0.6.2-linux-arm64.tar.gz",
26
- "sha256": "5b85119a5bc7f7458044fd89724286208dd4d4c807e7c7fac25d2d1ba44a22d4",
27
- "size": 205212732,
28
- "unpackedSize": 787758614
25
+ "file": "mostra-0.7.0-linux-arm64.tar.gz",
26
+ "sha256": "e327d0199da2737b8da1ab0cf2d60ec1142d12a2d27c7bda2df9b2c7c6a3055b",
27
+ "size": 205405627,
28
+ "unpackedSize": 788496276
29
29
  },
30
30
  "win32-x64": {
31
- "file": "mostra-0.6.2-win32-x64.tar.gz",
32
- "sha256": "8d5d52cb406b69da9a6738ef5460ba8585cb79a4c1db89e722715aa1e6b045a5",
33
- "size": 186735181,
34
- "unpackedSize": 704881165
31
+ "file": "mostra-0.7.0-win32-x64.tar.gz",
32
+ "sha256": "3fb76936e8cfdd57a97c9df45816764567fb671ea0848c57b29670a631117860",
33
+ "size": 186922293,
34
+ "unpackedSize": 705618827
35
35
  },
36
36
  "win32-arm64": {
37
- "file": "mostra-0.6.2-win32-arm64.tar.gz",
38
- "sha256": "278f2c8a976be60b2e696f25b6aa21c4be139427089d5c633636e4b525ca8ed3",
39
- "size": 180855490,
40
- "unpackedSize": 685612616
37
+ "file": "mostra-0.7.0-win32-arm64.tar.gz",
38
+ "sha256": "ded12be0fb87f46f86b1d115782bb3ee15e3ac13f1297d28f08f41f3475e3254",
39
+ "size": 181030785,
40
+ "unpackedSize": 686350278
41
41
  }
42
42
  }
43
43
  }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ArtifactRef, ArtifactSummary, BundleFiles, BundleInfo, BundlePins, BundlePlatform, BundleSetup, CapabilityLink, ControlsPolicy, DependencyPolicy, Diagnostic, DraftMirror, EventFilter, EventRecord, InstanceCapabilities, InstanceInfo, LivePushParams, LivePushResult, MethodDefinition, PortIdentityResolveParams, PortSecretsGetParams, PortTrustedControlsActivatedParams, PublishReceipt, Results, ResultsMarkdown, SourceRef, StateGetResult, StatePatchParams, StatePatchResult, SubmissionEnvelope, SubmissionPolicy, SubmissionsDeliverResult, SubmitChannel, VerifyVerdict, ViewUrlParams, ViewerSpec, WaitCondition, WaitResult } from "@mostra/protocol";
1
+ import { ArtifactRef, ArtifactSummary, BundleFiles, BundleInfo, BundlePins, BundlePlatform, BundleSetup, CapabilityLink, ControlsPolicy, DependencyPolicy, Diagnostic, DraftMirror, EventFilter, EventRecord, InstanceCapabilities, InstanceInfo, LivePushParams, LivePushResult, MethodDefinition, PortAddressingExternalBaseParams, PortAddressingExternalBaseResult, PortIdentityResolveParams, PortSecretsGetParams, PortTrustedControlsActivatedParams, PublishReceipt, Results, ResultsMarkdown, ShareStartParams, ShareStartResult, ShareStopResult, SourceRef, StateGetResult, StatePatchParams, StatePatchResult, SubmissionEnvelope, SubmissionPolicy, SubmissionsDeliverResult, SubmitChannel, VerifyVerdict, ViewUrlParams, ViewerSpec, WaitCondition, WaitResult } from "@mostra/protocol";
2
2
  import { Duplex } from "node:stream";
3
3
  //#region src/bundle/download.d.ts
4
4
  /** Progress of one download, in bytes. */
@@ -245,6 +245,15 @@ interface Ports {
245
245
  readonly drafts?: {
246
246
  mirror(draft: DraftMirror): void | Promise<void>;
247
247
  };
248
+ /**
249
+ * Gives one of an artifact's listeners an external address (HO-10, D158 item 6): the origin of
250
+ * the host's own tunnel that forwards to `request.local`, which joins the links Mostra mints
251
+ * and its Host allowlist; `null` keeps the loopback address, and withdraws one given before.
252
+ * Answer within 5 s.
253
+ */
254
+ readonly addressing?: {
255
+ externalBase(request: PortAddressingExternalBaseParams): PortAddressingExternalBaseResult | Promise<PortAddressingExternalBaseResult>;
256
+ };
248
257
  /** Answers `secret()` first, before the home's store (D131); `null` falls back. */
249
258
  readonly secrets?: {
250
259
  get(request: PortSecretsGetParams): string | null | Promise<string | null>;
@@ -369,6 +378,13 @@ interface Mostra {
369
378
  pushLive(artifact: ArtifactInput, push: Omit<LivePushParams, "artifact">): Promise<LivePushResult>;
370
379
  /** `view/url`: a new capability link (D97). */
371
380
  viewUrl(artifact: ArtifactInput, options?: Omit<ViewUrlParams, "artifact">): Promise<CapabilityLink>;
381
+ /**
382
+ * `share/start`: opens the artifact through a tunnel this machine runs (D158): `tailnet`
383
+ * (Tailscale Serve), or a public `funnel` or `cloudflare` share with a link that expires.
384
+ */
385
+ share(artifact: ArtifactInput, options: Omit<ShareStartParams, "artifact">): Promise<ShareStartResult>;
386
+ /** `share/stop`: ends a share by its ID, and revokes its link. */
387
+ stopShare(shareId: string): Promise<ShareStopResult>;
372
388
  /**
373
389
  * The events matching `options.filter`, page by page, in cursor order, with no gap across a
374
390
  * pause (`events/subscribe`). With a `name`, each page is acknowledged when the next one is
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/bundle/download.ts","../src/bundle/setup.ts","../src/bundle/cache.ts","../src/bundle/tree.ts","../src/runtime.ts","../src/control.ts","../src/events.ts","../src/mostra.ts","../src/platform.ts","../src/version.ts"],"mappings":";;;;UAqBiB;;WAEN;;WAEA;;;wBAmMK,UAAU;;;;KClMd,cAAc,SAAS;;UAGlB;;WAEN;;WAEA,MAAM;;;KAIL;;UAGK;;WAEN,MAAM;;WAEN,SAAS;;WAET,WAAW,MAAM;;WAEjB;;;wBAIK,YAAY;;wBAKZ,QAAQ,KAAK;;wBAYP,WAAW,eAAe,QAAQ;;;;;;wBAwClC,UAAU,QAAQ,SAAS,QAAQ;;wBAoBzC,YAAY;;;;;wBA4CN,WACpB,QAAQ,QACR;WAAoB;WAA0B,WAAW;IACxD;;wBAemB,aAAa,QAAQ,SAAS;;;;;;;wBAkG9B,YAAY,cAAc,UAAS,eAAoB,QAAQ;;;;;;;;;wBC7OrE,UAAU,KAAK,aAAa;;wBAgB5B,UAAU,KAAK,aAAa;;KAKhC;WACI;IAAqB;WACtB;;WACA,MAAM;;;UAGJ;;WAEN,KAAK;;WAEL,UAAU;;WAEV,SAAS;;WAET,eAAe,UAAU;;;;;;wBAUd,cAAc,MAAM,YAAY,SAAS,i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;;WAEA,QAAQ,OAAO;;;KAId,yBAAyB;;UAGpB;;WAEN,UAAU;;WAEV,cAAc;;WAEd;;WAEA,mBAAmB;;WAEnB,SAAS;;WAET,QAAQ,QAAQ;;EAEzB,KAAK,GAAG,GAAG,QAAQ,iBAAiB,GAAG,IAAI,QAAQ,GAAG,UAAU,cAAc,QAAQ;;EAEtF,QACE,QAAQ,eACR;aACW;aACA,SAAS;aACT;MAEV,QAAQ;;EAEX,OACE,QAAQ,eACR;aAAqB;MACpB,QAAQ;;;;;;EAMX,KACE,UAAU,eACV,OAAO,eACP;aACW;aACA;aACA,SAAS;MAEnB,QAAQ;;EAEX,QACE,UAAU,eACV;aAAqB;aAA8B;MAClD,QAAQ;;EAEX,QACE,UAAU,eACV;aAAoB;aAA8B;MACjD,QAAQ;;EAEX,SAAS,UAAU,eAAe,0BAA0B,QAAQ;;EAEpE,WACE,UAAU,eACV,OAAO,KAAK,gCACX,QAAQ;;EAEX,SACE,UAAU,eACV,MAAM,KAAK,8BACV,QAAQ;;EAEX,QACE,UAAU,eACV,UAAU,KAAK,6BACd,QAAQ;;;;;;EAMX,OAAO,UAAU,qBAAqB,cAAc;;EAEpD,SAAS,QAAQ;;;UAIF;;WAEN;;;qBAaE;;wBAGG,YAAY,OAAO,gBAAgB,cAAc;;;;;;wBAgG3C,aAAa,SAAS,gBAAgB,QAAQ;;;;UC9WnD;;WAEN;;WAEA;;WAEA;;;wBA+BK,mBAAmB;;;;;wBAYnB,eAAe,QAAO,gBAAoC;;;;wBChC1D"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/bundle/download.ts","../src/bundle/setup.ts","../src/bundle/cache.ts","../src/bundle/tree.ts","../src/runtime.ts","../src/control.ts","../src/events.ts","../src/mostra.ts","../src/platform.ts","../src/version.ts"],"mappings":";;;;UAqBiB;;WAEN;;WAEA;;;wBAmMK,UAAU;;;;KClMd,cAAc,SAAS;;UAGlB;;WAEN;;WAEA,MAAM;;;KAIL;;UAGK;;WAEN,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AK,6BACd,QAAQ;;;;;EAKX,MACE,UAAU,eACV,SAAS,KAAK,gCACb,QAAQ;;EAEX,UAAU,kBAAkB,QAAQ;;;;;;EAMpC,OAAO,UAAU,qBAAqB,cAAc;;EAEpD,SAAS,QAAQ;;;UAIF;;WAEN;;;qBAcE;;wBAGG,YAAY,OAAO,gBAAgB,cAAc;;;;;;wBAqG3C,aAAa,SAAS,gBAAgB,QAAQ;;;;UCjZnD;;WAEN;;WAEA;;WAEA;;;wBA+BK,mBAAmB;;;;;wBAYnB,eAAe,QAAO,gBAAoC;;;;wBChC1D"}
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { C as safeRelative, S as linkStaysInside, T as redactUrl, _ as setupBundle, a as sdkVersion, b as describeTree, c as bundleDir, d as browsersDir, f as checkBrowser, g as readSetup, h as readBundle, i as runtimeOf, l as cacheRoot, m as offline, n as readPins, o as bundlePlatform, p as checkFiles, r as resolveRuntime, s as currentPlatform, t as enclosingBundle, u as installPinned, v as setupExtras, w as childEnvironment, x as hashFile, y as checkTree } from "./runtime-NiLgW1ED.js";
2
2
  import { dirname, join, resolve } from "node:path";
3
- import { ARTIFACT_PROGRESS, EVENTS_NOTIFY, EventsNotifyParams, HOST_PROTOCOL_REVISIONS, LineSplitter, RpcError, RpcPeer, WAIT_MAX_MS, artifactPublishMethod, artifactVerifyMethod, createDiagnostic, encodeLine, eventsAckMethod, eventsSubscribeMethod, eventsUnsubscribeMethod, livePushMethod, mostraInitializeMethod, portDraftsMirrorMethod, portIdentityResolveMethod, portSecretsGetMethod, portSubmissionsDeliverMethod, portTrustedControlsActivatedMethod, portTrustedControlsPolicyMethod, receivable, resultsGetMethod, stateGetMethod, statePatchMethod, viewUrlMethod, waitMethod } from "@mostra/protocol";
3
+ import { ARTIFACT_PROGRESS, EVENTS_NOTIFY, EventsNotifyParams, HOST_PROTOCOL_REVISIONS, LineSplitter, RpcError, RpcPeer, WAIT_MAX_MS, artifactPublishMethod, artifactVerifyMethod, createDiagnostic, encodeLine, eventsAckMethod, eventsSubscribeMethod, eventsUnsubscribeMethod, livePushMethod, mostraInitializeMethod, portAddressingExternalBaseMethod, portDraftsMirrorMethod, portIdentityResolveMethod, portSecretsGetMethod, portSubmissionsDeliverMethod, portTrustedControlsActivatedMethod, portTrustedControlsPolicyMethod, receivable, resultsGetMethod, shareStartMethod, shareStopMethod, stateGetMethod, statePatchMethod, viewUrlMethod, waitMethod } from "@mostra/protocol";
4
4
  import { existsSync, realpathSync } from "node:fs";
5
5
  import { Duplex } from "node:stream";
6
6
  import { spawn } from "node:child_process";
@@ -344,6 +344,7 @@ var EventStream = class {
344
344
  /** The port methods the SDK serves, by port. */
345
345
  const PORT_METHODS = {
346
346
  identity: [portIdentityResolveMethod],
347
+ addressing: [portAddressingExternalBaseMethod],
347
348
  submissions: [portSubmissionsDeliverMethod],
348
349
  drafts: [portDraftsMirrorMethod],
349
350
  secrets: [portSecretsGetMethod],
@@ -363,6 +364,7 @@ function closedError(message) {
363
364
  function portHandler(ports, method) {
364
365
  switch (method) {
365
366
  case portIdentityResolveMethod.method: return ports.identity && ((params) => ports.identity?.resolve(params));
367
+ case portAddressingExternalBaseMethod.method: return ports.addressing && ((params) => ports.addressing?.externalBase(params));
366
368
  case portSubmissionsDeliverMethod.method: return ports.submissions && ((params) => ports.submissions?.deliver(params));
367
369
  case portDraftsMirrorMethod.method: return ports.drafts && ((params) => ports.drafts?.mirror(params));
368
370
  case portSecretsGetMethod.method: return ports.secrets && ((params) => ports.secrets?.get(params));
@@ -586,6 +588,11 @@ async function createMostra(options) {
586
588
  artifact: artifactRef(artifact),
587
589
  ...urlOptions
588
590
  }),
591
+ share: (artifact, shareOptions) => call(shareStartMethod, {
592
+ artifact: artifactRef(artifact),
593
+ ...shareOptions
594
+ }),
595
+ stopShare: (shareId) => call(shareStopMethod, { shareId }),
589
596
  events: (streamOptions = {}) => openEventStream({
590
597
  call,
591
598
  onNotification: (handler) => {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/control.ts","../src/events.ts","../src/mostra.ts"],"sourcesContent":["/**\n * Opening a home's control endpoint as a client (D45, D81, D150): the socket or pipe that\n * `instance.json` names, where a home's daemon serves the host protocol.\n *\n * - **POSIX:** a Unix socket in the owner-only runtime directory, opened with `node:net`.\n * - **Windows:** an owner-only named pipe, opened through the runtime's helper, `mostra-win\n * connect`. A pipe's old name in `instance.json` may be free for another user to take, and\n * Node.js can neither check who created a pipe nor stop its server acting as the client, so the\n * helper connects without letting the server impersonate the client, refuses a pipe whose owner\n * isn't this user, and relays the bytes over its standard streams (Opus review of WP-W1).\n *\n * The helper is the one beside the runtime the caller resolved: `MOSTRA_WIN_HELPER`, else the\n * runtime bundle's `bin/mostra-win.exe`, else a development checkout's Cargo build.\n */\nimport { spawn } from \"node:child_process\";\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { createConnection, type Socket } from \"node:net\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { Duplex } from \"node:stream\";\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport type { Environment } from \"./bundle/setup.ts\";\nimport type { Runtime } from \"./runtime.ts\";\n\n/** Options of {@link connectControl}. */\nexport interface ControlOptions {\n /** The runtime whose helper opens a Windows pipe; required on Windows. */\n readonly runtime?: Runtime | undefined;\n /** The environment: `MOSTRA_WIN_HELPER`. */\n readonly env?: Environment | undefined;\n /** How long to wait for the endpoint to answer. Default 5000. */\n readonly timeoutMs?: number | undefined;\n /** The operating system, `process.platform` by default. */\n readonly platform?: string | undefined;\n}\n\nconst PIPE_PREFIX = \"\\\\\\\\.\\\\pipe\\\\\";\n\n/** The helper's exit code for a pipe another user owns (`crates/mostra-win/src/win/connect.rs`). */\nconst NOT_OWNED_EXIT = 3;\n\nfunction unreachable(endpoint: string, why: string): RpcError {\n return new RpcError(\n createDiagnostic(\"MOSTRA_HOST_CONNECTION_CLOSED\", {\n message: `Couldn't reach the instance at ${endpoint} (${why}).`,\n }),\n );\n}\n\n/**\n * The Windows helper beside `runtime`: `MOSTRA_WIN_HELPER`, else the bundle's\n * `bin/mostra-win.exe`, else, for a checkout's `packages/runtime/dist/bin.js`, Cargo's\n * `target/release` then `target/debug`. Throws `MOSTRA_ENV_HELPER_MISSING` when none exists.\n */\nexport function windowsHelper(runtime: Runtime | undefined, env: Environment): string {\n const override = env[\"MOSTRA_WIN_HELPER\"];\n if (override) {\n if (existsSync(override)) return override;\n throw missingHelper(`MOSTRA_WIN_HELPER names ${override}, which doesn't exist.`);\n }\n if (runtime === undefined) {\n throw missingHelper(\"No runtime was resolved, so Mostra's Windows helper can't be found.\");\n }\n const candidates =\n runtime.bundle !== undefined\n ? [join(runtime.bundle.root, \"bin\", \"mostra-win.exe\")]\n : [\"release\", \"debug\"].map((profile) =>\n resolve(\n // The runtime's own order (`helperPath`) starts from where its code really is, so a\n // link to its entry (a relative `MOSTRA_RUNTIME_BIN` through a junction) changes nothing.\n dirname(realEntry(runtime.runtimeEntry)),\n \"..\",\n \"..\",\n \"..\",\n \"target\",\n profile,\n \"mostra-win.exe\",\n ),\n );\n const found = candidates.find((candidate) => existsSync(candidate));\n if (found === undefined) {\n throw missingHelper(\n `Mostra's Windows helper isn't installed; looked for ${candidates.join(\", \")}.`,\n );\n }\n return found;\n}\n\nfunction realEntry(entry: string): string {\n try {\n return realpathSync.native(entry);\n } catch {\n return entry;\n }\n}\n\nfunction missingHelper(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_ENV_HELPER_MISSING\", { message }));\n}\n\n/**\n * Connects to a home's control endpoint. Rejects with `MOSTRA_HOST_CONNECTION_CLOSED` when nothing\n * serves it in time or, on Windows, when another user owns the pipe; with\n * `MOSTRA_ENV_HELPER_MISSING` when the Windows helper can't be found.\n */\nexport function connectControl(endpoint: string, options: ControlOptions = {}): Promise<Duplex> {\n const timeoutMs = options.timeoutMs ?? 5000;\n if ((options.platform ?? process.platform) === \"win32\") {\n return connectPipe(\n endpoint,\n windowsHelper(options.runtime, options.env ?? process.env),\n timeoutMs,\n );\n }\n return new Promise((resolvePromise, reject) => {\n const socket: Socket = createConnection(endpoint);\n const timer = setTimeout(() => {\n socket.destroy();\n reject(unreachable(endpoint, \"timed out\"));\n }, timeoutMs);\n socket.once(\"error\", (error: NodeJS.ErrnoException) => {\n clearTimeout(timer);\n reject(unreachable(endpoint, error.code ?? \"failed\"));\n });\n socket.once(\"connect\", () => {\n clearTimeout(timer);\n resolvePromise(socket);\n });\n });\n}\n\nfunction connectPipe(endpoint: string, helper: string, timeoutMs: number): Promise<Duplex> {\n const name = endpoint.startsWith(PIPE_PREFIX) ? endpoint.slice(PIPE_PREFIX.length) : endpoint;\n return new Promise((resolvePromise, reject) => {\n const child = spawn(helper, [\"connect\", name], {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n windowsHide: true,\n });\n let settled = false;\n const fail = (why: string): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n child.kill();\n reject(unreachable(endpoint, why));\n };\n const timer = setTimeout(() => fail(\"timed out\"), timeoutMs);\n child.once(\"error\", (error) => fail(error.message));\n child.once(\"exit\", (code) =>\n fail(code === NOT_OWNED_EXIT ? \"another user owns that pipe\" : `the helper exited ${code}`),\n );\n let text = \"\";\n child.stderr.setEncoding(\"utf8\");\n child.stderr.on(\"data\", (chunk: string) => {\n if (settled) return;\n text += chunk;\n const end = text.indexOf(\"\\n\");\n if (end < 0) return;\n let line: { connected?: boolean; code?: string; error?: string } = {};\n try {\n line = JSON.parse(text.slice(0, end)) as typeof line;\n } catch {\n // Treated as a failure below.\n }\n if (line.connected !== true) {\n fail(\n line.code === \"not-owned\"\n ? \"another user owns that pipe\"\n : (line.error ?? text.slice(0, end)),\n );\n return;\n }\n settled = true;\n clearTimeout(timer);\n resolvePromise(Duplex.from({ readable: child.stdout, writable: child.stdin }));\n });\n });\n}\n","/**\n * Events as an async iterator (IN-08, D101): pages from `events/subscribe`, in cursor order. A\n * consumer that falls behind pauses the subscription instead of buffering without bound or\n * stalling the connection's other calls: past `highWaterMark` pages it unsubscribes, and once it\n * has caught up it subscribes again after the last cursor it received, so nothing is missed or\n * repeated. With a `name`, a page is acknowledged (`events/ack`) when the next one is asked for,\n * which is when the consumer has handled it; a stream of the same name later resumes there.\n */\nimport {\n createDiagnostic,\n type Diagnostic,\n type EventFilter,\n type EventRecord,\n EventsNotifyParams,\n eventsAckMethod,\n eventsSubscribeMethod,\n eventsUnsubscribeMethod,\n type MethodDefinition,\n RpcError,\n receivable,\n} from \"@mostra/protocol\";\n\n/** One page of events. */\nexport interface EventPage {\n /** The events, in cursor order. */\n readonly events: readonly EventRecord[];\n /** Everything up to this cursor was examined: the cursor to resume after. */\n readonly cursor: string;\n /** Set when compaction removed events in this range (`MOSTRA_HOST_CURSOR_COMPACTED`). */\n readonly compacted?: Diagnostic;\n}\n\n/** Options of a stream. */\nexport interface EventStreamOptions {\n /** Which events: artifacts and type patterns. Default: every event. */\n readonly filter?: EventFilter;\n /** Start after this cursor. Default: a named stream's acknowledged cursor, else now. */\n readonly after?: string;\n /** A durable subscriber name: pages are acknowledged under it as they are handled. */\n readonly name?: string;\n /** Pages held before the subscription pauses. Default 16. */\n readonly highWaterMark?: number;\n /** Ends the stream. */\n readonly signal?: AbortSignal;\n}\n\n/** What a stream needs of the session. */\nexport interface EventSession {\n call<P, R>(method: MethodDefinition<P, R>, params: P): Promise<R>;\n /** Registers a handler for `events/notify`; returns its removal. */\n onNotification(handler: (params: unknown) => void): () => void;\n /** Resolves when the session ends. */\n readonly closed: Promise<void>;\n}\n\n/** Opens a stream; nothing is subscribed until the first page is asked for. */\nexport function openEventStream(\n session: EventSession,\n options: EventStreamOptions,\n): AsyncIterable<EventPage> {\n return {\n [Symbol.asyncIterator]: () => new EventStream(session, options),\n };\n}\n\nclass EventStream implements AsyncIterator<EventPage> {\n readonly #session: EventSession;\n readonly #options: EventStreamOptions;\n readonly #high: number;\n readonly #queue: EventPage[] = [];\n #subscription: string | undefined;\n /** The cursor of the last page received, where a resumed subscription starts. */\n #received: string | undefined;\n /** The cursor of the last page handed out; handled once the next page is asked for. */\n #handedOut: string | undefined;\n /** The cursor of the last page the consumer handled, and of the last acknowledged. */\n #handled: string | undefined;\n #acked: string | undefined;\n #paused = false;\n /**\n * Pages that arrived while a subscribe was in flight, for a subscription not known yet: the\n * answer and its first page can reach the session in one chunk, and the page is dispatched\n * before the code awaiting the answer resumes. Kept until the answer names its ID.\n */\n #early: EventsNotifyParams[] | undefined;\n /** The unsubscribe of a pause; its answer means no page of that subscription follows. */\n #pausing: Promise<void> | undefined;\n /** A subscribe whose answer is on its way (`#subscribe`). */\n #subscribing: Promise<void> | undefined;\n #started = false;\n #ended: { error?: unknown } | undefined;\n #wake: (() => void) | undefined;\n readonly #removeHandler: () => void;\n\n constructor(session: EventSession, options: EventStreamOptions) {\n this.#session = session;\n this.#options = options;\n this.#high = Math.max(1, options.highWaterMark ?? 16);\n this.#removeHandler = session.onNotification((params) => this.#receive(params));\n void session.closed.then(() =>\n this.#end(\n new RpcError(\n createDiagnostic(\"MOSTRA_HOST_CONNECTION_CLOSED\", {\n message: \"The Mostra instance exited while its events were being read.\",\n }),\n ),\n ),\n );\n options.signal?.addEventListener(\"abort\", () => void this.return(), { once: true });\n }\n\n #receive(params: unknown): void {\n // Events of types a newer instance added arrive too, never dropping their page (#45).\n const parsed = receivable(EventsNotifyParams).safeParse(params);\n if (!parsed.success) return;\n if (parsed.data.subscriptionId !== this.#subscription) {\n this.#early?.push(parsed.data);\n return;\n }\n this.#accept(parsed.data);\n }\n\n #accept({ events, cursor, compacted }: EventsNotifyParams): void {\n this.#queue.push({ events, cursor, ...(compacted ? { compacted } : {}) });\n this.#received = cursor;\n if (this.#queue.length >= this.#high && !this.#paused) this.#pausing = this.#pause();\n this.#wake?.();\n }\n\n /**\n * Subscribes after `after`. While the answer is on its way the call is `#subscribing`, so\n * `return()` can wait for it and end the subscription it names (GPT review finding 5).\n */\n #subscribe(after: string | undefined): Promise<void> {\n const opening = this.#open(after);\n this.#subscribing = opening;\n return opening.finally(() => {\n if (this.#subscribing === opening) this.#subscribing = undefined;\n });\n }\n\n async #open(after: string | undefined): Promise<void> {\n this.#early = [];\n let answer: { subscriptionId: string; cursor: string };\n let early: EventsNotifyParams[];\n try {\n answer = await this.#session.call(eventsSubscribeMethod, {\n ...(this.#options.filter ? { filter: this.#options.filter } : {}),\n ...(after !== undefined ? { after } : {}),\n ...(this.#options.name ? { name: this.#options.name } : {}),\n });\n } finally {\n early = this.#early;\n this.#early = undefined;\n }\n // Synchronous from here: no page can be dispatched before the ID is known.\n this.#subscription = answer.subscriptionId;\n this.#received ??= answer.cursor;\n // The pages of this subscription that came before its answer was handled, in order.\n for (const page of early) if (page.subscriptionId === answer.subscriptionId) this.#accept(page);\n }\n\n async #pause(): Promise<void> {\n this.#paused = true;\n const id = this.#subscription;\n if (id === undefined) return;\n // What the consumer handled is acknowledged while the subscription still exists: the ack goes\n // out before the unsubscribe on the connection, which keeps their order.\n const acked = this.#sendAck(id);\n // Pages already on their way still arrive under this ID and are kept. The answer comes after\n // them on the connection, so once it is here the subscription is over.\n await this.#session\n .call(eventsUnsubscribeMethod, { subscriptionId: id })\n .catch(() => undefined);\n // A pause runs from a page's arrival, where nobody awaits it, so it never rejects (Opus review\n // finding 7): an ack the instance refused (or a connection gone) ends the stream with that\n // error, which the consumer's next() then throws.\n await acked.catch((error: unknown) => this.#end(error));\n if (this.#subscription === id) this.#subscription = undefined;\n }\n\n async #resume(): Promise<void> {\n await this.#pausing;\n this.#pausing = undefined;\n this.#paused = false;\n await this.#subscribe(this.#received);\n }\n\n /**\n * Acknowledges what the consumer handled under subscription `id`, if a named stream has handled\n * more than it acknowledged. The line is written when this is called (the session writes each\n * call at once), so it is ordered before anything sent after it.\n */\n #sendAck(id: string): Promise<void> {\n const cursor = this.#handled;\n if (!this.#options.name || cursor === undefined || cursor === this.#acked)\n return Promise.resolve();\n this.#acked = cursor;\n return this.#session\n .call(eventsAckMethod, { subscriptionId: id, cursor })\n .then(() => undefined);\n }\n\n #end(error?: unknown): void {\n if (this.#ended) return;\n this.#ended = error === undefined ? {} : { error };\n this.#removeHandler();\n this.#wake?.();\n }\n\n async next(): Promise<IteratorResult<EventPage>> {\n if (!this.#started) {\n this.#started = true;\n await this.#subscribe(this.#options.after);\n }\n // Asking for the next page means the consumer handled the one before it.\n if (this.#handedOut !== undefined) this.#handled = this.#handedOut;\n if (this.#paused && !this.#ended && this.#queue.length <= this.#high / 2) await this.#resume();\n // Never under a subscription being paused: its unsubscribe may already be on its way, and\n // the pause acknowledges what was handled before it.\n if (!this.#paused && this.#subscription !== undefined) await this.#sendAck(this.#subscription);\n for (;;) {\n const page = this.#queue.shift();\n if (page !== undefined) {\n this.#handedOut = page.cursor;\n return { done: false, value: page };\n }\n if (this.#ended) {\n if (this.#ended.error !== undefined) throw this.#ended.error;\n return { done: true, value: undefined };\n }\n if (this.#paused) {\n await this.#resume();\n await this.#sendAck(this.#subscription as string);\n }\n await new Promise<void>((done) => {\n this.#wake = done;\n });\n this.#wake = undefined;\n }\n }\n\n /**\n * Ends the stream: the subscription ends, and a named stream acknowledges every page the\n * consumer handled, never the last one handed out (the loop may have stopped inside it).\n */\n async return(): Promise<IteratorResult<EventPage>> {\n this.#end();\n this.#queue.length = 0;\n await this.#pausing;\n // A subscribe on its way names a subscription that exists on the instance once it is\n // answered: wait for it, so it is ended below like any other.\n await this.#subscribing?.catch(() => undefined);\n const id = this.#subscription;\n if (id !== undefined) {\n this.#subscription = undefined;\n const acked = this.#sendAck(id);\n await this.#session\n .call(eventsUnsubscribeMethod, { subscriptionId: id })\n .catch(() => undefined);\n await acked.catch(() => undefined);\n } else if (this.#options.name && this.#handled !== undefined && this.#handled !== this.#acked) {\n // Paused when it ended, with pages handled since: a subscription of the name, just long\n // enough to acknowledge them (its pages are ignored; the handler is gone).\n await this.#subscribe(this.#received).catch(() => undefined);\n const again = this.#subscription;\n if (again !== undefined) {\n this.#subscription = undefined;\n const acked = this.#sendAck(again);\n await this.#session\n .call(eventsUnsubscribeMethod, { subscriptionId: again })\n .catch(() => undefined);\n await acked.catch(() => undefined);\n }\n }\n return { done: true, value: undefined };\n }\n}\n","/**\n * `createMostra` (HO-04, D25, D58, D59): a JavaScript host's handle on its own Mostra instance.\n * It finds a verified runtime (the pinned bundle, downloaded once), spawns `mostra-runtime host`\n * for the host's home over stdio, opens the protocol session, serves the host's ports and offers\n * the calls every host makes. The instance lives exactly as long as this handle: `close()` ends\n * it, and so does the host's process exiting.\n *\n * ```ts\n * const mostra = await createMostra({\n * home: \"/var/lib/inbox/mostra\",\n * client: { name: \"inbox-app\", version: \"1.4.0\" },\n * ports: { submissions: { deliver: async (envelope) => ({ accepted: true }) } },\n * });\n * const receipt = await mostra.publish(\"/work/inbox\");\n * const outcome = await mostra.wait(receipt.artifactId, \"submitted\");\n * await mostra.close();\n * ```\n */\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport { resolve } from \"node:path\";\nimport {\n type AnyMethod,\n ARTIFACT_PROGRESS,\n type ArtifactRef,\n type ArtifactSummary,\n artifactPublishMethod,\n artifactVerifyMethod,\n type CapabilityLink,\n type ControlsPolicy,\n createDiagnostic,\n type DependencyPolicy,\n type Diagnostic,\n type DraftMirror,\n EVENTS_NOTIFY,\n encodeLine,\n HOST_PROTOCOL_REVISIONS,\n type HomeConfig,\n type InstanceCapabilities,\n type InstanceInfo,\n LineSplitter,\n type LivePushParams,\n type LivePushResult,\n livePushMethod,\n type MethodDefinition,\n type MostraInitializeResult,\n mostraInitializeMethod,\n type PortIdentityResolveParams,\n type PortName,\n type PortSecretsGetParams,\n type PortTrustedControlsActivatedParams,\n type PublishReceipt,\n portDraftsMirrorMethod,\n portIdentityResolveMethod,\n portSecretsGetMethod,\n portSubmissionsDeliverMethod,\n portTrustedControlsActivatedMethod,\n portTrustedControlsPolicyMethod,\n type Results,\n type ResultsMarkdown,\n RpcError,\n RpcPeer,\n receivable,\n resultsGetMethod,\n type SourceRef,\n type StateGetResult,\n type StatePatchParams,\n type StatePatchResult,\n type SubmissionEnvelope,\n type SubmissionPolicy,\n type SubmissionsDeliverResult,\n type SubmitChannel,\n stateGetMethod,\n statePatchMethod,\n type VerifyVerdict,\n type ViewerSpec,\n type ViewUrlParams,\n viewUrlMethod,\n WAIT_MAX_MS,\n type WaitCondition,\n type WaitResult,\n waitMethod,\n} from \"@mostra/protocol\";\nimport type { InstallProgress } from \"./bundle/cache.ts\";\nimport type { Environment } from \"./bundle/setup.ts\";\nimport { childEnvironment } from \"./environment.ts\";\nimport { type EventPage, type EventStreamOptions, openEventStream } from \"./events.ts\";\nimport { type Runtime, resolveRuntime } from \"./runtime.ts\";\nimport { sdkVersion } from \"./version.ts\";\n\n/**\n * The ports a host may serve (INTERFACES §7). Each is optional and has a standalone default;\n * Mostra calls a port only on the instance this handle spawned, and every call is idempotent by\n * its stable ID, so a port may see the same call again after a crash.\n */\nexport interface Ports {\n /**\n * Names the person behind a link minted without a viewer, from the request's headers (D143):\n * `{ ref, name? }` (one viewer per `ref`), or `null` for the home's local user. Answer within\n * 5 s; a failure refuses the link rather than guess.\n */\n readonly identity?: {\n resolve(request: PortIdentityResolveParams): ViewerSpec | null | Promise<ViewerSpec | null>;\n };\n /** Receives each submission once it is durable (D58, D105). Answer within 30 s. */\n readonly submissions?: {\n deliver(\n envelope: SubmissionEnvelope,\n ): SubmissionsDeliverResult | Promise<SubmissionsDeliverResult>;\n };\n /** Receives each viewer draft's latest revision, best effort, never retried (IN-06). */\n readonly drafts?: { mirror(draft: DraftMirror): void | Promise<void> };\n /** Answers `secret()` first, before the home's store (D131); `null` falls back. */\n readonly secrets?: {\n get(request: PortSecretsGetParams): string | null | Promise<string | null>;\n };\n /** Decides each view's submit channels and trusted controls (D108). Answer within 5 s. */\n readonly trustedControls?: {\n policy(artifact: ArtifactSummary): ControlsPolicy | Promise<ControlsPolicy>;\n activated?(event: PortTrustedControlsActivatedParams): void | Promise<void>;\n };\n}\n\n/** Home settings a host chooses (INTERFACES §6 `HomeConfig`), kept in the home's `config.json`. */\nexport interface HomeSettings {\n /** The submission policy for artifacts whose publish names none (D102). */\n readonly submission?: SubmissionPolicy;\n /** The channels that may submit (D40, D108); absent, both. */\n readonly submitChannels?: readonly SubmitChannel[];\n /** How packages enter an artifact's lockfile (D43, D95). */\n readonly dependencies?: DependencyPolicy;\n}\n\n/** Options of {@link createMostra}. */\nexport interface MostraOptions {\n /** The home this host owns (D45). Created 0700 when missing. */\n readonly home: string;\n /**\n * Who the host is. The name owns the host's deliveries across restarts (D105), so keep it\n * stable; it defaults to `mostra-sdk`.\n */\n readonly client?: { readonly name: string; readonly version?: string };\n /** The ports this host serves. */\n readonly ports?: Ports;\n /**\n * Whether submissions made while this host is away wait for it (D105): the registered ports\n * are recorded as ports this host always provides. Default `true`; `false` leaves the home's\n * record as it is.\n */\n readonly expectPorts?: boolean;\n /** Home settings, kept in the home's `config.json` for every later client. */\n readonly settings?: HomeSettings;\n /** An extracted runtime bundle to use instead of the pinned one. */\n readonly bundle?: string;\n /** The gateway's bind address and URL host (D99); loopback by default. */\n readonly bind?: string;\n /** The host name URLs use, which a wildcard `bind` needs (D99). */\n readonly urlHost?: string;\n /** The instance's environment. Default: this process's. */\n readonly env?: Environment;\n /** Each line the instance logs (JSON, on its stderr). A callback that throws is ignored. */\n readonly onLog?: (line: string) => void;\n /** Progress of the first download or setup of the runtime bundle. A throw is ignored. */\n readonly onProgress?: (progress: InstallProgress) => void;\n /**\n * An exception a port threw; the instance got `MOSTRA_HOST_INTERNAL_ERROR` and will retry. A\n * callback that throws is ignored, and the instance is answered all the same.\n */\n readonly onPortError?: (error: unknown, method: string) => void;\n /** Gives up finding the runtime and starting the instance. */\n readonly signal?: AbortSignal;\n}\n\n/** How the instance ended. */\nexport interface InstanceExit {\n /** Its exit code: 0 after a clean stop. */\n readonly code: number | null;\n /** The signal that ended it, if one did. */\n readonly signal: NodeJS.Signals | null;\n}\n\n/** An artifact by ID (`art_…`), by source path, or as the protocol's reference. */\nexport type ArtifactInput = string | ArtifactRef;\n\n/** A host's handle on its instance. */\nexport interface Mostra {\n /** The instance: release, home, platform, PID and mode. */\n readonly instance: InstanceInfo;\n /** What the instance serves. */\n readonly capabilities: InstanceCapabilities;\n /** The negotiated host protocol revision. */\n readonly revision: string;\n /** The session's warnings (an unsupported port, for example). */\n readonly warnings: readonly Diagnostic[];\n /** The runtime it runs on. */\n readonly runtime: Runtime;\n /** Resolves when the instance has exited, for whatever reason. */\n readonly closed: Promise<InstanceExit>;\n /** Calls any host protocol method by its definition from `@mostra/protocol`. */\n call<P, R>(method: MethodDefinition<P, R>, params: P, options?: CallOptions): Promise<R>;\n /** `artifact/publish`: verifies (D41) and publishes; durable before it resolves (H-07). */\n publish(\n source: ArtifactInput,\n options?: {\n readonly force?: boolean;\n readonly policy?: SubmissionPolicy;\n readonly requestId?: string;\n },\n ): Promise<PublishReceipt>;\n /** `artifact/verify`: one verdict, never a publish (D138). */\n verify(\n source: ArtifactInput,\n options?: { readonly screenshots?: \"on-failure\" | \"always\" | \"never\" },\n ): Promise<VerifyVerdict>;\n /**\n * `wait` (IN-10, D103): until the condition holds or `timeoutMs` passes (default: the longest\n * timer, about 24.8 days). `still_waiting` carries the cursor to wait from next; an aborted wait\n * rejects with the signal's reason and loses nothing.\n */\n wait(\n artifact: ArtifactInput,\n until: WaitCondition,\n options?: {\n readonly after?: string;\n readonly timeoutMs?: number;\n readonly signal?: AbortSignal;\n },\n ): Promise<WaitResult>;\n /** `results/get`: a submission as JSON (the default) or Markdown (INTERFACES §8). */\n results(\n artifact: ArtifactInput,\n options?: { readonly submission?: string; readonly format?: \"json\" },\n ): Promise<Results>;\n /** `results/get` as Markdown, for an agent to read. */\n results(\n artifact: ArtifactInput,\n options: { readonly submission?: string; readonly format: \"md\" },\n ): Promise<ResultsMarkdown>;\n /** `state/get`: artifact-scoped fields (D63). */\n getState(artifact: ArtifactInput, ids?: readonly string[]): Promise<StateGetResult>;\n /** `state/patch`: writes artifact-scoped fields through compare-and-set (D63). */\n patchState(\n artifact: ArtifactInput,\n patch: Omit<StatePatchParams, \"artifact\">,\n ): Promise<StatePatchResult>;\n /** `live/push`: a live source's next value (D56). */\n pushLive(\n artifact: ArtifactInput,\n push: Omit<LivePushParams, \"artifact\">,\n ): Promise<LivePushResult>;\n /** `view/url`: a new capability link (D97). */\n viewUrl(\n artifact: ArtifactInput,\n options?: Omit<ViewUrlParams, \"artifact\">,\n ): Promise<CapabilityLink>;\n /**\n * The events matching `options.filter`, page by page, in cursor order, with no gap across a\n * pause (`events/subscribe`). With a `name`, each page is acknowledged when the next one is\n * asked for, so a later stream of that name resumes after the last page handled.\n */\n events(options?: EventStreamOptions): AsyncIterable<EventPage>;\n /** Ends the instance: its stdio closes, and it is stopped if it doesn't exit within 10 s. */\n close(): Promise<InstanceExit>;\n}\n\n/** Options of one call. */\nexport interface CallOptions {\n /** Gives up after this many milliseconds with `MOSTRA_HOST_TIMEOUT`. Default: none. */\n readonly timeoutMs?: number;\n}\n\n/** The port methods the SDK serves, by port. */\nconst PORT_METHODS = {\n identity: [portIdentityResolveMethod],\n submissions: [portSubmissionsDeliverMethod],\n drafts: [portDraftsMirrorMethod],\n secrets: [portSecretsGetMethod],\n trustedControls: [portTrustedControlsPolicyMethod, portTrustedControlsActivatedMethod],\n} as const satisfies Record<keyof Ports, readonly AnyMethod[]>;\n\n/** The client name of an SDK host that names none. */\nexport const SDK_CLIENT_NAME = \"mostra-sdk\";\n\n/** `art_…` is an artifact ID; anything else a source path, resolved against the working directory. */\nexport function artifactRef(input: ArtifactInput): ArtifactRef & SourceRef {\n if (typeof input !== \"string\") return input as ArtifactRef & SourceRef;\n return input.startsWith(\"art_\") ? { artifactId: input } : { path: resolve(input) };\n}\n\nfunction closedError(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_HOST_CONNECTION_CLOSED\", { message }));\n}\n\n/** The handler for one port method, its params already checked. */\nfunction portHandler(ports: Ports, method: string): ((params: unknown) => unknown) | undefined {\n switch (method) {\n case portIdentityResolveMethod.method:\n return (\n ports.identity && ((params) => ports.identity?.resolve(params as PortIdentityResolveParams))\n );\n case portSubmissionsDeliverMethod.method:\n return (\n ports.submissions && ((params) => ports.submissions?.deliver(params as SubmissionEnvelope))\n );\n case portDraftsMirrorMethod.method:\n return ports.drafts && ((params) => ports.drafts?.mirror(params as DraftMirror));\n case portSecretsGetMethod.method:\n return ports.secrets && ((params) => ports.secrets?.get(params as PortSecretsGetParams));\n case portTrustedControlsPolicyMethod.method:\n return (\n ports.trustedControls &&\n ((params) =>\n ports.trustedControls?.policy((params as { artifact: ArtifactSummary }).artifact))\n );\n case portTrustedControlsActivatedMethod.method:\n return (\n ports.trustedControls &&\n (async (params) => {\n await ports.trustedControls?.activated?.(params as PortTrustedControlsActivatedParams);\n return {};\n })\n );\n default:\n return undefined;\n }\n}\n\n/** The port names `ports` registers; anything unknown is a mistake worth failing on. */\nfunction portNames(ports: Ports): PortName[] {\n const names: PortName[] = [];\n for (const [name, value] of Object.entries(ports)) {\n if (value === undefined) continue;\n if (!(name in PORT_METHODS)) {\n throw new TypeError(\n `createMostra: no port \"${name}\" (the SDK serves ${Object.keys(PORT_METHODS).join(\", \")}).`,\n );\n }\n names.push(name as PortName);\n }\n return names;\n}\n\n/**\n * Ends the child: stdin closed (which stops it, D87), then SIGTERM after `graceMs`, then SIGKILL\n * after 5 s more. Windows has no signals between processes (D150 item 6): there the first of\n * them ends the process at once.\n */\nfunction stopChild(\n child: ChildProcess,\n exited: Promise<InstanceExit>,\n graceMs: number,\n): Promise<InstanceExit> {\n child.stdin?.end();\n const term = setTimeout(() => child.kill(\"SIGTERM\"), graceMs);\n const kill = setTimeout(() => child.kill(\"SIGKILL\"), graceMs + 5000);\n return exited.finally(() => {\n clearTimeout(term);\n clearTimeout(kill);\n });\n}\n\n/** `callback`, made unable to throw into its caller. */\nfunction guarded<A extends unknown[]>(\n callback: ((...args: A) => void) | undefined,\n): ((...args: A) => void) | undefined {\n if (callback === undefined) return undefined;\n return (...args: A) => {\n try {\n callback(...args);\n } catch {\n // The host's own code failed; Mostra's work goes on.\n }\n };\n}\n\n/**\n * Spawns an instance for `home` and opens its session. Rejects with the instance's own diagnostic\n * when it can't start (`MOSTRA_HOME_LOCKED`, `MOSTRA_PLATFORM_UNSUPPORTED` …), or with the\n * runtime's (`MOSTRA_ENV_BUNDLE_*`) when no verified runtime can be found.\n */\nexport async function createMostra(options: MostraOptions): Promise<Mostra> {\n // The host's callbacks run inside Mostra's own handlers (a pipe's data listener, the RPC\n // peer's error path, a download's progress): one that throws must never escape into the host's\n // process as an uncaught exception or unhandled rejection, nor stop an answer (Opus review\n // finding 6). A callback that throws is ignored.\n const onLog = guarded(options.onLog);\n const onProgress = guarded(options.onProgress);\n const onPortError = guarded(options.onPortError);\n const ports = options.ports ?? {};\n const names = portNames(ports);\n const env = options.env ?? process.env;\n const home = resolve(options.home);\n const runtime = await resolveRuntime({\n bundle: options.bundle,\n env,\n signal: options.signal,\n ...(onProgress ? { onProgress } : {}),\n });\n options.signal?.throwIfAborted();\n const args = [runtime.runtimeEntry, \"host\", \"--home\", home];\n if (options.bind !== undefined) args.push(\"--bind\", options.bind);\n if (options.urlHost !== undefined) args.push(\"--url-host\", options.urlHost);\n const child = spawn(runtime.node, args, {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n // The host's environment, which on Windows keeps the system's own variables (D153).\n env: childEnvironment(env),\n // A Windows host with no console of its own (a desktop app) opens no window for its instance.\n windowsHide: true,\n });\n const logTail: string[] = [];\n const exited = new Promise<InstanceExit>((done) => {\n child.on(\"close\", (code, signal) => done({ code, signal }));\n child.on(\"error\", () => done({ code: null, signal: null }));\n });\n let spawnError: Error | undefined;\n child.on(\"error\", (error) => {\n spawnError = error;\n });\n const errLines = new LineSplitter();\n child.stderr?.setEncoding(\"utf8\");\n child.stderr?.on(\"data\", (chunk: string) => {\n for (const line of errLines.push(chunk)) {\n logTail.push(line);\n if (logTail.length > 20) logTail.shift();\n onLog?.(line);\n }\n });\n\n const notificationHandlers = new Map<string, Set<(params: unknown) => void>>();\n const peer = new RpcPeer({\n send: (message) => {\n if (child.stdin?.writable) child.stdin.write(encodeLine(message));\n },\n onRequest: async (method, params) => {\n const definition = Object.values(PORT_METHODS)\n .flat()\n .find((candidate) => candidate.method === method) as\n | MethodDefinition<unknown, unknown>\n | undefined;\n const handler = definition && portHandler(ports, method);\n if (!definition || !handler) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOST_METHOD_UNKNOWN\", {\n message: `This host serves no method ${method}.`,\n }),\n -32601,\n );\n }\n // A newer instance may send enum values and union members this host's schemas don't\n // name yet (#45): the port's handler meets them, as it meets any value it can't act on.\n const parsed = receivable(definition.params).safeParse(params);\n if (!parsed.success) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOST_INVALID_PARAMS\", {\n message: `The params of ${method} don't match its schema.`,\n }),\n -32602,\n );\n }\n const answer = await handler(parsed.data);\n const checked = definition.result.safeParse(answer ?? null);\n if (!checked.success) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOST_INTERNAL_ERROR\", {\n message: `The host's ${method} answered something its schema refuses.`,\n }),\n );\n }\n return checked.data;\n },\n onNotification: (method, params) => {\n for (const handler of notificationHandlers.get(method) ?? []) handler(params);\n },\n onInternalError: (error, method) => onPortError?.(error, method),\n });\n const lines = new LineSplitter();\n child.stdout?.setEncoding(\"utf8\");\n child.stdout?.on(\"data\", (chunk: string) => {\n for (const line of lines.push(chunk)) peer.receiveLine(line);\n });\n child.stdout?.on(\"close\", () => {\n peer.close(\n createDiagnostic(\"MOSTRA_HOST_CONNECTION_CLOSED\", {\n message: `The Mostra instance for ${home} exited${logTail.length > 0 ? `; its last log line: ${logTail.at(-1)}` : \"\"}.`,\n }),\n );\n });\n // A pipe to an instance that died fails its next write (EPIPE) on its own schedule. Without a\n // listener that error is an uncaught exception in the host's own process: every pipe has one,\n // and a write that failed ends the session at once, as the instance's exit does.\n child.stdin?.on(\"error\", (error: NodeJS.ErrnoException) => {\n peer.close(\n createDiagnostic(\"MOSTRA_HOST_CONNECTION_CLOSED\", {\n message: `The Mostra instance for ${home} stopped reading (${error.code ?? error.message}).`,\n }),\n );\n });\n child.stdout?.on(\"error\", () => {});\n child.stderr?.on(\"error\", () => {});\n\n const abort = (): void => {\n void stopChild(child, exited, 0);\n };\n options.signal?.addEventListener(\"abort\", abort, { once: true });\n const homeConfig: HomeConfig = {\n path: home,\n // What this host always provides, an empty list included: a host that stopped serving a port\n // clears the record, so its absence is never awaited (Opus review of WP-12, finding 7).\n ...(options.expectPorts !== false ? { ports: names } : {}),\n ...(options.settings?.submission ? { submission: options.settings.submission } : {}),\n ...(options.settings?.submitChannels\n ? { submitChannels: options.settings.submitChannels }\n : {}),\n ...(options.settings?.dependencies ? { dependencies: options.settings.dependencies } : {}),\n };\n let session: MostraInitializeResult;\n try {\n session = await peer.call(mostraInitializeMethod, {\n client: {\n name: options.client?.name ?? SDK_CLIENT_NAME,\n version: options.client?.version ?? sdkVersion(),\n },\n revisions: [...HOST_PROTOCOL_REVISIONS],\n capabilities: { notifications: [EVENTS_NOTIFY, ARTIFACT_PROGRESS] },\n ports: names,\n home: homeConfig,\n });\n } catch (error) {\n await stopChild(child, exited, 2000);\n if (spawnError) throw closedError(`Couldn't start ${runtime.node}: ${spawnError.message}`);\n throw error;\n } finally {\n options.signal?.removeEventListener(\"abort\", abort);\n }\n\n const call = <P, R>(\n method: MethodDefinition<P, R>,\n params: P,\n callOptions?: CallOptions,\n ): Promise<R> =>\n peer.call(\n method,\n params,\n callOptions?.timeoutMs !== undefined ? { timeoutMs: callOptions.timeoutMs } : {},\n );\n let closing: Promise<InstanceExit> | undefined;\n\n const mostra: Mostra = {\n instance: session.instance,\n capabilities: session.capabilities,\n revision: session.revision,\n warnings: session.warnings,\n runtime,\n closed: exited,\n call,\n publish: (source, publishOptions = {}) =>\n call(artifactPublishMethod, { source: artifactRef(source), ...publishOptions }),\n verify: (source, verifyOptions = {}) =>\n call(artifactVerifyMethod, { source: artifactRef(source), ...verifyOptions }),\n wait: (artifact, until, waitOptions = {}) => {\n const signal = waitOptions.signal;\n // Checked before the request goes out: nothing is sent for a wait already given up, so no\n // answer is left without a handler (GPT review finding 4).\n if (signal?.aborted) return Promise.reject(signal.reason);\n const pending = call(waitMethod, {\n artifact: artifactRef(artifact),\n until,\n timeoutMs: waitOptions.timeoutMs ?? WAIT_MAX_MS,\n ...(waitOptions.after !== undefined ? { after: waitOptions.after } : {}),\n });\n if (!signal) return pending;\n // The instance's wait runs on until its own timeout; its late answer, or the connection's\n // end, is handled here and dropped.\n return new Promise<WaitResult>((done, fail) => {\n const onAbort = (): void => fail(signal.reason);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n pending.then(done, fail).finally(() => signal.removeEventListener(\"abort\", onAbort));\n });\n },\n results: ((\n artifact: ArtifactInput,\n resultsOptions: { submission?: string; format?: \"json\" | \"md\" } = {},\n ) =>\n call(resultsGetMethod, {\n artifact: artifactRef(artifact),\n ...resultsOptions,\n })) as Mostra[\"results\"],\n getState: (artifact, ids) =>\n call(stateGetMethod, { artifact: artifactRef(artifact), ...(ids ? { ids: [...ids] } : {}) }),\n patchState: (artifact, patch) =>\n call(statePatchMethod, { artifact: artifactRef(artifact), ...patch }),\n pushLive: (artifact, push) =>\n call(livePushMethod, { artifact: artifactRef(artifact), ...push }),\n viewUrl: (artifact, urlOptions = {}) =>\n call(viewUrlMethod, { artifact: artifactRef(artifact), ...urlOptions }),\n events: (streamOptions = {}) =>\n openEventStream(\n {\n call,\n onNotification: (handler) => {\n let set = notificationHandlers.get(EVENTS_NOTIFY);\n if (!set) {\n set = new Set();\n notificationHandlers.set(EVENTS_NOTIFY, set);\n }\n set.add(handler);\n return () => set?.delete(handler);\n },\n closed: exited.then(() => undefined),\n },\n streamOptions,\n ),\n close: () => {\n closing ??= stopChild(child, exited, 10_000);\n return closing;\n },\n };\n return mostra;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAmCA,MAA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SAAqB,MAAM,SAAS;IAC7C,MAAM,gBAAsB,KAAK,OAAO,MAAM;IAC9C,OAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;IACxD,QAAQ,KAAK,MAAM,IAAI,CAAC,CAAC,cAAc,OAAO,oBAAoB,SAAS,OAAO,CAAC;GACrF,CAAC;EACH;EACA,WACE,UACA,iBAAkE,CAAC,MAEnE,KAAK,kBAAkB;GACrB,UAAU,YAAY,QAAQ;GAC9B,GAAG;EACL,CAAC;EACH,WAAW,UAAU,QACnB,KAAK,gBAAgB;GAAE,UAAU,YAAY,QAAQ;GAAG,GAAI,MAAM,EAAE,KAAK,CAAC,GAAG,GAAG,EAAE,IAAI,CAAC;EAAG,CAAC;EAC7F,aAAa,UAAU,UACrB,KAAK,kBAAkB;GAAE,UAAU,YAAY,QAAQ;GAAG,GAAG;EAAM,CAAC;EACtE,WAAW,UAAU,SACnB,KAAK,gBAAgB;GAAE,UAAU,YAAY,QAAQ;GAAG,GAAG;EAAK,CAAC;EACnE,UAAU,UAAU,aAAa,CAAC,MAChC,KAAK,eAAe;GAAE,UAAU,YAAY,QAAQ;GAAG,GAAG;EAAW,CAAC;EACxE,SAAS,gBAAgB,CAAC,MACxB,gBACE;GACE;GACA,iBAAiB,YAAY;IAC3B,IAAI,MAAM,qBAAqB,IAAI,aAAa;IAChD,IAAI,CAAC,KAAK;KACR,sBAAM,IAAI,IAAI;KACd,qBAAqB,IAAI,eAAe,GAAG;IAC7C;IACA,IAAI,IAAI,OAAO;IACf,aAAa,KAAK,OAAO,OAAO;GAClC;GACA,QAAQ,OAAO,WAAW,KAAA,CAAS;EACrC,GACA,aACF;EACF,aAAa;GACX,YAAY,UAAU,OAAO,QAAQ,GAAM;GAC3C,OAAO;EACT;CAEU;AACd"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/control.ts","../src/events.ts","../src/mostra.ts"],"sourcesContent":["/**\n * Opening a home's control endpoint as a client (D45, D81, D150): the socket or pipe that\n * `instance.json` names, where a home's daemon serves the host protocol.\n *\n * - **POSIX:** a Unix socket in the owner-only runtime directory, opened with `node:net`.\n * - **Windows:** an owner-only named pipe, opened through the runtime's helper, `mostra-win\n * connect`. A pipe's old name in `instance.json` may be free for another user to take, and\n * Node.js can neither check who created a pipe nor stop its server acting as the client, so the\n * helper connects without letting the server impersonate the client, refuses a pipe whose owner\n * isn't this user, and relays the bytes over its standard streams (Opus review of WP-W1).\n *\n * The helper is the one beside the runtime the caller resolved: `MOSTRA_WIN_HELPER`, else the\n * runtime bundle's `bin/mostra-win.exe`, else a development checkout's Cargo build.\n */\nimport { spawn } from \"node:child_process\";\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { createConnection, type Socket } from \"node:net\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { Duplex } from \"node:stream\";\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport type { Environment } from \"./bundle/setup.ts\";\nimport type { Runtime } from \"./runtime.ts\";\n\n/** Options of {@link connectControl}. */\nexport interface ControlOptions {\n /** The runtime whose helper opens a Windows pipe; required on Windows. */\n readonly runtime?: Runtime | undefined;\n /** The environment: `MOSTRA_WIN_HELPER`. */\n readonly env?: Environment | undefined;\n /** How long to wait for the endpoint to answer. Default 5000. */\n readonly timeoutMs?: number | undefined;\n /** The operating system, `process.platform` by default. */\n readonly platform?: string | undefined;\n}\n\nconst PIPE_PREFIX = \"\\\\\\\\.\\\\pipe\\\\\";\n\n/** The helper's exit code for a pipe another user owns (`crates/mostra-win/src/win/connect.rs`). */\nconst NOT_OWNED_EXIT = 3;\n\nfunction unreachable(endpoint: string, why: string): RpcError {\n return new RpcError(\n createDiagnostic(\"MOSTRA_HOST_CONNECTION_CLOSED\", {\n message: `Couldn't reach the instance at ${endpoint} (${why}).`,\n }),\n );\n}\n\n/**\n * The Windows helper beside `runtime`: `MOSTRA_WIN_HELPER`, else the bundle's\n * `bin/mostra-win.exe`, else, for a checkout's `packages/runtime/dist/bin.js`, Cargo's\n * `target/release` then `target/debug`. Throws `MOSTRA_ENV_HELPER_MISSING` when none exists.\n */\nexport function windowsHelper(runtime: Runtime | undefined, env: Environment): string {\n const override = env[\"MOSTRA_WIN_HELPER\"];\n if (override) {\n if (existsSync(override)) return override;\n throw missingHelper(`MOSTRA_WIN_HELPER names ${override}, which doesn't exist.`);\n }\n if (runtime === undefined) {\n throw missingHelper(\"No runtime was resolved, so Mostra's Windows helper can't be found.\");\n }\n const candidates =\n runtime.bundle !== undefined\n ? [join(runtime.bundle.root, \"bin\", \"mostra-win.exe\")]\n : [\"release\", \"debug\"].map((profile) =>\n resolve(\n // The runtime's own order (`helperPath`) starts from where its code really is, so a\n // link to its entry (a relative `MOSTRA_RUNTIME_BIN` through a junction) changes nothing.\n dirname(realEntry(runtime.runtimeEntry)),\n \"..\",\n \"..\",\n \"..\",\n \"target\",\n profile,\n \"mostra-win.exe\",\n ),\n );\n const found = candidates.find((candidate) => existsSync(candidate));\n if (found === undefined) {\n throw missingHelper(\n `Mostra's Windows helper isn't installed; looked for ${candidates.join(\", \")}.`,\n );\n }\n return found;\n}\n\nfunction realEntry(entry: string): string {\n try {\n return realpathSync.native(entry);\n } catch {\n return entry;\n }\n}\n\nfunction missingHelper(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_ENV_HELPER_MISSING\", { message }));\n}\n\n/**\n * Connects to a home's control endpoint. Rejects with `MOSTRA_HOST_CONNECTION_CLOSED` when nothing\n * serves it in time or, on Windows, when another user owns the pipe; with\n * `MOSTRA_ENV_HELPER_MISSING` when the Windows helper can't be found.\n */\nexport function connectControl(endpoint: string, options: ControlOptions = {}): Promise<Duplex> {\n const timeoutMs = options.timeoutMs ?? 5000;\n if ((options.platform ?? process.platform) === \"win32\") {\n return connectPipe(\n endpoint,\n windowsHelper(options.runtime, options.env ?? process.env),\n timeoutMs,\n );\n }\n return new Promise((resolvePromise, reject) => {\n const socket: Socket = createConnection(endpoint);\n const timer = setTimeout(() => {\n socket.destroy();\n reject(unreachable(endpoint, \"timed out\"));\n }, timeoutMs);\n socket.once(\"error\", (error: NodeJS.ErrnoException) => {\n clearTimeout(timer);\n reject(unreachable(endpoint, error.code ?? \"failed\"));\n });\n socket.once(\"connect\", () => {\n clearTimeout(timer);\n resolvePromise(socket);\n });\n });\n}\n\nfunction connectPipe(endpoint: string, helper: string, timeoutMs: number): Promise<Duplex> {\n const name = endpoint.startsWith(PIPE_PREFIX) ? endpoint.slice(PIPE_PREFIX.length) : endpoint;\n return new Promise((resolvePromise, reject) => {\n const child = spawn(helper, [\"connect\", name], {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n windowsHide: true,\n });\n let settled = false;\n const fail = (why: string): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n child.kill();\n reject(unreachable(endpoint, why));\n };\n const timer = setTimeout(() => fail(\"timed out\"), timeoutMs);\n child.once(\"error\", (error) => fail(error.message));\n child.once(\"exit\", (code) =>\n fail(code === NOT_OWNED_EXIT ? \"another user owns that pipe\" : `the helper exited ${code}`),\n );\n let text = \"\";\n child.stderr.setEncoding(\"utf8\");\n child.stderr.on(\"data\", (chunk: string) => {\n if (settled) return;\n text += chunk;\n const end = text.indexOf(\"\\n\");\n if (end < 0) return;\n let line: { connected?: boolean; code?: string; error?: string } = {};\n try {\n line = JSON.parse(text.slice(0, end)) as typeof line;\n } catch {\n // Treated as a failure below.\n }\n if (line.connected !== true) {\n fail(\n line.code === \"not-owned\"\n ? \"another user owns that pipe\"\n : (line.error ?? text.slice(0, end)),\n );\n return;\n }\n settled = true;\n clearTimeout(timer);\n resolvePromise(Duplex.from({ readable: child.stdout, writable: child.stdin }));\n });\n });\n}\n","/**\n * Events as an async iterator (IN-08, D101): pages from `events/subscribe`, in cursor order. A\n * consumer that falls behind pauses the subscription instead of buffering without bound or\n * stalling the connection's other calls: past `highWaterMark` pages it unsubscribes, and once it\n * has caught up it subscribes again after the last cursor it received, so nothing is missed or\n * repeated. With a `name`, a page is acknowledged (`events/ack`) when the next one is asked for,\n * which is when the consumer has handled it; a stream of the same name later resumes there.\n */\nimport {\n createDiagnostic,\n type Diagnostic,\n type EventFilter,\n type EventRecord,\n EventsNotifyParams,\n eventsAckMethod,\n eventsSubscribeMethod,\n eventsUnsubscribeMethod,\n type MethodDefinition,\n RpcError,\n receivable,\n} from \"@mostra/protocol\";\n\n/** One page of events. */\nexport interface EventPage {\n /** The events, in cursor order. */\n readonly events: readonly EventRecord[];\n /** Everything up to this cursor was examined: the cursor to resume after. */\n readonly cursor: string;\n /** Set when compaction removed events in this range (`MOSTRA_HOST_CURSOR_COMPACTED`). */\n readonly compacted?: Diagnostic;\n}\n\n/** Options of a stream. */\nexport interface EventStreamOptions {\n /** Which events: artifacts and type patterns. Default: every event. */\n readonly filter?: EventFilter;\n /** Start after this cursor. Default: a named stream's acknowledged cursor, else now. */\n readonly after?: string;\n /** A durable subscriber name: pages are acknowledged under it as they are handled. */\n readonly name?: string;\n /** Pages held before the subscription pauses. Default 16. */\n readonly highWaterMark?: number;\n /** Ends the stream. */\n readonly signal?: AbortSignal;\n}\n\n/** What a stream needs of the session. */\nexport interface EventSession {\n call<P, R>(method: MethodDefinition<P, R>, params: P): Promise<R>;\n /** Registers a handler for `events/notify`; returns its removal. */\n onNotification(handler: (params: unknown) => void): () => void;\n /** Resolves when the session ends. */\n readonly closed: Promise<void>;\n}\n\n/** Opens a stream; nothing is subscribed until the first page is asked for. */\nexport function openEventStream(\n session: EventSession,\n options: EventStreamOptions,\n): AsyncIterable<EventPage> {\n return {\n [Symbol.asyncIterator]: () => new EventStream(session, options),\n };\n}\n\nclass EventStream implements AsyncIterator<EventPage> {\n readonly #session: EventSession;\n readonly #options: EventStreamOptions;\n readonly #high: number;\n readonly #queue: EventPage[] = [];\n #subscription: string | undefined;\n /** The cursor of the last page received, where a resumed subscription starts. */\n #received: string | undefined;\n /** The cursor of the last page handed out; handled once the next page is asked for. */\n #handedOut: string | undefined;\n /** The cursor of the last page the consumer handled, and of the last acknowledged. */\n #handled: string | undefined;\n #acked: string | undefined;\n #paused = false;\n /**\n * Pages that arrived while a subscribe was in flight, for a subscription not known yet: the\n * answer and its first page can reach the session in one chunk, and the page is dispatched\n * before the code awaiting the answer resumes. Kept until the answer names its ID.\n */\n #early: EventsNotifyParams[] | undefined;\n /** The unsubscribe of a pause; its answer means no page of that subscription follows. */\n #pausing: Promise<void> | undefined;\n /** A subscribe whose answer is on its way (`#subscribe`). */\n #subscribing: Promise<void> | undefined;\n #started = false;\n #ended: { error?: unknown } | undefined;\n #wake: (() => void) | undefined;\n readonly #removeHandler: () => void;\n\n constructor(session: EventSession, options: EventStreamOptions) {\n this.#session = session;\n this.#options = options;\n this.#high = Math.max(1, options.highWaterMark ?? 16);\n this.#removeHandler = session.onNotification((params) => this.#receive(params));\n void session.closed.then(() =>\n this.#end(\n new RpcError(\n createDiagnostic(\"MOSTRA_HOST_CONNECTION_CLOSED\", {\n message: \"The Mostra instance exited while its events were being read.\",\n }),\n ),\n ),\n );\n options.signal?.addEventListener(\"abort\", () => void this.return(), { once: true });\n }\n\n #receive(params: unknown): void {\n // Events of types a newer instance added arrive too, never dropping their page (#45).\n const parsed = receivable(EventsNotifyParams).safeParse(params);\n if (!parsed.success) return;\n if (parsed.data.subscriptionId !== this.#subscription) {\n this.#early?.push(parsed.data);\n return;\n }\n this.#accept(parsed.data);\n }\n\n #accept({ events, cursor, compacted }: EventsNotifyParams): void {\n this.#queue.push({ events, cursor, ...(compacted ? { compacted } : {}) });\n this.#received = cursor;\n if (this.#queue.length >= this.#high && !this.#paused) this.#pausing = this.#pause();\n this.#wake?.();\n }\n\n /**\n * Subscribes after `after`. While the answer is on its way the call is `#subscribing`, so\n * `return()` can wait for it and end the subscription it names (GPT review finding 5).\n */\n #subscribe(after: string | undefined): Promise<void> {\n const opening = this.#open(after);\n this.#subscribing = opening;\n return opening.finally(() => {\n if (this.#subscribing === opening) this.#subscribing = undefined;\n });\n }\n\n async #open(after: string | undefined): Promise<void> {\n this.#early = [];\n let answer: { subscriptionId: string; cursor: string };\n let early: EventsNotifyParams[];\n try {\n answer = await this.#session.call(eventsSubscribeMethod, {\n ...(this.#options.filter ? { filter: this.#options.filter } : {}),\n ...(after !== undefined ? { after } : {}),\n ...(this.#options.name ? { name: this.#options.name } : {}),\n });\n } finally {\n early = this.#early;\n this.#early = undefined;\n }\n // Synchronous from here: no page can be dispatched before the ID is known.\n this.#subscription = answer.subscriptionId;\n this.#received ??= answer.cursor;\n // The pages of this subscription that came before its answer was handled, in order.\n for (const page of early) if (page.subscriptionId === answer.subscriptionId) this.#accept(page);\n }\n\n async #pause(): Promise<void> {\n this.#paused = true;\n const id = this.#subscription;\n if (id === undefined) return;\n // What the consumer handled is acknowledged while the subscription still exists: the ack goes\n // out before the unsubscribe on the connection, which keeps their order.\n const acked = this.#sendAck(id);\n // Pages already on their way still arrive under this ID and are kept. The answer comes after\n // them on the connection, so once it is here the subscription is over.\n await this.#session\n .call(eventsUnsubscribeMethod, { subscriptionId: id })\n .catch(() => undefined);\n // A pause runs from a page's arrival, where nobody awaits it, so it never rejects (Opus review\n // finding 7): an ack the instance refused (or a connection gone) ends the stream with that\n // error, which the consumer's next() then throws.\n await acked.catch((error: unknown) => this.#end(error));\n if (this.#subscription === id) this.#subscription = undefined;\n }\n\n async #resume(): Promise<void> {\n await this.#pausing;\n this.#pausing = undefined;\n this.#paused = false;\n await this.#subscribe(this.#received);\n }\n\n /**\n * Acknowledges what the consumer handled under subscription `id`, if a named stream has handled\n * more than it acknowledged. The line is written when this is called (the session writes each\n * call at once), so it is ordered before anything sent after it.\n */\n #sendAck(id: string): Promise<void> {\n const cursor = this.#handled;\n if (!this.#options.name || cursor === undefined || cursor === this.#acked)\n return Promise.resolve();\n this.#acked = cursor;\n return this.#session\n .call(eventsAckMethod, { subscriptionId: id, cursor })\n .then(() => undefined);\n }\n\n #end(error?: unknown): void {\n if (this.#ended) return;\n this.#ended = error === undefined ? {} : { error };\n this.#removeHandler();\n this.#wake?.();\n }\n\n async next(): Promise<IteratorResult<EventPage>> {\n if (!this.#started) {\n this.#started = true;\n await this.#subscribe(this.#options.after);\n }\n // Asking for the next page means the consumer handled the one before it.\n if (this.#handedOut !== undefined) this.#handled = this.#handedOut;\n if (this.#paused && !this.#ended && this.#queue.length <= this.#high / 2) await this.#resume();\n // Never under a subscription being paused: its unsubscribe may already be on its way, and\n // the pause acknowledges what was handled before it.\n if (!this.#paused && this.#subscription !== undefined) await this.#sendAck(this.#subscription);\n for (;;) {\n const page = this.#queue.shift();\n if (page !== undefined) {\n this.#handedOut = page.cursor;\n return { done: false, value: page };\n }\n if (this.#ended) {\n if (this.#ended.error !== undefined) throw this.#ended.error;\n return { done: true, value: undefined };\n }\n if (this.#paused) {\n await this.#resume();\n await this.#sendAck(this.#subscription as string);\n }\n await new Promise<void>((done) => {\n this.#wake = done;\n });\n this.#wake = undefined;\n }\n }\n\n /**\n * Ends the stream: the subscription ends, and a named stream acknowledges every page the\n * consumer handled, never the last one handed out (the loop may have stopped inside it).\n */\n async return(): Promise<IteratorResult<EventPage>> {\n this.#end();\n this.#queue.length = 0;\n await this.#pausing;\n // A subscribe on its way names a subscription that exists on the instance once it is\n // answered: wait for it, so it is ended below like any other.\n await this.#subscribing?.catch(() => undefined);\n const id = this.#subscription;\n if (id !== undefined) {\n this.#subscription = undefined;\n const acked = this.#sendAck(id);\n await this.#session\n .call(eventsUnsubscribeMethod, { subscriptionId: id })\n .catch(() => undefined);\n await acked.catch(() => undefined);\n } else if (this.#options.name && this.#handled !== undefined && this.#handled !== this.#acked) {\n // Paused when it ended, with pages handled since: a subscription of the name, just long\n // enough to acknowledge them (its pages are ignored; the handler is gone).\n await this.#subscribe(this.#received).catch(() => undefined);\n const again = this.#subscription;\n if (again !== undefined) {\n this.#subscription = undefined;\n const acked = this.#sendAck(again);\n await this.#session\n .call(eventsUnsubscribeMethod, { subscriptionId: again })\n .catch(() => undefined);\n await acked.catch(() => undefined);\n }\n }\n return { done: true, value: undefined };\n }\n}\n","/**\n * `createMostra` (HO-04, D25, D58, D59): a JavaScript host's handle on its own Mostra instance.\n * It finds a verified runtime (the pinned bundle, downloaded once), spawns `mostra-runtime host`\n * for the host's home over stdio, opens the protocol session, serves the host's ports and offers\n * the calls every host makes. The instance lives exactly as long as this handle: `close()` ends\n * it, and so does the host's process exiting.\n *\n * ```ts\n * const mostra = await createMostra({\n * home: \"/var/lib/inbox/mostra\",\n * client: { name: \"inbox-app\", version: \"1.4.0\" },\n * ports: { submissions: { deliver: async (envelope) => ({ accepted: true }) } },\n * });\n * const receipt = await mostra.publish(\"/work/inbox\");\n * const outcome = await mostra.wait(receipt.artifactId, \"submitted\");\n * await mostra.close();\n * ```\n */\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport { resolve } from \"node:path\";\nimport {\n type AnyMethod,\n ARTIFACT_PROGRESS,\n type ArtifactRef,\n type ArtifactSummary,\n artifactPublishMethod,\n artifactVerifyMethod,\n type CapabilityLink,\n type ControlsPolicy,\n createDiagnostic,\n type DependencyPolicy,\n type Diagnostic,\n type DraftMirror,\n EVENTS_NOTIFY,\n encodeLine,\n HOST_PROTOCOL_REVISIONS,\n type HomeConfig,\n type InstanceCapabilities,\n type InstanceInfo,\n LineSplitter,\n type LivePushParams,\n type LivePushResult,\n livePushMethod,\n type MethodDefinition,\n type MostraInitializeResult,\n mostraInitializeMethod,\n type PortAddressingExternalBaseParams,\n type PortAddressingExternalBaseResult,\n type PortIdentityResolveParams,\n type PortName,\n type PortSecretsGetParams,\n type PortTrustedControlsActivatedParams,\n type PublishReceipt,\n portAddressingExternalBaseMethod,\n portDraftsMirrorMethod,\n portIdentityResolveMethod,\n portSecretsGetMethod,\n portSubmissionsDeliverMethod,\n portTrustedControlsActivatedMethod,\n portTrustedControlsPolicyMethod,\n type Results,\n type ResultsMarkdown,\n RpcError,\n RpcPeer,\n receivable,\n resultsGetMethod,\n type ShareStartParams,\n type ShareStartResult,\n type ShareStopResult,\n type SourceRef,\n type StateGetResult,\n type StatePatchParams,\n type StatePatchResult,\n type SubmissionEnvelope,\n type SubmissionPolicy,\n type SubmissionsDeliverResult,\n type SubmitChannel,\n shareStartMethod,\n shareStopMethod,\n stateGetMethod,\n statePatchMethod,\n type VerifyVerdict,\n type ViewerSpec,\n type ViewUrlParams,\n viewUrlMethod,\n WAIT_MAX_MS,\n type WaitCondition,\n type WaitResult,\n waitMethod,\n} from \"@mostra/protocol\";\nimport type { InstallProgress } from \"./bundle/cache.ts\";\nimport type { Environment } from \"./bundle/setup.ts\";\nimport { childEnvironment } from \"./environment.ts\";\nimport { type EventPage, type EventStreamOptions, openEventStream } from \"./events.ts\";\nimport { type Runtime, resolveRuntime } from \"./runtime.ts\";\nimport { sdkVersion } from \"./version.ts\";\n\n/**\n * The ports a host may serve (INTERFACES §7). Each is optional and has a standalone default;\n * Mostra calls a port only on the instance this handle spawned, and every call is idempotent by\n * its stable ID, so a port may see the same call again after a crash.\n */\nexport interface Ports {\n /**\n * Names the person behind a link minted without a viewer, from the request's headers (D143):\n * `{ ref, name? }` (one viewer per `ref`), or `null` for the home's local user. Answer within\n * 5 s; a failure refuses the link rather than guess.\n */\n readonly identity?: {\n resolve(request: PortIdentityResolveParams): ViewerSpec | null | Promise<ViewerSpec | null>;\n };\n /** Receives each submission once it is durable (D58, D105). Answer within 30 s. */\n readonly submissions?: {\n deliver(\n envelope: SubmissionEnvelope,\n ): SubmissionsDeliverResult | Promise<SubmissionsDeliverResult>;\n };\n /** Receives each viewer draft's latest revision, best effort, never retried (IN-06). */\n readonly drafts?: { mirror(draft: DraftMirror): void | Promise<void> };\n /**\n * Gives one of an artifact's listeners an external address (HO-10, D158 item 6): the origin of\n * the host's own tunnel that forwards to `request.local`, which joins the links Mostra mints\n * and its Host allowlist; `null` keeps the loopback address, and withdraws one given before.\n * Answer within 5 s.\n */\n readonly addressing?: {\n externalBase(\n request: PortAddressingExternalBaseParams,\n ): PortAddressingExternalBaseResult | Promise<PortAddressingExternalBaseResult>;\n };\n /** Answers `secret()` first, before the home's store (D131); `null` falls back. */\n readonly secrets?: {\n get(request: PortSecretsGetParams): string | null | Promise<string | null>;\n };\n /** Decides each view's submit channels and trusted controls (D108). Answer within 5 s. */\n readonly trustedControls?: {\n policy(artifact: ArtifactSummary): ControlsPolicy | Promise<ControlsPolicy>;\n activated?(event: PortTrustedControlsActivatedParams): void | Promise<void>;\n };\n}\n\n/** Home settings a host chooses (INTERFACES §6 `HomeConfig`), kept in the home's `config.json`. */\nexport interface HomeSettings {\n /** The submission policy for artifacts whose publish names none (D102). */\n readonly submission?: SubmissionPolicy;\n /** The channels that may submit (D40, D108); absent, both. */\n readonly submitChannels?: readonly SubmitChannel[];\n /** How packages enter an artifact's lockfile (D43, D95). */\n readonly dependencies?: DependencyPolicy;\n}\n\n/** Options of {@link createMostra}. */\nexport interface MostraOptions {\n /** The home this host owns (D45). Created 0700 when missing. */\n readonly home: string;\n /**\n * Who the host is. The name owns the host's deliveries across restarts (D105), so keep it\n * stable; it defaults to `mostra-sdk`.\n */\n readonly client?: { readonly name: string; readonly version?: string };\n /** The ports this host serves. */\n readonly ports?: Ports;\n /**\n * Whether submissions made while this host is away wait for it (D105): the registered ports\n * are recorded as ports this host always provides. Default `true`; `false` leaves the home's\n * record as it is.\n */\n readonly expectPorts?: boolean;\n /** Home settings, kept in the home's `config.json` for every later client. */\n readonly settings?: HomeSettings;\n /** An extracted runtime bundle to use instead of the pinned one. */\n readonly bundle?: string;\n /** The gateway's bind address and URL host (D99); loopback by default. */\n readonly bind?: string;\n /** The host name URLs use, which a wildcard `bind` needs (D99). */\n readonly urlHost?: string;\n /** The instance's environment. Default: this process's. */\n readonly env?: Environment;\n /** Each line the instance logs (JSON, on its stderr). A callback that throws is ignored. */\n readonly onLog?: (line: string) => void;\n /** Progress of the first download or setup of the runtime bundle. A throw is ignored. */\n readonly onProgress?: (progress: InstallProgress) => void;\n /**\n * An exception a port threw; the instance got `MOSTRA_HOST_INTERNAL_ERROR` and will retry. A\n * callback that throws is ignored, and the instance is answered all the same.\n */\n readonly onPortError?: (error: unknown, method: string) => void;\n /** Gives up finding the runtime and starting the instance. */\n readonly signal?: AbortSignal;\n}\n\n/** How the instance ended. */\nexport interface InstanceExit {\n /** Its exit code: 0 after a clean stop. */\n readonly code: number | null;\n /** The signal that ended it, if one did. */\n readonly signal: NodeJS.Signals | null;\n}\n\n/** An artifact by ID (`art_…`), by source path, or as the protocol's reference. */\nexport type ArtifactInput = string | ArtifactRef;\n\n/** A host's handle on its instance. */\nexport interface Mostra {\n /** The instance: release, home, platform, PID and mode. */\n readonly instance: InstanceInfo;\n /** What the instance serves. */\n readonly capabilities: InstanceCapabilities;\n /** The negotiated host protocol revision. */\n readonly revision: string;\n /** The session's warnings (an unsupported port, for example). */\n readonly warnings: readonly Diagnostic[];\n /** The runtime it runs on. */\n readonly runtime: Runtime;\n /** Resolves when the instance has exited, for whatever reason. */\n readonly closed: Promise<InstanceExit>;\n /** Calls any host protocol method by its definition from `@mostra/protocol`. */\n call<P, R>(method: MethodDefinition<P, R>, params: P, options?: CallOptions): Promise<R>;\n /** `artifact/publish`: verifies (D41) and publishes; durable before it resolves (H-07). */\n publish(\n source: ArtifactInput,\n options?: {\n readonly force?: boolean;\n readonly policy?: SubmissionPolicy;\n readonly requestId?: string;\n },\n ): Promise<PublishReceipt>;\n /** `artifact/verify`: one verdict, never a publish (D138). */\n verify(\n source: ArtifactInput,\n options?: { readonly screenshots?: \"on-failure\" | \"always\" | \"never\" },\n ): Promise<VerifyVerdict>;\n /**\n * `wait` (IN-10, D103): until the condition holds or `timeoutMs` passes (default: the longest\n * timer, about 24.8 days). `still_waiting` carries the cursor to wait from next; an aborted wait\n * rejects with the signal's reason and loses nothing.\n */\n wait(\n artifact: ArtifactInput,\n until: WaitCondition,\n options?: {\n readonly after?: string;\n readonly timeoutMs?: number;\n readonly signal?: AbortSignal;\n },\n ): Promise<WaitResult>;\n /** `results/get`: a submission as JSON (the default) or Markdown (INTERFACES §8). */\n results(\n artifact: ArtifactInput,\n options?: { readonly submission?: string; readonly format?: \"json\" },\n ): Promise<Results>;\n /** `results/get` as Markdown, for an agent to read. */\n results(\n artifact: ArtifactInput,\n options: { readonly submission?: string; readonly format: \"md\" },\n ): Promise<ResultsMarkdown>;\n /** `state/get`: artifact-scoped fields (D63). */\n getState(artifact: ArtifactInput, ids?: readonly string[]): Promise<StateGetResult>;\n /** `state/patch`: writes artifact-scoped fields through compare-and-set (D63). */\n patchState(\n artifact: ArtifactInput,\n patch: Omit<StatePatchParams, \"artifact\">,\n ): Promise<StatePatchResult>;\n /** `live/push`: a live source's next value (D56). */\n pushLive(\n artifact: ArtifactInput,\n push: Omit<LivePushParams, \"artifact\">,\n ): Promise<LivePushResult>;\n /** `view/url`: a new capability link (D97). */\n viewUrl(\n artifact: ArtifactInput,\n options?: Omit<ViewUrlParams, \"artifact\">,\n ): Promise<CapabilityLink>;\n /**\n * `share/start`: opens the artifact through a tunnel this machine runs (D158): `tailnet`\n * (Tailscale Serve), or a public `funnel` or `cloudflare` share with a link that expires.\n */\n share(\n artifact: ArtifactInput,\n options: Omit<ShareStartParams, \"artifact\">,\n ): Promise<ShareStartResult>;\n /** `share/stop`: ends a share by its ID, and revokes its link. */\n stopShare(shareId: string): Promise<ShareStopResult>;\n /**\n * The events matching `options.filter`, page by page, in cursor order, with no gap across a\n * pause (`events/subscribe`). With a `name`, each page is acknowledged when the next one is\n * asked for, so a later stream of that name resumes after the last page handled.\n */\n events(options?: EventStreamOptions): AsyncIterable<EventPage>;\n /** Ends the instance: its stdio closes, and it is stopped if it doesn't exit within 10 s. */\n close(): Promise<InstanceExit>;\n}\n\n/** Options of one call. */\nexport interface CallOptions {\n /** Gives up after this many milliseconds with `MOSTRA_HOST_TIMEOUT`. Default: none. */\n readonly timeoutMs?: number;\n}\n\n/** The port methods the SDK serves, by port. */\nconst PORT_METHODS = {\n identity: [portIdentityResolveMethod],\n addressing: [portAddressingExternalBaseMethod],\n submissions: [portSubmissionsDeliverMethod],\n drafts: [portDraftsMirrorMethod],\n secrets: [portSecretsGetMethod],\n trustedControls: [portTrustedControlsPolicyMethod, portTrustedControlsActivatedMethod],\n} as const satisfies Record<keyof Ports, readonly AnyMethod[]>;\n\n/** The client name of an SDK host that names none. */\nexport const SDK_CLIENT_NAME = \"mostra-sdk\";\n\n/** `art_…` is an artifact ID; anything else a source path, resolved against the working directory. */\nexport function artifactRef(input: ArtifactInput): ArtifactRef & SourceRef {\n if (typeof input !== \"string\") return input as ArtifactRef & SourceRef;\n return input.startsWith(\"art_\") ? { artifactId: input } : { path: resolve(input) };\n}\n\nfunction closedError(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_HOST_CONNECTION_CLOSED\", { message }));\n}\n\n/** The handler for one port method, its params already checked. */\nfunction portHandler(ports: Ports, method: string): ((params: unknown) => unknown) | undefined {\n switch (method) {\n case portIdentityResolveMethod.method:\n return (\n ports.identity && ((params) => ports.identity?.resolve(params as PortIdentityResolveParams))\n );\n case portAddressingExternalBaseMethod.method:\n return (\n ports.addressing &&\n ((params) => ports.addressing?.externalBase(params as PortAddressingExternalBaseParams))\n );\n case portSubmissionsDeliverMethod.method:\n return (\n ports.submissions && ((params) => ports.submissions?.deliver(params as SubmissionEnvelope))\n );\n case portDraftsMirrorMethod.method:\n return ports.drafts && ((params) => ports.drafts?.mirror(params as DraftMirror));\n case portSecretsGetMethod.method:\n return ports.secrets && ((params) => ports.secrets?.get(params as PortSecretsGetParams));\n case portTrustedControlsPolicyMethod.method:\n return (\n ports.trustedControls &&\n ((params) =>\n ports.trustedControls?.policy((params as { artifact: ArtifactSummary }).artifact))\n );\n case portTrustedControlsActivatedMethod.method:\n return (\n ports.trustedControls &&\n (async (params) => {\n await ports.trustedControls?.activated?.(params as PortTrustedControlsActivatedParams);\n return {};\n })\n );\n default:\n return undefined;\n }\n}\n\n/** The port names `ports` registers; anything unknown is a mistake worth failing on. */\nfunction portNames(ports: Ports): PortName[] {\n const names: PortName[] = [];\n for (const [name, value] of Object.entries(ports)) {\n if (value === undefined) continue;\n if (!(name in PORT_METHODS)) {\n throw new TypeError(\n `createMostra: no port \"${name}\" (the SDK serves ${Object.keys(PORT_METHODS).join(\", \")}).`,\n );\n }\n names.push(name as PortName);\n }\n return names;\n}\n\n/**\n * Ends the child: stdin closed (which stops it, D87), then SIGTERM after `graceMs`, then SIGKILL\n * after 5 s more. Windows has no signals between processes (D150 item 6): there the first of\n * them ends the process at once.\n */\nfunction stopChild(\n child: ChildProcess,\n exited: Promise<InstanceExit>,\n graceMs: number,\n): Promise<InstanceExit> {\n child.stdin?.end();\n const term = setTimeout(() => child.kill(\"SIGTERM\"), graceMs);\n const kill = setTimeout(() => child.kill(\"SIGKILL\"), graceMs + 5000);\n return exited.finally(() => {\n clearTimeout(term);\n clearTimeout(kill);\n });\n}\n\n/** `callback`, made unable to throw into its caller. */\nfunction guarded<A extends unknown[]>(\n callback: ((...args: A) => void) | undefined,\n): ((...args: A) => void) | undefined {\n if (callback === undefined) return undefined;\n return (...args: A) => {\n try {\n callback(...args);\n } catch {\n // The host's own code failed; Mostra's work goes on.\n }\n };\n}\n\n/**\n * Spawns an instance for `home` and opens its session. Rejects with the instance's own diagnostic\n * when it can't start (`MOSTRA_HOME_LOCKED`, `MOSTRA_PLATFORM_UNSUPPORTED` …), or with the\n * runtime's (`MOSTRA_ENV_BUNDLE_*`) when no verified runtime can be found.\n */\nexport async function createMostra(options: MostraOptions): Promise<Mostra> {\n // The host's callbacks run inside Mostra's own handlers (a pipe's data listener, the RPC\n // peer's error path, a download's progress): one that throws must never escape into the host's\n // process as an uncaught exception or unhandled rejection, nor stop an answer (Opus review\n // finding 6). A callback that throws is ignored.\n const onLog = guarded(options.onLog);\n const onProgress = guarded(options.onProgress);\n const onPortError = guarded(options.onPortError);\n const ports = options.ports ?? {};\n const names = portNames(ports);\n const env = options.env ?? process.env;\n const home = resolve(options.home);\n const runtime = await resolveRuntime({\n bundle: options.bundle,\n env,\n signal: options.signal,\n ...(onProgress ? { onProgress } : {}),\n });\n options.signal?.throwIfAborted();\n const args = [runtime.runtimeEntry, \"host\", \"--home\", home];\n if (options.bind !== undefined) args.push(\"--bind\", options.bind);\n if (options.urlHost !== undefined) args.push(\"--url-host\", options.urlHost);\n const child = spawn(runtime.node, args, {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n // The host's environment, which on Windows keeps the system's own variables (D153).\n env: childEnvironment(env),\n // A Windows host with no console of its own (a desktop app) opens no window for its instance.\n windowsHide: true,\n });\n const logTail: string[] = [];\n const exited = new Promise<InstanceExit>((done) => {\n child.on(\"close\", (code, signal) => done({ code, signal }));\n child.on(\"error\", () => done({ code: null, signal: null }));\n });\n let spawnError: Error | undefined;\n child.on(\"error\", (error) => {\n spawnError = error;\n });\n const errLines = new LineSplitter();\n child.stderr?.setEncoding(\"utf8\");\n child.stderr?.on(\"data\", (chunk: string) => {\n for (const line of errLines.push(chunk)) {\n logTail.push(line);\n if (logTail.length > 20) logTail.shift();\n onLog?.(line);\n }\n });\n\n const notificationHandlers = new Map<string, Set<(params: unknown) => void>>();\n const peer = new RpcPeer({\n send: (message) => {\n if (child.stdin?.writable) child.stdin.write(encodeLine(message));\n },\n onRequest: async (method, params) => {\n const definition = Object.values(PORT_METHODS)\n .flat()\n .find((candidate) => candidate.method === method) as\n | MethodDefinition<unknown, unknown>\n | undefined;\n const handler = definition && portHandler(ports, method);\n if (!definition || !handler) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOST_METHOD_UNKNOWN\", {\n message: `This host serves no method ${method}.`,\n }),\n -32601,\n );\n }\n // A newer instance may send enum values and union members this host's schemas don't\n // name yet (#45): the port's handler meets them, as it meets any value it can't act on.\n const parsed = receivable(definition.params).safeParse(params);\n if (!parsed.success) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOST_INVALID_PARAMS\", {\n message: `The params of ${method} don't match its schema.`,\n }),\n -32602,\n );\n }\n const answer = await handler(parsed.data);\n const checked = definition.result.safeParse(answer ?? null);\n if (!checked.success) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOST_INTERNAL_ERROR\", {\n message: `The host's ${method} answered something its schema refuses.`,\n }),\n );\n }\n return checked.data;\n },\n onNotification: (method, params) => {\n for (const handler of notificationHandlers.get(method) ?? []) handler(params);\n },\n onInternalError: (error, method) => onPortError?.(error, method),\n });\n const lines = new LineSplitter();\n child.stdout?.setEncoding(\"utf8\");\n child.stdout?.on(\"data\", (chunk: string) => {\n for (const line of lines.push(chunk)) peer.receiveLine(line);\n });\n child.stdout?.on(\"close\", () => {\n peer.close(\n createDiagnostic(\"MOSTRA_HOST_CONNECTION_CLOSED\", {\n message: `The Mostra instance for ${home} exited${logTail.length > 0 ? `; its last log line: ${logTail.at(-1)}` : \"\"}.`,\n }),\n );\n });\n // A pipe to an instance that died fails its next write (EPIPE) on its own schedule. Without a\n // listener that error is an uncaught exception in the host's own process: every pipe has one,\n // and a write that failed ends the session at once, as the instance's exit does.\n child.stdin?.on(\"error\", (error: NodeJS.ErrnoException) => {\n peer.close(\n createDiagnostic(\"MOSTRA_HOST_CONNECTION_CLOSED\", {\n message: `The Mostra instance for ${home} stopped reading (${error.code ?? error.message}).`,\n }),\n );\n });\n child.stdout?.on(\"error\", () => {});\n child.stderr?.on(\"error\", () => {});\n\n const abort = (): void => {\n void stopChild(child, exited, 0);\n };\n options.signal?.addEventListener(\"abort\", abort, { once: true });\n const homeConfig: HomeConfig = {\n path: home,\n // What this host always provides, an empty list included: a host that stopped serving a port\n // clears the record, so its absence is never awaited (Opus review of WP-12, finding 7).\n ...(options.expectPorts !== false ? { ports: names } : {}),\n ...(options.settings?.submission ? { submission: options.settings.submission } : {}),\n ...(options.settings?.submitChannels\n ? { submitChannels: options.settings.submitChannels }\n : {}),\n ...(options.settings?.dependencies ? { dependencies: options.settings.dependencies } : {}),\n };\n let session: MostraInitializeResult;\n try {\n session = await peer.call(mostraInitializeMethod, {\n client: {\n name: options.client?.name ?? SDK_CLIENT_NAME,\n version: options.client?.version ?? sdkVersion(),\n },\n revisions: [...HOST_PROTOCOL_REVISIONS],\n capabilities: { notifications: [EVENTS_NOTIFY, ARTIFACT_PROGRESS] },\n ports: names,\n home: homeConfig,\n });\n } catch (error) {\n await stopChild(child, exited, 2000);\n if (spawnError) throw closedError(`Couldn't start ${runtime.node}: ${spawnError.message}`);\n throw error;\n } finally {\n options.signal?.removeEventListener(\"abort\", abort);\n }\n\n const call = <P, R>(\n method: MethodDefinition<P, R>,\n params: P,\n callOptions?: CallOptions,\n ): Promise<R> =>\n peer.call(\n method,\n params,\n callOptions?.timeoutMs !== undefined ? { timeoutMs: callOptions.timeoutMs } : {},\n );\n let closing: Promise<InstanceExit> | undefined;\n\n const mostra: Mostra = {\n instance: session.instance,\n capabilities: session.capabilities,\n revision: session.revision,\n warnings: session.warnings,\n runtime,\n closed: exited,\n call,\n publish: (source, publishOptions = {}) =>\n call(artifactPublishMethod, { source: artifactRef(source), ...publishOptions }),\n verify: (source, verifyOptions = {}) =>\n call(artifactVerifyMethod, { source: artifactRef(source), ...verifyOptions }),\n wait: (artifact, until, waitOptions = {}) => {\n const signal = waitOptions.signal;\n // Checked before the request goes out: nothing is sent for a wait already given up, so no\n // answer is left without a handler (GPT review finding 4).\n if (signal?.aborted) return Promise.reject(signal.reason);\n const pending = call(waitMethod, {\n artifact: artifactRef(artifact),\n until,\n timeoutMs: waitOptions.timeoutMs ?? WAIT_MAX_MS,\n ...(waitOptions.after !== undefined ? { after: waitOptions.after } : {}),\n });\n if (!signal) return pending;\n // The instance's wait runs on until its own timeout; its late answer, or the connection's\n // end, is handled here and dropped.\n return new Promise<WaitResult>((done, fail) => {\n const onAbort = (): void => fail(signal.reason);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n pending.then(done, fail).finally(() => signal.removeEventListener(\"abort\", onAbort));\n });\n },\n results: ((\n artifact: ArtifactInput,\n resultsOptions: { submission?: string; format?: \"json\" | \"md\" } = {},\n ) =>\n call(resultsGetMethod, {\n artifact: artifactRef(artifact),\n ...resultsOptions,\n })) as Mostra[\"results\"],\n getState: (artifact, ids) =>\n call(stateGetMethod, { artifact: artifactRef(artifact), ...(ids ? { ids: [...ids] } : {}) }),\n patchState: (artifact, patch) =>\n call(statePatchMethod, { artifact: artifactRef(artifact), ...patch }),\n pushLive: (artifact, push) =>\n call(livePushMethod, { artifact: artifactRef(artifact), ...push }),\n viewUrl: (artifact, urlOptions = {}) =>\n call(viewUrlMethod, { artifact: artifactRef(artifact), ...urlOptions }),\n share: (artifact, shareOptions) =>\n call(shareStartMethod, { artifact: artifactRef(artifact), ...shareOptions }),\n stopShare: (shareId) => call(shareStopMethod, { shareId }),\n events: (streamOptions = {}) =>\n openEventStream(\n {\n call,\n onNotification: (handler) => {\n let set = notificationHandlers.get(EVENTS_NOTIFY);\n if (!set) {\n set = new Set();\n notificationHandlers.set(EVENTS_NOTIFY, set);\n }\n set.add(handler);\n return () => set?.delete(handler);\n },\n closed: exited.then(() => undefined),\n },\n streamOptions,\n ),\n close: () => {\n closing ??= stopChild(child, exited, 10_000);\n return closing;\n },\n };\n return mostra;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAmCA,MAAM,cAAc;;AAGpB,MAAM,iBAAiB;AAEvB,SAAS,YAAY,UAAkB,KAAuB;CAC5D,OAAO,IAAI,SACT,iBAAiB,iCAAiC,EAChD,SAAS,kCAAkC,SAAS,IAAI,IAAI,IAC9D,CAAC,CACH;AACF;;;;;;AAOA,SAAgB,cAAc,SAA8B,KAA0B;CACpF,MAAM,WAAW,IAAI;CACrB,IAAI,UAAU;EACZ,IAAI,WAAW,QAAQ,GAAG,OAAO;EACjC,MAAM,cAAc,2BAA2B,SAAS,uBAAuB;CACjF;CACA,IAAI,YAAY,KAAA,GACd,MAAM,cAAc,qEAAqE;CAE3F,MAAM,aACJ,QAAQ,WAAW,KAAA,IACf,CAAC,KAAK,QAAQ,OAAO,MAAM,OAAO,gBAAgB,CAAC,IACnD,CAAC,WAAW,OAAO,CAAC,CAAC,KAAK,YACxB,QAGE,QAAQ,UAAU,Q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CAAC;EAAG,CAAC;EAC7F,aAAa,UAAU,UACrB,KAAK,kBAAkB;GAAE,UAAU,YAAY,QAAQ;GAAG,GAAG;EAAM,CAAC;EACtE,WAAW,UAAU,SACnB,KAAK,gBAAgB;GAAE,UAAU,YAAY,QAAQ;GAAG,GAAG;EAAK,CAAC;EACnE,UAAU,UAAU,aAAa,CAAC,MAChC,KAAK,eAAe;GAAE,UAAU,YAAY,QAAQ;GAAG,GAAG;EAAW,CAAC;EACxE,QAAQ,UAAU,iBAChB,KAAK,kBAAkB;GAAE,UAAU,YAAY,QAAQ;GAAG,GAAG;EAAa,CAAC;EAC7E,YAAY,YAAY,KAAK,iBAAiB,EAAE,QAAQ,CAAC;EACzD,SAAS,gBAAgB,CAAC,MACxB,gBACE;GACE;GACA,iBAAiB,YAAY;IAC3B,IAAI,MAAM,qBAAqB,IAAI,aAAa;IAChD,IAAI,CAAC,KAAK;KACR,sBAAM,IAAI,IAAI;KACd,qBAAqB,IAAI,eAAe,GAAG;IAC7C;IACA,IAAI,IAAI,OAAO;IACf,aAAa,KAAK,OAAO,OAAO;GAClC;GACA,QAAQ,OAAO,WAAW,KAAA,CAAS;EACrC,GACA,aACF;EACF,aAAa;GACX,YAAY,UAAU,OAAO,QAAQ,GAAM;GAC3C,OAAO;EACT;CAEU;AACd"}
@@ -1 +1 @@
1
- {"version":3,"file":"runtime-NiLgW1ED.js","names":["invalid","open","BundleAssetSchema"],"sources":["../src/bundle/download.ts","../src/bundle/extract.ts","../src/environment.ts","../src/bundle/tree.ts","../src/bundle/links.ts","../src/bundle/setup.ts","../src/bundle/cache.ts","../src/platform.ts","../src/version.ts","../src/runtime.ts"],"sourcesContent":["/**\n * Fetching a pinned archive (RT-01): streamed to disk while it is hashed, never longer than the\n * pin says, through the environment's proxy (`HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`), retried on\n * failures that a retry can cure, and checked against the pin before anyone reads it.\n */\nimport { createHash } from \"node:crypto\";\nimport { createReadStream, createWriteStream } from \"node:fs\";\nimport { rm } from \"node:fs/promises\";\nimport { Readable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport { fileURLToPath } from \"node:url\";\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport { EnvHttpProxyAgent, fetch } from \"undici\";\n\n/** What a download must match. */\nexport interface Expected {\n readonly sha256: string;\n readonly size: number;\n}\n\n/** Progress of one download, in bytes. */\nexport interface DownloadProgress {\n /** Bytes received so far. */\n readonly received: number;\n /** Bytes the pin says the archive has. */\n readonly total: number;\n}\n\n/** Options of {@link download}. */\nexport interface DownloadOptions {\n /**\n * The environment whose proxy settings apply (`HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, either\n * case): a host's own, never silently `process.env`'s. Default `process.env`.\n */\n readonly env?: Readonly<Record<string, string | undefined>> | undefined;\n readonly signal?: AbortSignal | undefined;\n readonly onProgress?: ((progress: DownloadProgress) => void) | undefined;\n /** How long the connection may stay silent. Default 60 s. */\n readonly stallMs?: number | undefined;\n /** Attempts in all, for failures a retry can cure. Default 3. */\n readonly attempts?: number | undefined;\n}\n\n/** A failure a retry won't cure (an HTTP 4xx other than 408 and 429, a wrong size or digest). */\nclass Final extends Error {}\n\n/**\n * Downloads `url` (`https:`, `http:` or `file:`) to `dest` and checks its size and SHA-256.\n * Throws `MOSTRA_ENV_BUNDLE_INVALID` when the bytes aren't the pinned ones and\n * `MOSTRA_ENV_BUNDLE_DOWNLOAD_FAILED` otherwise; `dest` never survives a failure.\n */\nexport async function download(\n url: string,\n dest: string,\n expected: Expected,\n options: DownloadOptions = {},\n): Promise<void> {\n const attempts = options.attempts ?? 3;\n let last: unknown;\n for (let attempt = 1; attempt <= attempts; attempt++) {\n try {\n const actual = await once(url, dest, expected, options);\n if (actual !== expected.sha256) {\n throw invalid(\n `The download from ${redactUrl(url)} has SHA-256 ${actual}, not the pinned ${expected.sha256}.`,\n );\n }\n return;\n } catch (error) {\n await rm(dest, { force: true });\n last = error;\n if (error instanceof RpcError || error instanceof Final || options.signal?.aborted) break;\n if ((error as NodeJS.ErrnoException).code === \"ENOSPC\") break;\n if (attempt < attempts) await delay(1000 * 4 ** (attempt - 1), options.signal);\n }\n }\n if (last instanceof RpcError) throw last;\n if (options.signal?.aborted) throw options.signal.reason;\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_DOWNLOAD_FAILED\", {\n message: `Couldn't download ${redactUrl(url)}: ${scrubUrls(describe(last))}`,\n }),\n );\n}\n\nasync function once(\n url: string,\n dest: string,\n expected: Expected,\n options: DownloadOptions,\n): Promise<string> {\n const hash = createHash(\"sha256\");\n let received = 0;\n const stallMs = options.stallMs ?? 60_000;\n const controller = new AbortController();\n const abort = (): void => controller.abort(options.signal?.reason);\n options.signal?.addEventListener(\"abort\", abort, { once: true });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const arm = (): void => {\n if (timer !== undefined) clearTimeout(timer);\n timer = setTimeout(\n () => controller.abort(new Error(`no data for ${stallMs / 1000} s`)),\n stallMs,\n );\n };\n try {\n arm();\n const body = await open(url, controller.signal, options.env ?? process.env);\n const counter = async function* (source: AsyncIterable<Uint8Array>) {\n for await (const chunk of source) {\n arm();\n received += chunk.length;\n if (received > expected.size) {\n throw invalid(\n `The download from ${redactUrl(url)} is larger than the pinned ${expected.size} bytes.`,\n );\n }\n hash.update(chunk);\n options.onProgress?.({ received, total: expected.size });\n yield chunk;\n }\n };\n await pipeline(body, counter, createWriteStream(dest, { mode: 0o600 }), {\n signal: controller.signal,\n });\n if (received !== expected.size) {\n throw invalid(\n `The download from ${redactUrl(url)} has ${received} bytes, not the pinned ${expected.size}.`,\n );\n }\n return hash.digest(\"hex\");\n } catch (error) {\n if (controller.signal.aborted && !(error instanceof RpcError)) {\n const reason: unknown = controller.signal.reason;\n throw reason instanceof Error ? reason : new Error(String(reason));\n }\n throw error;\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n options.signal?.removeEventListener(\"abort\", abort);\n }\n}\n\n/** The body of `url` as a stream. */\nasync function open(\n url: string,\n signal: AbortSignal,\n env: Readonly<Record<string, string | undefined>>,\n): Promise<AsyncIterable<Uint8Array>> {\n const parsed = new URL(url);\n if (parsed.protocol === \"file:\") {\n return createReadStream(fileURLToPath(parsed), { signal }) as AsyncIterable<Uint8Array>;\n }\n if (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") {\n throw new Final(`${parsed.protocol} URLs aren't supported`);\n }\n // fetch refuses a URL with credentials, so a mirror's (`https://user:pass@host/…`) travel as\n // Basic authorization, which fetch drops on a redirect to another origin.\n const headers: Record<string, string> = {\n \"user-agent\": \"mostra-sdk\",\n accept: \"application/octet-stream\",\n };\n if (parsed.username !== \"\" || parsed.password !== \"\") {\n const user = decodeURIComponent(parsed.username);\n const password = decodeURIComponent(parsed.password);\n headers[\"authorization\"] = `Basic ${Buffer.from(`${user}:${password}`).toString(\"base64\")}`;\n parsed.username = \"\";\n parsed.password = \"\";\n }\n const response = await fetch(parsed, {\n dispatcher: proxyAgent(env),\n redirect: \"follow\",\n signal,\n headers,\n });\n if (!response.ok || response.body === null) {\n const status = response.status;\n await response.body?.cancel().catch(() => undefined);\n const message = `HTTP ${status}${response.statusText ? ` ${response.statusText}` : \"\"}`;\n if (status >= 400 && status < 500 && status !== 408 && status !== 429) throw new Final(message);\n throw new Error(message);\n }\n return Readable.fromWeb(response.body as import(\"node:stream/web\").ReadableStream<Uint8Array>);\n}\n\nconst agents = new Map<string, EnvHttpProxyAgent>();\n/**\n * The agent for `env`'s `HTTPS_PROXY`, `HTTP_PROXY` and `NO_PROXY` (lowercase first, as curl\n * reads them), one per distinct setting. Each is passed explicitly, an empty one included, so\n * undici never falls back to `process.env` (GPT review finding 6).\n */\nfunction proxyAgent(env: Readonly<Record<string, string | undefined>>): EnvHttpProxyAgent {\n const settings = {\n httpProxy: env[\"http_proxy\"] ?? env[\"HTTP_PROXY\"] ?? \"\",\n httpsProxy: env[\"https_proxy\"] ?? env[\"HTTPS_PROXY\"] ?? \"\",\n noProxy: env[\"no_proxy\"] ?? env[\"NO_PROXY\"] ?? \"\",\n };\n const key = JSON.stringify(settings);\n let agent = agents.get(key);\n if (agent === undefined) {\n agent = new EnvHttpProxyAgent(settings);\n agents.set(key, agent);\n }\n return agent;\n}\n\n/**\n * `text` with every URL in it reduced to {@link redactUrl}'s form: an error from the network stack\n * repeats the URL it failed on, credentials, query and all (a mirror's or a proxy's), and a\n * diagnostic is printed (GPT review finding 2).\n */\nexport function scrubUrls(text: string): string {\n return text.replace(/\\b[a-z][a-z0-9+.-]*:\\/\\/[^\\s\"'<>()]+/gi, (url) => redactUrl(url));\n}\n\nfunction invalid(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_ENV_BUNDLE_INVALID\", { message }));\n}\n\n/** A URL without credentials or a query, safe to print. */\nexport function redactUrl(url: string): string {\n try {\n const parsed = new URL(url);\n parsed.username = \"\";\n parsed.password = \"\";\n parsed.search = \"\";\n parsed.hash = \"\";\n return parsed.toString();\n } catch {\n return \"(an invalid URL)\";\n }\n}\n\nfunction describe(error: unknown): string {\n if (!(error instanceof Error)) return String(error);\n const cause = (error as { cause?: unknown }).cause;\n const code = (cause as { code?: string } | undefined)?.code ?? (error as { code?: string }).code;\n return code !== undefined && !error.message.includes(code)\n ? `${error.message} (${code})`\n : error.message;\n}\n\nfunction delay(ms: number, signal: AbortSignal | undefined): Promise<void> {\n return new Promise((done) => {\n const timer = setTimeout(done, ms);\n signal?.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n done();\n },\n { once: true },\n );\n });\n}\n","/**\n * Unpacking a downloaded archive (RT-01) into a new, empty directory. Only regular files,\n * directories and symbolic links are accepted, all under the archive's one top directory, which is\n * stripped; an entry's path must be relative, with no `..`, `.` or empty part and no backslash\n * (nor, on Windows, a colon; node-tar reads a backslash there as a separator, so its parts are\n * judged as separate ones), and no path may appear twice. Links are made only after every file\n * and directory is written, and after every link's own directory, so no write and no link ever\n * goes through one. Setup then checks the whole tree\n * against the bundle's file list (`checkTree`), which refuses any file or link it doesn't list and\n * any link that leaves the bundle. A pinned archive's SHA-256 is checked before any of this. A\n * Windows archive holds no links at all (D153): one that does is refused, since its junctions are\n * made by setup, from `files.json`.\n *\n * The files are written synchronously as node-tar's parser reads them. node-tar's own `x` checks\n * and clobbers what each path already holds, and on Windows writes one entry at a time; into an\n * empty directory none of that is needed, and a first install wrote its ~50,000 files 4 to 10\n * times slower for it: 6 minutes on Windows arm64 (#88, VERIFIED_FACTS, MT-02).\n */\nimport { closeSync, createReadStream, mkdirSync, openSync, symlinkSync, writeSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport { Parser, type ReadEntry } from \"tar\";\n\nconst FILES = new Set([\"File\", \"OldFile\", \"ContiguousFile\"]);\n\n/** Options of {@link extractBundle}. */\nexport interface ExtractOptions {\n /** `keep` extracts symbolic links; `refuse` refuses an archive that has any (Windows'). */\n readonly links?: \"keep\" | \"refuse\";\n}\n\n/** An entry a bundle's archive never has, or an archive that doesn't read as a tar at all. */\nclass ArchiveRefused extends Error {}\n\n/**\n * Whether `error` is two of the archive's entries meeting where the file system names them as one\n * path: a file where a directory must go, a directory or file already there, names the file system\n * folds alike (`σ` and `ς`, `ß` and `ss`). The directory is new and only this extractor writes in\n * it, so these are never the disk's failure (the Opus review of MT-02).\n */\nfunction collides(error: unknown): boolean {\n const code = (error as NodeJS.ErrnoException).code;\n return code === \"EEXIST\" || code === \"ENOTDIR\" || code === \"EISDIR\";\n}\n\n/** Extracts `archive` (a `.tar.gz` with one top directory `top`) into the empty directory `into`. */\nexport async function extractBundle(\n archive: string,\n into: string,\n top: string,\n options: ExtractOptions = {},\n): Promise<void> {\n try {\n await unpack(archive, resolve(into), top, options.links === \"refuse\");\n } catch (error) {\n if (error instanceof ArchiveRefused) {\n throw new RpcError(createDiagnostic(\"MOSTRA_ENV_BUNDLE_INVALID\", { message: error.message }));\n }\n const code = (error as NodeJS.ErrnoException).code;\n // The file system failing (a full disk, a permission) isn't the archive's fault.\n if (typeof code === \"string\" && /^E[A-Z]+$/.test(code) && code !== \"EOF\") {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_DOWNLOAD_FAILED\", {\n message: `The runtime bundle couldn't be written to ${into}: ${(error as Error).message}${code === \"ENOSPC\" ? \" (the disk is full)\" : \"\"}`,\n }),\n );\n }\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_INVALID\", {\n message: `The runtime bundle's archive couldn't be read: ${(error as Error).message}`,\n }),\n );\n }\n}\n\n/** The path below `top` an entry names, as parts, or why it is refused. */\nexport function entryParts(path: string, top: string, windows: boolean): string[] | string {\n const parts = path.split(\"/\");\n if (parts[0] !== top) return \"it is outside the bundle's directory\";\n // A directory's name ends with a slash.\n if (parts.length > 1 && parts.at(-1) === \"\") parts.pop();\n const below = parts.slice(1);\n for (const part of below) {\n if (part === \"\" || part === \".\" || part === \"..\") return \"its path isn't a plain relative one\";\n if (part.includes(\"\\\\\") || (windows && part.includes(\":\"))) {\n return \"its path holds a character a bundle's paths never have\";\n }\n }\n return below;\n}\n\nasync function unpack(archive: string, root: string, top: string, refuseLinks: boolean) {\n const windows = process.platform === \"win32\";\n const seen = new Set<string>();\n const made = new Set<string>([root]);\n const links: { path: string; target: string }[] = [];\n const ensureDir = (dir: string): void => {\n if (made.has(dir)) return;\n mkdirSync(dir, { recursive: true, mode: 0o755 });\n for (let at = dir; !made.has(at); at = dirname(at)) made.add(at);\n };\n let failure: unknown;\n let open: number | undefined;\n const fail = (error: unknown): void => {\n failure ??= error;\n };\n const refuse = (path: string, type: string, why: string): void =>\n fail(\n new ArchiveRefused(\n `The runtime bundle's archive holds an entry a bundle never has: ${path} (${type}): ${why}.`,\n ),\n );\n\n const parser = new Parser({ strict: true });\n parser.on(\"entry\", (entry: ReadEntry) => {\n const type = String(entry.type);\n if (failure !== undefined) return entry.resume();\n const parts = entryParts(entry.path, top, windows);\n if (typeof parts === \"string\") {\n refuse(entry.path, type, parts);\n return entry.resume();\n }\n const path = parts.length === 0 ? root : join(root, ...parts);\n // Windows and macOS keep one file for names that differ only in case or (macOS) in Unicode\n // normalization, so those are the same path there.\n const key =\n windows || process.platform === \"darwin\" ? path.normalize(\"NFC\").toLowerCase() : path;\n if (parts.length > 0 && seen.has(key)) {\n refuse(entry.path, type, \"its path appears twice\");\n return entry.resume();\n }\n seen.add(key);\n try {\n if (type === \"Directory\") {\n entry.resume();\n ensureDir(path);\n } else if (type === \"SymbolicLink\" && parts.length > 0) {\n entry.resume();\n if (refuseLinks) refuse(entry.path, type, \"a Windows bundle's links are made by setup\");\n else if (!entry.linkpath) refuse(entry.path, type, \"it links to nothing\");\n else links.push({ path, target: entry.linkpath });\n } else if (FILES.has(type) && parts.length > 0) {\n ensureDir(dirname(path));\n // A new file only (`wx`): nothing that was there before, a link least of all, is written to.\n const fd = openSync(path, \"wx\", (entry.mode ?? 0) & 0o111 ? 0o755 : 0o644);\n open = fd;\n entry.on(\"data\", (chunk: Buffer) => {\n if (failure !== undefined) return;\n try {\n let at = 0;\n while (at < chunk.length) at += writeSync(fd, chunk, at);\n } catch (error) {\n fail(error);\n }\n });\n entry.on(\"end\", () => {\n open = undefined;\n try {\n closeSync(fd);\n } catch (error) {\n fail(error);\n }\n });\n } else {\n refuse(entry.path, type, \"a bundle holds only files, directories and links\");\n entry.resume();\n }\n } catch (error) {\n if (collides(error))\n refuse(entry.path, type, \"its path meets another entry's, as this file system names them\");\n else fail(error);\n entry.resume();\n }\n });\n // A parser error (a damaged header, a bad gzip stream) is the archive's: it settles the wait\n // rather than rejecting a promise nobody awaits yet.\n const ended = new Promise<void>((done) => {\n parser.on(\"end\", done);\n parser.on(\"error\", (error: Error) => {\n fail(new ArchiveRefused(`The runtime bundle's archive couldn't be read: ${error.message}`));\n done();\n });\n });\n try {\n for await (const chunk of createReadStream(archive, { highWaterMark: 1024 * 1024 })) {\n parser.write(chunk as Buffer);\n if (failure !== undefined) break;\n }\n if (failure === undefined) {\n parser.end();\n await ended;\n }\n } finally {\n if (open !== undefined) closeSync(open);\n }\n if (failure !== undefined) throw failure;\n // Every link's directory first, while no link exists: a link whose path another entry lies\n // beneath (another link included) then meets a real directory and is refused, and no directory is\n // ever made or reached through a link (the GPT review of MT-02).\n const refused = (path: string, why: string): ArchiveRefused =>\n new ArchiveRefused(\n `The runtime bundle's archive holds an entry a bundle never has: ${path} (SymbolicLink): ${why}.`,\n );\n for (const link of links) {\n try {\n ensureDir(dirname(link.path));\n } catch (error) {\n if (collides(error)) throw refused(link.path, \"it lies beneath a file\");\n throw error;\n }\n }\n for (const link of links) {\n try {\n symlinkSync(link.target, link.path);\n } catch (error) {\n // Its path is a directory other entries filled (the link would have been written through), or\n // a name the file system folds with another entry's.\n if (collides(error))\n throw refused(link.path, \"other entries are inside it, or meet its path\");\n throw error;\n }\n }\n}\n","/**\n * The environment of a process the SDK starts (the instance, the browser's fetch). A host may\n * give an environment of its own (`createMostra`'s `env`), and on Windows a program starts only\n * with the system's own variables: Node.js aborts without `SystemRoot`, which its random-number\n * source needs. So on Windows each of them this process has is added where the host's environment\n * lacks it, matched without case as Windows matches names (D150 item 9, D153). They name the\n * system's own folders and nothing of the user's secrets. Elsewhere the environment is the host's,\n * as it is.\n */\n/** An environment as a host gives it. */\ntype Environment = Readonly<Record<string, string | undefined>>;\n\n/** What Windows gives every program, which a child of the SDK keeps (D150 item 9). */\nconst WINDOWS_SYSTEM_VARIABLES: readonly string[] = [\n \"SystemRoot\",\n \"SystemDrive\",\n \"windir\",\n \"ComSpec\",\n \"PATHEXT\",\n \"TEMP\",\n \"TMP\",\n \"USERPROFILE\",\n \"HOMEDRIVE\",\n \"HOMEPATH\",\n \"APPDATA\",\n \"LOCALAPPDATA\",\n \"ProgramData\",\n \"ProgramFiles\",\n \"ProgramFiles(x86)\",\n \"ProgramW6432\",\n \"CommonProgramFiles\",\n \"CommonProgramFiles(x86)\",\n \"CommonProgramW6432\",\n \"USERNAME\",\n \"USERDOMAIN\",\n \"COMPUTERNAME\",\n \"OS\",\n \"NUMBER_OF_PROCESSORS\",\n \"PROCESSOR_ARCHITECTURE\",\n \"PROCESSOR_IDENTIFIER\",\n];\n\n/** `env` for a child process: on Windows with the system's own variables this process has. */\nexport function childEnvironment(\n env: Environment,\n options: { readonly platform?: string; readonly own?: Environment } = {},\n): NodeJS.ProcessEnv {\n const out: NodeJS.ProcessEnv = {};\n for (const [name, value] of Object.entries(env)) if (value !== undefined) out[name] = value;\n if ((options.platform ?? process.platform) !== \"win32\") return out;\n const own = options.own ?? process.env;\n const present = new Set(Object.keys(out).map((name) => name.toUpperCase()));\n for (const name of WINDOWS_SYSTEM_VARIABLES) {\n if (present.has(name.toUpperCase())) continue;\n const found = Object.entries(own).find(([key]) => key.toUpperCase() === name.toUpperCase());\n if (found?.[1] !== undefined) out[found[0]] = found[1];\n }\n return out;\n}\n","/**\n * A bundle's files against its manifest (RT-01): one walk that both writes `files.json` (the\n * assembler) and checks an extracted bundle against it (setup), so the two can't disagree about\n * what counts. Links must stay inside the bundle; nothing may be missing, changed or extra.\n *\n * On Windows (D153) a link is read as the relative, `/`-separated path from its directory to its\n * target, whether it is a symbolic link (`..\\\\x`, as pnpm makes them for an administrator) or a\n * junction (an absolute target, as setup makes them for everyone), so `files.json` reads the same\n * on every system; and no file is executable, since Windows keeps no execute bit (D150 item 8).\n */\nimport { createHash } from \"node:crypto\";\nimport { createReadStream, realpathSync } from \"node:fs\";\nimport { lstat, readdir, readlink } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport type { BundleFileEntry, BundleFiles, BundleLinkEntry } from \"@mostra/protocol\";\n\n/** Whether this process runs on Windows, whose links and modes the walk reads its own way. */\nconst WINDOWS = process.platform === \"win32\";\n\n/**\n * A link's target as the manifest spells it: relative to the link's directory, `/`-separated.\n * POSIX targets are kept exactly as written; a Windows junction's absolute target, and a Windows\n * symbolic link's `\\\\`-separated one, are rewritten into that form. `realRoot` is `root`'s real\n * path, which a caller reading many links computes once (Opus review of WP-W3, finding 8).\n */\nexport function linkTarget(\n root: string,\n path: string,\n written: string,\n realRoot: string | undefined = realOrNone(root),\n): string {\n if (!WINDOWS) return written;\n // A junction's target may carry the `\\\\?\\` prefix of Windows' own namespace.\n const plain = written.startsWith(\"\\\\\\\\?\\\\\") ? written.slice(4) : written;\n if (!isAbsolute(plain)) return plain.split(sep).join(\"/\");\n // A junction stores an absolute path, spelled as whoever made it spelled the bundle's root:\n // setup uses the real path, while `root` may be another spelling of it (an 8.3 short name such\n // as `RUNNER~1`, another case). Each spelling of the link's directory is tried against the\n // same spelling of the root, so neither reads as a detour out of the bundle; Windows compares\n // without case.\n const given = resolve(root);\n const dir = dirname(join(given, path));\n const spellings: [string, string][] = [[given, dir]];\n // A root that doesn't exist holds no junction; the lexical form then reports the mismatch.\n if (realRoot !== undefined) spellings.push([realRoot, join(realRoot, relative(given, dir))]);\n const lower = plain.toLowerCase();\n for (const [base, from] of spellings) {\n if (lower === base.toLowerCase() || lower.startsWith(`${base.toLowerCase()}${sep}`))\n return relative(from, plain).split(sep).join(\"/\");\n }\n return relative(dir, plain).split(sep).join(\"/\");\n}\n\n/** `root`'s real path on Windows (where junction targets need it), or `undefined`. */\nexport function realOrNone(root: string): string | undefined {\n if (!WINDOWS) return undefined;\n try {\n return realpathSync.native(resolve(root));\n } catch {\n return undefined;\n }\n}\n\n/** The SHA-256 and size of one file, read as a stream. */\nexport async function hashFile(path: string): Promise<{ sha256: string; size: number }> {\n const hash = createHash(\"sha256\");\n let size = 0;\n for await (const chunk of createReadStream(path)) {\n hash.update(chunk as Buffer);\n size += (chunk as Buffer).length;\n }\n return { sha256: hash.digest(\"hex\"), size };\n}\n\n/** One entry of a walk: a regular file or a link, by `/`-separated path from the root. */\ntype Walked =\n | { readonly kind: \"file\"; readonly path: string; readonly executable: boolean }\n | { readonly kind: \"link\"; readonly path: string; readonly target: string }\n | { readonly kind: \"other\"; readonly path: string };\n\n/** Every file and link under `root`, sorted by path, skipping `exclude`d paths (and below). */\nasync function walk(root: string, exclude: (path: string) => boolean): Promise<Walked[]> {\n const out: Walked[] = [];\n const realRoot = realOrNone(root);\n const visit = async (dir: string): Promise<void> => {\n const entries = await readdir(join(root, dir), { withFileTypes: true });\n for (const entry of entries) {\n const path = dir === \"\" ? entry.name : `${dir}/${entry.name}`;\n if (exclude(path)) continue;\n if (entry.isDirectory()) await visit(path);\n else if (entry.isSymbolicLink()) {\n const written = await readlink(join(root, path));\n out.push({ kind: \"link\", path, target: linkTarget(root, path, written, realRoot) });\n } else if (entry.isFile()) {\n // Windows keeps no execute bit: Node.js reports one there for every file it can read.\n const executable = WINDOWS ? false : ((await lstat(join(root, path))).mode & 0o100) !== 0;\n out.push({ kind: \"file\", path, executable });\n } else out.push({ kind: \"other\", path });\n }\n };\n await visit(\"\");\n return out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n}\n\n/** Runs `task` over `items`, at most `limit` at a time, keeping the order of results. */\nasync function mapLimit<T, R>(\n items: readonly T[],\n limit: number,\n task: (item: T) => Promise<R>,\n): Promise<R[]> {\n const results = new Array<R>(items.length);\n let next = 0;\n const worker = async (): Promise<void> => {\n while (next < items.length) {\n const index = next++;\n results[index] = await task(items[index] as T);\n }\n };\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));\n return results;\n}\n\n/** Whether a link's target is relative and resolves inside `root`. */\nexport function linkStaysInside(root: string, path: string, target: string): boolean {\n if (isAbsolute(target) || /[\\\\:\\0]/.test(target)) return false;\n const base = resolve(root);\n const resolved = resolve(base, dirname(path), target);\n return resolved === base || resolved.startsWith(base + sep);\n}\n\n/** Whether a manifest path is a plain relative path: no absolute start, no `.` or `..` segment. */\nexport function safeRelative(path: string): boolean {\n if (path === \"\" || isAbsolute(path) || path.includes(\"\\\\\") || path.includes(\"\\0\")) return false;\n return path.split(\"/\").every((segment) => segment !== \"\" && segment !== \".\" && segment !== \"..\");\n}\n\n/**\n * The manifest of the tree under `root`: every regular file with its SHA-256, size and execute\n * bit, every link with its target. Throws on anything else (a device, a socket, a link leaving\n * the tree), which a bundle must never contain.\n */\nexport async function describeTree(\n root: string,\n exclude: (path: string) => boolean = () => false,\n): Promise<BundleFiles> {\n const walked = await walk(root, exclude);\n const files: BundleFileEntry[] = [];\n const links: BundleLinkEntry[] = [];\n const regular = walked.filter((entry) => entry.kind === \"file\");\n const hashed = await mapLimit(regular, 32, (entry) => hashFile(join(root, entry.path)));\n regular.forEach((entry, index) => {\n const { sha256, size } = hashed[index] as { sha256: string; size: number };\n files.push({ path: entry.path, size, sha256, executable: entry.executable });\n });\n for (const entry of walked) {\n if (entry.kind === \"other\") throw new Error(`${entry.path} is neither a file nor a link.`);\n if (entry.kind !== \"link\") continue;\n if (!linkStaysInside(root, entry.path, entry.target))\n throw new Error(`${entry.path} links outside the tree (${entry.target}).`);\n links.push({ path: entry.path, target: entry.target });\n }\n return { schemaVersion: 1, files, links };\n}\n\n/** What a check found: an empty list means the tree matches. Paths are relative to the root. */\nexport type TreeProblems = readonly string[];\n\n/**\n * Checks the tree under `root` against `manifest`: each listed file present, regular, with its\n * size, SHA-256 and execute bit; each link present with its target, staying inside; and nothing\n * else besides what `allowExtra` accepts. Reports at most `limit` problems.\n */\nexport async function checkTree(\n root: string,\n manifest: BundleFiles,\n options: {\n readonly allowExtra?: (path: string) => boolean;\n readonly limit?: number;\n /**\n * Whether the links are checked; `false` checks the files alone and lets each listed link be\n * there or not, for a Windows bundle whose junctions setup makes after a rename (D153).\n */\n readonly links?: boolean;\n } = {},\n): Promise<TreeProblems> {\n const limit = options.limit ?? 20;\n const allowExtra = options.allowExtra ?? (() => false);\n const checkLinks = options.links ?? true;\n const problems: string[] = [];\n const add = (problem: string): void => {\n if (problems.length < limit) problems.push(problem);\n };\n const expectedFiles = new Map(manifest.files.map((entry) => [entry.path, entry]));\n const expectedLinks = new Map(manifest.links.map((entry) => [entry.path, entry]));\n for (const path of [...expectedFiles.keys(), ...expectedLinks.keys()]) {\n if (!safeRelative(path)) add(`${path}: not a plain relative path`);\n }\n if (problems.length > 0) return problems;\n // An allowed extra is skipped whole unless something listed lies at or below it.\n const listedDirs = new Set<string>();\n for (const path of [...expectedFiles.keys(), ...expectedLinks.keys()]) {\n const segments = path.split(\"/\");\n for (let index = 1; index < segments.length; index++)\n listedDirs.add(segments.slice(0, index).join(\"/\"));\n }\n const walked = await walk(\n root,\n (path) =>\n allowExtra(path) &&\n !expectedFiles.has(path) &&\n !expectedLinks.has(path) &&\n !listedDirs.has(path),\n );\n const found = new Map(walked.map((entry) => [entry.path, entry]));\n for (const entry of walked) {\n if (!expectedFiles.has(entry.path) && !expectedLinks.has(entry.path)) {\n if (!allowExtra(entry.path)) add(`${entry.path}: not in the bundle's file list`);\n }\n }\n for (const [path, link] of checkLinks ? expectedLinks : new Map<string, BundleLinkEntry>()) {\n const actual = found.get(path);\n if (actual?.kind !== \"link\") add(`${path}: missing link`);\n else if (actual.target !== link.target)\n add(`${path}: links to ${actual.target}, not ${link.target}`);\n else if (!linkStaysInside(root, path, link.target)) add(`${path}: links outside the bundle`);\n }\n const files = [...expectedFiles.values()];\n const results = await mapLimit(files, 32, async (entry) => {\n const actual = found.get(entry.path);\n if (actual?.kind !== \"file\") return `${entry.path}: missing file`;\n if (actual.executable !== entry.executable)\n return `${entry.path}: ${entry.executable ? \"not executable\" : \"executable\"}`;\n const { sha256, size } = await hashFile(join(root, entry.path));\n if (size !== entry.size) return `${entry.path}: ${size} bytes, not ${entry.size}`;\n if (sha256 !== entry.sha256) return `${entry.path}: its SHA-256 differs`;\n return undefined;\n });\n for (const result of results) if (result !== undefined) add(result);\n return problems;\n}\n","/**\n * A Windows bundle's links (D153). An ordinary Windows user can't create symbolic links (that\n * takes an administrator or Developer Mode), so a Windows archive holds none: its `files.json`\n * lists each link, every one to a directory inside the bundle, and setup makes each a junction,\n * which any user can create. A junction names its target by absolute path, so it is made at the\n * bundle's real path, and a bundle moved since is set up again (`readSetup` compares the root\n * its marker names).\n *\n * Nothing outside the bundle is ever touched: a listed link's path and target must stay inside\n * it, every directory above a link must be a real directory (never a link), the target must be a\n * directory, and what already sits at a link's path is replaced only when it is itself a link, or\n * a real directory holding exactly the files and bytes of the link's target. That is what a copy\n * made by a tool that follows junctions leaves (Explorer, `Copy-Item`, `robocopy` without `/SJ`,\n * and a move to another drive, which is a copy), so such a copy is set up again; a directory\n * holding anything else is refused and kept (Opus review of WP-W3, finding 4).\n *\n * Two setups of one bundle may run at once (a moved bundle met by two commands): each step\n * tolerates the other's, and a link counts as made once it names its target, whoever made it\n * (finding 5).\n */\nimport {\n lstat,\n mkdir,\n readdir,\n readlink,\n rm,\n rmdir,\n stat,\n symlink,\n unlink,\n} from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport type { BundleFiles, BundleLinkEntry } from \"@mostra/protocol\";\nimport { hashFile, linkStaysInside, linkTarget, realOrNone, safeRelative } from \"./tree.ts\";\n\n/** Why a link couldn't be made; the caller reports it as `MOSTRA_ENV_BUNDLE_INVALID`. */\nexport class LinkRefused extends Error {}\n\n/** Whether `path` (an absolute path inside `root`) has only real directories above it. */\nasync function realParents(root: string, path: string): Promise<boolean> {\n let dir = dirname(path);\n const chain: string[] = [];\n while (dir.length > root.length) {\n chain.unshift(dir);\n dir = dirname(dir);\n }\n for (const parent of chain) {\n const info = await lstat(parent).catch(() => undefined);\n if (info === undefined) {\n await mkdir(parent);\n continue;\n }\n if (!info.isDirectory() || info.isSymbolicLink()) return false;\n }\n return true;\n}\n\n/**\n * Makes every link `manifest` lists as a junction under `root`, which must be the bundle's real\n * path (`realpath.native`). A link that already names its target is kept; one that names another\n * (the bundle moved) is replaced. Throws {@link LinkRefused} for a link the manifest can't have.\n */\nexport async function makeJunctions(root: string, manifest: BundleFiles): Promise<void> {\n // A link's target may lie behind another link (`node_modules/x` through a scope's link), so a\n // link whose target isn't there yet waits for the next round; a round that makes nothing ends.\n const realRoot = realOrNone(root);\n let waiting = [...manifest.links].sort((a, b) => a.path.length - b.path.length);\n while (waiting.length > 0) {\n const later: typeof waiting = [];\n for (const link of waiting) {\n if (!(await makeJunction(root, link, realRoot))) later.push(link);\n }\n if (later.length === waiting.length) {\n const first = later[0] as BundleLinkEntry;\n throw new LinkRefused(`${first.path} links to ${first.target}, which is no directory.`);\n }\n waiting = later;\n }\n}\n\n/** Makes one link; `false` when its target isn't a directory (yet). */\nasync function makeJunction(\n root: string,\n link: BundleLinkEntry,\n realRoot: string | undefined,\n): Promise<boolean> {\n if (!safeRelative(link.path) || !linkStaysInside(root, link.path, link.target)) {\n throw new LinkRefused(`${link.path} links outside the bundle (${link.target}).`);\n }\n const at = join(root, link.path);\n const target = resolve(dirname(at), link.target);\n if (!(await realParents(root, at))) {\n throw new LinkRefused(`${link.path} sits below a link or a file.`);\n }\n const kind = await stat(target).catch(() => undefined);\n if (kind === undefined || !kind.isDirectory()) {\n return names(root, link, at, realRoot);\n }\n // Another setup of this bundle may be making the same links (finding 5). Each attempt reads the\n // state afresh and accepts a link that names its target, whoever made it; a setup removes only\n // what doesn't, and always makes the link right after, while nothing ever makes a stale one, so\n // the link names its target once both stop.\n let last: unknown;\n for (let attempt = 0; attempt < 20; attempt++) {\n if (await names(root, link, at, realRoot)) return true;\n const current = await lstat(at).catch(() => undefined);\n try {\n if (current?.isSymbolicLink()) {\n // A junction is a directory to Windows: `rmdir` removes the link, never what it names.\n await rmdir(at).catch(async (error: NodeJS.ErrnoException) => {\n if (error.code !== \"ENOENT\") await unlink(at);\n });\n } else if (current !== undefined) {\n if (!current.isDirectory() || !(await sameTree(at, target))) {\n // Read again: another setup may have replaced the copy while it was compared.\n if (await names(root, link, at, realRoot)) return true;\n const now = await lstat(at).catch(() => undefined);\n if (now !== undefined && !now.isSymbolicLink()) {\n throw new LinkRefused(\n `${link.path} is a file or directory where the bundle has a link, and it isn't a copy of ${link.target}.`,\n );\n }\n continue;\n }\n // A copy of the target: no link inside it (`sameTree` refuses one), so nothing outside it.\n await rm(at, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });\n }\n await symlink(target, at, \"junction\");\n } catch (error) {\n if (error instanceof LinkRefused) throw error;\n last = error; // another setup's step came between: the next attempt reads the state again\n }\n }\n if (await names(root, link, at, realRoot)) return true;\n throw new LinkRefused(\n `${link.path} couldn't be made as a junction to ${link.target}${last ? `: ${(last as Error).message}` : \"\"}.`,\n );\n}\n\n/** Whether the link at `at` exists and names the manifest's target. */\nasync function names(\n root: string,\n link: BundleLinkEntry,\n at: string,\n realRoot: string | undefined,\n): Promise<boolean> {\n const info = await lstat(at).catch(() => undefined);\n if (info === undefined || !info.isSymbolicLink()) return false;\n const written = await readlink(at).catch(() => undefined);\n return written !== undefined && linkTarget(root, link.path, written, realRoot) === link.target;\n}\n\n/**\n * Whether the real directory `copy` holds exactly what `original` holds: the same names, files of\n * the same bytes, and directories alike all the way down. A link anywhere in the copy, or an entry\n * of any other kind, makes it no copy.\n */\nasync function sameTree(copy: string, original: string): Promise<boolean> {\n const [mine, theirs] = await Promise.all([\n readdir(copy, { withFileTypes: true }).catch(() => undefined),\n readdir(original, { withFileTypes: true }).catch(() => undefined),\n ]);\n if (mine === undefined || theirs === undefined || mine.length !== theirs.length) return false;\n const byName = new Map(theirs.map((entry) => [entry.name, entry]));\n for (const entry of mine) {\n const other = byName.get(entry.name);\n if (other === undefined || entry.isSymbolicLink()) return false;\n const a = join(copy, entry.name);\n const b = join(original, entry.name);\n if (entry.isDirectory()) {\n // The original may reach a directory through a link (a junction made a moment ago).\n if (!(await stat(b).catch(() => undefined))?.isDirectory()) return false;\n if (!(await sameTree(a, b))) return false;\n } else if (entry.isFile()) {\n if (!(other.isFile() || other.isSymbolicLink()) || !(await sameBytes(a, b))) return false;\n } else return false;\n }\n return true;\n}\n\n/** Whether two files hold the same bytes (streamed, so a large program isn't held in memory). */\nasync function sameBytes(a: string, b: string): Promise<boolean> {\n const [sa, sb] = await Promise.all([stat(a), stat(b)]).catch(() => [undefined, undefined]);\n if (sa === undefined || sb === undefined || !sb.isFile() || sa.size !== sb.size) return false;\n const [ha, hb] = await Promise.all([hashFile(a), hashFile(b)]);\n return ha.sha256 === hb.sha256;\n}\n","/**\n * Making an extracted bundle usable (RT-01, D142): its files checked against `files.json`, which\n * `bundle.json` pins by SHA-256; the verify browser fetched through the bundle's own Playwright\n * and checked against the bundle's pin; then `.mostra-setup.json`, the one marker every reader\n * trusts. The SDK runs it after a download; `bin/mostra-setup` runs it for a bundle extracted by\n * hand, and for the Rust crate (WP-12), so there is one implementation of what \"ready\" means.\n */\nimport { spawn } from \"node:child_process\";\nimport { realpathSync } from \"node:fs\";\nimport { readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n BUNDLE_SETUP_MARKER,\n BundleFiles,\n BundleInfo,\n BundleSetup,\n createDiagnostic,\n isWindowsBundle,\n RpcError,\n} from \"@mostra/protocol\";\nimport { childEnvironment } from \"../environment.ts\";\nimport { scrubUrls } from \"./download.ts\";\nimport { LinkRefused, makeJunctions } from \"./links.ts\";\nimport { checkTree, hashFile, safeRelative } from \"./tree.ts\";\n\n/** The environment setup reads. */\nexport type Environment = Readonly<Record<string, string | undefined>>;\n\n/** An extracted bundle and what its `bundle.json` says. */\nexport interface Bundle {\n /** Its root directory, holding `bundle.json`. */\n readonly root: string;\n /** Its parsed `bundle.json`. */\n readonly info: BundleInfo;\n}\n\n/** One step of setup, for progress reports. */\nexport type SetupStep = \"files\" | \"browser\";\n\n/** Options of {@link setupBundle}. */\nexport interface SetupOptions {\n /** The environment: `MOSTRA_OFFLINE`, proxies, Playwright's download mirror. */\n readonly env?: Environment | undefined;\n /** Gives up the browser's download. */\n readonly signal?: AbortSignal | undefined;\n /** Each step as it starts. */\n readonly onStep?: ((step: SetupStep) => void) | undefined;\n /** Skip checking the files, for a tree the caller checked a moment ago. */\n readonly filesChecked?: boolean | undefined;\n}\n\n/** The directory Playwright's browsers live in, inside a bundle. */\nexport function browsersDir(root: string): string {\n return join(root, \"browsers\");\n}\n\n/** Whether `MOSTRA_OFFLINE` says Mostra is offline: any value but empty, `0`, `false` or `no`. */\nexport function offline(env: Environment): boolean {\n const value = env[\"MOSTRA_OFFLINE\"]?.trim().toLowerCase();\n return (\n value !== undefined && value !== \"\" && value !== \"0\" && value !== \"false\" && value !== \"no\"\n );\n}\n\nfunction invalid(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_ENV_BUNDLE_INVALID\", { message }));\n}\n\n/** Reads `bundle.json` at `root`. Throws `MOSTRA_ENV_BUNDLE_INVALID` when it isn't a bundle's. */\nexport async function readBundle(root: string): Promise<Bundle> {\n let text: string;\n try {\n text = await readFile(join(root, \"bundle.json\"), \"utf8\");\n } catch (error) {\n throw invalid(`${root} has no readable bundle.json (${(error as Error).message}).`);\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n throw invalid(`${join(root, \"bundle.json\")} isn't JSON.`);\n }\n const result = BundleInfo.safeParse(parsed);\n if (!result.success) throw invalid(`${join(root, \"bundle.json\")} isn't a runtime bundle's.`);\n const info = result.data;\n const paths = [\n info.node.path,\n ...Object.values(info.entries),\n info.files.path,\n info.browser.installer,\n ];\n if (!paths.every(safeRelative))\n throw invalid(`${join(root, \"bundle.json\")} names a path outside the bundle.`);\n return { root, info };\n}\n\n/**\n * The bundle's real path: links followed, Windows' short names written out, the case as the file\n * system keeps it. A Windows bundle's junctions point into it, and its marker names it.\n */\nexport function realRoot(root: string): string {\n return realpathSync.native(root);\n}\n\n/**\n * The setup marker, when it describes exactly this bundle. A Windows bundle's marker must also\n * name the root it sits at now: its junctions point into the root setup ran at, so a bundle moved\n * or copied since is set up again, which makes them afresh (D153).\n */\nexport async function readSetup(bundle: Bundle): Promise<BundleSetup | undefined> {\n try {\n const marker = BundleSetup.parse(\n JSON.parse(await readFile(join(bundle.root, BUNDLE_SETUP_MARKER), \"utf8\")),\n );\n const { info } = bundle;\n const here = isWindowsBundle(info.platform) ? marker.root === realRoot(bundle.root) : true;\n return here &&\n marker.files === info.files.sha256 &&\n marker.version === info.version &&\n marker.platform === info.platform &&\n marker.browser.revision === info.browser.revision\n ? marker\n : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** What `checkTree` may find besides the listed files: the bundle's own records and browsers. */\nexport function setupExtras(path: string): boolean {\n return (\n path === \"bundle.json\" ||\n path === \"files.json\" ||\n path === \"browsers\" ||\n path.startsWith(\"browsers/\") ||\n path === BUNDLE_SETUP_MARKER ||\n path.startsWith(`${BUNDLE_SETUP_MARKER}.tmp-`)\n );\n}\n\n/** The bundle's `files.json`, once its SHA-256 is the one `bundle.json` pins. */\nasync function readManifest(bundle: Bundle): Promise<BundleFiles> {\n const { root, info } = bundle;\n const listing = join(root, info.files.path);\n const { sha256 } = await hashFile(listing).catch(() => ({ sha256: \"\" }));\n if (sha256 !== info.files.sha256) {\n throw invalid(`${info.files.path} doesn't match the SHA-256 that bundle.json pins.`);\n }\n const manifest = BundleFiles.safeParse(JSON.parse(await readFile(listing, \"utf8\")));\n if (!manifest.success) throw invalid(`${info.files.path} isn't a bundle's file list.`);\n return manifest.data;\n}\n\n/**\n * Makes a Windows bundle's links, each a junction at the bundle's real path (D153); nothing for\n * any other bundle, whose archive carries its links. Throws `MOSTRA_ENV_BUNDLE_INVALID` for a link\n * the bundle can't have.\n */\nexport async function makeLinks(bundle: Bundle, read?: BundleFiles): Promise<void> {\n if (!isWindowsBundle(bundle.info.platform)) return;\n const manifest = read ?? (await readManifest(bundle));\n try {\n await makeJunctions(realRoot(bundle.root), manifest);\n } catch (error) {\n if (error instanceof LinkRefused) throw invalid(`The runtime bundle's links: ${error.message}`);\n throw error;\n }\n}\n\n/**\n * Checks the bundle's files; throws `MOSTRA_ENV_BUNDLE_INVALID` naming what differs. With\n * `links: false` the files alone are checked (a Windows bundle before `makeLinks` made its junctions).\n */\nexport async function checkFiles(\n bundle: Bundle,\n options: { readonly links?: boolean; readonly manifest?: BundleFiles } = {},\n): Promise<void> {\n const { root, info } = bundle;\n const manifest = options.manifest ?? (await readManifest(bundle));\n const problems = await checkTree(root, manifest, {\n allowExtra: setupExtras,\n links: options.links ?? true,\n });\n if (problems.length > 0) {\n throw invalid(\n `Mostra ${info.version}'s runtime bundle for ${info.platform} differs from its file list: ${problems.join(\"; \")}.`,\n );\n }\n}\n\n/** The browser files that differ from the pin, relative to `browsers/`. */\nexport async function checkBrowser(bundle: Bundle): Promise<readonly string[]> {\n const problems = await checkTree(\n browsersDir(bundle.root),\n { schemaVersion: 1, files: bundle.info.browser.files, links: [] },\n // Playwright's own markers, its `.links` registry and any other browser it fetched.\n { allowExtra: () => true },\n ).catch((error: unknown) => [`browsers: ${(error as Error).message}`]);\n return problems;\n}\n\n/** The environment the browser install runs in: proxies and Playwright's mirror pass through. */\nfunction installEnvironment(bundle: Bundle, env: Environment): NodeJS.ProcessEnv {\n const out: Record<string, string> = {};\n for (const [name, value] of Object.entries(env)) {\n if (value !== undefined && !name.startsWith(\"MOSTRA_\") && name !== \"PLAYWRIGHT_BROWSERS_PATH\")\n out[name] = value;\n }\n out[\"PLAYWRIGHT_BROWSERS_PATH\"] = browsersDir(bundle.root);\n return childEnvironment(out);\n}\n\n/** The variables whose URLs may carry credentials the browser's fetch uses. */\nconst CREDENTIAL_URLS = [\n \"PLAYWRIGHT_DOWNLOAD_HOST\",\n \"HTTPS_PROXY\",\n \"https_proxy\",\n \"HTTP_PROXY\",\n \"http_proxy\",\n \"ALL_PROXY\",\n \"all_proxy\",\n];\n\n/** `text` without URLs' credentials or queries, and without any password `env`'s URLs carry. */\nexport function scrubSecrets(text: string, env: Environment): string {\n let out = scrubUrls(text);\n for (const name of CREDENTIAL_URLS) {\n const value = env[name];\n if (!value) continue;\n // A proxy is often written without a scheme (`user:pass@host:3128`), which `URL` would read\n // as the scheme `user:`.\n const spelled = value.includes(\"://\") ? value : `http://${value}`;\n const parsed = URL.canParse(spelled) ? new URL(spelled) : undefined;\n for (const secret of [parsed?.password, parsed?.username]) {\n if (!secret) continue;\n for (const form of new Set([secret, decodeURIComponent(secret)]))\n if (form.length >= 3) out = out.split(form).join(\"***\");\n }\n }\n return out;\n}\n\n/** Runs the bundle's Playwright to fetch the pinned browser; at most 15 minutes. */\nasync function installBrowser(bundle: Bundle, options: SetupOptions): Promise<void> {\n const { root, info } = bundle;\n const output: string[] = [];\n const code = await new Promise<number | string>((resolve) => {\n const child = spawn(\n join(root, info.node.path),\n [join(root, info.browser.installer), \"install\", \"chromium-headless-shell\"],\n {\n cwd: root,\n env: installEnvironment(bundle, options.env ?? process.env),\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n windowsHide: true,\n ...(options.signal ? { signal: options.signal } : {}),\n timeout: 15 * 60_000,\n },\n );\n const keep = (chunk: Buffer): void => {\n output.push(chunk.toString(\"utf8\"));\n if (output.length > 40) output.shift();\n };\n child.stdout.on(\"data\", keep);\n child.stderr.on(\"data\", keep);\n child.on(\"error\", (error) => resolve(error.message));\n child.on(\"close\", (exit, signal) => resolve(exit ?? signal ?? \"unknown\"));\n });\n if (code === 0) return;\n // Playwright prints the URLs it fetches, and a mirror's or proxy's may carry credentials\n // (Opus review finding 3): every URL is reduced to its printable form, and any password the\n // environment names is removed wherever it appears.\n const tail = scrubSecrets(\n output.join(\"\").trim().split(\"\\n\").slice(-6).join(\" | \"),\n options.env ?? process.env,\n );\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_DOWNLOAD_FAILED\", {\n message: `Fetching the verify browser (${info.browser.name} ${info.browser.browserVersion}) failed (${code}): ${tail}`,\n }),\n );\n}\n\n/**\n * Makes the bundle at `root` ready: checks its files, fetches and checks the browser when it is\n * missing or differs, and writes `.mostra-setup.json`. Idempotent: a ready bundle returns its\n * marker after the checks. Throws `MOSTRA_ENV_BUNDLE_INVALID`, `MOSTRA_ENV_BUNDLE_UNAVAILABLE`\n * (offline with no browser) or `MOSTRA_ENV_BUNDLE_DOWNLOAD_FAILED`.\n */\nexport async function setupBundle(root: string, options: SetupOptions = {}): Promise<BundleSetup> {\n const env = options.env ?? process.env;\n const bundle = await readBundle(root);\n // A Windows bundle's junctions are made where it sits now, each read back as it is made; a\n // tree checked a moment ago (`filesChecked`, before the cache's rename) needs nothing more.\n // `files.json` is read and checked against its pin once, for both steps (Opus review of\n // WP-W3, finding 9): it lists every file of the bundle and is large.\n const windows = isWindowsBundle(bundle.info.platform);\n const manifest = windows || !options.filesChecked ? await readManifest(bundle) : undefined;\n await makeLinks(bundle, manifest);\n if (!options.filesChecked) {\n options.onStep?.(\"files\");\n await checkFiles(bundle, manifest ? { manifest } : {});\n }\n options.onStep?.(\"browser\");\n if ((await checkBrowser(bundle)).length > 0) {\n if (offline(env)) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_UNAVAILABLE\", {\n message: `The runtime bundle at ${root} has no verify browser yet, and MOSTRA_OFFLINE keeps Mostra from fetching it.`,\n }),\n );\n }\n // Fresh, never over what's there: a directory that differs from the pin may still carry\n // Playwright's \"installation complete\" marker, and Playwright would then fetch nothing.\n await rm(browsersDir(root), { recursive: true, force: true });\n await installBrowser(bundle, options);\n const problems = await checkBrowser(bundle);\n if (problems.length > 0) {\n throw invalid(\n `The verify browser Playwright fetched differs from the bundle's pin: ${problems.join(\"; \")}.`,\n );\n }\n }\n const marker: BundleSetup = {\n schemaVersion: 1,\n version: bundle.info.version,\n platform: bundle.info.platform,\n files: bundle.info.files.sha256,\n browser: { revision: bundle.info.browser.revision },\n at: new Date().toISOString(),\n root: realRoot(root),\n };\n const temporary = join(root, `${BUNDLE_SETUP_MARKER}.tmp-${process.pid}`);\n await writeFile(temporary, `${JSON.stringify(marker, null, 2)}\\n`);\n await rename(temporary, join(root, BUNDLE_SETUP_MARKER));\n return marker;\n}\n","/**\n * The local cache of runtime bundles (RT-01): one directory per archive digest, so a bundle is\n * found by what it is, not by what it's called. A bundle enters the cache only through\n * {@link installPinned}: downloaded against its pin, extracted into a temporary directory, its\n * files checked, renamed into place, its browser fetched, and only then marked ready. Concurrent\n * installers of one bundle share a lock, so it is downloaded once; a crash leaves a temporary\n * directory the next install removes, never a half-ready bundle.\n */\nimport { randomBytes } from \"node:crypto\";\nimport {\n link,\n mkdir,\n open,\n readdir,\n readFile,\n rename,\n rm,\n stat,\n statfs,\n utimes,\n} from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join, posix, resolve, win32 } from \"node:path\";\nimport {\n type BundleAsset,\n BundleAsset as BundleAssetSchema,\n type BundlePins,\n type BundlePlatform,\n bundleAssetName,\n createDiagnostic,\n isWindowsBundle,\n RpcError,\n} from \"@mostra/protocol\";\nimport { type DownloadProgress, download } from \"./download.ts\";\nimport { extractBundle } from \"./extract.ts\";\nimport {\n type Bundle,\n checkFiles,\n type Environment,\n offline,\n readBundle,\n readSetup,\n type SetupStep,\n setupBundle,\n} from \"./setup.ts\";\n\n/**\n * Where the cache is: `MOSTRA_CACHE_DIR`, else the platform's per-user cache directory:\n * `~/Library/Caches/mostra` on macOS, `%LOCALAPPDATA%\\mostra-cache` on Windows (beside the home,\n * `%LOCALAPPDATA%\\mostra`, as npm keeps `npm-cache`), `${XDG_CACHE_HOME:-~/.cache}/mostra` on\n * Linux.\n */\nexport function cacheRoot(env: Environment, platform: string = process.platform): string {\n const override = env[\"MOSTRA_CACHE_DIR\"];\n if (override) return resolve(override);\n if (platform === \"win32\") {\n const local =\n env[\"LOCALAPPDATA\"] || win32.join(env[\"USERPROFILE\"] || homedir(), \"AppData\", \"Local\");\n return win32.join(local, \"mostra-cache\");\n }\n // POSIX paths, whatever system computes them (`platform` is the one the cache is for).\n const home = env[\"HOME\"] || homedir();\n if (platform === \"darwin\") return posix.join(home, \"Library\", \"Caches\", \"mostra\");\n const xdg = env[\"XDG_CACHE_HOME\"];\n return posix.join(xdg?.startsWith(\"/\") ? xdg : posix.join(home, \".cache\"), \"mostra\");\n}\n\n/** The directory a bundle with this archive digest lives in. */\nexport function bundleDir(env: Environment, sha256: string): string {\n return join(cacheRoot(env), \"bundles\", sha256);\n}\n\n/** What an install reports while it works. */\nexport type InstallProgress =\n | ({ readonly step: \"download\" } & DownloadProgress)\n | { readonly step: \"extract\" | \"lock\" }\n | { readonly step: SetupStep };\n\n/** Options of {@link installPinned}. */\nexport interface InstallOptions {\n /** The environment: the cache, mirror and offline variables, proxies. */\n readonly env: Environment;\n /** The platform whose archive to install. */\n readonly platform: BundlePlatform;\n /** Gives up the install; nothing partial is kept. */\n readonly signal?: AbortSignal | undefined;\n /** Each step, and the bytes received while downloading. */\n readonly onProgress?: ((progress: InstallProgress) => void) | undefined;\n}\n\n/** The space an install needs beyond the archive and its files: the browser and some margin. */\nconst BROWSER_ALLOWANCE = 500 * 1024 * 1024;\n\n/**\n * The pinned bundle for this platform, ready to run: from the cache when it is there and ready,\n * else installed. `MOSTRA_BUNDLE_MIRROR` replaces the release URL (files keep their names).\n */\nexport async function installPinned(pins: BundlePins, options: InstallOptions): Promise<Bundle> {\n const asset = pins.assets[options.platform];\n // Checked before any I/O: the asset's name becomes a path in the cache's scratch directory and\n // its digest the bundle's directory (Opus review finding 8), so the asset must be well-formed\n // and named exactly as its release's archive for this platform.\n if (\n asset !== undefined &&\n (!BundleAssetSchema.safeParse(asset).success ||\n asset.file !== bundleAssetName(pins.version, options.platform))\n ) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_INVALID\", {\n message: `The pins name ${JSON.stringify(asset.file)} for ${options.platform}, not Mostra ${pins.version}'s archive ${bundleAssetName(pins.version, options.platform)}.`,\n }),\n );\n }\n if (asset === undefined) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_UNAVAILABLE\", {\n message: `Mostra ${pins.version} has no runtime bundle for ${options.platform}.`,\n }),\n );\n }\n const dir = bundleDir(options.env, asset.sha256);\n const ready = await readyAt(dir);\n if (ready) return ready;\n if (offline(options.env)) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_UNAVAILABLE\", {\n message: `Mostra ${pins.version}'s runtime bundle isn't in the cache (${dir}), and MOSTRA_OFFLINE keeps Mostra from fetching it.`,\n }),\n );\n }\n const bundles = join(cacheRoot(options.env), \"bundles\");\n await mkdir(bundles, { recursive: true, mode: 0o700 });\n options.onProgress?.({ step: \"lock\" });\n const release = await lock(join(bundles, `${asset.sha256}.lock`), options.signal);\n try {\n const raced = await readyAt(dir);\n if (raced) return raced;\n await sweep(bundles);\n if (await exists(dir)) {\n // A bundle whose setup didn't finish (no network for the browser, a crash). Only its own\n // files decide whether it is downloaded afresh: a file that differs from the pins can't be\n // repaired in place, but the browser can be fetched again, and downloading 200 MB again\n // never changes what Playwright serves (Opus review finding 5). Anything else, such as a\n // permission error, is thrown: it says nothing about the bundle, so nothing is deleted.\n if (await filesIntact(dir)) return await finish(dir, { ...options, filesChecked: true });\n await rm(dir, { recursive: true, force: true });\n }\n await fetchInto(pins, asset, dir, bundles, options);\n return await finish(dir, { ...options, filesChecked: true });\n } finally {\n await release();\n }\n}\n\n/**\n * Whether the bundle at `dir` holds exactly what its `files.json` lists. `false` only for\n * `MOSTRA_ENV_BUNDLE_INVALID` (a missing or changed file, a `bundle.json` that doesn't read);\n * every other error is thrown.\n */\nasync function filesIntact(dir: string): Promise<boolean> {\n try {\n const bundle = await readBundle(dir);\n // A Windows bundle's junctions are made by setup, after this (D153).\n await checkFiles(bundle, { links: !isWindowsBundle(bundle.info.platform) });\n return true;\n } catch (error) {\n if (error instanceof RpcError && error.diagnostic.code === \"MOSTRA_ENV_BUNDLE_INVALID\")\n return false;\n throw error;\n }\n}\n\n/** The bundle at `dir` when it exists and its setup marker matches it. */\nasync function readyAt(dir: string): Promise<Bundle | undefined> {\n const bundle = await readBundle(dir).catch(() => undefined);\n if (bundle === undefined) return undefined;\n return (await readSetup(bundle)) ? bundle : undefined;\n}\n\nasync function finish(\n dir: string,\n options: InstallOptions & { readonly filesChecked?: boolean },\n): Promise<Bundle> {\n await setupBundle(dir, {\n env: options.env,\n signal: options.signal,\n filesChecked: options.filesChecked,\n onStep: (step) => options.onProgress?.({ step }),\n });\n return readBundle(dir);\n}\n\n/** Downloads, extracts and checks the archive, then renames it into `dir`. */\nasync function fetchInto(\n pins: BundlePins,\n asset: BundleAsset,\n dir: string,\n bundles: string,\n options: InstallOptions,\n): Promise<void> {\n await requireSpace(bundles, asset);\n const scratch = join(bundles, `.tmp-${process.pid}-${randomBytes(6).toString(\"hex\")}`);\n await mkdir(scratch, { mode: 0o700 });\n try {\n const archive = join(scratch, asset.file);\n const base = options.env[\"MOSTRA_BUNDLE_MIRROR\"] || pins.release;\n const url = `${withoutTrailingSlashes(base)}/${encodeURIComponent(asset.file)}`;\n await download(url, archive, asset, {\n env: options.env,\n signal: options.signal,\n onProgress: (progress) => options.onProgress?.({ step: \"download\", ...progress }),\n });\n options.onProgress?.({ step: \"extract\" });\n const root = join(scratch, \"root\");\n await mkdir(root);\n const top = asset.file.replace(/\\.tar\\.gz$/, \"\");\n if (top !== bundleAssetName(pins.version, options.platform).replace(/\\.tar\\.gz$/, \"\")) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_INVALID\", {\n message: `The pinned archive ${asset.file} isn't Mostra ${pins.version}'s bundle for ${options.platform}.`,\n }),\n );\n }\n // A Windows archive holds no links (D153): its junctions are made once it is in place.\n const windows = isWindowsBundle(options.platform);\n await extractBundle(archive, root, top, { links: windows ? \"refuse\" : \"keep\" });\n await rm(archive, { force: true });\n const bundle = await readBundle(root);\n if (bundle.info.version !== pins.version || bundle.info.platform !== options.platform) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_INVALID\", {\n message: `The archive holds Mostra ${bundle.info.version} for ${bundle.info.platform}, not ${pins.version} for ${options.platform}.`,\n }),\n );\n }\n options.onProgress?.({ step: \"files\" });\n await checkFiles(bundle, { links: !windows });\n try {\n await renameIntoPlace(root, dir);\n } catch (error) {\n // Another installer finished first (the lock is an optimization, never what correctness\n // rests on): its directory is used, whose files it checked before renaming them into place.\n // Windows refuses a rename over an existing directory with EPERM.\n const code = (error as NodeJS.ErrnoException).code;\n const taken = code === \"ENOTEMPTY\" || code === \"EEXIST\" || code === \"EPERM\";\n if (!taken || !(await exists(dir))) throw error;\n }\n } finally {\n // Windows may hold the files a moment (an antivirus scan); a scratch directory left anyway\n // is removed by the next install's sweep.\n await rm(scratch, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }).catch(\n () => undefined,\n );\n }\n}\n\n/**\n * Renames `from` to `to`. On Windows a file that an antivirus scan or the indexer holds for a\n * moment refuses the rename (EPERM, EACCES, EBUSY) though nothing is wrong, so the rename is\n * tried again with backoff for up to 3 s, as the runtime's renames are (D150 item 8), and never\n * turned into a copy; a refusal that lasts is thrown, and EPERM over an existing directory with it.\n */\nasync function renameIntoPlace(from: string, to: string): Promise<void> {\n const deadline = Date.now() + 3000;\n for (let wait = 25; ; wait = Math.min(wait * 2, 400)) {\n try {\n await rename(from, to);\n return;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n const held = code === \"EPERM\" || code === \"EACCES\" || code === \"EBUSY\";\n if (process.platform !== \"win32\" || !held || Date.now() > deadline || (await exists(to)))\n throw error;\n await new Promise((done) => setTimeout(done, wait));\n }\n }\n}\n\n/** Fails early when the cache's file system can't hold the bundle. */\nasync function requireSpace(dir: string, asset: BundleAsset): Promise<void> {\n const fs = await statfs(dir).catch(() => undefined);\n if (fs === undefined) return;\n const free = Number(fs.bavail) * Number(fs.bsize);\n const needed = asset.size + asset.unpackedSize + BROWSER_ALLOWANCE;\n if (free < needed) {\n const gib = (bytes: number): string => `${(bytes / 1024 ** 3).toFixed(1)} GiB`;\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_DOWNLOAD_FAILED\", {\n message: `The runtime bundle needs about ${gib(needed)} free in ${dir}, and ${gib(free)} is free (the disk is full).`,\n }),\n );\n }\n}\n\n/** Removes temporary directories an interrupted install left, when their process is gone. */\nasync function sweep(bundles: string): Promise<void> {\n for (const name of await readdir(bundles).catch(() => [] as string[])) {\n const match = /^\\.tmp-(\\d+)-/.exec(name);\n if (match && !alive(Number(match[1]))) {\n await rm(join(bundles, name), { recursive: true, force: true });\n }\n }\n}\n\nasync function exists(path: string): Promise<boolean> {\n return stat(path).then(\n () => true,\n () => false,\n );\n}\n\nfunction alive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\n/** How old a lock may get before another installer takes it over whatever its owner. */\nconst STALE_LOCK_MS = 60 * 60_000;\n/**\n * How often a held lock is touched, so an install longer than {@link STALE_LOCK_MS} (a slow\n * network, a large browser) is never taken from its live owner (Opus review of WP-12, finding 10).\n */\nconst LOCK_TOUCH_MS = 60_000;\n\n/** `url` without trailing slashes, in linear time (a regex would be quadratic on many slashes). */\nfunction withoutTrailingSlashes(url: string): string {\n let end = url.length;\n while (end > 0 && url[end - 1] === \"/\") end -= 1;\n return url.slice(0, end);\n}\n\n/** A lock judged stale: the file judged, by its identity and what it held. */\nexport interface JudgedLock {\n readonly ino: number;\n readonly dev: number;\n readonly text: string;\n}\n\n/**\n * Judges the lock at `path` through one descriptor: `gone`, `live`, or stale (its owner gone, or\n * older than an hour) with what identifies the file judged.\n */\nexport async function judgeLock(path: string): Promise<\"gone\" | \"live\" | JudgedLock> {\n let handle: Awaited<ReturnType<typeof open>>;\n try {\n handle = await open(path, \"r\");\n } catch {\n return \"gone\";\n }\n try {\n const info = await handle.stat();\n const text = await handle.readFile(\"utf8\");\n const owner = Number.parseInt(text, 10);\n const stale =\n Date.now() - info.mtimeMs > STALE_LOCK_MS ||\n (Number.isInteger(owner) && owner > 0 && !alive(owner));\n return stale ? { ino: info.ino, dev: info.dev, text } : \"live\";\n } finally {\n await handle.close();\n }\n}\n\n/**\n * Moves the lock at `path` aside and removes it only if it is the file `judged` describes, by\n * identity and by contents: a fresh lock another installer took in between is put back (or, if a\n * third took one meanwhile, left to the next round). The contents matter because a file system may\n * give a new file the number of one just removed (ext4 does at once), and each lock holds its\n * owner's PID and its own token (MT-02).\n */\nexport async function removeJudged(path: string, judged: JudgedLock): Promise<void> {\n const aside = `${path}.stale-${randomBytes(6).toString(\"hex\")}`;\n try {\n await rename(path, aside);\n } catch {\n return; // someone else moved or removed it\n }\n // Its identity and contents through one descriptor, so both describe the same file.\n let same = false;\n const handle = await open(aside, \"r\").catch(() => undefined);\n if (handle) {\n try {\n const moved = await handle.stat();\n const text = await handle.readFile(\"utf8\");\n same = moved.ino === judged.ino && moved.dev === judged.dev && text === judged.text;\n } catch {\n // Unreadable: not provably the file judged, so it is put back.\n } finally {\n await handle.close();\n }\n }\n // Not the file judged stale: a fresh lock. Put it back unless a newer one exists.\n if (!same) await link(aside, path).catch(() => undefined);\n await rm(aside, { force: true });\n}\n\n/**\n * Removes the lock at `path` when it is stale and says whether it may be taken now. The lock only\n * saves a second download; the scratch directory and its rename keep the cache correct whatever\n * happens here.\n */\nasync function takeOverIfStale(path: string): Promise<boolean> {\n const judged = await judgeLock(path);\n if (judged === \"gone\") return true; // gone already: try to take it\n if (judged === \"live\") return false;\n await removeJudged(path, judged);\n return true;\n}\n\n/**\n * Takes the install lock at `path`: an exclusive create holding the owner's PID. A lock whose\n * owner is gone, or older than an hour, is taken over; otherwise the caller waits for it.\n */\nasync function lock(path: string, signal: AbortSignal | undefined): Promise<() => Promise<void>> {\n const token = randomBytes(8).toString(\"hex\");\n for (;;) {\n signal?.throwIfAborted();\n try {\n const handle = await open(path, \"wx\", 0o600);\n await handle.writeFile(`${process.pid} ${token}\\n`);\n await handle.close();\n const touch = setInterval(() => {\n void readFile(path, \"utf8\")\n .then((text) => {\n if (text.includes(token)) return utimes(path, new Date(), new Date());\n return undefined;\n })\n .catch(() => undefined);\n }, LOCK_TOUCH_MS);\n touch.unref();\n // Released by moving it aside and removing it only if it is still this installer's own.\n return async () => {\n clearInterval(touch);\n const aside = `${path}.done-${randomBytes(6).toString(\"hex\")}`;\n if (\n !(await rename(path, aside).then(\n () => true,\n () => false,\n ))\n )\n return;\n const text = await readFile(aside, \"utf8\").catch(() => \"\");\n if (!text.includes(token)) await link(aside, path).catch(() => undefined);\n await rm(aside, { force: true });\n };\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n }\n if (await takeOverIfStale(path)) continue;\n await new Promise((done) => setTimeout(done, 250));\n }\n}\n","/**\n * Which runtime bundle this machine takes (RT-01, RT-12, D35, D146): one per operating system and\n * architecture of v1 (macOS, glibc Linux and Windows, each on x64 and arm64). Anything else fails\n * closed before a download starts.\n */\nimport {\n BUNDLE_PLATFORMS,\n type BundlePlatform,\n createDiagnostic,\n RpcError,\n} from \"@mostra/protocol\";\n\n/** What the platform check reads: the running process by default. */\nexport interface PlatformFacts {\n /** `process.platform`. */\n readonly platform: string;\n /** `process.arch`. */\n readonly arch: string;\n /** The glibc release on Linux, `undefined` on musl or elsewhere. */\n readonly glibc?: string | undefined;\n}\n\n/** What {@link glibcRuntime} needs of `process.report`. */\ninterface Reporter {\n /** Node.js 22.13 and 23.3 or later; `@types/node` 24.19 doesn't declare it yet. */\n excludeNetwork?: boolean;\n getReport(): object;\n}\n\n/**\n * The glibc release Node.js reports, read from its diagnostic report's header. The report runs in\n * the caller's process (a host's server, say) and by default resolves the name of every open TCP\n * handle, synchronously; with `excludeNetwork` it does none of that (Opus review finding 4), as\n * detect-libc does. The setting is restored after.\n */\nexport function glibcRuntime(report: Reporter | undefined): string | undefined {\n if (report === undefined) return undefined;\n const before = report.excludeNetwork ?? false;\n report.excludeNetwork = true;\n try {\n return (report.getReport() as { header?: { glibcVersionRuntime?: string } }).header\n ?.glibcVersionRuntime;\n } finally {\n report.excludeNetwork = before;\n }\n}\n\nlet facts: PlatformFacts | undefined;\n\n/** The facts of the running process, read once. */\nexport function currentPlatform(): PlatformFacts {\n facts ??=\n process.platform === \"linux\"\n ? { platform: process.platform, arch: process.arch, glibc: glibcRuntime(process.report) }\n : { platform: process.platform, arch: process.arch };\n return facts;\n}\n\n/**\n * The bundle platform for these facts. Throws `MOSTRA_PLATFORM_UNSUPPORTED` for other systems and\n * architectures and for Linux without glibc, whose libraries the bundle's Node.js and browser need.\n */\nexport function bundlePlatform(facts: PlatformFacts = currentPlatform()): BundlePlatform {\n const name = `${facts.platform}-${facts.arch}`;\n const known = (BUNDLE_PLATFORMS as readonly string[]).includes(name);\n if (known && facts.platform === \"linux\" && facts.glibc === undefined) {\n throw unsupported(\n `Mostra's Linux bundle needs glibc, and this system has none (musl, as on Alpine Linux); it supports macOS, glibc-based Linux and Windows on x64 and arm64.`,\n );\n }\n if (!known) {\n const label = facts.platform === \"win32\" ? `Windows (${name})` : name;\n throw unsupported(\n `Mostra doesn't run on ${label}; it supports macOS, Linux and Windows on x64 and arm64.`,\n );\n }\n return name as BundlePlatform;\n}\n\nfunction unsupported(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_PLATFORM_UNSUPPORTED\", { message }));\n}\n","/** The SDK's own package: its root directory and its release. */\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nlet found: { readonly root: string; readonly version: string } | undefined;\n\nfunction own(): { readonly root: string; readonly version: string } {\n if (found) return found;\n let dir = dirname(fileURLToPath(import.meta.url));\n for (;;) {\n try {\n const manifest = JSON.parse(readFileSync(join(dir, \"package.json\"), \"utf8\")) as {\n name?: string;\n version?: string;\n };\n if (manifest.name === \"@mostra/sdk\" && manifest.version) {\n found = { root: dir, version: manifest.version };\n return found;\n }\n } catch {\n // Keep looking upwards.\n }\n const parent = dirname(dir);\n if (parent === dir) throw new Error(\"Couldn't find @mostra/sdk's package.json.\");\n dir = parent;\n }\n}\n\n/** This SDK's release: the client version an SDK host reports by default. */\nexport function sdkVersion(): string {\n return own().version;\n}\n\n/** The SDK package's directory; `dist/bundles.json` lives under it in a release. */\nexport function packageRoot(): string {\n return own().root;\n}\n","/**\n * Which runtime a host runs (RT-01, D85). In order:\n *\n * 1. `bundle`, a directory the caller names (the SDK's option), then `MOSTRA_BUNDLE`;\n * 2. `MOSTRA_RUNTIME_BIN`, a `mostra-runtime` entry run with this process's Node (tests and\n * development);\n * 3. the bundle this package itself sits in (the CLI inside a bundle);\n * 4. the bundle this package's release pins (`bundles.json`), from the cache or downloaded;\n * 5. a development checkout's built runtime beside this package.\n *\n * Anything a bundle supplies is checked first: its setup marker must match it, or setup runs.\n */\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { BundlePins, createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport { type InstallProgress, installPinned } from \"./bundle/cache.ts\";\nimport {\n type Bundle,\n type Environment,\n readBundle,\n readSetup,\n type SetupStep,\n setupBundle,\n} from \"./bundle/setup.ts\";\nimport { bundlePlatform } from \"./platform.ts\";\nimport { packageRoot } from \"./version.ts\";\n\n/** A runtime to spawn: the Node.js to run it with and its entry points. */\nexport interface Runtime {\n /** How it was found. */\n readonly source: \"bundle\" | \"override\" | \"development\";\n /** The Node.js executable: the bundle's own, or this process's for the others. */\n readonly node: string;\n /** `mostra-runtime`'s entry (`host`, `daemon`, `service`). */\n readonly runtimeEntry: string;\n /** The `mostra` CLI's entry, when this runtime has one. */\n readonly cliEntry?: string;\n /** The bundle, when the runtime is one. */\n readonly bundle?: Bundle;\n}\n\n/** Options of {@link resolveRuntime}. */\nexport interface RuntimeOptions {\n /** An extracted bundle to use, ahead of everything else. */\n readonly bundle?: string | undefined;\n /** The environment: `MOSTRA_BUNDLE`, `MOSTRA_RUNTIME_BIN`, the cache's variables. */\n readonly env?: Environment | undefined;\n /** Gives up a download or setup. */\n readonly signal?: AbortSignal | undefined;\n /** Progress of a download or setup, for a person waiting (the CLI prints it on stderr). */\n readonly onProgress?: ((progress: InstallProgress) => void) | undefined;\n}\n\n/**\n * Where the pins are read from: `<package>/dist/bundles.json`, which the release writes before\n * publishing. `MOSTRA_TEST_BUNDLE_PINS` names another file only for a package that runs from a\n * development checkout (its real path outside any `node_modules`), where the tests use it: an\n * installed copy (npm's `node_modules`, or a bundle's `lib/node_modules`) ignores it, so a\n * variable leaked into a user's environment can't swap the pins npm's provenance covers (Opus\n * review finding 8).\n */\nexport function pinsFile(env: Environment, root: string): string {\n const override = env[\"MOSTRA_TEST_BUNDLE_PINS\"];\n // Either separator: a path spelled with `/` on Windows is still inside `node_modules`.\n const installed = root.split(/[\\\\/]/).includes(\"node_modules\");\n return override && !installed ? override : join(root, \"dist\", \"bundles.json\");\n}\n\n/** The pins this build carries: `dist/bundles.json` (a test override applies only in a development checkout). */\nexport function readPins(env: Environment): BundlePins | undefined {\n const file = pinsFile(env, packageRoot());\n if (!existsSync(file)) return undefined;\n let data: unknown;\n try {\n data = JSON.parse(readFileSync(file, \"utf8\"));\n } catch {\n data = undefined; // not JSON (or unreadable): the same refusal as a file of the wrong shape\n }\n const parsed = BundlePins.safeParse(data);\n if (!parsed.success) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_INVALID\", {\n message: `${file} isn't a release's bundle pins.`,\n }),\n );\n }\n return parsed.data;\n}\n\n/** The bundle this package was installed into, if any: `<root>/lib/node_modules/@mostra/sdk`. */\nexport function enclosingBundle(): string | undefined {\n const root = resolve(packageRoot(), \"..\", \"..\", \"..\", \"..\");\n return existsSync(join(root, \"bundle.json\")) &&\n existsSync(join(root, \"lib\", \"node_modules\", \"@mostra\", \"sdk\"))\n ? root\n : undefined;\n}\n\n/** The runtime described by a bundle, once it is set up. */\nasync function fromBundle(root: string, options: RuntimeOptions): Promise<Runtime> {\n let bundle = await readBundle(resolve(root));\n if (!(await readSetup(bundle))) {\n await setupBundle(bundle.root, {\n env: options.env,\n signal: options.signal,\n onStep: (step: SetupStep) => options.onProgress?.({ step }),\n });\n bundle = await readBundle(bundle.root);\n }\n return runtimeOf(bundle);\n}\n\n/** A bundle's entry points as a runtime. */\nexport function runtimeOf(bundle: Bundle): Runtime {\n const { root, info } = bundle;\n return {\n source: \"bundle\",\n node: join(root, info.node.path),\n runtimeEntry: join(root, info.entries.runtime),\n cliEntry: join(root, info.entries.cli),\n bundle,\n };\n}\n\n/** A development checkout's runtime: `packages/runtime/dist/bin.js` beside this package. */\nfunction development(): Runtime | undefined {\n const root = packageRoot();\n const entry = resolve(root, \"..\", \"runtime\", \"dist\", \"bin.js\");\n if (!existsSync(entry)) return undefined;\n const cli = resolve(root, \"..\", \"cli\", \"dist\", \"bin.js\");\n return {\n source: \"development\",\n node: process.execPath,\n runtimeEntry: entry,\n ...(existsSync(cli) ? { cliEntry: cli } : {}),\n };\n}\n\n/**\n * Finds the runtime to spawn, downloading and setting up the pinned bundle when nothing nearer\n * exists. Throws `MOSTRA_PLATFORM_UNSUPPORTED`, `MOSTRA_ENV_RUNTIME_MISSING` (a\n * `MOSTRA_RUNTIME_BIN` that doesn't exist), `MOSTRA_ENV_BUNDLE_UNAVAILABLE`,\n * `MOSTRA_ENV_BUNDLE_INVALID` or `MOSTRA_ENV_BUNDLE_DOWNLOAD_FAILED`.\n */\nexport async function resolveRuntime(options: RuntimeOptions = {}): Promise<Runtime> {\n const env = options.env ?? process.env;\n const named = options.bundle ?? (env[\"MOSTRA_BUNDLE\"] || undefined);\n if (named !== undefined) return fromBundle(named, { ...options, env });\n const override = env[\"MOSTRA_RUNTIME_BIN\"];\n if (override) {\n if (!existsSync(override)) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_RUNTIME_MISSING\", {\n message: `MOSTRA_RUNTIME_BIN names ${override}, which doesn't exist.`,\n }),\n );\n }\n return { source: \"override\", node: process.execPath, runtimeEntry: override };\n }\n const enclosing = enclosingBundle();\n if (enclosing !== undefined) return fromBundle(enclosing, { ...options, env });\n const pins = readPins(env);\n if (pins !== undefined) {\n const bundle = await installPinned(pins, {\n env,\n platform: bundlePlatform(),\n signal: options.signal,\n onProgress: options.onProgress,\n });\n return runtimeOf(bundle);\n }\n const checkout = development();\n if (checkout !== undefined) return checkout;\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_UNAVAILABLE\", {\n message:\n \"This build of @mostra/sdk pins no runtime bundle and has no runtime beside it; set MOSTRA_BUNDLE to an extracted bundle.\",\n }),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA4CA,IAAM,QAAN,cAAoB,MAAM,CAAC;;;;;;AAO3B,eAAsB,SACpB,KACA,MACA,UACA,UAA2B,CAAC,GACb;CACf,MAAM,WAAW,QAAQ,YAAY;CACrC,IAAI;CACJ,KAAK,IAAI,UAAU,GAAG,WAAW,UAAU,WACzC,IAAI;EACF,MAAM,SAAS,MAAM,KAAK,KAAK,MAAM,UAAU,OAAO;EACtD,IAAI,WAAW,SAAS,QACtB,MAAMA,UACJ,qBAAqB,UAAU,GAAG,EAAE,eAAe,OAAO,mBAAmB,SAAS,OAAO,EAC/F;EAEF;CACF,SAAS,OAAO;EACd,MAAM,GAAG,MAAM,EAAE,OAAO,KAAK,CAAC;EAC9B,OAAO;EACP,IAAI,iBAAiB,YAAY,iBAAiB,SAAS,QAAQ,QAAQ,SAAS;EACpF,IAAK,MAAgC,SAAS,UAAU;EACxD,IAAI,UAAU,UAAU,MAAM,MAAM,MAAO,MAAM,UAAU,IAAI,QAAQ,MAAM;CAC/E;CAEF,IAAI,gBAAgB,UAAU,MAAM;CACpC,IAAI,QAAQ,QAAQ,SAAS,MAAM,QAAQ,OAAO;CAClD,MAAM,IAAI,SACR,iBAAiB,qCAAqC,EACpD,SAAS,qBAAqB,UAAU,GAAG,EAAE,IAAI,UAAU,SAAS,IAAI,CAAC,IAC3E,CAAC,CACH;AACF;AAEA,eAAe,KACb,KACA,MACA,UACA,SACiB;CACjB,MAAM,OAAO,WAAW,QAAQ;CAChC,IAAI,WAAW;CACf,MAAM,UAAU,QAAQ,WAAW;CACnC,MAAM,aAAa,IAAI,gBAAgB;CACvC,MAAM,cAAoB,WAAW,MAAM,QAAQ,QAAQ,MAAM;CACjE,QAAQ,QAAQ,iBAAiB,S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WAAW,QAAQ,GACtB,MAAM,IAAI,SACR,iBAAiB,8BAA8B,EAC7C,SAAS,4BAA4B,SAAS,wBAChD,CAAC,CACH;EAEF,OAAO;GAAE,QAAQ;GAAY,MAAM,QAAQ;GAAU,cAAc;EAAS;CAC9E;CACA,MAAM,YAAY,gBAAgB;CAClC,IAAI,cAAc,KAAA,GAAW,OAAO,WAAW,WAAW;EAAE,GAAG;EAAS;CAAI,CAAC;CAC7E,MAAM,OAAO,SAAS,GAAG;CACzB,IAAI,SAAS,KAAA,GAOX,OAAO,UAAU,MANI,cAAc,MAAM;EACvC;EACA,UAAU,eAAe;EACzB,QAAQ,QAAQ;EAChB,YAAY,QAAQ;CACtB,CAAC,CACsB;CAEzB,MAAM,WAAW,YAAY;CAC7B,IAAI,aAAa,KAAA,GAAW,OAAO;CACnC,MAAM,IAAI,SACR,iBAAiB,iCAAiC,EAChD,SACE,2HACJ,CAAC,CACH;AACF"}
1
+ {"version":3,"file":"runtime-NiLgW1ED.js","names":["invalid","open","BundleAssetSchema"],"sources":["../src/bundle/download.ts","../src/bundle/extract.ts","../src/environment.ts","../src/bundle/tree.ts","../src/bundle/links.ts","../src/bundle/setup.ts","../src/bundle/cache.ts","../src/platform.ts","../src/version.ts","../src/runtime.ts"],"sourcesContent":["/**\n * Fetching a pinned archive (RT-01): streamed to disk while it is hashed, never longer than the\n * pin says, through the environment's proxy (`HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`), retried on\n * failures that a retry can cure, and checked against the pin before anyone reads it.\n */\nimport { createHash } from \"node:crypto\";\nimport { createReadStream, createWriteStream } from \"node:fs\";\nimport { rm } from \"node:fs/promises\";\nimport { Readable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport { fileURLToPath } from \"node:url\";\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport { EnvHttpProxyAgent, fetch } from \"undici\";\n\n/** What a download must match. */\nexport interface Expected {\n readonly sha256: string;\n readonly size: number;\n}\n\n/** Progress of one download, in bytes. */\nexport interface DownloadProgress {\n /** Bytes received so far. */\n readonly received: number;\n /** Bytes the pin says the archive has. */\n readonly total: number;\n}\n\n/** Options of {@link download}. */\nexport interface DownloadOptions {\n /**\n * The environment whose proxy settings apply (`HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, either\n * case): a host's own, never silently `process.env`'s. Default `process.env`.\n */\n readonly env?: Readonly<Record<string, string | undefined>> | undefined;\n readonly signal?: AbortSignal | undefined;\n readonly onProgress?: ((progress: DownloadProgress) => void) | undefined;\n /** How long the connection may stay silent. Default 60 s. */\n readonly stallMs?: number | undefined;\n /** Attempts in all, for failures a retry can cure. Default 3. */\n readonly attempts?: number | undefined;\n}\n\n/** A failure a retry won't cure (an HTTP 4xx other than 408 and 429, a wrong size or digest). */\nclass Final extends Error {}\n\n/**\n * Downloads `url` (`https:`, `http:` or `file:`) to `dest` and checks its size and SHA-256.\n * Throws `MOSTRA_ENV_BUNDLE_INVALID` when the bytes aren't the pinned ones and\n * `MOSTRA_ENV_BUNDLE_DOWNLOAD_FAILED` otherwise; `dest` never survives a failure.\n */\nexport async function download(\n url: string,\n dest: string,\n expected: Expected,\n options: DownloadOptions = {},\n): Promise<void> {\n const attempts = options.attempts ?? 3;\n let last: unknown;\n for (let attempt = 1; attempt <= attempts; attempt++) {\n try {\n const actual = await once(url, dest, expected, options);\n if (actual !== expected.sha256) {\n throw invalid(\n `The download from ${redactUrl(url)} has SHA-256 ${actual}, not the pinned ${expected.sha256}.`,\n );\n }\n return;\n } catch (error) {\n await rm(dest, { force: true });\n last = error;\n if (error instanceof RpcError || error instanceof Final || options.signal?.aborted) break;\n if ((error as NodeJS.ErrnoException).code === \"ENOSPC\") break;\n if (attempt < attempts) await delay(1000 * 4 ** (attempt - 1), options.signal);\n }\n }\n if (last instanceof RpcError) throw last;\n if (options.signal?.aborted) throw options.signal.reason;\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_DOWNLOAD_FAILED\", {\n message: `Couldn't download ${redactUrl(url)}: ${scrubUrls(describe(last))}`,\n }),\n );\n}\n\nasync function once(\n url: string,\n dest: string,\n expected: Expected,\n options: DownloadOptions,\n): Promise<string> {\n const hash = createHash(\"sha256\");\n let received = 0;\n const stallMs = options.stallMs ?? 60_000;\n const controller = new AbortController();\n const abort = (): void => controller.abort(options.signal?.reason);\n options.signal?.addEventListener(\"abort\", abort, { once: true });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const arm = (): void => {\n if (timer !== undefined) clearTimeout(timer);\n timer = setTimeout(\n () => controller.abort(new Error(`no data for ${stallMs / 1000} s`)),\n stallMs,\n );\n };\n try {\n arm();\n const body = await open(url, controller.signal, options.env ?? process.env);\n const counter = async function* (source: AsyncIterable<Uint8Array>) {\n for await (const chunk of source) {\n arm();\n received += chunk.length;\n if (received > expected.size) {\n throw invalid(\n `The download from ${redactUrl(url)} is larger than the pinned ${expected.size} bytes.`,\n );\n }\n hash.update(chunk);\n options.onProgress?.({ received, total: expected.size });\n yield chunk;\n }\n };\n await pipeline(body, counter, createWriteStream(dest, { mode: 0o600 }), {\n signal: controller.signal,\n });\n if (received !== expected.size) {\n throw invalid(\n `The download from ${redactUrl(url)} has ${received} bytes, not the pinned ${expected.size}.`,\n );\n }\n return hash.digest(\"hex\");\n } catch (error) {\n if (controller.signal.aborted && !(error instanceof RpcError)) {\n const reason: unknown = controller.signal.reason;\n throw reason instanceof Error ? reason : new Error(String(reason));\n }\n throw error;\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n options.signal?.removeEventListener(\"abort\", abort);\n }\n}\n\n/** The body of `url` as a stream. */\nasync function open(\n url: string,\n signal: AbortSignal,\n env: Readonly<Record<string, string | undefined>>,\n): Promise<AsyncIterable<Uint8Array>> {\n const parsed = new URL(url);\n if (parsed.protocol === \"file:\") {\n return createReadStream(fileURLToPath(parsed), { signal }) as AsyncIterable<Uint8Array>;\n }\n if (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") {\n throw new Final(`${parsed.protocol} URLs aren't supported`);\n }\n // fetch refuses a URL with credentials, so a mirror's (`https://user:pass@host/…`) travel as\n // Basic authorization, which fetch drops on a redirect to another origin.\n const headers: Record<string, string> = {\n \"user-agent\": \"mostra-sdk\",\n accept: \"application/octet-stream\",\n };\n if (parsed.username !== \"\" || parsed.password !== \"\") {\n const user = decodeURIComponent(parsed.username);\n const password = decodeURIComponent(parsed.password);\n headers[\"authorization\"] = `Basic ${Buffer.from(`${user}:${password}`).toString(\"base64\")}`;\n parsed.username = \"\";\n parsed.password = \"\";\n }\n const response = await fetch(parsed, {\n dispatcher: proxyAgent(env),\n redirect: \"follow\",\n signal,\n headers,\n });\n if (!response.ok || response.body === null) {\n const status = response.status;\n await response.body?.cancel().catch(() => undefined);\n const message = `HTTP ${status}${response.statusText ? ` ${response.statusText}` : \"\"}`;\n if (status >= 400 && status < 500 && status !== 408 && status !== 429) throw new Final(message);\n throw new Error(message);\n }\n return Readable.fromWeb(response.body as import(\"node:stream/web\").ReadableStream<Uint8Array>);\n}\n\nconst agents = new Map<string, EnvHttpProxyAgent>();\n/**\n * The agent for `env`'s `HTTPS_PROXY`, `HTTP_PROXY` and `NO_PROXY` (lowercase first, as curl\n * reads them), one per distinct setting. Each is passed explicitly, an empty one included, so\n * undici never falls back to `process.env` (GPT review finding 6).\n */\nfunction proxyAgent(env: Readonly<Record<string, string | undefined>>): EnvHttpProxyAgent {\n const settings = {\n httpProxy: env[\"http_proxy\"] ?? env[\"HTTP_PROXY\"] ?? \"\",\n httpsProxy: env[\"https_proxy\"] ?? env[\"HTTPS_PROXY\"] ?? \"\",\n noProxy: env[\"no_proxy\"] ?? env[\"NO_PROXY\"] ?? \"\",\n };\n const key = JSON.stringify(settings);\n let agent = agents.get(key);\n if (agent === undefined) {\n agent = new EnvHttpProxyAgent(settings);\n agents.set(key, agent);\n }\n return agent;\n}\n\n/**\n * `text` with every URL in it reduced to {@link redactUrl}'s form: an error from the network stack\n * repeats the URL it failed on, credentials, query and all (a mirror's or a proxy's), and a\n * diagnostic is printed (GPT review finding 2).\n */\nexport function scrubUrls(text: string): string {\n return text.replace(/\\b[a-z][a-z0-9+.-]*:\\/\\/[^\\s\"'<>()]+/gi, (url) => redactUrl(url));\n}\n\nfunction invalid(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_ENV_BUNDLE_INVALID\", { message }));\n}\n\n/** A URL without credentials or a query, safe to print. */\nexport function redactUrl(url: string): string {\n try {\n const parsed = new URL(url);\n parsed.username = \"\";\n parsed.password = \"\";\n parsed.search = \"\";\n parsed.hash = \"\";\n return parsed.toString();\n } catch {\n return \"(an invalid URL)\";\n }\n}\n\nfunction describe(error: unknown): string {\n if (!(error instanceof Error)) return String(error);\n const cause = (error as { cause?: unknown }).cause;\n const code = (cause as { code?: string } | undefined)?.code ?? (error as { code?: string }).code;\n return code !== undefined && !error.message.includes(code)\n ? `${error.message} (${code})`\n : error.message;\n}\n\nfunction delay(ms: number, signal: AbortSignal | undefined): Promise<void> {\n return new Promise((done) => {\n const timer = setTimeout(done, ms);\n signal?.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n done();\n },\n { once: true },\n );\n });\n}\n","/**\n * Unpacking a downloaded archive (RT-01) into a new, empty directory. Only regular files,\n * directories and symbolic links are accepted, all under the archive's one top directory, which is\n * stripped; an entry's path must be relative, with no `..`, `.` or empty part and no backslash\n * (nor, on Windows, a colon; node-tar reads a backslash there as a separator, so its parts are\n * judged as separate ones), and no path may appear twice. Links are made only after every file\n * and directory is written, and after every link's own directory, so no write and no link ever\n * goes through one. Setup then checks the whole tree\n * against the bundle's file list (`checkTree`), which refuses any file or link it doesn't list and\n * any link that leaves the bundle. A pinned archive's SHA-256 is checked before any of this. A\n * Windows archive holds no links at all (D153): one that does is refused, since its junctions are\n * made by setup, from `files.json`.\n *\n * The files are written synchronously as node-tar's parser reads them. node-tar's own `x` checks\n * and clobbers what each path already holds, and on Windows writes one entry at a time; into an\n * empty directory none of that is needed, and a first install wrote its ~50,000 files 4 to 10\n * times slower for it: 6 minutes on Windows arm64 (#88, VERIFIED_FACTS, MT-02).\n */\nimport { closeSync, createReadStream, mkdirSync, openSync, symlinkSync, writeSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport { Parser, type ReadEntry } from \"tar\";\n\nconst FILES = new Set([\"File\", \"OldFile\", \"ContiguousFile\"]);\n\n/** Options of {@link extractBundle}. */\nexport interface ExtractOptions {\n /** `keep` extracts symbolic links; `refuse` refuses an archive that has any (Windows'). */\n readonly links?: \"keep\" | \"refuse\";\n}\n\n/** An entry a bundle's archive never has, or an archive that doesn't read as a tar at all. */\nclass ArchiveRefused extends Error {}\n\n/**\n * Whether `error` is two of the archive's entries meeting where the file system names them as one\n * path: a file where a directory must go, a directory or file already there, names the file system\n * folds alike (`σ` and `ς`, `ß` and `ss`). The directory is new and only this extractor writes in\n * it, so these are never the disk's failure (the Opus review of MT-02).\n */\nfunction collides(error: unknown): boolean {\n const code = (error as NodeJS.ErrnoException).code;\n return code === \"EEXIST\" || code === \"ENOTDIR\" || code === \"EISDIR\";\n}\n\n/** Extracts `archive` (a `.tar.gz` with one top directory `top`) into the empty directory `into`. */\nexport async function extractBundle(\n archive: string,\n into: string,\n top: string,\n options: ExtractOptions = {},\n): Promise<void> {\n try {\n await unpack(archive, resolve(into), top, options.links === \"refuse\");\n } catch (error) {\n if (error instanceof ArchiveRefused) {\n throw new RpcError(createDiagnostic(\"MOSTRA_ENV_BUNDLE_INVALID\", { message: error.message }));\n }\n const code = (error as NodeJS.ErrnoException).code;\n // The file system failing (a full disk, a permission) isn't the archive's fault.\n if (typeof code === \"string\" && /^E[A-Z]+$/.test(code) && code !== \"EOF\") {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_DOWNLOAD_FAILED\", {\n message: `The runtime bundle couldn't be written to ${into}: ${(error as Error).message}${code === \"ENOSPC\" ? \" (the disk is full)\" : \"\"}`,\n }),\n );\n }\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_INVALID\", {\n message: `The runtime bundle's archive couldn't be read: ${(error as Error).message}`,\n }),\n );\n }\n}\n\n/** The path below `top` an entry names, as parts, or why it is refused. */\nexport function entryParts(path: string, top: string, windows: boolean): string[] | string {\n const parts = path.split(\"/\");\n if (parts[0] !== top) return \"it is outside the bundle's directory\";\n // A directory's name ends with a slash.\n if (parts.length > 1 && parts.at(-1) === \"\") parts.pop();\n const below = parts.slice(1);\n for (const part of below) {\n if (part === \"\" || part === \".\" || part === \"..\") return \"its path isn't a plain relative one\";\n if (part.includes(\"\\\\\") || (windows && part.includes(\":\"))) {\n return \"its path holds a character a bundle's paths never have\";\n }\n }\n return below;\n}\n\nasync function unpack(archive: string, root: string, top: string, refuseLinks: boolean) {\n const windows = process.platform === \"win32\";\n const seen = new Set<string>();\n const made = new Set<string>([root]);\n const links: { path: string; target: string }[] = [];\n const ensureDir = (dir: string): void => {\n if (made.has(dir)) return;\n mkdirSync(dir, { recursive: true, mode: 0o755 });\n for (let at = dir; !made.has(at); at = dirname(at)) made.add(at);\n };\n let failure: unknown;\n let open: number | undefined;\n const fail = (error: unknown): void => {\n failure ??= error;\n };\n const refuse = (path: string, type: string, why: string): void =>\n fail(\n new ArchiveRefused(\n `The runtime bundle's archive holds an entry a bundle never has: ${path} (${type}): ${why}.`,\n ),\n );\n\n const parser = new Parser({ strict: true });\n parser.on(\"entry\", (entry: ReadEntry) => {\n const type = String(entry.type);\n if (failure !== undefined) return entry.resume();\n const parts = entryParts(entry.path, top, windows);\n if (typeof parts === \"string\") {\n refuse(entry.path, type, parts);\n return entry.resume();\n }\n const path = parts.length === 0 ? root : join(root, ...parts);\n // Windows and macOS keep one file for names that differ only in case or (macOS) in Unicode\n // normalization, so those are the same path there.\n const key =\n windows || process.platform === \"darwin\" ? path.normalize(\"NFC\").toLowerCase() : path;\n if (parts.length > 0 && seen.has(key)) {\n refuse(entry.path, type, \"its path appears twice\");\n return entry.resume();\n }\n seen.add(key);\n try {\n if (type === \"Directory\") {\n entry.resume();\n ensureDir(path);\n } else if (type === \"SymbolicLink\" && parts.length > 0) {\n entry.resume();\n if (refuseLinks) refuse(entry.path, type, \"a Windows bundle's links are made by setup\");\n else if (!entry.linkpath) refuse(entry.path, type, \"it links to nothing\");\n else links.push({ path, target: entry.linkpath });\n } else if (FILES.has(type) && parts.length > 0) {\n ensureDir(dirname(path));\n // A new file only (`wx`): nothing that was there before, a link least of all, is written to.\n const fd = openSync(path, \"wx\", (entry.mode ?? 0) & 0o111 ? 0o755 : 0o644);\n open = fd;\n entry.on(\"data\", (chunk: Buffer) => {\n if (failure !== undefined) return;\n try {\n let at = 0;\n while (at < chunk.length) at += writeSync(fd, chunk, at);\n } catch (error) {\n fail(error);\n }\n });\n entry.on(\"end\", () => {\n open = undefined;\n try {\n closeSync(fd);\n } catch (error) {\n fail(error);\n }\n });\n } else {\n refuse(entry.path, type, \"a bundle holds only files, directories and links\");\n entry.resume();\n }\n } catch (error) {\n if (collides(error))\n refuse(entry.path, type, \"its path meets another entry's, as this file system names them\");\n else fail(error);\n entry.resume();\n }\n });\n // A parser error (a damaged header, a bad gzip stream) is the archive's: it settles the wait\n // rather than rejecting a promise nobody awaits yet.\n const ended = new Promise<void>((done) => {\n parser.on(\"end\", done);\n parser.on(\"error\", (error: Error) => {\n fail(new ArchiveRefused(`The runtime bundle's archive couldn't be read: ${error.message}`));\n done();\n });\n });\n try {\n for await (const chunk of createReadStream(archive, { highWaterMark: 1024 * 1024 })) {\n parser.write(chunk as Buffer);\n if (failure !== undefined) break;\n }\n if (failure === undefined) {\n parser.end();\n await ended;\n }\n } finally {\n if (open !== undefined) closeSync(open);\n }\n if (failure !== undefined) throw failure;\n // Every link's directory first, while no link exists: a link whose path another entry lies\n // beneath (another link included) then meets a real directory and is refused, and no directory is\n // ever made or reached through a link (the GPT review of MT-02).\n const refused = (path: string, why: string): ArchiveRefused =>\n new ArchiveRefused(\n `The runtime bundle's archive holds an entry a bundle never has: ${path} (SymbolicLink): ${why}.`,\n );\n for (const link of links) {\n try {\n ensureDir(dirname(link.path));\n } catch (error) {\n if (collides(error)) throw refused(link.path, \"it lies beneath a file\");\n throw error;\n }\n }\n for (const link of links) {\n try {\n symlinkSync(link.target, link.path);\n } catch (error) {\n // Its path is a directory other entries filled (the link would have been written through), or\n // a name the file system folds with another entry's.\n if (collides(error))\n throw refused(link.path, \"other entries are inside it, or meet its path\");\n throw error;\n }\n }\n}\n","/**\n * The environment of a process the SDK starts (the instance, the browser's fetch). A host may\n * give an environment of its own (`createMostra`'s `env`), and on Windows a program starts only\n * with the system's own variables: Node.js aborts without `SystemRoot`, which its random-number\n * source needs. So on Windows each of them this process has is added where the host's environment\n * lacks it, matched without case as Windows matches names (D150 item 9, D153). They name the\n * system's own folders and nothing of the user's secrets. Elsewhere the environment is the host's,\n * as it is.\n */\n/** An environment as a host gives it. */\ntype Environment = Readonly<Record<string, string | undefined>>;\n\n/** What Windows gives every program, which a child of the SDK keeps (D150 item 9). */\nconst WINDOWS_SYSTEM_VARIABLES: readonly string[] = [\n \"SystemRoot\",\n \"SystemDrive\",\n \"windir\",\n \"ComSpec\",\n \"PATHEXT\",\n \"TEMP\",\n \"TMP\",\n \"USERPROFILE\",\n \"HOMEDRIVE\",\n \"HOMEPATH\",\n \"APPDATA\",\n \"LOCALAPPDATA\",\n \"ProgramData\",\n \"ProgramFiles\",\n \"ProgramFiles(x86)\",\n \"ProgramW6432\",\n \"CommonProgramFiles\",\n \"CommonProgramFiles(x86)\",\n \"CommonProgramW6432\",\n \"USERNAME\",\n \"USERDOMAIN\",\n \"COMPUTERNAME\",\n \"OS\",\n \"NUMBER_OF_PROCESSORS\",\n \"PROCESSOR_ARCHITECTURE\",\n \"PROCESSOR_IDENTIFIER\",\n];\n\n/** `env` for a child process: on Windows with the system's own variables this process has. */\nexport function childEnvironment(\n env: Environment,\n options: { readonly platform?: string; readonly own?: Environment } = {},\n): NodeJS.ProcessEnv {\n const out: NodeJS.ProcessEnv = {};\n for (const [name, value] of Object.entries(env)) if (value !== undefined) out[name] = value;\n if ((options.platform ?? process.platform) !== \"win32\") return out;\n const own = options.own ?? process.env;\n const present = new Set(Object.keys(out).map((name) => name.toUpperCase()));\n for (const name of WINDOWS_SYSTEM_VARIABLES) {\n if (present.has(name.toUpperCase())) continue;\n const found = Object.entries(own).find(([key]) => key.toUpperCase() === name.toUpperCase());\n if (found?.[1] !== undefined) out[found[0]] = found[1];\n }\n return out;\n}\n","/**\n * A bundle's files against its manifest (RT-01): one walk that both writes `files.json` (the\n * assembler) and checks an extracted bundle against it (setup), so the two can't disagree about\n * what counts. Links must stay inside the bundle; nothing may be missing, changed or extra.\n *\n * On Windows (D153) a link is read as the relative, `/`-separated path from its directory to its\n * target, whether it is a symbolic link (`..\\\\x`, as pnpm makes them for an administrator) or a\n * junction (an absolute target, as setup makes them for everyone), so `files.json` reads the same\n * on every system; and no file is executable, since Windows keeps no execute bit (D150 item 8).\n */\nimport { createHash } from \"node:crypto\";\nimport { createReadStream, realpathSync } from \"node:fs\";\nimport { lstat, readdir, readlink } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport type { BundleFileEntry, BundleFiles, BundleLinkEntry } from \"@mostra/protocol\";\n\n/** Whether this process runs on Windows, whose links and modes the walk reads its own way. */\nconst WINDOWS = process.platform === \"win32\";\n\n/**\n * A link's target as the manifest spells it: relative to the link's directory, `/`-separated.\n * POSIX targets are kept exactly as written; a Windows junction's absolute target, and a Windows\n * symbolic link's `\\\\`-separated one, are rewritten into that form. `realRoot` is `root`'s real\n * path, which a caller reading many links computes once (Opus review of WP-W3, finding 8).\n */\nexport function linkTarget(\n root: string,\n path: string,\n written: string,\n realRoot: string | undefined = realOrNone(root),\n): string {\n if (!WINDOWS) return written;\n // A junction's target may carry the `\\\\?\\` prefix of Windows' own namespace.\n const plain = written.startsWith(\"\\\\\\\\?\\\\\") ? written.slice(4) : written;\n if (!isAbsolute(plain)) return plain.split(sep).join(\"/\");\n // A junction stores an absolute path, spelled as whoever made it spelled the bundle's root:\n // setup uses the real path, while `root` may be another spelling of it (an 8.3 short name such\n // as `RUNNER~1`, another case). Each spelling of the link's directory is tried against the\n // same spelling of the root, so neither reads as a detour out of the bundle; Windows compares\n // without case.\n const given = resolve(root);\n const dir = dirname(join(given, path));\n const spellings: [string, string][] = [[given, dir]];\n // A root that doesn't exist holds no junction; the lexical form then reports the mismatch.\n if (realRoot !== undefined) spellings.push([realRoot, join(realRoot, relative(given, dir))]);\n const lower = plain.toLowerCase();\n for (const [base, from] of spellings) {\n if (lower === base.toLowerCase() || lower.startsWith(`${base.toLowerCase()}${sep}`))\n return relative(from, plain).split(sep).join(\"/\");\n }\n return relative(dir, plain).split(sep).join(\"/\");\n}\n\n/** `root`'s real path on Windows (where junction targets need it), or `undefined`. */\nexport function realOrNone(root: string): string | undefined {\n if (!WINDOWS) return undefined;\n try {\n return realpathSync.native(resolve(root));\n } catch {\n return undefined;\n }\n}\n\n/** The SHA-256 and size of one file, read as a stream. */\nexport async function hashFile(path: string): Promise<{ sha256: string; size: number }> {\n const hash = createHash(\"sha256\");\n let size = 0;\n for await (const chunk of createReadStream(path)) {\n hash.update(chunk as Buffer);\n size += (chunk as Buffer).length;\n }\n return { sha256: hash.digest(\"hex\"), size };\n}\n\n/** One entry of a walk: a regular file or a link, by `/`-separated path from the root. */\ntype Walked =\n | { readonly kind: \"file\"; readonly path: string; readonly executable: boolean }\n | { readonly kind: \"link\"; readonly path: string; readonly target: string }\n | { readonly kind: \"other\"; readonly path: string };\n\n/** Every file and link under `root`, sorted by path, skipping `exclude`d paths (and below). */\nasync function walk(root: string, exclude: (path: string) => boolean): Promise<Walked[]> {\n const out: Walked[] = [];\n const realRoot = realOrNone(root);\n const visit = async (dir: string): Promise<void> => {\n const entries = await readdir(join(root, dir), { withFileTypes: true });\n for (const entry of entries) {\n const path = dir === \"\" ? entry.name : `${dir}/${entry.name}`;\n if (exclude(path)) continue;\n if (entry.isDirectory()) await visit(path);\n else if (entry.isSymbolicLink()) {\n const written = await readlink(join(root, path));\n out.push({ kind: \"link\", path, target: linkTarget(root, path, written, realRoot) });\n } else if (entry.isFile()) {\n // Windows keeps no execute bit: Node.js reports one there for every file it can read.\n const executable = WINDOWS ? false : ((await lstat(join(root, path))).mode & 0o100) !== 0;\n out.push({ kind: \"file\", path, executable });\n } else out.push({ kind: \"other\", path });\n }\n };\n await visit(\"\");\n return out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n}\n\n/** Runs `task` over `items`, at most `limit` at a time, keeping the order of results. */\nasync function mapLimit<T, R>(\n items: readonly T[],\n limit: number,\n task: (item: T) => Promise<R>,\n): Promise<R[]> {\n const results = new Array<R>(items.length);\n let next = 0;\n const worker = async (): Promise<void> => {\n while (next < items.length) {\n const index = next++;\n results[index] = await task(items[index] as T);\n }\n };\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));\n return results;\n}\n\n/** Whether a link's target is relative and resolves inside `root`. */\nexport function linkStaysInside(root: string, path: string, target: string): boolean {\n if (isAbsolute(target) || /[\\\\:\\0]/.test(target)) return false;\n const base = resolve(root);\n const resolved = resolve(base, dirname(path), target);\n return resolved === base || resolved.startsWith(base + sep);\n}\n\n/** Whether a manifest path is a plain relative path: no absolute start, no `.` or `..` segment. */\nexport function safeRelative(path: string): boolean {\n if (path === \"\" || isAbsolute(path) || path.includes(\"\\\\\") || path.includes(\"\\0\")) return false;\n return path.split(\"/\").every((segment) => segment !== \"\" && segment !== \".\" && segment !== \"..\");\n}\n\n/**\n * The manifest of the tree under `root`: every regular file with its SHA-256, size and execute\n * bit, every link with its target. Throws on anything else (a device, a socket, a link leaving\n * the tree), which a bundle must never contain.\n */\nexport async function describeTree(\n root: string,\n exclude: (path: string) => boolean = () => false,\n): Promise<BundleFiles> {\n const walked = await walk(root, exclude);\n const files: BundleFileEntry[] = [];\n const links: BundleLinkEntry[] = [];\n const regular = walked.filter((entry) => entry.kind === \"file\");\n const hashed = await mapLimit(regular, 32, (entry) => hashFile(join(root, entry.path)));\n regular.forEach((entry, index) => {\n const { sha256, size } = hashed[index] as { sha256: string; size: number };\n files.push({ path: entry.path, size, sha256, executable: entry.executable });\n });\n for (const entry of walked) {\n if (entry.kind === \"other\") throw new Error(`${entry.path} is neither a file nor a link.`);\n if (entry.kind !== \"link\") continue;\n if (!linkStaysInside(root, entry.path, entry.target))\n throw new Error(`${entry.path} links outside the tree (${entry.target}).`);\n links.push({ path: entry.path, target: entry.target });\n }\n return { schemaVersion: 1, files, links };\n}\n\n/** What a check found: an empty list means the tree matches. Paths are relative to the root. */\nexport type TreeProblems = readonly string[];\n\n/**\n * Checks the tree under `root` against `manifest`: each listed file present, regular, with its\n * size, SHA-256 and execute bit; each link present with its target, staying inside; and nothing\n * else besides what `allowExtra` accepts. Reports at most `limit` problems.\n */\nexport async function checkTree(\n root: string,\n manifest: BundleFiles,\n options: {\n readonly allowExtra?: (path: string) => boolean;\n readonly limit?: number;\n /**\n * Whether the links are checked; `false` checks the files alone and lets each listed link be\n * there or not, for a Windows bundle whose junctions setup makes after a rename (D153).\n */\n readonly links?: boolean;\n } = {},\n): Promise<TreeProblems> {\n const limit = options.limit ?? 20;\n const allowExtra = options.allowExtra ?? (() => false);\n const checkLinks = options.links ?? true;\n const problems: string[] = [];\n const add = (problem: string): void => {\n if (problems.length < limit) problems.push(problem);\n };\n const expectedFiles = new Map(manifest.files.map((entry) => [entry.path, entry]));\n const expectedLinks = new Map(manifest.links.map((entry) => [entry.path, entry]));\n for (const path of [...expectedFiles.keys(), ...expectedLinks.keys()]) {\n if (!safeRelative(path)) add(`${path}: not a plain relative path`);\n }\n if (problems.length > 0) return problems;\n // An allowed extra is skipped whole unless something listed lies at or below it.\n const listedDirs = new Set<string>();\n for (const path of [...expectedFiles.keys(), ...expectedLinks.keys()]) {\n const segments = path.split(\"/\");\n for (let index = 1; index < segments.length; index++)\n listedDirs.add(segments.slice(0, index).join(\"/\"));\n }\n const walked = await walk(\n root,\n (path) =>\n allowExtra(path) &&\n !expectedFiles.has(path) &&\n !expectedLinks.has(path) &&\n !listedDirs.has(path),\n );\n const found = new Map(walked.map((entry) => [entry.path, entry]));\n for (const entry of walked) {\n if (!expectedFiles.has(entry.path) && !expectedLinks.has(entry.path)) {\n if (!allowExtra(entry.path)) add(`${entry.path}: not in the bundle's file list`);\n }\n }\n for (const [path, link] of checkLinks ? expectedLinks : new Map<string, BundleLinkEntry>()) {\n const actual = found.get(path);\n if (actual?.kind !== \"link\") add(`${path}: missing link`);\n else if (actual.target !== link.target)\n add(`${path}: links to ${actual.target}, not ${link.target}`);\n else if (!linkStaysInside(root, path, link.target)) add(`${path}: links outside the bundle`);\n }\n const files = [...expectedFiles.values()];\n const results = await mapLimit(files, 32, async (entry) => {\n const actual = found.get(entry.path);\n if (actual?.kind !== \"file\") return `${entry.path}: missing file`;\n if (actual.executable !== entry.executable)\n return `${entry.path}: ${entry.executable ? \"not executable\" : \"executable\"}`;\n const { sha256, size } = await hashFile(join(root, entry.path));\n if (size !== entry.size) return `${entry.path}: ${size} bytes, not ${entry.size}`;\n if (sha256 !== entry.sha256) return `${entry.path}: its SHA-256 differs`;\n return undefined;\n });\n for (const result of results) if (result !== undefined) add(result);\n return problems;\n}\n","/**\n * A Windows bundle's links (D153). An ordinary Windows user can't create symbolic links (that\n * takes an administrator or Developer Mode), so a Windows archive holds none: its `files.json`\n * lists each link, every one to a directory inside the bundle, and setup makes each a junction,\n * which any user can create. A junction names its target by absolute path, so it is made at the\n * bundle's real path, and a bundle moved since is set up again (`readSetup` compares the root\n * its marker names).\n *\n * Nothing outside the bundle is ever touched: a listed link's path and target must stay inside\n * it, every directory above a link must be a real directory (never a link), the target must be a\n * directory, and what already sits at a link's path is replaced only when it is itself a link, or\n * a real directory holding exactly the files and bytes of the link's target. That is what a copy\n * made by a tool that follows junctions leaves (Explorer, `Copy-Item`, `robocopy` without `/SJ`,\n * and a move to another drive, which is a copy), so such a copy is set up again; a directory\n * holding anything else is refused and kept (Opus review of WP-W3, finding 4).\n *\n * Two setups of one bundle may run at once (a moved bundle met by two commands): each step\n * tolerates the other's, and a link counts as made once it names its target, whoever made it\n * (finding 5).\n */\nimport {\n lstat,\n mkdir,\n readdir,\n readlink,\n rm,\n rmdir,\n stat,\n symlink,\n unlink,\n} from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport type { BundleFiles, BundleLinkEntry } from \"@mostra/protocol\";\nimport { hashFile, linkStaysInside, linkTarget, realOrNone, safeRelative } from \"./tree.ts\";\n\n/** Why a link couldn't be made; the caller reports it as `MOSTRA_ENV_BUNDLE_INVALID`. */\nexport class LinkRefused extends Error {}\n\n/** Whether `path` (an absolute path inside `root`) has only real directories above it. */\nasync function realParents(root: string, path: string): Promise<boolean> {\n let dir = dirname(path);\n const chain: string[] = [];\n while (dir.length > root.length) {\n chain.unshift(dir);\n dir = dirname(dir);\n }\n for (const parent of chain) {\n const info = await lstat(parent).catch(() => undefined);\n if (info === undefined) {\n await mkdir(parent);\n continue;\n }\n if (!info.isDirectory() || info.isSymbolicLink()) return false;\n }\n return true;\n}\n\n/**\n * Makes every link `manifest` lists as a junction under `root`, which must be the bundle's real\n * path (`realpath.native`). A link that already names its target is kept; one that names another\n * (the bundle moved) is replaced. Throws {@link LinkRefused} for a link the manifest can't have.\n */\nexport async function makeJunctions(root: string, manifest: BundleFiles): Promise<void> {\n // A link's target may lie behind another link (`node_modules/x` through a scope's link), so a\n // link whose target isn't there yet waits for the next round; a round that makes nothing ends.\n const realRoot = realOrNone(root);\n let waiting = [...manifest.links].sort((a, b) => a.path.length - b.path.length);\n while (waiting.length > 0) {\n const later: typeof waiting = [];\n for (const link of waiting) {\n if (!(await makeJunction(root, link, realRoot))) later.push(link);\n }\n if (later.length === waiting.length) {\n const first = later[0] as BundleLinkEntry;\n throw new LinkRefused(`${first.path} links to ${first.target}, which is no directory.`);\n }\n waiting = later;\n }\n}\n\n/** Makes one link; `false` when its target isn't a directory (yet). */\nasync function makeJunction(\n root: string,\n link: BundleLinkEntry,\n realRoot: string | undefined,\n): Promise<boolean> {\n if (!safeRelative(link.path) || !linkStaysInside(root, link.path, link.target)) {\n throw new LinkRefused(`${link.path} links outside the bundle (${link.target}).`);\n }\n const at = join(root, link.path);\n const target = resolve(dirname(at), link.target);\n if (!(await realParents(root, at))) {\n throw new LinkRefused(`${link.path} sits below a link or a file.`);\n }\n const kind = await stat(target).catch(() => undefined);\n if (kind === undefined || !kind.isDirectory()) {\n return names(root, link, at, realRoot);\n }\n // Another setup of this bundle may be making the same links (finding 5). Each attempt reads the\n // state afresh and accepts a link that names its target, whoever made it; a setup removes only\n // what doesn't, and always makes the link right after, while nothing ever makes a stale one, so\n // the link names its target once both stop.\n let last: unknown;\n for (let attempt = 0; attempt < 20; attempt++) {\n if (await names(root, link, at, realRoot)) return true;\n const current = await lstat(at).catch(() => undefined);\n try {\n if (current?.isSymbolicLink()) {\n // A junction is a directory to Windows: `rmdir` removes the link, never what it names.\n await rmdir(at).catch(async (error: NodeJS.ErrnoException) => {\n if (error.code !== \"ENOENT\") await unlink(at);\n });\n } else if (current !== undefined) {\n if (!current.isDirectory() || !(await sameTree(at, target))) {\n // Read again: another setup may have replaced the copy while it was compared.\n if (await names(root, link, at, realRoot)) return true;\n const now = await lstat(at).catch(() => undefined);\n if (now !== undefined && !now.isSymbolicLink()) {\n throw new LinkRefused(\n `${link.path} is a file or directory where the bundle has a link, and it isn't a copy of ${link.target}.`,\n );\n }\n continue;\n }\n // A copy of the target: no link inside it (`sameTree` refuses one), so nothing outside it.\n await rm(at, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });\n }\n await symlink(target, at, \"junction\");\n } catch (error) {\n if (error instanceof LinkRefused) throw error;\n last = error; // another setup's step came between: the next attempt reads the state again\n }\n }\n if (await names(root, link, at, realRoot)) return true;\n throw new LinkRefused(\n `${link.path} couldn't be made as a junction to ${link.target}${last ? `: ${(last as Error).message}` : \"\"}.`,\n );\n}\n\n/** Whether the link at `at` exists and names the manifest's target. */\nasync function names(\n root: string,\n link: BundleLinkEntry,\n at: string,\n realRoot: string | undefined,\n): Promise<boolean> {\n const info = await lstat(at).catch(() => undefined);\n if (info === undefined || !info.isSymbolicLink()) return false;\n const written = await readlink(at).catch(() => undefined);\n return written !== undefined && linkTarget(root, link.path, written, realRoot) === link.target;\n}\n\n/**\n * Whether the real directory `copy` holds exactly what `original` holds: the same names, files of\n * the same bytes, and directories alike all the way down. A link anywhere in the copy, or an entry\n * of any other kind, makes it no copy.\n */\nasync function sameTree(copy: string, original: string): Promise<boolean> {\n const [mine, theirs] = await Promise.all([\n readdir(copy, { withFileTypes: true }).catch(() => undefined),\n readdir(original, { withFileTypes: true }).catch(() => undefined),\n ]);\n if (mine === undefined || theirs === undefined || mine.length !== theirs.length) return false;\n const byName = new Map(theirs.map((entry) => [entry.name, entry]));\n for (const entry of mine) {\n const other = byName.get(entry.name);\n if (other === undefined || entry.isSymbolicLink()) return false;\n const a = join(copy, entry.name);\n const b = join(original, entry.name);\n if (entry.isDirectory()) {\n // The original may reach a directory through a link (a junction made a moment ago).\n if (!(await stat(b).catch(() => undefined))?.isDirectory()) return false;\n if (!(await sameTree(a, b))) return false;\n } else if (entry.isFile()) {\n if (!(other.isFile() || other.isSymbolicLink()) || !(await sameBytes(a, b))) return false;\n } else return false;\n }\n return true;\n}\n\n/** Whether two files hold the same bytes (streamed, so a large program isn't held in memory). */\nasync function sameBytes(a: string, b: string): Promise<boolean> {\n const [sa, sb] = await Promise.all([stat(a), stat(b)]).catch(() => [undefined, undefined]);\n if (sa === undefined || sb === undefined || !sb.isFile() || sa.size !== sb.size) return false;\n const [ha, hb] = await Promise.all([hashFile(a), hashFile(b)]);\n return ha.sha256 === hb.sha256;\n}\n","/**\n * Making an extracted bundle usable (RT-01, D142): its files checked against `files.json`, which\n * `bundle.json` pins by SHA-256; the verify browser fetched through the bundle's own Playwright\n * and checked against the bundle's pin; then `.mostra-setup.json`, the one marker every reader\n * trusts. The SDK runs it after a download; `bin/mostra-setup` runs it for a bundle extracted by\n * hand, and for the Rust crate (WP-12), so there is one implementation of what \"ready\" means.\n */\nimport { spawn } from \"node:child_process\";\nimport { realpathSync } from \"node:fs\";\nimport { readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n BUNDLE_SETUP_MARKER,\n BundleFiles,\n BundleInfo,\n BundleSetup,\n createDiagnostic,\n isWindowsBundle,\n RpcError,\n} from \"@mostra/protocol\";\nimport { childEnvironment } from \"../environment.ts\";\nimport { scrubUrls } from \"./download.ts\";\nimport { LinkRefused, makeJunctions } from \"./links.ts\";\nimport { checkTree, hashFile, safeRelative } from \"./tree.ts\";\n\n/** The environment setup reads. */\nexport type Environment = Readonly<Record<string, string | undefined>>;\n\n/** An extracted bundle and what its `bundle.json` says. */\nexport interface Bundle {\n /** Its root directory, holding `bundle.json`. */\n readonly root: string;\n /** Its parsed `bundle.json`. */\n readonly info: BundleInfo;\n}\n\n/** One step of setup, for progress reports. */\nexport type SetupStep = \"files\" | \"browser\";\n\n/** Options of {@link setupBundle}. */\nexport interface SetupOptions {\n /** The environment: `MOSTRA_OFFLINE`, proxies, Playwright's download mirror. */\n readonly env?: Environment | undefined;\n /** Gives up the browser's download. */\n readonly signal?: AbortSignal | undefined;\n /** Each step as it starts. */\n readonly onStep?: ((step: SetupStep) => void) | undefined;\n /** Skip checking the files, for a tree the caller checked a moment ago. */\n readonly filesChecked?: boolean | undefined;\n}\n\n/** The directory Playwright's browsers live in, inside a bundle. */\nexport function browsersDir(root: string): string {\n return join(root, \"browsers\");\n}\n\n/** Whether `MOSTRA_OFFLINE` says Mostra is offline: any value but empty, `0`, `false` or `no`. */\nexport function offline(env: Environment): boolean {\n const value = env[\"MOSTRA_OFFLINE\"]?.trim().toLowerCase();\n return (\n value !== undefined && value !== \"\" && value !== \"0\" && value !== \"false\" && value !== \"no\"\n );\n}\n\nfunction invalid(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_ENV_BUNDLE_INVALID\", { message }));\n}\n\n/** Reads `bundle.json` at `root`. Throws `MOSTRA_ENV_BUNDLE_INVALID` when it isn't a bundle's. */\nexport async function readBundle(root: string): Promise<Bundle> {\n let text: string;\n try {\n text = await readFile(join(root, \"bundle.json\"), \"utf8\");\n } catch (error) {\n throw invalid(`${root} has no readable bundle.json (${(error as Error).message}).`);\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n throw invalid(`${join(root, \"bundle.json\")} isn't JSON.`);\n }\n const result = BundleInfo.safeParse(parsed);\n if (!result.success) throw invalid(`${join(root, \"bundle.json\")} isn't a runtime bundle's.`);\n const info = result.data;\n const paths = [\n info.node.path,\n ...Object.values(info.entries),\n info.files.path,\n info.browser.installer,\n ];\n if (!paths.every(safeRelative))\n throw invalid(`${join(root, \"bundle.json\")} names a path outside the bundle.`);\n return { root, info };\n}\n\n/**\n * The bundle's real path: links followed, Windows' short names written out, the case as the file\n * system keeps it. A Windows bundle's junctions point into it, and its marker names it.\n */\nexport function realRoot(root: string): string {\n return realpathSync.native(root);\n}\n\n/**\n * The setup marker, when it describes exactly this bundle. A Windows bundle's marker must also\n * name the root it sits at now: its junctions point into the root setup ran at, so a bundle moved\n * or copied since is set up again, which makes them afresh (D153).\n */\nexport async function readSetup(bundle: Bundle): Promise<BundleSetup | undefined> {\n try {\n const marker = BundleSetup.parse(\n JSON.parse(await readFile(join(bundle.root, BUNDLE_SETUP_MARKER), \"utf8\")),\n );\n const { info } = bundle;\n const here = isWindowsBundle(info.platform) ? marker.root === realRoot(bundle.root) : true;\n return here &&\n marker.files === info.files.sha256 &&\n marker.version === info.version &&\n marker.platform === info.platform &&\n marker.browser.revision === info.browser.revision\n ? marker\n : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** What `checkTree` may find besides the listed files: the bundle's own records and browsers. */\nexport function setupExtras(path: string): boolean {\n return (\n path === \"bundle.json\" ||\n path === \"files.json\" ||\n path === \"browsers\" ||\n path.startsWith(\"browsers/\") ||\n path === BUNDLE_SETUP_MARKER ||\n path.startsWith(`${BUNDLE_SETUP_MARKER}.tmp-`)\n );\n}\n\n/** The bundle's `files.json`, once its SHA-256 is the one `bundle.json` pins. */\nasync function readManifest(bundle: Bundle): Promise<BundleFiles> {\n const { root, info } = bundle;\n const listing = join(root, info.files.path);\n const { sha256 } = await hashFile(listing).catch(() => ({ sha256: \"\" }));\n if (sha256 !== info.files.sha256) {\n throw invalid(`${info.files.path} doesn't match the SHA-256 that bundle.json pins.`);\n }\n const manifest = BundleFiles.safeParse(JSON.parse(await readFile(listing, \"utf8\")));\n if (!manifest.success) throw invalid(`${info.files.path} isn't a bundle's file list.`);\n return manifest.data;\n}\n\n/**\n * Makes a Windows bundle's links, each a junction at the bundle's real path (D153); nothing for\n * any other bundle, whose archive carries its links. Throws `MOSTRA_ENV_BUNDLE_INVALID` for a link\n * the bundle can't have.\n */\nexport async function makeLinks(bundle: Bundle, read?: BundleFiles): Promise<void> {\n if (!isWindowsBundle(bundle.info.platform)) return;\n const manifest = read ?? (await readManifest(bundle));\n try {\n await makeJunctions(realRoot(bundle.root), manifest);\n } catch (error) {\n if (error instanceof LinkRefused) throw invalid(`The runtime bundle's links: ${error.message}`);\n throw error;\n }\n}\n\n/**\n * Checks the bundle's files; throws `MOSTRA_ENV_BUNDLE_INVALID` naming what differs. With\n * `links: false` the files alone are checked (a Windows bundle before `makeLinks` made its junctions).\n */\nexport async function checkFiles(\n bundle: Bundle,\n options: { readonly links?: boolean; readonly manifest?: BundleFiles } = {},\n): Promise<void> {\n const { root, info } = bundle;\n const manifest = options.manifest ?? (await readManifest(bundle));\n const problems = await checkTree(root, manifest, {\n allowExtra: setupExtras,\n links: options.links ?? true,\n });\n if (problems.length > 0) {\n throw invalid(\n `Mostra ${info.version}'s runtime bundle for ${info.platform} differs from its file list: ${problems.join(\"; \")}.`,\n );\n }\n}\n\n/** The browser files that differ from the pin, relative to `browsers/`. */\nexport async function checkBrowser(bundle: Bundle): Promise<readonly string[]> {\n const problems = await checkTree(\n browsersDir(bundle.root),\n { schemaVersion: 1, files: bundle.info.browser.files, links: [] },\n // Playwright's own markers, its `.links` registry and any other browser it fetched.\n { allowExtra: () => true },\n ).catch((error: unknown) => [`browsers: ${(error as Error).message}`]);\n return problems;\n}\n\n/** The environment the browser install runs in: proxies and Playwright's mirror pass through. */\nfunction installEnvironment(bundle: Bundle, env: Environment): NodeJS.ProcessEnv {\n const out: Record<string, string> = {};\n for (const [name, value] of Object.entries(env)) {\n if (value !== undefined && !name.startsWith(\"MOSTRA_\") && name !== \"PLAYWRIGHT_BROWSERS_PATH\")\n out[name] = value;\n }\n out[\"PLAYWRIGHT_BROWSERS_PATH\"] = browsersDir(bundle.root);\n return childEnvironment(out);\n}\n\n/** The variables whose URLs may carry credentials the browser's fetch uses. */\nconst CREDENTIAL_URLS = [\n \"PLAYWRIGHT_DOWNLOAD_HOST\",\n \"HTTPS_PROXY\",\n \"https_proxy\",\n \"HTTP_PROXY\",\n \"http_proxy\",\n \"ALL_PROXY\",\n \"all_proxy\",\n];\n\n/** `text` without URLs' credentials or queries, and without any password `env`'s URLs carry. */\nexport function scrubSecrets(text: string, env: Environment): string {\n let out = scrubUrls(text);\n for (const name of CREDENTIAL_URLS) {\n const value = env[name];\n if (!value) continue;\n // A proxy is often written without a scheme (`user:pass@host:3128`), which `URL` would read\n // as the scheme `user:`.\n const spelled = value.includes(\"://\") ? value : `http://${value}`;\n const parsed = URL.canParse(spelled) ? new URL(spelled) : undefined;\n for (const secret of [parsed?.password, parsed?.username]) {\n if (!secret) continue;\n for (const form of new Set([secret, decodeURIComponent(secret)]))\n if (form.length >= 3) out = out.split(form).join(\"***\");\n }\n }\n return out;\n}\n\n/** Runs the bundle's Playwright to fetch the pinned browser; at most 15 minutes. */\nasync function installBrowser(bundle: Bundle, options: SetupOptions): Promise<void> {\n const { root, info } = bundle;\n const output: string[] = [];\n const code = await new Promise<number | string>((resolve) => {\n const child = spawn(\n join(root, info.node.path),\n [join(root, info.browser.installer), \"install\", \"chromium-headless-shell\"],\n {\n cwd: root,\n env: installEnvironment(bundle, options.env ?? process.env),\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n windowsHide: true,\n ...(options.signal ? { signal: options.signal } : {}),\n timeout: 15 * 60_000,\n },\n );\n const keep = (chunk: Buffer): void => {\n output.push(chunk.toString(\"utf8\"));\n if (output.length > 40) output.shift();\n };\n child.stdout.on(\"data\", keep);\n child.stderr.on(\"data\", keep);\n child.on(\"error\", (error) => resolve(error.message));\n child.on(\"close\", (exit, signal) => resolve(exit ?? signal ?? \"unknown\"));\n });\n if (code === 0) return;\n // Playwright prints the URLs it fetches, and a mirror's or proxy's may carry credentials\n // (Opus review finding 3): every URL is reduced to its printable form, and any password the\n // environment names is removed wherever it appears.\n const tail = scrubSecrets(\n output.join(\"\").trim().split(\"\\n\").slice(-6).join(\" | \"),\n options.env ?? process.env,\n );\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_DOWNLOAD_FAILED\", {\n message: `Fetching the verify browser (${info.browser.name} ${info.browser.browserVersion}) failed (${code}): ${tail}`,\n }),\n );\n}\n\n/**\n * Makes the bundle at `root` ready: checks its files, fetches and checks the browser when it is\n * missing or differs, and writes `.mostra-setup.json`. Idempotent: a ready bundle returns its\n * marker after the checks. Throws `MOSTRA_ENV_BUNDLE_INVALID`, `MOSTRA_ENV_BUNDLE_UNAVAILABLE`\n * (offline with no browser) or `MOSTRA_ENV_BUNDLE_DOWNLOAD_FAILED`.\n */\nexport async function setupBundle(root: string, options: SetupOptions = {}): Promise<BundleSetup> {\n const env = options.env ?? process.env;\n const bundle = await readBundle(root);\n // A Windows bundle's junctions are made where it sits now, each read back as it is made; a\n // tree checked a moment ago (`filesChecked`, before the cache's rename) needs nothing more.\n // `files.json` is read and checked against its pin once, for both steps (Opus review of\n // WP-W3, finding 9): it lists every file of the bundle and is large.\n const windows = isWindowsBundle(bundle.info.platform);\n const manifest = windows || !options.filesChecked ? await readManifest(bundle) : undefined;\n await makeLinks(bundle, manifest);\n if (!options.filesChecked) {\n options.onStep?.(\"files\");\n await checkFiles(bundle, manifest ? { manifest } : {});\n }\n options.onStep?.(\"browser\");\n if ((await checkBrowser(bundle)).length > 0) {\n if (offline(env)) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_UNAVAILABLE\", {\n message: `The runtime bundle at ${root} has no verify browser yet, and MOSTRA_OFFLINE keeps Mostra from fetching it.`,\n }),\n );\n }\n // Fresh, never over what's there: a directory that differs from the pin may still carry\n // Playwright's \"installation complete\" marker, and Playwright would then fetch nothing.\n await rm(browsersDir(root), { recursive: true, force: true });\n await installBrowser(bundle, options);\n const problems = await checkBrowser(bundle);\n if (problems.length > 0) {\n throw invalid(\n `The verify browser Playwright fetched differs from the bundle's pin: ${problems.join(\"; \")}.`,\n );\n }\n }\n const marker: BundleSetup = {\n schemaVersion: 1,\n version: bundle.info.version,\n platform: bundle.info.platform,\n files: bundle.info.files.sha256,\n browser: { revision: bundle.info.browser.revision },\n at: new Date().toISOString(),\n root: realRoot(root),\n };\n const temporary = join(root, `${BUNDLE_SETUP_MARKER}.tmp-${process.pid}`);\n await writeFile(temporary, `${JSON.stringify(marker, null, 2)}\\n`);\n await rename(temporary, join(root, BUNDLE_SETUP_MARKER));\n return marker;\n}\n","/**\n * The local cache of runtime bundles (RT-01): one directory per archive digest, so a bundle is\n * found by what it is, not by what it's called. A bundle enters the cache only through\n * {@link installPinned}: downloaded against its pin, extracted into a temporary directory, its\n * files checked, renamed into place, its browser fetched, and only then marked ready. Concurrent\n * installers of one bundle share a lock, so it is downloaded once; a crash leaves a temporary\n * directory the next install removes, never a half-ready bundle.\n */\nimport { randomBytes } from \"node:crypto\";\nimport {\n link,\n mkdir,\n open,\n readdir,\n readFile,\n rename,\n rm,\n stat,\n statfs,\n utimes,\n} from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join, posix, resolve, win32 } from \"node:path\";\nimport {\n type BundleAsset,\n BundleAsset as BundleAssetSchema,\n type BundlePins,\n type BundlePlatform,\n bundleAssetName,\n createDiagnostic,\n isWindowsBundle,\n RpcError,\n} from \"@mostra/protocol\";\nimport { type DownloadProgress, download } from \"./download.ts\";\nimport { extractBundle } from \"./extract.ts\";\nimport {\n type Bundle,\n checkFiles,\n type Environment,\n offline,\n readBundle,\n readSetup,\n type SetupStep,\n setupBundle,\n} from \"./setup.ts\";\n\n/**\n * Where the cache is: `MOSTRA_CACHE_DIR`, else the platform's per-user cache directory:\n * `~/Library/Caches/mostra` on macOS, `%LOCALAPPDATA%\\mostra-cache` on Windows (beside the home,\n * `%LOCALAPPDATA%\\mostra`, as npm keeps `npm-cache`), `${XDG_CACHE_HOME:-~/.cache}/mostra` on\n * Linux.\n */\nexport function cacheRoot(env: Environment, platform: string = process.platform): string {\n const override = env[\"MOSTRA_CACHE_DIR\"];\n if (override) return resolve(override);\n if (platform === \"win32\") {\n const local =\n env[\"LOCALAPPDATA\"] || win32.join(env[\"USERPROFILE\"] || homedir(), \"AppData\", \"Local\");\n return win32.join(local, \"mostra-cache\");\n }\n // POSIX paths, whatever system computes them (`platform` is the one the cache is for).\n const home = env[\"HOME\"] || homedir();\n if (platform === \"darwin\") return posix.join(home, \"Library\", \"Caches\", \"mostra\");\n const xdg = env[\"XDG_CACHE_HOME\"];\n return posix.join(xdg?.startsWith(\"/\") ? xdg : posix.join(home, \".cache\"), \"mostra\");\n}\n\n/** The directory a bundle with this archive digest lives in. */\nexport function bundleDir(env: Environment, sha256: string): string {\n return join(cacheRoot(env), \"bundles\", sha256);\n}\n\n/** What an install reports while it works. */\nexport type InstallProgress =\n | ({ readonly step: \"download\" } & DownloadProgress)\n | { readonly step: \"extract\" | \"lock\" }\n | { readonly step: SetupStep };\n\n/** Options of {@link installPinned}. */\nexport interface InstallOptions {\n /** The environment: the cache, mirror and offline variables, proxies. */\n readonly env: Environment;\n /** The platform whose archive to install. */\n readonly platform: BundlePlatform;\n /** Gives up the install; nothing partial is kept. */\n readonly signal?: AbortSignal | undefined;\n /** Each step, and the bytes received while downloading. */\n readonly onProgress?: ((progress: InstallProgress) => void) | undefined;\n}\n\n/** The space an install needs beyond the archive and its files: the browser and some margin. */\nconst BROWSER_ALLOWANCE = 500 * 1024 * 1024;\n\n/**\n * The pinned bundle for this platform, ready to run: from the cache when it is there and ready,\n * else installed. `MOSTRA_BUNDLE_MIRROR` replaces the release URL (files keep their names).\n */\nexport async function installPinned(pins: BundlePins, options: InstallOptions): Promise<Bundle> {\n const asset = pins.assets[options.platform];\n // Checked before any I/O: the asset's name becomes a path in the cache's scratch directory and\n // its digest the bundle's directory (Opus review finding 8), so the asset must be well-formed\n // and named exactly as its release's archive for this platform.\n if (\n asset !== undefined &&\n (!BundleAssetSchema.safeParse(asset).success ||\n asset.file !== bundleAssetName(pins.version, options.platform))\n ) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_INVALID\", {\n message: `The pins name ${JSON.stringify(asset.file)} for ${options.platform}, not Mostra ${pins.version}'s archive ${bundleAssetName(pins.version, options.platform)}.`,\n }),\n );\n }\n if (asset === undefined) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_UNAVAILABLE\", {\n message: `Mostra ${pins.version} has no runtime bundle for ${options.platform}.`,\n }),\n );\n }\n const dir = bundleDir(options.env, asset.sha256);\n const ready = await readyAt(dir);\n if (ready) return ready;\n if (offline(options.env)) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_UNAVAILABLE\", {\n message: `Mostra ${pins.version}'s runtime bundle isn't in the cache (${dir}), and MOSTRA_OFFLINE keeps Mostra from fetching it.`,\n }),\n );\n }\n const bundles = join(cacheRoot(options.env), \"bundles\");\n await mkdir(bundles, { recursive: true, mode: 0o700 });\n options.onProgress?.({ step: \"lock\" });\n const release = await lock(join(bundles, `${asset.sha256}.lock`), options.signal);\n try {\n const raced = await readyAt(dir);\n if (raced) return raced;\n await sweep(bundles);\n if (await exists(dir)) {\n // A bundle whose setup didn't finish (no network for the browser, a crash). Only its own\n // files decide whether it is downloaded afresh: a file that differs from the pins can't be\n // repaired in place, but the browser can be fetched again, and downloading 200 MB again\n // never changes what Playwright serves (Opus review finding 5). Anything else, such as a\n // permission error, is thrown: it says nothing about the bundle, so nothing is deleted.\n if (await filesIntact(dir)) return await finish(dir, { ...options, filesChecked: true });\n await rm(dir, { recursive: true, force: true });\n }\n await fetchInto(pins, asset, dir, bundles, options);\n return await finish(dir, { ...options, filesChecked: true });\n } finally {\n await release();\n }\n}\n\n/**\n * Whether the bundle at `dir` holds exactly what its `files.json` lists. `false` only for\n * `MOSTRA_ENV_BUNDLE_INVALID` (a missing or changed file, a `bundle.json` that doesn't read);\n * every other error is thrown.\n */\nasync function filesIntact(dir: string): Promise<boolean> {\n try {\n const bundle = await readBundle(dir);\n // A Windows bundle's junctions are made by setup, after this (D153).\n await checkFiles(bundle, { links: !isWindowsBundle(bundle.info.platform) });\n return true;\n } catch (error) {\n if (error instanceof RpcError && error.diagnostic.code === \"MOSTRA_ENV_BUNDLE_INVALID\")\n return false;\n throw error;\n }\n}\n\n/** The bundle at `dir` when it exists and its setup marker matches it. */\nasync function readyAt(dir: string): Promise<Bundle | undefined> {\n const bundle = await readBundle(dir).catch(() => undefined);\n if (bundle === undefined) return undefined;\n return (await readSetup(bundle)) ? bundle : undefined;\n}\n\nasync function finish(\n dir: string,\n options: InstallOptions & { readonly filesChecked?: boolean },\n): Promise<Bundle> {\n await setupBundle(dir, {\n env: options.env,\n signal: options.signal,\n filesChecked: options.filesChecked,\n onStep: (step) => options.onProgress?.({ step }),\n });\n return readBundle(dir);\n}\n\n/** Downloads, extracts and checks the archive, then renames it into `dir`. */\nasync function fetchInto(\n pins: BundlePins,\n asset: BundleAsset,\n dir: string,\n bundles: string,\n options: InstallOptions,\n): Promise<void> {\n await requireSpace(bundles, asset);\n const scratch = join(bundles, `.tmp-${process.pid}-${randomBytes(6).toString(\"hex\")}`);\n await mkdir(scratch, { mode: 0o700 });\n try {\n const archive = join(scratch, asset.file);\n const base = options.env[\"MOSTRA_BUNDLE_MIRROR\"] || pins.release;\n const url = `${withoutTrailingSlashes(base)}/${encodeURIComponent(asset.file)}`;\n await download(url, archive, asset, {\n env: options.env,\n signal: options.signal,\n onProgress: (progress) => options.onProgress?.({ step: \"download\", ...progress }),\n });\n options.onProgress?.({ step: \"extract\" });\n const root = join(scratch, \"root\");\n await mkdir(root);\n const top = asset.file.replace(/\\.tar\\.gz$/, \"\");\n if (top !== bundleAssetName(pins.version, options.platform).replace(/\\.tar\\.gz$/, \"\")) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_INVALID\", {\n message: `The pinned archive ${asset.file} isn't Mostra ${pins.version}'s bundle for ${options.platform}.`,\n }),\n );\n }\n // A Windows archive holds no links (D153): its junctions are made once it is in place.\n const windows = isWindowsBundle(options.platform);\n await extractBundle(archive, root, top, { links: windows ? \"refuse\" : \"keep\" });\n await rm(archive, { force: true });\n const bundle = await readBundle(root);\n if (bundle.info.version !== pins.version || bundle.info.platform !== options.platform) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_INVALID\", {\n message: `The archive holds Mostra ${bundle.info.version} for ${bundle.info.platform}, not ${pins.version} for ${options.platform}.`,\n }),\n );\n }\n options.onProgress?.({ step: \"files\" });\n await checkFiles(bundle, { links: !windows });\n try {\n await renameIntoPlace(root, dir);\n } catch (error) {\n // Another installer finished first (the lock is an optimization, never what correctness\n // rests on): its directory is used, whose files it checked before renaming them into place.\n // Windows refuses a rename over an existing directory with EPERM.\n const code = (error as NodeJS.ErrnoException).code;\n const taken = code === \"ENOTEMPTY\" || code === \"EEXIST\" || code === \"EPERM\";\n if (!taken || !(await exists(dir))) throw error;\n }\n } finally {\n // Windows may hold the files a moment (an antivirus scan); a scratch directory left anyway\n // is removed by the next install's sweep.\n await rm(scratch, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }).catch(\n () => undefined,\n );\n }\n}\n\n/**\n * Renames `from` to `to`. On Windows a file that an antivirus scan or the indexer holds for a\n * moment refuses the rename (EPERM, EACCES, EBUSY) though nothing is wrong, so the rename is\n * tried again with backoff for up to 3 s, as the runtime's renames are (D150 item 8), and never\n * turned into a copy; a refusal that lasts is thrown, and EPERM over an existing directory with it.\n */\nexport async function renameIntoPlace(from: string, to: string): Promise<void> {\n const deadline = Date.now() + 3000;\n for (let wait = 25; ; wait = Math.min(wait * 2, 400)) {\n try {\n await rename(from, to);\n return;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n const held = code === \"EPERM\" || code === \"EACCES\" || code === \"EBUSY\";\n if (process.platform !== \"win32\" || !held || Date.now() > deadline || (await exists(to)))\n throw error;\n await new Promise((done) => setTimeout(done, wait));\n }\n }\n}\n\n/** Fails early when the cache's file system can't hold the bundle. */\nasync function requireSpace(dir: string, asset: BundleAsset): Promise<void> {\n const fs = await statfs(dir).catch(() => undefined);\n if (fs === undefined) return;\n const free = Number(fs.bavail) * Number(fs.bsize);\n const needed = asset.size + asset.unpackedSize + BROWSER_ALLOWANCE;\n if (free < needed) {\n const gib = (bytes: number): string => `${(bytes / 1024 ** 3).toFixed(1)} GiB`;\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_DOWNLOAD_FAILED\", {\n message: `The runtime bundle needs about ${gib(needed)} free in ${dir}, and ${gib(free)} is free (the disk is full).`,\n }),\n );\n }\n}\n\n/** Removes temporary directories an interrupted install left, when their process is gone. */\nasync function sweep(bundles: string): Promise<void> {\n for (const name of await readdir(bundles).catch(() => [] as string[])) {\n const match = /^\\.tmp-(\\d+)-/.exec(name);\n if (match && !alive(Number(match[1]))) {\n await rm(join(bundles, name), { recursive: true, force: true });\n }\n }\n}\n\nasync function exists(path: string): Promise<boolean> {\n return stat(path).then(\n () => true,\n () => false,\n );\n}\n\nfunction alive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\n/** How old a lock may get before another installer takes it over whatever its owner. */\nconst STALE_LOCK_MS = 60 * 60_000;\n/**\n * How often a held lock is touched, so an install longer than {@link STALE_LOCK_MS} (a slow\n * network, a large browser) is never taken from its live owner (Opus review of WP-12, finding 10).\n */\nconst LOCK_TOUCH_MS = 60_000;\n\n/** `url` without trailing slashes, in linear time (a regex would be quadratic on many slashes). */\nfunction withoutTrailingSlashes(url: string): string {\n let end = url.length;\n while (end > 0 && url[end - 1] === \"/\") end -= 1;\n return url.slice(0, end);\n}\n\n/** A lock judged stale: the file judged, by its identity and what it held. */\nexport interface JudgedLock {\n readonly ino: number;\n readonly dev: number;\n readonly text: string;\n}\n\n/**\n * Judges the lock at `path` through one descriptor: `gone`, `live`, or stale (its owner gone, or\n * older than an hour) with what identifies the file judged.\n */\nexport async function judgeLock(path: string): Promise<\"gone\" | \"live\" | JudgedLock> {\n let handle: Awaited<ReturnType<typeof open>>;\n try {\n handle = await open(path, \"r\");\n } catch {\n return \"gone\";\n }\n try {\n const info = await handle.stat();\n const text = await handle.readFile(\"utf8\");\n const owner = Number.parseInt(text, 10);\n const stale =\n Date.now() - info.mtimeMs > STALE_LOCK_MS ||\n (Number.isInteger(owner) && owner > 0 && !alive(owner));\n return stale ? { ino: info.ino, dev: info.dev, text } : \"live\";\n } finally {\n await handle.close();\n }\n}\n\n/**\n * Moves the lock at `path` aside and removes it only if it is the file `judged` describes, by\n * identity and by contents: a fresh lock another installer took in between is put back (or, if a\n * third took one meanwhile, left to the next round). The contents matter because a file system may\n * give a new file the number of one just removed (ext4 does at once), and each lock holds its\n * owner's PID and its own token (MT-02).\n */\nexport async function removeJudged(path: string, judged: JudgedLock): Promise<void> {\n const aside = `${path}.stale-${randomBytes(6).toString(\"hex\")}`;\n try {\n await rename(path, aside);\n } catch {\n return; // someone else moved or removed it\n }\n // Its identity and contents through one descriptor, so both describe the same file.\n let same = false;\n const handle = await open(aside, \"r\").catch(() => undefined);\n if (handle) {\n try {\n const moved = await handle.stat();\n const text = await handle.readFile(\"utf8\");\n same = moved.ino === judged.ino && moved.dev === judged.dev && text === judged.text;\n } catch {\n // Unreadable: not provably the file judged, so it is put back.\n } finally {\n await handle.close();\n }\n }\n // Not the file judged stale: a fresh lock. Put it back unless a newer one exists.\n if (!same) await link(aside, path).catch(() => undefined);\n await rm(aside, { force: true });\n}\n\n/**\n * Removes the lock at `path` when it is stale and says whether it may be taken now. The lock only\n * saves a second download; the scratch directory and its rename keep the cache correct whatever\n * happens here.\n */\nasync function takeOverIfStale(path: string): Promise<boolean> {\n const judged = await judgeLock(path);\n if (judged === \"gone\") return true; // gone already: try to take it\n if (judged === \"live\") return false;\n await removeJudged(path, judged);\n return true;\n}\n\n/**\n * Takes the install lock at `path`: an exclusive create holding the owner's PID. A lock whose\n * owner is gone, or older than an hour, is taken over; otherwise the caller waits for it.\n */\nasync function lock(path: string, signal: AbortSignal | undefined): Promise<() => Promise<void>> {\n const token = randomBytes(8).toString(\"hex\");\n for (;;) {\n signal?.throwIfAborted();\n try {\n const handle = await open(path, \"wx\", 0o600);\n await handle.writeFile(`${process.pid} ${token}\\n`);\n await handle.close();\n const touch = setInterval(() => {\n void readFile(path, \"utf8\")\n .then((text) => {\n if (text.includes(token)) return utimes(path, new Date(), new Date());\n return undefined;\n })\n .catch(() => undefined);\n }, LOCK_TOUCH_MS);\n touch.unref();\n // Released by moving it aside and removing it only if it is still this installer's own.\n return async () => {\n clearInterval(touch);\n const aside = `${path}.done-${randomBytes(6).toString(\"hex\")}`;\n if (\n !(await rename(path, aside).then(\n () => true,\n () => false,\n ))\n )\n return;\n const text = await readFile(aside, \"utf8\").catch(() => \"\");\n if (!text.includes(token)) await link(aside, path).catch(() => undefined);\n await rm(aside, { force: true });\n };\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n }\n if (await takeOverIfStale(path)) continue;\n await new Promise((done) => setTimeout(done, 250));\n }\n}\n","/**\n * Which runtime bundle this machine takes (RT-01, RT-12, D35, D146): one per operating system and\n * architecture of v1 (macOS, glibc Linux and Windows, each on x64 and arm64). Anything else fails\n * closed before a download starts.\n */\nimport {\n BUNDLE_PLATFORMS,\n type BundlePlatform,\n createDiagnostic,\n RpcError,\n} from \"@mostra/protocol\";\n\n/** What the platform check reads: the running process by default. */\nexport interface PlatformFacts {\n /** `process.platform`. */\n readonly platform: string;\n /** `process.arch`. */\n readonly arch: string;\n /** The glibc release on Linux, `undefined` on musl or elsewhere. */\n readonly glibc?: string | undefined;\n}\n\n/** What {@link glibcRuntime} needs of `process.report`. */\ninterface Reporter {\n /** Node.js 22.13 and 23.3 or later; `@types/node` 24.19 doesn't declare it yet. */\n excludeNetwork?: boolean;\n getReport(): object;\n}\n\n/**\n * The glibc release Node.js reports, read from its diagnostic report's header. The report runs in\n * the caller's process (a host's server, say) and by default resolves the name of every open TCP\n * handle, synchronously; with `excludeNetwork` it does none of that (Opus review finding 4), as\n * detect-libc does. The setting is restored after.\n */\nexport function glibcRuntime(report: Reporter | undefined): string | undefined {\n if (report === undefined) return undefined;\n const before = report.excludeNetwork ?? false;\n report.excludeNetwork = true;\n try {\n return (report.getReport() as { header?: { glibcVersionRuntime?: string } }).header\n ?.glibcVersionRuntime;\n } finally {\n report.excludeNetwork = before;\n }\n}\n\nlet facts: PlatformFacts | undefined;\n\n/** The facts of the running process, read once. */\nexport function currentPlatform(): PlatformFacts {\n facts ??=\n process.platform === \"linux\"\n ? { platform: process.platform, arch: process.arch, glibc: glibcRuntime(process.report) }\n : { platform: process.platform, arch: process.arch };\n return facts;\n}\n\n/**\n * The bundle platform for these facts. Throws `MOSTRA_PLATFORM_UNSUPPORTED` for other systems and\n * architectures and for Linux without glibc, whose libraries the bundle's Node.js and browser need.\n */\nexport function bundlePlatform(facts: PlatformFacts = currentPlatform()): BundlePlatform {\n const name = `${facts.platform}-${facts.arch}`;\n const known = (BUNDLE_PLATFORMS as readonly string[]).includes(name);\n if (known && facts.platform === \"linux\" && facts.glibc === undefined) {\n throw unsupported(\n `Mostra's Linux bundle needs glibc, and this system has none (musl, as on Alpine Linux); it supports macOS, glibc-based Linux and Windows on x64 and arm64.`,\n );\n }\n if (!known) {\n const label = facts.platform === \"win32\" ? `Windows (${name})` : name;\n throw unsupported(\n `Mostra doesn't run on ${label}; it supports macOS, Linux and Windows on x64 and arm64.`,\n );\n }\n return name as BundlePlatform;\n}\n\nfunction unsupported(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_PLATFORM_UNSUPPORTED\", { message }));\n}\n","/** The SDK's own package: its root directory and its release. */\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nlet found: { readonly root: string; readonly version: string } | undefined;\n\nfunction own(): { readonly root: string; readonly version: string } {\n if (found) return found;\n let dir = dirname(fileURLToPath(import.meta.url));\n for (;;) {\n try {\n const manifest = JSON.parse(readFileSync(join(dir, \"package.json\"), \"utf8\")) as {\n name?: string;\n version?: string;\n };\n if (manifest.name === \"@mostra/sdk\" && manifest.version) {\n found = { root: dir, version: manifest.version };\n return found;\n }\n } catch {\n // Keep looking upwards.\n }\n const parent = dirname(dir);\n if (parent === dir) throw new Error(\"Couldn't find @mostra/sdk's package.json.\");\n dir = parent;\n }\n}\n\n/** This SDK's release: the client version an SDK host reports by default. */\nexport function sdkVersion(): string {\n return own().version;\n}\n\n/** The SDK package's directory; `dist/bundles.json` lives under it in a release. */\nexport function packageRoot(): string {\n return own().root;\n}\n","/**\n * Which runtime a host runs (RT-01, D85). In order:\n *\n * 1. `bundle`, a directory the caller names (the SDK's option), then `MOSTRA_BUNDLE`;\n * 2. `MOSTRA_RUNTIME_BIN`, a `mostra-runtime` entry run with this process's Node (tests and\n * development);\n * 3. the bundle this package itself sits in (the CLI inside a bundle);\n * 4. the bundle this package's release pins (`bundles.json`), from the cache or downloaded;\n * 5. a development checkout's built runtime beside this package.\n *\n * Anything a bundle supplies is checked first: its setup marker must match it, or setup runs.\n */\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { BundlePins, createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport { type InstallProgress, installPinned } from \"./bundle/cache.ts\";\nimport {\n type Bundle,\n type Environment,\n readBundle,\n readSetup,\n type SetupStep,\n setupBundle,\n} from \"./bundle/setup.ts\";\nimport { bundlePlatform } from \"./platform.ts\";\nimport { packageRoot } from \"./version.ts\";\n\n/** A runtime to spawn: the Node.js to run it with and its entry points. */\nexport interface Runtime {\n /** How it was found. */\n readonly source: \"bundle\" | \"override\" | \"development\";\n /** The Node.js executable: the bundle's own, or this process's for the others. */\n readonly node: string;\n /** `mostra-runtime`'s entry (`host`, `daemon`, `service`). */\n readonly runtimeEntry: string;\n /** The `mostra` CLI's entry, when this runtime has one. */\n readonly cliEntry?: string;\n /** The bundle, when the runtime is one. */\n readonly bundle?: Bundle;\n}\n\n/** Options of {@link resolveRuntime}. */\nexport interface RuntimeOptions {\n /** An extracted bundle to use, ahead of everything else. */\n readonly bundle?: string | undefined;\n /** The environment: `MOSTRA_BUNDLE`, `MOSTRA_RUNTIME_BIN`, the cache's variables. */\n readonly env?: Environment | undefined;\n /** Gives up a download or setup. */\n readonly signal?: AbortSignal | undefined;\n /** Progress of a download or setup, for a person waiting (the CLI prints it on stderr). */\n readonly onProgress?: ((progress: InstallProgress) => void) | undefined;\n}\n\n/**\n * Where the pins are read from: `<package>/dist/bundles.json`, which the release writes before\n * publishing. `MOSTRA_TEST_BUNDLE_PINS` names another file only for a package that runs from a\n * development checkout (its real path outside any `node_modules`), where the tests use it: an\n * installed copy (npm's `node_modules`, or a bundle's `lib/node_modules`) ignores it, so a\n * variable leaked into a user's environment can't swap the pins npm's provenance covers (Opus\n * review finding 8).\n */\nexport function pinsFile(env: Environment, root: string): string {\n const override = env[\"MOSTRA_TEST_BUNDLE_PINS\"];\n // Either separator: a path spelled with `/` on Windows is still inside `node_modules`.\n const installed = root.split(/[\\\\/]/).includes(\"node_modules\");\n return override && !installed ? override : join(root, \"dist\", \"bundles.json\");\n}\n\n/** The pins this build carries: `dist/bundles.json` (a test override applies only in a development checkout). */\nexport function readPins(env: Environment): BundlePins | undefined {\n const file = pinsFile(env, packageRoot());\n if (!existsSync(file)) return undefined;\n let data: unknown;\n try {\n data = JSON.parse(readFileSync(file, \"utf8\"));\n } catch {\n data = undefined; // not JSON (or unreadable): the same refusal as a file of the wrong shape\n }\n const parsed = BundlePins.safeParse(data);\n if (!parsed.success) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_INVALID\", {\n message: `${file} isn't a release's bundle pins.`,\n }),\n );\n }\n return parsed.data;\n}\n\n/** The bundle this package was installed into, if any: `<root>/lib/node_modules/@mostra/sdk`. */\nexport function enclosingBundle(): string | undefined {\n const root = resolve(packageRoot(), \"..\", \"..\", \"..\", \"..\");\n return existsSync(join(root, \"bundle.json\")) &&\n existsSync(join(root, \"lib\", \"node_modules\", \"@mostra\", \"sdk\"))\n ? root\n : undefined;\n}\n\n/** The runtime described by a bundle, once it is set up. */\nasync function fromBundle(root: string, options: RuntimeOptions): Promise<Runtime> {\n let bundle = await readBundle(resolve(root));\n if (!(await readSetup(bundle))) {\n await setupBundle(bundle.root, {\n env: options.env,\n signal: options.signal,\n onStep: (step: SetupStep) => options.onProgress?.({ step }),\n });\n bundle = await readBundle(bundle.root);\n }\n return runtimeOf(bundle);\n}\n\n/** A bundle's entry points as a runtime. */\nexport function runtimeOf(bundle: Bundle): Runtime {\n const { root, info } = bundle;\n return {\n source: \"bundle\",\n node: join(root, info.node.path),\n runtimeEntry: join(root, info.entries.runtime),\n cliEntry: join(root, info.entries.cli),\n bundle,\n };\n}\n\n/** A development checkout's runtime: `packages/runtime/dist/bin.js` beside this package. */\nfunction development(): Runtime | undefined {\n const root = packageRoot();\n const entry = resolve(root, \"..\", \"runtime\", \"dist\", \"bin.js\");\n if (!existsSync(entry)) return undefined;\n const cli = resolve(root, \"..\", \"cli\", \"dist\", \"bin.js\");\n return {\n source: \"development\",\n node: process.execPath,\n runtimeEntry: entry,\n ...(existsSync(cli) ? { cliEntry: cli } : {}),\n };\n}\n\n/**\n * Finds the runtime to spawn, downloading and setting up the pinned bundle when nothing nearer\n * exists. Throws `MOSTRA_PLATFORM_UNSUPPORTED`, `MOSTRA_ENV_RUNTIME_MISSING` (a\n * `MOSTRA_RUNTIME_BIN` that doesn't exist), `MOSTRA_ENV_BUNDLE_UNAVAILABLE`,\n * `MOSTRA_ENV_BUNDLE_INVALID` or `MOSTRA_ENV_BUNDLE_DOWNLOAD_FAILED`.\n */\nexport async function resolveRuntime(options: RuntimeOptions = {}): Promise<Runtime> {\n const env = options.env ?? process.env;\n const named = options.bundle ?? (env[\"MOSTRA_BUNDLE\"] || undefined);\n if (named !== undefined) return fromBundle(named, { ...options, env });\n const override = env[\"MOSTRA_RUNTIME_BIN\"];\n if (override) {\n if (!existsSync(override)) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_RUNTIME_MISSING\", {\n message: `MOSTRA_RUNTIME_BIN names ${override}, which doesn't exist.`,\n }),\n );\n }\n return { source: \"override\", node: process.execPath, runtimeEntry: override };\n }\n const enclosing = enclosingBundle();\n if (enclosing !== undefined) return fromBundle(enclosing, { ...options, env });\n const pins = readPins(env);\n if (pins !== undefined) {\n const bundle = await installPinned(pins, {\n env,\n platform: bundlePlatform(),\n signal: options.signal,\n onProgress: options.onProgress,\n });\n return runtimeOf(bundle);\n }\n const checkout = development();\n if (checkout !== undefined) return checkout;\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BUNDLE_UNAVAILABLE\", {\n message:\n \"This build of @mostra/sdk pins no runtime bundle and has no runtime beside it; set MOSTRA_BUNDLE to an extracted bundle.\",\n }),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA4CA,IAAM,QAAN,cAAoB,MAAM,CAAC;;;;;;AAO3B,eAAsB,SACpB,KACA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;EAAE,GAAG;EAAS;CAAI,CAAC;CAC7E,MAAM,OAAO,SAAS,GAAG;CACzB,IAAI,SAAS,KAAA,GAOX,OAAO,UAAU,MANI,cAAc,MAAM;EACvC;EACA,UAAU,eAAe;EACzB,QAAQ,QAAQ;EAChB,YAAY,QAAQ;CACtB,CAAC,CACsB;CAEzB,MAAM,WAAW,YAAY;CAC7B,IAAI,aAAa,KAAA,GAAW,OAAO;CACnC,MAAM,IAAI,SACR,iBAAiB,iCAAiC,EAChD,SACE,2HACJ,CAAC,CACH;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mostra/sdk",
3
- "version": "0.6.2",
3
+ "version": "0.7.0",
4
4
  "description": "Embed Mostra in a JavaScript host: createMostra({ home, ports }) spawns a verified runtime bundle, serves your ports and speaks the host protocol.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "The Mostra Authors",
@@ -34,12 +34,12 @@
34
34
  "provenance": true
35
35
  },
36
36
  "dependencies": {
37
- "@mostra/protocol": "0.6.2",
37
+ "@mostra/protocol": "0.7.0",
38
38
  "tar": "7.5.22",
39
39
  "undici": "8.12.3"
40
40
  },
41
41
  "devDependencies": {
42
- "@mostra/runtime": "0.6.2",
42
+ "@mostra/runtime": "0.7.0",
43
43
  "@mostra/tools": "0.0.0",
44
44
  "@types/node": "24.19.2",
45
45
  "tsdown": "0.23.1",
@@ -260,7 +260,7 @@ async function fetchInto(
260
260
  * tried again with backoff for up to 3 s, as the runtime's renames are (D150 item 8), and never
261
261
  * turned into a copy; a refusal that lasts is thrown, and EPERM over an existing directory with it.
262
262
  */
263
- async function renameIntoPlace(from: string, to: string): Promise<void> {
263
+ export async function renameIntoPlace(from: string, to: string): Promise<void> {
264
264
  const deadline = Date.now() + 3000;
265
265
  for (let wait = 25; ; wait = Math.min(wait * 2, 400)) {
266
266
  try {
package/src/mostra.ts CHANGED
@@ -44,11 +44,14 @@ import {
44
44
  type MethodDefinition,
45
45
  type MostraInitializeResult,
46
46
  mostraInitializeMethod,
47
+ type PortAddressingExternalBaseParams,
48
+ type PortAddressingExternalBaseResult,
47
49
  type PortIdentityResolveParams,
48
50
  type PortName,
49
51
  type PortSecretsGetParams,
50
52
  type PortTrustedControlsActivatedParams,
51
53
  type PublishReceipt,
54
+ portAddressingExternalBaseMethod,
52
55
  portDraftsMirrorMethod,
53
56
  portIdentityResolveMethod,
54
57
  portSecretsGetMethod,
@@ -61,6 +64,9 @@ import {
61
64
  RpcPeer,
62
65
  receivable,
63
66
  resultsGetMethod,
67
+ type ShareStartParams,
68
+ type ShareStartResult,
69
+ type ShareStopResult,
64
70
  type SourceRef,
65
71
  type StateGetResult,
66
72
  type StatePatchParams,
@@ -69,6 +75,8 @@ import {
69
75
  type SubmissionPolicy,
70
76
  type SubmissionsDeliverResult,
71
77
  type SubmitChannel,
78
+ shareStartMethod,
79
+ shareStopMethod,
72
80
  stateGetMethod,
73
81
  statePatchMethod,
74
82
  type VerifyVerdict,
@@ -109,6 +117,17 @@ export interface Ports {
109
117
  };
110
118
  /** Receives each viewer draft's latest revision, best effort, never retried (IN-06). */
111
119
  readonly drafts?: { mirror(draft: DraftMirror): void | Promise<void> };
120
+ /**
121
+ * Gives one of an artifact's listeners an external address (HO-10, D158 item 6): the origin of
122
+ * the host's own tunnel that forwards to `request.local`, which joins the links Mostra mints
123
+ * and its Host allowlist; `null` keeps the loopback address, and withdraws one given before.
124
+ * Answer within 5 s.
125
+ */
126
+ readonly addressing?: {
127
+ externalBase(
128
+ request: PortAddressingExternalBaseParams,
129
+ ): PortAddressingExternalBaseResult | Promise<PortAddressingExternalBaseResult>;
130
+ };
112
131
  /** Answers `secret()` first, before the home's store (D131); `null` falls back. */
113
132
  readonly secrets?: {
114
133
  get(request: PortSecretsGetParams): string | null | Promise<string | null>;
@@ -252,6 +271,16 @@ export interface Mostra {
252
271
  artifact: ArtifactInput,
253
272
  options?: Omit<ViewUrlParams, "artifact">,
254
273
  ): Promise<CapabilityLink>;
274
+ /**
275
+ * `share/start`: opens the artifact through a tunnel this machine runs (D158): `tailnet`
276
+ * (Tailscale Serve), or a public `funnel` or `cloudflare` share with a link that expires.
277
+ */
278
+ share(
279
+ artifact: ArtifactInput,
280
+ options: Omit<ShareStartParams, "artifact">,
281
+ ): Promise<ShareStartResult>;
282
+ /** `share/stop`: ends a share by its ID, and revokes its link. */
283
+ stopShare(shareId: string): Promise<ShareStopResult>;
255
284
  /**
256
285
  * The events matching `options.filter`, page by page, in cursor order, with no gap across a
257
286
  * pause (`events/subscribe`). With a `name`, each page is acknowledged when the next one is
@@ -271,6 +300,7 @@ export interface CallOptions {
271
300
  /** The port methods the SDK serves, by port. */
272
301
  const PORT_METHODS = {
273
302
  identity: [portIdentityResolveMethod],
303
+ addressing: [portAddressingExternalBaseMethod],
274
304
  submissions: [portSubmissionsDeliverMethod],
275
305
  drafts: [portDraftsMirrorMethod],
276
306
  secrets: [portSecretsGetMethod],
@@ -297,6 +327,11 @@ function portHandler(ports: Ports, method: string): ((params: unknown) => unknow
297
327
  return (
298
328
  ports.identity && ((params) => ports.identity?.resolve(params as PortIdentityResolveParams))
299
329
  );
330
+ case portAddressingExternalBaseMethod.method:
331
+ return (
332
+ ports.addressing &&
333
+ ((params) => ports.addressing?.externalBase(params as PortAddressingExternalBaseParams))
334
+ );
300
335
  case portSubmissionsDeliverMethod.method:
301
336
  return (
302
337
  ports.submissions && ((params) => ports.submissions?.deliver(params as SubmissionEnvelope))
@@ -592,6 +627,9 @@ export async function createMostra(options: MostraOptions): Promise<Mostra> {
592
627
  call(livePushMethod, { artifact: artifactRef(artifact), ...push }),
593
628
  viewUrl: (artifact, urlOptions = {}) =>
594
629
  call(viewUrlMethod, { artifact: artifactRef(artifact), ...urlOptions }),
630
+ share: (artifact, shareOptions) =>
631
+ call(shareStartMethod, { artifact: artifactRef(artifact), ...shareOptions }),
632
+ stopShare: (shareId) => call(shareStopMethod, { shareId }),
595
633
  events: (streamOptions = {}) =>
596
634
  openEventStream(
597
635
  {