integration.spec.ts 9.2 KB

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