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

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