subagent-spawn.spec.ts 22 KB

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