code-mode.spec.ts 82 KB

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