index.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. /**
  2. * Worker-thread code runtime: a fresh worker runs each host-type-stripped TypeScript program
  3. * and bridges bindings over its message port. This is containment, not a security boundary:
  4. * model code has bash-equivalent trust despite an empty environment, a heap cap, measured
  5. * event-loop busy-time and wall-time budgets, and termination that also stops synchronous loops.
  6. * @module @deepseek-ai/dsh-code-runtime-worker
  7. */
  8. import { Worker } from 'node:worker_threads'
  9. import { stripTypeScriptTypes } from 'node:module'
  10. import type { Readable } from 'node:stream'
  11. import { fileURLToPath } from 'node:url'
  12. import { Context } from 'cordis'
  13. import z from 'schemastery'
  14. import { CodeRuntime } from '@deepseek-ai/dsh-code-runtime'
  15. import type { CodeBindingNamespace, CodeJsonValue, CodeRunFailure, CodeRunRequest, CodeRunResult } from '@deepseek-ai/dsh-code-runtime'
  16. import { snapshotJsonValue } from '@deepseek-ai/dsh-session'
  17. import type { ReplyMessage, WorkerBootData, WorkerToHost } from './protocol.ts'
  18. import { jsonStringBytesUpTo, jsonValueBytesUpTo, truncateJsonStringBytes } from './output-json.ts'
  19. import { decodeWorkerJson, encodeWorkerJson } from './worker-json.ts'
  20. import type { WorkerJsonWire } from './worker-json.ts'
  21. /** Plugin config: every execution cap, changeable from `cordis.yml` (no hardcoded tunables). */
  22. export interface Config {
  23. /**
  24. * Busy-time budget in milliseconds: the run fails with kind `'timeout'`
  25. * once the worker's MEASURED event-loop active time
  26. * (`worker.performance.eventLoopUtilization()`) exceeds this. Metering
  27. * measured busy time — not wall time, not host-side pending-call
  28. * bookkeeping — is what makes the budget both fair (a program awaiting a
  29. * slow tool accrues nothing) and ungameable (a hot loop accrues whether
  30. * or not a decoy dispatch is in flight).
  31. */
  32. computeMs?: number
  33. /**
  34. * Wall-clock ceiling in milliseconds; never pauses for anything. The
  35. * backstop for what busy-time cannot see (a program awaiting a promise
  36. * nobody will resolve).
  37. */
  38. maxWallMs?: number
  39. /**
  40. * Hard cap for serialized log-array, completion-value, and failure-message payloads;
  41. * fixed result-envelope syntax is excluded.
  42. */
  43. maxOutputBytes?: number
  44. /** The worker's max old-generation heap in MiB (`resourceLimits`); overflow kills the worker, surfacing as kind `'worker-exit'`. */
  45. maxOldGenerationSizeMb?: number
  46. }
  47. /** {@link Config} after schemastery fills the defaults (every field present). */
  48. type ResolvedConfig = Required<Config>
  49. /**
  50. * How often the host samples the worker's event-loop utilization for the
  51. * `computeMs` budget. An internal cadence, not config: the only effect of
  52. * the interval is budget-expiry granularity (a run can overshoot by up to
  53. * one interval), and nothing a deployment could tune here improves that
  54. * without burning host CPU.
  55. */
  56. const ELU_POLL_INTERVAL_MS = 25
  57. /** Smallest cap that can represent the counted payloads: an empty logs array plus an empty JSON failure message. */
  58. const MIN_OUTPUT_BYTES = 4
  59. /** ECMAScript reserved words that cannot be async-function parameter names — rejected as binding globals. */
  60. const RESERVED_WORDS = new Set([
  61. 'await', 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do',
  62. 'else', 'enum', 'export', 'extends', 'false', 'finally', 'for', 'function', 'if', 'import', 'in',
  63. 'instanceof', 'new', 'null', 'return', 'super', 'switch', 'this', 'throw', 'true', 'try', 'typeof',
  64. 'var', 'void', 'while', 'with', 'yield', 'let', 'static', 'implements', 'interface', 'package',
  65. 'private', 'protected', 'public', 'arguments', 'eval',
  66. ])
  67. /** Valid async-function parameter name (the binding global becomes one). */
  68. const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/
  69. /** Error properties whose binding-member replacement would destroy the promised Error contract. */
  70. const RESERVED_ERROR_PROPERTIES = new Set(['name', 'message', 'stack'])
  71. /**
  72. * The shell a program is wrapped in for the type-strip, matching the
  73. * grammatical context it will execute in (an async function body, where
  74. * top-level `return` and `await` are legal — a bare module parse would
  75. * reject the `return`). Strip mode is position-preserving (removed syntax
  76. * becomes whitespace, nothing shifts), so the wrapper survives the strip
  77. * byte-identical and the body slices back out with the model's own
  78. * line/column positions intact.
  79. */
  80. const STRIP_WRAP = { prefix: 'async function __dsh_program__() {\n', suffix: '\n}' } as const
  81. /** One in-flight run's host-side state, tracked for disposal. */
  82. interface LiveRun {
  83. worker: Worker
  84. settle(failure: CodeRunFailure): void
  85. finished: Promise<void>
  86. }
  87. /**
  88. * The worker entry path. Source runs unbuilt (`src/worker.ts`, loadable
  89. * directly on this repo's Node range via native type stripping — the file
  90. * is erasable-only with type-only relative imports); the built package
  91. * ships it as a sibling CommonJS bundle (`lib/worker.cjs`, its own tsdown
  92. * entry) because pkg's VFS Worker hook compiles string-path entries as
  93. * CommonJS.
  94. * The URL *pathname*'s extension says which world this module is in —
  95. * pathname, because dev-time module runners (vitest) may suffix
  96. * `import.meta.url` with a query string; relative resolution drops it. Worker
  97. * receives a filesystem string so pkg's VFS Worker hook can resolve it.
  98. */
  99. /* v8 ignore next -- the './worker.cjs' arm is the built-lib world, unreachable unbuilt by construction; the built-lib e2e pins it. */
  100. const WORKER_PATH = fileURLToPath(new URL(new URL(import.meta.url).pathname.endsWith('.ts') ? './worker.ts' : './worker.cjs', import.meta.url))
  101. /** Render an unknown thrown value as a message, `Error` or not. */
  102. function messageOf(error: unknown): string {
  103. return error instanceof Error ? error.message : String(error)
  104. }
  105. /** Resolve after a worker pipe emits all queued data, or closes/errors during termination. */
  106. function waitForPipeDrain(stream: Readable): Promise<void> {
  107. if (stream.readableEnded || stream.destroyed) return Promise.resolve()
  108. return new Promise((resolve) => {
  109. const done = (): void => {
  110. stream.off('end', done)
  111. stream.off('close', done)
  112. stream.off('error', done)
  113. resolve()
  114. }
  115. stream.once('end', done)
  116. stream.once('close', done)
  117. stream.once('error', done)
  118. // Close the event-registration race if termination finished between the
  119. // initial state check and the listeners above.
  120. /* v8 ignore next -- this race cannot be scheduled deterministically between the adjacent state check and listener registration. */
  121. if (stream.readableEnded || stream.destroyed) done()
  122. })
  123. }
  124. /**
  125. * Runtime shape gate for inbound port traffic. The peer runs MODEL CODE and
  126. * can post anything — `null`, primitives, objects with poisoned fields — so
  127. * the compile-time `WorkerToHost` type means nothing here: everything is
  128. * re-validated and REBUILT field by field (a forged extra field never rides
  129. * along; a non-number call id can never be echoed into a reply). Junk returns
  130. * `undefined` and is dropped — a throw in the host's `message` listener would
  131. * crash the host process.
  132. */
  133. function parseWorkerMessage(raw: unknown): WorkerToHost | undefined {
  134. if (typeof raw !== 'object' || raw === null) return undefined
  135. const m = raw as Record<string, unknown>
  136. switch (m.type) {
  137. case 'call': {
  138. if (typeof m.id !== 'number' || typeof m.global !== 'string' || typeof m.name !== 'string') return undefined
  139. return { type: 'call', id: m.id, global: m.global, name: m.name, args: m.args as WorkerJsonWire }
  140. }
  141. case 'log': {
  142. if (typeof m.text !== 'string') return undefined
  143. return { type: 'log', text: m.text }
  144. }
  145. case 'output-limit': return { type: 'output-limit' }
  146. case 'done': {
  147. if (m.error === undefined) return { type: 'done', ...m.value !== undefined ? { value: m.value as WorkerJsonWire } : {} }
  148. const error = m.error
  149. if (typeof error !== 'object' || error === null) return undefined
  150. const { kind, message } = error as Record<string, unknown>
  151. if ((kind !== 'exception' && kind !== 'invalid-output' && kind !== 'output-limit') || typeof message !== 'string') return undefined
  152. return { type: 'done', error: { kind, message } }
  153. }
  154. default: return undefined
  155. }
  156. }
  157. /** One run's combined outer-output ledger; binding values never enter it. */
  158. class OutputLedger {
  159. private bytes = 2 // JSON serialization of the empty logs array: []
  160. private entries = 0
  161. constructor(private readonly maxBytes: number) {}
  162. /** Admit one exact log entry, or report that the hard cap was crossed. */
  163. admit(text: string, sink: string[]): boolean {
  164. const separatorBytes = this.entries > 0 ? 1 : 0
  165. const stringBytes = jsonStringBytesUpTo(text, this.maxBytes - this.bytes - separatorBytes)
  166. if (stringBytes === undefined) return false
  167. this.bytes += stringBytes + separatorBytes
  168. this.entries += 1
  169. sink.push(text)
  170. return true
  171. }
  172. /** Finalize a successful absent-or-JSON completion against the combined cap. */
  173. success(logs: string[], value?: CodeJsonValue): CodeRunResult {
  174. if (value !== undefined && jsonValueBytesUpTo(value, this.maxBytes - this.bytes) === undefined) return this.limit(logs)
  175. return { logs, ...value !== undefined ? { value } : {} }
  176. }
  177. /** Finalize a failure diagnostic, with output-limit taking precedence when combined bytes exceed the cap. */
  178. failure(logs: string[], error: CodeRunFailure): CodeRunResult {
  179. if (jsonStringBytesUpTo(error.message, this.maxBytes - this.bytes) === undefined) return this.limit(logs)
  180. return { logs, error }
  181. }
  182. /** Build the explicit output-limit failure while retaining a fitting prefix of the final log. */
  183. limit(logs: string[]): CodeRunResult {
  184. const fullMessage = `outer output exceeded ${this.maxBytes} bytes`
  185. // The fixed diagnostic is ASCII, so every character is one byte plus the quotes.
  186. const messageBytes = fullMessage.length + 2
  187. const retained: string[] = []
  188. let retainedBytes = 2
  189. const logBudget = this.maxBytes - messageBytes
  190. for (const text of logs) {
  191. const separatorBytes = retained.length > 0 ? 1 : 0
  192. const availableBytes = logBudget - retainedBytes - separatorBytes
  193. const stringBytes = jsonStringBytesUpTo(text, availableBytes)
  194. if (stringBytes !== undefined) {
  195. retained.push(text)
  196. retainedBytes += stringBytes + separatorBytes
  197. continue
  198. }
  199. const prefix = truncateJsonStringBytes(text, availableBytes)
  200. if (prefix.length > 0) {
  201. const prefixBytes = jsonStringBytesUpTo(prefix, availableBytes)
  202. /* v8 ignore next -- truncateJsonStringBytes guarantees its returned prefix fits the same budget. */
  203. if (prefixBytes === undefined) throw new Error('output ledger produced an oversized log prefix')
  204. retained.push(prefix)
  205. retainedBytes += prefixBytes + separatorBytes
  206. }
  207. break
  208. }
  209. const availableMessageBytes = this.maxBytes - retainedBytes
  210. const message = truncateJsonStringBytes(fullMessage, availableMessageBytes)
  211. return { logs: retained, error: { kind: 'output-limit', message } }
  212. }
  213. }
  214. /**
  215. * The shipped {@link CodeRuntime} backend (`ctx.codeRuntime`). Registers as
  216. * the `codeRuntime` service; every cap comes from validated config. See the
  217. * module doc for the containment model and the class JSDoc on the seam for
  218. * the contract this implements (error-as-field, hostile-peer port,
  219. * no cross-run state, dispose to quiescence).
  220. */
  221. export class WorkerCodeRuntime extends CodeRuntime {
  222. static Config: z<Config> = z.object({
  223. computeMs: z.number().default(60_000),
  224. maxWallMs: z.number().default(600_000),
  225. maxOutputBytes: z.number().default(67_108_864),
  226. maxOldGenerationSizeMb: z.number().default(512),
  227. })
  228. readonly language = 'typescript'
  229. readonly isolation = 'worker-thread'
  230. private readonly config: ResolvedConfig
  231. private readonly live = new Set<LiveRun>()
  232. private disposed = false
  233. constructor(ctx: Context, config: Config) {
  234. super(ctx)
  235. // Schemastery filled the defaults; the cast records that. Positivity is a
  236. // semantic check the schema's plain number type does not carry.
  237. this.config = config as ResolvedConfig
  238. for (const [key, value] of Object.entries(this.config)) {
  239. if (!(Number.isFinite(value) && value > 0)) throw new Error(`dsh-code-runtime-worker: config.${key} must be a positive number, got ${String(value)}`)
  240. }
  241. if (!Number.isSafeInteger(this.config.maxOutputBytes) || this.config.maxOutputBytes < MIN_OUTPUT_BYTES) {
  242. throw new Error(`dsh-code-runtime-worker: config.maxOutputBytes must be a safe integer of at least ${MIN_OUTPUT_BYTES}, got ${String(this.config.maxOutputBytes)}`)
  243. }
  244. ctx.effect(() => () => this.teardown(), 'worker code-runtime teardown')
  245. }
  246. /**
  247. * Dispose to quiescence: mark the service unusable, fail every in-flight
  248. * run as aborted, and AWAIT each worker's exit so no worker outlives the
  249. * fiber.
  250. */
  251. private async teardown(): Promise<void> {
  252. this.disposed = true
  253. const runs = [...this.live]
  254. for (const run of runs) run.settle({ kind: 'abort', message: 'runtime disposed' })
  255. await Promise.all(runs.map(run => run.finished))
  256. }
  257. /**
  258. * Execute one program in a fresh worker. Program outcomes — including a
  259. * type-strip syntax error, which never spawns a worker — resolve with
  260. * `result.error`; the method rejects only for seam misuse (a disposed
  261. * runtime, an invalid binding namespace).
  262. * @param request - the program, its bindings, and the abort signal.
  263. * @returns the run's outcome per the seam contract.
  264. */
  265. async run(request: CodeRunRequest): Promise<CodeRunResult> {
  266. if (this.disposed) throw new Error('dsh-code-runtime-worker: run() after disposal')
  267. const bindings = this.validateBindings(request)
  268. if (request.signal?.aborted) {
  269. return this.failureBeforeWorker({ kind: 'abort', message: String(request.signal.reason) })
  270. }
  271. let code: string
  272. try {
  273. const stripped = stripTypeScriptTypes(STRIP_WRAP.prefix + request.program + STRIP_WRAP.suffix)
  274. code = stripped.slice(STRIP_WRAP.prefix.length, stripped.length - STRIP_WRAP.suffix.length)
  275. } catch (error: unknown) {
  276. // A program that does not survive the type-strip (syntax error,
  277. // non-erasable syntax like `enum`) is a program failure, reported the
  278. // same way a thrown exception would be — and no worker ever spawns.
  279. return this.failureBeforeWorker({ kind: 'exception', message: messageOf(error) })
  280. }
  281. return await this.execute(request, code, bindings)
  282. }
  283. /** Apply the outer-output ledger to failures that occur before a worker owns one. */
  284. private failureBeforeWorker(error: CodeRunFailure): CodeRunResult {
  285. return new OutputLedger(this.config.maxOutputBytes).failure([], error)
  286. }
  287. /** Reject malformed binding globals or typed-error declarations as seam misuse. */
  288. private validateBindings(request: CodeRunRequest): Map<string, CodeBindingNamespace> {
  289. const bindings = new Map<string, CodeBindingNamespace>()
  290. for (const namespace of request.bindings) {
  291. if (!IDENTIFIER.test(namespace.global) || RESERVED_WORDS.has(namespace.global)) {
  292. throw new Error(`dsh-code-runtime-worker: binding global ${JSON.stringify(namespace.global)} is not a usable identifier`)
  293. }
  294. if (namespace.global === 'console' || bindings.has(namespace.global)) {
  295. throw new Error(`dsh-code-runtime-worker: duplicate binding global ${JSON.stringify(namespace.global)}`)
  296. }
  297. bindings.set(namespace.global, namespace)
  298. }
  299. const errorClassNames = new Set<string>()
  300. for (const namespace of request.bindings) {
  301. const descriptor = namespace.errorClass
  302. if (!descriptor) continue
  303. if (!IDENTIFIER.test(descriptor.name) || RESERVED_WORDS.has(descriptor.name)) {
  304. throw new Error(`dsh-code-runtime-worker: binding error class ${JSON.stringify(descriptor.name)} is not a usable identifier`)
  305. }
  306. if (descriptor.name === 'console' || bindings.has(descriptor.name) || errorClassNames.has(descriptor.name)) {
  307. throw new Error(`dsh-code-runtime-worker: duplicate injected global ${JSON.stringify(descriptor.name)}`)
  308. }
  309. if (descriptor.memberNameProperty.length === 0 || RESERVED_ERROR_PROPERTIES.has(descriptor.memberNameProperty)) {
  310. throw new Error(`dsh-code-runtime-worker: binding error member property ${JSON.stringify(descriptor.memberNameProperty)} is not usable`)
  311. }
  312. errorClassNames.add(descriptor.name)
  313. }
  314. return bindings
  315. }
  316. /** Spawn the worker for one validated, type-stripped run and drive it to settlement. */
  317. private execute(
  318. request: CodeRunRequest,
  319. code: string,
  320. bindings: Map<string, CodeBindingNamespace>,
  321. ): Promise<CodeRunResult> {
  322. const bootData: WorkerBootData = {
  323. code,
  324. namespaces: [...bindings].map(([global, namespace]) => ({
  325. global,
  326. names: Object.keys(namespace.functions),
  327. ...namespace.errorClass ? { errorClass: namespace.errorClass } : {},
  328. })),
  329. maxOutputBytes: this.config.maxOutputBytes,
  330. }
  331. const worker = new Worker(WORKER_PATH, {
  332. workerData: bootData,
  333. // Model code gets NO ambient environment — stronger than the scrubbed
  334. // env the defensive-patterns rule requires for spawned commands.
  335. env: {},
  336. // Hermetic flags too: without this the worker inherits the host process's execArgv (a
  337. // test runner's or tsx's loader hooks), which a bare isolate with an empty environment
  338. // cannot satisfy.
  339. execArgv: [],
  340. resourceLimits: { maxOldGenerationSizeMb: this.config.maxOldGenerationSizeMb },
  341. // Backstop capture: the bootstrap patches JS-level writes into its own
  342. // ordered buffer, so these pipes normally stay silent; anything that
  343. // still arrives (native-level writes) is appended after the done logs.
  344. stdout: true,
  345. stderr: true,
  346. })
  347. return new Promise<CodeRunResult>((resolve) => {
  348. let settled = false
  349. const answered = new Set<number>()
  350. const logs: string[] = []
  351. const strayLogs: string[] = []
  352. const output = new OutputLedger(this.config.maxOutputBytes)
  353. let terminalOverride: CodeRunResult | undefined
  354. // Pipe and message-port delivery are independent. Continue bounded pipe
  355. // capture after a terminal message while worker termination drains bytes
  356. // that were already queued; `finish` materializes the result only after
  357. // termination completes.
  358. const captureStray = (chunk: Buffer): void => {
  359. /* v8 ignore next -- a second post-overflow chunk races immediate worker termination; the first overflow path is covered. */
  360. if (terminalOverride !== undefined) return
  361. const text = chunk.toString('utf8')
  362. if (!output.admit(text, strayLogs)) {
  363. const limited = output.limit([...logs, ...strayLogs, text])
  364. terminalOverride = limited
  365. finish(limited)
  366. }
  367. }
  368. worker.stdout.on('data', captureStray)
  369. worker.stderr.on('data', captureStray)
  370. // Exactly one outcome wins. Every path cleans up, terminates, and awaits the worker;
  371. // logs captured before timeout, abort, or failure remain in the result.
  372. let finishResolve!: () => void
  373. const finished = new Promise<void>((done) => { finishResolve = done })
  374. const finish = (finalize: CodeRunResult | (() => CodeRunResult)): void => {
  375. if (settled) return
  376. settled = true
  377. clearInterval(eluTimer)
  378. clearTimeout(wallTimer)
  379. request.signal?.removeEventListener('abort', onAbort)
  380. this.live.delete(live)
  381. // Let the poll phase deliver pipe bytes already queued independently
  382. // of the terminal port message before termination closes the streams.
  383. void new Promise<void>((resume) => { setImmediate(resume) }).then(async () => {
  384. const stdoutDrained = waitForPipeDrain(worker.stdout)
  385. const stderrDrained = waitForPipeDrain(worker.stderr)
  386. await Promise.all([worker.terminate(), stdoutDrained, stderrDrained])
  387. const result = terminalOverride ?? (typeof finalize === 'function' ? finalize() : finalize)
  388. finishResolve()
  389. resolve(result)
  390. })
  391. }
  392. const onDone = (message: WorkerToHost): void => {
  393. if (message.type !== 'done') return
  394. if (message.error) {
  395. const error = message.error
  396. finish(() => output.failure([...logs, ...strayLogs], error))
  397. return
  398. }
  399. if (message.value === undefined) {
  400. finish(() => output.success([...logs, ...strayLogs]))
  401. return
  402. }
  403. const value = decodeWorkerJson(message.value)
  404. if (value === undefined) {
  405. finish(() => output.failure([...logs, ...strayLogs], { kind: 'invalid-output', message: 'program completion must be lossless JSON' }))
  406. } else {
  407. finish(() => output.success([...logs, ...strayLogs], value))
  408. }
  409. }
  410. const onCall = (message: WorkerToHost): void => {
  411. if (message.type !== 'call' || settled) return
  412. // Hostile-peer rules: a duplicate id is ignored, an unknown name is
  413. // answered with a failure, and a binding throw/reject becomes the
  414. // program-side rejection — contained here, never a host crash.
  415. if (answered.has(message.id)) return
  416. answered.add(message.id)
  417. const reply = (payload: ReplyMessage): void => {
  418. if (settled) return
  419. // Canonical resolutions were snapshotted as lossless JSON before
  420. // this point, so this payload is structured-cloneable by contract.
  421. worker.postMessage(payload)
  422. }
  423. const record = bindings.get(message.global)?.functions
  424. // Own-property lookup only: a forged name like 'constructor' or
  425. // 'hasOwnProperty' must not walk the record's prototype chain and
  426. // reach a callable the consumer never declared.
  427. const fn = record && Object.hasOwn(record, message.name) ? record[message.name] : undefined
  428. if (typeof fn !== 'function') {
  429. reply({ type: 'reply', id: message.id, ok: false, message: `unknown binding ${JSON.stringify(`${message.global}.${message.name}`)}` })
  430. return
  431. }
  432. const args = decodeWorkerJson(message.args)
  433. if (args === undefined) {
  434. reply({ type: 'reply', id: message.id, ok: false, message: 'binding arguments must be lossless JSON' })
  435. return
  436. }
  437. void (async () => {
  438. try {
  439. const resolved = await fn(args)
  440. let value: CodeJsonValue | undefined
  441. try {
  442. value = snapshotJsonValue(resolved)
  443. } catch {
  444. value = undefined
  445. }
  446. if (value === undefined) {
  447. reply({ type: 'reply', id: message.id, ok: false, message: 'binding resolution must be lossless JSON' })
  448. } else {
  449. reply({ type: 'reply', id: message.id, ok: true, value: encodeWorkerJson(value) })
  450. }
  451. } catch (error: unknown) {
  452. reply({ type: 'reply', id: message.id, ok: false, message: messageOf(error) })
  453. }
  454. })()
  455. }
  456. worker.on('message', (raw: unknown) => {
  457. // Parse before touching: the peer can post ANY shape, and a throw in
  458. // this listener would crash the host process. Junk drops silently.
  459. const message = parseWorkerMessage(raw)
  460. if (!message) return
  461. if (message.type === 'log' && !settled && !output.admit(message.text, logs)) {
  462. const limited = output.limit([...logs, ...strayLogs, message.text])
  463. finish(limited)
  464. return
  465. }
  466. if (message.type === 'output-limit' && !settled) {
  467. const limited = output.limit([...logs, ...strayLogs])
  468. finish(limited)
  469. return
  470. }
  471. onCall(message)
  472. onDone(message)
  473. })
  474. worker.on('error', (error: Error) => {
  475. finish(() => output.failure([...logs, ...strayLogs], { kind: 'worker-exit', message: `worker error: ${error.message}` }))
  476. })
  477. worker.on('exit', (exitCode: number) => {
  478. finish(() => output.failure([...logs, ...strayLogs], { kind: 'worker-exit', message: `worker exited with code ${exitCode} before completing` }))
  479. })
  480. // The compute budget reads the worker's own measured busy time, so a
  481. // hot loop expires it no matter what dispatches are in flight, while a
  482. // program idling on a slow binding accrues nothing.
  483. const eluTimer = setInterval(() => {
  484. const elu = worker.performance.eventLoopUtilization()
  485. if (elu.active > this.config.computeMs) {
  486. finish(() => output.failure([...logs, ...strayLogs], { kind: 'timeout', message: `compute budget exhausted (${this.config.computeMs}ms busy)` }))
  487. }
  488. }, ELU_POLL_INTERVAL_MS)
  489. const wallTimer = setTimeout(() => {
  490. finish(() => output.failure([...logs, ...strayLogs], { kind: 'timeout', message: `wall-clock ceiling reached (${this.config.maxWallMs}ms)` }))
  491. }, this.config.maxWallMs)
  492. const onAbort = (): void => {
  493. finish(() => output.failure([...logs, ...strayLogs], { kind: 'abort', message: String(request.signal?.reason) }))
  494. }
  495. request.signal?.addEventListener('abort', onAbort, { once: true })
  496. const live: LiveRun = {
  497. worker,
  498. finished,
  499. settle: (failure: CodeRunFailure) => { finish(() => output.failure([...logs, ...strayLogs], failure)) },
  500. }
  501. this.live.add(live)
  502. })
  503. }
  504. }
  505. export default WorkerCodeRuntime