subagent-in-process-driver.spec.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. import { ToolCallId, createUserMessage } from '@deepseek-ai/dsh-llm'
  2. import { describe, expect, it } from 'vitest'
  3. import { Context } from '@deepseek-ai/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 InvariantRegistry 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 SubagentRuntime, { snapshotSubagentDescriptor } from '@deepseek-ai/dsh-subagent'
  13. import { defineContentToolFixture } from '@deepseek-ai/dsh-tools'
  14. import { maxTokensResponse, MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
  15. import { startInProcessRun } from '../src/index.ts'
  16. type Script = ConstructorParameters<typeof MockAdapter>[0]
  17. async function mountInvariants(ctx: Context): Promise<void> {
  18. await ctx.plugin(InvariantRegistry)
  19. await ctx.plugin(SessionInvariant)
  20. await ctx.plugin(AgentInvariant)
  21. await ctx.plugin(AgentLoopInvariant)
  22. }
  23. async function setup(script: Script, parentOptions: Partial<AgentOptions> = {}) {
  24. const ctx = new Context()
  25. await mountAgentLoopTestDependencies(ctx)
  26. await mountInvariants(ctx)
  27. await ctx.plugin(AgentLoop, { agents: [] })
  28. await ctx.plugin(SubagentRuntime)
  29. const adapter = new MockAdapter(script)
  30. ctx.llm.registerAdapter(['mock'], adapter)
  31. const parent = await ctx.agentLoop.create(SessionId('parent'), { provider: 'mock', model: 'mock', ...parentOptions })
  32. return { ctx, parent, adapter }
  33. }
  34. function request(parent: Agent, signal = new AbortController().signal) {
  35. return {
  36. label: 'child task',
  37. prompt: [{ type: 'text' as const, text: 'child task' }],
  38. parent,
  39. signal,
  40. descriptor: snapshotSubagentDescriptor({
  41. mode: 'one-shot',
  42. provider: 'test',
  43. label: 'child task',
  44. }),
  45. }
  46. }
  47. function text(blocks: readonly { type: string; text?: string }[]): string {
  48. return blocks.filter(block => block.type === 'text').map(block => block.text).join('')
  49. }
  50. describe('startInProcessRun', () => {
  51. it('returns only after publication, drives a fresh child, and disposes it', async () => {
  52. const { ctx, parent } = await setup([textResponse('driver answer')])
  53. const run = await startInProcessRun(request(parent), {})
  54. expect(ctx.agents.get(run.id)).toBeDefined()
  55. const result = await run.result
  56. expect(result.stopReason).toBe('completed')
  57. expect(text(result.output)).toBe('driver answer')
  58. expect(ctx.agents.get(run.id)!.options.subagentDepth).toBe(1)
  59. await run.dispose()
  60. await run.dispose()
  61. expect(ctx.agents.get(run.id)).toBeUndefined()
  62. })
  63. it('uses explicit child model selectors when the parent has none and preserves its cwd', async () => {
  64. const { ctx } = await setup([textResponse('driver answer')])
  65. const parent = await ctx.agentLoop.create(SessionId('bare-parent'), {}, { cwd: '/workspace' })
  66. const run = await startInProcessRun({
  67. ...request(parent),
  68. agentOptions: { provider: 'mock', model: 'mock' },
  69. }, {})
  70. const child = ctx.agents.get(run.id)!
  71. expect(child.options).toMatchObject({ provider: 'mock', model: 'mock' })
  72. expect(child.session.header.cwd).toBe('/workspace')
  73. await expect(run.result).resolves.toMatchObject({ stopReason: 'completed' })
  74. await run.dispose()
  75. })
  76. it('reports a prompt a pre-step rejection discarded as refusal, not completion', async () => {
  77. const { ctx, parent } = await setup([])
  78. // A UserPromptSubmit deny or a policy plugin: the child claims its prompt,
  79. // the rejection discards it, and the turn closes `blocked` with no step.
  80. ctx.on('agent/pre-step', async ({ agent: subject }, next) => {
  81. if (subject === parent) return next()
  82. return { kind: 'reject' as const }
  83. })
  84. const run = await startInProcessRun(request(parent), {})
  85. await expect(run.result).resolves.toMatchObject({ stopReason: 'refusal' })
  86. await run.dispose()
  87. })
  88. it('does not add a final durability checkpoint to a foreground run', async () => {
  89. const { ctx, parent } = await setup([textResponse('driver answer')])
  90. let flushes = 0
  91. ctx.on('session/flush', (session) => {
  92. if (session.header.parentSession === undefined) return
  93. flushes++
  94. throw new Error('disk full')
  95. })
  96. const run = await startInProcessRun(request(parent), {})
  97. await expect(run.result).resolves.toMatchObject({ stopReason: 'completed' })
  98. expect(flushes).toBe(0)
  99. await run.dispose()
  100. })
  101. it('keeps published run and handle disposal failures on separate channels', async () => {
  102. const { ctx, parent } = await setup([])
  103. const runError = new Error('published run failed')
  104. const disposalError = new Error('published handle disposal failed')
  105. const beforeAgents = ctx.agents.list().length
  106. const beforeSessions = ctx.sessions.list().length
  107. const parentWithFailedDisposal = {
  108. options: parent.options,
  109. session: parent.session,
  110. ctx: {
  111. get: () => undefined,
  112. agents: {
  113. create: async (options: Parameters<typeof ctx.agents.create>[0]) => {
  114. const handle = await ctx.agents.create(options)
  115. handle.agent.followup = () => { throw runError }
  116. return {
  117. ...handle,
  118. dispose: async () => {
  119. await handle.dispose()
  120. throw disposalError
  121. },
  122. }
  123. },
  124. },
  125. },
  126. } as unknown as Agent
  127. const run = await startInProcessRun(request(parentWithFailedDisposal), {})
  128. expect(ctx.agents.get(run.id)).toBeDefined()
  129. await expect(run.result).rejects.toBe(runError)
  130. await expect(run.dispose()).rejects.toBe(disposalError)
  131. expect(ctx.agents.list()).toHaveLength(beforeAgents)
  132. expect(ctx.sessions.list()).toHaveLength(beforeSessions)
  133. })
  134. it('reports the turn outcome when later metadata is appended during flush', async () => {
  135. const { ctx, parent } = await setup([maxTokensResponse('partial answer')])
  136. let injected = false
  137. ctx.on('session/flush', (session) => {
  138. if (injected || session.header.parentSession === undefined) return
  139. const lastEnd = session.snapshotEvents().findLast(event => event.type === 'turn/end')
  140. if (lastEnd?.type !== 'turn/end' || lastEnd.data.reason.kind !== 'max-tokens') return
  141. injected = true
  142. session.append('user/message', createUserMessage({
  143. content: [{ type: 'text', text: 'late metadata' }],
  144. source: { kind: 'plugin', plugin: 'late-metadata' },
  145. }), { surfaceOp: 'append' })
  146. })
  147. const run = await startInProcessRun(request(parent), {})
  148. const result = await run.result
  149. const child = ctx.agents.get(run.id)!
  150. expect(injected).toBe(false)
  151. expect(child.session.snapshotEvents().findLast(event => event.type === 'turn/end'))
  152. .toMatchObject({ data: { reason: { kind: 'max-tokens' } } })
  153. expect(result.stopReason).toBe('max-tokens')
  154. await run.dispose()
  155. })
  156. it('keeps earlier streamed text when the final step appends an empty usage-only message', async () => {
  157. // A tool-only max-tokens step records an empty assistant/message for
  158. // usage. The result retains the preceding assistant output.
  159. const { ctx, parent } = await setup([
  160. toolCallResponse('t1', 'noop', {}, 'partial one'),
  161. [
  162. { type: 'block-start', index: 0, blockType: 'tool-call' },
  163. { type: 'tool-call-delta', index: 0, id: ToolCallId('t2'), name: 'noop', argumentsDelta: '{}' },
  164. { type: 'block-end', index: 0, block: { type: 'tool-call', id: ToolCallId('t2'), name: 'noop', arguments: '{}' } },
  165. { type: 'usage', usage: { inputTokens: 20, outputTokens: 5 } },
  166. { type: 'finish', reason: { kind: 'max-tokens' } },
  167. ],
  168. ])
  169. const disposeNoop = ctx.tools.register(defineContentToolFixture({
  170. name: 'noop', description: 'probe', parameters: {},
  171. execute() { return Promise.resolve([{ type: 'text', text: 'noop result' }]) },
  172. }))
  173. const run = await startInProcessRun(request(parent), {})
  174. const result = await run.result
  175. expect(result.stopReason).toBe('max-tokens')
  176. expect(text(result.output)).toBe('partial one')
  177. await run.dispose()
  178. disposeNoop()
  179. })
  180. it('seeds a forked child but reads only the child-owned output', async () => {
  181. const { ctx, parent } = await setup([textResponse('parent answer'), textResponse('child answer')])
  182. parent.followup(createUserMessage({ content: [{ type: 'text', text: 'parent question' }], source: { kind: 'user' } }))
  183. await parent.whenIdle()
  184. const seed = parent.session.snapshotEvents()
  185. const run = await startInProcessRun(request(parent), { seed })
  186. const result = await run.result
  187. expect(text(result.output)).toBe('child answer')
  188. const child = ctx.agents.get(run.id)!
  189. expect(child.session.header.isSeeded).toBe(true)
  190. expect(child.session.inheritedEventCount).toBe(seed.length)
  191. expect(child.session.snapshotEvents().slice(0, seed.length)).toEqual(seed)
  192. // The seeded `system/message` stays surface node 0: the child renders the
  193. // same prompt, so its loop appends no second system node.
  194. const seededSystem = seed.find(event => event.type === 'system/message')
  195. expect(seededSystem).toBeDefined()
  196. expect(child.session.snapshotEvents().filter(event => event.type === 'system/message')).toHaveLength(1)
  197. expect(child.session.surface.nodes[0]).toBe(seededSystem?.seq)
  198. expect(child.session.deriveMessages()[0]).toEqual(parent.session.deriveMessages()[0])
  199. await run.dispose()
  200. })
  201. it('replaces a seeded system node in place when the forked child renders a different prompt', async () => {
  202. const { ctx, parent, adapter } = await setup([textResponse('parent answer'), textResponse('child answer')])
  203. parent.followup(createUserMessage({ content: [{ type: 'text', text: 'parent question' }], source: { kind: 'user' } }))
  204. await parent.whenIdle()
  205. const seed = parent.session.snapshotEvents()
  206. const seededSystem = seed.find(event => event.type === 'system/message')
  207. if (seededSystem === undefined) throw new Error('the parent log lacks a system node')
  208. ctx.systemPrompt.section({ name: 'test:after-fork', order: 10, text: 'Registered after the fork seed.' })
  209. const run = await startInProcessRun(request(parent), { seed })
  210. await run.result
  211. const child = ctx.agents.get(run.id)!
  212. const systemNodes = child.session.snapshotEvents().filter(event => event.type === 'system/message')
  213. expect(systemNodes.map(event => event.seq)).toEqual([seededSystem.seq, systemNodes[1]?.seq])
  214. expect(systemNodes[1]?.surfaceOp).toEqual({ op: 'replace', startSeq: seededSystem.seq, endSeq: seededSystem.seq })
  215. expect(systemNodes[1]?.sourceEventSeqs).toEqual([seededSystem.seq])
  216. expect(child.session.surface.nodes[0]).toBe(systemNodes[1]?.seq)
  217. const childRequest = adapter.requests.at(-1)!
  218. expect(childRequest.system).toBeUndefined()
  219. expect(childRequest.messages[0]).toMatchObject({
  220. role: 'system',
  221. content: [{ type: 'text', text: expect.stringContaining('Registered after the fork seed.') as unknown }],
  222. })
  223. await run.dispose()
  224. })
  225. it('persists the child origin and depth in its session header', async () => {
  226. const { ctx, parent } = await setup([textResponse('child answer')])
  227. const run = await startInProcessRun(request(parent), {})
  228. await run.result
  229. // The recursion budget is durable session data, not only runtime options —
  230. // a depth that lived only in AgentOptions would reset to 0 on resume.
  231. expect(ctx.agents.get(run.id)!.session.header).toMatchObject({
  232. origin: 'subagent',
  233. delegationDepth: 1,
  234. })
  235. await run.dispose()
  236. })
  237. it('inherits the parent output-token cap and accepts an explicit child override', async () => {
  238. const { ctx, parent, adapter } = await setup(
  239. [textResponse('inherited'), textResponse('overridden')],
  240. { maxTokens: 111 },
  241. )
  242. const inherited = await startInProcessRun(request(parent), {})
  243. await inherited.result
  244. expect(adapter.requests[0]?.maxTokens).toBe(111)
  245. expect(ctx.agents.get(inherited.id)?.options.maxTokens).toBe(111)
  246. await inherited.dispose()
  247. const overridden = await startInProcessRun({
  248. ...request(parent),
  249. agentOptions: { maxTokens: 222 },
  250. }, {})
  251. await overridden.result
  252. expect(adapter.requests[1]?.maxTokens).toBe(222)
  253. expect(ctx.agents.get(overridden.id)?.options.maxTokens).toBe(222)
  254. await overridden.dispose()
  255. })
  256. it('counts a RESUMED child by its persisted header depth, not the absent runtime depth', async () => {
  257. // Resume rebuilds runtime options, so the durable header must keep this
  258. // depth-1 child from delegating as though it were top-level.
  259. const { ctx } = await setup([textResponse('unused')])
  260. const resumed = (await ctx.agents.create({
  261. sessionId: SessionId('resumed-child'),
  262. meta: { parentSession: SessionId('root'), delegationDepth: 1 },
  263. agentOptions: { provider: 'mock', model: 'mock' },
  264. signal: new AbortController().signal,
  265. })).agent
  266. await expect(startInProcessRun({ ...request(resumed), maxDepth: 1 }, {}))
  267. .rejects.toMatchObject({ name: 'SubagentDepthError', attemptedDepth: 2, maxDepth: 1 })
  268. })
  269. it('lets runtime options deepen but never lower the persisted depth', async () => {
  270. const { ctx } = await setup([textResponse('unused')])
  271. const parent = (await ctx.agents.create({
  272. sessionId: SessionId('deep-parent'),
  273. meta: { delegationDepth: 2 },
  274. agentOptions: { provider: 'mock', model: 'mock', subagentDepth: 1 },
  275. signal: new AbortController().signal,
  276. })).agent
  277. // Persisted 2 vs runtime 1: the child is depth 3, so maxDepth 2 rejects.
  278. await expect(startInProcessRun({ ...request(parent), maxDepth: 2 }, {}))
  279. .rejects.toMatchObject({ name: 'SubagentDepthError', attemptedDepth: 3, maxDepth: 2 })
  280. })
  281. it('rejects invalid and exceeded depth before publication', async () => {
  282. const { parent } = await setup([])
  283. await expect(startInProcessRun({ ...request(parent), maxDepth: -1 }, {}))
  284. .rejects.toThrow('non-negative safe integer')
  285. await expect(startInProcessRun({ ...request(parent), maxDepth: 0 }, {}))
  286. .rejects.toMatchObject({ name: 'SubagentDepthError' })
  287. for (const value of [Number.NaN, 1.5, -1, -0, Number.MAX_SAFE_INTEGER + 1]) {
  288. const malformed = { options: { subagentDepth: value }, session: { header: {} } } as unknown as Agent
  289. await expect(startInProcessRun(request(malformed), {}))
  290. .rejects.toThrow('agent subagentDepth must be a non-negative safe integer')
  291. }
  292. const maxParent = { options: { subagentDepth: Number.MAX_SAFE_INTEGER }, session: { header: {} } } as unknown as Agent
  293. await expect(startInProcessRun(request(maxParent), {})).rejects.toBeInstanceOf(RangeError)
  294. })
  295. it('rejects an already-aborted request without publishing a child', async () => {
  296. const { ctx, parent } = await setup([])
  297. const beforeAgents = ctx.agents.list().length
  298. const beforeSessions = ctx.sessions.list().length
  299. const controller = new AbortController()
  300. controller.abort('too late')
  301. await expect(startInProcessRun(request(parent, controller.signal), {}))
  302. .rejects.toThrow('aborted before child publication')
  303. expect(ctx.agents.list()).toHaveLength(beforeAgents)
  304. expect(ctx.sessions.list()).toHaveLength(beforeSessions)
  305. })
  306. it('stamps only the resolved depth when neither parent nor request declares a model route', async () => {
  307. // The one-shot analogue of the deleted resume coverage ("resumes without
  308. // inventing undeclared agent model options"): a bare parent with no request
  309. // agentOptions yields a child whose options carry ONLY the stamped depth —
  310. // no provider/model is fabricated, so the child's turn errors for want of a
  311. // route rather than silently adopting one.
  312. const { ctx } = await setup([])
  313. const parent = await ctx.agentLoop.create(SessionId('routeless-parent'), {})
  314. const run = await startInProcessRun(request(parent), {})
  315. const child = ctx.agents.get(run.id)!
  316. expect(child.options).toEqual({ subagentDepth: 1 })
  317. await expect(run.result).resolves.toMatchObject({ stopReason: 'error' })
  318. await run.dispose()
  319. })
  320. it('uses the request signal after publication and dispose as cancellation paths', async () => {
  321. const { parent, adapter } = await setup(['hang', 'hang'])
  322. const controller = new AbortController()
  323. const signalled = await startInProcessRun(request(parent, controller.signal), {})
  324. await new Promise(resolve => setTimeout(resolve, 30))
  325. controller.abort('stop child')
  326. // No step completed a message, so the text streamed before the abort is
  327. // the cancelled run's output.
  328. await expect(signalled.result).resolves.toEqual({
  329. output: [{ type: 'text', text: 'partial' }],
  330. stopReason: 'aborted',
  331. })
  332. expect(adapter.requests[0]?.signal?.reason).toEqual({ kind: 'parent' })
  333. const child = parent.ctx.agents.get(signalled.id)
  334. const turnEnd = child?.session.snapshotEvents().findLast(event => event.type === 'turn/end')
  335. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'aborted', reason: { kind: 'parent' } })
  336. await signalled.dispose()
  337. const disposed = await startInProcessRun(request(parent), {})
  338. await new Promise(resolve => setTimeout(resolve, 30))
  339. await disposed.dispose()
  340. await expect(disposed.result).resolves.toMatchObject({ stopReason: 'aborted' })
  341. })
  342. it('cleans a failed unpublished setup before rejecting', async () => {
  343. const { ctx, parent } = await setup([])
  344. const beforeAgents = ctx.agents.list().length
  345. const beforeSessions = ctx.sessions.list().length
  346. await expect(startInProcessRun({
  347. ...request(parent),
  348. toolFilter: { deny: ['unknown-tool'] },
  349. }, {})).rejects.toThrow('unknown global tool')
  350. expect(ctx.agents.list()).toHaveLength(beforeAgents)
  351. expect(ctx.sessions.list()).toHaveLength(beforeSessions)
  352. })
  353. it('treats abort after factory publication as a cancelled run with an id', async () => {
  354. const { ctx, parent } = await setup([])
  355. const controller = new AbortController()
  356. const beforeAgents = ctx.agents.list().length
  357. const beforeSessions = ctx.sessions.list().length
  358. const parentWithAbortAtHandoff = {
  359. options: parent.options,
  360. session: parent.session,
  361. ctx: {
  362. // The driver's synchronous inheritance capture probes both policy
  363. // services opportunistically; this stub composes neither.
  364. get: () => undefined,
  365. agents: {
  366. create: async (options: Parameters<typeof ctx.agents.create>[0]) => {
  367. const handle = await ctx.agents.create(options)
  368. // `create()` has detached its creation-only listener, but the
  369. // published run has not installed its live listener yet.
  370. controller.abort('handoff race')
  371. return handle
  372. },
  373. },
  374. },
  375. } as unknown as Agent
  376. const run = await startInProcessRun(request(parentWithAbortAtHandoff, controller.signal), {})
  377. expect(ctx.agents.get(run.id)).toBeDefined()
  378. await expect(run.result).resolves.toEqual({ output: [], stopReason: 'aborted' })
  379. await run.dispose()
  380. expect(ctx.agents.list()).toHaveLength(beforeAgents)
  381. expect(ctx.sessions.list()).toHaveLength(beforeSessions)
  382. })
  383. })