code-mode.spec.ts 40 KB

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