integration.spec.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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.followup({ content: [{ type: 'text', text: 'inspect the current session' }], source: { kind: 'user' } })
  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. await ctx.sessions.flush(agent.session)
  108. expect(existsSync(location!.path)).toBe(true)
  109. const header = JSON.parse(readFileSync(location!.path, 'utf8').split('\n')[0]!) as { type: string; id: string }
  110. expect(header).toMatchObject({ type: 'session', id: 'session-env-id' })
  111. await handle.dispose()
  112. })
  113. it('foreground: model calls bash, sees the result, replies', async () => {
  114. const adapter = new MockAdapter([
  115. toolCallResponse('call-1', 'bash', { command: 'echo integration-ok', description: 'test command' }, 'Running it.'),
  116. textResponse('The command printed integration-ok.'),
  117. ])
  118. const ctx = await harness(adapter)
  119. const agent = ctx.agentLoop.create(SessionId('it-fg'), { provider: 'mock', model: 'mock' })
  120. agent.followup({ content: [{ type: 'text', text: 'run echo integration-ok' }], source: { kind: 'user' } })
  121. await waitForIdle(ctx, agent)
  122. const log = events(agent)
  123. const toolCall = findEvent(log, 'tool/call')
  124. expect(toolCall.data.name).toBe('bash')
  125. const toolResult = findEvent(log, 'tool/result')
  126. expect(toolResult.data.isError).toBe(false)
  127. expect(resultText(toolResult)).toBe('integration-ok\n')
  128. // The second model call saw the tool result in its derived history.
  129. const lastRequest = adapter.requests.at(-1)
  130. const toolResultBlocks = (lastRequest?.messages ?? [])
  131. .flatMap(message => message.content)
  132. .filter(block => block.type === 'tool-result')
  133. expect(toolResultBlocks).toHaveLength(1)
  134. const finalMessage = findEvent(log, 'assistant/message', 'last')
  135. expect(finalMessage.data.content.some(
  136. block => block.type === 'text' && block.text.includes('integration-ok'),
  137. )).toBe(true)
  138. })
  139. it('foreground: non-zero exit is reported in the result text, not as isError', async () => {
  140. const adapter = new MockAdapter([
  141. toolCallResponse('call-1', 'bash', { command: 'exit 9', description: 'test command' }),
  142. textResponse('It failed with code 9.'),
  143. ])
  144. const ctx = await harness(adapter)
  145. const agent = ctx.agentLoop.create(SessionId('it-exit'), { provider: 'mock', model: 'mock' })
  146. agent.followup({ content: [{ type: 'text', text: 'run exit 9' }], source: { kind: 'user' } })
  147. await waitForIdle(ctx, agent)
  148. const toolResult = findEvent(events(agent), 'tool/result')
  149. expect(toolResult.data.isError).toBe(false)
  150. expect(resultText(toolResult)).toContain('[exit code: 9]')
  151. })
  152. it('background: start ack → completion notice as user/message → task_output collects it', async () => {
  153. // The task id is deterministic (a fresh TaskService counts per kind from 1),
  154. // so the script can name `bash-1` without threading a generated id.
  155. const adapter = new MockAdapter([
  156. toolCallResponse('call-1', 'bash', { command: 'echo bg-ok', description: 'test command', run_in_background: true }),
  157. textResponse('Started it in the background.'),
  158. toolCallResponse('call-2', 'task_output', { task_id: 'bash-1' }),
  159. textResponse('Background task finished.'),
  160. ])
  161. const ctx = await harness(adapter)
  162. const agent = ctx.agentLoop.create(SessionId('it-bg'), { provider: 'mock', model: 'mock' })
  163. agent.followup({ content: [{ type: 'text', text: 'run echo bg-ok in the background' }], source: { kind: 'user' } })
  164. await waitForIdle(ctx, agent)
  165. const firstResult = findEvent(events(agent), 'tool/result')
  166. expect(firstResult.data.isError).toBe(false)
  167. expect(resultText(firstResult)).toBe('started background task bash-1')
  168. // The task settles on its own; the tool-tasks notice listener injects a
  169. // durable plugin-sourced user/message into the owning agent's session
  170. // (settlement may race turn end, so poll for it).
  171. const isNotice = (e: SessionEvent): e is SessionEvent<'user/message'> =>
  172. e.type === 'user/message' && e.data.source.kind === 'plugin'
  173. await pollUntil(() => events(agent).some(isNotice))
  174. const notice = events(agent).find(isNotice)!
  175. expect(notice.data.content.some(
  176. block => block.type === 'text' && block.text.includes('background task bash-1 (bash: echo bg-ok) finished'),
  177. )).toBe(true)
  178. expect(notice.data.source).toEqual({ kind: 'plugin', plugin: 'tool-tasks' })
  179. // The next turn collects the output through the generic task tool.
  180. agent.followup({ content: [{ type: 'text', text: 'collect it' }], source: { kind: 'user' } })
  181. await waitForIdle(ctx, agent)
  182. const readResult = findEvent(events(agent), 'tool/result', 'last')
  183. expect(readResult.data.isError).toBe(false)
  184. expect(resultText(readResult)).toContain('bg-ok')
  185. expect(resultText(readResult)).toContain('[status: completed, exit code: 0]')
  186. })
  187. })