workflow-workerthread.spec.ts 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { fileURLToPath } from 'node:url'
  3. import type { Worker } from 'node:worker_threads'
  4. import { Context } from 'cordis'
  5. import Loader from '@cordisjs/plugin-loader'
  6. import type { Agent } from '@deepseek-ai/dsh-agent'
  7. import SubagentService from '@deepseek-ai/dsh-subagent'
  8. import type { SubagentCapabilities, SubagentProvider, SubagentResult, SubagentRun, SubagentStartRequest } from '@deepseek-ai/dsh-subagent'
  9. import type { WorkflowMeta, WorkflowResult, WorkflowResultInfo, WorkflowRun, WorkflowRunInfo } from '@deepseek-ai/dsh-workflow'
  10. import * as workerEngineModule from '../src/index.ts'
  11. import WorkerWorkflowEngine, { type Config } from '../src/index.ts'
  12. import { HostToWorkerType, WorkerToHostType } from '../src/protocol.ts'
  13. import { SessionId } from '@deepseek-ai/dsh-session'
  14. /** A minimal parent stand-in: the engine only threads it through to the provider. */
  15. function fakeParent(): Agent {
  16. return { id: SessionId('workflow-parent'), options: {} } as unknown as Agent
  17. }
  18. // Allow cold worker startup on contended CI runners.
  19. vi.setConfig({ testTimeout: 30_000 })
  20. /**
  21. * Wait up to 10 seconds for CPU-bound worker startup or cross-thread delivery on contended CI.
  22. * Host reactions after an observed event use explicit tight overrides, so this generous startup
  23. * allowance cannot hide multi-second reap regressions.
  24. */
  25. function waitFor(assertion: () => void, timeout = 10_000): Promise<void> {
  26. return vi.waitFor(assertion, { timeout, interval: 50 })
  27. }
  28. /** The vm-context escape hatch, spelled once: real Worker tests use it to make the WORKER misbehave. */
  29. const ESCAPE = "globalThis.constructor.constructor('return process')()"
  30. /** One controllable child run: the test (or auto mode) settles it. */
  31. interface ControlledRun {
  32. request: SubagentStartRequest
  33. /** Fulfill the provider's async start with a ready child. */
  34. publish(): void
  35. /** Reject the provider's async start before ownership transfer. */
  36. rejectStart(error: unknown): void
  37. settle(result: SubagentResult): void
  38. rejectResult(error: unknown): void
  39. cancelled: string | undefined
  40. disposed: boolean
  41. disposeCalls: number
  42. }
  43. /**
  44. * A scripted in-test provider over the REAL SubagentService registry: `auto`
  45. * settles each run via the reply function on a microtask; `manual` piles runs
  46. * up in `runs` for the test to settle. A run aborts (settles `aborted`) when
  47. * the request signal fires, like the real in-process backends.
  48. */
  49. class StubProvider implements SubagentProvider {
  50. readonly capabilities: SubagentCapabilities = { outputSchema: true, depthLimit: true, toolFilter: true, persona: false }
  51. readonly inheritsParentContext = false
  52. readonly runs: ControlledRun[] = []
  53. constructor(
  54. readonly name: string,
  55. private readonly reply?: (request: SubagentStartRequest, index: number) => SubagentResult,
  56. private readonly disposeDelayMs = 0,
  57. private readonly deferStart = false,
  58. private readonly onAbortString?: (reason: string | undefined, index: number) => void,
  59. private readonly onSignalAbort?: (reason: unknown, index: number) => void,
  60. ) {}
  61. async start(request: SubagentStartRequest): Promise<SubagentRun> {
  62. const startGate = Promise.withResolvers<undefined>()
  63. const terminal = Promise.withResolvers<SubagentResult>()
  64. terminal.promise.catch(() => { /* provider owns early settlement until publication */ })
  65. let published = false
  66. const controlled: ControlledRun = {
  67. request,
  68. publish: () => { published = true; startGate.resolve(undefined) },
  69. rejectStart: (error) => { startGate.reject(error) },
  70. settle: (result) => { terminal.resolve(result) },
  71. rejectResult: (error) => { terminal.reject(error) },
  72. cancelled: undefined,
  73. disposed: false,
  74. disposeCalls: 0,
  75. }
  76. this.runs.push(controlled)
  77. const index = this.runs.length - 1
  78. request.signal.addEventListener('abort', () => {
  79. controlled.cancelled = String(request.signal.reason ?? 'cancelled')
  80. this.onAbortString?.(String(request.signal.reason ?? 'cancelled'), index)
  81. this.onSignalAbort?.(request.signal.reason, index)
  82. if (published) terminal.resolve({ output: [], stopReason: 'aborted' })
  83. else startGate.reject(new Error('child start aborted before publication'))
  84. }, { once: true })
  85. if (!this.deferStart) controlled.publish()
  86. if (this.reply) {
  87. const reply = this.reply
  88. queueMicrotask(() => { terminal.resolve(reply(request, index)) })
  89. }
  90. try {
  91. await startGate.promise
  92. } catch (error: unknown) {
  93. controlled.disposeCalls += 1
  94. controlled.disposed = true
  95. throw error
  96. }
  97. if (request.signal.aborted) throw new Error('child start aborted before publication')
  98. return {
  99. id: SessionId(`stub-child-${index}`),
  100. localAgent: undefined,
  101. result: terminal.promise,
  102. dispose: () => {
  103. controlled.disposeCalls += 1
  104. if (this.disposeDelayMs === 0) {
  105. controlled.disposed = true
  106. return Promise.resolve()
  107. }
  108. return new Promise<void>((resolve) => {
  109. setTimeout(() => {
  110. controlled.disposed = true
  111. resolve()
  112. }, this.disposeDelayMs)
  113. })
  114. },
  115. }
  116. }
  117. }
  118. /** Text-reply helper for auto providers. */
  119. function text(reply: string): SubagentResult {
  120. return { output: [{ type: 'text', text: reply }], stopReason: 'completed' }
  121. }
  122. interface SetupOptions {
  123. config?: Config
  124. reply?: (request: SubagentStartRequest, index: number) => SubagentResult
  125. manual?: boolean
  126. disposeDelayMs?: number
  127. deferStart?: boolean
  128. onChildAbortString?: (reason: string | undefined, index: number) => void
  129. onChildSignalAbort?: (reason: unknown, index: number) => void
  130. }
  131. async function setup(options?: SetupOptions) {
  132. const ctx = new Context()
  133. await ctx.plugin(SubagentService)
  134. const provider = new StubProvider(
  135. 'stub',
  136. options?.manual ? undefined : options?.reply ?? (() => text('stub reply')),
  137. options?.disposeDelayMs ?? 0,
  138. options?.deferStart ?? false,
  139. options?.onChildAbortString,
  140. options?.onChildSignalAbort,
  141. )
  142. ctx.subagents.registerProvider(provider)
  143. // A fixed concurrency ceiling: the auto-resolved default is machine-derived
  144. // (cores - 2, floored at 1), so tests that expect N children in flight
  145. // would wedge on small CI runners.
  146. const engineFiber = await ctx.plugin(WorkerWorkflowEngine, { provider: 'stub', maxConcurrentAgents: 8, ...options?.config })
  147. return { ctx, provider, parent: fakeParent(), engineFiber }
  148. }
  149. /** The standard test meta plus a body, spread into a start request. */
  150. function scripted(body: string, metaExtra?: Partial<WorkflowMeta>): { script: string; meta: WorkflowMeta } {
  151. return { script: body, meta: { name: 'test-flow', description: 'a test workflow', ...metaExtra } }
  152. }
  153. /** Start + await one run, disposing on the way out. */
  154. async function run(ctx: Context, parent: Agent, source: { script: string; meta: WorkflowMeta }, args?: unknown): Promise<WorkflowResult> {
  155. const handle = ctx.workflows.start({ ...source, parent, ...args !== undefined ? { args } : {} })
  156. try {
  157. return await handle.result
  158. } finally {
  159. await handle.dispose()
  160. }
  161. }
  162. describe('dsh-workflow-workerthread', () => {
  163. describe('script execution over a real worker thread', () => {
  164. it('runs a script end-to-end: agent() text results, phases, log, args, return value, events', async () => {
  165. const { ctx, parent, provider } = await setup({ reply: (_request, index) => text(`answer-${index}`) })
  166. const events: [string, unknown[]][] = []
  167. for (const name of ['workflow/start', 'workflow/phase', 'workflow/log', 'workflow/agent-start', 'workflow/agent-end', 'workflow/end'] as const) {
  168. ctx.on(name, (...payload: unknown[]) => { events.push([name, payload]) })
  169. }
  170. const result = await run(ctx, parent, scripted(`
  171. phase('Scan')
  172. log('starting with ' + args.files.length + ' files')
  173. const answers = await pipeline(args.files, (prev, item) => agent('read ' + item))
  174. phase('Report')
  175. return { answers, count: args.files.length }
  176. `, { phases: [{ title: 'Scan' }, { title: 'Report' }] }), { files: ['a.ts', 'b.ts'] })
  177. expect(result.stopReason).toBe('completed')
  178. expect(result.agentsStarted).toBe(2)
  179. expect(result.value).toEqual({ answers: ['answer-0', 'answer-1'], count: 2 })
  180. expect(provider.runs.every(r => r.disposed)).toBe(true)
  181. const names = events.map(([name]) => name)
  182. expect(names[0]).toBe('workflow/start')
  183. expect(names).toContain('workflow/phase')
  184. expect(names).toContain('workflow/log')
  185. expect(names.at(-1)).toBe('workflow/end')
  186. const info = events[0]![1][0] as WorkflowRunInfo
  187. expect(info.meta.name).toBe('test-flow')
  188. const end = events.at(-1)![1][1] as Record<string, unknown>
  189. expect(end).toEqual({ stopReason: 'completed', agentsStarted: 2 })
  190. expect('value' in end).toBe(false)
  191. })
  192. it('agent({schema, model}) forwards outputSchema and agentOptions to the provider across the thread', async () => {
  193. const { ctx, parent, provider } = await setup({
  194. reply: () => ({ output: [], structured: { files: ['x.ts', 'y.ts'] }, stopReason: 'completed' }),
  195. })
  196. const result = await run(ctx, parent, scripted(`
  197. const found = await agent('list files', { label: 'inventory', model: 'deepseek-v4-pro', schema: { type: 'object', properties: { files: { type: 'array', items: { type: 'string' } } }, required: ['files'] } })
  198. return { first: found.files[0], count: found.files.length }
  199. `))
  200. expect(result.value).toEqual({ first: 'x.ts', count: 2 })
  201. expect(provider.runs[0]!.request.outputSchema).toEqual({
  202. type: 'object',
  203. properties: { files: { type: 'array', items: { type: 'string' } } },
  204. required: ['files'],
  205. })
  206. expect(provider.runs[0]!.request.agentOptions).toEqual({ model: 'deepseek-v4-pro' })
  207. expect(provider.runs[0]!.request.label).toBe('inventory')
  208. expect(provider.runs[0]!.request.parent).toBeDefined()
  209. })
  210. it('agent({provider}) forwards provider-only agentOptions across the thread', async () => {
  211. const { ctx, parent, provider } = await setup()
  212. const result = await run(ctx, parent, scripted("return await agent('route me', { provider: 'openai' })"))
  213. expect(result.value).toBe('stub reply')
  214. expect(provider.runs[0]!.request.agentOptions).toEqual({ provider: 'openai' })
  215. })
  216. it('a start-request provider override selects every child without changing the engine default', async () => {
  217. const { ctx, parent, provider } = await setup()
  218. const selected = new StubProvider('selected', () => text('selected reply'))
  219. ctx.subagents.registerProvider(selected)
  220. const overridden = ctx.workflows.start({
  221. ...scripted("return await agent('route this run')"),
  222. parent,
  223. subagentProvider: 'selected',
  224. })
  225. expect((await overridden.result).value).toBe('selected reply')
  226. await overridden.dispose()
  227. expect(selected.runs).toHaveLength(1)
  228. expect(provider.runs).toHaveLength(0)
  229. const ordinary = await run(ctx, parent, scripted("return await agent('use the default')"))
  230. expect(ordinary.value).toBe('stub reply')
  231. expect(provider.runs).toHaveLength(1)
  232. })
  233. it('rejects invalid start-request provider routes before publishing a run', async () => {
  234. const { ctx, parent } = await setup()
  235. let starts = 0
  236. ctx.on('workflow/start', () => { starts += 1 })
  237. const messages: string[] = []
  238. for (const subagentProvider of ['', 'missing']) {
  239. let run: WorkflowRun | undefined
  240. let thrown: unknown
  241. try {
  242. run = ctx.workflows.start({
  243. ...scripted("return 'must not start'"),
  244. parent,
  245. subagentProvider,
  246. })
  247. } catch (error: unknown) {
  248. thrown = error
  249. }
  250. await run?.dispose()
  251. messages.push(thrown instanceof Error ? thrown.message : '')
  252. }
  253. expect(messages).toEqual([
  254. 'workflow subagentProvider must be a non-empty normalized string',
  255. 'no subagent provider registered for "missing"',
  256. ])
  257. expect(starts).toBe(0)
  258. })
  259. it('rejects invalid per-run total-agent caps before publishing a run', async () => {
  260. const { ctx, parent } = await setup({ config: { maxTotalAgents: 2 } })
  261. let starts = 0
  262. ctx.on('workflow/start', () => { starts += 1 })
  263. const errors: unknown[] = []
  264. for (const maxTotalAgents of [0, 1.5, Number.NaN, 3]) {
  265. try {
  266. const handle = ctx.workflows.start({
  267. ...scripted("return 'must not start'"),
  268. parent,
  269. maxTotalAgents,
  270. })
  271. await handle.dispose()
  272. } catch (error: unknown) {
  273. errors.push(error)
  274. }
  275. }
  276. expect(errors.slice(0, 3)).toEqual(Array(3).fill(expect.objectContaining({
  277. code: 'INVALID_ARGUMENT',
  278. message: 'workflow maxTotalAgents must be a positive safe integer',
  279. })))
  280. expect(errors[3]).toMatchObject({
  281. code: 'INVALID_ARGUMENT',
  282. message: 'workflow maxTotalAgents 3 exceeds the engine ceiling 2',
  283. })
  284. expect(starts).toBe(0)
  285. })
  286. it('enforces a per-run total-agent cap below the engine ceiling', async () => {
  287. const { ctx, parent } = await setup({ config: { maxTotalAgents: 2 } })
  288. const handle = ctx.workflows.start({
  289. ...scripted("await agent('first'); await agent('second'); return 'unreachable'"),
  290. parent,
  291. maxTotalAgents: 1,
  292. })
  293. const result = await handle.result
  294. expect(result.stopReason).toBe('error')
  295. expect(result.agentsStarted).toBe(1)
  296. expect(result.error).toContain('total agent cap (1)')
  297. await handle.dispose()
  298. })
  299. it('a fatal hook error inside the worker kills the script and reports the error', async () => {
  300. const { ctx, parent } = await setup()
  301. const result = await run(ctx, parent, scripted("return await parallel([() => agent('x', { isolation: 'worktree' })])"))
  302. expect(result.stopReason).toBe('error')
  303. expect(result.error).toContain('"isolation" is deferred')
  304. })
  305. it('rejects an unregistered configured provider before publishing a run', async () => {
  306. const { ctx, parent } = await setup({ config: { provider: 'nonexistent' } })
  307. let thrown: unknown
  308. try {
  309. ctx.workflows.start({ ...scripted("return 'must not start'"), parent })
  310. } catch (error: unknown) {
  311. thrown = error
  312. }
  313. expect(thrown).toMatchObject({
  314. code: 'AGENT_START',
  315. message: 'no subagent provider registered for "nonexistent"',
  316. })
  317. })
  318. it('waits for async provider start before announcing a result that settled early', async () => {
  319. const { ctx, parent, provider } = await setup({ manual: true, deferStart: true })
  320. const order: string[] = []
  321. ctx.on('workflow/agent-start', (_info, agent) => { order.push(`start:${agent.seq}`) })
  322. ctx.on('workflow/agent-end', (_info, agent) => { order.push(`end:${agent.outcome}`) })
  323. ctx.on('workflow/end', () => { order.push('run-end') })
  324. const handle = ctx.workflows.start({ ...scripted("return await agent('p')"), parent })
  325. await waitFor(() => { expect(provider.runs.length).toBe(1) })
  326. const early = text('accepted value')
  327. provider.runs[0]!.settle(early)
  328. // The provider still owns this early result while start is pending.
  329. await new Promise(resolve => setTimeout(resolve, 0))
  330. expect(order).toEqual([])
  331. provider.runs[0]!.publish()
  332. const result = await handle.result
  333. expect(result.value).toBe('accepted value')
  334. expect(order).toEqual(['start:1', 'end:completed', 'run-end'])
  335. await handle.dispose()
  336. expect(provider.runs[0]!.disposeCalls).toBe(1)
  337. })
  338. it('observes an early result rejection but sends ChildStarted before ChildFailed after start fulfills', async () => {
  339. const { ctx, parent, provider } = await setup({ manual: true, deferStart: true })
  340. const lifecycle: string[] = []
  341. ctx.on('workflow/agent-start', () => { lifecycle.push('start') })
  342. ctx.on('workflow/agent-end', (_info, agent) => { lifecycle.push(`end:${agent.outcome}`) })
  343. const handle = ctx.workflows.start({
  344. ...scripted("try { await agent('p'); return 'unreachable' } catch (e) { return { code: e.code, message: e.message } }"),
  345. parent,
  346. })
  347. const worker = (handle as unknown as { worker: { postMessage(message: unknown): void } }).worker
  348. const post = vi.spyOn(worker, 'postMessage')
  349. const childMessageTypes = (): HostToWorkerType[] => post.mock.calls
  350. .map(([message]) => (message as { type: HostToWorkerType }).type)
  351. .filter(type => type === HostToWorkerType.ChildStarted || type === HostToWorkerType.ChildFailed)
  352. await waitFor(() => { expect(provider.runs.length).toBe(1) })
  353. provider.runs[0]!.rejectResult(new Error('backend failed before publication'))
  354. await new Promise(resolve => setTimeout(resolve, 0))
  355. expect(childMessageTypes()).toEqual([])
  356. expect(lifecycle).toEqual([])
  357. provider.runs[0]!.publish()
  358. const result = await handle.result
  359. expect(result.value).toMatchObject({ code: 'AGENT_RESULT' })
  360. expect((result.value as { message: string }).message).toContain('backend failed before publication')
  361. expect(childMessageTypes()).toEqual([HostToWorkerType.ChildStarted, HostToWorkerType.ChildFailed])
  362. expect(lifecycle).toEqual(['start', 'end:failed'])
  363. post.mockRestore()
  364. await handle.dispose()
  365. })
  366. it('classifies provider start rejection as AGENT_START, drops an early result, and emits no false lifecycle pair', async () => {
  367. const { ctx, parent, provider } = await setup({ manual: true, deferStart: true })
  368. const lifecycle: string[] = []
  369. ctx.on('workflow/agent-start', () => { lifecycle.push('start') })
  370. ctx.on('workflow/agent-end', () => { lifecycle.push('end') })
  371. const handle = ctx.workflows.start({
  372. ...scripted("try { await agent('p'); return 'unreachable' } catch (e) { return { code: e.code, message: e.message } }"),
  373. parent,
  374. })
  375. await waitFor(() => { expect(provider.runs.length).toBe(1) })
  376. // ACP-style failure can settle result(error) before its session/publication
  377. // boundary rejects. Start rejection must dominate that buffered child outcome.
  378. provider.runs[0]!.settle({ output: [], stopReason: 'error' })
  379. await new Promise(resolve => setTimeout(resolve, 0))
  380. provider.runs[0]!.rejectStart(new Error('publication rolled back'))
  381. const result = await handle.result
  382. expect(result.value).toMatchObject({ code: 'AGENT_START' })
  383. expect((result.value as { message: string }).message).toContain('publication rolled back')
  384. expect(lifecycle).toEqual([])
  385. await waitFor(() => {
  386. expect(provider.runs[0]!.disposed).toBe(true)
  387. expect(provider.runs[0]!.disposeCalls).toBe(1)
  388. })
  389. await handle.dispose()
  390. expect(provider.runs[0]!.disposeCalls).toBe(1)
  391. })
  392. it('aborts a pending provider start once without publishing workflow lifecycle', async () => {
  393. const { ctx, parent, provider } = await setup({ manual: true, deferStart: true, config: { disposeGraceMs: 500 } })
  394. const lifecycle: string[] = []
  395. ctx.on('workflow/agent-start', () => { lifecycle.push('start') })
  396. ctx.on('workflow/agent-end', () => { lifecycle.push('end') })
  397. const handle = ctx.workflows.start({ ...scripted("return await agent('pending')"), parent })
  398. await waitFor(() => { expect(provider.runs.length).toBe(1) })
  399. const disposal = handle.dispose()
  400. await waitFor(() => {
  401. expect(provider.runs[0]!.cancelled).toBe('workflow disposed')
  402. expect(provider.runs[0]!.disposed).toBe(true)
  403. })
  404. // Ensure the host-driven disposal removed the registry entry before the
  405. // late start rejection; its callback must not invoke dispose again.
  406. await new Promise(resolve => setTimeout(resolve, 0))
  407. provider.runs[0]!.rejectStart(new Error('cancelled before publication'))
  408. const result = await handle.result
  409. await disposal
  410. expect(result.stopReason).toBe('cancelled')
  411. expect(lifecycle).toEqual([])
  412. expect(provider.runs[0]!.disposeCalls).toBe(1)
  413. })
  414. it('a child result REJECTION crosses back as a fatal AGENT_RESULT error (a broken provider is not a failed child)', async () => {
  415. const ctx = new Context()
  416. await ctx.plugin(SubagentService)
  417. const provider: SubagentProvider = {
  418. name: 'rejecting',
  419. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: false },
  420. inheritsParentContext: false,
  421. start: async () => ({
  422. id: SessionId('reject-child'),
  423. localAgent: undefined,
  424. result: Promise.reject(new Error('backend exploded')),
  425. dispose: () => Promise.resolve(),
  426. }),
  427. }
  428. ctx.subagents.registerProvider(provider)
  429. await ctx.plugin(WorkerWorkflowEngine, { provider: 'rejecting', maxConcurrentAgents: 2 })
  430. const result = await run(ctx, fakeParent(), scripted(`
  431. try { await agent('p'); return 'unreachable' } catch (e) { return { name: e.name, code: e.code, fatal: e.fatal, message: e.message } }
  432. `))
  433. expect(result.value).toMatchObject({ name: 'WorkflowError', code: 'AGENT_RESULT', fatal: true })
  434. expect((result.value as { message: string }).message).toContain('backend exploded')
  435. })
  436. it('maps a non-JSON ready-child result to fatal AGENT_RESULT instead of wedging the bridge', async () => {
  437. const { ctx, parent } = await setup({
  438. reply: () => ({ output: [], structured: () => { /* deliberately outside lossless JSON */ }, stopReason: 'completed' }),
  439. })
  440. const result = await run(ctx, parent, scripted(`
  441. try { await agent('p'); return 'unreachable' } catch (e) { return { code: e.code, message: e.message } }
  442. `))
  443. expect(result.value).toMatchObject({ code: 'AGENT_RESULT' })
  444. expect((result.value as { message: string }).message).toContain('workflow child result could not cross the worker boundary')
  445. })
  446. it('contains a non-JSON result even if the injected subagent service violates its normalization contract', async () => {
  447. // The real worker boundary must reject a non-JSON same-process result.
  448. const { ctx, parent } = await setup()
  449. const invalid = {
  450. output: [],
  451. structured: () => { /* deliberately outside lossless JSON */ },
  452. stopReason: 'completed',
  453. } as unknown as SubagentResult
  454. const start = vi.spyOn(ctx.subagents, 'start').mockResolvedValue({
  455. id: SessionId('raw-invalid-child'),
  456. localAgent: undefined,
  457. result: Promise.resolve(invalid),
  458. dispose: () => Promise.resolve(),
  459. })
  460. const result = await run(ctx, parent, scripted(`
  461. try { await agent('p'); return 'unreachable' } catch (e) { return { code: e.code, message: e.message } }
  462. `))
  463. expect(start).toHaveBeenCalledOnce()
  464. expect(result.value).toMatchObject({ code: 'AGENT_RESULT' })
  465. expect((result.value as { message: string }).message)
  466. .toContain('workflow child result could not cross the worker boundary')
  467. })
  468. it('a child whose dispose() throws synchronously cannot wedge the script (the host acks anyway)', async () => {
  469. const ctx = new Context()
  470. await ctx.plugin(SubagentService)
  471. const provider: SubagentProvider = {
  472. name: 'bad-dispose',
  473. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: false },
  474. inheritsParentContext: false,
  475. start: async () => ({
  476. id: SessionId('bad-dispose-child'),
  477. localAgent: undefined,
  478. result: Promise.resolve({ output: [{ type: 'text', text: 'fine' }], stopReason: 'completed' }),
  479. cancel: () => { /* settled already */ },
  480. dispose: () => { throw new Error('dispose exploded') },
  481. }),
  482. }
  483. ctx.subagents.registerProvider(provider)
  484. await ctx.plugin(WorkerWorkflowEngine, { provider: 'bad-dispose', maxConcurrentAgents: 2 })
  485. const result = await run(ctx, fakeParent(), scripted("return await agent('p')"))
  486. expect(result.stopReason).toBe('completed')
  487. expect(result.value).toBe('fine')
  488. })
  489. it('a child dispose() rejecting an UNRENDERABLE value still acks — the containment warn is total', async () => {
  490. const ctx = new Context()
  491. await ctx.plugin(SubagentService)
  492. const provider: SubagentProvider = {
  493. name: 'coercion-trap-dispose',
  494. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: false },
  495. inheritsParentContext: false,
  496. start: async () => ({
  497. id: SessionId('trap-child'),
  498. localAgent: undefined,
  499. result: Promise.resolve({ output: [{ type: 'text', text: 'fine' }], stopReason: 'completed' }),
  500. cancel: () => { /* settled already */ },
  501. // The rejection VALUE's own coercion throws: a warn built with bare
  502. // String(error) would itself throw, skipping the ChildDisposed ack
  503. // and wedging the script's finally until the grace/terminate path.
  504. // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- the non-Error rejection IS the scenario under test
  505. dispose: () => Promise.reject({ toString: () => { throw new Error('coercion trap') } }),
  506. }),
  507. }
  508. ctx.subagents.registerProvider(provider)
  509. await ctx.plugin(WorkerWorkflowEngine, { provider: 'coercion-trap-dispose', maxConcurrentAgents: 2 })
  510. const result = await run(ctx, fakeParent(), scripted("return await agent('p')"))
  511. expect(result.stopReason).toBe('completed')
  512. expect(result.value).toBe('fine')
  513. })
  514. it('the worker spawns with an EMPTY environment: an escaped script finds no ambient credentials', async () => {
  515. const { ctx, parent } = await setup()
  516. // A canary in the HARNESS process's env: with an inherited environment
  517. // the escape below would read it back (exactly how DEEPSEEK_API_KEY
  518. // would leak); env: {} in the spawn options is what keeps it out.
  519. process.env.WORKFLOW_ENV_CANARY = 'leak me'
  520. try {
  521. const result = await run(ctx, parent, scripted(`
  522. const proc = ${ESCAPE}
  523. return { canary: proc.env.WORKFLOW_ENV_CANARY ?? null, keys: Object.keys(proc.env).length }
  524. `))
  525. expect(result.stopReason).toBe('completed')
  526. expect(result.value).toEqual({ canary: null, keys: 0 })
  527. } finally {
  528. delete process.env.WORKFLOW_ENV_CANARY
  529. }
  530. })
  531. it('the unbuilt worker forwards exactly TSX_TSCONFIG_PATH through the scrub: the paths-map pin survives, secrets do not', async () => {
  532. const { ctx, parent } = await setup()
  533. // The ACP snapshot harness runs the parent with its cwd OUTSIDE the
  534. // repo and pins the repo tsconfig through this variable; the worker
  535. // must inherit the pin (or its dsh-* imports silently resolve to
  536. // unbuilt lib/ bundles) while every other variable stays scrubbed.
  537. const tsconfig = fileURLToPath(new URL('../../../../tsconfig.json', import.meta.url))
  538. process.env.TSX_TSCONFIG_PATH = tsconfig
  539. process.env.WORKFLOW_ENV_CANARY = 'leak me'
  540. try {
  541. const result = await run(ctx, parent, scripted(`
  542. const proc = ${ESCAPE}
  543. return { keys: Object.keys(proc.env), tsconfig: proc.env.TSX_TSCONFIG_PATH }
  544. `))
  545. expect(result.stopReason).toBe('completed')
  546. expect(result.value).toEqual({ keys: ['TSX_TSCONFIG_PATH'], tsconfig })
  547. } finally {
  548. delete process.env.TSX_TSCONFIG_PATH
  549. delete process.env.WORKFLOW_ENV_CANARY
  550. }
  551. })
  552. })
  553. describe('lifecycle: parse errors, cancellation, termination, disposal', () => {
  554. it('start() throws synchronously for invalid meta data or an unparseable body (host-side pre-checks)', async () => {
  555. const { ctx, parent } = await setup()
  556. // Meta is DATA — shape violations reject loud, every one named.
  557. expect(() => ctx.workflows.start({ script: 'return 1', meta: { name: '', description: 'd' }, parent })).toThrow(/meta\.name must be a non-empty string/)
  558. expect(() => ctx.workflows.start({ script: 'return 1', meta: { name: 'x', description: 'd', extra: 1 } as unknown as WorkflowMeta, parent })).toThrow(/META_INVALID|not a recognized field/)
  559. expect(() => ctx.workflows.start({ ...scripted('return ((('), parent })).toThrow(/does not parse/)
  560. // The likeliest authoring slip — a Claude Code-style meta header in the
  561. // body — gets a pointed message, not a bare SyntaxError.
  562. expect(() => ctx.workflows.start({ ...scripted("export const meta = { name: 'x', description: 'd' }\nreturn 1"), parent })).toThrow(/meta rides the `meta` request field/)
  563. })
  564. it('cancel() aborts in-flight children (signal AND cancel RPC) and settles the run cancelled', async () => {
  565. const { ctx, parent, provider } = await setup({ manual: true })
  566. const ends: unknown[] = []
  567. ctx.on('workflow/agent-end', (_info, agent) => { ends.push(agent) })
  568. const runEnds: WorkflowResultInfo[] = []
  569. ctx.on('workflow/end', (_info, result) => { runEnds.push(result) })
  570. const handle = ctx.workflows.start({ ...scripted("return await agent('long job')"), parent })
  571. await waitFor(() => { expect(provider.runs.length).toBe(1) })
  572. handle.cancel('user stopped it')
  573. const result = await handle.result
  574. expect(result.stopReason).toBe('cancelled')
  575. expect(result.error).toContain('user stopped it')
  576. await handle.dispose()
  577. expect(provider.runs[0]!.disposed).toBe(true)
  578. expect(ends).toEqual([expect.objectContaining({ seq: 1, outcome: 'cancelled' })])
  579. // workflow/end is an observer's only death signal: it fires for a
  580. // cancelled run too, mirroring the settled outcome data.
  581. expect(runEnds).toEqual([{ stopReason: 'cancelled', error: result.error, agentsStarted: result.agentsStarted }])
  582. })
  583. it('an already-aborted request signal cancels before the body ever runs (the go handshake holds it)', async () => {
  584. const { ctx, parent, provider } = await setup()
  585. const controller = new AbortController()
  586. controller.abort()
  587. const logs: string[] = []
  588. ctx.on('workflow/log', (_info, message) => { logs.push(message) })
  589. const handle = ctx.workflows.start({ ...scripted("log('ran')\nreturn 123"), parent, signal: controller.signal })
  590. const result = await handle.result
  591. expect(result.stopReason).toBe('cancelled')
  592. expect(result.value).toBeNull()
  593. expect(logs).toEqual([])
  594. expect(provider.runs.length).toBe(0)
  595. await handle.dispose()
  596. })
  597. it('cancel() right after start() cancels before the body runs; the signal aborting mid-run cancels like cancel()', async () => {
  598. const { ctx, parent, provider } = await setup({ manual: true })
  599. const first = ctx.workflows.start({ ...scripted("return await agent('never')"), parent })
  600. // No-reason cancel: the canonical default reason must ride the result.
  601. first.cancel()
  602. const firstResult = await first.result
  603. expect(firstResult.stopReason).toBe('cancelled')
  604. expect(firstResult.error).toContain('workflow cancelled')
  605. expect(provider.runs.length).toBe(0)
  606. await first.dispose()
  607. const controller = new AbortController()
  608. const second = ctx.workflows.start({ ...scripted("return await agent('job')"), parent, signal: controller.signal })
  609. await waitFor(() => { expect(provider.runs.length).toBe(1) })
  610. controller.abort()
  611. expect((await second.result).stopReason).toBe('cancelled')
  612. await second.dispose()
  613. })
  614. it('removes the exact external abort callback on first settlement or teardown', async () => {
  615. const { ctx, parent } = await setup()
  616. const settledController = new AbortController()
  617. const settledAdd = vi.spyOn(settledController.signal, 'addEventListener')
  618. const settledRemove = vi.spyOn(settledController.signal, 'removeEventListener')
  619. const completed = ctx.workflows.start({ ...scripted('return 123'), parent, signal: settledController.signal })
  620. const settledAbort = settledAdd.mock.calls.find(([type]) => type === 'abort')?.[1]
  621. expect(typeof settledAbort).toBe('function')
  622. await expect(completed.result).resolves.toMatchObject({ value: 123, stopReason: 'completed' })
  623. expect(settledRemove).toHaveBeenCalledWith('abort', settledAbort)
  624. const cancelAfterSettle = vi.spyOn(completed, 'cancel')
  625. settledController.abort()
  626. expect(cancelAfterSettle).not.toHaveBeenCalled()
  627. cancelAfterSettle.mockRestore()
  628. await completed.dispose()
  629. const manual = await setup({ manual: true })
  630. const teardownController = new AbortController()
  631. const teardownAdd = vi.spyOn(teardownController.signal, 'addEventListener')
  632. const teardownRemove = vi.spyOn(teardownController.signal, 'removeEventListener')
  633. const tornDown = manual.ctx.workflows.start({
  634. ...scripted("return await agent('job')"),
  635. parent: manual.parent,
  636. signal: teardownController.signal,
  637. })
  638. await waitFor(() => { expect(manual.provider.runs).toHaveLength(1) })
  639. const teardownAbort = teardownAdd.mock.calls.find(([type]) => type === 'abort')?.[1]
  640. expect(typeof teardownAbort).toBe('function')
  641. const disposing = tornDown.dispose()
  642. expect(teardownRemove).toHaveBeenCalledWith('abort', teardownAbort)
  643. await disposing
  644. })
  645. it('a child-start racing the host cancel is refused: no child starts after cancellation', async () => {
  646. const { ctx, parent, provider } = await setup({ manual: true })
  647. // Cancel from INSIDE the log listener: the worker has already posted
  648. // its child-start (queued right behind the log message), so the host
  649. // processes it with cancelReason set — the refusal arm no real-world
  650. // timing can hit reliably. (The closure runs only after `handle` below
  651. // is initialized — the listener fires on the worker's first message.)
  652. ctx.on('workflow/log', () => { handle.cancel('cancelled from the log listener') })
  653. const handle = ctx.workflows.start({ ...scripted("log('mark')\nreturn await agent('late')"), parent })
  654. const result = await handle.result
  655. expect(result.stopReason).toBe('cancelled')
  656. expect(provider.runs.length).toBe(0)
  657. await handle.dispose()
  658. })
  659. it('post-cancel narration is suppressed host-side, and completion racing a cancel reports cancelled', async () => {
  660. const { ctx, parent } = await setup()
  661. const narration: string[] = []
  662. ctx.on('workflow/log', (_info, message) => { narration.push(message) })
  663. ctx.on('workflow/phase', (_info, title) => { narration.push(`phase:${title}`) })
  664. const handle = ctx.workflows.start({
  665. // The sync spin keeps the worker's loop busy so the cancel message
  666. // cannot be processed before the script settles `completed` — the
  667. // worker posts a completed result that must LOSE to the in-flight
  668. // host cancellation. The trailing narration exercises host-side
  669. // suppression: posted pre-cancel-processing worker-side, arriving
  670. // post-cancel host-side.
  671. ...scripted(`
  672. log('started')
  673. const end = Date.now() + 1000
  674. while (Date.now() < end) {}
  675. phase('late phase')
  676. log('late log')
  677. return 'done'
  678. `),
  679. parent,
  680. })
  681. await waitFor(() => { expect(narration).toContain('started') })
  682. handle.cancel('raced the completion')
  683. const result = await handle.result
  684. expect(result.stopReason).toBe('cancelled')
  685. expect(result.error).toContain('raced the completion')
  686. expect(narration).toEqual(['started'])
  687. await handle.dispose()
  688. }, 15_000)
  689. it('cancel() force-settles a script parked on a promise no hook owns, and TERMINATES its worker', async () => {
  690. const { ctx, parent } = await setup({ config: { provider: 'stub', disposeGraceMs: 50 } })
  691. const runEnds: WorkflowResultInfo[] = []
  692. ctx.on('workflow/end', (_info, result) => { runEnds.push(result) })
  693. const handle = ctx.workflows.start({
  694. ...scripted("await new Promise(() => {})\nreturn 'unreachable'"),
  695. parent,
  696. })
  697. handle.cancel('user aborted')
  698. const result = await handle.result
  699. expect(result.stopReason).toBe('cancelled')
  700. expect(result.error).toContain('user aborted')
  701. // The grace force-settle fires workflow/end exactly like an ordinary
  702. // settlement — a terminated script's death still reaches observers.
  703. expect(runEnds).toEqual([{ stopReason: 'cancelled', error: result.error, agentsStarted: 0 }])
  704. await handle.dispose()
  705. })
  706. it('dispose() on a stuck script returns within the grace instead of hanging (result settles cancelled)', async () => {
  707. const { ctx, parent } = await setup({ config: { provider: 'stub', disposeGraceMs: 50 } })
  708. const handle = ctx.workflows.start({
  709. ...scripted("await new Promise(() => {})\nreturn 'unreachable'"),
  710. parent,
  711. })
  712. const before = Date.now()
  713. await handle.dispose()
  714. expect(Date.now() - before).toBeLessThan(2000)
  715. const result = await handle.result
  716. expect(result.stopReason).toBe('cancelled')
  717. })
  718. it('dispose() is idempotent and settles cleanly after a completed run', async () => {
  719. const { ctx, parent } = await setup()
  720. const handle = ctx.workflows.start({ ...scripted('return 1'), parent })
  721. await handle.result
  722. await handle.dispose()
  723. await handle.dispose()
  724. })
  725. it('a settled run arms NO grace timer: disposing a completed run must not pin it for disposeGraceMs', async () => {
  726. // A distinctive grace so the spy can tell the cancel-path grace timer
  727. // apart from every other timeout in flight.
  728. const GRACE = 44_444
  729. const { ctx, parent } = await setup({ config: { provider: 'stub', disposeGraceMs: GRACE } })
  730. const handle = ctx.workflows.start({ ...scripted('return 1'), parent })
  731. await handle.result
  732. const spy = vi.spyOn(globalThis, 'setTimeout')
  733. try {
  734. await handle.dispose()
  735. // dispose()'s own bounded-wait sleep is the ONLY grace-sized timer
  736. // allowed here; before the settled guard, cancel() armed a second one
  737. // that nothing would ever clear (the run was already settled), keeping
  738. // the WorkerRun/Worker closure alive until the grace expired.
  739. const graceTimers = spy.mock.calls.filter(call => call[1] === GRACE)
  740. expect(graceTimers.length).toBe(1)
  741. } finally {
  742. spy.mockRestore()
  743. }
  744. })
  745. it('strays: children fired without await are aborted once the script settles, and dispose() waits for their disposal', async () => {
  746. const { ctx, parent, provider } = await setup({ manual: true, disposeDelayMs: 40 })
  747. const handle = ctx.workflows.start({
  748. ...scripted(`
  749. agent('stray')
  750. return 'done without awaiting'
  751. `),
  752. parent,
  753. })
  754. const result = await handle.result
  755. expect(result.stopReason).toBe('completed')
  756. await waitFor(() => { expect(provider.runs.length).toBe(1) })
  757. await handle.dispose()
  758. // Not a waitFor: by the time dispose() returns, the slow child disposal
  759. // must already be complete (host-side registry quiescence).
  760. expect(provider.runs[0]!.disposed).toBe(true)
  761. })
  762. it('result settlement reaps a registered stray even when the worker cannot relay disposal', async () => {
  763. const { ctx, parent, provider } = await setup({
  764. manual: true,
  765. config: { provider: 'stub', disposeGraceMs: 30_000 },
  766. })
  767. const handle = ctx.workflows.start({
  768. ...scripted("agent('stray')\nawait new Promise(() => {})"),
  769. parent,
  770. })
  771. await waitFor(() => { expect(provider.runs).toHaveLength(1) })
  772. // Claim the host result while the real worker remains wedged, so it can
  773. // send neither ChildDispose nor an exit. This leaves the accepted child
  774. // in the host registry when public disposal begins.
  775. const worker = (handle as unknown as { worker: Worker }).worker
  776. worker.emit('message', {
  777. type: WorkerToHostType.Result,
  778. result: { value: 'synthetic completion', stopReason: 'completed', agentsStarted: 1 },
  779. })
  780. await expect(handle.result).resolves.toMatchObject({ stopReason: 'completed' })
  781. await waitFor(() => { expect(provider.runs[0]!.disposed).toBe(true) }, 1000)
  782. const disposal = handle.dispose()
  783. await disposal
  784. expect(provider.runs[0]!.disposeCalls).toBe(1)
  785. await ctx.fiber.dispose()
  786. })
  787. it('the settle-reap fires the request signal too: a provider honoring ONLY the signal winds its stray down promptly', async () => {
  788. const ctx = new Context()
  789. await ctx.plugin(SubagentService)
  790. const aborted: string[] = []
  791. const provider: SubagentProvider = {
  792. name: 'signal-only',
  793. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: false },
  794. inheritsParentContext: false,
  795. start: async (request) => {
  796. let settle!: (result: SubagentResult) => void
  797. const result = new Promise<SubagentResult>((resolve) => { settle = resolve })
  798. request.signal.addEventListener('abort', () => {
  799. aborted.push(String(request.signal.reason))
  800. settle({ output: [], stopReason: 'aborted' })
  801. }, { once: true })
  802. return {
  803. id: SessionId('signal-only-child'),
  804. localAgent: undefined,
  805. result,
  806. dispose: () => Promise.resolve(),
  807. }
  808. },
  809. }
  810. ctx.subagents.registerProvider(provider)
  811. await ctx.plugin(WorkerWorkflowEngine, { provider: 'signal-only', maxConcurrentAgents: 2 })
  812. const handle = ctx.workflows.start({
  813. ...scripted(`
  814. agent('stray, never awaited')
  815. return 'done'
  816. `),
  817. parent: fakeParent(),
  818. })
  819. const result = await handle.result
  820. expect(result.stopReason).toBe('completed')
  821. // BEFORE dispose(): the settlement itself must have aborted the signal —
  822. // without it this child would stay live until dispose's terminate. This
  823. // is a HOST-PROMPTNESS claim, not a cold-start race — a tight explicit
  824. // bound (unlike the file default) so a multi-second reap regression
  825. // cannot pass by outlasting the wait.
  826. await waitFor(() => { expect(aborted).toEqual(['workflow settled']) }, 1000)
  827. await handle.dispose()
  828. })
  829. it('the settle-reap aborts a pending provider start before workflow/end', async () => {
  830. const { ctx, parent, provider } = await setup({ manual: true, deferStart: true })
  831. const childLifecycle: string[] = []
  832. let cancellationAtWorkflowEnd: string | undefined
  833. ctx.on('workflow/agent-start', () => { childLifecycle.push('start') })
  834. ctx.on('workflow/agent-end', () => { childLifecycle.push('end') })
  835. ctx.on('workflow/end', () => {
  836. cancellationAtWorkflowEnd = provider.runs[0]?.cancelled
  837. })
  838. const handle = ctx.workflows.start({
  839. ...scripted(`
  840. agent('start-pending stray')
  841. return 'done'
  842. `),
  843. parent,
  844. })
  845. const result = await handle.result
  846. expect(result.stopReason).toBe('completed')
  847. expect(provider.runs).toHaveLength(1)
  848. expect(provider.runs[0]!.request.signal?.aborted).toBe(true)
  849. expect(provider.runs[0]!.request.signal?.reason).toBe('workflow settled')
  850. expect(provider.runs[0]!.cancelled).toBe('workflow settled')
  851. expect(cancellationAtWorkflowEnd).toBe('workflow settled')
  852. expect(childLifecycle).toEqual([])
  853. await handle.dispose()
  854. expect(provider.runs[0]!.disposeCalls).toBe(1)
  855. })
  856. it('a duplicate Result after the terminal claim cannot repeat cleanup or rewrite the outcome', async () => {
  857. let signalAborts = 0
  858. const { ctx, parent, provider } = await setup({
  859. manual: true,
  860. onChildAbortString: (_reason, index) => { if (index === 0) signalAborts += 1 },
  861. })
  862. const handle = ctx.workflows.start({
  863. ...scripted("agent('stray')\nawait new Promise(() => {})"),
  864. parent,
  865. })
  866. await waitFor(() => { expect(provider.runs).toHaveLength(1) })
  867. const worker = (handle as unknown as { worker: Worker }).worker
  868. worker.emit('message', {
  869. type: WorkerToHostType.Result,
  870. result: { value: 'first', stopReason: 'completed', agentsStarted: 1 },
  871. })
  872. worker.emit('message', {
  873. type: WorkerToHostType.Result,
  874. result: { value: 'late', stopReason: 'completed', agentsStarted: 1 },
  875. })
  876. await expect(handle.result).resolves.toMatchObject({ value: 'first', stopReason: 'completed' })
  877. expect(signalAborts).toBe(1)
  878. await handle.dispose()
  879. expect(signalAborts).toBe(1)
  880. await ctx.fiber.dispose()
  881. })
  882. it('a grace-terminated worker reaps its child on exit without waiting for consumer dispose()', async () => {
  883. const { ctx, parent, provider } = await setup({
  884. manual: true,
  885. config: { provider: 'stub', maxConcurrentAgents: 2, disposeGraceMs: 100 },
  886. })
  887. const handle = ctx.workflows.start({
  888. // Let child-start cross, then make the worker unable to process its
  889. // Cancel message. Grace settles the result and terminates the thread;
  890. // that exit must independently own the host registry's disposal pass.
  891. ...scripted(`
  892. agent('survives until exit reap')
  893. for (let i = 0; i < 20; i++) await null
  894. const end = Date.now() + 1500
  895. while (Date.now() < end) {}
  896. return 'unreachable'
  897. `),
  898. parent,
  899. })
  900. await waitFor(() => { expect(provider.runs).toHaveLength(1) })
  901. handle.cancel('force termination')
  902. const result = await handle.result
  903. expect(result.stopReason).toBe('cancelled')
  904. // Deliberately assert before handle.dispose(): host-owned worker exit,
  905. // not consumer courtesy, is responsible for this resource guarantee.
  906. await waitFor(() => { expect(provider.runs[0]!.disposed).toBe(true) }, 1000)
  907. expect(provider.runs[0]!.disposeCalls).toBe(1)
  908. await handle.dispose()
  909. await ctx.fiber.dispose()
  910. }, 15_000)
  911. it('dispose() on a wedged worker host-drives child disposal inside the grace: it returns with the children DISPOSED, not with their teardown still in flight', async () => {
  912. const { ctx, parent, provider } = await setup({
  913. manual: true,
  914. disposeDelayMs: 40,
  915. config: { provider: 'stub', maxConcurrentAgents: 8, disposeGraceMs: 400 },
  916. })
  917. const handle = ctx.workflows.start({
  918. // Same shape as the wedged-cancel test above: the child's start RPC
  919. // reaches the host, then the script seizes its worker's loop, so the
  920. // worker can relay NO dispose RPC — the host's own dispose() drive is
  921. // the only thing that can start (and finish) this child's disposal
  922. // before the grace runs out.
  923. ...scripted(`
  924. agent('wedged child')
  925. for (let i = 0; i < 20; i++) await null
  926. const end = Date.now() + 1500
  927. while (Date.now() < end) {}
  928. return 'raced'
  929. `),
  930. parent,
  931. })
  932. await waitFor(() => { expect(provider.runs.length).toBe(1) })
  933. const before = Date.now()
  934. await handle.dispose()
  935. // Bounded by the grace (plus the terminate), never by the 1.5s spin.
  936. expect(Date.now() - before).toBeLessThan(1200)
  937. // Not a waitFor: dispose() resolving IS the quiescence claim — the slow
  938. // child disposal must be complete, not merely started (before the
  939. // host-driven drive, disposal only STARTED at the post-terminate reap,
  940. // so dispose() returned with it still in flight).
  941. expect(provider.runs[0]!.disposed).toBe(true)
  942. const result = await handle.result
  943. expect(result.stopReason).toBe('cancelled')
  944. }, 15_000)
  945. it('a live child disposed by the dispose() drive is disposed ONCE, and the worker\'s late dispose RPC still gets its ack (the script settles, not the grace)', async () => {
  946. const { ctx, parent, provider } = await setup({ manual: true })
  947. const handle = ctx.workflows.start({
  948. ...scripted(`
  949. await agent('long child')
  950. return 'unreachable'
  951. `),
  952. parent,
  953. })
  954. await waitFor(() => { expect(provider.runs.length).toBe(1) })
  955. const handleDispose = handle.dispose()
  956. const result = await handle.result
  957. // The script itself settled (the wrapper's own dispose RPC found the
  958. // child already reaped host-side and was acked) — a missing ack would
  959. // wedge the wrapper's finally until the 5s default grace force-settle.
  960. expect(result.stopReason).toBe('cancelled')
  961. expect(result.error).toContain('workflow disposed')
  962. await handleDispose
  963. expect(provider.runs[0]!.disposed).toBe(true)
  964. // The memo: the host drive and the worker's RPC share one disposal.
  965. expect(provider.runs[0]!.disposeCalls).toBe(1)
  966. })
  967. it('the grace force-settle pairs every stranded start: a host-synthesized cancelled agent-end lands before workflow/end', async () => {
  968. const { ctx, parent, provider } = await setup({ manual: true, config: { provider: 'stub', maxConcurrentAgents: 8, disposeGraceMs: 300 } })
  969. const ends: { seq: number; outcome: string }[] = []
  970. const order: string[] = []
  971. ctx.on('workflow/agent-start', (_info, agent) => { order.push(`start:${agent.seq}`) })
  972. ctx.on('workflow/agent-end', (_info, agent) => {
  973. ends.push({ seq: agent.seq, outcome: agent.outcome })
  974. order.push(`end:${agent.seq}`)
  975. })
  976. ctx.on('workflow/end', () => { order.push('run-end') })
  977. const handle = ctx.workflows.start({
  978. // 'slow' starts and its agent-start crosses to observers (the awaited
  979. // 'fast' call keeps the worker loop turning), then the script seizes
  980. // the loop: the wedged worker can never author slow's agent-end —
  981. // only the host's ledger can close the pair.
  982. ...scripted(`
  983. const p = agent('slow')
  984. await agent('fast')
  985. const end = Date.now() + 1500
  986. while (Date.now() < end) {}
  987. return 'raced'
  988. `),
  989. parent,
  990. })
  991. await waitFor(() => { expect(order.filter(entry => entry.startsWith('start:')).length).toBe(2) })
  992. const fast = provider.runs.find(run => (run.request.prompt[0] as { text?: string }).text === 'fast')!
  993. fast.settle(text('fast done'))
  994. handle.cancel('stop now')
  995. const result = await handle.result
  996. expect(result.stopReason).toBe('cancelled')
  997. // fast's end is the worker's own report; slow's is host-synthesized at
  998. // the force-settle — exactly one end per started seq, no third event.
  999. expect(ends).toEqual([
  1000. { seq: 2, outcome: 'completed' },
  1001. { seq: 1, outcome: 'cancelled' },
  1002. ])
  1003. // Both ends reached observers BEFORE workflow/end: a progress consumer
  1004. // can finalize its state at run-end without dangling agents.
  1005. expect(order.indexOf('run-end')).toBe(order.length - 1)
  1006. await handle.dispose()
  1007. }, 15_000)
  1008. it('graceful cancellation keeps pairing worker-authored: exactly one agent-end per start, nothing synthesized on top', async () => {
  1009. const { ctx, parent, provider } = await setup({ manual: true })
  1010. const ends: { seq: number; outcome: string }[] = []
  1011. const order: string[] = []
  1012. ctx.on('workflow/agent-end', (_info, agent) => {
  1013. ends.push({ seq: agent.seq, outcome: agent.outcome })
  1014. order.push(`end:${agent.seq}`)
  1015. })
  1016. ctx.on('workflow/end', () => { order.push('run-end') })
  1017. const handle = ctx.workflows.start({
  1018. ...scripted("await parallel([() => agent('a'), () => agent('b')])\nreturn 'unreachable'"),
  1019. parent,
  1020. })
  1021. await waitFor(() => { expect(provider.runs.length).toBe(2) })
  1022. handle.cancel('user stop')
  1023. const result = await handle.result
  1024. expect(result.stopReason).toBe('cancelled')
  1025. // The live worker reported both pairs itself; the ledger must not add
  1026. // a synthesized duplicate on any path that settles inside the grace.
  1027. expect(ends.map(end => end.outcome)).toEqual(['cancelled', 'cancelled'])
  1028. expect(new Set(ends.map(end => end.seq)).size).toBe(2)
  1029. expect(order.indexOf('run-end')).toBe(order.length - 1)
  1030. await handle.dispose()
  1031. })
  1032. })
  1033. describe('worker death', () => {
  1034. it('the first death signal closes admission to messages Node delivers before exit', async () => {
  1035. const { ctx, parent, provider } = await setup({ manual: true })
  1036. const phases: string[] = []
  1037. ctx.on('workflow/phase', (_info, title) => { phases.push(title) })
  1038. const handle = ctx.workflows.start({
  1039. ...scripted('await new Promise(() => {})'),
  1040. parent,
  1041. })
  1042. const worker = (handle as unknown as { worker: Worker }).worker
  1043. // Node may physically emit error -> queued message -> exit. Reproduce
  1044. // that ordering deterministically at the Worker event boundary: the
  1045. // late protocol data must not create work, narrate, or rewrite error.
  1046. worker.emit('error', new Error('synthetic error-before-message'))
  1047. worker.emit('message', { type: WorkerToHostType.Phase, title: 'late phase' })
  1048. worker.emit('message', {
  1049. type: WorkerToHostType.ChildStart,
  1050. callId: 999,
  1051. request: { prompt: 'late child' },
  1052. })
  1053. worker.emit('message', {
  1054. type: WorkerToHostType.Result,
  1055. result: { value: 'late', stopReason: 'completed', agentsStarted: 1 },
  1056. })
  1057. const result = await handle.result
  1058. expect(result.stopReason).toBe('error')
  1059. expect(result.error).toContain('synthetic error-before-message')
  1060. expect(provider.runs).toHaveLength(0)
  1061. expect(phases).toEqual([])
  1062. await handle.dispose()
  1063. await ctx.fiber.dispose()
  1064. })
  1065. it('refuses and disposes a provider run that becomes ready after its real worker dies', async () => {
  1066. const ctx = new Context()
  1067. await ctx.plugin(SubagentService)
  1068. const requested = Promise.withResolvers<SubagentStartRequest>()
  1069. const ready = Promise.withResolvers<SubagentRun>()
  1070. let disposeCalls = 0
  1071. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => ctx.logger)
  1072. const provider: SubagentProvider = {
  1073. name: 'late-ready',
  1074. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: false },
  1075. inheritsParentContext: false,
  1076. start: (request) => {
  1077. requested.resolve(request)
  1078. // Model a backend whose independent startup boundary cannot be
  1079. // interrupted promptly. The host must still reject ownership if the
  1080. // worker dies before this promise transfers the ready run.
  1081. return ready.promise
  1082. },
  1083. }
  1084. ctx.subagents.registerProvider(provider)
  1085. await ctx.plugin(WorkerWorkflowEngine, { provider: 'late-ready', maxConcurrentAgents: 1 })
  1086. const lifecycle: string[] = []
  1087. ctx.on('workflow/agent-start', () => { lifecycle.push('start') })
  1088. ctx.on('workflow/agent-end', () => { lifecycle.push('end') })
  1089. const handle = ctx.workflows.start({
  1090. ...scripted("return await agent('pending startup')"),
  1091. parent: fakeParent(),
  1092. })
  1093. const request = await requested.promise
  1094. const worker = (handle as unknown as { worker: Worker }).worker
  1095. // Kill the actual Worker while provider startup is independently
  1096. // pending. Death closes admission and aborts the shared signal, but this
  1097. // deliberately uncooperative provider still fulfills afterward.
  1098. await worker.terminate()
  1099. const result = await handle.result
  1100. expect(result.stopReason).toBe('error')
  1101. expect(result.error).toContain('exit code')
  1102. expect(request.signal.aborted).toBe(true)
  1103. expect(request.signal.reason).toBe('workflow worker gone')
  1104. ready.resolve({
  1105. id: SessionId('late-ready-child'),
  1106. localAgent: undefined,
  1107. result: Promise.resolve({ output: [], stopReason: 'aborted' }),
  1108. dispose: () => {
  1109. disposeCalls += 1
  1110. return Promise.reject(new Error('late ready dispose failed'))
  1111. },
  1112. })
  1113. await waitFor(() => {
  1114. expect(disposeCalls).toBe(1)
  1115. expect(warn).toHaveBeenCalledWith(expect.stringContaining('refused child dispose failed: Error: late ready dispose failed'))
  1116. }, 1000)
  1117. expect(lifecycle).toEqual([])
  1118. await handle.dispose()
  1119. expect(disposeCalls).toBe(1)
  1120. await ctx.fiber.dispose()
  1121. })
  1122. it('a worker that exits before settling reports an error result and reaps its children', async () => {
  1123. const ctx = new Context()
  1124. await ctx.plugin(SubagentService)
  1125. // The child's dispose() REJECTS on top of the worker death: the reap
  1126. // must contain it (warn, not crash) while still emptying the registry.
  1127. const signalAborts: unknown[] = []
  1128. const provider: SubagentProvider = {
  1129. name: 'doomed',
  1130. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: false },
  1131. inheritsParentContext: false,
  1132. start: async (request) => {
  1133. request.signal.addEventListener('abort', () => {
  1134. signalAborts.push(request.signal.reason)
  1135. // The death claim precedes the shared-signal fanout. This
  1136. // synchronous callback cannot turn death into cancellation.
  1137. handle.cancel('reentered from worker-death signal cleanup')
  1138. }, { once: true })
  1139. return {
  1140. id: SessionId('doomed-child'),
  1141. localAgent: undefined,
  1142. result: new Promise(() => { /* never settles; the reap is the teardown */ }),
  1143. dispose: () => Promise.reject(new Error('dispose exploded during reap')),
  1144. }
  1145. },
  1146. }
  1147. ctx.subagents.registerProvider(provider)
  1148. await ctx.plugin(WorkerWorkflowEngine, { provider: 'doomed', maxConcurrentAgents: 2 })
  1149. const runEnds: WorkflowResultInfo[] = []
  1150. ctx.on('workflow/end', (_info, result) => { runEnds.push(result) })
  1151. const handle = ctx.workflows.start({
  1152. // The stray child's start RPC reaches the host, then the script kills
  1153. // its own worker through the documented vm escape — the host must
  1154. // settle `error` with the exit diagnostics and wind the child down.
  1155. ...scripted(`
  1156. agent('doomed')
  1157. const proc = ${ESCAPE}
  1158. const st = globalThis.constructor.constructor('return setTimeout')()
  1159. await new Promise(resolve => st(resolve, 200))
  1160. proc.exit(7)
  1161. `),
  1162. parent: fakeParent(),
  1163. })
  1164. const result = await handle.result
  1165. expect(result.stopReason).toBe('error')
  1166. expect(result.error).toContain('exit code 7')
  1167. expect(result.agentsStarted).toBe(1)
  1168. // A worker death is a stop reason like any other: workflow/end fires
  1169. // with the error outcome — for a bus observer it is the only obituary.
  1170. expect(runEnds).toEqual([{ stopReason: 'error', error: result.error, agentsStarted: 1 }])
  1171. // Result already settled — this is the reap's promptness, not a
  1172. // cold-start race; tight explicit bound (see the helper's doc comment).
  1173. await waitFor(() => {
  1174. expect(signalAborts).toEqual(['workflow worker gone'])
  1175. }, 1000)
  1176. await Promise.resolve()
  1177. expect(result.stopReason).toBe('error')
  1178. await handle.dispose()
  1179. }, 15_000)
  1180. it('an uncaught exception inside the worker surfaces as an error result and reaps the in-flight child', async () => {
  1181. const { ctx, parent, provider } = await setup({ manual: true })
  1182. const handle = ctx.workflows.start({
  1183. ...scripted(`
  1184. agent('in flight when the worker dies')
  1185. const proc = ${ESCAPE}
  1186. const st = globalThis.constructor.constructor('return setTimeout')()
  1187. await new Promise(resolve => st(resolve, 200))
  1188. proc.nextTick(() => { throw new Error('worker blew up') })
  1189. await new Promise(() => {})
  1190. `),
  1191. parent,
  1192. })
  1193. const result = await handle.result
  1194. expect(result.stopReason).toBe('error')
  1195. expect(result.error).toContain('worker blew up')
  1196. // The reap wound the stray child down (cancel + a CLEAN dispose).
  1197. // Result already settled — this is the reap's promptness, not a
  1198. // cold-start race; tight explicit bound (see the helper's doc comment).
  1199. await waitFor(() => {
  1200. expect(provider.runs.length).toBe(1)
  1201. expect(provider.runs[0]!.disposed).toBe(true)
  1202. }, 1000)
  1203. await handle.dispose()
  1204. }, 15_000)
  1205. it('a worker death pairs every stranded start: the synthesized cancelled agent-end precedes the error workflow/end', async () => {
  1206. const { ctx, parent, provider } = await setup({ manual: true })
  1207. const ends: { seq: number; outcome: string }[] = []
  1208. const order: string[] = []
  1209. ctx.on('workflow/agent-start', (_info, agent) => { order.push(`start:${agent.seq}`) })
  1210. ctx.on('workflow/agent-end', (_info, agent) => {
  1211. ends.push({ seq: agent.seq, outcome: agent.outcome })
  1212. order.push(`end:${agent.seq}`)
  1213. })
  1214. ctx.on('workflow/end', () => { order.push('run-end') })
  1215. const handle = ctx.workflows.start({
  1216. // Same choreography as the force-settle pairing test, but the worker
  1217. // DIES (the documented vm escape) instead of being terminated: the
  1218. // exit path must close slow's pair from the ledger too. The escaped
  1219. // setTimeout lets the already-posted messages flush before the kill.
  1220. ...scripted(`
  1221. const p = agent('slow')
  1222. await agent('fast')
  1223. const proc = ${ESCAPE}
  1224. const st = globalThis.constructor.constructor('return setTimeout')()
  1225. await new Promise(resolve => st(resolve, 150))
  1226. proc.exit(7)
  1227. `),
  1228. parent,
  1229. })
  1230. await waitFor(() => { expect(order.filter(entry => entry.startsWith('start:')).length).toBe(2) })
  1231. const fast = provider.runs.find(run => (run.request.prompt[0] as { text?: string }).text === 'fast')!
  1232. fast.settle(text('fast done'))
  1233. const result = await handle.result
  1234. expect(result.stopReason).toBe('error')
  1235. expect(result.error).toContain('exit code 7')
  1236. expect(ends).toEqual([
  1237. { seq: 2, outcome: 'completed' },
  1238. { seq: 1, outcome: 'cancelled' },
  1239. ])
  1240. expect(order.indexOf('run-end')).toBe(order.length - 1)
  1241. await handle.dispose()
  1242. }, 15_000)
  1243. it('a dispose ack racing the worker death is dropped, not crashed (post after exit)', async () => {
  1244. // Slow child disposal: the ack resolves only AFTER the worker died, so
  1245. // it has nowhere to go and must be dropped silently (the workerGone
  1246. // guard in post()).
  1247. const { ctx, parent, provider } = await setup({ disposeDelayMs: 300 })
  1248. const handle = ctx.workflows.start({
  1249. // The STRAY child settles instantly, so its wrapper starts the slow
  1250. // host-side disposal concurrently while the script goes on to kill
  1251. // its own worker — the ack then resolves into a dead thread.
  1252. ...scripted(`
  1253. agent('stray, never awaited')
  1254. const proc = ${ESCAPE}
  1255. const st = globalThis.constructor.constructor('return setTimeout')()
  1256. await new Promise(resolve => st(resolve, 150))
  1257. proc.exit(5)
  1258. `),
  1259. parent,
  1260. })
  1261. const result = await handle.result
  1262. expect(result.stopReason).toBe('error')
  1263. expect(result.error).toContain('exit code 5')
  1264. // Result already settled — this is the reap's promptness (bounded
  1265. // above the mock's fixed 300ms dispose delay, not a cold-start race);
  1266. // tight explicit bound (see the helper's doc comment).
  1267. await waitFor(() => { expect(provider.runs[0]!.disposed).toBe(true) }, 1000)
  1268. await handle.dispose()
  1269. }, 15_000)
  1270. it('a worker death AFTER a cancel reports cancelled, not error', async () => {
  1271. const { ctx, parent } = await setup({ config: { provider: 'stub', disposeGraceMs: 60_000 } })
  1272. const handle = ctx.workflows.start({
  1273. ...scripted(`
  1274. const proc = ${ESCAPE}
  1275. const st = globalThis.constructor.constructor('return setTimeout')()
  1276. log('armed')
  1277. await new Promise(resolve => st(resolve, 400))
  1278. proc.exit(3)
  1279. `),
  1280. parent,
  1281. })
  1282. const logs: string[] = []
  1283. ctx.on('workflow/log', (_info, message) => { logs.push(message) })
  1284. await waitFor(() => { expect(logs).toContain('armed') })
  1285. handle.cancel('stop it')
  1286. // The grace is deliberately huge: only the worker's own death (exit 3,
  1287. // unreachable by the cancel — the script ignores hooks) settles this.
  1288. const result = await handle.result
  1289. expect(result.stopReason).toBe('cancelled')
  1290. expect(result.error).toContain('stop it')
  1291. await handle.dispose()
  1292. }, 15_000)
  1293. })
  1294. describe('service surface', () => {
  1295. it('run ids are unique and lifecycle meta is the run\'s borrowed immutable value', async () => {
  1296. const { ctx, parent } = await setup()
  1297. let eventMeta: WorkflowRunInfo | undefined
  1298. ctx.on('workflow/start', (info) => { eventMeta = info })
  1299. const first = ctx.workflows.start({ ...scripted('return 1'), parent })
  1300. const second = ctx.workflows.start({ ...scripted('return 2'), parent })
  1301. expect(first.id).not.toBe(second.id)
  1302. expect(eventMeta!.meta).toBe(second.meta)
  1303. expect(second.meta.name).toBe('test-flow')
  1304. await Promise.all([first.result, second.result])
  1305. await first.dispose()
  1306. await second.dispose()
  1307. })
  1308. it('unregisters ctx.workflows when the engine fiber is disposed (HMR safety)', async () => {
  1309. const ctx = new Context()
  1310. await ctx.plugin(SubagentService)
  1311. const fiber = await ctx.plugin(WorkerWorkflowEngine, {})
  1312. expect(ctx.get('workflows')).toBeDefined()
  1313. await fiber.dispose()
  1314. expect(ctx.get('workflows')).toBeUndefined()
  1315. })
  1316. it('keeps a holder-owned run usable when the engine unloads before its child starts', async () => {
  1317. const { ctx, parent, provider, engineFiber } = await setup({ reply: () => text('survived reload') })
  1318. let handle!: ReturnType<typeof ctx.workflows.start>
  1319. const holder = await ctx.plugin(Object.assign((inner: Context) => {
  1320. handle = inner.workflows.start({ ...scripted("return await agent('after reload')"), parent })
  1321. }, { inject: ['workflows'] }))
  1322. try {
  1323. // A real worker cannot deliver child-start in the synchronous start()
  1324. // slice. Unload the provider before that message arrives: the returned
  1325. // run belongs to `holder`, not to the engine fiber being reloaded.
  1326. expect(provider.runs).toHaveLength(0)
  1327. await engineFiber.dispose()
  1328. expect(ctx.get('workflows')).toBeUndefined()
  1329. await expect(handle.result).resolves.toEqual({
  1330. value: 'survived reload',
  1331. stopReason: 'completed',
  1332. agentsStarted: 1,
  1333. })
  1334. expect(provider.runs).toHaveLength(1)
  1335. } finally {
  1336. await handle.dispose()
  1337. await holder.dispose()
  1338. await ctx.fiber.dispose()
  1339. }
  1340. })
  1341. it('has the class-plugin export shape (default = the engine service class)', () => {
  1342. expect(workerEngineModule.default).toBe(WorkerWorkflowEngine)
  1343. expect('WorkerWorkflowEngine' in workerEngineModule).toBe(false)
  1344. const loader = Object.create(Loader.prototype) as Loader
  1345. const unwrapped: unknown = loader.unwrapExports(workerEngineModule)
  1346. expect(unwrapped).toBe(WorkerWorkflowEngine)
  1347. })
  1348. })
  1349. })