integration.spec.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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 { SessionId, type SessionEvent } from '@deepseek-ai/dsh-session'
  7. import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl'
  8. import { AgentId } from '@deepseek-ai/dsh-agent'
  9. import AgentLoop, { ReactLoopAgent } from '@deepseek-ai/dsh-agent-loop'
  10. import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
  11. import TaskService from '@deepseek-ai/dsh-tasks'
  12. import * as ToolTasks from '@deepseek-ai/dsh-tool-tasks'
  13. import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
  14. import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
  15. import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
  16. /**
  17. * Full-loop integration: a scripted mock model drives the REAL bash tool
  18. * through the agent loop, exercising the same seams a live model would
  19. * (tool/call + tool/result session events, the generic `ctx.tasks` runtime,
  20. * agent.inject completion notices).
  21. */
  22. async function harness(adapter: MockAdapter, sessionRoot?: string, dshHome?: string) {
  23. const ctx = new Context()
  24. await mountAgentLoopTestDependencies(ctx)
  25. if (sessionRoot !== undefined) await ctx.plugin(SessionPersistenceJsonl, { root: sessionRoot })
  26. await ctx.plugin(AgentLoop, { agents: [] })
  27. await ctx.plugin(TaskService)
  28. await ctx.plugin(ToolTasks)
  29. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
  30. await ctx.plugin(ToolBash, dshHome === undefined ? {} : { dshHome })
  31. ctx.llm.registerAdapter(['mock'], adapter)
  32. return ctx
  33. }
  34. const dirs: string[] = []
  35. afterEach(() => {
  36. vi.unstubAllEnvs()
  37. for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
  38. })
  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. /** Poll until `predicate` holds (background settlement races turn end). */
  72. async function pollUntil(predicate: () => boolean, timeoutMs = 5_000): Promise<void> {
  73. const deadline = Date.now() + timeoutMs
  74. while (Date.now() < deadline) {
  75. if (predicate()) return
  76. await new Promise(resolve => setTimeout(resolve, 20))
  77. }
  78. throw new Error(`condition not met within ${timeoutMs}ms`)
  79. }
  80. describe('bash tool through the agent loop', () => {
  81. it('first-turn bash receives session identity before the lazy JSONL file materializes', async () => {
  82. const root = mkdtempSync(join(tmpdir(), 'dsh-bash-session-env-'))
  83. dirs.push(root)
  84. const dshHome = join(root, 'dsh-home')
  85. vi.stubEnv('DSH_STALE_PARENT', 'stale')
  86. const adapter = new MockAdapter([
  87. toolCallResponse('call-1', 'bash', {
  88. 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',
  89. description: 'inspect session environment',
  90. }),
  91. textResponse('Session environment inspected.'),
  92. ])
  93. const ctx = await harness(adapter, root, dshHome)
  94. const handle = await ctx.agents.create({
  95. agentId: AgentId('session-env'),
  96. sessionId: SessionId('session-env-id'),
  97. agentOptions: { provider: 'mock', model: 'mock' },
  98. })
  99. const agent = handle.agent as ReactLoopAgent
  100. const location = ctx.sessionPersistence.locate(agent.session.header)
  101. expect(location?.kind).toBe('jsonl')
  102. agent.send([{ type: 'text', text: 'inspect the current session' }])
  103. await waitForIdle(ctx, agent)
  104. const result = findEvent(events(agent), 'tool/result')
  105. expect(resultText(result)).toBe(`${dshHome}\n1\nsession-env-id\n${location?.path}\nunset\nabsent\n`)
  106. expect(existsSync(location!.path)).toBe(true)
  107. const header = JSON.parse(readFileSync(location!.path, 'utf8').split('\n')[0]!) as { type: string; id: string }
  108. expect(header).toMatchObject({ type: 'session', id: 'session-env-id' })
  109. await handle.dispose()
  110. })
  111. it('foreground: model calls bash, sees the result, replies', async () => {
  112. const adapter = new MockAdapter([
  113. toolCallResponse('call-1', 'bash', { command: 'echo integration-ok', description: 'test command' }, 'Running it.'),
  114. textResponse('The command printed integration-ok.'),
  115. ])
  116. const ctx = await harness(adapter)
  117. const agent = ctx.agentLoop.create(AgentId('it-fg'), { provider: 'mock', model: 'mock' })
  118. agent.send([{ type: 'text', text: 'run echo integration-ok' }])
  119. await waitForIdle(ctx, agent)
  120. const log = events(agent)
  121. const toolCall = findEvent(log, 'tool/call')
  122. expect(toolCall.data.name).toBe('bash')
  123. const toolResult = findEvent(log, 'tool/result')
  124. expect(toolResult.data.isError).toBe(false)
  125. expect(resultText(toolResult)).toBe('integration-ok\n')
  126. // The second model call saw the tool result in its derived history.
  127. const lastRequest = adapter.requests.at(-1)
  128. const toolResultBlocks = (lastRequest?.messages ?? [])
  129. .flatMap(message => message.content)
  130. .filter(block => block.type === 'tool-result')
  131. expect(toolResultBlocks).toHaveLength(1)
  132. const finalMessage = findEvent(log, 'assistant/message', 'last')
  133. expect(finalMessage.data.content.some(
  134. block => block.type === 'text' && block.text.includes('integration-ok'),
  135. )).toBe(true)
  136. })
  137. it('foreground: non-zero exit is reported in the result text, not as isError', async () => {
  138. const adapter = new MockAdapter([
  139. toolCallResponse('call-1', 'bash', { command: 'exit 9', description: 'test command' }),
  140. textResponse('It failed with code 9.'),
  141. ])
  142. const ctx = await harness(adapter)
  143. const agent = ctx.agentLoop.create(AgentId('it-exit'), { provider: 'mock', model: 'mock' })
  144. agent.send([{ type: 'text', text: 'run exit 9' }])
  145. await waitForIdle(ctx, agent)
  146. const toolResult = findEvent(events(agent), 'tool/result')
  147. expect(toolResult.data.isError).toBe(false)
  148. expect(resultText(toolResult)).toContain('[exit code: 9]')
  149. })
  150. it('background: start ack → completion notice as context/message → task_output collects it', async () => {
  151. // The task id is deterministic (a fresh TaskService counts per kind from 1),
  152. // so the script can name `bash-1` without threading a generated id.
  153. const adapter = new MockAdapter([
  154. toolCallResponse('call-1', 'bash', { command: 'echo bg-ok', description: 'test command', run_in_background: true }),
  155. textResponse('Started it in the background.'),
  156. toolCallResponse('call-2', 'task_output', { task_id: 'bash-1' }),
  157. textResponse('Background task finished.'),
  158. ])
  159. const ctx = await harness(adapter)
  160. const agent = ctx.agentLoop.create(AgentId('it-bg'), { provider: 'mock', model: 'mock' })
  161. agent.send([{ type: 'text', text: 'run echo bg-ok in the background' }])
  162. await waitForIdle(ctx, agent)
  163. const firstResult = findEvent(events(agent), 'tool/result')
  164. expect(firstResult.data.isError).toBe(false)
  165. expect(resultText(firstResult)).toBe('started background task bash-1')
  166. // The task settles on its own; the tool-tasks notice listener injects a
  167. // durable context/message into the owning agent's session (settlement may
  168. // race turn end, so poll for it).
  169. await pollUntil(() => events(agent).some(event => event.type === 'context/message'))
  170. const notice = findEvent(events(agent), 'context/message')
  171. expect(notice.data.content.some(
  172. block => block.type === 'text' && block.text.includes('background task bash-1 (bash: echo bg-ok) finished'),
  173. )).toBe(true)
  174. expect(notice.data.source).toEqual({ kind: 'plugin', plugin: 'tool-tasks' })
  175. // The next turn collects the output through the generic task tool.
  176. agent.send([{ type: 'text', text: 'collect it' }])
  177. await waitForIdle(ctx, agent)
  178. const readResult = findEvent(events(agent), 'tool/result', 'last')
  179. expect(readResult.data.isError).toBe(false)
  180. expect(resultText(readResult)).toContain('bg-ok')
  181. expect(resultText(readResult)).toContain('[status: completed, exit code: 0]')
  182. })
  183. })