code-mode.spec.ts 37 KB

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