integration.spec.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. import { afterEach, describe, expect, it, vi } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
  4. import { tmpdir } from 'node:os'
  5. import { join } from 'node:path'
  6. import LlmService from '@deepseek-ai/dsh-llm'
  7. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  8. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  9. import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl'
  10. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  11. import ToolRegistry from '@deepseek-ai/dsh-tools'
  12. import AgentRegistry, { AgentId } from '@deepseek-ai/dsh-agent'
  13. import AgentLoop, { ReactLoopAgent } from '@deepseek-ai/dsh-agent-loop'
  14. import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
  15. import { BashTaskId } from '@deepseek-ai/dsh-bash'
  16. import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
  17. import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
  18. /**
  19. * Full-loop integration: a scripted mock model drives the REAL bash tool
  20. * through the agent loop, exercising the same seams a live model would
  21. * (tool/call + tool/result session events, agent.inject notifications).
  22. */
  23. async function harness(adapter: MockAdapter, sessionRoot?: string, dshHome?: string) {
  24. const ctx = new Context()
  25. await ctx.plugin(LlmService)
  26. await ctx.plugin(SessionStore)
  27. if (sessionRoot !== undefined) await ctx.plugin(SessionPersistenceJsonl, { root: sessionRoot })
  28. await ctx.plugin(SystemPrompt)
  29. await ctx.plugin(ToolRegistry)
  30. await ctx.plugin(AgentRegistry)
  31. await ctx.plugin(AgentLoop, { agents: [] })
  32. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
  33. await ctx.plugin(ToolBash, dshHome === undefined ? {} : { dshHome })
  34. ctx.llm.registerAdapter(['mock'], adapter)
  35. return ctx
  36. }
  37. const dirs: string[] = []
  38. afterEach(() => {
  39. vi.unstubAllEnvs()
  40. for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
  41. })
  42. function waitForIdle(ctx: Context, agent: ReactLoopAgent): Promise<void> {
  43. return new Promise((resolve) => {
  44. const dispose = ctx.on('agent/status', (subject, status) => {
  45. if (subject === agent && status === 'idle') {
  46. dispose()
  47. resolve()
  48. }
  49. })
  50. })
  51. }
  52. function events(agent: ReactLoopAgent): SessionEvent[] {
  53. return [...agent.session.events]
  54. }
  55. /** Find a session event by type, narrowed; throws when absent. */
  56. function findEvent<T extends SessionEvent['type']>(
  57. log: SessionEvent[],
  58. type: T,
  59. position: 'first' | 'last' = 'first',
  60. ): Extract<SessionEvent, { type: T }> {
  61. const found = position === 'first'
  62. ? log.find(event => event.type === type)
  63. : log.findLast(event => event.type === type)
  64. if (!found) throw new Error(`no ${type} event in the session log`)
  65. return found as Extract<SessionEvent, { type: T }>
  66. }
  67. function resultText(event: SessionEvent): string {
  68. if (event.type !== 'tool/result') return ''
  69. return event.data.content
  70. .filter(block => block.type === 'text')
  71. .map(block => block.text)
  72. .join('')
  73. }
  74. describe('bash tool through the agent loop', () => {
  75. it('first-turn bash receives session identity before the lazy JSONL file materializes', async () => {
  76. const root = mkdtempSync(join(tmpdir(), 'dsh-bash-session-env-'))
  77. dirs.push(root)
  78. const dshHome = join(root, 'dsh-home')
  79. vi.stubEnv('DSH_STALE_PARENT', 'stale')
  80. const adapter = new MockAdapter([
  81. toolCallResponse('call-1', 'bash', {
  82. command: 'printf \'%s\\n%s\\n%s\\n%s\\n%s\\n\' "$DSH_HOME" "$DSH_SHELL" "$DSH_SESSION_ID" "$DSH_SESSION_JSONL" "${DSH_STALE_PARENT-unset}"; if [ -e "$DSH_SESSION_JSONL" ]; then printf \'present\\n\'; else printf \'absent\\n\'; fi',
  83. description: 'inspect session environment',
  84. }),
  85. textResponse('Session environment inspected.'),
  86. ])
  87. const ctx = await harness(adapter, root, dshHome)
  88. const handle = await ctx.agents.create({
  89. agentId: AgentId('session-env'),
  90. sessionId: SessionId('session-env-id'),
  91. agentOptions: { model: 'mock' },
  92. })
  93. const agent = handle.agent as ReactLoopAgent
  94. const location = ctx.sessionPersistence.locate(agent.session.header)
  95. expect(location?.kind).toBe('jsonl')
  96. agent.send([{ type: 'text', text: 'inspect the current session' }])
  97. await waitForIdle(ctx, agent)
  98. const result = findEvent(events(agent), 'tool/result')
  99. expect(resultText(result)).toBe(`${dshHome}\n1\nsession-env-id\n${location?.path}\nunset\nabsent\n`)
  100. expect(existsSync(location!.path)).toBe(true)
  101. const header = JSON.parse(readFileSync(location!.path, 'utf8').split('\n')[0]!) as { type: string; id: string }
  102. expect(header).toMatchObject({ type: 'session', id: 'session-env-id' })
  103. await handle.dispose()
  104. })
  105. it('foreground: model calls bash, sees the result, replies', async () => {
  106. const adapter = new MockAdapter([
  107. toolCallResponse('call-1', 'bash', { command: 'echo integration-ok', description: 'test command' }, 'Running it.'),
  108. textResponse('The command printed integration-ok.'),
  109. ])
  110. const ctx = await harness(adapter)
  111. const agent = ctx.agentLoop.create(AgentId('it-fg'), { model: 'mock' })
  112. agent.send([{ type: 'text', text: 'run echo integration-ok' }])
  113. await waitForIdle(ctx, agent)
  114. const log = events(agent)
  115. const toolCall = findEvent(log, 'tool/call')
  116. expect(toolCall.data.name).toBe('bash')
  117. const toolResult = findEvent(log, 'tool/result')
  118. expect(toolResult.data.isError).toBe(false)
  119. expect(resultText(toolResult)).toBe('integration-ok\n')
  120. // The second model call saw the tool result in its derived history.
  121. const lastRequest = adapter.requests.at(-1)
  122. const toolResultBlocks = (lastRequest?.messages ?? [])
  123. .flatMap(message => message.content)
  124. .filter(block => block.type === 'tool-result')
  125. expect(toolResultBlocks).toHaveLength(1)
  126. const finalMessage = findEvent(log, 'assistant/message', 'last')
  127. expect(finalMessage.data.content.some(
  128. block => block.type === 'text' && block.text.includes('integration-ok'),
  129. )).toBe(true)
  130. })
  131. it('foreground: non-zero exit is reported in the result text, not as isError', async () => {
  132. const adapter = new MockAdapter([
  133. toolCallResponse('call-1', 'bash', { command: 'exit 9', description: 'test command' }),
  134. textResponse('It failed with code 9.'),
  135. ])
  136. const ctx = await harness(adapter)
  137. const agent = ctx.agentLoop.create(AgentId('it-exit'), { model: 'mock' })
  138. agent.send([{ type: 'text', text: 'run exit 9' }])
  139. await waitForIdle(ctx, agent)
  140. const toolResult = findEvent(events(agent), 'tool/result')
  141. expect(toolResult.data.isError).toBe(false)
  142. expect(resultText(toolResult)).toContain('[exit code: 9]')
  143. })
  144. it('background: start → poll → completion notice lands as context/message', async () => {
  145. const adapter = new MockAdapter([
  146. toolCallResponse('call-1', 'bash', { command: 'echo bg-ok', description: 'test command', run_in_background: true }),
  147. // Each harness owns a fresh BashLocal service, whose first task id is
  148. // deterministically bash-1. Keep the scripted call faithful to what the
  149. // model sent; tool arguments are immutable once execution policy begins.
  150. toolCallResponse('call-2', 'bash_output', { task_id: 'bash-1' }, undefined),
  151. textResponse('Background task finished.'),
  152. ])
  153. let taskId = ''
  154. const ctx = await harness(adapter)
  155. const agent = ctx.agentLoop.create(AgentId('it-bg'), { model: 'mock' })
  156. // Capture the generated id so the deterministic fixture is checked against
  157. // the real executor instead of silently assuming it.
  158. ctx.on('session/event', (_session, event) => {
  159. if (event.type === 'tool/result' && taskId === '') {
  160. const match = /task (bash-\d+)/.exec(resultText(event))
  161. if (match) taskId = match[1]!
  162. }
  163. })
  164. agent.send([{ type: 'text', text: 'run echo bg-ok in the background' }])
  165. await waitForIdle(ctx, agent)
  166. expect(taskId).toBe('bash-1')
  167. // Wait for the background task itself (completion may race turn end).
  168. const task = ctx.bash.get(BashTaskId(taskId))
  169. if (!task) throw new Error(`task ${taskId} not registered`)
  170. await task.done
  171. const log = events(agent)
  172. const firstResult = findEvent(log, 'tool/result')
  173. expect(resultText(firstResult)).toBe(`started background task ${taskId}`)
  174. const notice = findEvent(log, 'context/message')
  175. expect(notice.data.content.some(
  176. block => block.type === 'text' && block.text.includes(`background bash task ${taskId} finished`),
  177. )).toBe(true)
  178. expect(notice.data.source).toEqual({ kind: 'plugin', plugin: 'tool-bash' })
  179. })
  180. })