subagent-fork.spec.ts 13 KB

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