code-mode.e2e.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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, vi } from 'vitest'
  5. import { Context } from 'cordis'
  6. import LlmService, { createUserMessage, CallId, HarnessError } 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, defineTool } from '@deepseek-ai/dsh-tools'
  11. import type { ToolExecutionResult } from '@deepseek-ai/dsh-tools'
  12. import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent'
  13. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  14. import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
  15. import * as BashEnvPlugin from '@deepseek-ai/dsh-bash-env'
  16. import LocalSubprocessService from '@deepseek-ai/dsh-subprocess-local'
  17. import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
  18. import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek'
  19. import { WorkerCodeRuntime } from '@deepseek-ai/dsh-code-runtime-worker'
  20. import LocalFileSystem from '@deepseek-ai/dsh-fs-local'
  21. import * as ToolFs from '@deepseek-ai/dsh-tool-fs'
  22. import * as WorkspaceContext from '@deepseek-ai/dsh-workspace-context'
  23. import LocalTaskService from '@deepseek-ai/dsh-tasks-local'
  24. import * as ToolTasks from '@deepseek-ai/dsh-tool-tasks'
  25. import * as ToolCordis from '@deepseek-ai/dsh-tool-cordis'
  26. /**
  27. * With-key Code Mode proof: a real model receives only `run_code`, composes two
  28. * sub-calls, writes a file, and returns curated output while the log records
  29. * each `tool/code-dispatch`. The keyless Loader smoke is in the sibling test.
  30. */
  31. const PERSONA = 'You are a coding agent. You work by writing TypeScript programs for run_code: '
  32. + 'batch related tool work into one program and print or return ONLY the findings that matter.'
  33. const WORKSPACE_PROBE = 'dragonfruit-8675309'
  34. let ctx: Context | undefined
  35. let workdir: string | undefined
  36. afterEach(async () => {
  37. // Always dispose, even on failure/retry/timeout: agent-loop teardown stops
  38. // the loop, the executor kills stray processes, and the code runtime's
  39. // dispose awaits worker exits.
  40. await ctx?.fiber.dispose()
  41. ctx = undefined
  42. if (workdir !== undefined) await rm(workdir, { recursive: true, force: true })
  43. workdir = undefined
  44. })
  45. async function codeModeHarness(cwd: string): Promise<Context> {
  46. const harness = new Context()
  47. await harness.plugin(LlmService)
  48. await harness.plugin(SessionStore)
  49. await harness.plugin(SystemPrompt, { persona: PERSONA })
  50. await harness.plugin(ToolRegistry, { mode: 'code' })
  51. await harness.plugin(AgentRegistry)
  52. await harness.plugin(AgentLoop, { agents: [] })
  53. await harness.plugin(LlmDeepSeek)
  54. await harness.plugin(LocalSubprocessService)
  55. await harness.plugin(BashEnvPlugin)
  56. await harness.plugin(LocalBashExecutor, { cwd, timeoutMs: 30_000 })
  57. await harness.plugin(ToolBash)
  58. await harness.plugin(WorkerCodeRuntime, {})
  59. return harness
  60. }
  61. async function workspaceCodeModeHarness(): Promise<Context> {
  62. const harness = new Context()
  63. await harness.plugin(LlmService)
  64. await harness.plugin(SessionStore)
  65. await harness.plugin(SystemPrompt, { persona: PERSONA })
  66. await harness.plugin(ToolRegistry, { mode: 'code' })
  67. await harness.plugin(AgentRegistry)
  68. await harness.plugin(LocalFileSystem, { cwd: '/' })
  69. await harness.plugin(ToolFs)
  70. await harness.plugin(WorkspaceContext, { maxBytes: 65536 })
  71. await harness.plugin(AgentLoop, { agents: [] })
  72. await harness.plugin(LlmDeepSeek, { models: [{ id: 'deepseek-v4-flash' }] })
  73. await harness.plugin(WorkerCodeRuntime, {})
  74. return harness
  75. }
  76. let keylessCall = 0
  77. const testToolSignal = new AbortController().signal
  78. /** Execute one outer Code Mode call through the real registry and worker. */
  79. function runCode(harness: Context, code: string, signal: AbortSignal = testToolSignal): Promise<ToolExecutionResult> {
  80. return harness.tools.execute({
  81. callId: CallId(`keyless-code-${++keylessCall}`),
  82. name: RUN_CODE_NAME,
  83. arguments: { code, description: 'Run the e2e program' },
  84. signal,
  85. })
  86. }
  87. /** Read the optional completion from a successful canonical `run_code` value. */
  88. function completion(result: ToolExecutionResult): unknown {
  89. if (result.isError) {
  90. throw new Error(result.content.filter(block => block.type === 'text').map(block => block.text).join('\n'))
  91. }
  92. const value = result.value
  93. if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error('invalid run_code result')
  94. return value.result
  95. }
  96. /** Keyless real-worker harness for direct typed-binding acceptance tests. */
  97. async function typedCodeModeHarness(): Promise<Context> {
  98. const harness = new Context()
  99. await harness.plugin(SystemPrompt)
  100. await harness.plugin(ToolRegistry, { mode: 'code' })
  101. await harness.plugin(WorkerCodeRuntime, {})
  102. return harness
  103. }
  104. /** Keyless real-worker harness with the task-owned bash lifecycle. */
  105. async function backgroundCodeModeHarness(cwd: string): Promise<Context> {
  106. const harness = await typedCodeModeHarness()
  107. await harness.plugin(LocalTaskService)
  108. await harness.plugin(ToolTasks, {})
  109. await harness.plugin(LocalSubprocessService)
  110. await harness.plugin(BashEnvPlugin)
  111. await harness.plugin(LocalBashExecutor, { cwd, timeoutMs: 30_000 })
  112. await harness.plugin(ToolBash)
  113. return harness
  114. }
  115. describe('Code Mode typed values: keyless real-worker contracts', () => {
  116. it('crosses a large intermediate value intact and exposes only typed tool failure fields', async () => {
  117. ctx = await typedCodeModeHarness()
  118. ctx.tools.register(defineTool({
  119. name: 'large_value',
  120. description: 'Return a large canonical string.',
  121. parameters: {},
  122. output: {
  123. schema: { type: 'string' },
  124. render: (_args, value) => [{ type: 'text', text: value }],
  125. },
  126. execute: () => Promise.resolve('x'.repeat(100_000)),
  127. }))
  128. ctx.tools.register(defineTool({
  129. name: 'always_fail',
  130. description: 'Fail for ToolCallError coverage.',
  131. parameters: {},
  132. output: { schema: { type: 'null' }, render: () => [] },
  133. execute: () => Promise.reject(new HarnessError('expected failure', 'EXPECTED_INTERNAL_CODE')),
  134. }))
  135. const value = completion(await runCode(ctx, `
  136. const large = await tools.large_value({});
  137. let failure;
  138. try {
  139. await tools.always_fail({});
  140. } catch (error) {
  141. failure = {
  142. typed: error instanceof ToolCallError,
  143. name: error.name,
  144. toolName: error.toolName,
  145. message: error.message,
  146. exposesCode: 'code' in error,
  147. exposesContent: 'content' in error,
  148. exposesInfo: 'info' in error,
  149. };
  150. }
  151. return { length: large.length, failure };
  152. `))
  153. expect(value).toEqual({
  154. length: 100_000,
  155. failure: {
  156. typed: true,
  157. name: 'ToolCallError',
  158. toolName: 'always_fail',
  159. message: 'expected failure',
  160. exposesCode: false,
  161. exposesContent: false,
  162. exposesInfo: false,
  163. },
  164. })
  165. })
  166. it('returns a background task id, settles the outer run, and polls that id to completion', async () => {
  167. workdir = await mkdtemp(join(tmpdir(), 'dsh-code-mode-background-'))
  168. ctx = await backgroundCodeModeHarness(workdir)
  169. const taskId = completion(await runCode(ctx, `
  170. const started = await tools.bash({
  171. command: "sleep 0.2; printf 'background-complete\\n'",
  172. description: 'Run completion marker in background',
  173. run_in_background: true,
  174. });
  175. return started.taskId;
  176. `))
  177. expect(taskId).toBe('bash-1')
  178. const polled = completion(await runCode(ctx, `
  179. return await tools.task_output({ task_id: ${JSON.stringify(taskId)}, wait: true, timeout_ms: 5000 });
  180. `))
  181. if (typeof polled !== 'object' || polled === null || Array.isArray(polled)) throw new Error('invalid task_output completion')
  182. const taskOutput = polled as Record<string, unknown>
  183. expect(taskOutput.text).toContain('background-complete')
  184. expect(taskOutput.task).toMatchObject({ id: taskId, kind: 'bash', status: 'completed' })
  185. }, 15_000)
  186. it('pre-abort spawns nothing; post-publication abort leaves task_kill as the cancellation owner', async () => {
  187. workdir = await mkdtemp(join(tmpdir(), 'dsh-code-mode-task-cancel-'))
  188. ctx = await backgroundCodeModeHarness(workdir)
  189. const pre = new AbortController()
  190. pre.abort('pre-aborted')
  191. const preResult = await runCode(ctx, `
  192. return await tools.bash({ command: 'sleep 10', description: 'Must never start', run_in_background: true });
  193. `, pre.signal)
  194. expect(preResult.isError).toBe(true)
  195. expect(ctx.tasks.list()).toEqual([])
  196. const afterPublication = new AbortController()
  197. const running = runCode(ctx, `
  198. const started = await tools.bash({ command: 'sleep 10', description: 'Wait for explicit task kill', run_in_background: true });
  199. console.log(started.taskId);
  200. await new Promise(() => {});
  201. `, afterPublication.signal)
  202. for (let attempt = 0; attempt < 100 && ctx.tasks.list().length === 0; attempt++) {
  203. await new Promise(resolve => setTimeout(resolve, 10))
  204. }
  205. const task = ctx.tasks.list()[0]
  206. expect(task).toMatchObject({ id: 'bash-1', status: 'running' })
  207. afterPublication.abort('outer-call-cancelled')
  208. expect((await running).isError).toBe(true)
  209. expect(ctx.tasks.list()[0]).toMatchObject({ id: task!.id, status: 'running' })
  210. const killed = completion(await runCode(ctx, `
  211. return await tools.task_kill({ task_id: ${JSON.stringify(task!.id)}, reason: 'test owns cancellation' });
  212. `))
  213. expect(killed).toMatchObject({ outcome: 'cancellation-requested', task: { id: task!.id } })
  214. const settled = completion(await runCode(ctx, `
  215. return await tools.task_output({ task_id: ${JSON.stringify(task!.id)}, wait: true, timeout_ms: 5000 });
  216. `))
  217. expect(settled).toMatchObject({ task: { id: task!.id, status: 'killed' } })
  218. }, 15_000)
  219. it('keeps foreground bash coupled to the outer signal', async () => {
  220. workdir = await mkdtemp(join(tmpdir(), 'dsh-code-mode-foreground-cancel-'))
  221. ctx = await backgroundCodeModeHarness(workdir)
  222. const controller = new AbortController()
  223. const startedAt = Date.now()
  224. const pending = runCode(ctx, `
  225. return await tools.bash({ command: 'sleep 10', description: 'Run cancellable foreground command' });
  226. `, controller.signal)
  227. setTimeout(() => { controller.abort('stop-foreground') }, 200)
  228. const result = await pending
  229. expect(result.isError).toBe(true)
  230. expect(Date.now() - startedAt).toBeLessThan(5_000)
  231. expect(ctx.tasks.list()).toEqual([])
  232. }, 15_000)
  233. it('uses cordis_mount DTO ids directly for running and pending temporary Plugins, then confirms removal', async () => {
  234. ctx = await typedCodeModeHarness()
  235. await ctx.plugin(ToolCordis)
  236. const value = completion(await runCode(ctx, `
  237. const active = await tools.cordis_mount({
  238. code: "return { name: 'active-code-mode-plugin', apply(ctx) {} }",
  239. });
  240. const pending = await tools.cordis_mount({
  241. code: "return { name: 'pending-code-mode-plugin', inject: ['missing-code-mode-service'], apply(ctx) {} }",
  242. });
  243. const before = await tools.cordis_inspect({ what: 'temporary' });
  244. const stopped = await tools.cordis_unmount({ id: active.id });
  245. const after = await tools.cordis_inspect({ what: 'temporary' });
  246. await tools.cordis_unmount({ id: pending.id });
  247. return {
  248. active,
  249. pending,
  250. stopped,
  251. beforeContainsId: before.includes(active.id),
  252. afterContainsId: after.includes(active.id),
  253. };
  254. `))
  255. expect(value).toEqual({
  256. active: {
  257. id: 'dyn-1',
  258. pluginName: 'active-code-mode-plugin',
  259. state: 'active',
  260. provides: [],
  261. waitingFor: [],
  262. },
  263. pending: {
  264. id: 'dyn-2',
  265. pluginName: 'pending-code-mode-plugin',
  266. state: 'pending',
  267. provides: [],
  268. waitingFor: ['missing-code-mode-service'],
  269. },
  270. stopped: { id: 'dyn-1', pluginName: 'active-code-mode-plugin' },
  271. beforeContainsId: true,
  272. afterContainsId: false,
  273. })
  274. })
  275. })
  276. function waitForIdle(harness: Context, agent: Agent): Promise<void> {
  277. return new Promise((resolve) => {
  278. const dispose = harness.on('agent/status', ({ agent: subject, status }) => {
  279. if (subject === agent && status === 'idle') {
  280. dispose()
  281. resolve()
  282. }
  283. })
  284. })
  285. }
  286. describe.skipIf(!process.env.DEEPSEEK_API_KEY)('Code Mode: real model writes a program over real tools', () => {
  287. it('collapses the wire tool list to [run_code], bridges sub-calls, and returns curated output', async () => {
  288. workdir = await mkdtemp(join(tmpdir(), 'dsh-code-mode-e2e-'))
  289. ctx = await codeModeHarness(workdir)
  290. const agent = ctx.agentLoop.create(SessionId('e2e-code-mode'), { provider: 'deepseek-official', model: 'deepseek-v4-flash' })
  291. agent.followup(createUserMessage({
  292. content: [{
  293. type: 'text',
  294. text: 'Using one run_code program: run `echo alpha-7` with the bash tool, run `echo beta-9` with the bash tool, '
  295. + 'then write both outputs joined by a plus sign into combined.txt (bash heredoc or redirect), '
  296. + 'and return only the joined string.',
  297. }], source: { kind: 'user' } }))
  298. await waitForIdle(ctx, agent)
  299. const events: SessionEvent[] = [...agent.session.events]
  300. // The wire contract: every request this session made offered EXACTLY ONE
  301. // tool — run_code (the logged header snapshots the assembled list).
  302. const headers = events.filter(event => event.type === 'request/header')
  303. expect(headers.length).toBeGreaterThan(0)
  304. for (const header of headers) {
  305. expect(header.data.header.tools?.map(tool => tool.name)).toEqual([RUN_CODE_NAME])
  306. }
  307. // The model actually went through run_code…
  308. const calls = events.filter(event => event.type === 'tool/call')
  309. expect(calls.length).toBeGreaterThan(0)
  310. expect(calls.every(event => event.data.name === RUN_CODE_NAME)).toBe(true)
  311. // …and the program's tool calls landed as dispatch events under it.
  312. const dispatches = events.filter(event => event.type === 'tool/code-dispatch')
  313. expect(dispatches.length).toBeGreaterThanOrEqual(2)
  314. expect(dispatches.every(event => event.data.name === 'bash')).toBe(true)
  315. const parents = new Set(calls.map(event => event.data.callId))
  316. expect(dispatches.every(event => parents.has(event.data.parentCallId))).toBe(true)
  317. // World verification: the file the program wrote, and the curated answer.
  318. const combined = await readFile(join(workdir, 'combined.txt'), 'utf8')
  319. expect(combined).toContain('alpha-7')
  320. expect(combined).toContain('beta-9')
  321. const finalMessage = events.findLast(event => event.type === 'assistant/message')
  322. const finalText = finalMessage !== undefined
  323. ? finalMessage.data.message.content.filter(block => block.type === 'text').map(block => block.text).join('')
  324. : ''
  325. expect(finalText).toContain('alpha-7')
  326. expect(finalText).toContain('beta-9')
  327. }, 180_000)
  328. it('projects nested workspace instructions discovered by an fs sub-call', async () => {
  329. workdir = await mkdtemp(join(tmpdir(), 'dsh-code-mode-workspace-e2e-'))
  330. await mkdir(join(workdir, '.git'), { recursive: true })
  331. await mkdir(join(workdir, 'pkg/deep'), { recursive: true })
  332. await writeFile(join(workdir, 'pkg/AGENTS.md'), `If asked for the Code Mode workspace handshake, reply with exactly ${WORKSPACE_PROBE} and nothing else.\n`)
  333. await writeFile(join(workdir, 'pkg/deep/task.txt'), 'Touch this file to discover the nested instructions.\n')
  334. ctx = await workspaceCodeModeHarness()
  335. const handle = await ctx.agents.create({
  336. sessionId: SessionId('e2e-code-mode-workspace-session'),
  337. meta: { cwd: workdir },
  338. agentOptions: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  339. })
  340. handle.agent.followup(createUserMessage({
  341. content: [{
  342. type: 'text',
  343. text: 'Use one run_code program to call tools.read on pkg/deep/task.txt. After it finishes, answer: Code Mode workspace handshake?',
  344. }], source: { kind: 'user' } }))
  345. await waitForIdle(ctx, handle.agent)
  346. const events: SessionEvent[] = [...handle.agent.session.events]
  347. const dispatch = events.find(event => event.type === 'tool/code-dispatch' && event.data.name === 'read')
  348. const outerResult = events.find(event => event.type === 'tool/result')
  349. const workspaceContext = await vi.waitFor(() => {
  350. const splice = handle.agent.session.events.findLast(event => event.type === 'agent/inbox/spliced'
  351. && event.data.inserted.some(message => message.source.kind === 'workspace-instructions'))
  352. const inserted = splice?.type === 'agent/inbox/spliced'
  353. ? splice.data.inserted.find(message => message.source.kind === 'workspace-instructions')
  354. : undefined
  355. expect(inserted).toBeDefined()
  356. return inserted!
  357. })
  358. expect(dispatch).toBeDefined()
  359. expect(outerResult).toBeDefined()
  360. const contextText = workspaceContext.content
  361. .filter(block => block.type === 'text')
  362. .map(block => block.text)
  363. .join('\n')
  364. expect(contextText).toContain(WORKSPACE_PROBE)
  365. }, 180_000)
  366. })