subagent-inprocess.spec.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. import { CallId, 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 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 { 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(InvariantService)
  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(SubagentService)
  29. const adapter = new MockAdapter(script)
  30. ctx.llm.registerAdapter(['mock'], adapter)
  31. const parent = 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 = 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.events.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.events.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: CallId('t2'), name: 'noop', argumentsDelta: '{}' },
  164. { type: 'block-end', index: 0, block: { type: 'tool-call', id: CallId('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.events.slice()
  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.seedLength).toBe(seed.length)
  190. expect(child.session.events.slice(0, seed.length)).toEqual(seed)
  191. await run.dispose()
  192. })
  193. it('persists the child origin and depth in its session header', async () => {
  194. const { ctx, parent } = await setup([textResponse('child answer')])
  195. const run = await startInProcessRun(request(parent), {})
  196. await run.result
  197. // The recursion budget is durable session data, not only runtime options —
  198. // a depth that lived only in AgentOptions would reset to 0 on resume.
  199. expect(ctx.agents.get(run.id)!.session.header).toMatchObject({
  200. origin: 'subagent',
  201. delegationDepth: 1,
  202. })
  203. await run.dispose()
  204. })
  205. it('inherits the parent output-token cap and accepts an explicit child override', async () => {
  206. const { ctx, parent, adapter } = await setup(
  207. [textResponse('inherited'), textResponse('overridden')],
  208. { maxTokens: 111 },
  209. )
  210. const inherited = await startInProcessRun(request(parent), {})
  211. await inherited.result
  212. expect(adapter.requests[0]?.maxTokens).toBe(111)
  213. expect(ctx.agents.get(inherited.id)?.options.maxTokens).toBe(111)
  214. await inherited.dispose()
  215. const overridden = await startInProcessRun({
  216. ...request(parent),
  217. agentOptions: { maxTokens: 222 },
  218. }, {})
  219. await overridden.result
  220. expect(adapter.requests[1]?.maxTokens).toBe(222)
  221. expect(ctx.agents.get(overridden.id)?.options.maxTokens).toBe(222)
  222. await overridden.dispose()
  223. })
  224. it('counts a RESUMED child by its persisted header depth, not the absent runtime depth', async () => {
  225. // Resume rebuilds runtime options, so the durable header must keep this
  226. // depth-1 child from delegating as though it were top-level.
  227. const { ctx } = await setup([textResponse('unused')])
  228. const resumed = (await ctx.agents.create({
  229. sessionId: SessionId('resumed-child'),
  230. meta: { parentSession: SessionId('root'), delegationDepth: 1 },
  231. agentOptions: { provider: 'mock', model: 'mock' },
  232. signal: new AbortController().signal,
  233. })).agent
  234. await expect(startInProcessRun({ ...request(resumed), maxDepth: 1 }, {}))
  235. .rejects.toMatchObject({ name: 'SubagentDepthError', attemptedDepth: 2, maxDepth: 1 })
  236. })
  237. it('lets runtime options deepen but never lower the persisted depth', async () => {
  238. const { ctx } = await setup([textResponse('unused')])
  239. const parent = (await ctx.agents.create({
  240. sessionId: SessionId('deep-parent'),
  241. meta: { delegationDepth: 2 },
  242. agentOptions: { provider: 'mock', model: 'mock', subagentDepth: 1 },
  243. signal: new AbortController().signal,
  244. })).agent
  245. // Persisted 2 vs runtime 1: the child is depth 3, so maxDepth 2 rejects.
  246. await expect(startInProcessRun({ ...request(parent), maxDepth: 2 }, {}))
  247. .rejects.toMatchObject({ name: 'SubagentDepthError', attemptedDepth: 3, maxDepth: 2 })
  248. })
  249. it('rejects invalid and exceeded depth before publication', async () => {
  250. const { parent } = await setup([])
  251. await expect(startInProcessRun({ ...request(parent), maxDepth: -1 }, {}))
  252. .rejects.toThrow('non-negative safe integer')
  253. await expect(startInProcessRun({ ...request(parent), maxDepth: 0 }, {}))
  254. .rejects.toMatchObject({ name: 'SubagentDepthError' })
  255. for (const value of [Number.NaN, 1.5, -1, -0, Number.MAX_SAFE_INTEGER + 1]) {
  256. const malformed = { options: { subagentDepth: value }, session: { header: {} } } as unknown as Agent
  257. await expect(startInProcessRun(request(malformed), {}))
  258. .rejects.toThrow('agent subagentDepth must be a non-negative safe integer')
  259. }
  260. const maxParent = { options: { subagentDepth: Number.MAX_SAFE_INTEGER }, session: { header: {} } } as unknown as Agent
  261. await expect(startInProcessRun(request(maxParent), {})).rejects.toBeInstanceOf(RangeError)
  262. })
  263. it('rejects an already-aborted request without publishing a child', async () => {
  264. const { ctx, parent } = await setup([])
  265. const beforeAgents = ctx.agents.list().length
  266. const beforeSessions = ctx.sessions.list().length
  267. const controller = new AbortController()
  268. controller.abort('too late')
  269. await expect(startInProcessRun(request(parent, controller.signal), {}))
  270. .rejects.toThrow('aborted before child publication')
  271. expect(ctx.agents.list()).toHaveLength(beforeAgents)
  272. expect(ctx.sessions.list()).toHaveLength(beforeSessions)
  273. })
  274. it('stamps only the resolved depth when neither parent nor request declares a model route', async () => {
  275. // The one-shot analogue of the deleted resume coverage ("resumes without
  276. // inventing undeclared agent model options"): a bare parent with no request
  277. // agentOptions yields a child whose options carry ONLY the stamped depth —
  278. // no provider/model is fabricated, so the child's turn errors for want of a
  279. // route rather than silently adopting one.
  280. const { ctx } = await setup([])
  281. const parent = ctx.agentLoop.create(SessionId('routeless-parent'), {})
  282. const run = await startInProcessRun(request(parent), {})
  283. const child = ctx.agents.get(run.id)!
  284. expect(child.options).toEqual({ subagentDepth: 1 })
  285. await expect(run.result).resolves.toMatchObject({ stopReason: 'error' })
  286. await run.dispose()
  287. })
  288. it('uses the request signal after publication and dispose as cancellation paths', async () => {
  289. const { parent, adapter } = await setup(['hang', 'hang'])
  290. const controller = new AbortController()
  291. const signalled = await startInProcessRun(request(parent, controller.signal), {})
  292. await new Promise(resolve => setTimeout(resolve, 30))
  293. controller.abort('stop child')
  294. // No step completed a message, so the text streamed before the abort is
  295. // the cancelled run's output.
  296. await expect(signalled.result).resolves.toEqual({
  297. output: [{ type: 'text', text: 'partial' }],
  298. stopReason: 'aborted',
  299. })
  300. expect(adapter.requests[0]?.signal?.reason).toEqual({ kind: 'parent' })
  301. const child = parent.ctx.agents.get(signalled.id)
  302. const turnEnd = child?.session.events.findLast(event => event.type === 'turn/end')
  303. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'aborted', reason: { kind: 'parent' } })
  304. await signalled.dispose()
  305. const disposed = await startInProcessRun(request(parent), {})
  306. await new Promise(resolve => setTimeout(resolve, 30))
  307. await disposed.dispose()
  308. await expect(disposed.result).resolves.toMatchObject({ stopReason: 'aborted' })
  309. })
  310. it('cleans a failed unpublished setup before rejecting', async () => {
  311. const { ctx, parent } = await setup([])
  312. const beforeAgents = ctx.agents.list().length
  313. const beforeSessions = ctx.sessions.list().length
  314. await expect(startInProcessRun({
  315. ...request(parent),
  316. toolFilter: { deny: ['unknown-tool'] },
  317. }, {})).rejects.toThrow('unknown inherited tool')
  318. expect(ctx.agents.list()).toHaveLength(beforeAgents)
  319. expect(ctx.sessions.list()).toHaveLength(beforeSessions)
  320. })
  321. it('treats abort after factory publication as a cancelled run with an id', async () => {
  322. const { ctx, parent } = await setup([])
  323. const controller = new AbortController()
  324. const beforeAgents = ctx.agents.list().length
  325. const beforeSessions = ctx.sessions.list().length
  326. const parentWithAbortAtHandoff = {
  327. options: parent.options,
  328. session: parent.session,
  329. ctx: {
  330. // The driver's synchronous inheritance capture probes both policy
  331. // services opportunistically; this stub composes neither.
  332. get: () => undefined,
  333. agents: {
  334. create: async (options: Parameters<typeof ctx.agents.create>[0]) => {
  335. const handle = await ctx.agents.create(options)
  336. // `create()` has detached its creation-only listener, but the
  337. // published run has not installed its live listener yet.
  338. controller.abort('handoff race')
  339. return handle
  340. },
  341. },
  342. },
  343. } as unknown as Agent
  344. const run = await startInProcessRun(request(parentWithAbortAtHandoff, controller.signal), {})
  345. expect(ctx.agents.get(run.id)).toBeDefined()
  346. await expect(run.result).resolves.toEqual({ output: [], stopReason: 'aborted' })
  347. await run.dispose()
  348. expect(ctx.agents.list()).toHaveLength(beforeAgents)
  349. expect(ctx.sessions.list()).toHaveLength(beforeSessions)
  350. })
  351. })