integration.spec.ts 11 KB

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