subagent-spawn.spec.ts 21 KB

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