integration.spec.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. import { afterEach, describe, expect, it } 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) {
  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)
  34. ctx.llm.registerAdapter(['mock'], adapter)
  35. return ctx
  36. }
  37. const dirs: string[] = []
  38. afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })
  39. function waitForIdle(ctx: Context, agent: ReactLoopAgent): Promise<void> {
  40. return new Promise((resolve) => {
  41. const dispose = ctx.on('agent/status', (subject, status) => {
  42. if (subject === agent && status === 'idle') {
  43. dispose()
  44. resolve()
  45. }
  46. })
  47. })
  48. }
  49. function events(agent: ReactLoopAgent): SessionEvent[] {
  50. return [...agent.session.events]
  51. }
  52. /** Find a session event by type, narrowed; throws when absent. */
  53. function findEvent<T extends SessionEvent['type']>(
  54. log: SessionEvent[],
  55. type: T,
  56. position: 'first' | 'last' = 'first',
  57. ): Extract<SessionEvent, { type: T }> {
  58. const found = position === 'first'
  59. ? log.find(event => event.type === type)
  60. : log.findLast(event => event.type === type)
  61. if (!found) throw new Error(`no ${type} event in the session log`)
  62. return found as Extract<SessionEvent, { type: T }>
  63. }
  64. function resultText(event: SessionEvent): string {
  65. if (event.type !== 'tool/result') return ''
  66. return event.data.content
  67. .filter(block => block.type === 'text')
  68. .map(block => block.text)
  69. .join('')
  70. }
  71. describe('bash tool through the agent loop', () => {
  72. it('first-turn bash receives session identity before the lazy JSONL file materializes', async () => {
  73. const root = mkdtempSync(join(tmpdir(), 'dsh-bash-session-env-'))
  74. dirs.push(root)
  75. const adapter = new MockAdapter([
  76. toolCallResponse('call-1', 'bash', {
  77. command: 'printf \'%s\\n%s\\n\' "$DSH_SESSION_ID" "$DSH_SESSION_JSONL"; if [ -e "$DSH_SESSION_JSONL" ]; then printf \'present\\n\'; else printf \'absent\\n\'; fi',
  78. description: 'inspect session environment',
  79. }),
  80. textResponse('Session environment inspected.'),
  81. ])
  82. const ctx = await harness(adapter, root)
  83. const handle = ctx.agents.create({
  84. agentId: AgentId('session-env'),
  85. sessionId: SessionId('session-env-id'),
  86. agentOptions: { model: 'mock' },
  87. })
  88. const agent = handle.agent as ReactLoopAgent
  89. const location = ctx.sessionPersistence.locate(agent.session.header)
  90. expect(location?.kind).toBe('jsonl')
  91. agent.send([{ type: 'text', text: 'inspect the current session' }])
  92. await waitForIdle(ctx, agent)
  93. const result = findEvent(events(agent), 'tool/result')
  94. expect(resultText(result)).toBe(`session-env-id\n${location?.path}\nabsent\n`)
  95. expect(existsSync(location!.path)).toBe(true)
  96. const header = JSON.parse(readFileSync(location!.path, 'utf8').split('\n')[0]!) as { type: string; id: string }
  97. expect(header).toMatchObject({ type: 'session', id: 'session-env-id' })
  98. await handle.dispose()
  99. })
  100. it('foreground: model calls bash, sees the result, replies', async () => {
  101. const adapter = new MockAdapter([
  102. toolCallResponse('call-1', 'bash', { command: 'echo integration-ok', description: 'test command' }, 'Running it.'),
  103. textResponse('The command printed integration-ok.'),
  104. ])
  105. const ctx = await harness(adapter)
  106. const agent = ctx.agentLoop.create(AgentId('it-fg'), { model: 'mock' })
  107. agent.send([{ type: 'text', text: 'run echo integration-ok' }])
  108. await waitForIdle(ctx, agent)
  109. const log = events(agent)
  110. const toolCall = findEvent(log, 'tool/call')
  111. expect(toolCall.data.name).toBe('bash')
  112. const toolResult = findEvent(log, 'tool/result')
  113. expect(toolResult.data.isError).toBe(false)
  114. expect(resultText(toolResult)).toBe('integration-ok\n')
  115. // The second model call saw the tool result in its derived history.
  116. const lastRequest = adapter.requests.at(-1)
  117. const toolResultBlocks = (lastRequest?.messages ?? [])
  118. .flatMap(message => message.content)
  119. .filter(block => block.type === 'tool-result')
  120. expect(toolResultBlocks).toHaveLength(1)
  121. const finalMessage = findEvent(log, 'assistant/message', 'last')
  122. expect(finalMessage.data.content.some(
  123. block => block.type === 'text' && block.text.includes('integration-ok'),
  124. )).toBe(true)
  125. })
  126. it('foreground: non-zero exit is reported in the result text, not as isError', async () => {
  127. const adapter = new MockAdapter([
  128. toolCallResponse('call-1', 'bash', { command: 'exit 9', description: 'test command' }),
  129. textResponse('It failed with code 9.'),
  130. ])
  131. const ctx = await harness(adapter)
  132. const agent = ctx.agentLoop.create(AgentId('it-exit'), { model: 'mock' })
  133. agent.send([{ type: 'text', text: 'run exit 9' }])
  134. await waitForIdle(ctx, agent)
  135. const toolResult = findEvent(events(agent), 'tool/result')
  136. expect(toolResult.data.isError).toBe(false)
  137. expect(resultText(toolResult)).toContain('[exit code: 9]')
  138. })
  139. it('background: start → poll → completion notice lands as context/message', async () => {
  140. const adapter = new MockAdapter([
  141. toolCallResponse('call-1', 'bash', { command: 'echo bg-ok', description: 'test command', run_in_background: true }),
  142. toolCallResponse('call-2', 'bash_output', {}, undefined),
  143. textResponse('Background task finished.'),
  144. ])
  145. // The second tool call needs the REAL task id from the first result;
  146. // a tools/pre-execute listener rewrites the scripted arguments. (This uses
  147. // the low-level capability to mutate `exec` before dispatch — the
  148. // unadvertised mechanism behind a future first-class input-rewrite decision;
  149. // here it is a test shim to thread the generated id, not a product feature.)
  150. let taskId = ''
  151. const ctx = await harness(adapter)
  152. const agent = ctx.agentLoop.create(AgentId('it-bg'), { model: 'mock' })
  153. // Intercept the first tool result to capture the generated task id, then
  154. // rewrite the second scripted call's arguments to use it.
  155. ctx.on('session/event', (_session, event) => {
  156. if (event.type === 'tool/result' && taskId === '') {
  157. const match = /task (bash-\d+)/.exec(resultText(event))
  158. if (match) taskId = match[1]!
  159. }
  160. })
  161. ctx.on('tools/pre-execute', async (exec, next) => {
  162. if (exec.name === 'bash_output') {
  163. exec.arguments = { task_id: taskId }
  164. }
  165. return next()
  166. })
  167. agent.send([{ type: 'text', text: 'run echo bg-ok in the background' }])
  168. await waitForIdle(ctx, agent)
  169. // Wait for the background task itself (completion may race turn end).
  170. const task = ctx.bash.get(BashTaskId(taskId))
  171. if (!task) throw new Error(`task ${taskId} not registered`)
  172. await task.done
  173. const log = events(agent)
  174. const firstResult = findEvent(log, 'tool/result')
  175. expect(resultText(firstResult)).toBe(`started background task ${taskId}`)
  176. const notice = findEvent(log, 'context/message')
  177. expect(notice.data.content.some(
  178. block => block.type === 'text' && block.text.includes(`background bash task ${taskId} finished`),
  179. )).toBe(true)
  180. expect(notice.data.source).toEqual({ kind: 'plugin', plugin: 'tool-bash' })
  181. })
  182. })