code-mode.e2e.ts 17 KB

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