subagent-inprocess.spec.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { AgentId, type Agent } from '@deepseek-ai/dsh-agent'
  4. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  5. import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
  6. import * as Invariants from '@deepseek-ai/dsh-invariants'
  7. import SubagentService from '@deepseek-ai/dsh-subagent'
  8. import { MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
  9. import { depthOf, SubagentDepthError, startInProcessRun } from '../src/index.ts'
  10. type Script = ConstructorParameters<typeof MockAdapter>[0]
  11. async function setup(script: Script) {
  12. const ctx = new Context()
  13. await mountAgentLoopTestDependencies(ctx)
  14. await ctx.plugin(Invariants)
  15. await ctx.plugin(AgentLoop, { agents: [] })
  16. await ctx.plugin(SubagentService)
  17. ctx.llm.registerAdapter(['mock'], new MockAdapter(script))
  18. const parent = ctx.agentLoop.create(AgentId('parent'), { model: 'mock' })
  19. return { ctx, parent }
  20. }
  21. function request(parent: Agent, signal = new AbortController().signal) {
  22. return { prompt: [{ type: 'text' as const, text: 'child task' }], parent, signal }
  23. }
  24. function text(blocks: readonly { type: string; text?: string }[]): string {
  25. return blocks.filter(block => block.type === 'text').map(block => block.text).join('')
  26. }
  27. describe('depthOf', () => {
  28. it('reads zero for a top-level agent and an explicit child depth', async () => {
  29. const { parent } = await setup([])
  30. expect(depthOf(parent)).toBe(0)
  31. expect(depthOf({ options: { subagentDepth: 3 } } as unknown as Agent)).toBe(3)
  32. })
  33. it.each([Number.NaN, 1.5, -1, -0, Number.MAX_SAFE_INTEGER + 1])('rejects malformed depth %s', (value) => {
  34. expect(() => depthOf({ options: { subagentDepth: value } } as unknown as Agent))
  35. .toThrow('non-negative safe integer')
  36. })
  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(depthOf(ctx.agents.get(run.id)!)).toBe(1)
  47. await run.dispose()
  48. await run.dispose()
  49. expect(ctx.agents.get(run.id)).toBeUndefined()
  50. })
  51. it('seeds a forked child but reads only the child-owned output', async () => {
  52. const { ctx, parent } = await setup([textResponse('parent answer'), textResponse('child answer')])
  53. parent.send([{ type: 'text', text: 'parent question' }])
  54. await parent.whenIdle()
  55. const seed = parent.session.events.slice()
  56. const run = await startInProcessRun(request(parent), { seed })
  57. const result = await run.result
  58. expect(text(result.output)).toBe('child answer')
  59. const child = ctx.agents.get(run.id)!
  60. expect(child.session.header.seedLength).toBe(seed.length)
  61. expect(child.session.events.slice(0, seed.length)).toEqual(seed)
  62. await run.dispose()
  63. })
  64. it('rejects invalid and exceeded depth before publication', async () => {
  65. const { parent } = await setup([])
  66. await expect(startInProcessRun({ ...request(parent), maxDepth: -1 }, {}))
  67. .rejects.toThrow('non-negative safe integer')
  68. await expect(startInProcessRun({ ...request(parent), maxDepth: 0 }, {}))
  69. .rejects.toBeInstanceOf(SubagentDepthError)
  70. const maxParent = { options: { subagentDepth: Number.MAX_SAFE_INTEGER } } as unknown as Agent
  71. await expect(startInProcessRun(request(maxParent), {})).rejects.toBeInstanceOf(RangeError)
  72. })
  73. it('rejects an already-aborted request without publishing a child', async () => {
  74. const { ctx, parent } = await setup([])
  75. const beforeAgents = ctx.agents.list().length
  76. const beforeSessions = ctx.sessions.list().length
  77. const controller = new AbortController()
  78. controller.abort('too late')
  79. await expect(startInProcessRun(request(parent, controller.signal), {}))
  80. .rejects.toThrow('aborted before child publication')
  81. expect(ctx.agents.list()).toHaveLength(beforeAgents)
  82. expect(ctx.sessions.list()).toHaveLength(beforeSessions)
  83. })
  84. it('uses the request signal after publication and dispose as cancellation paths', async () => {
  85. const { parent } = await setup(['hang', 'hang'])
  86. const controller = new AbortController()
  87. const signalled = await startInProcessRun(request(parent, controller.signal), {})
  88. await new Promise(resolve => setTimeout(resolve, 30))
  89. controller.abort('stop child')
  90. await expect(signalled.result).resolves.toMatchObject({ stopReason: 'aborted' })
  91. await signalled.dispose()
  92. const disposed = await startInProcessRun(request(parent), {})
  93. await new Promise(resolve => setTimeout(resolve, 30))
  94. await disposed.dispose()
  95. await expect(disposed.result).resolves.toMatchObject({ stopReason: 'aborted' })
  96. })
  97. it('cleans a failed unpublished setup before rejecting', async () => {
  98. const { ctx, parent } = await setup([])
  99. const beforeAgents = ctx.agents.list().length
  100. const beforeSessions = ctx.sessions.list().length
  101. await expect(startInProcessRun({
  102. ...request(parent),
  103. toolFilter: { deny: ['unknown-tool'] },
  104. }, {})).rejects.toThrow('unknown global tool')
  105. expect(ctx.agents.list()).toHaveLength(beforeAgents)
  106. expect(ctx.sessions.list()).toHaveLength(beforeSessions)
  107. })
  108. it('closes the abort handoff after the factory detaches its creation listener', async () => {
  109. const { ctx, parent } = await setup([])
  110. const controller = new AbortController()
  111. const beforeAgents = ctx.agents.list().length
  112. const beforeSessions = ctx.sessions.list().length
  113. const parentWithAbortAtHandoff = {
  114. options: parent.options,
  115. session: parent.session,
  116. ctx: {
  117. agents: {
  118. create: async (options: Parameters<typeof ctx.agents.create>[0]) => {
  119. const handle = await ctx.agents.create(options)
  120. // `create()` has detached its creation-only listener, but the
  121. // provider continuation has not installed its live-run listener.
  122. controller.abort('handoff race')
  123. return handle
  124. },
  125. },
  126. },
  127. } as unknown as Agent
  128. await expect(startInProcessRun(request(parentWithAbortAtHandoff, controller.signal), {}))
  129. .rejects.toThrow('aborted before child publication')
  130. expect(ctx.agents.list()).toHaveLength(beforeAgents)
  131. expect(ctx.sessions.list()).toHaveLength(beforeSessions)
  132. })
  133. })