workflow-workerthread.spec.ts 63 KB

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