integration.spec.ts 9.5 KB

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