posipaki 0.44.0 → 0.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/{hooks-Dpbe39oa.d.ts → hooks-DO-efRM_.d.ts} +2 -2
  2. package/dist/{hooks-Dpbe39oa.d.ts.map → hooks-DO-efRM_.d.ts.map} +1 -1
  3. package/dist/hooks.d.ts +1 -1
  4. package/dist/index.d.ts +4 -4
  5. package/dist/index.js +1 -1
  6. package/dist/plugins/debug-logger.d.ts +2 -2
  7. package/dist/plugins/tree-introspection.d.ts +2 -2
  8. package/dist/{process-CoEKoY5f.d.ts → process-eCAv2tIS.d.ts} +2 -2
  9. package/dist/{process-CoEKoY5f.d.ts.map → process-eCAv2tIS.d.ts.map} +1 -1
  10. package/dist/remote/gateway-cli.js +1157 -50
  11. package/dist/remote/gateway-cli.js.map +1 -1
  12. package/dist/remote/index.d.ts +4 -232
  13. package/dist/remote/index.d.ts.map +1 -1
  14. package/dist/remote/index.js +2 -2
  15. package/dist/remote/index.js.map +1 -1
  16. package/dist/remote/node.d.ts +29 -54
  17. package/dist/remote/node.d.ts.map +1 -1
  18. package/dist/remote/node.js +128 -128
  19. package/dist/remote/node.js.map +1 -1
  20. package/dist/testing/index.d.ts +4 -4
  21. package/dist/testing/index.d.ts.map +1 -1
  22. package/dist/testing/index.js.map +1 -1
  23. package/dist/{types-CuabnerI.d.ts → types-U3NvKgpg.d.ts} +10 -1
  24. package/dist/{types-CuabnerI.d.ts.map → types-U3NvKgpg.d.ts.map} +1 -1
  25. package/dist/{version-B6eNJRZD.js → version-yonmO5bG.js} +2 -2
  26. package/dist/{version-B6eNJRZD.js.map → version-yonmO5bG.js.map} +1 -1
  27. package/dist/websocket-DT8zKD34.d.ts +836 -0
  28. package/dist/websocket-DT8zKD34.d.ts.map +1 -0
  29. package/dist/{websocket-DecgMfb3.js → websocket-DkDAHMFm.js} +1102 -85
  30. package/dist/websocket-DkDAHMFm.js.map +1 -0
  31. package/dist/xfetch.d.ts +2 -2
  32. package/package.json +1 -1
  33. package/dist/websocket-DecgMfb3.js.map +0 -1
  34. package/dist/websocket-sGQcEDbm.d.ts +0 -310
  35. package/dist/websocket-sGQcEDbm.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"node.js","names":["atPath","wireErrorFrame","wireErrorReason","errorText","errorText","Lines"],"sources":["../../src/remote/transports/fifo.ts","../../src/remote/fifo.ts","../../src/remote/spawners/fifo-command.ts","../../src/remote/kit.ts","../../src/remote/spawners/fifo-argv.ts","../../src/remote/define-subprocess.ts","../../src/remote/stdio.ts","../../src/remote/streams.ts","../../src/remote/gateway.ts","../../src/remote/host.ts","../../src/remote/gateway-client.ts","../../src/remote/socket.ts","../../src/remote/spawners/socket-client.ts","../../src/remote/websocket.ts"],"sourcesContent":["// ── FIFO transport ─────────────────────────────────────────────────────────\n//\n// Newline-delimited UTF-8 over named fifos. Strict handler lifecycle:\n// onMessage() throws if a handler is already set; call removeHandler() first.\n\nimport { open, type FileHandle } from \"node:fs/promises\";\nimport type { ReadStream, WriteStream } from \"node:fs\";\nimport * as readline from \"node:readline\";\nimport type { StringTransport } from \"../channel.js\";\n\nexport class FifoUtf8NlineTransport implements StringTransport {\n private readFd: FileHandle | null;\n private writeFd: FileHandle | null;\n private rl: readline.Interface | null;\n private rs: ReadStream | null;\n private ws: WriteStream | null;\n private pvtOnMessage: ((line: string) => void) | null = null;\n private pvtOnClose: (() => void) | null = null;\n private closed = false;\n private closingPromise: Promise<void> | null = null;\n private pvtError: Error | null = null;\n\n private constructor(opts: { readFd?: FileHandle; writeFd?: FileHandle }) {\n this.readFd = opts.readFd ?? null;\n this.writeFd = opts.writeFd ?? null;\n\n if (this.readFd) {\n this.rs = this.readFd.createReadStream({ encoding: \"utf-8\" });\n this.rl = readline.createInterface({ input: this.rs });\n\n this.rl.on(\"line\", (line) => {\n if (this.pvtOnMessage && !this.closed) this.pvtOnMessage(line);\n });\n\n this.rl.on(\"close\", () => {\n this.pvtOnClose?.();\n this.close();\n });\n\n this.rs.on(\"error\", (err: Error) => {\n this.pvtError = err;\n this.close();\n });\n } else {\n this.rs = null;\n this.rl = null;\n }\n\n if (this.writeFd) {\n this.ws = this.writeFd.createWriteStream({ encoding: \"utf-8\" });\n this.ws.on(\"error\", (err: Error) => {\n this.pvtError = err;\n this.close();\n });\n } else {\n this.ws = null;\n }\n }\n\n // ── factories ──────────────────────────────────────────────────────────\n\n static openReaderFd(readFd: FileHandle): FifoUtf8NlineTransport {\n return new FifoUtf8NlineTransport({ readFd });\n }\n\n static openWriterFd(writeFd: FileHandle): FifoUtf8NlineTransport {\n return new FifoUtf8NlineTransport({ writeFd });\n }\n\n static fromFds(readFd: FileHandle, writeFd: FileHandle): FifoUtf8NlineTransport {\n return new FifoUtf8NlineTransport({ readFd, writeFd });\n }\n\n // ── bidirectional connection ───────────────────────────────────────────\n\n /**\n * Start opening a bidirectional connection. Opens readPath for reading\n * in the background, returns a promise. The caller should do whatever\n * setup is needed to unblock the read (e.g. spawn a process that opens\n * readPath for writing), then await the returned transport.\n *\n * The transport itself is built only once both directions are open. A read\n * stream created while no writer exists on its fifo is handed an immediate\n * end-of-stream by some runtimes (bun), which closes a channel that has not\n * carried a byte yet — so the writes side is opened before the reader exists.\n */\n static beginConnect(\n readPath: string,\n writePath: string,\n ): { transport: Promise<FifoUtf8NlineTransport> } {\n const readFdPromise = open(readPath, \"r\");\n\n const transport = readFdPromise.then(async (readFd) => {\n const writeFd = await open(writePath, \"w\");\n return FifoUtf8NlineTransport.fromFds(readFd, writeFd);\n });\n\n return { transport };\n }\n\n /**\n * Open a bidirectional connection. Opens writePath for writing first\n * (unblocking the peer's read), starts reading readPath in the\n * background, then awaits both.\n *\n * Use this when you are the side that responds to the peer's beginConnect\n * (i.e. you don't need to interleave any setup between the read and write\n * opens). Built like `beginConnect`: the transport exists only after both\n * directions do.\n */\n static async connect(readPath: string, writePath: string): Promise<FifoUtf8NlineTransport> {\n const readFdPromise = open(readPath, \"r\");\n const writeFd = await open(writePath, \"w\");\n const readFd = await readFdPromise;\n return FifoUtf8NlineTransport.fromFds(readFd, writeFd);\n }\n\n // ── public API ─────────────────────────────────────────────────────────\n\n get canSend(): boolean {\n return this.writeFd !== null && !this.closed;\n }\n\n onMessage(handler: (line: string) => void): void {\n if (this.closed) throw new Error(\"FifoUtf8NlineTransport: closed\");\n if (this.readFd === null) throw new Error(\"FifoUtf8NlineTransport: not a reader\");\n if (this.pvtOnMessage !== null) {\n throw new Error(\"FifoUtf8NlineTransport: handler already set — call removeHandler() first\");\n }\n this.pvtOnMessage = handler;\n }\n\n removeHandler(): ((line: string) => void) | null {\n const prev = this.pvtOnMessage;\n this.pvtOnMessage = null;\n return prev;\n }\n\n onClose(handler: () => void): void {\n this.pvtOnClose = handler;\n }\n\n get hasHandler(): boolean {\n return this.pvtOnMessage !== null;\n }\n\n get lastError(): Error | null {\n return this.pvtError;\n }\n\n async send(line: string): Promise<void> {\n if (this.closed) throw new Error(\"FifoUtf8NlineTransport: closed\");\n if (this.writeFd === null) throw new Error(\"FifoUtf8NlineTransport: not a writer\");\n if (!line.endsWith(\"\\n\")) line += \"\\n\";\n await this.ws?.write(line);\n }\n\n async close(): Promise<void> {\n this.closingPromise = this.closingPromise || this.pvtClose();\n await this.closingPromise;\n this.closed = true;\n }\n\n private async pvtClose(): Promise<void> {\n // tranfser control back to caller\n // so they can capture the promise reference\n // and prevent reentry\n await Promise.resolve();\n\n if (this.rl) {\n this.rl.close();\n this.rl = null;\n }\n if (this.rs) {\n this.rs.destroy();\n this.rs = null;\n }\n if (this.ws) {\n await new Promise<void>((resolve) => {\n try {\n this.ws?.end(\"\", resolve);\n } catch {\n resolve();\n }\n });\n this.ws = null;\n }\n\n if (this.readFd) {\n try {\n await this.readFd.close();\n } catch {}\n this.readFd = null;\n }\n if (this.writeFd) {\n try {\n await this.writeFd.close();\n } catch {}\n this.writeFd = null;\n }\n }\n}\n","// ── a fifo pair, as a listener and as a client ─────────────────────────────\n//\n// Two named pipes are one connection: whoever reads one and writes the other is talking to the side that\n// did the opposite. The medium gives one client per lifetime, so the listener takes one connection and is\n// done, and the pair itself is made idempotently and never removed from under a client's feet.\n\nimport { execFile } from \"node:child_process\";\nimport { mkdir, open, stat } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { promisify } from \"node:util\";\n\nimport type { ClientSpawner } from \"./client.js\";\nimport { isProto } from \"./channel.js\";\nimport { json1Channel, VERSION } from \"./protocols/json1.js\";\nimport type { Connection, Listener } from \"./reactor.js\";\nimport { FifoUtf8NlineTransport } from \"./transports/fifo.js\";\n\nconst runMkfifo = promisify(execFile);\n\n/**\n * The pair, named as the serving side sees it: `read` is where it reads, and `write` where it writes. The\n * client side passes the same pair and swaps them, which is what makes it a pair rather than two paths.\n */\nexport interface FifoPair {\n readonly read: string;\n readonly write: string;\n}\n\nexport interface FifoListenerOptions<Meta = unknown> {\n /** Make the pair when it is missing, and refuse a path that exists and is not a fifo. Default true. */\n make?: boolean;\n /** Admission and identity: what this returns is the connection's meta. */\n identify?(pair: FifoPair): Meta | Promise<Meta>;\n}\n\n/** What is at a path: nothing, a fifo, or something else. */\nasync function atPath(path: string): Promise<\"missing\" | \"fifo\" | \"other\"> {\n try {\n const info = await stat(path);\n return info.isFIFO() ? \"fifo\" : \"other\";\n } catch {\n return \"missing\";\n }\n}\n\n/**\n * Make the pair unless it is already there. A fifo is a file and one pair serves every connection, so\n * nothing is recreated; something that is not a fifo where the pair goes is refused rather than worked\n * around, because a regular file read as input is a silence nobody can explain.\n */\nexport async function makeFifoPair(pair: FifoPair): Promise<void> {\n await mkdir(dirname(pair.read), { recursive: true });\n await mkdir(dirname(pair.write), { recursive: true });\n for (const path of [pair.read, pair.write]) {\n const there = await atPath(path);\n if (there === \"fifo\") continue;\n if (there === \"other\") throw new Error(`makeFifoPair: ${path} is not a fifo`);\n await runMkfifo(\"mkfifo\", [\"-m\", \"0600\", path]);\n }\n}\n\n/**\n * Listen on a pair, as the served side: it reads `pair.read` and writes `pair.write`, and it opens the\n * write end first. That order is the handshake: a stream opened for reading on a fifo nobody writes to is\n * handed an immediate end-of-stream by some runtimes, which closes a connection that never carried a byte.\n */\nexport async function fifoListener<Meta = unknown>(\n pair: FifoPair,\n options: FifoListenerOptions<Meta> = {},\n): Promise<Listener<Meta>> {\n if (options.make ?? true) await makeFifoPair(pair);\n\n let taken = false;\n let closed = false;\n let parked: (() => Promise<void>) | null = null;\n let settled: Promise<void> = Promise.resolve();\n let release: { close: () => Promise<void> } | null = null;\n\n const unblock = async (): Promise<void> => {\n // The parked open is a writer waiting for a reader on `write`; reading it here is what releases it,\n // and a writer on `read` is what releases the read it opens next. Both are held until it is through.\n const reader = await open(pair.write, \"r\");\n const writer = await open(pair.read, \"w\");\n release = {\n close: async () => {\n await writer.close();\n await reader.close();\n },\n };\n };\n return {\n async accept(): Promise<Connection<Meta>> {\n if (taken) throw new Error(\"fifoListener: the pair carries one connection per lifetime\");\n if (closed) throw new Error(\"fifoListener: closed\");\n taken = true;\n parked = unblock;\n\n let through: () => void = () => {};\n settled = new Promise<void>((resolve) => {\n through = resolve;\n });\n try {\n const transport = await FifoUtf8NlineTransport.connect(pair.read, pair.write);\n parked = null;\n if (closed) {\n // The release is what let this open through, and the listener is over: the connection it made is\n // closed rather than served.\n await transport.close();\n throw new Error(\"fifoListener: closed while waiting for a connection\");\n }\n const meta = options.identify ? await options.identify(pair) : (undefined as Meta);\n return { meta, transport };\n } finally {\n through();\n }\n },\n async close(): Promise<void> {\n closed = true;\n // Release a wait parked on the pair, let the accept finish either way, and only then let go of the\n // handles that released it: they are what the parked open was waiting for.\n if (parked) await parked();\n await settled;\n await release?.close();\n },\n };\n}\n\n/**\n * Connect to a pair, as the client side: it reads what the listener writes and writes what it reads,\n * and it awaits the `$proto` frame, which is the side of the handshake a served actor speaks.\n */\nexport function fifoClientSpawner<Args = unknown>(\n pair: FifoPair | ((args: Args) => FifoPair),\n): ClientSpawner<Args> {\n return async (args) => {\n const served = typeof pair === \"function\" ? pair(args) : pair;\n // The swap: this side reads what the serving side writes.\n const { transport } = FifoUtf8NlineTransport.beginConnect(served.write, served.read);\n const channel = json1Channel(await transport);\n const first = await new Promise<Record<string, unknown>>((resolve) => {\n const off = channel.onMessage((frame) => {\n off();\n resolve(frame);\n });\n });\n if (!isProto(first) || first.$proto !== VERSION) {\n throw new Error(`unsupported protocol: ${JSON.stringify(first).slice(0, 50)}`);\n }\n return channel;\n };\n}\n","// ── FIFO client spawner (command) ──────────────────────────────────────────\n//\n// Environment-specific: spawns a command, makes the two named fifos it is to serve on, and hands back\n// the frame Channel whose far side is that child. The pair's own half is fifo.ts's — connect, and wait\n// for the `$proto` — so what is left here is the child, the paths in its argv, and the cleanup.\n\nimport { spawn } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { unlink } from \"node:fs/promises\";\nimport type { Channel } from \"../channel.js\";\nimport { fifoClientSpawner, makeFifoPair } from \"../fifo.js\";\n\nexport function commandSpawner(command: string[]): () => Promise<Channel> {\n return async () => {\n const basePath = join(tmpdir(), `posipaki-${randomUUID()}`);\n // The pair as the child meets it: it reads `.out` and writes `.in`. Made before the child exists,\n // so the child's own open finds it waiting rather than making it late.\n await makeFifoPair({ read: `${basePath}.out`, write: `${basePath}.in` });\n\n const child = spawn(\n command[0],\n [...command.slice(1), `--fifo-in=${basePath}.in`, `--fifo-out=${basePath}.out`],\n {\n cwd: process.cwd(),\n stdio: [\"inherit\", \"inherit\", \"inherit\"],\n },\n );\n\n const channel = await fifoClientSpawner<unknown>({\n read: `${basePath}.out`,\n write: `${basePath}.in`,\n })(undefined);\n\n let cleaned = false;\n const cleanup = (): void => {\n if (cleaned) return;\n cleaned = true;\n void channel.close();\n unlink(`${basePath}.in`).catch(() => {});\n unlink(`${basePath}.out`).catch(() => {});\n };\n child.on(\"exit\", cleanup);\n\n return channel;\n };\n}\n","// ── Kit ────────────────────────────────────────────────────────────────────\n//\n// Getting a payload onto a host we know nothing about. A way in gives us a\n// shell; from there one script runs everywhere: probe what is really there, write\n// the kit only if it is not, and report every step as one machine-readable line.\n// The script always arrives on stdin, never in argv — and since stdin *is* the\n// script, the payload gets its own channel into the same environment (a second\n// `ssh`, an `exec` on a container that is already running).\n//\n// The script assumes POSIX sh and nothing else: `command -v`, `mkdir -p`,\n// `wc -c`, `base64 -d`. A broken environment therefore reaches the client as a\n// readable reason instead of a channel that just closes.\n//\n// A kit is named after the *host version* it serves — the app, the build its bytes came from\n// and the posipaki release that speaks to it — so two consumers, two builds or two releases\n// cannot land on each other's files, and the directory a kit sits in cannot disagree with the\n// identity the client then states on the wire. A payload that is started for a host version\n// other than its own refuses to serve (see `hostVersionAccepts`), so a name alone is never\n// mistaken for the build behind it.\n\nimport { createHash } from \"node:crypto\";\nimport { LIB_VERSION } from \"../version.js\";\n\n/** Runtimes a kit is happy to be run with, best first. A caller may override. */\nexport const DEFAULT_RUNTIMES = [\"node\", \"nodejs\", \"bun\"];\n\n/** Layout of a staged kit — the contract's own version, recorded in `version.json`. */\nexport const KIT_LAYOUT = 1;\n\n/** Where kits live on a host, relative to `$HOME`, unless the caller says otherwise. */\nexport const DEFAULT_KIT_PARENT = \"bin/posipaki\";\n\n/** The names a kit's two bundles get: the payload, and the gateway that relays to it. */\nexport const PAYLOAD_ARTIFACT = \"payload.js\";\nexport const GATEWAY_ARTIFACT = \"gateway.js\";\n\nexport interface KitFile {\n /** Name inside the kit directory, e.g. `payload.js`. */\n name: string;\n /** The file's bytes, base64 — what the script writes. */\n base64: string;\n /** Byte count, for the cheap presence check. */\n bytes: number;\n /** sha256 of the file, recorded in `version.json`. */\n sha256: string;\n}\n\n/** Who is staging this kit: the consumer's own name and build version. */\nexport interface KitApp {\n name: string;\n version: string;\n}\n\nexport interface Kit {\n /** Directory name: the host version this kit serves, as {@link hostVersion} renders it. */\n name: string;\n /** Everything the kit installs, `version.json` last. */\n files: KitFile[];\n /** Runtime candidates, in order; the first one found wins. */\n runtimes: string[];\n /** Directory the kit lands in, relative to the host's `$HOME`. */\n parent: string;\n /** The consumer this kit belongs to. */\n app: KitApp;\n}\n\nexport interface MakeKitOptions {\n /** Required: a kit with no owner cannot be told apart from another's. */\n app: KitApp;\n /** Defaults to {@link DEFAULT_RUNTIMES}. */\n runtimes?: string[];\n /** Defaults to {@link DEFAULT_KIT_PARENT}. */\n parent?: string;\n}\n\nexport type BootstrapReport =\n | { kind: \"ready\"; kitDir: string; runtime: string; staged: boolean }\n | { kind: \"error\"; reason: string };\n\n/** Hex sha256 of some content. */\nexport function sha256Hex(content: string | Uint8Array): string {\n return createHash(\"sha256\").update(content).digest(\"hex\");\n}\n\n/** What may stand as one fact in a host version: no `@`, no whitespace, no `/`. */\nconst FACT = /^[A-Za-z0-9][A-Za-z0-9.+_-]*$/;\n\n/** The label posipaki's own field carries, so nobody has to guess which field it is. */\nconst POSIPAKI_FIELD = \"posipaki-\";\n\n/** A host version read back: what a consumer stated, and the posipaki that rendered it. */\nexport interface HostVersion extends KitApp {\n posipaki: string;\n}\n\n/** A name or version that could not stand as one fact in a host version. */\nexport class HostVersionError extends Error {}\n\n/**\n * The one value that says what a host is expected to run: whose payload it is, which build\n * those bytes came from, and the posipaki release that speaks to it —\n * `email-agent@1.0.0+d52ee13@posipaki-0.35.0`.\n *\n * One string rather than three flags because it is one fact: it names the kit directory, it\n * travels with every way in, and the payload compares it with its own before it serves. A\n * consumer states the two facts only it knows; posipaki renders its own release, so that\n * field cannot be got wrong. `@` separates, and no name or version may contain one.\n */\nexport function hostVersion(app: KitApp): string {\n const facts: [string, string][] = [\n [\"name\", app.name],\n [\"version\", app.version],\n ];\n for (const [what, value] of facts) {\n if (!FACT.test(value)) {\n throw new HostVersionError(\n `an app ${what} must match ${FACT.source}: ${JSON.stringify(value)}`,\n );\n }\n }\n return `${app.name}@${app.version}@${POSIPAKI_FIELD}${LIB_VERSION}`;\n}\n\n/** What a {@link hostVersion} string names, or undefined when it names nothing. */\nexport function parseHostVersion(text: string): HostVersion | undefined {\n const fields = text.split(\"@\");\n if (fields.length !== 3) return undefined;\n const [name, version, posipaki] = fields as [string, string, string];\n if (!FACT.test(name) || !FACT.test(version)) return undefined;\n if (!posipaki.startsWith(POSIPAKI_FIELD)) return undefined;\n const release = posipaki.slice(POSIPAKI_FIELD.length);\n if (!FACT.test(release)) return undefined;\n return { name, version, posipaki: release };\n}\n\n/** Exit code a payload refuses a start with: it is not the build that was asked for. */\nexport const PAYLOAD_REFUSED = 78;\n\nexport type HostVersionVerdict = { ok: true } | { ok: false; reason: string };\n\n/**\n * Whether a payload may serve what it was asked for. `own` is what its bytes carry, `asked`\n * is what the caller said — two independent facts, and one of the four combinations is the\n * dangerous one: an artifact that knows what it is, started by a caller that never said which\n * host version it is for, is exactly the stale caller we refuse.\n *\n * No baked version, nothing to compare: an artifact that does not know what it is cannot be\n * wrong about it, and a caller that states a version for such a payload is only being helpful.\n */\nexport function hostVersionAccepts(\n own: string | undefined,\n asked: string | undefined,\n): HostVersionVerdict {\n if (own === undefined) return { ok: true };\n if (asked === undefined) {\n return { ok: false, reason: `this artifact is ${own}, and no host version was asked for` };\n }\n if (!sameHostVersion(own, asked)) {\n return { ok: false, reason: `asked to serve ${asked}, but this artifact is ${own}` };\n }\n return { ok: true };\n}\n\n/**\n * Whether two host versions are the same build. Equality for now: {@link hostVersionAccepts}\n * is the rule, and this is the one function that decides what \"the same\" means — so a range, a\n * compatibility table or a protocol-only comparison is a change here and nowhere else.\n */\nexport function sameHostVersion(own: string, asked: string): boolean {\n return own === asked;\n}\n\n/** Wrap base64 at a comfortable width; `base64 -d` ignores the newlines. */\nfunction wrapped(base64: string, width = 76): string {\n const lines: string[] = [];\n for (let at = 0; at < base64.length; at += width) lines.push(base64.slice(at, at + width));\n return lines.join(\"\\n\");\n}\n\n/**\n * Describe a kit around its files. Its name is the host version it serves, and `version.json`\n * — which records that name and every file's hash — is written as one of them: it describes\n * the payload and the gateway, never itself.\n */\nexport function makeKit(\n files: { name: string; content: string | Uint8Array }[],\n options: MakeKitOptions,\n): Kit {\n const raw = files.map((file) => ({\n name: file.name,\n bytes: Buffer.byteLength(file.content),\n sha256: sha256Hex(file.content),\n base64: Buffer.from(file.content).toString(\"base64\"),\n }));\n const kit: Kit = {\n name: hostVersion(options.app),\n files: raw,\n runtimes: [...(options.runtimes ?? DEFAULT_RUNTIMES)],\n parent: options.parent ?? DEFAULT_KIT_PARENT,\n app: options.app,\n };\n const version = Buffer.from(`${JSON.stringify(kitVersion(kit), null, 2)}\\n`);\n return {\n ...kit,\n files: [\n ...kit.files,\n {\n name: \"version.json\",\n bytes: version.byteLength,\n sha256: sha256Hex(version),\n base64: version.toString(\"base64\"),\n },\n ],\n };\n}\n\n/** What `version.json` says: the identity, the facts it was rendered from, and the hashes. */\nexport function kitVersion(kit: Kit): Record<string, unknown> {\n return {\n hostVersion: kit.name,\n app: kit.app,\n posipaki: LIB_VERSION,\n layout: KIT_LAYOUT,\n files: kit.files.map((file) => ({ name: file.name, sha256: file.sha256, bytes: file.bytes })),\n };\n}\n\n/** The `[ -f … ] && [ \"$(wc -c < …)\" -eq … ]` test for one file. */\nfunction presentTest(file: KitFile): string {\n return `[ -f \"$kit_dir/${file.name}\" ] && [ \"$(wc -c < \"$kit_dir/${file.name}\")\" -eq ${file.bytes} ]`;\n}\n\n/** One file: write it to a temp name, then move it into place. */\nfunction writeFile(file: KitFile): string {\n return [\n ` base64 -d > \"$tmp\" <<'KIT_FILE'`,\n wrapped(file.base64),\n \"KIT_FILE\",\n ` mv \"$tmp\" \"$kit_dir/${file.name}\" || { echo \"error cannot install ${file.name}\"; exit 73; }`,\n ].join(\"\\n\");\n}\n\n/**\n * The bootstrap, as one POSIX sh script.\n *\n * Staging is the whole job. The script always arrives on stdin, never in argv,\n * and that is also why it cannot carry the wire: the caller runs the payload on a\n * second channel into the same environment once this one has reported.\n */\nexport function bootstrapScript(kit: Kit): string {\n const checks = kit.files.map(presentTest).join(\" && \\\\\\n \");\n const lines = [\n \"# ── kit bootstrap ─────────────────────────────────────────────────────────\",\n \"# probe, stage what is missing, report every step as one machine-readable line.\",\n \"set -u\",\n \"\",\n 'if [ -z \"${HOME:-}\" ]; then echo \"error HOME is not set\"; exit 74; fi',\n `kit_dir=\"$HOME/${kit.parent}/${kit.name}\"`,\n \"\",\n 'runtime=\"\"',\n `for candidate in ${kit.runtimes.join(\" \")}; do`,\n ' if command -v \"$candidate\" >/dev/null 2>&1; then runtime=\"$(command -v \"$candidate\")\"; break; fi',\n \"done\",\n `if [ -z \"$runtime\" ]; then echo \"error no runtime among: ${kit.runtimes.join(\" \")}\"; exit 75; fi`,\n 'if ! command -v base64 >/dev/null 2>&1; then echo \"error base64 is missing\"; exit 76; fi',\n \"\",\n `if ${checks}; then`,\n ' echo \"present\"',\n \"else\",\n ` mkdir -p \"$kit_dir\" || { echo \"error cannot create $kit_dir\"; exit 73; }`,\n ' tmp=\"$kit_dir/.staging.$$\"',\n ...kit.files.map(writeFile),\n ' echo \"staged\"',\n \"fi\",\n 'echo \"kit $kit_dir\"',\n 'echo \"runtime $runtime\"',\n ];\n return `${lines.join(\"\\n\")}\\n`;\n}\n\n/** Read the script's report back. Missing or unknown lines are an error. */\nexport function parseBootstrapReport(stdout: string): BootstrapReport {\n let kitDir = \"\";\n let runtime = \"\";\n let staged: boolean | null = null;\n for (const raw of stdout.split(\"\\n\")) {\n const line = raw.trim();\n if (line === \"\") continue;\n if (line.startsWith(\"error \")) return { kind: \"error\", reason: line.slice(\"error \".length) };\n if (line === \"staged\") {\n staged = true;\n continue;\n }\n if (line === \"present\") {\n staged = false;\n continue;\n }\n if (line.startsWith(\"kit \")) {\n kitDir = line.slice(\"kit \".length);\n continue;\n }\n if (line.startsWith(\"runtime \")) {\n runtime = line.slice(\"runtime \".length);\n continue;\n }\n }\n if (kitDir === \"\" || runtime === \"\" || staged === null) {\n const seen = stdout.trim();\n return {\n kind: \"error\",\n reason: seen === \"\" ? \"no report at all\" : `incomplete report: ${seen}`,\n };\n }\n return { kind: \"ready\", kitDir, runtime, staged };\n}\n","// ── FIFO server spawner (argv) ─────────────────────────────────────────────\n//\n// Environment-specific: reads what the caller put in argv — the two named fifos, and the host\n// version this artifact is being started for — checks that it *is* that build, connects, and\n// returns a frame Channel with the $proto handshake already sent.\n//\n// The check comes first, before anything is opened: a payload that is not the build that was\n// asked for has no business on a wire, and saying so before it connects is the only moment\n// where the reason is still readable to the caller.\n\nimport { FifoUtf8NlineTransport } from \"../transports/fifo.js\";\nimport { json1Channel, VERSION } from \"../protocols/json1.js\";\nimport type { Channel } from \"../channel.js\";\nimport { PAYLOAD_REFUSED, hostVersionAccepts } from \"../kit.js\";\n\n/** A `--flag=<value>` argument, or undefined. */\nfunction flag(name: string): string | undefined {\n const prefix = `--${name}=`;\n return process.argv.find((a) => a.startsWith(prefix))?.slice(prefix.length);\n}\n\n/**\n * Serve one payload over the fifo pair in argv.\n *\n * `own` is the host version this artifact's bytes carry, when its build stamped one: given it,\n * the payload refuses to serve a host version that differs, and refuses a start that names\n * none. Nothing stamped means nothing to check — and `--host-version`, if the caller sent one\n * anyway, is simply not ours to compare with.\n */\nexport async function fifoArgvSpawner(own?: string): Promise<Channel> {\n const verdict = hostVersionAccepts(own, flag(\"host-version\"));\n if (!verdict.ok) {\n console.error(`payload: ${verdict.reason}`);\n process.exit(PAYLOAD_REFUSED);\n }\n\n const fifoIn = flag(\"fifo-in\");\n const fifoOut = flag(\"fifo-out\");\n if (!fifoIn || !fifoOut) {\n console.error(\"server: --fifo-in=<path> and --fifo-out=<path> required\");\n process.exit(1);\n }\n\n const transport = await FifoUtf8NlineTransport.connect(fifoOut, fifoIn);\n const channel = json1Channel(transport);\n await channel.send({ $proto: VERSION });\n return channel;\n}\n","// ── defineSubprocessActor ───────────────────────────────────────────────────\n//\n// Environment-specific glue: wraps an actor definition so that spawning it runs\n// it in a subprocess over two named fifos. It does the guesswork — argv marker\n// detection and runner auto-detection — and prepares the client spawner. This\n// is the only place in the subprocess path that imports transports/protocols.\n\nimport { fileURLToPath } from \"node:url\";\nimport { createHash } from \"node:crypto\";\nimport type { Message } from \"../types.js\";\nimport type { ActorDefinition, HandlerOptions, MethodOptions, ReflectionOptions } from \"../actor-types.js\";\nimport type { KitApp } from \"./kit.js\";\nimport { hostVersion } from \"./kit.js\";\nimport { remoteClient } from \"./client.js\";\nimport { serveRemoteActor } from \"./reactor.js\";\nimport { commandSpawner } from \"./spawners/fifo-command.js\";\nimport { fifoArgvSpawner } from \"./spawners/fifo-argv.js\";\n\nexport interface SubprocessActorOptions {\n manual?: boolean;\n /**\n * Who this payload is: the app name and the build its bytes came from, as the consumer states\n * them. This is one switch for both halves of the seam — stated, every start passes\n * `--host-version` and the payload refuses to serve anything else; unstated, neither happens,\n * because there is no version to pass and none to check.\n */\n hostVersion?: KitApp;\n}\n\nexport interface SubprocessActorBundle<\n Args,\n State,\n InMsg extends Message,\n OutMsg extends Message,\n R extends ReflectionOptions,\n> {\n actor: ActorDefinition<Args, State, InMsg, OutMsg, R>;\n runRemoteRoot(): Promise<void>;\n isRemoteRoot: boolean;\n}\n\nfunction pathHash(path: string): string {\n return createHash(\"sha256\").update(path).digest(\"hex\").slice(0, 12);\n}\n\nconst MARKER_PREFIX = \"--remote=\";\n\nexport function defineSubprocessActor<\n Args,\n State,\n InMsg extends Message,\n OutMsg extends Message,\n Methods extends MethodOptions,\n Handlers extends HandlerOptions<InMsg>,\n R extends ReflectionOptions,\n>(\n actor: ActorDefinition<Args, State, InMsg, OutMsg, R>,\n url: string,\n opts: SubprocessActorOptions = {},\n): SubprocessActorBundle<Args, State, InMsg, OutMsg, R> {\n const scriptPath = fileURLToPath(url);\n const marker = `${MARKER_PREFIX}${pathHash(scriptPath)}`;\n const isRemoteRoot = !opts.manual && process.argv.includes(marker);\n const own =\n opts.hostVersion === undefined\n ? undefined\n : hostVersion(opts.hostVersion);\n\n const serve = () => serveRemoteActor(actor, () => fifoArgvSpawner(own));\n\n if (isRemoteRoot) {\n void serve();\n }\n\n const isBun = typeof (globalThis as { Bun?: unknown }).Bun !== \"undefined\";\n const runner = isBun ? \"bun\" : \"node\";\n const spawner = commandSpawner([\n runner,\n scriptPath,\n marker,\n ...(own === undefined ? [] : [`--host-version=${own}`]),\n ]);\n\n const proxyDef = remoteClient<Args, State, InMsg, OutMsg, Methods, Handlers, R>(\n actor.name ?? \"actor\",\n spawner,\n );\n\n return {\n actor: proxyDef,\n runRemoteRoot: serve,\n isRemoteRoot,\n };\n}\n","// ── stdio wire ─────────────────────────────────────────────────────────────\n//\n// A newline-delimited JSON channel over a pair of streams: the one wire every\n// way into a foreign execution context can carry. Two callers rely on it, and\n// they are two halves of the same thing:\n//\n// * the client of a spawn we make ourselves, on fds handed to the child (see\n// `fdStreams`) — private fds, so the child's own stdout stays free;\n// * a first-stage command on its own stdin/stdout, over ssh, under `sudo`, in\n// a container — where stdio is the only channel there is.\n//\n// Frames are one JSON object per line. Whatever the far end prints is carried as an *output\n// frame* (`$fd`), so it can never be mistaken for a frame of the protocol itself; a failed start\n// is carried as an `$error` frame.\n//\n// Output frames are routed above the protocol step, by whoever holds the connection (output.ts):\n// every line decodes to a frame, and the ones that are the far end's own print go to that\n// holder's sink instead of to the seam. The handshake below reads the first frame that is the\n// protocol's, since the far end's own print may come first.\n\nimport { createReadStream, createWriteStream } from \"node:fs\";\nimport * as readline from \"node:readline\";\nimport type { Readable, Writable } from \"node:stream\";\nimport {\n errorFrame as wireErrorFrame,\n errorReason as wireErrorReason,\n isProto,\n outputOf,\n type Channel,\n type OutputFd,\n type StringTransport,\n} from \"./channel.js\";\nimport { VERSION, json1Channel } from \"./protocols/json1.js\";\nimport { stderrSink, withOutput, type OutputSink } from \"./output.js\";\n\n/** The stream pair a line transport talks over. */\nexport interface LineStreams {\n read: Readable;\n write: Writable;\n}\n\n/** How long to wait for the far end's first protocol frame. */\nexport const HANDSHAKE_TIMEOUT_MS = 15_000;\n\n/** Raised when the wire itself fails: no frame, the wrong protocol, a peer that went away. */\nexport class StdioWireError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"StdioWireError\";\n }\n}\n\n/** An `$error` frame as a line. The word and its shape are the shared vocabulary's\n * (channel.ts) — one word for a wire that cannot be spoken over, whether the failure was at\n * the start of a session or in the middle of one; what this file owns is its line form. */\nexport function errorFrame(reason: string): string {\n return JSON.stringify(wireErrorFrame(reason));\n}\n\n/** The reason an `$error` frame carries, or null when it is not one. */\nexport function errorReason(frame: Record<string, unknown>): string | null {\n return wireErrorReason(frame);\n}\n\n// ── transports ─────────────────────────────────────────────────────────────\n\n/** Is this write error just a peer that already left? */\nfunction peerGone(code: unknown): boolean {\n return (\n code === \"EPIPE\" ||\n code === \"ERR_STREAM_DESTROYED\" ||\n code === \"ERR_STREAM_WRITE_AFTER_END\" ||\n code === \"ERR_STREAM_ALREADY_FINISHED\"\n );\n}\n\nfunction errorText(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * A `StringTransport` over a read/write stream pair, one JSON frame per line.\n *\n * `close()` is idempotent and never throws: teardown races are normal here —\n * the peer exits, the read side ends, and a write arrives a moment later.\n */\nexport class LineTransport implements StringTransport {\n private readonly streams: LineStreams;\n private pvtOnMessage: ((line: string) => void) | null = null;\n private pvtOnClose: (() => void) | null = null;\n private pvtClosed = false;\n private pvtClosing: Promise<void> | null = null;\n\n constructor(streams: LineStreams) {\n this.streams = streams;\n const lines = readline.createInterface({ input: streams.read });\n lines.on(\"line\", (line) => {\n if (this.pvtOnMessage && !this.pvtClosed) this.pvtOnMessage(line);\n });\n lines.on(\"close\", () => {\n this.pvtOnClose?.();\n void this.close();\n });\n // A stream error is a peer that went away, not a reason to take the process\n // down with an unhandled 'error' event.\n streams.read.on(\"error\", () => {\n void this.close();\n });\n streams.write.on(\"error\", () => {\n void this.close();\n });\n }\n\n get closed(): boolean {\n return this.pvtClosed;\n }\n\n get hasHandler(): boolean {\n return this.pvtOnMessage !== null;\n }\n\n onMessage(handler: (line: string) => void): void {\n if (this.pvtClosed) throw new StdioWireError(\"stdio transport: closed\");\n if (this.pvtOnMessage !== null) {\n throw new StdioWireError(\"stdio transport: handler already set — call removeHandler()\");\n }\n this.pvtOnMessage = handler;\n }\n\n removeHandler(): ((line: string) => void) | null {\n const previous = this.pvtOnMessage;\n this.pvtOnMessage = null;\n return previous;\n }\n\n onClose(handler: () => void): void {\n this.pvtOnClose = handler;\n }\n\n send(frame: string): Promise<void> {\n if (this.pvtClosed) {\n return Promise.resolve();\n }\n const line = frame.endsWith(\"\\n\") ? frame : `${frame}\\n`;\n return new Promise<void>((resolve, reject) => {\n try {\n this.streams.write.write(line, (err?: Error | null) => {\n if (!err) return resolve();\n const code = (err as { code?: unknown }).code;\n // A peer that has hung up cannot be told anything; the write that\n // races its exit is not an error in this transport.\n if (peerGone(code)) {\n return resolve();\n }\n reject(new StdioWireError(`stdio transport: ${err.message}`));\n });\n } catch (err) {\n reject(new StdioWireError(`stdio transport: ${errorText(err)}`));\n }\n });\n }\n\n async close(): Promise<void> {\n this.pvtClosing ??= this.pvtClose();\n await this.pvtClosing;\n }\n\n private async pvtClose(): Promise<void> {\n await Promise.resolve();\n\n this.pvtClosed = true;\n // Best effort: a half-open stream (the peer is already gone) must not turn\n // teardown into an exception.\n try {\n this.streams.read.destroy?.();\n } catch {\n /* already gone */\n }\n try {\n if (!this.streams.write.writableEnded) this.streams.write.end();\n } catch {\n /* already gone */\n }\n }\n}\n\n/** Streams over two fds of *our own* process — the child side of an fd wire. */\nexport function fdStreams(readFd: number, writeFd: number): LineStreams {\n const read = createReadStream(\"\", { fd: readFd, encoding: \"utf-8\", autoClose: false });\n const write = createWriteStream(\"\", { fd: writeFd, encoding: \"utf-8\", autoClose: false });\n return { read, write };\n}\n\n// ── handshakes ─────────────────────────────────────────────────────────────\n\n/** The next frame that is the protocol's, or a timeout. The far end's own output is not the\n * protocol's: it goes to `sink` while this waits, and the wait carries on. */\nasync function nextFrame(\n channel: Channel,\n timeoutMs: number,\n sink: OutputSink,\n): Promise<Record<string, unknown>> {\n return await new Promise((resolve, reject) => {\n const timer = setTimeout(\n () => reject(new StdioWireError(`no protocol frame within ${timeoutMs}ms`)),\n timeoutMs,\n );\n timer.unref?.();\n const off = channel.onMessage((frame) => {\n const output = outputOf(frame);\n if (output) {\n sink(output.fd, output.data);\n return;\n }\n off();\n clearTimeout(timer);\n resolve(frame);\n });\n });\n}\n\nexport interface ClientChannelOptions {\n /** Where the far end's own output goes. Defaults to our stderr. */\n onOutput?: OutputSink;\n /** How long to wait for the peer's protocol frame. Defaults to {@link HANDSHAKE_TIMEOUT_MS}. */\n timeoutMs?: number;\n}\n\n/**\n * The client end of the connection: hand the streams to the seam and wait for the peer's `$proto`,\n * with the far end's own output going to `onOutput` (our stderr by default) as it arrives. A\n * first stage reports a failed start as an `$error` frame instead.\n */\nexport async function clientChannel(\n streams: LineStreams,\n opts: ClientChannelOptions = {},\n): Promise<Channel> {\n const channel = json1Channel(new LineTransport(streams));\n const sink = opts.onOutput ?? stderrSink();\n const frame = await nextFrame(channel, opts.timeoutMs ?? HANDSHAKE_TIMEOUT_MS, sink);\n\n const reason = errorReason(frame);\n if (reason) throw new StdioWireError(reason);\n if (!isProto(frame)) {\n throw new StdioWireError(`unexpected first frame: ${JSON.stringify(frame).slice(0, 120)}`);\n }\n if (frame.$proto !== VERSION) {\n throw new StdioWireError(`unsupported protocol ${String(frame.$proto)}, expected ${VERSION}`);\n }\n // From here on the far end's own output is this connection's business and not the transport's:\n // every frame reaches the seam, and the ones that are its print are taken off on the way in.\n return withOutput(channel, sink);\n}\n\n/** The server end of the wire — a payload speaking stdio itself. */\nexport async function serverChannel(streams: LineStreams): Promise<Channel> {\n const channel = json1Channel(new LineTransport(streams));\n await channel.send({ $proto: VERSION });\n return channel;\n}\n","// ── the connection as byte streams ─────────────────────────────────────────\n//\n// A frame with `$fd` is what one end's root says on one of its own streams (`outputFrame`,\n// channel.ts): the number is the stream a program knows, and both directions of a stream live\n// under it. This is the layer that turns those frames into the streams a program holds, so a\n// logger, a terminal or a child's own stdio plugs into a connection with a pipe.\n//\n// channel ──{$fd: 1, data}──▶ stdout.read what the other root printed\n// channel ◀─{$fd: 1, data}──── stdout.write what this root prints\n//\n// Both directions on one fd, because both ends have a root and each reads what the other prints.\n// Nothing is buffered beyond the streams themselves: a `read` nobody drains grows, and a `write`\n// is one frame per chunk.\n\nimport { PassThrough, Writable, type Readable } from \"node:stream\";\n\nimport { outputFrame, outputOf, type Channel, type OutputFd } from \"./channel.js\";\n\n/**\n * What a log line needs: a stream says `info` or `warn`, and nothing here cares which logger it is.\n * The seam states the two methods rather than importing one, so a debug logger, a console or a test's\n * own collector all fit without the remote layer depending on a plugin.\n */\nexport interface LineLog {\n info(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n}\n\n/** One stream of a connection: what the other end's root says on it, and what this end's root says. */\nexport interface FdStream {\n /** The other end's root, printing on this stream of its own. */\n readonly read: Readable;\n /** This end's root, printing on this stream; the other end reads it. */\n readonly write: Writable;\n}\n\n/** The three streams of a connection, and the one way to let them go. */\nexport interface FdSet {\n readonly stdin: FdStream;\n readonly stdout: FdStream;\n readonly stderr: FdStream;\n /** Stop reading the connection, and end every stream of it. */\n close(): void;\n}\n\n/** Where a frame goes: a connection's own `send`, or a transport's, encoded. */\nexport type OutputSender = (frame: Record<string, unknown>) => void | Promise<void>;\n\n/**\n * A writable that writes what is written to it as output frames of one fd: one chunk is one frame.\n *\n * The shape of an output frame lives here rather than at each caller — the gateway relays a payload's\n * own output and holds no channel — and a send that fails is the stream's error, not a lost line.\n */\nexport function fdWriter(send: OutputSender, fd: OutputFd): Writable {\n return new Writable({\n write(chunk: Buffer | string, _encoding, done): void {\n // `send` may answer nothing (a transport that writes synchronously): either way the chunk is\n // taken once it is out, and a failure is the stream's to report.\n void Promise.resolve(send(outputFrame(fd, String(chunk)))).then(\n () => done(),\n (error: unknown) => done(error as Error),\n );\n },\n });\n}\n\n/**\n * The byte streams of a connection: what each end's root prints, and what it reads.\n *\n * The frames are the connection's, so anyone may also read them directly (`Channel.onMessage`); what\n * this adds is the shape a program outside the seam already speaks.\n */\nexport function connectionFds(channel: Channel): FdSet {\n const sides = new Map<OutputFd, { stream: FdStream; read: PassThrough }>();\n\n const side = (fd: OutputFd): FdStream => {\n const read = new PassThrough();\n const stream: FdStream = { read, write: fdWriter((frame) => channel.send(frame), fd) };\n sides.set(fd, { stream, read });\n return stream;\n };\n\n const stdin = side(0);\n const stdout = side(1);\n const stderr = side(2);\n\n const off = channel.onMessage((frame) => {\n const output = outputOf(frame);\n if (!output) return;\n sides.get(output.fd)?.read.push(output.data);\n });\n\n return {\n stdin,\n stdout,\n stderr,\n close(): void {\n off();\n for (const { stream, read } of sides.values()) {\n read.end();\n stream.write.end();\n }\n },\n };\n}\n\n/**\n * A writable that turns what is written to it into log lines: fd 1 arrives as `info` and fd 2 as\n * `warn`, and the tail is held until a newline (or the end) so a chunk boundary is not a line\n * boundary.\n */\nexport function logStream(log: LineLog, opts: { fd?: OutputFd } = {}): Writable {\n const warn = opts.fd === 2;\n const say = (line: string): void => {\n if (warn) log.warn(line);\n else log.info(line);\n };\n\n let tail = \"\";\n /** Everything up to the last newline goes out; what follows one waits to be finished. */\n const drain = (): void => {\n const lines = tail.split(\"\\n\");\n tail = lines.pop() ?? \"\";\n for (const line of lines) {\n if (line.length > 0) say(line);\n }\n };\n\n return new Writable({\n write(chunk: Buffer | string, _encoding, done): void {\n tail += String(chunk);\n drain();\n done();\n },\n final(done): void {\n drain();\n if (tail.length > 0) say(tail);\n done();\n },\n });\n}\n","// ── Gateway ────────────────────────────────────────────────────────────────\n//\n// The first-stage command. Run this *inside* a foreign environment — directly,\n// under `sudo`, over ssh, in a container — and it:\n//\n// 1. creates the channel to the payload (fifo paths it makes itself, in a\n// private temp dir, so they belong to the uid that will open them),\n// 2. starts the payload — the first argument, required — hands it everything else it was\n// given (the host version among it) and relays frames between stdin/stdout,\n// 3. carries whatever the payload prints to the client as output frames\n// (`$fd`), so the payload's own stdout can never be mistaken for protocol.\n//\n// Why a gateway at all: a fifo path created on the client side is useless when the\n// payload runs as another uid (it cannot open it) or on another host (the path is\n// not there). stdio is the one channel every way into an environment gives us, so\n// the wire is stdio and the fifo stays inside the environment.\n//\n// The gateway reads nothing out of what it carries and owns no flag: the payload's path and\n// every argument after it go through verbatim, in order. The payload is the one who refuses a\n// host version it is not, and a relay that judged would be a second place for that decision.\n//\n// Directories and processes are cleaned up on every exit path, which is also why\n// the client never sees a transport being closed twice.\n//\n// It imports nothing but node builtins and this package, so the payload behind it\n// can be anything the runtime there can start.\n\nimport { execFile, spawn, type ChildProcess } from \"node:child_process\";\nimport { mkdtemp, rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { basename, join } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport type { OutputFd } from \"./channel.js\";\nimport { encode } from \"./protocols/json1.js\";\nimport { fdWriter } from \"./streams.js\";\nimport { errorFrame } from \"./stdio.js\";\nimport type { LineTransport } from \"./stdio.js\";\nimport { LineTransport as Lines } from \"./stdio.js\";\nimport { FifoUtf8NlineTransport } from \"./transports/fifo.js\";\n\nconst run = promisify(execFile);\n\n/** Exit code for \"this environment could not be set up\". */\nexport const GATEWAY_FAILED = 1;\n\nexport interface GatewayBoot {\n /**\n * The program to start for the payload: the first word of the command the client composed —\n * a runtime, or a program that runs itself. Required, and first, and the gateway has no\n * opinion of its own about which it is.\n */\n worker: string;\n /**\n * Everything after the payload, carried to it **as is** and in order: the consumer's own\n * arguments, and posipaki's own facts among them (the host version travels this way). The\n * gateway reads nothing by name and owns no flag, so nothing of the caller's is interpreted,\n * eaten, re-ordered or re-spelled — and the next fact added to that line needs no new\n * vocabulary here.\n */\n passthrough: string[];\n}\n\nfunction errorText(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * A label for the gateway's own temp directory: the program this environment was made for.\n * It is the gateway's business alone — the payload is not told which label it is.\n */\nfunction label(worker: string): string {\n const name = basename(worker).replace(/[^A-Za-z0-9.+@_-]/g, \"-\").slice(0, 60);\n return name === \"\" ? \"payload\" : name;\n}\n\n/**\n * The argv that boots this gateway — built by the client, read by\n * {@link gatewayBoot}, so the two halves cannot drift apart.\n *\n * The payload comes first and its arguments after it, so a positional argument of the\n * payload's own can never be mistaken for the payload.\n */\nexport function gatewayArgs(boot: GatewayBoot): string[] {\n return [boot.worker, ...boot.passthrough];\n}\n\n/** The boot a gateway was started with, or the reason it cannot start. */\nexport function gatewayBoot(argv: string[]): GatewayBoot {\n const [worker, ...passthrough] = argv;\n if (worker === undefined || worker.startsWith(\"--\")) {\n throw new Error(\"no <payload>: the gateway relays to a payload, named as its first argument\");\n }\n return { passthrough, worker };\n}\n\n/**\n * End a start that failed. The reason has already gone out on the wire, and\n * returning is not enough: the `open()` on a fifo no payload will ever write sits\n * in the threadpool forever, so the loop never drains and the gateway would linger\n * with a dead payload on its books.\n */\nfunction abandon(): never {\n process.exit(GATEWAY_FAILED);\n}\n\n/** Carry a failed start to the client, then let the caller exit non-zero. */\nasync function fail(wire: LineTransport, reason: string): Promise<void> {\n process.stderr.write(`gateway: ${reason}\\n`);\n try {\n await wire.send(errorFrame(reason));\n } catch {\n /* the client is gone too — the exit code still says what happened */\n }\n}\n\n/** Copy everything the payload prints to the client, as output frames of the fd it came in on. */\nfunction forwardOutput(stream: NodeJS.ReadableStream, wire: LineTransport, fd: OutputFd): void {\n stream.setEncoding(\"utf-8\");\n const out = fdWriter((frame) => wire.send(encode(frame)), fd);\n // The client hung up: the payload's exit is what matters now, and a frame that could not be\n // delivered is not something anyone here can act on.\n out.on(\"error\", () => {});\n stream.pipe(out, { end: false });\n}\n\n/**\n * Serve one environment over stdin/stdout. Returns the exit code; the caller\n * turns it into `process.exitCode`.\n */\nexport async function runGateway(argv: string[] = process.argv.slice(2)): Promise<number> {\n const wire = new Lines({ read: process.stdin, write: process.stdout });\n\n let booted: GatewayBoot;\n try {\n booted = gatewayBoot(argv);\n } catch (err) {\n // Nothing has been started yet, so there is nothing to tear down — but the\n // client still deserves the reason rather than a channel that closes on it,\n // and the loop can outlive us: an open stdin nobody will close keeps the\n // process alive, so this is an exit, not a return.\n await fail(wire, errorText(err));\n abandon();\n }\n const { passthrough, worker } = booted;\n\n const dir = await mkdtemp(join(tmpdir(), `posipaki-${label(worker)}-`));\n const fifoIn = join(dir, \"in\"); // the payload writes, we read\n const fifoOut = join(dir, \"out\"); // we write, the payload reads\n\n let child: ChildProcess | null = null;\n let fifo: FifoUtf8NlineTransport | null = null;\n\n /**\n * Everything this gateway owns, undone. All of it is idempotent, because the\n * exit path and the signal path can both arrive.\n */\n const teardown = async (): Promise<void> => {\n child?.kill();\n await fifo?.close().catch(() => {});\n await rm(dir, { recursive: true, force: true }).catch(() => {});\n };\n\n /**\n * A client that gives up stops us with a signal, and a gateway that died on the\n * spot would leave its payload behind in the environment — a process holding a\n * fifo nobody will ever write, which is a leak the environment cannot clean up\n * for us. So the signals do what the exit path does.\n */\n const onTerminate = () => {\n void teardown()\n .catch(() => {})\n .then(() => process.exit(GATEWAY_FAILED));\n };\n for (const signal of [\"SIGTERM\", \"SIGINT\", \"SIGHUP\"] as const) process.on(signal, onTerminate);\n\n try {\n await run(\"mkfifo\", [\"-m\", \"600\", fifoIn, fifoOut]);\n } catch (err) {\n await fail(wire, `cannot create the environment's fifos: ${errorText(err)}`);\n await teardown();\n abandon();\n }\n\n // Open the read side in the background, then start the payload that unblocks\n // it — the order the fifo handshake requires.\n const connection = FifoUtf8NlineTransport.beginConnect(fifoIn, fifoOut);\n const workerArgs = [worker, ...passthrough, `--fifo-in=${fifoIn}`, `--fifo-out=${fifoOut}`];\n // Whatever the client said starts the payload, run as it said: a runtime with a script of\n // ours, or a program of the caller's own. The gateway does not know which it is, and does\n // not choose a runtime on the far end's behalf.\n const workerProc = spawn(workerArgs[0]!, workerArgs.slice(1), {\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n child = workerProc;\n forwardOutput(workerProc.stdout, wire, 1);\n forwardOutput(workerProc.stderr, wire, 2);\n\n const exited = new Promise<number>((settle) => {\n // A payload killed by a signal (the client hung up, and we killed it) has no\n // code — for us that is a clean end, not a failure.\n workerProc.once(\"exit\", (code) => settle(code ?? 0));\n });\n\n try {\n fifo = await Promise.race([\n connection.transport,\n exited.then((code) => {\n throw new Error(`the payload exited with code ${code} before it opened its channel`);\n }),\n ]);\n } catch (err) {\n await fail(wire, errorText(err));\n await teardown();\n abandon();\n }\n\n // Relay: the protocol is the client's and the payload's business, not ours.\n const relay = fifo;\n relay.onMessage((line) => {\n void wire.send(line).catch(() => {\n /* client gone */\n });\n });\n wire.onMessage((line) => {\n void relay.send(line).catch(() => {\n /* the payload is gone; its exit path cleans up */\n });\n });\n wire.onClose(() => {\n child?.kill();\n });\n\n const code = await exited;\n await teardown();\n await wire.close();\n return code;\n}\n","// ── Running one command on the host ────────────────────────────────────────\n//\n// Everything a way in does, it does by running a command: staging is a command in an\n// environment, and the actor is another one whose stdin/stdout are the wire. Both go\n// through the two functions here, and both are handed in — so a test can stage and run\n// without a sandbox, a host or a container, and a consumer can run host commands its\n// own way.\n\nimport { spawn } from \"node:child_process\";\nimport type { ChildProcess, StdioOptions } from \"node:child_process\";\n\nexport interface HostResult {\n code: number | null;\n stdout: string;\n stderr: string;\n}\n\n/** Run a command, feed it its stdin, and wait for what it said. */\nexport type HostRun = (command: string[], stdin: string) => Promise<HostResult>;\n\n/** The real thing: spawn it, feed it, collect it. */\nexport const runHost: HostRun = (command, stdin) =>\n new Promise((settle, fail) => {\n const child = spawn(command[0]!, command.slice(1), { stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n const out: string[] = [];\n const err: string[] = [];\n child.stdout.setEncoding(\"utf-8\");\n child.stderr.setEncoding(\"utf-8\");\n child.stdout.on(\"data\", (chunk: string) => out.push(chunk));\n child.stderr.on(\"data\", (chunk: string) => err.push(chunk));\n child.once(\"error\", (error) => fail(error));\n // A host that hangs up while we are still writing has failed; the exit code and\n // stderr carry that, so the write error is not the story here.\n child.stdin.on(\"error\", () => {});\n child.once(\"close\", (code) => settle({ code, stdout: out.join(\"\"), stderr: err.join(\"\") }));\n child.stdin.end(stdin);\n });\n\n/** How the wire's process is started, with the stdio it needs. */\nexport type SpawnChild = (command: string[], stdio: StdioOptions) => ChildProcess;\n\n/** The real thing: node's own spawn, in our working directory. */\nexport const spawnChild: SpawnChild = (command, stdio) =>\n spawn(command[0]!, command.slice(1), { cwd: process.cwd(), stdio });\n","// ── The client side of the gateway ─────────────────────────────────────────\n//\n// A consumer has two things: a payload, and the build its bytes came from. A way in has\n// one: how to run a command somewhere else. Everything else is the same whatever the way\n// in is, and this module is that everything else:\n//\n// 1. the gateway script is posipaki's own entry (`posipaki/remote/gateway-cli.js`, a\n// published specifier, so it is resolved where the kit is staged from) — or the\n// consumer's, for a program that carries its own;\n// 2. both bundles go into one kit, whose directory name *is* the host version it serves —\n// the app, the build those bytes came from, the posipaki release that speaks to them —\n// so a second run of the same build finds the kit already there and copies nothing;\n// 3. whatever has to be *copied* there is staged through the way in's own channel — the\n// core's bootstrap script, one report line per step — which is also where the runtime\n// that will run it is found, so a way in never has to know what a `node` is. A\n// program the caller says is already installed is not staged at all, and then no\n// command of ours runs in the environment beyond the two that matter;\n// 4. the gateway runs there — `<runtime> <kit>/gateway.js` when it was staged, the caller's\n// own command when it was not — its stdin/stdout are the wire, and it makes the fifos\n// inside the environment and starts the payload against them. The payload is run this\n// way in *every* way in, which is why the payload is only ever a fifo worker. The\n// payload's own command and the host version are arguments the gateway carries without\n// knowing which is which: staged artifacts are ours, and the payload checks itself\n// against what it was asked for.\n//\n// What a way in supplies is `entry`: the argv that runs a command there. It is the whole\n// difference between bwrap, ssh, a container and this machine, and it is one function.\n\nimport type { ChildProcess, StdioOptions } from \"node:child_process\";\nimport { readFile } from \"node:fs/promises\";\nimport type { Readable, Writable } from \"node:stream\";\nimport { fileURLToPath } from \"node:url\";\nimport type { Channel } from \"./channel.js\";\nimport type { ClientSpawner } from \"./client.js\";\nimport { gatewayArgs } from \"./gateway.js\";\nimport { runHost, spawnChild } from \"./host.js\";\nimport type { HostResult, HostRun, SpawnChild } from \"./host.js\";\nimport {\n DEFAULT_KIT_PARENT,\n DEFAULT_RUNTIMES,\n GATEWAY_ARTIFACT,\n PAYLOAD_ARTIFACT,\n bootstrapScript,\n hostVersion,\n makeKit,\n parseBootstrapReport,\n} from \"./kit.js\";\nimport type { Kit, KitApp } from \"./kit.js\";\nimport { clientChannel } from \"./stdio.js\";\nimport { stderrSink, type OutputSink } from \"./output.js\";\nimport type { LineStreams } from \"./stdio.js\";\nimport type { OutputFd } from \"./channel.js\";\n\n/** posipaki's own gateway program. A consumer with one of its own stages that instead. */\nexport const GATEWAY_ENTRY = \"posipaki/remote/gateway-cli.js\";\n\n/** How much of what a failed staging command said is quoted back as part of the reason. */\nconst SAID_TAIL = 400;\n\n/** How much of the far end's stderr is kept, to be the reason a start failed. */\nconst REASON_TAIL = 400;\n\n/** Staging failed, or the far end never spoke: the caller's spec, or the environment's answer. */\nexport class RemoteSpecError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"RemoteSpecError\";\n }\n}\n\n/** What a way in is handed, and how it runs what it is handed. */\nexport interface RemoteWayIn {\n /** What the far end's output and errors are tagged with. */\n name: string;\n /** The argv that runs `command` there: bwrap's policy, ssh's host, podman's container. */\n entry: (command: string[]) => string[];\n /** How a plain command runs there and is waited for. Injectable, so a test needs no way in. */\n run?: HostRun;\n /** How the wire's process is started there. Injectable likewise. */\n spawn?: SpawnChild;\n}\n\n/**\n * A program the way in starts there: a bundle of ours to copy into the environment, or a\n * command that already runs there — an absolute path, a name on `$PATH`, a runtime and a\n * script of its own. Which of the two it is, is the caller's decision, and it is the only\n * thing posipaki needs to know about where the far end comes from.\n */\nexport type HostProgram = { stage: string } | { run: string[] };\n\n/** Everything a client needs: where the two programs are, whose payload it is, and the way in. */\nexport interface RemoteSpec<Args> extends RemoteWayIn {\n /** The payload: ours to stage there, or the one already installed there. */\n payload: HostProgram;\n /**\n * Whose payload this is: the app name and the build those bytes came from. Required\n * whenever anything is staged — a kit's directory *is* the host version — and stated to the\n * payload whenever it is given at all, which is the one fact a caller can hand an installed\n * payload about the build it is expected to be. Omitted, nothing is stated and nothing is\n * checked, which is only right for a payload whose bytes carry no version of their own.\n */\n hostVersion?: KitApp;\n /** The gateway: posipaki's own bundle, staged, unless the caller says otherwise. */\n gateway?: HostProgram;\n /** Runtime candidates on the far side, best first. Defaults to `DEFAULT_RUNTIMES`. */\n runtime?: string[];\n /** Where the kit lands there, relative to its `$HOME`. Defaults to `DEFAULT_KIT_PARENT`. */\n parent?: string;\n /**\n * The payload's own arguments, built from the args the actor was spawned with. The gateway\n * carries them to the payload untouched — it does not know what they mean, and does not need\n * to: what a consumer tells its own far end is the consumer's business.\n */\n payloadArgs?: (args: Args) => string[];\n /** Where the far end's own output goes. Defaults to our stderr, tagged with `name`. */\n onOutput?: OutputSink;\n /** How long to wait for the far end's first protocol frame. */\n handshakeTimeoutMs?: number;\n /** Called when the far end's process is gone, whichever way it went. */\n onGone?: () => void;\n}\n\n/**\n * The part of a spec the machinery here reads, with the actor's own arguments left out:\n * staging, the channel and the argv are the same whatever an actor is told.\n */\ntype Spec = Omit<RemoteSpec<unknown>, \"payloadArgs\">;\n\n/** The argv that starts each of the two programs there. */\ninterface Programs {\n gateway: string[];\n payload: string[];\n}\n\nfunction isStage(program: HostProgram): program is { stage: string } {\n return \"stage\" in program;\n}\n\nfunction errorText(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * posipaki's own gateway program, resolved where the consumer installed it — the default for\n * a caller that has none of its own to deploy.\n */\nfunction gatewayEntry(): string {\n try {\n return fileURLToPath(import.meta.resolve(GATEWAY_ENTRY));\n } catch (err) {\n throw new RemoteSpecError(\n `cannot find posipaki's gateway program (${GATEWAY_ENTRY}): ${errorText(err)}. ` +\n \"Stage one with `gateway:` — a consumer whose program carries its own.\",\n );\n }\n}\n\n/** The kit's files: what has to be copied there, under the names the script writes them as. */\nasync function kitFiles(\n gateway: HostProgram,\n payload: HostProgram,\n): Promise<{ name: string; content: Buffer }[]> {\n const files: { name: string; content: Buffer }[] = [];\n if (isStage(payload)) files.push({ name: PAYLOAD_ARTIFACT, content: await readFile(payload.stage) });\n if (isStage(gateway)) files.push({ name: GATEWAY_ARTIFACT, content: await readFile(gateway.stage) });\n return files;\n}\n\n/** A command with nothing to run is a spec that says nothing; refuse it before spawning it. */\nfunction programCommand(program: { run: string[] }, what: string, name: string): string[] {\n if (program.run.length === 0 || program.run[0] === undefined || program.run[0] === \"\") {\n throw new RemoteSpecError(`${name}: ${what} is a command with nothing to run`);\n }\n return program.run;\n}\n\n/**\n * The two commands, staging whatever has to be copied there first.\n *\n * Nothing staged means no command of ours runs in the environment at all: the caller's own\n * argv is handed through as it stands, which is the case for a program that is already\n * installed. Something staged needs a host version to name the kit with — and a kit's\n * directory *is* the host version, so there is nothing to guess at.\n */\nasync function programsFor(spec: Spec, run: HostRun): Promise<Programs> {\n const gateway: HostProgram = spec.gateway ?? { stage: gatewayEntry() };\n const payload = spec.payload;\n if (!isStage(gateway) && !isStage(payload)) {\n return {\n gateway: programCommand(gateway, \"the gateway\", spec.name),\n payload: programCommand(payload, \"the payload\", spec.name),\n };\n }\n if (spec.hostVersion === undefined) {\n throw new RemoteSpecError(\n `nothing names the kit to stage into ${spec.name}: state hostVersion — a kit's directory ` +\n \"is the host version, and a payload refuses to serve one its own bytes do not carry\",\n );\n }\n const kit = makeKit(await kitFiles(gateway, payload), {\n app: spec.hostVersion,\n runtimes: spec.runtime ?? DEFAULT_RUNTIMES,\n parent: spec.parent ?? DEFAULT_KIT_PARENT,\n });\n const staged = await stageKit(spec, kit, run);\n const at = (artifact: string) => [staged.runtime, `${staged.kitDir}/${artifact}`];\n return {\n gateway: isStage(gateway) ? at(GATEWAY_ARTIFACT) : gateway.run,\n payload: isStage(payload) ? at(PAYLOAD_ARTIFACT) : payload.run,\n };\n}\n\n/** The tail of what a command said, for a failure that has no better story. */\nfunction said(result: HostResult): string {\n const text = `${result.stderr}${result.stdout}`.trim();\n const tail = text.length > SAID_TAIL ? text.slice(-SAID_TAIL) : text;\n return tail === \"\" ? `exit code ${result.code}` : tail;\n}\n\n/**\n * Put the kit where the environment can see it and say what will run it. Idempotent:\n * the script probes, writes only what is missing and reports — so a spawn of a build\n * that is already staged costs one process and no writes.\n */\nasync function stageKit(spec: Spec, kit: Kit, run: HostRun): Promise<{ kitDir: string; runtime: string }> {\n const result = await run(spec.entry([\"sh\", \"-s\"]), bootstrapScript(kit));\n const report = parseBootstrapReport(result.stdout);\n if (report.kind === \"error\") {\n // A report that never arrived is not a reason; what the environment said is.\n const incomplete =\n report.reason.startsWith(\"incomplete\") || report.reason.startsWith(\"no report\");\n throw new RemoteSpecError(\n `staging into ${spec.name} failed: ${report.reason}${incomplete ? ` (${said(result)})` : \"\"}`,\n );\n }\n return { kitDir: report.kitDir, runtime: report.runtime };\n}\n\n/**\n * Start the run command and hand its own stdin/stdout to the wire. An environment that\n * dies before it speaks — bwrap not installed, a host that refuses, a payload that\n * cannot be run — fails the spawn with what it said, rather than a channel that never\n * answers.\n */\nasync function openChannel(\n spec: Spec,\n command: string[],\n spawn: SpawnChild,\n): Promise<Channel> {\n const sink = spec.onOutput ?? stderrSink(spec.name);\n let tail = \"\";\n const output: OutputSink = (fd: OutputFd, data: string) => {\n if (fd === 2) tail = (tail + data).slice(-REASON_TAIL);\n sink(fd, data);\n };\n\n // The run's own stdin and stdout *are* the wire, so both have to be pipes.\n const stdio: StdioOptions = [\"pipe\", \"pipe\", \"pipe\"];\n const child: ChildProcess = spawn(command, stdio);\n const streams: LineStreams = { read: child.stdout as Readable, write: child.stdin as Writable };\n\n // The run's stdin and stdout are the wire; its stderr is not. That is where the way\n // in itself speaks — \"bwrap: Can't find source path\", \"Permission denied\" — so it goes\n // to the sink, and the tail of it becomes the reason a start that died is reported with.\n child.stderr?.setEncoding(\"utf-8\");\n child.stderr?.on(\"data\", (chunk: string) => output(2, chunk));\n\n const exited = new Promise<never>((_, reject) => {\n // `close`, not `exit`: the process being gone is not the same as everything it said\n // having arrived, and the tail of its stderr is the whole reason here.\n child.once(\"close\", (code, signal) => {\n const how = signal === null ? `code ${code}` : `signal ${signal}`;\n const why = tail.trim();\n reject(new Error(`exited with ${how}${why ? `: ${why}` : \"\"}`));\n });\n child.once(\"error\", (err) => reject(new Error(`cannot start: ${err.message}`)));\n });\n // A spawn that resolves leaves this rejection unobserved — fine, as long as it is not\n // reported as an unhandled rejection.\n exited.catch(() => {});\n\n let channel: Channel;\n try {\n channel = await Promise.race([\n clientChannel(streams, {\n onOutput: output,\n ...(spec.handshakeTimeoutMs === undefined ? {} : { timeoutMs: spec.handshakeTimeoutMs }),\n }),\n exited,\n ]);\n } catch (err) {\n child.kill();\n throw new RemoteSpecError(`${spec.name} is not available: ${errorText(err)}`);\n }\n\n // The far end's exit is the channel's close: whichever side goes first, the other stops\n // waiting — and the caller is told, because its slot must stop pointing at a process\n // that is gone.\n child.once(\"exit\", () => {\n spec.onGone?.();\n void channel.close().catch(() => {});\n });\n return channel;\n}\n\n/**\n * A spawner for an actor that lives behind a gateway in some environment: put the payload and\n * posipaki's gateway wherever they belong, run the gateway, speak the client side.\n */\nexport function gatewayClient<Args>(spec: RemoteSpec<Args>): ClientSpawner<Args> {\n const run: HostRun = spec.run ?? runHost;\n const spawn: SpawnChild = spec.spawn ?? spawnChild;\n return async (args: Args): Promise<Channel> => {\n // The spec is read before a command runs on its behalf: a payload that is not there\n // should fail here, not as an environment that cannot be reached.\n const programs = await programsFor(spec, run);\n const command = [\n ...programs.gateway,\n ...gatewayArgs({\n // What the payload is started as, then posipaki's own facts among the caller's\n // arguments: the host version, and whatever the consumer adds for its own far end.\n // Which of these is whose is not the gateway's business — it starts what it is handed\n // and carries the rest.\n passthrough: [\n ...programs.payload.slice(1),\n ...(spec.hostVersion === undefined\n ? []\n : [`--host-version=${hostVersion(spec.hostVersion)}`]),\n ...(spec.payloadArgs?.(args) ?? []),\n ],\n worker: programs.payload[0]!,\n }),\n ];\n return openChannel(spec, spec.entry(command), spawn);\n };\n}\n\n/**\n * The way in where the environment is this machine: nothing wraps the command, and the\n * kit is staged under `$HOME` like any other. Everything below the entry is the same as\n * for a sandbox, a host or a container — which is the point of it being here.\n */\nexport function hostRemote<Args>(\n spec: Omit<RemoteSpec<Args>, \"name\" | \"entry\"> & { name?: string },\n): ClientSpawner<Args> {\n return gatewayClient({ name: \"this host\", entry: (command) => command, ...spec });\n}\n","// ── unix sockets: a listener, and a client ─────────────────────────────────\n//\n// A local socket as a medium for the reactor: the listener binds a path, takes one connection at a time\n// and hands it on; the client side is one call. The medium brings no framing of its own — a socket is a\n// duplex stream, and LineTransport already carries newline-delimited frames over one.\n\nimport { chmod, stat, unlink } from \"node:fs/promises\";\nimport { connect, createServer, type Server, type Socket } from \"node:net\";\n\nimport type { Connection, Listener } from \"./reactor.js\";\nimport { LineTransport } from \"./stdio.js\";\n\n/** The socket file's mode when the caller does not say: the path is the access control. */\nconst DEFAULT_MODE = 0o600;\n\n/** How long a connect waits before it gives up. */\nconst DEFAULT_TIMEOUT_MS = 5000;\n\n/** What a listener knows about an accepted connection before an actor exists for it. */\nexport interface UnixSocketPeer {\n /** The path this side is bound to. */\n readonly path: string;\n /**\n * The peer's credentials, where the runtime gives them (Linux `SO_PEERCRED`). Node exposes none on a\n * unix socket today, so this is undefined under node; the field is here for a runtime that can.\n */\n readonly peer?: { readonly uid: number; readonly gid: number; readonly pid?: number };\n}\n\nexport interface UnixSocketListenerOptions<Meta = unknown> {\n /** The socket file. Made when the listener starts, and removed when it stops. */\n path: string;\n /** The mode of the socket file, set before the first connection is taken. Default 0o600. */\n mode?: number;\n /**\n * Whether a path that exists and refuses a connection may be replaced: a socket nobody listens on is a\n * crash's leftover. A path that is not a socket at all is refused rather than removed.\n */\n replaceStale?: boolean;\n /** The listen backlog, passed through to the runtime. */\n backlog?: number;\n /**\n * Admission and identity. What it returns is the connection's meta; throwing refuses the connection\n * before any actor exists.\n */\n identify?(peer: UnixSocketPeer): Meta | Promise<Meta>;\n}\n\nexport interface UnixSocketClientOptions {\n /** How long to wait for the connection, in milliseconds. Default 5000. */\n timeoutMs?: number;\n}\n\n/** What is at a path: nothing, a live listener, a socket nobody listens on, or something else. */\nasync function atPath(path: string): Promise<\"free\" | \"listening\" | \"stale\" | \"other\"> {\n try {\n const info = await stat(path);\n if (!info.isSocket()) return \"other\";\n } catch {\n return \"free\";\n }\n const answered = await new Promise<boolean>((resolve) => {\n const probe = connect(path);\n probe.once(\"connect\", () => {\n probe.destroy();\n resolve(true);\n });\n probe.once(\"error\", () => {\n probe.destroy();\n resolve(false);\n });\n });\n return answered ? \"listening\" : \"stale\";\n}\n\n/**\n * Bind a path and answer connections from it, as the reactor's Listener: the socket file is made before\n * the first accept, its mode is set before the first connection is taken, and `close()` removes it if it\n * is still the inode this listener bound.\n */\nexport async function unixSocketListener<Meta = unknown>(\n options: UnixSocketListenerOptions<Meta>,\n): Promise<Listener<Meta>> {\n const { path, mode = DEFAULT_MODE, replaceStale = true, backlog } = options;\n\n const there = await atPath(path);\n if (there === \"listening\") throw new Error(`unixSocketListener: something is listening at ${path}`);\n if (there === \"other\") throw new Error(`unixSocketListener: ${path} is not a socket`);\n if (there === \"stale\") {\n if (!replaceStale) throw new Error(`unixSocketListener: ${path} is a socket nobody listens on`);\n await unlink(path);\n }\n\n // Every connection this listener has taken or is holding: the close ends them, so a client learns the\n // listener is gone from its read end closing, and `server.close()` is not held open by a live socket.\n const connections = new Set<Socket>();\n const accepted: Socket[] = [];\n let waiting: { resolve: (socket: Socket) => void; reject: (error: Error) => void } | null = null;\n let closed = false;\n\n const server: Server = createServer();\n server.on(\"connection\", (socket) => {\n connections.add(socket);\n socket.on(\"close\", () => connections.delete(socket));\n const taken = waiting;\n waiting = null;\n if (taken) taken.resolve(socket);\n else accepted.push(socket);\n });\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen({ path, backlog }, () => {\n server.removeListener(\"error\", reject);\n resolve();\n });\n });\n // The runtime makes the socket file with the process's umask; setting the mode here narrows the window\n // in which it is wider than asked for, since nothing has been accepted yet.\n await chmod(path, mode);\n const bound = await stat(path);\n\n const release = (error: Error): void => {\n const pending = waiting;\n waiting = null;\n pending?.reject(error);\n };\n\n return {\n accept(signal?: AbortSignal): Promise<Connection<Meta>> {\n if (closed) return Promise.reject(new Error(`unixSocketListener: ${path} is closed`));\n const taken = accepted.shift();\n const socket =\n taken ??\n new Promise<Socket>((resolve, reject) => {\n waiting = { resolve, reject };\n signal?.addEventListener(\n \"abort\",\n () => {\n if (waiting?.resolve === resolve) release(new Error(`unixSocketListener: ${path} was stopped`));\n reject(new Error(`unixSocketListener: ${path} was stopped`));\n },\n { once: true },\n );\n });\n return Promise.resolve(socket).then(async (connection) => {\n const peer: UnixSocketPeer = { path };\n const meta = options.identify ? await options.identify(peer) : (undefined as Meta);\n return { meta, transport: new LineTransport({ read: connection, write: connection }) };\n });\n },\n async close(): Promise<void> {\n closed = true;\n release(new Error(`unixSocketListener: ${path} is closed`));\n // Deleting from the set while iterating it is defined, and the deletion is the socket's own close\n // handler on a later turn, so the loop sees each of them once.\n for (const socket of connections) socket.destroy();\n connections.clear();\n accepted.length = 0;\n await new Promise<void>((resolve) => server.close(() => resolve()));\n try {\n const now = await stat(path);\n if (now.dev === bound.dev && now.ino === bound.ino) await unlink(path);\n } catch {\n // Already gone: nothing this listener made is left to remove.\n }\n },\n };\n}\n\n/** Connect to a listener: one call, and no open order, since a socket is connected or it is not. */\nexport async function connectUnixSocket(\n path: string,\n options: UnixSocketClientOptions = {},\n): Promise<LineTransport> {\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const socket = await new Promise<Socket>((resolve, reject) => {\n const attempt = connect(path);\n const timer = setTimeout(() => {\n attempt.destroy();\n reject(new Error(`connectUnixSocket: nothing answered at ${path} within ${timeoutMs}ms`));\n }, timeoutMs);\n attempt.once(\"connect\", () => {\n clearTimeout(timer);\n resolve(attempt);\n });\n attempt.once(\"error\", (error: Error) => {\n clearTimeout(timer);\n reject(new Error(`connectUnixSocket: ${path}: ${error.message}`));\n });\n });\n return new LineTransport({ read: socket, write: socket });\n}\n","// ── unix socket client spawner ─────────────────────────────────────────────\n//\n// Environment-specific: connects to a listening socket, wraps it in LineTransport, and returns a frame\n// Channel with the `$proto` handshake already validated.\n\nimport { isProto, outputOf } from \"../channel.js\";\nimport type { ClientSpawner } from \"../client.js\";\nimport { json1Channel, VERSION } from \"../protocols/json1.js\";\nimport { connectUnixSocket, type UnixSocketClientOptions } from \"../socket.js\";\nimport { stderrSink, withOutput, type OutputSink } from \"../output.js\";\n\n/** What a socket client needs: how to reach it, and where the far end's own output goes. */\nexport interface SocketClientSpawnerOptions extends UnixSocketClientOptions {\n /** Where the far end's own output goes. Defaults to our stderr. */\n onOutput?: OutputSink;\n}\n\nexport function socketClientSpawner<Args = unknown>(\n path: string | ((args: Args) => string),\n options: SocketClientSpawnerOptions = {},\n): ClientSpawner<Args> {\n return async (args) => {\n const target = typeof path === \"function\" ? path(args) : path;\n const transport = await connectUnixSocket(target, options);\n const channel = json1Channel(transport);\n const sink = options.onOutput ?? stderrSink();\n\n // The waiter is set with no await between it and the connection: the transport starts reading as\n // soon as it is made, so a server that says `$proto` first thing would have it dropped otherwise.\n // A frame that is the far end's own print is not the protocol's, so it goes to the sink and the\n // wait carries on.\n const first = await new Promise<Record<string, unknown>>((resolve) => {\n const off = channel.onMessage((frame) => {\n const output = outputOf(frame);\n if (output) {\n sink(output.fd, output.data);\n return;\n }\n off();\n resolve(frame);\n });\n });\n if (!isProto(first) || first.$proto !== VERSION) {\n throw new Error(`unsupported protocol: ${JSON.stringify(first)}`);\n }\n return withOutput(channel, sink);\n };\n}\n","// ── websockets: a listener over an HTTP server's upgrades ────────────────────\n//\n// A websocket as a medium for the reactor. The consumer's HTTP server owns the socket, and the\n// handshake is the WebSocket implementation's own step — with `ws`, or whatever the runtime ships —\n// so this listener takes one thing from the consumer: the call that completes it. Everything else\n// here is the accept loop: which upgrade becomes a connection, who may present one, and what a\n// refused one is told. One upgrade is one connection, so there is nothing to keep between them.\n\nimport type { IncomingMessage } from \"node:http\";\nimport type { Duplex } from \"node:stream\";\n\nimport type { Connection, Listener } from \"./reactor.js\";\nimport { WebSocketTransport, type WebSocketLike } from \"./transports/websocket.js\";\n\n/** What the far side is told when admission refuses it: not this door, and no handshake happened. */\nconst REFUSED = \"HTTP/1.1 401 Unauthorized\\r\\nconnection: close\\r\\n\\r\\n\";\n\n/** A server that reports an upgrade before answering it: node's `http`/`https` server. */\nexport interface UpgradeSource {\n on(event: \"upgrade\", listener: (request: IncomingMessage, socket: Duplex, head: Buffer) => void): unknown;\n off(event: \"upgrade\", listener: (request: IncomingMessage, socket: Duplex, head: Buffer) => void): unknown;\n}\n\n/** What arrived: the request that asked to upgrade, and the URL it asked for. */\nexport interface WebSocketUpgrade {\n readonly request: IncomingMessage;\n readonly url: URL;\n}\n\nexport interface WebSocketListenerOptions<Meta = unknown> {\n /** The server whose upgrades become connections. */\n server: UpgradeSource;\n /**\n * Which path upgrades. An upgrade on any other path is not this listener's and is left as it\n * arrived, so one server can route its paths between listeners. Every path upgrades when it is\n * not given.\n */\n path?: string;\n /**\n * Admission and identity. What it returns is the connection's meta; throwing refuses the upgrade\n * before any actor exists — a refused connection costs no actor and no channel — and the far side\n * is told by `refuse`.\n */\n identify?(upgrade: WebSocketUpgrade): Meta | Promise<Meta>;\n /**\n * Complete the handshake and answer with the socket: the WebSocket implementation's own step,\n * which is the one thing the library does not carry. With `ws`:\n *\n * ```ts\n * upgrade: (request, socket, head) =>\n * new Promise((resolve) => wss.handleUpgrade(request, socket, head, (ws) => resolve(socketOf(ws))))\n * ```\n */\n upgrade(request: IncomingMessage, socket: Duplex, head: Buffer): Promise<WebSocketLike>;\n /** What a refused upgrade is told. Default: `401`, and the socket is closed. */\n refuse?(socket: Duplex, error: unknown, upgrade: WebSocketUpgrade): void;\n}\n\n/** An upgrade admission accepted, waiting for a connection to be taken from the queue. */\ninterface Admitted<Meta> {\n request: IncomingMessage;\n socket: Duplex;\n head: Buffer;\n meta: Meta;\n}\n\n/**\n * Take connections from an HTTP server's upgrades, as the reactor's `Listener`.\n *\n * Admission happens when the upgrade arrives, so a refusal is the far side's before any handshake,\n * and the handshake happens when a connection is accepted: what the reactor is handed is an open\n * websocket and the meta it was admitted with.\n */\nexport function webSocketListener<Meta = unknown>(options: WebSocketListenerOptions<Meta>): Listener<Meta> {\n const { server, path } = options;\n /** Every socket this listener is responsible for: what it has taken, and what it is holding. */\n const held = new Set<Duplex>();\n const accepted: Admitted<Meta>[] = [];\n let waiting: { resolve: (admitted: Admitted<Meta>) => void; reject: (error: Error) => void } | null = null;\n let closed = false;\n // One admission at a time, in the order the upgrades arrived: an `identify` that waits would\n // otherwise let a later connection overtake an earlier one.\n let admitting: Promise<void> = Promise.resolve();\n\n const handshake = async (admitted: Admitted<Meta>): Promise<Connection<Meta>> => {\n const socket = await options.upgrade(admitted.request, admitted.socket, admitted.head);\n return { meta: admitted.meta, transport: new WebSocketTransport(socket) };\n };\n\n const take = (admitted: Admitted<Meta>): void => {\n held.add(admitted.socket);\n admitted.socket.once(\"close\", () => held.delete(admitted.socket));\n const pending = waiting;\n waiting = null;\n if (pending) pending.resolve(admitted);\n else accepted.push(admitted);\n };\n\n const admit = async (request: IncomingMessage, socket: Duplex, head: Buffer): Promise<void> => {\n let url: URL;\n try {\n url = new URL(request.url ?? \"/\", `http://${request.headers.host ?? \"localhost\"}`);\n } catch {\n // A request that cannot even be read as one is not one this listener can serve.\n socket.destroy();\n return;\n }\n if (path !== undefined && url.pathname !== path) return;\n const upgrade: WebSocketUpgrade = { request, url };\n let meta: Meta;\n try {\n meta = options.identify ? await options.identify(upgrade) : (undefined as Meta);\n } catch (error) {\n try {\n if (options.refuse) options.refuse(socket, error, upgrade);\n else socket.end(REFUSED);\n } catch {\n // A refusal hook that throws is still a refusal: the socket goes rather than the far side\n // waiting for an answer nobody is going to write.\n socket.destroy();\n }\n return;\n }\n // A far side that gave up while admission was being decided is nobody's to serve.\n if (closed || socket.destroyed) return;\n take({ request, socket, head, meta });\n };\n\n const arrived = (request: IncomingMessage, socket: Duplex, head: Buffer): void => {\n admitting = admitting.then(() => admit(request, socket, head));\n };\n\n server.on(\"upgrade\", arrived);\n\n const release = (error: Error): void => {\n const pending = waiting;\n waiting = null;\n pending?.reject(error);\n };\n\n return {\n accept(signal?: AbortSignal): Promise<Connection<Meta>> {\n if (closed) return Promise.reject(new Error(\"webSocketListener: closed\"));\n const taken = accepted.shift();\n if (taken) return handshake(taken);\n return new Promise<Connection<Meta>>((resolve, reject) => {\n const mine = {\n resolve: (admitted: Admitted<Meta>) => {\n handshake(admitted).then(resolve, reject);\n },\n reject,\n };\n waiting = mine;\n signal?.addEventListener(\n \"abort\",\n () => {\n if (waiting === mine) waiting = null;\n reject(new Error(\"webSocketListener: stopped\"));\n },\n { once: true },\n );\n });\n },\n async close(): Promise<void> {\n closed = true;\n server.off(\"upgrade\", arrived);\n release(new Error(\"webSocketListener: closed\"));\n // A connection this listener was given ends with it: the client learns that from its own socket\n // closing rather than from a handshake nobody is left to answer.\n for (const socket of held) socket.destroy();\n held.clear();\n accepted.length = 0;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAUA,IAAa,yBAAb,MAAa,uBAAkD;CAY7D,YAAoB,MAAqD;EANjB,KAAA,eAAA;EACd,KAAA,aAAA;EACzB,KAAA,SAAA;EAC8B,KAAA,iBAAA;EACd,KAAA,WAAA;EAG/B,KAAK,SAAS,KAAK,UAAU;EAC7B,KAAK,UAAU,KAAK,WAAW;EAE/B,IAAI,KAAK,QAAQ;GACf,KAAK,KAAK,KAAK,OAAO,iBAAiB,EAAE,UAAU,QAAQ,CAAC;GAC5D,KAAK,KAAK,SAAS,gBAAgB,EAAE,OAAO,KAAK,GAAG,CAAC;GAErD,KAAK,GAAG,GAAG,SAA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AC1C,KAAK,MAAM;GACX,SAAS,SAAS;EACpB;CACF;AACF"}
