code-mode.spec.ts 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  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, defineContentToolFixture, defineTool } from '@deepseek-ai/dsh-tools'
  10. import type { Config, 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 { SessionEventMap } from '@deepseek-ai/dsh-session'
  14. /**
  15. * Code Mode unit tier (per the Agent Note's plan): provider contribution per mode,
  16. * misconfiguration rejections, the run_code dispatch bridge (serialization,
  17. * abort, JSON normalization, error mapping, events, quiescence), and HMR
  18. * safety — all against an in-repo fake runtime, exactly the
  19. * interface/implementation/consumer shape the seam promises.
  20. */
  21. /** A scriptable in-repo CodeRuntime: each test sets `behavior` to drive the bindings however it needs. */
  22. class FakeRuntime extends CodeRuntime {
  23. readonly language: string
  24. readonly isolation = 'fake'
  25. behavior: (request: CodeRunRequest) => Promise<CodeRunResult> = () => Promise.resolve({ logs: [] })
  26. lastRequest?: CodeRunRequest
  27. constructor(ctx: Context, config: { language?: string } = {}) {
  28. super(ctx)
  29. this.language = config.language ?? 'typescript'
  30. }
  31. run(request: CodeRunRequest): Promise<CodeRunResult> {
  32. this.lastRequest = request
  33. return this.behavior(request)
  34. }
  35. }
  36. interface SetupOptions {
  37. mode?: Config['mode']
  38. runtime?: false | { language?: string }
  39. toolOrder?: string[]
  40. }
  41. async function setup(options: SetupOptions = {}) {
  42. const ctx = new Context()
  43. await ctx.plugin(SystemPrompt, { ...options.toolOrder ? { toolOrder: options.toolOrder } : {} })
  44. await ctx.plugin(ToolRegistry, { mode: options.mode ?? 'code' })
  45. let runtime: FakeRuntime | undefined
  46. if (options.runtime !== false) {
  47. await ctx.plugin(FakeRuntime, options.runtime ?? {})
  48. runtime = ctx.codeRuntime as FakeRuntime
  49. }
  50. return { ctx, tools: ctx.tools, systemPrompt: ctx.systemPrompt, runtime: runtime! }
  51. }
  52. /** Mint one production-shaped agent scope that can register scoped tool policy. */
  53. async function mintAgentScope(ctx: Context, name = 'scoped'): Promise<{ scope: Scope; agent: Agent }> {
  54. const agent = { id: SessionId(name) } as Agent
  55. let scope!: Scope
  56. await ctx.plugin(Object.assign((inner: Context) => { scope = createScope(inner, agent) },
  57. { inject: ['tools', 'systemPrompt'] }))
  58. return { scope, agent }
  59. }
  60. /** Register a trivial echo tool; returns the calls it received. */
  61. function registerEcho(ctx: Context, name = 'echo'): unknown[] {
  62. const calls: unknown[] = []
  63. ctx.tools.register(defineTool({
  64. name,
  65. description: `Echo tool ${name}.`,
  66. parameters: { value: { type: 'string', required: true } },
  67. output: {
  68. schema: { type: 'string' },
  69. render: (_args, value) => [{ type: 'text', text: value }],
  70. },
  71. execute(args) {
  72. calls.push(args)
  73. return Promise.resolve(`${name}:${args.value}`)
  74. },
  75. }))
  76. return calls
  77. }
  78. /** A structural fake of the owning agent: captures session appends. */
  79. function fakeAgent(options: { cwd?: string } = { cwd: '/workspace' }): { agent: Agent; events: { type: string; data: unknown }[] } {
  80. const events: { type: string; data: unknown }[] = []
  81. const agent = {
  82. session: {
  83. header: options.cwd === undefined ? {} : { cwd: options.cwd },
  84. append: (type: string, data: unknown) => { events.push({ type, data }) },
  85. },
  86. } as unknown as Agent
  87. return { agent, events }
  88. }
  89. /** Dispatch run_code through the registry pipeline, as the loop would. */
  90. async function runCode(ctx: Context, code: string, extras: { agent?: Agent; signal?: AbortSignal } = {}): Promise<ToolExecutionResult> {
  91. return ctx.tools.execute({
  92. callId: CallId('call-1'),
  93. name: RUN_CODE_NAME,
  94. arguments: { code },
  95. ...extras.agent ? { agent: extras.agent } : {},
  96. ...extras.signal ? { signal: extras.signal } : {},
  97. })
  98. }
  99. describe('mode-aware wire contribution', () => {
  100. it("mode 'native' contributes every schema, no run_code, no SDK section — and needs no runtime", async () => {
  101. const { ctx, systemPrompt } = await setup({ mode: 'native', runtime: false })
  102. registerEcho(ctx)
  103. const assembly = await systemPrompt.assemble()
  104. expect(assembly.tools.map(tool => tool.name)).toEqual(['echo'])
  105. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  106. })
  107. it("mode 'code' contributes exactly [run_code] plus the SDK section declaring the other tools", async () => {
  108. const { ctx, systemPrompt } = await setup({ mode: 'code' })
  109. registerEcho(ctx)
  110. const assembly = await systemPrompt.assemble()
  111. expect(assembly.tools.map(tool => tool.name)).toEqual([RUN_CODE_NAME])
  112. const sdk = assembly.sections.find(section => section.name === 'tools:sdk')
  113. expect(sdk?.text).toContain('declare const tools: {')
  114. expect(sdk?.text).toContain('echo: {')
  115. expect(sdk?.text).not.toContain('run_code:')
  116. })
  117. it.each(['code', 'both'] as const)('treats expert assembly output as authoritative in mode %s', async (mode) => {
  118. const { ctx, systemPrompt } = await setup({ mode })
  119. registerEcho(ctx)
  120. ctx.on('system-prompt/assemble', async (_assembly, _context, next) => {
  121. const assembly = await next()
  122. return {
  123. ...assembly,
  124. sections: assembly.sections.filter(section => section.name !== 'tools:sdk'),
  125. tools: assembly.tools.filter(tool => tool.name !== RUN_CODE_NAME),
  126. }
  127. }, { prepend: true })
  128. const assembly = await systemPrompt.assemble()
  129. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  130. expect(assembly.tools.some(tool => tool.name === RUN_CODE_NAME)).toBe(false)
  131. })
  132. it.each(['code', 'both'] as const)('lets one scope shadow the default SDK section in mode %s', async (mode) => {
  133. const { ctx, systemPrompt } = await setup({ mode })
  134. registerEcho(ctx)
  135. const { scope, agent } = await mintAgentScope(ctx)
  136. scope.ctx.systemPrompt.section({ name: 'tools:sdk', order: 150, text: 'SCOPED SDK' })
  137. const scoped = await systemPrompt.assemble({ scope: agent })
  138. const global = await systemPrompt.assemble()
  139. expect(scoped.sections.find(section => section.name === 'tools:sdk')?.text).toBe('SCOPED SDK')
  140. expect(global.sections.find(section => section.name === 'tools:sdk')?.text).toContain('declare const tools:')
  141. })
  142. it("mode 'both' contributes every native schema plus run_code, and the SDK section", async () => {
  143. const { ctx, systemPrompt } = await setup({ mode: 'both' })
  144. registerEcho(ctx)
  145. const assembly = await systemPrompt.assemble()
  146. expect(assembly.tools.map(tool => tool.name)).toEqual(['echo', RUN_CODE_NAME])
  147. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(true)
  148. })
  149. it.each(['code', 'both'] as const)('keeps the run_code transport outside scoped allow-list filtering in mode %s', async (mode) => {
  150. const { ctx, systemPrompt, runtime } = await setup({ mode })
  151. registerEcho(ctx, 'echo')
  152. registerEcho(ctx, 'hidden')
  153. const { scope, agent } = await mintAgentScope(ctx)
  154. const lift = scope.ctx.tools.restrict({ allow: ['echo'] })
  155. const assembly = await systemPrompt.assemble({ scope: agent })
  156. expect(assembly.tools.map(tool => tool.name)).toEqual(mode === 'code'
  157. ? [RUN_CODE_NAME]
  158. : ['echo', RUN_CODE_NAME])
  159. const sdk = assembly.sections.find(section => section.name === 'tools:sdk')?.text
  160. expect(sdk).toContain('echo: {')
  161. expect(sdk).not.toContain('hidden:')
  162. runtime.behavior = request => Promise.resolve({
  163. logs: [],
  164. value: Object.keys(request.bindings[0]!.functions).sort().join(','),
  165. })
  166. const result = await runCode(ctx, 'return Object.keys(tools)', { agent })
  167. expect(result.isError).toBe(false)
  168. expect(result.content).toEqual([{ type: 'text', text: 'echo' }])
  169. lift()
  170. const unrestricted = await systemPrompt.assemble({ scope: agent })
  171. expect(unrestricted.tools.map(tool => tool.name)).toEqual(mode === 'code'
  172. ? [RUN_CODE_NAME]
  173. : ['echo', 'hidden', RUN_CODE_NAME])
  174. })
  175. it.each(['code', 'both'] as const)('keeps the run_code transport outside scoped deny-list filtering in mode %s', async (mode) => {
  176. const { ctx, systemPrompt, runtime } = await setup({ mode })
  177. registerEcho(ctx, 'denied')
  178. registerEcho(ctx, 'kept')
  179. const { scope, agent } = await mintAgentScope(ctx)
  180. scope.ctx.tools.restrict({ deny: ['denied'] })
  181. const assembly = await systemPrompt.assemble({ scope: agent })
  182. expect(assembly.tools.map(tool => tool.name)).toEqual(mode === 'code'
  183. ? [RUN_CODE_NAME]
  184. : ['kept', RUN_CODE_NAME])
  185. const sdk = assembly.sections.find(section => section.name === 'tools:sdk')?.text
  186. expect(sdk).not.toContain('denied:')
  187. expect(sdk).toContain('kept: {')
  188. runtime.behavior = request => Promise.resolve({
  189. logs: [],
  190. value: Object.keys(request.bindings[0]!.functions).sort().join(','),
  191. })
  192. const result = await runCode(ctx, 'return Object.keys(tools)', { agent })
  193. expect(result.isError).toBe(false)
  194. expect(result.content).toEqual([{ type: 'text', text: 'kept' }])
  195. })
  196. it.each(['code', 'both'] as const)('reserves run_code against scoped shadows and explicit restrictions in mode %s', async (mode) => {
  197. const { ctx, systemPrompt } = await setup({ mode })
  198. const { scope, agent } = await mintAgentScope(ctx)
  199. const impostor = defineContentToolFixture({
  200. name: RUN_CODE_NAME,
  201. description: 'Scoped impostor.',
  202. parameters: {},
  203. execute: () => Promise.resolve([{ type: 'text' as const, text: 'impostor' }]),
  204. })
  205. expect(() => scope.ctx.tools.register(impostor)).toThrow(/reserved for the Code Mode presentation transport/)
  206. expect(() => ctx.tools.register(impostor)).toThrow(/reserved for the Code Mode presentation transport/)
  207. expect(() => scope.ctx.tools.restrict({ allow: [RUN_CODE_NAME] })).toThrow(/cannot name reserved Code Mode presentation transport/)
  208. expect(() => scope.ctx.tools.restrict({ deny: [RUN_CODE_NAME] })).toThrow(/cannot name reserved Code Mode presentation transport/)
  209. scope.ctx.systemPrompt.section({ name: 'scoped-note', order: 149, text: 'safe note' })
  210. scope.ctx.tools.register(defineContentToolFixture({
  211. name: 'scoped_safe',
  212. description: 'Safe scoped tool.',
  213. parameters: {},
  214. execute: () => Promise.resolve([{ type: 'text' as const, text: 'safe' }]),
  215. }))
  216. const assembly = await systemPrompt.assemble({ scope: agent })
  217. const transports = assembly.tools.filter(tool => tool.name === RUN_CODE_NAME)
  218. expect(transports).toHaveLength(1)
  219. expect(transports[0]?.description).toContain('Execute a TypeScript program')
  220. expect(assembly.sections.find(section => section.name === 'scoped-note')?.text).toBe('safe note')
  221. expect(assembly.sections.find(section => section.name === 'tools:sdk')?.text).toContain('scoped_safe:')
  222. expect(ctx.tools.get(RUN_CODE_NAME, agent)).toBe(ctx.tools.get(RUN_CODE_NAME))
  223. const result = await runCode(ctx, 'return 1', { agent })
  224. expect(result.content).toEqual([{ type: 'text', text: '(run_code completed with no output)' }])
  225. })
  226. 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) => {
  227. const { ctx, systemPrompt } = await setup({
  228. mode,
  229. toolOrder: [RUN_CODE_NAME, '<unlisted-tools>'],
  230. })
  231. registerEcho(ctx)
  232. const { agent } = await mintAgentScope(ctx)
  233. const assembly = await systemPrompt.assemble({ scope: agent })
  234. expect(assembly.tools.map(tool => tool.name)).toEqual(mode === 'code'
  235. ? [RUN_CODE_NAME]
  236. : [RUN_CODE_NAME, 'echo'])
  237. })
  238. it("never exposes run_code to programs, even under mode 'both' (no recursive dispatch path)", async () => {
  239. const { ctx, runtime } = await setup({ mode: 'both' })
  240. registerEcho(ctx)
  241. runtime.behavior = (request) => {
  242. const functions = request.bindings[0]!.functions
  243. return Promise.resolve({
  244. logs: [],
  245. value: JSON.stringify({
  246. names: Object.keys(functions).sort(),
  247. // Own-property AND prototype-chain reads both come back empty —
  248. // there is no handle a program could re-enter run_code through.
  249. runCode: String(functions[RUN_CODE_NAME]),
  250. }),
  251. })
  252. }
  253. const result = await runCode(ctx, 'program')
  254. expect(result.isError).toBe(false)
  255. expect(JSON.parse((result.content[0] as { text: string }).text)).toEqual({ names: ['echo'], runCode: 'undefined' })
  256. })
  257. it('renders byte-identical SDK text across consecutive assemblies of an unchanged tool set', async () => {
  258. const { ctx, systemPrompt } = await setup({ mode: 'code' })
  259. registerEcho(ctx)
  260. const first = await systemPrompt.assemble()
  261. const second = await systemPrompt.assemble()
  262. const text = (assembly: typeof first) => assembly.sections.find(section => section.name === 'tools:sdk')?.text
  263. expect(text(first)).toBe(text(second))
  264. })
  265. it('rejects every assembly when a non-native mode has no code runtime', async () => {
  266. const { systemPrompt } = await setup({ mode: 'code', runtime: false })
  267. await expect(systemPrompt.assemble()).rejects.toThrow(/requires a code runtime/)
  268. })
  269. it("rejects every assembly when the runtime's language is not typescript", async () => {
  270. const { systemPrompt } = await setup({ mode: 'code', runtime: { language: 'python' } })
  271. await expect(systemPrompt.assemble()).rejects.toThrow(/language is "python"/)
  272. })
  273. it("rejects the assembly when toolOrder names a native tool that mode 'code' no longer contributes", async () => {
  274. const { ctx, systemPrompt } = await setup({ mode: 'code', toolOrder: ['echo', '<unlisted-tools>'] })
  275. registerEcho(ctx)
  276. await expect(systemPrompt.assemble()).rejects.toThrow(/toolOrder lists unregistered tool "echo"/)
  277. })
  278. it('removes run_code and the SDK section when the registry fiber disposes (HMR safety)', async () => {
  279. const ctx = new Context()
  280. await ctx.plugin(SystemPrompt, {})
  281. await ctx.plugin(FakeRuntime, {})
  282. const fiber = await ctx.plugin(ToolRegistry, { mode: 'code' })
  283. expect(ctx.tools.get(RUN_CODE_NAME)).toBeDefined()
  284. await fiber.dispose()
  285. const assembly = await ctx.systemPrompt.assemble()
  286. expect(assembly.tools).toEqual([])
  287. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  288. })
  289. })
  290. describe('the run_code dispatch bridge', () => {
  291. it('bridges tool calls, returns only the curated output, and logs one event per dispatch', async () => {
  292. const { ctx, runtime } = await setup({ mode: 'code' })
  293. const calls = registerEcho(ctx)
  294. const { agent, events } = fakeAgent()
  295. runtime.behavior = async (request) => {
  296. const tools = request.bindings[0]!.functions
  297. const first = await tools.echo!({ value: 'one' })
  298. const second = await tools.echo!({ value: 'two' })
  299. if (typeof first !== 'string' || typeof second !== 'string') throw new Error('echo returned a non-string')
  300. return { logs: [`saw ${first}`], value: second }
  301. }
  302. const result = await runCode(ctx, 'const …: string = …', { agent })
  303. expect(result.isError).toBe(false)
  304. if (result.isError) throw new Error('expected run_code success')
  305. expect(result.value).toEqual({ logs: ['saw echo:one'], result: 'echo:two' })
  306. expect(result.content).toEqual([{ type: 'text', text: 'saw echo:one\necho:two' }])
  307. expect(calls).toEqual([{ value: 'one' }, { value: 'two' }])
  308. const dispatches = events.filter(event => event.type === 'tool/code-dispatch')
  309. expect(dispatches.map(event => event.data)).toEqual([
  310. { parentCallId: 'call-1', subCallId: 'call-1:code:1', name: 'echo', arguments: { value: 'one' }, isError: false, resultSummary: 'echo:one' },
  311. { parentCallId: 'call-1', subCallId: 'call-1:code:2', name: 'echo', arguments: { value: 'two' }, isError: false, resultSummary: 'echo:two' },
  312. ])
  313. expect(result.meta).toBeUndefined()
  314. })
  315. it('exposes only an opaque parent token to nested result observers', async () => {
  316. const { ctx, runtime } = await setup({ mode: 'code' })
  317. registerEcho(ctx)
  318. runtime.behavior = async (request) => {
  319. await request.bindings[0]!.functions.echo!({ value: 'nested' })
  320. return { logs: [], value: 'done' }
  321. }
  322. // Freeze the nested observer's parent correlation. If that were the live
  323. // outer execution object, the timeout-style wrapper could not restore it.
  324. ctx.on('tools/execute', async (exec, next) => {
  325. if (exec.name !== RUN_CODE_NAME) return next()
  326. const previous = exec.signal
  327. exec.signal = new AbortController().signal
  328. const result = await next()
  329. if (previous === undefined) delete exec.signal
  330. else exec.signal = previous
  331. return result
  332. })
  333. ctx.on('tools/result', (exec) => {
  334. if (exec.parent !== undefined) Object.freeze(exec.parent)
  335. })
  336. const result = await runCode(ctx, 'await tools.echo({ value: "nested" })')
  337. expect(result.isError).toBe(false)
  338. expect(result.content).toEqual([{ type: 'text', text: 'done' }])
  339. })
  340. it('serializes Promise.all dispatches: tool executions never overlap, in submission order', async () => {
  341. const { ctx, runtime } = await setup({ mode: 'code' })
  342. const intervals: [string, string][] = []
  343. let active = 0
  344. ctx.tools.register(defineTool({
  345. name: 'probe',
  346. description: 'Records execution overlap.',
  347. parameters: { id: { type: 'string', required: true } },
  348. output: {
  349. schema: { type: 'string' },
  350. render: (_args, value) => [{ type: 'text', text: value }],
  351. },
  352. async execute(args) {
  353. active++
  354. expect(active, 'probe executions overlapped').toBe(1)
  355. intervals.push(['enter', args.id])
  356. await new Promise(resolve => setTimeout(resolve, 20))
  357. intervals.push(['exit', args.id])
  358. active--
  359. return args.id
  360. },
  361. }))
  362. runtime.behavior = async (request) => {
  363. const tools = request.bindings[0]!.functions
  364. const values = await Promise.all([tools.probe!({ id: 'a' }), tools.probe!({ id: 'b' }), tools.probe!({ id: 'c' })])
  365. if (!values.every(value => typeof value === 'string')) throw new Error('probe returned a non-string')
  366. return { logs: [], value: values.join(',') }
  367. }
  368. const result = await runCode(ctx, 'program')
  369. expect(result.isError).toBe(false)
  370. expect(intervals).toEqual([
  371. ['enter', 'a'], ['exit', 'a'],
  372. ['enter', 'b'], ['exit', 'b'],
  373. ['enter', 'c'], ['exit', 'c'],
  374. ])
  375. expect(result.content[0]).toEqual({ type: 'text', text: 'a,b,c' })
  376. })
  377. it('rejects the program-side call when the tool errors, with the tool error text', async () => {
  378. const { ctx, runtime } = await setup({ mode: 'code' })
  379. ctx.tools.register(defineContentToolFixture({
  380. name: 'fail',
  381. description: 'Always fails.',
  382. parameters: {},
  383. execute(): Promise<never> { return Promise.reject(new Error('deliberate failure')) },
  384. }))
  385. runtime.behavior = async (request) => {
  386. try {
  387. await request.bindings[0]!.functions.fail!({})
  388. return { logs: [], value: 'unreachable' }
  389. } catch (error: unknown) {
  390. return { logs: [], value: `caught: ${error instanceof Error ? error.message : String(error)}` }
  391. }
  392. }
  393. const result = await runCode(ctx, 'program')
  394. expect(result.content[0]).toEqual({ type: 'text', text: 'caught: deliberate failure' })
  395. })
  396. it('a tools/pre-execute deny reaches the program as a binding rejection', async () => {
  397. const { ctx, runtime } = await setup({ mode: 'code' })
  398. registerEcho(ctx)
  399. ctx.on('tools/pre-execute', (exec, next) => {
  400. if (exec.name === 'echo') return Promise.resolve({ kind: 'deny' as const, reason: 'not on my watch' })
  401. return next()
  402. })
  403. runtime.behavior = async (request) => {
  404. try {
  405. await request.bindings[0]!.functions.echo!({ value: 'x' })
  406. return { logs: [], value: 'unreachable' }
  407. } catch (error: unknown) {
  408. return { logs: [], value: `denied: ${error instanceof Error ? error.message : String(error)}` }
  409. }
  410. }
  411. const result = await runCode(ctx, 'program')
  412. expect(result.content[0]?.type).toBe('text')
  413. expect((result.content[0] as { text: string }).text).toContain('not on my watch')
  414. })
  415. it('rejects a binding argument that is not lossless JSON, dispatching nothing', async () => {
  416. const { ctx, runtime } = await setup({ mode: 'code' })
  417. const calls = registerEcho(ctx)
  418. const { agent, events } = fakeAgent()
  419. runtime.behavior = async (request) => {
  420. try {
  421. await request.bindings[0]!.functions.echo!({ value: 'x', big: 1n })
  422. return { logs: [], value: 'unreachable' }
  423. } catch (error: unknown) {
  424. return { logs: [], value: error instanceof Error ? error.message : String(error) }
  425. }
  426. }
  427. const result = await runCode(ctx, 'program', { agent })
  428. expect((result.content[0] as { text: string }).text).toContain('lossless JSON')
  429. expect(calls).toEqual([])
  430. expect(events.filter(event => event.type === 'tool/code-dispatch')).toEqual([])
  431. })
  432. it('dispatches and logs independent snapshots of the same lossless JSON value', async () => {
  433. const { ctx, runtime } = await setup({ mode: 'code' })
  434. const calls = registerEcho(ctx)
  435. const { agent, events } = fakeAgent()
  436. runtime.behavior = async (request) => {
  437. const args = Object.assign(Object.create(null) as Record<string, unknown>, { value: 'x', nested: ['same'] })
  438. await request.bindings[0]!.functions.echo!(args)
  439. return { logs: [] }
  440. }
  441. await runCode(ctx, 'program', { agent })
  442. expect(calls).toEqual([{ value: 'x', nested: ['same'] }])
  443. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  444. expect(dispatch.arguments).toEqual({ value: 'x', nested: ['same'] })
  445. })
  446. it('defers sub-call additionalContexts onto the outer run_code result', async () => {
  447. const { ctx, runtime } = await setup({ mode: 'code' })
  448. registerEcho(ctx)
  449. ctx.on('tools/post-execute', (exec, _result, next): Promise<PostToolDecision> => {
  450. if (exec.name === 'echo') {
  451. return Promise.resolve({
  452. kind: 'accept' as const,
  453. additionalContexts: [{
  454. content: [{ type: 'text' as const, text: `context for ${exec.callId}` }],
  455. source: { kind: 'plugin' as const, plugin: 'test' },
  456. meta: { callId: exec.callId },
  457. }],
  458. })
  459. }
  460. return next()
  461. })
  462. runtime.behavior = async (request) => {
  463. await request.bindings[0]!.functions.echo!({ value: 'x' })
  464. await request.bindings[0]!.functions.echo!({ value: 'y' })
  465. return { logs: [], value: 'done' }
  466. }
  467. const result = await runCode(ctx, 'program')
  468. expect(result.isError).toBe(false)
  469. expect(result.additionalContexts).toEqual([
  470. {
  471. content: [{ type: 'text', text: 'context for call-1:code:1' }],
  472. source: { kind: 'plugin', plugin: 'test' },
  473. meta: { callId: 'call-1:code:1' },
  474. },
  475. {
  476. content: [{ type: 'text', text: 'context for call-1:code:2' }],
  477. source: { kind: 'plugin', plugin: 'test' },
  478. meta: { callId: 'call-1:code:2' },
  479. },
  480. ])
  481. })
  482. it('keeps sub-call contexts when run_code fails after the nested dispatch', async () => {
  483. const { ctx, runtime } = await setup({ mode: 'both' })
  484. registerEcho(ctx)
  485. ctx.on('tools/post-execute', (exec, _result, next): Promise<PostToolDecision> => {
  486. if (exec.name !== 'echo') return next()
  487. return Promise.resolve({
  488. kind: 'accept',
  489. additionalContexts: [{
  490. content: [{ type: 'text', text: 'nested context' }],
  491. source: { kind: 'plugin', plugin: 'test' },
  492. }],
  493. })
  494. })
  495. runtime.behavior = async (request) => {
  496. await request.bindings[0]!.functions.echo!({ value: 'x' })
  497. return { logs: [], error: { kind: 'exception', message: 'program failed later' } }
  498. }
  499. const result = await runCode(ctx, 'program')
  500. expect(result.isError).toBe(true)
  501. expect(result.additionalContexts).toEqual([{
  502. content: [{ type: 'text', text: 'nested context' }],
  503. source: { kind: 'plugin', plugin: 'test' },
  504. }])
  505. })
  506. it('converts a failed run into a structured isError result carrying kind, message, and captured logs', async () => {
  507. const { ctx, runtime } = await setup({ mode: 'code' })
  508. runtime.behavior = () => Promise.resolve({
  509. logs: ['got this far'],
  510. error: { kind: 'timeout', message: 'compute budget exhausted (300ms busy)' },
  511. })
  512. const result = await runCode(ctx, 'program')
  513. expect(result.isError).toBe(true)
  514. expect(result.error).toMatchObject({ info: { name: 'CodeRunFailedError', code: 'CODE_RUN_FAILED' } })
  515. const text = (result.content[0] as { text: string }).text
  516. expect(text).toContain('code run failed (timeout)')
  517. expect(text).toContain('compute budget exhausted')
  518. expect(text).toContain('got this far')
  519. })
  520. it('CodeRunFailedError is a HarnessError with the CODE_RUN_FAILED code', () => {
  521. const error = new CodeRunFailedError('boom')
  522. expect(error.code).toBe('CODE_RUN_FAILED')
  523. expect(error.name).toBe('CodeRunFailedError')
  524. })
  525. it('aborting the outer signal aborts the in-flight sub-dispatch and abandons queued ones', async () => {
  526. const { ctx, runtime } = await setup({ mode: 'code' })
  527. const seen: string[] = []
  528. let sawAbort = false
  529. ctx.tools.register(defineContentToolFixture({
  530. name: 'slow',
  531. description: 'Slow tool observing its signal.',
  532. parameters: { id: { type: 'string', required: true } },
  533. async execute(args, exec) {
  534. seen.push(args.id)
  535. await new Promise<void>((resolve) => {
  536. const timer = setTimeout(resolve, 500)
  537. exec.signal?.addEventListener('abort', () => { sawAbort = true; clearTimeout(timer); resolve() }, { once: true })
  538. })
  539. return [{ type: 'text' as const, text: args.id }]
  540. },
  541. }))
  542. const controller = new AbortController()
  543. runtime.behavior = async (request) => {
  544. const tools = request.bindings[0]!.functions
  545. const calls = [tools.slow!({ id: 'first' }).catch(() => 'rejected'), tools.slow!({ id: 'second' }).catch(() => 'rejected')]
  546. setTimeout(() => { controller.abort('user-cancel') }, 50)
  547. await Promise.all(calls)
  548. // A real runtime would be terminated by the abort; the fake honors the
  549. // contract by reporting the abort as the run failure.
  550. return { logs: [], error: { kind: 'abort', message: 'user-cancel' } }
  551. }
  552. const result = await runCode(ctx, 'program', { signal: controller.signal })
  553. expect(result.isError).toBe(true)
  554. expect((result.content[0] as { text: string }).text).toContain('code run failed (abort)')
  555. expect(seen).toEqual(['first'])
  556. expect(sawAbort).toBe(true)
  557. })
  558. it('a runtime that starts a binding call and then REJECTS still reaches quiescence before returning', async () => {
  559. const { ctx, runtime } = await setup({ mode: 'code' })
  560. const { agent, events } = fakeAgent()
  561. let sawAbort = false
  562. let started!: () => void
  563. const inFlight = new Promise<void>((resolve) => { started = resolve })
  564. ctx.tools.register(defineContentToolFixture({
  565. name: 'slow',
  566. description: 'Slow tool observing its signal.',
  567. parameters: { id: { type: 'string', required: true } },
  568. async execute(args, exec) {
  569. started()
  570. await new Promise<void>((resolve) => {
  571. const timer = setTimeout(resolve, 500)
  572. exec.signal?.addEventListener('abort', () => { sawAbort = true; clearTimeout(timer); resolve() }, { once: true })
  573. })
  574. return [{ type: 'text' as const, text: args.id }]
  575. },
  576. }))
  577. runtime.behavior = async (request) => {
  578. // Start a sub-dispatch, keep its rejection held, and fail the run once the tool is
  579. // genuinely in flight — a seam error after work has begun.
  580. request.bindings[0]!.functions.slow!({ id: 'orphan' }).catch(() => 'held')
  581. await inFlight
  582. throw new Error('backend exploded')
  583. }
  584. const result = await runCode(ctx, 'program', { agent })
  585. expect(result.isError).toBe(true)
  586. expect((result.content[0] as { text: string }).text).toContain('backend exploded')
  587. // Quiescence held: the in-flight sub-dispatch was aborted and its event
  588. // logged INSIDE the run_code execution, not after it returned.
  589. expect(sawAbort).toBe(true)
  590. expect(events.filter(event => event.type === 'tool/code-dispatch').map(event => (event.data as { name: string }).name)).toEqual(['slow'])
  591. })
  592. it('runs without an owning agent: dispatches work, event logging is skipped', async () => {
  593. const { ctx, runtime } = await setup({ mode: 'code' })
  594. const calls = registerEcho(ctx)
  595. runtime.behavior = async (request) => {
  596. await request.bindings[0]!.functions.echo!({ value: 'x' })
  597. return { logs: [], value: 'ok' }
  598. }
  599. const result = await runCode(ctx, 'program')
  600. expect(result.isError).toBe(false)
  601. expect(calls).toEqual([{ value: 'x' }])
  602. })
  603. it('executing run_code under a missing runtime is a structured isError, not a crash', async () => {
  604. const ctx = new Context()
  605. await ctx.plugin(SystemPrompt, {})
  606. await ctx.plugin(ToolRegistry, { mode: 'code' })
  607. const result = await runCode(ctx, 'program')
  608. expect(result.isError).toBe(true)
  609. expect((result.content[0] as { text: string }).text).toContain('requires a code runtime')
  610. })
  611. it('presents the program as the execute-card title', async () => {
  612. const { ctx } = await setup({ mode: 'code' })
  613. const tool = ctx.tools.get(RUN_CODE_NAME)!
  614. // The program IS the title, mirroring how command tools title their cards
  615. // with the command: an ACP client's execute-card header is the only
  616. // always-visible slot (Zed renders no body content and no raw input for
  617. // execute-kind cards without a real terminal).
  618. expect(tool.presentCall?.({ code: 'return 1' })).toEqual({
  619. card: 'generic',
  620. title: 'return 1',
  621. kind: 'execute',
  622. rawInput: 'return 1',
  623. })
  624. })
  625. it.each([
  626. ['logs only', 'printed', false],
  627. ['result only', 'returned', false],
  628. ['logs plus result', 'printed\nreturned', false],
  629. ['no output', '(run_code completed with no output)', false],
  630. ['spilled result', 'HEAD\n\n(Omitted 100 bytes. Full formatted result stored at: /tmp/run-code.txt.)\n\nTAIL', false],
  631. ] as const)('presents %s from the final post-policy content', async (_name, text, isError) => {
  632. const { ctx } = await setup({ mode: 'code' })
  633. const tool = ctx.tools.get(RUN_CODE_NAME)!
  634. // The result omits the title — an update replaces only provided fields,
  635. // so the pending card's program title persists through completion.
  636. const content = [{ type: 'text' as const, text }]
  637. expect(tool.presentResult?.({ code: 'return 1' }, {
  638. content,
  639. isError,
  640. // Stale or unrelated metadata must not replace the authoritative
  641. // post-policy content used by the card.
  642. meta: { logs: ['stale logs-only projection'] },
  643. })).toEqual({ card: 'generic', content })
  644. })
  645. it('presents failure content produced by the canonical execution pipeline', async () => {
  646. const { ctx, runtime } = await setup({ mode: 'code' })
  647. runtime.behavior = () => Promise.resolve({
  648. logs: ['captured before failure'],
  649. error: { kind: 'output-limit', message: 'outer output exceeded 8 bytes' },
  650. })
  651. const result = await runCode(ctx, 'return 1')
  652. const tool = ctx.tools.get(RUN_CODE_NAME)!
  653. expect(result.isError).toBe(true)
  654. expect(result.content).toEqual([{
  655. type: 'text',
  656. text: 'Error: code run failed (output-limit): outer output exceeded 8 bytes\nCaptured output:\ncaptured before failure',
  657. }])
  658. expect(tool.presentResult?.({ code: 'return 1' }, result)).toEqual({
  659. card: 'generic',
  660. content: result.content,
  661. })
  662. })
  663. it('renders non-text sub-result blocks as placeholders and truncates long event summaries', async () => {
  664. const { ctx, runtime } = await setup({ mode: 'code' })
  665. const { agent, events } = fakeAgent()
  666. const long = 'x'.repeat(300)
  667. ctx.tools.register(defineTool({
  668. name: 'mixed',
  669. description: 'Returns mixed content.',
  670. parameters: {},
  671. output: {
  672. schema: { type: 'string' },
  673. render: () => [
  674. { type: 'text', text: long },
  675. { type: 'reasoning', text: 'hidden' },
  676. ],
  677. },
  678. execute() {
  679. return Promise.resolve('mixed-value')
  680. },
  681. }))
  682. runtime.behavior = async (request) => {
  683. const value = await request.bindings[0]!.functions.mixed!({})
  684. return { logs: [], value }
  685. }
  686. const result = await runCode(ctx, 'program', { agent })
  687. expect(result.isError).toBe(false)
  688. expect((result.content[0] as { text: string }).text).toBe('mixed-value')
  689. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  690. expect(dispatch.resultSummary.length).toBe(201)
  691. expect(dispatch.resultSummary.endsWith('…')).toBe(true)
  692. })
  693. it('normalizes the session workspace root before bounding durable result summaries', async () => {
  694. const { ctx, runtime } = await setup({ mode: 'code' })
  695. ctx.tools.register(defineTool({
  696. name: 'workspace_path',
  697. description: 'Return a path beneath the session workspace.',
  698. parameters: {},
  699. output: {
  700. schema: { type: 'string' },
  701. render: (_args, value) => [{ type: 'text', text: value }],
  702. },
  703. execute(_args, exec) {
  704. const cwd = exec.agent?.session.header.cwd ?? ''
  705. return Promise.resolve(`<path>${cwd}/nested/task.txt</path>\n${'x'.repeat(240)}`)
  706. },
  707. }))
  708. runtime.behavior = async request => ({
  709. logs: [],
  710. value: await request.bindings[0]!.functions.workspace_path!({}),
  711. })
  712. const short = fakeAgent({ cwd: '/tmp/workspace' })
  713. const long = fakeAgent({ cwd: `/tmp/${'long-segment/'.repeat(30)}workspace` })
  714. const shortResult = await runCode(ctx, 'program', { agent: short.agent })
  715. const longResult = await runCode(ctx, 'program', { agent: long.agent })
  716. const shortDispatch = short.events[0]!.data as SessionEventMap['tool/code-dispatch']
  717. const longDispatch = long.events[0]!.data as SessionEventMap['tool/code-dispatch']
  718. expect(shortResult.content).not.toEqual(longResult.content)
  719. expect(shortDispatch.resultSummary).toBe(longDispatch.resultSummary)
  720. expect(shortDispatch.resultSummary).toHaveLength(201)
  721. expect(shortDispatch.resultSummary).toMatch(/^<path>\.\/nested\/task\.txt<\/path>\n.+…$/)
  722. })
  723. it('leaves result summaries unchanged when a session cwd is absent or is the filesystem root', async () => {
  724. const { ctx, runtime } = await setup({ mode: 'code' })
  725. registerEcho(ctx)
  726. runtime.behavior = async request => ({
  727. logs: [],
  728. value: await request.bindings[0]!.functions.echo!({ value: '/workspace/value' }),
  729. })
  730. const absent = fakeAgent({})
  731. const root = fakeAgent({ cwd: '/' })
  732. await runCode(ctx, 'program', { agent: absent.agent })
  733. await runCode(ctx, 'program', { agent: root.agent })
  734. expect((absent.events[0]!.data as SessionEventMap['tool/code-dispatch']).resultSummary).toBe('echo:/workspace/value')
  735. expect((root.events[0]!.data as SessionEventMap['tool/code-dispatch']).resultSummary).toBe('echo:/workspace/value')
  736. })
  737. it('rejects undefined, getter-throwing, exotic, and unrepresentable binding arguments before dispatch', async () => {
  738. const { ctx, runtime } = await setup({ mode: 'code' })
  739. const calls = registerEcho(ctx)
  740. const { agent, events } = fakeAgent()
  741. runtime.behavior = async (request) => {
  742. const echo = request.bindings[0]!.functions.echo!
  743. const catchMessage = (promise: Promise<unknown>) => promise.then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error))
  744. return {
  745. logs: [],
  746. value: [
  747. // Root undefined must reject up front: the event log rejects it as
  748. // data, and nothing may execute unlogged.
  749. await catchMessage(echo(undefined)),
  750. await catchMessage(echo(Object.defineProperty({}, 'bad', { enumerable: true, get() { throw 'raw-throw' } }))),
  751. await catchMessage(echo(Object.defineProperty({}, 'bad', { enumerable: true, get() { throw new Error('error-throw') } }))),
  752. await catchMessage(echo(new Date(0))),
  753. // A bare function is a value JSON cannot represent at all.
  754. await catchMessage(echo(() => 1)),
  755. ].join(' | '),
  756. }
  757. }
  758. const result = await runCode(ctx, 'program', { agent })
  759. const text = (result.content[0] as { text: string }).text
  760. expect(text).toContain('call the tool with an arguments object')
  761. expect(text).toContain('lossless JSON: raw-throw')
  762. expect(text).toContain('lossless JSON: error-throw')
  763. expect(text.match(/tool arguments must be lossless JSON/g)).toHaveLength(5)
  764. // None dispatched or logged.
  765. expect(calls).toEqual([])
  766. expect(events.filter(event => event.type === 'tool/code-dispatch')).toEqual([])
  767. })
  768. it('gives the tool and durable log the same immutable argument value', async () => {
  769. const { ctx, runtime } = await setup({ mode: 'code' })
  770. const { agent, events } = fakeAgent()
  771. let mutationSucceeded: boolean | undefined
  772. ctx.tools.register(defineContentToolFixture({
  773. name: 'mutator',
  774. description: 'Attempts to mutate its args object.',
  775. parameters: { list: { type: 'array', required: true } },
  776. execute(args) {
  777. mutationSucceeded = Reflect.set(args.list, 1, 'injected-by-tool')
  778. return Promise.resolve([{ type: 'text' as const, text: 'protected' }])
  779. },
  780. }))
  781. runtime.behavior = async (request) => {
  782. await request.bindings[0]!.functions.mutator!({ list: ['original'] })
  783. return { logs: [] }
  784. }
  785. const result = await runCode(ctx, 'program', { agent })
  786. expect(result.isError).toBe(false)
  787. expect(mutationSucceeded).toBe(false)
  788. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  789. expect(dispatch.arguments).toEqual({ list: ['original'] })
  790. })
  791. it('exposes a tool named __proto__ as an ordinary own binding', async () => {
  792. const { ctx, runtime } = await setup({ mode: 'code' })
  793. ctx.tools.register(defineTool({
  794. name: '__proto__',
  795. description: 'A prototype-colliding tool name.',
  796. parameters: {},
  797. output: {
  798. schema: { type: 'string' },
  799. render: (_args, value) => [{ type: 'text', text: value }],
  800. },
  801. execute() { return Promise.resolve('proto-tool-ok') },
  802. }))
  803. runtime.behavior = async (request) => {
  804. const functions = request.bindings[0]!.functions
  805. expect(Object.getPrototypeOf(functions)).toBeNull()
  806. const value = await functions['__proto__']!({})
  807. return { logs: [], value }
  808. }
  809. const result = await runCode(ctx, 'program')
  810. expect(result.isError).toBe(false)
  811. expect(result.content[0]).toEqual({ type: 'text', text: 'proto-tool-ok' })
  812. })
  813. it('renders every non-string JSON root as pretty JSON while preserving strings raw', async () => {
  814. const { ctx, runtime } = await setup({ mode: 'code' })
  815. runtime.behavior = () => Promise.resolve({ logs: [], value: { n: 42 } })
  816. expect((await runCode(ctx, 'object')).content[0]).toEqual({ type: 'text', text: '{\n "n": 42\n}' })
  817. runtime.behavior = () => Promise.resolve({ logs: [], value: ['x', 2] })
  818. expect((await runCode(ctx, 'array')).content[0]).toEqual({ type: 'text', text: '[\n "x",\n 2\n]' })
  819. runtime.behavior = () => Promise.resolve({ logs: [], value: null })
  820. expect((await runCode(ctx, 'null')).content[0]).toEqual({ type: 'text', text: 'null' })
  821. runtime.behavior = () => Promise.resolve({ logs: [], value: 'raw' })
  822. expect((await runCode(ctx, 'string')).content[0]).toEqual({ type: 'text', text: 'raw' })
  823. runtime.behavior = () => Promise.resolve({ logs: [] })
  824. const absent = await runCode(ctx, 'undefined')
  825. expect(absent.content[0]).toEqual({ type: 'text', text: '(run_code completed with no output)' })
  826. expect(absent.isError ? undefined : absent.value).toEqual({ logs: [] })
  827. })
  828. it('reports a pre-aborted outer signal as the run failure without dispatching anything', async () => {
  829. const { ctx, runtime } = await setup({ mode: 'code' })
  830. const calls = registerEcho(ctx)
  831. runtime.behavior = (request) => {
  832. // The fake honors the seam contract for an already-aborted signal.
  833. if (request.signal?.aborted) return Promise.resolve({ logs: [], error: { kind: 'abort' as const, message: String(request.signal.reason) } })
  834. return Promise.resolve({ logs: [], value: 'unreachable' })
  835. }
  836. const controller = new AbortController()
  837. controller.abort('too-late')
  838. const result = await runCode(ctx, 'program', { signal: controller.signal })
  839. expect(result.isError).toBe(true)
  840. expect((result.content[0] as { text: string }).text).toContain('code run failed (abort)')
  841. expect(calls).toEqual([])
  842. })
  843. it('rejects a binding invoked after the run is over without dispatching it', async () => {
  844. const { ctx, runtime } = await setup({ mode: 'code' })
  845. const calls = registerEcho(ctx)
  846. const controller = new AbortController()
  847. runtime.behavior = async (request) => {
  848. controller.abort('cancelled-mid-run')
  849. const message = await request.bindings[0]!.functions.echo!({ value: 'x' })
  850. .then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error))
  851. return { logs: [], value: message }
  852. }
  853. const result = await runCode(ctx, 'program', { signal: controller.signal })
  854. expect(result.isError).toBe(false)
  855. expect((result.content[0] as { text: string }).text).toContain('not dispatched')
  856. expect(calls).toEqual([])
  857. })
  858. it('a tool/code-dispatch event never derives a model message', () => {
  859. const session = new Session(SessionId('code-mode-derive'))
  860. session.append('user/message', { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  861. session.append('tool/code-dispatch', {
  862. parentCallId: CallId('p1'),
  863. subCallId: CallId('p1:code:1'),
  864. name: 'echo',
  865. arguments: { value: 'x' },
  866. isError: false,
  867. resultSummary: 'echo:x',
  868. })
  869. const derived = session.deriveMessages()
  870. expect(derived).toHaveLength(1)
  871. expect(derived[0]?.role).toBe('user')
  872. })
  873. it('defaults to native mode under direct construction with no config', async () => {
  874. const ctx = new Context()
  875. await ctx.plugin(SystemPrompt, {})
  876. const registry = new ToolRegistry(ctx)
  877. expect(registry.get(RUN_CODE_NAME)).toBeUndefined()
  878. const assembly = await ctx.systemPrompt.assemble()
  879. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  880. })
  881. })