code-mode.spec.ts 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480
  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('a tool unregistered between binding enumeration and dispatch fails as unknown tool', async () => {
  438. const { ctx, runtime } = await setup({ mode: 'code' })
  439. const calls: unknown[] = []
  440. const dispose = ctx.tools.register(defineTool({
  441. name: 'ephemeral',
  442. description: 'Unregistered between binding enumeration and dispatch.',
  443. parameters: {},
  444. output: {
  445. schema: { type: 'string' },
  446. render: (_args, value) => [{ type: 'text', text: value }],
  447. },
  448. execute() {
  449. calls.push('ran')
  450. return Promise.resolve('ok')
  451. },
  452. }))
  453. runtime.behavior = async (request) => {
  454. // The binding exists (enumerated at run start); the registry mutation
  455. // makes prepare resolve UNKNOWN_TOOL as a final-result, which commits
  456. // through scheduler.finish (no post-execute).
  457. dispose()
  458. const message = await request.bindings[0]!.functions.ephemeral!({})
  459. .then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error))
  460. return { logs: [], value: message }
  461. }
  462. const result = await runCode(ctx, 'program')
  463. expect(result.isError).toBe(false)
  464. if (result.isError) throw new Error('expected success')
  465. expect(result.value).toMatchObject({ result: 'unknown tool "ephemeral"' })
  466. expect(calls).toEqual([])
  467. })
  468. it('ordered pre-execute never overlaps: a slow policy on one call delays the next start', async () => {
  469. const { ctx, runtime } = await setup({ mode: 'code' })
  470. const gated = registerGated(ctx, 'safe_read', true)
  471. const stages: string[] = []
  472. let releaseGate: (() => void) | undefined
  473. ctx.on('tools/pre-execute', async (preExec, next) => {
  474. if (preExec.name !== 'safe_read') return next()
  475. stages.push(`pre-enter:${String(preExec.callId)}`)
  476. if (releaseGate === undefined) {
  477. // The FIRST call's policy awaits an asynchronous decision.
  478. await new Promise<void>((resolve) => { releaseGate = resolve })
  479. }
  480. stages.push(`pre-exit:${String(preExec.callId)}`)
  481. return next()
  482. })
  483. runtime.behavior = async (request) => {
  484. const tools = request.bindings[0]!.functions
  485. const all = Promise.all([tools.safe_read!({ id: 'a' }), tools.safe_read!({ id: 'b' })])
  486. // Both submissions are in; the second pre-execute must NOT have entered
  487. // while the first is still awaiting its policy decision.
  488. await expect.poll(() => stages.length).toBeGreaterThanOrEqual(1)
  489. expect(stages).toEqual(['pre-enter:call-1:code:1'])
  490. releaseGate!()
  491. await expect.poll(() => gated.pending()).toBe(2)
  492. gated.releaseAll()
  493. await all
  494. return { logs: [], value: 'ordered-prepare' }
  495. }
  496. const result = await runCode(ctx, 'program')
  497. expect(result.isError).toBe(false)
  498. expect(stages).toEqual([
  499. 'pre-enter:call-1:code:1', 'pre-exit:call-1:code:1',
  500. 'pre-enter:call-1:code:2', 'pre-exit:call-1:code:2',
  501. ])
  502. })
  503. it('an exclusive call holds its barrier through post-execute: the next start waits for the commit', async () => {
  504. const { ctx, runtime } = await setup({ mode: 'code' })
  505. const writer = registerGated(ctx, 'writer', false)
  506. const reader = registerGated(ctx, 'safe_read', true)
  507. const stages: string[] = []
  508. let releasePost: (() => void) | undefined
  509. ctx.on('tools/post-execute', async (postExec, _result, next): Promise<PostToolDecision> => {
  510. if (postExec.name === 'writer') {
  511. stages.push('post-enter:writer')
  512. await new Promise<void>((resolve) => { releasePost = resolve })
  513. stages.push('post-exit:writer')
  514. }
  515. return next()
  516. })
  517. runtime.behavior = async (request) => {
  518. const tools = request.bindings[0]!.functions
  519. const w = tools.writer!({ id: 'w' })
  520. const r = tools.safe_read!({ id: 'r' })
  521. await expect.poll(() => writer.pending()).toBe(1)
  522. writer.release()
  523. // The writer's body is done and its async post-execute is running; the
  524. // parallel read must not have STARTED (no pre/body) while the exclusive
  525. // call's pipeline is still open.
  526. await expect.poll(() => stages).toContain('post-enter:writer')
  527. expect(reader.pending()).toBe(0)
  528. releasePost!()
  529. await w
  530. await expect.poll(() => reader.pending()).toBe(1)
  531. reader.releaseAll()
  532. await r
  533. return { logs: [], value: 'barrier-through-commit' }
  534. }
  535. const result = await runCode(ctx, 'program')
  536. expect(result.isError).toBe(false)
  537. expect(stages).toEqual(['post-enter:writer', 'post-exit:writer'])
  538. })
  539. it('run settlement drains a commit already in progress: the settle event lands inside the turn', async () => {
  540. const { ctx, runtime } = await setup({ mode: 'code' })
  541. const gated = registerGated(ctx, 'safe_read', true)
  542. const { agent, events } = fakeAgent()
  543. let releasePost: (() => void) | undefined
  544. ctx.on('tools/post-execute', async (postExec, _result, next): Promise<PostToolDecision> => {
  545. if (postExec.name === 'safe_read') {
  546. await new Promise<void>((resolve) => { releasePost = resolve })
  547. }
  548. return next()
  549. })
  550. runtime.behavior = async (request) => {
  551. // Fire-and-forget: the program returns while the sub-call's async
  552. // post-execute commit is mid-flight.
  553. request.bindings[0]!.functions.safe_read!({ id: 'a' }).catch(() => 'run-over')
  554. await expect.poll(() => gated.pending()).toBe(1)
  555. gated.release()
  556. await expect.poll(() => releasePost !== undefined).toBe(true)
  557. queueMicrotask(() => { releasePost!() })
  558. return { logs: [], value: 'returned-early' }
  559. }
  560. const result = await runCode(ctx, 'program', { agent })
  561. expect(result.isError).toBe(false)
  562. // The drain awaited the in-progress commit: the settle event exists and
  563. // preceded the run_code turn closing (all appends happen inside
  564. // execute()). The run's settlement aborted the sub-call's signal while
  565. // its post-execute was mid-flight, so the native cancellation contract
  566. // replaces the successful outcome with the aborted result — the event is
  567. // still durable and in-turn, which is the invariant under test.
  568. const settles = events.filter(event => event.type === 'tool/code-dispatch')
  569. expect(settles).toHaveLength(1)
  570. expect(settles[0]?.data).toMatchObject({ name: 'safe_read', isError: true })
  571. })
  572. it('post-execute and context commitment stay in submission order under out-of-order completion', async () => {
  573. const { ctx, runtime } = await setup({ mode: 'code' })
  574. const gated = registerGated(ctx, 'safe_read', true)
  575. const postOrder: string[] = []
  576. ctx.on('tools/post-execute', async (postExec, _result, next): Promise<PostToolDecision> => {
  577. if (postExec.name === 'safe_read') {
  578. postOrder.push(String(postExec.callId))
  579. return {
  580. kind: 'accept' as const,
  581. additionalContexts: [{
  582. content: [{ type: 'text' as const, text: `ctx:${String(postExec.callId)}` }],
  583. source: { kind: 'plugin' as const, plugin: 'order-probe' },
  584. }],
  585. }
  586. }
  587. return next()
  588. })
  589. runtime.behavior = async (request) => {
  590. const tools = request.bindings[0]!.functions
  591. const all = Promise.all([tools.safe_read!({ id: 'a' }), tools.safe_read!({ id: 'b' })])
  592. await expect.poll(() => gated.pending()).toBe(2)
  593. // Complete b FIRST (out of submission order), then a.
  594. gated.release() // releases a (FIFO gate) — invert: release twice reversed is not possible;
  595. gated.releaseAll()
  596. await all
  597. return { logs: [], value: 'ordered-commit' }
  598. }
  599. const result = await runCode(ctx, 'program')
  600. expect(result.isError).toBe(false)
  601. // Post-execute observed submission order regardless of completion interleave.
  602. expect(postOrder).toEqual(['call-1:code:1', 'call-1:code:2'])
  603. // Deferred contexts reach the outer result in the same order.
  604. expect(result.additionalContexts?.map(c => (c.content[0] as { text: string }).text))
  605. .toEqual(['ctx:call-1:code:1', 'ctx:call-1:code:2'])
  606. })
  607. it('a queued-unstarted call abandoned by run settlement logs no start event', async () => {
  608. const { ctx, runtime } = await setup({ mode: 'code' })
  609. const gated = registerGated(ctx, 'writer', false)
  610. const { agent, events } = fakeAgent()
  611. const abandoned: string[] = []
  612. runtime.behavior = async (request) => {
  613. const tools = request.bindings[0]!.functions
  614. // First exclusive call occupies the pool; the second queues unstarted.
  615. // Both rejections are captured (abandonment fires only at settlement,
  616. // AFTER this program has already failed — awaiting it here would deadlock).
  617. tools.writer!({ id: 'w1' }).catch(() => 'settled-under-abort')
  618. tools.writer!({ id: 'w2' }).catch((error: unknown) => {
  619. abandoned.push(error instanceof Error ? error.message : String(error))
  620. })
  621. await expect.poll(() => gated.pending()).toBe(1)
  622. // Fail the program while w1 is in flight and w2 is queued unstarted.
  623. throw new Error('program failed with a queued call')
  624. }
  625. const result = await runCode(ctx, 'program', { agent })
  626. expect(result.isError).toBe(true)
  627. const starts = events.filter(event => event.type === 'tool/code-dispatch-start').map(event => (event.data as { subCallId: string }).subCallId)
  628. const settles = events.filter(event => event.type === 'tool/code-dispatch').map(event => (event.data as { subCallId: string }).subCallId)
  629. // w1 started and settled under the abort; w2 never started and never
  630. // settled — no start event, no settle event, binding rejected with the
  631. // abandonment message at drain time.
  632. expect(starts).toEqual(['call-1:code:1'])
  633. expect(settles).toEqual(['call-1:code:1'])
  634. expect(abandoned).toEqual(['run_code run is over (run_code settled); writer tool call abandoned'])
  635. })
  636. })
  637. describe('the run_code dispatch bridge', () => {
  638. it('bridges tool calls, returns only the curated output, and logs one event per dispatch', async () => {
  639. const { ctx, runtime } = await setup({ mode: 'code' })
  640. const calls = registerEcho(ctx)
  641. const { agent, events } = fakeAgent()
  642. runtime.behavior = async (request) => {
  643. const tools = request.bindings[0]!.functions
  644. const first = await tools.echo!({ value: 'one' })
  645. const second = await tools.echo!({ value: 'two' })
  646. if (typeof first !== 'string' || typeof second !== 'string') throw new Error('echo returned a non-string')
  647. return { logs: [`saw ${first}`], value: second }
  648. }
  649. const result = await runCode(ctx, 'const …: string = …', { agent })
  650. expect(result.isError).toBe(false)
  651. if (result.isError) throw new Error('expected run_code success')
  652. expect(result.value).toEqual({ logs: ['saw echo:one'], result: 'echo:two' })
  653. expect(result.content).toEqual([{ type: 'text', text: 'saw echo:one\necho:two' }])
  654. expect(calls).toEqual([{ value: 'one' }, { value: 'two' }])
  655. const dispatches = events.filter(event => event.type === 'tool/code-dispatch')
  656. expect(dispatches.map(event => event.data)).toEqual([
  657. {
  658. parentCallId: 'call-1', subCallId: 'call-1:code:1', name: 'echo',
  659. arguments: { value: 'one' }, isError: false, content: [{ type: 'text', text: 'echo:one' }],
  660. },
  661. {
  662. parentCallId: 'call-1', subCallId: 'call-1:code:2', name: 'echo',
  663. arguments: { value: 'two' }, isError: false, content: [{ type: 'text', text: 'echo:two' }],
  664. },
  665. ])
  666. expect(result.meta).toBeUndefined()
  667. })
  668. it('exposes only an opaque parent token to nested result observers', async () => {
  669. const { ctx, runtime } = await setup({ mode: 'code' })
  670. registerEcho(ctx)
  671. runtime.behavior = async (request) => {
  672. await request.bindings[0]!.functions.echo!({ value: 'nested' })
  673. return { logs: [], value: 'done' }
  674. }
  675. // Freeze the nested observer's parent correlation. If that were the live
  676. // outer execution object, the timeout-style wrapper could not restore it.
  677. ctx.on('tools/execute', async (exec, next) => {
  678. if (exec.name !== RUN_CODE_NAME) return next()
  679. const previous = exec.signal
  680. exec.signal = new AbortController().signal
  681. const result = await next()
  682. exec.signal = previous
  683. return result
  684. })
  685. ctx.on('tools/result', (exec) => {
  686. if (exec.parent !== undefined) Object.freeze(exec.parent)
  687. })
  688. const result = await runCode(ctx, 'await tools.echo({ value: "nested" })')
  689. expect(result.isError).toBe(false)
  690. expect(result.content).toEqual([{ type: 'text', text: 'done' }])
  691. })
  692. it('forwards a nested terminal conclusion onto the successful run_code result', async () => {
  693. const { ctx, runtime } = await setup({ mode: 'code' })
  694. ctx.tools.register(defineTool({
  695. name: 'finalize',
  696. description: 'Terminal tool.',
  697. parameters: {},
  698. output: {
  699. schema: { type: 'string' },
  700. render: (_args, value) => [{ type: 'text', text: value }],
  701. },
  702. execute(_args, exec) {
  703. exec.concludeTurn()
  704. return Promise.resolve('done')
  705. },
  706. }))
  707. runtime.behavior = async (request) => {
  708. await request.bindings[0]!.functions.finalize!({})
  709. return { logs: [], value: 'program complete' }
  710. }
  711. const concluded = await runCode(ctx, 'await tools.finalize({})')
  712. expect(concluded.isError).toBe(false)
  713. expect(concluded.concludesTurn).toBe(true)
  714. // A policy that converts the nested success into an error strips the
  715. // marker with the result type: the recovering program cannot conclude.
  716. const veto = ctx.on('tools/post-execute', async (exec, _result, next): Promise<PostToolDecision> => {
  717. if (exec.name !== 'finalize') return next()
  718. return { kind: 'block', feedback: [{ type: 'text', text: 'terminal rejected' }] }
  719. })
  720. runtime.behavior = async (request) => {
  721. await request.bindings[0]!.functions.finalize!({}).catch(() => undefined)
  722. return { logs: [], value: 'recovered' }
  723. }
  724. const recovered = await runCode(ctx, 'await tools.finalize({}).catch(() => {})')
  725. veto()
  726. expect(recovered.isError).toBe(false)
  727. expect(recovered.concludesTurn).toBeUndefined()
  728. })
  729. it('serializes Promise.all dispatches: tool executions never overlap, in submission order', async () => {
  730. const { ctx, runtime } = await setup({ mode: 'code' })
  731. const intervals: [string, string][] = []
  732. let active = 0
  733. ctx.tools.register(defineTool({
  734. name: 'probe',
  735. description: 'Records execution overlap.',
  736. parameters: { id: { type: 'string', required: true } },
  737. output: {
  738. schema: { type: 'string' },
  739. render: (_args, value) => [{ type: 'text', text: value }],
  740. },
  741. async execute(args) {
  742. active++
  743. expect(active, 'probe executions overlapped').toBe(1)
  744. intervals.push(['enter', args.id])
  745. await new Promise(resolve => setTimeout(resolve, 20))
  746. intervals.push(['exit', args.id])
  747. active--
  748. return args.id
  749. },
  750. }))
  751. runtime.behavior = async (request) => {
  752. const tools = request.bindings[0]!.functions
  753. const values = await Promise.all([tools.probe!({ id: 'a' }), tools.probe!({ id: 'b' }), tools.probe!({ id: 'c' })])
  754. if (!values.every(value => typeof value === 'string')) throw new Error('probe returned a non-string')
  755. return { logs: [], value: values.join(',') }
  756. }
  757. const result = await runCode(ctx, 'program')
  758. expect(result.isError).toBe(false)
  759. expect(intervals).toEqual([
  760. ['enter', 'a'], ['exit', 'a'],
  761. ['enter', 'b'], ['exit', 'b'],
  762. ['enter', 'c'], ['exit', 'c'],
  763. ])
  764. expect(result.content[0]).toEqual({ type: 'text', text: 'a,b,c' })
  765. })
  766. it('rejects the program-side call when the tool errors, with the tool error text', async () => {
  767. const { ctx, runtime } = await setup({ mode: 'code' })
  768. ctx.tools.register(defineContentToolFixture({
  769. name: 'fail',
  770. description: 'Always fails.',
  771. parameters: {},
  772. execute(): Promise<never> { return Promise.reject(new Error('deliberate failure')) },
  773. }))
  774. runtime.behavior = async (request) => {
  775. try {
  776. await request.bindings[0]!.functions.fail!({})
  777. return { logs: [], value: 'unreachable' }
  778. } catch (error: unknown) {
  779. return { logs: [], value: `caught: ${error instanceof Error ? error.message : String(error)}` }
  780. }
  781. }
  782. const result = await runCode(ctx, 'program')
  783. expect(result.content[0]).toEqual({ type: 'text', text: 'caught: deliberate failure' })
  784. })
  785. it('a throwing tools/code-dispatch-log listener is contained: the unshaped content is logged', async () => {
  786. const { ctx, runtime } = await setup({ mode: 'code' })
  787. registerEcho(ctx)
  788. ctx.on('tools/code-dispatch-log', () => { throw new Error('shaper exploded') })
  789. const { agent, events } = fakeAgent()
  790. runtime.behavior = async (request) => {
  791. const value = await request.bindings[0]!.functions.echo!({ value: 'x' })
  792. return { logs: [], value: value as string }
  793. }
  794. const result = await runCode(ctx, 'program', { agent })
  795. expect(result.isError).toBe(false)
  796. const settle = events.find(event => event.type === 'tool/code-dispatch')
  797. expect(settle?.data).toMatchObject({ name: 'echo', isError: false, content: [{ type: 'text', text: 'echo:x' }] })
  798. })
  799. it('a throwing tools/pre-execute listener settles the sub-call without post-execute', async () => {
  800. const { ctx, runtime } = await setup({ mode: 'code' })
  801. const calls = registerEcho(ctx)
  802. const postExecuted: string[] = []
  803. ctx.on('tools/pre-execute', (exec, next) => {
  804. if (exec.name === 'echo') throw new Error('gate exploded')
  805. return next()
  806. })
  807. ctx.on('tools/post-execute', (exec, _result, next): Promise<PostToolDecision> => {
  808. if (exec.name === 'echo') postExecuted.push(exec.name)
  809. return next()
  810. })
  811. const { agent, events } = fakeAgent()
  812. runtime.behavior = async (request) => {
  813. const message = await request.bindings[0]!.functions.echo!({ value: 'x' })
  814. .then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error))
  815. return { logs: [], value: message }
  816. }
  817. const result = await runCode(ctx, 'program', { agent })
  818. expect(result.isError).toBe(false)
  819. if (result.isError) throw new Error('expected success')
  820. expect(result.value).toMatchObject({ result: 'gate exploded' })
  821. // The pipeline failure is final: the body never ran and post-execute was
  822. // skipped, yet the settle event still carries the error outcome.
  823. expect(calls).toEqual([])
  824. expect(postExecuted).toEqual([])
  825. const settles = events.filter(event => event.type === 'tool/code-dispatch')
  826. expect(settles).toHaveLength(1)
  827. expect(settles[0]?.data).toMatchObject({ name: 'echo', isError: true })
  828. })
  829. it('a tools/pre-execute deny reaches the program as a binding rejection', async () => {
  830. const { ctx, runtime } = await setup({ mode: 'code' })
  831. registerEcho(ctx)
  832. ctx.on('tools/pre-execute', (exec, next) => {
  833. if (exec.name === 'echo') return Promise.resolve({ kind: 'deny' as const, reason: 'not on my watch' })
  834. return next()
  835. })
  836. runtime.behavior = async (request) => {
  837. try {
  838. await request.bindings[0]!.functions.echo!({ value: 'x' })
  839. return { logs: [], value: 'unreachable' }
  840. } catch (error: unknown) {
  841. return { logs: [], value: `denied: ${error instanceof Error ? error.message : String(error)}` }
  842. }
  843. }
  844. const result = await runCode(ctx, 'program')
  845. expect(result.content[0]?.type).toBe('text')
  846. expect((result.content[0] as { text: string }).text).toContain('not on my watch')
  847. })
  848. it('rejects a binding argument that is not lossless JSON, dispatching nothing', async () => {
  849. const { ctx, runtime } = await setup({ mode: 'code' })
  850. const calls = registerEcho(ctx)
  851. const { agent, events } = fakeAgent()
  852. runtime.behavior = async (request) => {
  853. try {
  854. await request.bindings[0]!.functions.echo!({ value: 'x', big: 1n })
  855. return { logs: [], value: 'unreachable' }
  856. } catch (error: unknown) {
  857. return { logs: [], value: error instanceof Error ? error.message : String(error) }
  858. }
  859. }
  860. const result = await runCode(ctx, 'program', { agent })
  861. expect((result.content[0] as { text: string }).text).toContain('lossless JSON')
  862. expect(calls).toEqual([])
  863. expect(events.filter(event => event.type === 'tool/code-dispatch')).toEqual([])
  864. })
  865. it('dispatches and logs independent snapshots of the same lossless JSON value', async () => {
  866. const { ctx, runtime } = await setup({ mode: 'code' })
  867. const calls = registerEcho(ctx)
  868. const { agent, events } = fakeAgent()
  869. runtime.behavior = async (request) => {
  870. const args = Object.assign(Object.create(null) as Record<string, unknown>, { value: 'x', nested: ['same'] })
  871. await request.bindings[0]!.functions.echo!(args)
  872. return { logs: [] }
  873. }
  874. await runCode(ctx, 'program', { agent })
  875. expect(calls).toEqual([{ value: 'x', nested: ['same'] }])
  876. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  877. expect(dispatch.arguments).toEqual({ value: 'x', nested: ['same'] })
  878. })
  879. it('defers sub-call additionalContexts onto the outer run_code result', async () => {
  880. const { ctx, runtime } = await setup({ mode: 'code' })
  881. registerEcho(ctx)
  882. ctx.on('tools/post-execute', (exec, _result, next): Promise<PostToolDecision> => {
  883. if (exec.name === 'echo') {
  884. return Promise.resolve({
  885. kind: 'accept' as const,
  886. additionalContexts: [{
  887. content: [{ type: 'text' as const, text: `context for ${exec.callId}` }],
  888. source: { kind: 'plugin' as const, plugin: 'test' },
  889. meta: { callId: exec.callId },
  890. }],
  891. })
  892. }
  893. return next()
  894. })
  895. runtime.behavior = async (request) => {
  896. await request.bindings[0]!.functions.echo!({ value: 'x' })
  897. await request.bindings[0]!.functions.echo!({ value: 'y' })
  898. return { logs: [], value: 'done' }
  899. }
  900. const result = await runCode(ctx, 'program')
  901. expect(result.isError).toBe(false)
  902. expect(result.additionalContexts).toEqual([
  903. {
  904. content: [{ type: 'text', text: 'context for call-1:code:1' }],
  905. source: { kind: 'plugin', plugin: 'test' },
  906. meta: { callId: 'call-1:code:1' },
  907. },
  908. {
  909. content: [{ type: 'text', text: 'context for call-1:code:2' }],
  910. source: { kind: 'plugin', plugin: 'test' },
  911. meta: { callId: 'call-1:code:2' },
  912. },
  913. ])
  914. })
  915. it('keeps sub-call contexts when run_code fails after the nested dispatch', async () => {
  916. const { ctx, runtime } = await setup({ mode: 'both' })
  917. registerEcho(ctx)
  918. ctx.on('tools/post-execute', (exec, _result, next): Promise<PostToolDecision> => {
  919. if (exec.name !== 'echo') return next()
  920. return Promise.resolve({
  921. kind: 'accept',
  922. additionalContexts: [{
  923. content: [{ type: 'text', text: 'nested context' }],
  924. source: { kind: 'plugin', plugin: 'test' },
  925. }],
  926. })
  927. })
  928. runtime.behavior = async (request) => {
  929. await request.bindings[0]!.functions.echo!({ value: 'x' })
  930. return { logs: [], error: { kind: 'exception', message: 'program failed later' } }
  931. }
  932. const result = await runCode(ctx, 'program')
  933. expect(result.isError).toBe(true)
  934. expect(result.additionalContexts).toEqual([{
  935. content: [{ type: 'text', text: 'nested context' }],
  936. source: { kind: 'plugin', plugin: 'test' },
  937. }])
  938. })
  939. it('converts a failed run into a structured isError result carrying kind, message, and captured logs', async () => {
  940. const { ctx, runtime } = await setup({ mode: 'code' })
  941. runtime.behavior = () => Promise.resolve({
  942. logs: ['got this far'],
  943. error: { kind: 'timeout', message: 'compute budget exhausted (300ms busy)' },
  944. })
  945. const result = await runCode(ctx, 'program')
  946. expect(result.isError).toBe(true)
  947. expect(result.error).toMatchObject({ info: { name: 'CodeRunFailedError', code: 'CODE_RUN_FAILED' } })
  948. const text = (result.content[0] as { text: string }).text
  949. expect(text).toContain('code run failed (timeout)')
  950. expect(text).toContain('compute budget exhausted')
  951. expect(text).toContain('got this far')
  952. })
  953. it('CodeRunFailedError is a HarnessError with the CODE_RUN_FAILED code', () => {
  954. const error = new CodeRunFailedError('boom')
  955. expect(error.code).toBe('CODE_RUN_FAILED')
  956. expect(error.name).toBe('CodeRunFailedError')
  957. })
  958. it('aborting the outer signal aborts the in-flight sub-dispatch and abandons queued ones', async () => {
  959. const { ctx, runtime } = await setup({ mode: 'code' })
  960. const seen: string[] = []
  961. let sawAbort = false
  962. ctx.tools.register(defineContentToolFixture({
  963. name: 'slow',
  964. description: 'Slow tool observing its signal.',
  965. parameters: { id: { type: 'string', required: true } },
  966. async execute(args, exec) {
  967. seen.push(args.id)
  968. await new Promise<void>((resolve) => {
  969. const timer = setTimeout(resolve, 500)
  970. exec.signal.addEventListener('abort', () => { sawAbort = true; clearTimeout(timer); resolve() }, { once: true })
  971. })
  972. return [{ type: 'text' as const, text: args.id }]
  973. },
  974. }))
  975. const controller = new AbortController()
  976. runtime.behavior = async (request) => {
  977. const tools = request.bindings[0]!.functions
  978. const calls = [tools.slow!({ id: 'first' }).catch(() => 'rejected'), tools.slow!({ id: 'second' }).catch(() => 'rejected')]
  979. setTimeout(() => { controller.abort('user-cancel') }, 50)
  980. await Promise.all(calls)
  981. // A real runtime would be terminated by the abort; the fake honors the
  982. // contract by reporting the abort as the run failure.
  983. return { logs: [], error: { kind: 'abort', message: 'user-cancel' } }
  984. }
  985. const result = await runCode(ctx, 'program', { signal: controller.signal })
  986. expect(result.isError).toBe(true)
  987. expect((result.content[0] as { text: string }).text).toContain('code run failed (abort)')
  988. expect(seen).toEqual(['first'])
  989. expect(sawAbort).toBe(true)
  990. })
  991. it('a runtime that starts a binding call and then REJECTS still reaches quiescence before returning', async () => {
  992. const { ctx, runtime } = await setup({ mode: 'code' })
  993. const { agent, events } = fakeAgent()
  994. let sawAbort = false
  995. let started!: () => void
  996. const inFlight = new Promise<void>((resolve) => { started = resolve })
  997. ctx.tools.register(defineContentToolFixture({
  998. name: 'slow',
  999. description: 'Slow tool observing its signal.',
  1000. parameters: { id: { type: 'string', required: true } },
  1001. async execute(args, exec) {
  1002. started()
  1003. await new Promise<void>((resolve) => {
  1004. const timer = setTimeout(resolve, 500)
  1005. exec.signal.addEventListener('abort', () => { sawAbort = true; clearTimeout(timer); resolve() }, { once: true })
  1006. })
  1007. return [{ type: 'text' as const, text: args.id }]
  1008. },
  1009. }))
  1010. runtime.behavior = async (request) => {
  1011. // Start a sub-dispatch, keep its rejection held, and fail the run once the tool is
  1012. // genuinely in flight — a seam error after work has begun.
  1013. request.bindings[0]!.functions.slow!({ id: 'orphan' }).catch(() => 'held')
  1014. await inFlight
  1015. throw new Error('backend exploded')
  1016. }
  1017. const result = await runCode(ctx, 'program', { agent })
  1018. expect(result.isError).toBe(true)
  1019. expect((result.content[0] as { text: string }).text).toContain('backend exploded')
  1020. // Quiescence held: the in-flight sub-dispatch was aborted and its event
  1021. // logged INSIDE the run_code execution, not after it returned.
  1022. expect(sawAbort).toBe(true)
  1023. expect(events.filter(event => event.type === 'tool/code-dispatch').map(event => (event.data as { name: string }).name)).toEqual(['slow'])
  1024. })
  1025. it('runs without an owning agent: dispatches work, event logging is skipped', async () => {
  1026. const { ctx, runtime } = await setup({ mode: 'code' })
  1027. const calls = registerEcho(ctx)
  1028. runtime.behavior = async (request) => {
  1029. await request.bindings[0]!.functions.echo!({ value: 'x' })
  1030. return { logs: [], value: 'ok' }
  1031. }
  1032. const result = await runCode(ctx, 'program')
  1033. expect(result.isError).toBe(false)
  1034. expect(calls).toEqual([{ value: 'x' }])
  1035. })
  1036. it('executing run_code under a missing runtime is a structured isError, not a crash', async () => {
  1037. const ctx = new Context()
  1038. await ctx.plugin(SystemPrompt, {})
  1039. await ctx.plugin(ToolRegistry, { mode: 'code' })
  1040. const result = await runCode(ctx, 'program')
  1041. expect(result.isError).toBe(true)
  1042. expect((result.content[0] as { text: string }).text).toContain('requires a code runtime')
  1043. })
  1044. it('presents the model-authored description as the execute-card title over the program input', async () => {
  1045. const { ctx } = await setup({ mode: 'code' })
  1046. const tool = ctx.tools.get(RUN_CODE_NAME)!
  1047. // The description labels the card (the bash description precedent); the
  1048. // program itself remains the expanded raw input.
  1049. expect(tool.presentCall?.({ code: 'return 1', description: 'Return the constant one' })).toEqual({
  1050. card: 'generic',
  1051. title: 'Return the constant one',
  1052. kind: 'execute',
  1053. rawInput: 'return 1',
  1054. })
  1055. })
  1056. it('rejects a whitespace-only description with a structured isError', async () => {
  1057. const { ctx } = await setup({ mode: 'code' })
  1058. const result = await runCode(ctx, 'return 1', { description: ' ' })
  1059. expect(result.isError).toBe(true)
  1060. expect((result.content[0] as { text: string }).text).toContain('invalid description')
  1061. })
  1062. it.each([
  1063. ['logs only', { logs: ['printed'] }, 'printed'],
  1064. ['result only', { logs: [], value: 'returned' }, 'returned'],
  1065. ['logs plus result', { logs: ['printed'], value: 'returned' }, 'printed\nreturned'],
  1066. ['no output', { logs: [] }, '(run_code completed with no output)'],
  1067. ] as [string, CodeRunResult, string][])('keeps %s in durable content without a result presenter', async (_name, output, text) => {
  1068. const { ctx, runtime } = await setup({ mode: 'code' })
  1069. runtime.behavior = () => Promise.resolve(output)
  1070. const result = await runCode(ctx, 'return 1')
  1071. const tool = ctx.tools.get(RUN_CODE_NAME)!
  1072. expect(result.content).toEqual([{ type: 'text', text }])
  1073. // Surfaces keep the pending program title and render this durable content
  1074. // through their generic fallback. Omitting a result view also prevents the
  1075. // host frame from carrying the same raw content a second time.
  1076. expect('presentResult' in tool).toBe(false)
  1077. })
  1078. it('keeps a post-policy spill preview in durable content without a result presenter', async () => {
  1079. const { ctx, runtime } = await setup({ mode: 'code' })
  1080. const preview = 'HEAD\n\n(Omitted 100 bytes. Full formatted result stored at: /tmp/run-code.txt.)\n\nTAIL'
  1081. runtime.behavior = () => Promise.resolve({ logs: ['printed'], value: 'returned' })
  1082. ctx.on('tools/post-execute', (exec, _result, next): Promise<PostToolDecision> => {
  1083. if (exec.name !== RUN_CODE_NAME) return next()
  1084. return Promise.resolve({ kind: 'accept', content: [{ type: 'text', text: preview }] })
  1085. })
  1086. const result = await runCode(ctx, 'return 1')
  1087. const tool = ctx.tools.get(RUN_CODE_NAME)!
  1088. expect(result.content).toEqual([{ type: 'text', text: preview }])
  1089. expect('presentResult' in tool).toBe(false)
  1090. })
  1091. it('keeps canonical failure content durable without a result presenter', async () => {
  1092. const { ctx, runtime } = await setup({ mode: 'code' })
  1093. runtime.behavior = () => Promise.resolve({
  1094. logs: ['captured before failure'],
  1095. error: { kind: 'output-limit', message: 'outer output exceeded 8 bytes' },
  1096. })
  1097. const result = await runCode(ctx, 'return 1')
  1098. const tool = ctx.tools.get(RUN_CODE_NAME)!
  1099. expect(result.isError).toBe(true)
  1100. expect(result.content).toEqual([{
  1101. type: 'text',
  1102. text: 'Error: code run failed (output-limit): outer output exceeded 8 bytes\nCaptured output:\ncaptured before failure',
  1103. }])
  1104. expect('presentResult' in tool).toBe(false)
  1105. })
  1106. it('logs the complete sub-result content verbatim, non-text blocks and long text included', async () => {
  1107. const { ctx, runtime } = await setup({ mode: 'code' })
  1108. const { agent, events } = fakeAgent()
  1109. const long = 'x'.repeat(300)
  1110. ctx.tools.register(defineTool({
  1111. name: 'mixed',
  1112. description: 'Returns mixed content.',
  1113. parameters: {},
  1114. output: {
  1115. schema: { type: 'string' },
  1116. render: () => [
  1117. { type: 'text', text: long },
  1118. { type: 'reasoning', text: 'hidden' },
  1119. ],
  1120. },
  1121. execute() {
  1122. return Promise.resolve('mixed-value')
  1123. },
  1124. }))
  1125. runtime.behavior = async (request) => {
  1126. const value = await request.bindings[0]!.functions.mixed!({})
  1127. return { logs: [], value }
  1128. }
  1129. const result = await runCode(ctx, 'program', { agent })
  1130. expect(result.isError).toBe(false)
  1131. expect((result.content[0] as { text: string }).text).toBe('mixed-value')
  1132. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  1133. expect(dispatch.content).toEqual([
  1134. { type: 'text', text: long },
  1135. { type: 'reasoning', text: 'hidden' },
  1136. ])
  1137. })
  1138. it('rejects undefined, getter-throwing, exotic, and unrepresentable binding arguments before dispatch', async () => {
  1139. const { ctx, runtime } = await setup({ mode: 'code' })
  1140. const calls = registerEcho(ctx)
  1141. const { agent, events } = fakeAgent()
  1142. runtime.behavior = async (request) => {
  1143. const echo = request.bindings[0]!.functions.echo!
  1144. const catchMessage = (promise: Promise<unknown>) => promise.then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error))
  1145. return {
  1146. logs: [],
  1147. value: [
  1148. // Root undefined must reject up front: the event log rejects it as
  1149. // data, and nothing may execute unlogged.
  1150. await catchMessage(echo(undefined)),
  1151. await catchMessage(echo(Object.defineProperty({}, 'bad', { enumerable: true, get() { throw 'raw-throw' } }))),
  1152. await catchMessage(echo(Object.defineProperty({}, 'bad', { enumerable: true, get() { throw new Error('error-throw') } }))),
  1153. await catchMessage(echo(new Date(0))),
  1154. // A bare function is a value JSON cannot represent at all.
  1155. await catchMessage(echo(() => 1)),
  1156. ].join(' | '),
  1157. }
  1158. }
  1159. const result = await runCode(ctx, 'program', { agent })
  1160. const text = (result.content[0] as { text: string }).text
  1161. expect(text).toContain('call the tool with an arguments object')
  1162. expect(text).toContain('lossless JSON: raw-throw')
  1163. expect(text).toContain('lossless JSON: error-throw')
  1164. expect(text.match(/tool arguments must be lossless JSON/g)).toHaveLength(5)
  1165. // None dispatched or logged.
  1166. expect(calls).toEqual([])
  1167. expect(events.filter(event => event.type === 'tool/code-dispatch')).toEqual([])
  1168. })
  1169. it('dispatches and durably logs binding arguments deeper than the structured-clone call stack', async () => {
  1170. const { ctx, runtime } = await setup({ mode: 'code' })
  1171. const depth = 5_000
  1172. let observedDepth = 0
  1173. let observedLeaf: JsonValue | undefined
  1174. ctx.tools.register(defineTool({
  1175. name: 'deep_args',
  1176. description: 'Measure a deeply nested JSON argument.',
  1177. parameters: { nested: { type: 'json', required: true } },
  1178. output: {
  1179. schema: { type: 'integer' },
  1180. render: (_args, value) => [{ type: 'text', text: String(value) }],
  1181. },
  1182. execute(args) {
  1183. let cursor = args.nested
  1184. while (Array.isArray(cursor)) {
  1185. if (cursor.length !== 1) throw new Error('expected one item per nesting layer')
  1186. observedDepth++
  1187. cursor = cursor[0]!
  1188. }
  1189. observedLeaf = cursor
  1190. return Promise.resolve(observedDepth)
  1191. },
  1192. }))
  1193. const session = new Session(SessionId('deep-code-arguments'))
  1194. const agent = { session } as Agent
  1195. runtime.behavior = async (request) => {
  1196. let nested: JsonValue = 'leaf'
  1197. for (let index = 0; index < depth; index++) nested = [nested]
  1198. const value = await request.bindings[0]!.functions.deep_args!({ nested })
  1199. return { logs: [], value }
  1200. }
  1201. const result = await runCode(ctx, 'return tools.deep_args(...)', { agent })
  1202. expect(result.isError).toBe(false)
  1203. expect(result.isError ? undefined : result.value).toEqual({ logs: [], result: depth })
  1204. expect({ observedDepth, observedLeaf }).toEqual({ observedDepth: depth, observedLeaf: 'leaf' })
  1205. const dispatch = session.events.find(event => event.type === 'tool/code-dispatch')
  1206. if (dispatch === undefined) throw new Error('expected a durable tool/code-dispatch event')
  1207. const logged = dispatch.data.arguments as { nested: JsonValue }
  1208. let loggedDepth = 0
  1209. let loggedCursor = logged.nested
  1210. while (Array.isArray(loggedCursor)) {
  1211. if (loggedCursor.length !== 1) throw new Error('expected one logged item per nesting layer')
  1212. loggedDepth++
  1213. loggedCursor = loggedCursor[0]!
  1214. }
  1215. expect({ loggedDepth, loggedCursor }).toEqual({ loggedDepth: depth, loggedCursor: 'leaf' })
  1216. })
  1217. it('gives the tool and durable log the same immutable argument value', async () => {
  1218. const { ctx, runtime } = await setup({ mode: 'code' })
  1219. const { agent, events } = fakeAgent()
  1220. let mutationSucceeded: boolean | undefined
  1221. ctx.tools.register(defineContentToolFixture({
  1222. name: 'mutator',
  1223. description: 'Attempts to mutate its args object.',
  1224. parameters: { list: { type: 'array', required: true } },
  1225. execute(args) {
  1226. mutationSucceeded = Reflect.set(args.list, 1, 'injected-by-tool')
  1227. return Promise.resolve([{ type: 'text' as const, text: 'protected' }])
  1228. },
  1229. }))
  1230. runtime.behavior = async (request) => {
  1231. await request.bindings[0]!.functions.mutator!({ list: ['original'] })
  1232. return { logs: [] }
  1233. }
  1234. const result = await runCode(ctx, 'program', { agent })
  1235. expect(result.isError).toBe(false)
  1236. expect(mutationSucceeded).toBe(false)
  1237. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  1238. expect(dispatch.arguments).toEqual({ list: ['original'] })
  1239. })
  1240. it('exposes a tool named __proto__ as an ordinary own binding', async () => {
  1241. const { ctx, runtime } = await setup({ mode: 'code' })
  1242. ctx.tools.register(defineTool({
  1243. name: '__proto__',
  1244. description: 'A prototype-colliding tool name.',
  1245. parameters: {},
  1246. output: {
  1247. schema: { type: 'string' },
  1248. render: (_args, value) => [{ type: 'text', text: value }],
  1249. },
  1250. execute() { return Promise.resolve('proto-tool-ok') },
  1251. }))
  1252. runtime.behavior = async (request) => {
  1253. const functions = request.bindings[0]!.functions
  1254. expect(Object.getPrototypeOf(functions)).toBeNull()
  1255. const value = await functions['__proto__']!({})
  1256. return { logs: [], value }
  1257. }
  1258. const result = await runCode(ctx, 'program')
  1259. expect(result.isError).toBe(false)
  1260. expect(result.content[0]).toEqual({ type: 'text', text: 'proto-tool-ok' })
  1261. })
  1262. it('renders every non-string JSON root as pretty JSON while preserving strings raw', async () => {
  1263. const { ctx, runtime } = await setup({ mode: 'code' })
  1264. runtime.behavior = () => Promise.resolve({ logs: [], value: { n: 42, ok: true } })
  1265. expect((await runCode(ctx, 'object')).content[0]).toEqual({ type: 'text', text: '{\n "n": 42,\n "ok": true\n}' })
  1266. runtime.behavior = () => Promise.resolve({ logs: [], value: {} })
  1267. expect((await runCode(ctx, 'empty object')).content[0]).toEqual({ type: 'text', text: '{}' })
  1268. const nested = { outer: [{ inner: true }] }
  1269. runtime.behavior = () => Promise.resolve({ logs: [], value: nested })
  1270. expect((await runCode(ctx, 'nested')).content[0]).toEqual({ type: 'text', text: JSON.stringify(nested, null, 2) })
  1271. runtime.behavior = () => Promise.resolve({ logs: [], value: ['x', 2] })
  1272. expect((await runCode(ctx, 'array')).content[0]).toEqual({ type: 'text', text: '[\n "x",\n 2\n]' })
  1273. runtime.behavior = () => Promise.resolve({ logs: [], value: [] })
  1274. expect((await runCode(ctx, 'empty array')).content[0]).toEqual({ type: 'text', text: '[]' })
  1275. runtime.behavior = () => Promise.resolve({ logs: [], value: null })
  1276. expect((await runCode(ctx, 'null')).content[0]).toEqual({ type: 'text', text: 'null' })
  1277. runtime.behavior = () => Promise.resolve({ logs: [], value: 'raw' })
  1278. expect((await runCode(ctx, 'string')).content[0]).toEqual({ type: 'text', text: 'raw' })
  1279. runtime.behavior = () => Promise.resolve({ logs: [] })
  1280. const absent = await runCode(ctx, 'undefined')
  1281. expect(absent.content[0]).toEqual({ type: 'text', text: '(run_code completed with no output)' })
  1282. expect(absent.isError ? undefined : absent.value).toEqual({ logs: [] })
  1283. })
  1284. it('renders deeply nested JSON without recursive traversal or quadratic indentation', async () => {
  1285. const { ctx, runtime } = await setup({ mode: 'code' })
  1286. let value: JsonValue = {
  1287. emptyArray: [],
  1288. emptyObject: {},
  1289. pair: ['leaf', 2],
  1290. record: { first: true, second: null },
  1291. }
  1292. for (let depth = 0; depth < 5_000; depth++) value = [value]
  1293. runtime.behavior = () => Promise.resolve({ logs: [], value })
  1294. const result = await runCode(ctx, 'deep result')
  1295. expect(result.isError).toBe(false)
  1296. const text = (result.content[0] as { type: 'text'; text: string }).text
  1297. expect(text.startsWith('[\n [\n [')).toBe(true)
  1298. expect(text).toContain('"leaf"')
  1299. expect(text.endsWith(']')).toBe(true)
  1300. expect(text.length).toBeLessThan(11_000)
  1301. })
  1302. it('short-circuits a pre-aborted outer signal before the code runtime', async () => {
  1303. const { ctx, runtime } = await setup({ mode: 'code' })
  1304. const calls = registerEcho(ctx)
  1305. runtime.behavior = (request) => {
  1306. // The fake honors the seam contract for an already-aborted signal.
  1307. if (request.signal?.aborted) return Promise.resolve({ logs: [], error: { kind: 'abort' as const, message: String(request.signal.reason) } })
  1308. return Promise.resolve({ logs: [], value: 'unreachable' })
  1309. }
  1310. const controller = new AbortController()
  1311. controller.abort('too-late')
  1312. const result = await runCode(ctx, 'program', { signal: controller.signal })
  1313. expect(result.isError).toBe(true)
  1314. expect(result).toEqual({
  1315. content: [{ type: 'text', text: 'Error: tool call aborted before dispatch' }],
  1316. isError: true,
  1317. error: {
  1318. message: 'tool call aborted before dispatch',
  1319. info: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH },
  1320. },
  1321. })
  1322. expect(runtime.lastRequest).toBeUndefined()
  1323. expect(calls).toEqual([])
  1324. })
  1325. it('reports cancellation after rejecting a late binding without dispatching it', async () => {
  1326. const { ctx, runtime } = await setup({ mode: 'code' })
  1327. const calls = registerEcho(ctx)
  1328. const controller = new AbortController()
  1329. runtime.behavior = async (request) => {
  1330. controller.abort('cancelled-mid-run')
  1331. const message = await request.bindings[0]!.functions.echo!({ value: 'x' })
  1332. .then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error))
  1333. return { logs: [], value: message }
  1334. }
  1335. const result = await runCode(ctx, 'program', { signal: controller.signal })
  1336. expect(result.isError).toBe(true)
  1337. expect(result.error).toEqual({
  1338. message: 'tool call aborted',
  1339. info: { name: 'AbortError', code: 'ABORTED' },
  1340. })
  1341. expect((result.content[0] as { text: string }).text).toBe('Error: tool call aborted')
  1342. expect(calls).toEqual([])
  1343. })
  1344. it('a tool/code-dispatch event never derives a model message', () => {
  1345. const session = new Session(SessionId('code-mode-derive'))
  1346. session.append('user/message', { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  1347. session.append('tool/code-dispatch', {
  1348. parentCallId: CallId('p1'),
  1349. subCallId: CallId('p1:code:1'),
  1350. name: 'echo',
  1351. arguments: { value: 'x' },
  1352. isError: false,
  1353. content: [{ type: 'text', text: 'echo:x' }],
  1354. })
  1355. const derived = session.deriveMessages()
  1356. expect(derived).toHaveLength(1)
  1357. expect(derived[0]?.role).toBe('user')
  1358. })
  1359. it('direct construction rejects a non-positive parallel sub-call cap at load', async () => {
  1360. const ctx = new Context()
  1361. await ctx.plugin(SystemPrompt, {})
  1362. expect(() => new ToolRegistry(ctx, { mode: 'code', maxParallelSubCalls: 0 }))
  1363. .toThrow('maxParallelSubCalls must be a positive integer')
  1364. })
  1365. it('direct construction in code mode defaults the parallel sub-call cap', async () => {
  1366. const ctx = new Context()
  1367. await ctx.plugin(SystemPrompt, {})
  1368. const registry = new ToolRegistry(ctx, { mode: 'code' })
  1369. expect(registry.get(RUN_CODE_NAME)).toBeDefined()
  1370. })
  1371. it('defaults to native mode under direct construction with no config', async () => {
  1372. const ctx = new Context()
  1373. await ctx.plugin(SystemPrompt, {})
  1374. const registry = new ToolRegistry(ctx)
  1375. expect(registry.get(RUN_CODE_NAME)).toBeUndefined()
  1376. const assembly = await ctx.systemPrompt.assemble()
  1377. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  1378. })
  1379. })