1
0

subagent-fork.spec.ts 10 KB

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