code-mode.spec.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  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: [{ source: 'console', level: 'log', text: `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: [{ source: 'console', level: 'log', text: 'saw echo:one' }], dispatches: 2 })
  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. // Model a timeout-style outer wrapper: it temporarily installs a signal,
  315. // delegates, then restores the exact prior shape. A nested result observer
  316. // is observe-only and must not receive the live outer execution object;
  317. // freezing the correlation value it sees therefore cannot break restore.
  318. ctx.on('tools/execute', async (exec, next) => {
  319. if (exec.name !== RUN_CODE_NAME) return next()
  320. const previous = exec.signal
  321. exec.signal = new AbortController().signal
  322. const result = await next()
  323. if (previous === undefined) delete exec.signal
  324. else exec.signal = previous
  325. return result
  326. })
  327. ctx.on('tools/result', (exec) => {
  328. if (exec.parent !== undefined) Object.freeze(exec.parent)
  329. })
  330. const result = await runCode(ctx, 'await tools.echo({ value: "nested" })')
  331. expect(result.isError).toBe(false)
  332. expect(result.content).toEqual([{ type: 'text', text: 'done' }])
  333. })
  334. it('serializes Promise.all dispatches: tool executions never overlap, in submission order', async () => {
  335. const { ctx, runtime } = await setup({ mode: 'code' })
  336. const intervals: [string, string][] = []
  337. let active = 0
  338. ctx.tools.register(defineTool({
  339. name: 'probe',
  340. description: 'Records execution overlap.',
  341. parameters: { id: { type: 'string', required: true } },
  342. async execute(args) {
  343. active++
  344. expect(active, 'probe executions overlapped').toBe(1)
  345. intervals.push(['enter', args.id])
  346. await new Promise(resolve => setTimeout(resolve, 20))
  347. intervals.push(['exit', args.id])
  348. active--
  349. return [{ type: 'text' as const, text: args.id }]
  350. },
  351. }))
  352. runtime.behavior = async (request) => {
  353. const tools = request.bindings[0]!.functions
  354. const values = await Promise.all([tools.probe!({ id: 'a' }), tools.probe!({ id: 'b' }), tools.probe!({ id: 'c' })])
  355. return { logs: [], value: values.join(',') }
  356. }
  357. const result = await runCode(ctx, 'program')
  358. expect(result.isError).toBe(false)
  359. expect(intervals).toEqual([
  360. ['enter', 'a'], ['exit', 'a'],
  361. ['enter', 'b'], ['exit', 'b'],
  362. ['enter', 'c'], ['exit', 'c'],
  363. ])
  364. expect(result.content[0]).toEqual({ type: 'text', text: 'a,b,c' })
  365. })
  366. it('rejects the program-side call when the tool errors, with the tool error text', async () => {
  367. const { ctx, runtime } = await setup({ mode: 'code' })
  368. ctx.tools.register(defineTool({
  369. name: 'fail',
  370. description: 'Always fails.',
  371. parameters: {},
  372. execute(): Promise<never> { return Promise.reject(new Error('deliberate failure')) },
  373. }))
  374. runtime.behavior = async (request) => {
  375. try {
  376. await request.bindings[0]!.functions.fail!({})
  377. return { logs: [], value: 'unreachable' }
  378. } catch (error: unknown) {
  379. return { logs: [], value: `caught: ${error instanceof Error ? error.message : String(error)}` }
  380. }
  381. }
  382. const result = await runCode(ctx, 'program')
  383. expect(result.content[0]).toEqual({ type: 'text', text: 'caught: Error: deliberate failure' })
  384. })
  385. it('a tools/pre-execute deny reaches the program as a binding rejection', async () => {
  386. const { ctx, runtime } = await setup({ mode: 'code' })
  387. registerEcho(ctx)
  388. ctx.on('tools/pre-execute', (exec, next) => {
  389. if (exec.name === 'echo') return Promise.resolve({ kind: 'deny' as const, reason: 'not on my watch' })
  390. return next()
  391. })
  392. runtime.behavior = async (request) => {
  393. try {
  394. await request.bindings[0]!.functions.echo!({ value: 'x' })
  395. return { logs: [], value: 'unreachable' }
  396. } catch (error: unknown) {
  397. return { logs: [], value: `denied: ${error instanceof Error ? error.message : String(error)}` }
  398. }
  399. }
  400. const result = await runCode(ctx, 'program')
  401. expect(result.content[0]?.type).toBe('text')
  402. expect((result.content[0] as { text: string }).text).toContain('not on my watch')
  403. })
  404. it('rejects a binding argument that does not survive JSON normalization, dispatching nothing', async () => {
  405. const { ctx, runtime } = await setup({ mode: 'code' })
  406. const calls = registerEcho(ctx)
  407. const { agent, events } = fakeAgent()
  408. runtime.behavior = async (request) => {
  409. try {
  410. await request.bindings[0]!.functions.echo!({ value: 'x', big: 1n })
  411. return { logs: [], value: 'unreachable' }
  412. } catch (error: unknown) {
  413. return { logs: [], value: error instanceof Error ? error.message : String(error) }
  414. }
  415. }
  416. const result = await runCode(ctx, 'program', { agent })
  417. expect((result.content[0] as { text: string }).text).toContain('JSON-serializable')
  418. expect(calls).toEqual([])
  419. expect(events.filter(event => event.type === 'tool/code-dispatch')).toEqual([])
  420. })
  421. it('dispatches the JSON-normalized value: what the tool sees is what the event logs', async () => {
  422. const { ctx, runtime } = await setup({ mode: 'code' })
  423. const calls = registerEcho(ctx)
  424. const { agent, events } = fakeAgent()
  425. runtime.behavior = async (request) => {
  426. // A Date survives structured clone but is not JSON; the bridge
  427. // normalizes it to its JSON form (an ISO string) BEFORE dispatch.
  428. await request.bindings[0]!.functions.echo!({ value: 'x', when: new Date(0) }).catch(() => undefined)
  429. return { logs: [] }
  430. }
  431. await runCode(ctx, 'program', { agent })
  432. expect(calls).toEqual([{ value: 'x', when: '1970-01-01T00:00:00.000Z' }])
  433. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  434. expect(dispatch.arguments).toEqual({ value: 'x', when: '1970-01-01T00:00:00.000Z' })
  435. })
  436. it('suppresses sub-call additionalContext (deliberately; pinned)', 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. additionalContext: { content: [{ type: 'text' as const, text: 'context for the next request' }], source: { kind: 'plugin' as const, plugin: 'test' } },
  444. })
  445. }
  446. return next()
  447. })
  448. runtime.behavior = async (request) => {
  449. await request.bindings[0]!.functions.echo!({ value: 'x' })
  450. return { logs: [], value: 'done' }
  451. }
  452. const result = await runCode(ctx, 'program')
  453. expect(result.isError).toBe(false)
  454. // The sub-call's context has no safe outlet mid-run; the parent result
  455. // must not carry it either.
  456. expect(result.additionalContext).toBeUndefined()
  457. })
  458. it('converts a failed run into a structured isError result carrying kind, message, and captured logs', async () => {
  459. const { ctx, runtime } = await setup({ mode: 'code' })
  460. runtime.behavior = () => Promise.resolve({
  461. logs: [{ source: 'console', level: 'log', text: 'got this far' }],
  462. error: { kind: 'timeout', message: 'compute budget exhausted (300ms busy)' },
  463. })
  464. const result = await runCode(ctx, 'program')
  465. expect(result.isError).toBe(true)
  466. expect(result.error).toEqual({ name: 'CodeRunFailedError', code: 'CODE_RUN_FAILED' })
  467. const text = (result.content[0] as { text: string }).text
  468. expect(text).toContain('code run failed (timeout)')
  469. expect(text).toContain('compute budget exhausted')
  470. expect(text).toContain('got this far')
  471. })
  472. it('CodeRunFailedError is a HarnessError with the CODE_RUN_FAILED code', () => {
  473. const error = new CodeRunFailedError('boom')
  474. expect(error.code).toBe('CODE_RUN_FAILED')
  475. expect(error.name).toBe('CodeRunFailedError')
  476. })
  477. it('aborting the outer signal aborts the in-flight sub-dispatch and abandons queued ones', async () => {
  478. const { ctx, runtime } = await setup({ mode: 'code' })
  479. const seen: string[] = []
  480. let sawAbort = false
  481. ctx.tools.register(defineTool({
  482. name: 'slow',
  483. description: 'Slow tool observing its signal.',
  484. parameters: { id: { type: 'string', required: true } },
  485. async execute(args, exec) {
  486. seen.push(args.id)
  487. await new Promise<void>((resolve) => {
  488. const timer = setTimeout(resolve, 500)
  489. exec.signal?.addEventListener('abort', () => { sawAbort = true; clearTimeout(timer); resolve() }, { once: true })
  490. })
  491. return [{ type: 'text' as const, text: args.id }]
  492. },
  493. }))
  494. const controller = new AbortController()
  495. runtime.behavior = async (request) => {
  496. const tools = request.bindings[0]!.functions
  497. const calls = [tools.slow!({ id: 'first' }).catch(() => 'rejected'), tools.slow!({ id: 'second' }).catch(() => 'rejected')]
  498. setTimeout(() => { controller.abort('user-cancel') }, 50)
  499. await Promise.all(calls)
  500. // A real runtime would be terminated by the abort; the fake honors the
  501. // contract by reporting the abort as the run failure.
  502. return { logs: [], error: { kind: 'abort', message: 'user-cancel' } }
  503. }
  504. const result = await runCode(ctx, 'program', { signal: controller.signal })
  505. expect(result.isError).toBe(true)
  506. expect((result.content[0] as { text: string }).text).toContain('code run failed (abort)')
  507. expect(seen).toEqual(['first'])
  508. expect(sawAbort).toBe(true)
  509. })
  510. it('a runtime that starts a binding call and then REJECTS still reaches quiescence before returning', async () => {
  511. const { ctx, runtime } = await setup({ mode: 'code' })
  512. const { agent, events } = fakeAgent()
  513. let sawAbort = false
  514. let started!: () => void
  515. const inFlight = new Promise<void>((resolve) => { started = resolve })
  516. ctx.tools.register(defineTool({
  517. name: 'slow',
  518. description: 'Slow tool observing its signal.',
  519. parameters: { id: { type: 'string', required: true } },
  520. async execute(args, exec) {
  521. started()
  522. await new Promise<void>((resolve) => {
  523. const timer = setTimeout(resolve, 500)
  524. exec.signal?.addEventListener('abort', () => { sawAbort = true; clearTimeout(timer); resolve() }, { once: true })
  525. })
  526. return [{ type: 'text' as const, text: args.id }]
  527. },
  528. }))
  529. runtime.behavior = async (request) => {
  530. // Start a sub-dispatch, keep its rejection held, and fail the run once
  531. // the tool is genuinely in flight — a seam error AFTER work has begun.
  532. // The bridge's settlement still owes quiescence: without the finally,
  533. // run_code would return now and the slow tool would finish (and log)
  534. // afterwards.
  535. request.bindings[0]!.functions.slow!({ id: 'orphan' }).catch(() => 'held')
  536. await inFlight
  537. throw new Error('backend exploded')
  538. }
  539. const result = await runCode(ctx, 'program', { agent })
  540. expect(result.isError).toBe(true)
  541. expect((result.content[0] as { text: string }).text).toContain('backend exploded')
  542. // Quiescence held: the in-flight sub-dispatch was aborted and its event
  543. // logged INSIDE the run_code execution, not after it returned.
  544. expect(sawAbort).toBe(true)
  545. expect(events.filter(event => event.type === 'tool/code-dispatch').map(event => (event.data as { name: string }).name)).toEqual(['slow'])
  546. })
  547. it('runs without an owning agent: dispatches work, event logging is skipped', async () => {
  548. const { ctx, runtime } = await setup({ mode: 'code' })
  549. const calls = registerEcho(ctx)
  550. runtime.behavior = async (request) => {
  551. await request.bindings[0]!.functions.echo!({ value: 'x' })
  552. return { logs: [], value: 'ok' }
  553. }
  554. const result = await runCode(ctx, 'program')
  555. expect(result.isError).toBe(false)
  556. expect(calls).toEqual([{ value: 'x' }])
  557. })
  558. it('executing run_code under a missing runtime is a structured isError, not a crash', async () => {
  559. const ctx = new Context()
  560. await ctx.plugin(SystemPrompt, {})
  561. await ctx.plugin(ToolRegistry, { mode: 'code' })
  562. const result = await runCode(ctx, 'program')
  563. expect(result.isError).toBe(true)
  564. expect((result.content[0] as { text: string }).text).toContain('requires a code runtime')
  565. })
  566. it('presents the PROGRAM as the execute-card title on both call and result (the one slot execute cards always show)', async () => {
  567. const { ctx } = await setup({ mode: 'code' })
  568. const tool = ctx.tools.get(RUN_CODE_NAME)!
  569. // The program IS the title, mirroring how command tools title their cards
  570. // with the command: an ACP client's execute-card header is the only
  571. // always-visible slot (Zed renders no body content and no raw input for
  572. // execute-kind cards without a real terminal).
  573. expect(tool.presentCall?.({ code: 'return 1' })).toEqual({
  574. card: 'generic',
  575. title: 'return 1',
  576. kind: 'execute',
  577. rawInput: 'return 1',
  578. })
  579. const view = tool.presentResult?.({ code: 'return 1' }, {
  580. content: [{ type: 'text', text: 'model-facing' }],
  581. isError: false,
  582. meta: { logs: [{ source: 'console', level: 'log', text: 'printed' }], dispatches: 1 },
  583. })
  584. // The result omits the title — an update replaces only provided fields,
  585. // so the pending card's program title persists through completion.
  586. expect(view).toEqual({
  587. card: 'generic',
  588. content: [{ type: 'text', text: 'printed' }],
  589. })
  590. // No captured output → no content either; everything pending persists.
  591. expect(tool.presentResult?.({ code: 'x' }, { content: [], isError: false, meta: { logs: [], dispatches: 2 } }))
  592. .toEqual({ card: 'generic' })
  593. // Replay with an unrecognizable meta falls back to the generic rendering.
  594. expect(tool.presentResult?.({ code: 'x' }, { content: [], isError: false, meta: { other: true } })).toBeUndefined()
  595. expect(tool.presentResult?.({ code: 'x' }, { content: [], isError: false })).toBeUndefined()
  596. })
  597. it('renders non-text sub-result blocks as placeholders and truncates long event summaries', async () => {
  598. const { ctx, runtime } = await setup({ mode: 'code' })
  599. const { agent, events } = fakeAgent()
  600. const long = 'x'.repeat(300)
  601. ctx.tools.register(defineTool({
  602. name: 'mixed',
  603. description: 'Returns mixed content.',
  604. parameters: {},
  605. execute() {
  606. return Promise.resolve([
  607. { type: 'text' as const, text: long },
  608. { type: 'reasoning' as const, text: 'hidden' },
  609. ])
  610. },
  611. }))
  612. runtime.behavior = async (request) => {
  613. const value = await request.bindings[0]!.functions.mixed!({})
  614. return { logs: [], value }
  615. }
  616. const result = await runCode(ctx, 'program', { agent })
  617. expect(result.isError).toBe(false)
  618. expect((result.content[0] as { text: string }).text).toBe(`${long}\n[reasoning content]`)
  619. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  620. expect(dispatch.resultSummary.length).toBe(201)
  621. expect(dispatch.resultSummary.endsWith('…')).toBe(true)
  622. })
  623. it('rejects undefined, JSON-throwing, and JSON-unrepresentable binding arguments BEFORE dispatch', async () => {
  624. const { ctx, runtime } = await setup({ mode: 'code' })
  625. const calls = registerEcho(ctx)
  626. const { agent, events } = fakeAgent()
  627. runtime.behavior = async (request) => {
  628. const echo = request.bindings[0]!.functions.echo!
  629. const catchMessage = (promise: Promise<unknown>) => promise.then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error))
  630. return {
  631. logs: [],
  632. value: [
  633. // Root undefined must reject up front: the event log rejects it as
  634. // data, and nothing may execute unlogged.
  635. await catchMessage(echo(undefined)),
  636. // A toJSON that throws a NON-Error propagates out of JSON.stringify.
  637. await catchMessage(echo({ toJSON() { throw 'raw-throw' } })),
  638. // A bare function is a value JSON cannot represent at all.
  639. await catchMessage(echo(() => 1)),
  640. ].join(' | '),
  641. }
  642. }
  643. const result = await runCode(ctx, 'program', { agent })
  644. const text = (result.content[0] as { text: string }).text
  645. expect(text).toContain('call the tool with an arguments object')
  646. expect(text).toContain('JSON-serializable: raw-throw')
  647. expect(text).toContain('a value JSON cannot represent')
  648. // None of the three dispatched, none logged.
  649. expect(calls).toEqual([])
  650. expect(events.filter(event => event.type === 'tool/code-dispatch')).toEqual([])
  651. })
  652. it('gives the tool and durable log the same immutable argument value', async () => {
  653. const { ctx, runtime } = await setup({ mode: 'code' })
  654. const { agent, events } = fakeAgent()
  655. let mutationSucceeded: boolean | undefined
  656. ctx.tools.register(defineTool({
  657. name: 'mutator',
  658. description: 'Attempts to mutate its args object.',
  659. parameters: { list: { type: 'array', required: true } },
  660. execute(args) {
  661. mutationSucceeded = Reflect.set(args.list, 1, 'injected-by-tool')
  662. return Promise.resolve([{ type: 'text' as const, text: 'protected' }])
  663. },
  664. }))
  665. runtime.behavior = async (request) => {
  666. await request.bindings[0]!.functions.mutator!({ list: ['original'] })
  667. return { logs: [] }
  668. }
  669. const result = await runCode(ctx, 'program', { agent })
  670. expect(result.isError).toBe(false)
  671. expect(mutationSucceeded).toBe(false)
  672. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  673. expect(dispatch.arguments).toEqual({ list: ['original'] })
  674. })
  675. it('exposes a tool named __proto__ as an ordinary own binding', async () => {
  676. const { ctx, runtime } = await setup({ mode: 'code' })
  677. ctx.tools.register(defineTool({
  678. name: '__proto__',
  679. description: 'A prototype-colliding tool name.',
  680. parameters: {},
  681. execute() { return Promise.resolve([{ type: 'text' as const, text: 'proto-tool-ok' }]) },
  682. }))
  683. runtime.behavior = async (request) => {
  684. const functions = request.bindings[0]!.functions
  685. expect(Object.getPrototypeOf(functions)).toBeNull()
  686. const value = await functions['__proto__']!({})
  687. return { logs: [], value }
  688. }
  689. const result = await runCode(ctx, 'program')
  690. expect(result.isError).toBe(false)
  691. expect(result.content[0]).toEqual({ type: 'text', text: 'proto-tool-ok' })
  692. })
  693. it('renders a non-string completion value inspect-style', async () => {
  694. const { ctx, runtime } = await setup({ mode: 'code' })
  695. runtime.behavior = () => Promise.resolve({ logs: [], value: { n: 42 } })
  696. const result = await runCode(ctx, 'program')
  697. expect((result.content[0] as { text: string }).text).toBe('{ n: 42 }')
  698. })
  699. it('reports a pre-aborted outer signal as the run failure without dispatching anything', async () => {
  700. const { ctx, runtime } = await setup({ mode: 'code' })
  701. const calls = registerEcho(ctx)
  702. runtime.behavior = (request) => {
  703. // The fake honors the seam contract for an already-aborted signal.
  704. if (request.signal?.aborted) return Promise.resolve({ logs: [], error: { kind: 'abort' as const, message: String(request.signal.reason) } })
  705. return Promise.resolve({ logs: [], value: 'unreachable' })
  706. }
  707. const controller = new AbortController()
  708. controller.abort('too-late')
  709. const result = await runCode(ctx, 'program', { signal: controller.signal })
  710. expect(result.isError).toBe(true)
  711. expect((result.content[0] as { text: string }).text).toContain('code run failed (abort)')
  712. expect(calls).toEqual([])
  713. })
  714. it('rejects a binding invoked after the run is over without dispatching it', async () => {
  715. const { ctx, runtime } = await setup({ mode: 'code' })
  716. const calls = registerEcho(ctx)
  717. const controller = new AbortController()
  718. runtime.behavior = async (request) => {
  719. controller.abort('cancelled-mid-run')
  720. const message = await request.bindings[0]!.functions.echo!({ value: 'x' })
  721. .then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error))
  722. return { logs: [], value: message }
  723. }
  724. const result = await runCode(ctx, 'program', { signal: controller.signal })
  725. expect(result.isError).toBe(false)
  726. expect((result.content[0] as { text: string }).text).toContain('not dispatched')
  727. expect(calls).toEqual([])
  728. })
  729. it('a tool/code-dispatch event never derives a model message', () => {
  730. const session = new Session(SessionId('code-mode-derive'))
  731. session.append('user/message', { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  732. session.append('tool/code-dispatch', {
  733. parentCallId: CallId('p1'),
  734. subCallId: CallId('p1:code:1'),
  735. name: 'echo',
  736. arguments: { value: 'x' },
  737. isError: false,
  738. resultSummary: 'echo:x',
  739. })
  740. const derived = session.deriveMessages()
  741. expect(derived).toHaveLength(1)
  742. expect(derived[0]?.role).toBe('user')
  743. })
  744. it('defaults to native mode under direct construction with no config', async () => {
  745. const ctx = new Context()
  746. await ctx.plugin(SystemPrompt, {})
  747. const registry = new ToolRegistry(ctx)
  748. expect(registry.get(RUN_CODE_NAME)).toBeUndefined()
  749. const assembly = await ctx.systemPrompt.assemble()
  750. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  751. })
  752. })