subagent-inprocess.spec.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { type Agent } from '@deepseek-ai/dsh-agent'
  4. import { SessionId } from '@deepseek-ai/dsh-session'
  5. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  6. import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
  7. import InvariantService from '@deepseek-ai/dsh-invariants'
  8. import * as SessionInvariant from '@deepseek-ai/dsh-session/invariant'
  9. import * as AgentInvariant from '@deepseek-ai/dsh-agent/invariant'
  10. import * as AgentLoopInvariant from '@deepseek-ai/dsh-agent-loop/invariant'
  11. import SubagentService from '@deepseek-ai/dsh-subagent'
  12. import { maxTokensResponse, MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
  13. import { startInProcessRun } from '../src/index.ts'
  14. type Script = ConstructorParameters<typeof MockAdapter>[0]
  15. async function mountInvariants(ctx: Context): Promise<void> {
  16. await ctx.plugin(InvariantService)
  17. await ctx.plugin(SessionInvariant)
  18. await ctx.plugin(AgentInvariant)
  19. await ctx.plugin(AgentLoopInvariant)
  20. }
  21. async function setup(script: Script) {
  22. const ctx = new Context()
  23. await mountAgentLoopTestDependencies(ctx)
  24. await mountInvariants(ctx)
  25. await ctx.plugin(AgentLoop, { agents: [] })
  26. await ctx.plugin(SubagentService)
  27. const adapter = new MockAdapter(script)
  28. ctx.llm.registerAdapter(['mock'], adapter)
  29. const parent = ctx.agentLoop.create(SessionId('parent'), { provider: 'mock', model: 'mock' })
  30. return { ctx, parent, adapter }
  31. }
  32. function request(parent: Agent, signal = new AbortController().signal) {
  33. return { prompt: [{ type: 'text' as const, text: 'child task' }], parent, signal }
  34. }
  35. function text(blocks: readonly { type: string; text?: string }[]): string {
  36. return blocks.filter(block => block.type === 'text').map(block => block.text).join('')
  37. }
  38. describe('startInProcessRun', () => {
  39. it('returns only after publication, drives a fresh child, and disposes it', async () => {
  40. const { ctx, parent } = await setup([textResponse('driver answer')])
  41. const run = await startInProcessRun(request(parent), {})
  42. expect(ctx.agents.get(run.id)).toBeDefined()
  43. const result = await run.result
  44. expect(result.stopReason).toBe('completed')
  45. expect(text(result.output)).toBe('driver answer')
  46. expect(ctx.agents.get(run.id)!.options.subagentDepth).toBe(1)
  47. await run.dispose()
  48. await run.dispose()
  49. expect(ctx.agents.get(run.id)).toBeUndefined()
  50. })
  51. it('reports the message-turn outcome when a later non-message turn completes during flush', async () => {
  52. const { ctx, parent } = await setup([maxTokensResponse('partial answer')])
  53. let injected = false
  54. ctx.on('session/flush', (session) => {
  55. if (injected || session.header.parentSession === undefined) return
  56. const lastEnd = session.events.findLast(event => event.type === 'turn/end')
  57. if (lastEnd?.type !== 'turn/end' || lastEnd.data.reason.kind !== 'max-tokens') return
  58. injected = true
  59. const turn = lastEnd.data.turn + 1
  60. session.append('turn/start', {
  61. turn,
  62. trigger: { kind: 'injection', source: { kind: 'plugin', plugin: 'late-metadata' } },
  63. })
  64. session.append('user/message', {
  65. content: [{ type: 'text', text: 'late metadata' }],
  66. source: { kind: 'plugin', plugin: 'late-metadata' },
  67. }, { surfaceOp: 'append' })
  68. session.append('turn/end', { turn, reason: { kind: 'completed' } })
  69. })
  70. const run = await startInProcessRun(request(parent), {})
  71. const result = await run.result
  72. const child = ctx.agents.get(run.id)!
  73. expect(child.session.events.findLast(event => event.type === 'turn/end'))
  74. .toMatchObject({ data: { reason: { kind: 'completed' } } })
  75. expect(result.stopReason).toBe('max-tokens')
  76. await run.dispose()
  77. })
  78. it('seeds a forked child but reads only the child-owned output', async () => {
  79. const { ctx, parent } = await setup([textResponse('parent answer'), textResponse('child answer')])
  80. parent.followup([{ type: 'text', text: 'parent question' }])
  81. await parent.whenIdle()
  82. const seed = parent.session.events.slice()
  83. const run = await startInProcessRun(request(parent), { seed })
  84. const result = await run.result
  85. expect(text(result.output)).toBe('child answer')
  86. const child = ctx.agents.get(run.id)!
  87. expect(child.session.header.seedLength).toBe(seed.length)
  88. expect(child.session.events.slice(0, seed.length)).toEqual(seed)
  89. await run.dispose()
  90. })
  91. it('persists the child depth in its session header', async () => {
  92. const { ctx, parent } = await setup([textResponse('child answer')])
  93. const run = await startInProcessRun(request(parent), {})
  94. await run.result
  95. // The recursion budget is durable session data, not only runtime options —
  96. // a depth that lived only in AgentOptions would reset to 0 on resume.
  97. expect(ctx.agents.get(run.id)!.session.header.delegationDepth).toBe(1)
  98. await run.dispose()
  99. })
  100. it('counts a RESUMED child by its persisted header depth, not the absent runtime depth', async () => {
  101. // Resume rebuilds runtime options, so the durable header must keep this
  102. // depth-1 child from delegating as though it were top-level.
  103. const { ctx } = await setup([textResponse('unused')])
  104. const resumed = (await ctx.agents.create({
  105. sessionId: SessionId('resumed-child'),
  106. meta: { parentSession: SessionId('root'), delegationDepth: 1 },
  107. agentOptions: { provider: 'mock', model: 'mock' },
  108. signal: new AbortController().signal,
  109. })).agent
  110. await expect(startInProcessRun({ ...request(resumed), maxDepth: 1 }, {}))
  111. .rejects.toMatchObject({ name: 'SubagentDepthError', attemptedDepth: 2, maxDepth: 1 })
  112. })
  113. it('lets runtime options deepen but never lower the persisted depth', async () => {
  114. const { ctx } = await setup([textResponse('unused')])
  115. const parent = (await ctx.agents.create({
  116. sessionId: SessionId('deep-parent'),
  117. meta: { delegationDepth: 2 },
  118. agentOptions: { provider: 'mock', model: 'mock', subagentDepth: 1 },
  119. signal: new AbortController().signal,
  120. })).agent
  121. // Persisted 2 vs runtime 1: the child is depth 3, so maxDepth 2 rejects.
  122. await expect(startInProcessRun({ ...request(parent), maxDepth: 2 }, {}))
  123. .rejects.toMatchObject({ name: 'SubagentDepthError', attemptedDepth: 3, maxDepth: 2 })
  124. })
  125. it('rejects invalid and exceeded depth before publication', async () => {
  126. const { parent } = await setup([])
  127. await expect(startInProcessRun({ ...request(parent), maxDepth: -1 }, {}))
  128. .rejects.toThrow('non-negative safe integer')
  129. await expect(startInProcessRun({ ...request(parent), maxDepth: 0 }, {}))
  130. .rejects.toMatchObject({ name: 'SubagentDepthError' })
  131. for (const value of [Number.NaN, 1.5, -1, -0, Number.MAX_SAFE_INTEGER + 1]) {
  132. const malformed = { options: { subagentDepth: value }, session: { header: {} } } as unknown as Agent
  133. await expect(startInProcessRun(request(malformed), {}))
  134. .rejects.toThrow('agent subagentDepth must be a non-negative safe integer')
  135. }
  136. const maxParent = { options: { subagentDepth: Number.MAX_SAFE_INTEGER }, session: { header: {} } } as unknown as Agent
  137. await expect(startInProcessRun(request(maxParent), {})).rejects.toBeInstanceOf(RangeError)
  138. })
  139. it('rejects an already-aborted request without publishing a child', async () => {
  140. const { ctx, parent } = await setup([])
  141. const beforeAgents = ctx.agents.list().length
  142. const beforeSessions = ctx.sessions.list().length
  143. const controller = new AbortController()
  144. controller.abort('too late')
  145. await expect(startInProcessRun(request(parent, controller.signal), {}))
  146. .rejects.toThrow('aborted before child publication')
  147. expect(ctx.agents.list()).toHaveLength(beforeAgents)
  148. expect(ctx.sessions.list()).toHaveLength(beforeSessions)
  149. })
  150. it('uses the request signal after publication and dispose as cancellation paths', async () => {
  151. const { parent, adapter } = await setup(['hang', 'hang'])
  152. const controller = new AbortController()
  153. const signalled = await startInProcessRun(request(parent, controller.signal), {})
  154. await new Promise(resolve => setTimeout(resolve, 30))
  155. controller.abort('stop child')
  156. await expect(signalled.result).resolves.toMatchObject({ stopReason: 'aborted' })
  157. expect(adapter.requests[0]?.signal?.reason).toEqual({ kind: 'parent' })
  158. const child = parent.ctx.agents.get(signalled.id)
  159. const turnEnd = child?.session.events.findLast(event => event.type === 'turn/end')
  160. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'aborted' })
  161. await signalled.dispose()
  162. const disposed = await startInProcessRun(request(parent), {})
  163. await new Promise(resolve => setTimeout(resolve, 30))
  164. await disposed.dispose()
  165. await expect(disposed.result).resolves.toMatchObject({ stopReason: 'aborted' })
  166. })
  167. it('cleans a failed unpublished setup before rejecting', async () => {
  168. const { ctx, parent } = await setup([])
  169. const beforeAgents = ctx.agents.list().length
  170. const beforeSessions = ctx.sessions.list().length
  171. await expect(startInProcessRun({
  172. ...request(parent),
  173. toolFilter: { deny: ['unknown-tool'] },
  174. }, {})).rejects.toThrow('unknown global tool')
  175. expect(ctx.agents.list()).toHaveLength(beforeAgents)
  176. expect(ctx.sessions.list()).toHaveLength(beforeSessions)
  177. })
  178. it('closes the abort handoff after the factory detaches its creation listener', async () => {
  179. const { ctx, parent } = await setup([])
  180. const controller = new AbortController()
  181. const beforeAgents = ctx.agents.list().length
  182. const beforeSessions = ctx.sessions.list().length
  183. const parentWithAbortAtHandoff = {
  184. options: parent.options,
  185. session: parent.session,
  186. ctx: {
  187. agents: {
  188. create: async (options: Parameters<typeof ctx.agents.create>[0]) => {
  189. const handle = await ctx.agents.create(options)
  190. // `create()` has detached its creation-only listener, but the
  191. // provider continuation has not installed its live-run listener.
  192. controller.abort('handoff race')
  193. return handle
  194. },
  195. },
  196. },
  197. } as unknown as Agent
  198. await expect(startInProcessRun(request(parentWithAbortAtHandoff, controller.signal), {}))
  199. .rejects.toThrow('aborted before child publication')
  200. expect(ctx.agents.list()).toHaveLength(beforeAgents)
  201. expect(ctx.sessions.list()).toHaveLength(beforeSessions)
  202. })
  203. })