bootstrap.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. /**
  2. * Worker-side execution logic, written as plain functions over an injected
  3. * port so the unit suite can run every line IN-PROCESS against a fake port
  4. * (a real worker thread is a separate V8 isolate the coverage provider
  5. * cannot observe). The real worker entry (`worker.ts`) is a thin
  6. * self-executing glue file over {@link runWorkerMain}, excluded from
  7. * coverage the same way `bin.ts` entrypoints are, and exercised end-to-end
  8. * by the integration tests that spawn real workers.
  9. *
  10. * @module @deepseek-ai/dsh-code-runtime-worker/src/bootstrap
  11. */
  12. import { inspect } from 'node:util'
  13. import { serialize } from 'node:v8'
  14. import type { CodeLogEntry } from '@deepseek-ai/dsh-code-runtime'
  15. import { logTruncationMarker } from './protocol.ts'
  16. import type { DoneMessage, ReplyMessage, WorkerBootData, WorkerToHost } from './protocol.ts'
  17. /** The port surface the bootstrap needs — satisfied by `parentPort` and by the tests' fake. */
  18. export interface BootstrapPort {
  19. postMessage(message: WorkerToHost): void
  20. on(event: 'message', listener: (message: ReplyMessage) => void): void
  21. }
  22. /**
  23. * A writable stream's `write` slot, as the bootstrap patches it (see
  24. * {@link captureStreamWrites}). Method-typed so the real
  25. * `process.stdout`/`process.stderr` (narrower chunk parameters) remain
  26. * assignable.
  27. */
  28. export interface PatchableStream {
  29. write(chunk: unknown, ...rest: unknown[]): boolean
  30. }
  31. /**
  32. * Ordered log capture under one shared byte budget, delivered to a sink as
  33. * each entry lands (the real sink streams entries over the port eagerly, so
  34. * captured output survives a mid-run termination). Once the budget is
  35. * exhausted it emits exactly one in-band marker entry (on the `stderr`
  36. * diagnostics channel) and silently drops everything after — the cap is a
  37. * blast-radius bound, so "how much was lost" intentionally stays unmeasured.
  38. */
  39. export class LogBuffer {
  40. private remaining: number
  41. private truncated = false
  42. // Explicit fields, not constructor parameter properties: this module loads
  43. // under Node's native strip-only mode, which rejects non-erasable syntax —
  44. // and parameter properties are non-erasable.
  45. private readonly maxBytes: number
  46. private readonly sink: (entry: CodeLogEntry) => void
  47. constructor(maxBytes: number, sink: (entry: CodeLogEntry) => void) {
  48. this.maxBytes = maxBytes
  49. this.sink = sink
  50. this.remaining = maxBytes
  51. }
  52. /**
  53. * Emit one entry to the sink, charging its text against the budget (drops + marks once exhausted).
  54. * @param entry - the log entry to deliver.
  55. */
  56. push(entry: CodeLogEntry): void {
  57. if (this.truncated) return
  58. const cost = Buffer.byteLength(entry.text, 'utf8')
  59. if (cost > this.remaining) {
  60. this.truncated = true
  61. this.sink({ source: 'stderr', text: logTruncationMarker(this.maxBytes) })
  62. return
  63. }
  64. this.remaining -= cost
  65. this.sink(entry)
  66. }
  67. }
  68. /** The five console methods the shim captures, in the seam's level vocabulary. */
  69. const CONSOLE_LEVELS = ['log', 'info', 'warn', 'error', 'debug'] as const
  70. /**
  71. * A `console` replacement whose five leveled methods render their arguments
  72. * `util.inspect`-style (matching real console formatting closely enough for
  73. * a model to recognize its own output) into the buffer. Only these five
  74. * exist — the program gets a deliberately small console, not Node's full
  75. * surface.
  76. * @param logs - the buffer every rendered line is pushed into.
  77. * @returns the five-method console object handed to the program.
  78. */
  79. export function makeConsoleShim(logs: LogBuffer): Record<(typeof CONSOLE_LEVELS)[number], (...args: unknown[]) => void> {
  80. const render = (args: unknown[]): string =>
  81. args.map(arg => typeof arg === 'string' ? arg : inspect(arg, INSPECT_OPTIONS)).join(' ')
  82. const shim = Object.create(null) as Record<(typeof CONSOLE_LEVELS)[number], (...args: unknown[]) => void>
  83. for (const level of CONSOLE_LEVELS) {
  84. shim[level] = (...args: unknown[]) => { logs.push({ source: 'console', level, text: render(args) }) }
  85. }
  86. return shim
  87. }
  88. /**
  89. * Redirect a stream's `write` into the log buffer (the program-visible
  90. * `process.stdout`/`process.stderr` in the real worker), so raw writes land
  91. * in emission order alongside console output instead of racing down a pipe.
  92. * The shim keeps Node's `write(chunk[, encoding][, callback])` contract: the
  93. * callback fires asynchronously once the chunk is admitted (a program
  94. * awaiting flush completion must complete, not sit until the wall timeout),
  95. * even for writes the exhausted budget drops.
  96. * @param logs - the buffer captured writes are pushed into.
  97. * @param stream - the stream whose `write` slot is patched.
  98. * @param source - the log source the captured writes are attributed to.
  99. * @returns the restore function (the in-process tests un-patch; the real
  100. * worker never needs to).
  101. */
  102. export function captureStreamWrites(logs: LogBuffer, stream: PatchableStream, source: 'stdout' | 'stderr'): () => void {
  103. // The slot's VALUE is stored for restore and reassigned — never invoked
  104. // detached, so the unbound-method concern does not apply.
  105. // eslint-disable-next-line @typescript-eslint/unbound-method
  106. const original = stream.write
  107. stream.write = (chunk: unknown, ...rest: unknown[]): boolean => {
  108. logs.push({ source, text: typeof chunk === 'string' ? chunk : String(chunk) })
  109. // Node's optional-encoding shape: the callback is whichever of the next
  110. // two positions holds a function (a non-function there is the encoding).
  111. const callback = [rest[0], rest[1]].find(
  112. (arg): arg is (error?: Error | null) => void => typeof arg === 'function',
  113. )
  114. if (callback) queueMicrotask(() => { callback(null) })
  115. return true
  116. }
  117. return () => { stream.write = original }
  118. }
  119. /** Bounded inspect options: deep enough to be useful, bounded so a pathological value cannot explode the rendering. */
  120. const INSPECT_OPTIONS = { depth: 4, maxArrayLength: 100, maxStringLength: 10_000 } as const
  121. /**
  122. * The longest prefix of `text` whose UTF-8 encoding fits `maxBytes`, cut at
  123. * a code-point boundary (never mid-surrogate-pair). The byte caps are BYTE
  124. * caps — `String.prototype.slice` counts UTF-16 code units, up to 3× smaller
  125. * than what a multibyte string actually costs across the boundary.
  126. * @param text - the string to bound.
  127. * @param maxBytes - the UTF-8 byte budget the prefix must fit.
  128. * @returns the prefix (all of `text` when it already fits).
  129. */
  130. export function truncateUtf8Bytes(text: string, maxBytes: number): string {
  131. if (Buffer.byteLength(text, 'utf8') <= maxBytes) return text
  132. let bytes = 0
  133. let end = 0
  134. for (const char of text) {
  135. const cost = Buffer.byteLength(char, 'utf8')
  136. if (bytes + cost > maxBytes) break
  137. bytes += cost
  138. end += char.length
  139. }
  140. return text.slice(0, end)
  141. }
  142. /**
  143. * Prepare the program's completion value for the done message: a value whose
  144. * MEASURED cross-boundary size fits `maxValueBytes` crosses raw — exact
  145. * bytes for a string, the structured-clone wire size (`v8.serialize`) for
  146. * everything else, so a huge container whose BOUNDED inspect rendering
  147. * happens to be small cannot smuggle itself past the cap. Anything else
  148. * (non-cloneable, or oversized) is REPLACED by its bounded `util.inspect`
  149. * rendering, byte-truncated ({@link truncateUtf8Bytes}) with an in-band
  150. * marker — the seam contract's "a non-transferable value is replaced by a
  151. * string rendering", extended to oversized ones so a huge return cannot
  152. * flood the host.
  153. * @param value - the program's completion value.
  154. * @param maxValueBytes - the byte cap for the value.
  155. * @returns the done-message fragment: `{}` for `undefined`, else `{ value }`.
  156. */
  157. export function prepareValue(value: unknown, maxValueBytes: number): { value?: unknown } {
  158. if (value === undefined) return {}
  159. if (typeof value === 'string') {
  160. if (Buffer.byteLength(value, 'utf8') <= maxValueBytes) return { value }
  161. } else {
  162. let size: number | undefined
  163. try {
  164. size = serialize(value).byteLength
  165. } catch {
  166. // Only the verdict matters: the value has parts the structured-clone
  167. // algorithm rejects (functions, classes, …) and must cross as its
  168. // rendering instead.
  169. size = undefined
  170. }
  171. if (size !== undefined && size <= maxValueBytes) return { value }
  172. }
  173. const rendered = typeof value === 'string' ? value : inspect(value, INSPECT_OPTIONS)
  174. const capped = Buffer.byteLength(rendered, 'utf8') > maxValueBytes
  175. ? `${truncateUtf8Bytes(rendered, maxValueBytes)}… [truncated]`
  176. : rendered
  177. return { value: capped }
  178. }
  179. /** One awaited binding call's settlement handles, keyed by call id in the pending map. */
  180. export interface PendingCall {
  181. resolve(value: unknown): void
  182. reject(error: Error): void
  183. }
  184. /**
  185. * Route host replies into the pending-call map: each reply settles its call
  186. * at most once, and a reply for an unknown id (stray, or a duplicate answer
  187. * to an id already settled) is ignored. Shared wiring between
  188. * {@link runWorkerMain} and the tests that exercise {@link makeNamespaces}
  189. * standalone.
  190. * @param port - the port whose `message` events carry the replies.
  191. * @param pending - the id-keyed map of unsettled binding calls.
  192. */
  193. export function wireReplies(port: BootstrapPort, pending: Map<number, PendingCall>): void {
  194. port.on('message', (message: ReplyMessage) => {
  195. const entry = pending.get(message.id)
  196. if (!entry) return
  197. pending.delete(message.id)
  198. if (message.ok) entry.resolve(message.value)
  199. else entry.reject(new Error(message.message))
  200. })
  201. }
  202. /**
  203. * Build the binding namespace objects the program sees: one null-prototype
  204. * global per namespace, each declared name an own enumerable async function
  205. * that bridges over the port (`__proto__`/`constructor`/`toString` are
  206. * ordinary keys, never prototype collisions). A non-cloneable argument
  207. * rejects that one call with a descriptive error; the host's reply (`ok`
  208. * false) rejects it likewise, so a failed tool call surfaces in the program
  209. * as an ordinary promise rejection.
  210. * @param data - the boot payload's namespace declarations (globals + names).
  211. * @param port - the port binding calls are posted to.
  212. * @param pending - the id-keyed map each posted call parks its handles in.
  213. * @param nextId - the shared mutable id counter (worker-issued correlation ids).
  214. * @returns one namespace object per declaration, in declaration order.
  215. */
  216. export function makeNamespaces(
  217. data: Pick<WorkerBootData, 'namespaces'>,
  218. port: BootstrapPort,
  219. pending: Map<number, PendingCall>,
  220. nextId: { value: number },
  221. ): Record<string, unknown>[] {
  222. return data.namespaces.map(({ global, names }) => {
  223. const namespace = Object.create(null) as Record<string, unknown>
  224. for (const name of names) {
  225. Object.defineProperty(namespace, name, {
  226. enumerable: true,
  227. value: (args: unknown): Promise<unknown> => new Promise((resolve, reject) => {
  228. const id = nextId.value++
  229. pending.set(id, { resolve, reject })
  230. try {
  231. port.postMessage({ type: 'call', id, global, name, args })
  232. } catch (error: unknown) {
  233. pending.delete(id)
  234. reject(new Error(`binding arguments must be structured-cloneable: ${error instanceof Error ? error.message : String(error)}`))
  235. }
  236. }),
  237. })
  238. }
  239. return namespace
  240. })
  241. }
  242. /**
  243. * Run one program to settlement and post the {@link DoneMessage}: wires the
  244. * reply handler, materializes the namespaces and console shim, compiles the
  245. * type-stripped body as an async function (top-level `await`/`return`
  246. * work), and reports a thrown program error as the done message's `error`
  247. * field. Exactly one done message is ever posted.
  248. * @param port - the message port to the host (the real `parentPort`, or the tests' fake).
  249. * @param data - the boot payload the host sent.
  250. * @param streams - the stream objects whose `write` is captured (the real
  251. * `process.stdout`/`process.stderr` in the worker; fakes in tests).
  252. * @returns resolves after the done message is posted (the tests await it;
  253. * the real entry lets the worker exit naturally).
  254. */
  255. export async function runWorkerMain(
  256. port: BootstrapPort,
  257. data: WorkerBootData,
  258. streams: { stdout: PatchableStream; stderr: PatchableStream },
  259. ): Promise<void> {
  260. const logs = new LogBuffer(data.maxLogBytes, (entry) => { port.postMessage({ type: 'log', entry }) })
  261. captureStreamWrites(logs, streams.stdout, 'stdout')
  262. captureStreamWrites(logs, streams.stderr, 'stderr')
  263. const pending = new Map<number, PendingCall>()
  264. wireReplies(port, pending)
  265. const nextId = { value: 1 }
  266. const namespaces = makeNamespaces(data, port, pending, nextId)
  267. const consoleShim = makeConsoleShim(logs)
  268. let done: DoneMessage
  269. try {
  270. // The async function constructor, reached through an instance because
  271. // `AsyncFunction` is not a global. The program body is strict-mode.
  272. /* v8 ignore next -- the arrow exists only to reach the AsyncFunction constructor; it is never invoked. */
  273. const AsyncFunction = (async () => {}).constructor as new (...args: string[]) => (...fnArgs: unknown[]) => Promise<unknown>
  274. const fn = new AsyncFunction(...data.namespaces.map(namespace => namespace.global), 'console', `'use strict';\n${data.code}`)
  275. const value = await fn(...namespaces, consoleShim)
  276. done = { type: 'done', ...prepareValue(value, data.maxValueBytes) }
  277. } catch (error: unknown) {
  278. const message = error instanceof Error ? error.stack ?? error.message : String(error)
  279. done = { type: 'done', error: { message } }
  280. }
  281. port.postMessage(done)
  282. }