1
0

subagent-spawn.spec.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import Loader from '@cordisjs/plugin-loader'
  4. import AgentRegistry, { AgentId } 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 { depthOf, STRUCTURED_OUTPUT_TOOL, SubagentDepthError } 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(AgentId('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(depthOf(parent)).toBe(0)
  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(depthOf(child)).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(SubagentDepthError)
  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. agentId: AgentId('cwd-parent'),
  205. sessionId: SessionId('cwd-parent-session'),
  206. meta: { cwd: '/tmp/parent-workspace' },
  207. agentOptions: { provider: 'mock', model: 'mock' },
  208. })
  209. const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent: parentHandle.agent })
  210. await run.result
  211. const child = ctx.agents.get(run.id)!
  212. expect(child.session.header.cwd).toBe('/tmp/parent-workspace')
  213. await run.dispose()
  214. await parentHandle.dispose()
  215. })
  216. it('uses request.agentOptions.model when the parent has no model of its own', async () => {
  217. const { ctx } = await setup([textResponse('explicit model child')])
  218. // A parent with NO model (its own turns would need one supplied per-request).
  219. const parentHandle = await ctx.agents.create({
  220. agentId: AgentId('modelless-parent'),
  221. sessionId: SessionId('modelless-parent-session'),
  222. agentOptions: {},
  223. })
  224. // The request supplies the child's model explicitly.
  225. const run = await start(ctx, 'spawn', {
  226. prompt: [{ type: 'text', text: 'p' }],
  227. parent: parentHandle.agent,
  228. agentOptions: { provider: 'mock', model: 'mock' },
  229. })
  230. const result = await run.result
  231. expect(result.stopReason).toBe('completed')
  232. expect(text(result.output)).toBe('explicit model child')
  233. await run.dispose()
  234. await parentHandle.dispose()
  235. })
  236. it('advertises every start-time capability (depthLimit, outputSchema, toolFilter, persona)', async () => {
  237. const { ctx } = await setup([])
  238. const provider = ctx.subagents.getProvider('spawn')!
  239. expect(provider.capabilities).toEqual({ outputSchema: true, depthLimit: true, toolFilter: true, persona: true })
  240. })
  241. it('unregisters the provider when its fiber is disposed (HMR safety)', async () => {
  242. const ctx = new Context()
  243. await ctx.plugin(SubagentService)
  244. await ctx.plugin(AgentRegistry)
  245. const fiber = await ctx.plugin(spawn, { providerName: 'spawn' })
  246. expect(ctx.subagents.list()).toEqual(['spawn'])
  247. await fiber.dispose()
  248. expect(ctx.subagents.list()).toEqual([])
  249. })
  250. it('captures structured output through the shipped plugin (driver runtime, plugin wiring)', async () => {
  251. const { ctx, parent } = await setup([
  252. toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 42 }),
  253. ])
  254. const run = await start(ctx, 'spawn', {
  255. prompt: [{ type: 'text', text: 'produce the answer' }],
  256. parent,
  257. outputSchema: { type: 'object', properties: { answer: { type: 'number' } }, required: ['answer'] },
  258. })
  259. const result = await run.result
  260. expect(result.stopReason).toBe('completed')
  261. expect(result.structured).toEqual({ answer: 42 })
  262. // Run-scoped runtime: the settle released the last acquisition.
  263. expect(ctx.tools.get(STRUCTURED_OUTPUT_TOOL)).toBeUndefined()
  264. await run.dispose()
  265. })
  266. it('a backend unload does not revoke an accepted holder-owned run', async () => {
  267. // Rebuild the stack by hand so we hold the backend's fiber.
  268. const ctx = new Context()
  269. const adapter = new MockAdapter(['hang'])
  270. await mountAgentLoopTestDependencies(ctx)
  271. await ctx.plugin(Invariants)
  272. await ctx.plugin(AgentLoop, { agents: [] })
  273. await ctx.plugin(SubagentService)
  274. const fiber = await ctx.plugin(spawn, { providerName: 'spawn' })
  275. ctx.llm.registerAdapter(['mock'], adapter)
  276. const parent = ctx.agentLoop.create(AgentId('parent'), { provider: 'mock', model: 'mock' })
  277. const controller = new AbortController()
  278. const run = await start(ctx, 'spawn', {
  279. prompt: [{ type: 'text', text: 'q' }],
  280. parent,
  281. signal: controller.signal,
  282. outputSchema: { type: 'object', properties: { a: { type: 'number' } } },
  283. })
  284. // Provider removal prevents new starts but the returned run belongs to its
  285. // holder and remains live.
  286. await new Promise(resolve => setTimeout(resolve, 30))
  287. await fiber.dispose()
  288. expect(ctx.subagents.getProvider('spawn')).toBeUndefined()
  289. expect(ctx.agents.get(run.id)).toBeDefined()
  290. controller.abort('test complete')
  291. const result = await run.result
  292. expect(result.stopReason).toBe('aborted')
  293. expect(ctx.tools.get(STRUCTURED_OUTPUT_TOOL)).toBeUndefined()
  294. await run.dispose()
  295. })
  296. it('a start racing an already-unloading backend cannot begin child creation', async () => {
  297. const ctx = new Context()
  298. await mountAgentLoopTestDependencies(ctx)
  299. await ctx.plugin(AgentLoop, { agents: [] })
  300. await ctx.plugin(SubagentService)
  301. const fiber = await ctx.plugin(spawn, { providerName: 'spawn' })
  302. const parent = ctx.agentLoop.create(AgentId('parent'), { provider: 'mock', model: 'mock' })
  303. const parentEffects = parent.ctx.fiber.getEffects().length
  304. const published: string[] = []
  305. ctx.on('session/created', () => void published.push('session/created'))
  306. ctx.on('agent/created', () => void published.push('agent/created'))
  307. const unloading = fiber.dispose()
  308. await unloading
  309. await expect(start(ctx, 'spawn', {
  310. prompt: [{ type: 'text', text: 'must never start' }], parent,
  311. })).rejects.toThrow(/no subagent provider/)
  312. expect(parent.ctx.fiber.getEffects()).toHaveLength(parentEffects)
  313. expect(published).toEqual([])
  314. })
  315. it('has the namespace-plugin export shape (no stray default)', () => {
  316. expect('default' in spawn).toBe(false)
  317. expect(spawn.name).toBe('subagent-spawn')
  318. expect(spawn.inject).toEqual(['subagents'])
  319. const loader = Object.create(Loader.prototype) as Loader
  320. const unwrapped = loader.unwrapExports(spawn) as Record<string, unknown>
  321. expect(unwrapped).toBe(spawn)
  322. expect(unwrapped.name).toBe('subagent-spawn')
  323. expect(unwrapped.inject).toEqual(['subagents'])
  324. expect(typeof unwrapped.apply).toBe('function')
  325. })
  326. describe('persona and toolFilter (the scoped child world)', () => {
  327. it('a per-child persona shadows the deployment persona in the child request only', async () => {
  328. const { ctx, parent, adapter } = await setup([
  329. textResponse('parent answer'),
  330. textResponse('child answer'),
  331. ])
  332. parent.send([{ type: 'text', text: 'hi' }])
  333. await parent.whenIdle()
  334. const run = await start(ctx, 'spawn', {
  335. prompt: [{ type: 'text', text: 'do X' }],
  336. parent,
  337. persona: 'You are the tersest test runner.',
  338. })
  339. await run.result
  340. const childRequest = adapter.requests.at(-1)!
  341. expect(childRequest.system).toContain('You are the tersest test runner.')
  342. // The parent's earlier request carried no such persona.
  343. expect(adapter.requests[0]!.system ?? '').not.toContain('tersest test runner')
  344. await run.dispose()
  345. })
  346. it('toolFilter hides denied tools from the child prompt AND refuses their execution', async () => {
  347. const { ctx, parent, adapter } = await setup([
  348. // The child tries the denied tool anyway, then answers.
  349. toolCallResponse('c1', 'forbidden_tool', {}),
  350. textResponse('done'),
  351. ])
  352. ctx.tools.register({
  353. name: 'forbidden_tool', description: 'global', parameters: {},
  354. execute: () => Promise.resolve([{ type: 'text', text: 'ran' }]),
  355. })
  356. const run = await start(ctx, 'spawn', {
  357. prompt: [{ type: 'text', text: 'do X' }],
  358. parent,
  359. toolFilter: { deny: ['forbidden_tool'] },
  360. })
  361. const result = await run.result
  362. expect(result.stopReason).toBe('completed')
  363. // Not advertised…
  364. const childRequest = adapter.requests[0]!
  365. expect((childRequest.tools ?? []).map(t => t.name)).not.toContain('forbidden_tool')
  366. // …and the attempted call executed as UNKNOWN_TOOL (visible in the log).
  367. const child = ctx.agents.get(run.id)!
  368. const toolResult = child.session.events.find(e => e.type === 'tool/result')!
  369. expect(JSON.stringify(toolResult.data)).toContain('unknown tool')
  370. await run.dispose()
  371. })
  372. it('an unknown toolFilter name fails the spawn loudly with no orphaned child', async () => {
  373. const { ctx, parent } = await setup([])
  374. const before = ctx.agents.list().length
  375. await expect(start(ctx, 'spawn', {
  376. prompt: [{ type: 'text', text: 'do X' }],
  377. parent,
  378. toolFilter: { deny: ['no_such_tool'] },
  379. })).rejects.toThrow(/unknown global tool "no_such_tool"/)
  380. expect(ctx.agents.list().length).toBe(before)
  381. })
  382. })
  383. it('spawning from a DISPOSING parent fails loud with no orphaned child (INACTIVE_EFFECT teaching error)', async () => {
  384. const { ctx } = await setup([])
  385. // A handle-owned parent we can dispose (config agents dispose with the loop fiber).
  386. const parentHandle = await ctx.agents.create({
  387. agentId: AgentId('doomed-parent'),
  388. sessionId: SessionId('doomed-s'),
  389. agentOptions: { provider: 'mock', model: 'mock' },
  390. })
  391. await parentHandle.dispose()
  392. const before = ctx.agents.list().length
  393. const sessionsBefore = ctx.sessions.list().length
  394. const published: string[] = []
  395. ctx.on('session/created', () => void published.push('session/created'))
  396. ctx.on('agent/created', () => void published.push('agent/created'))
  397. ctx.on('agent/session-start', () => void published.push('agent/session-start'))
  398. await expect(start(ctx, 'spawn', {
  399. prompt: [{ type: 'text', text: 'do X' }],
  400. parent: parentHandle.agent,
  401. })).rejects.toThrow(/inactive context/)
  402. expect(ctx.agents.list().length).toBe(before)
  403. expect(ctx.sessions.list()).toHaveLength(sessionsBefore)
  404. expect(published).toEqual([])
  405. })
  406. it('parent disposal during the child setup transaction prevents every publication notification', async () => {
  407. const { ctx } = await setup([])
  408. const parentHandle = await ctx.agents.create({
  409. agentId: AgentId('setup-race-parent'),
  410. sessionId: SessionId('setup-race-parent-session'),
  411. agentOptions: { provider: 'mock', model: 'mock' },
  412. })
  413. const published: string[] = []
  414. ctx.on('session/created', () => void published.push('session/created'))
  415. ctx.on('agent/created', () => void published.push('agent/created'))
  416. ctx.on('agent/session-start', () => void published.push('agent/session-start'))
  417. const starting = start(ctx, 'spawn', {
  418. prompt: [{ type: 'text', text: 'must never run' }],
  419. parent: parentHandle.agent,
  420. })
  421. // The factory has entered its awaited unpublished setup transaction. The
  422. // parent context owns that transaction, so disposal wins without an
  423. // observer ever seeing the child.
  424. await parentHandle.dispose()
  425. await expect(starting).rejects.toThrow(/owner disposed during setup|inactive context/)
  426. expect(published).toEqual([])
  427. })
  428. })