subagent-spawn.spec.ts 22 KB

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