subagent-fork.spec.ts 11 KB

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