subagent-inprocess.spec.ts 8.3 KB

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