subagent-fork.spec.ts 10 KB

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