code-mode.spec.ts 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { CallId } from '@deepseek-ai/dsh-llm'
  4. import { createScope } from '@deepseek-ai/dsh-scope'
  5. import type { Scope } from '@deepseek-ai/dsh-scope'
  6. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  7. import { CodeRuntime } from '@deepseek-ai/dsh-code-runtime'
  8. import type { CodeRunRequest, CodeRunResult } from '@deepseek-ai/dsh-code-runtime'
  9. import ToolRegistry, { CodeRunFailedError, RUN_CODE_NAME, defineTool } from '@deepseek-ai/dsh-tools'
  10. import type { Config, PostToolDecision, ToolExecutionResult } from '@deepseek-ai/dsh-tools'
  11. import { AgentId } from '@deepseek-ai/dsh-agent'
  12. import type { Agent } from '@deepseek-ai/dsh-agent'
  13. import { Session, SessionId } from '@deepseek-ai/dsh-session'
  14. import type { SessionEventMap } from '@deepseek-ai/dsh-session'
  15. /**
  16. * Code Mode unit tier (per the RFC's plan): provider contribution per mode,
  17. * misconfiguration rejections, the run_code dispatch bridge (serialization,
  18. * abort, JSON normalization, error mapping, events, quiescence), and HMR
  19. * safety — all against an in-repo fake runtime, exactly the
  20. * interface/implementation/consumer shape the seam promises.
  21. */
  22. /** A scriptable in-repo CodeRuntime: each test sets `behavior` to drive the bindings however it needs. */
  23. class FakeRuntime extends CodeRuntime {
  24. readonly language: string
  25. readonly isolation = 'fake'
  26. behavior: (request: CodeRunRequest) => Promise<CodeRunResult> = () => Promise.resolve({ logs: [] })
  27. lastRequest?: CodeRunRequest
  28. constructor(ctx: Context, config: { language?: string } = {}) {
  29. super(ctx)
  30. this.language = config.language ?? 'typescript'
  31. }
  32. run(request: CodeRunRequest): Promise<CodeRunResult> {
  33. this.lastRequest = request
  34. return this.behavior(request)
  35. }
  36. }
  37. interface SetupOptions {
  38. mode?: Config['mode']
  39. runtime?: false | { language?: string }
  40. toolOrder?: string[]
  41. }
  42. async function setup(options: SetupOptions = {}) {
  43. const ctx = new Context()
  44. await ctx.plugin(SystemPrompt, { ...options.toolOrder ? { toolOrder: options.toolOrder } : {} })
  45. await ctx.plugin(ToolRegistry, { mode: options.mode ?? 'code' })
  46. let runtime: FakeRuntime | undefined
  47. if (options.runtime !== false) {
  48. await ctx.plugin(FakeRuntime, options.runtime ?? {})
  49. runtime = ctx.codeRuntime as FakeRuntime
  50. }
  51. return { ctx, tools: ctx.tools, systemPrompt: ctx.systemPrompt, runtime: runtime! }
  52. }
  53. /** Mint one production-shaped agent scope that can register scoped tool policy. */
  54. async function mintAgentScope(ctx: Context, name = 'scoped'): Promise<{ scope: Scope; agent: Agent }> {
  55. const agent = { id: AgentId(name) } as Agent
  56. let scope!: Scope
  57. await ctx.plugin(Object.assign((inner: Context) => { scope = createScope(inner, agent) },
  58. { inject: ['tools', 'systemPrompt'] }))
  59. return { scope, agent }
  60. }
  61. /** Register a trivial echo tool; returns the calls it received. */
  62. function registerEcho(ctx: Context, name = 'echo'): unknown[] {
  63. const calls: unknown[] = []
  64. ctx.tools.register(defineTool({
  65. name,
  66. description: `Echo tool ${name}.`,
  67. parameters: { value: { type: 'string', required: true } },
  68. execute(args) {
  69. calls.push(args)
  70. return Promise.resolve([{ type: 'text' as const, text: `${name}:${args.value}` }])
  71. },
  72. }))
  73. return calls
  74. }
  75. /** A structural fake of the owning agent: captures session appends. */
  76. function fakeAgent(options: { cwd?: string } = { cwd: '/workspace' }): { agent: Agent; events: { type: string; data: unknown }[] } {
  77. const events: { type: string; data: unknown }[] = []
  78. const agent = {
  79. session: {
  80. header: options.cwd === undefined ? {} : { cwd: options.cwd },
  81. append: (type: string, data: unknown) => { events.push({ type, data }) },
  82. },
  83. } as unknown as Agent
  84. return { agent, events }
  85. }
  86. /** Dispatch run_code through the registry pipeline, as the loop would. */
  87. async function runCode(ctx: Context, code: string, extras: { agent?: Agent; signal?: AbortSignal } = {}): Promise<ToolExecutionResult> {
  88. return ctx.tools.execute({
  89. callId: CallId('call-1'),
  90. name: RUN_CODE_NAME,
  91. arguments: { code },
  92. ...extras.agent ? { agent: extras.agent } : {},
  93. ...extras.signal ? { signal: extras.signal } : {},
  94. })
  95. }
  96. describe('mode-aware wire contribution', () => {
  97. it("mode 'native' contributes every schema, no run_code, no SDK section — and needs no runtime", async () => {
  98. const { ctx, systemPrompt } = await setup({ mode: 'native', runtime: false })
  99. registerEcho(ctx)
  100. const assembly = await systemPrompt.assemble()
  101. expect(assembly.tools.map(tool => tool.name)).toEqual(['echo'])
  102. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  103. })
  104. it("mode 'code' contributes exactly [run_code] plus the SDK section declaring the other tools", async () => {
  105. const { ctx, systemPrompt } = await setup({ mode: 'code' })
  106. registerEcho(ctx)
  107. const assembly = await systemPrompt.assemble()
  108. expect(assembly.tools.map(tool => tool.name)).toEqual([RUN_CODE_NAME])
  109. const sdk = assembly.sections.find(section => section.name === 'tools:sdk')
  110. expect(sdk?.text).toContain('declare const tools: {')
  111. expect(sdk?.text).toContain('echo(args:')
  112. expect(sdk?.text).not.toContain('run_code(args:')
  113. })
  114. it.each(['code', 'both'] as const)('treats expert assembly output as authoritative in mode %s', async (mode) => {
  115. const { ctx, systemPrompt } = await setup({ mode })
  116. registerEcho(ctx)
  117. ctx.on('system-prompt/assemble', async (_assembly, _context, next) => {
  118. const assembly = await next()
  119. return {
  120. ...assembly,
  121. sections: assembly.sections.filter(section => section.name !== 'tools:sdk'),
  122. tools: assembly.tools.filter(tool => tool.name !== RUN_CODE_NAME),
  123. }
  124. }, { prepend: true })
  125. const assembly = await systemPrompt.assemble()
  126. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  127. expect(assembly.tools.some(tool => tool.name === RUN_CODE_NAME)).toBe(false)
  128. })
  129. it.each(['code', 'both'] as const)('lets one scope shadow the default SDK section in mode %s', async (mode) => {
  130. const { ctx, systemPrompt } = await setup({ mode })
  131. registerEcho(ctx)
  132. const { scope, agent } = await mintAgentScope(ctx)
  133. scope.ctx.systemPrompt.section({ name: 'tools:sdk', order: 150, text: 'SCOPED SDK' })
  134. const scoped = await systemPrompt.assemble({ scope: agent })
  135. const global = await systemPrompt.assemble()
  136. expect(scoped.sections.find(section => section.name === 'tools:sdk')?.text).toBe('SCOPED SDK')
  137. expect(global.sections.find(section => section.name === 'tools:sdk')?.text).toContain('declare const tools:')
  138. })
  139. it("mode 'both' contributes every native schema plus run_code, and the SDK section", async () => {
  140. const { ctx, systemPrompt } = await setup({ mode: 'both' })
  141. registerEcho(ctx)
  142. const assembly = await systemPrompt.assemble()
  143. expect(assembly.tools.map(tool => tool.name)).toEqual(['echo', RUN_CODE_NAME])
  144. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(true)
  145. })
  146. it.each(['code', 'both'] as const)('keeps the run_code transport outside scoped allow-list filtering in mode %s', async (mode) => {
  147. const { ctx, systemPrompt, runtime } = await setup({ mode })
  148. registerEcho(ctx, 'echo')
  149. registerEcho(ctx, 'hidden')
  150. const { scope, agent } = await mintAgentScope(ctx)
  151. const lift = scope.ctx.tools.restrict({ allow: ['echo'] })
  152. const assembly = await systemPrompt.assemble({ scope: agent })
  153. expect(assembly.tools.map(tool => tool.name)).toEqual(mode === 'code'
  154. ? [RUN_CODE_NAME]
  155. : ['echo', RUN_CODE_NAME])
  156. const sdk = assembly.sections.find(section => section.name === 'tools:sdk')?.text
  157. expect(sdk).toContain('echo(args:')
  158. expect(sdk).not.toContain('hidden(args:')
  159. runtime.behavior = request => Promise.resolve({
  160. logs: [],
  161. value: Object.keys(request.bindings[0]!.functions).sort().join(','),
  162. })
  163. const result = await runCode(ctx, 'return Object.keys(tools)', { agent })
  164. expect(result.isError).toBe(false)
  165. expect(result.content).toEqual([{ type: 'text', text: 'echo' }])
  166. lift()
  167. const unrestricted = await systemPrompt.assemble({ scope: agent })
  168. expect(unrestricted.tools.map(tool => tool.name)).toEqual(mode === 'code'
  169. ? [RUN_CODE_NAME]
  170. : ['echo', 'hidden', RUN_CODE_NAME])
  171. })
  172. it.each(['code', 'both'] as const)('keeps the run_code transport outside scoped deny-list filtering in mode %s', async (mode) => {
  173. const { ctx, systemPrompt, runtime } = await setup({ mode })
  174. registerEcho(ctx, 'denied')
  175. registerEcho(ctx, 'kept')
  176. const { scope, agent } = await mintAgentScope(ctx)
  177. scope.ctx.tools.restrict({ deny: ['denied'] })
  178. const assembly = await systemPrompt.assemble({ scope: agent })
  179. expect(assembly.tools.map(tool => tool.name)).toEqual(mode === 'code'
  180. ? [RUN_CODE_NAME]
  181. : ['kept', RUN_CODE_NAME])
  182. const sdk = assembly.sections.find(section => section.name === 'tools:sdk')?.text
  183. expect(sdk).not.toContain('denied(args:')
  184. expect(sdk).toContain('kept(args:')
  185. runtime.behavior = request => Promise.resolve({
  186. logs: [],
  187. value: Object.keys(request.bindings[0]!.functions).sort().join(','),
  188. })
  189. const result = await runCode(ctx, 'return Object.keys(tools)', { agent })
  190. expect(result.isError).toBe(false)
  191. expect(result.content).toEqual([{ type: 'text', text: 'kept' }])
  192. })
  193. it.each(['code', 'both'] as const)('reserves run_code against scoped shadows and explicit restrictions in mode %s', async (mode) => {
  194. const { ctx, systemPrompt } = await setup({ mode })
  195. const { scope, agent } = await mintAgentScope(ctx)
  196. const impostor = defineTool({
  197. name: RUN_CODE_NAME,
  198. description: 'Scoped impostor.',
  199. parameters: {},
  200. execute: () => Promise.resolve([{ type: 'text' as const, text: 'impostor' }]),
  201. })
  202. expect(() => scope.ctx.tools.register(impostor)).toThrow(/reserved for the Code Mode presentation transport/)
  203. expect(() => ctx.tools.register(impostor)).toThrow(/reserved for the Code Mode presentation transport/)
  204. expect(() => scope.ctx.tools.restrict({ allow: [RUN_CODE_NAME] })).toThrow(/cannot name reserved Code Mode presentation transport/)
  205. expect(() => scope.ctx.tools.restrict({ deny: [RUN_CODE_NAME] })).toThrow(/cannot name reserved Code Mode presentation transport/)
  206. scope.ctx.systemPrompt.section({ name: 'scoped-note', order: 149, text: 'safe note' })
  207. scope.ctx.tools.register(defineTool({
  208. name: 'scoped_safe',
  209. description: 'Safe scoped tool.',
  210. parameters: {},
  211. execute: () => Promise.resolve([{ type: 'text' as const, text: 'safe' }]),
  212. }))
  213. const assembly = await systemPrompt.assemble({ scope: agent })
  214. const transports = assembly.tools.filter(tool => tool.name === RUN_CODE_NAME)
  215. expect(transports).toHaveLength(1)
  216. expect(transports[0]?.description).toContain('Execute a TypeScript program')
  217. expect(assembly.sections.find(section => section.name === 'scoped-note')?.text).toBe('safe note')
  218. expect(assembly.sections.find(section => section.name === 'tools:sdk')?.text).toContain('scoped_safe(args:')
  219. expect(ctx.tools.get(RUN_CODE_NAME, agent)).toBe(ctx.tools.get(RUN_CODE_NAME))
  220. const result = await runCode(ctx, 'return 1', { agent })
  221. expect(result.content).toEqual([{ type: 'text', text: '(run_code completed with no output)' }])
  222. })
  223. it.each(['code', 'both'] as const)('keeps run_code in the toolOrder universe without exposing it as a restriction target in mode %s', async (mode) => {
  224. const { ctx, systemPrompt } = await setup({
  225. mode,
  226. toolOrder: [RUN_CODE_NAME, '<unlisted-tools>'],
  227. })
  228. registerEcho(ctx)
  229. const { agent } = await mintAgentScope(ctx)
  230. const assembly = await systemPrompt.assemble({ scope: agent })
  231. expect(assembly.tools.map(tool => tool.name)).toEqual(mode === 'code'
  232. ? [RUN_CODE_NAME]
  233. : [RUN_CODE_NAME, 'echo'])
  234. })
  235. it("never exposes run_code to programs, even under mode 'both' (no recursive dispatch path)", async () => {
  236. const { ctx, runtime } = await setup({ mode: 'both' })
  237. registerEcho(ctx)
  238. runtime.behavior = (request) => {
  239. const functions = request.bindings[0]!.functions
  240. return Promise.resolve({
  241. logs: [],
  242. value: JSON.stringify({
  243. names: Object.keys(functions).sort(),
  244. // Own-property AND prototype-chain reads both come back empty —
  245. // there is no handle a program could re-enter run_code through.
  246. runCode: String(functions[RUN_CODE_NAME]),
  247. }),
  248. })
  249. }
  250. const result = await runCode(ctx, 'program')
  251. expect(result.isError).toBe(false)
  252. expect(JSON.parse((result.content[0] as { text: string }).text)).toEqual({ names: ['echo'], runCode: 'undefined' })
  253. })
  254. it('renders byte-identical SDK text across consecutive assemblies of an unchanged tool set', async () => {
  255. const { ctx, systemPrompt } = await setup({ mode: 'code' })
  256. registerEcho(ctx)
  257. const first = await systemPrompt.assemble()
  258. const second = await systemPrompt.assemble()
  259. const text = (assembly: typeof first) => assembly.sections.find(section => section.name === 'tools:sdk')?.text
  260. expect(text(first)).toBe(text(second))
  261. })
  262. it('rejects every assembly when a non-native mode has no code runtime', async () => {
  263. const { systemPrompt } = await setup({ mode: 'code', runtime: false })
  264. await expect(systemPrompt.assemble()).rejects.toThrow(/requires a code runtime/)
  265. })
  266. it("rejects every assembly when the runtime's language is not typescript", async () => {
  267. const { systemPrompt } = await setup({ mode: 'code', runtime: { language: 'python' } })
  268. await expect(systemPrompt.assemble()).rejects.toThrow(/language is "python"/)
  269. })
  270. it("rejects the assembly when toolOrder names a native tool that mode 'code' no longer contributes", async () => {
  271. const { ctx, systemPrompt } = await setup({ mode: 'code', toolOrder: ['echo', '<unlisted-tools>'] })
  272. registerEcho(ctx)
  273. await expect(systemPrompt.assemble()).rejects.toThrow(/toolOrder lists unregistered tool "echo"/)
  274. })
  275. it('removes run_code and the SDK section when the registry fiber disposes (HMR safety)', async () => {
  276. const ctx = new Context()
  277. await ctx.plugin(SystemPrompt, {})
  278. await ctx.plugin(FakeRuntime, {})
  279. const fiber = await ctx.plugin(ToolRegistry, { mode: 'code' })
  280. expect(ctx.tools.get(RUN_CODE_NAME)).toBeDefined()
  281. await fiber.dispose()
  282. const assembly = await ctx.systemPrompt.assemble()
  283. expect(assembly.tools).toEqual([])
  284. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  285. })
  286. })
  287. describe('the run_code dispatch bridge', () => {
  288. it('bridges tool calls, returns only the curated output, and logs one event per dispatch', async () => {
  289. const { ctx, runtime } = await setup({ mode: 'code' })
  290. const calls = registerEcho(ctx)
  291. const { agent, events } = fakeAgent()
  292. runtime.behavior = async (request) => {
  293. const tools = request.bindings[0]!.functions
  294. const first = await tools.echo!({ value: 'one' })
  295. const second = await tools.echo!({ value: 'two' })
  296. return { logs: [`saw ${String(first)}`], value: second }
  297. }
  298. const result = await runCode(ctx, 'const …: string = …', { agent })
  299. expect(result.isError).toBe(false)
  300. expect(result.content).toEqual([{ type: 'text', text: 'saw echo:one\necho:two' }])
  301. expect(calls).toEqual([{ value: 'one' }, { value: 'two' }])
  302. const dispatches = events.filter(event => event.type === 'tool/code-dispatch')
  303. expect(dispatches.map(event => event.data)).toEqual([
  304. { parentCallId: 'call-1', subCallId: 'call-1:code:1', name: 'echo', arguments: { value: 'one' }, isError: false, resultSummary: 'echo:one' },
  305. { parentCallId: 'call-1', subCallId: 'call-1:code:2', name: 'echo', arguments: { value: 'two' }, isError: false, resultSummary: 'echo:two' },
  306. ])
  307. expect(result.meta).toEqual({ logs: ['saw echo:one'] })
  308. })
  309. it('exposes only an opaque parent token to nested result observers', async () => {
  310. const { ctx, runtime } = await setup({ mode: 'code' })
  311. registerEcho(ctx)
  312. runtime.behavior = async (request) => {
  313. await request.bindings[0]!.functions.echo!({ value: 'nested' })
  314. return { logs: [], value: 'done' }
  315. }
  316. // Freeze the nested observer's parent correlation. If that were the live
  317. // outer execution object, the timeout-style wrapper could not restore it.
  318. ctx.on('tools/execute', async (exec, next) => {
  319. if (exec.name !== RUN_CODE_NAME) return next()
  320. const previous = exec.signal
  321. exec.signal = new AbortController().signal
  322. const result = await next()
  323. if (previous === undefined) delete exec.signal
  324. else exec.signal = previous
  325. return result
  326. })
  327. ctx.on('tools/result', (exec) => {
  328. if (exec.parent !== undefined) Object.freeze(exec.parent)
  329. })
  330. const result = await runCode(ctx, 'await tools.echo({ value: "nested" })')
  331. expect(result.isError).toBe(false)
  332. expect(result.content).toEqual([{ type: 'text', text: 'done' }])
  333. })
  334. it('serializes Promise.all dispatches: tool executions never overlap, in submission order', async () => {
  335. const { ctx, runtime } = await setup({ mode: 'code' })
  336. const intervals: [string, string][] = []
  337. let active = 0
  338. ctx.tools.register(defineTool({
  339. name: 'probe',
  340. description: 'Records execution overlap.',
  341. parameters: { id: { type: 'string', required: true } },
  342. async execute(args) {
  343. active++
  344. expect(active, 'probe executions overlapped').toBe(1)
  345. intervals.push(['enter', args.id])
  346. await new Promise(resolve => setTimeout(resolve, 20))
  347. intervals.push(['exit', args.id])
  348. active--
  349. return [{ type: 'text' as const, text: args.id }]
  350. },
  351. }))
  352. runtime.behavior = async (request) => {
  353. const tools = request.bindings[0]!.functions
  354. const values = await Promise.all([tools.probe!({ id: 'a' }), tools.probe!({ id: 'b' }), tools.probe!({ id: 'c' })])
  355. return { logs: [], value: values.join(',') }
  356. }
  357. const result = await runCode(ctx, 'program')
  358. expect(result.isError).toBe(false)
  359. expect(intervals).toEqual([
  360. ['enter', 'a'], ['exit', 'a'],
  361. ['enter', 'b'], ['exit', 'b'],
  362. ['enter', 'c'], ['exit', 'c'],
  363. ])
  364. expect(result.content[0]).toEqual({ type: 'text', text: 'a,b,c' })
  365. })
  366. it('rejects the program-side call when the tool errors, with the tool error text', async () => {
  367. const { ctx, runtime } = await setup({ mode: 'code' })
  368. ctx.tools.register(defineTool({
  369. name: 'fail',
  370. description: 'Always fails.',
  371. parameters: {},
  372. execute(): Promise<never> { return Promise.reject(new Error('deliberate failure')) },
  373. }))
  374. runtime.behavior = async (request) => {
  375. try {
  376. await request.bindings[0]!.functions.fail!({})
  377. return { logs: [], value: 'unreachable' }
  378. } catch (error: unknown) {
  379. return { logs: [], value: `caught: ${error instanceof Error ? error.message : String(error)}` }
  380. }
  381. }
  382. const result = await runCode(ctx, 'program')
  383. expect(result.content[0]).toEqual({ type: 'text', text: 'caught: Error: deliberate failure' })
  384. })
  385. it('a tools/pre-execute deny reaches the program as a binding rejection', async () => {
  386. const { ctx, runtime } = await setup({ mode: 'code' })
  387. registerEcho(ctx)
  388. ctx.on('tools/pre-execute', (exec, next) => {
  389. if (exec.name === 'echo') return Promise.resolve({ kind: 'deny' as const, reason: 'not on my watch' })
  390. return next()
  391. })
  392. runtime.behavior = async (request) => {
  393. try {
  394. await request.bindings[0]!.functions.echo!({ value: 'x' })
  395. return { logs: [], value: 'unreachable' }
  396. } catch (error: unknown) {
  397. return { logs: [], value: `denied: ${error instanceof Error ? error.message : String(error)}` }
  398. }
  399. }
  400. const result = await runCode(ctx, 'program')
  401. expect(result.content[0]?.type).toBe('text')
  402. expect((result.content[0] as { text: string }).text).toContain('not on my watch')
  403. })
  404. it('rejects a binding argument that does not survive JSON normalization, dispatching nothing', async () => {
  405. const { ctx, runtime } = await setup({ mode: 'code' })
  406. const calls = registerEcho(ctx)
  407. const { agent, events } = fakeAgent()
  408. runtime.behavior = async (request) => {
  409. try {
  410. await request.bindings[0]!.functions.echo!({ value: 'x', big: 1n })
  411. return { logs: [], value: 'unreachable' }
  412. } catch (error: unknown) {
  413. return { logs: [], value: error instanceof Error ? error.message : String(error) }
  414. }
  415. }
  416. const result = await runCode(ctx, 'program', { agent })
  417. expect((result.content[0] as { text: string }).text).toContain('JSON-serializable')
  418. expect(calls).toEqual([])
  419. expect(events.filter(event => event.type === 'tool/code-dispatch')).toEqual([])
  420. })
  421. it('dispatches the JSON-normalized value: what the tool sees is what the event logs', async () => {
  422. const { ctx, runtime } = await setup({ mode: 'code' })
  423. const calls = registerEcho(ctx)
  424. const { agent, events } = fakeAgent()
  425. runtime.behavior = async (request) => {
  426. // A Date survives structured clone but is not JSON; the bridge
  427. // normalizes it to its JSON form (an ISO string) BEFORE dispatch.
  428. await request.bindings[0]!.functions.echo!({ value: 'x', when: new Date(0) }).catch(() => undefined)
  429. return { logs: [] }
  430. }
  431. await runCode(ctx, 'program', { agent })
  432. expect(calls).toEqual([{ value: 'x', when: '1970-01-01T00:00:00.000Z' }])
  433. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  434. expect(dispatch.arguments).toEqual({ value: 'x', when: '1970-01-01T00:00:00.000Z' })
  435. })
  436. it('defers sub-call additionalContexts onto the outer run_code result', async () => {
  437. const { ctx, runtime } = await setup({ mode: 'code' })
  438. registerEcho(ctx)
  439. ctx.on('tools/post-execute', (exec, _result, next): Promise<PostToolDecision> => {
  440. if (exec.name === 'echo') {
  441. return Promise.resolve({
  442. kind: 'accept' as const,
  443. additionalContexts: [{
  444. content: [{ type: 'text' as const, text: `context for ${exec.callId}` }],
  445. source: { kind: 'plugin' as const, plugin: 'test' },
  446. envelope: 'raw' as const,
  447. meta: { callId: exec.callId },
  448. }],
  449. })
  450. }
  451. return next()
  452. })
  453. runtime.behavior = async (request) => {
  454. await request.bindings[0]!.functions.echo!({ value: 'x' })
  455. await request.bindings[0]!.functions.echo!({ value: 'y' })
  456. return { logs: [], value: 'done' }
  457. }
  458. const result = await runCode(ctx, 'program')
  459. expect(result.isError).toBe(false)
  460. expect(result.additionalContexts).toEqual([
  461. {
  462. content: [{ type: 'text', text: 'context for call-1:code:1' }],
  463. source: { kind: 'plugin', plugin: 'test' },
  464. envelope: 'raw',
  465. meta: { callId: 'call-1:code:1' },
  466. },
  467. {
  468. content: [{ type: 'text', text: 'context for call-1:code:2' }],
  469. source: { kind: 'plugin', plugin: 'test' },
  470. envelope: 'raw',
  471. meta: { callId: 'call-1:code:2' },
  472. },
  473. ])
  474. })
  475. it('keeps sub-call contexts when run_code fails after the nested dispatch', async () => {
  476. const { ctx, runtime } = await setup({ mode: 'both' })
  477. registerEcho(ctx)
  478. ctx.on('tools/post-execute', (exec, _result, next): Promise<PostToolDecision> => {
  479. if (exec.name !== 'echo') return next()
  480. return Promise.resolve({
  481. kind: 'accept',
  482. additionalContexts: [{
  483. content: [{ type: 'text', text: 'nested context' }],
  484. source: { kind: 'plugin', plugin: 'test' },
  485. }],
  486. })
  487. })
  488. runtime.behavior = async (request) => {
  489. await request.bindings[0]!.functions.echo!({ value: 'x' })
  490. return { logs: [], error: { kind: 'exception', message: 'program failed later' } }
  491. }
  492. const result = await runCode(ctx, 'program')
  493. expect(result.isError).toBe(true)
  494. expect(result.additionalContexts).toEqual([{
  495. content: [{ type: 'text', text: 'nested context' }],
  496. source: { kind: 'plugin', plugin: 'test' },
  497. }])
  498. })
  499. it('converts a failed run into a structured isError result carrying kind, message, and captured logs', async () => {
  500. const { ctx, runtime } = await setup({ mode: 'code' })
  501. runtime.behavior = () => Promise.resolve({
  502. logs: ['got this far'],
  503. error: { kind: 'timeout', message: 'compute budget exhausted (300ms busy)' },
  504. })
  505. const result = await runCode(ctx, 'program')
  506. expect(result.isError).toBe(true)
  507. expect(result.error).toEqual({ name: 'CodeRunFailedError', code: 'CODE_RUN_FAILED' })
  508. const text = (result.content[0] as { text: string }).text
  509. expect(text).toContain('code run failed (timeout)')
  510. expect(text).toContain('compute budget exhausted')
  511. expect(text).toContain('got this far')
  512. })
  513. it('CodeRunFailedError is a HarnessError with the CODE_RUN_FAILED code', () => {
  514. const error = new CodeRunFailedError('boom')
  515. expect(error.code).toBe('CODE_RUN_FAILED')
  516. expect(error.name).toBe('CodeRunFailedError')
  517. })
  518. it('aborting the outer signal aborts the in-flight sub-dispatch and abandons queued ones', async () => {
  519. const { ctx, runtime } = await setup({ mode: 'code' })
  520. const seen: string[] = []
  521. let sawAbort = false
  522. ctx.tools.register(defineTool({
  523. name: 'slow',
  524. description: 'Slow tool observing its signal.',
  525. parameters: { id: { type: 'string', required: true } },
  526. async execute(args, exec) {
  527. seen.push(args.id)
  528. await new Promise<void>((resolve) => {
  529. const timer = setTimeout(resolve, 500)
  530. exec.signal?.addEventListener('abort', () => { sawAbort = true; clearTimeout(timer); resolve() }, { once: true })
  531. })
  532. return [{ type: 'text' as const, text: args.id }]
  533. },
  534. }))
  535. const controller = new AbortController()
  536. runtime.behavior = async (request) => {
  537. const tools = request.bindings[0]!.functions
  538. const calls = [tools.slow!({ id: 'first' }).catch(() => 'rejected'), tools.slow!({ id: 'second' }).catch(() => 'rejected')]
  539. setTimeout(() => { controller.abort('user-cancel') }, 50)
  540. await Promise.all(calls)
  541. // A real runtime would be terminated by the abort; the fake honors the
  542. // contract by reporting the abort as the run failure.
  543. return { logs: [], error: { kind: 'abort', message: 'user-cancel' } }
  544. }
  545. const result = await runCode(ctx, 'program', { signal: controller.signal })
  546. expect(result.isError).toBe(true)
  547. expect((result.content[0] as { text: string }).text).toContain('code run failed (abort)')
  548. expect(seen).toEqual(['first'])
  549. expect(sawAbort).toBe(true)
  550. })
  551. it('a runtime that starts a binding call and then REJECTS still reaches quiescence before returning', async () => {
  552. const { ctx, runtime } = await setup({ mode: 'code' })
  553. const { agent, events } = fakeAgent()
  554. let sawAbort = false
  555. let started!: () => void
  556. const inFlight = new Promise<void>((resolve) => { started = resolve })
  557. ctx.tools.register(defineTool({
  558. name: 'slow',
  559. description: 'Slow tool observing its signal.',
  560. parameters: { id: { type: 'string', required: true } },
  561. async execute(args, exec) {
  562. started()
  563. await new Promise<void>((resolve) => {
  564. const timer = setTimeout(resolve, 500)
  565. exec.signal?.addEventListener('abort', () => { sawAbort = true; clearTimeout(timer); resolve() }, { once: true })
  566. })
  567. return [{ type: 'text' as const, text: args.id }]
  568. },
  569. }))
  570. runtime.behavior = async (request) => {
  571. // Start a sub-dispatch, keep its rejection held, and fail the run once the tool is
  572. // genuinely in flight — a seam error after work has begun.
  573. request.bindings[0]!.functions.slow!({ id: 'orphan' }).catch(() => 'held')
  574. await inFlight
  575. throw new Error('backend exploded')
  576. }
  577. const result = await runCode(ctx, 'program', { agent })
  578. expect(result.isError).toBe(true)
  579. expect((result.content[0] as { text: string }).text).toContain('backend exploded')
  580. // Quiescence held: the in-flight sub-dispatch was aborted and its event
  581. // logged INSIDE the run_code execution, not after it returned.
  582. expect(sawAbort).toBe(true)
  583. expect(events.filter(event => event.type === 'tool/code-dispatch').map(event => (event.data as { name: string }).name)).toEqual(['slow'])
  584. })
  585. it('runs without an owning agent: dispatches work, event logging is skipped', async () => {
  586. const { ctx, runtime } = await setup({ mode: 'code' })
  587. const calls = registerEcho(ctx)
  588. runtime.behavior = async (request) => {
  589. await request.bindings[0]!.functions.echo!({ value: 'x' })
  590. return { logs: [], value: 'ok' }
  591. }
  592. const result = await runCode(ctx, 'program')
  593. expect(result.isError).toBe(false)
  594. expect(calls).toEqual([{ value: 'x' }])
  595. })
  596. it('executing run_code under a missing runtime is a structured isError, not a crash', async () => {
  597. const ctx = new Context()
  598. await ctx.plugin(SystemPrompt, {})
  599. await ctx.plugin(ToolRegistry, { mode: 'code' })
  600. const result = await runCode(ctx, 'program')
  601. expect(result.isError).toBe(true)
  602. expect((result.content[0] as { text: string }).text).toContain('requires a code runtime')
  603. })
  604. it('presents the PROGRAM as the execute-card title on both call and result (the one slot execute cards always show)', async () => {
  605. const { ctx } = await setup({ mode: 'code' })
  606. const tool = ctx.tools.get(RUN_CODE_NAME)!
  607. // The program IS the title, mirroring how command tools title their cards
  608. // with the command: an ACP client's execute-card header is the only
  609. // always-visible slot (Zed renders no body content and no raw input for
  610. // execute-kind cards without a real terminal).
  611. expect(tool.presentCall?.({ code: 'return 1' })).toEqual({
  612. card: 'generic',
  613. title: 'return 1',
  614. kind: 'execute',
  615. rawInput: 'return 1',
  616. })
  617. const view = tool.presentResult?.({ code: 'return 1' }, {
  618. content: [{ type: 'text', text: 'model-facing' }],
  619. isError: false,
  620. meta: { logs: ['printed'] },
  621. })
  622. // The result omits the title — an update replaces only provided fields,
  623. // so the pending card's program title persists through completion.
  624. expect(view).toEqual({
  625. card: 'generic',
  626. content: [{ type: 'text', text: 'printed' }],
  627. })
  628. // No captured output → no content either; everything pending persists.
  629. expect(tool.presentResult?.({ code: 'x' }, { content: [], isError: false, meta: { logs: [] } }))
  630. .toEqual({ card: 'generic' })
  631. // Replay with an unrecognizable meta falls back to the generic rendering.
  632. expect(tool.presentResult?.({ code: 'x' }, { content: [], isError: false, meta: { logs: [{ text: 'legacy' }], dispatches: 1 } })).toBeUndefined()
  633. expect(tool.presentResult?.({ code: 'x' }, { content: [], isError: false, meta: { other: true } })).toBeUndefined()
  634. expect(tool.presentResult?.({ code: 'x' }, { content: [], isError: false })).toBeUndefined()
  635. })
  636. it('renders non-text sub-result blocks as placeholders and truncates long event summaries', async () => {
  637. const { ctx, runtime } = await setup({ mode: 'code' })
  638. const { agent, events } = fakeAgent()
  639. const long = 'x'.repeat(300)
  640. ctx.tools.register(defineTool({
  641. name: 'mixed',
  642. description: 'Returns mixed content.',
  643. parameters: {},
  644. execute() {
  645. return Promise.resolve([
  646. { type: 'text' as const, text: long },
  647. { type: 'reasoning' as const, text: 'hidden' },
  648. ])
  649. },
  650. }))
  651. runtime.behavior = async (request) => {
  652. const value = await request.bindings[0]!.functions.mixed!({})
  653. return { logs: [], value }
  654. }
  655. const result = await runCode(ctx, 'program', { agent })
  656. expect(result.isError).toBe(false)
  657. expect((result.content[0] as { text: string }).text).toBe(`${long}\n[reasoning content]`)
  658. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  659. expect(dispatch.resultSummary.length).toBe(201)
  660. expect(dispatch.resultSummary.endsWith('…')).toBe(true)
  661. })
  662. it('normalizes the session workspace root before bounding durable result summaries', async () => {
  663. const { ctx, runtime } = await setup({ mode: 'code' })
  664. ctx.tools.register(defineTool({
  665. name: 'workspace_path',
  666. description: 'Return a path beneath the session workspace.',
  667. parameters: {},
  668. execute(_args, exec) {
  669. const cwd = exec.agent?.session.header.cwd ?? ''
  670. return Promise.resolve([{ type: 'text' as const, text: `<path>${cwd}/nested/task.txt</path>\n${'x'.repeat(240)}` }])
  671. },
  672. }))
  673. runtime.behavior = async request => ({
  674. logs: [],
  675. value: await request.bindings[0]!.functions.workspace_path!({}),
  676. })
  677. const short = fakeAgent({ cwd: '/tmp/workspace' })
  678. const long = fakeAgent({ cwd: `/tmp/${'long-segment/'.repeat(30)}workspace` })
  679. const shortResult = await runCode(ctx, 'program', { agent: short.agent })
  680. const longResult = await runCode(ctx, 'program', { agent: long.agent })
  681. const shortDispatch = short.events[0]!.data as SessionEventMap['tool/code-dispatch']
  682. const longDispatch = long.events[0]!.data as SessionEventMap['tool/code-dispatch']
  683. expect(shortResult.content).not.toEqual(longResult.content)
  684. expect(shortDispatch.resultSummary).toBe(longDispatch.resultSummary)
  685. expect(shortDispatch.resultSummary).toHaveLength(201)
  686. expect(shortDispatch.resultSummary).toMatch(/^<path>\.\/nested\/task\.txt<\/path>\n.+…$/)
  687. })
  688. it('leaves result summaries unchanged when a session cwd is absent or is the filesystem root', async () => {
  689. const { ctx, runtime } = await setup({ mode: 'code' })
  690. registerEcho(ctx)
  691. runtime.behavior = async request => ({
  692. logs: [],
  693. value: await request.bindings[0]!.functions.echo!({ value: '/workspace/value' }),
  694. })
  695. const absent = fakeAgent({})
  696. const root = fakeAgent({ cwd: '/' })
  697. await runCode(ctx, 'program', { agent: absent.agent })
  698. await runCode(ctx, 'program', { agent: root.agent })
  699. expect((absent.events[0]!.data as SessionEventMap['tool/code-dispatch']).resultSummary).toBe('echo:/workspace/value')
  700. expect((root.events[0]!.data as SessionEventMap['tool/code-dispatch']).resultSummary).toBe('echo:/workspace/value')
  701. })
  702. it('rejects undefined, JSON-throwing, and JSON-unrepresentable binding arguments BEFORE dispatch', async () => {
  703. const { ctx, runtime } = await setup({ mode: 'code' })
  704. const calls = registerEcho(ctx)
  705. const { agent, events } = fakeAgent()
  706. runtime.behavior = async (request) => {
  707. const echo = request.bindings[0]!.functions.echo!
  708. const catchMessage = (promise: Promise<unknown>) => promise.then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error))
  709. return {
  710. logs: [],
  711. value: [
  712. // Root undefined must reject up front: the event log rejects it as
  713. // data, and nothing may execute unlogged.
  714. await catchMessage(echo(undefined)),
  715. // A toJSON that throws a NON-Error propagates out of JSON.stringify.
  716. await catchMessage(echo({ toJSON() { throw 'raw-throw' } })),
  717. // A bare function is a value JSON cannot represent at all.
  718. await catchMessage(echo(() => 1)),
  719. ].join(' | '),
  720. }
  721. }
  722. const result = await runCode(ctx, 'program', { agent })
  723. const text = (result.content[0] as { text: string }).text
  724. expect(text).toContain('call the tool with an arguments object')
  725. expect(text).toContain('JSON-serializable: raw-throw')
  726. expect(text).toContain('a value JSON cannot represent')
  727. // None of the three dispatched, none logged.
  728. expect(calls).toEqual([])
  729. expect(events.filter(event => event.type === 'tool/code-dispatch')).toEqual([])
  730. })
  731. it('gives the tool and durable log the same immutable argument value', async () => {
  732. const { ctx, runtime } = await setup({ mode: 'code' })
  733. const { agent, events } = fakeAgent()
  734. let mutationSucceeded: boolean | undefined
  735. ctx.tools.register(defineTool({
  736. name: 'mutator',
  737. description: 'Attempts to mutate its args object.',
  738. parameters: { list: { type: 'array', required: true } },
  739. execute(args) {
  740. mutationSucceeded = Reflect.set(args.list, 1, 'injected-by-tool')
  741. return Promise.resolve([{ type: 'text' as const, text: 'protected' }])
  742. },
  743. }))
  744. runtime.behavior = async (request) => {
  745. await request.bindings[0]!.functions.mutator!({ list: ['original'] })
  746. return { logs: [] }
  747. }
  748. const result = await runCode(ctx, 'program', { agent })
  749. expect(result.isError).toBe(false)
  750. expect(mutationSucceeded).toBe(false)
  751. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  752. expect(dispatch.arguments).toEqual({ list: ['original'] })
  753. })
  754. it('exposes a tool named __proto__ as an ordinary own binding', async () => {
  755. const { ctx, runtime } = await setup({ mode: 'code' })
  756. ctx.tools.register(defineTool({
  757. name: '__proto__',
  758. description: 'A prototype-colliding tool name.',
  759. parameters: {},
  760. execute() { return Promise.resolve([{ type: 'text' as const, text: 'proto-tool-ok' }]) },
  761. }))
  762. runtime.behavior = async (request) => {
  763. const functions = request.bindings[0]!.functions
  764. expect(Object.getPrototypeOf(functions)).toBeNull()
  765. const value = await functions['__proto__']!({})
  766. return { logs: [], value }
  767. }
  768. const result = await runCode(ctx, 'program')
  769. expect(result.isError).toBe(false)
  770. expect(result.content[0]).toEqual({ type: 'text', text: 'proto-tool-ok' })
  771. })
  772. it('renders a non-string completion value inspect-style', async () => {
  773. const { ctx, runtime } = await setup({ mode: 'code' })
  774. runtime.behavior = () => Promise.resolve({ logs: [], value: { n: 42 } })
  775. const result = await runCode(ctx, 'program')
  776. expect((result.content[0] as { text: string }).text).toBe('{ n: 42 }')
  777. })
  778. it('reports a pre-aborted outer signal as the run failure without dispatching anything', async () => {
  779. const { ctx, runtime } = await setup({ mode: 'code' })
  780. const calls = registerEcho(ctx)
  781. runtime.behavior = (request) => {
  782. // The fake honors the seam contract for an already-aborted signal.
  783. if (request.signal?.aborted) return Promise.resolve({ logs: [], error: { kind: 'abort' as const, message: String(request.signal.reason) } })
  784. return Promise.resolve({ logs: [], value: 'unreachable' })
  785. }
  786. const controller = new AbortController()
  787. controller.abort('too-late')
  788. const result = await runCode(ctx, 'program', { signal: controller.signal })
  789. expect(result.isError).toBe(true)
  790. expect((result.content[0] as { text: string }).text).toContain('code run failed (abort)')
  791. expect(calls).toEqual([])
  792. })
  793. it('rejects a binding invoked after the run is over without dispatching it', async () => {
  794. const { ctx, runtime } = await setup({ mode: 'code' })
  795. const calls = registerEcho(ctx)
  796. const controller = new AbortController()
  797. runtime.behavior = async (request) => {
  798. controller.abort('cancelled-mid-run')
  799. const message = await request.bindings[0]!.functions.echo!({ value: 'x' })
  800. .then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error))
  801. return { logs: [], value: message }
  802. }
  803. const result = await runCode(ctx, 'program', { signal: controller.signal })
  804. expect(result.isError).toBe(false)
  805. expect((result.content[0] as { text: string }).text).toContain('not dispatched')
  806. expect(calls).toEqual([])
  807. })
  808. it('a tool/code-dispatch event never derives a model message', () => {
  809. const session = new Session(SessionId('code-mode-derive'))
  810. session.append('user/message', { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  811. session.append('tool/code-dispatch', {
  812. parentCallId: CallId('p1'),
  813. subCallId: CallId('p1:code:1'),
  814. name: 'echo',
  815. arguments: { value: 'x' },
  816. isError: false,
  817. resultSummary: 'echo:x',
  818. })
  819. const derived = session.deriveMessages()
  820. expect(derived).toHaveLength(1)
  821. expect(derived[0]?.role).toBe('user')
  822. })
  823. it('defaults to native mode under direct construction with no config', async () => {
  824. const ctx = new Context()
  825. await ctx.plugin(SystemPrompt, {})
  826. const registry = new ToolRegistry(ctx)
  827. expect(registry.get(RUN_CODE_NAME)).toBeUndefined()
  828. const assembly = await ctx.systemPrompt.assemble()
  829. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  830. })
  831. })