subagent-inprocess.spec.ts 6.7 KB

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