integration.spec.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import LlmService from '@deepseek-ai/dsh-llm'
  4. import SessionStore from '@deepseek-ai/dsh-session'
  5. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  6. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  7. import ToolRegistry from '@deepseek-ai/dsh-tools'
  8. import AgentRegistry, { AgentId } from '@deepseek-ai/dsh-agent'
  9. import AgentLoop, { ReactLoopAgent } from '@deepseek-ai/dsh-agent-loop'
  10. import TaskService from '@deepseek-ai/dsh-tasks'
  11. import * as ToolTasks from '@deepseek-ai/dsh-tool-tasks'
  12. import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
  13. import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
  14. import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
  15. /**
  16. * Full-loop integration: a scripted mock model drives the REAL bash tool
  17. * through the agent loop, exercising the same seams a live model would
  18. * (tool/call + tool/result session events, the generic `ctx.tasks` runtime,
  19. * agent.inject completion notices).
  20. */
  21. async function harness(adapter: MockAdapter) {
  22. const ctx = new Context()
  23. await ctx.plugin(LlmService)
  24. await ctx.plugin(SessionStore)
  25. await ctx.plugin(SystemPrompt)
  26. await ctx.plugin(ToolRegistry)
  27. await ctx.plugin(AgentRegistry)
  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)
  33. ctx.llm.registerAdapter(['mock'], adapter)
  34. return ctx
  35. }
  36. function waitForIdle(ctx: Context, agent: ReactLoopAgent): Promise<void> {
  37. return new Promise((resolve) => {
  38. const dispose = ctx.on('agent/status', (subject, status) => {
  39. if (subject === agent && status === 'idle') {
  40. dispose()
  41. resolve()
  42. }
  43. })
  44. })
  45. }
  46. function events(agent: ReactLoopAgent): SessionEvent[] {
  47. return [...agent.session.events]
  48. }
  49. /** Find a session event by type, narrowed; throws when absent. */
  50. function findEvent<T extends SessionEvent['type']>(
  51. log: SessionEvent[],
  52. type: T,
  53. position: 'first' | 'last' = 'first',
  54. ): Extract<SessionEvent, { type: T }> {
  55. const found = position === 'first'
  56. ? log.find(event => event.type === type)
  57. : log.findLast(event => event.type === type)
  58. if (!found) throw new Error(`no ${type} event in the session log`)
  59. return found as Extract<SessionEvent, { type: T }>
  60. }
  61. function resultText(event: SessionEvent): string {
  62. if (event.type !== 'tool/result') return ''
  63. return event.data.content
  64. .filter(block => block.type === 'text')
  65. .map(block => block.text)
  66. .join('')
  67. }
  68. /** Poll until `predicate` holds (background settlement races turn end). */
  69. async function pollUntil(predicate: () => boolean, timeoutMs = 5_000): Promise<void> {
  70. const deadline = Date.now() + timeoutMs
  71. while (Date.now() < deadline) {
  72. if (predicate()) return
  73. await new Promise(resolve => setTimeout(resolve, 20))
  74. }
  75. throw new Error(`condition not met within ${timeoutMs}ms`)
  76. }
  77. describe('bash tool through the agent loop', () => {
  78. it('foreground: model calls bash, sees the result, replies', async () => {
  79. const adapter = new MockAdapter([
  80. toolCallResponse('call-1', 'bash', { command: 'echo integration-ok', description: 'test command' }, 'Running it.'),
  81. textResponse('The command printed integration-ok.'),
  82. ])
  83. const ctx = await harness(adapter)
  84. const agent = ctx.agentLoop.create(AgentId('it-fg'), { model: 'mock' })
  85. agent.send([{ type: 'text', text: 'run echo integration-ok' }])
  86. await waitForIdle(ctx, agent)
  87. const log = events(agent)
  88. const toolCall = findEvent(log, 'tool/call')
  89. expect(toolCall.data.name).toBe('bash')
  90. const toolResult = findEvent(log, 'tool/result')
  91. expect(toolResult.data.isError).toBe(false)
  92. expect(resultText(toolResult)).toBe('integration-ok\n')
  93. // The second model call saw the tool result in its derived history.
  94. const lastRequest = adapter.requests.at(-1)
  95. const toolResultBlocks = (lastRequest?.messages ?? [])
  96. .flatMap(message => message.content)
  97. .filter(block => block.type === 'tool-result')
  98. expect(toolResultBlocks).toHaveLength(1)
  99. const finalMessage = findEvent(log, 'assistant/message', 'last')
  100. expect(finalMessage.data.content.some(
  101. block => block.type === 'text' && block.text.includes('integration-ok'),
  102. )).toBe(true)
  103. })
  104. it('foreground: non-zero exit is reported in the result text, not as isError', async () => {
  105. const adapter = new MockAdapter([
  106. toolCallResponse('call-1', 'bash', { command: 'exit 9', description: 'test command' }),
  107. textResponse('It failed with code 9.'),
  108. ])
  109. const ctx = await harness(adapter)
  110. const agent = ctx.agentLoop.create(AgentId('it-exit'), { model: 'mock' })
  111. agent.send([{ type: 'text', text: 'run exit 9' }])
  112. await waitForIdle(ctx, agent)
  113. const toolResult = findEvent(events(agent), 'tool/result')
  114. expect(toolResult.data.isError).toBe(false)
  115. expect(resultText(toolResult)).toContain('[exit code: 9]')
  116. })
  117. it('background: start ack → completion notice as context/message → task_output collects it', async () => {
  118. // The task id is deterministic (a fresh TaskService counts per kind from 1),
  119. // so the script can name `bash-1` without threading a generated id.
  120. const adapter = new MockAdapter([
  121. toolCallResponse('call-1', 'bash', { command: 'echo bg-ok', description: 'test command', run_in_background: true }),
  122. textResponse('Started it in the background.'),
  123. toolCallResponse('call-2', 'task_output', { task_id: 'bash-1' }),
  124. textResponse('Background task finished.'),
  125. ])
  126. const ctx = await harness(adapter)
  127. const agent = ctx.agentLoop.create(AgentId('it-bg'), { model: 'mock' })
  128. agent.send([{ type: 'text', text: 'run echo bg-ok in the background' }])
  129. await waitForIdle(ctx, agent)
  130. const firstResult = findEvent(events(agent), 'tool/result')
  131. expect(firstResult.data.isError).toBe(false)
  132. expect(resultText(firstResult)).toBe('started background task bash-1')
  133. // The task settles on its own; the tool-tasks notice listener injects a
  134. // durable context/message into the owning agent's session (settlement may
  135. // race turn end, so poll for it).
  136. await pollUntil(() => events(agent).some(event => event.type === 'context/message'))
  137. const notice = findEvent(events(agent), 'context/message')
  138. expect(notice.data.content.some(
  139. block => block.type === 'text' && block.text.includes('background task bash-1 (bash: echo bg-ok) finished'),
  140. )).toBe(true)
  141. expect(notice.data.source).toEqual({ kind: 'plugin', plugin: 'tool-tasks' })
  142. // The next turn collects the output through the generic task tool.
  143. agent.send([{ type: 'text', text: 'collect it' }])
  144. await waitForIdle(ctx, agent)
  145. const readResult = findEvent(events(agent), 'tool/result', 'last')
  146. expect(readResult.data.isError).toBe(false)
  147. expect(resultText(readResult)).toContain('bg-ok')
  148. expect(resultText(readResult)).toContain('[status: completed, exit code: 0]')
  149. })
  150. })