integration.spec.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  2. import { afterEach, describe, expect, it, vi } from 'vitest'
  3. import { Context } from '@deepseek-ai/cordis'
  4. import { mkdtempSync, rmSync, writeFileSync } 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 JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'
  9. import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  10. import type { Agent } from '@deepseek-ai/dsh-agent'
  11. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  12. import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
  13. import LocalJobRegistry from '@deepseek-ai/dsh-jobs-local'
  14. import * as ToolTasks from '@deepseek-ai/dsh-tool-jobs'
  15. import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
  16. import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local'
  17. import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
  18. import * as BashEnvPlugin from '@deepseek-ai/dsh-shell-env'
  19. import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
  20. /**
  21. * Full-loop integration: a scripted mock model drives the REAL bash tool
  22. * through the agent loop, exercising the same execution paths a live model would
  23. * (tool/call + tool/result session events, the generic `ctx.jobs` runtime,
  24. * agent.inject completion notices).
  25. */
  26. async function harness(adapter: MockAdapter, sessionRoot?: string, dshHome?: string) {
  27. const ctx = new Context()
  28. await mountAgentLoopTestDependencies(ctx)
  29. // AgentLoop declares the registry as a required injection.
  30. await ctx.plugin(SessionProjectionRegistry)
  31. if (sessionRoot !== undefined) {
  32. await ctx.plugin(JsonlSessionPersistence, { root: sessionRoot, compression: 'none' })
  33. }
  34. await ctx.plugin(AgentLoop, { agents: [] })
  35. await ctx.plugin(LocalJobRegistry)
  36. await ctx.plugin(ToolTasks)
  37. await ctx.plugin(LocalSubprocessRuntime)
  38. await ctx.plugin(BashEnvPlugin, dshHome === undefined ? {} : { dshHome })
  39. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
  40. await ctx.plugin(ToolBash)
  41. ctx.llm.registerAdapter(['mock'], adapter)
  42. return ctx
  43. }
  44. const dirs: string[] = []
  45. afterEach(() => {
  46. vi.unstubAllEnvs()
  47. for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
  48. })
  49. function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
  50. return new Promise((resolve) => {
  51. const dispose = ctx.on('agent/status', ({ agent: subject, status }) => {
  52. if (subject === agent && status === 'idle') {
  53. dispose()
  54. resolve()
  55. }
  56. })
  57. })
  58. }
  59. function events(agent: Agent): readonly SessionEvent[] {
  60. return agent.session.snapshotEvents()
  61. }
  62. /** Find a session event by type, narrowed; throws when absent. */
  63. function findEvent<T extends SessionEvent['type']>(
  64. log: readonly SessionEvent[],
  65. type: T,
  66. position: 'first' | 'last' = 'first',
  67. ): Extract<SessionEvent, { type: T }> {
  68. const found = position === 'first'
  69. ? log.find(event => event.type === type)
  70. : log.findLast(event => event.type === type)
  71. if (!found) throw new Error(`no ${type} event in the session log`)
  72. return found as Extract<SessionEvent, { type: T }>
  73. }
  74. function resultText(event: SessionEvent): string {
  75. if (event.type !== 'tool/result') return ''
  76. return event.data.message.content[0].content
  77. .filter(block => block.type === 'text')
  78. .map(block => block.text)
  79. .join('')
  80. }
  81. /** Poll until `predicate` holds (background settlement races turn end). */
  82. async function pollUntil(predicate: () => boolean, timeoutMs = 5_000): Promise<void> {
  83. const deadline = Date.now() + timeoutMs
  84. while (Date.now() < deadline) {
  85. if (predicate()) return
  86. await new Promise(resolve => setTimeout(resolve, 20))
  87. }
  88. throw new Error(`condition not met within ${timeoutMs}ms`)
  89. }
  90. describe('bash tool through the agent loop', () => {
  91. it('first-turn bash receives session identity in a scrubbed DSH_* namespace', async () => {
  92. const root = mkdtempSync(join(tmpdir(), 'dsh-bash-session-env-'))
  93. dirs.push(root)
  94. const dshHome = join(root, 'dsh-home')
  95. vi.stubEnv('DSH_STALE_PARENT', 'stale')
  96. const adapter = new MockAdapter([
  97. toolCallResponse('call-1', 'bash', {
  98. command: 'printf \'%s\\n%s\\n%s\\n%s\\n\' "$DSH_HOME" "$DSH_SHELL" "$DSH_SESSION_ID" "${DSH_STALE_PARENT-unset}"',
  99. description: 'inspect session environment',
  100. }),
  101. textResponse('Session environment inspected.'),
  102. ])
  103. const ctx = await harness(adapter, root, dshHome)
  104. const handle = await ctx.agents.create({
  105. sessionId: SessionId('session-env-id'),
  106. agentOptions: { provider: 'mock', model: 'mock' },
  107. })
  108. const agent = handle.agent
  109. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'inspect the current session' }], source: { kind: 'user' } }))
  110. await waitForIdle(ctx, agent)
  111. const result = findEvent(events(agent), 'tool/result')
  112. expect(resultText(result)).toBe(`${dshHome}\n1\nsession-env-id\nunset\n`)
  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 = await ctx.agentLoop.create(SessionId('it-fg'), { provider: 'mock', model: 'mock' })
  122. agent.followup(createUserMessage({ 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.message.content[0].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.message.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 = await ctx.agentLoop.create(SessionId('it-exit'), { provider: 'mock', model: 'mock' })
  148. agent.followup(createUserMessage({ 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.message.content[0].isError).toBe(false)
  152. expect(resultText(toolResult)).toContain('[exit code: 9]')
  153. })
  154. it('background: start ack → completion wakes the idle agent → job_output collects it', async () => {
  155. // The command blocks on a sentinel this test creates only after the agent
  156. // has gone idle, so settlement cannot fold into the still-running turn.
  157. // Without that fence a fast command can settle before step 2's pre-step
  158. // claim, which folds the notice into a turn whose scripted reply is final:
  159. // the turn then closes with an empty next-step inbox and the collection
  160. // entries are never reached.
  161. const dir = mkdtempSync(join(tmpdir(), 'dsh-bg-'))
  162. dirs.push(dir)
  163. const sentinel = join(dir, 'release')
  164. // The job id is deterministic (a fresh LocalJobRegistry counts per kind from 1),
  165. // so the script can name `bash-1` without threading a generated id.
  166. const adapter = new MockAdapter([
  167. toolCallResponse('call-1', 'bash', {
  168. command: `while [ ! -f ${JSON.stringify(sentinel)} ]; do sleep 0.02; done; echo bg-ok`,
  169. description: 'test command',
  170. run_in_background: true,
  171. }),
  172. textResponse('Started it in the background.'),
  173. toolCallResponse('call-2', 'job_output', { job_id: 'bash-1' }),
  174. textResponse('Background job finished.'),
  175. ])
  176. const ctx = await harness(adapter)
  177. const agent = await ctx.agentLoop.create(SessionId('it-bg'), { provider: 'mock', model: 'mock' })
  178. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'run echo bg-ok in the background' }], source: { kind: 'user' } }))
  179. await waitForIdle(ctx, agent)
  180. const firstResult = findEvent(events(agent), 'tool/result')
  181. expect(firstResult.data.message.content[0].isError).toBe(false)
  182. expect(resultText(firstResult)).toBe('started background job bash-1')
  183. // The turn closed with the task still running, so the notice cannot exist yet.
  184. const isNotice = (e: SessionEvent): e is SessionEvent<'user/message'> =>
  185. e.type === 'user/message' && e.data.source.kind === 'plugin'
  186. expect(events(agent).some(isNotice)).toBe(false)
  187. // Releasing the command now settles it against a provably idle owner. No
  188. // second user message: the wake alone opens the turn that collects it.
  189. writeFileSync(sentinel, '')
  190. const lastResultText = (): string => {
  191. const found = events(agent).findLast(event => event.type === 'tool/result')
  192. return found === undefined ? '' : resultText(found)
  193. }
  194. await pollUntil(() => events(agent).some(isNotice) && lastResultText().includes('bg-ok'))
  195. // Two turns: the user's, then the one the completion opened by itself.
  196. expect(events(agent).filter(event => event.type === 'turn/start')).toHaveLength(2)
  197. // The notice carries the gated command as its label, so this pins the id,
  198. // the terminal status, and the producer identity; the verbatim notice text
  199. // and its bounding are pinned in the tool-jobs unit tests.
  200. const notice = events(agent).find(isNotice)!
  201. const noticeText = notice.data.content
  202. .filter(block => block.type === 'text').map(block => block.text).join('')
  203. expect(noticeText).toContain('background job bash-1 (bash: ')
  204. expect(noticeText).toContain('finished [status: completed, exit code: 0]')
  205. expect(notice.data.source).toMatchObject({
  206. kind: 'plugin',
  207. plugin: 'tool-jobs',
  208. form: 'notice',
  209. })
  210. const readResult = findEvent(events(agent), 'tool/result', 'last')
  211. expect(readResult.data.message.content[0].isError).toBe(false)
  212. expect(resultText(readResult)).toContain('bg-ok')
  213. expect(resultText(readResult)).toContain('[status: completed, exit code: 0]')
  214. })
  215. })