workflow-workerthread.spec.ts 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287
  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('a worker that exits before settling reports an error result and reaps its children', async () => {
  976. const ctx = new Context()
  977. await ctx.plugin(SubagentService)
  978. // The child's dispose() REJECTS on top of the worker death: the reap
  979. // must contain it (warn, not crash) while still emptying the registry.
  980. const signalAborts: unknown[] = []
  981. const provider: SubagentProvider = {
  982. name: 'doomed',
  983. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: false },
  984. inheritsParentContext: false,
  985. start: async (request) => {
  986. request.signal.addEventListener('abort', () => {
  987. signalAborts.push(request.signal.reason)
  988. // The death claim precedes the shared-signal fanout. This
  989. // synchronous callback cannot turn death into cancellation.
  990. handle.cancel('reentered from worker-death signal cleanup')
  991. }, { once: true })
  992. return {
  993. id: AgentId('doomed-child'),
  994. result: new Promise(() => { /* never settles; the reap is the teardown */ }),
  995. dispose: () => Promise.reject(new Error('dispose exploded during reap')),
  996. }
  997. },
  998. }
  999. ctx.subagents.registerProvider(provider)
  1000. await ctx.plugin(WorkerWorkflowEngine, { provider: 'doomed', maxConcurrentAgents: 2 })
  1001. const runEnds: WorkflowResultInfo[] = []
  1002. ctx.on('workflow/end', (_info, result) => { runEnds.push(result) })
  1003. const handle = ctx.workflows.start({
  1004. // The stray child's start RPC reaches the host, then the script kills
  1005. // its own worker through the documented vm escape — the host must
  1006. // settle `error` with the exit diagnostics and wind the child down.
  1007. ...scripted(`
  1008. agent('doomed')
  1009. const proc = ${ESCAPE}
  1010. const st = globalThis.constructor.constructor('return setTimeout')()
  1011. await new Promise(resolve => st(resolve, 200))
  1012. proc.exit(7)
  1013. `),
  1014. parent: fakeParent(),
  1015. })
  1016. const result = await handle.result
  1017. expect(result.stopReason).toBe('error')
  1018. expect(result.error).toContain('exit code 7')
  1019. expect(result.agentsStarted).toBe(1)
  1020. // A worker death is a stop reason like any other: workflow/end fires
  1021. // with the error outcome — for a bus observer it is the only obituary.
  1022. expect(runEnds).toEqual([{ stopReason: 'error', error: result.error, agentsStarted: 1 }])
  1023. // Result already settled — this is the reap's promptness, not a
  1024. // cold-start race; tight explicit bound (see the helper's doc comment).
  1025. await waitFor(() => {
  1026. expect(signalAborts).toEqual(['workflow worker gone'])
  1027. }, 1000)
  1028. await Promise.resolve()
  1029. expect(result.stopReason).toBe('error')
  1030. await handle.dispose()
  1031. }, 15_000)
  1032. it('an uncaught exception inside the worker surfaces as an error result and reaps the in-flight child', async () => {
  1033. const { ctx, parent, provider } = await setup({ manual: true })
  1034. const handle = ctx.workflows.start({
  1035. ...scripted(`
  1036. agent('in flight when the worker dies')
  1037. const proc = ${ESCAPE}
  1038. const st = globalThis.constructor.constructor('return setTimeout')()
  1039. await new Promise(resolve => st(resolve, 200))
  1040. proc.nextTick(() => { throw new Error('worker blew up') })
  1041. await new Promise(() => {})
  1042. `),
  1043. parent,
  1044. })
  1045. const result = await handle.result
  1046. expect(result.stopReason).toBe('error')
  1047. expect(result.error).toContain('worker blew up')
  1048. // The reap wound the stray child down (cancel + a CLEAN dispose).
  1049. // Result already settled — this is the reap's promptness, not a
  1050. // cold-start race; tight explicit bound (see the helper's doc comment).
  1051. await waitFor(() => {
  1052. expect(provider.runs.length).toBe(1)
  1053. expect(provider.runs[0]!.disposed).toBe(true)
  1054. }, 1000)
  1055. await handle.dispose()
  1056. }, 15_000)
  1057. it('a worker death pairs every stranded start: the synthesized cancelled agent-end precedes the error workflow/end', async () => {
  1058. const { ctx, parent, provider } = await setup({ manual: true })
  1059. const ends: { seq: number; outcome: string }[] = []
  1060. const order: string[] = []
  1061. ctx.on('workflow/agent-start', (_info, agent) => { order.push(`start:${agent.seq}`) })
  1062. ctx.on('workflow/agent-end', (_info, agent) => {
  1063. ends.push({ seq: agent.seq, outcome: agent.outcome })
  1064. order.push(`end:${agent.seq}`)
  1065. })
  1066. ctx.on('workflow/end', () => { order.push('run-end') })
  1067. const handle = ctx.workflows.start({
  1068. // Same choreography as the force-settle pairing test, but the worker
  1069. // DIES (the documented vm escape) instead of being terminated: the
  1070. // exit path must close slow's pair from the ledger too. The escaped
  1071. // setTimeout lets the already-posted messages flush before the kill.
  1072. ...scripted(`
  1073. const p = agent('slow')
  1074. await agent('fast')
  1075. const proc = ${ESCAPE}
  1076. const st = globalThis.constructor.constructor('return setTimeout')()
  1077. await new Promise(resolve => st(resolve, 150))
  1078. proc.exit(7)
  1079. `),
  1080. parent,
  1081. })
  1082. await waitFor(() => { expect(order.filter(entry => entry.startsWith('start:')).length).toBe(2) })
  1083. const fast = provider.runs.find(run => (run.request.prompt[0] as { text?: string }).text === 'fast')!
  1084. fast.settle(text('fast done'))
  1085. const result = await handle.result
  1086. expect(result.stopReason).toBe('error')
  1087. expect(result.error).toContain('exit code 7')
  1088. expect(ends).toEqual([
  1089. { seq: 2, outcome: 'completed' },
  1090. { seq: 1, outcome: 'cancelled' },
  1091. ])
  1092. expect(order.indexOf('run-end')).toBe(order.length - 1)
  1093. await handle.dispose()
  1094. }, 15_000)
  1095. it('a dispose ack racing the worker death is dropped, not crashed (post after exit)', async () => {
  1096. // Slow child disposal: the ack resolves only AFTER the worker died, so
  1097. // it has nowhere to go and must be dropped silently (the workerGone
  1098. // guard in post()).
  1099. const { ctx, parent, provider } = await setup({ disposeDelayMs: 300 })
  1100. const handle = ctx.workflows.start({
  1101. // The STRAY child settles instantly, so its wrapper starts the slow
  1102. // host-side disposal concurrently while the script goes on to kill
  1103. // its own worker — the ack then resolves into a dead thread.
  1104. ...scripted(`
  1105. agent('stray, never awaited')
  1106. const proc = ${ESCAPE}
  1107. const st = globalThis.constructor.constructor('return setTimeout')()
  1108. await new Promise(resolve => st(resolve, 150))
  1109. proc.exit(5)
  1110. `),
  1111. parent,
  1112. })
  1113. const result = await handle.result
  1114. expect(result.stopReason).toBe('error')
  1115. expect(result.error).toContain('exit code 5')
  1116. // Result already settled — this is the reap's promptness (bounded
  1117. // above the mock's fixed 300ms dispose delay, not a cold-start race);
  1118. // tight explicit bound (see the helper's doc comment).
  1119. await waitFor(() => { expect(provider.runs[0]!.disposed).toBe(true) }, 1000)
  1120. await handle.dispose()
  1121. }, 15_000)
  1122. it('a worker death AFTER a cancel reports cancelled, not error', async () => {
  1123. const { ctx, parent } = await setup({ config: { provider: 'stub', disposeGraceMs: 60_000 } })
  1124. const handle = ctx.workflows.start({
  1125. ...scripted(`
  1126. const proc = ${ESCAPE}
  1127. const st = globalThis.constructor.constructor('return setTimeout')()
  1128. log('armed')
  1129. await new Promise(resolve => st(resolve, 400))
  1130. proc.exit(3)
  1131. `),
  1132. parent,
  1133. })
  1134. const logs: string[] = []
  1135. ctx.on('workflow/log', (_info, message) => { logs.push(message) })
  1136. await waitFor(() => { expect(logs).toContain('armed') })
  1137. handle.cancel('stop it')
  1138. // The grace is deliberately huge: only the worker's own death (exit 3,
  1139. // unreachable by the cancel — the script ignores hooks) settles this.
  1140. const result = await handle.result
  1141. expect(result.stopReason).toBe('cancelled')
  1142. expect(result.error).toContain('stop it')
  1143. await handle.dispose()
  1144. }, 15_000)
  1145. })
  1146. describe('service surface', () => {
  1147. it('run ids are unique and lifecycle meta is the run\'s borrowed immutable value', async () => {
  1148. const { ctx, parent } = await setup()
  1149. let eventMeta: WorkflowRunInfo | undefined
  1150. ctx.on('workflow/start', (info) => { eventMeta = info })
  1151. const first = ctx.workflows.start({ ...scripted('return 1'), parent })
  1152. const second = ctx.workflows.start({ ...scripted('return 2'), parent })
  1153. expect(first.id).not.toBe(second.id)
  1154. expect(eventMeta!.meta).toBe(second.meta)
  1155. expect(second.meta.name).toBe('test-flow')
  1156. await Promise.all([first.result, second.result])
  1157. await first.dispose()
  1158. await second.dispose()
  1159. })
  1160. it('unregisters ctx.workflows when the engine fiber is disposed (HMR safety)', async () => {
  1161. const ctx = new Context()
  1162. await ctx.plugin(SubagentService)
  1163. const fiber = await ctx.plugin(WorkerWorkflowEngine, {})
  1164. expect(ctx.get('workflows')).toBeDefined()
  1165. await fiber.dispose()
  1166. expect(ctx.get('workflows')).toBeUndefined()
  1167. })
  1168. it('keeps a holder-owned run usable when the engine unloads before its child starts', async () => {
  1169. const { ctx, parent, provider, engineFiber } = await setup({ reply: () => text('survived reload') })
  1170. let handle!: ReturnType<typeof ctx.workflows.start>
  1171. const holder = await ctx.plugin(Object.assign((inner: Context) => {
  1172. handle = inner.workflows.start({ ...scripted("return await agent('after reload')"), parent })
  1173. }, { inject: ['workflows'] }))
  1174. try {
  1175. // A real worker cannot deliver child-start in the synchronous start()
  1176. // slice. Unload the provider before that message arrives: the returned
  1177. // run belongs to `holder`, not to the engine fiber being reloaded.
  1178. expect(provider.runs).toHaveLength(0)
  1179. await engineFiber.dispose()
  1180. expect(ctx.get('workflows')).toBeUndefined()
  1181. await expect(handle.result).resolves.toEqual({
  1182. value: 'survived reload',
  1183. stopReason: 'completed',
  1184. agentsStarted: 1,
  1185. })
  1186. expect(provider.runs).toHaveLength(1)
  1187. } finally {
  1188. await handle.dispose()
  1189. await holder.dispose()
  1190. await ctx.fiber.dispose()
  1191. }
  1192. })
  1193. it('has the class-plugin export shape (default = the engine service class)', () => {
  1194. expect(workerEngineModule.default).toBe(WorkerWorkflowEngine)
  1195. const loader = Object.create(Loader.prototype) as Loader
  1196. const unwrapped: unknown = loader.unwrapExports(workerEngineModule)
  1197. expect(unwrapped).toBe(WorkerWorkflowEngine)
  1198. })
  1199. })
  1200. })