integration.spec.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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 { existsSync, mkdtempSync, readFileSync, 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): SessionEvent[] {
  60. return [...agent.session.events]
  61. }
  62. /** Find a session event by type, narrowed; throws when absent. */
  63. function findEvent<T extends SessionEvent['type']>(
  64. log: 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 before the lazy JSONL file materializes', 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%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',
  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. const location = ctx.sessionPersistence.locate(agent.session.header)
  110. expect(location?.kind).toBe('jsonl')
  111. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'inspect the current session' }], source: { kind: 'user' } }))
  112. await waitForIdle(ctx, agent)
  113. const result = findEvent(events(agent), 'tool/result')
  114. expect(resultText(result)).toBe(`${dshHome}\n1\nsession-env-id\n${location?.path}\nunset\nabsent\n`)
  115. await ctx.sessions.flush(agent.session)
  116. expect(existsSync(location!.path)).toBe(true)
  117. const header = JSON.parse(readFileSync(location!.path, 'utf8').split('\n')[0]!) as { type: string; id: string }
  118. expect(header).toMatchObject({ type: 'session', id: 'session-env-id' })
  119. await handle.dispose()
  120. })
  121. it('foreground: model calls bash, sees the result, replies', async () => {
  122. const adapter = new MockAdapter([
  123. toolCallResponse('call-1', 'bash', { command: 'echo integration-ok', description: 'test command' }, 'Running it.'),
  124. textResponse('The command printed integration-ok.'),
  125. ])
  126. const ctx = await harness(adapter)
  127. const agent = ctx.agentLoop.create(SessionId('it-fg'), { provider: 'mock', model: 'mock' })
  128. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'run echo integration-ok' }], source: { kind: 'user' } }))
  129. await waitForIdle(ctx, agent)
  130. const log = events(agent)
  131. const toolCall = findEvent(log, 'tool/call')
  132. expect(toolCall.data.name).toBe('bash')
  133. const toolResult = findEvent(log, 'tool/result')
  134. expect(toolResult.data.message.content[0].isError).toBe(false)
  135. expect(resultText(toolResult)).toBe('integration-ok\n')
  136. // The second model call saw the tool result in its derived history.
  137. const lastRequest = adapter.requests.at(-1)
  138. const toolResultBlocks = (lastRequest?.messages ?? [])
  139. .flatMap(message => message.content)
  140. .filter(block => block.type === 'tool-result')
  141. expect(toolResultBlocks).toHaveLength(1)
  142. const finalMessage = findEvent(log, 'assistant/message', 'last')
  143. expect(finalMessage.data.message.content.some(
  144. block => block.type === 'text' && block.text.includes('integration-ok'),
  145. )).toBe(true)
  146. })
  147. it('foreground: non-zero exit is reported in the result text, not as isError', async () => {
  148. const adapter = new MockAdapter([
  149. toolCallResponse('call-1', 'bash', { command: 'exit 9', description: 'test command' }),
  150. textResponse('It failed with code 9.'),
  151. ])
  152. const ctx = await harness(adapter)
  153. const agent = ctx.agentLoop.create(SessionId('it-exit'), { provider: 'mock', model: 'mock' })
  154. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'run exit 9' }], source: { kind: 'user' } }))
  155. await waitForIdle(ctx, agent)
  156. const toolResult = findEvent(events(agent), 'tool/result')
  157. expect(toolResult.data.message.content[0].isError).toBe(false)
  158. expect(resultText(toolResult)).toContain('[exit code: 9]')
  159. })
  160. it('background: start ack → completion wakes the idle agent → job_output collects it', async () => {
  161. // The command blocks on a sentinel this test creates only after the agent
  162. // has gone idle, so settlement cannot fold into the still-running turn.
  163. // Without that fence a fast command can settle before step 2's pre-step
  164. // claim, which folds the notice into a turn whose scripted reply is final:
  165. // the turn then closes with an empty next-step inbox and the collection
  166. // entries are never reached.
  167. const dir = mkdtempSync(join(tmpdir(), 'dsh-bg-'))
  168. dirs.push(dir)
  169. const sentinel = join(dir, 'release')
  170. // The job id is deterministic (a fresh LocalJobRegistry counts per kind from 1),
  171. // so the script can name `bash-1` without threading a generated id.
  172. const adapter = new MockAdapter([
  173. toolCallResponse('call-1', 'bash', {
  174. command: `while [ ! -f ${JSON.stringify(sentinel)} ]; do sleep 0.02; done; echo bg-ok`,
  175. description: 'test command',
  176. run_in_background: true,
  177. }),
  178. textResponse('Started it in the background.'),
  179. toolCallResponse('call-2', 'job_output', { job_id: 'bash-1' }),
  180. textResponse('Background job finished.'),
  181. ])
  182. const ctx = await harness(adapter)
  183. const agent = ctx.agentLoop.create(SessionId('it-bg'), { provider: 'mock', model: 'mock' })
  184. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'run echo bg-ok in the background' }], source: { kind: 'user' } }))
  185. await waitForIdle(ctx, agent)
  186. const firstResult = findEvent(events(agent), 'tool/result')
  187. expect(firstResult.data.message.content[0].isError).toBe(false)
  188. expect(resultText(firstResult)).toBe('started background job bash-1')
  189. // The turn closed with the task still running, so the notice cannot exist yet.
  190. const isNotice = (e: SessionEvent): e is SessionEvent<'user/message'> =>
  191. e.type === 'user/message' && e.data.source.kind === 'plugin'
  192. expect(events(agent).some(isNotice)).toBe(false)
  193. // Releasing the command now settles it against a provably idle owner. No
  194. // second user message: the wake alone opens the turn that collects it.
  195. writeFileSync(sentinel, '')
  196. const lastResultText = (): string => {
  197. const found = events(agent).findLast(event => event.type === 'tool/result')
  198. return found === undefined ? '' : resultText(found)
  199. }
  200. await pollUntil(() => events(agent).some(isNotice) && lastResultText().includes('bg-ok'))
  201. // Two turns: the user's, then the one the completion opened by itself.
  202. expect(events(agent).filter(event => event.type === 'turn/start')).toHaveLength(2)
  203. // The notice carries the gated command as its label, so this pins the id,
  204. // the terminal status, and the producer identity; the verbatim notice text
  205. // and its bounding are pinned in the tool-jobs unit tests.
  206. const notice = events(agent).find(isNotice)!
  207. const noticeText = notice.data.content
  208. .filter(block => block.type === 'text').map(block => block.text).join('')
  209. expect(noticeText).toContain('background job bash-1 (bash: ')
  210. expect(noticeText).toContain('finished [status: completed, exit code: 0]')
  211. expect(notice.data.source).toMatchObject({
  212. kind: 'plugin',
  213. plugin: 'tool-jobs',
  214. form: 'notice',
  215. })
  216. const readResult = findEvent(events(agent), 'tool/result', 'last')
  217. expect(readResult.data.message.content[0].isError).toBe(false)
  218. expect(resultText(readResult)).toContain('bg-ok')
  219. expect(resultText(readResult)).toContain('[status: completed, exit code: 0]')
  220. })
  221. })