code-mode.spec.ts 70 KB

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