code-mode.spec.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { CallId } from '@deepseek-ai/dsh-llm'
  4. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  5. import { CodeRuntime } from '@deepseek-ai/dsh-code-runtime'
  6. import type { CodeRunRequest, CodeRunResult } from '@deepseek-ai/dsh-code-runtime'
  7. import ToolRegistry, { CodeRunFailedError, RUN_CODE_NAME, defineTool } from '@deepseek-ai/dsh-tools'
  8. import type { Config, PostToolDecision, ToolExecutionResult } from '@deepseek-ai/dsh-tools'
  9. import type { Agent } from '@deepseek-ai/dsh-agent'
  10. import { Session, SessionId } from '@deepseek-ai/dsh-session'
  11. import type { SessionEventMap } from '@deepseek-ai/dsh-session'
  12. /**
  13. * Code Mode unit tier (per the RFC's plan): provider contribution per mode,
  14. * misconfiguration rejections, the run_code dispatch bridge (serialization,
  15. * abort, JSON normalization, error mapping, events, quiescence), and HMR
  16. * safety — all against an in-repo fake runtime, exactly the
  17. * interface/implementation/consumer shape the seam promises.
  18. */
  19. /** A scriptable in-repo CodeRuntime: each test sets `behavior` to drive the bindings however it needs. */
  20. class FakeRuntime extends CodeRuntime {
  21. readonly language: string
  22. readonly isolation = 'fake'
  23. behavior: (request: CodeRunRequest) => Promise<CodeRunResult> = () => Promise.resolve({ logs: [] })
  24. lastRequest?: CodeRunRequest
  25. constructor(ctx: Context, config: { language?: string } = {}) {
  26. super(ctx)
  27. this.language = config.language ?? 'typescript'
  28. }
  29. run(request: CodeRunRequest): Promise<CodeRunResult> {
  30. this.lastRequest = request
  31. return this.behavior(request)
  32. }
  33. }
  34. interface SetupOptions {
  35. mode?: Config['mode']
  36. runtime?: false | { language?: string }
  37. toolOrder?: string[]
  38. }
  39. async function setup(options: SetupOptions = {}) {
  40. const ctx = new Context()
  41. await ctx.plugin(SystemPrompt, { ...options.toolOrder ? { toolOrder: options.toolOrder } : {} })
  42. await ctx.plugin(ToolRegistry, { mode: options.mode ?? 'code' })
  43. let runtime: FakeRuntime | undefined
  44. if (options.runtime !== false) {
  45. await ctx.plugin(FakeRuntime, options.runtime ?? {})
  46. runtime = ctx.codeRuntime as FakeRuntime
  47. }
  48. return { ctx, tools: ctx.tools, systemPrompt: ctx.systemPrompt, runtime: runtime! }
  49. }
  50. /** Register a trivial echo tool; returns the calls it received. */
  51. function registerEcho(ctx: Context, name = 'echo'): unknown[] {
  52. const calls: unknown[] = []
  53. ctx.tools.register(defineTool({
  54. name,
  55. description: `Echo tool ${name}.`,
  56. parameters: { value: { type: 'string', required: true } },
  57. execute(args) {
  58. calls.push(args)
  59. return Promise.resolve([{ type: 'text' as const, text: `${name}:${args.value}` }])
  60. },
  61. }))
  62. return calls
  63. }
  64. /** A structural fake of the owning agent: captures session appends. */
  65. function fakeAgent(): { agent: Agent; events: { type: string; data: unknown }[] } {
  66. const events: { type: string; data: unknown }[] = []
  67. const agent = {
  68. session: {
  69. append: (type: string, data: unknown) => { events.push({ type, data }) },
  70. },
  71. } as unknown as Agent
  72. return { agent, events }
  73. }
  74. /** Dispatch run_code through the registry pipeline, as the loop would. */
  75. async function runCode(ctx: Context, code: string, extras: { agent?: Agent; signal?: AbortSignal } = {}): Promise<ToolExecutionResult> {
  76. return ctx.tools.execute({
  77. callId: CallId('call-1'),
  78. name: RUN_CODE_NAME,
  79. arguments: { code },
  80. ...extras.agent ? { agent: extras.agent } : {},
  81. ...extras.signal ? { signal: extras.signal } : {},
  82. })
  83. }
  84. describe('mode-aware wire contribution', () => {
  85. it("mode 'native' contributes every schema, no run_code, no SDK section — and needs no runtime", async () => {
  86. const { ctx, systemPrompt } = await setup({ mode: 'native', runtime: false })
  87. registerEcho(ctx)
  88. const assembly = await systemPrompt.assemble()
  89. expect(assembly.tools.map(tool => tool.name)).toEqual(['echo'])
  90. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  91. })
  92. it("mode 'code' contributes exactly [run_code] plus the SDK section declaring the other tools", async () => {
  93. const { ctx, systemPrompt } = await setup({ mode: 'code' })
  94. registerEcho(ctx)
  95. const assembly = await systemPrompt.assemble()
  96. expect(assembly.tools.map(tool => tool.name)).toEqual([RUN_CODE_NAME])
  97. const sdk = assembly.sections.find(section => section.name === 'tools:sdk')
  98. expect(sdk?.text).toContain('declare const tools: {')
  99. expect(sdk?.text).toContain('echo(args:')
  100. expect(sdk?.text).not.toContain('run_code(args:')
  101. })
  102. it("mode 'both' contributes every native schema plus run_code, and the SDK section", async () => {
  103. const { ctx, systemPrompt } = await setup({ mode: 'both' })
  104. registerEcho(ctx)
  105. const assembly = await systemPrompt.assemble()
  106. expect(assembly.tools.map(tool => tool.name)).toEqual(['echo', RUN_CODE_NAME])
  107. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(true)
  108. })
  109. it("never exposes run_code to programs, even under mode 'both' (no recursive dispatch path)", async () => {
  110. const { ctx, runtime } = await setup({ mode: 'both' })
  111. registerEcho(ctx)
  112. runtime.behavior = (request) => {
  113. const functions = request.bindings[0]!.functions
  114. return Promise.resolve({
  115. logs: [],
  116. value: JSON.stringify({
  117. names: Object.keys(functions).sort(),
  118. // Own-property AND prototype-chain reads both come back empty —
  119. // there is no handle a program could re-enter run_code through.
  120. runCode: String(functions[RUN_CODE_NAME]),
  121. }),
  122. })
  123. }
  124. const result = await runCode(ctx, 'program')
  125. expect(result.isError).toBe(false)
  126. expect(JSON.parse((result.content[0] as { text: string }).text)).toEqual({ names: ['echo'], runCode: 'undefined' })
  127. })
  128. it('renders byte-identical SDK text across consecutive assemblies of an unchanged tool set', async () => {
  129. const { ctx, systemPrompt } = await setup({ mode: 'code' })
  130. registerEcho(ctx)
  131. const first = await systemPrompt.assemble()
  132. const second = await systemPrompt.assemble()
  133. const text = (assembly: typeof first) => assembly.sections.find(section => section.name === 'tools:sdk')?.text
  134. expect(text(first)).toBe(text(second))
  135. })
  136. it('rejects every assembly when a non-native mode has no code runtime', async () => {
  137. const { systemPrompt } = await setup({ mode: 'code', runtime: false })
  138. await expect(systemPrompt.assemble()).rejects.toThrow(/requires a code runtime/)
  139. })
  140. it("rejects every assembly when the runtime's language is not typescript", async () => {
  141. const { systemPrompt } = await setup({ mode: 'code', runtime: { language: 'python' } })
  142. await expect(systemPrompt.assemble()).rejects.toThrow(/language is "python"/)
  143. })
  144. it("rejects the assembly when toolOrder names a native tool that mode 'code' no longer contributes", async () => {
  145. const { ctx, systemPrompt } = await setup({ mode: 'code', toolOrder: ['echo', '<unlisted-tools>'] })
  146. registerEcho(ctx)
  147. await expect(systemPrompt.assemble()).rejects.toThrow(/toolOrder lists unregistered tool "echo"/)
  148. })
  149. it('removes run_code and the SDK section when the registry fiber disposes (HMR safety)', async () => {
  150. const ctx = new Context()
  151. await ctx.plugin(SystemPrompt, {})
  152. await ctx.plugin(FakeRuntime, {})
  153. const fiber = await ctx.plugin(ToolRegistry, { mode: 'code' })
  154. expect(ctx.tools.get(RUN_CODE_NAME)).toBeDefined()
  155. await fiber.dispose()
  156. const assembly = await ctx.systemPrompt.assemble()
  157. expect(assembly.tools).toEqual([])
  158. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  159. })
  160. })
  161. describe('the run_code dispatch bridge', () => {
  162. it('bridges tool calls, returns only the curated output, and logs one event per dispatch', async () => {
  163. const { ctx, runtime } = await setup({ mode: 'code' })
  164. const calls = registerEcho(ctx)
  165. const { agent, events } = fakeAgent()
  166. runtime.behavior = async (request) => {
  167. const tools = request.bindings[0]!.functions
  168. const first = await tools.echo!({ value: 'one' })
  169. const second = await tools.echo!({ value: 'two' })
  170. return { logs: [{ source: 'console', level: 'log', text: `saw ${String(first)}` }], value: second }
  171. }
  172. const result = await runCode(ctx, 'const …: string = …', { agent })
  173. expect(result.isError).toBe(false)
  174. expect(result.content).toEqual([{ type: 'text', text: 'saw echo:one\necho:two' }])
  175. expect(calls).toEqual([{ value: 'one' }, { value: 'two' }])
  176. const dispatches = events.filter(event => event.type === 'tool/code-dispatch')
  177. expect(dispatches.map(event => event.data)).toEqual([
  178. { parentCallId: 'call-1', subCallId: 'call-1:code:1', name: 'echo', arguments: { value: 'one' }, isError: false, resultSummary: 'echo:one' },
  179. { parentCallId: 'call-1', subCallId: 'call-1:code:2', name: 'echo', arguments: { value: 'two' }, isError: false, resultSummary: 'echo:two' },
  180. ])
  181. expect(result.meta).toEqual({ logs: [{ source: 'console', level: 'log', text: 'saw echo:one' }], dispatches: 2 })
  182. })
  183. it('serializes Promise.all dispatches: tool executions never overlap, in submission order', async () => {
  184. const { ctx, runtime } = await setup({ mode: 'code' })
  185. const intervals: [string, string][] = []
  186. let active = 0
  187. ctx.tools.register(defineTool({
  188. name: 'probe',
  189. description: 'Records execution overlap.',
  190. parameters: { id: { type: 'string', required: true } },
  191. async execute(args) {
  192. active++
  193. expect(active, 'probe executions overlapped').toBe(1)
  194. intervals.push(['enter', args.id])
  195. await new Promise(resolve => setTimeout(resolve, 20))
  196. intervals.push(['exit', args.id])
  197. active--
  198. return [{ type: 'text' as const, text: args.id }]
  199. },
  200. }))
  201. runtime.behavior = async (request) => {
  202. const tools = request.bindings[0]!.functions
  203. const values = await Promise.all([tools.probe!({ id: 'a' }), tools.probe!({ id: 'b' }), tools.probe!({ id: 'c' })])
  204. return { logs: [], value: values.join(',') }
  205. }
  206. const result = await runCode(ctx, 'program')
  207. expect(result.isError).toBe(false)
  208. expect(intervals).toEqual([
  209. ['enter', 'a'], ['exit', 'a'],
  210. ['enter', 'b'], ['exit', 'b'],
  211. ['enter', 'c'], ['exit', 'c'],
  212. ])
  213. expect(result.content[0]).toEqual({ type: 'text', text: 'a,b,c' })
  214. })
  215. it('rejects the program-side call when the tool errors, with the tool error text', async () => {
  216. const { ctx, runtime } = await setup({ mode: 'code' })
  217. ctx.tools.register(defineTool({
  218. name: 'fail',
  219. description: 'Always fails.',
  220. parameters: {},
  221. execute(): Promise<never> { return Promise.reject(new Error('deliberate failure')) },
  222. }))
  223. runtime.behavior = async (request) => {
  224. try {
  225. await request.bindings[0]!.functions.fail!({})
  226. return { logs: [], value: 'unreachable' }
  227. } catch (error: unknown) {
  228. return { logs: [], value: `caught: ${error instanceof Error ? error.message : String(error)}` }
  229. }
  230. }
  231. const result = await runCode(ctx, 'program')
  232. expect(result.content[0]).toEqual({ type: 'text', text: 'caught: Error: deliberate failure' })
  233. })
  234. it('a tools/pre-execute deny reaches the program as a binding rejection', async () => {
  235. const { ctx, runtime } = await setup({ mode: 'code' })
  236. registerEcho(ctx)
  237. ctx.on('tools/pre-execute', (exec, next) => {
  238. if (exec.name === 'echo') return Promise.resolve({ kind: 'deny' as const, reason: 'not on my watch' })
  239. return next()
  240. })
  241. runtime.behavior = async (request) => {
  242. try {
  243. await request.bindings[0]!.functions.echo!({ value: 'x' })
  244. return { logs: [], value: 'unreachable' }
  245. } catch (error: unknown) {
  246. return { logs: [], value: `denied: ${error instanceof Error ? error.message : String(error)}` }
  247. }
  248. }
  249. const result = await runCode(ctx, 'program')
  250. expect(result.content[0]?.type).toBe('text')
  251. expect((result.content[0] as { text: string }).text).toContain('not on my watch')
  252. })
  253. it('rejects a binding argument that does not survive JSON normalization, dispatching nothing', async () => {
  254. const { ctx, runtime } = await setup({ mode: 'code' })
  255. const calls = registerEcho(ctx)
  256. const { agent, events } = fakeAgent()
  257. runtime.behavior = async (request) => {
  258. try {
  259. await request.bindings[0]!.functions.echo!({ value: 'x', big: 1n })
  260. return { logs: [], value: 'unreachable' }
  261. } catch (error: unknown) {
  262. return { logs: [], value: error instanceof Error ? error.message : String(error) }
  263. }
  264. }
  265. const result = await runCode(ctx, 'program', { agent })
  266. expect((result.content[0] as { text: string }).text).toContain('JSON-serializable')
  267. expect(calls).toEqual([])
  268. expect(events.filter(event => event.type === 'tool/code-dispatch')).toEqual([])
  269. })
  270. it('dispatches the JSON-normalized value: what the tool sees is what the event logs', async () => {
  271. const { ctx, runtime } = await setup({ mode: 'code' })
  272. const calls = registerEcho(ctx)
  273. const { agent, events } = fakeAgent()
  274. runtime.behavior = async (request) => {
  275. // A Date survives structured clone but is not JSON; the bridge
  276. // normalizes it to its JSON form (an ISO string) BEFORE dispatch.
  277. await request.bindings[0]!.functions.echo!({ value: 'x', when: new Date(0) }).catch(() => undefined)
  278. return { logs: [] }
  279. }
  280. await runCode(ctx, 'program', { agent })
  281. expect(calls).toEqual([{ value: 'x', when: '1970-01-01T00:00:00.000Z' }])
  282. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  283. expect(dispatch.arguments).toEqual({ value: 'x', when: '1970-01-01T00:00:00.000Z' })
  284. })
  285. it('suppresses sub-call additionalContext (deliberately; pinned)', async () => {
  286. const { ctx, runtime } = await setup({ mode: 'code' })
  287. registerEcho(ctx)
  288. ctx.on('tools/post-execute', (exec, _result, next): Promise<PostToolDecision> => {
  289. if (exec.name === 'echo') {
  290. return Promise.resolve({
  291. kind: 'accept' as const,
  292. additionalContext: { content: [{ type: 'text' as const, text: 'context for the next request' }], source: { kind: 'plugin' as const, plugin: 'test' } },
  293. })
  294. }
  295. return next()
  296. })
  297. runtime.behavior = async (request) => {
  298. await request.bindings[0]!.functions.echo!({ value: 'x' })
  299. return { logs: [], value: 'done' }
  300. }
  301. const result = await runCode(ctx, 'program')
  302. expect(result.isError).toBe(false)
  303. // The sub-call's context has no safe outlet mid-run; the parent result
  304. // must not carry it either.
  305. expect(result.additionalContext).toBeUndefined()
  306. })
  307. it('converts a failed run into a structured isError result carrying kind, message, and captured logs', async () => {
  308. const { ctx, runtime } = await setup({ mode: 'code' })
  309. runtime.behavior = () => Promise.resolve({
  310. logs: [{ source: 'console', level: 'log', text: 'got this far' }],
  311. error: { kind: 'timeout', message: 'compute budget exhausted (300ms busy)' },
  312. })
  313. const result = await runCode(ctx, 'program')
  314. expect(result.isError).toBe(true)
  315. expect(result.error).toEqual({ name: 'CodeRunFailedError', code: 'CODE_RUN_FAILED' })
  316. const text = (result.content[0] as { text: string }).text
  317. expect(text).toContain('code run failed (timeout)')
  318. expect(text).toContain('compute budget exhausted')
  319. expect(text).toContain('got this far')
  320. })
  321. it('CodeRunFailedError is a HarnessError with the CODE_RUN_FAILED code', () => {
  322. const error = new CodeRunFailedError('boom')
  323. expect(error.code).toBe('CODE_RUN_FAILED')
  324. expect(error.name).toBe('CodeRunFailedError')
  325. })
  326. it('aborting the outer signal aborts the in-flight sub-dispatch and abandons queued ones', async () => {
  327. const { ctx, runtime } = await setup({ mode: 'code' })
  328. const seen: string[] = []
  329. let sawAbort = false
  330. ctx.tools.register(defineTool({
  331. name: 'slow',
  332. description: 'Slow tool observing its signal.',
  333. parameters: { id: { type: 'string', required: true } },
  334. async execute(args, exec) {
  335. seen.push(args.id)
  336. await new Promise<void>((resolve) => {
  337. const timer = setTimeout(resolve, 500)
  338. exec.signal?.addEventListener('abort', () => { sawAbort = true; clearTimeout(timer); resolve() }, { once: true })
  339. })
  340. return [{ type: 'text' as const, text: args.id }]
  341. },
  342. }))
  343. const controller = new AbortController()
  344. runtime.behavior = async (request) => {
  345. const tools = request.bindings[0]!.functions
  346. const calls = [tools.slow!({ id: 'first' }).catch(() => 'rejected'), tools.slow!({ id: 'second' }).catch(() => 'rejected')]
  347. setTimeout(() => { controller.abort('user-cancel') }, 50)
  348. await Promise.all(calls)
  349. // A real runtime would be terminated by the abort; the fake honors the
  350. // contract by reporting the abort as the run failure.
  351. return { logs: [], error: { kind: 'abort', message: 'user-cancel' } }
  352. }
  353. const result = await runCode(ctx, 'program', { signal: controller.signal })
  354. expect(result.isError).toBe(true)
  355. expect((result.content[0] as { text: string }).text).toContain('code run failed (abort)')
  356. expect(seen).toEqual(['first'])
  357. expect(sawAbort).toBe(true)
  358. })
  359. it('a runtime that starts a binding call and then REJECTS still reaches quiescence before returning', async () => {
  360. const { ctx, runtime } = await setup({ mode: 'code' })
  361. const { agent, events } = fakeAgent()
  362. let sawAbort = false
  363. let started!: () => void
  364. const inFlight = new Promise<void>((resolve) => { started = resolve })
  365. ctx.tools.register(defineTool({
  366. name: 'slow',
  367. description: 'Slow tool observing its signal.',
  368. parameters: { id: { type: 'string', required: true } },
  369. async execute(args, exec) {
  370. started()
  371. await new Promise<void>((resolve) => {
  372. const timer = setTimeout(resolve, 500)
  373. exec.signal?.addEventListener('abort', () => { sawAbort = true; clearTimeout(timer); resolve() }, { once: true })
  374. })
  375. return [{ type: 'text' as const, text: args.id }]
  376. },
  377. }))
  378. runtime.behavior = async (request) => {
  379. // Start a sub-dispatch, keep its rejection held, and fail the run once
  380. // the tool is genuinely in flight — a seam error AFTER work has begun.
  381. // The bridge's settlement still owes quiescence: without the finally,
  382. // run_code would return now and the slow tool would finish (and log)
  383. // afterwards.
  384. request.bindings[0]!.functions.slow!({ id: 'orphan' }).catch(() => 'held')
  385. await inFlight
  386. throw new Error('backend exploded')
  387. }
  388. const result = await runCode(ctx, 'program', { agent })
  389. expect(result.isError).toBe(true)
  390. expect((result.content[0] as { text: string }).text).toContain('backend exploded')
  391. // Quiescence held: the in-flight sub-dispatch was aborted and its event
  392. // logged INSIDE the run_code execution, not after it returned.
  393. expect(sawAbort).toBe(true)
  394. expect(events.filter(event => event.type === 'tool/code-dispatch').map(event => (event.data as { name: string }).name)).toEqual(['slow'])
  395. })
  396. it('runs without an owning agent: dispatches work, event logging is skipped', async () => {
  397. const { ctx, runtime } = await setup({ mode: 'code' })
  398. const calls = registerEcho(ctx)
  399. runtime.behavior = async (request) => {
  400. await request.bindings[0]!.functions.echo!({ value: 'x' })
  401. return { logs: [], value: 'ok' }
  402. }
  403. const result = await runCode(ctx, 'program')
  404. expect(result.isError).toBe(false)
  405. expect(calls).toEqual([{ value: 'x' }])
  406. })
  407. it('executing run_code under a missing runtime is a structured isError, not a crash', async () => {
  408. const ctx = new Context()
  409. await ctx.plugin(SystemPrompt, {})
  410. await ctx.plugin(ToolRegistry, { mode: 'code' })
  411. const result = await runCode(ctx, 'program')
  412. expect(result.isError).toBe(true)
  413. expect((result.content[0] as { text: string }).text).toContain('requires a code runtime')
  414. })
  415. it('presents the PROGRAM as the execute-card title on both call and result (the one slot execute cards always show)', async () => {
  416. const { ctx } = await setup({ mode: 'code' })
  417. const tool = ctx.tools.get(RUN_CODE_NAME)!
  418. // The program IS the title, mirroring how command tools title their cards
  419. // with the command: an ACP client's execute-card header is the only
  420. // always-visible slot (Zed renders no body content and no raw input for
  421. // execute-kind cards without a real terminal).
  422. expect(tool.presentCall?.({ code: 'return 1' })).toEqual({
  423. card: 'generic',
  424. title: 'return 1',
  425. kind: 'execute',
  426. rawInput: 'return 1',
  427. })
  428. const view = tool.presentResult?.({ code: 'return 1' }, {
  429. content: [{ type: 'text', text: 'model-facing' }],
  430. isError: false,
  431. meta: { logs: [{ source: 'console', level: 'log', text: 'printed' }], dispatches: 1 },
  432. })
  433. // The result omits the title — an update replaces only provided fields,
  434. // so the pending card's program title persists through completion.
  435. expect(view).toEqual({
  436. card: 'generic',
  437. content: [{ type: 'text', text: 'printed' }],
  438. })
  439. // No captured output → no content either; everything pending persists.
  440. expect(tool.presentResult?.({ code: 'x' }, { content: [], isError: false, meta: { logs: [], dispatches: 2 } }))
  441. .toEqual({ card: 'generic' })
  442. // Replay with an unrecognizable meta falls back to the generic rendering.
  443. expect(tool.presentResult?.({ code: 'x' }, { content: [], isError: false, meta: { other: true } })).toBeUndefined()
  444. expect(tool.presentResult?.({ code: 'x' }, { content: [], isError: false })).toBeUndefined()
  445. })
  446. it('renders non-text sub-result blocks as placeholders and truncates long event summaries', async () => {
  447. const { ctx, runtime } = await setup({ mode: 'code' })
  448. const { agent, events } = fakeAgent()
  449. const long = 'x'.repeat(300)
  450. ctx.tools.register(defineTool({
  451. name: 'mixed',
  452. description: 'Returns mixed content.',
  453. parameters: {},
  454. execute() {
  455. return Promise.resolve([
  456. { type: 'text' as const, text: long },
  457. { type: 'reasoning' as const, text: 'hidden' },
  458. ])
  459. },
  460. }))
  461. runtime.behavior = async (request) => {
  462. const value = await request.bindings[0]!.functions.mixed!({})
  463. return { logs: [], value }
  464. }
  465. const result = await runCode(ctx, 'program', { agent })
  466. expect(result.isError).toBe(false)
  467. expect((result.content[0] as { text: string }).text).toBe(`${long}\n[reasoning content]`)
  468. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  469. expect(dispatch.resultSummary.length).toBe(201)
  470. expect(dispatch.resultSummary.endsWith('…')).toBe(true)
  471. })
  472. it('rejects undefined, JSON-throwing, and JSON-unrepresentable binding arguments BEFORE dispatch', async () => {
  473. const { ctx, runtime } = await setup({ mode: 'code' })
  474. const calls = registerEcho(ctx)
  475. const { agent, events } = fakeAgent()
  476. runtime.behavior = async (request) => {
  477. const echo = request.bindings[0]!.functions.echo!
  478. const catchMessage = (promise: Promise<unknown>) => promise.then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error))
  479. return {
  480. logs: [],
  481. value: [
  482. // Root undefined must reject up front: the event log rejects it as
  483. // data, and nothing may execute unlogged.
  484. await catchMessage(echo(undefined)),
  485. // A toJSON that throws a NON-Error propagates out of JSON.stringify.
  486. await catchMessage(echo({ toJSON() { throw 'raw-throw' } })),
  487. // A bare function is a value JSON cannot represent at all.
  488. await catchMessage(echo(() => 1)),
  489. ].join(' | '),
  490. }
  491. }
  492. const result = await runCode(ctx, 'program', { agent })
  493. const text = (result.content[0] as { text: string }).text
  494. expect(text).toContain('call the tool with an arguments object')
  495. expect(text).toContain('JSON-serializable: raw-throw')
  496. expect(text).toContain('a value JSON cannot represent')
  497. // None of the three dispatched, none logged.
  498. expect(calls).toEqual([])
  499. expect(events.filter(event => event.type === 'tool/code-dispatch')).toEqual([])
  500. })
  501. it('logs the value the tool RECEIVED even when the tool mutates its arguments', async () => {
  502. const { ctx, runtime } = await setup({ mode: 'code' })
  503. const { agent, events } = fakeAgent()
  504. ctx.tools.register(defineTool({
  505. name: 'mutator',
  506. description: 'Mutates its own args object.',
  507. parameters: { list: { type: 'array', required: true } },
  508. execute(args) {
  509. args.list.push('injected-by-tool')
  510. return Promise.resolve([{ type: 'text' as const, text: 'mutated' }])
  511. },
  512. }))
  513. runtime.behavior = async (request) => {
  514. await request.bindings[0]!.functions.mutator!({ list: ['original'] })
  515. return { logs: [] }
  516. }
  517. const result = await runCode(ctx, 'program', { agent })
  518. expect(result.isError).toBe(false)
  519. const dispatch = events.find(event => event.type === 'tool/code-dispatch')?.data as SessionEventMap['tool/code-dispatch']
  520. expect(dispatch.arguments).toEqual({ list: ['original'] })
  521. })
  522. it('exposes a tool named __proto__ as an ordinary own binding', async () => {
  523. const { ctx, runtime } = await setup({ mode: 'code' })
  524. ctx.tools.register(defineTool({
  525. name: '__proto__',
  526. description: 'A prototype-colliding tool name.',
  527. parameters: {},
  528. execute() { return Promise.resolve([{ type: 'text' as const, text: 'proto-tool-ok' }]) },
  529. }))
  530. runtime.behavior = async (request) => {
  531. const functions = request.bindings[0]!.functions
  532. expect(Object.getPrototypeOf(functions)).toBeNull()
  533. const value = await functions['__proto__']!({})
  534. return { logs: [], value }
  535. }
  536. const result = await runCode(ctx, 'program')
  537. expect(result.isError).toBe(false)
  538. expect(result.content[0]).toEqual({ type: 'text', text: 'proto-tool-ok' })
  539. })
  540. it('renders a non-string completion value inspect-style', async () => {
  541. const { ctx, runtime } = await setup({ mode: 'code' })
  542. runtime.behavior = () => Promise.resolve({ logs: [], value: { n: 42 } })
  543. const result = await runCode(ctx, 'program')
  544. expect((result.content[0] as { text: string }).text).toBe('{ n: 42 }')
  545. })
  546. it('reports a pre-aborted outer signal as the run failure without dispatching anything', async () => {
  547. const { ctx, runtime } = await setup({ mode: 'code' })
  548. const calls = registerEcho(ctx)
  549. runtime.behavior = (request) => {
  550. // The fake honors the seam contract for an already-aborted signal.
  551. if (request.signal?.aborted) return Promise.resolve({ logs: [], error: { kind: 'abort' as const, message: String(request.signal.reason) } })
  552. return Promise.resolve({ logs: [], value: 'unreachable' })
  553. }
  554. const controller = new AbortController()
  555. controller.abort('too-late')
  556. const result = await runCode(ctx, 'program', { signal: controller.signal })
  557. expect(result.isError).toBe(true)
  558. expect((result.content[0] as { text: string }).text).toContain('code run failed (abort)')
  559. expect(calls).toEqual([])
  560. })
  561. it('rejects a binding invoked after the run is over without dispatching it', async () => {
  562. const { ctx, runtime } = await setup({ mode: 'code' })
  563. const calls = registerEcho(ctx)
  564. const controller = new AbortController()
  565. runtime.behavior = async (request) => {
  566. controller.abort('cancelled-mid-run')
  567. const message = await request.bindings[0]!.functions.echo!({ value: 'x' })
  568. .then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error))
  569. return { logs: [], value: message }
  570. }
  571. const result = await runCode(ctx, 'program', { signal: controller.signal })
  572. expect(result.isError).toBe(false)
  573. expect((result.content[0] as { text: string }).text).toContain('not dispatched')
  574. expect(calls).toEqual([])
  575. })
  576. it('a tool/code-dispatch event never derives a model message', () => {
  577. const session = new Session(SessionId('code-mode-derive'))
  578. session.append('user/message', { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  579. session.append('tool/code-dispatch', {
  580. parentCallId: CallId('p1'),
  581. subCallId: CallId('p1:code:1'),
  582. name: 'echo',
  583. arguments: { value: 'x' },
  584. isError: false,
  585. resultSummary: 'echo:x',
  586. })
  587. const derived = session.deriveMessages()
  588. expect(derived).toHaveLength(1)
  589. expect(derived[0]?.role).toBe('user')
  590. })
  591. it('defaults to native mode under direct construction with no config', async () => {
  592. const ctx = new Context()
  593. await ctx.plugin(SystemPrompt, {})
  594. const registry = new ToolRegistry(ctx)
  595. expect(registry.get(RUN_CODE_NAME)).toBeUndefined()
  596. const assembly = await ctx.systemPrompt.assemble()
  597. expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  598. })
  599. })