code-mode.spec.ts 37 KB

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