code-mode.e2e.ts 19 KB

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