workflow-workerthread.spec.ts 64 KB

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