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

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