subagent-spawn.spec.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. import { describe, expect, it } from 'vitest'
  2. import { Context, symbols, type EffectMeta } from 'cordis'
  3. import Loader from '@cordisjs/plugin-loader'
  4. import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent'
  5. import { SessionId } from '@deepseek-ai/dsh-session'
  6. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  7. import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
  8. import InvariantService from '@deepseek-ai/dsh-invariants'
  9. import * as SessionInvariant from '@deepseek-ai/dsh-session/invariant'
  10. import * as AgentInvariant from '@deepseek-ai/dsh-agent/invariant'
  11. import * as AgentLoopInvariant from '@deepseek-ai/dsh-agent-loop/invariant'
  12. import SubagentService, { type SubagentStartRequest } from '@deepseek-ai/dsh-subagent'
  13. import { MockAdapter, maxTokensResponse, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
  14. import * as spawn from '../src/index.ts'
  15. import { STRUCTURED_OUTPUT_TOOL } from '@deepseek-ai/dsh-subagent-inprocess'
  16. import { defineContentToolFixture } from '@deepseek-ai/dsh-tools'
  17. type Script = ConstructorParameters<typeof MockAdapter>[0]
  18. async function mountInvariants(ctx: Context): Promise<void> {
  19. await ctx.plugin(InvariantService)
  20. await ctx.plugin(SessionInvariant)
  21. await ctx.plugin(AgentInvariant)
  22. await ctx.plugin(AgentLoopInvariant)
  23. }
  24. /**
  25. * Drives the REAL spawn backend end-to-end: a real agent loop + a scripted mock
  26. * MODEL (the only mocked boundary) + the real SubagentService + the real
  27. * invariant service plus package companions (so a malformed child session log would fail the test).
  28. * The parent is a real config agent; the spawn provider creates a real child
  29. * agent on the same context and we assert its output.
  30. */
  31. async function setup(script: Script) {
  32. const ctx = new Context()
  33. const adapter = new MockAdapter(script)
  34. await mountAgentLoopTestDependencies(ctx)
  35. await mountInvariants(ctx)
  36. await ctx.plugin(AgentLoop, { agents: [] })
  37. await ctx.plugin(SubagentService)
  38. await ctx.plugin(spawn, { providerName: 'spawn' })
  39. ctx.llm.registerAdapter(['mock'], adapter)
  40. const parent = ctx.agentLoop.create(SessionId('parent'), { provider: 'mock', model: 'mock' })
  41. return { ctx, parent, adapter }
  42. }
  43. function text(blocks: { type: string; text?: string }[]): string {
  44. return blocks.filter(b => b.type === 'text').map(b => b.text).join('')
  45. }
  46. function start(ctx: Context, provider: string, request: Omit<SubagentStartRequest, 'signal'> & { signal?: AbortSignal }) {
  47. return ctx.subagents.start(provider, { signal: request.signal ?? new AbortController().signal, ...request })
  48. }
  49. /** Invoke the child lifecycle effect while its parent-owned setup is still unpublished. */
  50. function disposeChildLifecycle(parent: Agent): void {
  51. const lifecycle = [...parent.ctx.fiber._disposables]
  52. .find((dispose) => {
  53. const effect = (dispose as typeof dispose & { [symbols.effect]?: EffectMeta })[symbols.effect]
  54. return effect?.label.startsWith('agentLoop.lifecycle(') === true
  55. })
  56. if (lifecycle === undefined) throw new Error('child lifecycle effect not found')
  57. void lifecycle()
  58. }
  59. describe('dsh-subagent-spawn', () => {
  60. it('runs a fresh child to completion and returns its final assistant output', async () => {
  61. // One model call for the child: a plain text answer.
  62. const { ctx, parent } = await setup([textResponse('child answer')])
  63. const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'do X' }], parent })
  64. const result = await run.result
  65. expect(result.stopReason).toBe('completed')
  66. expect(text(result.output)).toBe('child answer')
  67. await run.dispose()
  68. })
  69. it('emits subagent/start only after the fresh child is published', async () => {
  70. const { ctx, parent } = await setup([textResponse('child answer')])
  71. let childAtStart: ReturnType<typeof ctx.agents.get>
  72. ctx.on('subagent/start', (info) => {
  73. if (info.provider === 'spawn') childAtStart = ctx.agents.get(info.id)
  74. })
  75. const starting = start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'do X' }], parent })
  76. // Creation is asynchronous; no lifecycle claim is made while the child is
  77. // still inside its unpublished setup transaction.
  78. expect(childAtStart).toBeUndefined()
  79. const run = await starting
  80. expect(childAtStart).toBe(ctx.agents.get(run.id))
  81. expect(childAtStart?.id).toBe(run.id)
  82. await run.result
  83. await run.dispose()
  84. })
  85. it('gives the child its OWN session (not the parent\'s), with parentSession lineage', async () => {
  86. const { ctx, parent } = await setup([textResponse('hi')])
  87. const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
  88. await run.result
  89. const child = ctx.agents.get(run.id)!
  90. expect(child.session.header.id).not.toBe(parent.session.header.id)
  91. expect(child.session.header.parentSession).toBe(parent.session.header.id)
  92. await run.dispose()
  93. })
  94. it('a fresh child does NOT inherit the parent conversation (its log starts empty before the prompt)', async () => {
  95. // Drive the parent through one real turn so it has history, THEN spawn.
  96. const { ctx, parent } = await setup([textResponse('parent turn'), textResponse('child sees nothing')])
  97. parent.followup({ content: [{ type: 'text', text: 'parent prompt' }], source: { kind: 'user' } })
  98. await parent.whenIdle()
  99. const parentEventCount = parent.session.events.length
  100. expect(parentEventCount).toBeGreaterThan(0)
  101. const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'child prompt' }], parent })
  102. await run.result
  103. const child = ctx.agents.get(run.id)!
  104. // The child's first user/message is its OWN prompt, not the parent's history.
  105. const firstUser = child.session.events.find(e => e.type === 'user/message')
  106. expect(firstUser).toBeDefined()
  107. await run.dispose()
  108. })
  109. it('disposes the child to quiescence (agent removed from the registry)', async () => {
  110. const { ctx, parent } = await setup([textResponse('x')])
  111. const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
  112. await run.result
  113. expect(ctx.agents.get(run.id)).toBeDefined()
  114. await run.dispose()
  115. // After dispose, the child is unregistered (the AgentHandle teardown ran).
  116. expect(ctx.agents.get(run.id)).toBeUndefined()
  117. })
  118. it('stamps child depth = parent depth + 1 (via the merged AgentOptions field)', async () => {
  119. const { ctx, parent } = await setup([textResponse('x')])
  120. expect(parent.options.subagentDepth).toBeUndefined()
  121. const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
  122. await run.result
  123. const child = ctx.agents.get(run.id)!
  124. expect(child.options.subagentDepth).toBe(1)
  125. await run.dispose()
  126. })
  127. it('refuses to spawn past maxDepth (depthLimit capability)', async () => {
  128. const { ctx, parent } = await setup([])
  129. // parent is depth 0, child would be depth 1 — cap at 0 forbids any child.
  130. await expect(start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent, maxDepth: 0 }))
  131. .rejects.toThrow('subagent depth 1 exceeds maxDepth 0')
  132. })
  133. it('maps a child that hit its token ceiling to stopReason "max-tokens"', async () => {
  134. const { ctx, parent } = await setup([maxTokensResponse('cut off')])
  135. const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
  136. const result = await run.result
  137. expect(result.stopReason).toBe('max-tokens')
  138. await run.dispose()
  139. })
  140. it('maps a child whose turn errored (script exhausted) to stopReason "error" with empty output', async () => {
  141. // Empty script: the child's first model call throws "script exhausted", the
  142. // turn ends `error`, and there is no assistant/message → empty output.
  143. const { ctx, parent } = await setup([])
  144. const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
  145. const result = await run.result
  146. expect(result.stopReason).toBe('error')
  147. expect(result.output).toEqual([])
  148. await run.dispose()
  149. })
  150. it('rejects without publishing when the request signal is already aborted', async () => {
  151. // An already-aborted signal emits no future event, so start must check it before listening and
  152. // settle aborted without running the child. The empty model script proves no turn occurs.
  153. const controller = new AbortController()
  154. controller.abort()
  155. const { ctx, parent } = await setup([])
  156. await expect(start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent, signal: controller.signal }))
  157. .rejects.toThrow('aborted before child publication')
  158. })
  159. it('same-tick cancellation rejects start and prevents child publication', async () => {
  160. // Same-tick cancellation must win before async factory publication: no child may become
  161. // visible, `started` must not fulfill, and the empty script proves no model turn occurs.
  162. const { ctx, parent } = await setup([])
  163. const beforeAgents = ctx.agents.list().length
  164. const beforeSessions = ctx.sessions.list().length
  165. const published: string[] = []
  166. ctx.on('session/created', () => void published.push('session/created'))
  167. ctx.on('agent/created', () => void published.push('agent/created'))
  168. ctx.on('agent/session-start', () => void published.push('agent/session-start'))
  169. ctx.on('subagent/start', () => void published.push('subagent/start'))
  170. ctx.on('subagent/end', () => void published.push('subagent/end'))
  171. const controller = new AbortController()
  172. const starting = start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent, signal: controller.signal })
  173. controller.abort('early')
  174. await expect(starting).rejects.toThrow()
  175. await Promise.resolve()
  176. expect(ctx.agents.list()).toHaveLength(beforeAgents)
  177. expect(ctx.sessions.list()).toHaveLength(beforeSessions)
  178. expect(published).toEqual([])
  179. })
  180. it('a cancel from agent/inbox/enqueue maps a no-turn child log to aborted', async () => {
  181. const { ctx, parent } = await setup([])
  182. const controller = new AbortController()
  183. ctx.on('agent/inbox/enqueue', () => { controller.abort('queued-window') })
  184. const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent, signal: controller.signal })
  185. const result = await run.result
  186. expect(result).toMatchObject({ stopReason: 'aborted', output: [] })
  187. const child = ctx.agents.get(run.id)!
  188. expect(child.session.events.some(event => event.type === 'turn/end')).toBe(false)
  189. await run.dispose()
  190. })
  191. it('cancelling a running child settles the run as aborted (the abort bridge + cancel())', async () => {
  192. // 'hang' makes the child's model stream one chunk then wait until aborted.
  193. const controller = new AbortController()
  194. const { ctx, parent } = await setup(['hang'])
  195. const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent, signal: controller.signal })
  196. // Let the child's turn start, then abort via the request signal (the
  197. // backend bridges it to child.cancel()).
  198. await new Promise(r => setTimeout(r, 30))
  199. controller.abort()
  200. const result = await run.result
  201. expect(result.stopReason).toBe('aborted')
  202. await run.dispose()
  203. })
  204. it('dispose cancels the child and reaches quiescence', async () => {
  205. const { ctx, parent } = await setup(['hang'])
  206. const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
  207. await new Promise(r => setTimeout(r, 30))
  208. await run.dispose()
  209. const result = await run.result
  210. expect(result.stopReason).toBe('aborted')
  211. })
  212. it('does not expose the optional runtime methods (sendMessage/resume) in this cut', async () => {
  213. const { ctx, parent } = await setup([textResponse('x')])
  214. const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
  215. expect('sendMessage' in run).toBe(false)
  216. expect('resume' in run).toBe(false)
  217. await run.result
  218. await run.dispose()
  219. })
  220. it('inherits the parent cwd into the child session', async () => {
  221. const { ctx } = await setup([textResponse('x')])
  222. // A parent WITH a cwd (config agents have none, so create one explicitly).
  223. const parentHandle = await ctx.agents.create({
  224. sessionId: SessionId('cwd-parent-session'),
  225. meta: { cwd: '/tmp/parent-workspace' },
  226. agentOptions: { provider: 'mock', model: 'mock' },
  227. })
  228. const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent: parentHandle.agent })
  229. await run.result
  230. const child = ctx.agents.get(run.id)!
  231. expect(child.session.header.cwd).toBe('/tmp/parent-workspace')
  232. await run.dispose()
  233. await parentHandle.dispose()
  234. })
  235. it('uses request.agentOptions.model when the parent has no model of its own', async () => {
  236. const { ctx } = await setup([textResponse('explicit model child')])
  237. // A parent with NO model (its own turns would need one supplied per-request).
  238. const parentHandle = await ctx.agents.create({
  239. sessionId: SessionId('modelless-parent-session'),
  240. agentOptions: {},
  241. })
  242. // The request supplies the child's model explicitly.
  243. const run = await start(ctx, 'spawn', {
  244. prompt: [{ type: 'text', text: 'p' }],
  245. parent: parentHandle.agent,
  246. agentOptions: { provider: 'mock', model: 'mock' },
  247. })
  248. const result = await run.result
  249. expect(result.stopReason).toBe('completed')
  250. expect(text(result.output)).toBe('explicit model child')
  251. await run.dispose()
  252. await parentHandle.dispose()
  253. })
  254. it('advertises every start-time capability (depthLimit, outputSchema, toolFilter, persona)', async () => {
  255. const { ctx } = await setup([])
  256. const provider = ctx.subagents.getProvider('spawn')!
  257. expect(provider.capabilities).toEqual({ outputSchema: true, depthLimit: true, toolFilter: true, persona: true })
  258. })
  259. it('unregisters the provider when its fiber is disposed (HMR safety)', async () => {
  260. const ctx = new Context()
  261. await ctx.plugin(SubagentService)
  262. await ctx.plugin(AgentRegistry)
  263. const fiber = await ctx.plugin(spawn, { providerName: 'spawn' })
  264. expect(ctx.subagents.list()).toEqual(['spawn'])
  265. await fiber.dispose()
  266. expect(ctx.subagents.list()).toEqual([])
  267. })
  268. it('captures structured output through the shipped plugin (driver runtime, plugin wiring)', async () => {
  269. const { ctx, parent } = await setup([
  270. toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 42 }),
  271. ])
  272. const run = await start(ctx, 'spawn', {
  273. prompt: [{ type: 'text', text: 'produce the answer' }],
  274. parent,
  275. outputSchema: { type: 'object', properties: { answer: { type: 'number' } }, required: ['answer'] },
  276. })
  277. const result = await run.result
  278. expect(result.stopReason).toBe('completed')
  279. expect(result.structured).toEqual({ answer: 42 })
  280. // Run-scoped runtime: the settle released the last acquisition.
  281. expect(ctx.tools.get(STRUCTURED_OUTPUT_TOOL)).toBeUndefined()
  282. await run.dispose()
  283. })
  284. it('a backend unload does not revoke an accepted holder-owned run', async () => {
  285. // Rebuild the stack by hand so we hold the backend's fiber.
  286. const ctx = new Context()
  287. const adapter = new MockAdapter(['hang'])
  288. await mountAgentLoopTestDependencies(ctx)
  289. await mountInvariants(ctx)
  290. await ctx.plugin(AgentLoop, { agents: [] })
  291. await ctx.plugin(SubagentService)
  292. const fiber = await ctx.plugin(spawn, { providerName: 'spawn' })
  293. ctx.llm.registerAdapter(['mock'], adapter)
  294. const parent = ctx.agentLoop.create(SessionId('parent'), { provider: 'mock', model: 'mock' })
  295. const controller = new AbortController()
  296. const run = await start(ctx, 'spawn', {
  297. prompt: [{ type: 'text', text: 'q' }],
  298. parent,
  299. signal: controller.signal,
  300. outputSchema: { type: 'object', properties: { a: { type: 'number' } } },
  301. })
  302. // Provider removal prevents new starts but the returned run belongs to its
  303. // holder and remains live.
  304. await new Promise(resolve => setTimeout(resolve, 30))
  305. await fiber.dispose()
  306. expect(ctx.subagents.getProvider('spawn')).toBeUndefined()
  307. expect(ctx.agents.get(run.id)).toBeDefined()
  308. controller.abort('test complete')
  309. const result = await run.result
  310. expect(result.stopReason).toBe('aborted')
  311. expect(ctx.tools.get(STRUCTURED_OUTPUT_TOOL)).toBeUndefined()
  312. await run.dispose()
  313. })
  314. it('a start racing an already-unloading backend cannot begin child creation', async () => {
  315. const ctx = new Context()
  316. await mountAgentLoopTestDependencies(ctx)
  317. await ctx.plugin(AgentLoop, { agents: [] })
  318. await ctx.plugin(SubagentService)
  319. const fiber = await ctx.plugin(spawn, { providerName: 'spawn' })
  320. const parent = ctx.agentLoop.create(SessionId('parent'), { provider: 'mock', model: 'mock' })
  321. const parentEffects = parent.ctx.fiber.getEffects().length
  322. const published: string[] = []
  323. ctx.on('session/created', () => void published.push('session/created'))
  324. ctx.on('agent/created', () => void published.push('agent/created'))
  325. const unloading = fiber.dispose()
  326. await unloading
  327. await expect(start(ctx, 'spawn', {
  328. prompt: [{ type: 'text', text: 'must never start' }], parent,
  329. })).rejects.toThrow(/no subagent provider/)
  330. expect(parent.ctx.fiber.getEffects()).toHaveLength(parentEffects)
  331. expect(published).toEqual([])
  332. })
  333. it('has the namespace-plugin export shape (no stray default)', () => {
  334. expect('default' in spawn).toBe(false)
  335. expect(spawn.name).toBe('subagent-spawn')
  336. expect(spawn.inject).toEqual(['subagents'])
  337. const loader = Object.create(Loader.prototype) as Loader
  338. const unwrapped = loader.unwrapExports(spawn) as Record<string, unknown>
  339. expect(unwrapped).toBe(spawn)
  340. expect(unwrapped.name).toBe('subagent-spawn')
  341. expect(unwrapped.inject).toEqual(['subagents'])
  342. expect(typeof unwrapped.apply).toBe('function')
  343. })
  344. describe('persona and toolFilter (the scoped child world)', () => {
  345. it('a per-child persona shadows the deployment persona in the child request only', async () => {
  346. const { ctx, parent, adapter } = await setup([
  347. textResponse('parent answer'),
  348. textResponse('child answer'),
  349. ])
  350. parent.followup({ content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } })
  351. await parent.whenIdle()
  352. const run = await start(ctx, 'spawn', {
  353. prompt: [{ type: 'text', text: 'do X' }],
  354. parent,
  355. persona: 'You are the tersest test runner.',
  356. })
  357. await run.result
  358. const childRequest = adapter.requests.at(-1)!
  359. expect(childRequest.system).toContain('You are the tersest test runner.')
  360. // The parent's earlier request carried no such persona.
  361. expect(adapter.requests[0]!.system ?? '').not.toContain('tersest test runner')
  362. await run.dispose()
  363. })
  364. it('toolFilter hides denied tools from the child prompt AND refuses their execution', async () => {
  365. const { ctx, parent, adapter } = await setup([
  366. // The child tries the denied tool anyway, then answers.
  367. toolCallResponse('c1', 'forbidden_tool', {}),
  368. textResponse('done'),
  369. ])
  370. ctx.tools.register(defineContentToolFixture({
  371. name: 'forbidden_tool', description: 'global', parameters: {},
  372. execute: () => Promise.resolve([{ type: 'text', text: 'ran' }]),
  373. }))
  374. const run = await start(ctx, 'spawn', {
  375. prompt: [{ type: 'text', text: 'do X' }],
  376. parent,
  377. toolFilter: { deny: ['forbidden_tool'] },
  378. })
  379. const result = await run.result
  380. expect(result.stopReason).toBe('completed')
  381. // Not advertised…
  382. const childRequest = adapter.requests[0]!
  383. expect((childRequest.tools ?? []).map(t => t.name)).not.toContain('forbidden_tool')
  384. // …and the attempted call executed as UNKNOWN_TOOL (visible in the log).
  385. const child = ctx.agents.get(run.id)!
  386. const toolResult = child.session.events.find(e => e.type === 'tool/result')!
  387. expect(JSON.stringify(toolResult.data)).toContain('unknown tool')
  388. await run.dispose()
  389. })
  390. it('an unknown toolFilter name fails the spawn loudly with no orphaned child', async () => {
  391. const { ctx, parent } = await setup([])
  392. const before = ctx.agents.list().length
  393. await expect(start(ctx, 'spawn', {
  394. prompt: [{ type: 'text', text: 'do X' }],
  395. parent,
  396. toolFilter: { deny: ['no_such_tool'] },
  397. })).rejects.toThrow(/unknown global tool "no_such_tool"/)
  398. expect(ctx.agents.list().length).toBe(before)
  399. })
  400. })
  401. it('spawning from a DISPOSING parent fails loud with no orphaned child (INACTIVE_EFFECT teaching error)', async () => {
  402. const { ctx } = await setup([])
  403. // A handle-owned parent we can dispose (config agents dispose with the loop fiber).
  404. const parentHandle = await ctx.agents.create({
  405. sessionId: SessionId('doomed-s'),
  406. agentOptions: { provider: 'mock', model: 'mock' },
  407. })
  408. await parentHandle.dispose()
  409. const before = ctx.agents.list().length
  410. const sessionsBefore = ctx.sessions.list().length
  411. const published: string[] = []
  412. ctx.on('session/created', () => void published.push('session/created'))
  413. ctx.on('agent/created', () => void published.push('agent/created'))
  414. ctx.on('agent/session-start', () => void published.push('agent/session-start'))
  415. await expect(start(ctx, 'spawn', {
  416. prompt: [{ type: 'text', text: 'do X' }],
  417. parent: parentHandle.agent,
  418. })).rejects.toThrow(/inactive context/)
  419. expect(ctx.agents.list().length).toBe(before)
  420. expect(ctx.sessions.list()).toHaveLength(sessionsBefore)
  421. expect(published).toEqual([])
  422. })
  423. it('parent disposal during the child setup transaction prevents every publication notification', async () => {
  424. const { ctx } = await setup([])
  425. const parentHandle = await ctx.agents.create({
  426. sessionId: SessionId('setup-race-parent-session'),
  427. agentOptions: { provider: 'mock', model: 'mock' },
  428. })
  429. const published: string[] = []
  430. ctx.on('session/created', () => void published.push('session/created'))
  431. ctx.on('agent/created', () => void published.push('agent/created'))
  432. ctx.on('agent/session-start', () => void published.push('agent/session-start'))
  433. let teardownStarted = false
  434. ctx.on('internal/plugin', (fiber) => {
  435. if (teardownStarted || fiber.name !== 'scope') return
  436. teardownStarted = true
  437. disposeChildLifecycle(parentHandle.agent)
  438. })
  439. const starting = start(ctx, 'spawn', {
  440. prompt: [{ type: 'text', text: 'must never run' }],
  441. parent: parentHandle.agent,
  442. })
  443. // The factory has entered its awaited unpublished setup transaction. The
  444. // parent context owns that transaction, so disposal wins without an
  445. // observer ever seeing the child.
  446. await expect(starting).rejects.toThrow(/owner disposed during setup|inactive context/)
  447. await parentHandle.dispose()
  448. expect(published).toEqual([])
  449. })
  450. })