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

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