code-mode.spec.ts 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from '@deepseek-ai/cordis'
  3. import { createUserMessage, 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 ToolRuntime, { 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. * Service Definition / Service provider / Consumer roles 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(ToolRuntime, { 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 an agent scope configured like production 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("mode 'code' states the run_code-only rule BEFORE the per-tool guidance that names each tool", async () => {
  125. const { ctx, systemPrompt } = await setup({ mode: 'code' })
  126. registerEcho(ctx)
  127. // Stand in for a real tool's guidance section, which sits in the 100-199
  128. // band and names its tool without saying how it is reached.
  129. ctx.systemPrompt.section({ name: 'tool:echo', order: 100, text: 'Use the echo tool.' })
  130. const assembly = await systemPrompt.assemble()
  131. const names = assembly.sections.map(section => section.name)
  132. const rule = assembly.sections.find(section => section.name === 'tools:code-only')
  133. expect(rule?.text).toContain(`\`${RUN_CODE_NAME}\` is the only tool you can call directly`)
  134. // The rule is worthless after the guidance it qualifies.
  135. expect(names.indexOf('tools:code-only')).toBeLessThan(names.indexOf('tool:echo'))
  136. expect(names.indexOf('tools:code-only')).toBeLessThan(names.indexOf('tools:sdk'))
  137. })
  138. it("mode 'both' omits the run_code-only rule, because native calls do execute there", async () => {
  139. const { ctx, systemPrompt } = await setup({ mode: 'both' })
  140. registerEcho(ctx)
  141. const assembly = await systemPrompt.assemble()
  142. // Registered (the deployment is non-native) but empty, so the renderer
  143. // drops it: `both` executes the native call the rule would forbid.
  144. expect(assembly.sections.find(section => section.name === 'tools:code-only')?.text).toBe('')
  145. expect(assembly.tools.map(tool => tool.name)).toContain('echo')
  146. })
  147. it('projects deeply nested output schemas into the Code Mode SDK without structured-clone recursion', async () => {
  148. const { ctx, systemPrompt } = await setup({ mode: 'code' })
  149. let output: JsonSchemaNode = { type: 'string' }
  150. for (let depth = 0; depth < 5_000; depth++) {
  151. output = { oneOf: [output, { type: 'null' }] }
  152. }
  153. ctx.tools.register({
  154. name: 'deep_output',
  155. description: 'Return a deeply nested output union.',
  156. parameters: { type: 'object', properties: {} },
  157. output: {
  158. schema: output,
  159. render: (_args, value) => [{ type: 'text', text: typeof value === 'string' ? value : 'null' }],
  160. },
  161. execute() { return Promise.resolve('ok') },
  162. })
  163. const assembly = await systemPrompt.assemble()
  164. const sdk = assembly.sections.find(section => section.name === 'tools:sdk')?.text
  165. expect(sdk).toContain('deep_output: Record<string, JsonValue>;')
  166. expect(sdk).toContain('deep_output: string | null')
  167. })
  168. it.each(['code', 'both'] as const)('treats expert assembly output as authoritative in mode %s', async (mode) => {
  169. const { ctx, systemPrompt } = await setup({ mode })
  170. registerEcho(ctx)
  171. ctx.on('system-prompt/assemble', async (_assembly, _context, next) => {
  172. const assembly = await next()
  173. return {
  174. ...assembly,
  175. sections: assembly.sections.filter(section => section.name !== 'tools:sdk'),
  176. tools: assembly.tools.filter(tool => tool.name !== RUN_CODE_NAME),
  177. }
  178. }, { prepend: true })
  179. const assembly = await systemPrompt.assemble()
  180. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  181. expect(assembly.tools.some(tool => tool.name === RUN_CODE_NAME)).toBe(false)
  182. })
  183. it.each(['code', 'both'] as const)('lets one scope shadow the default SDK section in mode %s', async (mode) => {
  184. const { ctx, systemPrompt } = await setup({ mode })
  185. registerEcho(ctx)
  186. const { scope, agent } = await mintAgentScope(ctx)
  187. scope.ctx.systemPrompt.section({ name: 'tools:sdk', order: 150, text: 'SCOPED SDK' })
  188. const scoped = await systemPrompt.assemble({ scope: agent })
  189. const global = await systemPrompt.assemble()
  190. expect(scoped.sections.find(section => section.name === 'tools:sdk')?.text).toBe('SCOPED SDK')
  191. expect(global.sections.find(section => section.name === 'tools:sdk')?.text).toContain('declare const tools:')
  192. })
  193. it("mode 'both' contributes every native schema plus run_code, and the SDK section", async () => {
  194. const { ctx, systemPrompt } = await setup({ mode: 'both' })
  195. registerEcho(ctx)
  196. const assembly = await systemPrompt.assemble()
  197. expect(assembly.tools.map(tool => tool.name)).toEqual(['echo', RUN_CODE_NAME])
  198. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(true)
  199. })
  200. it.each(['code', 'both'] as const)('keeps the run_code transport outside scoped allow-list filtering in mode %s', async (mode) => {
  201. const { ctx, systemPrompt, runtime } = await setup({ mode })
  202. registerEcho(ctx, 'echo')
  203. registerEcho(ctx, 'hidden')
  204. const { scope, agent } = await mintAgentScope(ctx)
  205. const lift = scope.ctx.tools.restrict({ allow: ['echo'] })
  206. const assembly = await systemPrompt.assemble({ scope: agent })
  207. expect(assembly.tools.map(tool => tool.name)).toEqual(mode === 'code'
  208. ? [RUN_CODE_NAME]
  209. : ['echo', RUN_CODE_NAME])
  210. const sdk = assembly.sections.find(section => section.name === 'tools:sdk')?.text
  211. expect(sdk).toContain('echo: {')
  212. expect(sdk).not.toContain('hidden:')
  213. runtime.behavior = request => Promise.resolve({
  214. logs: [],
  215. value: Object.keys(request.bindings[0]!.functions).sort().join(','),
  216. })
  217. const result = await runCode(ctx, 'return Object.keys(tools)', { agent })
  218. expect(result.isError).toBe(false)
  219. expect(result.content).toEqual([{ type: 'text', text: 'echo' }])
  220. lift()
  221. const unrestricted = await systemPrompt.assemble({ scope: agent })
  222. expect(unrestricted.tools.map(tool => tool.name)).toEqual(mode === 'code'
  223. ? [RUN_CODE_NAME]
  224. : ['echo', 'hidden', RUN_CODE_NAME])
  225. })
  226. it.each(['code', 'both'] as const)('keeps the run_code transport outside scoped deny-list filtering in mode %s', async (mode) => {
  227. const { ctx, systemPrompt, runtime } = await setup({ mode })
  228. registerEcho(ctx, 'denied')
  229. registerEcho(ctx, 'kept')
  230. const { scope, agent } = await mintAgentScope(ctx)
  231. scope.ctx.tools.restrict({ deny: ['denied'] })
  232. const assembly = await systemPrompt.assemble({ scope: agent })
  233. expect(assembly.tools.map(tool => tool.name)).toEqual(mode === 'code'
  234. ? [RUN_CODE_NAME]
  235. : ['kept', RUN_CODE_NAME])
  236. const sdk = assembly.sections.find(section => section.name === 'tools:sdk')?.text
  237. expect(sdk).not.toContain('denied:')
  238. expect(sdk).toContain('kept: {')
  239. runtime.behavior = request => Promise.resolve({
  240. logs: [],
  241. value: Object.keys(request.bindings[0]!.functions).sort().join(','),
  242. })
  243. const result = await runCode(ctx, 'return Object.keys(tools)', { agent })
  244. expect(result.isError).toBe(false)
  245. expect(result.content).toEqual([{ type: 'text', text: 'kept' }])
  246. })
  247. it.each(['code', 'both'] as const)('reserves run_code against scoped shadows and explicit restrictions in mode %s', async (mode) => {
  248. const { ctx, systemPrompt } = await setup({ mode })
  249. const { scope, agent } = await mintAgentScope(ctx)
  250. const impostor = defineContentToolFixture({
  251. name: RUN_CODE_NAME,
  252. description: 'Scoped impostor.',
  253. parameters: {},
  254. execute: () => Promise.resolve([{ type: 'text' as const, text: 'impostor' }]),
  255. })
  256. expect(() => scope.ctx.tools.register(impostor)).toThrow(/reserved for the Code Mode presentation transport/)
  257. expect(() => ctx.tools.register(impostor)).toThrow(/reserved for the Code Mode presentation transport/)
  258. expect(() => scope.ctx.tools.restrict({ allow: [RUN_CODE_NAME] })).toThrow(/cannot name reserved Code Mode presentation transport/)
  259. expect(() => scope.ctx.tools.restrict({ deny: [RUN_CODE_NAME] })).toThrow(/cannot name reserved Code Mode presentation transport/)
  260. scope.ctx.systemPrompt.section({ name: 'scoped-note', order: 149, text: 'safe note' })
  261. scope.ctx.tools.register(defineContentToolFixture({
  262. name: 'scoped_safe',
  263. description: 'Safe scoped tool.',
  264. parameters: {},
  265. execute: () => Promise.resolve([{ type: 'text' as const, text: 'safe' }]),
  266. }))
  267. const assembly = await systemPrompt.assemble({ scope: agent })
  268. const transports = assembly.tools.filter(tool => tool.name === RUN_CODE_NAME)
  269. expect(transports).toHaveLength(1)
  270. expect(transports[0]?.description).toContain('Execute a TypeScript program')
  271. expect(assembly.sections.find(section => section.name === 'scoped-note')?.text).toBe('safe note')
  272. expect(assembly.sections.find(section => section.name === 'tools:sdk')?.text).toContain('scoped_safe:')
  273. expect(ctx.tools.get(RUN_CODE_NAME, agent)).toBe(ctx.tools.get(RUN_CODE_NAME))
  274. const result = await runCode(ctx, 'return 1', { agent })
  275. expect(result.content).toEqual([{ type: 'text', text: '(run_code completed with no output)' }])
  276. })
  277. 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) => {
  278. const { ctx, systemPrompt } = await setup({
  279. mode,
  280. toolOrder: [RUN_CODE_NAME, '<unlisted-tools>'],
  281. })
  282. registerEcho(ctx)
  283. const { agent } = await mintAgentScope(ctx)
  284. const assembly = await systemPrompt.assemble({ scope: agent })
  285. expect(assembly.tools.map(tool => tool.name)).toEqual(mode === 'code'
  286. ? [RUN_CODE_NAME]
  287. : [RUN_CODE_NAME, 'echo'])
  288. })
  289. it("never exposes run_code to programs, even under mode 'both' (no recursive dispatch path)", async () => {
  290. const { ctx, runtime } = await setup({ mode: 'both' })
  291. registerEcho(ctx)
  292. runtime.behavior = (request) => {
  293. expect(request.bindings[0]!.errorClass).toEqual({
  294. name: 'ToolCallError',
  295. memberNameProperty: 'toolName',
  296. })
  297. const functions = request.bindings[0]!.functions
  298. return Promise.resolve({
  299. logs: [],
  300. value: JSON.stringify({
  301. names: Object.keys(functions).sort(),
  302. // Own-property AND prototype-chain reads both come back empty —
  303. // there is no handle a program could re-enter run_code through.
  304. runCode: String(functions[RUN_CODE_NAME]),
  305. }),
  306. })
  307. }
  308. const result = await runCode(ctx, 'program')
  309. expect(result.isError).toBe(false)
  310. expect(JSON.parse((result.content[0] as { text: string }).text)).toEqual({ names: ['echo'], runCode: 'undefined' })
  311. })
  312. it('renders byte-identical SDK text across consecutive assemblies of an unchanged tool set', async () => {
  313. const { ctx, systemPrompt } = await setup({ mode: 'code' })
  314. registerEcho(ctx)
  315. const first = await systemPrompt.assemble()
  316. const second = await systemPrompt.assemble()
  317. const text = (assembly: typeof first) => assembly.sections.find(section => section.name === 'tools:sdk')?.text
  318. expect(text(first)).toBe(text(second))
  319. })
  320. it('rejects every assembly when a non-native mode has no code runtime', async () => {
  321. const { systemPrompt } = await setup({ mode: 'code', runtime: false })
  322. await expect(systemPrompt.assemble()).rejects.toThrow(/requires a code runtime/)
  323. })
  324. it('rejects every assembly when the runtime language has no registered SDK renderer', async () => {
  325. const { systemPrompt } = await setup({ mode: 'code', runtime: { language: 'ruby' } })
  326. await expect(systemPrompt.assemble()).rejects.toThrow(/no SDK renderer registered for runtime language "ruby"/)
  327. })
  328. it('assembles under a python runtime by picking the Python SDK renderer', async () => {
  329. const { ctx, systemPrompt } = await setup({ mode: 'code', runtime: { language: 'python' } })
  330. registerEcho(ctx)
  331. const assembly = await systemPrompt.assemble()
  332. const sdk = assembly.sections.find(section => section.name === 'tools:sdk')
  333. expect(sdk?.text).toContain('class Tools(Protocol):')
  334. expect(sdk?.text).toContain('async def echo(self, args:')
  335. expect(sdk?.text).toContain('top-level `await`')
  336. })
  337. it("assembles under a python runtime in mode 'both' as well, SDK and schema together", async () => {
  338. // `both` reaches the same wireSchemas/requireCodeRuntime/SDK-section code
  339. // as `code`, so this pins the mode-by-language matrix rather than a
  340. // separate path — including that the `wireSchemas` projection behind
  341. // `assembly.tools` picks the Python flavor under `both` instead of hitting
  342. // the flavor-table guard.
  343. const { ctx, systemPrompt } = await setup({ mode: 'both', runtime: { language: 'python' } })
  344. registerEcho(ctx)
  345. const assembly = await systemPrompt.assemble()
  346. expect(assembly.sections.find(section => section.name === 'tools:sdk')?.text).toContain('class Tools(Protocol):')
  347. const runCodeSchema = assembly.tools.find(tool => tool.name === RUN_CODE_NAME)
  348. expect(runCodeSchema?.description).toContain('Execute a Python program')
  349. // `both` keeps the native tools alongside run_code; `code` does not.
  350. expect(assembly.tools.map(tool => tool.name)).toContain('echo')
  351. })
  352. it('emits a TypeScript-flavored run_code schema under a typescript runtime', async () => {
  353. const { ctx, systemPrompt } = await setup({ mode: 'code', runtime: { language: 'typescript' } })
  354. registerEcho(ctx)
  355. const assembly = await systemPrompt.assemble()
  356. const runCodeSchema = assembly.tools.find(tool => tool.name === RUN_CODE_NAME)
  357. expect(runCodeSchema?.description).toContain('Execute a TypeScript program')
  358. expect(runCodeSchema?.description).toContain('BODY of an')
  359. const codeParam = (runCodeSchema?.parameters as { properties: { code: { description: string } } }).properties.code
  360. expect(codeParam.description).toBe('The program: the body of an async TypeScript function.')
  361. })
  362. it('emits a Python-flavored run_code schema under a python runtime (matches the SDK language)', async () => {
  363. const { ctx, systemPrompt } = await setup({ mode: 'code', runtime: { language: 'python' } })
  364. registerEcho(ctx)
  365. const assembly = await systemPrompt.assemble()
  366. const runCodeSchema = assembly.tools.find(tool => tool.name === RUN_CODE_NAME)
  367. expect(runCodeSchema?.description).toContain('Execute a Python program')
  368. expect(runCodeSchema?.description).toContain('`return <value>`')
  369. expect(runCodeSchema?.description).not.toContain('TypeScript')
  370. const codeParam = (runCodeSchema?.parameters as { properties: { code: { description: string } } }).properties.code
  371. expect(codeParam.description).toBe('The program: the body of an async Python function.')
  372. })
  373. it('resolves the run_code schema flavor lazily and fails loud on a language absent from the flavor table', async () => {
  374. // The flavor getter reads the runtime directly (peekRuntime), so it — not
  375. // requireCodeRuntime — owns the flavor-table guard. Keeping
  376. // RUN_CODE_FLAVORS in step with SDK_RENDERERS is the compiler's job (both
  377. // are `satisfies`-checked against CodeSdkLanguage), so what the guard
  378. // covers is a mounted runtime naming a language absent from both tables,
  379. // which throws when the schema is projected. Assembly's
  380. // requireCodeRuntime rejects such a language earlier; this reaches the
  381. // guard on its own.
  382. const { ctx } = await setup({ mode: 'code', runtime: { language: 'ruby' } })
  383. const definition = ctx.tools.get(RUN_CODE_NAME)
  384. // Names the known languages, symmetric with the SDK_RENDERERS guard: this
  385. // is the reachable rejection, so it must be at least as diagnosable.
  386. expect(() => definition?.description)
  387. .toThrow(/no run_code schema flavor registered for runtime language "ruby" \(known: "typescript", "python"\)/)
  388. })
  389. it('degrades the run_code flavor to TypeScript when no runtime is mounted', async () => {
  390. // Any reader of the definition without a mounted runtime uses this fallback; the
  391. // shipped one is the tool-catalog generator, which boots the registry under
  392. // `mode: code` and reads run_code's schema WITHOUT a runtime. peekRuntime
  393. // returns undefined there, so the flavor getter degrades to the TS default
  394. // rather than throwing. None of those readers feeds a model: assembly goes
  395. // through wireSchemas, which requires a runtime first.
  396. const { ctx } = await setup({ mode: 'code', runtime: false })
  397. const definition = ctx.tools.get(RUN_CODE_NAME)
  398. expect(definition?.description).toContain('Execute a TypeScript program')
  399. const params = definition?.parameters as { properties: { code: { description: string } } }
  400. expect(params.properties.code.description).toBe('The program: the body of an async TypeScript function.')
  401. })
  402. it("rejects the assembly when toolOrder names a native tool that mode 'code' no longer contributes", async () => {
  403. const { ctx, systemPrompt } = await setup({ mode: 'code', toolOrder: ['echo', '<unlisted-tools>'] })
  404. registerEcho(ctx)
  405. await expect(systemPrompt.assemble()).rejects.toThrow(/toolOrder lists unregistered tool "echo"/)
  406. })
  407. it('removes run_code and the SDK section when the registry fiber disposes (HMR safety)', async () => {
  408. const ctx = new Context()
  409. await ctx.plugin(SystemPrompt, {})
  410. await ctx.plugin(FakeRuntime, {})
  411. const fiber = await ctx.plugin(ToolRuntime, { mode: 'code' })
  412. expect(ctx.tools.get(RUN_CODE_NAME)).toBeDefined()
  413. await fiber.dispose()
  414. const assembly = await ctx.systemPrompt.assemble()
  415. expect(assembly.tools).toEqual([])
  416. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  417. })
  418. })
  419. describe('the sub-dispatch scheduler (native concurrency contract)', () => {
  420. /** Register a tool whose calls resolve only when the test releases them; returns live-call telemetry. */
  421. function registerGated(ctx: Context, name: string, concurrencySafe: boolean) {
  422. const gates: (() => void)[] = []
  423. let live = 0
  424. let peak = 0
  425. const order: string[] = []
  426. ctx.tools.register(defineTool({
  427. name,
  428. description: `Gated tool ${name}.`,
  429. parameters: { id: { type: 'string', required: true } },
  430. output: {
  431. schema: { type: 'string' },
  432. render: (_args, value) => [{ type: 'text', text: value }],
  433. },
  434. ...concurrencySafe ? { isConcurrencySafe: () => true } : {},
  435. async execute(args, exec) {
  436. order.push(`start:${args.id}`)
  437. live++
  438. peak = Math.max(peak, live)
  439. // Abort-observing like a real tool: the run-scoped abort releases the
  440. // gate so the bridge's drain reaches quiescence.
  441. await new Promise<void>((release) => {
  442. gates.push(release)
  443. exec.signal.addEventListener('abort', () => { release() }, { once: true })
  444. })
  445. live--
  446. order.push(`end:${args.id}`)
  447. return `${name}:${args.id}`
  448. },
  449. }))
  450. const release = (): void => { gates.shift()?.() }
  451. const releaseAll = (): void => { while (gates.length > 0) gates.shift()!() }
  452. return { order, release, releaseAll, peakLive: () => peak, pending: () => gates.length }
  453. }
  454. it('overlaps concurrency-safe calls under Promise.all and logs a start event per dispatch', async () => {
  455. const { ctx, runtime } = await setup({ mode: 'code' })
  456. const gated = registerGated(ctx, 'safe_read', true)
  457. const { agent, events } = fakeAgent()
  458. runtime.behavior = async (request) => {
  459. const tools = request.bindings[0]!.functions
  460. const all = Promise.all([
  461. tools.safe_read!({ id: 'a' }),
  462. tools.safe_read!({ id: 'b' }),
  463. tools.safe_read!({ id: 'c' }),
  464. ])
  465. // All three must be START-able without any completion (overlap proof).
  466. await expect.poll(() => gated.pending()).toBe(3)
  467. gated.releaseAll()
  468. return { logs: [], value: (await all).map(String).join(',') }
  469. }
  470. const result = await runCode(ctx, 'program', { agent })
  471. expect(result.isError).toBe(false)
  472. expect(gated.peakLive()).toBe(3)
  473. if (result.isError) throw new Error('expected success')
  474. expect(result.value).toMatchObject({ result: 'safe_read:a,safe_read:b,safe_read:c' })
  475. // One start per dispatch, paired with its settle by subCallId, starts in submission order.
  476. const starts = events.filter(event => event.type === 'tool/code-dispatch-start').map(event => event.data as { subCallId: string })
  477. const settles = events.filter(event => event.type === 'tool/code-dispatch').map(event => event.data as { subCallId: string })
  478. expect(starts.map(start => start.subCallId)).toEqual(['call-1:code:1', 'call-1:code:2', 'call-1:code:3'])
  479. expect(new Set(settles.map(settle => settle.subCallId))).toEqual(new Set(starts.map(start => start.subCallId)))
  480. })
  481. it('an exclusive call bars overlap: safe calls drain first, it runs alone, later calls wait', async () => {
  482. const { ctx, runtime } = await setup({ mode: 'code' })
  483. const safe = registerGated(ctx, 'safe_read', true)
  484. const unsafe = registerGated(ctx, 'writer', false)
  485. runtime.behavior = async (request) => {
  486. const tools = request.bindings[0]!.functions
  487. const reads = [tools.safe_read!({ id: 'r1' }), tools.safe_read!({ id: 'r2' })]
  488. const write = tools.writer!({ id: 'w' })
  489. const tail = tools.safe_read!({ id: 'r3' })
  490. await expect.poll(() => safe.pending()).toBe(2)
  491. // The exclusive call must NOT have started while the pool is live.
  492. expect(unsafe.pending()).toBe(0)
  493. safe.releaseAll()
  494. await expect.poll(() => unsafe.pending()).toBe(1)
  495. // The trailing safe call must NOT start while the exclusive one runs.
  496. expect(safe.pending()).toBe(0)
  497. unsafe.release()
  498. await expect.poll(() => safe.pending()).toBe(1)
  499. safe.releaseAll()
  500. await Promise.all([...reads, write, tail])
  501. return { logs: [], value: 'ordered' }
  502. }
  503. const result = await runCode(ctx, 'program')
  504. expect(result.isError).toBe(false)
  505. expect(safe.order.slice(0, 2)).toEqual(['start:r1', 'start:r2'])
  506. expect(unsafe.order).toEqual(['start:w', 'end:w'])
  507. // r3 started only after w ended.
  508. expect(safe.order.indexOf('start:r3')).toBeGreaterThan(safe.order.indexOf('end:r1'))
  509. })
  510. it('maxParallelSubCalls caps the overlap window', async () => {
  511. const { ctx, runtime } = await setup({ mode: 'code', maxParallelSubCalls: 2 })
  512. const gated = registerGated(ctx, 'safe_read', true)
  513. runtime.behavior = async (request) => {
  514. const tools = request.bindings[0]!.functions
  515. const all = Promise.all([
  516. tools.safe_read!({ id: 'a' }),
  517. tools.safe_read!({ id: 'b' }),
  518. tools.safe_read!({ id: 'c' }),
  519. ])
  520. await expect.poll(() => gated.pending()).toBe(2)
  521. // The third call waits for a slot.
  522. expect(gated.pending()).toBe(2)
  523. gated.release()
  524. await expect.poll(() => gated.pending()).toBe(2)
  525. gated.releaseAll()
  526. await all
  527. return { logs: [], value: 'capped' }
  528. }
  529. const result = await runCode(ctx, 'program')
  530. if (result.isError) console.error('CAP-FAIL:', (result.content[0] as { text: string }).text)
  531. expect(result.isError).toBe(false)
  532. expect(gated.peakLive()).toBe(2)
  533. })
  534. it('a tool unregistered between binding enumeration and dispatch fails as unknown tool', async () => {
  535. const { ctx, runtime } = await setup({ mode: 'code' })
  536. const calls: unknown[] = []
  537. const dispose = ctx.tools.register(defineTool({
  538. name: 'ephemeral',
  539. description: 'Unregistered between binding enumeration and dispatch.',
  540. parameters: {},
  541. output: {
  542. schema: { type: 'string' },
  543. render: (_args, value) => [{ type: 'text', text: value }],
  544. },
  545. execute() {
  546. calls.push('ran')
  547. return Promise.resolve('ok')
  548. },
  549. }))
  550. runtime.behavior = async (request) => {
  551. // The binding exists (enumerated at run start); the registry mutation
  552. // makes prepare resolve UNKNOWN_TOOL as a final-result, which commits
  553. // through scheduler.finish (no post-execute).
  554. dispose()
  555. const message = await request.bindings[0]!.functions.ephemeral!({})
  556. .then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error))
  557. return { logs: [], value: message }
  558. }
  559. const result = await runCode(ctx, 'program')
  560. expect(result.isError).toBe(false)
  561. if (result.isError) throw new Error('expected success')
  562. expect(result.value).toMatchObject({ result: 'unknown tool "ephemeral"' })
  563. expect(calls).toEqual([])
  564. })
  565. it('ordered pre-execute never overlaps: a slow policy on one call delays the next start', async () => {
  566. const { ctx, runtime } = await setup({ mode: 'code' })
  567. const gated = registerGated(ctx, 'safe_read', true)
  568. const stages: string[] = []
  569. let releaseGate: (() => void) | undefined
  570. ctx.on('tools/pre-execute', async (preExec, next) => {
  571. if (preExec.name !== 'safe_read') return next()
  572. stages.push(`pre-enter:${String(preExec.callId)}`)
  573. if (releaseGate === undefined) {
  574. // The FIRST call's policy awaits an asynchronous decision.
  575. await new Promise<void>((resolve) => { releaseGate = resolve })
  576. }
  577. stages.push(`pre-exit:${String(preExec.callId)}`)
  578. return next()
  579. })
  580. runtime.behavior = async (request) => {
  581. const tools = request.bindings[0]!.functions
  582. const all = Promise.all([tools.safe_read!({ id: 'a' }), tools.safe_read!({ id: 'b' })])
  583. // Both submissions are in; the second pre-execute must NOT have entered
  584. // while the first is still awaiting its policy decision.
  585. await expect.poll(() => stages.length).toBeGreaterThanOrEqual(1)
  586. expect(stages).toEqual(['pre-enter:call-1:code:1'])
  587. releaseGate!()
  588. await expect.poll(() => gated.pending()).toBe(2)
  589. gated.releaseAll()
  590. await all
  591. return { logs: [], value: 'ordered-prepare' }
  592. }
  593. const result = await runCode(ctx, 'program')
  594. expect(result.isError).toBe(false)
  595. expect(stages).toEqual([
  596. 'pre-enter:call-1:code:1', 'pre-exit:call-1:code:1',
  597. 'pre-enter:call-1:code:2', 'pre-exit:call-1:code:2',
  598. ])
  599. })
  600. it('an exclusive call holds its barrier through post-execute: the next start waits for the commit', async () => {
  601. const { ctx, runtime } = await setup({ mode: 'code' })
  602. const writer = registerGated(ctx, 'writer', false)
  603. const reader = registerGated(ctx, 'safe_read', true)
  604. const stages: string[] = []
  605. let releasePost: (() => void) | undefined
  606. ctx.on('tools/post-execute', async (postExec, _result, next): Promise<PostToolDecision> => {
  607. if (postExec.name === 'writer') {
  608. stages.push('post-enter:writer')
  609. await new Promise<void>((resolve) => { releasePost = resolve })
  610. stages.push('post-exit:writer')
  611. }
  612. return next()
  613. })
  614. runtime.behavior = async (request) => {
  615. const tools = request.bindings[0]!.functions
  616. const w = tools.writer!({ id: 'w' })
  617. const r = tools.safe_read!({ id: 'r' })
  618. await expect.poll(() => writer.pending()).toBe(1)
  619. writer.release()
  620. // The writer's body is done and its async post-execute is running; the
  621. // parallel read must not have STARTED (no pre/body) while the exclusive
  622. // call's pipeline is still open.
  623. await expect.poll(() => stages).toContain('post-enter:writer')
  624. expect(reader.pending()).toBe(0)
  625. releasePost!()
  626. await w
  627. await expect.poll(() => reader.pending()).toBe(1)
  628. reader.releaseAll()
  629. await r
  630. return { logs: [], value: 'barrier-through-commit' }
  631. }
  632. const result = await runCode(ctx, 'program')
  633. expect(result.isError).toBe(false)
  634. expect(stages).toEqual(['post-enter:writer', 'post-exit:writer'])
  635. })
  636. it('run settlement drains a commit already in progress: the settle event is appended inside the turn', async () => {
  637. const { ctx, runtime } = await setup({ mode: 'code' })
  638. const gated = registerGated(ctx, 'safe_read', true)
  639. const { agent, events } = fakeAgent()
  640. let releasePost: (() => void) | undefined
  641. ctx.on('tools/post-execute', async (postExec, _result, next): Promise<PostToolDecision> => {
  642. if (postExec.name === 'safe_read') {
  643. await new Promise<void>((resolve) => { releasePost = resolve })
  644. }
  645. return next()
  646. })
  647. runtime.behavior = async (request) => {
  648. // Fire-and-forget: the program returns while the sub-call's async
  649. // post-execute commit is mid-flight.
  650. request.bindings[0]!.functions.safe_read!({ id: 'a' }).catch(() => 'run-over')
  651. await expect.poll(() => gated.pending()).toBe(1)
  652. gated.release()
  653. await expect.poll(() => releasePost !== undefined).toBe(true)
  654. queueMicrotask(() => { releasePost!() })
  655. return { logs: [], value: 'returned-early' }
  656. }
  657. const result = await runCode(ctx, 'program', { agent })
  658. expect(result.isError).toBe(false)
  659. // The drain awaited the in-progress commit: the settle event exists and
  660. // preceded the run_code turn closing (all appends happen inside
  661. // execute()). The run's settlement aborted the sub-call's signal while
  662. // its post-execute was mid-flight, so the native cancellation contract
  663. // replaces the successful outcome with the aborted result — the event is
  664. // still durable and in-turn, which is the invariant under test.
  665. const settles = events.filter(event => event.type === 'tool/code-dispatch')
  666. expect(settles).toHaveLength(1)
  667. expect(settles[0]?.data).toMatchObject({ name: 'safe_read', isError: true })
  668. })
  669. it('post-execute and context commitment stay in submission order under out-of-order completion', async () => {
  670. const { ctx, runtime } = await setup({ mode: 'code' })
  671. const gated = registerGated(ctx, 'safe_read', true)
  672. const postOrder: string[] = []
  673. ctx.on('tools/post-execute', async (postExec, _result, next): Promise<PostToolDecision> => {
  674. if (postExec.name === 'safe_read') {
  675. postOrder.push(String(postExec.callId))
  676. return {
  677. kind: 'accept' as const,
  678. additionalContexts: [createUserMessage({
  679. content: [{ type: 'text' as const, text: `ctx:${String(postExec.callId)}` }],
  680. source: { kind: 'plugin' as const, plugin: 'order-probe' },
  681. })],
  682. }
  683. }
  684. return next()
  685. })
  686. runtime.behavior = async (request) => {
  687. const tools = request.bindings[0]!.functions
  688. const all = Promise.all([tools.safe_read!({ id: 'a' }), tools.safe_read!({ id: 'b' })])
  689. await expect.poll(() => gated.pending()).toBe(2)
  690. // Complete b FIRST (out of submission order), then a.
  691. gated.release() // releases a (FIFO gate) — invert: release twice reversed is not possible;
  692. gated.releaseAll()
  693. await all
  694. return { logs: [], value: 'ordered-commit' }
  695. }
  696. const result = await runCode(ctx, 'program')
  697. expect(result.isError).toBe(false)
  698. // Post-execute observed submission order regardless of completion interleave.
  699. expect(postOrder).toEqual(['call-1:code:1', 'call-1:code:2'])
  700. // Deferred contexts reach the outer result in the same order.
  701. expect(result.additionalContexts?.map(c => (c.content[0] as { text: string }).text))
  702. .toEqual(['ctx:call-1:code:1', 'ctx:call-1:code:2'])
  703. })
  704. it('a queued-unstarted call abandoned by run settlement logs no start event', async () => {
  705. const { ctx, runtime } = await setup({ mode: 'code' })
  706. const gated = registerGated(ctx, 'writer', false)
  707. const { agent, events } = fakeAgent()
  708. const abandoned: string[] = []
  709. runtime.behavior = async (request) => {
  710. const tools = request.bindings[0]!.functions
  711. // First exclusive call occupies the pool; the second queues unstarted.
  712. // Both rejections are captured (abandonment fires only at settlement,
  713. // AFTER this program has already failed — awaiting it here would deadlock).
  714. tools.writer!({ id: 'w1' }).catch(() => 'settled-under-abort')
  715. tools.writer!({ id: 'w2' }).catch((error: unknown) => {
  716. abandoned.push(error instanceof Error ? error.message : String(error))
  717. })
  718. await expect.poll(() => gated.pending()).toBe(1)
  719. // Fail the program while w1 is in flight and w2 is queued unstarted.
  720. throw new Error('program failed with a queued call')
  721. }
  722. const result = await runCode(ctx, 'program', { agent })
  723. expect(result.isError).toBe(true)
  724. const starts = events.filter(event => event.type === 'tool/code-dispatch-start').map(event => (event.data as { subCallId: string }).subCallId)
  725. const settles = events.filter(event => event.type === 'tool/code-dispatch').map(event => (event.data as { subCallId: string }).subCallId)
  726. // w1 started and settled under the abort; w2 never started and never
  727. // settled — no start event, no settle event, binding rejected with the
  728. // abandonment message at drain time.
  729. expect(starts).toEqual(['call-1:code:1'])
  730. expect(settles).toEqual(['call-1:code:1'])
  731. expect(abandoned).toEqual(['run_code run is over (run_code settled); writer tool call abandoned'])
  732. })
  733. })
  734. describe('the run_code dispatch bridge', () => {
  735. it('bridges tool calls, returns only the curated output, and logs one event per dispatch', async () => {
  736. const { ctx, runtime } = await setup({ mode: 'code' })
  737. const calls = registerEcho(ctx)
  738. const { agent, events } = fakeAgent()
  739. runtime.behavior = async (request) => {
  740. const tools = request.bindings[0]!.functions
  741. const first = await tools.echo!({ value: 'one' })
  742. const second = await tools.echo!({ value: 'two' })
  743. if (typeof first !== 'string' || typeof second !== 'string') throw new Error('echo returned a non-string')
  744. return { logs: [`saw ${first}`], value: second }
  745. }
  746. const result = await runCode(ctx, 'const …: string = …', { agent })
  747. expect(result.isError).toBe(false)
  748. if (result.isError) throw new Error('expected run_code success')
  749. expect(result.value).toEqual({ logs: ['saw echo:one'], result: 'echo:two' })
  750. expect(result.content).toEqual([{ type: 'text', text: 'saw echo:one\necho:two' }])
  751. expect(calls).toEqual([{ value: 'one' }, { value: 'two' }])
  752. const dispatches = events.filter(event => event.type === 'tool/code-dispatch')
  753. expect(dispatches.map(event => event.data)).toEqual([
  754. {
  755. rootCallId: 'call-1', parentCallId: 'call-1', subCallId: 'call-1:code:1', name: 'echo',
  756. arguments: { value: 'one' }, isError: false, content: [{ type: 'text', text: 'echo:one' }],
  757. },
  758. {
  759. rootCallId: 'call-1', parentCallId: 'call-1', subCallId: 'call-1:code:2', name: 'echo',
  760. arguments: { value: 'two' }, isError: false, content: [{ type: 'text', text: 'echo:two' }],
  761. },
  762. ])
  763. expect(result.meta).toBeUndefined()
  764. })
  765. it('exposes only an opaque parent token to nested result observers', async () => {
  766. const { ctx, runtime } = await setup({ mode: 'code' })
  767. registerEcho(ctx)
  768. runtime.behavior = async (request) => {
  769. await request.bindings[0]!.functions.echo!({ value: 'nested' })
  770. return { logs: [], value: 'done' }
  771. }
  772. // Freeze the nested observer's parent correlation. If that were the live
  773. // outer execution object, the timeout-style wrapper could not restore it.
  774. ctx.on('tools/execute', async (exec, next) => {
  775. if (exec.name !== RUN_CODE_NAME) return next()
  776. const previous = exec.signal
  777. exec.signal = new AbortController().signal
  778. const result = await next()
  779. exec.signal = previous
  780. return result
  781. })
  782. ctx.on('tools/result', (exec) => {
  783. if (exec.parent !== undefined) Object.freeze(exec.parent)
  784. })
  785. const result = await runCode(ctx, 'await tools.echo({ value: "nested" })')
  786. expect(result.isError).toBe(false)
  787. expect(result.content).toEqual([{ type: 'text', text: 'done' }])
  788. })
  789. it('forwards a nested terminal conclusion onto the successful run_code result', async () => {
  790. const { ctx, runtime } = await setup({ mode: 'code' })
  791. ctx.tools.register(defineTool({
  792. name: 'finalize',
  793. description: 'Terminal tool.',
  794. parameters: {},
  795. output: {
  796. schema: { type: 'string' },
  797. render: (_args, value) => [{ type: 'text', text: value }],
  798. },
  799. execute(_args, exec) {
  800. exec.concludeTurn()
  801. return Promise.resolve('done')
  802. },
  803. }))
  804. runtime.behavior = async (request) => {
  805. await request.bindings[0]!.functions.finalize!({})
  806. return { logs: [], value: 'program complete' }
  807. }
  808. const concluded = await runCode(ctx, 'await tools.finalize({})')
  809. expect(concluded.isError).toBe(false)
  810. expect(concluded.concludesTurn).toBe(true)
  811. // A policy that converts the nested success into an error strips the
  812. // marker with the result type: the recovering program cannot conclude.
  813. const veto = ctx.on('tools/post-execute', async (exec, _result, next): Promise<PostToolDecision> => {
  814. if (exec.name !== 'finalize') return next()
  815. return { kind: 'block', feedback: [{ type: 'text', text: 'terminal rejected' }] }
  816. })
  817. runtime.behavior = async (request) => {
  818. await request.bindings[0]!.functions.finalize!({}).catch(() => undefined)
  819. return { logs: [], value: 'recovered' }
  820. }
  821. const recovered = await runCode(ctx, 'await tools.finalize({}).catch(() => {})')
  822. veto()
  823. expect(recovered.isError).toBe(false)
  824. expect(recovered.concludesTurn).toBeUndefined()
  825. })
  826. it('serializes Promise.all dispatches: tool executions never overlap, in submission order', async () => {
  827. const { ctx, runtime } = await setup({ mode: 'code' })
  828. const intervals: [string, string][] = []
  829. let active = 0
  830. ctx.tools.register(defineTool({
  831. name: 'probe',
  832. description: 'Records execution overlap.',
  833. parameters: { id: { type: 'string', required: true } },
  834. output: {
  835. schema: { type: 'string' },
  836. render: (_args, value) => [{ type: 'text', text: value }],
  837. },
  838. async execute(args) {
  839. active++
  840. expect(active, 'probe executions overlapped').toBe(1)
  841. intervals.push(['enter', args.id])
  842. await new Promise(resolve => setTimeout(resolve, 20))
  843. intervals.push(['exit', args.id])
  844. active--
  845. return args.id
  846. },
  847. }))
  848. runtime.behavior = async (request) => {
  849. const tools = request.bindings[0]!.functions
  850. const values = await Promise.all([tools.probe!({ id: 'a' }), tools.probe!({ id: 'b' }), tools.probe!({ id: 'c' })])
  851. if (!values.every(value => typeof value === 'string')) throw new Error('probe returned a non-string')
  852. return { logs: [], value: values.join(',') }
  853. }
  854. const result = await runCode(ctx, 'program')
  855. expect(result.isError).toBe(false)
  856. expect(intervals).toEqual([
  857. ['enter', 'a'], ['exit', 'a'],
  858. ['enter', 'b'], ['exit', 'b'],
  859. ['enter', 'c'], ['exit', 'c'],
  860. ])
  861. expect(result.content[0]).toEqual({ type: 'text', text: 'a,b,c' })
  862. })
  863. it('rejects the program-side call when the tool errors, with the tool error text', async () => {
  864. const { ctx, runtime } = await setup({ mode: 'code' })
  865. ctx.tools.register(defineContentToolFixture({
  866. name: 'fail',
  867. description: 'Always fails.',
  868. parameters: {},
  869. execute(): Promise<never> { return Promise.reject(new Error('deliberate failure')) },
  870. }))
  871. runtime.behavior = async (request) => {
  872. try {
  873. await request.bindings[0]!.functions.fail!({})
  874. return { logs: [], value: 'unreachable' }
  875. } catch (error: unknown) {
  876. return { logs: [], value: `caught: ${error instanceof Error ? error.message : String(error)}` }
  877. }
  878. }
  879. const result = await runCode(ctx, 'program')
  880. expect(result.content[0]).toEqual({ type: 'text', text: 'caught: deliberate failure' })
  881. })
  882. it('a throwing tools/code-dispatch-log listener is contained: the original settled content is logged', async () => {
  883. const { ctx, runtime } = await setup({ mode: 'code' })
  884. registerEcho(ctx)
  885. ctx.on('tools/code-dispatch-log', () => { throw new Error('log-content listener failed') })
  886. const { agent, events } = fakeAgent()
  887. runtime.behavior = async (request) => {
  888. const value = await request.bindings[0]!.functions.echo!({ value: 'x' })
  889. return { logs: [], value: value as string }
  890. }
  891. const result = await runCode(ctx, 'program', { agent })
  892. expect(result.isError).toBe(false)
  893. const settle = events.find(event => event.type === 'tool/code-dispatch')
  894. expect(settle?.data).toMatchObject({ name: 'echo', isError: false, content: [{ type: 'text', text: 'echo:x' }] })
  895. })
  896. it('a throwing tools/pre-execute listener settles the sub-call without post-execute', async () => {
  897. const { ctx, runtime } = await setup({ mode: 'code' })
  898. const calls = registerEcho(ctx)
  899. const postExecuted: string[] = []
  900. ctx.on('tools/pre-execute', (exec, next) => {
  901. if (exec.name === 'echo') throw new Error('gate exploded')
  902. return next()
  903. })
  904. ctx.on('tools/post-execute', (exec, _result, next): Promise<PostToolDecision> => {
  905. if (exec.name === 'echo') postExecuted.push(exec.name)
  906. return next()
  907. })
  908. const { agent, events } = fakeAgent()
  909. runtime.behavior = async (request) => {
  910. const message = await request.bindings[0]!.functions.echo!({ value: 'x' })
  911. .then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error))
  912. return { logs: [], value: message }
  913. }
  914. const result = await runCode(ctx, 'program', { agent })
  915. expect(result.isError).toBe(false)
  916. if (result.isError) throw new Error('expected success')
  917. expect(result.value).toMatchObject({ result: 'gate exploded' })
  918. // The pipeline failure is final: the body never ran and post-execute was
  919. // skipped, yet the settle event still carries the error outcome.
  920. expect(calls).toEqual([])
  921. expect(postExecuted).toEqual([])
  922. const settles = events.filter(event => event.type === 'tool/code-dispatch')
  923. expect(settles).toHaveLength(1)
  924. expect(settles[0]?.data).toMatchObject({ name: 'echo', isError: true })
  925. })
  926. it('a tools/pre-execute deny reaches the program as a binding rejection', async () => {
  927. const { ctx, runtime } = await setup({ mode: 'code' })
  928. registerEcho(ctx)
  929. ctx.on('tools/pre-execute', (exec, next) => {
  930. if (exec.name === 'echo') return Promise.resolve({ kind: 'deny' as const, reason: 'not on my watch' })
  931. return next()
  932. })
  933. runtime.behavior = async (request) => {
  934. try {
  935. await request.bindings[0]!.functions.echo!({ value: 'x' })
  936. return { logs: [], value: 'unreachable' }
  937. } catch (error: unknown) {
  938. return { logs: [], value: `denied: ${error instanceof Error ? error.message : String(error)}` }
  939. }
  940. }
  941. const result = await runCode(ctx, 'program')
  942. expect(result.content[0]?.type).toBe('text')
  943. expect((result.content[0] as { text: string }).text).toContain('not on my watch')
  944. })
  945. it('rejects a binding argument that is not lossless JSON, dispatching nothing', async () => {
  946. const { ctx, runtime } = await setup({ mode: 'code' })
  947. const calls = registerEcho(ctx)
  948. const { agent, events } = fakeAgent()
  949. runtime.behavior = async (request) => {
  950. try {
  951. await request.bindings[0]!.functions.echo!({ value: 'x', big: 1n })
  952. return { logs: [], value: 'unreachable' }
  953. } catch (error: unknown) {
  954. return { logs: [], value: error instanceof Error ? error.message : String(error) }
  955. }
  956. }
  957. const result = await runCode(ctx, 'program', { agent })
  958. expect((result.content[0] as { text: string }).text).toContain('lossless JSON')
  959. expect(calls).toEqual([])
  960. expect(events.filter(event => event.type === 'tool/code-dispatch')).toEqual([])
  961. })
  962. it('dispatches and logs independent snapshots of the same lossless JSON value', async () => {
  963. const { ctx, runtime } = await setup({ mode: 'code' })
  964. const calls = registerEcho(ctx)
  965. const { agent, events } = fakeAgent()
  966. runtime.behavior = async (request) => {
  967. const args = Object.assign(Object.create(null) as Record<string, unknown>, { value: 'x', nested: ['same'] })
  968. await request.bindings[0]!.functions.echo!(args)
  969. return { logs: [] }
  970. }
  971. await runCode(ctx, 'program', { agent })
  972. expect(calls).toEqual([{ value: 'x', nested: ['same'] }])
  973. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  974. expect(dispatch.arguments).toEqual({ value: 'x', nested: ['same'] })
  975. })
  976. it('defers sub-call additionalContexts onto the outer run_code result', async () => {
  977. const { ctx, runtime } = await setup({ mode: 'code' })
  978. registerEcho(ctx)
  979. ctx.on('tools/post-execute', (exec, _result, next): Promise<PostToolDecision> => {
  980. if (exec.name === 'echo') {
  981. return Promise.resolve({
  982. kind: 'accept' as const,
  983. additionalContexts: [createUserMessage({
  984. content: [{ type: 'text' as const, text: `context for ${exec.callId}` }],
  985. source: { kind: 'plugin' as const, plugin: 'test' },
  986. })],
  987. })
  988. }
  989. return next()
  990. })
  991. runtime.behavior = async (request) => {
  992. await request.bindings[0]!.functions.echo!({ value: 'x' })
  993. await request.bindings[0]!.functions.echo!({ value: 'y' })
  994. return { logs: [], value: 'done' }
  995. }
  996. const result = await runCode(ctx, 'program')
  997. expect(result.isError).toBe(false)
  998. expect(result.additionalContexts).toMatchObject([
  999. {
  1000. role: 'user',
  1001. content: [{ type: 'text', text: 'context for call-1:code:1' }],
  1002. source: { kind: 'plugin', plugin: 'test' },
  1003. },
  1004. {
  1005. role: 'user',
  1006. content: [{ type: 'text', text: 'context for call-1:code:2' }],
  1007. source: { kind: 'plugin', plugin: 'test' },
  1008. },
  1009. ])
  1010. })
  1011. it('keeps sub-call contexts when run_code fails after the nested dispatch', async () => {
  1012. const { ctx, runtime } = await setup({ mode: 'both' })
  1013. registerEcho(ctx)
  1014. ctx.on('tools/post-execute', (exec, _result, next): Promise<PostToolDecision> => {
  1015. if (exec.name !== 'echo') return next()
  1016. return Promise.resolve({
  1017. kind: 'accept',
  1018. additionalContexts: [createUserMessage({
  1019. content: [{ type: 'text', text: 'nested context' }],
  1020. source: { kind: 'plugin', plugin: 'test' },
  1021. })],
  1022. })
  1023. })
  1024. runtime.behavior = async (request) => {
  1025. await request.bindings[0]!.functions.echo!({ value: 'x' })
  1026. return { logs: [], error: { kind: 'exception', message: 'program failed later' } }
  1027. }
  1028. const result = await runCode(ctx, 'program')
  1029. expect(result.isError).toBe(true)
  1030. expect(result.additionalContexts).toEqual([{
  1031. id: expect.any(String) as unknown,
  1032. role: 'user',
  1033. content: [{ type: 'text', text: 'nested context' }],
  1034. source: { kind: 'plugin', plugin: 'test' },
  1035. }])
  1036. })
  1037. it('converts a failed run into a structured isError result carrying kind, message, and captured logs', async () => {
  1038. const { ctx, runtime } = await setup({ mode: 'code' })
  1039. runtime.behavior = () => Promise.resolve({
  1040. logs: ['got this far'],
  1041. error: { kind: 'timeout', message: 'compute budget exhausted (300ms busy)' },
  1042. })
  1043. const result = await runCode(ctx, 'program')
  1044. expect(result.isError).toBe(true)
  1045. expect(result.error).toMatchObject({ info: { name: 'CodeRunFailedError', code: 'CODE_RUN_FAILED' } })
  1046. const text = (result.content[0] as { text: string }).text
  1047. expect(text).toContain('code run failed (timeout)')
  1048. expect(text).toContain('compute budget exhausted')
  1049. expect(text).toContain('got this far')
  1050. })
  1051. it('CodeRunFailedError is a HarnessError with the CODE_RUN_FAILED code', () => {
  1052. const error = new CodeRunFailedError('boom')
  1053. expect(error.code).toBe('CODE_RUN_FAILED')
  1054. expect(error.name).toBe('CodeRunFailedError')
  1055. })
  1056. it('aborting the outer signal aborts the in-flight sub-dispatch and abandons queued ones', async () => {
  1057. const { ctx, runtime } = await setup({ mode: 'code' })
  1058. const seen: string[] = []
  1059. let sawAbort = false
  1060. ctx.tools.register(defineContentToolFixture({
  1061. name: 'slow',
  1062. description: 'Slow tool observing its signal.',
  1063. parameters: { id: { type: 'string', required: true } },
  1064. async execute(args, exec) {
  1065. seen.push(args.id)
  1066. await new Promise<void>((resolve) => {
  1067. const timer = setTimeout(resolve, 500)
  1068. exec.signal.addEventListener('abort', () => { sawAbort = true; clearTimeout(timer); resolve() }, { once: true })
  1069. })
  1070. return [{ type: 'text' as const, text: args.id }]
  1071. },
  1072. }))
  1073. const controller = new AbortController()
  1074. runtime.behavior = async (request) => {
  1075. const tools = request.bindings[0]!.functions
  1076. const calls = [tools.slow!({ id: 'first' }).catch(() => 'rejected'), tools.slow!({ id: 'second' }).catch(() => 'rejected')]
  1077. setTimeout(() => { controller.abort('user-cancel') }, 50)
  1078. await Promise.all(calls)
  1079. // A real runtime would be terminated by the abort; the fake honors the
  1080. // contract by reporting the abort as the run failure.
  1081. return { logs: [], error: { kind: 'abort', message: 'user-cancel' } }
  1082. }
  1083. const result = await runCode(ctx, 'program', { signal: controller.signal })
  1084. expect(result.isError).toBe(true)
  1085. expect((result.content[0] as { text: string }).text).toContain('code run failed (abort)')
  1086. expect(seen).toEqual(['first'])
  1087. expect(sawAbort).toBe(true)
  1088. })
  1089. it('a runtime that starts a binding call and then REJECTS still reaches quiescence before returning', async () => {
  1090. const { ctx, runtime } = await setup({ mode: 'code' })
  1091. const { agent, events } = fakeAgent()
  1092. let sawAbort = false
  1093. let started!: () => void
  1094. const inFlight = new Promise<void>((resolve) => { started = resolve })
  1095. ctx.tools.register(defineContentToolFixture({
  1096. name: 'slow',
  1097. description: 'Slow tool observing its signal.',
  1098. parameters: { id: { type: 'string', required: true } },
  1099. async execute(args, exec) {
  1100. started()
  1101. await new Promise<void>((resolve) => {
  1102. const timer = setTimeout(resolve, 500)
  1103. exec.signal.addEventListener('abort', () => { sawAbort = true; clearTimeout(timer); resolve() }, { once: true })
  1104. })
  1105. return [{ type: 'text' as const, text: args.id }]
  1106. },
  1107. }))
  1108. runtime.behavior = async (request) => {
  1109. // Start a sub-dispatch, keep its rejection held, and fail the run once the tool is
  1110. // genuinely in flight — a seam error after work has begun.
  1111. request.bindings[0]!.functions.slow!({ id: 'orphan' }).catch(() => 'held')
  1112. await inFlight
  1113. throw new Error('backend exploded')
  1114. }
  1115. const result = await runCode(ctx, 'program', { agent })
  1116. expect(result.isError).toBe(true)
  1117. expect((result.content[0] as { text: string }).text).toContain('backend exploded')
  1118. // Quiescence held: the in-flight sub-dispatch was aborted and its event
  1119. // logged INSIDE the run_code execution, not after it returned.
  1120. expect(sawAbort).toBe(true)
  1121. expect(events.filter(event => event.type === 'tool/code-dispatch').map(event => (event.data as { name: string }).name)).toEqual(['slow'])
  1122. })
  1123. it('runs without an owning agent: dispatches work, event logging is skipped', async () => {
  1124. const { ctx, runtime } = await setup({ mode: 'code' })
  1125. const calls = registerEcho(ctx)
  1126. runtime.behavior = async (request) => {
  1127. await request.bindings[0]!.functions.echo!({ value: 'x' })
  1128. return { logs: [], value: 'ok' }
  1129. }
  1130. const result = await runCode(ctx, 'program')
  1131. expect(result.isError).toBe(false)
  1132. expect(calls).toEqual([{ value: 'x' }])
  1133. })
  1134. it('executing run_code under a missing runtime is a structured isError, not a crash', async () => {
  1135. const ctx = new Context()
  1136. await ctx.plugin(SystemPrompt, {})
  1137. await ctx.plugin(ToolRuntime, { mode: 'code' })
  1138. const result = await runCode(ctx, 'program')
  1139. expect(result.isError).toBe(true)
  1140. expect((result.content[0] as { text: string }).text).toContain('requires a code runtime')
  1141. })
  1142. it('presents the model-authored description as the execute-card title over the program input', async () => {
  1143. const { ctx } = await setup({ mode: 'code' })
  1144. const tool = ctx.tools.get(RUN_CODE_NAME)!
  1145. // The description labels the card (the bash description precedent); the
  1146. // program itself remains the expanded raw input.
  1147. expect(tool.presentCall?.({ code: 'return 1', description: 'Return the constant one' })).toEqual({
  1148. card: 'generic',
  1149. title: 'Return the constant one',
  1150. kind: 'execute',
  1151. rawInput: 'return 1',
  1152. })
  1153. })
  1154. it('rejects a whitespace-only description with a structured isError', async () => {
  1155. const { ctx } = await setup({ mode: 'code' })
  1156. const result = await runCode(ctx, 'return 1', { description: ' ' })
  1157. expect(result.isError).toBe(true)
  1158. expect((result.content[0] as { text: string }).text).toContain('invalid description')
  1159. })
  1160. it.each([
  1161. ['logs only', { logs: ['printed'] }, 'printed'],
  1162. ['result only', { logs: [], value: 'returned' }, 'returned'],
  1163. ['logs plus result', { logs: ['printed'], value: 'returned' }, 'printed\nreturned'],
  1164. ['no output', { logs: [] }, '(run_code completed with no output)'],
  1165. ] as [string, CodeRunResult, string][])('keeps %s in durable content without a result presenter', async (_name, output, text) => {
  1166. const { ctx, runtime } = await setup({ mode: 'code' })
  1167. runtime.behavior = () => Promise.resolve(output)
  1168. const result = await runCode(ctx, 'return 1')
  1169. const tool = ctx.tools.get(RUN_CODE_NAME)!
  1170. expect(result.content).toEqual([{ type: 'text', text }])
  1171. // Presenters keep the pending program title and render this durable content
  1172. // through their generic fallback. Omitting a result view also prevents the
  1173. // host frame from carrying the same raw content a second time.
  1174. expect('presentResult' in tool).toBe(false)
  1175. })
  1176. it('keeps a post-policy spill preview in durable content without a result presenter', async () => {
  1177. const { ctx, runtime } = await setup({ mode: 'code' })
  1178. const preview = 'HEAD\n\n(Omitted 100 bytes. Full formatted result stored at: /tmp/run-code.txt.)\n\nTAIL'
  1179. runtime.behavior = () => Promise.resolve({ logs: ['printed'], value: 'returned' })
  1180. ctx.on('tools/post-execute', (exec, _result, next): Promise<PostToolDecision> => {
  1181. if (exec.name !== RUN_CODE_NAME) return next()
  1182. return Promise.resolve({ kind: 'accept', content: [{ type: 'text', text: preview }] })
  1183. })
  1184. const result = await runCode(ctx, 'return 1')
  1185. const tool = ctx.tools.get(RUN_CODE_NAME)!
  1186. expect(result.content).toEqual([{ type: 'text', text: preview }])
  1187. expect('presentResult' in tool).toBe(false)
  1188. })
  1189. it('keeps canonical failure content durable without a result presenter', async () => {
  1190. const { ctx, runtime } = await setup({ mode: 'code' })
  1191. runtime.behavior = () => Promise.resolve({
  1192. logs: ['captured before failure'],
  1193. error: { kind: 'output-limit', message: 'outer output exceeded 8 bytes' },
  1194. })
  1195. const result = await runCode(ctx, 'return 1')
  1196. const tool = ctx.tools.get(RUN_CODE_NAME)!
  1197. expect(result.isError).toBe(true)
  1198. expect(result.content).toEqual([{
  1199. type: 'text',
  1200. text: 'Error: code run failed (output-limit): outer output exceeded 8 bytes\nCaptured output:\ncaptured before failure',
  1201. }])
  1202. expect('presentResult' in tool).toBe(false)
  1203. })
  1204. it('logs the complete sub-result content verbatim, non-text blocks and long text included', async () => {
  1205. const { ctx, runtime } = await setup({ mode: 'code' })
  1206. const { agent, events } = fakeAgent()
  1207. const long = 'x'.repeat(300)
  1208. ctx.tools.register(defineTool({
  1209. name: 'mixed',
  1210. description: 'Returns mixed content.',
  1211. parameters: {},
  1212. output: {
  1213. schema: { type: 'string' },
  1214. render: () => [
  1215. { type: 'text', text: long },
  1216. { type: 'reasoning', text: 'hidden' },
  1217. ],
  1218. },
  1219. execute() {
  1220. return Promise.resolve('mixed-value')
  1221. },
  1222. }))
  1223. runtime.behavior = async (request) => {
  1224. const value = await request.bindings[0]!.functions.mixed!({})
  1225. return { logs: [], value }
  1226. }
  1227. const result = await runCode(ctx, 'program', { agent })
  1228. expect(result.isError).toBe(false)
  1229. expect((result.content[0] as { text: string }).text).toBe('mixed-value')
  1230. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  1231. expect(dispatch.content).toEqual([
  1232. { type: 'text', text: long },
  1233. { type: 'reasoning', text: 'hidden' },
  1234. ])
  1235. })
  1236. it('rejects undefined, getter-throwing, exotic, and unrepresentable binding arguments before dispatch', async () => {
  1237. const { ctx, runtime } = await setup({ mode: 'code' })
  1238. const calls = registerEcho(ctx)
  1239. const { agent, events } = fakeAgent()
  1240. runtime.behavior = async (request) => {
  1241. const echo = request.bindings[0]!.functions.echo!
  1242. const catchMessage = (promise: Promise<unknown>) => promise.then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error))
  1243. return {
  1244. logs: [],
  1245. value: [
  1246. // Root undefined must reject up front: the event log rejects it as
  1247. // data, and nothing may execute unlogged.
  1248. await catchMessage(echo(undefined)),
  1249. await catchMessage(echo(Object.defineProperty({}, 'bad', { enumerable: true, get() { throw 'raw-throw' } }))),
  1250. await catchMessage(echo(Object.defineProperty({}, 'bad', { enumerable: true, get() { throw new Error('error-throw') } }))),
  1251. await catchMessage(echo(new Date(0))),
  1252. // A bare function is a value JSON cannot represent at all.
  1253. await catchMessage(echo(() => 1)),
  1254. ].join(' | '),
  1255. }
  1256. }
  1257. const result = await runCode(ctx, 'program', { agent })
  1258. const text = (result.content[0] as { text: string }).text
  1259. expect(text).toContain('call the tool with an arguments object')
  1260. expect(text).toContain('lossless JSON: raw-throw')
  1261. expect(text).toContain('lossless JSON: error-throw')
  1262. expect(text.match(/tool arguments must be lossless JSON/g)).toHaveLength(5)
  1263. // None dispatched or logged.
  1264. expect(calls).toEqual([])
  1265. expect(events.filter(event => event.type === 'tool/code-dispatch')).toEqual([])
  1266. })
  1267. it('dispatches and durably logs binding arguments deeper than the structured-clone call stack', async () => {
  1268. const { ctx, runtime } = await setup({ mode: 'code' })
  1269. const depth = 5_000
  1270. let observedDepth = 0
  1271. let observedLeaf: JsonValue | undefined
  1272. ctx.tools.register(defineTool({
  1273. name: 'deep_args',
  1274. description: 'Measure a deeply nested JSON argument.',
  1275. parameters: { nested: { type: 'json', required: true } },
  1276. output: {
  1277. schema: { type: 'integer' },
  1278. render: (_args, value) => [{ type: 'text', text: String(value) }],
  1279. },
  1280. execute(args) {
  1281. let cursor = args.nested
  1282. while (Array.isArray(cursor)) {
  1283. if (cursor.length !== 1) throw new Error('expected one item per nesting layer')
  1284. observedDepth++
  1285. cursor = cursor[0]!
  1286. }
  1287. observedLeaf = cursor
  1288. return Promise.resolve(observedDepth)
  1289. },
  1290. }))
  1291. const session = Session.create(SessionId('deep-code-arguments'))
  1292. const agent = { session } as Agent
  1293. runtime.behavior = async (request) => {
  1294. let nested: JsonValue = 'leaf'
  1295. for (let index = 0; index < depth; index++) nested = [nested]
  1296. const value = await request.bindings[0]!.functions.deep_args!({ nested })
  1297. return { logs: [], value }
  1298. }
  1299. const result = await runCode(ctx, 'return tools.deep_args(...)', { agent })
  1300. expect(result.isError).toBe(false)
  1301. expect(result.isError ? undefined : result.value).toEqual({ logs: [], result: depth })
  1302. expect({ observedDepth, observedLeaf }).toEqual({ observedDepth: depth, observedLeaf: 'leaf' })
  1303. const dispatch = session.events.find(event => event.type === 'tool/code-dispatch')
  1304. if (dispatch === undefined) throw new Error('expected a durable tool/code-dispatch event')
  1305. const logged = dispatch.data.arguments as { nested: JsonValue }
  1306. let loggedDepth = 0
  1307. let loggedCursor = logged.nested
  1308. while (Array.isArray(loggedCursor)) {
  1309. if (loggedCursor.length !== 1) throw new Error('expected one logged item per nesting layer')
  1310. loggedDepth++
  1311. loggedCursor = loggedCursor[0]!
  1312. }
  1313. expect({ loggedDepth, loggedCursor }).toEqual({ loggedDepth: depth, loggedCursor: 'leaf' })
  1314. })
  1315. it('gives the tool and durable log the same immutable argument value', async () => {
  1316. const { ctx, runtime } = await setup({ mode: 'code' })
  1317. const { agent, events } = fakeAgent()
  1318. let mutationSucceeded: boolean | undefined
  1319. ctx.tools.register(defineContentToolFixture({
  1320. name: 'mutator',
  1321. description: 'Attempts to mutate its args object.',
  1322. parameters: { list: { type: 'array', required: true } },
  1323. execute(args) {
  1324. mutationSucceeded = Reflect.set(args.list, 1, 'injected-by-tool')
  1325. return Promise.resolve([{ type: 'text' as const, text: 'protected' }])
  1326. },
  1327. }))
  1328. runtime.behavior = async (request) => {
  1329. await request.bindings[0]!.functions.mutator!({ list: ['original'] })
  1330. return { logs: [] }
  1331. }
  1332. const result = await runCode(ctx, 'program', { agent })
  1333. expect(result.isError).toBe(false)
  1334. expect(mutationSucceeded).toBe(false)
  1335. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  1336. expect(dispatch.arguments).toEqual({ list: ['original'] })
  1337. })
  1338. it('exposes a tool named __proto__ as an ordinary own binding', async () => {
  1339. const { ctx, runtime } = await setup({ mode: 'code' })
  1340. ctx.tools.register(defineTool({
  1341. name: '__proto__',
  1342. description: 'A prototype-colliding tool name.',
  1343. parameters: {},
  1344. output: {
  1345. schema: { type: 'string' },
  1346. render: (_args, value) => [{ type: 'text', text: value }],
  1347. },
  1348. execute() { return Promise.resolve('proto-tool-ok') },
  1349. }))
  1350. runtime.behavior = async (request) => {
  1351. const functions = request.bindings[0]!.functions
  1352. expect(Object.getPrototypeOf(functions)).toBeNull()
  1353. const value = await functions['__proto__']!({})
  1354. return { logs: [], value }
  1355. }
  1356. const result = await runCode(ctx, 'program')
  1357. expect(result.isError).toBe(false)
  1358. expect(result.content[0]).toEqual({ type: 'text', text: 'proto-tool-ok' })
  1359. })
  1360. it('renders every non-string JSON root as pretty JSON while preserving strings raw', async () => {
  1361. const { ctx, runtime } = await setup({ mode: 'code' })
  1362. runtime.behavior = () => Promise.resolve({ logs: [], value: { n: 42, ok: true } })
  1363. expect((await runCode(ctx, 'object')).content[0]).toEqual({ type: 'text', text: '{\n "n": 42,\n "ok": true\n}' })
  1364. runtime.behavior = () => Promise.resolve({ logs: [], value: {} })
  1365. expect((await runCode(ctx, 'empty object')).content[0]).toEqual({ type: 'text', text: '{}' })
  1366. const nested = { outer: [{ inner: true }] }
  1367. runtime.behavior = () => Promise.resolve({ logs: [], value: nested })
  1368. expect((await runCode(ctx, 'nested')).content[0]).toEqual({ type: 'text', text: JSON.stringify(nested, null, 2) })
  1369. runtime.behavior = () => Promise.resolve({ logs: [], value: ['x', 2] })
  1370. expect((await runCode(ctx, 'array')).content[0]).toEqual({ type: 'text', text: '[\n "x",\n 2\n]' })
  1371. runtime.behavior = () => Promise.resolve({ logs: [], value: [] })
  1372. expect((await runCode(ctx, 'empty array')).content[0]).toEqual({ type: 'text', text: '[]' })
  1373. runtime.behavior = () => Promise.resolve({ logs: [], value: null })
  1374. expect((await runCode(ctx, 'null')).content[0]).toEqual({ type: 'text', text: 'null' })
  1375. runtime.behavior = () => Promise.resolve({ logs: [], value: 'raw' })
  1376. expect((await runCode(ctx, 'string')).content[0]).toEqual({ type: 'text', text: 'raw' })
  1377. runtime.behavior = () => Promise.resolve({ logs: [] })
  1378. const absent = await runCode(ctx, 'undefined')
  1379. expect(absent.content[0]).toEqual({ type: 'text', text: '(run_code completed with no output)' })
  1380. expect(absent.isError ? undefined : absent.value).toEqual({ logs: [] })
  1381. })
  1382. it('renders deeply nested JSON without recursive traversal or quadratic indentation', async () => {
  1383. const { ctx, runtime } = await setup({ mode: 'code' })
  1384. let value: JsonValue = {
  1385. emptyArray: [],
  1386. emptyObject: {},
  1387. pair: ['leaf', 2],
  1388. record: { first: true, second: null },
  1389. }
  1390. for (let depth = 0; depth < 5_000; depth++) value = [value]
  1391. runtime.behavior = () => Promise.resolve({ logs: [], value })
  1392. const result = await runCode(ctx, 'deep result')
  1393. expect(result.isError).toBe(false)
  1394. const text = (result.content[0] as { type: 'text'; text: string }).text
  1395. expect(text.startsWith('[\n [\n [')).toBe(true)
  1396. expect(text).toContain('"leaf"')
  1397. expect(text.endsWith(']')).toBe(true)
  1398. expect(text.length).toBeLessThan(11_000)
  1399. })
  1400. it('short-circuits a pre-aborted outer signal before the code runtime', async () => {
  1401. const { ctx, runtime } = await setup({ mode: 'code' })
  1402. const calls = registerEcho(ctx)
  1403. runtime.behavior = (request) => {
  1404. // The fake honors the seam contract for an already-aborted signal.
  1405. if (request.signal?.aborted) return Promise.resolve({ logs: [], error: { kind: 'abort' as const, message: String(request.signal.reason) } })
  1406. return Promise.resolve({ logs: [], value: 'unreachable' })
  1407. }
  1408. const controller = new AbortController()
  1409. controller.abort('too-late')
  1410. const result = await runCode(ctx, 'program', { signal: controller.signal })
  1411. expect(result.isError).toBe(true)
  1412. expect(result).toEqual({
  1413. content: [{ type: 'text', text: 'Error: tool call aborted before dispatch' }],
  1414. isError: true,
  1415. error: {
  1416. message: 'tool call aborted before dispatch',
  1417. info: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH },
  1418. },
  1419. })
  1420. expect(runtime.lastRequest).toBeUndefined()
  1421. expect(calls).toEqual([])
  1422. })
  1423. it('reports cancellation after rejecting a late binding without dispatching it', async () => {
  1424. const { ctx, runtime } = await setup({ mode: 'code' })
  1425. const calls = registerEcho(ctx)
  1426. const controller = new AbortController()
  1427. runtime.behavior = async (request) => {
  1428. controller.abort('cancelled-mid-run')
  1429. const message = await request.bindings[0]!.functions.echo!({ value: 'x' })
  1430. .then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error))
  1431. return { logs: [], value: message }
  1432. }
  1433. const result = await runCode(ctx, 'program', { signal: controller.signal })
  1434. expect(result.isError).toBe(true)
  1435. expect(result.error).toEqual({
  1436. message: 'tool call aborted',
  1437. info: { name: 'AbortError', code: 'ABORTED' },
  1438. })
  1439. expect((result.content[0] as { text: string }).text).toBe('Error: tool call aborted')
  1440. expect(calls).toEqual([])
  1441. })
  1442. it('a tool/code-dispatch event never derives a model message', () => {
  1443. const session = Session.create(SessionId('code-mode-derive'))
  1444. session.append('user/message', createUserMessage({
  1445. content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' },
  1446. }), { surfaceOp: 'append' })
  1447. session.append('tool/code-dispatch', {
  1448. rootCallId: CallId('p1'),
  1449. parentCallId: CallId('p1'),
  1450. subCallId: CallId('p1:code:1'),
  1451. name: 'echo',
  1452. arguments: { value: 'x' },
  1453. isError: false,
  1454. content: [{ type: 'text', text: 'echo:x' }],
  1455. })
  1456. const derived = session.deriveMessages()
  1457. expect(derived).toHaveLength(1)
  1458. expect(derived[0]?.role).toBe('user')
  1459. })
  1460. it('direct construction rejects a non-positive parallel sub-call cap at load', async () => {
  1461. const ctx = new Context()
  1462. await ctx.plugin(SystemPrompt, {})
  1463. expect(() => new ToolRuntime(ctx, { mode: 'code', maxParallelSubCalls: 0 }))
  1464. .toThrow('maxParallelSubCalls must be a positive integer')
  1465. })
  1466. it('direct construction in code mode defaults the parallel sub-call cap', async () => {
  1467. const ctx = new Context()
  1468. await ctx.plugin(SystemPrompt, {})
  1469. const registry = new ToolRuntime(ctx, { mode: 'code' })
  1470. expect(registry.get(RUN_CODE_NAME)).toBeDefined()
  1471. })
  1472. it('defaults to native mode under direct construction with no config', async () => {
  1473. const ctx = new Context()
  1474. await ctx.plugin(SystemPrompt, {})
  1475. const registry = new ToolRuntime(ctx)
  1476. expect(registry.get(RUN_CODE_NAME)).toBeUndefined()
  1477. const assembly = await ctx.systemPrompt.assemble()
  1478. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  1479. })
  1480. it('denies a model-direct native-tool call under code mode as UNKNOWN_TOOL', async () => {
  1481. const ctx = new Context()
  1482. await ctx.plugin(SystemPrompt, {})
  1483. const registry = new ToolRuntime(ctx, { mode: 'code' })
  1484. registerEcho(ctx, 'write')
  1485. const result = await registry.execute({
  1486. signal: testToolSignal,
  1487. callId: CallId('call-1'),
  1488. name: 'write',
  1489. arguments: { text: 'hello' },
  1490. })
  1491. expect(result.isError).toBe(true)
  1492. expect(result.error?.info).toEqual({ name: 'ToolNotFoundError', code: 'UNKNOWN_TOOL' })
  1493. // The name IS declared to this model, so a bare `unknown tool` reads as a
  1494. // broken deployment. The denial carries the route instead.
  1495. expect(result.error?.message).toBe(
  1496. `unknown tool "write": only \`${RUN_CODE_NAME}\` is callable directly — call \`write\` from inside a \`${RUN_CODE_NAME}\` program instead`,
  1497. )
  1498. })
  1499. it('routes a pre-aborted collapsed call through ABORTED_BEFORE_DISPATCH', async () => {
  1500. const ctx = new Context()
  1501. await ctx.plugin(SystemPrompt, {})
  1502. const registry = new ToolRuntime(ctx, { mode: 'code' })
  1503. registerEcho(ctx, 'write')
  1504. const aborted = new AbortController()
  1505. aborted.abort()
  1506. const result = await registry.execute({
  1507. signal: aborted.signal,
  1508. callId: CallId('call-1'),
  1509. name: 'write',
  1510. arguments: { text: 'hello' },
  1511. })
  1512. expect(result.isError).toBe(true)
  1513. expect(result.error?.info?.code).toBe(TOOL_ABORTED_BEFORE_DISPATCH)
  1514. })
  1515. })
  1516. /**
  1517. * Presentation is per agent, because an agent preset composes it: one
  1518. * deployment runs a Code Mode agent beside native ones, and neither may see
  1519. * the other's catalog. The deployment `mode` is the default those agents
  1520. * shadow, not a process-wide fact.
  1521. */
  1522. describe('per-agent presentation', () => {
  1523. it('gives one agent Code Mode while the deployment stays native', async () => {
  1524. const { ctx, systemPrompt } = await setup({ mode: 'native' })
  1525. const calls = registerEcho(ctx)
  1526. const { scope, agent } = await mintAgentScope(ctx)
  1527. scope.ctx.tools.presentAs('code')
  1528. const coded = await systemPrompt.assemble({ scope: agent })
  1529. expect(coded.tools.map(tool => tool.name)).toEqual([RUN_CODE_NAME])
  1530. expect(coded.sections.find(section => section.name === 'tools:sdk')?.text)
  1531. .toContain('echo')
  1532. // Announced surface and callable surface must agree for THIS agent, whose
  1533. // mode is its own rather than the deployment's.
  1534. const denied = await ctx.tools.execute({
  1535. signal: testToolSignal,
  1536. callId: CallId('coded-direct'),
  1537. name: 'echo',
  1538. arguments: { value: 'coded' },
  1539. agent,
  1540. })
  1541. expect(denied.error?.info).toEqual({ name: 'ToolNotFoundError', code: 'UNKNOWN_TOOL' })
  1542. expect(calls).toEqual([])
  1543. // The deployment default is untouched: an agent that declared nothing —
  1544. // and the global view behind it — still sees the native catalog.
  1545. const native = await systemPrompt.assemble()
  1546. expect(native.tools.map(tool => tool.name)).toEqual(['echo'])
  1547. expect(native.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  1548. })
  1549. it('inherits a STANDING preset scope\'s mode down the chain, agents beside it unaffected', async () => {
  1550. const { bindScopeParent } = await import('@deepseek-ai/dsh-scope')
  1551. const { ctx, systemPrompt } = await setup({ mode: 'native' })
  1552. const calls = registerEcho(ctx)
  1553. // The preset's standing scope declares once; the agent only PARENTS to it
  1554. // (the per-preset standing mount configuration has no per-agent declaration).
  1555. const standing = await mintAgentScope(ctx, 'preset:code-like')
  1556. standing.scope.ctx.tools.presentAs('code')
  1557. const joined = await mintAgentScope(ctx, 'joined-agent')
  1558. bindScopeParent(joined.agent, standing.agent)
  1559. const loner = await mintAgentScope(ctx, 'loner-agent')
  1560. expect(ctx.tools.get(RUN_CODE_NAME, joined.agent)).toBeDefined()
  1561. const coded = await systemPrompt.assemble({ scope: joined.agent })
  1562. expect(coded.tools.map(tool => tool.name)).toEqual([RUN_CODE_NAME])
  1563. // Through the EXECUTOR, not just the wire: the deployment default is
  1564. // `native` here, so a collapse predicate reading it instead of this
  1565. // scope's effective mode would announce [run_code] and still execute the
  1566. // native call — the bypass, reopened for exactly the preset composition
  1567. // `dsh-agent-tool-presentation` produces.
  1568. expect(ctx.tools.executionMode({
  1569. signal: testToolSignal,
  1570. callId: CallId('preset-coded-schedule'),
  1571. name: 'echo',
  1572. arguments: { value: 'joined' },
  1573. agent: joined.agent,
  1574. })).toEqual({ kind: 'exclusive' })
  1575. const denied = await ctx.tools.execute({
  1576. signal: testToolSignal,
  1577. callId: CallId('preset-coded-direct'),
  1578. name: 'echo',
  1579. arguments: { value: 'joined' },
  1580. agent: joined.agent,
  1581. })
  1582. expect(denied.error?.info).toEqual({ name: 'ToolNotFoundError', code: 'UNKNOWN_TOOL' })
  1583. expect(calls).toEqual([])
  1584. // A sibling that never parented stays native, as does the global view.
  1585. expect(ctx.tools.get(RUN_CODE_NAME, loner.agent)).toBeUndefined()
  1586. const native = await systemPrompt.assemble({ scope: loner.agent })
  1587. expect(native.tools.map(tool => tool.name)).toEqual(['echo'])
  1588. const allowed = await ctx.tools.execute({
  1589. signal: testToolSignal,
  1590. callId: CallId('native-sibling-direct'),
  1591. name: 'echo',
  1592. arguments: { value: 'loner' },
  1593. agent: loner.agent,
  1594. })
  1595. expect(allowed).toMatchObject({ isError: false, value: 'echo:loner' })
  1596. expect(calls).toEqual([{ value: 'loner' }])
  1597. })
  1598. it('keeps run_code out of a native agent\'s dispatch table', async () => {
  1599. const { ctx } = await setup({ mode: 'native' })
  1600. registerEcho(ctx)
  1601. const coded = await mintAgentScope(ctx, 'coded')
  1602. const plain = await mintAgentScope(ctx, 'plain')
  1603. coded.scope.ctx.tools.presentAs('code')
  1604. // Not merely hidden from the prompt: the transport one agent presents must
  1605. // not be dispatchable by another that never presented it.
  1606. expect(ctx.tools.get(RUN_CODE_NAME, coded.agent)).toBeDefined()
  1607. expect(ctx.tools.get(RUN_CODE_NAME, plain.agent)).toBeUndefined()
  1608. expect(ctx.tools.get(RUN_CODE_NAME)).toBeUndefined()
  1609. })
  1610. it('lets an agent opt out of a code-mode deployment', async () => {
  1611. const { ctx, systemPrompt } = await setup({ mode: 'code' })
  1612. registerEcho(ctx)
  1613. const { scope, agent } = await mintAgentScope(ctx)
  1614. scope.ctx.tools.presentAs('native')
  1615. const assembly = await systemPrompt.assemble({ scope: agent })
  1616. expect(assembly.tools.map(tool => tool.name)).toEqual(['echo'])
  1617. // The deployment's global section still reaches this scope; rendering it
  1618. // empty is what keeps the opted-out agent's prompt free of an SDK.
  1619. expect(assembly.sections.find(section => section.name === 'tools:sdk')?.text).toBe('')
  1620. })
  1621. it('restores the deployment default when the agent unloads', async () => {
  1622. const { ctx, systemPrompt } = await setup({ mode: 'native' })
  1623. registerEcho(ctx)
  1624. const { scope, agent } = await mintAgentScope(ctx)
  1625. const dispose = scope.ctx.tools.presentAs('code')
  1626. dispose()
  1627. const assembly = await systemPrompt.assemble({ scope: agent })
  1628. expect(assembly.tools.map(tool => tool.name)).toEqual(['echo'])
  1629. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  1630. })
  1631. it('refuses a second declaration for the same agent', async () => {
  1632. const { ctx } = await setup({ mode: 'native' })
  1633. const { scope } = await mintAgentScope(ctx)
  1634. scope.ctx.tools.presentAs('code')
  1635. // Two answers to "which form does the model see" is a contradiction, and
  1636. // silently keeping either one would make the composition unreadable.
  1637. expect(() => scope.ctx.tools.presentAs('both'))
  1638. .toThrow('conflicts with "code" already declared')
  1639. })
  1640. it('refuses an unscoped declaration', async () => {
  1641. const { ctx } = await setup({ mode: 'native' })
  1642. expect(() => ctx.tools.presentAs('code'))
  1643. .toThrow('requires a scoped context')
  1644. })
  1645. it('reserves run_code even where no agent presents it', async () => {
  1646. const { ctx } = await setup({ mode: 'native' })
  1647. // The name must stay free under a native deployment too: an agent preset
  1648. // mounting later would otherwise collide with whatever took it.
  1649. expect(() => registerEcho(ctx, RUN_CODE_NAME)).toThrow('is reserved')
  1650. })
  1651. it('reports the missing runtime against the agent\'s own mode', async () => {
  1652. const { ctx, systemPrompt } = await setup({ mode: 'native', runtime: false })
  1653. registerEcho(ctx)
  1654. const { scope, agent } = await mintAgentScope(ctx)
  1655. scope.ctx.tools.presentAs('both')
  1656. await expect(systemPrompt.assemble({ scope: agent }))
  1657. .rejects.toThrow('mode "both" requires a code runtime')
  1658. })
  1659. })