workflow-workerthread.spec.ts 77 KB

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