index.ts 20 KB

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