@johnhenry/browsermesh-pod 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,306 @@
1
+ /**
2
+ * node-runtimes.mjs -- the two `PodRuntime`s (see `pod-runtime.mjs`) that
3
+ * Node can provide without a native dependency, and what each does and does
4
+ * NOT protect. Import from `@johnhenry/browsermesh-pod/node-runtimes`; the
5
+ * package root stays free of `node:` imports so it still loads in a Worker.
6
+ *
7
+ * ## `createWorkerThreadsRuntime()` -- boundary `none`
8
+ *
9
+ * The pod is a `worker_threads` Worker in the host's own process. What it
10
+ * gives: a heap limit (`resourceLimits`), an environment holding only what
11
+ * the podspec named (the `env` option, not a copy of the host's), captured
12
+ * stdout, and termination. What it does NOT give, and no flag changes:
13
+ * the module can read and write any file the host process can, open any
14
+ * network connection, spawn processes, and share the host's address space
15
+ * with the host's secrets. `worker_threads` and `node:vm` are NOT security
16
+ * boundaries. Use it to pack trusted modules into one process. It is
17
+ * advertised as the `node` lane, never `isolate`, and the placement planner
18
+ * only gives it work from requesters the operator trusts.
19
+ *
20
+ * ## `createPermissionProcessRuntime()` -- boundary `process`
21
+ *
22
+ * The pod is a child Node process started with the permission model on:
23
+ * `--permission` with read access to only the entry file, the hosted module
24
+ * and the paths the catalog entry names; no write access, no network, no
25
+ * child processes, no worker threads, no native addons, no WASI, no
26
+ * inspector; an environment holding only what the podspec named; a heap
27
+ * limit (`--max-old-space-size`). Node's own documentation says the
28
+ * permission model is a safety net against mistakes, not a sandbox against
29
+ * hostile code: the pod shares the host's user and kernel, and anything the
30
+ * model does not cover (for example already-open file descriptors, the
31
+ * process's own `/proc`, kernel and V8 vulnerabilities) is open to it. It
32
+ * is `process`, not `language` or `hardware`, so untrusted requesters are
33
+ * not placed on it.
34
+ *
35
+ * Neither is the isolate lane. See `pod-runtime.mjs` for how an
36
+ * `isolated-vm` or `workerd` runtime plugs into the same interface.
37
+ */
38
+
39
+ import { Worker } from 'node:worker_threads'
40
+ import { fork } from 'node:child_process'
41
+ import { realpathSync } from 'node:fs'
42
+ import { fileURLToPath, pathToFileURL } from 'node:url'
43
+ import { isAbsolute } from 'node:path'
44
+ import { POD_LANE } from './host-protocol.mjs'
45
+ import { RUNTIME_BOUNDARY } from './pod-runtime.mjs'
46
+
47
+ const ENTRY_PATH = fileURLToPath(new URL('./node-runtime-entry.mjs', import.meta.url))
48
+
49
+ /** How long `start()` waits for the module to load. */
50
+ const DEFAULT_START_TIMEOUT_MS = 10_000
51
+
52
+ /** How much of a child's stderr is kept to classify its exit. */
53
+ const STDERR_TAIL_BYTES = 4096
54
+
55
+ /**
56
+ * @param {string} modulePath
57
+ * @returns {string}
58
+ */
59
+ function requireAbsolute(modulePath) {
60
+ if (typeof modulePath !== 'string' || !isAbsolute(modulePath)) {
61
+ throw new Error('a hosted module path must be absolute')
62
+ }
63
+ return modulePath
64
+ }
65
+
66
+ /**
67
+ * Split a stream into lines for `onLog`.
68
+ * @param {import('node:stream').Readable|null} stream
69
+ * @param {(line: string) => void} onLine
70
+ */
71
+ function forEachLine(stream, onLine) {
72
+ if (!stream) return
73
+ let buffer = ''
74
+ stream.setEncoding('utf8')
75
+ stream.on('data', (chunk) => {
76
+ buffer += chunk
77
+ let at = buffer.indexOf('\n')
78
+ while (at !== -1) {
79
+ onLine(buffer.slice(0, at))
80
+ buffer = buffer.slice(at + 1)
81
+ at = buffer.indexOf('\n')
82
+ }
83
+ })
84
+ stream.on('end', () => { if (buffer) onLine(buffer) })
85
+ }
86
+
87
+ /**
88
+ * The request/reply plumbing both runtimes share: a handle over a channel
89
+ * that speaks `node-runtime-entry.mjs`'s protocol.
90
+ *
91
+ * @param {object} channel
92
+ * @param {(message: object) => void} channel.send
93
+ * @returns {{handle: object, onMessage: (m: object) => void, failAll: (err: Error) => void}}
94
+ */
95
+ function makeRequester(channel) {
96
+ let nextId = 1
97
+ /** @type {Map<number, {resolve: Function, reject: Function, timer: *}>} */
98
+ const pending = new Map()
99
+ return {
100
+ handle: {
101
+ request(payload, { timeoutMs = 5000 } = {}) {
102
+ return new Promise((resolve, reject) => {
103
+ const id = nextId
104
+ nextId += 1
105
+ const timer = setTimeout(() => {
106
+ pending.delete(id)
107
+ const err = new Error(`no reply within ${timeoutMs} ms`)
108
+ err.code = 'ETIMEDOUT'
109
+ reject(err)
110
+ }, timeoutMs)
111
+ pending.set(id, { resolve, reject, timer })
112
+ channel.send({ type: 'request', id, payload })
113
+ })
114
+ },
115
+ },
116
+ onMessage(message) {
117
+ if (message?.type !== 'reply') return
118
+ const entry = pending.get(message.id)
119
+ if (!entry) return
120
+ pending.delete(message.id)
121
+ clearTimeout(entry.timer)
122
+ if (message.ok) entry.resolve(message.reply)
123
+ else entry.reject(new Error(message.message))
124
+ },
125
+ failAll(err) {
126
+ for (const [id, entry] of pending) {
127
+ clearTimeout(entry.timer)
128
+ entry.reject(err)
129
+ pending.delete(id)
130
+ }
131
+ },
132
+ }
133
+ }
134
+
135
+ /**
136
+ * @param {object} [opts]
137
+ * @param {number} [opts.startTimeoutMs]
138
+ * @returns {import('./pod-runtime.mjs').PodRuntime}
139
+ */
140
+ export function createWorkerThreadsRuntime({ startTimeoutMs = DEFAULT_START_TIMEOUT_MS } = {}) {
141
+ return {
142
+ kind: 'worker_threads',
143
+ lane: POD_LANE.NODE,
144
+ boundary: RUNTIME_BOUNDARY.NONE,
145
+
146
+ start(opts) {
147
+ requireAbsolute(opts.modulePath)
148
+ return new Promise((resolve, reject) => {
149
+ const worker = new Worker(ENTRY_PATH, {
150
+ workerData: {
151
+ name: opts.name,
152
+ moduleUrl: pathToFileURL(opts.modulePath).href,
153
+ env: opts.env,
154
+ input: opts.input,
155
+ },
156
+ // An environment of exactly what the podspec named, not a copy of the host's.
157
+ env: { ...opts.env },
158
+ execArgv: [],
159
+ argv: [],
160
+ stdout: true,
161
+ stderr: true,
162
+ resourceLimits: { maxOldGenerationSizeMb: opts.limits?.memMib },
163
+ })
164
+ const requester = makeRequester({ send: (message) => worker.postMessage(message) })
165
+ forEachLine(worker.stdout, opts.onLog)
166
+ forEachLine(worker.stderr, opts.onLog)
167
+
168
+ let settled = false
169
+ let terminating = false
170
+ /** @type {string|null} */
171
+ let failure = null
172
+ const timer = setTimeout(() => finish(new Error('timed out while starting')), startTimeoutMs)
173
+
174
+ /** @param {Error|null} err */
175
+ function finish(err) {
176
+ if (settled) return
177
+ settled = true
178
+ clearTimeout(timer)
179
+ if (err) {
180
+ worker.terminate().catch(() => {})
181
+ reject(err)
182
+ } else {
183
+ resolve({
184
+ request: requester.handle.request,
185
+ async terminate() {
186
+ terminating = true
187
+ requester.failAll(new Error('pod terminated'))
188
+ await worker.terminate()
189
+ },
190
+ })
191
+ }
192
+ }
193
+
194
+ worker.on('message', (message) => {
195
+ if (message?.type === 'ready') finish(null)
196
+ else if (message?.type === 'start-error') finish(new Error(message.message))
197
+ else if (message?.type === 'log') opts.onLog(message.line)
198
+ else requester.onMessage(message)
199
+ })
200
+ worker.on('error', (err) => {
201
+ failure = err?.code === 'ERR_WORKER_OUT_OF_MEMORY' ? 'oom' : 'crashed'
202
+ if (!settled) finish(err)
203
+ })
204
+ worker.on('exit', (code) => {
205
+ requester.failAll(new Error('pod exited'))
206
+ if (!settled) { finish(new Error(`worker exited with code ${code} while starting`)); return }
207
+ if (terminating) return
208
+ opts.onExit({ code, reason: failure ?? (code === 0 ? 'exited' : 'crashed') })
209
+ })
210
+ })
211
+ },
212
+ }
213
+ }
214
+
215
+ /**
216
+ * @param {object} [opts]
217
+ * @param {number} [opts.startTimeoutMs]
218
+ * @param {string} [opts.nodePath=process.execPath]
219
+ * @returns {import('./pod-runtime.mjs').PodRuntime}
220
+ */
221
+ export function createPermissionProcessRuntime({ startTimeoutMs = DEFAULT_START_TIMEOUT_MS, nodePath = process.execPath } = {}) {
222
+ return {
223
+ kind: 'node-permission-process',
224
+ lane: POD_LANE.NODE,
225
+ boundary: RUNTIME_BOUNDARY.PROCESS,
226
+
227
+ start(opts) {
228
+ requireAbsolute(opts.modulePath)
229
+ return new Promise((resolve, reject) => {
230
+ // The permission model matches real paths; /tmp and /var are symlinks on macOS.
231
+ const readable = [ENTRY_PATH, opts.modulePath, ...(opts.readPaths ?? [])].map((p) => realpathSync(p))
232
+ const memMib = opts.limits?.memMib
233
+ const child = fork(ENTRY_PATH, [JSON.stringify({
234
+ name: opts.name,
235
+ moduleUrl: pathToFileURL(realpathSync(opts.modulePath)).href,
236
+ env: opts.env,
237
+ input: opts.input,
238
+ })], {
239
+ execPath: nodePath,
240
+ execArgv: [
241
+ '--permission',
242
+ ...readable.map((p) => `--allow-fs-read=${p}`),
243
+ ...(memMib ? [`--max-old-space-size=${memMib}`] : []),
244
+ ],
245
+ // Exactly what the podspec named: nothing of the host's environment.
246
+ env: { ...opts.env },
247
+ stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
248
+ serialization: 'json',
249
+ })
250
+ const requester = makeRequester({ send: (message) => child.send(message) })
251
+ forEachLine(child.stdout, opts.onLog)
252
+ let stderrTail = ''
253
+ child.stderr.setEncoding('utf8')
254
+ child.stderr.on('data', (chunk) => {
255
+ stderrTail = (stderrTail + chunk).slice(-STDERR_TAIL_BYTES)
256
+ })
257
+
258
+ let settled = false
259
+ let terminating = false
260
+ const timer = setTimeout(() => finish(new Error('timed out while starting')), startTimeoutMs)
261
+
262
+ /** @param {Error|null} err */
263
+ function finish(err) {
264
+ if (settled) return
265
+ settled = true
266
+ clearTimeout(timer)
267
+ if (err) {
268
+ child.kill('SIGKILL')
269
+ reject(err)
270
+ } else {
271
+ resolve({
272
+ request: requester.handle.request,
273
+ terminate() {
274
+ terminating = true
275
+ requester.failAll(new Error('pod terminated'))
276
+ return new Promise((done) => {
277
+ if (child.exitCode !== null || child.signalCode !== null) { done(); return }
278
+ child.once('exit', () => done())
279
+ child.kill('SIGKILL')
280
+ })
281
+ },
282
+ })
283
+ }
284
+ }
285
+
286
+ child.on('message', (message) => {
287
+ if (message?.type === 'ready') finish(null)
288
+ else if (message?.type === 'start-error') finish(new Error(message.message))
289
+ else if (message?.type === 'log') opts.onLog(message.line)
290
+ else requester.onMessage(message)
291
+ })
292
+ child.on('error', (err) => { if (!settled) finish(err) })
293
+ child.on('exit', (code, signal) => {
294
+ requester.failAll(new Error('pod exited'))
295
+ if (!settled) { finish(new Error(`process exited with ${signal ?? code} while starting: ${stderrTail.trim().split('\n').at(-1) ?? ''}`)); return }
296
+ if (terminating) return
297
+ const oom = /heap out of memory|ERR_WORKER_OUT_OF_MEMORY|allocation failed/i.test(stderrTail)
298
+ opts.onExit({
299
+ code: code ?? 1,
300
+ reason: oom ? 'oom' : (code === 0 && !signal ? 'exited' : 'crashed'),
301
+ })
302
+ })
303
+ })
304
+ },
305
+ }
306
+ }
@@ -0,0 +1,374 @@
1
+ /**
2
+ * pod-runtime.mjs -- the adapter interface between a `PodHostDriver` and
3
+ * whatever actually runs a hosted pod's code in this process family, plus
4
+ * the driver that sits on top of it (issue #185, lane A and its honest
5
+ * stand-ins).
6
+ *
7
+ * A **`PodRuntime`** is the narrow thing that differs between ways of
8
+ * running a module in isolation:
9
+ *
10
+ * - `worker_threads` same process, no boundary (`node-runtimes.mjs`)
11
+ * - Node permission-model child separate process with fs/net/exec denied
12
+ * (`node-runtimes.mjs`); NOT a sandbox
13
+ * - `isolated-vm` a V8 isolate (specified below, NOT built:
14
+ * it is a native dependency)
15
+ * - `workerd` a V8 isolate in its own process (the
16
+ * `spikes/isolate-pod-host` Worker host
17
+ * speaks this protocol over HTTP instead)
18
+ *
19
+ * `createRuntimeLaneDriver()` turns any of them into a `PodHostDriver`, so
20
+ * the pod-host service, the placement pool and the supervisor see one lane
21
+ * driver whatever sits behind it. The driver owns everything that must not
22
+ * depend on the runtime: podspec validation, which modules may run (a
23
+ * host-side catalog, never a path from the requester), which environment
24
+ * variables a pod may be given, admission limits, the lifecycle state
25
+ * machine and the events.
26
+ *
27
+ * ## The contract a runtime implements
28
+ *
29
+ * ```
30
+ * runtime = {
31
+ * kind: string, // 'worker_threads' | 'isolated-vm' | ...
32
+ * lane: 'isolate' | 'node' | ..., // the POD_LANE this runtime may be advertised as
33
+ * boundary: 'none'|'process'|'language'|'hardware',
34
+ * start(opts) -> Promise<handle>
35
+ * }
36
+ * opts = { name, modulePath, env, input, limits: {memMib?}, readPaths?,
37
+ * onExit({code, reason}), onLog(line) }
38
+ * handle = { request(payload, {timeoutMs}) -> Promise<reply>, terminate() -> Promise<void> }
39
+ * ```
40
+ *
41
+ * `start()` resolves once the module has loaded and its optional `start()`
42
+ * has run, and rejects if it cannot. `onExit` fires exactly once if the pod
43
+ * stops on its own (`reason`: `'oom'`, `'crashed'`, `'exited'`); it does not
44
+ * fire for a `terminate()` the driver asked for.
45
+ *
46
+ * The hosted module (from the catalog) exports:
47
+ * `async start(ctx)` (optional) and `async handle(payload, ctx)`, where
48
+ * `ctx = { name, env, input, log(line) }`. Its return value is the reply to
49
+ * `send`.
50
+ *
51
+ * ## A runtime that claims the isolate lane must be one
52
+ *
53
+ * A driver whose runtime advertises `lane: 'isolate'` is refused unless its
54
+ * `boundary` is `language` or `hardware`. `runtime:isolate` is what the
55
+ * scorer matches, so a `worker_threads` runtime (boundary `none`) must be
56
+ * advertised as the `node` lane, where untrusted requesters are not placed.
57
+ * `node:vm` contexts and `worker_threads` are NOT security boundaries.
58
+ *
59
+ * ## Specifying the isolate implementation against this interface
60
+ *
61
+ * An `isolated-vm` runtime (NOT in this repository: it is a native
62
+ * dependency, which is the owner's decision to add) implements `start()` by
63
+ * creating one `ivm.Isolate({ memoryLimit: limits.memMib })` and one context,
64
+ * compiling the module source (read by the host from `modulePath`; the
65
+ * module may only `import` what the host provides as references),
66
+ * and bridging `request` and `onLog` through `Reference`/`ExternalCopy`
67
+ * callbacks; `terminate()` is `isolate.dispose()`; an out-of-memory
68
+ * disposal is reported as `onExit({reason: 'oom'})`. It declares
69
+ * `boundary: 'language'`, runs in a process of its own (the upstream README
70
+ * itself says to), and so may declare `lane: 'isolate'`. A `workerd` runtime
71
+ * is the same shape with a Worker per pod. Neither needs any change to the
72
+ * driver, the pool or the service.
73
+ *
74
+ * Zero dependencies and no `node:` imports: this module loads in a Worker, a
75
+ * browser or a microVM guest. The Node implementations are in
76
+ * `node-runtimes.mjs`.
77
+ */
78
+
79
+ import {
80
+ POD_HOST_ERROR,
81
+ POD_HOST_EVENT_KIND,
82
+ POD_HOST_VERB,
83
+ POD_LANE,
84
+ POD_LANES,
85
+ POD_LIFECYCLE,
86
+ PodHostDriverError,
87
+ canTransition,
88
+ createHostEvent,
89
+ createUnsupportedDriverMethod,
90
+ validatePodSpec,
91
+ } from './host-protocol.mjs'
92
+
93
+ /** How strongly a runtime separates a pod from its host, weakest first. */
94
+ export const RUNTIME_BOUNDARY = Object.freeze({
95
+ NONE: 'none',
96
+ PROCESS: 'process',
97
+ LANGUAGE: 'language',
98
+ HARDWARE: 'hardware',
99
+ })
100
+
101
+ const BOUNDARIES = Object.freeze(Object.values(RUNTIME_BOUNDARY))
102
+ const ISOLATE_BOUNDARIES = Object.freeze([RUNTIME_BOUNDARY.LANGUAGE, RUNTIME_BOUNDARY.HARDWARE])
103
+
104
+ /**
105
+ * Environment variable names a requester may not set: they change how the
106
+ * runtime loads code or applies its own restrictions (`NODE_OPTIONS` can
107
+ * carry permission flags, `LD_PRELOAD`/`DYLD_*` load libraries).
108
+ */
109
+ export const FORBIDDEN_ENV_NAME = /^(NODE_|LD_|DYLD_|UV_|OPENSSL_)/i
110
+
111
+ /** What `limits.memMib` becomes when a podspec states none. */
112
+ const DEFAULT_MEM_MIB = 128
113
+
114
+ /** Default wait for a `send` reply. */
115
+ const DEFAULT_SEND_TIMEOUT_MS = 5000
116
+
117
+ const VERBS = Object.freeze([
118
+ POD_HOST_VERB.SPAWN, POD_HOST_VERB.STATUS, POD_HOST_VERB.SEND,
119
+ POD_HOST_VERB.DRAIN, POD_HOST_VERB.LIST,
120
+ ])
121
+
122
+ /**
123
+ * @param {object} opts
124
+ * @param {object} opts.runtime - A `PodRuntime` (see the module doc comment).
125
+ * @param {Record<string, string|{path: string, readPaths?: string[]}>} opts.modules
126
+ * Catalog of module names a podspec's `run.ref` may name, to absolute file
127
+ * paths on THIS host. A requester never supplies a path.
128
+ * @param {number} [opts.maxPods] - Admission limit: more is refused `EBUSY`.
129
+ * @param {number} [opts.maxMemMib] - Largest `limits.memMib` a pod may ask for.
130
+ * @param {number} [opts.defaultMemMib=128]
131
+ * @param {number} [opts.sendTimeoutMs=5000]
132
+ * @returns {import('./host-protocol.mjs').PodHostDriver}
133
+ */
134
+ export function createRuntimeLaneDriver({
135
+ runtime, modules = {}, maxPods, maxMemMib, defaultMemMib = DEFAULT_MEM_MIB, sendTimeoutMs = DEFAULT_SEND_TIMEOUT_MS,
136
+ } = {}) {
137
+ if (!runtime || typeof runtime.start !== 'function') {
138
+ throw new Error('createRuntimeLaneDriver: a runtime with start() is required')
139
+ }
140
+ if (!POD_LANES.includes(runtime.lane)) {
141
+ throw new Error(`createRuntimeLaneDriver: runtime.lane must be one of ${POD_LANES.join('|')}`)
142
+ }
143
+ if (!BOUNDARIES.includes(runtime.boundary)) {
144
+ throw new Error(`createRuntimeLaneDriver: runtime.boundary must be one of ${BOUNDARIES.join('|')}`)
145
+ }
146
+ if (runtime.lane === POD_LANE.ISOLATE && !ISOLATE_BOUNDARIES.includes(runtime.boundary)) {
147
+ throw new Error(
148
+ `createRuntimeLaneDriver: a runtime with boundary '${runtime.boundary}' cannot be advertised as the isolate lane `
149
+ + '(worker_threads and node:vm are not isolation boundaries; advertise it as the node lane)',
150
+ )
151
+ }
152
+
153
+ const lane = runtime.lane
154
+ /** @type {Map<string, {name: string, spec: object, state: string, createdAt: number, updatedAt: number, handle: object|null, sends: number}>} */
155
+ const pods = new Map()
156
+ /** @type {Set<(event: object) => void>} */
157
+ const listeners = new Set()
158
+
159
+ /** @param {object} event */
160
+ function emit(event) {
161
+ for (const fn of [...listeners]) {
162
+ try {
163
+ fn(event)
164
+ } catch {
165
+ // A throwing subscriber never breaks the driver.
166
+ }
167
+ }
168
+ }
169
+
170
+ /** @param {object} record @param {string} to @param {string} reason */
171
+ function transition(record, to, reason) {
172
+ if (!canTransition(record.state, to)) {
173
+ throw new PodHostDriverError(POD_HOST_ERROR.EBUSY, `pod '${record.name}' cannot go ${record.state} -> ${to}`, { name: record.name })
174
+ }
175
+ const from = record.state
176
+ record.state = to
177
+ record.updatedAt = Date.now()
178
+ emit(createHostEvent(POD_HOST_EVENT_KIND.LIFECYCLE, { name: record.name, lane, from, to, reason }))
179
+ }
180
+
181
+ /** @param {object} record */
182
+ function statusOf(record) {
183
+ return {
184
+ name: record.name,
185
+ lane,
186
+ state: record.state,
187
+ spec: record.spec,
188
+ createdAt: record.createdAt,
189
+ updatedAt: record.updatedAt,
190
+ sends: record.sends,
191
+ podId: null,
192
+ }
193
+ }
194
+
195
+ /** @param {string} name @returns {object} */
196
+ function require_(name) {
197
+ const record = pods.get(name)
198
+ if (!record) throw new PodHostDriverError(POD_HOST_ERROR.ENOENT, `no pod named '${name}'`, { name })
199
+ return record
200
+ }
201
+
202
+ /** @param {string} name @returns {object} */
203
+ function requireLive(name) {
204
+ const record = require_(name)
205
+ if (record.state === POD_LIFECYCLE.GONE) {
206
+ throw new PodHostDriverError(POD_HOST_ERROR.ENOENT, `pod '${name}' is gone`, { name })
207
+ }
208
+ return record
209
+ }
210
+
211
+ /** @param {object} value A validated podspec. @returns {{modulePath: string, readPaths: string[]}} */
212
+ function resolveModule(value) {
213
+ if (value.run.kind !== 'module' && value.run.kind !== 'skill') {
214
+ throw new PodHostDriverError(
215
+ POD_HOST_ERROR.EINVAL,
216
+ `run.kind '${value.run.kind}' is not runnable by this host (module or skill only)`,
217
+ { kind: value.run.kind },
218
+ )
219
+ }
220
+ const entry = Object.hasOwn(modules, value.run.ref) ? modules[value.run.ref] : undefined
221
+ if (!entry) {
222
+ throw new PodHostDriverError(POD_HOST_ERROR.ENOENT, `no module registered under '${value.run.ref}'`, { ref: value.run.ref })
223
+ }
224
+ return typeof entry === 'string'
225
+ ? { modulePath: entry, readPaths: [] }
226
+ : { modulePath: entry.path, readPaths: [...(entry.readPaths ?? [])] }
227
+ }
228
+
229
+ return {
230
+ lane,
231
+ runtime,
232
+
233
+ capabilities() {
234
+ return { verbs: [...VERBS], boundary: runtime.boundary, runtime: runtime.kind }
235
+ },
236
+
237
+ onEvent(fn) {
238
+ if (typeof fn !== 'function') return () => {}
239
+ listeners.add(fn)
240
+ return () => { listeners.delete(fn) }
241
+ },
242
+
243
+ async spawn(spec) {
244
+ const validated = validatePodSpec(spec)
245
+ if (!validated.ok) {
246
+ throw new PodHostDriverError(POD_HOST_ERROR.EINVAL, validated.errors.join('; '), { errors: validated.errors })
247
+ }
248
+ const value = validated.value
249
+ if (value.lane !== lane) {
250
+ throw new PodHostDriverError(POD_HOST_ERROR.ELANE, `this host runs the '${lane}' lane, not '${value.lane}'`, { lane: value.lane })
251
+ }
252
+ const existing = pods.get(value.name)
253
+ if (existing && existing.state !== POD_LIFECYCLE.GONE) {
254
+ throw new PodHostDriverError(POD_HOST_ERROR.EEXIST, `pod '${value.name}' already exists`, { name: value.name })
255
+ }
256
+ const live = [...pods.values()].filter((p) => p.state !== POD_LIFECYCLE.GONE).length
257
+ if (maxPods !== undefined && live >= maxPods) {
258
+ throw new PodHostDriverError(POD_HOST_ERROR.EBUSY, `host is at its limit of ${maxPods} pods`, { maxPods })
259
+ }
260
+ for (const key of Object.keys(value.env ?? {})) {
261
+ if (FORBIDDEN_ENV_NAME.test(key)) {
262
+ throw new PodHostDriverError(POD_HOST_ERROR.EINVAL, `env '${key}' may not be set`, { env: key })
263
+ }
264
+ }
265
+ const memMib = value.limits?.memMib ?? defaultMemMib
266
+ if (maxMemMib !== undefined && memMib > maxMemMib) {
267
+ throw new PodHostDriverError(POD_HOST_ERROR.EINVAL, `limits.memMib ${memMib} exceeds this host's maximum of ${maxMemMib}`, { memMib, maxMemMib })
268
+ }
269
+ const { modulePath, readPaths } = resolveModule(value)
270
+
271
+ const now = Date.now()
272
+ const record = { name: value.name, spec: value, state: POD_LIFECYCLE.COLD, createdAt: now, updatedAt: now, handle: null, sends: 0 }
273
+ pods.set(value.name, record)
274
+ transition(record, POD_LIFECYCLE.BOOTING, 'spawn')
275
+
276
+ let started = false
277
+ /** @type {{code: number|null, reason: string}|null} */
278
+ let earlyExit = null
279
+ try {
280
+ record.handle = await runtime.start({
281
+ name: value.name,
282
+ modulePath,
283
+ readPaths,
284
+ env: { ...(value.env ?? {}) },
285
+ input: value.run.input ?? null,
286
+ limits: { memMib },
287
+ onLog: (line) => emit(createHostEvent(POD_HOST_EVENT_KIND.LOG, { name: value.name, lane, stream: 'stdout', chunk: String(line) })),
288
+ onExit: (info) => {
289
+ if (!started) { earlyExit = info; return }
290
+ onUnexpectedExit(record, info)
291
+ },
292
+ })
293
+ } catch (err) {
294
+ record.handle = null
295
+ transition(record, POD_LIFECYCLE.GONE, 'start-failed')
296
+ throw new PodHostDriverError(POD_HOST_ERROR.EINVAL, `pod failed to start: ${err?.message || String(err)}`, { name: value.name })
297
+ }
298
+ started = true
299
+ if (earlyExit) {
300
+ // The runtime reported an exit while start() was still settling.
301
+ record.handle = null
302
+ transition(record, POD_LIFECYCLE.GONE, 'start-failed')
303
+ throw new PodHostDriverError(POD_HOST_ERROR.EINVAL, `pod exited while starting (${earlyExit.reason})`, { name: value.name })
304
+ }
305
+ transition(record, POD_LIFECYCLE.REGISTERED, 'spawn')
306
+ return statusOf(record)
307
+ },
308
+
309
+ async status(name) {
310
+ return statusOf(require_(name))
311
+ },
312
+
313
+ async send(name, msg) {
314
+ const record = requireLive(name)
315
+ if (record.state !== POD_LIFECYCLE.REGISTERED && record.state !== POD_LIFECYCLE.SERVING) {
316
+ throw new PodHostDriverError(POD_HOST_ERROR.EBUSY, `pod '${name}' is ${record.state}`, { name })
317
+ }
318
+ record.sends += 1
319
+ const timeoutMs = record.spec.limits?.timeoutMs ?? sendTimeoutMs
320
+ try {
321
+ const reply = await record.handle.request({ to: msg?.to ?? null, payload: msg?.payload ?? null }, { timeoutMs })
322
+ return { delivered: true, reply }
323
+ } catch (err) {
324
+ if (err instanceof PodHostDriverError) throw err
325
+ const timedOut = err?.code === 'ETIMEDOUT'
326
+ throw new PodHostDriverError(
327
+ timedOut ? POD_HOST_ERROR.ETIMEDOUT : POD_HOST_ERROR.EINVAL,
328
+ timedOut ? `pod '${name}' did not reply within ${timeoutMs} ms` : `pod '${name}' failed the request: ${err?.message || String(err)}`,
329
+ { name },
330
+ )
331
+ }
332
+ },
333
+
334
+ exec: createUnsupportedDriverMethod(POD_HOST_VERB.EXEC, lane),
335
+ snapshot: createUnsupportedDriverMethod(POD_HOST_VERB.SNAPSHOT, lane),
336
+ restore: createUnsupportedDriverMethod(POD_HOST_VERB.RESTORE, lane),
337
+
338
+ async drain(name, opts = {}) {
339
+ const record = require_(name)
340
+ if (record.state !== POD_LIFECYCLE.GONE) {
341
+ transition(record, POD_LIFECYCLE.DRAINING, 'drain')
342
+ const handle = record.handle
343
+ record.handle = null
344
+ try {
345
+ await handle?.terminate()
346
+ } finally {
347
+ transition(record, POD_LIFECYCLE.GONE, 'drain')
348
+ }
349
+ }
350
+ emit(createHostEvent(POD_HOST_EVENT_KIND.EXIT, {
351
+ name, lane, code: 0, cascade: opts.cascade === true, reason: 'drained', restartable: false,
352
+ }))
353
+ return statusOf(record)
354
+ },
355
+
356
+ async list() {
357
+ return [...pods.values()].map(statusOf)
358
+ },
359
+ }
360
+
361
+ /**
362
+ * A pod stopped without being asked to.
363
+ * @param {object} record
364
+ * @param {{code: number|null, reason: string}} info
365
+ */
366
+ function onUnexpectedExit(record, info) {
367
+ if (record.state === POD_LIFECYCLE.GONE || record.state === POD_LIFECYCLE.DRAINING) return
368
+ record.handle = null
369
+ transition(record, POD_LIFECYCLE.GONE, info.reason)
370
+ emit(createHostEvent(POD_HOST_EVENT_KIND.EXIT, {
371
+ name: record.name, lane, code: info.code ?? 1, reason: info.reason === 'exited' ? 'exited' : 'crashed', restartable: true,
372
+ }))
373
+ }
374
+ }