runtime.spec.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { WorkerCodeRuntime } from '@deepseek-ai/dsh-code-runtime-worker'
  4. import type { Config } from '@deepseek-ai/dsh-code-runtime-worker'
  5. import type { CodeBindingFunction, CodeBindingNamespace, CodeRunResult } from '@deepseek-ai/dsh-code-runtime'
  6. /**
  7. * Integration suite over REAL worker threads (no mocks — workers are cheap
  8. * and local, per docs/testing.md's real-over-mock policy). Each test builds
  9. * a fresh context so budgets can be tuned per case.
  10. */
  11. async function setup(config: Config = {}) {
  12. const ctx = new Context()
  13. await ctx.plugin(WorkerCodeRuntime, config)
  14. const runtime = ctx.codeRuntime as WorkerCodeRuntime
  15. return { ctx, runtime }
  16. }
  17. /** Convenience: one namespace `tools` with the given functions. */
  18. function tools(functions: Record<string, (args: unknown) => Promise<unknown>>): CodeBindingNamespace[] {
  19. return [{ global: 'tools', functions: functions as Record<string, CodeBindingFunction> }]
  20. }
  21. describe('WorkerCodeRuntime — programs and bindings (real workers)', () => {
  22. it('registers with the seam descriptors', async () => {
  23. const { runtime } = await setup()
  24. expect(runtime.language).toBe('typescript')
  25. expect(runtime.isolation).toBe('worker-thread')
  26. })
  27. it('runs TypeScript (erasable syntax), captures output in order, returns the value', async () => {
  28. const { runtime } = await setup()
  29. const result = await runtime.run({
  30. program: `
  31. interface Point { x: number; y: number }
  32. const p: Point = { x: 1, y: 2 } as Point;
  33. console.log('point', p);
  34. process.stdout.write('raw-out\\n');
  35. console.warn('careful');
  36. return p.x + p.y;
  37. `,
  38. bindings: [],
  39. })
  40. expect(result.error).toBeUndefined()
  41. expect(result.value).toBe(3)
  42. expect(result.logs).toEqual(['point { x: 1, y: 2 }', 'raw-out\n', 'careful'])
  43. })
  44. it('bridges binding calls both ways and rejects the program-side call on a host rejection', async () => {
  45. const { runtime } = await setup()
  46. const calls: unknown[] = []
  47. const result = await runtime.run({
  48. program: `
  49. const first = await tools.echo({ n: 1 });
  50. let caught = {};
  51. try { await tools.fail({}) } catch (error) { caught = { isTyped: error instanceof ToolCallError, name: error.name, toolName: error.toolName, message: error.message } }
  52. let caughtRaw = {};
  53. try { await tools.failRaw({}) } catch (error) { caughtRaw = { name: error.name, toolName: error.toolName, message: error.message } }
  54. return { first, caught, caughtRaw };
  55. `,
  56. bindings: tools({
  57. echo: async (args) => { calls.push(args); return { echoed: args } },
  58. fail: async () => { throw new Error('nope') },
  59. // A non-Error throw: the host renders it, the program still catches.
  60. failRaw: async () => { throw 'raw-nope' },
  61. }),
  62. })
  63. expect(result.error).toBeUndefined()
  64. expect(result.value).toEqual({
  65. first: { echoed: { n: 1 } },
  66. caught: { isTyped: true, name: 'ToolCallError', toolName: 'fail', message: 'nope' },
  67. caughtRaw: { name: 'ToolCallError', toolName: 'failRaw', message: 'raw-nope' },
  68. })
  69. expect(calls).toEqual([{ n: 1 }])
  70. })
  71. it('reports non-erasable syntax as an exception without spawning a worker', async () => {
  72. const { runtime } = await setup()
  73. const result = await runtime.run({ program: 'enum E { A }\nreturn 1', bindings: [] })
  74. expect(result.error?.kind).toBe('exception')
  75. expect(result.error?.message).toMatch(/enum|strip/i)
  76. })
  77. it('reports a runtime throw as an exception with the message', async () => {
  78. const { runtime } = await setup()
  79. const result = await runtime.run({ program: 'throw new Error("kaboom")', bindings: [] })
  80. expect(result.error?.kind).toBe('exception')
  81. expect(result.error?.message).toContain('kaboom')
  82. })
  83. it('gives the program an EMPTY environment', async () => {
  84. const { runtime } = await setup()
  85. const result = await runtime.run({ program: 'return JSON.stringify(process.env)', bindings: [] })
  86. expect(result.value).toBe('{}')
  87. })
  88. it('rejects a non-lossless completion instead of replacing it with rendered text', async () => {
  89. const { runtime } = await setup()
  90. const result = await runtime.run({ program: 'return { f: () => 1 }', bindings: [] })
  91. expect(result.value).toBeUndefined()
  92. expect(result.error).toEqual({ kind: 'invalid-output', message: 'program completion must be lossless JSON' })
  93. })
  94. it('completes a program that returns nothing with no value at all', async () => {
  95. const { runtime } = await setup()
  96. const result = await runtime.run({ program: 'const x = 1', bindings: [] })
  97. expect(result.error).toBeUndefined()
  98. expect('value' in result).toBe(false)
  99. })
  100. it('keeps logs streamed before a failure', async () => {
  101. const { runtime } = await setup()
  102. const result = await runtime.run({
  103. program: 'console.log("before"); throw new Error("after-log")',
  104. bindings: [],
  105. })
  106. expect(result.error?.kind).toBe('exception')
  107. expect(result.logs).toContain('before')
  108. })
  109. })
  110. describe('WorkerCodeRuntime — budgets and containment (real workers)', () => {
  111. it('ends a hot loop at the compute budget — including behind a pending decoy dispatch', async () => {
  112. const { runtime } = await setup({ computeMs: 300, maxWallMs: 30_000 })
  113. const result = await runtime.run({
  114. // The decoy: fire a call at a never-resolving binding WITHOUT awaiting,
  115. // then spin. Host-side pending-call bookkeeping would pause a naive
  116. // budget here; measured busy time cannot be fooled.
  117. program: 'void tools.slow({}); for (;;) {}',
  118. bindings: tools({ slow: () => new Promise(() => {}) }),
  119. })
  120. expect(result.error?.kind).toBe('timeout')
  121. expect(result.error?.message).toContain('compute budget')
  122. }, 15_000)
  123. it('does not charge time spent awaiting a slow binding against the compute budget', async () => {
  124. // Keep the binding delay above the compute allowance while leaving enough
  125. // headroom for worker bootstrap on loaded CI hosts.
  126. const { runtime } = await setup({ computeMs: 1_000, maxWallMs: 30_000 })
  127. const result = await runtime.run({
  128. program: 'return await tools.slow({})',
  129. bindings: tools({ slow: () => new Promise(resolve => setTimeout(() => { resolve('slow-done') }, 1_500)) }),
  130. })
  131. expect(result.error).toBeUndefined()
  132. expect(result.value).toBe('slow-done')
  133. }, 15_000)
  134. it('ends an idle-forever run at the wall-clock ceiling', async () => {
  135. const { runtime } = await setup({ computeMs: 30_000, maxWallMs: 400 })
  136. const result = await runtime.run({
  137. program: 'await tools.never({}); return 1',
  138. bindings: tools({ never: () => new Promise(() => {}) }),
  139. })
  140. expect(result.error?.kind).toBe('timeout')
  141. expect(result.error?.message).toContain('wall-clock ceiling')
  142. }, 15_000)
  143. it('reports an abort mid-run and stops the worker', async () => {
  144. const { runtime } = await setup()
  145. const controller = new AbortController()
  146. setTimeout(() => { controller.abort('user-cancel') }, 150)
  147. const result = await runtime.run({ program: 'for (;;) {}', bindings: [], signal: controller.signal })
  148. expect(result.error).toEqual({ kind: 'abort', message: 'user-cancel' })
  149. }, 15_000)
  150. it('reports a pre-aborted signal without spawning', async () => {
  151. const { runtime } = await setup()
  152. const controller = new AbortController()
  153. controller.abort('too-late')
  154. const result = await runtime.run({ program: 'return 1', bindings: [], signal: controller.signal })
  155. expect(result.error).toEqual({ kind: 'abort', message: 'too-late' })
  156. })
  157. it('drops a binding resolution that lands after the run settled', async () => {
  158. const { runtime } = await setup()
  159. const controller = new AbortController()
  160. let replyDelivered!: Promise<void>
  161. const result = await runtime.run({
  162. program: 'void tools.late({}); for (;;) {}',
  163. bindings: tools({
  164. // Anchored on invocation: abort 100ms after the call reaches the
  165. // host, resolve 400ms after — by then the run has settled, so the
  166. // resolution's reply hits the post-settlement drop.
  167. late: () => new Promise((resolve) => {
  168. setTimeout(() => { controller.abort('cancel-now') }, 100)
  169. replyDelivered = new Promise(done => setTimeout(() => { resolve('too-late'); done() }, 400))
  170. }),
  171. }),
  172. signal: controller.signal,
  173. })
  174. expect(result.error).toEqual({ kind: 'abort', message: 'cancel-now' })
  175. // Let the late resolution actually fire so its reply executes instead of
  176. // being cancelled with the test.
  177. await replyDelivered
  178. }, 15_000)
  179. it('contains an OOM under resourceLimits as worker-exit, host process healthy', async () => {
  180. const { runtime } = await setup({ maxOldGenerationSizeMb: 32 })
  181. const result = await runtime.run({
  182. program: 'const hog = []; for (;;) hog.push(new Array(1e6).fill(1));',
  183. bindings: [],
  184. })
  185. expect(result.error?.kind).toBe('worker-exit')
  186. // And the host is fine: run something else.
  187. const after = await runtime.run({ program: 'return "alive"', bindings: [] })
  188. expect(after.value).toBe('alive')
  189. }, 30_000)
  190. it('fails runaway log output explicitly while retaining a bounded prefix', async () => {
  191. const { runtime } = await setup({ maxOutputBytes: 300 })
  192. const result = await runtime.run({
  193. program: 'for (let i = 0; i < 1000; i++) console.log("spam line", i); return 1',
  194. bindings: [],
  195. })
  196. expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 300 bytes' })
  197. expect(result.value).toBeUndefined()
  198. expect(result.logs.length).toBeGreaterThan(0)
  199. expect(Buffer.byteLength(JSON.stringify(result.logs), 'utf8')).toBeLessThan(300)
  200. })
  201. it('retains a fitting prefix when one oversized log is the first output', async () => {
  202. const { runtime } = await setup({ maxOutputBytes: 96 })
  203. const result = await runtime.run({
  204. program: 'console.log(`start-${`😀"\\\\\\n`.repeat(100)}`); return null',
  205. bindings: [],
  206. })
  207. expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 96 bytes' })
  208. expect(result.logs).toHaveLength(1)
  209. expect(result.logs[0]?.startsWith('start-')).toBe(true)
  210. expect(Buffer.byteLength(JSON.stringify(result.logs), 'utf8')
  211. + Buffer.byteLength(JSON.stringify(result.error?.message), 'utf8')).toBeLessThanOrEqual(96)
  212. })
  213. it('fails an oversized return value without substituting a string', async () => {
  214. const { runtime } = await setup({ maxOutputBytes: 64 })
  215. const result = await runtime.run({ program: 'return "y".repeat(10_000)', bindings: [] })
  216. expect(result.value).toBeUndefined()
  217. expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 64 bytes' })
  218. })
  219. it('uses UTF-8 serialized bytes at the exact completion boundary', async () => {
  220. const exact = await setup({ maxOutputBytes: 7 })
  221. const exactResult = await exact.runtime.run({ program: 'return "€"', bindings: [] })
  222. // [] costs two bytes and JSON serialization of "€" costs five.
  223. expect(exactResult).toEqual({ logs: [], value: '€' })
  224. const over = await setup({ maxOutputBytes: 6 })
  225. const overResult = await over.runtime.run({ program: 'return "€"', bindings: [] })
  226. expect(overResult.error?.kind).toBe('output-limit')
  227. })
  228. it('accounts logs and completion in one exact combined ledger', async () => {
  229. // JSON(["abc"]) is seven bytes and JSON("xy") is four.
  230. const exact = await setup({ maxOutputBytes: 11 })
  231. expect(await exact.runtime.run({ program: 'console.log("abc"); return "xy"', bindings: [] }))
  232. .toEqual({ logs: ['abc'], value: 'xy' })
  233. const over = await setup({ maxOutputBytes: 10 })
  234. const result = await over.runtime.run({ program: 'console.log("abc"); return "xy"', bindings: [] })
  235. expect(result.value).toBeUndefined()
  236. expect(result.error?.kind).toBe('output-limit')
  237. expect(Buffer.byteLength(JSON.stringify(result.logs), 'utf8') + Buffer.byteLength(JSON.stringify(result.error?.message), 'utf8')).toBeLessThanOrEqual(10)
  238. })
  239. it('completes a program that awaits its write callback, capturing the chunk', async () => {
  240. // Node's write(chunk[, encoding][, callback]) contract: dropping the
  241. // callback would leave this promise pending until the wall ceiling and
  242. // misreport a completed program as a timeout.
  243. const { runtime } = await setup({ maxWallMs: 2_000 })
  244. const result = await runtime.run({
  245. program: 'await new Promise(resolve => process.stdout.write("flushed", resolve)); return "done"',
  246. bindings: [],
  247. })
  248. expect(result.error).toBeUndefined()
  249. expect(result.value).toBe('done')
  250. expect(result.logs).toContain('flushed')
  251. })
  252. it('returns a large JSON container exactly when the outer cap permits it', async () => {
  253. const { runtime } = await setup()
  254. const result = await runtime.run({ program: 'return new Array(50_000).fill(7)', bindings: [] })
  255. expect(result.error).toBeUndefined()
  256. expect(result.value).toEqual(new Array(50_000).fill(7))
  257. })
  258. it('returns an exact completion at the default 64 MiB combined boundary', async () => {
  259. const { runtime } = await setup()
  260. // [] costs two bytes and the JSON string contributes two quotes, leaving
  261. // exactly this many payload bytes under the 67_108_864-byte default.
  262. const result = await runtime.run({ program: 'return "x".repeat(67_108_860)', bindings: [] })
  263. expect(result.error).toBeUndefined()
  264. expect(result.logs).toEqual([])
  265. expect(result.value).toHaveLength(67_108_860)
  266. }, 60_000)
  267. it('fails one byte over the default 64 MiB combined boundary', async () => {
  268. const { runtime } = await setup()
  269. const result = await runtime.run({ program: 'return "x".repeat(67_108_861)', bindings: [] })
  270. expect(result.value).toBeUndefined()
  271. expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 67108864 bytes' })
  272. }, 60_000)
  273. it('accounts pipe writes that bypass the patched write slot in the same outer ledger', async () => {
  274. const { runtime } = await setup({ maxOutputBytes: 80 })
  275. const result = await runtime.run({
  276. // The prototype write bypasses the patched instance and reaches the real pipe. Pauses keep
  277. // writes in separate chunks and let both reach the host before settlement.
  278. program: `
  279. const write = (text) => Object.getPrototypeOf(process.stdout).write.call(process.stdout, text);
  280. write('a'.repeat(20));
  281. await new Promise(resolve => setTimeout(resolve, 150));
  282. write('b'.repeat(100));
  283. await new Promise(resolve => setTimeout(resolve, 100));
  284. return 1;
  285. `,
  286. bindings: [],
  287. })
  288. expect(result.error?.kind).toBe('output-limit')
  289. expect(result.logs).toContain('a'.repeat(20))
  290. expect(result.logs[1]?.length).toBeGreaterThan(0)
  291. expect('b'.repeat(100).startsWith(result.logs[1] ?? '')).toBe(true)
  292. }, 15_000)
  293. })
  294. describe('WorkerCodeRuntime — hostile programs (real workers)', () => {
  295. it('survives forged port traffic: unknown binding names, duplicate ids, junk shapes', async () => {
  296. const { runtime } = await setup()
  297. const result = await runtime.run({
  298. program: `
  299. const { parentPort } = await import('node:worker_threads');
  300. parentPort.postMessage({ type: 'call', id: 7777, global: 'tools', name: 'missing', args: {} });
  301. parentPort.postMessage({ type: 'call', id: 7777, global: 'tools', name: 'missing', args: {} });
  302. parentPort.postMessage({ type: 'call', id: 7778, global: 'tools', name: 'constructor', args: {} });
  303. parentPort.postMessage({ type: 'junk' });
  304. return await tools.real({});
  305. `,
  306. bindings: tools({ real: async () => 'still-works' }),
  307. })
  308. expect(result.error).toBeUndefined()
  309. expect(result.value).toBe('still-works')
  310. })
  311. it('survives arbitrary junk on the port: non-objects, junk types, malformed calls, logs, and dones', async () => {
  312. const { runtime } = await setup()
  313. const result = await runtime.run({
  314. program: `
  315. const { parentPort } = await import('node:worker_threads');
  316. for (const junk of [
  317. null, 42, 'junk', [],
  318. { type: 'nope' },
  319. { type: 'call' },
  320. { type: 'call', id: 'x', global: 'tools', name: 'real', args: {} },
  321. { type: 'call', id: 1e9, global: 7, name: 'real', args: {} },
  322. { type: 'call', id: 1e9, global: 'tools', name: 7, args: {} },
  323. { type: 'log' },
  324. { type: 'log', text: null },
  325. { type: 'log', text: 7 },
  326. { type: 'log', text: {} },
  327. { type: 'done', error: 5 },
  328. { type: 'done', error: { kind: 'exception', message: 5 } },
  329. { type: 'done', error: { kind: 'invented', message: 'bad kind' } },
  330. ]) parentPort.postMessage(junk);
  331. return await tools.real({});
  332. `,
  333. bindings: tools({ real: async () => 'still-works' }),
  334. })
  335. expect(result.error).toBeUndefined()
  336. expect(result.value).toBe('still-works')
  337. expect(result.logs).toEqual([])
  338. })
  339. it('fails forged log floods and forged done values through the same outer cap', async () => {
  340. const { runtime } = await setup({ maxOutputBytes: 200 })
  341. const result = await runtime.run({
  342. // Forged messages bypass the worker-side LogBuffer and completion check
  343. // entirely — only the host-side ledger and re-cap stand between model
  344. // code and an unbounded result.
  345. program: `
  346. const { parentPort } = await import('node:worker_threads');
  347. for (let i = 0; i < 50; i++) parentPort.postMessage({ type: 'log', text: 'F'.repeat(100), forged: true });
  348. parentPort.postMessage({ type: 'done', value: 'V'.repeat(100000) });
  349. for (;;) {}
  350. `,
  351. bindings: [],
  352. })
  353. expect(result.value).toBeUndefined()
  354. expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 200 bytes' })
  355. expect(Buffer.byteLength(JSON.stringify(result.logs), 'utf8')).toBeLessThan(200)
  356. })
  357. it('drops a malformed forged done carrying both value and error', async () => {
  358. const { runtime } = await setup()
  359. const result = await runtime.run({
  360. program: `
  361. const { parentPort } = await import('node:worker_threads');
  362. parentPort.postMessage({ type: 'done', value: 'lied', error: { kind: 'exception', message: 'fake failure' } });
  363. return 'honest';
  364. `,
  365. bindings: [],
  366. })
  367. expect(result).toEqual({ logs: [], error: { kind: 'exception', message: 'fake failure' } })
  368. })
  369. it('turns forged over-limit error text into output-limit at the host', async () => {
  370. const { runtime } = await setup({ maxOutputBytes: 64 })
  371. const result = await runtime.run({
  372. program: `
  373. const { parentPort } = await import('node:worker_threads');
  374. parentPort.postMessage({ type: 'done', error: { kind: 'exception', message: '€'.repeat(1000) } });
  375. for (;;) {}
  376. `,
  377. bindings: [],
  378. })
  379. expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 64 bytes' })
  380. })
  381. it('answers a binding whose resolution is not lossless JSON with a typed failure reply', async () => {
  382. const { runtime } = await setup()
  383. const result = await runtime.run({
  384. program: 'try { await tools.bad({}) } catch (error) { return { name: error.name, toolName: error.toolName, message: error.message } }',
  385. bindings: tools({ bad: async () => (() => 1) }),
  386. })
  387. expect(result.value).toEqual({ name: 'ToolCallError', toolName: 'bad', message: 'binding resolution must be lossless JSON' })
  388. })
  389. it('rejects lossy binding arguments in the worker before invoking the host binding', async () => {
  390. const { runtime } = await setup()
  391. let calls = 0
  392. const result = await runtime.run({
  393. program: `
  394. const decorated = [1]; Object.defineProperty(decorated, 'extra', { value: true });
  395. const values = [new Date(), decorated, () => 1];
  396. const failures = [];
  397. for (const value of values) {
  398. try { await tools.never(value) } catch (error) {
  399. failures.push({ typed: error instanceof ToolCallError, name: error.name, toolName: error.toolName, message: error.message });
  400. }
  401. }
  402. return failures;
  403. `,
  404. bindings: tools({ never: async () => { calls += 1; return null } }),
  405. })
  406. expect(calls).toBe(0)
  407. expect(result.value).toEqual(new Array(3).fill({
  408. typed: true,
  409. name: 'ToolCallError',
  410. toolName: 'never',
  411. message: 'binding arguments must be lossless JSON',
  412. }))
  413. })
  414. it('contains throwing getters while snapshotting binding resolutions', async () => {
  415. const { runtime } = await setup()
  416. const result = await runtime.run({
  417. program: 'try { await tools.bad({}) } catch (error) { return { name: error.name, toolName: error.toolName, message: error.message } }',
  418. bindings: tools({ bad: async () => Object.defineProperty({}, 'bad', { enumerable: true, get() { throw new Error('getter exploded') } }) }),
  419. })
  420. expect(result.value).toEqual({ name: 'ToolCallError', toolName: 'bad', message: 'binding resolution must be lossless JSON' })
  421. })
  422. it('revalidates a forged lossy completion at the host boundary', async () => {
  423. const { runtime } = await setup()
  424. const result = await runtime.run({
  425. program: `
  426. const { parentPort } = await import('node:worker_threads');
  427. parentPort.postMessage({ type: 'done', value: -0 });
  428. for (;;) {}
  429. `,
  430. bindings: [],
  431. })
  432. expect(result).toEqual({ logs: [], error: { kind: 'invalid-output', message: 'program completion must be lossless JSON' } })
  433. })
  434. it('honors a forged worker-side output-limit signal', async () => {
  435. const { runtime } = await setup()
  436. const result = await runtime.run({
  437. program: `
  438. const { parentPort } = await import('node:worker_threads');
  439. parentPort.postMessage({ type: 'output-limit' });
  440. for (;;) {}
  441. `,
  442. bindings: [],
  443. })
  444. expect(result).toEqual({ logs: [], error: { kind: 'output-limit', message: 'outer output exceeded 67108864 bytes' } })
  445. })
  446. it('exposes binding names that collide with Object.prototype as ordinary functions', async () => {
  447. const { runtime } = await setup()
  448. const result = await runtime.run({
  449. program: 'return [await tools["__proto__"]({}), await tools["constructor"]({}), typeof tools["hasOwnProperty"]]',
  450. // Computed keys: a literal `'__proto__': …` entry would SET the record's
  451. // prototype instead of declaring a binding of that name.
  452. bindings: tools({ ['__proto__']: async () => 'proto-ok', ['constructor']: async () => 'ctor-ok' }),
  453. })
  454. expect(result.value).toEqual(['proto-ok', 'ctor-ok', 'undefined'])
  455. })
  456. })
  457. describe('WorkerCodeRuntime — seam misuse and lifecycle', () => {
  458. it('rejects invalid binding globals loudly (identifier, reserved word, duplicate, reserved injected globals)', async () => {
  459. const { runtime } = await setup()
  460. const cases: [string, RegExp][] = [
  461. ['not valid!', /not a usable identifier/],
  462. ['await', /not a usable identifier/],
  463. ['console', /duplicate binding global/],
  464. ['ToolCallError', /duplicate binding global/],
  465. ]
  466. for (const [global, message] of cases) {
  467. await expect(runtime.run({ program: 'return 1', bindings: [{ global, functions: {} }] })).rejects.toThrow(message)
  468. }
  469. await expect(runtime.run({
  470. program: 'return 1',
  471. bindings: [{ global: 'tools', functions: {} }, { global: 'tools', functions: {} }],
  472. })).rejects.toThrow(/duplicate binding global/)
  473. })
  474. it('rejects config values that are not positive numbers', async () => {
  475. const ctx = new Context()
  476. await expect(ctx.plugin(WorkerCodeRuntime, { computeMs: -1 })).rejects.toThrow(/positive number/)
  477. })
  478. it('requires maxOutputBytes to fit the smallest outer failure envelope', async () => {
  479. const ctx = new Context()
  480. await expect(ctx.plugin(WorkerCodeRuntime, { maxOutputBytes: 3 })).rejects.toThrow(/safe integer of at least 4/)
  481. await expect(ctx.plugin(WorkerCodeRuntime, { maxOutputBytes: 4.5 })).rejects.toThrow(/safe integer of at least 4/)
  482. })
  483. it('keeps runs isolated: no state survives from one run to the next', async () => {
  484. const { runtime } = await setup()
  485. await runtime.run({ program: 'globalThis.leak = "value"; return 1', bindings: [] })
  486. const second = await runtime.run({ program: 'return typeof globalThis.leak', bindings: [] })
  487. expect(second.value).toBe('undefined')
  488. })
  489. it('disposal aborts in-flight runs, awaits worker exit, and rejects later runs', async () => {
  490. const ctx = new Context()
  491. const fiber = await ctx.plugin(WorkerCodeRuntime)
  492. const runtime = ctx.codeRuntime as WorkerCodeRuntime
  493. const inflight: Promise<CodeRunResult> = runtime.run({ program: 'for (;;) {}', bindings: [] })
  494. // Give the worker a moment to actually start spinning.
  495. await new Promise(resolve => setTimeout(resolve, 200))
  496. await fiber.dispose()
  497. const result = await inflight
  498. expect(result.error).toEqual({ kind: 'abort', message: 'runtime disposed' })
  499. await expect(runtime.run({ program: 'return 1', bindings: [] })).rejects.toThrow(/after disposal/)
  500. }, 15_000)
  501. it('removes ctx.codeRuntime when the providing fiber disposes (HMR safety)', async () => {
  502. const ctx = new Context()
  503. const fiber = await ctx.plugin(WorkerCodeRuntime)
  504. expect(ctx.get('codeRuntime')).toBeInstanceOf(WorkerCodeRuntime)
  505. await fiber.dispose()
  506. expect(ctx.get('codeRuntime')).toBeUndefined()
  507. })
  508. })