workflow-workerthread.spec.ts 64 KB

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