subagent-spawn.spec.ts 23 KB

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