integration.spec.ts 9.7 KB

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