code-mode.e2e.ts 18 KB

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