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

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