subagent-spawn.spec.ts 23 KB

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