subagent-spawn-in-process.spec.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  2. import { describe, expect, it } from 'vitest'
  3. import { Context, symbols, type EffectMeta } from '@deepseek-ai/cordis'
  4. import Loader from '@deepseek-ai/cordis-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 InvariantRegistry 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 SubagentRuntime, { 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-in-process-driver'
  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(InvariantRegistry)
  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 SubagentRuntime + 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(SubagentRuntime)
  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-in-process', () => {
  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', async () => {
  259. const { ctx } = await setup([])
  260. const provider = ctx.subagents.getProvider('spawn')!
  261. expect(provider.capabilities).toEqual({
  262. agentOptions: true,
  263. outputSchema: true,
  264. depthLimit: true,
  265. toolFilter: true,
  266. persona: true,
  267. })
  268. })
  269. it('unregisters the provider when its fiber is disposed (HMR safety)', async () => {
  270. const ctx = new Context()
  271. await ctx.plugin(SubagentRuntime)
  272. await ctx.plugin(AgentRegistry)
  273. const fiber = await ctx.plugin(spawn, { providerName: 'spawn' })
  274. expect(ctx.subagents.list()).toEqual(['spawn'])
  275. await fiber.dispose()
  276. expect(ctx.subagents.list()).toEqual([])
  277. })
  278. it('captures structured output through the shipped plugin (driver runtime, plugin wiring)', async () => {
  279. const { ctx, parent } = await setup([
  280. toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 42 }),
  281. ])
  282. const run = await start(ctx, 'spawn', {
  283. prompt: [{ type: 'text', text: 'produce the answer' }],
  284. parent,
  285. outputSchema: { type: 'object', properties: { answer: { type: 'number' } }, required: ['answer'] },
  286. })
  287. const result = await run.result
  288. expect(result.stopReason).toBe('completed')
  289. expect(result.structured).toEqual({ answer: 42 })
  290. expect(ctx.tools.get(STRUCTURED_OUTPUT_TOOL)).toBeUndefined()
  291. await run.dispose()
  292. })
  293. it('a backend unload does not revoke an accepted holder-owned run', async () => {
  294. // Rebuild the stack by hand so we hold the backend's fiber.
  295. const ctx = new Context()
  296. const adapter = new MockAdapter(['hang'])
  297. await mountAgentLoopTestDependencies(ctx)
  298. await mountInvariants(ctx)
  299. await ctx.plugin(AgentLoop, { agents: [] })
  300. await ctx.plugin(SubagentRuntime)
  301. const fiber = await ctx.plugin(spawn, { providerName: 'spawn' })
  302. ctx.llm.registerAdapter(['mock'], adapter)
  303. const parent = ctx.agentLoop.create(SessionId('parent'), { provider: 'mock', model: 'mock' })
  304. const controller = new AbortController()
  305. const run = await start(ctx, 'spawn', {
  306. prompt: [{ type: 'text', text: 'q' }],
  307. parent,
  308. signal: controller.signal,
  309. outputSchema: { type: 'object', properties: { a: { type: 'number' } } },
  310. })
  311. // Provider removal prevents new starts but the returned run belongs to its
  312. // holder and remains live.
  313. await new Promise(resolve => setTimeout(resolve, 30))
  314. await fiber.dispose()
  315. expect(ctx.subagents.getProvider('spawn')).toBeUndefined()
  316. expect(ctx.agents.get(run.id)).toBeDefined()
  317. controller.abort('test complete')
  318. const result = await run.result
  319. expect(result.stopReason).toBe('aborted')
  320. expect(ctx.tools.get(STRUCTURED_OUTPUT_TOOL)).toBeUndefined()
  321. await run.dispose()
  322. })
  323. it('a start racing an already-unloading backend cannot begin child creation', async () => {
  324. const ctx = new Context()
  325. await mountAgentLoopTestDependencies(ctx)
  326. await ctx.plugin(AgentLoop, { agents: [] })
  327. await ctx.plugin(SubagentRuntime)
  328. const fiber = await ctx.plugin(spawn, { providerName: 'spawn' })
  329. const parent = ctx.agentLoop.create(SessionId('parent'), { provider: 'mock', model: 'mock' })
  330. const parentEffects = parent.ctx.fiber.getEffects().length
  331. const published: string[] = []
  332. ctx.on('session/created', () => void published.push('session/created'))
  333. ctx.on('agent/created', () => void published.push('agent/created'))
  334. const unloading = fiber.dispose()
  335. await unloading
  336. await expect(start(ctx, 'spawn', {
  337. prompt: [{ type: 'text', text: 'must never start' }], parent,
  338. })).rejects.toThrow(/no subagent provider/)
  339. expect(parent.ctx.fiber.getEffects()).toHaveLength(parentEffects)
  340. expect(published).toEqual([])
  341. })
  342. it('has the namespace-plugin export shape (no stray default)', () => {
  343. expect('default' in spawn).toBe(false)
  344. expect(spawn.name).toBe('subagent-spawn-in-process')
  345. expect(spawn.inject).toEqual(['subagents'])
  346. const loader = Object.create(Loader.prototype) as Loader
  347. const unwrapped = loader.unwrapExports(spawn) as Record<string, unknown>
  348. expect(unwrapped).toBe(spawn)
  349. expect(unwrapped.name).toBe('subagent-spawn-in-process')
  350. expect(unwrapped.inject).toEqual(['subagents'])
  351. expect(typeof unwrapped.apply).toBe('function')
  352. })
  353. describe('persona and toolFilter (the scoped child world)', () => {
  354. it('a per-child persona shadows the deployment persona in the child request only', async () => {
  355. const { ctx, parent, adapter } = await setup([
  356. textResponse('parent answer'),
  357. textResponse('child answer'),
  358. ])
  359. parent.followup(createUserMessage({ content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }))
  360. await parent.whenIdle()
  361. const run = await start(ctx, 'spawn', {
  362. prompt: [{ type: 'text', text: 'do X' }],
  363. parent,
  364. persona: 'You are the tersest test runner.',
  365. })
  366. await run.result
  367. const childRequest = adapter.requests.at(-1)!
  368. expect(childRequest.system).toContain('You are the tersest test runner.')
  369. // The parent's earlier request carried no such persona.
  370. expect(adapter.requests[0]!.system ?? '').not.toContain('tersest test runner')
  371. await run.dispose()
  372. })
  373. it('toolFilter hides denied tools from the child prompt AND refuses their execution', async () => {
  374. const { ctx, parent, adapter } = await setup([
  375. // The child tries the denied tool anyway, then answers.
  376. toolCallResponse('c1', 'forbidden_tool', {}),
  377. textResponse('done'),
  378. ])
  379. ctx.tools.register(defineContentToolFixture({
  380. name: 'forbidden_tool', description: 'global', parameters: {},
  381. execute: () => Promise.resolve([{ type: 'text', text: 'ran' }]),
  382. }))
  383. const run = await start(ctx, 'spawn', {
  384. prompt: [{ type: 'text', text: 'do X' }],
  385. parent,
  386. toolFilter: { deny: ['forbidden_tool'] },
  387. })
  388. const result = await run.result
  389. expect(result.stopReason).toBe('completed')
  390. // Not advertised…
  391. const childRequest = adapter.requests[0]!
  392. expect((childRequest.tools ?? []).map(t => t.name)).not.toContain('forbidden_tool')
  393. // …and the attempted call executed as UNKNOWN_TOOL (visible in the log).
  394. const child = ctx.agents.get(run.id)!
  395. const toolResult = child.session.events.find(e => e.type === 'tool/result')!
  396. expect(JSON.stringify(toolResult.data)).toContain('unknown tool')
  397. await run.dispose()
  398. })
  399. it('an unknown toolFilter name fails the spawn loudly with no orphaned child', async () => {
  400. const { ctx, parent } = await setup([])
  401. const before = ctx.agents.list().length
  402. await expect(start(ctx, 'spawn', {
  403. prompt: [{ type: 'text', text: 'do X' }],
  404. parent,
  405. toolFilter: { deny: ['no_such_tool'] },
  406. })).rejects.toThrow(/unknown global tool "no_such_tool"/)
  407. expect(ctx.agents.list().length).toBe(before)
  408. })
  409. })
  410. it('spawning from a DISPOSING parent fails loud with no orphaned child (INACTIVE_EFFECT teaching error)', async () => {
  411. const { ctx } = await setup([])
  412. // A handle-owned parent we can dispose (config agents dispose with the loop fiber).
  413. const parentHandle = await ctx.agents.create({
  414. sessionId: SessionId('doomed-s'),
  415. agentOptions: { provider: 'mock', model: 'mock' },
  416. })
  417. await parentHandle.dispose()
  418. const before = ctx.agents.list().length
  419. const sessionsBefore = ctx.sessions.list().length
  420. const published: string[] = []
  421. ctx.on('session/created', () => void published.push('session/created'))
  422. ctx.on('agent/created', () => void published.push('agent/created'))
  423. ctx.on('agent/session-start', () => void published.push('agent/session-start'))
  424. await expect(start(ctx, 'spawn', {
  425. prompt: [{ type: 'text', text: 'do X' }],
  426. parent: parentHandle.agent,
  427. })).rejects.toThrow(/inactive context/)
  428. expect(ctx.agents.list().length).toBe(before)
  429. expect(ctx.sessions.list()).toHaveLength(sessionsBefore)
  430. expect(published).toEqual([])
  431. })
  432. it('parent disposal during the child setup transaction prevents every publication notification', async () => {
  433. const { ctx } = await setup([])
  434. const parentHandle = await ctx.agents.create({
  435. sessionId: SessionId('setup-race-parent-session'),
  436. agentOptions: { provider: 'mock', model: 'mock' },
  437. })
  438. const published: string[] = []
  439. ctx.on('session/created', () => void published.push('session/created'))
  440. ctx.on('agent/created', () => void published.push('agent/created'))
  441. ctx.on('agent/session-start', () => void published.push('agent/session-start'))
  442. let teardownStarted = false
  443. ctx.on('internal/plugin', (fiber) => {
  444. if (teardownStarted || fiber.name !== 'scope') return
  445. teardownStarted = true
  446. disposeChildLifecycle(parentHandle.agent)
  447. })
  448. const starting = start(ctx, 'spawn', {
  449. prompt: [{ type: 'text', text: 'must never run' }],
  450. parent: parentHandle.agent,
  451. })
  452. // The factory has entered its awaited unpublished setup transaction. The
  453. // parent context owns that transaction, so disposal wins without an
  454. // observer ever seeing the child.
  455. await expect(starting).rejects.toThrow(/owner disposed during setup|inactive context/)
  456. await parentHandle.dispose()
  457. expect(published).toEqual([])
  458. })
  459. })