code-mode.e2e.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { afterEach, describe, expect, it } from 'vitest'
  5. import { Context } from 'cordis'
  6. import LlmService from '@deepseek-ai/dsh-llm'
  7. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  8. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  9. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  10. import ToolRegistry, { RUN_CODE_NAME } from '@deepseek-ai/dsh-tools'
  11. import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent'
  12. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  13. import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
  14. import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
  15. import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek'
  16. import { WorkerCodeRuntime } from '@deepseek-ai/dsh-code-runtime-worker'
  17. import LocalFileSystem from '@deepseek-ai/dsh-fs-local'
  18. import * as ToolFs from '@deepseek-ai/dsh-tool-fs'
  19. import * as WorkspaceContext from '@deepseek-ai/dsh-workspace-context'
  20. /**
  21. * With-key Code Mode proof: a real model receives only `run_code`, composes two
  22. * sub-calls, writes a file, and returns curated output while the log records
  23. * each `tool/code-dispatch`. The keyless Loader smoke is in the sibling test.
  24. */
  25. const PERSONA = 'You are a coding agent. You work by writing TypeScript programs for run_code: '
  26. + 'batch related tool work into one program and print or return ONLY the findings that matter.'
  27. const WORKSPACE_PROBE = 'dragonfruit-8675309'
  28. let ctx: Context | undefined
  29. let workdir: string | undefined
  30. afterEach(async () => {
  31. // Always dispose, even on failure/retry/timeout: agent-loop teardown stops
  32. // the loop, the executor kills stray processes, and the code runtime's
  33. // dispose awaits worker exits.
  34. await ctx?.fiber.dispose()
  35. ctx = undefined
  36. if (workdir !== undefined) await rm(workdir, { recursive: true, force: true })
  37. workdir = undefined
  38. })
  39. async function codeModeHarness(cwd: string): Promise<Context> {
  40. const harness = new Context()
  41. await harness.plugin(LlmService)
  42. await harness.plugin(SessionStore)
  43. await harness.plugin(SystemPrompt, { persona: PERSONA })
  44. await harness.plugin(ToolRegistry, { mode: 'code' })
  45. await harness.plugin(AgentRegistry)
  46. await harness.plugin(AgentLoop, { agents: [] })
  47. await harness.plugin(LlmDeepSeek)
  48. await harness.plugin(LocalBashExecutor, { cwd, timeoutMs: 30_000 })
  49. await harness.plugin(ToolBash)
  50. await harness.plugin(WorkerCodeRuntime, {})
  51. return harness
  52. }
  53. async function workspaceCodeModeHarness(): Promise<Context> {
  54. const harness = new Context()
  55. await harness.plugin(LlmService)
  56. await harness.plugin(SessionStore)
  57. await harness.plugin(SystemPrompt, { persona: PERSONA })
  58. await harness.plugin(ToolRegistry, { mode: 'code' })
  59. await harness.plugin(AgentRegistry)
  60. await harness.plugin(LocalFileSystem, { cwd: '/' })
  61. await harness.plugin(ToolFs)
  62. await harness.plugin(WorkspaceContext, { maxBytes: 65536 })
  63. await harness.plugin(AgentLoop, { agents: [] })
  64. await harness.plugin(LlmDeepSeek, { models: [{ id: 'deepseek-v4-flash' }] })
  65. await harness.plugin(WorkerCodeRuntime, {})
  66. return harness
  67. }
  68. function waitForIdle(harness: Context, agent: Agent): Promise<void> {
  69. return new Promise((resolve) => {
  70. const dispose = harness.on('agent/status', (subject, status) => {
  71. if (subject === agent && status === 'idle') {
  72. dispose()
  73. resolve()
  74. }
  75. })
  76. })
  77. }
  78. describe.skipIf(!process.env.DEEPSEEK_API_KEY)('Code Mode: real model writes a program over real tools', () => {
  79. it('collapses the wire tool list to [run_code], bridges sub-calls, and returns curated output', async () => {
  80. workdir = await mkdtemp(join(tmpdir(), 'dsh-code-mode-e2e-'))
  81. ctx = await codeModeHarness(workdir)
  82. const agent = ctx.agentLoop.create(SessionId('e2e-code-mode'), { provider: 'deepseek', model: 'deepseek-v4-flash' })
  83. agent.send([{
  84. type: 'text',
  85. text: 'Using one run_code program: run `echo alpha-7` with the bash tool, run `echo beta-9` with the bash tool, '
  86. + 'then write both outputs joined by a plus sign into combined.txt (bash heredoc or redirect), '
  87. + 'and return only the joined string.',
  88. }])
  89. await waitForIdle(ctx, agent)
  90. const events: SessionEvent[] = [...agent.session.events]
  91. // The wire contract: every request this session made offered EXACTLY ONE
  92. // tool — run_code (the logged header snapshots the assembled list).
  93. const headers = events.filter(event => event.type === 'request/header')
  94. expect(headers.length).toBeGreaterThan(0)
  95. for (const header of headers) {
  96. expect(header.data.header.tools?.map(tool => tool.name)).toEqual([RUN_CODE_NAME])
  97. }
  98. // The model actually went through run_code…
  99. const calls = events.filter(event => event.type === 'tool/call')
  100. expect(calls.length).toBeGreaterThan(0)
  101. expect(calls.every(event => event.data.name === RUN_CODE_NAME)).toBe(true)
  102. // …and the program's tool calls landed as dispatch events under it.
  103. const dispatches = events.filter(event => event.type === 'tool/code-dispatch')
  104. expect(dispatches.length).toBeGreaterThanOrEqual(2)
  105. expect(dispatches.every(event => event.data.name === 'bash')).toBe(true)
  106. const parents = new Set(calls.map(event => event.data.callId))
  107. expect(dispatches.every(event => parents.has(event.data.parentCallId))).toBe(true)
  108. // World verification: the file the program wrote, and the curated answer.
  109. const combined = await readFile(join(workdir, 'combined.txt'), 'utf8')
  110. expect(combined).toContain('alpha-7')
  111. expect(combined).toContain('beta-9')
  112. const finalMessage = events.findLast(event => event.type === 'assistant/message')
  113. const finalText = finalMessage !== undefined
  114. ? finalMessage.data.content.filter(block => block.type === 'text').map(block => block.text).join('')
  115. : ''
  116. expect(finalText).toContain('alpha-7')
  117. expect(finalText).toContain('beta-9')
  118. }, 180_000)
  119. it('delivers nested workspace instructions discovered by an fs sub-call after the outer result', async () => {
  120. workdir = await mkdtemp(join(tmpdir(), 'dsh-code-mode-workspace-e2e-'))
  121. await mkdir(join(workdir, '.git'), { recursive: true })
  122. await mkdir(join(workdir, 'pkg/deep'), { recursive: true })
  123. await writeFile(join(workdir, 'pkg/AGENTS.md'), `If asked for the Code Mode workspace handshake, reply with exactly ${WORKSPACE_PROBE} and nothing else.\n`)
  124. await writeFile(join(workdir, 'pkg/deep/task.txt'), 'Touch this file to discover the nested instructions.\n')
  125. ctx = await workspaceCodeModeHarness()
  126. const handle = await ctx.agents.create({
  127. sessionId: SessionId('e2e-code-mode-workspace-session'),
  128. meta: { cwd: workdir },
  129. agentOptions: { provider: 'deepseek', model: 'deepseek-v4-flash' },
  130. })
  131. handle.agent.send([{
  132. type: 'text',
  133. text: 'Use one run_code program to call tools.read on pkg/deep/task.txt. After it finishes, answer: Code Mode workspace handshake?',
  134. }])
  135. await waitForIdle(ctx, handle.agent)
  136. const events: SessionEvent[] = [...handle.agent.session.events]
  137. const dispatch = events.find(event => event.type === 'tool/code-dispatch' && event.data.name === 'read')
  138. const outerResult = events.find(event => event.type === 'tool/result')
  139. const workspaceContext = events.find(event => event.type === 'context/message'
  140. && typeof event.data.meta === 'object'
  141. && event.data.meta !== null
  142. && !Array.isArray(event.data.meta)
  143. && event.data.meta.kind === 'workspace-instructions')
  144. expect(dispatch).toBeDefined()
  145. expect(outerResult).toBeDefined()
  146. expect(workspaceContext).toBeDefined()
  147. expect(workspaceContext!.seq).toBeGreaterThan(outerResult!.seq)
  148. const finalMessage = events.findLast(event => event.type === 'assistant/message')
  149. const answer = finalMessage?.type === 'assistant/message'
  150. ? finalMessage.data.content.filter(block => block.type === 'text').map(block => block.text).join('')
  151. : ''
  152. expect(answer).toContain(WORKSPACE_PROBE)
  153. }, 180_000)
  154. })