subagent-spawn.spec.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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('cancelling a running child settles the run as aborted (the abort bridge + cancel())', async () => {
  182. // 'hang' makes the child's model stream one chunk then wait until aborted.
  183. const controller = new AbortController()
  184. const { ctx, parent } = await setup(['hang'])
  185. const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent, signal: controller.signal })
  186. // Let the child's turn start, then abort via the request signal (the
  187. // backend bridges it to child.cancel()).
  188. await new Promise(r => setTimeout(r, 30))
  189. controller.abort()
  190. const result = await run.result
  191. expect(result.stopReason).toBe('aborted')
  192. await run.dispose()
  193. })
  194. it('dispose cancels the child and reaches quiescence', async () => {
  195. const { ctx, parent } = await setup(['hang'])
  196. const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
  197. await new Promise(r => setTimeout(r, 30))
  198. await run.dispose()
  199. const result = await run.result
  200. expect(result.stopReason).toBe('aborted')
  201. })
  202. it('a one-shot run exposes neither steer nor resume; continuable creation is a provider capability', async () => {
  203. const { ctx, parent } = await setup([textResponse('x')])
  204. const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
  205. // A run is one disposable foreground activation: it has no steering and no
  206. // cold resume. Continuable conversations never become a run — the
  207. // continuation manager drives them through the provider's
  208. // `prepareContinuable` capability instead.
  209. expect('steer' in run).toBe(false)
  210. expect('resume' in run).toBe(false)
  211. await run.result
  212. // The spawn provider DOES advertise continuable creation, and — because a
  213. // spawned child starts fresh — contributes no seed.
  214. const provider = ctx.subagents.getProvider('spawn')!
  215. expect(typeof provider.prepareContinuable).toBe('function')
  216. const spec = await provider.prepareContinuable!({
  217. sessionId: SessionId('continuable-child'),
  218. parent,
  219. signal: new AbortController().signal,
  220. })
  221. expect(spec.seed).toBeUndefined()
  222. await run.dispose()
  223. })
  224. it('inherits the parent cwd into the child session', async () => {
  225. const { ctx } = await setup([textResponse('x')])
  226. // A parent WITH a cwd (config agents have none, so create one explicitly).
  227. const parentHandle = await ctx.agents.create({
  228. sessionId: SessionId('cwd-parent-session'),
  229. meta: { cwd: '/tmp/parent-workspace' },
  230. agentOptions: { provider: 'mock', model: 'mock' },
  231. })
  232. const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent: parentHandle.agent })
  233. await run.result
  234. const child = ctx.agents.get(run.id)!
  235. expect(child.session.header.cwd).toBe('/tmp/parent-workspace')
  236. await run.dispose()
  237. await parentHandle.dispose()
  238. })
  239. it('uses request.agentOptions.model when the parent has no model of its own', async () => {
  240. const { ctx } = await setup([textResponse('explicit model child')])
  241. // A parent with NO model (its own turns would need one supplied per-request).
  242. const parentHandle = await ctx.agents.create({
  243. sessionId: SessionId('modelless-parent-session'),
  244. agentOptions: {},
  245. })
  246. // The request supplies the child's model explicitly.
  247. const run = await start(ctx, 'spawn', {
  248. prompt: [{ type: 'text', text: 'p' }],
  249. parent: parentHandle.agent,
  250. agentOptions: { provider: 'mock', model: 'mock' },
  251. })
  252. const result = await run.result
  253. expect(result.stopReason).toBe('completed')
  254. expect(text(result.output)).toBe('explicit model child')
  255. await run.dispose()
  256. await parentHandle.dispose()
  257. })
  258. it('advertises every start-time capability (depthLimit, outputSchema, toolFilter, persona)', async () => {
  259. const { ctx } = await setup([])
  260. const provider = ctx.subagents.getProvider('spawn')!
  261. expect(provider.capabilities).toEqual({ outputSchema: true, depthLimit: true, toolFilter: true, persona: true })
  262. })
  263. it('unregisters the provider when its fiber is disposed (HMR safety)', async () => {
  264. const ctx = new Context()
  265. await ctx.plugin(SubagentService)
  266. await ctx.plugin(AgentRegistry)
  267. const fiber = await ctx.plugin(spawn, { providerName: 'spawn' })
  268. expect(ctx.subagents.list()).toEqual(['spawn'])
  269. await fiber.dispose()
  270. expect(ctx.subagents.list()).toEqual([])
  271. })
  272. it('captures structured output through the shipped plugin (driver runtime, plugin wiring)', async () => {
  273. const { ctx, parent } = await setup([
  274. toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 42 }),
  275. ])
  276. const run = await start(ctx, 'spawn', {
  277. prompt: [{ type: 'text', text: 'produce the answer' }],
  278. parent,
  279. outputSchema: { type: 'object', properties: { answer: { type: 'number' } }, required: ['answer'] },
  280. })
  281. const result = await run.result
  282. expect(result.stopReason).toBe('completed')
  283. expect(result.structured).toEqual({ answer: 42 })
  284. // Run-scoped runtime: the settle released the last acquisition.
  285. expect(ctx.tools.get(STRUCTURED_OUTPUT_TOOL)).toBeUndefined()
  286. await run.dispose()
  287. })
  288. it('a backend unload does not revoke an accepted holder-owned run', async () => {
  289. // Rebuild the stack by hand so we hold the backend's fiber.
  290. const ctx = new Context()
  291. const adapter = new MockAdapter(['hang'])
  292. await mountAgentLoopTestDependencies(ctx)
  293. await mountInvariants(ctx)
  294. await ctx.plugin(AgentLoop, { agents: [] })
  295. await ctx.plugin(SubagentService)
  296. const fiber = await ctx.plugin(spawn, { providerName: 'spawn' })
  297. ctx.llm.registerAdapter(['mock'], adapter)
  298. const parent = ctx.agentLoop.create(SessionId('parent'), { provider: 'mock', model: 'mock' })
  299. const controller = new AbortController()
  300. const run = await start(ctx, 'spawn', {
  301. prompt: [{ type: 'text', text: 'q' }],
  302. parent,
  303. signal: controller.signal,
  304. outputSchema: { type: 'object', properties: { a: { type: 'number' } } },
  305. })
  306. // Provider removal prevents new starts but the returned run belongs to its
  307. // holder and remains live.
  308. await new Promise(resolve => setTimeout(resolve, 30))
  309. await fiber.dispose()
  310. expect(ctx.subagents.getProvider('spawn')).toBeUndefined()
  311. expect(ctx.agents.get(run.id)).toBeDefined()
  312. controller.abort('test complete')
  313. const result = await run.result
  314. expect(result.stopReason).toBe('aborted')
  315. expect(ctx.tools.get(STRUCTURED_OUTPUT_TOOL)).toBeUndefined()
  316. await run.dispose()
  317. })
  318. it('a start racing an already-unloading backend cannot begin child creation', async () => {
  319. const ctx = new Context()
  320. await mountAgentLoopTestDependencies(ctx)
  321. await ctx.plugin(AgentLoop, { agents: [] })
  322. await ctx.plugin(SubagentService)
  323. const fiber = await ctx.plugin(spawn, { providerName: 'spawn' })
  324. const parent = ctx.agentLoop.create(SessionId('parent'), { provider: 'mock', model: 'mock' })
  325. const parentEffects = parent.ctx.fiber.getEffects().length
  326. const published: string[] = []
  327. ctx.on('session/created', () => void published.push('session/created'))
  328. ctx.on('agent/created', () => void published.push('agent/created'))
  329. const unloading = fiber.dispose()
  330. await unloading
  331. await expect(start(ctx, 'spawn', {
  332. prompt: [{ type: 'text', text: 'must never start' }], parent,
  333. })).rejects.toThrow(/no subagent provider/)
  334. expect(parent.ctx.fiber.getEffects()).toHaveLength(parentEffects)
  335. expect(published).toEqual([])
  336. })
  337. it('has the namespace-plugin export shape (no stray default)', () => {
  338. expect('default' in spawn).toBe(false)
  339. expect(spawn.name).toBe('subagent-spawn')
  340. expect(spawn.inject).toEqual(['subagents'])
  341. const loader = Object.create(Loader.prototype) as Loader
  342. const unwrapped = loader.unwrapExports(spawn) as Record<string, unknown>
  343. expect(unwrapped).toBe(spawn)
  344. expect(unwrapped.name).toBe('subagent-spawn')
  345. expect(unwrapped.inject).toEqual(['subagents'])
  346. expect(typeof unwrapped.apply).toBe('function')
  347. })
  348. describe('persona and toolFilter (the scoped child world)', () => {
  349. it('a per-child persona shadows the deployment persona in the child request only', async () => {
  350. const { ctx, parent, adapter } = await setup([
  351. textResponse('parent answer'),
  352. textResponse('child answer'),
  353. ])
  354. parent.followup(createUserMessage({ content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }))
  355. await parent.whenIdle()
  356. const run = await start(ctx, 'spawn', {
  357. prompt: [{ type: 'text', text: 'do X' }],
  358. parent,
  359. persona: 'You are the tersest test runner.',
  360. })
  361. await run.result
  362. const childRequest = adapter.requests.at(-1)!
  363. expect(childRequest.system).toContain('You are the tersest test runner.')
  364. // The parent's earlier request carried no such persona.
  365. expect(adapter.requests[0]!.system ?? '').not.toContain('tersest test runner')
  366. await run.dispose()
  367. })
  368. it('toolFilter hides denied tools from the child prompt AND refuses their execution', async () => {
  369. const { ctx, parent, adapter } = await setup([
  370. // The child tries the denied tool anyway, then answers.
  371. toolCallResponse('c1', 'forbidden_tool', {}),
  372. textResponse('done'),
  373. ])
  374. ctx.tools.register(defineContentToolFixture({
  375. name: 'forbidden_tool', description: 'global', parameters: {},
  376. execute: () => Promise.resolve([{ type: 'text', text: 'ran' }]),
  377. }))
  378. const run = await start(ctx, 'spawn', {
  379. prompt: [{ type: 'text', text: 'do X' }],
  380. parent,
  381. toolFilter: { deny: ['forbidden_tool'] },
  382. })
  383. const result = await run.result
  384. expect(result.stopReason).toBe('completed')
  385. // Not advertised…
  386. const childRequest = adapter.requests[0]!
  387. expect((childRequest.tools ?? []).map(t => t.name)).not.toContain('forbidden_tool')
  388. // …and the attempted call executed as UNKNOWN_TOOL (visible in the log).
  389. const child = ctx.agents.get(run.id)!
  390. const toolResult = child.session.events.find(e => e.type === 'tool/result')!
  391. expect(JSON.stringify(toolResult.data)).toContain('unknown tool')
  392. await run.dispose()
  393. })
  394. it('an unknown toolFilter name fails the spawn loudly with no orphaned child', async () => {
  395. const { ctx, parent } = await setup([])
  396. const before = ctx.agents.list().length
  397. await expect(start(ctx, 'spawn', {
  398. prompt: [{ type: 'text', text: 'do X' }],
  399. parent,
  400. toolFilter: { deny: ['no_such_tool'] },
  401. })).rejects.toThrow(/unknown global tool "no_such_tool"/)
  402. expect(ctx.agents.list().length).toBe(before)
  403. })
  404. })
  405. it('spawning from a DISPOSING parent fails loud with no orphaned child (INACTIVE_EFFECT teaching error)', async () => {
  406. const { ctx } = await setup([])
  407. // A handle-owned parent we can dispose (config agents dispose with the loop fiber).
  408. const parentHandle = await ctx.agents.create({
  409. sessionId: SessionId('doomed-s'),
  410. agentOptions: { provider: 'mock', model: 'mock' },
  411. })
  412. await parentHandle.dispose()
  413. const before = ctx.agents.list().length
  414. const sessionsBefore = ctx.sessions.list().length
  415. const published: string[] = []
  416. ctx.on('session/created', () => void published.push('session/created'))
  417. ctx.on('agent/created', () => void published.push('agent/created'))
  418. ctx.on('agent/session-start', () => void published.push('agent/session-start'))
  419. await expect(start(ctx, 'spawn', {
  420. prompt: [{ type: 'text', text: 'do X' }],
  421. parent: parentHandle.agent,
  422. })).rejects.toThrow(/inactive context/)
  423. expect(ctx.agents.list().length).toBe(before)
  424. expect(ctx.sessions.list()).toHaveLength(sessionsBefore)
  425. expect(published).toEqual([])
  426. })
  427. it('parent disposal during the child setup transaction prevents every publication notification', async () => {
  428. const { ctx } = await setup([])
  429. const parentHandle = await ctx.agents.create({
  430. sessionId: SessionId('setup-race-parent-session'),
  431. agentOptions: { provider: 'mock', model: 'mock' },
  432. })
  433. const published: string[] = []
  434. ctx.on('session/created', () => void published.push('session/created'))
  435. ctx.on('agent/created', () => void published.push('agent/created'))
  436. ctx.on('agent/session-start', () => void published.push('agent/session-start'))
  437. let teardownStarted = false
  438. ctx.on('internal/plugin', (fiber) => {
  439. if (teardownStarted || fiber.name !== 'scope') return
  440. teardownStarted = true
  441. disposeChildLifecycle(parentHandle.agent)
  442. })
  443. const starting = start(ctx, 'spawn', {
  444. prompt: [{ type: 'text', text: 'must never run' }],
  445. parent: parentHandle.agent,
  446. })
  447. // The factory has entered its awaited unpublished setup transaction. The
  448. // parent context owns that transaction, so disposal wins without an
  449. // observer ever seeing the child.
  450. await expect(starting).rejects.toThrow(/owner disposed during setup|inactive context/)
  451. await parentHandle.dispose()
  452. expect(published).toEqual([])
  453. })
  454. })