integration.spec.ts 11 KB

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