subagent-inprocess.spec.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  2. import { describe, expect, it } from 'vitest'
  3. import { Context } from 'cordis'
  4. import { type Agent, type AgentOptions } 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, { snapshotSubagentDescriptor } from '@deepseek-ai/dsh-subagent'
  13. import { maxTokensResponse, MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
  14. import { startInProcessRun } from '../src/index.ts'
  15. type Script = ConstructorParameters<typeof MockAdapter>[0]
  16. async function mountInvariants(ctx: Context): Promise<void> {
  17. await ctx.plugin(InvariantService)
  18. await ctx.plugin(SessionInvariant)
  19. await ctx.plugin(AgentInvariant)
  20. await ctx.plugin(AgentLoopInvariant)
  21. }
  22. async function setup(script: Script, parentOptions: Partial<AgentOptions> = {}) {
  23. const ctx = new Context()
  24. await mountAgentLoopTestDependencies(ctx)
  25. await mountInvariants(ctx)
  26. await ctx.plugin(AgentLoop, { agents: [] })
  27. await ctx.plugin(SubagentService)
  28. const adapter = new MockAdapter(script)
  29. ctx.llm.registerAdapter(['mock'], adapter)
  30. const parent = ctx.agentLoop.create(SessionId('parent'), { provider: 'mock', model: 'mock', ...parentOptions })
  31. return { ctx, parent, adapter }
  32. }
  33. function request(parent: Agent, signal = new AbortController().signal) {
  34. return {
  35. label: 'child task',
  36. prompt: [{ type: 'text' as const, text: 'child task' }],
  37. parent,
  38. signal,
  39. descriptor: snapshotSubagentDescriptor({
  40. mode: 'one-shot',
  41. provider: 'test',
  42. label: 'child task',
  43. }),
  44. }
  45. }
  46. function text(blocks: readonly { type: string; text?: string }[]): string {
  47. return blocks.filter(block => block.type === 'text').map(block => block.text).join('')
  48. }
  49. describe('startInProcessRun', () => {
  50. it('returns only after publication, drives a fresh child, and disposes it', async () => {
  51. const { ctx, parent } = await setup([textResponse('driver answer')])
  52. const run = await startInProcessRun(request(parent), {})
  53. expect(ctx.agents.get(run.id)).toBeDefined()
  54. const result = await run.result
  55. expect(result.stopReason).toBe('completed')
  56. expect(text(result.output)).toBe('driver answer')
  57. expect(ctx.agents.get(run.id)!.options.subagentDepth).toBe(1)
  58. await run.dispose()
  59. await run.dispose()
  60. expect(ctx.agents.get(run.id)).toBeUndefined()
  61. })
  62. it('uses explicit child model selectors when the parent has none and preserves its cwd', async () => {
  63. const { ctx } = await setup([textResponse('driver answer')])
  64. const parent = ctx.agentLoop.create(SessionId('bare-parent'), {}, { cwd: '/workspace' })
  65. const run = await startInProcessRun({
  66. ...request(parent),
  67. agentOptions: { provider: 'mock', model: 'mock' },
  68. }, {})
  69. const child = ctx.agents.get(run.id)!
  70. expect(child.options).toMatchObject({ provider: 'mock', model: 'mock' })
  71. expect(child.session.header.cwd).toBe('/workspace')
  72. await expect(run.result).resolves.toMatchObject({ stopReason: 'completed' })
  73. await run.dispose()
  74. })
  75. it('does not add a final durability checkpoint to a foreground run', async () => {
  76. const { ctx, parent } = await setup([textResponse('driver answer')])
  77. let flushes = 0
  78. ctx.on('session/flush', (session) => {
  79. if (session.header.parentSession === undefined) return
  80. flushes++
  81. throw new Error('disk full')
  82. })
  83. const run = await startInProcessRun(request(parent), {})
  84. await expect(run.result).resolves.toMatchObject({ stopReason: 'completed' })
  85. expect(flushes).toBe(0)
  86. await run.dispose()
  87. })
  88. it('keeps published run and handle disposal failures on separate channels', async () => {
  89. const { ctx, parent } = await setup([])
  90. const runError = new Error('published run failed')
  91. const disposalError = new Error('published handle disposal failed')
  92. const beforeAgents = ctx.agents.list().length
  93. const beforeSessions = ctx.sessions.list().length
  94. const parentWithFailedDisposal = {
  95. options: parent.options,
  96. session: parent.session,
  97. ctx: {
  98. get: () => undefined,
  99. agents: {
  100. create: async (options: Parameters<typeof ctx.agents.create>[0]) => {
  101. const handle = await ctx.agents.create(options)
  102. handle.agent.followup = () => { throw runError }
  103. return {
  104. ...handle,
  105. dispose: async () => {
  106. await handle.dispose()
  107. throw disposalError
  108. },
  109. }
  110. },
  111. },
  112. },
  113. } as unknown as Agent
  114. const run = await startInProcessRun(request(parentWithFailedDisposal), {})
  115. expect(ctx.agents.get(run.id)).toBeDefined()
  116. await expect(run.result).rejects.toBe(runError)
  117. await expect(run.dispose()).rejects.toBe(disposalError)
  118. expect(ctx.agents.list()).toHaveLength(beforeAgents)
  119. expect(ctx.sessions.list()).toHaveLength(beforeSessions)
  120. })
  121. it('reports the turn outcome when later metadata is appended during flush', async () => {
  122. const { ctx, parent } = await setup([maxTokensResponse('partial answer')])
  123. let injected = false
  124. ctx.on('session/flush', (session) => {
  125. if (injected || session.header.parentSession === undefined) return
  126. const lastEnd = session.events.findLast(event => event.type === 'turn/end')
  127. if (lastEnd?.type !== 'turn/end' || lastEnd.data.reason.kind !== 'max-tokens') return
  128. injected = true
  129. session.append('user/message', createUserMessage({
  130. content: [{ type: 'text', text: 'late metadata' }],
  131. source: { kind: 'plugin', plugin: 'late-metadata' },
  132. }), { surfaceOp: 'append' })
  133. })
  134. const run = await startInProcessRun(request(parent), {})
  135. const result = await run.result
  136. const child = ctx.agents.get(run.id)!
  137. expect(injected).toBe(false)
  138. expect(child.session.events.findLast(event => event.type === 'turn/end'))
  139. .toMatchObject({ data: { reason: { kind: 'max-tokens' } } })
  140. expect(result.stopReason).toBe('max-tokens')
  141. await run.dispose()
  142. })
  143. it('seeds a forked child but reads only the child-owned output', async () => {
  144. const { ctx, parent } = await setup([textResponse('parent answer'), textResponse('child answer')])
  145. parent.followup(createUserMessage({ content: [{ type: 'text', text: 'parent question' }], source: { kind: 'user' } }))
  146. await parent.whenIdle()
  147. const seed = parent.session.events.slice()
  148. const run = await startInProcessRun(request(parent), { seed })
  149. const result = await run.result
  150. expect(text(result.output)).toBe('child answer')
  151. const child = ctx.agents.get(run.id)!
  152. expect(child.session.header.seedLength).toBe(seed.length)
  153. expect(child.session.events.slice(0, seed.length)).toEqual(seed)
  154. await run.dispose()
  155. })
  156. it('persists the child origin and depth in its session header', async () => {
  157. const { ctx, parent } = await setup([textResponse('child answer')])
  158. const run = await startInProcessRun(request(parent), {})
  159. await run.result
  160. // The recursion budget is durable session data, not only runtime options —
  161. // a depth that lived only in AgentOptions would reset to 0 on resume.
  162. expect(ctx.agents.get(run.id)!.session.header).toMatchObject({
  163. origin: 'subagent',
  164. delegationDepth: 1,
  165. })
  166. await run.dispose()
  167. })
  168. it('inherits the parent output-token cap and accepts an explicit child override', async () => {
  169. const { ctx, parent, adapter } = await setup(
  170. [textResponse('inherited'), textResponse('overridden')],
  171. { maxTokens: 111 },
  172. )
  173. const inherited = await startInProcessRun(request(parent), {})
  174. await inherited.result
  175. expect(adapter.requests[0]?.maxTokens).toBe(111)
  176. expect(ctx.agents.get(inherited.id)?.options.maxTokens).toBe(111)
  177. await inherited.dispose()
  178. const overridden = await startInProcessRun({
  179. ...request(parent),
  180. agentOptions: { maxTokens: 222 },
  181. }, {})
  182. await overridden.result
  183. expect(adapter.requests[1]?.maxTokens).toBe(222)
  184. expect(ctx.agents.get(overridden.id)?.options.maxTokens).toBe(222)
  185. await overridden.dispose()
  186. })
  187. it('counts a RESUMED child by its persisted header depth, not the absent runtime depth', async () => {
  188. // Resume rebuilds runtime options, so the durable header must keep this
  189. // depth-1 child from delegating as though it were top-level.
  190. const { ctx } = await setup([textResponse('unused')])
  191. const resumed = (await ctx.agents.create({
  192. sessionId: SessionId('resumed-child'),
  193. meta: { parentSession: SessionId('root'), delegationDepth: 1 },
  194. agentOptions: { provider: 'mock', model: 'mock' },
  195. signal: new AbortController().signal,
  196. })).agent
  197. await expect(startInProcessRun({ ...request(resumed), maxDepth: 1 }, {}))
  198. .rejects.toMatchObject({ name: 'SubagentDepthError', attemptedDepth: 2, maxDepth: 1 })
  199. })
  200. it('lets runtime options deepen but never lower the persisted depth', async () => {
  201. const { ctx } = await setup([textResponse('unused')])
  202. const parent = (await ctx.agents.create({
  203. sessionId: SessionId('deep-parent'),
  204. meta: { delegationDepth: 2 },
  205. agentOptions: { provider: 'mock', model: 'mock', subagentDepth: 1 },
  206. signal: new AbortController().signal,
  207. })).agent
  208. // Persisted 2 vs runtime 1: the child is depth 3, so maxDepth 2 rejects.
  209. await expect(startInProcessRun({ ...request(parent), maxDepth: 2 }, {}))
  210. .rejects.toMatchObject({ name: 'SubagentDepthError', attemptedDepth: 3, maxDepth: 2 })
  211. })
  212. it('rejects invalid and exceeded depth before publication', async () => {
  213. const { parent } = await setup([])
  214. await expect(startInProcessRun({ ...request(parent), maxDepth: -1 }, {}))
  215. .rejects.toThrow('non-negative safe integer')
  216. await expect(startInProcessRun({ ...request(parent), maxDepth: 0 }, {}))
  217. .rejects.toMatchObject({ name: 'SubagentDepthError' })
  218. for (const value of [Number.NaN, 1.5, -1, -0, Number.MAX_SAFE_INTEGER + 1]) {
  219. const malformed = { options: { subagentDepth: value }, session: { header: {} } } as unknown as Agent
  220. await expect(startInProcessRun(request(malformed), {}))
  221. .rejects.toThrow('agent subagentDepth must be a non-negative safe integer')
  222. }
  223. const maxParent = { options: { subagentDepth: Number.MAX_SAFE_INTEGER }, session: { header: {} } } as unknown as Agent
  224. await expect(startInProcessRun(request(maxParent), {})).rejects.toBeInstanceOf(RangeError)
  225. })
  226. it('rejects an already-aborted request without publishing a child', async () => {
  227. const { ctx, parent } = await setup([])
  228. const beforeAgents = ctx.agents.list().length
  229. const beforeSessions = ctx.sessions.list().length
  230. const controller = new AbortController()
  231. controller.abort('too late')
  232. await expect(startInProcessRun(request(parent, controller.signal), {}))
  233. .rejects.toThrow('aborted before child publication')
  234. expect(ctx.agents.list()).toHaveLength(beforeAgents)
  235. expect(ctx.sessions.list()).toHaveLength(beforeSessions)
  236. })
  237. it('stamps only the resolved depth when neither parent nor request declares a model route', async () => {
  238. // The one-shot analogue of the deleted resume coverage ("resumes without
  239. // inventing undeclared agent model options"): a bare parent with no request
  240. // agentOptions yields a child whose options carry ONLY the stamped depth —
  241. // no provider/model is fabricated, so the child's turn errors for want of a
  242. // route rather than silently adopting one.
  243. const { ctx } = await setup([])
  244. const parent = ctx.agentLoop.create(SessionId('routeless-parent'), {})
  245. const run = await startInProcessRun(request(parent), {})
  246. const child = ctx.agents.get(run.id)!
  247. expect(child.options).toEqual({ subagentDepth: 1 })
  248. await expect(run.result).resolves.toMatchObject({ stopReason: 'error' })
  249. await run.dispose()
  250. })
  251. it('uses the request signal after publication and dispose as cancellation paths', async () => {
  252. const { parent, adapter } = await setup(['hang', 'hang'])
  253. const controller = new AbortController()
  254. const signalled = await startInProcessRun(request(parent, controller.signal), {})
  255. await new Promise(resolve => setTimeout(resolve, 30))
  256. controller.abort('stop child')
  257. await expect(signalled.result).resolves.toMatchObject({ stopReason: 'aborted' })
  258. expect(adapter.requests[0]?.signal?.reason).toEqual({ kind: 'parent' })
  259. const child = parent.ctx.agents.get(signalled.id)
  260. const turnEnd = child?.session.events.findLast(event => event.type === 'turn/end')
  261. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'aborted', reason: { kind: 'parent' } })
  262. await signalled.dispose()
  263. const disposed = await startInProcessRun(request(parent), {})
  264. await new Promise(resolve => setTimeout(resolve, 30))
  265. await disposed.dispose()
  266. await expect(disposed.result).resolves.toMatchObject({ stopReason: 'aborted' })
  267. })
  268. it('cleans a failed unpublished setup before rejecting', async () => {
  269. const { ctx, parent } = await setup([])
  270. const beforeAgents = ctx.agents.list().length
  271. const beforeSessions = ctx.sessions.list().length
  272. await expect(startInProcessRun({
  273. ...request(parent),
  274. toolFilter: { deny: ['unknown-tool'] },
  275. }, {})).rejects.toThrow('unknown global tool')
  276. expect(ctx.agents.list()).toHaveLength(beforeAgents)
  277. expect(ctx.sessions.list()).toHaveLength(beforeSessions)
  278. })
  279. it('treats abort after factory publication as a cancelled run with an id', async () => {
  280. const { ctx, parent } = await setup([])
  281. const controller = new AbortController()
  282. const beforeAgents = ctx.agents.list().length
  283. const beforeSessions = ctx.sessions.list().length
  284. const parentWithAbortAtHandoff = {
  285. options: parent.options,
  286. session: parent.session,
  287. ctx: {
  288. // The driver's synchronous inheritance capture probes both policy
  289. // services opportunistically; this stub composes neither.
  290. get: () => undefined,
  291. agents: {
  292. create: async (options: Parameters<typeof ctx.agents.create>[0]) => {
  293. const handle = await ctx.agents.create(options)
  294. // `create()` has detached its creation-only listener, but the
  295. // published run has not installed its live listener yet.
  296. controller.abort('handoff race')
  297. return handle
  298. },
  299. },
  300. },
  301. } as unknown as Agent
  302. const run = await startInProcessRun(request(parentWithAbortAtHandoff, controller.signal), {})
  303. expect(ctx.agents.get(run.id)).toBeDefined()
  304. await expect(run.result).resolves.toEqual({ output: [], stopReason: 'aborted' })
  305. await run.dispose()
  306. expect(ctx.agents.list()).toHaveLength(beforeAgents)
  307. expect(ctx.sessions.list()).toHaveLength(beforeSessions)
  308. })
  309. })