subagent-fork.spec.ts 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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 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. /** 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 invariants plugin re-replays a seeded child
  24. * log on `session/created` (its freeze-check), so a malformed (unbalanced) fork
  25. * seed makes these tests THROW — that is the regression guard for the
  26. * completed-turn-prefix boundary.
  27. */
  28. async function setup(script: Script) {
  29. const ctx = new Context()
  30. await ctx.plugin(LlmService)
  31. await ctx.plugin(SessionStore)
  32. await ctx.plugin(SystemPrompt)
  33. await ctx.plugin(ToolRegistry)
  34. await ctx.plugin(AgentRegistry)
  35. await ctx.plugin(Invariants)
  36. await ctx.plugin(AgentLoop, { agents: [] })
  37. await ctx.plugin(SubagentService)
  38. await ctx.plugin(fork, { providerName: 'fork' })
  39. ctx.llm.registerAdapter(['mock'], new MockAdapter(script))
  40. const parent = ctx.agentLoop.create(AgentId('parent'), { model: 'mock' })
  41. return { ctx, parent }
  42. }
  43. function text(blocks: { type: string; text?: string }[]): string {
  44. return blocks.filter(b => b.type === 'text').map(b => b.text).join('')
  45. }
  46. describe('completedTurnPrefix', () => {
  47. it('returns an empty prefix for a parent that has never completed a turn', async () => {
  48. const { parent } = await setup([])
  49. expect(completedTurnPrefix(parent)).toEqual([])
  50. })
  51. it('returns the balanced prefix up to and including the last turn/end', async () => {
  52. const { parent } = await setup([textResponse('first'), textResponse('second')])
  53. parent.send([{ type: 'text', text: 'q1' }])
  54. await parent.whenIdle()
  55. parent.send([{ type: 'text', text: 'q2' }])
  56. await parent.whenIdle()
  57. const prefix = completedTurnPrefix(parent)
  58. // Ends exactly at the last turn/end; seq is contiguous from 0.
  59. expect(prefix.at(-1)?.type).toBe('turn/end')
  60. expect(prefix.map(e => e.seq)).toEqual(prefix.map((_, i) => i))
  61. // Both completed turns are present.
  62. expect(prefix.filter(e => e.type === 'turn/end')).toHaveLength(2)
  63. })
  64. })
  65. describe('dsh-subagent-fork', () => {
  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. expect(completedTurnPrefix(parent)).toEqual([])
  71. const run = ctx.subagents.start('fork', { prompt: [{ type: 'text', text: 'child q' }], parent })
  72. const result = await run.result
  73. expect(result.stopReason).toBe('completed')
  74. expect(text(result.output)).toBe('fresh child')
  75. const child = ctx.agents.get(run.id)!
  76. // Only the child's own turn — no seeded parent turns.
  77. expect(child.session.events.filter(e => e.type === 'turn/end')).toHaveLength(1)
  78. await run.dispose()
  79. })
  80. it('seeds the child with the parent\'s completed-turn prefix (child inherits context)', async () => {
  81. // Parent runs one turn, then we fork. The child's seeded log should contain
  82. // the parent's first turn, and the child should run its own new turn on top.
  83. const { ctx, parent } = await setup([textResponse('parent answer'), textResponse('child answer')])
  84. parent.send([{ type: 'text', text: 'parent question' }])
  85. await parent.whenIdle()
  86. const parentPrefixLen = parent.session.events.length
  87. const run = ctx.subagents.start('fork', { prompt: [{ type: 'text', text: 'child question' }], parent })
  88. const result = await run.result
  89. expect(result.stopReason).toBe('completed')
  90. expect(text(result.output)).toBe('child answer')
  91. const child = ctx.agents.get(run.id)!
  92. // The child's log STARTS with the parent's prefix (seeded), then its own turn.
  93. expect(child.session.events.length).toBeGreaterThan(parentPrefixLen)
  94. // The seeded prefix carried the parent's user message.
  95. const seededUser = child.session.events.slice(0, parentPrefixLen).find(e => e.type === 'user/message')
  96. expect(seededUser).toBeDefined()
  97. // Lineage stamped.
  98. expect(child.session.header.parentSession).toBe(parent.session.header.id)
  99. // The seed boundary is recorded on the header (= the seeded prefix length),
  100. // so a reload / replay harness can tell the inherited prefix from the
  101. // child's own events.
  102. expect(child.session.header.seedLength).toBe(parentPrefixLen)
  103. await run.dispose()
  104. })
  105. it('produces an invariant-CLEAN seed: forking mid-turn excludes the open turn', async () => {
  106. // Drive the parent so it has ONE completed turn, then start a SECOND turn
  107. // that is still open (a hanging model call), and fork while it's in flight.
  108. // The fork must seed only the completed first turn — an unbalanced seed
  109. // would make the invariants replay throw inside ctx.subagents.start.
  110. const { ctx, parent } = await setup([textResponse('done'), 'hang', textResponse('child')])
  111. parent.send([{ type: 'text', text: 'q1' }])
  112. await parent.whenIdle()
  113. // Start a second turn that hangs (open turn/start + open step, never ends).
  114. parent.send([{ type: 'text', text: 'q2' }])
  115. await new Promise(r => setTimeout(r, 20)) // let the hanging turn open
  116. // Forking now must NOT throw (the open second turn is excluded from the seed).
  117. const run = ctx.subagents.start('fork', { prompt: [{ type: 'text', text: 'child q' }], parent })
  118. const result = await run.result
  119. expect(result.stopReason).toBe('completed')
  120. expect(text(result.output)).toBe('child')
  121. const child = ctx.agents.get(run.id)!
  122. // The child's seed has exactly the ONE completed parent turn (the open one excluded).
  123. const seedTurnEnds = child.session.events.filter(e => e.type === 'turn/end')
  124. // 1 from the seeded parent turn + 1 from the child's own completed turn.
  125. expect(seedTurnEnds.length).toBe(2)
  126. parent.cancel()
  127. await run.dispose()
  128. })
  129. it('captures structured output through the shipped plugin (seeded child, driver runtime)', async () => {
  130. const { ctx, parent } = await setup([
  131. textResponse('parent turn'),
  132. toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 9 }),
  133. ])
  134. parent.send([{ type: 'text', text: 'warm up' }])
  135. await parent.whenIdle()
  136. const run = ctx.subagents.start('fork', {
  137. prompt: [{ type: 'text', text: 'report structured' }],
  138. parent,
  139. outputSchema: { type: 'object', properties: { answer: { type: 'number' } }, required: ['answer'] },
  140. })
  141. const result = await run.result
  142. expect(result.stopReason).toBe('completed')
  143. expect(result.structured).toEqual({ answer: 9 })
  144. // Run-scoped runtime: nothing stays registered after the settle.
  145. expect(ctx.tools.get(STRUCTURED_OUTPUT_TOOL)).toBeUndefined()
  146. await run.dispose()
  147. })
  148. it('does NOT return the seeded parent output when the child produces no message of its own', async () => {
  149. // Regression: readResult must scope to the child's OWN events (after the
  150. // seed). The parent completes a turn with a distinctive assistant message,
  151. // then the fork child's own turn finishes with a bare `stop` and NO
  152. // assistant/message. Scanning the whole (seeded) log would return the
  153. // parent's "parent stale" message with stopReason 'completed'; scoped to the
  154. // child's own events the output is empty.
  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 = ctx.subagents.start('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. })