code-mode.spec.ts 48 KB

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