subagent-fork-in-process.spec.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  2. import { describe, expect, it } from 'vitest'
  3. import { Context } from '@deepseek-ai/cordis'
  4. import Loader from '@deepseek-ai/cordis-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 InvariantRegistry 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 SubagentRuntime, { 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-in-process-driver'
  18. type Script = ConstructorParameters<typeof MockAdapter>[0]
  19. async function mountInvariants(ctx: Context): Promise<void> {
  20. await ctx.plugin(InvariantRegistry)
  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(SubagentRuntime)
  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-in-process', () => {
  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. const { ctx, parent } = await setup([textResponse('parent answer'), textResponse('child answer')])
  97. parent.followup(createUserMessage({ content: [{ type: 'text', text: 'parent question' }], source: { kind: 'user' } }))
  98. await parent.whenIdle()
  99. const parentPrefixLen = parent.session.events.length
  100. const run = await start(ctx, 'fork', { prompt: [{ type: 'text', text: 'child question' }], parent })
  101. const result = await run.result
  102. expect(result.stopReason).toBe('completed')
  103. expect(text(result.output)).toBe('child answer')
  104. const child = ctx.agents.get(run.id)!
  105. // The child's log STARTS with the parent's prefix (seeded), then its own turn.
  106. expect(child.session.events.length).toBeGreaterThan(parentPrefixLen)
  107. // The seeded prefix carried the parent's user message.
  108. const seededUser = child.session.events.slice(0, parentPrefixLen).find(e => e.type === 'user/message')
  109. expect(seededUser).toBeDefined()
  110. // Lineage stamped.
  111. expect(child.session.header.parentSession).toBe(parent.session.header.id)
  112. // The seed boundary is recorded on the header (= the seeded prefix length),
  113. // so a reload / replay harness can tell the inherited prefix from the
  114. // child's own events.
  115. expect(child.session.header.seedLength).toBe(parentPrefixLen)
  116. await run.dispose()
  117. })
  118. it('produces an invariant-CLEAN seed: forking mid-turn excludes the open turn', async () => {
  119. // Drive the parent so it has one completed turn, then start a SECOND turn that is still
  120. // open (a hanging model call), and fork while it's in flight. The seed must stop after the
  121. // balanced first turn; including the open turn would fail invariant replay during start.
  122. const { ctx, parent } = await setup([textResponse('done'), 'hang', textResponse('child')])
  123. parent.followup(createUserMessage({ content: [{ type: 'text', text: 'q1' }], source: { kind: 'user' } }))
  124. await parent.whenIdle()
  125. // Start a second turn that hangs (open turn/start + open step, never ends).
  126. parent.followup(createUserMessage({ content: [{ type: 'text', text: 'q2' }], source: { kind: 'user' } }))
  127. await new Promise(r => setTimeout(r, 20)) // let the hanging turn open
  128. // Forking now must NOT throw (the open second turn is excluded from the seed).
  129. const run = await start(ctx, 'fork', { prompt: [{ type: 'text', text: 'child q' }], parent })
  130. const result = await run.result
  131. expect(result.stopReason).toBe('completed')
  132. expect(text(result.output)).toBe('child')
  133. const child = ctx.agents.get(run.id)!
  134. // The child's seed has exactly the ONE completed parent turn (the open one excluded).
  135. const seedTurnEnds = child.session.events.filter(e => e.type === 'turn/end')
  136. // 1 from the seeded parent turn + 1 from the child's own completed turn.
  137. expect(seedTurnEnds.length).toBe(2)
  138. parent.cancel({ kind: 'user' })
  139. await run.dispose()
  140. })
  141. it('captures structured output through the shipped plugin (seeded child, driver runtime)', async () => {
  142. const { ctx, parent } = await setup([
  143. textResponse('parent turn'),
  144. toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 9 }),
  145. ])
  146. parent.followup(createUserMessage({ content: [{ type: 'text', text: 'warm up' }], source: { kind: 'user' } }))
  147. await parent.whenIdle()
  148. const run = await start(ctx, 'fork', {
  149. prompt: [{ type: 'text', text: 'report structured' }],
  150. parent,
  151. outputSchema: { type: 'object', properties: { answer: { type: 'number' } }, required: ['answer'] },
  152. })
  153. const result = await run.result
  154. expect(result.stopReason).toBe('completed')
  155. expect(result.structured).toEqual({ answer: 9 })
  156. expect(ctx.tools.get(STRUCTURED_OUTPUT_TOOL)).toBeUndefined()
  157. await run.dispose()
  158. })
  159. it('does NOT return the seeded parent output when the child produces no message of its own', async () => {
  160. // `readResult` must scan only child-owned events after the seed. The child emits no assistant
  161. // message, so scanning the whole log would incorrectly return the parent's distinctive text.
  162. const { ctx, parent } = await setup([textResponse('parent stale'), emptyStop])
  163. parent.followup(createUserMessage({ content: [{ type: 'text', text: 'parent question' }], source: { kind: 'user' } }))
  164. await parent.whenIdle()
  165. const run = await start(ctx, 'fork', { prompt: [{ type: 'text', text: 'child question' }], parent })
  166. const result = await run.result
  167. // The child completed its own (empty) turn — completed, but with NO output
  168. // borrowed from the seeded parent prefix.
  169. expect(result.stopReason).toBe('completed')
  170. expect(result.output).toEqual([])
  171. await run.dispose()
  172. })
  173. it('advertises every start-time capability', async () => {
  174. const { ctx } = await setup([])
  175. expect(ctx.subagents.getProvider('fork')!.capabilities).toEqual({
  176. agentOptions: true,
  177. outputSchema: true,
  178. depthLimit: true,
  179. toolFilter: true,
  180. persona: true,
  181. })
  182. })
  183. it('unregisters the provider when its fiber is disposed (HMR safety)', async () => {
  184. const ctx = new Context()
  185. await ctx.plugin(SubagentRuntime)
  186. await ctx.plugin(AgentRegistry)
  187. const fiber = await ctx.plugin(fork, { providerName: 'fork' })
  188. expect(ctx.subagents.list()).toEqual(['fork'])
  189. await fiber.dispose()
  190. expect(ctx.subagents.list()).toEqual([])
  191. })
  192. it('contributes the completed-turn prefix as a continuable child\'s seed', async () => {
  193. const { ctx, parent } = await setup([textResponse('parent turn'), textResponse('child answer')])
  194. const provider = ctx.subagents.getProvider('fork')!
  195. const signal = new AbortController().signal
  196. // Before any completed parent turn there is nothing to inherit, so the
  197. // child starts fresh rather than carrying an empty seed.
  198. const fresh = await provider.prepareContinuable!({
  199. sessionId: SessionId('continuable-fresh'),
  200. parent,
  201. signal,
  202. })
  203. expect(fresh.seed).toBeUndefined()
  204. // Complete one parent turn, then the prefix is captured once at creation.
  205. parent.followup(createUserMessage({ content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } }))
  206. await parent.whenIdle()
  207. const seeded = await provider.prepareContinuable!({
  208. sessionId: SessionId('continuable-seeded'),
  209. parent,
  210. signal,
  211. })
  212. expect(seeded.seed).toBeDefined()
  213. const lastSeeded = seeded.seed!.at(-1)
  214. // The seed ends at a completed turn, so it replays as a valid child log.
  215. expect(lastSeeded?.type).toBe('turn/end')
  216. expect(seeded.seed!.map(event => event.seq)).toEqual(seeded.seed!.map((_event, index) => index))
  217. })
  218. it('has the namespace-plugin export shape (no stray default)', () => {
  219. expect('default' in fork).toBe(false)
  220. expect(fork.name).toBe('subagent-fork-in-process')
  221. expect(fork.inject).toEqual(['subagents'])
  222. const loader = Object.create(Loader.prototype) as Loader
  223. const unwrapped = loader.unwrapExports(fork) as Record<string, unknown>
  224. expect(unwrapped).toBe(fork)
  225. expect(unwrapped.name).toBe('subagent-fork-in-process')
  226. expect(unwrapped.inject).toEqual(['subagents'])
  227. expect(typeof unwrapped.apply).toBe('function')
  228. })
  229. })