bootstrap.spec.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. import { describe, expect, it } from 'vitest'
  2. import { EventEmitter } from 'node:events'
  3. import { LogBuffer, makeConsoleShim, makeNamespaces, captureStreamWrites, prepareCompletion, runWorkerMain, ToolCallError, truncateUtf8Bytes, wireReplies } from '../src/bootstrap.ts'
  4. import type { BootstrapPort, PatchableStream, PendingCall } from '../src/bootstrap.ts'
  5. import type { ReplyMessage, WorkerToHost } from '../src/protocol.ts'
  6. import { decodeWorkerJson, encodeWorkerJson } from '../src/worker-json.ts'
  7. /**
  8. * An in-process stand-in for the worker's parentPort: the test plays the
  9. * HOST side — inspect what the bootstrap posted, feed replies back — so
  10. * every line of worker-side logic runs under coverage without spawning an
  11. * isolate (real-worker behavior is pinned by runtime.spec.ts).
  12. */
  13. class FakePort implements BootstrapPort {
  14. sent: WorkerToHost[] = []
  15. private readonly emitter = new EventEmitter()
  16. /** Host-scripted responder; return undefined to leave the call pending. */
  17. respond: (message: WorkerToHost) => ReplyMessage | undefined = () => undefined
  18. postMessage(message: WorkerToHost): void {
  19. this.sent.push(message)
  20. const reply = this.respond(message)
  21. if (reply) queueMicrotask(() => this.emitter.emit('message', reply))
  22. }
  23. on(event: 'message', listener: (message: ReplyMessage) => void): void {
  24. this.emitter.on(event, listener)
  25. }
  26. deliver(message: ReplyMessage): void {
  27. this.emitter.emit('message', message)
  28. }
  29. logs(): string[] {
  30. return this.sent.filter(message => message.type === 'log').map(message => message.text)
  31. }
  32. done(): WorkerToHost | undefined {
  33. return this.sent.find(message => message.type === 'done')
  34. }
  35. doneValue(): unknown {
  36. const done = this.done()
  37. return done?.type === 'done' && done.value !== undefined ? decodeWorkerJson(done.value) : undefined
  38. }
  39. }
  40. function fakeStreams(): { stdout: PatchableStream; stderr: PatchableStream } {
  41. return { stdout: { write: () => true }, stderr: { write: () => true } }
  42. }
  43. /** Capture one promise rejection without Vitest's intentionally `any` matcher channel. */
  44. async function rejectionOf(promise: Promise<unknown>): Promise<unknown> {
  45. try {
  46. await promise
  47. return undefined
  48. } catch (error: unknown) {
  49. return error
  50. }
  51. }
  52. const BOOT = { maxOutputBytes: 65_536 }
  53. describe('LogBuffer', () => {
  54. it('streams entries to the sink until the byte budget, then emits one fitting prefix and reports the limit once', () => {
  55. const seen: string[] = []
  56. let limits = 0
  57. const buffer = new LogBuffer(10, text => seen.push(text), () => { limits += 1 })
  58. buffer.push('12345')
  59. buffer.push('123456')
  60. buffer.push('dropped')
  61. expect(seen).toEqual(['12345', '12345'])
  62. expect(limits).toBe(1)
  63. const exactlyFull: string[] = []
  64. const fullBuffer = new LogBuffer(4, text => exactlyFull.push(text))
  65. fullBuffer.push('1234')
  66. fullBuffer.push('no-prefix-fits')
  67. expect(exactlyFull).toEqual(['1234'])
  68. })
  69. })
  70. describe('makeConsoleShim', () => {
  71. it('captures the five methods and renders non-strings inspect-style', () => {
  72. const seen: string[] = []
  73. const shim = makeConsoleShim(new LogBuffer(1_000, text => seen.push(text)))
  74. shim.log('plain', { a: 1 })
  75. shim.info('i')
  76. shim.warn('w')
  77. shim.error('e')
  78. shim.debug('d')
  79. expect(seen).toEqual(['plain { a: 1 }', 'i', 'w', 'e', 'd'])
  80. })
  81. })
  82. describe('captureStreamWrites', () => {
  83. it('redirects writes into the buffer and restores on request', () => {
  84. const seen: string[] = []
  85. const buffer = new LogBuffer(1_000, text => seen.push(text))
  86. let underlying = ''
  87. const stream: PatchableStream = { write: (chunk: unknown) => { underlying += String(chunk); return true } }
  88. const restore = captureStreamWrites(buffer, stream)
  89. stream.write('captured', 'utf8')
  90. stream.write(Buffer.from('bytes'))
  91. restore()
  92. stream.write('after')
  93. expect(seen).toEqual(['captured', 'bytes'])
  94. expect(underlying).toBe('after')
  95. })
  96. it('invokes the write callback asynchronously, in both optional-encoding shapes', async () => {
  97. const buffer = new LogBuffer(1_000, () => {})
  98. const stream: PatchableStream = { write: () => true }
  99. captureStreamWrites(buffer, stream)
  100. const calls: (Error | null | undefined)[] = []
  101. stream.write('two-arg', (error?: Error | null) => calls.push(error))
  102. stream.write('three-arg', 'utf8', (error?: Error | null) => calls.push(error))
  103. // Node's contract: the callback fires after the write call returns.
  104. expect(calls).toEqual([])
  105. await new Promise<void>(resolve => stream.write('awaited flush', resolve))
  106. expect(calls).toEqual([null, null])
  107. })
  108. it('still fires the callback for a write the exhausted budget drops', async () => {
  109. const buffer = new LogBuffer(4, () => {})
  110. const stream: PatchableStream = { write: () => true }
  111. captureStreamWrites(buffer, stream)
  112. stream.write('this write overflows the budget and is dropped')
  113. await new Promise<void>(resolve => stream.write('also dropped', resolve))
  114. })
  115. })
  116. describe('prepareCompletion', () => {
  117. it('omits undefined and passes lossless JSON values exactly', () => {
  118. expect(prepareCompletion(undefined, 100)).toEqual({})
  119. expect(prepareCompletion({ a: [1, 'two'] }, 100)).toEqual({ value: encodeWorkerJson({ a: [1, 'two'] }) })
  120. })
  121. it('turns every lossy completion shape into invalid-output', () => {
  122. const cyclic: Record<string, unknown> = {}
  123. cyclic.self = cyclic
  124. const sparse = Array(2)
  125. class Exotic { readonly marker = true }
  126. for (const value of [{ fn: () => 1 }, -0, Number.POSITIVE_INFINITY, sparse, cyclic, new Exotic()]) {
  127. expect(prepareCompletion(value, 1_000)).toEqual({
  128. error: { kind: 'invalid-output', message: 'program completion must be lossless JSON' },
  129. })
  130. }
  131. })
  132. it('reports an oversized value instead of substituting rendered text', () => {
  133. expect(prepareCompletion('x'.repeat(50), 10)).toEqual({
  134. error: { kind: 'output-limit', message: 'outer output exceeded 10 bytes' },
  135. })
  136. })
  137. it('measures the exact JSON serialization at and over the boundary', () => {
  138. expect(prepareCompletion('€', 5)).toEqual({ value: encodeWorkerJson('€') })
  139. expect(prepareCompletion('€', 4)).toEqual({
  140. error: { kind: 'output-limit', message: 'outer output exceeded 4 bytes' },
  141. })
  142. })
  143. it('contains a getter failure as invalid-output', () => {
  144. const value = Object.defineProperty({}, 'x', { enumerable: true, get() { throw new Error('getter exploded') } })
  145. expect(prepareCompletion(value, 1_000)).toEqual({
  146. error: { kind: 'invalid-output', message: 'program completion must be lossless JSON' },
  147. })
  148. })
  149. })
  150. describe('truncateUtf8Bytes', () => {
  151. it('returns a fitting string whole', () => {
  152. expect(truncateUtf8Bytes('fits', 4)).toBe('fits')
  153. })
  154. it('cuts at a code-point boundary, never mid-surrogate-pair', () => {
  155. // Each 😀 is one code point, two code units, four UTF-8 bytes: a 5-byte
  156. // budget fits exactly one — and never leaves a lone surrogate behind.
  157. const cut = truncateUtf8Bytes('😀😀', 5)
  158. expect(cut).toBe('😀')
  159. expect(Buffer.byteLength(truncateUtf8Bytes('😀😀', 3), 'utf8')).toBe(0)
  160. })
  161. })
  162. describe('makeNamespaces', () => {
  163. it('rejects a malformed success reply instead of resolving a lossy binding value', async () => {
  164. const port = new FakePort()
  165. const pending = new Map<number, PendingCall>()
  166. wireReplies(port, pending)
  167. const result = new Promise<unknown>((resolve, reject) => { pending.set(1, { resolve, reject }) })
  168. port.deliver({ type: 'reply', id: 1, ok: true, value: [undefined] as never })
  169. await expect(result).rejects.toThrow('binding resolution must be lossless JSON')
  170. })
  171. it('exposes prototype-colliding names as ordinary own properties', async () => {
  172. const port = new FakePort()
  173. port.respond = message => message.type === 'call'
  174. ? { type: 'reply', id: message.id, ok: true, value: encodeWorkerJson(`${message.name}-ok`) }
  175. : undefined
  176. const pending = new Map<number, PendingCall>()
  177. wireReplies(port, pending)
  178. const [tools] = makeNamespaces({ namespaces: [{ global: 'tools', names: ['__proto__', 'constructor', 'toString'] }] }, port, pending, { value: 1 }) as [Record<string, (args: unknown) => Promise<unknown>>]
  179. expect(Object.getPrototypeOf(tools)).toBeNull()
  180. await expect(tools['__proto__']?.({})).resolves.toBe('__proto__-ok')
  181. await expect(tools['constructor']?.({})).resolves.toBe('constructor-ok')
  182. await expect(tools['toString']?.({})).resolves.toBe('toString-ok')
  183. })
  184. it('rejects a postMessage clone failure without leaking the pending entry', async () => {
  185. let firstCall = true
  186. const throwingPort: BootstrapPort = {
  187. // First call throws an Error (the real DataCloneError shape), the
  188. // second a bare string — the rejection renders both.
  189. postMessage: () => {
  190. if (firstCall) { firstCall = false; throw new Error('DataCloneError-ish') }
  191. throw 'raw-clone-failure'
  192. },
  193. on: () => {},
  194. }
  195. const pending = new Map<number, PendingCall>()
  196. const [tools] = makeNamespaces({ namespaces: [{ global: 'tools', names: ['x'] }] }, throwingPort, pending, { value: 1 }) as [Record<string, (args: unknown) => Promise<unknown>>]
  197. const first = await rejectionOf(tools.x?.({ first: true }) ?? Promise.resolve())
  198. const second = await rejectionOf(tools.x?.({ second: true }) ?? Promise.resolve())
  199. expect(first).toMatchObject({ name: 'ToolCallError', toolName: 'x' })
  200. expect(second).toMatchObject({ name: 'ToolCallError', toolName: 'x' })
  201. expect(first).toBeInstanceOf(ToolCallError)
  202. expect(second).toBeInstanceOf(ToolCallError)
  203. expect((first as Error).message).toMatch(/DataCloneError-ish/)
  204. expect((second as Error).message).toMatch(/raw-clone-failure/)
  205. expect(pending.size).toBe(0)
  206. })
  207. it('rejects lossy arguments before posting or allocating a call id', async () => {
  208. let posts = 0
  209. const port: BootstrapPort = { postMessage: () => { posts += 1 }, on: () => {} }
  210. const pending = new Map<number, PendingCall>()
  211. const nextId = { value: 1 }
  212. const [tools] = makeNamespaces(
  213. { namespaces: [{ global: 'tools', names: ['x'] }] }, port, pending, nextId,
  214. ) as [Record<string, (args: unknown) => Promise<unknown>>]
  215. const decorated = [1]
  216. Object.defineProperty(decorated, 'extra', { value: true })
  217. const throwing = Object.defineProperty({}, 'value', {
  218. enumerable: true,
  219. get: () => { throw new Error('getter exploded') },
  220. })
  221. for (const value of [() => 1, new Date(), decorated, throwing]) {
  222. const failure = await rejectionOf(tools.x?.(value) ?? Promise.resolve())
  223. expect(failure).toMatchObject({
  224. name: 'ToolCallError', toolName: 'x', message: 'binding arguments must be lossless JSON',
  225. })
  226. }
  227. expect(posts).toBe(0)
  228. expect(pending.size).toBe(0)
  229. expect(nextId.value).toBe(1)
  230. })
  231. it('uses ordinary Error for non-tools namespace failures', async () => {
  232. const deniedPort = new FakePort()
  233. deniedPort.respond = message => message.type === 'call'
  234. ? { type: 'reply', id: message.id, ok: false, message: 'helper denied' }
  235. : undefined
  236. const deniedPending = new Map<number, PendingCall>()
  237. wireReplies(deniedPort, deniedPending)
  238. const [helpers] = makeNamespaces({ namespaces: [{ global: 'helpers', names: ['x'] }] }, deniedPort, deniedPending, { value: 1 }) as [Record<string, (args: unknown) => Promise<unknown>>]
  239. const denied = await rejectionOf(helpers.x?.({}) ?? Promise.resolve())
  240. expect(denied).toBeInstanceOf(Error)
  241. expect(denied).not.toBeInstanceOf(ToolCallError)
  242. const invalid = await rejectionOf(helpers.x?.(() => 1) ?? Promise.resolve())
  243. expect(invalid).toBeInstanceOf(Error)
  244. expect(invalid).not.toBeInstanceOf(ToolCallError)
  245. expect((invalid as Error).message).toBe('binding arguments must be lossless JSON')
  246. const clonePort: BootstrapPort = { postMessage: () => { throw new Error('clone failed') }, on: () => {} }
  247. const [cloneHelpers] = makeNamespaces({ namespaces: [{ global: 'helpers', names: ['x'] }] }, clonePort, new Map(), { value: 1 }) as [Record<string, (args: unknown) => Promise<unknown>>]
  248. const cloneFailure = await rejectionOf(cloneHelpers.x?.({}) ?? Promise.resolve())
  249. expect(cloneFailure).toBeInstanceOf(Error)
  250. expect(cloneFailure).not.toBeInstanceOf(ToolCallError)
  251. })
  252. })
  253. describe('runWorkerMain', () => {
  254. it('runs a program end-to-end: bindings, console, return value', async () => {
  255. const port = new FakePort()
  256. port.respond = (message) => {
  257. if (message.type !== 'call') return undefined
  258. const args = decodeWorkerJson(message.args) as { n: number }
  259. return { type: 'reply', id: message.id, ok: true, value: encodeWorkerJson(args.n * 2) }
  260. }
  261. await runWorkerMain(port, {
  262. ...BOOT,
  263. code: 'const doubled = await tools.double({ n: 21 }); console.log("got", doubled); return { doubled };',
  264. namespaces: [{ global: 'tools', names: ['double'] }],
  265. }, fakeStreams())
  266. expect(port.logs()).toEqual(['got 42'])
  267. expect(port.doneValue()).toEqual({ doubled: 42 })
  268. })
  269. it('reports worker-side log capture overflow before completing', async () => {
  270. const port = new FakePort()
  271. await runWorkerMain(port, {
  272. maxOutputBytes: 4,
  273. code: 'console.log("12345"); return null',
  274. namespaces: [],
  275. }, fakeStreams())
  276. expect(port.sent).toContainEqual({ type: 'log', text: '1234' })
  277. expect(port.sent).toContainEqual({ type: 'output-limit' })
  278. expect(port.doneValue()).toBeNull()
  279. })
  280. it('reports a thrown program error on the done message', async () => {
  281. const port = new FakePort()
  282. await runWorkerMain(port, { ...BOOT, code: 'throw new Error("boom")', namespaces: [] }, fakeStreams())
  283. const done = port.done()
  284. expect(done?.type).toBe('done')
  285. expect(done?.type === 'done' ? done.error?.kind : undefined).toBe('exception')
  286. expect(done?.type === 'done' ? done.error?.message : undefined).toContain('boom')
  287. expect(done?.type === 'done' ? done.value : undefined).toBeUndefined()
  288. })
  289. it('renders non-Error throws and stack-less Errors on the done message', async () => {
  290. const rawPort = new FakePort()
  291. await runWorkerMain(rawPort, { ...BOOT, code: 'throw "raw-throw"', namespaces: [] }, fakeStreams())
  292. expect(rawPort.done()).toEqual({ type: 'done', error: { kind: 'exception', message: 'raw-throw' } })
  293. const barePort = new FakePort()
  294. await runWorkerMain(barePort, { ...BOOT, code: 'const e = new Error("bare"); e.stack = undefined; throw e', namespaces: [] }, fakeStreams())
  295. expect(barePort.done()).toEqual({ type: 'done', error: { kind: 'exception', message: 'bare' } })
  296. })
  297. it('surfaces a host failure reply as a program-side rejection it can catch', async () => {
  298. const port = new FakePort()
  299. port.respond = message => message.type === 'call' ? { type: 'reply', id: message.id, ok: false, message: 'denied by host' } : undefined
  300. await runWorkerMain(port, {
  301. ...BOOT,
  302. code: 'try { await tools.x({}) } catch (error) { return { caught: error instanceof ToolCallError, name: error.name, toolName: error.toolName, message: error.message } }',
  303. namespaces: [{ global: 'tools', names: ['x'] }],
  304. }, fakeStreams())
  305. expect(port.doneValue()).toEqual({ caught: true, name: 'ToolCallError', toolName: 'x', message: 'denied by host' })
  306. expect(new ToolCallError('x', 'nope')).toMatchObject({ name: 'ToolCallError', toolName: 'x', message: 'nope' })
  307. })
  308. it('ignores replies for unknown pending ids', async () => {
  309. const port = new FakePort()
  310. port.respond = (message) => {
  311. if (message.type !== 'call') return undefined
  312. // Deliver a stray reply first; the real one follows.
  313. port.deliver({ type: 'reply', id: 9_999, ok: true, value: encodeWorkerJson('stray') })
  314. return { type: 'reply', id: message.id, ok: true, value: encodeWorkerJson('real') }
  315. }
  316. await runWorkerMain(port, {
  317. ...BOOT,
  318. code: 'return await tools.x({})',
  319. namespaces: [{ global: 'tools', names: ['x'] }],
  320. }, fakeStreams())
  321. expect(port.doneValue()).toBe('real')
  322. })
  323. it('captures raw stream writes through the patched process streams', async () => {
  324. const port = new FakePort()
  325. const streams = fakeStreams()
  326. await runWorkerMain(port, { ...BOOT, code: 'return 1', namespaces: [] }, streams)
  327. streams.stdout.write('never seen — already restored? no: patch persists in worker')
  328. // The patch stays installed for the worker's lifetime; writes during the
  329. // program landed in order. Here the program wrote nothing via streams, so
  330. // only the post-run write above went through the patched slot.
  331. expect(port.logs().at(-1)).toBe('never seen — already restored? no: patch persists in worker')
  332. })
  333. })