code-mode.e2e.ts 17 KB

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