subagent-inprocess.spec.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  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('rejects invalid and exceeded depth before publication', async () => {
  55. const { parent } = await setup([])
  56. await expect(startInProcessRun({ ...request(parent), maxDepth: -1 }, {}))
  57. .rejects.toThrow('non-negative safe integer')
  58. await expect(startInProcessRun({ ...request(parent), maxDepth: 0 }, {}))
  59. .rejects.toMatchObject({ name: 'SubagentDepthError' })
  60. for (const value of [Number.NaN, 1.5, -1, -0, Number.MAX_SAFE_INTEGER + 1]) {
  61. const malformed = { options: { subagentDepth: value } } as unknown as Agent
  62. await expect(startInProcessRun(request(malformed), {}))
  63. .rejects.toThrow('agent subagentDepth must be a non-negative safe integer')
  64. }
  65. const maxParent = { options: { subagentDepth: Number.MAX_SAFE_INTEGER } } as unknown as Agent
  66. await expect(startInProcessRun(request(maxParent), {})).rejects.toBeInstanceOf(RangeError)
  67. })
  68. it('rejects an already-aborted request without publishing a child', async () => {
  69. const { ctx, parent } = await setup([])
  70. const beforeAgents = ctx.agents.list().length
  71. const beforeSessions = ctx.sessions.list().length
  72. const controller = new AbortController()
  73. controller.abort('too late')
  74. await expect(startInProcessRun(request(parent, controller.signal), {}))
  75. .rejects.toThrow('aborted before child publication')
  76. expect(ctx.agents.list()).toHaveLength(beforeAgents)
  77. expect(ctx.sessions.list()).toHaveLength(beforeSessions)
  78. })
  79. it('uses the request signal after publication and dispose as cancellation paths', async () => {
  80. const { parent } = await setup(['hang', 'hang'])
  81. const controller = new AbortController()
  82. const signalled = await startInProcessRun(request(parent, controller.signal), {})
  83. await new Promise(resolve => setTimeout(resolve, 30))
  84. controller.abort('stop child')
  85. await expect(signalled.result).resolves.toMatchObject({ stopReason: 'aborted' })
  86. await signalled.dispose()
  87. const disposed = await startInProcessRun(request(parent), {})
  88. await new Promise(resolve => setTimeout(resolve, 30))
  89. await disposed.dispose()
  90. await expect(disposed.result).resolves.toMatchObject({ stopReason: 'aborted' })
  91. })
  92. it('cleans a failed unpublished setup before rejecting', async () => {
  93. const { ctx, parent } = await setup([])
  94. const beforeAgents = ctx.agents.list().length
  95. const beforeSessions = ctx.sessions.list().length
  96. await expect(startInProcessRun({
  97. ...request(parent),
  98. toolFilter: { deny: ['unknown-tool'] },
  99. }, {})).rejects.toThrow('unknown global tool')
  100. expect(ctx.agents.list()).toHaveLength(beforeAgents)
  101. expect(ctx.sessions.list()).toHaveLength(beforeSessions)
  102. })
  103. it('closes the abort handoff after the factory detaches its creation listener', async () => {
  104. const { ctx, parent } = await setup([])
  105. const controller = new AbortController()
  106. const beforeAgents = ctx.agents.list().length
  107. const beforeSessions = ctx.sessions.list().length
  108. const parentWithAbortAtHandoff = {
  109. options: parent.options,
  110. session: parent.session,
  111. ctx: {
  112. agents: {
  113. create: async (options: Parameters<typeof ctx.agents.create>[0]) => {
  114. const handle = await ctx.agents.create(options)
  115. // `create()` has detached its creation-only listener, but the
  116. // provider continuation has not installed its live-run listener.
  117. controller.abort('handoff race')
  118. return handle
  119. },
  120. },
  121. },
  122. } as unknown as Agent
  123. await expect(startInProcessRun(request(parentWithAbortAtHandoff, controller.signal), {}))
  124. .rejects.toThrow('aborted before child publication')
  125. expect(ctx.agents.list()).toHaveLength(beforeAgents)
  126. expect(ctx.sessions.list()).toHaveLength(beforeSessions)
  127. })
  128. })