code-mode.spec.ts 56 KB

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