tools.spec.ts 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462
  1. import { describe, expect, expectTypeOf, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { CallId, HarnessError } from '@deepseek-ai/dsh-llm'
  4. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  5. import type { Agent } from '@deepseek-ai/dsh-agent'
  6. import ApprovalService, { type ApprovalOutcome, type ApprovalRequest } from '@deepseek-ai/dsh-user-approval'
  7. import ToolRegistry, {
  8. defineTool, schemaSpecToJsonSchema, validateArgs, ToolArgsError, ToolNotFoundError,
  9. type InferArgs, type SchemaSpec, type PreToolDecision, type PostToolDecision,
  10. type ToolExecution, type ToolExecutionResult,
  11. } from '@deepseek-ai/dsh-tools'
  12. async function setup() {
  13. const ctx = new Context()
  14. await ctx.plugin(SystemPrompt)
  15. await ctx.plugin(ToolRegistry)
  16. return ctx
  17. }
  18. const echoTool = defineTool({
  19. name: 'echo',
  20. description: 'echo arguments back',
  21. parameters: { text: { type: 'string' } },
  22. async execute(args) {
  23. return [{ type: 'text' as const, text: args.text ?? '' }]
  24. },
  25. })
  26. describe('ToolRegistry', () => {
  27. it('registers tools, exposes schemas, and feeds the system-prompt assembly', async () => {
  28. const ctx = await setup()
  29. ctx.tools.register(echoTool)
  30. expect(ctx.tools.schemas()).toEqual([{
  31. name: 'echo',
  32. description: 'echo arguments back',
  33. parameters: { type: 'object', properties: { text: { type: 'string' } } },
  34. }])
  35. // schemas() result must not leak execute — ToolSchema deliberately has no
  36. // 'execute' key, so widen through unknown to probe for the absent property
  37. expect((ctx.tools.schemas()[0] as unknown as Record<string, unknown>).execute).toBeUndefined()
  38. const assembly = await ctx.systemPrompt.assemble()
  39. expect(assembly.tools.map(t => t.name)).toEqual(['echo'])
  40. })
  41. it('schemas() drops the UI presentation callbacks — they must never reach the model', async () => {
  42. const ctx = await setup()
  43. // A tool that declares presentCall/presentResult (functions). schemas() feeds
  44. // the system-prompt assembly → the model request, so those callbacks (and
  45. // `execute`) must be stripped: a function in the JSON tool schema would
  46. // corrupt the request. schemas() is an explicit allowlist, so it can't leak.
  47. ctx.tools.register(defineTool({
  48. name: 'present',
  49. description: 'has presenters',
  50. parameters: { x: { type: 'string', required: true } },
  51. async execute() { return [] },
  52. presentCall: args => ({ card: 'generic', title: args.x }),
  53. presentResult: (args, result) => ({ card: 'generic', title: args.x, content: result.content }),
  54. }))
  55. const schema = ctx.tools.schemas()[0] as unknown as Record<string, unknown>
  56. expect(Object.keys(schema).sort()).toEqual(['description', 'name', 'parameters'])
  57. expect(schema.presentCall).toBeUndefined()
  58. expect(schema.presentResult).toBeUndefined()
  59. expect(schema.execute).toBeUndefined()
  60. })
  61. it('schemas() excludes timeoutMs — the budget must never reach the model', async () => {
  62. const ctx = await setup()
  63. ctx.tools.register(defineTool({
  64. name: 'budgeted', description: 'has a budget', parameters: {}, timeoutMs: 5_000,
  65. async execute() { return [{ type: 'text' as const, text: 'ok' }] },
  66. }))
  67. const schema = ctx.tools.schemas().find(s => s.name === 'budgeted')
  68. expect(schema).toBeDefined()
  69. expect('timeoutMs' in (schema as object)).toBe(false)
  70. })
  71. it('executes a tool and returns its content', async () => {
  72. const ctx = await setup()
  73. ctx.tools.register(echoTool)
  74. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  75. expect(result).toEqual({ content: [{ type: 'text', text: 'hi' }], isError: false })
  76. })
  77. it('threads a tool-attached meta (object return form) onto the result', async () => {
  78. const ctx = await setup()
  79. ctx.tools.register({
  80. ...echoTool,
  81. name: 'meta-tool',
  82. async execute() {
  83. return { content: [{ type: 'text', text: 'ok' }], meta: { diffs: [{ path: 'a', oldText: null, newText: 'x' }] } }
  84. },
  85. })
  86. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'meta-tool', arguments: {} })
  87. expect(result).toEqual({
  88. content: [{ type: 'text', text: 'ok' }],
  89. isError: false,
  90. meta: { diffs: [{ path: 'a', oldText: null, newText: 'x' }] },
  91. })
  92. })
  93. it('omits meta when the object return form supplies none', async () => {
  94. const ctx = await setup()
  95. ctx.tools.register({
  96. ...echoTool,
  97. name: 'no-meta-tool',
  98. async execute() {
  99. return { content: [{ type: 'text', text: 'ok' }] }
  100. },
  101. })
  102. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'no-meta-tool', arguments: {} })
  103. expect(result).toEqual({ content: [{ type: 'text', text: 'ok' }], isError: false })
  104. expect('meta' in result).toBe(false)
  105. })
  106. it('normalizes a contract-violating non-cloneable result before final notification', async () => {
  107. const ctx = await setup()
  108. let observedError: boolean | undefined
  109. ctx.on('tools/result', (_exec, result) => { observedError = result.isError })
  110. ctx.tools.register({
  111. ...echoTool,
  112. name: 'bad-meta',
  113. async execute() {
  114. return { content: [], meta: () => undefined }
  115. },
  116. })
  117. const result = await ctx.tools.execute({
  118. callId: CallId('bad-meta'), name: 'bad-meta', arguments: {},
  119. })
  120. expect(result.isError).toBe(true)
  121. expect(result.content[0]?.type === 'text' && result.content[0].text).toContain('Error:')
  122. expect(observedError).toBe(true)
  123. })
  124. it('returns isError results for unknown tools and throwing tools', async () => {
  125. const ctx = await setup()
  126. ctx.tools.register({
  127. ...echoTool,
  128. name: 'boom',
  129. async execute() {
  130. throw new Error('exploded')
  131. },
  132. })
  133. const unknown = await ctx.tools.execute({ callId: CallId('c1'), name: 'nope', arguments: {} })
  134. expect(unknown.isError).toBe(true)
  135. expect(unknown.content[0]).toMatchObject({ text: 'Error: unknown tool "nope"' })
  136. // An unknown tool is a routable failure class, same as a tool-thrown one.
  137. expect(unknown.error).toEqual({ name: 'ToolNotFoundError', code: 'UNKNOWN_TOOL' })
  138. const thrown = await ctx.tools.execute({ callId: CallId('c2'), name: 'boom', arguments: {} })
  139. expect(thrown.isError).toBe(true)
  140. expect(thrown.content[0]).toMatchObject({ text: 'Error: exploded' })
  141. })
  142. it('normalizes a hostile thrown value whose inspection and coercion both throw', async () => {
  143. const ctx = await setup()
  144. ctx.tools.register({
  145. ...echoTool,
  146. name: 'hostile-throw',
  147. async execute() {
  148. throw new Proxy({}, {
  149. getPrototypeOf: () => { throw new Error('prototype trap') },
  150. has: () => { throw new Error('has trap') },
  151. get: () => { throw new Error('get trap') },
  152. })
  153. },
  154. })
  155. await expect(ctx.tools.execute({
  156. callId: CallId('hostile'), name: 'hostile-throw', arguments: {},
  157. })).resolves.toMatchObject({
  158. isError: true,
  159. content: [{ type: 'text', text: 'Error: <unprintable thrown value>' }],
  160. })
  161. })
  162. it('ToolNotFoundError carries a stable message and code', async () => {
  163. const { HarnessError } = await import('@deepseek-ai/dsh-llm')
  164. const err = new ToolNotFoundError('ghost')
  165. expect(err).toBeInstanceOf(HarnessError)
  166. expect(err.name).toBe('ToolNotFoundError')
  167. expect(err.code).toBe('UNKNOWN_TOOL')
  168. expect(err.message).toBe('unknown tool "ghost"')
  169. })
  170. it('lets a tools/pre-execute listener deny a call (permission pattern)', async () => {
  171. const ctx = await setup()
  172. ctx.tools.register(echoTool)
  173. ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
  174. if (exec.name === 'echo') return { kind: 'deny', reason: 'denied by policy' }
  175. return next()
  176. })
  177. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  178. expect(result.isError).toBe(true)
  179. expect(result.content[0]).toMatchObject({ text: 'Error: denied by policy' })
  180. })
  181. it('an ask decision degrades to deny when no approval seam is mounted', async () => {
  182. const ctx = await setup()
  183. ctx.tools.register(echoTool)
  184. ctx.on('tools/pre-execute', async (_exec, _next): Promise<PreToolDecision> =>
  185. ({ kind: 'ask', reason: 'needs approval' }))
  186. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  187. expect(result.isError).toBe(true)
  188. expect(result.content[0]).toMatchObject({ text: 'Error: needs approval' })
  189. })
  190. it('an ask decision with no reason degrades to deny with a default message', async () => {
  191. const ctx = await setup()
  192. ctx.tools.register(echoTool)
  193. ctx.on('tools/pre-execute', async (_exec, _next): Promise<PreToolDecision> => ({ kind: 'ask' }))
  194. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  195. expect(result.isError).toBe(true)
  196. expect(result.content[0]).toMatchObject({ text: 'Error: tool "echo" requires approval (not yet supported)' })
  197. })
  198. describe('ask routing through ctx.approval', () => {
  199. /**
  200. * A minimal Agent stand-in — the approval seam reaches
  201. * `agent.session.append` and folds `.events`; the seeded open turn
  202. * satisfies request()'s enclosure precondition.
  203. */
  204. function fakeAgent(): Agent {
  205. return {
  206. session: { events: [{ type: 'turn/start' }], append: () => ({}) },
  207. } as unknown as Agent
  208. }
  209. async function approvalSetup() {
  210. const ctx = await setup()
  211. await ctx.plugin(ApprovalService)
  212. ctx.tools.register(echoTool)
  213. return ctx
  214. }
  215. it('dispatches the tool when the answerer grants allowed-once, forwarding the ask fields', async () => {
  216. const ctx = await approvalSetup()
  217. const agent = fakeAgent()
  218. const controller = new AbortController()
  219. const seen: ApprovalRequest[] = []
  220. ctx.on('approval/request', (req) => {
  221. seen.push(req)
  222. return Promise.resolve<ApprovalOutcome>('allowed-once')
  223. })
  224. ctx.on('tools/pre-execute', async (_exec, _next): Promise<PreToolDecision> =>
  225. ({ kind: 'ask', reason: 'hook wants a human' }))
  226. const result = await ctx.tools.execute({
  227. callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' }, agent, signal: controller.signal,
  228. })
  229. expect(result).toMatchObject({ isError: false, content: [{ type: 'text', text: 'hi' }] })
  230. expect(seen).toHaveLength(1)
  231. expect(seen[0]).toMatchObject({ agent, toolName: 'echo', callId: 'c1', reason: 'hook wants a human' })
  232. expect(seen[0]?.signal).toBe(controller.signal)
  233. })
  234. it('denies with the user-rejection reason on rejected', async () => {
  235. const ctx = await approvalSetup()
  236. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('rejected'))
  237. ctx.on('tools/pre-execute', async (_exec, _next): Promise<PreToolDecision> => ({ kind: 'ask' }))
  238. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'echo', arguments: {}, agent: fakeAgent() })
  239. expect(result.isError).toBe(true)
  240. expect(result.content[0]).toMatchObject({ text: 'Error: the user rejected tool "echo"' })
  241. })
  242. it('denies with the cancellation reason on cancelled', async () => {
  243. const ctx = await approvalSetup()
  244. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('cancelled'))
  245. ctx.on('tools/pre-execute', async (_exec, _next): Promise<PreToolDecision> => ({ kind: 'ask' }))
  246. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'echo', arguments: {}, agent: fakeAgent() })
  247. expect(result.isError).toBe(true)
  248. expect(result.content[0]).toMatchObject({ text: 'Error: approval for tool "echo" was cancelled' })
  249. })
  250. it('denies with the no-channel reason when the seam is mounted but nobody answers', async () => {
  251. const ctx = await approvalSetup()
  252. ctx.on('tools/pre-execute', async (_exec, _next): Promise<PreToolDecision> => ({ kind: 'ask' }))
  253. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'echo', arguments: {}, agent: fakeAgent() })
  254. expect(result.isError).toBe(true)
  255. expect(result.content[0]).toMatchObject({ text: 'Error: tool "echo" requires approval, but no approval channel is available' })
  256. })
  257. it('denies an agent-less execution without asking — nothing to route or audit through', async () => {
  258. const ctx = await approvalSetup()
  259. let asked = false
  260. ctx.on('approval/request', () => {
  261. asked = true
  262. return Promise.resolve<ApprovalOutcome>('allowed-once')
  263. })
  264. ctx.on('tools/pre-execute', async (_exec, _next): Promise<PreToolDecision> => ({ kind: 'ask' }))
  265. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'echo', arguments: {} })
  266. expect(asked).toBe(false)
  267. expect(result.isError).toBe(true)
  268. expect(result.content[0]).toMatchObject({ text: 'Error: tool "echo" requires approval, but the call has no agent to route it through' })
  269. })
  270. it('turns a rogue outcome from a NON-conforming approval stand-in into an isError result', async () => {
  271. // ApprovalService normalizes rogue answers itself; this pins the
  272. // registry's own exhaustiveness backstop by shadowing the service with a
  273. // stand-in that violates the outcome contract.
  274. const ctx = await setup()
  275. ctx.tools.register(echoTool)
  276. ctx.provide('approval', { request: () => Promise.resolve('yolo') } as unknown as ApprovalService)
  277. ctx.on('tools/pre-execute', async (_exec, _next): Promise<PreToolDecision> => ({ kind: 'ask' }))
  278. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'echo', arguments: {}, agent: fakeAgent() })
  279. expect(result.isError).toBe(true)
  280. const text = result.content[0]?.type === 'text' ? result.content[0].text : ''
  281. expect(text).toContain('unreachable')
  282. })
  283. })
  284. it('a tools/post-execute listener can replace the result content (accept) ', async () => {
  285. const ctx = await setup()
  286. ctx.tools.register(echoTool)
  287. ctx.on('tools/post-execute', async (_exec, _result, _next): Promise<PostToolDecision> =>
  288. ({ kind: 'accept', content: [{ type: 'text', text: 'rewritten' }] }))
  289. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  290. expect(result.isError).toBe(false)
  291. expect(result.content[0]).toMatchObject({ text: 'rewritten' })
  292. })
  293. it('a tools/post-execute block turns the call into an isError with corrective feedback', async () => {
  294. const ctx = await setup()
  295. ctx.tools.register(echoTool)
  296. ctx.on('tools/post-execute', async (_exec, _result, _next): Promise<PostToolDecision> =>
  297. ({ kind: 'block', feedback: [{ type: 'text', text: 'output rejected: try again' }] }))
  298. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  299. expect(result.isError).toBe(true)
  300. expect(result.content[0]).toMatchObject({ text: 'output rejected: try again' })
  301. })
  302. it('a block decision can ALSO attach additionalContexts', async () => {
  303. const ctx = await setup()
  304. ctx.tools.register(echoTool)
  305. ctx.on('tools/post-execute', async (_exec, _result, _next): Promise<PostToolDecision> =>
  306. ({
  307. kind: 'block',
  308. feedback: [{ type: 'text', text: 'rejected' }],
  309. additionalContexts: [{ content: [{ type: 'text', text: 'why it was rejected' }], source: { kind: 'plugin', plugin: 'test' } }],
  310. }))
  311. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  312. expect(result.isError).toBe(true)
  313. expect(result.content[0]).toMatchObject({ text: 'rejected' })
  314. expect(result.additionalContexts).toMatchObject([{ content: [{ text: 'why it was rejected' }], source: { kind: 'plugin', plugin: 'test' } }])
  315. })
  316. it('post-execute additionalContexts ride on the result for the loop to buffer', async () => {
  317. const ctx = await setup()
  318. ctx.tools.register(echoTool)
  319. ctx.on('tools/post-execute', async (_exec, _result, _next): Promise<PostToolDecision> =>
  320. ({ kind: 'accept', additionalContexts: [{ content: [{ type: 'text', text: 'fyi' }], source: { kind: 'plugin', plugin: 'test' } }] }))
  321. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  322. expect(result.additionalContexts).toMatchObject([{ content: [{ text: 'fyi' }], source: { kind: 'plugin', plugin: 'test' } }])
  323. })
  324. it('preserves tool-deferred, execute-wrapper, and post-execute contexts in order', async () => {
  325. const ctx = await setup()
  326. ctx.tools.register(defineTool({
  327. name: 'composite',
  328. description: 'composite',
  329. parameters: {},
  330. async execute(_args, exec) {
  331. exec.deferContext({ content: [{ type: 'text', text: 'nested-1' }], source: { kind: 'plugin', plugin: 'nested-1' }, meta: { n: 1 } })
  332. exec.deferContext({ content: [{ type: 'text', text: 'nested-2' }], source: { kind: 'plugin', plugin: 'nested-2' } })
  333. return [{ type: 'text', text: 'done' }]
  334. },
  335. }))
  336. ctx.on('tools/execute', async (_exec, next) => {
  337. const result = await next()
  338. return {
  339. ...result,
  340. additionalContexts: [
  341. ...result.additionalContexts ?? [],
  342. { content: [{ type: 'text', text: 'wrapper' }], source: { kind: 'plugin', plugin: 'wrapper' } },
  343. ],
  344. }
  345. })
  346. ctx.on('tools/post-execute', async (_exec, _result, next): Promise<PostToolDecision> => {
  347. const downstream = await next()
  348. return {
  349. ...downstream,
  350. additionalContexts: [
  351. { content: [{ type: 'text', text: 'post' }], source: { kind: 'plugin', plugin: 'post' } },
  352. ...downstream.additionalContexts ?? [],
  353. ],
  354. }
  355. })
  356. const result = await ctx.tools.execute({ callId: CallId('composite'), name: 'composite', arguments: {} })
  357. expect(result.additionalContexts?.map(context => context.source)).toEqual([
  358. { kind: 'plugin', plugin: 'nested-1' },
  359. { kind: 'plugin', plugin: 'nested-2' },
  360. { kind: 'plugin', plugin: 'wrapper' },
  361. { kind: 'plugin', plugin: 'post' },
  362. ])
  363. expect(result.additionalContexts?.[0]?.meta).toEqual({ n: 1 })
  364. })
  365. it('keeps deferred contexts when a composite tool throws, but drops them when the outer call is blocked', async () => {
  366. const ctx = await setup()
  367. ctx.tools.register(defineTool({
  368. name: 'failing-composite',
  369. description: 'failing composite',
  370. parameters: {},
  371. async execute(_args, exec) {
  372. exec.deferContext({ content: [{ type: 'text', text: 'nested' }], source: { kind: 'plugin', plugin: 'nested' } })
  373. throw new Error('outer failure')
  374. },
  375. }))
  376. const failed = await ctx.tools.execute({ callId: CallId('failed'), name: 'failing-composite', arguments: {} })
  377. expect(failed.isError).toBe(true)
  378. expect(failed.additionalContexts?.map(context => context.source)).toEqual([{ kind: 'plugin', plugin: 'nested' }])
  379. ctx.on('tools/post-execute', async (): Promise<PostToolDecision> => ({
  380. kind: 'block',
  381. feedback: [{ type: 'text', text: 'blocked' }],
  382. additionalContexts: [{ content: [{ type: 'text', text: 'block-only' }], source: { kind: 'plugin', plugin: 'blocker' } }],
  383. }))
  384. const blocked = await ctx.tools.execute({ callId: CallId('blocked'), name: 'failing-composite', arguments: {} })
  385. expect(blocked.isError).toBe(true)
  386. expect(blocked.additionalContexts?.map(context => context.source)).toEqual([{ kind: 'plugin', plugin: 'blocker' }])
  387. })
  388. it('composes pre + post waterfalls around dispatch (sandbox-wrap pattern)', async () => {
  389. const ctx = await setup()
  390. ctx.tools.register(echoTool)
  391. const order: string[] = []
  392. ctx.on('tools/pre-execute', async (_exec, next) => {
  393. order.push('pre:before')
  394. const decision = await next()
  395. order.push('pre:after')
  396. return decision
  397. })
  398. ctx.on('tools/post-execute', async (_exec, _result, next) => {
  399. order.push('post:before')
  400. const decision = await next()
  401. order.push('post:after')
  402. return decision
  403. })
  404. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'echo', arguments: { text: 'x' } })
  405. expect(result.isError).toBe(false)
  406. // pre runs fully (gate) before dispatch, then post runs over the result.
  407. expect(order).toEqual(['pre:before', 'pre:after', 'post:before', 'post:after'])
  408. })
  409. it('runs tools/execute after an allowed pre-execute, around dispatch, and before post-execute', async () => {
  410. const ctx = await setup()
  411. const order: string[] = []
  412. ctx.tools.register(defineTool({
  413. name: 'traced',
  414. description: 'echo',
  415. parameters: { text: { type: 'string' } },
  416. async execute(args) {
  417. order.push('dispatch')
  418. return [{ type: 'text' as const, text: args.text ?? '' }]
  419. },
  420. }))
  421. ctx.on('tools/pre-execute', async (_exec, next) => { order.push('pre'); return next() })
  422. ctx.on('tools/execute', async (_exec: ToolExecution, next: () => Promise<ToolExecutionResult>): Promise<ToolExecutionResult> => {
  423. order.push('execute:before')
  424. const result = await next()
  425. order.push('execute:after')
  426. return result
  427. })
  428. ctx.on('tools/post-execute', async (_exec, _result, next) => { order.push('post'); return next() })
  429. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'traced', arguments: { text: 'hi' } })
  430. expect(result).toEqual({ content: [{ type: 'text', text: 'hi' }], isError: false })
  431. // The around seam wraps dispatch; pre gates before it, post runs over its result.
  432. expect(order).toEqual(['pre', 'execute:before', 'dispatch', 'execute:after', 'post'])
  433. })
  434. it('a pre-execute deny short-circuits before tools/execute (the seam never runs)', async () => {
  435. const ctx = await setup()
  436. ctx.tools.register(echoTool)
  437. let entered = false
  438. ctx.on('tools/pre-execute', async (_exec, _next): Promise<PreToolDecision> => ({ kind: 'deny', reason: 'nope' }))
  439. ctx.on('tools/execute', async (_exec: ToolExecution, next: () => Promise<ToolExecutionResult>): Promise<ToolExecutionResult> => {
  440. entered = true
  441. return next()
  442. })
  443. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  444. expect(result.isError).toBe(true)
  445. expect(result.content[0]).toMatchObject({ text: 'Error: nope' })
  446. expect(entered).toBe(false) // a denied call never enters the around-dispatch seam
  447. })
  448. it('a thrown tool is normalized to an isError result BEFORE a tools/execute listener sees next()', async () => {
  449. const ctx = await setup()
  450. ctx.tools.register({
  451. ...echoTool,
  452. name: 'boom',
  453. async execute() { throw new HarnessError('kaboom', 'BOOM') },
  454. })
  455. let seen: { isError: boolean; error?: unknown } | undefined
  456. ctx.on('tools/execute', async (_exec: ToolExecution, next: () => Promise<ToolExecutionResult>): Promise<ToolExecutionResult> => {
  457. const result = await next()
  458. // The base next() IS dispatch-with-normalization: the wrapper sees the
  459. // normalized isError result, never a raw throw from the tool body.
  460. seen = { isError: result.isError, error: result.error }
  461. return result
  462. })
  463. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'boom', arguments: {} })
  464. expect(seen).toEqual({ isError: true, error: { name: 'HarnessError', code: 'BOOM' } })
  465. expect(result.isError).toBe(true)
  466. expect(result.content[0]).toMatchObject({ text: 'Error: kaboom' })
  467. })
  468. it('a thrown tool normalized inside tools/execute still reaches post-execute', async () => {
  469. const ctx = await setup()
  470. ctx.tools.register({
  471. ...echoTool,
  472. name: 'boom',
  473. async execute() { throw new Error('exploded') },
  474. })
  475. let postSaw: boolean | undefined
  476. ctx.on('tools/execute', async (_exec: ToolExecution, next: () => Promise<ToolExecutionResult>): Promise<ToolExecutionResult> => next())
  477. ctx.on('tools/post-execute', async (_exec, result, next) => {
  478. postSaw = result.isError
  479. return next()
  480. })
  481. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'boom', arguments: {} })
  482. expect(postSaw).toBe(true) // the normalized isError still flows through post-execute
  483. expect(result.isError).toBe(true)
  484. expect(result.content[0]).toMatchObject({ text: 'Error: exploded' })
  485. })
  486. it('a tools/execute listener can replace exec.signal for the dispatched tool (deadline pattern)', async () => {
  487. const ctx = await setup()
  488. let seenSignal: AbortSignal | undefined
  489. ctx.tools.register({
  490. ...echoTool,
  491. name: 'signal-probe',
  492. async execute(_args, exec) {
  493. seenSignal = exec.signal
  494. return [{ type: 'text' as const, text: 'ok' }]
  495. },
  496. })
  497. const upstream = new AbortController().signal
  498. const replacement = new AbortController().signal
  499. ctx.on('tools/execute', async (exec: ToolExecution, next: () => Promise<ToolExecutionResult>): Promise<ToolExecutionResult> => {
  500. expect(exec.signal).toBe(upstream)
  501. // Cordis next() ignores passed arguments, so a wrapper mutates exec in
  502. // place (the documented "mutate the shared object, then delegate" idiom).
  503. exec.signal = replacement
  504. return next()
  505. })
  506. await ctx.tools.execute({ callId: CallId('c1'), name: 'signal-probe', arguments: {}, signal: upstream })
  507. expect(seenSignal).toBe(replacement) // dispatch saw the wrapper's replacement, not the upstream
  508. })
  509. it('a tools/execute listener can short-circuit dispatch by returning a result without next()', async () => {
  510. const ctx = await setup()
  511. let dispatched = false
  512. ctx.tools.register({
  513. ...echoTool,
  514. name: 'never-runs',
  515. async execute() { dispatched = true; return [] },
  516. })
  517. ctx.on('tools/execute', async (_exec: ToolExecution, _next: () => Promise<ToolExecutionResult>): Promise<ToolExecutionResult> =>
  518. ({ content: [{ type: 'text', text: 'short-circuited' }], isError: false }))
  519. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'never-runs', arguments: {} })
  520. expect(dispatched).toBe(false) // returning without next() skips core dispatch
  521. expect(result.content[0]).toMatchObject({ text: 'short-circuited' })
  522. })
  523. it('preserves additionalContexts supplied by an around-dispatch result', async () => {
  524. const ctx = await setup()
  525. ctx.tools.register(echoTool)
  526. ctx.on('tools/execute', async () => ({
  527. content: [{ type: 'text', text: 'short-circuited with context' }],
  528. isError: false,
  529. additionalContexts: [{
  530. content: [{ type: 'text', text: 'from around dispatch' }],
  531. source: { kind: 'plugin', plugin: 'test' },
  532. }],
  533. }))
  534. const result = await ctx.tools.execute({
  535. callId: CallId('around-context'), name: 'echo', arguments: {},
  536. })
  537. expect(result.additionalContexts).toEqual([{
  538. content: [{ type: 'text', text: 'from around dispatch' }],
  539. source: { kind: 'plugin', plugin: 'test' },
  540. }])
  541. })
  542. it('returns an isError result when a tools/execute listener throws', async () => {
  543. const ctx = await setup()
  544. ctx.tools.register(echoTool)
  545. ctx.on('tools/execute', async () => { throw new Error('wrapper broke') })
  546. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  547. expect(result).toEqual({
  548. content: [{ type: 'text', text: 'Error: wrapper broke' }],
  549. isError: true,
  550. })
  551. })
  552. it('returns an isError result when a tools/pre-execute listener throws', async () => {
  553. const ctx = await setup()
  554. ctx.tools.register(echoTool)
  555. ctx.on('tools/pre-execute', async () => {
  556. throw new Error('permission hook broke')
  557. })
  558. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  559. expect(result).toEqual({
  560. content: [{ type: 'text', text: 'Error: permission hook broke' }],
  561. isError: true,
  562. })
  563. })
  564. it('returns an isError result when a tools/post-execute listener throws', async () => {
  565. const ctx = await setup()
  566. ctx.tools.register(echoTool)
  567. ctx.on('tools/post-execute', async () => {
  568. throw new Error('post hook broke')
  569. })
  570. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  571. expect(result).toEqual({
  572. content: [{ type: 'text', text: 'Error: post hook broke' }],
  573. isError: true,
  574. })
  575. })
  576. it('preserves structured error info when a tools/pre-execute listener throws HarnessError', async () => {
  577. const ctx = await setup()
  578. ctx.tools.register(echoTool)
  579. ctx.on('tools/pre-execute', async () => {
  580. throw new HarnessError('denied', 'DENIED')
  581. })
  582. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  583. expect(result).toMatchObject({
  584. isError: true,
  585. error: { name: 'HarnessError', code: 'DENIED' },
  586. })
  587. })
  588. it('schemas() snapshots tool schemas instead of exposing registry objects', async () => {
  589. const ctx = await setup()
  590. ctx.tools.register(echoTool)
  591. const first = ctx.tools.schemas()
  592. const firstParameters = first[0]!.parameters as { properties: Record<string, unknown> }
  593. firstParameters.properties['mutated'] = { type: 'string' }
  594. first[0]!.description = 'mutated'
  595. expect(ctx.tools.schemas()).toEqual([{
  596. name: 'echo',
  597. description: 'echo arguments back',
  598. parameters: { type: 'object', properties: { text: { type: 'string' } } },
  599. }])
  600. })
  601. it('rejects a non-positive or non-finite registration timeout', async () => {
  602. const ctx = await setup()
  603. expect(() => ctx.tools.register({ ...echoTool, name: 'zero-timeout', timeoutMs: 0 }))
  604. .toThrow('timeoutMs must be a positive finite number')
  605. expect(() => ctx.tools.register({ ...echoTool, name: 'infinite-timeout', timeoutMs: Number.POSITIVE_INFINITY }))
  606. .toThrow('timeoutMs must be a positive finite number')
  607. })
  608. it('rejects duplicate names and unregisters on fiber dispose (HMR safety)', async () => {
  609. const ctx = await setup()
  610. ctx.tools.register(echoTool)
  611. expect(() => ctx.tools.register(echoTool)).toThrow('already registered')
  612. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  613. inner.tools.register({ ...echoTool, name: 'scoped' })
  614. }, { inject: ['tools'] }))
  615. expect(ctx.tools.schemas().map(t => t.name)).toEqual(['echo', 'scoped'])
  616. await fiber.dispose()
  617. expect(ctx.tools.schemas().map(t => t.name)).toEqual(['echo'])
  618. })
  619. it('returns a callable disposer from register() that unregisters the tool', async () => {
  620. const ctx = await setup()
  621. ctx.tools.register(echoTool)
  622. // Register a second tool and call its returned disposer directly
  623. const dispose = ctx.tools.register({ ...echoTool, name: 'disposable' })
  624. expect(ctx.tools.schemas().map(t => t.name)).toEqual(['echo', 'disposable'])
  625. dispose()
  626. expect(ctx.tools.schemas().map(t => t.name)).toEqual(['echo'])
  627. })
  628. it('rolls back the tool entry when a tools/change listener throws (P1-1)', async () => {
  629. const ctx = await setup()
  630. let threw = false
  631. ctx.on('tools/change', () => {
  632. if (!threw) { threw = true; throw new Error('boom change listener') }
  633. })
  634. // The throwing emit must roll the entry back, not leak it.
  635. expect(() => ctx.tools.register(echoTool)).toThrow('boom change listener')
  636. expect(ctx.tools.get('echo')).toBeUndefined() // rolled back, not leaked
  637. expect(ctx.tools.schemas()).toHaveLength(0)
  638. // A subsequent listener-free register of the SAME name succeeds and is
  639. // exposed exactly once (the duplicate-name check is not wedged).
  640. const dispose = ctx.tools.register(echoTool)
  641. expect(ctx.tools.schemas().map(t => t.name)).toEqual(['echo'])
  642. dispose()
  643. expect(ctx.tools.get('echo')).toBeUndefined()
  644. })
  645. it('register() returns the EXACT effect disposer: a composite yield nests the teardown in order', async () => {
  646. // Registry methods return the exact Cordis effect disposer so a composite yield places
  647. // unregistration at its LIFO position. A wrapper would create a concurrent sibling; this async
  648. // probe yields during earlier teardown and would then observe the tool already removed.
  649. const ctx = await setup()
  650. const order: string[] = []
  651. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  652. inner.effect(function* () {
  653. yield () => { order.push('disposed-last') }
  654. yield inner.tools.register({ ...echoTool, name: 'nested' })
  655. order.push('registered')
  656. yield async () => {
  657. await new Promise(resolve => setTimeout(resolve, 0))
  658. order.push(inner.tools.get('nested') ? 'first: still registered' : 'first: already gone')
  659. }
  660. })
  661. }, { inject: ['tools'] }))
  662. await fiber.dispose()
  663. expect(order).toEqual(['registered', 'first: still registered', 'disposed-last'])
  664. expect(ctx.tools.get('nested')).toBeUndefined()
  665. })
  666. })
  667. describe('defineTool / schema DSL', () => {
  668. it('converts SchemaSpec to standard JSON Schema with required array', () => {
  669. const spec = {
  670. path: { type: 'string', required: true, description: 'Absolute path' },
  671. offset: { type: 'number' },
  672. limit: { type: 'number', description: 'Max lines' },
  673. } satisfies SchemaSpec
  674. const jsonSchema = schemaSpecToJsonSchema(spec)
  675. expect(jsonSchema).toEqual({
  676. type: 'object',
  677. properties: {
  678. path: { type: 'string', description: 'Absolute path' },
  679. offset: { type: 'number' },
  680. limit: { type: 'number', description: 'Max lines' },
  681. },
  682. required: ['path'],
  683. })
  684. })
  685. it('handles empty spec (no properties, no required)', () => {
  686. expect(schemaSpecToJsonSchema({})).toEqual({
  687. type: 'object',
  688. properties: {},
  689. })
  690. })
  691. it('handles nested object spec', () => {
  692. const spec = {
  693. config: {
  694. type: 'object',
  695. required: true,
  696. properties: {
  697. host: { type: 'string', required: true },
  698. port: { type: 'number' },
  699. },
  700. },
  701. } satisfies SchemaSpec
  702. const jsonSchema = schemaSpecToJsonSchema(spec)
  703. expect(jsonSchema).toEqual({
  704. type: 'object',
  705. properties: {
  706. config: {
  707. type: 'object',
  708. properties: {
  709. host: { type: 'string' },
  710. port: { type: 'number' },
  711. },
  712. required: ['host'],
  713. },
  714. },
  715. required: ['config'],
  716. })
  717. })
  718. it('defineTool returns a valid ToolDefinition with typed execute', async () => {
  719. const ctx = await setup()
  720. const tool = defineTool({
  721. name: 'typed-echo',
  722. description: 'A typed echo tool',
  723. parameters: {
  724. text: { type: 'string', required: true },
  725. uppercase: { type: 'boolean' },
  726. },
  727. async execute(args) {
  728. // args is typed: { text: string; uppercase?: boolean }
  729. const result = args.uppercase ? args.text.toUpperCase() : args.text
  730. return [{ type: 'text', text: result }]
  731. },
  732. })
  733. ctx.tools.register(tool)
  734. expect(ctx.tools.schemas()).toEqual([{
  735. name: 'typed-echo',
  736. description: 'A typed echo tool',
  737. parameters: {
  738. type: 'object',
  739. properties: {
  740. text: { type: 'string' },
  741. uppercase: { type: 'boolean' },
  742. },
  743. required: ['text'],
  744. },
  745. }])
  746. const result = await ctx.tools.execute({
  747. callId: CallId('c1'),
  748. name: 'typed-echo',
  749. arguments: { text: 'hello', uppercase: true },
  750. })
  751. expect(result.isError).toBe(false)
  752. expect(result.content).toEqual([{ type: 'text', text: 'HELLO' }])
  753. })
  754. it('type-level: InferArgs maps required properties to non-optional', () => {
  755. // Compile-time check: if this compiles, InferArgs is correct.
  756. // args.a is string (required), args.b is number|undefined (optional).
  757. const tool = defineTool({
  758. name: 'type-check',
  759. description: '',
  760. parameters: { a: { type: 'string' as const, required: true as const }, b: { type: 'number' as const } },
  761. async execute(args) {
  762. // Verify types at runtime via typeof
  763. expect(typeof args.a).toBe('string')
  764. // args.b should be undefined when not provided
  765. void args
  766. return [{ type: 'text', text: args.a }]
  767. },
  768. })
  769. void tool
  770. })
  771. it('registry round-trips a defineTool definition (register→schemas→execute)', async () => {
  772. const ctx = await setup()
  773. ctx.tools.register(defineTool({
  774. name: 'roundtrip',
  775. description: 'Round-trip test',
  776. parameters: {
  777. req: { type: 'string', required: true },
  778. opt: { type: 'number', description: 'Optional number' },
  779. },
  780. async execute(args) {
  781. return [{ type: 'text', text: `${args.req}:${args.opt ?? 'none'}` }]
  782. },
  783. }))
  784. // Schema round-trip: schemas() returns standard JSON Schema
  785. const schemas = ctx.tools.schemas()
  786. expect(schemas).toHaveLength(1)
  787. expect(schemas[0]!.parameters).toEqual({
  788. type: 'object',
  789. properties: {
  790. req: { type: 'string' },
  791. opt: { type: 'number', description: 'Optional number' },
  792. },
  793. required: ['req'],
  794. })
  795. // Execution round-trip
  796. const result = await ctx.tools.execute({
  797. callId: CallId('c1'),
  798. name: 'roundtrip',
  799. arguments: { req: 'hello' },
  800. })
  801. expect(result.isError).toBe(false)
  802. expect(result.content).toEqual([{ type: 'text', text: 'hello:none' }])
  803. })
  804. it('still accepts raw JSON-Schema ToolDefinition directly (MCP interop)', async () => {
  805. const ctx = await setup()
  806. ctx.tools.register({
  807. name: 'raw-tool',
  808. description: 'Raw JSON Schema tool (like an MCP adapter would register)',
  809. parameters: {
  810. type: 'object',
  811. properties: { path: { type: 'string' } },
  812. required: ['path'],
  813. },
  814. async execute(args: unknown) {
  815. const p = args as { path: string }
  816. return [{ type: 'text', text: p.path }]
  817. },
  818. })
  819. const schemas = ctx.tools.schemas()
  820. expect(schemas[0]!.parameters).toEqual({
  821. type: 'object',
  822. properties: { path: { type: 'string' } },
  823. required: ['path'],
  824. })
  825. const result = await ctx.tools.execute({
  826. callId: CallId('c1'),
  827. name: 'raw-tool',
  828. arguments: { path: '/tmp' },
  829. })
  830. expect(result.isError).toBe(false)
  831. expect(result.content).toEqual([{ type: 'text', text: '/tmp' }])
  832. })
  833. })
  834. describe('schema DSL edge cases', () => {
  835. it('emits enum values in JSON Schema property', () => {
  836. const spec = {
  837. color: { type: 'string', enum: ['red', 'green', 'blue'], description: 'Color choice' },
  838. } satisfies SchemaSpec
  839. const jsonSchema = schemaSpecToJsonSchema(spec)
  840. expect(jsonSchema.properties['color']).toMatchObject({
  841. type: 'string',
  842. enum: ['red', 'green', 'blue'],
  843. description: 'Color choice',
  844. })
  845. })
  846. it('emits default value in JSON Schema property', () => {
  847. const spec = {
  848. limit: { type: 'number', default: 25 },
  849. } satisfies SchemaSpec
  850. const jsonSchema = schemaSpecToJsonSchema(spec)
  851. expect(jsonSchema.properties['limit']).toMatchObject({
  852. type: 'number',
  853. default: 25,
  854. })
  855. })
  856. it('handles array items without nested properties (plain type array)', () => {
  857. const spec = {
  858. tags: { type: 'array', items: { type: 'string' } },
  859. } satisfies SchemaSpec
  860. const jsonSchema = schemaSpecToJsonSchema(spec)
  861. expect(jsonSchema.properties['tags']).toEqual({
  862. type: 'array',
  863. items: { type: 'string' },
  864. })
  865. })
  866. it('handles enum and default together in one property', () => {
  867. const spec = {
  868. level: { type: 'string', enum: ['low', 'high'], default: 'low' },
  869. } satisfies SchemaSpec
  870. const jsonSchema = schemaSpecToJsonSchema(spec)
  871. expect(jsonSchema.properties['level']).toMatchObject({
  872. type: 'string',
  873. enum: ['low', 'high'],
  874. default: 'low',
  875. })
  876. })
  877. it('omits description, enum, default keys when not specified', () => {
  878. const spec = {
  879. bare: { type: 'string' },
  880. } satisfies SchemaSpec
  881. const jsonSchema = schemaSpecToJsonSchema(spec)
  882. const prop = jsonSchema.properties['bare'] as Record<string, unknown>
  883. expect(prop).toEqual({ type: 'string' })
  884. expect('description' in prop).toBe(false)
  885. expect('enum' in prop).toBe(false)
  886. expect('default' in prop).toBe(false)
  887. })
  888. it('handles array with no items (items omitted)', () => {
  889. const spec = {
  890. raw: { type: 'array' },
  891. } satisfies SchemaSpec
  892. const jsonSchema = schemaSpecToJsonSchema(spec)
  893. expect(jsonSchema.properties['raw']).toEqual({
  894. type: 'array',
  895. })
  896. })
  897. it('handles nested object with all-optional properties (no required array)', () => {
  898. const spec = {
  899. config: {
  900. type: 'object',
  901. properties: {
  902. host: { type: 'string' },
  903. port: { type: 'number' },
  904. },
  905. },
  906. } satisfies SchemaSpec
  907. const jsonSchema = schemaSpecToJsonSchema(spec)
  908. expect(jsonSchema.properties['config']).toMatchObject({
  909. type: 'object',
  910. properties: {
  911. host: { type: 'string' },
  912. port: { type: 'number' },
  913. },
  914. })
  915. const config = jsonSchema.properties['config'] as Record<string, unknown>
  916. expect('required' in config).toBe(false)
  917. })
  918. })
  919. describe('schema DSL optional and nested contracts', () => {
  920. it('InferArgs makes non-required keys genuinely optional (omittable)', () => {
  921. type Args = InferArgs<{
  922. path: { type: 'string'; required: true }
  923. limit: { type: 'number' }
  924. }>
  925. expectTypeOf<Args>().toEqualTypeOf<{ path: string; limit?: number }>()
  926. const omitted: Args = { path: '/tmp' }
  927. expect(omitted.limit).toBeUndefined()
  928. })
  929. it('InferArgs recurses into array items, including arrays of objects', () => {
  930. type Args = InferArgs<{
  931. names: { type: 'array'; required: true; items: { type: 'string' } }
  932. servers: {
  933. type: 'array'
  934. items: {
  935. type: 'object'
  936. properties: {
  937. host: { type: 'string'; required: true }
  938. port: { type: 'number' }
  939. }
  940. }
  941. }
  942. }>
  943. expectTypeOf<Args>().toEqualTypeOf<{
  944. names: string[]
  945. servers?: { host: string; port?: number }[]
  946. }>()
  947. })
  948. it('runtime JSON Schema matches the array-of-objects inference', () => {
  949. const spec = {
  950. servers: {
  951. type: 'array',
  952. items: {
  953. type: 'object',
  954. properties: {
  955. host: { type: 'string', required: true },
  956. port: { type: 'number' },
  957. },
  958. },
  959. },
  960. } satisfies SchemaSpec
  961. expect(schemaSpecToJsonSchema(spec)).toEqual({
  962. type: 'object',
  963. properties: {
  964. servers: {
  965. type: 'array',
  966. items: {
  967. type: 'object',
  968. properties: {
  969. host: { type: 'string' },
  970. port: { type: 'number' },
  971. },
  972. required: ['host'],
  973. },
  974. },
  975. },
  976. })
  977. })
  978. it('reports messages from non-Error throws (throw { message })', async () => {
  979. const ctx = await setup()
  980. ctx.tools.register({
  981. ...echoTool,
  982. name: 'object-thrower',
  983. async execute() {
  984. // testing non-Error throws on purpose
  985. throw { message: 'denied by object' }
  986. },
  987. })
  988. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'object-thrower', arguments: {} })
  989. expect(result.isError).toBe(true)
  990. expect(result.content[0]).toMatchObject({ text: 'Error: denied by object' })
  991. })
  992. it('reports messages from throws of non-objects (throw "string")', async () => {
  993. const ctx = await setup()
  994. ctx.tools.register({
  995. ...echoTool,
  996. name: 'string-thrower',
  997. async execute() {
  998. // testing primitive throws on purpose
  999. throw 'kaboom'
  1000. },
  1001. })
  1002. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'string-thrower', arguments: {} })
  1003. expect(result.isError).toBe(true)
  1004. expect(result.content[0]).toMatchObject({ text: 'Error: kaboom' })
  1005. })
  1006. it('reports messages from throws of objects without message property', async () => {
  1007. const ctx = await setup()
  1008. ctx.tools.register({
  1009. ...echoTool,
  1010. name: 'object-no-message',
  1011. async execute() {
  1012. // testing object throw without .message
  1013. throw { code: 500 }
  1014. },
  1015. })
  1016. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'object-no-message', arguments: {} })
  1017. expect(result.isError).toBe(true)
  1018. const firstContent = result.content[0]!
  1019. expect(firstContent.type).toBe('text')
  1020. if (firstContent.type === 'text') {
  1021. expect(firstContent.text).toBe('Error: [object Object]')
  1022. }
  1023. })
  1024. })
  1025. describe('ToolRegistry.get', () => {
  1026. it('get() returns the registered tool definition', async () => {
  1027. const ctx = await setup()
  1028. ctx.tools.register(echoTool)
  1029. const tool = ctx.tools.get('echo')
  1030. expect(tool).toBeDefined()
  1031. expect(tool!.name).toBe('echo')
  1032. })
  1033. it('get() returns undefined for unknown tool names', async () => {
  1034. const ctx = await setup()
  1035. expect(ctx.tools.get('nope')).toBeUndefined()
  1036. })
  1037. })
  1038. describe('validateArgs (the runtime-validation Agent Note, part 1)', () => {
  1039. it('returns [] for valid args and is total over malformed input', () => {
  1040. const spec = {
  1041. path: { type: 'string', required: true },
  1042. limit: { type: 'number' },
  1043. } satisfies SchemaSpec
  1044. expect(validateArgs(spec, { path: '/tmp' })).toEqual([])
  1045. expect(validateArgs(spec, { path: '/tmp', limit: 5 })).toEqual([])
  1046. // never throws regardless of shape
  1047. expect(validateArgs(spec, null)).toHaveLength(1)
  1048. expect(validateArgs(spec, 'nope')).toHaveLength(1)
  1049. expect(validateArgs(spec, [])).toHaveLength(1)
  1050. })
  1051. it('flags a missing required key and a required key present as undefined', () => {
  1052. const spec = { path: { type: 'string', required: true } } satisfies SchemaSpec
  1053. expect(validateArgs(spec, {})).toEqual(['missing required property "path"'])
  1054. expect(validateArgs(spec, { path: undefined })).toEqual(['missing required property "path"'])
  1055. })
  1056. it('allows extra keys (no additionalProperties:false) and omitted optionals', () => {
  1057. const spec = { path: { type: 'string', required: true } } satisfies SchemaSpec
  1058. expect(validateArgs(spec, { path: '/tmp', extra: 1 })).toEqual([])
  1059. })
  1060. it('does not apply defaults (validation only)', () => {
  1061. const spec = { limit: { type: 'number', default: 25 } } satisfies SchemaSpec
  1062. // absent optional is valid, and validation does not synthesize the default
  1063. expect(validateArgs(spec, {})).toEqual([])
  1064. })
  1065. it('type-checks primitives', () => {
  1066. const spec = {
  1067. s: { type: 'string' },
  1068. n: { type: 'number' },
  1069. b: { type: 'boolean' },
  1070. } satisfies SchemaSpec
  1071. expect(validateArgs(spec, { s: 1 })).toEqual(['"s" must be a string'])
  1072. expect(validateArgs(spec, { n: 'x' })).toEqual(['"n" must be a number'])
  1073. expect(validateArgs(spec, { b: 'x' })).toEqual(['"b" must be a boolean'])
  1074. })
  1075. it('checks enum membership', () => {
  1076. const spec = { color: { type: 'string', enum: ['red', 'green'] } } satisfies SchemaSpec
  1077. expect(validateArgs(spec, { color: 'red' })).toEqual([])
  1078. expect(validateArgs(spec, { color: 'blue' })).toEqual(['"color" must be one of ["red","green"]'])
  1079. })
  1080. it('checks enum uniformly with the converter (enum on a non-string prop)', () => {
  1081. // The converter emits `enum` regardless of type; the validator must agree.
  1082. // `enum` is string[], so a number value can never be a member.
  1083. const spec = { n: { type: 'number', enum: ['1', '2'] } } as unknown as SchemaSpec
  1084. expect(validateArgs(spec, { n: 1 })).toEqual(['"n" must be one of ["1","2"]'])
  1085. })
  1086. it('rejects an unknown SchemaType at runtime (assertNever guard)', () => {
  1087. const spec = { x: { type: 'weird' } } as unknown as SchemaSpec
  1088. expect(() => validateArgs(spec, { x: 1 })).toThrow(/unreachable variant.*validateArgs/)
  1089. })
  1090. it('recurses into nested objects (and an object without properties only type-checks)', () => {
  1091. const spec = {
  1092. config: {
  1093. type: 'object',
  1094. required: true,
  1095. properties: { host: { type: 'string', required: true }, port: { type: 'number' } },
  1096. },
  1097. bag: { type: 'object' },
  1098. } satisfies SchemaSpec
  1099. expect(validateArgs(spec, { config: { host: 'h' }, bag: { anything: true } })).toEqual([])
  1100. expect(validateArgs(spec, { config: { port: 9 }, bag: 5 })).toEqual([
  1101. 'missing required property "config.host"',
  1102. '"bag" must be an object',
  1103. ])
  1104. })
  1105. it('recurses into array items (and an array without items only type-checks)', () => {
  1106. const spec = {
  1107. tags: { type: 'array', items: { type: 'string' } },
  1108. raw: { type: 'array' },
  1109. } satisfies SchemaSpec
  1110. expect(validateArgs(spec, { tags: ['a', 'b'], raw: [1, {}, 'x'] })).toEqual([])
  1111. expect(validateArgs(spec, { tags: ['a', 2] })).toEqual(['"tags[1]" must be a string'])
  1112. // a non-array value for an array-typed prop
  1113. expect(validateArgs(spec, { tags: 'nope' })).toEqual(['"tags" must be an array'])
  1114. })
  1115. it('validates arrays of objects element-wise', () => {
  1116. const spec = {
  1117. servers: {
  1118. type: 'array',
  1119. items: { type: 'object', properties: { host: { type: 'string', required: true } } },
  1120. },
  1121. } satisfies SchemaSpec
  1122. expect(validateArgs(spec, { servers: [{ host: 'a' }, {}] })).toEqual([
  1123. 'missing required property "servers[1].host"',
  1124. ])
  1125. })
  1126. })
  1127. describe('defineTool validation (the runtime-validation Agent Note, part 1)', () => {
  1128. it('returns an isError result with the violations when the model sends bad args', async () => {
  1129. const ctx = await setup()
  1130. ctx.tools.register(defineTool({
  1131. name: 'reader',
  1132. description: 'reads a path',
  1133. parameters: { path: { type: 'string', required: true } },
  1134. async execute(args) {
  1135. return [{ type: 'text', text: args.path }]
  1136. },
  1137. }))
  1138. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'reader', arguments: {} })
  1139. expect(result.isError).toBe(true)
  1140. expect(result.content[0]).toMatchObject({
  1141. text: 'Error: invalid arguments: missing required property "path"',
  1142. })
  1143. })
  1144. it('runs execute normally when args are valid', async () => {
  1145. const ctx = await setup()
  1146. ctx.tools.register(defineTool({
  1147. name: 'reader',
  1148. description: 'reads a path',
  1149. parameters: { path: { type: 'string', required: true } },
  1150. async execute(args) {
  1151. return [{ type: 'text', text: `read ${args.path}` }]
  1152. },
  1153. }))
  1154. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'reader', arguments: { path: '/x' } })
  1155. expect(result).toEqual({ content: [{ type: 'text', text: 'read /x' }], isError: false })
  1156. })
  1157. it('ToolArgsError carries a stable code and the violation list', () => {
  1158. const err = new ToolArgsError(['missing required property "a"', '"b" must be a number'])
  1159. expect(err).toBeInstanceOf(Error)
  1160. expect(err.name).toBe('ToolArgsError')
  1161. expect(err.code).toBe('INVALID_ARGS')
  1162. expect(err.violations).toEqual(['missing required property "a"', '"b" must be a number'])
  1163. expect(err.message).toBe('invalid arguments: missing required property "a"; "b" must be a number')
  1164. })
  1165. it('a schema-invalid call surfaces the structured error on the result', async () => {
  1166. const ctx = await setup()
  1167. ctx.tools.register(defineTool({
  1168. name: 'reader',
  1169. description: 'reads a path',
  1170. parameters: { path: { type: 'string', required: true } },
  1171. async execute(args) {
  1172. return [{ type: 'text', text: args.path }]
  1173. },
  1174. }))
  1175. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'reader', arguments: {} })
  1176. expect(result.isError).toBe(true)
  1177. expect(result.error).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' })
  1178. })
  1179. it('a tool throwing a HarnessError surfaces its name and code', async () => {
  1180. const { HarnessError } = await import('@deepseek-ai/dsh-llm')
  1181. const ctx = await setup()
  1182. ctx.tools.register({
  1183. ...echoTool,
  1184. name: 'coded',
  1185. async execute() {
  1186. throw new HarnessError('disk full', 'ENOSPC')
  1187. },
  1188. })
  1189. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'coded', arguments: {} })
  1190. expect(result.isError).toBe(true)
  1191. expect(result.error).toEqual({ name: 'HarnessError', code: 'ENOSPC' })
  1192. expect(result.content[0]).toMatchObject({ text: 'Error: disk full' })
  1193. })
  1194. it('a non-HarnessError throw has no structured error (only the text)', async () => {
  1195. const ctx = await setup()
  1196. ctx.tools.register({
  1197. ...echoTool,
  1198. name: 'plain',
  1199. async execute() {
  1200. throw new Error('just a message')
  1201. },
  1202. })
  1203. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'plain', arguments: {} })
  1204. expect(result.isError).toBe(true)
  1205. expect(result.error).toBeUndefined()
  1206. expect(result.content[0]).toMatchObject({ text: 'Error: just a message' })
  1207. })
  1208. it('raw-registered tools are NOT validated by defineTool (MCP keeps its own)', async () => {
  1209. const ctx = await setup()
  1210. // A raw ToolDefinition: no defineTool wrapping, so no validateArgs guard.
  1211. ctx.tools.register({
  1212. name: 'raw',
  1213. description: 'raw tool',
  1214. parameters: { type: 'object', properties: { path: { type: 'string' } }, required: ['path'] },
  1215. async execute(args: unknown) {
  1216. return [{ type: 'text', text: typeof args }]
  1217. },
  1218. })
  1219. // Missing the "required" path — but raw tools validate their own input, so
  1220. // this reaches execute rather than being rejected by the harness.
  1221. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'raw', arguments: {} })
  1222. expect(result.isError).toBe(false)
  1223. })
  1224. it('attaches a positive-finite timeoutMs to the definition', () => {
  1225. const tool = defineTool({
  1226. name: 'x', description: 'd', parameters: {}, timeoutMs: 30_000,
  1227. async execute() { return [{ type: 'text' as const, text: 'ok' }] },
  1228. })
  1229. expect(tool.timeoutMs).toBe(30_000)
  1230. })
  1231. it('omits timeoutMs when not declared', () => {
  1232. const tool = defineTool({
  1233. name: 'x', description: 'd', parameters: {},
  1234. async execute() { return [{ type: 'text' as const, text: 'ok' }] },
  1235. })
  1236. expect(tool.timeoutMs).toBeUndefined()
  1237. })
  1238. it('throws when timeoutMs is zero or negative', () => {
  1239. const make = (ms: number) => defineTool({
  1240. name: 'x', description: 'd', parameters: {}, timeoutMs: ms,
  1241. async execute() { return [{ type: 'text' as const, text: 'ok' }] },
  1242. })
  1243. expect(() => make(0)).toThrow('timeoutMs must be a positive finite number')
  1244. expect(() => make(-5)).toThrow('positive finite number')
  1245. })
  1246. it('throws when timeoutMs is non-finite', () => {
  1247. expect(() => defineTool({
  1248. name: 'x', description: 'd', parameters: {}, timeoutMs: Infinity,
  1249. async execute() { return [{ type: 'text' as const, text: 'ok' }] },
  1250. })).toThrow('positive finite number')
  1251. })
  1252. })
  1253. describe('defineTool presentation (presentCall / presentResult)', () => {
  1254. it('threads presentCall/presentResult onto the ToolDefinition with typed args', () => {
  1255. const tool = defineTool({
  1256. name: 'demo',
  1257. description: 'demo',
  1258. parameters: { path: { type: 'string', required: true }, n: { type: 'number' } },
  1259. async execute() { return [{ type: 'text', text: 'ok' }] },
  1260. presentCall(args) {
  1261. // args is typed { path: string; n?: number } — zero casts.
  1262. expectTypeOf(args).toEqualTypeOf<{ path: string; n?: number }>()
  1263. return { card: 'generic', title: `Open ${args.path}`, kind: 'read', rawInput: args.path }
  1264. },
  1265. presentResult(args, result) {
  1266. return { card: 'generic', title: `Opened ${args.path}`, content: result.content }
  1267. },
  1268. })
  1269. expect(tool.presentCall!({ path: '/a', n: 2 })).toEqual({ card: 'generic', title: 'Open /a', kind: 'read', rawInput: '/a' })
  1270. expect(tool.presentResult!({ path: '/a' }, { content: [{ type: 'text', text: 'x' }], isError: false }))
  1271. .toEqual({ card: 'generic', title: 'Opened /a', content: [{ type: 'text', text: 'x' }] })
  1272. })
  1273. it('a tool without presentCall/presentResult leaves them undefined (UI falls back generically)', () => {
  1274. const tool = defineTool({
  1275. name: 'plain',
  1276. description: 'plain',
  1277. parameters: { x: { type: 'string', required: true } },
  1278. async execute() { return [] },
  1279. })
  1280. expect(typeof tool.presentCall).toBe('undefined')
  1281. expect(typeof tool.presentResult).toBe('undefined')
  1282. })
  1283. it('presentCall/presentResult validate softly: malformed args return undefined, never throw (display runs on replay)', () => {
  1284. const tool = defineTool({
  1285. name: 'demo',
  1286. description: 'demo',
  1287. parameters: { path: { type: 'string', required: true } },
  1288. async execute() { return [] },
  1289. presentCall: args => ({ card: 'generic', title: args.path }),
  1290. presentResult: (args, result) => ({ card: 'generic', title: args.path, content: result.content }),
  1291. })
  1292. // Unlike execute (which throws ToolArgsError on a mismatch), the display
  1293. // methods soft-validate and fall back to undefined so a UI never crashes
  1294. // replaying an old/foreign log entry. The ToolDefinition methods take
  1295. // `unknown`, so malformed shapes pass without a cast.
  1296. expect(tool.presentCall?.({})).toBeUndefined()
  1297. expect(tool.presentResult?.({ wrong: 1 }, { content: [], isError: false })).toBeUndefined()
  1298. })
  1299. })