1
+ {"version":3,"file":"node.js","names":["atPath","wireErrorFrame","wireErrorReason","errorText","errorText","Lines"],"sources":["../../src/remote/transports/fifo.ts","../../src/remote/fifo.ts","../../src/remote/spawners/fifo-command.ts","../../src/remote/kit.ts","../../src/remote/spawners/fifo-argv.ts","../../src/remote/define-subprocess.ts","../../src/remote/stdio.ts","../../src/remote/streams.ts","../../src/remote/gateway.ts","../../src/remote/host.ts","../../src/remote/gateway-client.ts","../../src/remote/socket.ts","../../src/remote/spawners/socket-client.ts","../../src/remote/websocket.ts"],"sourcesContent":["// ── FIFO transport ─────────────────────────────────────────────────────────\n//\n// Newline-delimited UTF-8 over named fifos. Strict handler lifecycle:\n// onMessage() throws if a handler is already set; call removeHandler() first.\n\nimport { open, type FileHandle } from \"node:fs/promises\";\nimport type { ReadStream, WriteStream } from \"node:fs\";\nimport { readParts, type LineReader } from \"../lines.js\";\nimport type { StringTransport } from \"../channel.js\";\n\nexport class FifoUtf8NlineTransport implements StringTransport {\n private readFd: FileHandle | null;\n private writeFd: FileHandle | null;\n private reader: LineReader | null;\n private rs: ReadStream | null;\n private ws: WriteStream | null;\n private pvtOnMessage: ((line: string) => number | void) | null = null;\n private pvtOnBytes: ((bytes: Uint8Array) => void) | null = null;\n private pvtOnClose: (() => void) | null = null;\n private closed = false;\n private closingPromise: Promise<void> | null = null;\n private pvtError: Error | null = null;\n\n private constructor(opts: { readFd?: FileHandle; writeFd?: FileHandle }) {\n this.readFd = opts.readFd ?? null;\n this.writeFd = opts.writeFd ?? null;\n\n if (this.readFd) {\n this.rs = this.readFd.createReadStream();\n this.reader = readParts(\n this.rs,\n (line) => (this.closed ? undefined : this.pvtOnMessage?.(line)),\n (bytes) => {\n if (!this.closed) this.pvtOnBytes?.(bytes);\n },\n () => {\n this.pvtOnClose?.();\n void this.close();\n },\n );\n\n this.rs.on(\"error\", (err: Error) => {\n this.pvtError = err;\n this.close();\n });\n } else {\n this.rs = null;\n this.reader = null;\n }\n\n if (this.writeFd) {\n this.ws = this.writeFd.createWriteStream({});\n this.ws.on(\"error\", (err: Error) => {\n this.pvtError = err;\n this.close();\n });\n } else {\n this.ws = null;\n }\n }\n\n // ── factories ──────────────────────────────────────────────────────────\n\n static openReaderFd(readFd: FileHandle): FifoUtf8NlineTransport {\n return new FifoUtf8NlineTransport({ readFd });\n }\n\n static openWriterFd(writeFd: FileHandle): FifoUtf8NlineTransport {\n return new FifoUtf8NlineTransport({ writeFd });\n }\n\n static fromFds(readFd: FileHandle, writeFd: FileHandle): FifoUtf8NlineTransport {\n return new FifoUtf8NlineTransport({ readFd, writeFd });\n }\n\n // ── bidirectional connection ───────────────────────────────────────────\n\n /**\n * Start opening a bidirectional connection. Opens readPath for reading\n * in the background, returns a promise. The caller should do whatever\n * setup is needed to unblock the read (e.g. spawn a process that opens\n * readPath for writing), then await the returned transport.\n *\n * The transport itself is built only once both directions are open. A read\n * stream created while no writer exists on its fifo is handed an immediate\n * end-of-stream by some runtimes (bun), which closes a channel that has not\n * carried a byte yet — so the writes side is opened before the reader exists.\n */\n static beginConnect(\n readPath: string,\n writePath: string,\n ): { transport: Promise<FifoUtf8NlineTransport> } {\n const readFdPromise = open(readPath, \"r\");\n\n const transport = readFdPromise.then(async (readFd) => {\n const writeFd = await open(writePath, \"w\");\n return FifoUtf8NlineTransport.fromFds(readFd, writeFd);\n });\n\n return { transport };\n }\n\n /**\n * Open a bidirectional connection. Opens writePath for writing first\n * (unblocking the peer's read), starts reading readPath in the\n * background, then awaits both.\n *\n * Use this when you are the side that responds to the peer's beginConnect\n * (i.e. you don't need to interleave any setup between the read and write\n * opens). Built like `beginConnect`: the transport exists only after both\n * directions do.\n */\n static async connect(readPath: string, writePath: string): Promise<FifoUtf8NlineTransport> {\n const readFdPromise = open(readPath, \"r\");\n const writeFd = await open(writePath, \"w\");\n const readFd = await readFdPromise;\n return FifoUtf8NlineTransport.fromFds(readFd, writeFd);\n }\n\n // ── public API ─────────────────────────────────────────────────────────\n\n get canSend(): boolean {\n return this.writeFd !== null && !this.closed;\n }\n\n onBytes(handler: (bytes: Uint8Array) => void): void {\n if (this.closed) throw new Error(\"FifoUtf8NlineTransport: closed\");\n if (this.readFd === null) throw new Error(\"FifoUtf8NlineTransport: not a reader\");\n this.pvtOnBytes = handler;\n }\n\n onMessage(handler: (line: string) => number | void): void {\n if (this.closed) throw new Error(\"FifoUtf8NlineTransport: closed\");\n if (this.readFd === null) throw new Error(\"FifoUtf8NlineTransport: not a reader\");\n if (this.pvtOnMessage !== null) {\n throw new Error(\"FifoUtf8NlineTransport: handler already set — call removeHandler() first\");\n }\n this.pvtOnMessage = handler;\n }\n\n removeHandler(): ((line: string) => number | void) | null {\n const prev = this.pvtOnMessage;\n this.pvtOnMessage = null;\n return prev;\n }\n\n onClose(handler: () => void): void {\n this.pvtOnClose = handler;\n }\n\n get hasHandler(): boolean {\n return this.pvtOnMessage !== null;\n }\n\n get lastError(): Error | null {\n return this.pvtError;\n }\n\n async send(line: string): Promise<void> {\n if (this.closed) throw new Error(\"FifoUtf8NlineTransport: closed\");\n if (this.writeFd === null) throw new Error(\"FifoUtf8NlineTransport: not a writer\");\n if (!line.endsWith(\"\\n\")) line += \"\\n\";\n await this.ws?.write(line);\n }\n\n async sendBytes(bytes: Uint8Array): Promise<void> {\n if (this.closed) throw new Error(\"FifoUtf8NlineTransport: closed\");\n if (this.writeFd === null) throw new Error(\"FifoUtf8NlineTransport: not a writer\");\n await this.ws?.write(bytes);\n }\n\n async close(): Promise<void> {\n this.closingPromise = this.closingPromise || this.pvtClose();\n await this.closingPromise;\n this.closed = true;\n }\n\n private async pvtClose(): Promise<void> {\n // tranfser control back to caller\n // so they can capture the promise reference\n // and prevent reentry\n await Promise.resolve();\n\n if (this.reader) {\n this.reader.stop();\n this.reader = null;\n }\n if (this.rs) {\n this.rs.destroy();\n this.rs = null;\n }\n if (this.ws) {\n await new Promise<void>((resolve) => {\n try {\n this.ws?.end(\"\", resolve);\n } catch {\n resolve();\n }\n });\n this.ws = null;\n }\n\n if (this.readFd) {\n try {\n await this.readFd.close();\n } catch {}\n this.readFd = null;\n }\n if (this.writeFd) {\n try {\n await this.writeFd.close();\n } catch {}\n this.writeFd = null;\n }\n }\n}\n","// ── a fifo pair, as a listener and as a client ─────────────────────────────\n//\n// Two named pipes are one connection: whoever reads one and writes the other is talking to the side that\n// did the opposite. The medium gives one client per lifetime, so the listener takes one connection and is\n// done, and the pair itself is made idempotently and never removed from under a client's feet.\n\nimport { execFile } from \"node:child_process\";\nimport { mkdir, open, stat } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { promisify } from \"node:util\";\n\nimport type { ClientSpawner } from \"./client.js\";\nimport { isProto } from \"./channel.js\";\nimport { json1Channel, VERSION } from \"./protocols/json1.js\";\nimport type { Connection, Listener } from \"./reactor.js\";\nimport { FifoUtf8NlineTransport } from \"./transports/fifo.js\";\n\nconst runMkfifo = promisify(execFile);\n\n/**\n * The pair, named as the serving side sees it: `read` is where it reads, and `write` where it writes. The\n * client side passes the same pair and swaps them, which is what makes it a pair rather than two paths.\n */\nexport interface FifoPair {\n readonly read: string;\n readonly write: string;\n}\n\nexport interface FifoListenerOptions<Meta = unknown> {\n /** Make the pair when it is missing, and refuse a path that exists and is not a fifo. Default true. */\n make?: boolean;\n /** Admission and identity: what this returns is the connection's meta. */\n identify?(pair: FifoPair): Meta | Promise<Meta>;\n}\n\n/** What is at a path: nothing, a fifo, or something else. */\nasync function atPath(path: string): Promise<\"missing\" | \"fifo\" | \"other\"> {\n try {\n const info = await stat(path);\n return info.isFIFO() ? \"fifo\" : \"other\";\n } catch {\n return \"missing\";\n }\n}\n\n/**\n * Make the pair unless it is already there. A fifo is a file and one pair serves every connection, so\n * nothing is recreated; something that is not a fifo where the pair goes is refused rather than worked\n * around, because a regular file read as input is a silence nobody can explain.\n */\nexport async function makeFifoPair(pair: FifoPair): Promise<void> {\n await mkdir(dirname(pair.read), { recursive: true });\n await mkdir(dirname(pair.write), { recursive: true });\n for (const path of [pair.read, pair.write]) {\n const there = await atPath(path);\n if (there === \"fifo\") continue;\n if (there === \"other\") throw new Error(`makeFifoPair: ${path} is not a fifo`);\n await runMkfifo(\"mkfifo\", [\"-m\", \"0600\", path]);\n }\n}\n\n/**\n * Listen on a pair, as the served side: it reads `pair.read` and writes `pair.write`, and it opens the\n * write end first. That order is the handshake: a stream opened for reading on a fifo nobody writes to is\n * handed an immediate end-of-stream by some runtimes, which closes a connection that never carried a byte.\n */\nexport async function fifoListener<Meta = unknown>(\n pair: FifoPair,\n options: FifoListenerOptions<Meta> = {},\n): Promise<Listener<Meta>> {\n if (options.make ?? true) await makeFifoPair(pair);\n\n let taken = false;\n let closed = false;\n let parked: (() => Promise<void>) | null = null;\n let settled: Promise<void> = Promise.resolve();\n let release: { close: () => Promise<void> } | null = null;\n\n const unblock = async (): Promise<void> => {\n // The parked open is a writer waiting for a reader on `write`; reading it here is what releases it,\n // and a writer on `read` is what releases the read it opens next. Both are held until it is through.\n const reader = await open(pair.write, \"r\");\n const writer = await open(pair.read, \"w\");\n release = {\n close: async () => {\n await writer.close();\n await reader.close();\n },\n };\n };\n return {\n async accept(): Promise<Connection<Meta>> {\n if (taken) throw new Error(\"fifoListener: the pair carries one connection per lifetime\");\n if (closed) throw new Error(\"fifoListener: closed\");\n taken = true;\n parked = unblock;\n\n let through: () => void = () => {};\n settled = new Promise<void>((resolve) => {\n through = resolve;\n });\n try {\n const transport = await FifoUtf8NlineTransport.connect(pair.read, pair.write);\n parked = null;\n if (closed) {\n // The release is what let this open through, and the listener is over: the connection it made is\n // closed rather than served.\n await transport.close();\n throw new Error(\"fifoListener: closed while waiting for a connection\");\n }\n const meta = options.identify ? await options.identify(pair) : (undefined as Meta);\n return { meta, transport };\n } finally {\n through();\n }\n },\n async close(): Promise<void> {\n closed = true;\n // Release a wait parked on the pair, let the accept finish either way, and only then let go of the\n // handles that released it: they are what the parked open was waiting for.\n if (parked) await parked();\n await settled;\n await release?.close();\n },\n };\n}\n\n/**\n * Connect to a pair, as the client side: it reads what the listener writes and writes what it reads,\n * and it awaits the `$proto` frame, which is the side of the handshake a served actor speaks.\n */\nexport function fifoClientSpawner<Args = unknown>(\n pair: FifoPair | ((args: Args) => FifoPair),\n): ClientSpawner<Args> {\n return async (args) => {\n const served = typeof pair === \"function\" ? pair(args) : pair;\n // The swap: this side reads what the serving side writes.\n const { transport } = FifoUtf8NlineTransport.beginConnect(served.write, served.read);\n const channel = json1Channel(await transport);\n const first = await new Promise<Record<string, unknown>>((resolve) => {\n const off = channel.onMessage((frame) => {\n off();\n resolve(frame);\n });\n });\n if (!isProto(first) || first.$proto !== VERSION) {\n throw new Error(`unsupported protocol: ${JSON.stringify(first).slice(0, 50)}`);\n }\n return channel;\n };\n}\n","// ── FIFO client spawner (command) ──────────────────────────────────────────\n//\n// Environment-specific: spawns a command, makes the two named fifos it is to serve on, and hands back\n// the frame Channel whose far side is that child. The pair's own half is fifo.ts's — connect, and wait\n// for the `$proto` — so what is left here is the child, the paths in its argv, and the cleanup.\n\nimport { spawn } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { unlink } from \"node:fs/promises\";\nimport type { Channel } from \"../channel.js\";\nimport { fifoClientSpawner, makeFifoPair } from \"../fifo.js\";\n\nexport function commandSpawner(command: string[]): () => Promise<Channel> {\n return async () => {\n const basePath = join(tmpdir(), `posipaki-${randomUUID()}`);\n // The pair as the child meets it: it reads `.out` and writes `.in`. Made before the child exists,\n // so the child's own open finds it waiting rather than making it late.\n await makeFifoPair({ read: `${basePath}.out`, write: `${basePath}.in` });\n\n const child = spawn(\n command[0],\n [...command.slice(1), `--fifo-in=${basePath}.in`, `--fifo-out=${basePath}.out`],\n {\n cwd: process.cwd(),\n stdio: [\"inherit\", \"inherit\", \"inherit\"],\n },\n );\n\n const channel = await fifoClientSpawner<unknown>({\n read: `${basePath}.out`,\n write: `${basePath}.in`,\n })(undefined);\n\n let cleaned = false;\n const cleanup = (): void => {\n if (cleaned) return;\n cleaned = true;\n void channel.close();\n unlink(`${basePath}.in`).catch(() => {});\n unlink(`${basePath}.out`).catch(() => {});\n };\n child.on(\"exit\", cleanup);\n\n return channel;\n };\n}\n","// ── Kit ────────────────────────────────────────────────────────────────────\n//\n// Getting a payload onto a host we know nothing about. A way in gives us a\n// shell; from there one script runs everywhere: probe what is really there, write\n// the kit only if it is not, and report every step as one machine-readable line.\n// The script always arrives on stdin, never in argv — and since stdin *is* the\n// script, the payload gets its own channel into the same environment (a second\n// `ssh`, an `exec` on a container that is already running).\n//\n// The script assumes POSIX sh and nothing else: `command -v`, `mkdir -p`,\n// `wc -c`, `base64 -d`. A broken environment therefore reaches the client as a\n// readable reason instead of a channel that just closes.\n//\n// A kit is named after the *host version* it serves — the app, the build its bytes came from\n// and the posipaki release that speaks to it — so two consumers, two builds or two releases\n// cannot land on each other's files, and the directory a kit sits in cannot disagree with the\n// identity the client then states on the wire. A payload that is started for a host version\n// other than its own refuses to serve (see `hostVersionAccepts`), so a name alone is never\n// mistaken for the build behind it.\n\nimport { createHash } from \"node:crypto\";\nimport { LIB_VERSION } from \"../version.js\";\n\n/** Runtimes a kit is happy to be run with, best first. A caller may override. */\nexport const DEFAULT_RUNTIMES = [\"node\", \"nodejs\", \"bun\"];\n\n/** Layout of a staged kit — the contract's own version, recorded in `version.json`. */\nexport const KIT_LAYOUT = 1;\n\n/** Where kits live on a host, relative to `$HOME`, unless the caller says otherwise. */\nexport const DEFAULT_KIT_PARENT = \"bin/posipaki\";\n\n/** The names a kit's two bundles get: the payload, and the gateway that relays to it. */\nexport const PAYLOAD_ARTIFACT = \"payload.js\";\nexport const GATEWAY_ARTIFACT = \"gateway.js\";\n\nexport interface KitFile {\n /** Name inside the kit directory, e.g. `payload.js`. */\n name: string;\n /** The file's bytes, base64 — what the script writes. */\n base64: string;\n /** Byte count, for the cheap presence check. */\n bytes: number;\n /** sha256 of the file, recorded in `version.json`. */\n sha256: string;\n}\n\n/** Who is staging this kit: the consumer's own name and build version. */\nexport interface KitApp {\n name: string;\n version: string;\n}\n\nexport interface Kit {\n /** Directory name: the host version this kit serves, as {@link hostVersion} renders it. */\n name: string;\n /** Everything the kit installs, `version.json` last. */\n files: KitFile[];\n /** Runtime candidates, in order; the first one found wins. */\n runtimes: string[];\n /** Directory the kit lands in, relative to the host's `$HOME`. */\n parent: string;\n /** The consumer this kit belongs to. */\n app: KitApp;\n}\n\nexport interface MakeKitOptions {\n /** Required: a kit with no owner cannot be told apart from another's. */\n app: KitApp;\n /** Defaults to {@link DEFAULT_RUNTIMES}. */\n runtimes?: string[];\n /** Defaults to {@link DEFAULT_KIT_PARENT}. */\n parent?: string;\n}\n\nexport type BootstrapReport =\n | { kind: \"ready\"; kitDir: string; runtime: string; staged: boolean }\n | { kind: \"error\"; reason: string };\n\n/** Hex sha256 of some content. */\nexport function sha256Hex(content: string | Uint8Array): string {\n return createHash(\"sha256\").update(content).digest(\"hex\");\n}\n\n/** What may stand as one fact in a host version: no `@`, no whitespace, no `/`. */\nconst FACT = /^[A-Za-z0-9][A-Za-z0-9.+_-]*$/;\n\n/** The label posipaki's own field carries, so nobody has to guess which field it is. */\nconst POSIPAKI_FIELD = \"posipaki-\";\n\n/** A host version read back: what a consumer stated, and the posipaki that rendered it. */\nexport interface HostVersion extends KitApp {\n posipaki: string;\n}\n\n/** A name or version that could not stand as one fact in a host version. */\nexport class HostVersionError extends Error {}\n\n/**\n * The one value that says what a host is expected to run: whose payload it is, which build\n * those bytes came from, and the posipaki release that speaks to it —\n * `email-agent@1.0.0+d52ee13@posipaki-0.35.0`.\n *\n * One string rather than three flags because it is one fact: it names the kit directory, it\n * travels with every way in, and the payload compares it with its own before it serves. A\n * consumer states the two facts only it knows; posipaki renders its own release, so that\n * field cannot be got wrong. `@` separates, and no name or version may contain one.\n */\nexport function hostVersion(app: KitApp): string {\n const facts: [string, string][] = [\n [\"name\", app.name],\n [\"version\", app.version],\n ];\n for (const [what, value] of facts) {\n if (!FACT.test(value)) {\n throw new HostVersionError(\n `an app ${what} must match ${FACT.source}: ${JSON.stringify(value)}`,\n );\n }\n }\n return `${app.name}@${app.version}@${POSIPAKI_FIELD}${LIB_VERSION}`;\n}\n\n/** What a {@link hostVersion} string names, or undefined when it names nothing. */\nexport function parseHostVersion(text: string): HostVersion | undefined {\n const fields = text.split(\"@\");\n if (fields.length !== 3) return undefined;\n const [name, version, posipaki] = fields as [string, string, string];\n if (!FACT.test(name) || !FACT.test(version)) return undefined;\n if (!posipaki.startsWith(POSIPAKI_FIELD)) return undefined;\n const release = posipaki.slice(POSIPAKI_FIELD.length);\n if (!FACT.test(release)) return undefined;\n return { name, version, posipaki: release };\n}\n\n/** Exit code a payload refuses a start with: it is not the build that was asked for. */\nexport const PAYLOAD_REFUSED = 78;\n\nexport type HostVersionVerdict = { ok: true } | { ok: false; reason: string };\n\n/**\n * Whether a payload may serve what it was asked for. `own` is what its bytes carry, `asked`\n * is what the caller said — two independent facts, and one of the four combinations is the\n * dangerous one: an artifact that knows what it is, started by a caller that never said which\n * host version it is for, is exactly the stale caller we refuse.\n *\n * No baked version, nothing to compare: an artifact that does not know what it is cannot be\n * wrong about it, and a caller that states a version for such a payload is only being helpful.\n */\nexport function hostVersionAccepts(\n own: string | undefined,\n asked: string | undefined,\n): HostVersionVerdict {\n if (own === undefined) return { ok: true };\n if (asked === undefined) {\n return { ok: false, reason: `this artifact is ${own}, and no host version was asked for` };\n }\n if (!sameHostVersion(own, asked)) {\n return { ok: false, reason: `asked to serve ${asked}, but this artifact is ${own}` };\n }\n return { ok: true };\n}\n\n/**\n * Whether two host versions are the same build. Equality for now: {@link hostVersionAccepts}\n * is the rule, and this is the one function that decides what \"the same\" means — so a range, a\n * compatibility table or a protocol-only comparison is a change here and nowhere else.\n */\nexport function sameHostVersion(own: string, asked: string): boolean {\n return own === asked;\n}\n\n/** Wrap base64 at a comfortable width; `base64 -d` ignores the newlines. */\nfunction wrapped(base64: string, width = 76): string {\n const lines: string[] = [];\n for (let at = 0; at < base64.length; at += width) lines.push(base64.slice(at, at + width));\n return lines.join(\"\\n\");\n}\n\n/**\n * Describe a kit around its files. Its name is the host version it serves, and `version.json`\n * — which records that name and every file's hash — is written as one of them: it describes\n * the payload and the gateway, never itself.\n */\nexport function makeKit(\n files: { name: string; content: string | Uint8Array }[],\n options: MakeKitOptions,\n): Kit {\n const raw = files.map((file) => ({\n name: file.name,\n bytes: Buffer.byteLength(file.content),\n sha256: sha256Hex(file.content),\n base64: Buffer.from(file.content).toString(\"base64\"),\n }));\n const kit: Kit = {\n name: hostVersion(options.app),\n files: raw,\n runtimes: [...(options.runtimes ?? DEFAULT_RUNTIMES)],\n parent: options.parent ?? DEFAULT_KIT_PARENT,\n app: options.app,\n };\n const version = Buffer.from(`${JSON.stringify(kitVersion(kit), null, 2)}\\n`);\n return {\n ...kit,\n files: [\n ...kit.files,\n {\n name: \"version.json\",\n bytes: version.byteLength,\n sha256: sha256Hex(version),\n base64: version.toString(\"base64\"),\n },\n ],\n };\n}\n\n/** What `version.json` says: the identity, the facts it was rendered from, and the hashes. */\nexport function kitVersion(kit: Kit): Record<string, unknown> {\n return {\n hostVersion: kit.name,\n app: kit.app,\n posipaki: LIB_VERSION,\n layout: KIT_LAYOUT,\n files: kit.files.map((file) => ({ name: file.name, sha256: file.sha256, bytes: file.bytes })),\n };\n}\n\n/** The `[ -f … ] && [ \"$(wc -c < …)\" -eq … ]` test for one file. */\nfunction presentTest(file: KitFile): string {\n return `[ -f \"$kit_dir/${file.name}\" ] && [ \"$(wc -c < \"$kit_dir/${file.name}\")\" -eq ${file.bytes} ]`;\n}\n\n/** One file: write it to a temp name, then move it into place. */\nfunction writeFile(file: KitFile): string {\n return [\n ` base64 -d > \"$tmp\" <<'KIT_FILE'`,\n wrapped(file.base64),\n \"KIT_FILE\",\n ` mv \"$tmp\" \"$kit_dir/${file.name}\" || { echo \"error cannot install ${file.name}\"; exit 73; }`,\n ].join(\"\\n\");\n}\n\n/**\n * The bootstrap, as one POSIX sh script.\n *\n * Staging is the whole job. The script always arrives on stdin, never in argv,\n * and that is also why it cannot carry the wire: the caller runs the payload on a\n * second channel into the same environment once this one has reported.\n */\nexport function bootstrapScript(kit: Kit): string {\n const checks = kit.files.map(presentTest).join(\" && \\\\\\n \");\n const lines = [\n \"# ── kit bootstrap ─────────────────────────────────────────────────────────\",\n \"# probe, stage what is missing, report every step as one machine-readable line.\",\n \"set -u\",\n \"\",\n 'if [ -z \"${HOME:-}\" ]; then echo \"error HOME is not set\"; exit 74; fi',\n `kit_dir=\"$HOME/${kit.parent}/${kit.name}\"`,\n \"\",\n 'runtime=\"\"',\n `for candidate in ${kit.runtimes.join(\" \")}; do`,\n ' if command -v \"$candidate\" >/dev/null 2>&1; then runtime=\"$(command -v \"$candidate\")\"; break; fi',\n \"done\",\n `if [ -z \"$runtime\" ]; then echo \"error no runtime among: ${kit.runtimes.join(\" \")}\"; exit 75; fi`,\n 'if ! command -v base64 >/dev/null 2>&1; then echo \"error base64 is missing\"; exit 76; fi',\n \"\",\n `if ${checks}; then`,\n ' echo \"present\"',\n \"else\",\n ` mkdir -p \"$kit_dir\" || { echo \"error cannot create $kit_dir\"; exit 73; }`,\n ' tmp=\"$kit_dir/.staging.$$\"',\n ...kit.files.map(writeFile),\n ' echo \"staged\"',\n \"fi\",\n 'echo \"kit $kit_dir\"',\n 'echo \"runtime $runtime\"',\n ];\n return `${lines.join(\"\\n\")}\\n`;\n}\n\n/** Read the script's report back. Missing or unknown lines are an error. */\nexport function parseBootstrapReport(stdout: string): BootstrapReport {\n let kitDir = \"\";\n let runtime = \"\";\n let staged: boolean | null = null;\n for (const raw of stdout.split(\"\\n\")) {\n const line = raw.trim();\n if (line === \"\") continue;\n if (line.startsWith(\"error \")) return { kind: \"error\", reason: line.slice(\"error \".length) };\n if (line === \"staged\") {\n staged = true;\n continue;\n }\n if (line === \"present\") {\n staged = false;\n continue;\n }\n if (line.startsWith(\"kit \")) {\n kitDir = line.slice(\"kit \".length);\n continue;\n }\n if (line.startsWith(\"runtime \")) {\n runtime = line.slice(\"runtime \".length);\n continue;\n }\n }\n if (kitDir === \"\" || runtime === \"\" || staged === null) {\n const seen = stdout.trim();\n return {\n kind: \"error\",\n reason: seen === \"\" ? \"no report at all\" : `incomplete report: ${seen}`,\n };\n }\n return { kind: \"ready\", kitDir, runtime, staged };\n}\n","// ── FIFO server spawner (argv) ─────────────────────────────────────────────\n//\n// Environment-specific: reads what the caller put in argv — the two named fifos, and the host\n// version this artifact is being started for — checks that it *is* that build, connects, and\n// returns a frame Channel with the $proto handshake already sent.\n//\n// The check comes first, before anything is opened: a payload that is not the build that was\n// asked for has no business on a wire, and saying so before it connects is the only moment\n// where the reason is still readable to the caller.\n\nimport { FifoUtf8NlineTransport } from \"../transports/fifo.js\";\nimport { json1Channel, VERSION } from \"../protocols/json1.js\";\nimport type { Channel } from \"../channel.js\";\nimport { PAYLOAD_REFUSED, hostVersionAccepts } from \"../kit.js\";\n\n/** A `--flag=<value>` argument, or undefined. */\nfunction flag(name: string): string | undefined {\n const prefix = `--${name}=`;\n return process.argv.find((a) => a.startsWith(prefix))?.slice(prefix.length);\n}\n\n/**\n * Serve one payload over the fifo pair in argv.\n *\n * `own` is the host version this artifact's bytes carry, when its build stamped one: given it,\n * the payload refuses to serve a host version that differs, and refuses a start that names\n * none. Nothing stamped means nothing to check — and `--host-version`, if the caller sent one\n * anyway, is simply not ours to compare with.\n */\nexport async function fifoArgvSpawner(own?: string): Promise<Channel> {\n const verdict = hostVersionAccepts(own, flag(\"host-version\"));\n if (!verdict.ok) {\n console.error(`payload: ${verdict.reason}`);\n process.exit(PAYLOAD_REFUSED);\n }\n\n const fifoIn = flag(\"fifo-in\");\n const fifoOut = flag(\"fifo-out\");\n if (!fifoIn || !fifoOut) {\n console.error(\"server: --fifo-in=<path> and --fifo-out=<path> required\");\n process.exit(1);\n }\n\n const transport = await FifoUtf8NlineTransport.connect(fifoOut, fifoIn);\n const channel = json1Channel(transport);\n await channel.send({ $proto: VERSION });\n return channel;\n}\n","// ── defineSubprocessActor ───────────────────────────────────────────────────\n//\n// Environment-specific glue: wraps an actor definition so that spawning it runs\n// it in a subprocess over two named fifos. It does the guesswork — argv marker\n// detection and runner auto-detection — and prepares the client spawner. This\n// is the only place in the subprocess path that imports transports/protocols.\n\nimport { fileURLToPath } from \"node:url\";\nimport { createHash } from \"node:crypto\";\nimport type { Message } from \"../types.js\";\nimport type { ActorDefinition, HandlerOptions, MethodOptions, ReflectionOptions } from \"../actor-types.js\";\nimport type { KitApp } from \"./kit.js\";\nimport { hostVersion } from \"./kit.js\";\nimport { remoteClient } from \"./client.js\";\nimport { serveRemoteActor } from \"./reactor.js\";\nimport { commandSpawner } from \"./spawners/fifo-command.js\";\nimport { fifoArgvSpawner } from \"./spawners/fifo-argv.js\";\n\nexport interface SubprocessActorOptions {\n manual?: boolean;\n /**\n * Who this payload is: the app name and the build its bytes came from, as the consumer states\n * them. This is one switch for both halves of the seam — stated, every start passes\n * `--host-version` and the payload refuses to serve anything else; unstated, neither happens,\n * because there is no version to pass and none to check.\n */\n hostVersion?: KitApp;\n}\n\nexport interface SubprocessActorBundle<\n Args,\n State,\n InMsg extends Message,\n OutMsg extends Message,\n R extends ReflectionOptions,\n> {\n actor: ActorDefinition<Args, State, InMsg, OutMsg, R>;\n runRemoteRoot(): Promise<void>;\n isRemoteRoot: boolean;\n}\n\nfunction pathHash(path: string): string {\n return createHash(\"sha256\").update(path).digest(\"hex\").slice(0, 12);\n}\n\nconst MARKER_PREFIX = \"--remote=\";\n\nexport function defineSubprocessActor<\n Args,\n State,\n InMsg extends Message,\n OutMsg extends Message,\n Methods extends MethodOptions,\n Handlers extends HandlerOptions<InMsg>,\n R extends ReflectionOptions,\n>(\n actor: ActorDefinition<Args, State, InMsg, OutMsg, R>,\n url: string,\n opts: SubprocessActorOptions = {},\n): SubprocessActorBundle<Args, State, InMsg, OutMsg, R> {\n const scriptPath = fileURLToPath(url);\n const marker = `${MARKER_PREFIX}${pathHash(scriptPath)}`;\n const isRemoteRoot = !opts.manual && process.argv.includes(marker);\n const own =\n opts.hostVersion === undefined\n ? undefined\n : hostVersion(opts.hostVersion);\n\n const serve = () => serveRemoteActor(actor, () => fifoArgvSpawner(own));\n\n if (isRemoteRoot) {\n void serve();\n }\n\n const isBun = typeof (globalThis as { Bun?: unknown }).Bun !== \"undefined\";\n const runner = isBun ? \"bun\" : \"node\";\n const spawner = commandSpawner([\n runner,\n scriptPath,\n marker,\n ...(own === undefined ? [] : [`--host-version=${own}`]),\n ]);\n\n const proxyDef = remoteClient<Args, State, InMsg, OutMsg, Methods, Handlers, R>(\n actor.name ?? \"actor\",\n spawner,\n );\n\n return {\n actor: proxyDef,\n runRemoteRoot: serve,\n isRemoteRoot,\n };\n}\n","// ── stdio wire ─────────────────────────────────────────────────────────────\n//\n// A newline-delimited JSON channel over a pair of streams: the one wire every\n// way into a foreign execution context can carry. Two callers rely on it, and\n// they are two halves of the same thing:\n//\n// * the client of a spawn we make ourselves, on fds handed to the child (see\n// `fdStreams`) — private fds, so the child's own stdout stays free;\n// * a first-stage command on its own stdin/stdout, over ssh, under `sudo`, in\n// a container — where stdio is the only channel there is.\n//\n// Frames are one JSON object per line. Whatever the far end prints is carried as an *output\n// frame* (`$fd`), so it can never be mistaken for a frame of the protocol itself; a failed start\n// is carried as an `$error` frame.\n//\n// Output frames are routed above the protocol step, by whoever holds the connection (output.ts):\n// every line decodes to a frame, and the ones that are the far end's own print go to that\n// holder's sink instead of to the seam. The handshake below reads the first frame that is the\n// protocol's, since the far end's own print may come first.\n\nimport { createReadStream, createWriteStream } from \"node:fs\";\nimport { readParts } from \"./lines.js\";\nimport type { Readable, Writable } from \"node:stream\";\nimport {\n errorFrame as wireErrorFrame,\n errorReason as wireErrorReason,\n isProto,\n\n type Channel,\n\n type StringTransport,\n} from \"./channel.js\";\nimport { VERSION, json1Channel } from \"./protocols/json1.js\";\n\n\n/** The stream pair a line transport talks over. */\nexport interface LineStreams {\n read: Readable;\n write: Writable;\n}\n\n/** How long to wait for the far end's first protocol frame. */\nexport const HANDSHAKE_TIMEOUT_MS = 15_000;\n\n/** Raised when the wire itself fails: no frame, the wrong protocol, a peer that went away. */\nexport class StdioWireError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"StdioWireError\";\n }\n}\n\n/** An `$error` frame as a line. The word and its shape are the shared vocabulary's\n * (channel.ts) — one word for a wire that cannot be spoken over, whether the failure was at\n * the start of a session or in the middle of one; what this file owns is its line form. */\nexport function errorFrame(reason: string): string {\n return JSON.stringify(wireErrorFrame(reason));\n}\n\n/** The reason an `$error` frame carries, or null when it is not one. */\nexport function errorReason(frame: Record<string, unknown>): string | null {\n return wireErrorReason(frame);\n}\n\n// ── transports ─────────────────────────────────────────────────────────────\n\n/** Is this write error just a peer that already left? */\nfunction peerGone(code: unknown): boolean {\n return (\n code === \"EPIPE\" ||\n code === \"ERR_STREAM_DESTROYED\" ||\n code === \"ERR_STREAM_WRITE_AFTER_END\" ||\n code === \"ERR_STREAM_ALREADY_FINISHED\"\n );\n}\n\nfunction errorText(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * A `StringTransport` over a read/write stream pair, one JSON frame per line.\n *\n * `close()` is idempotent and never throws: teardown races are normal here —\n * the peer exits, the read side ends, and a write arrives a moment later.\n */\nexport class LineTransport implements StringTransport {\n private readonly streams: LineStreams;\n private pvtOnMessage: ((line: string) => number | void) | null = null;\n private pvtOnBytes: ((bytes: Uint8Array) => void) | null = null;\n private pvtOnClose: (() => void) | null = null;\n private pvtClosed = false;\n private pvtClosing: Promise<void> | null = null;\n\n constructor(streams: LineStreams) {\n this.streams = streams;\n readParts(\n streams.read,\n (line) => (this.pvtClosed ? undefined : this.pvtOnMessage?.(line)),\n (bytes) => {\n if (!this.pvtClosed) this.pvtOnBytes?.(bytes);\n },\n () => {\n this.pvtOnClose?.();\n void this.close();\n },\n );\n // A stream error is a peer that went away, not a reason to take the process\n // down with an unhandled 'error' event.\n streams.read.on(\"error\", () => {\n void this.close();\n });\n streams.write.on(\"error\", () => {\n void this.close();\n });\n }\n\n get closed(): boolean {\n return this.pvtClosed;\n }\n\n get hasHandler(): boolean {\n return this.pvtOnMessage !== null;\n }\n\n onMessage(handler: (line: string) => number | void): void {\n if (this.pvtClosed) throw new StdioWireError(\"stdio transport: closed\");\n if (this.pvtOnMessage !== null) {\n throw new StdioWireError(\"stdio transport: handler already set — call removeHandler()\");\n }\n this.pvtOnMessage = handler;\n }\n\n onBytes(handler: (bytes: Uint8Array) => void): void {\n if (this.pvtClosed) throw new StdioWireError(\"stdio transport: closed\");\n this.pvtOnBytes = handler;\n }\n\n removeHandler(): ((line: string) => number | void) | null {\n const previous = this.pvtOnMessage;\n this.pvtOnMessage = null;\n return previous;\n }\n\n onClose(handler: () => void): void {\n this.pvtOnClose = handler;\n }\n\n send(frame: string): Promise<void> {\n const line = frame.endsWith(\"\\n\") ? frame : `${frame}\\n`;\n return this.pvtWrite(line);\n }\n\n sendBytes(bytes: Uint8Array): Promise<void> {\n return this.pvtWrite(bytes);\n }\n\n private pvtWrite(data: string | Uint8Array): Promise<void> {\n if (this.pvtClosed) {\n return Promise.resolve();\n }\n return new Promise<void>((resolve, reject) => {\n try {\n this.streams.write.write(data, (err?: Error | null) => {\n if (!err) return resolve();\n const code = (err as { code?: unknown }).code;\n // A peer that has hung up cannot be told anything; the write that\n // races its exit is not an error in this transport.\n if (peerGone(code)) {\n return resolve();\n }\n reject(new StdioWireError(`stdio transport: ${err.message}`));\n });\n } catch (err) {\n reject(new StdioWireError(`stdio transport: ${errorText(err)}`));\n }\n });\n }\n\n async close(): Promise<void> {\n this.pvtClosing ??= this.pvtClose();\n await this.pvtClosing;\n }\n\n private async pvtClose(): Promise<void> {\n await Promise.resolve();\n\n this.pvtClosed = true;\n // Best effort: a half-open stream (the peer is already gone) must not turn\n // teardown into an exception.\n try {\n this.streams.read.destroy?.();\n } catch {\n /* already gone */\n }\n try {\n if (!this.streams.write.writableEnded) this.streams.write.end();\n } catch {\n /* already gone */\n }\n }\n}\n\n/** Streams over two fds of *our own* process — the child side of an fd wire. */\nexport function fdStreams(readFd: number, writeFd: number): LineStreams {\n const read = createReadStream(\"\", { fd: readFd, autoClose: false });\n const write = createWriteStream(\"\", { fd: writeFd, autoClose: false });\n return { read, write };\n}\n\n// ── handshakes ─────────────────────────────────────────────────────────────\n\n/** The next frame that is the protocol's, or a timeout. */\nasync function nextFrame(channel: Channel, timeoutMs: number): Promise<Record<string, unknown>> {\n return await new Promise((resolve, reject) => {\n const timer = setTimeout(\n () => reject(new StdioWireError(`no protocol frame within ${timeoutMs}ms`)),\n timeoutMs,\n );\n timer.unref?.();\n const off = channel.onMessage((frame) => {\n off();\n clearTimeout(timer);\n resolve(frame);\n });\n });\n}\n\nexport interface ClientChannelOptions {\n /** How long to wait for the peer's protocol frame. Defaults to {@link HANDSHAKE_TIMEOUT_MS}. */\n timeoutMs?: number;\n}\n\n/**\n * The client end of the connection: hand the streams to the seam and wait for the peer's `$proto`.\n * A first stage reports a failed start as an `$error` frame instead.\n *\n * What the far end prints is not here: it arrives as a stream the far end announces under a name,\n * and whoever wants it reads it by that name.\n */\nexport async function clientChannel(\n streams: LineStreams,\n opts: ClientChannelOptions = {},\n): Promise<Channel> {\n const channel = json1Channel(new LineTransport(streams));\n const frame = await nextFrame(channel, opts.timeoutMs ?? HANDSHAKE_TIMEOUT_MS);\n\n const reason = errorReason(frame);\n if (reason) throw new StdioWireError(reason);\n if (!isProto(frame)) {\n throw new StdioWireError(`unexpected first frame: ${JSON.stringify(frame).slice(0, 120)}`);\n }\n if (frame.$proto !== VERSION) {\n throw new StdioWireError(`unsupported protocol ${String(frame.$proto)}, expected ${VERSION}`);\n }\n return channel;\n}\n\n/** The server end of the wire — a payload speaking stdio itself. */\nexport async function serverChannel(streams: LineStreams): Promise<Channel> {\n const channel = json1Channel(new LineTransport(streams));\n await channel.send({ $proto: VERSION });\n return channel;\n}\n","// ── the connection's own logs ───────────────────────────────────────────────\n//\n// A program's prints are a stream it announces under a name (`stdout`, `stderr`) and the other side\n// reads like any other stream; what is left here is the conversion a *log* needs — lines out of\n// octets, at the level the stream says. The fd frames this file used to build are gone: the bytes\n// travel as streams, with credit and checksums, and the name says what they are.\n\nimport { Writable } from \"node:stream\";\n\n/**\n * What a log line needs: a stream says `info` or `warn`, and nothing here cares which logger it is.\n * The seam states the two methods rather than importing one, so a debug logger, a console or a test's\n * own collector all fit without the remote layer depending on a plugin.\n */\nexport interface LineLog {\n info(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n}\n\n/**\n * A writable that turns what is written to it into log lines: `stderr` arrives as `warn` and every\n * other name as `info`, and the tail is held until a newline (or the end) so a chunk boundary is not\n * a line boundary.\n */\nexport function logStream(log: LineLog, opts: { name?: string } = {}): Writable {\n const warn = opts.name === \"stderr\";\n const say = (line: string): void => {\n if (warn) log.warn(line);\n else log.info(line);\n };\n\n let tail = \"\";\n /** Everything up to the last newline goes out; what follows one waits to be finished. */\n const drain = (): void => {\n const lines = tail.split(\"\\n\");\n tail = lines.pop() ?? \"\";\n for (const line of lines) {\n if (line.length > 0) say(line);\n }\n };\n\n return new Writable({\n write(chunk: Buffer | string, _encoding, done): void {\n tail += String(chunk);\n drain();\n done();\n },\n final(done): void {\n drain();\n if (tail.length > 0) say(tail);\n done();\n },\n });\n}\n","// ── Gateway ────────────────────────────────────────────────────────────────\n//\n// The first-stage command. Run this *inside* a foreign environment — directly,\n// under `sudo`, over ssh, in a container — and it:\n//\n// 1. creates the channel to the payload (fifo paths it makes itself, in a\n// private temp dir, so they belong to the uid that will open them),\n// 2. starts the payload — the first argument, required — hands it everything else it was\n// given (the host version among it) and relays frames between stdin/stdout,\n// 3. carries whatever the payload prints to the client as output frames\n// (`$fd`), so the payload's own stdout can never be mistaken for protocol.\n//\n// Why a gateway at all: a fifo path created on the client side is useless when the\n// payload runs as another uid (it cannot open it) or on another host (the path is\n// not there). stdio is the one channel every way into an environment gives us, so\n// the wire is stdio and the fifo stays inside the environment.\n//\n// The gateway reads nothing out of what it carries and owns no flag: the payload's path and\n// every argument after it go through verbatim, in order. The payload is the one who refuses a\n// host version it is not, and a relay that judged would be a second place for that decision.\n//\n// Directories and processes are cleaned up on every exit path, which is also why\n// the client never sees a transport being closed twice.\n//\n// It imports nothing but node builtins and this package, so the payload behind it\n// can be anything the runtime there can start.\n\nimport { execFile, spawn, type ChildProcess } from \"node:child_process\";\nimport { mkdtemp, rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { basename, join } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { channelThrough } from \"./channel.js\";\nimport { json1Channel } from \"./protocols/json1.js\";\nimport { lowBand } from \"./process-ref.js\";\nimport { StreamStore } from \"./stream.js\";\nimport { errorFrame } from \"./stdio.js\";\nimport type { LineTransport } from \"./stdio.js\";\nimport { LineTransport as Lines } from \"./stdio.js\";\nimport { FifoUtf8NlineTransport } from \"./transports/fifo.js\";\n\nconst run = promisify(execFile);\n\n/** How much of a dying payload's own words travels in the reason a failed start carries. */\nconst REASON_TAIL = 4096;\n\n/** Exit code for \"this environment could not be set up\". */\nexport const GATEWAY_FAILED = 1;\n\nexport interface GatewayBoot {\n /**\n * The program to start for the payload: the first word of the command the client composed —\n * a runtime, or a program that runs itself. Required, and first, and the gateway has no\n * opinion of its own about which it is.\n */\n worker: string;\n /**\n * Everything after the payload, carried to it **as is** and in order: the consumer's own\n * arguments, and posipaki's own facts among them (the host version travels this way). The\n * gateway reads nothing by name and owns no flag, so nothing of the caller's is interpreted,\n * eaten, re-ordered or re-spelled — and the next fact added to that line needs no new\n * vocabulary here.\n */\n passthrough: string[];\n}\n\nfunction errorText(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * A label for the gateway's own temp directory: the program this environment was made for.\n * It is the gateway's business alone — the payload is not told which label it is.\n */\nfunction label(worker: string): string {\n const name = basename(worker).replace(/[^A-Za-z0-9.+@_-]/g, \"-\").slice(0, 60);\n return name === \"\" ? \"payload\" : name;\n}\n\n/**\n * The argv that boots this gateway — built by the client, read by\n * {@link gatewayBoot}, so the two halves cannot drift apart.\n *\n * The payload comes first and its arguments after it, so a positional argument of the\n * payload's own can never be mistaken for the payload.\n */\nexport function gatewayArgs(boot: GatewayBoot): string[] {\n return [boot.worker, ...boot.passthrough];\n}\n\n/** The boot a gateway was started with, or the reason it cannot start. */\nexport function gatewayBoot(argv: string[]): GatewayBoot {\n const [worker, ...passthrough] = argv;\n if (worker === undefined || worker.startsWith(\"--\")) {\n throw new Error(\"no <payload>: the gateway relays to a payload, named as its first argument\");\n }\n return { passthrough, worker };\n}\n\n/**\n * End a start that failed. The reason has already gone out on the wire, and\n * returning is not enough: the `open()` on a fifo no payload will ever write sits\n * in the threadpool forever, so the loop never drains and the gateway would linger\n * with a dead payload on its books.\n */\nfunction abandon(): never {\n process.exit(GATEWAY_FAILED);\n}\n\n/** Carry a failed start to the client, then let the caller exit non-zero. */\nasync function fail(wire: LineTransport, reason: string): Promise<void> {\n process.stderr.write(`gateway: ${reason}\\n`);\n try {\n await wire.send(errorFrame(reason));\n } catch {\n /* the client is gone too — the exit code still says what happened */\n }\n}\n\n/** The payload's own prints, as a stream: the pipe's chunks as they arrive. */\nasync function* chunksOf(stream: NodeJS.ReadableStream, prefix = \"\"): AsyncIterable<Uint8Array> {\n if (prefix.length > 0) yield new TextEncoder().encode(prefix);\n for await (const chunk of stream as AsyncIterable<Buffer | string>) {\n yield typeof chunk === \"string\" ? new TextEncoder().encode(chunk) : new Uint8Array(chunk);\n }\n}\n\n/** Everything a payload printed into its pipes, up to the point they end: what a start that dies\n * before its channel says about itself. A stream cannot carry it — there is no connection yet. */\n\n/**\n * Serve one environment over stdin/stdout. Returns the exit code; the caller\n * turns it into `process.exitCode`.\n */\nexport async function runGateway(argv: string[] = process.argv.slice(2)): Promise<number> {\n const wire = new Lines({ read: process.stdin, write: process.stdout });\n // One channel on the client wire, and the ids this gateway speaks from: the low band, which neither\n // the client nor the payload allocates in, so a stream of its own cannot collide with one of theirs.\n // The store answers only for the streams it offered; everything else belongs to the far side.\n const client = json1Channel(wire);\n const output = new StreamStore(client, \"even\", { ids: lowBand(\"even\"), attach: false });\n\n let booted: GatewayBoot;\n try {\n booted = gatewayBoot(argv);\n } catch (err) {\n // Nothing has been started yet, so there is nothing to tear down — but the\n // client still deserves the reason rather than a channel that closes on it,\n // and the loop can outlive us: an open stdin nobody will close keeps the\n // process alive, so this is an exit, not a return.\n await fail(wire, errorText(err));\n abandon();\n }\n const { passthrough, worker } = booted;\n\n const dir = await mkdtemp(join(tmpdir(), `posipaki-${label(worker)}-`));\n const fifoIn = join(dir, \"in\"); // the payload writes, we read\n const fifoOut = join(dir, \"out\"); // we write, the payload reads\n\n let child: ChildProcess | null = null;\n let fifo: FifoUtf8NlineTransport | null = null;\n\n /**\n * Everything this gateway owns, undone. All of it is idempotent, because the\n * exit path and the signal path can both arrive.\n */\n const teardown = async (): Promise<void> => {\n child?.kill();\n await fifo?.close().catch(() => {});\n await rm(dir, { recursive: true, force: true }).catch(() => {});\n };\n\n /**\n * A client that gives up stops us with a signal, and a gateway that died on the\n * spot would leave its payload behind in the environment — a process holding a\n * fifo nobody will ever write, which is a leak the environment cannot clean up\n * for us. So the signals do what the exit path does.\n */\n const onTerminate = () => {\n void teardown()\n .catch(() => {})\n .then(() => process.exit(GATEWAY_FAILED));\n };\n for (const signal of [\"SIGTERM\", \"SIGINT\", \"SIGHUP\"] as const) process.on(signal, onTerminate);\n\n try {\n await run(\"mkfifo\", [\"-m\", \"600\", fifoIn, fifoOut]);\n } catch (err) {\n await fail(wire, `cannot create the environment's fifos: ${errorText(err)}`);\n await teardown();\n abandon();\n }\n\n // Open the read side in the background, then start the payload that unblocks\n // it — the order the fifo handshake requires.\n const connection = FifoUtf8NlineTransport.beginConnect(fifoIn, fifoOut);\n const workerArgs = [worker, ...passthrough, `--fifo-in=${fifoIn}`, `--fifo-out=${fifoOut}`];\n // Whatever the client said starts the payload, run as it said: a runtime with a script of\n // ours, or a program of the caller's own. The gateway does not know which it is, and does\n // not choose a runtime on the far end's behalf.\n const workerProc = spawn(workerArgs[0]!, workerArgs.slice(1), {\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n child = workerProc;\n /** What the payload printed before the client spoke: a start that dies that early has no connection\n * to announce a stream on, and its words are the only way to say why it went. Kept per stream, so\n * the output that comes after is still attributed to the right one. */\n const early = { stdout: \"\", stderr: \"\" };\n const keep =\n (name: \"stdout\" | \"stderr\") =>\n (chunk: Buffer | string): void => {\n early[name] = (early[name] + String(chunk)).slice(-REASON_TAIL);\n };\n const keepOut = keep(\"stdout\");\n const keepErr = keep(\"stderr\");\n workerProc.stdout?.on(\"data\", keepOut);\n workerProc.stderr?.on(\"data\", keepErr);\n\n /** Announce the payload's own output as the two streams a program's prints belong on, with whatever\n * it said before the connection could carry it replayed as the first chunk. */\n const offerOutput = (): void => {\n const sides = [\n { stream: workerProc.stdout, name: \"stdout\", keep: keepOut },\n { stream: workerProc.stderr, name: \"stderr\", keep: keepErr },\n ] as const;\n for (const { stream, name, keep: drop } of sides) {\n if (!stream) continue;\n stream.off(\"data\", drop);\n stream.pause();\n output.offer(chunksOf(stream, early[name]), name);\n }\n };\n\n const exited = new Promise<number>((settle) => {\n // A payload killed by a signal (the client hung up, and we killed it) has no\n // code — for us that is a clean end, not a failure.\n workerProc.once(\"exit\", (code) => settle(code ?? 0));\n });\n\n try {\n fifo = await Promise.race([\n connection.transport,\n exited.then((code) => {\n throw new Error(`the payload exited with code ${code} before it opened its channel`);\n }),\n ]);\n } catch (err) {\n // A payload that dies before it opens its channel printed into pipes nobody is reading yet: its\n // last words are the only way to say why, and they are not a stream because no connection exists\n // to announce one on.\n const said = `${early.stdout}${early.stderr}`.trim();\n await fail(wire, `${errorText(err)}${said ? `: ${said}` : \"\"}`);\n await teardown();\n abandon();\n }\n\n // Relay frames, not lines: the gateway has streams of its own now — the payload's output — and one\n // the store claims is the gateway's, not the payload's business. Everything else crosses unchanged.\n // `fifo` is settled by the race above: a start that failed took the exit path and never got here.\n const payload = json1Channel(fifo as FifoUtf8NlineTransport);\n const fromClient = channelThrough(client, (frame) => output.handle(frame));\n const forward = (send: (frame: Record<string, unknown>) => unknown, frame: Record<string, unknown>): void => {\n void Promise.resolve(send(frame)).catch(() => {\n /* the far side is gone; its own exit path cleans up */\n });\n };\n let offered = false;\n fromClient.onMessage((frame) => {\n if (!offered) {\n offered = true;\n // The client has spoken, which means its store exists: an announcement made before that would\n // land in a connection with nobody listening for it.\n offerOutput();\n }\n forward((next) => payload.send(next), frame);\n });\n fromClient.onSegment?.((head, bytes) => {\n payload.sendSegment?.(head, bytes);\n });\n payload.onMessage((frame) => {\n forward((next) => client.send(next), frame);\n });\n payload.onSegment?.((head, bytes) => {\n client.sendSegment?.(head, bytes);\n });\n client.onClose(() => {\n child?.kill();\n });\n\n const code = await exited;\n await teardown();\n await wire.close();\n return code;\n}\n","// ── Running one command on the host ────────────────────────────────────────\n//\n// Everything a way in does, it does by running a command: staging is a command in an\n// environment, and the actor is another one whose stdin/stdout are the wire. Both go\n// through the two functions here, and both are handed in — so a test can stage and run\n// without a sandbox, a host or a container, and a consumer can run host commands its\n// own way.\n\nimport { spawn } from \"node:child_process\";\nimport type { ChildProcess, StdioOptions } from \"node:child_process\";\n\nexport interface HostResult {\n code: number | null;\n stdout: string;\n stderr: string;\n}\n\n/** Run a command, feed it its stdin, and wait for what it said. */\nexport type HostRun = (command: string[], stdin: string) => Promise<HostResult>;\n\n/** The real thing: spawn it, feed it, collect it. */\nexport const runHost: HostRun = (command, stdin) =>\n new Promise((settle, fail) => {\n const child = spawn(command[0]!, command.slice(1), { stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n const out: string[] = [];\n const err: string[] = [];\n child.stdout.setEncoding(\"utf-8\");\n child.stderr.setEncoding(\"utf-8\");\n child.stdout.on(\"data\", (chunk: string) => out.push(chunk));\n child.stderr.on(\"data\", (chunk: string) => err.push(chunk));\n child.once(\"error\", (error) => fail(error));\n // A host that hangs up while we are still writing has failed; the exit code and\n // stderr carry that, so the write error is not the story here.\n child.stdin.on(\"error\", () => {});\n child.once(\"close\", (code) => settle({ code, stdout: out.join(\"\"), stderr: err.join(\"\") }));\n child.stdin.end(stdin);\n });\n\n/** How the wire's process is started, with the stdio it needs. */\nexport type SpawnChild = (command: string[], stdio: StdioOptions) => ChildProcess;\n\n/** The real thing: node's own spawn, in our working directory. */\nexport const spawnChild: SpawnChild = (command, stdio) =>\n spawn(command[0]!, command.slice(1), { cwd: process.cwd(), stdio });\n","// ── The client side of the gateway ─────────────────────────────────────────\n//\n// A consumer has two things: a payload, and the build its bytes came from. A way in has\n// one: how to run a command somewhere else. Everything else is the same whatever the way\n// in is, and this module is that everything else:\n//\n// 1. the gateway script is posipaki's own entry (`posipaki/remote/gateway-cli.js`, a\n// published specifier, so it is resolved where the kit is staged from) — or the\n// consumer's, for a program that carries its own;\n// 2. both bundles go into one kit, whose directory name *is* the host version it serves —\n// the app, the build those bytes came from, the posipaki release that speaks to them —\n// so a second run of the same build finds the kit already there and copies nothing;\n// 3. whatever has to be *copied* there is staged through the way in's own channel — the\n// core's bootstrap script, one report line per step — which is also where the runtime\n// that will run it is found, so a way in never has to know what a `node` is. A\n// program the caller says is already installed is not staged at all, and then no\n// command of ours runs in the environment beyond the two that matter;\n// 4. the gateway runs there — `<runtime> <kit>/gateway.js` when it was staged, the caller's\n// own command when it was not — its stdin/stdout are the wire, and it makes the fifos\n// inside the environment and starts the payload against them. The payload is run this\n// way in *every* way in, which is why the payload is only ever a fifo worker. The\n// payload's own command and the host version are arguments the gateway carries without\n// knowing which is which: staged artifacts are ours, and the payload checks itself\n// against what it was asked for.\n//\n// What a way in supplies is `entry`: the argv that runs a command there. It is the whole\n// difference between bwrap, ssh, a container and this machine, and it is one function.\n\nimport type { ChildProcess, StdioOptions } from \"node:child_process\";\nimport { readFile } from \"node:fs/promises\";\nimport type { Readable, Writable } from \"node:stream\";\nimport { fileURLToPath } from \"node:url\";\nimport type { Channel } from \"./channel.js\";\nimport type { ClientSpawner } from \"./client.js\";\nimport { gatewayArgs } from \"./gateway.js\";\nimport { runHost, spawnChild } from \"./host.js\";\nimport type { HostResult, HostRun, SpawnChild } from \"./host.js\";\nimport {\n DEFAULT_KIT_PARENT,\n DEFAULT_RUNTIMES,\n GATEWAY_ARTIFACT,\n PAYLOAD_ARTIFACT,\n bootstrapScript,\n hostVersion,\n makeKit,\n parseBootstrapReport,\n} from \"./kit.js\";\nimport type { Kit, KitApp } from \"./kit.js\";\nimport { clientChannel } from \"./stdio.js\";\nimport { stderrSink, type OutputSink } from \"./output.js\";\nimport type { LineStreams } from \"./stdio.js\";\n\n/** posipaki's own gateway program. A consumer with one of its own stages that instead. */\nexport const GATEWAY_ENTRY = \"posipaki/remote/gateway-cli.js\";\n\n/** How much of what a failed staging command said is quoted back as part of the reason. */\nconst SAID_TAIL = 400;\n\n/** How much of the far end's stderr is kept, to be the reason a start failed. */\nconst REASON_TAIL = 400;\n\n/** Staging failed, or the far end never spoke: the caller's spec, or the environment's answer. */\nexport class RemoteSpecError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"RemoteSpecError\";\n }\n}\n\n/** What a way in is handed, and how it runs what it is handed. */\nexport interface RemoteWayIn {\n /** What the far end's output and errors are tagged with. */\n name: string;\n /** The argv that runs `command` there: bwrap's policy, ssh's host, podman's container. */\n entry: (command: string[]) => string[];\n /** How a plain command runs there and is waited for. Injectable, so a test needs no way in. */\n run?: HostRun;\n /** How the wire's process is started there. Injectable likewise. */\n spawn?: SpawnChild;\n}\n\n/**\n * A program the way in starts there: a bundle of ours to copy into the environment, or a\n * command that already runs there — an absolute path, a name on `$PATH`, a runtime and a\n * script of its own. Which of the two it is, is the caller's decision, and it is the only\n * thing posipaki needs to know about where the far end comes from.\n */\nexport type HostProgram = { stage: string } | { run: string[] };\n\n/** Everything a client needs: where the two programs are, whose payload it is, and the way in. */\nexport interface RemoteSpec<Args> extends RemoteWayIn {\n /** The payload: ours to stage there, or the one already installed there. */\n payload: HostProgram;\n /**\n * Whose payload this is: the app name and the build those bytes came from. Required\n * whenever anything is staged — a kit's directory *is* the host version — and stated to the\n * payload whenever it is given at all, which is the one fact a caller can hand an installed\n * payload about the build it is expected to be. Omitted, nothing is stated and nothing is\n * checked, which is only right for a payload whose bytes carry no version of their own.\n */\n hostVersion?: KitApp;\n /** The gateway: posipaki's own bundle, staged, unless the caller says otherwise. */\n gateway?: HostProgram;\n /** Runtime candidates on the far side, best first. Defaults to `DEFAULT_RUNTIMES`. */\n runtime?: string[];\n /** Where the kit lands there, relative to its `$HOME`. Defaults to `DEFAULT_KIT_PARENT`. */\n parent?: string;\n /**\n * The payload's own arguments, built from the args the actor was spawned with. The gateway\n * carries them to the payload untouched — it does not know what they mean, and does not need\n * to: what a consumer tells its own far end is the consumer's business.\n */\n payloadArgs?: (args: Args) => string[];\n /** Where the far end's own output goes. Defaults to our stderr, tagged with `name`. */\n onOutput?: OutputSink;\n /** How long to wait for the far end's first protocol frame. */\n handshakeTimeoutMs?: number;\n /** Called when the far end's process is gone, whichever way it went. */\n onGone?: () => void;\n}\n\n/**\n * The part of a spec the machinery here reads, with the actor's own arguments left out:\n * staging, the channel and the argv are the same whatever an actor is told.\n */\ntype Spec = Omit<RemoteSpec<unknown>, \"payloadArgs\">;\n\n/** The argv that starts each of the two programs there. */\ninterface Programs {\n gateway: string[];\n payload: string[];\n}\n\nfunction isStage(program: HostProgram): program is { stage: string } {\n return \"stage\" in program;\n}\n\nfunction errorText(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * posipaki's own gateway program, resolved where the consumer installed it — the default for\n * a caller that has none of its own to deploy.\n */\nfunction gatewayEntry(): string {\n try {\n return fileURLToPath(import.meta.resolve(GATEWAY_ENTRY));\n } catch (err) {\n throw new RemoteSpecError(\n `cannot find posipaki's gateway program (${GATEWAY_ENTRY}): ${errorText(err)}. ` +\n \"Stage one with `gateway:` — a consumer whose program carries its own.\",\n );\n }\n}\n\n/** The kit's files: what has to be copied there, under the names the script writes them as. */\nasync function kitFiles(\n gateway: HostProgram,\n payload: HostProgram,\n): Promise<{ name: string; content: Buffer }[]> {\n const files: { name: string; content: Buffer }[] = [];\n if (isStage(payload)) files.push({ name: PAYLOAD_ARTIFACT, content: await readFile(payload.stage) });\n if (isStage(gateway)) files.push({ name: GATEWAY_ARTIFACT, content: await readFile(gateway.stage) });\n return files;\n}\n\n/** A command with nothing to run is a spec that says nothing; refuse it before spawning it. */\nfunction programCommand(program: { run: string[] }, what: string, name: string): string[] {\n if (program.run.length === 0 || program.run[0] === undefined || program.run[0] === \"\") {\n throw new RemoteSpecError(`${name}: ${what} is a command with nothing to run`);\n }\n return program.run;\n}\n\n/**\n * The two commands, staging whatever has to be copied there first.\n *\n * Nothing staged means no command of ours runs in the environment at all: the caller's own\n * argv is handed through as it stands, which is the case for a program that is already\n * installed. Something staged needs a host version to name the kit with — and a kit's\n * directory *is* the host version, so there is nothing to guess at.\n */\nasync function programsFor(spec: Spec, run: HostRun): Promise<Programs> {\n const gateway: HostProgram = spec.gateway ?? { stage: gatewayEntry() };\n const payload = spec.payload;\n if (!isStage(gateway) && !isStage(payload)) {\n return {\n gateway: programCommand(gateway, \"the gateway\", spec.name),\n payload: programCommand(payload, \"the payload\", spec.name),\n };\n }\n if (spec.hostVersion === undefined) {\n throw new RemoteSpecError(\n `nothing names the kit to stage into ${spec.name}: state hostVersion — a kit's directory ` +\n \"is the host version, and a payload refuses to serve one its own bytes do not carry\",\n );\n }\n const kit = makeKit(await kitFiles(gateway, payload), {\n app: spec.hostVersion,\n runtimes: spec.runtime ?? DEFAULT_RUNTIMES,\n parent: spec.parent ?? DEFAULT_KIT_PARENT,\n });\n const staged = await stageKit(spec, kit, run);\n const at = (artifact: string) => [staged.runtime, `${staged.kitDir}/${artifact}`];\n return {\n gateway: isStage(gateway) ? at(GATEWAY_ARTIFACT) : gateway.run,\n payload: isStage(payload) ? at(PAYLOAD_ARTIFACT) : payload.run,\n };\n}\n\n/** The tail of what a command said, for a failure that has no better story. */\nfunction said(result: HostResult): string {\n const text = `${result.stderr}${result.stdout}`.trim();\n const tail = text.length > SAID_TAIL ? text.slice(-SAID_TAIL) : text;\n return tail === \"\" ? `exit code ${result.code}` : tail;\n}\n\n/**\n * Put the kit where the environment can see it and say what will run it. Idempotent:\n * the script probes, writes only what is missing and reports — so a spawn of a build\n * that is already staged costs one process and no writes.\n */\nasync function stageKit(spec: Spec, kit: Kit, run: HostRun): Promise<{ kitDir: string; runtime: string }> {\n const result = await run(spec.entry([\"sh\", \"-s\"]), bootstrapScript(kit));\n const report = parseBootstrapReport(result.stdout);\n if (report.kind === \"error\") {\n // A report that never arrived is not a reason; what the environment said is.\n const incomplete =\n report.reason.startsWith(\"incomplete\") || report.reason.startsWith(\"no report\");\n throw new RemoteSpecError(\n `staging into ${spec.name} failed: ${report.reason}${incomplete ? ` (${said(result)})` : \"\"}`,\n );\n }\n return { kitDir: report.kitDir, runtime: report.runtime };\n}\n\n/**\n * Start the run command and hand its own stdin/stdout to the wire. An environment that\n * dies before it speaks — bwrap not installed, a host that refuses, a payload that\n * cannot be run — fails the spawn with what it said, rather than a channel that never\n * answers.\n */\nasync function openChannel(\n spec: Spec,\n command: string[],\n spawn: SpawnChild,\n): Promise<Channel> {\n\n // The run's own stdin and stdout *are* the wire, so both have to be pipes.\n const stdio: StdioOptions = [\"pipe\", \"pipe\", \"pipe\"];\n const child: ChildProcess = spawn(command, stdio);\n const streams: LineStreams = { read: child.stdout as Readable, write: child.stdin as Writable };\n\n // The run's stdin and stdout are the wire; its stderr is not. That is where the way\n // in itself speaks — \"bwrap: Can't find source path\", \"Permission denied\" — so it goes\n // to the sink, and the tail of it becomes the reason a start that died is reported with.\n child.stderr?.setEncoding(\"utf-8\");\n child.stderr?.on(\"data\", (chunk: string) => {\n tail = (tail + chunk).slice(-REASON_TAIL);\n sink(\"stderr\", chunk);\n });\n // The run's own stdin and stdout *are* the wire; its stderr is not. That is where the way in\n // itself speaks — \"bwrap: Can't find source path\", \"Permission denied\" — so it goes to the sink as\n // `stderr`, and the tail of it becomes the reason a start that died is reported with. What the\n // payload behind the gateway prints is a different thing: it arrives as a stream the payload named.\n const sink = spec.onOutput ?? stderrSink(spec.name);\n let tail = \"\";\n\n const exited = new Promise<never>((_, reject) => {\n // `close`, not `exit`: the process being gone is not the same as everything it said\n // having arrived, and the tail of its stderr is the whole reason here.\n child.once(\"close\", (code, signal) => {\n const how = signal === null ? `code ${code}` : `signal ${signal}`;\n const why = tail.trim();\n reject(new Error(`exited with ${how}${why ? `: ${why}` : \"\"}`));\n });\n child.once(\"error\", (err) => reject(new Error(`cannot start: ${err.message}`)));\n });\n // A spawn that resolves leaves this rejection unobserved — fine, as long as it is not\n // reported as an unhandled rejection.\n exited.catch(() => {});\n\n let channel: Channel;\n try {\n channel = await Promise.race([\n clientChannel(streams, {\n ...(spec.handshakeTimeoutMs === undefined ? {} : { timeoutMs: spec.handshakeTimeoutMs }),\n }),\n exited,\n ]);\n } catch (err) {\n child.kill();\n throw new RemoteSpecError(`${spec.name} is not available: ${errorText(err)}`);\n }\n\n // The far end's exit is the channel's close: whichever side goes first, the other stops\n // waiting — and the caller is told, because its slot must stop pointing at a process\n // that is gone.\n child.once(\"exit\", () => {\n spec.onGone?.();\n void channel.close().catch(() => {});\n });\n return channel;\n}\n\n/**\n * A spawner for an actor that lives behind a gateway in some environment: put the payload and\n * posipaki's gateway wherever they belong, run the gateway, speak the client side.\n */\nexport function gatewayClient<Args>(spec: RemoteSpec<Args>): ClientSpawner<Args> {\n const run: HostRun = spec.run ?? runHost;\n const spawn: SpawnChild = spec.spawn ?? spawnChild;\n return async (args: Args): Promise<Channel> => {\n // The spec is read before a command runs on its behalf: a payload that is not there\n // should fail here, not as an environment that cannot be reached.\n const programs = await programsFor(spec, run);\n const command = [\n ...programs.gateway,\n ...gatewayArgs({\n // What the payload is started as, then posipaki's own facts among the caller's\n // arguments: the host version, and whatever the consumer adds for its own far end.\n // Which of these is whose is not the gateway's business — it starts what it is handed\n // and carries the rest.\n passthrough: [\n ...programs.payload.slice(1),\n ...(spec.hostVersion === undefined\n ? []\n : [`--host-version=${hostVersion(spec.hostVersion)}`]),\n ...(spec.payloadArgs?.(args) ?? []),\n ],\n worker: programs.payload[0]!,\n }),\n ];\n return openChannel(spec, spec.entry(command), spawn);\n };\n}\n\n/**\n * The way in where the environment is this machine: nothing wraps the command, and the\n * kit is staged under `$HOME` like any other. Everything below the entry is the same as\n * for a sandbox, a host or a container — which is the point of it being here.\n */\nexport function hostRemote<Args>(\n spec: Omit<RemoteSpec<Args>, \"name\" | \"entry\"> & { name?: string },\n): ClientSpawner<Args> {\n return gatewayClient({ name: \"this host\", entry: (command) => command, ...spec });\n}\n","// ── unix sockets: a listener, and a client ─────────────────────────────────\n//\n// A local socket as a medium for the reactor: the listener binds a path, takes one connection at a time\n// and hands it on; the client side is one call. The medium brings no framing of its own — a socket is a\n// duplex stream, and LineTransport already carries newline-delimited frames over one.\n\nimport { chmod, stat, unlink } from \"node:fs/promises\";\nimport { connect, createServer, type Server, type Socket } from \"node:net\";\n\nimport type { Connection, Listener } from \"./reactor.js\";\nimport { LineTransport } from \"./stdio.js\";\n\n/** The socket file's mode when the caller does not say: the path is the access control. */\nconst DEFAULT_MODE = 0o600;\n\n/** How long a connect waits before it gives up. */\nconst DEFAULT_TIMEOUT_MS = 5000;\n\n/** What a listener knows about an accepted connection before an actor exists for it. */\nexport interface UnixSocketPeer {\n /** The path this side is bound to. */\n readonly path: string;\n /**\n * The peer's credentials, where the runtime gives them (Linux `SO_PEERCRED`). Node exposes none on a\n * unix socket today, so this is undefined under node; the field is here for a runtime that can.\n */\n readonly peer?: { readonly uid: number; readonly gid: number; readonly pid?: number };\n}\n\nexport interface UnixSocketListenerOptions<Meta = unknown> {\n /** The socket file. Made when the listener starts, and removed when it stops. */\n path: string;\n /** The mode of the socket file, set before the first connection is taken. Default 0o600. */\n mode?: number;\n /**\n * Whether a path that exists and refuses a connection may be replaced: a socket nobody listens on is a\n * crash's leftover. A path that is not a socket at all is refused rather than removed.\n */\n replaceStale?: boolean;\n /** The listen backlog, passed through to the runtime. */\n backlog?: number;\n /**\n * Admission and identity. What it returns is the connection's meta; throwing refuses the connection\n * before any actor exists.\n */\n identify?(peer: UnixSocketPeer): Meta | Promise<Meta>;\n}\n\nexport interface UnixSocketClientOptions {\n /** How long to wait for the connection, in milliseconds. Default 5000. */\n timeoutMs?: number;\n}\n\n/** What is at a path: nothing, a live listener, a socket nobody listens on, or something else. */\nasync function atPath(path: string): Promise<\"free\" | \"listening\" | \"stale\" | \"other\"> {\n try {\n const info = await stat(path);\n if (!info.isSocket()) return \"other\";\n } catch {\n return \"free\";\n }\n const answered = await new Promise<boolean>((resolve) => {\n const probe = connect(path);\n probe.once(\"connect\", () => {\n probe.destroy();\n resolve(true);\n });\n probe.once(\"error\", () => {\n probe.destroy();\n resolve(false);\n });\n });\n return answered ? \"listening\" : \"stale\";\n}\n\n/**\n * Bind a path and answer connections from it, as the reactor's Listener: the socket file is made before\n * the first accept, its mode is set before the first connection is taken, and `close()` removes it if it\n * is still the inode this listener bound.\n */\nexport async function unixSocketListener<Meta = unknown>(\n options: UnixSocketListenerOptions<Meta>,\n): Promise<Listener<Meta>> {\n const { path, mode = DEFAULT_MODE, replaceStale = true, backlog } = options;\n\n const there = await atPath(path);\n if (there === \"listening\") throw new Error(`unixSocketListener: something is listening at ${path}`);\n if (there === \"other\") throw new Error(`unixSocketListener: ${path} is not a socket`);\n if (there === \"stale\") {\n if (!replaceStale) throw new Error(`unixSocketListener: ${path} is a socket nobody listens on`);\n await unlink(path);\n }\n\n // Every connection this listener has taken or is holding: the close ends them, so a client learns the\n // listener is gone from its read end closing, and `server.close()` is not held open by a live socket.\n const connections = new Set<Socket>();\n const accepted: Socket[] = [];\n let waiting: { resolve: (socket: Socket) => void; reject: (error: Error) => void } | null = null;\n let closed = false;\n\n const server: Server = createServer();\n server.on(\"connection\", (socket) => {\n connections.add(socket);\n socket.on(\"close\", () => connections.delete(socket));\n const taken = waiting;\n waiting = null;\n if (taken) taken.resolve(socket);\n else accepted.push(socket);\n });\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen({ path, backlog }, () => {\n server.removeListener(\"error\", reject);\n resolve();\n });\n });\n // The runtime makes the socket file with the process's umask; setting the mode here narrows the window\n // in which it is wider than asked for, since nothing has been accepted yet.\n await chmod(path, mode);\n const bound = await stat(path);\n\n const release = (error: Error): void => {\n const pending = waiting;\n waiting = null;\n pending?.reject(error);\n };\n\n return {\n accept(signal?: AbortSignal): Promise<Connection<Meta>> {\n if (closed) return Promise.reject(new Error(`unixSocketListener: ${path} is closed`));\n const taken = accepted.shift();\n const socket =\n taken ??\n new Promise<Socket>((resolve, reject) => {\n waiting = { resolve, reject };\n signal?.addEventListener(\n \"abort\",\n () => {\n if (waiting?.resolve === resolve) release(new Error(`unixSocketListener: ${path} was stopped`));\n reject(new Error(`unixSocketListener: ${path} was stopped`));\n },\n { once: true },\n );\n });\n return Promise.resolve(socket).then(async (connection) => {\n const peer: UnixSocketPeer = { path };\n const meta = options.identify ? await options.identify(peer) : (undefined as Meta);\n return { meta, transport: new LineTransport({ read: connection, write: connection }) };\n });\n },\n async close(): Promise<void> {\n closed = true;\n release(new Error(`unixSocketListener: ${path} is closed`));\n // Deleting from the set while iterating it is defined, and the deletion is the socket's own close\n // handler on a later turn, so the loop sees each of them once.\n for (const socket of connections) socket.destroy();\n connections.clear();\n accepted.length = 0;\n await new Promise<void>((resolve) => server.close(() => resolve()));\n try {\n const now = await stat(path);\n if (now.dev === bound.dev && now.ino === bound.ino) await unlink(path);\n } catch {\n // Already gone: nothing this listener made is left to remove.\n }\n },\n };\n}\n\n/** Connect to a listener: one call, and no open order, since a socket is connected or it is not. */\nexport async function connectUnixSocket(\n path: string,\n options: UnixSocketClientOptions = {},\n): Promise<LineTransport> {\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const socket = await new Promise<Socket>((resolve, reject) => {\n const attempt = connect(path);\n const timer = setTimeout(() => {\n attempt.destroy();\n reject(new Error(`connectUnixSocket: nothing answered at ${path} within ${timeoutMs}ms`));\n }, timeoutMs);\n attempt.once(\"connect\", () => {\n clearTimeout(timer);\n resolve(attempt);\n });\n attempt.once(\"error\", (error: Error) => {\n clearTimeout(timer);\n reject(new Error(`connectUnixSocket: ${path}: ${error.message}`));\n });\n });\n return new LineTransport({ read: socket, write: socket });\n}\n","// ── unix socket client spawner ─────────────────────────────────────────────\n//\n// Environment-specific: connects to a listening socket, wraps it in LineTransport, and returns a frame\n// Channel with the `$proto` handshake already validated.\n\nimport { isProto } from \"../channel.js\";\nimport type { ClientSpawner } from \"../client.js\";\nimport { json1Channel, VERSION } from \"../protocols/json1.js\";\nimport { connectUnixSocket, type UnixSocketClientOptions } from \"../socket.js\";\n\n\n/** What a socket client needs: how to reach it. */\nexport interface SocketClientSpawnerOptions extends UnixSocketClientOptions {\n}\n\nexport function socketClientSpawner<Args = unknown>(\n path: string | ((args: Args) => string),\n options: SocketClientSpawnerOptions = {},\n): ClientSpawner<Args> {\n return async (args) => {\n const target = typeof path === \"function\" ? path(args) : path;\n const transport = await connectUnixSocket(target, options);\n const channel = json1Channel(transport);\n\n // The waiter is set with no await between it and the connection: the transport starts reading as\n // soon as it is made, so a server that says `$proto` first thing would have it dropped otherwise.\n const first = await new Promise<Record<string, unknown>>((resolve) => {\n const off = channel.onMessage((frame) => {\n off();\n resolve(frame);\n });\n });\n if (!isProto(first) || first.$proto !== VERSION) {\n throw new Error(`unsupported protocol: ${JSON.stringify(first)}`);\n }\n return channel;\n };\n}\n","// ── websockets: a listener over an HTTP server's upgrades ────────────────────\n//\n// A websocket as a medium for the reactor. The consumer's HTTP server owns the socket, and the\n// handshake is the WebSocket implementation's own step — with `ws`, or whatever the runtime ships —\n// so this listener takes one thing from the consumer: the call that completes it. Everything else\n// here is the accept loop: which upgrade becomes a connection, who may present one, and what a\n// refused one is told. One upgrade is one connection, so there is nothing to keep between them.\n\nimport type { IncomingMessage } from \"node:http\";\nimport type { Duplex } from \"node:stream\";\n\nimport type { Connection, Listener } from \"./reactor.js\";\nimport { WebSocketTransport, type WebSocketLike } from \"./transports/websocket.js\";\n\n/** What the far side is told when admission refuses it: not this door, and no handshake happened. */\nconst REFUSED = \"HTTP/1.1 401 Unauthorized\\r\\nconnection: close\\r\\n\\r\\n\";\n\n/** A server that reports an upgrade before answering it: node's `http`/`https` server. */\nexport interface UpgradeSource {\n on(event: \"upgrade\", listener: (request: IncomingMessage, socket: Duplex, head: Buffer) => void): unknown;\n off(event: \"upgrade\", listener: (request: IncomingMessage, socket: Duplex, head: Buffer) => void): unknown;\n}\n\n/** What arrived: the request that asked to upgrade, and the URL it asked for. */\nexport interface WebSocketUpgrade {\n readonly request: IncomingMessage;\n readonly url: URL;\n}\n\nexport interface WebSocketListenerOptions<Meta = unknown> {\n /** The server whose upgrades become connections. */\n server: UpgradeSource;\n /**\n * Which path upgrades. An upgrade on any other path is not this listener's and is left as it\n * arrived, so one server can route its paths between listeners. Every path upgrades when it is\n * not given.\n */\n path?: string;\n /**\n * Admission and identity. What it returns is the connection's meta; throwing refuses the upgrade\n * before any actor exists — a refused connection costs no actor and no channel — and the far side\n * is told by `refuse`.\n */\n identify?(upgrade: WebSocketUpgrade): Meta | Promise<Meta>;\n /**\n * Complete the handshake and answer with the socket: the WebSocket implementation's own step,\n * which is the one thing the library does not carry. With `ws`:\n *\n * ```ts\n * upgrade: (request, socket, head) =>\n * new Promise((resolve) => wss.handleUpgrade(request, socket, head, (ws) => resolve(socketOf(ws))))\n * ```\n */\n upgrade(request: IncomingMessage, socket: Duplex, head: Buffer): Promise<WebSocketLike>;\n /** What a refused upgrade is told. Default: `401`, and the socket is closed. */\n refuse?(socket: Duplex, error: unknown, upgrade: WebSocketUpgrade): void;\n}\n\n/** An upgrade admission accepted, waiting for a connection to be taken from the queue. */\ninterface Admitted<Meta> {\n request: IncomingMessage;\n socket: Duplex;\n head: Buffer;\n meta: Meta;\n}\n\n/**\n * Take connections from an HTTP server's upgrades, as the reactor's `Listener`.\n *\n * Admission happens when the upgrade arrives, so a refusal is the far side's before any handshake,\n * and the handshake happens when a connection is accepted: what the reactor is handed is an open\n * websocket and the meta it was admitted with.\n */\nexport function webSocketListener<Meta = unknown>(options: WebSocketListenerOptions<Meta>): Listener<Meta> {\n const { server, path } = options;\n /** Every socket this listener is responsible for: what it has taken, and what it is holding. */\n const held = new Set<Duplex>();\n const accepted: Admitted<Meta>[] = [];\n let waiting: { resolve: (admitted: Admitted<Meta>) => void; reject: (error: Error) => void } | null = null;\n let closed = false;\n // One admission at a time, in the order the upgrades arrived: an `identify` that waits would\n // otherwise let a later connection overtake an earlier one.\n let admitting: Promise<void> = Promise.resolve();\n\n const handshake = async (admitted: Admitted<Meta>): Promise<Connection<Meta>> => {\n const socket = await options.upgrade(admitted.request, admitted.socket, admitted.head);\n return { meta: admitted.meta, transport: new WebSocketTransport(socket) };\n };\n\n const take = (admitted: Admitted<Meta>): void => {\n held.add(admitted.socket);\n admitted.socket.once(\"close\", () => held.delete(admitted.socket));\n const pending = waiting;\n waiting = null;\n if (pending) pending.resolve(admitted);\n else accepted.push(admitted);\n };\n\n const admit = async (request: IncomingMessage, socket: Duplex, head: Buffer): Promise<void> => {\n let url: URL;\n try {\n url = new URL(request.url ?? \"/\", `http://${request.headers.host ?? \"localhost\"}`);\n } catch {\n // A request that cannot even be read as one is not one this listener can serve.\n socket.destroy();\n return;\n }\n if (path !== undefined && url.pathname !== path) return;\n const upgrade: WebSocketUpgrade = { request, url };\n let meta: Meta;\n try {\n meta = options.identify ? await options.identify(upgrade) : (undefined as Meta);\n } catch (error) {\n try {\n if (options.refuse) options.refuse(socket, error, upgrade);\n else socket.end(REFUSED);\n } catch {\n // A refusal hook that throws is still a refusal: the socket goes rather than the far side\n // waiting for an answer nobody is going to write.\n socket.destroy();\n }\n return;\n }\n // A far side that gave up while admission was being decided is nobody's to serve.\n if (closed || socket.destroyed) return;\n take({ request, socket, head, meta });\n };\n\n const arrived = (request: IncomingMessage, socket: Duplex, head: Buffer): void => {\n admitting = admitting.then(() => admit(request, socket, head));\n };\n\n server.on(\"upgrade\", arrived);\n\n const release = (error: Error): void => {\n const pending = waiting;\n waiting = null;\n pending?.reject(error);\n };\n\n return {\n accept(signal?: AbortSignal): Promise<Connection<Meta>> {\n if (closed) return Promise.reject(new Error(\"webSocketListener: closed\"));\n const taken = accepted.shift();\n if (taken) return handshake(taken);\n return new Promise<Connection<Meta>>((resolve, reject) => {\n const mine = {\n resolve: (admitted: Admitted<Meta>) => {\n handshake(admitted).then(resolve, reject);\n },\n reject,\n };\n waiting = mine;\n signal?.addEventListener(\n \"abort\",\n () => {\n if (waiting === mine) waiting = null;\n reject(new Error(\"webSocketListener: stopped\"));\n },\n { once: true },\n );\n });\n },\n async close(): Promise<void> {\n closed = true;\n server.off(\"upgrade\", arrived);\n release(new Error(\"webSocketListener: closed\"));\n // A connection this listener was given ends with it: the client learns that from its own socket\n // closing rather than from a handshake nobody is left to answer.\n for (const socket of held) socket.destroy();\n held.clear();\n accepted.length = 0;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAUA,IAAa,yBAAb,MAAa,uBAAkD;CAa7D,YAAoB,MAAqD;EAPR,KAAA,eAAA;EACN,KAAA,aAAA;EACjB,KAAA,aAAA;EACzB,KAAA,SAAA;EAC8B,KAAA,iBAAA;EACd,KAAA,WAAA;EAG/B,KAAK,SAAS,KAAK,UAAU;EAC7B,KAAK,UAAU,KAAK,WAAW;EAE/B,IAAI,KAAK,QAAQ;GACf,KAAK,KAAK,KAAK,OAAO,iBAAiB;GACvC,KAAK,SAAS,UACZ,KAAK,KACJ,SAAU,KAAK,SAAS,KAAA,IAAY,KAAK,eAAe,IAAI,IAC5D,UAAU;IACT,IAAI,CAAC,KAAK,QAAQ,KAAK,aAAa,KAAK;GAC3C,SACM;IACJ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