subagent-spawn.spec.ts 23 KB

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