code-mode.spec.ts 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { 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's language is not typescript", async () => {
  302. const { systemPrompt } = await setup({ mode: 'code', runtime: { language: 'python' } })
  303. await expect(systemPrompt.assemble()).rejects.toThrow(/language is "python"/)
  304. })
  305. it("rejects the assembly when toolOrder names a native tool that mode 'code' no longer contributes", async () => {
  306. const { ctx, systemPrompt } = await setup({ mode: 'code', toolOrder: ['echo', '<unlisted-tools>'] })
  307. registerEcho(ctx)
  308. await expect(systemPrompt.assemble()).rejects.toThrow(/toolOrder lists unregistered tool "echo"/)
  309. })
  310. it('removes run_code and the SDK section when the registry fiber disposes (HMR safety)', async () => {
  311. const ctx = new Context()
  312. await ctx.plugin(SystemPrompt, {})
  313. await ctx.plugin(FakeRuntime, {})
  314. const fiber = await ctx.plugin(ToolRegistry, { mode: 'code' })
  315. expect(ctx.tools.get(RUN_CODE_NAME)).toBeDefined()
  316. await fiber.dispose()
  317. const assembly = await ctx.systemPrompt.assemble()
  318. expect(assembly.tools).toEqual([])
  319. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  320. })
  321. })
  322. describe('the sub-dispatch scheduler (native concurrency contract)', () => {
  323. /** Register a tool whose calls resolve only when the test releases them; returns live-call telemetry. */
  324. function registerGated(ctx: Context, name: string, concurrencySafe: boolean) {
  325. const gates: (() => void)[] = []
  326. let live = 0
  327. let peak = 0
  328. const order: string[] = []
  329. ctx.tools.register(defineTool({
  330. name,
  331. description: `Gated tool ${name}.`,
  332. parameters: { id: { type: 'string', required: true } },
  333. output: {
  334. schema: { type: 'string' },
  335. render: (_args, value) => [{ type: 'text', text: value }],
  336. },
  337. ...concurrencySafe ? { isConcurrencySafe: () => true } : {},
  338. async execute(args, exec) {
  339. order.push(`start:${args.id}`)
  340. live++
  341. peak = Math.max(peak, live)
  342. // Abort-observing like a real tool: the run-scoped abort releases the
  343. // gate so the bridge's drain reaches quiescence.
  344. await new Promise<void>((release) => {
  345. gates.push(release)
  346. exec.signal.addEventListener('abort', () => { release() }, { once: true })
  347. })
  348. live--
  349. order.push(`end:${args.id}`)
  350. return `${name}:${args.id}`
  351. },
  352. }))
  353. const release = (): void => { gates.shift()?.() }
  354. const releaseAll = (): void => { while (gates.length > 0) gates.shift()!() }
  355. return { order, release, releaseAll, peakLive: () => peak, pending: () => gates.length }
  356. }
  357. it('overlaps concurrency-safe calls under Promise.all and logs a start event per dispatch', async () => {
  358. const { ctx, runtime } = await setup({ mode: 'code' })
  359. const gated = registerGated(ctx, 'safe_read', true)
  360. const { agent, events } = fakeAgent()
  361. runtime.behavior = async (request) => {
  362. const tools = request.bindings[0]!.functions
  363. const all = Promise.all([
  364. tools.safe_read!({ id: 'a' }),
  365. tools.safe_read!({ id: 'b' }),
  366. tools.safe_read!({ id: 'c' }),
  367. ])
  368. // All three must be START-able without any completion (overlap proof).
  369. await expect.poll(() => gated.pending()).toBe(3)
  370. gated.releaseAll()
  371. return { logs: [], value: (await all).map(String).join(',') }
  372. }
  373. const result = await runCode(ctx, 'program', { agent })
  374. expect(result.isError).toBe(false)
  375. expect(gated.peakLive()).toBe(3)
  376. if (result.isError) throw new Error('expected success')
  377. expect(result.value).toMatchObject({ result: 'safe_read:a,safe_read:b,safe_read:c' })
  378. // One start per dispatch, paired with its settle by subCallId, starts in submission order.
  379. const starts = events.filter(event => event.type === 'tool/code-dispatch-start').map(event => event.data as { subCallId: string })
  380. const settles = events.filter(event => event.type === 'tool/code-dispatch').map(event => event.data as { subCallId: string })
  381. expect(starts.map(start => start.subCallId)).toEqual(['call-1:code:1', 'call-1:code:2', 'call-1:code:3'])
  382. expect(new Set(settles.map(settle => settle.subCallId))).toEqual(new Set(starts.map(start => start.subCallId)))
  383. })
  384. it('an exclusive call bars overlap: safe calls drain first, it runs alone, later calls wait', async () => {
  385. const { ctx, runtime } = await setup({ mode: 'code' })
  386. const safe = registerGated(ctx, 'safe_read', true)
  387. const unsafe = registerGated(ctx, 'writer', false)
  388. runtime.behavior = async (request) => {
  389. const tools = request.bindings[0]!.functions
  390. const reads = [tools.safe_read!({ id: 'r1' }), tools.safe_read!({ id: 'r2' })]
  391. const write = tools.writer!({ id: 'w' })
  392. const tail = tools.safe_read!({ id: 'r3' })
  393. await expect.poll(() => safe.pending()).toBe(2)
  394. // The exclusive call must NOT have started while the pool is live.
  395. expect(unsafe.pending()).toBe(0)
  396. safe.releaseAll()
  397. await expect.poll(() => unsafe.pending()).toBe(1)
  398. // The trailing safe call must NOT start while the exclusive one runs.
  399. expect(safe.pending()).toBe(0)
  400. unsafe.release()
  401. await expect.poll(() => safe.pending()).toBe(1)
  402. safe.releaseAll()
  403. await Promise.all([...reads, write, tail])
  404. return { logs: [], value: 'ordered' }
  405. }
  406. const result = await runCode(ctx, 'program')
  407. expect(result.isError).toBe(false)
  408. expect(safe.order.slice(0, 2)).toEqual(['start:r1', 'start:r2'])
  409. expect(unsafe.order).toEqual(['start:w', 'end:w'])
  410. // r3 started only after w ended.
  411. expect(safe.order.indexOf('start:r3')).toBeGreaterThan(safe.order.indexOf('end:r1'))
  412. })
  413. it('maxParallelSubCalls caps the overlap window', async () => {
  414. const { ctx, runtime } = await setup({ mode: 'code', maxParallelSubCalls: 2 })
  415. const gated = registerGated(ctx, 'safe_read', true)
  416. runtime.behavior = async (request) => {
  417. const tools = request.bindings[0]!.functions
  418. const all = Promise.all([
  419. tools.safe_read!({ id: 'a' }),
  420. tools.safe_read!({ id: 'b' }),
  421. tools.safe_read!({ id: 'c' }),
  422. ])
  423. await expect.poll(() => gated.pending()).toBe(2)
  424. // The third call waits for a slot.
  425. expect(gated.pending()).toBe(2)
  426. gated.release()
  427. await expect.poll(() => gated.pending()).toBe(2)
  428. gated.releaseAll()
  429. await all
  430. return { logs: [], value: 'capped' }
  431. }
  432. const result = await runCode(ctx, 'program')
  433. if (result.isError) console.error('CAP-FAIL:', (result.content[0] as { text: string }).text)
  434. expect(result.isError).toBe(false)
  435. expect(gated.peakLive()).toBe(2)
  436. })
  437. it('a tool unregistered between binding enumeration and dispatch fails as unknown tool', async () => {
  438. const { ctx, runtime } = await setup({ mode: 'code' })
  439. const calls: unknown[] = []
  440. const dispose = ctx.tools.register(defineTool({
  441. name: 'ephemeral',
  442. description: 'Unregistered between binding enumeration and dispatch.',
  443. parameters: {},
  444. output: {
  445. schema: { type: 'string' },
  446. render: (_args, value) => [{ type: 'text', text: value }],
  447. },
  448. execute() {
  449. calls.push('ran')
  450. return Promise.resolve('ok')
  451. },
  452. }))
  453. runtime.behavior = async (request) => {
  454. // The binding exists (enumerated at run start); the registry mutation
  455. // makes prepare resolve UNKNOWN_TOOL as a final-result, which commits
  456. // through scheduler.finish (no post-execute).
  457. dispose()
  458. const message = await request.bindings[0]!.functions.ephemeral!({})
  459. .then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error))
  460. return { logs: [], value: message }
  461. }
  462. const result = await runCode(ctx, 'program')
  463. expect(result.isError).toBe(false)
  464. if (result.isError) throw new Error('expected success')
  465. expect(result.value).toMatchObject({ result: 'unknown tool "ephemeral"' })
  466. expect(calls).toEqual([])
  467. })
  468. it('ordered pre-execute never overlaps: a slow policy on one call delays the next start', async () => {
  469. const { ctx, runtime } = await setup({ mode: 'code' })
  470. const gated = registerGated(ctx, 'safe_read', true)
  471. const stages: string[] = []
  472. let releaseGate: (() => void) | undefined
  473. ctx.on('tools/pre-execute', async (preExec, next) => {
  474. if (preExec.name !== 'safe_read') return next()
  475. stages.push(`pre-enter:${String(preExec.callId)}`)
  476. if (releaseGate === undefined) {
  477. // The FIRST call's policy awaits an asynchronous decision.
  478. await new Promise<void>((resolve) => { releaseGate = resolve })
  479. }
  480. stages.push(`pre-exit:${String(preExec.callId)}`)
  481. return next()
  482. })
  483. runtime.behavior = async (request) => {
  484. const tools = request.bindings[0]!.functions
  485. const all = Promise.all([tools.safe_read!({ id: 'a' }), tools.safe_read!({ id: 'b' })])
  486. // Both submissions are in; the second pre-execute must NOT have entered
  487. // while the first is still awaiting its policy decision.
  488. await expect.poll(() => stages.length).toBeGreaterThanOrEqual(1)
  489. expect(stages).toEqual(['pre-enter:call-1:code:1'])
  490. releaseGate!()
  491. await expect.poll(() => gated.pending()).toBe(2)
  492. gated.releaseAll()
  493. await all
  494. return { logs: [], value: 'ordered-prepare' }
  495. }
  496. const result = await runCode(ctx, 'program')
  497. expect(result.isError).toBe(false)
  498. expect(stages).toEqual([
  499. 'pre-enter:call-1:code:1', 'pre-exit:call-1:code:1',
  500. 'pre-enter:call-1:code:2', 'pre-exit:call-1:code:2',
  501. ])
  502. })
  503. it('an exclusive call holds its barrier through post-execute: the next start waits for the commit', async () => {
  504. const { ctx, runtime } = await setup({ mode: 'code' })
  505. const writer = registerGated(ctx, 'writer', false)
  506. const reader = registerGated(ctx, 'safe_read', true)
  507. const stages: string[] = []
  508. let releasePost: (() => void) | undefined
  509. ctx.on('tools/post-execute', async (postExec, _result, next): Promise<PostToolDecision> => {
  510. if (postExec.name === 'writer') {
  511. stages.push('post-enter:writer')
  512. await new Promise<void>((resolve) => { releasePost = resolve })
  513. stages.push('post-exit:writer')
  514. }
  515. return next()
  516. })
  517. runtime.behavior = async (request) => {
  518. const tools = request.bindings[0]!.functions
  519. const w = tools.writer!({ id: 'w' })
  520. const r = tools.safe_read!({ id: 'r' })
  521. await expect.poll(() => writer.pending()).toBe(1)
  522. writer.release()
  523. // The writer's body is done and its async post-execute is running; the
  524. // parallel read must not have STARTED (no pre/body) while the exclusive
  525. // call's pipeline is still open.
  526. await expect.poll(() => stages).toContain('post-enter:writer')
  527. expect(reader.pending()).toBe(0)
  528. releasePost!()
  529. await w
  530. await expect.poll(() => reader.pending()).toBe(1)
  531. reader.releaseAll()
  532. await r
  533. return { logs: [], value: 'barrier-through-commit' }
  534. }
  535. const result = await runCode(ctx, 'program')
  536. expect(result.isError).toBe(false)
  537. expect(stages).toEqual(['post-enter:writer', 'post-exit:writer'])
  538. })
  539. it('run settlement drains a commit already in progress: the settle event lands inside the turn', async () => {
  540. const { ctx, runtime } = await setup({ mode: 'code' })
  541. const gated = registerGated(ctx, 'safe_read', true)
  542. const { agent, events } = fakeAgent()
  543. let releasePost: (() => void) | undefined
  544. ctx.on('tools/post-execute', async (postExec, _result, next): Promise<PostToolDecision> => {
  545. if (postExec.name === 'safe_read') {
  546. await new Promise<void>((resolve) => { releasePost = resolve })
  547. }
  548. return next()
  549. })
  550. runtime.behavior = async (request) => {
  551. // Fire-and-forget: the program returns while the sub-call's async
  552. // post-execute commit is mid-flight.
  553. request.bindings[0]!.functions.safe_read!({ id: 'a' }).catch(() => 'run-over')
  554. await expect.poll(() => gated.pending()).toBe(1)
  555. gated.release()
  556. await expect.poll(() => releasePost !== undefined).toBe(true)
  557. queueMicrotask(() => { releasePost!() })
  558. return { logs: [], value: 'returned-early' }
  559. }
  560. const result = await runCode(ctx, 'program', { agent })
  561. expect(result.isError).toBe(false)
  562. // The drain awaited the in-progress commit: the settle event exists and
  563. // preceded the run_code turn closing (all appends happen inside
  564. // execute()). The run's settlement aborted the sub-call's signal while
  565. // its post-execute was mid-flight, so the native cancellation contract
  566. // replaces the successful outcome with the aborted result — the event is
  567. // still durable and in-turn, which is the invariant under test.
  568. const settles = events.filter(event => event.type === 'tool/code-dispatch')
  569. expect(settles).toHaveLength(1)
  570. expect(settles[0]?.data).toMatchObject({ name: 'safe_read', isError: true })
  571. })
  572. it('post-execute and context commitment stay in submission order under out-of-order completion', async () => {
  573. const { ctx, runtime } = await setup({ mode: 'code' })
  574. const gated = registerGated(ctx, 'safe_read', true)
  575. const postOrder: string[] = []
  576. ctx.on('tools/post-execute', async (postExec, _result, next): Promise<PostToolDecision> => {
  577. if (postExec.name === 'safe_read') {
  578. postOrder.push(String(postExec.callId))
  579. return {
  580. kind: 'accept' as const,
  581. additionalContexts: [{
  582. content: [{ type: 'text' as const, text: `ctx:${String(postExec.callId)}` }],
  583. source: { kind: 'plugin' as const, plugin: 'order-probe' },
  584. }],
  585. }
  586. }
  587. return next()
  588. })
  589. runtime.behavior = async (request) => {
  590. const tools = request.bindings[0]!.functions
  591. const all = Promise.all([tools.safe_read!({ id: 'a' }), tools.safe_read!({ id: 'b' })])
  592. await expect.poll(() => gated.pending()).toBe(2)
  593. // Complete b FIRST (out of submission order), then a.
  594. gated.release() // releases a (FIFO gate) — invert: release twice reversed is not possible;
  595. gated.releaseAll()
  596. await all
  597. return { logs: [], value: 'ordered-commit' }
  598. }
  599. const result = await runCode(ctx, 'program')
  600. expect(result.isError).toBe(false)
  601. // Post-execute observed submission order regardless of completion interleave.
  602. expect(postOrder).toEqual(['call-1:code:1', 'call-1:code:2'])
  603. // Deferred contexts reach the outer result in the same order.
  604. expect(result.additionalContexts?.map(c => (c.content[0] as { text: string }).text))
  605. .toEqual(['ctx:call-1:code:1', 'ctx:call-1:code:2'])
  606. })
  607. it('a queued-unstarted call abandoned by run settlement logs no start event', async () => {
  608. const { ctx, runtime } = await setup({ mode: 'code' })
  609. const gated = registerGated(ctx, 'writer', false)
  610. const { agent, events } = fakeAgent()
  611. const abandoned: string[] = []
  612. runtime.behavior = async (request) => {
  613. const tools = request.bindings[0]!.functions
  614. // First exclusive call occupies the pool; the second queues unstarted.
  615. // Both rejections are captured (abandonment fires only at settlement,
  616. // AFTER this program has already failed — awaiting it here would deadlock).
  617. tools.writer!({ id: 'w1' }).catch(() => 'settled-under-abort')
  618. tools.writer!({ id: 'w2' }).catch((error: unknown) => {
  619. abandoned.push(error instanceof Error ? error.message : String(error))
  620. })
  621. await expect.poll(() => gated.pending()).toBe(1)
  622. // Fail the program while w1 is in flight and w2 is queued unstarted.
  623. throw new Error('program failed with a queued call')
  624. }
  625. const result = await runCode(ctx, 'program', { agent })
  626. expect(result.isError).toBe(true)
  627. const starts = events.filter(event => event.type === 'tool/code-dispatch-start').map(event => (event.data as { subCallId: string }).subCallId)
  628. const settles = events.filter(event => event.type === 'tool/code-dispatch').map(event => (event.data as { subCallId: string }).subCallId)
  629. // w1 started and settled under the abort; w2 never started and never
  630. // settled — no start event, no settle event, binding rejected with the
  631. // abandonment message at drain time.
  632. expect(starts).toEqual(['call-1:code:1'])
  633. expect(settles).toEqual(['call-1:code:1'])
  634. expect(abandoned).toEqual(['run_code run is over (run_code settled); writer tool call abandoned'])
  635. })
  636. })
  637. describe('the run_code dispatch bridge', () => {
  638. it('bridges tool calls, returns only the curated output, and logs one event per dispatch', async () => {
  639. const { ctx, runtime } = await setup({ mode: 'code' })
  640. const calls = registerEcho(ctx)
  641. const { agent, events } = fakeAgent()
  642. runtime.behavior = async (request) => {
  643. const tools = request.bindings[0]!.functions
  644. const first = await tools.echo!({ value: 'one' })
  645. const second = await tools.echo!({ value: 'two' })
  646. if (typeof first !== 'string' || typeof second !== 'string') throw new Error('echo returned a non-string')
  647. return { logs: [`saw ${first}`], value: second }
  648. }
  649. const result = await runCode(ctx, 'const …: string = …', { agent })
  650. expect(result.isError).toBe(false)
  651. if (result.isError) throw new Error('expected run_code success')
  652. expect(result.value).toEqual({ logs: ['saw echo:one'], result: 'echo:two' })
  653. expect(result.content).toEqual([{ type: 'text', text: 'saw echo:one\necho:two' }])
  654. expect(calls).toEqual([{ value: 'one' }, { value: 'two' }])
  655. const dispatches = events.filter(event => event.type === 'tool/code-dispatch')
  656. expect(dispatches.map(event => event.data)).toEqual([
  657. {
  658. parentCallId: 'call-1', subCallId: 'call-1:code:1', name: 'echo',
  659. arguments: { value: 'one' }, isError: false, content: [{ type: 'text', text: 'echo:one' }],
  660. },
  661. {
  662. parentCallId: 'call-1', subCallId: 'call-1:code:2', name: 'echo',
  663. arguments: { value: 'two' }, isError: false, content: [{ type: 'text', text: 'echo:two' }],
  664. },
  665. ])
  666. expect(result.meta).toBeUndefined()
  667. })
  668. it('exposes only an opaque parent token to nested result observers', async () => {
  669. const { ctx, runtime } = await setup({ mode: 'code' })
  670. registerEcho(ctx)
  671. runtime.behavior = async (request) => {
  672. await request.bindings[0]!.functions.echo!({ value: 'nested' })
  673. return { logs: [], value: 'done' }
  674. }
  675. // Freeze the nested observer's parent correlation. If that were the live
  676. // outer execution object, the timeout-style wrapper could not restore it.
  677. ctx.on('tools/execute', async (exec, next) => {
  678. if (exec.name !== RUN_CODE_NAME) return next()
  679. const previous = exec.signal
  680. exec.signal = new AbortController().signal
  681. const result = await next()
  682. exec.signal = previous
  683. return result
  684. })
  685. ctx.on('tools/result', (exec) => {
  686. if (exec.parent !== undefined) Object.freeze(exec.parent)
  687. })
  688. const result = await runCode(ctx, 'await tools.echo({ value: "nested" })')
  689. expect(result.isError).toBe(false)
  690. expect(result.content).toEqual([{ type: 'text', text: 'done' }])
  691. })
  692. it('serializes Promise.all dispatches: tool executions never overlap, in submission order', async () => {
  693. const { ctx, runtime } = await setup({ mode: 'code' })
  694. const intervals: [string, string][] = []
  695. let active = 0
  696. ctx.tools.register(defineTool({
  697. name: 'probe',
  698. description: 'Records execution overlap.',
  699. parameters: { id: { type: 'string', required: true } },
  700. output: {
  701. schema: { type: 'string' },
  702. render: (_args, value) => [{ type: 'text', text: value }],
  703. },
  704. async execute(args) {
  705. active++
  706. expect(active, 'probe executions overlapped').toBe(1)
  707. intervals.push(['enter', args.id])
  708. await new Promise(resolve => setTimeout(resolve, 20))
  709. intervals.push(['exit', args.id])
  710. active--
  711. return args.id
  712. },
  713. }))
  714. runtime.behavior = async (request) => {
  715. const tools = request.bindings[0]!.functions
  716. const values = await Promise.all([tools.probe!({ id: 'a' }), tools.probe!({ id: 'b' }), tools.probe!({ id: 'c' })])
  717. if (!values.every(value => typeof value === 'string')) throw new Error('probe returned a non-string')
  718. return { logs: [], value: values.join(',') }
  719. }
  720. const result = await runCode(ctx, 'program')
  721. expect(result.isError).toBe(false)
  722. expect(intervals).toEqual([
  723. ['enter', 'a'], ['exit', 'a'],
  724. ['enter', 'b'], ['exit', 'b'],
  725. ['enter', 'c'], ['exit', 'c'],
  726. ])
  727. expect(result.content[0]).toEqual({ type: 'text', text: 'a,b,c' })
  728. })
  729. it('rejects the program-side call when the tool errors, with the tool error text', async () => {
  730. const { ctx, runtime } = await setup({ mode: 'code' })
  731. ctx.tools.register(defineContentToolFixture({
  732. name: 'fail',
  733. description: 'Always fails.',
  734. parameters: {},
  735. execute(): Promise<never> { return Promise.reject(new Error('deliberate failure')) },
  736. }))
  737. runtime.behavior = async (request) => {
  738. try {
  739. await request.bindings[0]!.functions.fail!({})
  740. return { logs: [], value: 'unreachable' }
  741. } catch (error: unknown) {
  742. return { logs: [], value: `caught: ${error instanceof Error ? error.message : String(error)}` }
  743. }
  744. }
  745. const result = await runCode(ctx, 'program')
  746. expect(result.content[0]).toEqual({ type: 'text', text: 'caught: deliberate failure' })
  747. })
  748. it('a throwing tools/code-dispatch-log listener is contained: the unshaped content is logged', async () => {
  749. const { ctx, runtime } = await setup({ mode: 'code' })
  750. registerEcho(ctx)
  751. ctx.on('tools/code-dispatch-log', () => { throw new Error('shaper exploded') })
  752. const { agent, events } = fakeAgent()
  753. runtime.behavior = async (request) => {
  754. const value = await request.bindings[0]!.functions.echo!({ value: 'x' })
  755. return { logs: [], value: value as string }
  756. }
  757. const result = await runCode(ctx, 'program', { agent })
  758. expect(result.isError).toBe(false)
  759. const settle = events.find(event => event.type === 'tool/code-dispatch')
  760. expect(settle?.data).toMatchObject({ name: 'echo', isError: false, content: [{ type: 'text', text: 'echo:x' }] })
  761. })
  762. it('a throwing tools/pre-execute listener settles the sub-call without post-execute', async () => {
  763. const { ctx, runtime } = await setup({ mode: 'code' })
  764. const calls = registerEcho(ctx)
  765. const postExecuted: string[] = []
  766. ctx.on('tools/pre-execute', (exec, next) => {
  767. if (exec.name === 'echo') throw new Error('gate exploded')
  768. return next()
  769. })
  770. ctx.on('tools/post-execute', (exec, _result, next): Promise<PostToolDecision> => {
  771. if (exec.name === 'echo') postExecuted.push(exec.name)
  772. return next()
  773. })
  774. const { agent, events } = fakeAgent()
  775. runtime.behavior = async (request) => {
  776. const message = await request.bindings[0]!.functions.echo!({ value: 'x' })
  777. .then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error))
  778. return { logs: [], value: message }
  779. }
  780. const result = await runCode(ctx, 'program', { agent })
  781. expect(result.isError).toBe(false)
  782. if (result.isError) throw new Error('expected success')
  783. expect(result.value).toMatchObject({ result: 'gate exploded' })
  784. // The pipeline failure is final: the body never ran and post-execute was
  785. // skipped, yet the settle event still carries the error outcome.
  786. expect(calls).toEqual([])
  787. expect(postExecuted).toEqual([])
  788. const settles = events.filter(event => event.type === 'tool/code-dispatch')
  789. expect(settles).toHaveLength(1)
  790. expect(settles[0]?.data).toMatchObject({ name: 'echo', isError: true })
  791. })
  792. it('a tools/pre-execute deny reaches the program as a binding rejection', async () => {
  793. const { ctx, runtime } = await setup({ mode: 'code' })
  794. registerEcho(ctx)
  795. ctx.on('tools/pre-execute', (exec, next) => {
  796. if (exec.name === 'echo') return Promise.resolve({ kind: 'deny' as const, reason: 'not on my watch' })
  797. return next()
  798. })
  799. runtime.behavior = async (request) => {
  800. try {
  801. await request.bindings[0]!.functions.echo!({ value: 'x' })
  802. return { logs: [], value: 'unreachable' }
  803. } catch (error: unknown) {
  804. return { logs: [], value: `denied: ${error instanceof Error ? error.message : String(error)}` }
  805. }
  806. }
  807. const result = await runCode(ctx, 'program')
  808. expect(result.content[0]?.type).toBe('text')
  809. expect((result.content[0] as { text: string }).text).toContain('not on my watch')
  810. })
  811. it('rejects a binding argument that is not lossless JSON, dispatching nothing', async () => {
  812. const { ctx, runtime } = await setup({ mode: 'code' })
  813. const calls = registerEcho(ctx)
  814. const { agent, events } = fakeAgent()
  815. runtime.behavior = async (request) => {
  816. try {
  817. await request.bindings[0]!.functions.echo!({ value: 'x', big: 1n })
  818. return { logs: [], value: 'unreachable' }
  819. } catch (error: unknown) {
  820. return { logs: [], value: error instanceof Error ? error.message : String(error) }
  821. }
  822. }
  823. const result = await runCode(ctx, 'program', { agent })
  824. expect((result.content[0] as { text: string }).text).toContain('lossless JSON')
  825. expect(calls).toEqual([])
  826. expect(events.filter(event => event.type === 'tool/code-dispatch')).toEqual([])
  827. })
  828. it('dispatches and logs independent snapshots of the same lossless JSON value', async () => {
  829. const { ctx, runtime } = await setup({ mode: 'code' })
  830. const calls = registerEcho(ctx)
  831. const { agent, events } = fakeAgent()
  832. runtime.behavior = async (request) => {
  833. const args = Object.assign(Object.create(null) as Record<string, unknown>, { value: 'x', nested: ['same'] })
  834. await request.bindings[0]!.functions.echo!(args)
  835. return { logs: [] }
  836. }
  837. await runCode(ctx, 'program', { agent })
  838. expect(calls).toEqual([{ value: 'x', nested: ['same'] }])
  839. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  840. expect(dispatch.arguments).toEqual({ value: 'x', nested: ['same'] })
  841. })
  842. it('defers sub-call additionalContexts onto the outer run_code result', async () => {
  843. const { ctx, runtime } = await setup({ mode: 'code' })
  844. registerEcho(ctx)
  845. ctx.on('tools/post-execute', (exec, _result, next): Promise<PostToolDecision> => {
  846. if (exec.name === 'echo') {
  847. return Promise.resolve({
  848. kind: 'accept' as const,
  849. additionalContexts: [{
  850. content: [{ type: 'text' as const, text: `context for ${exec.callId}` }],
  851. source: { kind: 'plugin' as const, plugin: 'test' },
  852. meta: { callId: exec.callId },
  853. }],
  854. })
  855. }
  856. return next()
  857. })
  858. runtime.behavior = async (request) => {
  859. await request.bindings[0]!.functions.echo!({ value: 'x' })
  860. await request.bindings[0]!.functions.echo!({ value: 'y' })
  861. return { logs: [], value: 'done' }
  862. }
  863. const result = await runCode(ctx, 'program')
  864. expect(result.isError).toBe(false)
  865. expect(result.additionalContexts).toEqual([
  866. {
  867. content: [{ type: 'text', text: 'context for call-1:code:1' }],
  868. source: { kind: 'plugin', plugin: 'test' },
  869. meta: { callId: 'call-1:code:1' },
  870. },
  871. {
  872. content: [{ type: 'text', text: 'context for call-1:code:2' }],
  873. source: { kind: 'plugin', plugin: 'test' },
  874. meta: { callId: 'call-1:code:2' },
  875. },
  876. ])
  877. })
  878. it('keeps sub-call contexts when run_code fails after the nested dispatch', async () => {
  879. const { ctx, runtime } = await setup({ mode: 'both' })
  880. registerEcho(ctx)
  881. ctx.on('tools/post-execute', (exec, _result, next): Promise<PostToolDecision> => {
  882. if (exec.name !== 'echo') return next()
  883. return Promise.resolve({
  884. kind: 'accept',
  885. additionalContexts: [{
  886. content: [{ type: 'text', text: 'nested context' }],
  887. source: { kind: 'plugin', plugin: 'test' },
  888. }],
  889. })
  890. })
  891. runtime.behavior = async (request) => {
  892. await request.bindings[0]!.functions.echo!({ value: 'x' })
  893. return { logs: [], error: { kind: 'exception', message: 'program failed later' } }
  894. }
  895. const result = await runCode(ctx, 'program')
  896. expect(result.isError).toBe(true)
  897. expect(result.additionalContexts).toEqual([{
  898. content: [{ type: 'text', text: 'nested context' }],
  899. source: { kind: 'plugin', plugin: 'test' },
  900. }])
  901. })
  902. it('converts a failed run into a structured isError result carrying kind, message, and captured logs', async () => {
  903. const { ctx, runtime } = await setup({ mode: 'code' })
  904. runtime.behavior = () => Promise.resolve({
  905. logs: ['got this far'],
  906. error: { kind: 'timeout', message: 'compute budget exhausted (300ms busy)' },
  907. })
  908. const result = await runCode(ctx, 'program')
  909. expect(result.isError).toBe(true)
  910. expect(result.error).toMatchObject({ info: { name: 'CodeRunFailedError', code: 'CODE_RUN_FAILED' } })
  911. const text = (result.content[0] as { text: string }).text
  912. expect(text).toContain('code run failed (timeout)')
  913. expect(text).toContain('compute budget exhausted')
  914. expect(text).toContain('got this far')
  915. })
  916. it('CodeRunFailedError is a HarnessError with the CODE_RUN_FAILED code', () => {
  917. const error = new CodeRunFailedError('boom')
  918. expect(error.code).toBe('CODE_RUN_FAILED')
  919. expect(error.name).toBe('CodeRunFailedError')
  920. })
  921. it('aborting the outer signal aborts the in-flight sub-dispatch and abandons queued ones', async () => {
  922. const { ctx, runtime } = await setup({ mode: 'code' })
  923. const seen: string[] = []
  924. let sawAbort = false
  925. ctx.tools.register(defineContentToolFixture({
  926. name: 'slow',
  927. description: 'Slow tool observing its signal.',
  928. parameters: { id: { type: 'string', required: true } },
  929. async execute(args, exec) {
  930. seen.push(args.id)
  931. await new Promise<void>((resolve) => {
  932. const timer = setTimeout(resolve, 500)
  933. exec.signal.addEventListener('abort', () => { sawAbort = true; clearTimeout(timer); resolve() }, { once: true })
  934. })
  935. return [{ type: 'text' as const, text: args.id }]
  936. },
  937. }))
  938. const controller = new AbortController()
  939. runtime.behavior = async (request) => {
  940. const tools = request.bindings[0]!.functions
  941. const calls = [tools.slow!({ id: 'first' }).catch(() => 'rejected'), tools.slow!({ id: 'second' }).catch(() => 'rejected')]
  942. setTimeout(() => { controller.abort('user-cancel') }, 50)
  943. await Promise.all(calls)
  944. // A real runtime would be terminated by the abort; the fake honors the
  945. // contract by reporting the abort as the run failure.
  946. return { logs: [], error: { kind: 'abort', message: 'user-cancel' } }
  947. }
  948. const result = await runCode(ctx, 'program', { signal: controller.signal })
  949. expect(result.isError).toBe(true)
  950. expect((result.content[0] as { text: string }).text).toContain('code run failed (abort)')
  951. expect(seen).toEqual(['first'])
  952. expect(sawAbort).toBe(true)
  953. })
  954. it('a runtime that starts a binding call and then REJECTS still reaches quiescence before returning', async () => {
  955. const { ctx, runtime } = await setup({ mode: 'code' })
  956. const { agent, events } = fakeAgent()
  957. let sawAbort = false
  958. let started!: () => void
  959. const inFlight = new Promise<void>((resolve) => { started = resolve })
  960. ctx.tools.register(defineContentToolFixture({
  961. name: 'slow',
  962. description: 'Slow tool observing its signal.',
  963. parameters: { id: { type: 'string', required: true } },
  964. async execute(args, exec) {
  965. started()
  966. await new Promise<void>((resolve) => {
  967. const timer = setTimeout(resolve, 500)
  968. exec.signal.addEventListener('abort', () => { sawAbort = true; clearTimeout(timer); resolve() }, { once: true })
  969. })
  970. return [{ type: 'text' as const, text: args.id }]
  971. },
  972. }))
  973. runtime.behavior = async (request) => {
  974. // Start a sub-dispatch, keep its rejection held, and fail the run once the tool is
  975. // genuinely in flight — a seam error after work has begun.
  976. request.bindings[0]!.functions.slow!({ id: 'orphan' }).catch(() => 'held')
  977. await inFlight
  978. throw new Error('backend exploded')
  979. }
  980. const result = await runCode(ctx, 'program', { agent })
  981. expect(result.isError).toBe(true)
  982. expect((result.content[0] as { text: string }).text).toContain('backend exploded')
  983. // Quiescence held: the in-flight sub-dispatch was aborted and its event
  984. // logged INSIDE the run_code execution, not after it returned.
  985. expect(sawAbort).toBe(true)
  986. expect(events.filter(event => event.type === 'tool/code-dispatch').map(event => (event.data as { name: string }).name)).toEqual(['slow'])
  987. })
  988. it('runs without an owning agent: dispatches work, event logging is skipped', async () => {
  989. const { ctx, runtime } = await setup({ mode: 'code' })
  990. const calls = registerEcho(ctx)
  991. runtime.behavior = async (request) => {
  992. await request.bindings[0]!.functions.echo!({ value: 'x' })
  993. return { logs: [], value: 'ok' }
  994. }
  995. const result = await runCode(ctx, 'program')
  996. expect(result.isError).toBe(false)
  997. expect(calls).toEqual([{ value: 'x' }])
  998. })
  999. it('executing run_code under a missing runtime is a structured isError, not a crash', async () => {
  1000. const ctx = new Context()
  1001. await ctx.plugin(SystemPrompt, {})
  1002. await ctx.plugin(ToolRegistry, { mode: 'code' })
  1003. const result = await runCode(ctx, 'program')
  1004. expect(result.isError).toBe(true)
  1005. expect((result.content[0] as { text: string }).text).toContain('requires a code runtime')
  1006. })
  1007. it('presents the model-authored description as the execute-card title over the program input', async () => {
  1008. const { ctx } = await setup({ mode: 'code' })
  1009. const tool = ctx.tools.get(RUN_CODE_NAME)!
  1010. // The description labels the card (the bash description precedent); the
  1011. // program itself remains the expanded raw input.
  1012. expect(tool.presentCall?.({ code: 'return 1', description: 'Return the constant one' })).toEqual({
  1013. card: 'generic',
  1014. title: 'Return the constant one',
  1015. kind: 'execute',
  1016. rawInput: 'return 1',
  1017. })
  1018. })
  1019. it('rejects a whitespace-only description with a structured isError', async () => {
  1020. const { ctx } = await setup({ mode: 'code' })
  1021. const result = await runCode(ctx, 'return 1', { description: ' ' })
  1022. expect(result.isError).toBe(true)
  1023. expect((result.content[0] as { text: string }).text).toContain('invalid description')
  1024. })
  1025. it.each([
  1026. ['logs only', { logs: ['printed'] }, 'printed'],
  1027. ['result only', { logs: [], value: 'returned' }, 'returned'],
  1028. ['logs plus result', { logs: ['printed'], value: 'returned' }, 'printed\nreturned'],
  1029. ['no output', { logs: [] }, '(run_code completed with no output)'],
  1030. ] as [string, CodeRunResult, string][])('keeps %s in durable content without a result presenter', async (_name, output, text) => {
  1031. const { ctx, runtime } = await setup({ mode: 'code' })
  1032. runtime.behavior = () => Promise.resolve(output)
  1033. const result = await runCode(ctx, 'return 1')
  1034. const tool = ctx.tools.get(RUN_CODE_NAME)!
  1035. expect(result.content).toEqual([{ type: 'text', text }])
  1036. // Surfaces keep the pending program title and render this durable content
  1037. // through their generic fallback. Omitting a result view also prevents the
  1038. // host frame from carrying the same raw content a second time.
  1039. expect('presentResult' in tool).toBe(false)
  1040. })
  1041. it('keeps a post-policy spill preview in durable content without a result presenter', async () => {
  1042. const { ctx, runtime } = await setup({ mode: 'code' })
  1043. const preview = 'HEAD\n\n(Omitted 100 bytes. Full formatted result stored at: /tmp/run-code.txt.)\n\nTAIL'
  1044. runtime.behavior = () => Promise.resolve({ logs: ['printed'], value: 'returned' })
  1045. ctx.on('tools/post-execute', (exec, _result, next): Promise<PostToolDecision> => {
  1046. if (exec.name !== RUN_CODE_NAME) return next()
  1047. return Promise.resolve({ kind: 'accept', content: [{ type: 'text', text: preview }] })
  1048. })
  1049. const result = await runCode(ctx, 'return 1')
  1050. const tool = ctx.tools.get(RUN_CODE_NAME)!
  1051. expect(result.content).toEqual([{ type: 'text', text: preview }])
  1052. expect('presentResult' in tool).toBe(false)
  1053. })
  1054. it('keeps canonical failure content durable without a result presenter', async () => {
  1055. const { ctx, runtime } = await setup({ mode: 'code' })
  1056. runtime.behavior = () => Promise.resolve({
  1057. logs: ['captured before failure'],
  1058. error: { kind: 'output-limit', message: 'outer output exceeded 8 bytes' },
  1059. })
  1060. const result = await runCode(ctx, 'return 1')
  1061. const tool = ctx.tools.get(RUN_CODE_NAME)!
  1062. expect(result.isError).toBe(true)
  1063. expect(result.content).toEqual([{
  1064. type: 'text',
  1065. text: 'Error: code run failed (output-limit): outer output exceeded 8 bytes\nCaptured output:\ncaptured before failure',
  1066. }])
  1067. expect('presentResult' in tool).toBe(false)
  1068. })
  1069. it('logs the complete sub-result content verbatim, non-text blocks and long text included', async () => {
  1070. const { ctx, runtime } = await setup({ mode: 'code' })
  1071. const { agent, events } = fakeAgent()
  1072. const long = 'x'.repeat(300)
  1073. ctx.tools.register(defineTool({
  1074. name: 'mixed',
  1075. description: 'Returns mixed content.',
  1076. parameters: {},
  1077. output: {
  1078. schema: { type: 'string' },
  1079. render: () => [
  1080. { type: 'text', text: long },
  1081. { type: 'reasoning', text: 'hidden' },
  1082. ],
  1083. },
  1084. execute() {
  1085. return Promise.resolve('mixed-value')
  1086. },
  1087. }))
  1088. runtime.behavior = async (request) => {
  1089. const value = await request.bindings[0]!.functions.mixed!({})
  1090. return { logs: [], value }
  1091. }
  1092. const result = await runCode(ctx, 'program', { agent })
  1093. expect(result.isError).toBe(false)
  1094. expect((result.content[0] as { text: string }).text).toBe('mixed-value')
  1095. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  1096. expect(dispatch.content).toEqual([
  1097. { type: 'text', text: long },
  1098. { type: 'reasoning', text: 'hidden' },
  1099. ])
  1100. })
  1101. it('rejects undefined, getter-throwing, exotic, and unrepresentable binding arguments before dispatch', async () => {
  1102. const { ctx, runtime } = await setup({ mode: 'code' })
  1103. const calls = registerEcho(ctx)
  1104. const { agent, events } = fakeAgent()
  1105. runtime.behavior = async (request) => {
  1106. const echo = request.bindings[0]!.functions.echo!
  1107. const catchMessage = (promise: Promise<unknown>) => promise.then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error))
  1108. return {
  1109. logs: [],
  1110. value: [
  1111. // Root undefined must reject up front: the event log rejects it as
  1112. // data, and nothing may execute unlogged.
  1113. await catchMessage(echo(undefined)),
  1114. await catchMessage(echo(Object.defineProperty({}, 'bad', { enumerable: true, get() { throw 'raw-throw' } }))),
  1115. await catchMessage(echo(Object.defineProperty({}, 'bad', { enumerable: true, get() { throw new Error('error-throw') } }))),
  1116. await catchMessage(echo(new Date(0))),
  1117. // A bare function is a value JSON cannot represent at all.
  1118. await catchMessage(echo(() => 1)),
  1119. ].join(' | '),
  1120. }
  1121. }
  1122. const result = await runCode(ctx, 'program', { agent })
  1123. const text = (result.content[0] as { text: string }).text
  1124. expect(text).toContain('call the tool with an arguments object')
  1125. expect(text).toContain('lossless JSON: raw-throw')
  1126. expect(text).toContain('lossless JSON: error-throw')
  1127. expect(text.match(/tool arguments must be lossless JSON/g)).toHaveLength(5)
  1128. // None dispatched or logged.
  1129. expect(calls).toEqual([])
  1130. expect(events.filter(event => event.type === 'tool/code-dispatch')).toEqual([])
  1131. })
  1132. it('dispatches and durably logs binding arguments deeper than the structured-clone call stack', async () => {
  1133. const { ctx, runtime } = await setup({ mode: 'code' })
  1134. const depth = 5_000
  1135. let observedDepth = 0
  1136. let observedLeaf: JsonValue | undefined
  1137. ctx.tools.register(defineTool({
  1138. name: 'deep_args',
  1139. description: 'Measure a deeply nested JSON argument.',
  1140. parameters: { nested: { type: 'json', required: true } },
  1141. output: {
  1142. schema: { type: 'integer' },
  1143. render: (_args, value) => [{ type: 'text', text: String(value) }],
  1144. },
  1145. execute(args) {
  1146. let cursor = args.nested
  1147. while (Array.isArray(cursor)) {
  1148. if (cursor.length !== 1) throw new Error('expected one item per nesting layer')
  1149. observedDepth++
  1150. cursor = cursor[0]!
  1151. }
  1152. observedLeaf = cursor
  1153. return Promise.resolve(observedDepth)
  1154. },
  1155. }))
  1156. const session = new Session(SessionId('deep-code-arguments'))
  1157. const agent = { session } as Agent
  1158. runtime.behavior = async (request) => {
  1159. let nested: JsonValue = 'leaf'
  1160. for (let index = 0; index < depth; index++) nested = [nested]
  1161. const value = await request.bindings[0]!.functions.deep_args!({ nested })
  1162. return { logs: [], value }
  1163. }
  1164. const result = await runCode(ctx, 'return tools.deep_args(...)', { agent })
  1165. expect(result.isError).toBe(false)
  1166. expect(result.isError ? undefined : result.value).toEqual({ logs: [], result: depth })
  1167. expect({ observedDepth, observedLeaf }).toEqual({ observedDepth: depth, observedLeaf: 'leaf' })
  1168. const dispatch = session.events.find(event => event.type === 'tool/code-dispatch')
  1169. if (dispatch === undefined) throw new Error('expected a durable tool/code-dispatch event')
  1170. const logged = dispatch.data.arguments as { nested: JsonValue }
  1171. let loggedDepth = 0
  1172. let loggedCursor = logged.nested
  1173. while (Array.isArray(loggedCursor)) {
  1174. if (loggedCursor.length !== 1) throw new Error('expected one logged item per nesting layer')
  1175. loggedDepth++
  1176. loggedCursor = loggedCursor[0]!
  1177. }
  1178. expect({ loggedDepth, loggedCursor }).toEqual({ loggedDepth: depth, loggedCursor: 'leaf' })
  1179. })
  1180. it('gives the tool and durable log the same immutable argument value', async () => {
  1181. const { ctx, runtime } = await setup({ mode: 'code' })
  1182. const { agent, events } = fakeAgent()
  1183. let mutationSucceeded: boolean | undefined
  1184. ctx.tools.register(defineContentToolFixture({
  1185. name: 'mutator',
  1186. description: 'Attempts to mutate its args object.',
  1187. parameters: { list: { type: 'array', required: true } },
  1188. execute(args) {
  1189. mutationSucceeded = Reflect.set(args.list, 1, 'injected-by-tool')
  1190. return Promise.resolve([{ type: 'text' as const, text: 'protected' }])
  1191. },
  1192. }))
  1193. runtime.behavior = async (request) => {
  1194. await request.bindings[0]!.functions.mutator!({ list: ['original'] })
  1195. return { logs: [] }
  1196. }
  1197. const result = await runCode(ctx, 'program', { agent })
  1198. expect(result.isError).toBe(false)
  1199. expect(mutationSucceeded).toBe(false)
  1200. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  1201. expect(dispatch.arguments).toEqual({ list: ['original'] })
  1202. })
  1203. it('exposes a tool named __proto__ as an ordinary own binding', async () => {
  1204. const { ctx, runtime } = await setup({ mode: 'code' })
  1205. ctx.tools.register(defineTool({
  1206. name: '__proto__',
  1207. description: 'A prototype-colliding tool name.',
  1208. parameters: {},
  1209. output: {
  1210. schema: { type: 'string' },
  1211. render: (_args, value) => [{ type: 'text', text: value }],
  1212. },
  1213. execute() { return Promise.resolve('proto-tool-ok') },
  1214. }))
  1215. runtime.behavior = async (request) => {
  1216. const functions = request.bindings[0]!.functions
  1217. expect(Object.getPrototypeOf(functions)).toBeNull()
  1218. const value = await functions['__proto__']!({})
  1219. return { logs: [], value }
  1220. }
  1221. const result = await runCode(ctx, 'program')
  1222. expect(result.isError).toBe(false)
  1223. expect(result.content[0]).toEqual({ type: 'text', text: 'proto-tool-ok' })
  1224. })
  1225. it('renders every non-string JSON root as pretty JSON while preserving strings raw', async () => {
  1226. const { ctx, runtime } = await setup({ mode: 'code' })
  1227. runtime.behavior = () => Promise.resolve({ logs: [], value: { n: 42, ok: true } })
  1228. expect((await runCode(ctx, 'object')).content[0]).toEqual({ type: 'text', text: '{\n "n": 42,\n "ok": true\n}' })
  1229. runtime.behavior = () => Promise.resolve({ logs: [], value: {} })
  1230. expect((await runCode(ctx, 'empty object')).content[0]).toEqual({ type: 'text', text: '{}' })
  1231. const nested = { outer: [{ inner: true }] }
  1232. runtime.behavior = () => Promise.resolve({ logs: [], value: nested })
  1233. expect((await runCode(ctx, 'nested')).content[0]).toEqual({ type: 'text', text: JSON.stringify(nested, null, 2) })
  1234. runtime.behavior = () => Promise.resolve({ logs: [], value: ['x', 2] })
  1235. expect((await runCode(ctx, 'array')).content[0]).toEqual({ type: 'text', text: '[\n "x",\n 2\n]' })
  1236. runtime.behavior = () => Promise.resolve({ logs: [], value: [] })
  1237. expect((await runCode(ctx, 'empty array')).content[0]).toEqual({ type: 'text', text: '[]' })
  1238. runtime.behavior = () => Promise.resolve({ logs: [], value: null })
  1239. expect((await runCode(ctx, 'null')).content[0]).toEqual({ type: 'text', text: 'null' })
  1240. runtime.behavior = () => Promise.resolve({ logs: [], value: 'raw' })
  1241. expect((await runCode(ctx, 'string')).content[0]).toEqual({ type: 'text', text: 'raw' })
  1242. runtime.behavior = () => Promise.resolve({ logs: [] })
  1243. const absent = await runCode(ctx, 'undefined')
  1244. expect(absent.content[0]).toEqual({ type: 'text', text: '(run_code completed with no output)' })
  1245. expect(absent.isError ? undefined : absent.value).toEqual({ logs: [] })
  1246. })
  1247. it('renders deeply nested JSON without recursive traversal or quadratic indentation', async () => {
  1248. const { ctx, runtime } = await setup({ mode: 'code' })
  1249. let value: JsonValue = {
  1250. emptyArray: [],
  1251. emptyObject: {},
  1252. pair: ['leaf', 2],
  1253. record: { first: true, second: null },
  1254. }
  1255. for (let depth = 0; depth < 5_000; depth++) value = [value]
  1256. runtime.behavior = () => Promise.resolve({ logs: [], value })
  1257. const result = await runCode(ctx, 'deep result')
  1258. expect(result.isError).toBe(false)
  1259. const text = (result.content[0] as { type: 'text'; text: string }).text
  1260. expect(text.startsWith('[\n [\n [')).toBe(true)
  1261. expect(text).toContain('"leaf"')
  1262. expect(text.endsWith(']')).toBe(true)
  1263. expect(text.length).toBeLessThan(11_000)
  1264. })
  1265. it('short-circuits a pre-aborted outer signal before the code runtime', async () => {
  1266. const { ctx, runtime } = await setup({ mode: 'code' })
  1267. const calls = registerEcho(ctx)
  1268. runtime.behavior = (request) => {
  1269. // The fake honors the seam contract for an already-aborted signal.
  1270. if (request.signal?.aborted) return Promise.resolve({ logs: [], error: { kind: 'abort' as const, message: String(request.signal.reason) } })
  1271. return Promise.resolve({ logs: [], value: 'unreachable' })
  1272. }
  1273. const controller = new AbortController()
  1274. controller.abort('too-late')
  1275. const result = await runCode(ctx, 'program', { signal: controller.signal })
  1276. expect(result.isError).toBe(true)
  1277. expect(result).toEqual({
  1278. content: [{ type: 'text', text: 'Error: tool call aborted before dispatch' }],
  1279. isError: true,
  1280. error: {
  1281. message: 'tool call aborted before dispatch',
  1282. info: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH },
  1283. },
  1284. })
  1285. expect(runtime.lastRequest).toBeUndefined()
  1286. expect(calls).toEqual([])
  1287. })
  1288. it('reports cancellation after rejecting a late binding without dispatching it', async () => {
  1289. const { ctx, runtime } = await setup({ mode: 'code' })
  1290. const calls = registerEcho(ctx)
  1291. const controller = new AbortController()
  1292. runtime.behavior = async (request) => {
  1293. controller.abort('cancelled-mid-run')
  1294. const message = await request.bindings[0]!.functions.echo!({ value: 'x' })
  1295. .then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error))
  1296. return { logs: [], value: message }
  1297. }
  1298. const result = await runCode(ctx, 'program', { signal: controller.signal })
  1299. expect(result.isError).toBe(true)
  1300. expect(result.error).toEqual({
  1301. message: 'tool call aborted',
  1302. info: { name: 'AbortError', code: 'ABORTED' },
  1303. })
  1304. expect((result.content[0] as { text: string }).text).toBe('Error: tool call aborted')
  1305. expect(calls).toEqual([])
  1306. })
  1307. it('a tool/code-dispatch event never derives a model message', () => {
  1308. const session = new Session(SessionId('code-mode-derive'))
  1309. session.append('user/message', { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  1310. session.append('tool/code-dispatch', {
  1311. parentCallId: CallId('p1'),
  1312. subCallId: CallId('p1:code:1'),
  1313. name: 'echo',
  1314. arguments: { value: 'x' },
  1315. isError: false,
  1316. content: [{ type: 'text', text: 'echo:x' }],
  1317. })
  1318. const derived = session.deriveMessages()
  1319. expect(derived).toHaveLength(1)
  1320. expect(derived[0]?.role).toBe('user')
  1321. })
  1322. it('direct construction rejects a non-positive parallel sub-call cap at load', async () => {
  1323. const ctx = new Context()
  1324. await ctx.plugin(SystemPrompt, {})
  1325. expect(() => new ToolRegistry(ctx, { mode: 'code', maxParallelSubCalls: 0 }))
  1326. .toThrow('maxParallelSubCalls must be a positive integer')
  1327. })
  1328. it('direct construction in code mode defaults the parallel sub-call cap', async () => {
  1329. const ctx = new Context()
  1330. await ctx.plugin(SystemPrompt, {})
  1331. const registry = new ToolRegistry(ctx, { mode: 'code' })
  1332. expect(registry.get(RUN_CODE_NAME)).toBeDefined()
  1333. })
  1334. it('defaults to native mode under direct construction with no config', async () => {
  1335. const ctx = new Context()
  1336. await ctx.plugin(SystemPrompt, {})
  1337. const registry = new ToolRegistry(ctx)
  1338. expect(registry.get(RUN_CODE_NAME)).toBeUndefined()
  1339. const assembly = await ctx.systemPrompt.assemble()
  1340. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  1341. })
  1342. })