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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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 SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  15. import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
  16. import type { StreamChunk } from '@deepseek-ai/dsh-llm'
  17. import * as fork from '../src/index.ts'
  18. import { STRUCTURED_OUTPUT_TOOL } from '@deepseek-ai/dsh-subagent-in-process-driver'
  19. type Script = ConstructorParameters<typeof MockAdapter>[0]
  20. async function mountInvariants(ctx: Context): Promise<void> {
  21. await ctx.plugin(InvariantRegistry)
  22. await ctx.plugin(SessionInvariant)
  23. await ctx.plugin(AgentInvariant)
  24. await ctx.plugin(AgentLoopInvariant)
  25. }
  26. function start(ctx: Context, provider: string, request: Omit<SubagentStartRequest, 'signal'> & { signal?: AbortSignal }) {
  27. return ctx.subagents.start(provider, { signal: request.signal ?? new AbortController().signal, ...request })
  28. }
  29. /** A bare `stop` finish that streams no content → the turn ends `completed`
  30. * with NO `assistant/message` of its own. */
  31. const emptyStop: StreamChunk[] = [{ type: 'finish', reason: { kind: 'stop' } }]
  32. /**
  33. * Drives the REAL fork backend with a real loop + scripted mock MODEL + the
  34. * real invariant service and package companions. The session contribution replays a seeded child log on
  35. * `session/created`, so a malformed (unbalanced) fork seed makes these tests
  36. * THROW — that is the regression guard for the completed-turn-prefix boundary.
  37. */
  38. async function setup(script: Script) {
  39. const ctx = new Context()
  40. await mountAgentLoopTestDependencies(ctx)
  41. await mountInvariants(ctx)
  42. await ctx.plugin(AgentLoop, { agents: [] })
  43. await ctx.plugin(SubagentRuntime)
  44. await ctx.plugin(fork, { providerName: 'fork' })
  45. ctx.llm.registerAdapter(['mock'], new MockAdapter(script))
  46. const parent = await ctx.agentLoop.create(SessionId('parent'), { provider: 'mock', model: 'mock' })
  47. return { ctx, parent }
  48. }
  49. function text(blocks: { type: string; text?: string }[]): string {
  50. return blocks.filter(b => b.type === 'text').map(b => b.text).join('')
  51. }
  52. describe('dsh-subagent-fork-in-process', () => {
  53. it('emits subagent/start only after the seeded child is published', async () => {
  54. const { ctx, parent } = await setup([textResponse('child answer')])
  55. let childAtStart: ReturnType<typeof ctx.agents.get>
  56. ctx.on('subagent/start', (info) => {
  57. if (info.provider === 'fork') childAtStart = ctx.agents.get(info.id)
  58. })
  59. const starting = start(ctx, 'fork', { prompt: [{ type: 'text', text: 'child q' }], parent })
  60. expect(childAtStart).toBeUndefined()
  61. const run = await starting
  62. expect(childAtStart).toBe(ctx.agents.get(run.id))
  63. expect(childAtStart?.id).toBe(run.id)
  64. await run.result
  65. await run.dispose()
  66. })
  67. it('forks an UNSEEDED (fresh) child when the parent has no completed turn', async () => {
  68. // The parent has never completed a turn → empty prefix → the provider omits
  69. // the seed → the child runs fresh. Exercises the `seed.length > 0` false arm.
  70. const { ctx, parent } = await setup([textResponse('fresh child')])
  71. const run = await start(ctx, '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.snapshotEvents().filter(e => e.type === 'turn/end')).toHaveLength(1)
  78. expect(child.session.header.isSeeded).toBe(false)
  79. expect(child.session.inheritedEventCount).toBe(0)
  80. await run.dispose()
  81. })
  82. it('seeds every completed parent turn through the last turn/end', async () => {
  83. const { ctx, parent } = await setup([textResponse('first'), textResponse('second'), textResponse('child')])
  84. parent.followup(createUserMessage({ content: [{ type: 'text', text: 'q1' }], source: { kind: 'user' } }))
  85. await parent.whenIdle()
  86. parent.followup(createUserMessage({ content: [{ type: 'text', text: 'q2' }], source: { kind: 'user' } }))
  87. await parent.whenIdle()
  88. const parentPrefixLen = parent.session.snapshotEvents().length
  89. const run = await start(ctx, 'fork', { prompt: [{ type: 'text', text: 'child q' }], parent })
  90. await run.result
  91. const child = ctx.agents.get(run.id)!
  92. expect(child.session.header.isSeeded).toBe(true)
  93. expect(child.session.inheritedEventCount).toBe(parentPrefixLen)
  94. expect(child.session.snapshotEvents().slice(0, parentPrefixLen).at(-1)?.type).toBe('turn/end')
  95. expect(child.session.snapshotEvents().slice(0, parentPrefixLen).filter(e => e.type === 'turn/end')).toHaveLength(2)
  96. await run.dispose()
  97. })
  98. it('seeds the child with the parent\'s completed-turn prefix (child inherits context)', async () => {
  99. const { ctx, parent } = await setup([textResponse('parent answer'), textResponse('child answer')])
  100. parent.followup(createUserMessage({ content: [{ type: 'text', text: 'parent question' }], source: { kind: 'user' } }))
  101. await parent.whenIdle()
  102. const parentPrefixLen = parent.session.snapshotEvents().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.snapshotEvents().length).toBeGreaterThan(parentPrefixLen)
  110. // The seeded prefix carried the parent's user message.
  111. const seededUser = child.session.snapshotEvents().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. // Logical metadata records lineage while Session state retains the exact
  116. // inherited cut for reload and replay.
  117. expect(child.session.header.isSeeded).toBe(true)
  118. expect(child.session.inheritedEventCount).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.followup(createUserMessage({ content: [{ type: 'text', text: 'q1' }], source: { kind: 'user' } }))
  127. await parent.whenIdle()
  128. // Start a second turn that hangs (open turn/start + open step, never ends).
  129. parent.followup(createUserMessage({ content: [{ type: 'text', text: 'q2' }], source: { kind: 'user' } }))
  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.snapshotEvents().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({ kind: 'user' })
  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.followup(createUserMessage({ content: [{ type: 'text', text: 'warm up' }], source: { kind: 'user' } }))
  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. 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', async () => {
  177. const { ctx } = await setup([])
  178. expect(ctx.subagents.getProvider('fork')!.capabilities).toEqual({
  179. agentOptions: true,
  180. outputSchema: true,
  181. depthLimit: true,
  182. toolFilter: true,
  183. persona: true,
  184. })
  185. })
  186. it('unregisters the provider when its fiber is disposed (HMR safety)', async () => {
  187. const ctx = new Context()
  188. await ctx.plugin(SessionProjectionRegistry)
  189. await ctx.plugin(SubagentRuntime)
  190. await ctx.plugin(AgentRegistry)
  191. const fiber = await ctx.plugin(fork, { providerName: 'fork' })
  192. expect(ctx.subagents.list()).toEqual(['fork'])
  193. await fiber.dispose()
  194. expect(ctx.subagents.list()).toEqual([])
  195. })
  196. it('contributes the completed-turn prefix as a continuable child\'s seed', async () => {
  197. const { ctx, parent } = await setup([textResponse('parent turn'), textResponse('child answer')])
  198. const provider = ctx.subagents.getProvider('fork')!
  199. const signal = new AbortController().signal
  200. // Before any completed parent turn there is nothing to inherit, so the
  201. // child starts fresh rather than carrying an empty seed.
  202. const fresh = await provider.prepareContinuable!({
  203. sessionId: SessionId('continuable-fresh'),
  204. parent,
  205. signal,
  206. })
  207. expect(fresh.seed).toBeUndefined()
  208. // Complete one parent turn, then the prefix is captured once at creation.
  209. parent.followup(createUserMessage({ content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } }))
  210. await parent.whenIdle()
  211. const seeded = await provider.prepareContinuable!({
  212. sessionId: SessionId('continuable-seeded'),
  213. parent,
  214. signal,
  215. })
  216. expect(seeded.seed).toBeDefined()
  217. const lastSeeded = seeded.seed!.at(-1)
  218. // The seed ends at a completed turn, so it replays as a valid child log.
  219. expect(lastSeeded?.type).toBe('turn/end')
  220. expect(seeded.seed!.map(event => event.seq)).toEqual(seeded.seed!.map((_event, index) => index))
  221. })
  222. it('has the namespace-plugin export shape (no stray default)', () => {
  223. expect('default' in fork).toBe(false)
  224. expect(fork.name).toBe('subagent-fork-in-process')
  225. expect(fork.inject).toEqual(['subagents'])
  226. const loader = Object.create(Loader.prototype) as Loader
  227. const unwrapped = loader.unwrapExports(fork) as Record<string, unknown>
  228. expect(unwrapped).toBe(fork)
  229. expect(unwrapped.name).toBe('subagent-fork-in-process')
  230. expect(unwrapped.inject).toEqual(['subagents'])
  231. expect(typeof unwrapped.apply).toBe('function')
  232. })
  233. })