subagent-fork.spec.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import Loader from '@cordisjs/plugin-loader'
  4. import AgentRegistry from '@deepseek-ai/dsh-agent'
  5. import { SessionId } from '@deepseek-ai/dsh-session'
  6. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  7. import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
  8. import InvariantService from '@deepseek-ai/dsh-invariants'
  9. import * as SessionInvariant from '@deepseek-ai/dsh-session/invariant'
  10. import * as AgentInvariant from '@deepseek-ai/dsh-agent/invariant'
  11. import * as AgentLoopInvariant from '@deepseek-ai/dsh-agent-loop/invariant'
  12. import SubagentService, { type SubagentStartRequest } from '@deepseek-ai/dsh-subagent'
  13. import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
  14. import type { StreamChunk } from '@deepseek-ai/dsh-llm'
  15. import * as fork from '../src/index.ts'
  16. import { STRUCTURED_OUTPUT_TOOL } from '@deepseek-ai/dsh-subagent-inprocess'
  17. type Script = ConstructorParameters<typeof MockAdapter>[0]
  18. async function mountInvariants(ctx: Context): Promise<void> {
  19. await ctx.plugin(InvariantService)
  20. await ctx.plugin(SessionInvariant)
  21. await ctx.plugin(AgentInvariant)
  22. await ctx.plugin(AgentLoopInvariant)
  23. }
  24. function start(ctx: Context, provider: string, request: Omit<SubagentStartRequest, 'signal'> & { signal?: AbortSignal }) {
  25. return ctx.subagents.start(provider, { signal: request.signal ?? new AbortController().signal, ...request })
  26. }
  27. /** A bare `stop` finish that streams no content → the turn ends `completed`
  28. * with NO `assistant/message` of its own. */
  29. const emptyStop: StreamChunk[] = [{ type: 'finish', reason: { kind: 'stop' } }]
  30. /**
  31. * Drives the REAL fork backend with a real loop + scripted mock MODEL + the
  32. * real invariant service and package companions. The session contribution replays a seeded child log on
  33. * `session/created`, so a malformed (unbalanced) fork seed makes these tests
  34. * THROW — that is the regression guard for the completed-turn-prefix boundary.
  35. */
  36. async function setup(script: Script) {
  37. const ctx = new Context()
  38. await mountAgentLoopTestDependencies(ctx)
  39. await mountInvariants(ctx)
  40. await ctx.plugin(AgentLoop, { agents: [] })
  41. await ctx.plugin(SubagentService)
  42. await ctx.plugin(fork, { providerName: 'fork' })
  43. ctx.llm.registerAdapter(['mock'], new MockAdapter(script))
  44. const parent = ctx.agentLoop.create(SessionId('parent'), { provider: 'mock', model: 'mock' })
  45. return { ctx, parent }
  46. }
  47. function text(blocks: { type: string; text?: string }[]): string {
  48. return blocks.filter(b => b.type === 'text').map(b => b.text).join('')
  49. }
  50. describe('dsh-subagent-fork', () => {
  51. it('emits subagent/start only after the seeded child is published', async () => {
  52. const { ctx, parent } = await setup([textResponse('child answer')])
  53. let childAtStart: ReturnType<typeof ctx.agents.get>
  54. ctx.on('subagent/start', (info) => {
  55. if (info.provider === 'fork') childAtStart = ctx.agents.get(info.id)
  56. })
  57. const starting = start(ctx, 'fork', { prompt: [{ type: 'text', text: 'child q' }], parent })
  58. expect(childAtStart).toBeUndefined()
  59. const run = await starting
  60. expect(childAtStart).toBe(ctx.agents.get(run.id))
  61. expect(childAtStart?.id).toBe(run.id)
  62. await run.result
  63. await run.dispose()
  64. })
  65. it('forks an UNSEEDED (fresh) child when the parent has no completed turn', async () => {
  66. // The parent has never completed a turn → empty prefix → the provider omits
  67. // the seed → the child runs fresh. Exercises the `seed.length > 0` false arm.
  68. const { ctx, parent } = await setup([textResponse('fresh child')])
  69. const run = await start(ctx, 'fork', { prompt: [{ type: 'text', text: 'child q' }], parent })
  70. const result = await run.result
  71. expect(result.stopReason).toBe('completed')
  72. expect(text(result.output)).toBe('fresh child')
  73. const child = ctx.agents.get(run.id)!
  74. // Only the child's own turn — no seeded parent turns.
  75. expect(child.session.events.filter(e => e.type === 'turn/end')).toHaveLength(1)
  76. expect(child.session.header.seedLength).toBeUndefined()
  77. await run.dispose()
  78. })
  79. it('seeds every completed parent turn through the last turn/end', async () => {
  80. const { ctx, parent } = await setup([textResponse('first'), textResponse('second'), textResponse('child')])
  81. parent.followup({ content: [{ type: 'text', text: 'q1' }], source: { kind: 'user' } })
  82. await parent.whenIdle()
  83. parent.followup({ content: [{ type: 'text', text: 'q2' }], source: { kind: 'user' } })
  84. await parent.whenIdle()
  85. const parentPrefixLen = parent.session.events.length
  86. const run = await start(ctx, 'fork', { prompt: [{ type: 'text', text: 'child q' }], parent })
  87. await run.result
  88. const child = ctx.agents.get(run.id)!
  89. expect(child.session.header.seedLength).toBe(parentPrefixLen)
  90. expect(child.session.events.slice(0, parentPrefixLen).at(-1)?.type).toBe('turn/end')
  91. expect(child.session.events.slice(0, parentPrefixLen).filter(e => e.type === 'turn/end')).toHaveLength(2)
  92. await run.dispose()
  93. })
  94. it('seeds the child with the parent\'s completed-turn prefix (child inherits context)', async () => {
  95. // Parent runs one turn, then we fork. The child's seeded log should contain
  96. // the parent's first turn, and the child should run its own new turn on top.
  97. const { ctx, parent } = await setup([textResponse('parent answer'), textResponse('child answer')])
  98. parent.followup({ content: [{ type: 'text', text: 'parent question' }], source: { kind: 'user' } })
  99. await parent.whenIdle()
  100. const parentPrefixLen = parent.session.events.length
  101. const run = await start(ctx, 'fork', { prompt: [{ type: 'text', text: 'child question' }], parent })
  102. const result = await run.result
  103. expect(result.stopReason).toBe('completed')
  104. expect(text(result.output)).toBe('child answer')
  105. const child = ctx.agents.get(run.id)!
  106. // The child's log STARTS with the parent's prefix (seeded), then its own turn.
  107. expect(child.session.events.length).toBeGreaterThan(parentPrefixLen)
  108. // The seeded prefix carried the parent's user message.
  109. const seededUser = child.session.events.slice(0, parentPrefixLen).find(e => e.type === 'user/message')
  110. expect(seededUser).toBeDefined()
  111. // Lineage stamped.
  112. expect(child.session.header.parentSession).toBe(parent.session.header.id)
  113. // The seed boundary is recorded on the header (= the seeded prefix length),
  114. // so a reload / replay harness can tell the inherited prefix from the
  115. // child's own events.
  116. expect(child.session.header.seedLength).toBe(parentPrefixLen)
  117. await run.dispose()
  118. })
  119. it('produces an invariant-CLEAN seed: forking mid-turn excludes the open turn', async () => {
  120. // Drive the parent so it has one completed turn, then start a SECOND turn that is still
  121. // open (a hanging model call), and fork while it's in flight. The seed must stop after the
  122. // balanced first turn; including the open turn would fail invariant replay during start.
  123. const { ctx, parent } = await setup([textResponse('done'), 'hang', textResponse('child')])
  124. parent.followup({ content: [{ type: 'text', text: 'q1' }], source: { kind: 'user' } })
  125. await parent.whenIdle()
  126. // Start a second turn that hangs (open turn/start + open step, never ends).
  127. parent.followup({ content: [{ type: 'text', text: 'q2' }], source: { kind: 'user' } })
  128. await new Promise(r => setTimeout(r, 20)) // let the hanging turn open
  129. // Forking now must NOT throw (the open second turn is excluded from the seed).
  130. const run = await start(ctx, 'fork', { prompt: [{ type: 'text', text: 'child q' }], parent })
  131. const result = await run.result
  132. expect(result.stopReason).toBe('completed')
  133. expect(text(result.output)).toBe('child')
  134. const child = ctx.agents.get(run.id)!
  135. // The child's seed has exactly the ONE completed parent turn (the open one excluded).
  136. const seedTurnEnds = child.session.events.filter(e => e.type === 'turn/end')
  137. // 1 from the seeded parent turn + 1 from the child's own completed turn.
  138. expect(seedTurnEnds.length).toBe(2)
  139. parent.cancel({ kind: 'user' })
  140. await run.dispose()
  141. })
  142. it('captures structured output through the shipped plugin (seeded child, driver runtime)', async () => {
  143. const { ctx, parent } = await setup([
  144. textResponse('parent turn'),
  145. toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 9 }),
  146. ])
  147. parent.followup({ content: [{ type: 'text', text: 'warm up' }], source: { kind: 'user' } })
  148. await parent.whenIdle()
  149. const run = await start(ctx, 'fork', {
  150. prompt: [{ type: 'text', text: 'report structured' }],
  151. parent,
  152. outputSchema: { type: 'object', properties: { answer: { type: 'number' } }, required: ['answer'] },
  153. })
  154. const result = await run.result
  155. expect(result.stopReason).toBe('completed')
  156. expect(result.structured).toEqual({ answer: 9 })
  157. // Run-scoped runtime: nothing stays registered after the settle.
  158. expect(ctx.tools.get(STRUCTURED_OUTPUT_TOOL)).toBeUndefined()
  159. await run.dispose()
  160. })
  161. it('does NOT return the seeded parent output when the child produces no message of its own', async () => {
  162. // `readResult` must scan only child-owned events after the seed. The child emits no assistant
  163. // message, so scanning the whole log would incorrectly return the parent's distinctive text.
  164. const { ctx, parent } = await setup([textResponse('parent stale'), emptyStop])
  165. parent.followup({ content: [{ type: 'text', text: 'parent question' }], source: { kind: 'user' } })
  166. await parent.whenIdle()
  167. const run = await start(ctx, 'fork', { prompt: [{ type: 'text', text: 'child question' }], parent })
  168. const result = await run.result
  169. // The child completed its own (empty) turn — completed, but with NO output
  170. // borrowed from the seeded parent prefix.
  171. expect(result.stopReason).toBe('completed')
  172. expect(result.output).toEqual([])
  173. await run.dispose()
  174. })
  175. it('advertises every start-time capability (depthLimit, outputSchema, toolFilter, persona)', async () => {
  176. const { ctx } = await setup([])
  177. expect(ctx.subagents.getProvider('fork')!.capabilities).toEqual({ outputSchema: true, depthLimit: true, toolFilter: true, persona: true })
  178. })
  179. it('unregisters the provider when its fiber is disposed (HMR safety)', async () => {
  180. const ctx = new Context()
  181. await ctx.plugin(SubagentService)
  182. await ctx.plugin(AgentRegistry)
  183. const fiber = await ctx.plugin(fork, { providerName: 'fork' })
  184. expect(ctx.subagents.list()).toEqual(['fork'])
  185. await fiber.dispose()
  186. expect(ctx.subagents.list()).toEqual([])
  187. })
  188. it('has the namespace-plugin export shape (no stray default)', () => {
  189. expect('default' in fork).toBe(false)
  190. expect(fork.name).toBe('subagent-fork')
  191. expect(fork.inject).toEqual(['subagents'])
  192. const loader = Object.create(Loader.prototype) as Loader
  193. const unwrapped = loader.unwrapExports(fork) as Record<string, unknown>
  194. expect(unwrapped).toBe(fork)
  195. expect(unwrapped.name).toBe('subagent-fork')
  196. expect(unwrapped.inject).toEqual(['subagents'])
  197. expect(typeof unwrapped.apply).toBe('function')
  198. })
  199. })