index.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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 { fileURLToPath } from 'node:url'
  11. import { Context } from 'cordis'
  12. import z from 'schemastery'
  13. import { CodeRuntime } from '@deepseek-ai/dsh-code-runtime'
  14. import type { CodeBindingFunction, CodeRunFailure, CodeRunRequest, CodeRunResult } from '@deepseek-ai/dsh-code-runtime'
  15. import { prepareValue, truncateUtf8Bytes } from './bootstrap.ts'
  16. import { logTruncationMarker } from './protocol.ts'
  17. import type { ReplyMessage, WorkerBootData, WorkerToHost } from './protocol.ts'
  18. /** Plugin config: every execution cap, changeable from `cordis.yml` (no hardcoded tunables). */
  19. export interface Config {
  20. /**
  21. * Busy-time budget in milliseconds: the run fails with kind `'timeout'`
  22. * once the worker's MEASURED event-loop active time
  23. * (`worker.performance.eventLoopUtilization()`) exceeds this. Metering
  24. * measured busy time — not wall time, not host-side pending-call
  25. * bookkeeping — is what makes the budget both fair (a program awaiting a
  26. * slow tool accrues nothing) and ungameable (a hot loop accrues whether
  27. * or not a decoy dispatch is in flight).
  28. */
  29. computeMs?: number
  30. /**
  31. * Wall-clock ceiling in milliseconds; never pauses for anything. The
  32. * backstop for what busy-time cannot see (a program awaiting a promise
  33. * nobody will resolve).
  34. */
  35. maxWallMs?: number
  36. /** Shared byte budget for captured log text (console + raw stream writes), truncation marked in-band. */
  37. maxLogBytes?: number
  38. /**
  39. * Byte cap for the completion value, measured by its real cross-boundary
  40. * size (string bytes, or structured-clone wire size); an oversized or
  41. * non-cloneable value crosses as a capped string rendering.
  42. */
  43. maxValueBytes?: 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. /** ECMAScript reserved words that cannot be async-function parameter names — rejected as binding globals. */
  58. const RESERVED_WORDS = new Set([
  59. 'await', 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do',
  60. 'else', 'enum', 'export', 'extends', 'false', 'finally', 'for', 'function', 'if', 'import', 'in',
  61. 'instanceof', 'new', 'null', 'return', 'super', 'switch', 'this', 'throw', 'true', 'try', 'typeof',
  62. 'var', 'void', 'while', 'with', 'yield', 'let', 'static', 'implements', 'interface', 'package',
  63. 'private', 'protected', 'public', 'arguments', 'eval',
  64. ])
  65. /** Valid async-function parameter name (the binding global becomes one). */
  66. const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/
  67. /**
  68. * The shell a program is wrapped in for the type-strip, matching the
  69. * grammatical context it will execute in (an async function body, where
  70. * top-level `return` and `await` are legal — a bare module parse would
  71. * reject the `return`). Strip mode is position-preserving (removed syntax
  72. * becomes whitespace, nothing shifts), so the wrapper survives the strip
  73. * byte-identical and the body slices back out with the model's own
  74. * line/column positions intact.
  75. */
  76. const STRIP_WRAP = { prefix: 'async function __dsh_program__() {\n', suffix: '\n}' } as const
  77. /** One in-flight run's host-side state, tracked for disposal. */
  78. interface LiveRun {
  79. worker: Worker
  80. settle(failure: CodeRunFailure): void
  81. finished: Promise<void>
  82. }
  83. /**
  84. * The worker entry path. Source runs unbuilt (`src/worker.ts`, loadable
  85. * directly on this repo's Node range via native type stripping — the file
  86. * is erasable-only with type-only relative imports); the built package
  87. * ships it as a sibling CommonJS bundle (`lib/worker.cjs`, its own tsdown
  88. * entry) because pkg's VFS Worker hook compiles string-path entries as
  89. * CommonJS.
  90. * The URL *pathname*'s extension says which world this module is in —
  91. * pathname, because dev-time module runners (vitest) may suffix
  92. * `import.meta.url` with a query string; relative resolution drops it. Worker
  93. * receives a filesystem string so pkg's VFS Worker hook can resolve it.
  94. */
  95. /* v8 ignore next -- the './worker.cjs' arm is the built-lib world, unreachable unbuilt by construction; the built-lib e2e pins it. */
  96. const WORKER_PATH = fileURLToPath(new URL(new URL(import.meta.url).pathname.endsWith('.ts') ? './worker.ts' : './worker.cjs', import.meta.url))
  97. /** Render an unknown thrown value as a message, `Error` or not. */
  98. function messageOf(error: unknown): string {
  99. return error instanceof Error ? error.message : String(error)
  100. }
  101. /**
  102. * Runtime shape gate for inbound port traffic. The peer runs MODEL CODE and
  103. * can post anything — `null`, primitives, objects with poisoned fields — so
  104. * the compile-time `WorkerToHost` type means nothing here: everything is
  105. * re-validated and REBUILT field by field (a forged extra field never rides
  106. * along; a non-number call id can never be echoed into a reply). Junk returns
  107. * `undefined` and is dropped — a throw in the host's `message` listener would
  108. * crash the host process.
  109. */
  110. function parseWorkerMessage(raw: unknown): WorkerToHost | undefined {
  111. if (typeof raw !== 'object' || raw === null) return undefined
  112. const m = raw as Record<string, unknown>
  113. switch (m.type) {
  114. case 'call': {
  115. if (typeof m.id !== 'number' || typeof m.global !== 'string' || typeof m.name !== 'string') return undefined
  116. return { type: 'call', id: m.id, global: m.global, name: m.name, args: m.args }
  117. }
  118. case 'log': {
  119. if (typeof m.text !== 'string') return undefined
  120. return { type: 'log', text: m.text }
  121. }
  122. case 'done': {
  123. if (m.error === undefined) return { type: 'done', ...m.value !== undefined ? { value: m.value } : {} }
  124. const error = m.error
  125. if (typeof error !== 'object' || error === null) return undefined
  126. const message = (error as Record<string, unknown>).message
  127. if (typeof message !== 'string') return undefined
  128. return { type: 'done', ...m.value !== undefined ? { value: m.value } : {}, error: { message } }
  129. }
  130. default: return undefined
  131. }
  132. }
  133. /**
  134. * Headroom the host's value re-cap grants over `maxValueBytes`: exactly the
  135. * truncation suffix {@link prepareValue} appends, so a value the WORKER
  136. * already capped (byte-exact prefix + this marker) passes through unchanged
  137. * instead of being marked twice.
  138. */
  139. const VALUE_RENDER_SLACK = Buffer.byteLength('… [truncated]', 'utf8')
  140. /**
  141. * The shipped {@link CodeRuntime} backend (`ctx.codeRuntime`). Registers as
  142. * the `codeRuntime` service; every cap comes from validated config. See the
  143. * module doc for the containment model and the class JSDoc on the seam for
  144. * the contract this implements (error-as-field, hostile-peer port,
  145. * no cross-run state, dispose to quiescence).
  146. */
  147. export class WorkerCodeRuntime extends CodeRuntime {
  148. static Config: z<Config> = z.object({
  149. computeMs: z.number().default(60_000),
  150. maxWallMs: z.number().default(600_000),
  151. maxLogBytes: z.number().default(65_536),
  152. maxValueBytes: z.number().default(32_768),
  153. maxOldGenerationSizeMb: z.number().default(512),
  154. })
  155. readonly language = 'typescript'
  156. readonly isolation = 'worker-thread'
  157. private readonly config: ResolvedConfig
  158. private readonly live = new Set<LiveRun>()
  159. private disposed = false
  160. constructor(ctx: Context, config: Config) {
  161. super(ctx)
  162. // Schemastery filled the defaults; the cast records that. Positivity is a
  163. // semantic check the schema's plain number type does not carry.
  164. this.config = config as ResolvedConfig
  165. for (const [key, value] of Object.entries(this.config)) {
  166. if (!(Number.isFinite(value) && value > 0)) throw new Error(`dsh-code-runtime-worker: config.${key} must be a positive number, got ${String(value)}`)
  167. }
  168. ctx.effect(() => () => this.teardown(), 'worker code-runtime teardown')
  169. }
  170. /**
  171. * Dispose to quiescence: mark the service unusable, fail every in-flight
  172. * run as aborted, and AWAIT each worker's exit so no worker outlives the
  173. * fiber.
  174. */
  175. private async teardown(): Promise<void> {
  176. this.disposed = true
  177. const runs = [...this.live]
  178. for (const run of runs) run.settle({ kind: 'abort', message: 'runtime disposed' })
  179. await Promise.all(runs.map(run => run.finished))
  180. }
  181. /**
  182. * Execute one program in a fresh worker. Program outcomes — including a
  183. * type-strip syntax error, which never spawns a worker — resolve with
  184. * `result.error`; the method rejects only for seam misuse (a disposed
  185. * runtime, an invalid binding namespace).
  186. * @param request - the program, its bindings, and the abort signal.
  187. * @returns the run's outcome per the seam contract.
  188. */
  189. async run(request: CodeRunRequest): Promise<CodeRunResult> {
  190. if (this.disposed) throw new Error('dsh-code-runtime-worker: run() after disposal')
  191. const bindings = this.validateBindings(request)
  192. if (request.signal?.aborted) {
  193. return { logs: [], error: { kind: 'abort', message: String(request.signal.reason) } }
  194. }
  195. let code: string
  196. try {
  197. const stripped = stripTypeScriptTypes(STRIP_WRAP.prefix + request.program + STRIP_WRAP.suffix)
  198. code = stripped.slice(STRIP_WRAP.prefix.length, stripped.length - STRIP_WRAP.suffix.length)
  199. } catch (error: unknown) {
  200. // A program that does not survive the type-strip (syntax error,
  201. // non-erasable syntax like `enum`) is a program failure, reported the
  202. // same way a thrown exception would be — and no worker ever spawns.
  203. return { logs: [], error: { kind: 'exception', message: messageOf(error) } }
  204. }
  205. return await this.execute(request, code, bindings)
  206. }
  207. /** Reject (seam misuse) malformed binding namespaces: non-identifier or reserved globals, duplicates, and the `console` collision. */
  208. private validateBindings(request: CodeRunRequest): Map<string, Record<string, CodeBindingFunction>> {
  209. const bindings = new Map<string, Record<string, CodeBindingFunction>>()
  210. for (const namespace of request.bindings) {
  211. if (!IDENTIFIER.test(namespace.global) || RESERVED_WORDS.has(namespace.global)) {
  212. throw new Error(`dsh-code-runtime-worker: binding global ${JSON.stringify(namespace.global)} is not a usable identifier`)
  213. }
  214. if (namespace.global === 'console' || bindings.has(namespace.global)) {
  215. throw new Error(`dsh-code-runtime-worker: duplicate binding global ${JSON.stringify(namespace.global)}`)
  216. }
  217. bindings.set(namespace.global, namespace.functions)
  218. }
  219. return bindings
  220. }
  221. /** Spawn the worker for one validated, type-stripped run and drive it to settlement. */
  222. private execute(
  223. request: CodeRunRequest,
  224. code: string,
  225. bindings: Map<string, Record<string, CodeBindingFunction>>,
  226. ): Promise<CodeRunResult> {
  227. const bootData: WorkerBootData = {
  228. code,
  229. namespaces: [...bindings].map(([global, functions]) => ({ global, names: Object.keys(functions) })),
  230. maxLogBytes: this.config.maxLogBytes,
  231. maxValueBytes: this.config.maxValueBytes,
  232. }
  233. const worker = new Worker(WORKER_PATH, {
  234. workerData: bootData,
  235. // Model code gets NO ambient environment — stronger than the scrubbed
  236. // env the defensive-patterns rule requires for spawned commands.
  237. env: {},
  238. // Hermetic flags too: without this the worker inherits the host process's execArgv (a
  239. // test runner's or tsx's loader hooks), which a bare isolate with an empty environment
  240. // cannot satisfy.
  241. execArgv: [],
  242. resourceLimits: { maxOldGenerationSizeMb: this.config.maxOldGenerationSizeMb },
  243. // Backstop capture: the bootstrap patches JS-level writes into its own
  244. // ordered buffer, so these pipes normally stay silent; anything that
  245. // still arrives (native-level writes) is appended after the done logs.
  246. stdout: true,
  247. stderr: true,
  248. })
  249. return new Promise<CodeRunResult>((resolve) => {
  250. let settled = false
  251. const answered = new Set<number>()
  252. const logs: string[] = []
  253. const strayLogs: string[] = []
  254. // One host-side budget covers normal, forged, and stray-pipe log entries. The first
  255. // overflow emits the shared in-band marker and drops everything after it.
  256. let logBudget = this.config.maxLogBytes
  257. let logsTruncated = false
  258. const admit = (text: string, sink: string[]): void => {
  259. if (logsTruncated) return
  260. const cost = Buffer.byteLength(text, 'utf8')
  261. if (cost > logBudget) {
  262. logsTruncated = true
  263. sink.push(logTruncationMarker(this.config.maxLogBytes))
  264. return
  265. }
  266. logBudget -= cost
  267. sink.push(text)
  268. }
  269. // No settled guard: `finish` snapshots the arrays when it resolves, so
  270. // a chunk flushing after settlement mutates only the discarded buffers,
  271. // and the ledger bounds that growth until the pipes close.
  272. const captureStray = (chunk: Buffer): void => {
  273. admit(chunk.toString('utf8'), strayLogs)
  274. }
  275. worker.stdout.on('data', captureStray)
  276. worker.stderr.on('data', captureStray)
  277. // Exactly one outcome wins. Every path cleans up, terminates, and awaits the worker;
  278. // logs captured before timeout, abort, or failure remain in the result.
  279. let finishResolve!: () => void
  280. const finished = new Promise<void>((done) => { finishResolve = done })
  281. const finish = (result: Omit<CodeRunResult, 'logs'>): void => {
  282. if (settled) return
  283. settled = true
  284. clearInterval(eluTimer)
  285. clearTimeout(wallTimer)
  286. request.signal?.removeEventListener('abort', onAbort)
  287. this.live.delete(live)
  288. void worker.terminate().then(() => {
  289. finishResolve()
  290. resolve({ ...result, logs: [...logs, ...strayLogs] })
  291. })
  292. }
  293. const onDone = (message: WorkerToHost): void => {
  294. if (message.type !== 'done') return
  295. // Re-cap forged completion traffic at the hostile boundary. Honest worker-capped values
  296. // pass unchanged via VALUE_RENDER_SLACK; error text is bounded too.
  297. finish({
  298. ...prepareValue(message.value, this.config.maxValueBytes + VALUE_RENDER_SLACK),
  299. ...message.error ? { error: { kind: 'exception' as const, message: truncateUtf8Bytes(message.error.message, this.config.maxValueBytes) } } : {},
  300. })
  301. }
  302. const onCall = (message: WorkerToHost): void => {
  303. if (message.type !== 'call' || settled) return
  304. // Hostile-peer rules: a duplicate id is ignored, an unknown name is
  305. // answered with a failure, and a binding throw/reject becomes the
  306. // program-side rejection — contained here, never a host crash.
  307. if (answered.has(message.id)) return
  308. answered.add(message.id)
  309. const reply = (payload: ReplyMessage): void => {
  310. if (settled) return
  311. try {
  312. worker.postMessage(payload)
  313. } catch {
  314. // The reply value failed structured clone; renegotiate as an error
  315. // reply, which is always clone-plain. Nothing else throws here.
  316. worker.postMessage({ type: 'reply', id: message.id, ok: false, message: 'binding resolution is not structured-cloneable' })
  317. }
  318. }
  319. const record = bindings.get(message.global)
  320. // Own-property lookup only: a forged name like 'constructor' or
  321. // 'hasOwnProperty' must not walk the record's prototype chain and
  322. // reach a callable the consumer never declared.
  323. const fn = record && Object.hasOwn(record, message.name) ? record[message.name] : undefined
  324. if (typeof fn !== 'function') {
  325. reply({ type: 'reply', id: message.id, ok: false, message: `unknown binding ${JSON.stringify(`${message.global}.${message.name}`)}` })
  326. return
  327. }
  328. void (async () => {
  329. try {
  330. reply({ type: 'reply', id: message.id, ok: true, value: await fn(message.args) })
  331. } catch (error: unknown) {
  332. reply({ type: 'reply', id: message.id, ok: false, message: messageOf(error) })
  333. }
  334. })()
  335. }
  336. worker.on('message', (raw: unknown) => {
  337. // Parse before touching: the peer can post ANY shape, and a throw in
  338. // this listener would crash the host process. Junk drops silently.
  339. const message = parseWorkerMessage(raw)
  340. if (!message) return
  341. if (message.type === 'log' && !settled) admit(message.text, logs)
  342. onCall(message)
  343. onDone(message)
  344. })
  345. worker.on('error', (error: Error) => {
  346. finish({ error: { kind: 'worker-exit', message: `worker error: ${error.message}` } })
  347. })
  348. worker.on('exit', (exitCode: number) => {
  349. finish({ error: { kind: 'worker-exit', message: `worker exited with code ${exitCode} before completing` } })
  350. })
  351. // The compute budget reads the worker's own measured busy time, so a
  352. // hot loop expires it no matter what dispatches are in flight, while a
  353. // program idling on a slow binding accrues nothing.
  354. const eluTimer = setInterval(() => {
  355. const elu = worker.performance.eventLoopUtilization()
  356. if (elu.active > this.config.computeMs) {
  357. finish({ error: { kind: 'timeout', message: `compute budget exhausted (${this.config.computeMs}ms busy)` } })
  358. }
  359. }, ELU_POLL_INTERVAL_MS)
  360. const wallTimer = setTimeout(() => {
  361. finish({ error: { kind: 'timeout', message: `wall-clock ceiling reached (${this.config.maxWallMs}ms)` } })
  362. }, this.config.maxWallMs)
  363. const onAbort = (): void => {
  364. finish({ error: { kind: 'abort', message: String(request.signal?.reason) } })
  365. }
  366. request.signal?.addEventListener('abort', onAbort, { once: true })
  367. const live: LiveRun = {
  368. worker,
  369. finished,
  370. settle: (failure: CodeRunFailure) => { finish({ error: failure }) },
  371. }
  372. this.live.add(live)
  373. })
  374. }
  375. }
  376. export default WorkerCodeRuntime