subagent-spawn.spec.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import Loader from '@cordisjs/plugin-loader'
  4. import LlmService from '@deepseek-ai/dsh-llm'
  5. import SessionStore from '@deepseek-ai/dsh-session'
  6. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  7. import ToolRegistry from '@deepseek-ai/dsh-tools'
  8. import AgentRegistry, { AgentId } from '@deepseek-ai/dsh-agent'
  9. import { SessionId } from '@deepseek-ai/dsh-session'
  10. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  11. import * as Invariants from '@deepseek-ai/dsh-invariants'
  12. import SubagentService from '@deepseek-ai/dsh-subagent'
  13. import { MockAdapter, maxTokensResponse, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
  14. import * as spawn from '../src/index.ts'
  15. import { depthOf, SubagentDepthError } from '@deepseek-ai/dsh-subagent-inprocess'
  16. type Script = ConstructorParameters<typeof MockAdapter>[0]
  17. /**
  18. * Drives the REAL spawn backend end-to-end: a real agent loop + a scripted mock
  19. * MODEL (the only mocked boundary) + the real SubagentService + the real
  20. * dsh-invariants plugin (so a malformed child session log would fail the test).
  21. * The parent is a real config agent; the spawn provider creates a real child
  22. * agent on the same context and we assert its output.
  23. */
  24. async function setup(script: Script) {
  25. const ctx = new Context()
  26. const adapter = new MockAdapter(script)
  27. await ctx.plugin(LlmService)
  28. await ctx.plugin(SessionStore)
  29. await ctx.plugin(SystemPrompt)
  30. await ctx.plugin(ToolRegistry)
  31. await ctx.plugin(AgentRegistry)
  32. await ctx.plugin(Invariants)
  33. await ctx.plugin(AgentLoop, { agents: [] })
  34. await ctx.plugin(SubagentService)
  35. await ctx.plugin(spawn, { providerName: 'spawn' })
  36. ctx.llm.registerAdapter(['mock'], adapter)
  37. const parent = ctx.agentLoop.create(AgentId('parent'), { model: 'mock' })
  38. return { ctx, parent, adapter }
  39. }
  40. function text(blocks: { type: string; text?: string }[]): string {
  41. return blocks.filter(b => b.type === 'text').map(b => b.text).join('')
  42. }
  43. describe('dsh-subagent-spawn', () => {
  44. it('runs a fresh child to completion and returns its final assistant output', async () => {
  45. // One model call for the child: a plain text answer.
  46. const { ctx, parent } = await setup([textResponse('child answer')])
  47. const run = ctx.subagents.start('spawn', { prompt: [{ type: 'text', text: 'do X' }], parent })
  48. const result = await run.result
  49. expect(result.stopReason).toBe('completed')
  50. expect(text(result.output)).toBe('child answer')
  51. await run.dispose()
  52. })
  53. it('gives the child its OWN session (not the parent\'s), with parentSession lineage', async () => {
  54. const { ctx, parent } = await setup([textResponse('hi')])
  55. const run = ctx.subagents.start('spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
  56. await run.result
  57. const child = ctx.agents.get(run.id)!
  58. expect(child.session.header.id).not.toBe(parent.session.header.id)
  59. expect(child.session.header.parentSession).toBe(parent.session.header.id)
  60. await run.dispose()
  61. })
  62. it('a fresh child does NOT inherit the parent conversation (its log starts empty before the prompt)', async () => {
  63. // Drive the parent through one real turn so it has history, THEN spawn.
  64. const { ctx, parent } = await setup([textResponse('parent turn'), textResponse('child sees nothing')])
  65. parent.send([{ type: 'text', text: 'parent prompt' }])
  66. await parent.whenIdle()
  67. const parentEventCount = parent.session.events.length
  68. expect(parentEventCount).toBeGreaterThan(0)
  69. const run = ctx.subagents.start('spawn', { prompt: [{ type: 'text', text: 'child prompt' }], parent })
  70. await run.result
  71. const child = ctx.agents.get(run.id)!
  72. // The child's first user/message is its OWN prompt, not the parent's history.
  73. const firstUser = child.session.events.find(e => e.type === 'user/message')
  74. expect(firstUser).toBeDefined()
  75. await run.dispose()
  76. })
  77. it('disposes the child to quiescence (agent removed from the registry)', async () => {
  78. const { ctx, parent } = await setup([textResponse('x')])
  79. const run = ctx.subagents.start('spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
  80. await run.result
  81. expect(ctx.agents.get(run.id)).toBeDefined()
  82. await run.dispose()
  83. // After dispose, the child is unregistered (the AgentHandle teardown ran).
  84. expect(ctx.agents.get(run.id)).toBeUndefined()
  85. })
  86. it('stamps child depth = parent depth + 1 (via the merged AgentOptions field)', async () => {
  87. const { ctx, parent } = await setup([textResponse('x')])
  88. expect(depthOf(parent)).toBe(0)
  89. const run = ctx.subagents.start('spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
  90. await run.result
  91. const child = ctx.agents.get(run.id)!
  92. expect(depthOf(child)).toBe(1)
  93. await run.dispose()
  94. })
  95. it('refuses to spawn past maxDepth (depthLimit capability)', async () => {
  96. const { ctx, parent } = await setup([])
  97. // parent is depth 0, child would be depth 1 — cap at 0 forbids any child.
  98. expect(() => ctx.subagents.start('spawn', { prompt: [{ type: 'text', text: 'p' }], parent, maxDepth: 0 }))
  99. .toThrow(SubagentDepthError)
  100. })
  101. it('maps a child that hit its token ceiling to stopReason "max-tokens"', async () => {
  102. const { ctx, parent } = await setup([maxTokensResponse('cut off')])
  103. const run = ctx.subagents.start('spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
  104. const result = await run.result
  105. expect(result.stopReason).toBe('max-tokens')
  106. await run.dispose()
  107. })
  108. it('maps a child whose turn errored (script exhausted) to stopReason "error" with empty output', async () => {
  109. // Empty script: the child's first model call throws "script exhausted", the
  110. // turn ends `error`, and there is no assistant/message → empty output.
  111. const { ctx, parent } = await setup([])
  112. const run = ctx.subagents.start('spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
  113. const result = await run.result
  114. expect(result.stopReason).toBe('error')
  115. expect(result.output).toEqual([])
  116. await run.dispose()
  117. })
  118. it('settles aborted (without running the child) when the request signal is ALREADY aborted', async () => {
  119. // Regression: a signal aborted BEFORE the run starts never fires an `abort`
  120. // event, so the listener can't catch it. The driver must check the
  121. // already-aborted case up front and settle `aborted` without running the
  122. // child — otherwise an already-cancelled request runs to `completed`. The
  123. // empty script proves the child's model is never called.
  124. const controller = new AbortController()
  125. controller.abort()
  126. const { ctx, parent } = await setup([])
  127. const run = ctx.subagents.start('spawn', { prompt: [{ type: 'text', text: 'p' }], parent, signal: controller.signal })
  128. const result = await run.result
  129. expect(result.stopReason).toBe('aborted')
  130. expect(result.output).toEqual([])
  131. await run.dispose()
  132. })
  133. it('cancelling BEFORE the child turn starts settles aborted, not error', async () => {
  134. // Regression: a cancel landing in the pre-turn window clears the queued
  135. // prompt before any `turn/end` is logged. Deriving the stop reason from
  136. // `turn/end` alone then mis-maps the no-turn case to `error`; the run must
  137. // honor the cancel contract and settle `aborted`. The cancel is synchronous
  138. // (same tick as start, before the loop's queued-wait continuation runs), so
  139. // the turn is dropped and the empty script is never consumed.
  140. const { ctx, parent } = await setup([])
  141. const run = ctx.subagents.start('spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
  142. run.cancel('early')
  143. const result = await run.result
  144. expect(result.stopReason).toBe('aborted')
  145. expect(result.output).toEqual([])
  146. await run.dispose()
  147. })
  148. it('cancelling a running child settles the run as aborted (the abort bridge + cancel())', async () => {
  149. // 'hang' makes the child's model stream one chunk then wait until aborted.
  150. const controller = new AbortController()
  151. const { ctx, parent } = await setup(['hang'])
  152. const run = ctx.subagents.start('spawn', { prompt: [{ type: 'text', text: 'p' }], parent, signal: controller.signal })
  153. // Let the child's turn start, then abort via the request signal (the
  154. // backend bridges it to child.cancel()).
  155. await new Promise(r => setTimeout(r, 30))
  156. controller.abort()
  157. const result = await run.result
  158. expect(result.stopReason).toBe('aborted')
  159. await run.dispose()
  160. })
  161. it('run.cancel() also cancels the child directly', async () => {
  162. const { ctx, parent } = await setup(['hang'])
  163. const run = ctx.subagents.start('spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
  164. await new Promise(r => setTimeout(r, 30))
  165. run.cancel('test cancel')
  166. const result = await run.result
  167. expect(result.stopReason).toBe('aborted')
  168. await run.dispose()
  169. })
  170. it('run.cancel() with no reason uses the default cancel reason', async () => {
  171. const { ctx, parent } = await setup(['hang'])
  172. const run = ctx.subagents.start('spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
  173. await new Promise(r => setTimeout(r, 30))
  174. run.cancel()
  175. const result = await run.result
  176. expect(result.stopReason).toBe('aborted')
  177. await run.dispose()
  178. })
  179. it('does not expose the optional runtime methods (sendMessage/resume) in this cut', async () => {
  180. const { ctx, parent } = await setup([textResponse('x')])
  181. const run = ctx.subagents.start('spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
  182. expect('sendMessage' in run).toBe(false)
  183. expect('resume' in run).toBe(false)
  184. await run.result
  185. await run.dispose()
  186. })
  187. it('inherits the parent cwd into the child session', async () => {
  188. const { ctx } = await setup([textResponse('x')])
  189. // A parent WITH a cwd (config agents have none, so create one explicitly).
  190. const parentHandle = ctx.agents.create({
  191. agentId: AgentId('cwd-parent'),
  192. sessionId: SessionId('cwd-parent-session'),
  193. meta: { cwd: '/tmp/parent-workspace' },
  194. agentOptions: { model: 'mock' },
  195. })
  196. const run = ctx.subagents.start('spawn', { prompt: [{ type: 'text', text: 'p' }], parent: parentHandle.agent })
  197. await run.result
  198. const child = ctx.agents.get(run.id)!
  199. expect(child.session.header.cwd).toBe('/tmp/parent-workspace')
  200. await run.dispose()
  201. await parentHandle.dispose()
  202. })
  203. it('uses request.agentOptions.model when the parent has no model of its own', async () => {
  204. const { ctx } = await setup([textResponse('explicit model child')])
  205. // A parent with NO model (its own turns would need one supplied per-request).
  206. const parentHandle = ctx.agents.create({
  207. agentId: AgentId('modelless-parent'),
  208. sessionId: SessionId('modelless-parent-session'),
  209. agentOptions: {},
  210. })
  211. // The request supplies the child's model explicitly.
  212. const run = ctx.subagents.start('spawn', {
  213. prompt: [{ type: 'text', text: 'p' }],
  214. parent: parentHandle.agent,
  215. agentOptions: { model: 'mock' },
  216. })
  217. const result = await run.result
  218. expect(result.stopReason).toBe('completed')
  219. expect(text(result.output)).toBe('explicit model child')
  220. await run.dispose()
  221. await parentHandle.dispose()
  222. })
  223. it('advertises depthLimit but not outputSchema/toolFilter', async () => {
  224. const { ctx } = await setup([])
  225. const provider = ctx.subagents.getProvider('spawn')!
  226. expect(provider.capabilities).toEqual({ outputSchema: false, depthLimit: true, toolFilter: false })
  227. })
  228. it('unregisters the provider when its fiber is disposed (HMR safety)', async () => {
  229. const ctx = new Context()
  230. await ctx.plugin(SubagentService)
  231. await ctx.plugin(AgentRegistry)
  232. const fiber = await ctx.plugin(spawn, { providerName: 'spawn' })
  233. expect(ctx.subagents.list()).toEqual(['spawn'])
  234. await fiber.dispose()
  235. expect(ctx.subagents.list()).toEqual([])
  236. })
  237. it('has the namespace-plugin export shape (no stray default)', () => {
  238. expect('default' in spawn).toBe(false)
  239. expect(spawn.name).toBe('subagent-spawn')
  240. expect(spawn.inject).toEqual(['subagents', 'agents'])
  241. const loader = Object.create(Loader.prototype) as Loader
  242. const unwrapped = loader.unwrapExports(spawn) as Record<string, unknown>
  243. expect(unwrapped).toBe(spawn)
  244. expect(unwrapped.name).toBe('subagent-spawn')
  245. expect(unwrapped.inject).toEqual(['subagents', 'agents'])
  246. expect(typeof unwrapped.apply).toBe('function')
  247. })
  248. })