code-mode.spec.ts 41 KB

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