integration.spec.ts 9.0 KB

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