code-mode.spec.ts 77 KB

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