code-mode.spec.ts 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859
  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 ToolRegistry, { CodeRunFailedError, RUN_CODE_NAME, TOOL_ABORTED_BEFORE_DISPATCH, defineContentToolFixture, defineTool } from '@deepseek-ai/dsh-tools'
  10. import type { Config, JsonSchemaNode, PostToolDecision, ToolExecutionResult } from '@deepseek-ai/dsh-tools'
  11. import type { Agent } from '@deepseek-ai/dsh-agent'
  12. import { Session, SessionId } from '@deepseek-ai/dsh-session'
  13. import type { JsonValue, SessionEventMap } from '@deepseek-ai/dsh-session'
  14. const testToolSignal = new AbortController().signal
  15. /**
  16. * Code Mode unit tier (per the Agent Note's plan): provider contribution per mode,
  17. * misconfiguration rejections, the run_code dispatch bridge (serialization,
  18. * abort, JSON normalization, error mapping, events, quiescence), and HMR
  19. * safety — all against an in-repo fake runtime, exactly the
  20. * 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(ToolRegistry, { mode: options.mode ?? 'code', ...options.maxParallelSubCalls !== undefined ? { maxParallelSubCalls: options.maxParallelSubCalls } : {} })
  47. let runtime: FakeRuntime | undefined
  48. if (options.runtime !== false) {
  49. await ctx.plugin(FakeRuntime, options.runtime ?? {})
  50. runtime = ctx.codeRuntime as FakeRuntime
  51. }
  52. return { ctx, tools: ctx.tools, systemPrompt: ctx.systemPrompt, runtime: runtime! }
  53. }
  54. /** Mint 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(ToolRegistry, { 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('defers image-bearing final sub-call content onto the outer run_code result', async () => {
  1012. const { ctx, runtime } = await setup({ mode: 'code' })
  1013. ctx.tools.register(defineContentToolFixture({
  1014. name: 'image_result',
  1015. description: 'Return one durable image.',
  1016. parameters: {},
  1017. execute: () => Promise.resolve([
  1018. { type: 'text', text: 'image result' },
  1019. {
  1020. type: 'image',
  1021. attachment: {
  1022. attachmentId: 'sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' as never,
  1023. mediaType: 'image/png', bytes: 1, width: 1, height: 1,
  1024. },
  1025. },
  1026. ]),
  1027. }))
  1028. runtime.behavior = async (request) => {
  1029. await request.bindings[0]!.functions.image_result!({})
  1030. return { logs: [], value: 'done' }
  1031. }
  1032. const result = await runCode(ctx, 'program')
  1033. expect(result.additionalContexts).toMatchObject([{
  1034. role: 'user',
  1035. source: { kind: 'plugin', plugin: 'tools-code-mode' },
  1036. content: [
  1037. { type: 'text', text: 'image result' },
  1038. { type: 'image', attachment: { mediaType: 'image/png', bytes: 1, width: 1, height: 1 } },
  1039. ],
  1040. }])
  1041. })
  1042. it('does not defer images removed by a nested post-execute decision', async () => {
  1043. for (const decision of ['block', 'replace'] as const) {
  1044. const { ctx, runtime } = await setup({ mode: 'code' })
  1045. ctx.tools.register(defineContentToolFixture({
  1046. name: 'image_result',
  1047. description: 'Return one durable image.',
  1048. parameters: {},
  1049. execute: () => Promise.resolve([{
  1050. type: 'image',
  1051. attachment: {
  1052. attachmentId: 'sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' as never,
  1053. mediaType: 'image/png', bytes: 1, width: 1, height: 1,
  1054. },
  1055. }]),
  1056. }))
  1057. ctx.on('tools/post-execute', (exec, _result, next): Promise<PostToolDecision> => {
  1058. if (exec.name !== 'image_result') return next()
  1059. return Promise.resolve(decision === 'block'
  1060. ? { kind: 'block', feedback: [{ type: 'text', text: 'blocked' }] }
  1061. : { kind: 'accept', content: [{ type: 'text', text: 'replaced' }] })
  1062. })
  1063. runtime.behavior = async (request) => {
  1064. await request.bindings[0]!.functions.image_result!({}).catch(() => undefined)
  1065. return { logs: [], value: 'done' }
  1066. }
  1067. const result = await runCode(ctx, 'program')
  1068. expect(result.additionalContexts).toBeUndefined()
  1069. await ctx.fiber.dispose()
  1070. }
  1071. })
  1072. it('keeps sub-call contexts when run_code fails after the nested dispatch', async () => {
  1073. const { ctx, runtime } = await setup({ mode: 'both' })
  1074. registerEcho(ctx)
  1075. ctx.on('tools/post-execute', (exec, _result, next): Promise<PostToolDecision> => {
  1076. if (exec.name !== 'echo') return next()
  1077. return Promise.resolve({
  1078. kind: 'accept',
  1079. additionalContexts: [createUserMessage({
  1080. content: [{ type: 'text', text: 'nested context' }],
  1081. source: { kind: 'plugin', plugin: 'test' },
  1082. })],
  1083. })
  1084. })
  1085. runtime.behavior = async (request) => {
  1086. await request.bindings[0]!.functions.echo!({ value: 'x' })
  1087. return { logs: [], error: { kind: 'exception', message: 'program failed later' } }
  1088. }
  1089. const result = await runCode(ctx, 'program')
  1090. expect(result.isError).toBe(true)
  1091. expect(result.additionalContexts).toEqual([{
  1092. id: expect.any(String) as unknown,
  1093. role: 'user',
  1094. content: [{ type: 'text', text: 'nested context' }],
  1095. source: { kind: 'plugin', plugin: 'test' },
  1096. }])
  1097. })
  1098. it('converts a failed run into a structured isError result carrying kind, message, and captured logs', async () => {
  1099. const { ctx, runtime } = await setup({ mode: 'code' })
  1100. runtime.behavior = () => Promise.resolve({
  1101. logs: ['got this far'],
  1102. error: { kind: 'timeout', message: 'compute budget exhausted (300ms busy)' },
  1103. })
  1104. const result = await runCode(ctx, 'program')
  1105. expect(result.isError).toBe(true)
  1106. expect(result.error).toMatchObject({ info: { name: 'CodeRunFailedError', code: 'CODE_RUN_FAILED' } })
  1107. const text = (result.content[0] as { text: string }).text
  1108. expect(text).toContain('code run failed (timeout)')
  1109. expect(text).toContain('compute budget exhausted')
  1110. expect(text).toContain('got this far')
  1111. })
  1112. it('CodeRunFailedError is a HarnessError with the CODE_RUN_FAILED code', () => {
  1113. const error = new CodeRunFailedError('boom')
  1114. expect(error.code).toBe('CODE_RUN_FAILED')
  1115. expect(error.name).toBe('CodeRunFailedError')
  1116. })
  1117. it('aborting the outer signal aborts the in-flight sub-dispatch and abandons queued ones', async () => {
  1118. const { ctx, runtime } = await setup({ mode: 'code' })
  1119. const seen: string[] = []
  1120. let sawAbort = false
  1121. ctx.tools.register(defineContentToolFixture({
  1122. name: 'slow',
  1123. description: 'Slow tool observing its signal.',
  1124. parameters: { id: { type: 'string', required: true } },
  1125. async execute(args, exec) {
  1126. seen.push(args.id)
  1127. await new Promise<void>((resolve) => {
  1128. const timer = setTimeout(resolve, 500)
  1129. exec.signal.addEventListener('abort', () => { sawAbort = true; clearTimeout(timer); resolve() }, { once: true })
  1130. })
  1131. return [{ type: 'text' as const, text: args.id }]
  1132. },
  1133. }))
  1134. const controller = new AbortController()
  1135. runtime.behavior = async (request) => {
  1136. const tools = request.bindings[0]!.functions
  1137. const calls = [tools.slow!({ id: 'first' }).catch(() => 'rejected'), tools.slow!({ id: 'second' }).catch(() => 'rejected')]
  1138. setTimeout(() => { controller.abort('user-cancel') }, 50)
  1139. await Promise.all(calls)
  1140. // A real runtime would be terminated by the abort; the fake honors the
  1141. // contract by reporting the abort as the run failure.
  1142. return { logs: [], error: { kind: 'abort', message: 'user-cancel' } }
  1143. }
  1144. const result = await runCode(ctx, 'program', { signal: controller.signal })
  1145. expect(result.isError).toBe(true)
  1146. expect((result.content[0] as { text: string }).text).toContain('code run failed (abort)')
  1147. expect(seen).toEqual(['first'])
  1148. expect(sawAbort).toBe(true)
  1149. })
  1150. it('a runtime that starts a binding call and then REJECTS still reaches quiescence before returning', async () => {
  1151. const { ctx, runtime } = await setup({ mode: 'code' })
  1152. const { agent, events } = fakeAgent()
  1153. let sawAbort = false
  1154. let started!: () => void
  1155. const inFlight = new Promise<void>((resolve) => { started = resolve })
  1156. ctx.tools.register(defineContentToolFixture({
  1157. name: 'slow',
  1158. description: 'Slow tool observing its signal.',
  1159. parameters: { id: { type: 'string', required: true } },
  1160. async execute(args, exec) {
  1161. started()
  1162. await new Promise<void>((resolve) => {
  1163. const timer = setTimeout(resolve, 500)
  1164. exec.signal.addEventListener('abort', () => { sawAbort = true; clearTimeout(timer); resolve() }, { once: true })
  1165. })
  1166. return [{ type: 'text' as const, text: args.id }]
  1167. },
  1168. }))
  1169. runtime.behavior = async (request) => {
  1170. // Start a sub-dispatch, keep its rejection held, and fail the run once the tool is
  1171. // genuinely in flight — a seam error after work has begun.
  1172. request.bindings[0]!.functions.slow!({ id: 'orphan' }).catch(() => 'held')
  1173. await inFlight
  1174. throw new Error('backend exploded')
  1175. }
  1176. const result = await runCode(ctx, 'program', { agent })
  1177. expect(result.isError).toBe(true)
  1178. expect((result.content[0] as { text: string }).text).toContain('backend exploded')
  1179. // Quiescence held: the in-flight sub-dispatch was aborted and its event
  1180. // logged INSIDE the run_code execution, not after it returned.
  1181. expect(sawAbort).toBe(true)
  1182. expect(events.filter(event => event.type === 'tool/code-dispatch').map(event => (event.data as { name: string }).name)).toEqual(['slow'])
  1183. })
  1184. it('runs without an owning agent: dispatches work, event logging is skipped', async () => {
  1185. const { ctx, runtime } = await setup({ mode: 'code' })
  1186. const calls = registerEcho(ctx)
  1187. runtime.behavior = async (request) => {
  1188. await request.bindings[0]!.functions.echo!({ value: 'x' })
  1189. return { logs: [], value: 'ok' }
  1190. }
  1191. const result = await runCode(ctx, 'program')
  1192. expect(result.isError).toBe(false)
  1193. expect(calls).toEqual([{ value: 'x' }])
  1194. })
  1195. it('executing run_code under a missing runtime is a structured isError, not a crash', async () => {
  1196. const ctx = new Context()
  1197. await ctx.plugin(SystemPrompt, {})
  1198. await ctx.plugin(ToolRegistry, { mode: 'code' })
  1199. const result = await runCode(ctx, 'program')
  1200. expect(result.isError).toBe(true)
  1201. expect((result.content[0] as { text: string }).text).toContain('requires a code runtime')
  1202. })
  1203. it('presents the model-authored description as the execute-card title over the program input', async () => {
  1204. const { ctx } = await setup({ mode: 'code' })
  1205. const tool = ctx.tools.get(RUN_CODE_NAME)!
  1206. // The description labels the card (the bash description precedent); the
  1207. // program itself remains the expanded raw input.
  1208. expect(tool.presentCall?.({ code: 'return 1', description: 'Return the constant one' })).toEqual({
  1209. card: 'generic',
  1210. title: 'Return the constant one',
  1211. kind: 'execute',
  1212. rawInput: 'return 1',
  1213. })
  1214. })
  1215. it('rejects a whitespace-only description with a structured isError', async () => {
  1216. const { ctx } = await setup({ mode: 'code' })
  1217. const result = await runCode(ctx, 'return 1', { description: ' ' })
  1218. expect(result.isError).toBe(true)
  1219. expect((result.content[0] as { text: string }).text).toContain('invalid description')
  1220. })
  1221. it.each([
  1222. ['logs only', { logs: ['printed'] }, 'printed'],
  1223. ['result only', { logs: [], value: 'returned' }, 'returned'],
  1224. ['logs plus result', { logs: ['printed'], value: 'returned' }, 'printed\nreturned'],
  1225. ['no output', { logs: [] }, '(run_code completed with no output)'],
  1226. ] as [string, CodeRunResult, string][])('keeps %s in durable content without a result presenter', async (_name, output, text) => {
  1227. const { ctx, runtime } = await setup({ mode: 'code' })
  1228. runtime.behavior = () => Promise.resolve(output)
  1229. const result = await runCode(ctx, 'return 1')
  1230. const tool = ctx.tools.get(RUN_CODE_NAME)!
  1231. expect(result.content).toEqual([{ type: 'text', text }])
  1232. // Presenters keep the pending program title and render this durable content
  1233. // through their generic fallback. Omitting a result view also prevents the
  1234. // host frame from carrying the same raw content a second time.
  1235. expect('presentResult' in tool).toBe(false)
  1236. })
  1237. it('keeps a post-policy spill preview in durable content without a result presenter', async () => {
  1238. const { ctx, runtime } = await setup({ mode: 'code' })
  1239. const preview = 'HEAD\n\n(Omitted 100 bytes. Full formatted result stored at: /tmp/run-code.txt.)\n\nTAIL'
  1240. runtime.behavior = () => Promise.resolve({ logs: ['printed'], value: 'returned' })
  1241. ctx.on('tools/post-execute', (exec, _result, next): Promise<PostToolDecision> => {
  1242. if (exec.name !== RUN_CODE_NAME) return next()
  1243. return Promise.resolve({ kind: 'accept', content: [{ type: 'text', text: preview }] })
  1244. })
  1245. const result = await runCode(ctx, 'return 1')
  1246. const tool = ctx.tools.get(RUN_CODE_NAME)!
  1247. expect(result.content).toEqual([{ type: 'text', text: preview }])
  1248. expect('presentResult' in tool).toBe(false)
  1249. })
  1250. it('keeps canonical failure content durable without a result presenter', async () => {
  1251. const { ctx, runtime } = await setup({ mode: 'code' })
  1252. runtime.behavior = () => Promise.resolve({
  1253. logs: ['captured before failure'],
  1254. error: { kind: 'output-limit', message: 'outer output exceeded 8 bytes' },
  1255. })
  1256. const result = await runCode(ctx, 'return 1')
  1257. const tool = ctx.tools.get(RUN_CODE_NAME)!
  1258. expect(result.isError).toBe(true)
  1259. expect(result.content).toEqual([{
  1260. type: 'text',
  1261. text: 'Error: code run failed (output-limit): outer output exceeded 8 bytes\nCaptured output:\ncaptured before failure',
  1262. }])
  1263. expect('presentResult' in tool).toBe(false)
  1264. })
  1265. it('logs the complete sub-result content verbatim, non-text blocks and long text included', async () => {
  1266. const { ctx, runtime } = await setup({ mode: 'code' })
  1267. const { agent, events } = fakeAgent()
  1268. const long = 'x'.repeat(300)
  1269. ctx.tools.register(defineTool({
  1270. name: 'mixed',
  1271. description: 'Returns mixed content.',
  1272. parameters: {},
  1273. output: {
  1274. schema: { type: 'string' },
  1275. render: () => [
  1276. { type: 'text', text: long },
  1277. { type: 'reasoning', text: 'hidden' },
  1278. ],
  1279. },
  1280. execute() {
  1281. return Promise.resolve('mixed-value')
  1282. },
  1283. }))
  1284. runtime.behavior = async (request) => {
  1285. const value = await request.bindings[0]!.functions.mixed!({})
  1286. return { logs: [], value }
  1287. }
  1288. const result = await runCode(ctx, 'program', { agent })
  1289. expect(result.isError).toBe(false)
  1290. expect((result.content[0] as { text: string }).text).toBe('mixed-value')
  1291. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  1292. expect(dispatch.content).toEqual([
  1293. { type: 'text', text: long },
  1294. { type: 'reasoning', text: 'hidden' },
  1295. ])
  1296. })
  1297. it('rejects undefined, getter-throwing, exotic, and unrepresentable binding arguments before dispatch', async () => {
  1298. const { ctx, runtime } = await setup({ mode: 'code' })
  1299. const calls = registerEcho(ctx)
  1300. const { agent, events } = fakeAgent()
  1301. runtime.behavior = async (request) => {
  1302. const echo = request.bindings[0]!.functions.echo!
  1303. const catchMessage = (promise: Promise<unknown>) => promise.then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error))
  1304. return {
  1305. logs: [],
  1306. value: [
  1307. // Root undefined must reject up front: the event log rejects it as
  1308. // data, and nothing may execute unlogged.
  1309. await catchMessage(echo(undefined)),
  1310. await catchMessage(echo(Object.defineProperty({}, 'bad', { enumerable: true, get() { throw 'raw-throw' } }))),
  1311. await catchMessage(echo(Object.defineProperty({}, 'bad', { enumerable: true, get() { throw new Error('error-throw') } }))),
  1312. await catchMessage(echo(new Date(0))),
  1313. // A bare function is a value JSON cannot represent at all.
  1314. await catchMessage(echo(() => 1)),
  1315. ].join(' | '),
  1316. }
  1317. }
  1318. const result = await runCode(ctx, 'program', { agent })
  1319. const text = (result.content[0] as { text: string }).text
  1320. expect(text).toContain('call the tool with an arguments object')
  1321. expect(text).toContain('lossless JSON: raw-throw')
  1322. expect(text).toContain('lossless JSON: error-throw')
  1323. expect(text.match(/tool arguments must be lossless JSON/g)).toHaveLength(5)
  1324. // None dispatched or logged.
  1325. expect(calls).toEqual([])
  1326. expect(events.filter(event => event.type === 'tool/code-dispatch')).toEqual([])
  1327. })
  1328. it('dispatches and durably logs binding arguments deeper than the structured-clone call stack', async () => {
  1329. const { ctx, runtime } = await setup({ mode: 'code' })
  1330. const depth = 5_000
  1331. let observedDepth = 0
  1332. let observedLeaf: JsonValue | undefined
  1333. ctx.tools.register(defineTool({
  1334. name: 'deep_args',
  1335. description: 'Measure a deeply nested JSON argument.',
  1336. parameters: { nested: { type: 'json', required: true } },
  1337. output: {
  1338. schema: { type: 'integer' },
  1339. render: (_args, value) => [{ type: 'text', text: String(value) }],
  1340. },
  1341. execute(args) {
  1342. let cursor = args.nested
  1343. while (Array.isArray(cursor)) {
  1344. if (cursor.length !== 1) throw new Error('expected one item per nesting layer')
  1345. observedDepth++
  1346. cursor = cursor[0]!
  1347. }
  1348. observedLeaf = cursor
  1349. return Promise.resolve(observedDepth)
  1350. },
  1351. }))
  1352. const session = Session.create(SessionId('deep-code-arguments'))
  1353. const agent = { session } as Agent
  1354. runtime.behavior = async (request) => {
  1355. let nested: JsonValue = 'leaf'
  1356. for (let index = 0; index < depth; index++) nested = [nested]
  1357. const value = await request.bindings[0]!.functions.deep_args!({ nested })
  1358. return { logs: [], value }
  1359. }
  1360. const result = await runCode(ctx, 'return tools.deep_args(...)', { agent })
  1361. expect(result.isError).toBe(false)
  1362. expect(result.isError ? undefined : result.value).toEqual({ logs: [], result: depth })
  1363. expect({ observedDepth, observedLeaf }).toEqual({ observedDepth: depth, observedLeaf: 'leaf' })
  1364. const dispatch = session.events.find(event => event.type === 'tool/code-dispatch')
  1365. if (dispatch === undefined) throw new Error('expected a durable tool/code-dispatch event')
  1366. const logged = dispatch.data.arguments as { nested: JsonValue }
  1367. let loggedDepth = 0
  1368. let loggedCursor = logged.nested
  1369. while (Array.isArray(loggedCursor)) {
  1370. if (loggedCursor.length !== 1) throw new Error('expected one logged item per nesting layer')
  1371. loggedDepth++
  1372. loggedCursor = loggedCursor[0]!
  1373. }
  1374. expect({ loggedDepth, loggedCursor }).toEqual({ loggedDepth: depth, loggedCursor: 'leaf' })
  1375. })
  1376. it('gives the tool and durable log the same immutable argument value', async () => {
  1377. const { ctx, runtime } = await setup({ mode: 'code' })
  1378. const { agent, events } = fakeAgent()
  1379. let mutationSucceeded: boolean | undefined
  1380. ctx.tools.register(defineContentToolFixture({
  1381. name: 'mutator',
  1382. description: 'Attempts to mutate its args object.',
  1383. parameters: { list: { type: 'array', required: true } },
  1384. execute(args) {
  1385. mutationSucceeded = Reflect.set(args.list, 1, 'injected-by-tool')
  1386. return Promise.resolve([{ type: 'text' as const, text: 'protected' }])
  1387. },
  1388. }))
  1389. runtime.behavior = async (request) => {
  1390. await request.bindings[0]!.functions.mutator!({ list: ['original'] })
  1391. return { logs: [] }
  1392. }
  1393. const result = await runCode(ctx, 'program', { agent })
  1394. expect(result.isError).toBe(false)
  1395. expect(mutationSucceeded).toBe(false)
  1396. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  1397. expect(dispatch.arguments).toEqual({ list: ['original'] })
  1398. })
  1399. it('exposes a tool named __proto__ as an ordinary own binding', async () => {
  1400. const { ctx, runtime } = await setup({ mode: 'code' })
  1401. ctx.tools.register(defineTool({
  1402. name: '__proto__',
  1403. description: 'A prototype-colliding tool name.',
  1404. parameters: {},
  1405. output: {
  1406. schema: { type: 'string' },
  1407. render: (_args, value) => [{ type: 'text', text: value }],
  1408. },
  1409. execute() { return Promise.resolve('proto-tool-ok') },
  1410. }))
  1411. runtime.behavior = async (request) => {
  1412. const functions = request.bindings[0]!.functions
  1413. expect(Object.getPrototypeOf(functions)).toBeNull()
  1414. const value = await functions['__proto__']!({})
  1415. return { logs: [], value }
  1416. }
  1417. const result = await runCode(ctx, 'program')
  1418. expect(result.isError).toBe(false)
  1419. expect(result.content[0]).toEqual({ type: 'text', text: 'proto-tool-ok' })
  1420. })
  1421. it('renders every non-string JSON root as pretty JSON while preserving strings raw', async () => {
  1422. const { ctx, runtime } = await setup({ mode: 'code' })
  1423. runtime.behavior = () => Promise.resolve({ logs: [], value: { n: 42, ok: true } })
  1424. expect((await runCode(ctx, 'object')).content[0]).toEqual({ type: 'text', text: '{\n "n": 42,\n "ok": true\n}' })
  1425. runtime.behavior = () => Promise.resolve({ logs: [], value: {} })
  1426. expect((await runCode(ctx, 'empty object')).content[0]).toEqual({ type: 'text', text: '{}' })
  1427. const nested = { outer: [{ inner: true }] }
  1428. runtime.behavior = () => Promise.resolve({ logs: [], value: nested })
  1429. expect((await runCode(ctx, 'nested')).content[0]).toEqual({ type: 'text', text: JSON.stringify(nested, null, 2) })
  1430. runtime.behavior = () => Promise.resolve({ logs: [], value: ['x', 2] })
  1431. expect((await runCode(ctx, 'array')).content[0]).toEqual({ type: 'text', text: '[\n "x",\n 2\n]' })
  1432. runtime.behavior = () => Promise.resolve({ logs: [], value: [] })
  1433. expect((await runCode(ctx, 'empty array')).content[0]).toEqual({ type: 'text', text: '[]' })
  1434. runtime.behavior = () => Promise.resolve({ logs: [], value: null })
  1435. expect((await runCode(ctx, 'null')).content[0]).toEqual({ type: 'text', text: 'null' })
  1436. runtime.behavior = () => Promise.resolve({ logs: [], value: 'raw' })
  1437. expect((await runCode(ctx, 'string')).content[0]).toEqual({ type: 'text', text: 'raw' })
  1438. runtime.behavior = () => Promise.resolve({ logs: [] })
  1439. const absent = await runCode(ctx, 'undefined')
  1440. expect(absent.content[0]).toEqual({ type: 'text', text: '(run_code completed with no output)' })
  1441. expect(absent.isError ? undefined : absent.value).toEqual({ logs: [] })
  1442. })
  1443. it('renders deeply nested JSON without recursive traversal or quadratic indentation', async () => {
  1444. const { ctx, runtime } = await setup({ mode: 'code' })
  1445. let value: JsonValue = {
  1446. emptyArray: [],
  1447. emptyObject: {},
  1448. pair: ['leaf', 2],
  1449. record: { first: true, second: null },
  1450. }
  1451. for (let depth = 0; depth < 5_000; depth++) value = [value]
  1452. runtime.behavior = () => Promise.resolve({ logs: [], value })
  1453. const result = await runCode(ctx, 'deep result')
  1454. expect(result.isError).toBe(false)
  1455. const text = (result.content[0] as { type: 'text'; text: string }).text
  1456. expect(text.startsWith('[\n [\n [')).toBe(true)
  1457. expect(text).toContain('"leaf"')
  1458. expect(text.endsWith(']')).toBe(true)
  1459. expect(text.length).toBeLessThan(11_000)
  1460. })
  1461. it('short-circuits a pre-aborted outer signal before the code runtime', async () => {
  1462. const { ctx, runtime } = await setup({ mode: 'code' })
  1463. const calls = registerEcho(ctx)
  1464. runtime.behavior = (request) => {
  1465. // The fake honors the seam contract for an already-aborted signal.
  1466. if (request.signal?.aborted) return Promise.resolve({ logs: [], error: { kind: 'abort' as const, message: String(request.signal.reason) } })
  1467. return Promise.resolve({ logs: [], value: 'unreachable' })
  1468. }
  1469. const controller = new AbortController()
  1470. controller.abort('too-late')
  1471. const result = await runCode(ctx, 'program', { signal: controller.signal })
  1472. expect(result.isError).toBe(true)
  1473. expect(result).toEqual({
  1474. content: [{ type: 'text', text: 'Error: tool call aborted before dispatch' }],
  1475. isError: true,
  1476. error: {
  1477. message: 'tool call aborted before dispatch',
  1478. info: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH },
  1479. },
  1480. })
  1481. expect(runtime.lastRequest).toBeUndefined()
  1482. expect(calls).toEqual([])
  1483. })
  1484. it('reports cancellation after rejecting a late binding without dispatching it', async () => {
  1485. const { ctx, runtime } = await setup({ mode: 'code' })
  1486. const calls = registerEcho(ctx)
  1487. const controller = new AbortController()
  1488. runtime.behavior = async (request) => {
  1489. controller.abort('cancelled-mid-run')
  1490. const message = await request.bindings[0]!.functions.echo!({ value: 'x' })
  1491. .then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error))
  1492. return { logs: [], value: message }
  1493. }
  1494. const result = await runCode(ctx, 'program', { signal: controller.signal })
  1495. expect(result.isError).toBe(true)
  1496. expect(result.error).toEqual({
  1497. message: 'tool call aborted',
  1498. info: { name: 'AbortError', code: 'ABORTED' },
  1499. })
  1500. expect((result.content[0] as { text: string }).text).toBe('Error: tool call aborted')
  1501. expect(calls).toEqual([])
  1502. })
  1503. it('a tool/code-dispatch event never derives a model message', () => {
  1504. const session = Session.create(SessionId('code-mode-derive'))
  1505. session.append('user/message', createUserMessage({
  1506. content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' },
  1507. }), { surfaceOp: 'append' })
  1508. session.append('tool/code-dispatch', {
  1509. rootCallId: CallId('p1'),
  1510. parentCallId: CallId('p1'),
  1511. subCallId: CallId('p1:code:1'),
  1512. name: 'echo',
  1513. arguments: { value: 'x' },
  1514. isError: false,
  1515. content: [{ type: 'text', text: 'echo:x' }],
  1516. })
  1517. const derived = session.deriveMessages()
  1518. expect(derived).toHaveLength(1)
  1519. expect(derived[0]?.role).toBe('user')
  1520. })
  1521. it('direct construction rejects a non-positive parallel sub-call cap at load', async () => {
  1522. const ctx = new Context()
  1523. await ctx.plugin(SystemPrompt, {})
  1524. expect(() => new ToolRegistry(ctx, { mode: 'code', maxParallelSubCalls: 0 }))
  1525. .toThrow('maxParallelSubCalls must be a positive integer')
  1526. })
  1527. it('direct construction in code mode defaults the parallel sub-call cap', async () => {
  1528. const ctx = new Context()
  1529. await ctx.plugin(SystemPrompt, {})
  1530. const registry = new ToolRegistry(ctx, { mode: 'code' })
  1531. expect(registry.get(RUN_CODE_NAME)).toBeDefined()
  1532. })
  1533. it('defaults to native mode under direct construction with no config', async () => {
  1534. const ctx = new Context()
  1535. await ctx.plugin(SystemPrompt, {})
  1536. const registry = new ToolRegistry(ctx)
  1537. expect(registry.get(RUN_CODE_NAME)).toBeUndefined()
  1538. const assembly = await ctx.systemPrompt.assemble()
  1539. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  1540. })
  1541. it('denies a model-direct native-tool call under code mode as UNKNOWN_TOOL', async () => {
  1542. const ctx = new Context()
  1543. await ctx.plugin(SystemPrompt, {})
  1544. const registry = new ToolRegistry(ctx, { mode: 'code' })
  1545. registerEcho(ctx, 'write')
  1546. const result = await registry.execute({
  1547. signal: testToolSignal,
  1548. callId: CallId('call-1'),
  1549. name: 'write',
  1550. arguments: { text: 'hello' },
  1551. })
  1552. expect(result.isError).toBe(true)
  1553. expect(result.error?.info).toEqual({ name: 'ToolNotFoundError', code: 'UNKNOWN_TOOL' })
  1554. // The name IS declared to this model, so a bare `unknown tool` reads as a
  1555. // broken deployment. The denial carries the route instead.
  1556. expect(result.error?.message).toBe(
  1557. `unknown tool "write": only \`${RUN_CODE_NAME}\` is callable directly — call \`write\` from inside a \`${RUN_CODE_NAME}\` program instead`,
  1558. )
  1559. })
  1560. it('routes a pre-aborted collapsed call through ABORTED_BEFORE_DISPATCH', async () => {
  1561. const ctx = new Context()
  1562. await ctx.plugin(SystemPrompt, {})
  1563. const registry = new ToolRegistry(ctx, { mode: 'code' })
  1564. registerEcho(ctx, 'write')
  1565. const aborted = new AbortController()
  1566. aborted.abort()
  1567. const result = await registry.execute({
  1568. signal: aborted.signal,
  1569. callId: CallId('call-1'),
  1570. name: 'write',
  1571. arguments: { text: 'hello' },
  1572. })
  1573. expect(result.isError).toBe(true)
  1574. expect(result.error?.info?.code).toBe(TOOL_ABORTED_BEFORE_DISPATCH)
  1575. })
  1576. })
  1577. /**
  1578. * Presentation is per agent, because an agent preset composes it: one
  1579. * deployment runs a Code Mode agent beside native ones, and neither may see
  1580. * the other's catalog. The deployment `mode` is the default those agents
  1581. * shadow, not a process-wide fact.
  1582. */
  1583. describe('per-agent presentation', () => {
  1584. it('gives one agent Code Mode while the deployment stays native', async () => {
  1585. const { ctx, systemPrompt } = await setup({ mode: 'native' })
  1586. const calls = registerEcho(ctx)
  1587. const { scope, agent } = await mintAgentScope(ctx)
  1588. scope.ctx.tools.presentAs('code')
  1589. const coded = await systemPrompt.assemble({ scope: agent })
  1590. expect(coded.tools.map(tool => tool.name)).toEqual([RUN_CODE_NAME])
  1591. expect(coded.sections.find(section => section.name === 'tools:sdk')?.text)
  1592. .toContain('echo')
  1593. // Announced surface and callable surface must agree for THIS agent, whose
  1594. // mode is its own rather than the deployment's.
  1595. const denied = await ctx.tools.execute({
  1596. signal: testToolSignal,
  1597. callId: CallId('coded-direct'),
  1598. name: 'echo',
  1599. arguments: { value: 'coded' },
  1600. agent,
  1601. })
  1602. expect(denied.error?.info).toEqual({ name: 'ToolNotFoundError', code: 'UNKNOWN_TOOL' })
  1603. expect(calls).toEqual([])
  1604. // The deployment default is untouched: an agent that declared nothing —
  1605. // and the global view behind it — still sees the native catalog.
  1606. const native = await systemPrompt.assemble()
  1607. expect(native.tools.map(tool => tool.name)).toEqual(['echo'])
  1608. expect(native.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  1609. })
  1610. it('inherits a STANDING preset scope\'s mode down the chain, agents beside it unaffected', async () => {
  1611. const { bindScopeParent } = await import('@deepseek-ai/dsh-scope')
  1612. const { ctx, systemPrompt } = await setup({ mode: 'native' })
  1613. const calls = registerEcho(ctx)
  1614. // The preset's standing scope declares once; the agent only PARENTS to it
  1615. // (the per-preset standing mount configuration has no per-agent declaration).
  1616. const standing = await mintAgentScope(ctx, 'preset:code-like')
  1617. standing.scope.ctx.tools.presentAs('code')
  1618. const joined = await mintAgentScope(ctx, 'joined-agent')
  1619. bindScopeParent(joined.agent, standing.agent)
  1620. const loner = await mintAgentScope(ctx, 'loner-agent')
  1621. expect(ctx.tools.get(RUN_CODE_NAME, joined.agent)).toBeDefined()
  1622. const coded = await systemPrompt.assemble({ scope: joined.agent })
  1623. expect(coded.tools.map(tool => tool.name)).toEqual([RUN_CODE_NAME])
  1624. // Through the EXECUTOR, not just the wire: the deployment default is
  1625. // `native` here, so a collapse predicate reading it instead of this
  1626. // scope's effective mode would announce [run_code] and still execute the
  1627. // native call — the bypass, reopened for exactly the preset composition
  1628. // `dsh-agent-tool-mode` produces.
  1629. expect(ctx.tools.executionMode({
  1630. signal: testToolSignal,
  1631. callId: CallId('preset-coded-schedule'),
  1632. name: 'echo',
  1633. arguments: { value: 'joined' },
  1634. agent: joined.agent,
  1635. })).toEqual({ kind: 'exclusive' })
  1636. const denied = await ctx.tools.execute({
  1637. signal: testToolSignal,
  1638. callId: CallId('preset-coded-direct'),
  1639. name: 'echo',
  1640. arguments: { value: 'joined' },
  1641. agent: joined.agent,
  1642. })
  1643. expect(denied.error?.info).toEqual({ name: 'ToolNotFoundError', code: 'UNKNOWN_TOOL' })
  1644. expect(calls).toEqual([])
  1645. // A sibling that never parented stays native, as does the global view.
  1646. expect(ctx.tools.get(RUN_CODE_NAME, loner.agent)).toBeUndefined()
  1647. const native = await systemPrompt.assemble({ scope: loner.agent })
  1648. expect(native.tools.map(tool => tool.name)).toEqual(['echo'])
  1649. const allowed = await ctx.tools.execute({
  1650. signal: testToolSignal,
  1651. callId: CallId('native-sibling-direct'),
  1652. name: 'echo',
  1653. arguments: { value: 'loner' },
  1654. agent: loner.agent,
  1655. })
  1656. expect(allowed).toMatchObject({ isError: false, value: 'echo:loner' })
  1657. expect(calls).toEqual([{ value: 'loner' }])
  1658. })
  1659. it('keeps run_code out of a native agent\'s dispatch table', async () => {
  1660. const { ctx } = await setup({ mode: 'native' })
  1661. registerEcho(ctx)
  1662. const coded = await mintAgentScope(ctx, 'coded')
  1663. const plain = await mintAgentScope(ctx, 'plain')
  1664. coded.scope.ctx.tools.presentAs('code')
  1665. // Not merely hidden from the prompt: the transport one agent presents must
  1666. // not be dispatchable by another that never presented it.
  1667. expect(ctx.tools.get(RUN_CODE_NAME, coded.agent)).toBeDefined()
  1668. expect(ctx.tools.get(RUN_CODE_NAME, plain.agent)).toBeUndefined()
  1669. expect(ctx.tools.get(RUN_CODE_NAME)).toBeUndefined()
  1670. })
  1671. it('lets an agent opt out of a code-mode deployment', async () => {
  1672. const { ctx, systemPrompt } = await setup({ mode: 'code' })
  1673. registerEcho(ctx)
  1674. const { scope, agent } = await mintAgentScope(ctx)
  1675. scope.ctx.tools.presentAs('native')
  1676. const assembly = await systemPrompt.assemble({ scope: agent })
  1677. expect(assembly.tools.map(tool => tool.name)).toEqual(['echo'])
  1678. // The deployment's global section still reaches this scope; rendering it
  1679. // empty is what keeps the opted-out agent's prompt free of an SDK.
  1680. expect(assembly.sections.find(section => section.name === 'tools:sdk')?.text).toBe('')
  1681. })
  1682. it('restores the deployment default when the agent unloads', async () => {
  1683. const { ctx, systemPrompt } = await setup({ mode: 'native' })
  1684. registerEcho(ctx)
  1685. const { scope, agent } = await mintAgentScope(ctx)
  1686. const dispose = scope.ctx.tools.presentAs('code')
  1687. dispose()
  1688. const assembly = await systemPrompt.assemble({ scope: agent })
  1689. expect(assembly.tools.map(tool => tool.name)).toEqual(['echo'])
  1690. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  1691. })
  1692. it('refuses a second declaration for the same agent', async () => {
  1693. const { ctx } = await setup({ mode: 'native' })
  1694. const { scope } = await mintAgentScope(ctx)
  1695. scope.ctx.tools.presentAs('code')
  1696. // Two answers to "which form does the model see" is a contradiction, and
  1697. // silently keeping either one would make the composition unreadable.
  1698. expect(() => scope.ctx.tools.presentAs('both'))
  1699. .toThrow('conflicts with "code" already declared')
  1700. })
  1701. it('refuses an unscoped declaration', async () => {
  1702. const { ctx } = await setup({ mode: 'native' })
  1703. expect(() => ctx.tools.presentAs('code'))
  1704. .toThrow('requires a scoped context')
  1705. })
  1706. it('reserves run_code even where no agent presents it', async () => {
  1707. const { ctx } = await setup({ mode: 'native' })
  1708. // The name must stay free under a native deployment too: an agent preset
  1709. // mounting later would otherwise collide with whatever took it.
  1710. expect(() => registerEcho(ctx, RUN_CODE_NAME)).toThrow('is reserved')
  1711. })
  1712. it('reports the missing runtime against the agent\'s own mode', async () => {
  1713. const { ctx, systemPrompt } = await setup({ mode: 'native', runtime: false })
  1714. registerEcho(ctx)
  1715. const { scope, agent } = await mintAgentScope(ctx)
  1716. scope.ctx.tools.presentAs('both')
  1717. await expect(systemPrompt.assemble({ scope: agent }))
  1718. .rejects.toThrow('mode "both" requires a code runtime')
  1719. })
  1720. })