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