integration.spec.ts 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import LlmService, { type StreamChunk } from '@deepseek-ai/dsh-llm'
  4. import SessionStore, { SessionId, type SessionEvent } from '@deepseek-ai/dsh-session'
  5. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  6. import ToolRegistry, { defineContentToolFixture } from '@deepseek-ai/dsh-tools'
  7. import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent'
  8. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  9. import PlanModeService, { foldPlanMode } from '@deepseek-ai/dsh-plan-mode'
  10. import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
  11. const PLAN_CONFIG = { section: 'Test plan mode instructions.' }
  12. /**
  13. * Full-loop integration: a scripted mock model drives the REAL plan-mode plugin
  14. * through the agent loop — the pending-intent flush at the request boundary, the
  15. * assembly the soft layer shapes (the exit tool + mode section), and the
  16. * `request/header` snapshots every transition leaves.
  17. * Only the model is mocked; the loop, the session log, and the plugin are
  18. * real.
  19. */
  20. async function harness(adapter: MockAdapter): Promise<Context> {
  21. const ctx = new Context()
  22. await ctx.plugin(LlmService)
  23. await ctx.plugin(SessionStore)
  24. await ctx.plugin(SystemPrompt)
  25. await ctx.plugin(ToolRegistry)
  26. await ctx.plugin(AgentRegistry)
  27. await ctx.plugin(AgentLoop, { agents: [] })
  28. await ctx.plugin(PlanModeService, PLAN_CONFIG)
  29. ctx.llm.registerAdapter(['mock'], adapter)
  30. for (const name of ['read', 'write']) {
  31. ctx.tools.register(defineContentToolFixture({
  32. name,
  33. description: `test tool ${name}`,
  34. parameters: {},
  35. execute: () => Promise.resolve([{ type: 'text', text: `ran ${name}` }]),
  36. }))
  37. }
  38. return ctx
  39. }
  40. function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
  41. return new Promise((resolve) => {
  42. const dispose = ctx.on('agent/status', (subject, status) => {
  43. if (subject === agent && status === 'idle') {
  44. dispose()
  45. resolve()
  46. }
  47. })
  48. })
  49. }
  50. function findEvent<T extends SessionEvent['type']>(
  51. log: readonly SessionEvent[],
  52. type: T,
  53. position: 'first' | 'last' = 'first',
  54. ): Extract<SessionEvent, { type: T }> {
  55. const found = position === 'first'
  56. ? log.find(event => event.type === type)
  57. : log.findLast(event => event.type === type)
  58. if (!found) throw new Error(`no ${type} event in the session log`)
  59. return found as Extract<SessionEvent, { type: T }>
  60. }
  61. describe('plan mode through the agent loop', () => {
  62. it('a pre-turn set() makes the FIRST header plan-shaped, and a non-shell call is guidance-constrained only', async () => {
  63. const adapter = new MockAdapter([
  64. toolCallResponse('call-1', 'write', {}, 'Writing during plan.'),
  65. textResponse('Noted in the plan.'),
  66. ])
  67. const ctx = await harness(adapter)
  68. const agent = ctx.agentLoop.create(SessionId('it-plan-seed'), { provider: 'mock', model: 'mock' })
  69. // Selected while idle: the pending intent flushes at the first
  70. // in-turn agent/step seam, before the first assembly.
  71. ctx.planMode.set(agent, true)
  72. agent.followup({ content: [{ type: 'text', text: 'explore the repo' }], source: { kind: 'user' } })
  73. await waitForIdle(ctx, agent)
  74. const log = agent.session.events
  75. const planMode = findEvent(log, 'plan/mode')
  76. const header = findEvent(log, 'request/header')
  77. expect(planMode.seq).toBeLessThan(header.seq)
  78. expect(header.data.reason).toBe('initial')
  79. expect(header.data.header.tools?.map(tool => tool.name)).toEqual(['exit_plan_mode', 'read', 'write'])
  80. expect(header.data.header.system).toContain('plan mode')
  81. // No tool gate: the write RUNS — plan restrains by the section's
  82. // guidance alone (enforcement lives on the independent sandbox/approval
  83. // axes). The mode itself stays plan throughout.
  84. const result = findEvent(log, 'tool/result')
  85. expect(result.data.isError).toBe(false)
  86. expect(foldPlanMode(log)).toBe(true)
  87. expect(log.some(event => event.type === 'user/message' && event.data.source.kind === 'plugin')).toBe(false)
  88. })
  89. it('a user flip between turns lands at the boundary: one notice and a changed header with stable tool schemas', async () => {
  90. const adapter = new MockAdapter([
  91. textResponse('First turn, default mode.'),
  92. textResponse('Second turn, plan mode.'),
  93. ])
  94. const ctx = await harness(adapter)
  95. const agent = ctx.agentLoop.create(SessionId('it-plan-flip'), { provider: 'mock', model: 'mock' })
  96. agent.followup({ content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } })
  97. await waitForIdle(ctx, agent)
  98. expect(foldPlanMode(agent.session.events)).toBe(false)
  99. const first = findEvent(agent.session.events, 'request/header')
  100. expect(first.data.header.tools?.map(tool => tool.name)).toEqual(['exit_plan_mode', 'read', 'write'])
  101. ctx.planMode.set(agent, true)
  102. agent.followup({ content: [{ type: 'text', text: 'now plan' }], source: { kind: 'user' } })
  103. await waitForIdle(ctx, agent)
  104. const log = agent.session.events
  105. expect(foldPlanMode(log)).toBe(true)
  106. const notices = log.filter(event => event.type === 'user/message' && event.data.source.kind === 'plugin')
  107. expect(notices).toHaveLength(1)
  108. expect(notices[0]?.type === 'user/message' && notices[0].data.content).toEqual([
  109. { type: 'text', text: 'The user switched this session to plan mode.' },
  110. ])
  111. // The changed request is logged as a complete snapshot.
  112. const second = findEvent(log, 'request/header', 'last')
  113. expect(second.data.reason).toBe('change')
  114. expect(second.data.header.tools?.map(tool => tool.name)).toEqual(['exit_plan_mode', 'read', 'write'])
  115. expect(second.data.header.tools).toEqual(first.data.header.tools)
  116. expect(second.data.header.system).toContain('plan mode')
  117. })
  118. it('a mode flip at error settlement shapes the retry before its assembly', async () => {
  119. const failedRequest = [{
  120. type: 'finish',
  121. reason: { kind: 'error', failure: { message: 'temporarily unavailable', code: 'SERVER', status: 503 } },
  122. }] satisfies StreamChunk[]
  123. const adapter = new MockAdapter([failedRequest, textResponse('Recovered in plan mode.')])
  124. const ctx = await harness(adapter)
  125. const agent = ctx.agentLoop.create(SessionId('it-plan-retry-flip'), { provider: 'mock', model: 'mock' })
  126. ctx.on('agent/request-error', async (
  127. subject, _turn, _step, _error, _failure, _priorFailures, _retryPolicy, _signal, next,
  128. ) => {
  129. if (subject !== agent) return next()
  130. ctx.planMode.set(agent, true)
  131. return { kind: 'retry' }
  132. })
  133. const idle = waitForIdle(ctx, agent)
  134. agent.followup({ content: [{ type: 'text', text: 'plan after the transient failure' }], source: { kind: 'user' } })
  135. await idle
  136. expect(adapter.requests).toHaveLength(2)
  137. expect(adapter.requests[0]?.system).not.toContain(PLAN_CONFIG.section)
  138. expect(adapter.requests[1]?.system).toContain(PLAN_CONFIG.section)
  139. expect(adapter.requests[1]?.tools).toEqual(adapter.requests[0]?.tools)
  140. const log = agent.session.events
  141. const planMode = findEvent(log, 'plan/mode')
  142. const firstEnd = log.find(event => event.type === 'step/end'
  143. && event.data.turn === 1 && event.data.step === 1)
  144. const retryStart = log.find(event => event.type === 'step/start'
  145. && event.data.turn === 2 && event.data.step === 1)
  146. expect(firstEnd?.seq).toBeLessThan(planMode.seq)
  147. expect(planMode.seq).toBeLessThan(retryStart?.seq ?? 0)
  148. expect(findEvent(log, 'request/header', 'last').data.header.system).toContain(PLAN_CONFIG.section)
  149. const notice = log.find(event => event.type === 'user/message' && event.data.source.kind === 'plugin')
  150. expect(notice?.type === 'user/message' && notice.data.content).toEqual([
  151. { type: 'text', text: 'The user switched this session to plan mode.' },
  152. ])
  153. })
  154. })