code-mode.spec.ts 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  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, 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. 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(defineTool({
  65. name,
  66. description: `Echo tool ${name}.`,
  67. parameters: { value: { type: 'string', required: true } },
  68. execute(args) {
  69. calls.push(args)
  70. return Promise.resolve([{ type: 'text' as const, text: `${name}:${args.value}` }])
  71. },
  72. }))
  73. return calls
  74. }
  75. /** A structural fake of the owning agent: captures session appends. */
  76. function fakeAgent(options: { cwd?: string } = { cwd: '/workspace' }): { agent: Agent; events: { type: string; data: unknown }[] } {
  77. const events: { type: string; data: unknown }[] = []
  78. const agent = {
  79. session: {
  80. header: options.cwd === undefined ? {} : { cwd: options.cwd },
  81. append: (type: string, data: unknown) => { events.push({ type, data }) },
  82. },
  83. } as unknown as Agent
  84. return { agent, events }
  85. }
  86. /** Dispatch run_code through the registry pipeline, as the loop would. */
  87. async function runCode(ctx: Context, code: string, extras: { agent?: Agent; signal?: AbortSignal } = {}): Promise<ToolExecutionResult> {
  88. return ctx.tools.execute({
  89. 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 = defineTool({
  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(defineTool({
  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. expect(result.content).toEqual([{ type: 'text', text: 'saw echo:one\necho:two' }])
  302. expect(calls).toEqual([{ value: 'one' }, { value: 'two' }])
  303. const dispatches = events.filter(event => event.type === 'tool/code-dispatch')
  304. expect(dispatches.map(event => event.data)).toEqual([
  305. { parentCallId: 'call-1', subCallId: 'call-1:code:1', name: 'echo', arguments: { value: 'one' }, isError: false, resultSummary: 'echo:one' },
  306. { parentCallId: 'call-1', subCallId: 'call-1:code:2', name: 'echo', arguments: { value: 'two' }, isError: false, resultSummary: 'echo:two' },
  307. ])
  308. expect(result.meta).toEqual({ logs: ['saw echo:one'] })
  309. })
  310. it('exposes only an opaque parent token to nested result observers', async () => {
  311. const { ctx, runtime } = await setup({ mode: 'code' })
  312. registerEcho(ctx)
  313. runtime.behavior = async (request) => {
  314. await request.bindings[0]!.functions.echo!({ value: 'nested' })
  315. return { logs: [], value: 'done' }
  316. }
  317. // Freeze the nested observer's parent correlation. If that were the live
  318. // outer execution object, the timeout-style wrapper could not restore it.
  319. ctx.on('tools/execute', async (exec, next) => {
  320. if (exec.name !== RUN_CODE_NAME) return next()
  321. const previous = exec.signal
  322. exec.signal = new AbortController().signal
  323. const result = await next()
  324. exec.signal = previous
  325. return result
  326. })
  327. ctx.on('tools/result', (exec) => {
  328. if (exec.parent !== undefined) Object.freeze(exec.parent)
  329. })
  330. const result = await runCode(ctx, 'await tools.echo({ value: "nested" })')
  331. expect(result.isError).toBe(false)
  332. expect(result.content).toEqual([{ type: 'text', text: 'done' }])
  333. })
  334. it('serializes Promise.all dispatches: tool executions never overlap, in submission order', async () => {
  335. const { ctx, runtime } = await setup({ mode: 'code' })
  336. const intervals: [string, string][] = []
  337. let active = 0
  338. ctx.tools.register(defineTool({
  339. name: 'probe',
  340. description: 'Records execution overlap.',
  341. parameters: { id: { type: 'string', required: true } },
  342. async execute(args) {
  343. active++
  344. expect(active, 'probe executions overlapped').toBe(1)
  345. intervals.push(['enter', args.id])
  346. await new Promise(resolve => setTimeout(resolve, 20))
  347. intervals.push(['exit', args.id])
  348. active--
  349. return [{ type: 'text' as const, text: args.id }]
  350. },
  351. }))
  352. runtime.behavior = async (request) => {
  353. const tools = request.bindings[0]!.functions
  354. const values = await Promise.all([tools.probe!({ id: 'a' }), tools.probe!({ id: 'b' }), tools.probe!({ id: 'c' })])
  355. return { logs: [], value: values.join(',') }
  356. }
  357. const result = await runCode(ctx, 'program')
  358. expect(result.isError).toBe(false)
  359. expect(intervals).toEqual([
  360. ['enter', 'a'], ['exit', 'a'],
  361. ['enter', 'b'], ['exit', 'b'],
  362. ['enter', 'c'], ['exit', 'c'],
  363. ])
  364. expect(result.content[0]).toEqual({ type: 'text', text: 'a,b,c' })
  365. })
  366. it('rejects the program-side call when the tool errors, with the tool error text', async () => {
  367. const { ctx, runtime } = await setup({ mode: 'code' })
  368. ctx.tools.register(defineTool({
  369. name: 'fail',
  370. description: 'Always fails.',
  371. parameters: {},
  372. execute(): Promise<never> { return Promise.reject(new Error('deliberate failure')) },
  373. }))
  374. runtime.behavior = async (request) => {
  375. try {
  376. await request.bindings[0]!.functions.fail!({})
  377. return { logs: [], value: 'unreachable' }
  378. } catch (error: unknown) {
  379. return { logs: [], value: `caught: ${error instanceof Error ? error.message : String(error)}` }
  380. }
  381. }
  382. const result = await runCode(ctx, 'program')
  383. expect(result.content[0]).toEqual({ type: 'text', text: 'caught: Error: deliberate failure' })
  384. })
  385. it('a tools/pre-execute deny reaches the program as a binding rejection', async () => {
  386. const { ctx, runtime } = await setup({ mode: 'code' })
  387. registerEcho(ctx)
  388. ctx.on('tools/pre-execute', (exec, next) => {
  389. if (exec.name === 'echo') return Promise.resolve({ kind: 'deny' as const, reason: 'not on my watch' })
  390. return next()
  391. })
  392. runtime.behavior = async (request) => {
  393. try {
  394. await request.bindings[0]!.functions.echo!({ value: 'x' })
  395. return { logs: [], value: 'unreachable' }
  396. } catch (error: unknown) {
  397. return { logs: [], value: `denied: ${error instanceof Error ? error.message : String(error)}` }
  398. }
  399. }
  400. const result = await runCode(ctx, 'program')
  401. expect(result.content[0]?.type).toBe('text')
  402. expect((result.content[0] as { text: string }).text).toContain('not on my watch')
  403. })
  404. it('rejects a binding argument that does not survive JSON normalization, dispatching nothing', async () => {
  405. const { ctx, runtime } = await setup({ mode: 'code' })
  406. const calls = registerEcho(ctx)
  407. const { agent, events } = fakeAgent()
  408. runtime.behavior = async (request) => {
  409. try {
  410. await request.bindings[0]!.functions.echo!({ value: 'x', big: 1n })
  411. return { logs: [], value: 'unreachable' }
  412. } catch (error: unknown) {
  413. return { logs: [], value: error instanceof Error ? error.message : String(error) }
  414. }
  415. }
  416. const result = await runCode(ctx, 'program', { agent })
  417. expect((result.content[0] as { text: string }).text).toContain('JSON-serializable')
  418. expect(calls).toEqual([])
  419. expect(events.filter(event => event.type === 'tool/code-dispatch')).toEqual([])
  420. })
  421. it('dispatches the JSON-normalized value: what the tool sees is what the event logs', async () => {
  422. const { ctx, runtime } = await setup({ mode: 'code' })
  423. const calls = registerEcho(ctx)
  424. const { agent, events } = fakeAgent()
  425. runtime.behavior = async (request) => {
  426. // A Date survives structured clone but is not JSON; the bridge
  427. // normalizes it to its JSON form (an ISO string) BEFORE dispatch.
  428. await request.bindings[0]!.functions.echo!({ value: 'x', when: new Date(0) }).catch(() => undefined)
  429. return { logs: [] }
  430. }
  431. await runCode(ctx, 'program', { agent })
  432. expect(calls).toEqual([{ value: 'x', when: '1970-01-01T00:00:00.000Z' }])
  433. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  434. expect(dispatch.arguments).toEqual({ value: 'x', when: '1970-01-01T00:00:00.000Z' })
  435. })
  436. it('defers sub-call additionalContexts onto the outer run_code result', async () => {
  437. const { ctx, runtime } = await setup({ mode: 'code' })
  438. registerEcho(ctx)
  439. ctx.on('tools/post-execute', (exec, _result, next): Promise<PostToolDecision> => {
  440. if (exec.name === 'echo') {
  441. return Promise.resolve({
  442. kind: 'accept' as const,
  443. additionalContexts: [{
  444. content: [{ type: 'text' as const, text: `context for ${exec.callId}` }],
  445. source: { kind: 'plugin' as const, plugin: 'test' },
  446. meta: { callId: exec.callId },
  447. }],
  448. })
  449. }
  450. return next()
  451. })
  452. runtime.behavior = async (request) => {
  453. await request.bindings[0]!.functions.echo!({ value: 'x' })
  454. await request.bindings[0]!.functions.echo!({ value: 'y' })
  455. return { logs: [], value: 'done' }
  456. }
  457. const result = await runCode(ctx, 'program')
  458. expect(result.isError).toBe(false)
  459. expect(result.additionalContexts).toEqual([
  460. {
  461. content: [{ type: 'text', text: 'context for call-1:code:1' }],
  462. source: { kind: 'plugin', plugin: 'test' },
  463. meta: { callId: 'call-1:code:1' },
  464. },
  465. {
  466. content: [{ type: 'text', text: 'context for call-1:code:2' }],
  467. source: { kind: 'plugin', plugin: 'test' },
  468. meta: { callId: 'call-1:code:2' },
  469. },
  470. ])
  471. })
  472. it('keeps sub-call contexts when run_code fails after the nested dispatch', async () => {
  473. const { ctx, runtime } = await setup({ mode: 'both' })
  474. registerEcho(ctx)
  475. ctx.on('tools/post-execute', (exec, _result, next): Promise<PostToolDecision> => {
  476. if (exec.name !== 'echo') return next()
  477. return Promise.resolve({
  478. kind: 'accept',
  479. additionalContexts: [{
  480. content: [{ type: 'text', text: 'nested context' }],
  481. source: { kind: 'plugin', plugin: 'test' },
  482. }],
  483. })
  484. })
  485. runtime.behavior = async (request) => {
  486. await request.bindings[0]!.functions.echo!({ value: 'x' })
  487. return { logs: [], error: { kind: 'exception', message: 'program failed later' } }
  488. }
  489. const result = await runCode(ctx, 'program')
  490. expect(result.isError).toBe(true)
  491. expect(result.additionalContexts).toEqual([{
  492. content: [{ type: 'text', text: 'nested context' }],
  493. source: { kind: 'plugin', plugin: 'test' },
  494. }])
  495. })
  496. it('converts a failed run into a structured isError result carrying kind, message, and captured logs', async () => {
  497. const { ctx, runtime } = await setup({ mode: 'code' })
  498. runtime.behavior = () => Promise.resolve({
  499. logs: ['got this far'],
  500. error: { kind: 'timeout', message: 'compute budget exhausted (300ms busy)' },
  501. })
  502. const result = await runCode(ctx, 'program')
  503. expect(result.isError).toBe(true)
  504. expect(result.error).toEqual({ name: 'CodeRunFailedError', code: 'CODE_RUN_FAILED' })
  505. const text = (result.content[0] as { text: string }).text
  506. expect(text).toContain('code run failed (timeout)')
  507. expect(text).toContain('compute budget exhausted')
  508. expect(text).toContain('got this far')
  509. })
  510. it('CodeRunFailedError is a HarnessError with the CODE_RUN_FAILED code', () => {
  511. const error = new CodeRunFailedError('boom')
  512. expect(error.code).toBe('CODE_RUN_FAILED')
  513. expect(error.name).toBe('CodeRunFailedError')
  514. })
  515. it('aborting the outer signal aborts the in-flight sub-dispatch and abandons queued ones', async () => {
  516. const { ctx, runtime } = await setup({ mode: 'code' })
  517. const seen: string[] = []
  518. let sawAbort = false
  519. ctx.tools.register(defineTool({
  520. name: 'slow',
  521. description: 'Slow tool observing its signal.',
  522. parameters: { id: { type: 'string', required: true } },
  523. async execute(args, exec) {
  524. seen.push(args.id)
  525. await new Promise<void>((resolve) => {
  526. const timer = setTimeout(resolve, 500)
  527. exec.signal.addEventListener('abort', () => { sawAbort = true; clearTimeout(timer); resolve() }, { once: true })
  528. })
  529. return [{ type: 'text' as const, text: args.id }]
  530. },
  531. }))
  532. const controller = new AbortController()
  533. runtime.behavior = async (request) => {
  534. const tools = request.bindings[0]!.functions
  535. const calls = [tools.slow!({ id: 'first' }).catch(() => 'rejected'), tools.slow!({ id: 'second' }).catch(() => 'rejected')]
  536. setTimeout(() => { controller.abort('user-cancel') }, 50)
  537. await Promise.all(calls)
  538. // A real runtime would be terminated by the abort; the fake honors the
  539. // contract by reporting the abort as the run failure.
  540. return { logs: [], error: { kind: 'abort', message: 'user-cancel' } }
  541. }
  542. const result = await runCode(ctx, 'program', { signal: controller.signal })
  543. expect(result.isError).toBe(true)
  544. expect((result.content[0] as { text: string }).text).toContain('code run failed (abort)')
  545. expect(seen).toEqual(['first'])
  546. expect(sawAbort).toBe(true)
  547. })
  548. it('a runtime that starts a binding call and then REJECTS still reaches quiescence before returning', async () => {
  549. const { ctx, runtime } = await setup({ mode: 'code' })
  550. const { agent, events } = fakeAgent()
  551. let sawAbort = false
  552. let started!: () => void
  553. const inFlight = new Promise<void>((resolve) => { started = resolve })
  554. ctx.tools.register(defineTool({
  555. name: 'slow',
  556. description: 'Slow tool observing its signal.',
  557. parameters: { id: { type: 'string', required: true } },
  558. async execute(args, exec) {
  559. started()
  560. await new Promise<void>((resolve) => {
  561. const timer = setTimeout(resolve, 500)
  562. exec.signal.addEventListener('abort', () => { sawAbort = true; clearTimeout(timer); resolve() }, { once: true })
  563. })
  564. return [{ type: 'text' as const, text: args.id }]
  565. },
  566. }))
  567. runtime.behavior = async (request) => {
  568. // Start a sub-dispatch, keep its rejection held, and fail the run once the tool is
  569. // genuinely in flight — a seam error after work has begun.
  570. request.bindings[0]!.functions.slow!({ id: 'orphan' }).catch(() => 'held')
  571. await inFlight
  572. throw new Error('backend exploded')
  573. }
  574. const result = await runCode(ctx, 'program', { agent })
  575. expect(result.isError).toBe(true)
  576. expect((result.content[0] as { text: string }).text).toContain('backend exploded')
  577. // Quiescence held: the in-flight sub-dispatch was aborted and its event
  578. // logged INSIDE the run_code execution, not after it returned.
  579. expect(sawAbort).toBe(true)
  580. expect(events.filter(event => event.type === 'tool/code-dispatch').map(event => (event.data as { name: string }).name)).toEqual(['slow'])
  581. })
  582. it('runs without an owning agent: dispatches work, event logging is skipped', async () => {
  583. const { ctx, runtime } = await setup({ mode: 'code' })
  584. const calls = registerEcho(ctx)
  585. runtime.behavior = async (request) => {
  586. await request.bindings[0]!.functions.echo!({ value: 'x' })
  587. return { logs: [], value: 'ok' }
  588. }
  589. const result = await runCode(ctx, 'program')
  590. expect(result.isError).toBe(false)
  591. expect(calls).toEqual([{ value: 'x' }])
  592. })
  593. it('executing run_code under a missing runtime is a structured isError, not a crash', async () => {
  594. const ctx = new Context()
  595. await ctx.plugin(SystemPrompt, {})
  596. await ctx.plugin(ToolRegistry, { mode: 'code' })
  597. const result = await runCode(ctx, 'program')
  598. expect(result.isError).toBe(true)
  599. expect((result.content[0] as { text: string }).text).toContain('requires a code runtime')
  600. })
  601. it('presents the PROGRAM as the execute-card title on both call and result (the one slot execute cards always show)', async () => {
  602. const { ctx } = await setup({ mode: 'code' })
  603. const tool = ctx.tools.get(RUN_CODE_NAME)!
  604. // The program IS the title, mirroring how command tools title their cards
  605. // with the command: an ACP client's execute-card header is the only
  606. // always-visible slot (Zed renders no body content and no raw input for
  607. // execute-kind cards without a real terminal).
  608. expect(tool.presentCall?.({ code: 'return 1' })).toEqual({
  609. card: 'generic',
  610. title: 'return 1',
  611. kind: 'execute',
  612. rawInput: 'return 1',
  613. })
  614. const view = tool.presentResult?.({ code: 'return 1' }, {
  615. content: [{ type: 'text', text: 'model-facing' }],
  616. isError: false,
  617. meta: { logs: ['printed'] },
  618. })
  619. // The result omits the title — an update replaces only provided fields,
  620. // so the pending card's program title persists through completion.
  621. expect(view).toEqual({
  622. card: 'generic',
  623. content: [{ type: 'text', text: 'printed' }],
  624. })
  625. // No captured output → no content either; everything pending persists.
  626. expect(tool.presentResult?.({ code: 'x' }, { content: [], isError: false, meta: { logs: [] } }))
  627. .toEqual({ card: 'generic' })
  628. // Replay with an unrecognizable meta falls back to the generic rendering.
  629. expect(tool.presentResult?.({ code: 'x' }, { content: [], isError: false, meta: { logs: [{ text: 'legacy' }], dispatches: 1 } })).toBeUndefined()
  630. expect(tool.presentResult?.({ code: 'x' }, { content: [], isError: false, meta: { other: true } })).toBeUndefined()
  631. expect(tool.presentResult?.({ code: 'x' }, { content: [], isError: false })).toBeUndefined()
  632. })
  633. it('renders non-text sub-result blocks as placeholders and truncates long event summaries', async () => {
  634. const { ctx, runtime } = await setup({ mode: 'code' })
  635. const { agent, events } = fakeAgent()
  636. const long = 'x'.repeat(300)
  637. ctx.tools.register(defineTool({
  638. name: 'mixed',
  639. description: 'Returns mixed content.',
  640. parameters: {},
  641. execute() {
  642. return Promise.resolve([
  643. { type: 'text' as const, text: long },
  644. { type: 'reasoning' as const, text: 'hidden' },
  645. ])
  646. },
  647. }))
  648. runtime.behavior = async (request) => {
  649. const value = await request.bindings[0]!.functions.mixed!({})
  650. return { logs: [], value }
  651. }
  652. const result = await runCode(ctx, 'program', { agent })
  653. expect(result.isError).toBe(false)
  654. expect((result.content[0] as { text: string }).text).toBe(`${long}\n[reasoning content]`)
  655. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  656. expect(dispatch.resultSummary.length).toBe(201)
  657. expect(dispatch.resultSummary.endsWith('…')).toBe(true)
  658. })
  659. it('normalizes the session workspace root before bounding durable result summaries', async () => {
  660. const { ctx, runtime } = await setup({ mode: 'code' })
  661. ctx.tools.register(defineTool({
  662. name: 'workspace_path',
  663. description: 'Return a path beneath the session workspace.',
  664. parameters: {},
  665. execute(_args, exec) {
  666. const cwd = exec.agent?.session.header.cwd ?? ''
  667. return Promise.resolve([{ type: 'text' as const, text: `<path>${cwd}/nested/task.txt</path>\n${'x'.repeat(240)}` }])
  668. },
  669. }))
  670. runtime.behavior = async request => ({
  671. logs: [],
  672. value: await request.bindings[0]!.functions.workspace_path!({}),
  673. })
  674. const short = fakeAgent({ cwd: '/tmp/workspace' })
  675. const long = fakeAgent({ cwd: `/tmp/${'long-segment/'.repeat(30)}workspace` })
  676. const shortResult = await runCode(ctx, 'program', { agent: short.agent })
  677. const longResult = await runCode(ctx, 'program', { agent: long.agent })
  678. const shortDispatch = short.events[0]!.data as SessionEventMap['tool/code-dispatch']
  679. const longDispatch = long.events[0]!.data as SessionEventMap['tool/code-dispatch']
  680. expect(shortResult.content).not.toEqual(longResult.content)
  681. expect(shortDispatch.resultSummary).toBe(longDispatch.resultSummary)
  682. expect(shortDispatch.resultSummary).toHaveLength(201)
  683. expect(shortDispatch.resultSummary).toMatch(/^<path>\.\/nested\/task\.txt<\/path>\n.+…$/)
  684. })
  685. it('leaves result summaries unchanged when a session cwd is absent or is the filesystem root', async () => {
  686. const { ctx, runtime } = await setup({ mode: 'code' })
  687. registerEcho(ctx)
  688. runtime.behavior = async request => ({
  689. logs: [],
  690. value: await request.bindings[0]!.functions.echo!({ value: '/workspace/value' }),
  691. })
  692. const absent = fakeAgent({})
  693. const root = fakeAgent({ cwd: '/' })
  694. await runCode(ctx, 'program', { agent: absent.agent })
  695. await runCode(ctx, 'program', { agent: root.agent })
  696. expect((absent.events[0]!.data as SessionEventMap['tool/code-dispatch']).resultSummary).toBe('echo:/workspace/value')
  697. expect((root.events[0]!.data as SessionEventMap['tool/code-dispatch']).resultSummary).toBe('echo:/workspace/value')
  698. })
  699. it('rejects undefined, JSON-throwing, and JSON-unrepresentable binding arguments BEFORE dispatch', async () => {
  700. const { ctx, runtime } = await setup({ mode: 'code' })
  701. const calls = registerEcho(ctx)
  702. const { agent, events } = fakeAgent()
  703. runtime.behavior = async (request) => {
  704. const echo = request.bindings[0]!.functions.echo!
  705. const catchMessage = (promise: Promise<unknown>) => promise.then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error))
  706. return {
  707. logs: [],
  708. value: [
  709. // Root undefined must reject up front: the event log rejects it as
  710. // data, and nothing may execute unlogged.
  711. await catchMessage(echo(undefined)),
  712. // A toJSON that throws a NON-Error propagates out of JSON.stringify.
  713. await catchMessage(echo({ toJSON() { throw 'raw-throw' } })),
  714. // A bare function is a value JSON cannot represent at all.
  715. await catchMessage(echo(() => 1)),
  716. ].join(' | '),
  717. }
  718. }
  719. const result = await runCode(ctx, 'program', { agent })
  720. const text = (result.content[0] as { text: string }).text
  721. expect(text).toContain('call the tool with an arguments object')
  722. expect(text).toContain('JSON-serializable: raw-throw')
  723. expect(text).toContain('a value JSON cannot represent')
  724. // None of the three dispatched, none logged.
  725. expect(calls).toEqual([])
  726. expect(events.filter(event => event.type === 'tool/code-dispatch')).toEqual([])
  727. })
  728. it('gives the tool and durable log the same immutable argument value', async () => {
  729. const { ctx, runtime } = await setup({ mode: 'code' })
  730. const { agent, events } = fakeAgent()
  731. let mutationSucceeded: boolean | undefined
  732. ctx.tools.register(defineTool({
  733. name: 'mutator',
  734. description: 'Attempts to mutate its args object.',
  735. parameters: { list: { type: 'array', required: true } },
  736. execute(args) {
  737. mutationSucceeded = Reflect.set(args.list, 1, 'injected-by-tool')
  738. return Promise.resolve([{ type: 'text' as const, text: 'protected' }])
  739. },
  740. }))
  741. runtime.behavior = async (request) => {
  742. await request.bindings[0]!.functions.mutator!({ list: ['original'] })
  743. return { logs: [] }
  744. }
  745. const result = await runCode(ctx, 'program', { agent })
  746. expect(result.isError).toBe(false)
  747. expect(mutationSucceeded).toBe(false)
  748. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  749. expect(dispatch.arguments).toEqual({ list: ['original'] })
  750. })
  751. it('exposes a tool named __proto__ as an ordinary own binding', async () => {
  752. const { ctx, runtime } = await setup({ mode: 'code' })
  753. ctx.tools.register(defineTool({
  754. name: '__proto__',
  755. description: 'A prototype-colliding tool name.',
  756. parameters: {},
  757. execute() { return Promise.resolve([{ type: 'text' as const, text: 'proto-tool-ok' }]) },
  758. }))
  759. runtime.behavior = async (request) => {
  760. const functions = request.bindings[0]!.functions
  761. expect(Object.getPrototypeOf(functions)).toBeNull()
  762. const value = await functions['__proto__']!({})
  763. return { logs: [], value }
  764. }
  765. const result = await runCode(ctx, 'program')
  766. expect(result.isError).toBe(false)
  767. expect(result.content[0]).toEqual({ type: 'text', text: 'proto-tool-ok' })
  768. })
  769. it('renders a non-string completion value inspect-style', async () => {
  770. const { ctx, runtime } = await setup({ mode: 'code' })
  771. runtime.behavior = () => Promise.resolve({ logs: [], value: { n: 42 } })
  772. const result = await runCode(ctx, 'program')
  773. expect((result.content[0] as { text: string }).text).toBe('{ n: 42 }')
  774. })
  775. it('short-circuits a pre-aborted outer signal before the code runtime', async () => {
  776. const { ctx, runtime } = await setup({ mode: 'code' })
  777. const calls = registerEcho(ctx)
  778. runtime.behavior = (request) => {
  779. // The fake honors the seam contract for an already-aborted signal.
  780. if (request.signal?.aborted) return Promise.resolve({ logs: [], error: { kind: 'abort' as const, message: String(request.signal.reason) } })
  781. return Promise.resolve({ logs: [], value: 'unreachable' })
  782. }
  783. const controller = new AbortController()
  784. controller.abort('too-late')
  785. const result = await runCode(ctx, 'program', { signal: controller.signal })
  786. expect(result.isError).toBe(true)
  787. expect(result).toEqual({
  788. content: [{ type: 'text', text: 'Error: tool call aborted before dispatch' }],
  789. isError: true,
  790. error: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH },
  791. })
  792. expect(runtime.lastRequest).toBeUndefined()
  793. expect(calls).toEqual([])
  794. })
  795. it('reports cancellation after rejecting a late binding without dispatching it', async () => {
  796. const { ctx, runtime } = await setup({ mode: 'code' })
  797. const calls = registerEcho(ctx)
  798. const controller = new AbortController()
  799. runtime.behavior = async (request) => {
  800. controller.abort('cancelled-mid-run')
  801. const message = await request.bindings[0]!.functions.echo!({ value: 'x' })
  802. .then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error))
  803. return { logs: [], value: message }
  804. }
  805. const result = await runCode(ctx, 'program', { signal: controller.signal })
  806. expect(result.isError).toBe(true)
  807. expect(result.error).toEqual({ name: 'AbortError', code: 'ABORTED' })
  808. expect((result.content[0] as { text: string }).text).toBe('Error: tool call aborted')
  809. expect(calls).toEqual([])
  810. })
  811. it('a tool/code-dispatch event never derives a model message', () => {
  812. const session = new Session(SessionId('code-mode-derive'))
  813. session.append('user/message', { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  814. session.append('tool/code-dispatch', {
  815. parentCallId: CallId('p1'),
  816. subCallId: CallId('p1:code:1'),
  817. name: 'echo',
  818. arguments: { value: 'x' },
  819. isError: false,
  820. resultSummary: 'echo:x',
  821. })
  822. const derived = session.deriveMessages()
  823. expect(derived).toHaveLength(1)
  824. expect(derived[0]?.role).toBe('user')
  825. })
  826. it('defaults to native mode under direct construction with no config', async () => {
  827. const ctx = new Context()
  828. await ctx.plugin(SystemPrompt, {})
  829. const registry = new ToolRegistry(ctx)
  830. expect(registry.get(RUN_CODE_NAME)).toBeUndefined()
  831. const assembly = await ctx.systemPrompt.assemble()
  832. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  833. })
  834. })