tools.spec.ts 104 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734
  1. import { describe, expect, expectTypeOf, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { CallId, HarnessError, type ContentBlock } 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. defineContentToolFixture, defineTool, JsonSchemaError, parameterSchemaSpecToJsonSchema, validateArgs, ToolArgsError, ToolNotFoundError,
  9. TOOL_ABORTED, TOOL_ABORTED_BEFORE_DISPATCH,
  10. type InferArgs, type JsonValue, type ParameterSchemaSpec, type PreToolDecision, type PostToolDecision,
  11. type JsonSchemaNode, type ToolDefinition, type ToolDispatchExecution, type ToolExecutionResult, type ToolExecutionToken,
  12. } from '@deepseek-ai/dsh-tools'
  13. const testToolSignal = new AbortController().signal
  14. async function setup() {
  15. const ctx = new Context()
  16. await ctx.plugin(SystemPrompt)
  17. await ctx.plugin(ToolRegistry)
  18. return ctx
  19. }
  20. const echoTool = defineTool({
  21. name: 'echo',
  22. description: 'echo arguments back',
  23. parameters: { text: { type: 'string' } },
  24. output: {
  25. schema: { type: 'string' },
  26. render: (_args, value) => [{ type: 'text', text: value }],
  27. },
  28. async execute(args) {
  29. return args.text ?? ''
  30. },
  31. })
  32. describe('ToolRegistry', () => {
  33. it('registers tools, exposes schemas, and feeds the system-prompt assembly', async () => {
  34. const ctx = await setup()
  35. ctx.tools.register(echoTool)
  36. expect(ctx.tools.schemas()).toEqual([{
  37. name: 'echo',
  38. description: 'echo arguments back',
  39. parameters: { type: 'object', properties: { text: { type: 'string' } } },
  40. }])
  41. // schemas() result must not leak execute — ToolSchema deliberately has no
  42. // 'execute' key, so widen through unknown to probe for the absent property
  43. expect((ctx.tools.schemas()[0] as unknown as Record<string, unknown>).execute).toBeUndefined()
  44. const assembly = await ctx.systemPrompt.assemble()
  45. expect(assembly.tools.map(t => t.name)).toEqual(['echo'])
  46. })
  47. it('schemas() drops host callbacks — they must never reach the model', async () => {
  48. const ctx = await setup()
  49. // Tool definitions contain output, finalization, execution, and presentation
  50. // callbacks. schemas() is an explicit allowlist so none can reach the model.
  51. ctx.tools.register(defineContentToolFixture({
  52. name: 'present',
  53. description: 'has presenters',
  54. parameters: { x: { type: 'string', required: true } },
  55. async execute() { return [] },
  56. finalizeContent: (_exec, result) => result.content,
  57. presentCall: args => ({ card: 'generic', title: args.x }),
  58. presentResult: (args, result) => ({ card: 'generic', title: args.x, content: result.content }),
  59. }))
  60. const schema = ctx.tools.schemas()[0] as unknown as Record<string, unknown>
  61. expect(Object.keys(schema).sort()).toEqual(['description', 'name', 'parameters'])
  62. expect(schema.finalizeContent).toBeUndefined()
  63. expect(schema.presentCall).toBeUndefined()
  64. expect(schema.presentResult).toBeUndefined()
  65. expect(schema.execute).toBeUndefined()
  66. })
  67. it('schemas() excludes timeoutMs — the budget must never reach the model', async () => {
  68. const ctx = await setup()
  69. ctx.tools.register(defineContentToolFixture({
  70. name: 'budgeted', description: 'has a budget', parameters: {}, timeoutMs: 5_000,
  71. async execute() { return [{ type: 'text' as const, text: 'ok' }] },
  72. }))
  73. const schema = ctx.tools.schemas().find(s => s.name === 'budgeted')
  74. expect(schema).toBeDefined()
  75. expect('timeoutMs' in (schema as object)).toBe(false)
  76. })
  77. it('executes a tool and returns its content', async () => {
  78. const ctx = await setup()
  79. ctx.tools.register(echoTool)
  80. let observed: ToolExecutionResult | undefined
  81. ctx.on('tools/result', (_exec, result) => { observed = result })
  82. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  83. expect(result).toEqual({ content: [{ type: 'text', text: 'hi' }], isError: false, value: 'hi' })
  84. expect(observed).toEqual(result)
  85. })
  86. it('projects presentation metadata from the canonical value', async () => {
  87. const ctx = await setup()
  88. ctx.tools.register({
  89. ...echoTool,
  90. name: 'meta-tool',
  91. output: {
  92. ...echoTool.output,
  93. presentationMeta: () => ({ diffs: [{ path: 'a', oldText: null, newText: 'x' }] }),
  94. },
  95. async execute() {
  96. return 'ok'
  97. },
  98. })
  99. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'meta-tool', arguments: {} })
  100. expect(result).toEqual({
  101. content: [{ type: 'text', text: 'ok' }],
  102. isError: false,
  103. meta: { diffs: [{ path: 'a', oldText: null, newText: 'x' }] },
  104. value: 'ok',
  105. })
  106. })
  107. it('omits meta when no presentation projector is declared', async () => {
  108. const ctx = await setup()
  109. ctx.tools.register({
  110. ...echoTool,
  111. name: 'no-meta-tool',
  112. async execute() {
  113. return 'ok'
  114. },
  115. })
  116. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'no-meta-tool', arguments: {} })
  117. expect(result).toEqual({ content: [{ type: 'text', text: 'ok' }], isError: false, value: 'ok' })
  118. expect('meta' in result).toBe(false)
  119. })
  120. it('normalizes a contract-violating non-cloneable result before final notification', async () => {
  121. const ctx = await setup()
  122. let observedError: boolean | undefined
  123. ctx.on('tools/result', (_exec, result) => { observedError = result.isError })
  124. ctx.tools.register({
  125. ...echoTool,
  126. name: 'bad-meta',
  127. output: {
  128. ...echoTool.output,
  129. presentationMeta: () => (() => undefined) as unknown as JsonValue,
  130. },
  131. async execute() {
  132. return 'ok'
  133. },
  134. })
  135. const result = await ctx.tools.execute({
  136. signal: testToolSignal,
  137. callId: CallId('bad-meta'), name: 'bad-meta', arguments: {},
  138. })
  139. expect(result.isError).toBe(true)
  140. expect(result.content[0]?.type === 'text' && result.content[0].text).toContain('Error:')
  141. expect(result.error).toMatchObject({ info: { name: 'ToolOutputError', code: 'INVALID_TOOL_OUTPUT' } })
  142. expect(observedError).toBe(true)
  143. })
  144. it('finalizes errors discovered while snapshotting non-content result fields', async () => {
  145. const ctx = await setup()
  146. let finalizeCalls = 0
  147. ctx.tools.register({
  148. ...echoTool,
  149. name: 'throwing-meta',
  150. output: {
  151. ...echoTool.output,
  152. presentationMeta() {
  153. const meta = {}
  154. Object.defineProperty(meta, 'value', {
  155. enumerable: true,
  156. get() { throw new Error('snapshot failed: '.repeat(100)) },
  157. })
  158. return meta
  159. },
  160. },
  161. finalizeContent(_exec, result) {
  162. finalizeCalls += 1
  163. const block = result.content[0]
  164. if (block?.type !== 'text') return undefined
  165. return [{ type: 'text', text: block.text.slice(0, 32) }]
  166. },
  167. async execute() {
  168. return 'body'
  169. },
  170. })
  171. const result = await ctx.tools.execute({
  172. signal: testToolSignal,
  173. callId: CallId('throwing-meta'), name: 'throwing-meta', arguments: {},
  174. })
  175. expect(result.isError).toBe(true)
  176. const block = result.content[0]
  177. expect(block?.type).toBe('text')
  178. expect(block?.type === 'text' ? block.text : '').toMatch(/^Error: tool "throwing-meta"/)
  179. expect(block?.type === 'text' ? block.text : '').toHaveLength(32)
  180. expect(finalizeCalls).toBe(1)
  181. })
  182. it('normalizes a throwing final content callback without invoking it again', async () => {
  183. const ctx = await setup()
  184. let finalizeCalls = 0
  185. ctx.tools.register({
  186. ...echoTool,
  187. name: 'throwing-finalizer',
  188. finalizeContent() {
  189. finalizeCalls += 1
  190. throw new Error('finalizer violated its total contract')
  191. },
  192. })
  193. const result = await ctx.tools.execute({
  194. signal: testToolSignal,
  195. callId: CallId('throwing-finalizer'), name: 'throwing-finalizer', arguments: {},
  196. })
  197. expect(result).toEqual({
  198. content: [{ type: 'text', text: 'Error: finalizer violated its total contract' }],
  199. isError: true,
  200. error: { message: 'finalizer violated its total contract' },
  201. })
  202. expect(finalizeCalls).toBe(1)
  203. })
  204. it('requires every raw registration to declare its canonical output', async () => {
  205. const ctx = await setup()
  206. const missingOutput = {
  207. name: 'legacy-content-tool',
  208. description: 'missing output',
  209. parameters: {},
  210. execute: async () => [{ type: 'text', text: 'legacy' }],
  211. } as unknown as ToolDefinition
  212. expect(() => ctx.tools.register(missingOutput))
  213. .toThrow('must declare output { schema, render, presentationMeta? }')
  214. })
  215. it('rejects lossy and schema-mismatched body values before post-execute', async () => {
  216. const ctx = await setup()
  217. ctx.tools.register(defineTool({
  218. name: 'lossy-output',
  219. description: 'lossy',
  220. parameters: {},
  221. output: { schema: { type: 'json' }, render: () => [] },
  222. execute: async () => (() => undefined) as unknown as JsonValue,
  223. }))
  224. ctx.tools.register(defineTool({
  225. name: 'wrong-output',
  226. description: 'wrong schema',
  227. parameters: {},
  228. output: { schema: { type: 'string' }, render: () => [] },
  229. execute: async () => 42 as unknown as string,
  230. }))
  231. const lossy = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('lossy'), name: 'lossy-output', arguments: {} })
  232. const mismatch = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('mismatch'), name: 'wrong-output', arguments: {} })
  233. expect(lossy.error).toMatchObject({ info: { name: 'ToolOutputError', code: 'INVALID_TOOL_OUTPUT' } })
  234. expect(lossy.content[0]?.type === 'text' ? lossy.content[0].text : '').toContain('not lossless JSON')
  235. expect(mismatch.error).toMatchObject({ info: { name: 'ToolOutputError', code: 'INVALID_TOOL_OUTPUT' } })
  236. expect(mismatch.content[0]?.type === 'text' ? mismatch.content[0].text : '').toContain('"value" must be a string')
  237. })
  238. it('classifies a throwing body snapshot as invalid tool output', async () => {
  239. const ctx = await setup()
  240. const hostile = Object.defineProperty({}, 'value', {
  241. enumerable: true,
  242. get: () => { throw new Error('body snapshot getter exploded') },
  243. })
  244. ctx.tools.register(defineTool({
  245. name: 'hostile-body',
  246. description: 'hostile body',
  247. parameters: {},
  248. output: { schema: { type: 'json' }, render: () => [] },
  249. execute: async () => hostile as JsonValue,
  250. }))
  251. const result = await ctx.tools.execute({
  252. signal: testToolSignal,
  253. callId: CallId('hostile-body'), name: 'hostile-body', arguments: {},
  254. })
  255. expect(result.error?.message).toContain('value snapshot failed: body snapshot getter exploded')
  256. expect(result.error?.info).toEqual({ name: 'ToolOutputError', code: 'INVALID_TOOL_OUTPUT' })
  257. })
  258. it.each(['render', 'presentationMeta'] as const)('contains a throwing output.%s projector as one failed call', async (projector) => {
  259. const ctx = await setup()
  260. ctx.tools.register(defineTool({
  261. name: `throwing-${projector}`,
  262. description: projector,
  263. parameters: {},
  264. output: {
  265. schema: { type: 'string' },
  266. render: () => {
  267. if (projector === 'render') throw new Error('renderer exploded')
  268. return [{ type: 'text', text: 'ok' }]
  269. },
  270. presentationMeta: () => {
  271. if (projector === 'presentationMeta') throw new Error('metadata exploded')
  272. return null
  273. },
  274. },
  275. execute: async () => 'ok',
  276. }))
  277. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId(projector), name: `throwing-${projector}`, arguments: {} })
  278. expect(result.isError).toBe(true)
  279. expect(result.error?.message)
  280. .toContain(projector === 'render' ? 'renderer exploded' : 'metadata exploded')
  281. expect(result.error?.info).toEqual({ name: 'ToolOutputError', code: 'INVALID_TOOL_OUTPUT' })
  282. expect('value' in result).toBe(false)
  283. })
  284. it.each(['render', 'presentationMeta'] as const)('contains a throwing output.%s snapshot as one failed call', async (projector) => {
  285. const ctx = await setup()
  286. const hostile = Object.defineProperty({}, 'value', {
  287. enumerable: true,
  288. get: () => { throw new Error('snapshot getter exploded') },
  289. })
  290. ctx.tools.register(defineTool({
  291. name: `hostile-${projector}`,
  292. description: projector,
  293. parameters: {},
  294. output: {
  295. schema: { type: 'string' },
  296. render: () => projector === 'render'
  297. ? hostile as unknown as ContentBlock[]
  298. : [{ type: 'text', text: 'ok' }],
  299. presentationMeta: () => projector === 'presentationMeta'
  300. ? hostile as unknown as JsonValue
  301. : null,
  302. },
  303. execute: async () => 'ok',
  304. }))
  305. const result = await ctx.tools.execute({
  306. signal: testToolSignal,
  307. callId: CallId(`hostile-${projector}`), name: `hostile-${projector}`, arguments: {},
  308. })
  309. expect(result.error?.message).toContain('snapshot getter exploded')
  310. expect(result.error?.info).toEqual({ name: 'ToolOutputError', code: 'INVALID_TOOL_OUTPUT' })
  311. })
  312. it('keeps value/meta through content replacement and recomputes both projections after value replacement', async () => {
  313. const ctx = await setup()
  314. ctx.tools.register(defineTool({
  315. name: 'projected',
  316. description: 'projected',
  317. parameters: {},
  318. output: {
  319. schema: {
  320. type: 'object',
  321. additionalProperties: false,
  322. properties: { text: { type: 'string', required: true } },
  323. },
  324. render: (_args, value) => [{ type: 'text', text: `render:${value.text}` }],
  325. presentationMeta: (_args, value) => ({ projected: value.text }),
  326. },
  327. execute: async () => ({ text: 'body' }),
  328. }))
  329. let replacement: 'content' | 'value' = 'content'
  330. ctx.on('tools/post-execute', async () => {
  331. if (replacement === 'content') {
  332. return { kind: 'accept', content: [{ type: 'text', text: 'policy content' }] }
  333. }
  334. return {
  335. kind: 'accept',
  336. value: { text: 'policy value' },
  337. additionalContexts: [{ content: [{ type: 'text', text: 'value context' }], source: { kind: 'plugin', plugin: 'test' } }],
  338. }
  339. })
  340. const content = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('content'), name: 'projected', arguments: {} })
  341. replacement = 'value'
  342. const value = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('value'), name: 'projected', arguments: {} })
  343. expect(content).toEqual({
  344. isError: false,
  345. value: { text: 'body' },
  346. content: [{ type: 'text', text: 'policy content' }],
  347. meta: { projected: 'body' },
  348. })
  349. expect(value).toEqual({
  350. isError: false,
  351. value: { text: 'policy value' },
  352. content: [{ type: 'text', text: 'render:policy value' }],
  353. meta: { projected: 'policy value' },
  354. additionalContexts: [{ content: [{ type: 'text', text: 'value context' }], source: { kind: 'plugin', plugin: 'test' } }],
  355. })
  356. })
  357. it('fails a post-execute decision that replaces both projections or supplies an invalid value', async () => {
  358. const both = await setup()
  359. both.tools.register(echoTool)
  360. both.on('tools/post-execute', async () => ({
  361. kind: 'accept',
  362. value: 'replacement',
  363. content: [{ type: 'text', text: 'also replacement' }],
  364. } as unknown as PostToolDecision))
  365. const bothResult = await both.tools.execute({ signal: testToolSignal, callId: CallId('both'), name: 'echo', arguments: {} })
  366. expect(bothResult).toMatchObject({
  367. isError: true,
  368. error: { message: 'tools/post-execute accept decision cannot replace both value and content' },
  369. })
  370. const invalid = await setup()
  371. invalid.tools.register(echoTool)
  372. invalid.on('tools/post-execute', async () => ({ kind: 'accept', value: 1 }))
  373. const invalidResult = await invalid.tools.execute({ signal: testToolSignal, callId: CallId('invalid'), name: 'echo', arguments: {} })
  374. expect(invalidResult.error).toMatchObject({ info: { code: 'INVALID_TOOL_OUTPUT' } })
  375. expect('value' in invalidResult).toBe(false)
  376. })
  377. it('turns a post-execute block into a valueless failure', async () => {
  378. const ctx = await setup()
  379. ctx.tools.register(echoTool)
  380. ctx.on('tools/post-execute', async () => ({
  381. kind: 'block',
  382. feedback: [{ type: 'text', text: 'blocked by policy' }],
  383. }))
  384. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('block'), name: 'echo', arguments: { text: 'secret' } })
  385. expect(result).toEqual({
  386. isError: true,
  387. error: { message: 'blocked by policy' },
  388. content: [{ type: 'text', text: 'blocked by policy' }],
  389. })
  390. expect('value' in result).toBe(false)
  391. })
  392. it('replaces a canonical value without manufacturing additional context', async () => {
  393. const ctx = await setup()
  394. ctx.tools.register(echoTool)
  395. ctx.on('tools/post-execute', async () => ({ kind: 'accept', value: 'replacement' }))
  396. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('replace-value'), name: 'echo', arguments: {} })
  397. expect(result).toEqual({
  398. isError: false,
  399. value: 'replacement',
  400. content: [{ type: 'text', text: 'replacement' }],
  401. })
  402. })
  403. it.each([
  404. [[], 'tool result blocked by post-execute policy'],
  405. [[{ type: 'reasoning', text: 'private rationale' }], '[reasoning content]'],
  406. ] as const)('derives a stable failure message from non-text or empty block feedback', async (feedback, message) => {
  407. const ctx = await setup()
  408. ctx.tools.register(echoTool)
  409. ctx.on('tools/post-execute', async () => ({ kind: 'block', feedback: [...feedback] }))
  410. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('block-message'), name: 'echo', arguments: {} })
  411. expect(result.error?.message).toBe(message)
  412. })
  413. it('contains a non-JSON post-execute failure projection as a safe final error', async () => {
  414. const ctx = await setup()
  415. ctx.tools.register(echoTool)
  416. ctx.on('tools/post-execute', async () => ({
  417. kind: 'block',
  418. feedback: [{ type: 'text', text: 'blocked', invalid: () => undefined } as never],
  419. }))
  420. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('invalid-block'), name: 'echo', arguments: {} })
  421. expect(result).toMatchObject({
  422. isError: true,
  423. error: { message: 'tool result must be losslessly JSON-serializable' },
  424. })
  425. })
  426. it('rejects value replacement on a failed dispatch', async () => {
  427. const ctx = await setup()
  428. ctx.tools.register({
  429. ...echoTool,
  430. name: 'throw-before-replace',
  431. async execute() { throw new Error('body failed') },
  432. })
  433. ctx.on('tools/post-execute', async () => ({ kind: 'accept', value: 'replacement' }))
  434. const result = await ctx.tools.execute({
  435. signal: testToolSignal,
  436. callId: CallId('failed-replace'), name: 'throw-before-replace', arguments: {},
  437. })
  438. expect(result.error?.message).toBe('tools/post-execute cannot replace the value of a failed result')
  439. })
  440. it('fails value replacement when the owning tool disappears before post-policy resolves', async () => {
  441. const ctx = await setup()
  442. const dispose = ctx.tools.register(echoTool)
  443. ctx.on('tools/post-execute', async () => {
  444. dispose()
  445. return { kind: 'accept', value: 'replacement' }
  446. })
  447. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('post-disposed'), name: 'echo', arguments: {} })
  448. expect(result.error).toEqual({
  449. message: 'unknown tool "echo"',
  450. info: { name: 'ToolNotFoundError', code: 'UNKNOWN_TOOL' },
  451. })
  452. })
  453. it('normalizes wrapper-authored failure metadata and contexts', async () => {
  454. const ctx = await setup()
  455. ctx.tools.register(echoTool)
  456. ctx.on('tools/execute', async () => ({
  457. isError: true,
  458. error: { message: 'wrapped failure' },
  459. content: [{ type: 'text', text: 'wrapper content' }],
  460. meta: { wrapped: true },
  461. additionalContexts: [{ content: [{ type: 'text', text: 'wrapper context' }], source: { kind: 'plugin', plugin: 'test' } }],
  462. }))
  463. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('wrapper-failure'), name: 'echo', arguments: {} })
  464. expect(result).toEqual({
  465. isError: true,
  466. error: { message: 'wrapped failure' },
  467. content: [{ type: 'text', text: 'wrapper content' }],
  468. meta: { wrapped: true },
  469. additionalContexts: [{ content: [{ type: 'text', text: 'wrapper context' }], source: { kind: 'plugin', plugin: 'test' } }],
  470. })
  471. })
  472. it('fails wrapper-authored success normalization when the owning tool disappears', async () => {
  473. const ctx = await setup()
  474. const dispose = ctx.tools.register(echoTool)
  475. ctx.on('tools/execute', async () => {
  476. dispose()
  477. return { isError: false, value: 'replacement', content: [] }
  478. })
  479. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('wrapper-disposed'), name: 'echo', arguments: {} })
  480. expect(result.error).toEqual({
  481. message: 'unknown tool "echo"',
  482. info: { name: 'ToolNotFoundError', code: 'UNKNOWN_TOOL' },
  483. })
  484. })
  485. it('suppresses presentation metadata only for nested composite dispatches', async () => {
  486. const ctx = await setup()
  487. ctx.tools.register({
  488. ...echoTool,
  489. name: 'meta-suppression',
  490. output: { ...echoTool.output, presentationMeta: () => ({ card: true }) },
  491. })
  492. const direct = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('direct'), name: 'meta-suppression', arguments: {} })
  493. const nested = await ctx.tools.execute({
  494. signal: testToolSignal,
  495. callId: CallId('nested'),
  496. name: 'meta-suppression',
  497. arguments: {},
  498. parent: Symbol('outer') as ToolExecutionToken,
  499. })
  500. expect(direct.meta).toEqual({ card: true })
  501. expect(nested.meta).toBeUndefined()
  502. expect(nested.isError ? undefined : nested.value).toBe('')
  503. })
  504. it('carries a nested conclusion on the nested result for its composite to forward', async () => {
  505. const ctx = await setup()
  506. ctx.tools.register({
  507. ...echoTool,
  508. name: 'terminal-nested',
  509. async execute(_args, exec) {
  510. exec.concludeTurn()
  511. return 'terminal'
  512. },
  513. })
  514. // A composite that forwards the marker from the nested result — the Code
  515. // Mode dispatch shape. A recovering composite (nested failure swallowed)
  516. // has no marker to forward: ToolExecutionFailure types concludesTurn as
  517. // never, so only an authoritative nested success can conclude the run.
  518. let call = 0
  519. ctx.tools.register({
  520. ...echoTool,
  521. name: 'composite',
  522. async execute(_args, exec) {
  523. call += 1
  524. const nested = await ctx.tools.execute({
  525. signal: exec.signal, callId: CallId(`nested-${call}`), name: 'terminal-nested', arguments: {}, parent: exec.token,
  526. })
  527. if (nested.concludesTurn) exec.concludeTurn()
  528. return nested.isError ? 'nested failed, composite recovered' : 'nested succeeded'
  529. },
  530. })
  531. // A policy converts the nested success into an error: the failed result
  532. // carries no marker, so the recovering composite does not conclude.
  533. const veto = ctx.on('tools/post-execute', async (exec, _result, next): Promise<PostToolDecision> => {
  534. if (exec.name !== 'terminal-nested') return next()
  535. return { kind: 'block', feedback: [{ type: 'text', text: 'nested success rejected' }] }
  536. })
  537. const recovered = await ctx.tools.execute({
  538. signal: testToolSignal, callId: CallId('composite-vetoed'), name: 'composite', arguments: {},
  539. })
  540. expect(recovered.isError).toBe(false)
  541. expect(recovered.concludesTurn).toBeUndefined()
  542. veto()
  543. // The same nested call succeeding carries the marker; the composite
  544. // forwards it onto its own successful result.
  545. const concluded = await ctx.tools.execute({
  546. signal: testToolSignal, callId: CallId('composite-ok'), name: 'composite', arguments: {},
  547. })
  548. expect(concluded.isError).toBe(false)
  549. expect(concluded.concludesTurn).toBe(true)
  550. })
  551. it('returns isError results for unknown tools and throwing tools', async () => {
  552. const ctx = await setup()
  553. ctx.tools.register({
  554. ...echoTool,
  555. name: 'boom',
  556. async execute() {
  557. throw new Error('exploded')
  558. },
  559. })
  560. const unknown = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'nope', arguments: {} })
  561. expect(unknown.isError).toBe(true)
  562. expect(unknown.content[0]).toMatchObject({ text: 'Error: unknown tool "nope"' })
  563. // An unknown tool is a routable failure class, same as a tool-thrown one.
  564. expect(unknown.error).toEqual({
  565. message: 'unknown tool "nope"',
  566. info: { name: 'ToolNotFoundError', code: 'UNKNOWN_TOOL' },
  567. })
  568. const thrown = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c2'), name: 'boom', arguments: {} })
  569. expect(thrown.isError).toBe(true)
  570. expect(thrown.content[0]).toMatchObject({ text: 'Error: exploded' })
  571. })
  572. it('normalizes a hostile thrown value whose inspection and coercion both throw', async () => {
  573. const ctx = await setup()
  574. ctx.tools.register({
  575. ...echoTool,
  576. name: 'hostile-throw',
  577. async execute() {
  578. throw new Proxy({}, {
  579. getPrototypeOf: () => { throw new Error('prototype trap') },
  580. has: () => { throw new Error('has trap') },
  581. get: () => { throw new Error('get trap') },
  582. })
  583. },
  584. })
  585. await expect(ctx.tools.execute({
  586. signal: testToolSignal,
  587. callId: CallId('hostile'), name: 'hostile-throw', arguments: {},
  588. })).resolves.toMatchObject({
  589. isError: true,
  590. content: [{ type: 'text', text: 'Error: <unprintable thrown value>' }],
  591. })
  592. })
  593. it('ToolNotFoundError carries a stable message and code', async () => {
  594. const { HarnessError } = await import('@deepseek-ai/dsh-llm')
  595. const err = new ToolNotFoundError('ghost')
  596. expect(err).toBeInstanceOf(HarnessError)
  597. expect(err.name).toBe('ToolNotFoundError')
  598. expect(err.code).toBe('UNKNOWN_TOOL')
  599. expect(err.message).toBe('unknown tool "ghost"')
  600. })
  601. it('lets a tools/pre-execute listener deny a call (permission pattern)', async () => {
  602. const ctx = await setup()
  603. ctx.tools.register(echoTool)
  604. let postSawFrozen = false
  605. ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
  606. if (exec.name === 'echo') return { kind: 'deny', reason: 'denied by policy' }
  607. return next()
  608. })
  609. ctx.on('tools/post-execute', async (_exec, result, next) => {
  610. postSawFrozen = Object.isFrozen(result)
  611. expect(Reflect.set(result, 'content', [])).toBe(false)
  612. return next()
  613. })
  614. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  615. expect(result.isError).toBe(true)
  616. expect(result.content[0]).toMatchObject({ text: 'Error: denied by policy' })
  617. expect(postSawFrozen).toBe(true)
  618. })
  619. it('an ask decision degrades to deny when no approval seam is mounted', async () => {
  620. const ctx = await setup()
  621. ctx.tools.register(echoTool)
  622. ctx.on('tools/pre-execute', async (_exec, _next): Promise<PreToolDecision> =>
  623. ({ kind: 'ask', reason: 'needs approval' }))
  624. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  625. expect(result.isError).toBe(true)
  626. expect(result.content[0]).toMatchObject({ text: 'Error: needs approval' })
  627. })
  628. it('an ask decision with no reason degrades to deny with a default message', async () => {
  629. const ctx = await setup()
  630. ctx.tools.register(echoTool)
  631. ctx.on('tools/pre-execute', async (_exec, _next): Promise<PreToolDecision> => ({ kind: 'ask' }))
  632. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  633. expect(result.isError).toBe(true)
  634. expect(result.content[0]).toMatchObject({ text: 'Error: tool "echo" requires approval (not yet supported)' })
  635. })
  636. describe('ask routing through ctx.approval', () => {
  637. /**
  638. * A minimal Agent stand-in — the approval seam reaches
  639. * `agent.session.append` and folds `.events`; the seeded open turn
  640. * satisfies request()'s enclosure precondition.
  641. */
  642. function fakeAgent(): Agent {
  643. return {
  644. session: { events: [{ type: 'turn/start' }], append: () => ({}) },
  645. } as unknown as Agent
  646. }
  647. async function approvalSetup() {
  648. const ctx = await setup()
  649. await ctx.plugin(ApprovalService)
  650. ctx.tools.register(echoTool)
  651. return ctx
  652. }
  653. it('dispatches the tool when the answerer grants allowed-once, forwarding the ask fields', async () => {
  654. const ctx = await approvalSetup()
  655. const agent = fakeAgent()
  656. const controller = new AbortController()
  657. const seen: ApprovalRequest[] = []
  658. ctx.on('approval/request', (req) => {
  659. seen.push(req)
  660. return Promise.resolve<ApprovalOutcome>('allowed-once')
  661. })
  662. ctx.on('tools/pre-execute', async (_exec, _next): Promise<PreToolDecision> =>
  663. ({ kind: 'ask', reason: 'hook wants a human' }))
  664. const result = await ctx.tools.execute({
  665. callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' }, agent, signal: controller.signal,
  666. })
  667. expect(result).toMatchObject({ isError: false, content: [{ type: 'text', text: 'hi' }] })
  668. expect(seen).toHaveLength(1)
  669. expect(seen[0]).toMatchObject({ agent, toolName: 'echo', callId: 'c1', reason: 'hook wants a human' })
  670. expect(seen[0]?.signal).toBe(controller.signal)
  671. })
  672. it('denies with the user-rejection reason on rejected', async () => {
  673. const ctx = await approvalSetup()
  674. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('rejected'))
  675. ctx.on('tools/pre-execute', async (_exec, _next): Promise<PreToolDecision> => ({ kind: 'ask' }))
  676. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'echo', arguments: {}, agent: fakeAgent() })
  677. expect(result.isError).toBe(true)
  678. expect(result.content[0]).toMatchObject({ text: 'Error: the user rejected tool "echo"' })
  679. })
  680. it('denies with the cancellation reason on cancelled', async () => {
  681. const ctx = await approvalSetup()
  682. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('cancelled'))
  683. ctx.on('tools/pre-execute', async (_exec, _next): Promise<PreToolDecision> => ({ kind: 'ask' }))
  684. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'echo', arguments: {}, agent: fakeAgent() })
  685. expect(result.isError).toBe(true)
  686. expect(result.content[0]).toMatchObject({ text: 'Error: approval for tool "echo" was cancelled' })
  687. })
  688. it('returns ABORTED_BEFORE_DISPATCH when caller cancellation overtakes approval', async () => {
  689. const ctx = await approvalSetup()
  690. const entered = Promise.withResolvers<undefined>()
  691. const release = Promise.withResolvers<ApprovalOutcome>()
  692. let dispatched = 0
  693. ctx.tools.register({
  694. ...echoTool,
  695. name: 'approval-probe',
  696. async execute() { dispatched += 1; return [] },
  697. })
  698. ctx.on('approval/request', () => {
  699. entered.resolve(undefined)
  700. return release.promise
  701. })
  702. ctx.on('tools/pre-execute', async (_exec, _next): Promise<PreToolDecision> => ({ kind: 'ask' }))
  703. const controller = new AbortController()
  704. const pending = ctx.tools.execute({
  705. callId: CallId('approval-cancelled'),
  706. name: 'approval-probe',
  707. arguments: {},
  708. agent: fakeAgent(),
  709. signal: controller.signal,
  710. })
  711. await entered.promise
  712. controller.abort('caller cancelled approval')
  713. release.resolve('allowed-once')
  714. await expect(pending).resolves.toMatchObject({
  715. isError: true,
  716. error: { info: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH } },
  717. })
  718. expect(dispatched).toBe(0)
  719. })
  720. it('denies with the no-channel reason when the seam is mounted but nobody answers', async () => {
  721. const ctx = await approvalSetup()
  722. ctx.on('tools/pre-execute', async (_exec, _next): Promise<PreToolDecision> => ({ kind: 'ask' }))
  723. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'echo', arguments: {}, agent: fakeAgent() })
  724. expect(result.isError).toBe(true)
  725. expect(result.content[0]).toMatchObject({ text: 'Error: tool "echo" requires approval, but no approval channel is available' })
  726. })
  727. it('denies an agent-less execution without asking — nothing to route or audit through', async () => {
  728. const ctx = await approvalSetup()
  729. let asked = false
  730. ctx.on('approval/request', () => {
  731. asked = true
  732. return Promise.resolve<ApprovalOutcome>('allowed-once')
  733. })
  734. ctx.on('tools/pre-execute', async (_exec, _next): Promise<PreToolDecision> => ({ kind: 'ask' }))
  735. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'echo', arguments: {} })
  736. expect(asked).toBe(false)
  737. expect(result.isError).toBe(true)
  738. expect(result.content[0]).toMatchObject({ text: 'Error: tool "echo" requires approval, but the call has no agent to route it through' })
  739. })
  740. it('turns a rogue outcome from a NON-conforming approval stand-in into an isError result', async () => {
  741. // ApprovalService normalizes rogue answers itself; this pins the
  742. // registry's own exhaustiveness backstop by shadowing the service with a
  743. // stand-in that violates the outcome contract.
  744. const ctx = await setup()
  745. ctx.tools.register(echoTool)
  746. ctx.provide('approval', { request: () => Promise.resolve('yolo') } as unknown as ApprovalService)
  747. ctx.on('tools/pre-execute', async (_exec, _next): Promise<PreToolDecision> => ({ kind: 'ask' }))
  748. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'echo', arguments: {}, agent: fakeAgent() })
  749. expect(result.isError).toBe(true)
  750. const text = result.content[0]?.type === 'text' ? result.content[0].text : ''
  751. expect(text).toContain('unreachable')
  752. })
  753. })
  754. it('a tools/post-execute listener can replace the result content (accept) ', async () => {
  755. const ctx = await setup()
  756. ctx.tools.register(echoTool)
  757. ctx.on('tools/post-execute', async (_exec, _result, _next): Promise<PostToolDecision> =>
  758. ({ kind: 'accept', content: [{ type: 'text', text: 'rewritten' }] }))
  759. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  760. expect(result.isError).toBe(false)
  761. expect(result.content[0]).toMatchObject({ text: 'rewritten' })
  762. })
  763. it('a tools/post-execute block turns the call into an isError with corrective feedback', async () => {
  764. const ctx = await setup()
  765. ctx.tools.register(echoTool)
  766. ctx.on('tools/post-execute', async (_exec, _result, _next): Promise<PostToolDecision> =>
  767. ({ kind: 'block', feedback: [{ type: 'text', text: 'output rejected: try again' }] }))
  768. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  769. expect(result.isError).toBe(true)
  770. expect(result.content[0]).toMatchObject({ text: 'output rejected: try again' })
  771. })
  772. it('runs the snapshotted final content transform after outer pipeline normalization', async () => {
  773. const ctx = await setup()
  774. const dispose = ctx.tools.register(defineContentToolFixture({
  775. name: 'bounded',
  776. description: 'bounded result',
  777. parameters: {},
  778. async execute() { return [{ type: 'text', text: 'body' }] },
  779. finalizeContent(exec, result) {
  780. expect(exec.name).toBe('bounded')
  781. expect(result.isError).toBe(true)
  782. return [{ type: 'text', text: 'bounded failure' }]
  783. },
  784. }))
  785. ctx.on('tools/pre-execute', async () => {
  786. dispose()
  787. throw new HarnessError('policy failed', 'POLICY_FAILED')
  788. })
  789. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('bounded'), name: 'bounded', arguments: {} })
  790. expect(result).toEqual({
  791. content: [{ type: 'text', text: 'bounded failure' }],
  792. isError: true,
  793. error: {
  794. message: 'policy failed',
  795. info: { name: 'HarnessError', code: 'POLICY_FAILED' },
  796. },
  797. })
  798. })
  799. it('a block decision can ALSO attach additionalContexts', async () => {
  800. const ctx = await setup()
  801. ctx.tools.register(echoTool)
  802. ctx.on('tools/post-execute', async (_exec, _result, _next): Promise<PostToolDecision> =>
  803. ({
  804. kind: 'block',
  805. feedback: [{ type: 'text', text: 'rejected' }],
  806. additionalContexts: [{ content: [{ type: 'text', text: 'why it was rejected' }], source: { kind: 'plugin', plugin: 'test' } }],
  807. }))
  808. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  809. expect(result.isError).toBe(true)
  810. expect(result.content[0]).toMatchObject({ text: 'rejected' })
  811. expect(result.additionalContexts).toMatchObject([{ content: [{ text: 'why it was rejected' }], source: { kind: 'plugin', plugin: 'test' } }])
  812. })
  813. it('post-execute additionalContexts ride on the result for the loop to buffer', async () => {
  814. const ctx = await setup()
  815. ctx.tools.register(echoTool)
  816. ctx.on('tools/post-execute', async (_exec, _result, _next): Promise<PostToolDecision> =>
  817. ({ kind: 'accept', additionalContexts: [{ content: [{ type: 'text', text: 'fyi' }], source: { kind: 'plugin', plugin: 'test' } }] }))
  818. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  819. expect(result.additionalContexts).toMatchObject([{ content: [{ text: 'fyi' }], source: { kind: 'plugin', plugin: 'test' } }])
  820. })
  821. it('preserves tool-deferred, execute-wrapper, and post-execute contexts in order', async () => {
  822. const ctx = await setup()
  823. ctx.tools.register(defineContentToolFixture({
  824. name: 'composite',
  825. description: 'composite',
  826. parameters: {},
  827. async execute(_args, exec) {
  828. exec.deferContext({ content: [{ type: 'text', text: 'nested-1' }], source: { kind: 'plugin', plugin: 'nested-1' } })
  829. exec.deferContext({ content: [{ type: 'text', text: 'nested-2' }], source: { kind: 'plugin', plugin: 'nested-2' } })
  830. return [{ type: 'text', text: 'done' }]
  831. },
  832. }))
  833. ctx.on('tools/execute', async (_exec, next) => {
  834. const result = await next()
  835. return {
  836. ...result,
  837. additionalContexts: [
  838. ...result.additionalContexts ?? [],
  839. { content: [{ type: 'text', text: 'wrapper' }], source: { kind: 'plugin', plugin: 'wrapper' } },
  840. ],
  841. }
  842. })
  843. ctx.on('tools/post-execute', async (_exec, _result, next): Promise<PostToolDecision> => {
  844. const downstream = await next()
  845. return {
  846. ...downstream,
  847. additionalContexts: [
  848. { content: [{ type: 'text', text: 'post' }], source: { kind: 'plugin', plugin: 'post' } },
  849. ...downstream.additionalContexts ?? [],
  850. ],
  851. }
  852. })
  853. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('composite'), name: 'composite', arguments: {} })
  854. expect(result.additionalContexts?.map(context => context.source)).toEqual([
  855. { kind: 'plugin', plugin: 'nested-1' },
  856. { kind: 'plugin', plugin: 'nested-2' },
  857. { kind: 'plugin', plugin: 'wrapper' },
  858. { kind: 'plugin', plugin: 'post' },
  859. ])
  860. })
  861. it('keeps deferred contexts when a composite tool throws, but drops them when the outer call is blocked', async () => {
  862. const ctx = await setup()
  863. ctx.tools.register(defineContentToolFixture({
  864. name: 'failing-composite',
  865. description: 'failing composite',
  866. parameters: {},
  867. async execute(_args, exec) {
  868. exec.deferContext({ content: [{ type: 'text', text: 'nested' }], source: { kind: 'plugin', plugin: 'nested' } })
  869. throw new Error('outer failure')
  870. },
  871. }))
  872. const failed = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('failed'), name: 'failing-composite', arguments: {} })
  873. expect(failed.isError).toBe(true)
  874. expect(failed.additionalContexts?.map(context => context.source)).toEqual([{ kind: 'plugin', plugin: 'nested' }])
  875. ctx.on('tools/post-execute', async (): Promise<PostToolDecision> => ({
  876. kind: 'block',
  877. feedback: [{ type: 'text', text: 'blocked' }],
  878. additionalContexts: [{ content: [{ type: 'text', text: 'block-only' }], source: { kind: 'plugin', plugin: 'blocker' } }],
  879. }))
  880. const blocked = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('blocked'), name: 'failing-composite', arguments: {} })
  881. expect(blocked.isError).toBe(true)
  882. expect(blocked.additionalContexts?.map(context => context.source)).toEqual([{ kind: 'plugin', plugin: 'blocker' }])
  883. })
  884. it('composes pre + post waterfalls around dispatch (sandbox-wrap pattern)', async () => {
  885. const ctx = await setup()
  886. ctx.tools.register(echoTool)
  887. const order: string[] = []
  888. ctx.on('tools/pre-execute', async (_exec, next) => {
  889. order.push('pre:before')
  890. const decision = await next()
  891. order.push('pre:after')
  892. return decision
  893. })
  894. ctx.on('tools/post-execute', async (_exec, _result, next) => {
  895. order.push('post:before')
  896. const decision = await next()
  897. order.push('post:after')
  898. return decision
  899. })
  900. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'echo', arguments: { text: 'x' } })
  901. expect(result.isError).toBe(false)
  902. // pre runs fully (gate) before dispatch, then post runs over the result.
  903. expect(order).toEqual(['pre:before', 'pre:after', 'post:before', 'post:after'])
  904. })
  905. it('runs tools/execute after an allowed pre-execute, around dispatch, and before post-execute', async () => {
  906. const ctx = await setup()
  907. const order: string[] = []
  908. ctx.tools.register(defineContentToolFixture({
  909. name: 'traced',
  910. description: 'echo',
  911. parameters: { text: { type: 'string' } },
  912. async execute(args) {
  913. order.push('dispatch')
  914. return [{ type: 'text' as const, text: args.text ?? '' }]
  915. },
  916. }))
  917. ctx.on('tools/pre-execute', async (_exec, next) => { order.push('pre'); return next() })
  918. ctx.on('tools/execute', async (_exec: ToolDispatchExecution, next: () => Promise<ToolExecutionResult>): Promise<ToolExecutionResult> => {
  919. order.push('execute:before')
  920. const result = await next()
  921. order.push('execute:after')
  922. return result
  923. })
  924. ctx.on('tools/post-execute', async (_exec, _result, next) => { order.push('post'); return next() })
  925. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'traced', arguments: { text: 'hi' } })
  926. expect(result).toEqual({ content: [{ type: 'text', text: 'hi' }], isError: false, value: [{ type: 'text', text: 'hi' }] })
  927. // The around seam wraps dispatch; pre gates before it, post runs over its result.
  928. expect(order).toEqual(['pre', 'execute:before', 'dispatch', 'execute:after', 'post'])
  929. })
  930. it('skips dispatch when caller cancellation arrives while pre-execute awaits', async () => {
  931. const ctx = await setup()
  932. let dispatched = 0
  933. ctx.tools.register({
  934. ...echoTool,
  935. name: 'must-not-run',
  936. async execute() { dispatched += 1; return [] },
  937. })
  938. const entered = Promise.withResolvers<undefined>()
  939. const release = Promise.withResolvers<undefined>()
  940. ctx.on('tools/pre-execute', async (_exec, next) => {
  941. entered.resolve(undefined)
  942. await release.promise
  943. return await next()
  944. })
  945. const controller = new AbortController()
  946. const pending = ctx.tools.execute({
  947. callId: CallId('cancelled-in-pre'), name: 'must-not-run', arguments: {}, signal: controller.signal,
  948. })
  949. await entered.promise
  950. controller.abort('cancelled in policy')
  951. release.resolve(undefined)
  952. await expect(pending).resolves.toMatchObject({
  953. content: [{ type: 'text', text: 'Error: tool call aborted before dispatch' }],
  954. isError: true,
  955. error: { info: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH } },
  956. })
  957. expect(dispatched).toBe(0)
  958. })
  959. it('preserves a pre-execute denial that settles after cancellation', async () => {
  960. const ctx = await setup()
  961. let dispatched = 0
  962. ctx.tools.register({
  963. ...echoTool,
  964. name: 'denied-after-cancel',
  965. async execute() { dispatched += 1; return [] },
  966. })
  967. const entered = Promise.withResolvers<undefined>()
  968. const release = Promise.withResolvers<undefined>()
  969. ctx.on('tools/pre-execute', async () => {
  970. entered.resolve(undefined)
  971. await release.promise
  972. return { kind: 'deny', reason: 'policy denied the call' }
  973. })
  974. const controller = new AbortController()
  975. const pending = ctx.tools.execute({
  976. callId: CallId('denied-after-cancel'), name: 'denied-after-cancel', arguments: {}, signal: controller.signal,
  977. })
  978. await entered.promise
  979. controller.abort('cancelled while policy decided')
  980. release.resolve(undefined)
  981. await expect(pending).resolves.toEqual({
  982. content: [{ type: 'text', text: 'Error: policy denied the call' }],
  983. isError: true,
  984. error: { message: 'policy denied the call' },
  985. })
  986. expect(dispatched).toBe(0)
  987. })
  988. it('preserves an async pre-execute failure that settles after cancellation', async () => {
  989. const ctx = await setup()
  990. let dispatched = 0
  991. ctx.tools.register({
  992. ...echoTool,
  993. name: 'must-not-run',
  994. async execute() { dispatched += 1; return [] },
  995. })
  996. const entered = Promise.withResolvers<undefined>()
  997. const release = Promise.withResolvers<undefined>()
  998. ctx.on('tools/pre-execute', async () => {
  999. entered.resolve(undefined)
  1000. await release.promise
  1001. throw new Error('gate interrupted')
  1002. })
  1003. const controller = new AbortController()
  1004. const pending = ctx.tools.execute({
  1005. callId: CallId('cancelled-pre-error'), name: 'must-not-run', arguments: {}, signal: controller.signal,
  1006. })
  1007. await entered.promise
  1008. controller.abort('cancelled in policy')
  1009. release.resolve(undefined)
  1010. await expect(pending).resolves.toEqual({
  1011. content: [{ type: 'text', text: 'Error: gate interrupted' }],
  1012. isError: true,
  1013. error: { message: 'gate interrupted' },
  1014. })
  1015. expect(dispatched).toBe(0)
  1016. })
  1017. it('rechecks caller cancellation after an async around-dispatch wrapper delegates', async () => {
  1018. const ctx = await setup()
  1019. let dispatched = 0
  1020. ctx.tools.register({
  1021. ...echoTool,
  1022. name: 'must-not-run',
  1023. async execute() { dispatched += 1; return [] },
  1024. })
  1025. const entered = Promise.withResolvers<undefined>()
  1026. const release = Promise.withResolvers<undefined>()
  1027. const replacement = new AbortController()
  1028. ctx.on('tools/execute', async (exec, next) => {
  1029. const upstream = exec.signal
  1030. exec.signal = replacement.signal
  1031. try {
  1032. entered.resolve(undefined)
  1033. await release.promise
  1034. return await next()
  1035. } finally {
  1036. exec.signal = upstream
  1037. }
  1038. })
  1039. const controller = new AbortController()
  1040. const pending = ctx.tools.execute({
  1041. callId: CallId('cancelled-in-around'), name: 'must-not-run', arguments: {}, signal: controller.signal,
  1042. })
  1043. await entered.promise
  1044. controller.abort('cancelled in wrapper')
  1045. release.resolve(undefined)
  1046. await expect(pending).resolves.toMatchObject({
  1047. isError: true,
  1048. error: { info: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH } },
  1049. })
  1050. expect(dispatched).toBe(0)
  1051. })
  1052. it('skips dispatch when an around wrapper supplies an already-aborted signal', async () => {
  1053. const ctx = await setup()
  1054. let dispatched = 0
  1055. ctx.tools.register({
  1056. ...echoTool,
  1057. name: 'must-not-run',
  1058. async execute() { dispatched += 1; return [] },
  1059. })
  1060. const replacement = AbortSignal.abort('wrapper cancelled')
  1061. ctx.on('tools/execute', async (exec, next) => {
  1062. const upstream = exec.signal
  1063. exec.signal = replacement
  1064. try {
  1065. return await next()
  1066. } finally {
  1067. exec.signal = upstream
  1068. }
  1069. })
  1070. const controller = new AbortController()
  1071. const result = await ctx.tools.execute({
  1072. callId: CallId('cancelled-wrapper'), name: 'must-not-run', arguments: {}, signal: controller.signal,
  1073. })
  1074. expect(result.error).toEqual({
  1075. message: 'tool call aborted before dispatch',
  1076. info: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH },
  1077. })
  1078. expect(dispatched).toBe(0)
  1079. })
  1080. it('uses ABORTED_BEFORE_DISPATCH when cancellation overtakes a wrapper short-circuit', async () => {
  1081. const ctx = await setup()
  1082. let dispatched = 0
  1083. ctx.tools.register({
  1084. ...echoTool,
  1085. name: 'short-circuited',
  1086. async execute() { dispatched += 1; return [] },
  1087. })
  1088. const entered = Promise.withResolvers<undefined>()
  1089. const release = Promise.withResolvers<undefined>()
  1090. ctx.on('tools/execute', async () => {
  1091. entered.resolve(undefined)
  1092. await release.promise
  1093. return {
  1094. value: 'wrapper success',
  1095. content: [{ type: 'text', text: 'wrapper success' }],
  1096. isError: false,
  1097. additionalContexts: [{
  1098. content: [{ type: 'text', text: 'wrapper context' }],
  1099. source: { kind: 'plugin', plugin: 'wrapper' },
  1100. }],
  1101. }
  1102. })
  1103. const controller = new AbortController()
  1104. const pending = ctx.tools.execute({
  1105. callId: CallId('cancelled-short-circuit'),
  1106. name: 'short-circuited',
  1107. arguments: {},
  1108. signal: controller.signal,
  1109. })
  1110. await entered.promise
  1111. controller.abort('cancelled while wrapper waited')
  1112. release.resolve(undefined)
  1113. await expect(pending).resolves.toMatchObject({
  1114. content: [{ type: 'text', text: 'Error: tool call aborted before dispatch' }],
  1115. isError: true,
  1116. error: { info: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH } },
  1117. additionalContexts: [{ source: { kind: 'plugin', plugin: 'wrapper' } }],
  1118. })
  1119. expect(dispatched).toBe(0)
  1120. })
  1121. it('replaces a late wrapper success with ABORTED and preserves deferred contexts', async () => {
  1122. const ctx = await setup()
  1123. ctx.tools.register({
  1124. ...echoTool,
  1125. name: 'completed-before-wrapper',
  1126. async execute(_args, exec) {
  1127. exec.deferContext({
  1128. content: [{ type: 'text', text: 'completed child work' }],
  1129. source: { kind: 'plugin', plugin: 'child' },
  1130. })
  1131. return 'body complete'
  1132. },
  1133. })
  1134. const entered = Promise.withResolvers<undefined>()
  1135. const release = Promise.withResolvers<undefined>()
  1136. ctx.on('tools/execute', async (_exec, next) => {
  1137. const result = await next()
  1138. entered.resolve(undefined)
  1139. await release.promise
  1140. return result
  1141. })
  1142. const controller = new AbortController()
  1143. const pending = ctx.tools.execute({
  1144. callId: CallId('cancelled-after-body'), name: 'completed-before-wrapper', arguments: {}, signal: controller.signal,
  1145. })
  1146. await entered.promise
  1147. controller.abort('cancelled while wrapper settled')
  1148. release.resolve(undefined)
  1149. await expect(pending).resolves.toMatchObject({
  1150. content: [{ type: 'text', text: 'Error: tool call aborted' }],
  1151. isError: true,
  1152. error: { info: { name: 'AbortError', code: TOOL_ABORTED } },
  1153. additionalContexts: [{ source: { kind: 'plugin', plugin: 'child' } }],
  1154. })
  1155. })
  1156. it('replaces a late post-execute success with ABORTED and preserves contexts', async () => {
  1157. const ctx = await setup()
  1158. ctx.tools.register({
  1159. ...echoTool,
  1160. name: 'completed-before-post',
  1161. async execute(_args, exec) {
  1162. exec.deferContext({
  1163. content: [{ type: 'text', text: 'completed child work' }],
  1164. source: { kind: 'plugin', plugin: 'child' },
  1165. })
  1166. return 'body complete'
  1167. },
  1168. })
  1169. const entered = Promise.withResolvers<undefined>()
  1170. const release = Promise.withResolvers<undefined>()
  1171. ctx.on('tools/post-execute', async (_exec, _result, next) => {
  1172. const decision = await next()
  1173. entered.resolve(undefined)
  1174. await release.promise
  1175. return {
  1176. ...decision,
  1177. additionalContexts: [{
  1178. content: [{ type: 'text', text: 'post context' }],
  1179. source: { kind: 'plugin', plugin: 'post' },
  1180. }],
  1181. }
  1182. })
  1183. const controller = new AbortController()
  1184. const pending = ctx.tools.execute({
  1185. callId: CallId('cancelled-in-post'), name: 'completed-before-post', arguments: {}, signal: controller.signal,
  1186. })
  1187. await entered.promise
  1188. controller.abort('cancelled while post policy waits')
  1189. release.resolve(undefined)
  1190. await expect(pending).resolves.toMatchObject({
  1191. content: [{ type: 'text', text: 'Error: tool call aborted' }],
  1192. isError: true,
  1193. error: { info: { name: 'AbortError', code: TOOL_ABORTED } },
  1194. additionalContexts: [
  1195. { source: { kind: 'plugin', plugin: 'child' } },
  1196. { source: { kind: 'plugin', plugin: 'post' } },
  1197. ],
  1198. })
  1199. })
  1200. it('preserves an around-dispatch failure that settles after cancellation', async () => {
  1201. const ctx = await setup()
  1202. let dispatched = 0
  1203. ctx.tools.register({
  1204. ...echoTool,
  1205. name: 'wrapper-failure',
  1206. async execute() { dispatched += 1; return [] },
  1207. })
  1208. const entered = Promise.withResolvers<undefined>()
  1209. const release = Promise.withResolvers<undefined>()
  1210. ctx.on('tools/execute', async () => {
  1211. entered.resolve(undefined)
  1212. await release.promise
  1213. throw new HarnessError('wrapper failed', 'WRAPPER_FAILURE')
  1214. })
  1215. const controller = new AbortController()
  1216. const pending = ctx.tools.execute({
  1217. callId: CallId('wrapper-failure'), name: 'wrapper-failure', arguments: {}, signal: controller.signal,
  1218. })
  1219. await entered.promise
  1220. controller.abort('cancelled while wrapper failed')
  1221. release.resolve(undefined)
  1222. await expect(pending).resolves.toMatchObject({
  1223. content: [{ type: 'text', text: 'Error: wrapper failed' }],
  1224. isError: true,
  1225. error: { info: { name: 'HarnessError', code: 'WRAPPER_FAILURE' } },
  1226. })
  1227. expect(dispatched).toBe(0)
  1228. })
  1229. it('preserves a tool-owned failure after the body observes cancellation', async () => {
  1230. const ctx = await setup()
  1231. const entered = Promise.withResolvers<undefined>()
  1232. ctx.tools.register({
  1233. ...echoTool,
  1234. name: 'tool-failure',
  1235. execute(_args, exec) {
  1236. entered.resolve(undefined)
  1237. return new Promise<never>((_resolve, reject) => {
  1238. exec.signal.addEventListener('abort', () => {
  1239. reject(new HarnessError('tool failed', 'TOOL_FAILURE'))
  1240. }, { once: true })
  1241. })
  1242. },
  1243. })
  1244. const controller = new AbortController()
  1245. const pending = ctx.tools.execute({
  1246. callId: CallId('tool-failure'), name: 'tool-failure', arguments: {}, signal: controller.signal,
  1247. })
  1248. await entered.promise
  1249. controller.abort('cancelled running body')
  1250. await expect(pending).resolves.toMatchObject({
  1251. content: [{ type: 'text', text: 'Error: tool failed' }],
  1252. isError: true,
  1253. error: { info: { name: 'HarnessError', code: 'TOOL_FAILURE' } },
  1254. })
  1255. })
  1256. it('preserves a post-policy failure that settles after cancellation', async () => {
  1257. const ctx = await setup()
  1258. ctx.tools.register(echoTool)
  1259. const entered = Promise.withResolvers<undefined>()
  1260. const release = Promise.withResolvers<undefined>()
  1261. ctx.on('tools/post-execute', async () => {
  1262. entered.resolve(undefined)
  1263. await release.promise
  1264. throw new HarnessError('post-policy failed', 'POST_FAILURE')
  1265. })
  1266. const controller = new AbortController()
  1267. const pending = ctx.tools.execute({
  1268. callId: CallId('post-failure'), name: 'echo', arguments: {}, signal: controller.signal,
  1269. })
  1270. await entered.promise
  1271. controller.abort('cancelled while post-policy failed')
  1272. release.resolve(undefined)
  1273. await expect(pending).resolves.toMatchObject({
  1274. content: [{ type: 'text', text: 'Error: post-policy failed' }],
  1275. isError: true,
  1276. error: { info: { name: 'HarnessError', code: 'POST_FAILURE' } },
  1277. })
  1278. })
  1279. it('fuses caller cancellation back into a wrapper replacement for the running body', async () => {
  1280. const ctx = await setup()
  1281. const entered = Promise.withResolvers<undefined>()
  1282. const replacement = new AbortController()
  1283. let bodySignal: AbortSignal | undefined
  1284. ctx.tools.register({
  1285. ...echoTool,
  1286. name: 'cooperative',
  1287. execute(_args, exec) {
  1288. bodySignal = exec.signal
  1289. entered.resolve(undefined)
  1290. if (exec.signal.aborted) return Promise.resolve('stopped')
  1291. return new Promise<string>((resolve) => {
  1292. exec.signal.addEventListener('abort', () => { resolve('stopped') }, { once: true })
  1293. })
  1294. },
  1295. })
  1296. ctx.on('tools/execute', async (exec, next) => {
  1297. const upstream = exec.signal
  1298. exec.signal = replacement.signal
  1299. try {
  1300. return await next()
  1301. } finally {
  1302. exec.signal = upstream
  1303. }
  1304. })
  1305. const controller = new AbortController()
  1306. const pending = ctx.tools.execute({
  1307. callId: CallId('cancelled-body'), name: 'cooperative', arguments: {}, signal: controller.signal,
  1308. })
  1309. await entered.promise
  1310. expect(bodySignal).not.toBe(controller.signal)
  1311. expect(bodySignal).not.toBe(replacement.signal)
  1312. controller.abort('cancel running body')
  1313. await expect(pending).resolves.toMatchObject({
  1314. isError: true,
  1315. error: { info: { name: 'AbortError', code: TOOL_ABORTED } },
  1316. })
  1317. expect(bodySignal?.aborted).toBe(true)
  1318. expect(replacement.signal.aborted).toBe(false)
  1319. })
  1320. it('restores the required caller signal after around dispatch', async () => {
  1321. const ctx = await setup()
  1322. let postSignal: AbortSignal | undefined
  1323. ctx.on('tools/execute', async (exec, next) => {
  1324. const upstream = exec.signal
  1325. exec.signal = new AbortController().signal
  1326. try {
  1327. return await next()
  1328. } finally {
  1329. exec.signal = upstream
  1330. }
  1331. })
  1332. ctx.on('tools/post-execute', async (exec, _result, next) => {
  1333. postSignal = exec.signal
  1334. return next()
  1335. })
  1336. const controller = new AbortController()
  1337. await ctx.tools.execute({
  1338. callId: CallId('restored-signal'), name: 'echo', arguments: {}, signal: controller.signal,
  1339. })
  1340. expect(postSignal).toBe(controller.signal)
  1341. })
  1342. it('waits for an uncooperative started body before returning ABORTED', async () => {
  1343. const ctx = await setup()
  1344. const entered = Promise.withResolvers<undefined>()
  1345. const release = Promise.withResolvers<string>()
  1346. ctx.tools.register({
  1347. ...echoTool,
  1348. name: 'uncooperative',
  1349. execute(_args, exec) {
  1350. exec.deferContext({
  1351. content: [{ type: 'text', text: 'nested outcome' }],
  1352. source: { kind: 'plugin', plugin: 'nested' },
  1353. })
  1354. entered.resolve(undefined)
  1355. return release.promise
  1356. },
  1357. })
  1358. const controller = new AbortController()
  1359. const pending = ctx.tools.execute({
  1360. callId: CallId('drain-body'), name: 'uncooperative', arguments: {}, signal: controller.signal,
  1361. })
  1362. await entered.promise
  1363. controller.abort('must still drain')
  1364. const state = await Promise.race([
  1365. pending.then(() => 'settled' as const),
  1366. Promise.resolve('pending' as const),
  1367. ])
  1368. expect(state).toBe('pending')
  1369. release.resolve('settled')
  1370. await expect(pending).resolves.toMatchObject({
  1371. isError: true,
  1372. error: { info: { name: 'AbortError', code: TOOL_ABORTED } },
  1373. additionalContexts: [{ source: { kind: 'plugin', plugin: 'nested' } }],
  1374. })
  1375. })
  1376. it('materializes a pre-aborted call and publishes one result without entering pipeline phases', async () => {
  1377. const ctx = await setup()
  1378. const phases = { pre: 0, around: 0, body: 0, post: 0, result: 0 }
  1379. const callerArguments = { nested: { value: 1 } }
  1380. const callerSignal = AbortSignal.abort('already cancelled')
  1381. let argumentReads = 0
  1382. let observedArguments: unknown
  1383. let observedExecution: object | undefined
  1384. let observedToken: symbol | undefined
  1385. let observedSignal: AbortSignal | undefined
  1386. let observedResult: ToolExecutionResult | undefined
  1387. ctx.tools.register({
  1388. ...echoTool,
  1389. name: 'domain-abort',
  1390. async execute() { phases.body += 1; return [] },
  1391. })
  1392. ctx.on('tools/pre-execute', async (_exec, next) => { phases.pre += 1; return next() })
  1393. ctx.on('tools/execute', async (_exec, next) => { phases.around += 1; return next() })
  1394. ctx.on('tools/post-execute', async (_exec, _result, next) => { phases.post += 1; return next() })
  1395. ctx.on('tools/result', (exec, result) => {
  1396. phases.result += 1
  1397. observedExecution = exec
  1398. observedArguments = exec.arguments
  1399. observedToken = exec.token
  1400. observedSignal = exec.signal
  1401. observedResult = result
  1402. })
  1403. const result = await ctx.tools.execute({
  1404. callId: CallId('pre-aborted'),
  1405. name: 'domain-abort',
  1406. get arguments() { argumentReads += 1; return callerArguments },
  1407. signal: callerSignal,
  1408. })
  1409. expect(argumentReads).toBe(1)
  1410. expect(phases).toEqual({ pre: 0, around: 0, body: 0, post: 0, result: 1 })
  1411. expect(result).toEqual({
  1412. content: [{ type: 'text', text: 'Error: tool call aborted before dispatch' }],
  1413. isError: true,
  1414. error: {
  1415. message: 'tool call aborted before dispatch',
  1416. info: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH },
  1417. },
  1418. })
  1419. expect(observedResult).toBe(result)
  1420. expect(Object.isFrozen(observedExecution)).toBe(true)
  1421. expect(typeof observedToken).toBe('symbol')
  1422. expect(observedSignal).toBe(callerSignal)
  1423. expect(Object.isFrozen(result)).toBe(true)
  1424. expect(observedArguments).not.toBe(callerArguments)
  1425. expect(Object.isFrozen(observedArguments)).toBe(true)
  1426. expect(Object.isFrozen((observedArguments as { nested: object }).nested)).toBe(true)
  1427. })
  1428. it('lets argument materialization failure win over a pre-aborted signal', async () => {
  1429. const ctx = await setup()
  1430. let observed = 0
  1431. ctx.on('tools/result', () => { observed += 1 })
  1432. const result = await ctx.tools.execute({
  1433. callId: CallId('invalid-pre-aborted'),
  1434. name: 'missing',
  1435. arguments: { invalid: () => undefined },
  1436. signal: AbortSignal.abort('already cancelled'),
  1437. })
  1438. expect(result).toEqual({
  1439. content: [{ type: 'text', text: 'Error: tool execution arguments must be losslessly JSON-serializable' }],
  1440. isError: true,
  1441. error: { message: 'tool execution arguments must be losslessly JSON-serializable' },
  1442. })
  1443. expect(observed).toBe(1)
  1444. })
  1445. it('a pre-execute deny short-circuits before tools/execute (the seam never runs)', async () => {
  1446. const ctx = await setup()
  1447. ctx.tools.register(echoTool)
  1448. let entered = false
  1449. ctx.on('tools/pre-execute', async (_exec, _next): Promise<PreToolDecision> => ({ kind: 'deny', reason: 'nope' }))
  1450. ctx.on('tools/execute', async (_exec: ToolDispatchExecution, next: () => Promise<ToolExecutionResult>): Promise<ToolExecutionResult> => {
  1451. entered = true
  1452. return next()
  1453. })
  1454. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  1455. expect(result.isError).toBe(true)
  1456. expect(result.content[0]).toMatchObject({ text: 'Error: nope' })
  1457. expect(entered).toBe(false) // a denied call never enters the around-dispatch seam
  1458. })
  1459. it('a thrown tool is normalized to an isError result BEFORE a tools/execute listener sees next()', async () => {
  1460. const ctx = await setup()
  1461. ctx.tools.register({
  1462. ...echoTool,
  1463. name: 'boom',
  1464. async execute() { throw new HarnessError('kaboom', 'BOOM') },
  1465. })
  1466. let seen: { isError: boolean; error?: unknown } | undefined
  1467. ctx.on('tools/execute', async (_exec: ToolDispatchExecution, next: () => Promise<ToolExecutionResult>): Promise<ToolExecutionResult> => {
  1468. const result = await next()
  1469. // The base next() IS dispatch-with-normalization: the wrapper sees the
  1470. // normalized isError result, never a raw throw from the tool body.
  1471. seen = { isError: result.isError, error: result.error }
  1472. return result
  1473. })
  1474. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'boom', arguments: {} })
  1475. expect(seen).toEqual({
  1476. isError: true,
  1477. error: { message: 'kaboom', info: { name: 'HarnessError', code: 'BOOM' } },
  1478. })
  1479. expect(result.isError).toBe(true)
  1480. expect(result.content[0]).toMatchObject({ text: 'Error: kaboom' })
  1481. })
  1482. it('freezes core dispatch outcomes before around and post listeners can observe them', async () => {
  1483. const ctx = await setup()
  1484. ctx.tools.register(echoTool)
  1485. const mutationAttempts: boolean[] = []
  1486. ctx.on('tools/execute', async (_exec, next) => {
  1487. const result = await next()
  1488. mutationAttempts.push(Reflect.set(result, 'value', 'around mutation'))
  1489. return result
  1490. })
  1491. ctx.on('tools/post-execute', async (_exec, result, next) => {
  1492. mutationAttempts.push(Reflect.set(result, 'value', 'post mutation'))
  1493. return next()
  1494. })
  1495. const result = await ctx.tools.execute({
  1496. signal: testToolSignal,
  1497. callId: CallId('frozen-canonical'), name: 'echo', arguments: { text: 'original' },
  1498. })
  1499. expect(mutationAttempts).toEqual([false, false])
  1500. expect(result.isError ? undefined : result.value).toBe('original')
  1501. })
  1502. it('a thrown tool normalized inside tools/execute still reaches post-execute', async () => {
  1503. const ctx = await setup()
  1504. ctx.tools.register({
  1505. ...echoTool,
  1506. name: 'boom',
  1507. async execute() { throw new Error('exploded') },
  1508. })
  1509. let postSaw: boolean | undefined
  1510. ctx.on('tools/execute', async (_exec: ToolDispatchExecution, next: () => Promise<ToolExecutionResult>): Promise<ToolExecutionResult> => next())
  1511. ctx.on('tools/post-execute', async (_exec, result, next) => {
  1512. postSaw = result.isError
  1513. return next()
  1514. })
  1515. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'boom', arguments: {} })
  1516. expect(postSaw).toBe(true) // the normalized isError still flows through post-execute
  1517. expect(result.isError).toBe(true)
  1518. expect(result.content[0]).toMatchObject({ text: 'Error: exploded' })
  1519. })
  1520. it('re-fuses the caller signal with an around-dispatch replacement for the body', async () => {
  1521. const ctx = await setup()
  1522. let seenSignal: AbortSignal | undefined
  1523. ctx.tools.register({
  1524. ...echoTool,
  1525. name: 'signal-probe',
  1526. async execute(_args, exec) {
  1527. seenSignal = exec.signal
  1528. return 'ok'
  1529. },
  1530. })
  1531. const upstream = new AbortController().signal
  1532. const replacement = new AbortController().signal
  1533. ctx.on('tools/execute', async (exec: ToolDispatchExecution, next: () => Promise<ToolExecutionResult>): Promise<ToolExecutionResult> => {
  1534. expect(exec.signal).toBe(upstream)
  1535. // Cordis next() ignores passed arguments, so a wrapper mutates exec in
  1536. // place (the documented "mutate the shared object, then delegate" idiom).
  1537. exec.signal = replacement
  1538. return next()
  1539. })
  1540. await ctx.tools.execute({ callId: CallId('c1'), name: 'signal-probe', arguments: {}, signal: upstream })
  1541. expect(seenSignal).toBeDefined()
  1542. expect(seenSignal).not.toBe(upstream)
  1543. expect(seenSignal).not.toBe(replacement)
  1544. })
  1545. it('a tools/execute listener can short-circuit dispatch by returning a result without next()', async () => {
  1546. const ctx = await setup()
  1547. let dispatched = false
  1548. ctx.tools.register({
  1549. ...echoTool,
  1550. name: 'never-runs',
  1551. async execute() { dispatched = true; return 'unreachable' },
  1552. })
  1553. ctx.on('tools/execute', async (_exec: ToolDispatchExecution, _next: () => Promise<ToolExecutionResult>): Promise<ToolExecutionResult> =>
  1554. ({ content: [{ type: 'text', text: 'ignored authored content' }], isError: false, value: 'short-circuited' }))
  1555. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'never-runs', arguments: {} })
  1556. expect(dispatched).toBe(false) // returning without next() skips core dispatch
  1557. expect(result.content[0]).toMatchObject({ text: 'short-circuited' })
  1558. })
  1559. it('revalidates a cached canonical result returned from a different dispatch', async () => {
  1560. const ctx = await setup()
  1561. ctx.tools.register({ ...echoTool, name: 'string-output', async execute() { return 'cached' } })
  1562. let objectBodyRan = false
  1563. ctx.tools.register(defineTool({
  1564. name: 'object-output',
  1565. description: 'Return one closed object.',
  1566. parameters: {},
  1567. output: {
  1568. schema: {
  1569. type: 'object',
  1570. properties: { ok: { type: 'boolean', required: true } },
  1571. additionalProperties: false,
  1572. },
  1573. render: (_args, value) => [{ type: 'text', text: String(value.ok) }],
  1574. },
  1575. execute() {
  1576. objectBodyRan = true
  1577. return Promise.resolve({ ok: true })
  1578. },
  1579. }))
  1580. let cached: ToolExecutionResult | undefined
  1581. ctx.on('tools/execute', async (exec, next) => {
  1582. if (exec.name === 'string-output') {
  1583. cached = await next()
  1584. return cached
  1585. }
  1586. if (exec.name === 'object-output') {
  1587. if (cached === undefined) throw new Error('expected the first dispatch result')
  1588. return cached
  1589. }
  1590. return next()
  1591. })
  1592. const first = await ctx.tools.execute({
  1593. signal: testToolSignal, callId: CallId('cached-first'), name: 'string-output', arguments: {},
  1594. })
  1595. const second = await ctx.tools.execute({
  1596. signal: testToolSignal, callId: CallId('cached-second'), name: 'object-output', arguments: {},
  1597. })
  1598. expect(first.isError ? undefined : first.value).toBe('cached')
  1599. expect(objectBodyRan).toBe(false)
  1600. expect(second).toMatchObject({
  1601. isError: true,
  1602. error: { info: { name: 'ToolOutputError', code: 'INVALID_TOOL_OUTPUT' } },
  1603. })
  1604. })
  1605. it('preserves additionalContexts supplied by an around-dispatch result', async () => {
  1606. const ctx = await setup()
  1607. ctx.tools.register(echoTool)
  1608. ctx.on('tools/execute', async () => ({
  1609. content: [{ type: 'text', text: 'short-circuited with context' }],
  1610. isError: false,
  1611. value: 'short-circuited with context',
  1612. additionalContexts: [{
  1613. content: [{ type: 'text', text: 'from around dispatch' }],
  1614. source: { kind: 'plugin', plugin: 'test' },
  1615. }],
  1616. }))
  1617. const result = await ctx.tools.execute({
  1618. signal: testToolSignal,
  1619. callId: CallId('around-context'), name: 'echo', arguments: {},
  1620. })
  1621. expect(result.additionalContexts).toEqual([{
  1622. content: [{ type: 'text', text: 'from around dispatch' }],
  1623. source: { kind: 'plugin', plugin: 'test' },
  1624. }])
  1625. })
  1626. it('returns an isError result when a tools/execute listener throws', async () => {
  1627. const ctx = await setup()
  1628. ctx.tools.register(echoTool)
  1629. ctx.on('tools/execute', async () => { throw new Error('wrapper broke') })
  1630. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  1631. expect(result).toEqual({
  1632. content: [{ type: 'text', text: 'Error: wrapper broke' }],
  1633. error: { message: 'wrapper broke' },
  1634. isError: true,
  1635. })
  1636. })
  1637. it('returns an isError result when a tools/pre-execute listener throws', async () => {
  1638. const ctx = await setup()
  1639. ctx.tools.register(echoTool)
  1640. ctx.on('tools/pre-execute', async () => {
  1641. throw new Error('permission hook broke')
  1642. })
  1643. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  1644. expect(result).toEqual({
  1645. content: [{ type: 'text', text: 'Error: permission hook broke' }],
  1646. error: { message: 'permission hook broke' },
  1647. isError: true,
  1648. })
  1649. })
  1650. it('returns an isError result when a tools/post-execute listener throws', async () => {
  1651. const ctx = await setup()
  1652. ctx.tools.register(echoTool)
  1653. ctx.on('tools/post-execute', async () => {
  1654. throw new Error('post hook broke')
  1655. })
  1656. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  1657. expect(result).toEqual({
  1658. content: [{ type: 'text', text: 'Error: post hook broke' }],
  1659. error: { message: 'post hook broke' },
  1660. isError: true,
  1661. })
  1662. })
  1663. it('preserves structured error info when a tools/pre-execute listener throws HarnessError', async () => {
  1664. const ctx = await setup()
  1665. ctx.tools.register(echoTool)
  1666. ctx.on('tools/pre-execute', async () => {
  1667. throw new HarnessError('denied', 'DENIED')
  1668. })
  1669. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } })
  1670. expect(result).toMatchObject({
  1671. isError: true,
  1672. error: { message: 'denied', info: { name: 'HarnessError', code: 'DENIED' } },
  1673. })
  1674. })
  1675. it('schemas() snapshots tool schemas instead of exposing registry objects', async () => {
  1676. const ctx = await setup()
  1677. ctx.tools.register(echoTool)
  1678. const first = ctx.tools.schemas()
  1679. const firstParameters = first[0]!.parameters as { properties: Record<string, unknown> }
  1680. firstParameters.properties['mutated'] = { type: 'string' }
  1681. first[0]!.description = 'mutated'
  1682. expect(ctx.tools.schemas()).toEqual([{
  1683. name: 'echo',
  1684. description: 'echo arguments back',
  1685. parameters: { type: 'object', properties: { text: { type: 'string' } } },
  1686. }])
  1687. })
  1688. it('schemas() snapshots deeply nested parameters without using structured-clone recursion', async () => {
  1689. const ctx = await setup()
  1690. const depth = 5_000
  1691. let nested: JsonSchemaNode = { type: 'string' }
  1692. for (let index = 0; index < depth; index++) nested = { oneOf: [nested, { type: 'null' }] }
  1693. ctx.tools.register({
  1694. ...echoTool,
  1695. name: 'deep-schema',
  1696. parameters: { type: 'object', properties: { nested } },
  1697. })
  1698. const projected = ctx.tools.schemas()[0]!.parameters as JsonSchemaNode
  1699. let cursor = projected.properties!.nested!
  1700. let layers = 0
  1701. while (cursor.oneOf !== undefined) {
  1702. cursor = cursor.oneOf[0]!
  1703. layers++
  1704. }
  1705. expect(layers).toBe(depth)
  1706. expect(cursor).toEqual({ type: 'string' })
  1707. })
  1708. it('rejects schema projection when a raw registration is not lossless JSON', async () => {
  1709. const ctx = await setup()
  1710. ctx.tools.register({
  1711. ...echoTool,
  1712. name: 'lossy-schema',
  1713. parameters: { type: 'object', default: Number.NaN },
  1714. })
  1715. expect(() => ctx.tools.schemas())
  1716. .toThrow('tool "lossy-schema" parameters must be lossless JSON before schema projection')
  1717. })
  1718. it('rejects a non-positive or non-finite registration timeout', async () => {
  1719. const ctx = await setup()
  1720. expect(() => ctx.tools.register({ ...echoTool, name: 'zero-timeout', timeoutMs: 0 }))
  1721. .toThrow('timeoutMs must be a positive finite number')
  1722. expect(() => ctx.tools.register({ ...echoTool, name: 'infinite-timeout', timeoutMs: Number.POSITIVE_INFINITY }))
  1723. .toThrow('timeoutMs must be a positive finite number')
  1724. })
  1725. it('rejects duplicate names and unregisters on fiber dispose (HMR safety)', async () => {
  1726. const ctx = await setup()
  1727. ctx.tools.register(echoTool)
  1728. expect(() => ctx.tools.register(echoTool)).toThrow('already registered')
  1729. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  1730. inner.tools.register({ ...echoTool, name: 'scoped' })
  1731. }, { inject: ['tools'] }))
  1732. expect(ctx.tools.schemas().map(t => t.name)).toEqual(['echo', 'scoped'])
  1733. await fiber.dispose()
  1734. expect(ctx.tools.schemas().map(t => t.name)).toEqual(['echo'])
  1735. })
  1736. it('returns a callable disposer from register() that unregisters the tool', async () => {
  1737. const ctx = await setup()
  1738. ctx.tools.register(echoTool)
  1739. const dispose = ctx.tools.register({ ...echoTool, name: 'disposable' })
  1740. expect(ctx.tools.schemas().map(t => t.name)).toEqual(['echo', 'disposable'])
  1741. dispose()
  1742. expect(ctx.tools.schemas().map(t => t.name)).toEqual(['echo'])
  1743. })
  1744. it('rolls back the tool entry when a tools/change listener throws (P1-1)', async () => {
  1745. const ctx = await setup()
  1746. let threw = false
  1747. ctx.on('tools/change', () => {
  1748. if (!threw) { threw = true; throw new Error('boom change listener') }
  1749. })
  1750. // The throwing emit must roll the entry back, not leak it.
  1751. expect(() => ctx.tools.register(echoTool)).toThrow('boom change listener')
  1752. expect(ctx.tools.get('echo')).toBeUndefined() // rolled back, not leaked
  1753. expect(ctx.tools.schemas()).toHaveLength(0)
  1754. // A subsequent listener-free register of the SAME name succeeds and is
  1755. // exposed exactly once (the duplicate-name check is not wedged).
  1756. const dispose = ctx.tools.register(echoTool)
  1757. expect(ctx.tools.schemas().map(t => t.name)).toEqual(['echo'])
  1758. dispose()
  1759. expect(ctx.tools.get('echo')).toBeUndefined()
  1760. })
  1761. it('register() returns the EXACT effect disposer: a composite yield nests the teardown in order', async () => {
  1762. // Registry methods return the exact Cordis effect disposer so a composite yield places
  1763. // unregistration at its LIFO position. A wrapper would create a concurrent sibling; this async
  1764. // probe yields during earlier teardown and would then observe the tool already removed.
  1765. const ctx = await setup()
  1766. const order: string[] = []
  1767. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  1768. inner.effect(function* () {
  1769. yield () => { order.push('disposed-last') }
  1770. yield inner.tools.register({ ...echoTool, name: 'nested' })
  1771. order.push('registered')
  1772. yield async () => {
  1773. await new Promise(resolve => setTimeout(resolve, 0))
  1774. order.push(inner.tools.get('nested') ? 'first: still registered' : 'first: already gone')
  1775. }
  1776. })
  1777. }, { inject: ['tools'] }))
  1778. await fiber.dispose()
  1779. expect(order).toEqual(['registered', 'first: still registered', 'disposed-last'])
  1780. expect(ctx.tools.get('nested')).toBeUndefined()
  1781. })
  1782. })
  1783. describe('defineTool / schema DSL', () => {
  1784. it('converts ParameterSchemaSpec to standard JSON Schema with required array', () => {
  1785. const spec = {
  1786. path: { type: 'string', required: true, description: 'Absolute path' },
  1787. offset: { type: 'number' },
  1788. limit: { type: 'number', description: 'Max lines' },
  1789. } satisfies ParameterSchemaSpec
  1790. const jsonSchema = parameterSchemaSpecToJsonSchema(spec)
  1791. expect(jsonSchema).toEqual({
  1792. type: 'object',
  1793. properties: {
  1794. path: { type: 'string', description: 'Absolute path' },
  1795. offset: { type: 'number' },
  1796. limit: { type: 'number', description: 'Max lines' },
  1797. },
  1798. required: ['path'],
  1799. })
  1800. })
  1801. it('handles empty spec (no properties, no required)', () => {
  1802. expect(parameterSchemaSpecToJsonSchema({})).toEqual({
  1803. type: 'object',
  1804. properties: {},
  1805. })
  1806. })
  1807. it('handles nested object spec', () => {
  1808. const spec = {
  1809. config: {
  1810. type: 'object',
  1811. additionalProperties: true,
  1812. required: true,
  1813. properties: {
  1814. host: { type: 'string', required: true },
  1815. port: { type: 'number' },
  1816. },
  1817. },
  1818. } satisfies ParameterSchemaSpec
  1819. const jsonSchema = parameterSchemaSpecToJsonSchema(spec)
  1820. expect(jsonSchema).toEqual({
  1821. type: 'object',
  1822. properties: {
  1823. config: {
  1824. type: 'object',
  1825. additionalProperties: true,
  1826. properties: {
  1827. host: { type: 'string' },
  1828. port: { type: 'number' },
  1829. },
  1830. required: ['host'],
  1831. },
  1832. },
  1833. required: ['config'],
  1834. })
  1835. })
  1836. it('defineTool returns a valid ToolDefinition with typed execute', async () => {
  1837. const ctx = await setup()
  1838. const tool = defineTool({
  1839. name: 'typed-echo',
  1840. description: 'A typed echo tool',
  1841. parameters: {
  1842. text: { type: 'string', required: true },
  1843. uppercase: { type: 'boolean' },
  1844. },
  1845. output: {
  1846. schema: { type: 'string' },
  1847. render: (_args, value) => [{ type: 'text', text: value }],
  1848. },
  1849. async execute(args) {
  1850. // args is typed: { text: string; uppercase?: boolean }
  1851. const result = args.uppercase ? args.text.toUpperCase() : args.text
  1852. return result
  1853. },
  1854. })
  1855. ctx.tools.register(tool)
  1856. expect(ctx.tools.schemas()).toEqual([{
  1857. name: 'typed-echo',
  1858. description: 'A typed echo tool',
  1859. parameters: {
  1860. type: 'object',
  1861. properties: {
  1862. text: { type: 'string' },
  1863. uppercase: { type: 'boolean' },
  1864. },
  1865. required: ['text'],
  1866. },
  1867. }])
  1868. const result = await ctx.tools.execute({
  1869. signal: testToolSignal,
  1870. callId: CallId('c1'),
  1871. name: 'typed-echo',
  1872. arguments: { text: 'hello', uppercase: true },
  1873. })
  1874. expect(result.isError).toBe(false)
  1875. expect(result.isError ? undefined : result.value).toBe('HELLO')
  1876. expect(result.content).toEqual([{ type: 'text', text: 'HELLO' }])
  1877. })
  1878. it('type-level: InferArgs maps required properties to non-optional', () => {
  1879. // Compile-time check: if this compiles, InferArgs is correct.
  1880. // args.a is string (required), args.b is number|undefined (optional).
  1881. const tool = defineTool({
  1882. name: 'type-check',
  1883. description: '',
  1884. parameters: { a: { type: 'string' as const, required: true as const }, b: { type: 'number' as const } },
  1885. output: { schema: { type: 'string' }, render: () => [] },
  1886. async execute(args) {
  1887. expect(typeof args.a).toBe('string')
  1888. void args
  1889. return args.a
  1890. },
  1891. })
  1892. void tool
  1893. })
  1894. it('registry round-trips a defineTool definition (register→schemas→execute)', async () => {
  1895. const ctx = await setup()
  1896. ctx.tools.register(defineTool({
  1897. name: 'roundtrip',
  1898. description: 'Round-trip test',
  1899. parameters: {
  1900. req: { type: 'string', required: true },
  1901. opt: { type: 'number', description: 'Optional number' },
  1902. },
  1903. output: {
  1904. schema: { type: 'string' },
  1905. render: (_args, value) => [{ type: 'text', text: value }],
  1906. },
  1907. async execute(args) {
  1908. return `${args.req}:${args.opt ?? 'none'}`
  1909. },
  1910. }))
  1911. // Schema round-trip: schemas() returns standard JSON Schema
  1912. const schemas = ctx.tools.schemas()
  1913. expect(schemas).toHaveLength(1)
  1914. expect(schemas[0]!.parameters).toEqual({
  1915. type: 'object',
  1916. properties: {
  1917. req: { type: 'string' },
  1918. opt: { type: 'number', description: 'Optional number' },
  1919. },
  1920. required: ['req'],
  1921. })
  1922. // Execution round-trip
  1923. const result = await ctx.tools.execute({
  1924. signal: testToolSignal,
  1925. callId: CallId('c1'),
  1926. name: 'roundtrip',
  1927. arguments: { req: 'hello' },
  1928. })
  1929. expect(result.isError).toBe(false)
  1930. expect(result.content).toEqual([{ type: 'text', text: 'hello:none' }])
  1931. })
  1932. it('still accepts raw JSON-Schema ToolDefinition directly (MCP interop)', async () => {
  1933. const ctx = await setup()
  1934. ctx.tools.register({
  1935. name: 'raw-tool',
  1936. description: 'Raw JSON Schema tool (like an MCP adapter would register)',
  1937. parameters: {
  1938. type: 'object',
  1939. properties: { path: { type: 'string' } },
  1940. required: ['path'],
  1941. },
  1942. output: {
  1943. schema: { type: 'string' },
  1944. render: (_args, value) => [{ type: 'text', text: value as string }],
  1945. },
  1946. async execute(args: unknown) {
  1947. const p = args as { path: string }
  1948. return p.path
  1949. },
  1950. })
  1951. const schemas = ctx.tools.schemas()
  1952. expect(schemas[0]!.parameters).toEqual({
  1953. type: 'object',
  1954. properties: { path: { type: 'string' } },
  1955. required: ['path'],
  1956. })
  1957. const result = await ctx.tools.execute({
  1958. signal: testToolSignal,
  1959. callId: CallId('c1'),
  1960. name: 'raw-tool',
  1961. arguments: { path: '/tmp' },
  1962. })
  1963. expect(result.isError).toBe(false)
  1964. expect(result.content).toEqual([{ type: 'text', text: '/tmp' }])
  1965. })
  1966. })
  1967. describe('schema DSL edge cases', () => {
  1968. it('emits enum values in JSON Schema property', () => {
  1969. const spec = {
  1970. color: { type: 'string', enum: ['red', 'green', 'blue'], description: 'Color choice' },
  1971. } satisfies ParameterSchemaSpec
  1972. const jsonSchema = parameterSchemaSpecToJsonSchema(spec)
  1973. expect(jsonSchema.properties['color']).toMatchObject({
  1974. type: 'string',
  1975. enum: ['red', 'green', 'blue'],
  1976. description: 'Color choice',
  1977. })
  1978. })
  1979. it('emits default value in JSON Schema property', () => {
  1980. const spec = {
  1981. limit: { type: 'number', default: 25 },
  1982. } satisfies ParameterSchemaSpec
  1983. const jsonSchema = parameterSchemaSpecToJsonSchema(spec)
  1984. expect(jsonSchema.properties['limit']).toMatchObject({
  1985. type: 'number',
  1986. default: 25,
  1987. })
  1988. })
  1989. it('handles array items without nested properties (plain type array)', () => {
  1990. const spec = {
  1991. tags: { type: 'array', items: { type: 'string' } },
  1992. } satisfies ParameterSchemaSpec
  1993. const jsonSchema = parameterSchemaSpecToJsonSchema(spec)
  1994. expect(jsonSchema.properties['tags']).toEqual({
  1995. type: 'array',
  1996. items: { type: 'string' },
  1997. })
  1998. })
  1999. it('handles enum and default together in one property', () => {
  2000. const spec = {
  2001. level: { type: 'string', enum: ['low', 'high'], default: 'low' },
  2002. } satisfies ParameterSchemaSpec
  2003. const jsonSchema = parameterSchemaSpecToJsonSchema(spec)
  2004. expect(jsonSchema.properties['level']).toMatchObject({
  2005. type: 'string',
  2006. enum: ['low', 'high'],
  2007. default: 'low',
  2008. })
  2009. })
  2010. it('omits description, enum, default keys when not specified', () => {
  2011. const spec = {
  2012. bare: { type: 'string' },
  2013. } satisfies ParameterSchemaSpec
  2014. const jsonSchema = parameterSchemaSpecToJsonSchema(spec)
  2015. const prop = jsonSchema.properties['bare'] as Record<string, unknown>
  2016. expect(prop).toEqual({ type: 'string' })
  2017. expect('description' in prop).toBe(false)
  2018. expect('enum' in prop).toBe(false)
  2019. expect('default' in prop).toBe(false)
  2020. })
  2021. it('handles array with no items (items omitted)', () => {
  2022. const spec = {
  2023. raw: { type: 'array' },
  2024. } satisfies ParameterSchemaSpec
  2025. const jsonSchema = parameterSchemaSpecToJsonSchema(spec)
  2026. expect(jsonSchema.properties['raw']).toEqual({
  2027. type: 'array',
  2028. })
  2029. })
  2030. it('handles nested object with all-optional properties (no required array)', () => {
  2031. const spec = {
  2032. config: {
  2033. type: 'object',
  2034. additionalProperties: true,
  2035. properties: {
  2036. host: { type: 'string' },
  2037. port: { type: 'number' },
  2038. },
  2039. },
  2040. } satisfies ParameterSchemaSpec
  2041. const jsonSchema = parameterSchemaSpecToJsonSchema(spec)
  2042. expect(jsonSchema.properties['config']).toMatchObject({
  2043. type: 'object',
  2044. properties: {
  2045. host: { type: 'string' },
  2046. port: { type: 'number' },
  2047. },
  2048. })
  2049. const config = jsonSchema.properties['config'] as Record<string, unknown>
  2050. expect('required' in config).toBe(false)
  2051. })
  2052. })
  2053. describe('schema DSL optional and nested contracts', () => {
  2054. it('InferArgs makes non-required keys genuinely optional (omittable)', () => {
  2055. type Args = InferArgs<{
  2056. path: { type: 'string'; required: true }
  2057. limit: { type: 'number' }
  2058. }>
  2059. expectTypeOf<Args>().toEqualTypeOf<{ path: string; limit?: number }>()
  2060. const omitted: Args = { path: '/tmp' }
  2061. expect(omitted.limit).toBeUndefined()
  2062. })
  2063. it('InferArgs recurses into array items, including arrays of objects', () => {
  2064. type Args = InferArgs<{
  2065. names: { type: 'array'; required: true; items: { type: 'string' } }
  2066. servers: {
  2067. type: 'array'
  2068. items: {
  2069. type: 'object'
  2070. additionalProperties: true
  2071. properties: {
  2072. host: { type: 'string'; required: true }
  2073. port: { type: 'number' }
  2074. }
  2075. }
  2076. }
  2077. }>
  2078. expectTypeOf<Args>().toEqualTypeOf<{
  2079. names: string[]
  2080. servers?: ({ host: string; port?: number } & Record<string, JsonValue>)[]
  2081. }>()
  2082. })
  2083. it('runtime JSON Schema matches the array-of-objects inference', () => {
  2084. const spec = {
  2085. servers: {
  2086. type: 'array',
  2087. items: {
  2088. type: 'object',
  2089. additionalProperties: true,
  2090. properties: {
  2091. host: { type: 'string', required: true },
  2092. port: { type: 'number' },
  2093. },
  2094. },
  2095. },
  2096. } satisfies ParameterSchemaSpec
  2097. expect(parameterSchemaSpecToJsonSchema(spec)).toEqual({
  2098. type: 'object',
  2099. properties: {
  2100. servers: {
  2101. type: 'array',
  2102. items: {
  2103. type: 'object',
  2104. additionalProperties: true,
  2105. properties: {
  2106. host: { type: 'string' },
  2107. port: { type: 'number' },
  2108. },
  2109. required: ['host'],
  2110. },
  2111. },
  2112. },
  2113. })
  2114. })
  2115. it('reports messages from non-Error throws (throw { message })', async () => {
  2116. const ctx = await setup()
  2117. ctx.tools.register({
  2118. ...echoTool,
  2119. name: 'object-thrower',
  2120. async execute() {
  2121. // testing non-Error throws on purpose
  2122. throw { message: 'denied by object' }
  2123. },
  2124. })
  2125. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'object-thrower', arguments: {} })
  2126. expect(result.isError).toBe(true)
  2127. expect(result.content[0]).toMatchObject({ text: 'Error: denied by object' })
  2128. })
  2129. it('reports messages from throws of non-objects (throw "string")', async () => {
  2130. const ctx = await setup()
  2131. ctx.tools.register({
  2132. ...echoTool,
  2133. name: 'string-thrower',
  2134. async execute() {
  2135. // testing primitive throws on purpose
  2136. throw 'kaboom'
  2137. },
  2138. })
  2139. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'string-thrower', arguments: {} })
  2140. expect(result.isError).toBe(true)
  2141. expect(result.content[0]).toMatchObject({ text: 'Error: kaboom' })
  2142. })
  2143. it('reports messages from throws of objects without message property', async () => {
  2144. const ctx = await setup()
  2145. ctx.tools.register({
  2146. ...echoTool,
  2147. name: 'object-no-message',
  2148. async execute() {
  2149. // testing object throw without .message
  2150. throw { code: 500 }
  2151. },
  2152. })
  2153. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'object-no-message', arguments: {} })
  2154. expect(result.isError).toBe(true)
  2155. const firstContent = result.content[0]!
  2156. expect(firstContent.type).toBe('text')
  2157. if (firstContent.type === 'text') {
  2158. expect(firstContent.text).toBe('Error: [object Object]')
  2159. }
  2160. })
  2161. })
  2162. describe('ToolRegistry.get', () => {
  2163. it('get() returns the registered tool definition', async () => {
  2164. const ctx = await setup()
  2165. ctx.tools.register(echoTool)
  2166. const tool = ctx.tools.get('echo')
  2167. expect(tool).toBeDefined()
  2168. expect(tool!.name).toBe('echo')
  2169. })
  2170. it('get() returns undefined for unknown tool names', async () => {
  2171. const ctx = await setup()
  2172. expect(ctx.tools.get('nope')).toBeUndefined()
  2173. })
  2174. })
  2175. describe('validateArgs (the runtime-validation Agent Note, part 1)', () => {
  2176. it('returns [] for valid args and is total over malformed input', () => {
  2177. const spec = {
  2178. path: { type: 'string', required: true },
  2179. limit: { type: 'number' },
  2180. } satisfies ParameterSchemaSpec
  2181. expect(validateArgs(spec, { path: '/tmp' })).toEqual([])
  2182. expect(validateArgs(spec, { path: '/tmp', limit: 5 })).toEqual([])
  2183. // never throws regardless of shape
  2184. expect(validateArgs(spec, null)).toHaveLength(1)
  2185. expect(validateArgs(spec, 'nope')).toHaveLength(1)
  2186. expect(validateArgs(spec, [])).toHaveLength(1)
  2187. })
  2188. it('flags a missing required key and a required key present as undefined', () => {
  2189. const spec = { path: { type: 'string', required: true } } satisfies ParameterSchemaSpec
  2190. expect(validateArgs(spec, {})).toEqual(['missing required property "path"'])
  2191. expect(validateArgs(spec, { path: undefined })).toEqual(['missing required property "path"'])
  2192. })
  2193. it('allows extra keys (no additionalProperties:false) and omitted optionals', () => {
  2194. const spec = { path: { type: 'string', required: true } } satisfies ParameterSchemaSpec
  2195. expect(validateArgs(spec, { path: '/tmp', extra: 1 })).toEqual([])
  2196. })
  2197. it('does not apply defaults (validation only)', () => {
  2198. const spec = { limit: { type: 'number', default: 25 } } satisfies ParameterSchemaSpec
  2199. // absent optional is valid, and validation does not synthesize the default
  2200. expect(validateArgs(spec, {})).toEqual([])
  2201. })
  2202. it('type-checks primitives', () => {
  2203. const spec = {
  2204. s: { type: 'string' },
  2205. n: { type: 'number' },
  2206. b: { type: 'boolean' },
  2207. } satisfies ParameterSchemaSpec
  2208. expect(validateArgs(spec, { s: 1 })).toEqual(['"s" must be a string'])
  2209. expect(validateArgs(spec, { n: 'x' })).toEqual(['"n" must be a number'])
  2210. expect(validateArgs(spec, { b: 'x' })).toEqual(['"b" must be a boolean'])
  2211. })
  2212. it('checks enum membership', () => {
  2213. const spec = { color: { type: 'string', enum: ['red', 'green'] } } satisfies ParameterSchemaSpec
  2214. expect(validateArgs(spec, { color: 'red' })).toEqual([])
  2215. expect(validateArgs(spec, { color: 'blue' })).toEqual(['"color" must be one of ["red","green"]'])
  2216. })
  2217. it('enforces type-correct scalar enum declarations', () => {
  2218. const spec = { n: { type: 'number', enum: [1, 2] } } satisfies ParameterSchemaSpec
  2219. expect(validateArgs(spec, { n: 1 })).toEqual([])
  2220. expect(validateArgs(spec, { n: 3 })).toEqual(['"n" must be one of [1,2]'])
  2221. const invalid = { n: { type: 'number', enum: ['1', '2'] } } as unknown as ParameterSchemaSpec
  2222. expect(() => validateArgs(invalid, { n: 1 })).toThrow(JsonSchemaError)
  2223. })
  2224. it('rejects an unknown schema type at the author boundary', () => {
  2225. const spec = { x: { type: 'weird' } } as unknown as ParameterSchemaSpec
  2226. expect(() => validateArgs(spec, { x: 1 })).toThrow(JsonSchemaError)
  2227. })
  2228. it('recurses into nested objects (and an object without properties only type-checks)', () => {
  2229. const spec = {
  2230. config: {
  2231. type: 'object',
  2232. additionalProperties: true,
  2233. required: true,
  2234. properties: { host: { type: 'string', required: true }, port: { type: 'number' } },
  2235. },
  2236. bag: { type: 'object', additionalProperties: true },
  2237. } satisfies ParameterSchemaSpec
  2238. expect(validateArgs(spec, { config: { host: 'h' }, bag: { anything: true } })).toEqual([])
  2239. expect(validateArgs(spec, { config: { port: 9 }, bag: 5 })).toEqual([
  2240. 'missing required property "config.host"',
  2241. '"bag" must be an object',
  2242. ])
  2243. })
  2244. it('recurses into array items (and an array without items only type-checks)', () => {
  2245. const spec = {
  2246. tags: { type: 'array', items: { type: 'string' } },
  2247. raw: { type: 'array' },
  2248. } satisfies ParameterSchemaSpec
  2249. expect(validateArgs(spec, { tags: ['a', 'b'], raw: [1, {}, 'x'] })).toEqual([])
  2250. expect(validateArgs(spec, { tags: ['a', 2] })).toEqual(['"tags[1]" must be a string'])
  2251. // a non-array value for an array-typed prop
  2252. expect(validateArgs(spec, { tags: 'nope' })).toEqual(['"tags" must be an array'])
  2253. })
  2254. it('validates arrays of objects element-wise', () => {
  2255. const spec = {
  2256. servers: {
  2257. type: 'array',
  2258. items: { type: 'object', additionalProperties: true, properties: { host: { type: 'string', required: true } } },
  2259. },
  2260. } satisfies ParameterSchemaSpec
  2261. expect(validateArgs(spec, { servers: [{ host: 'a' }, {}] })).toEqual([
  2262. 'missing required property "servers[1].host"',
  2263. ])
  2264. })
  2265. })
  2266. describe('defineTool validation (the runtime-validation Agent Note, part 1)', () => {
  2267. it('returns an isError result with the violations when the model sends bad args', async () => {
  2268. const ctx = await setup()
  2269. ctx.tools.register(defineContentToolFixture({
  2270. name: 'reader',
  2271. description: 'reads a path',
  2272. parameters: { path: { type: 'string', required: true } },
  2273. async execute(args) {
  2274. return [{ type: 'text', text: args.path }]
  2275. },
  2276. }))
  2277. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'reader', arguments: {} })
  2278. expect(result.isError).toBe(true)
  2279. expect(result.content[0]).toMatchObject({
  2280. text: 'Error: invalid arguments: missing required property "path"',
  2281. })
  2282. })
  2283. it('runs execute normally when args are valid', async () => {
  2284. const ctx = await setup()
  2285. ctx.tools.register(defineContentToolFixture({
  2286. name: 'reader',
  2287. description: 'reads a path',
  2288. parameters: { path: { type: 'string', required: true } },
  2289. async execute(args) {
  2290. return [{ type: 'text', text: `read ${args.path}` }]
  2291. },
  2292. }))
  2293. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'reader', arguments: { path: '/x' } })
  2294. expect(result).toEqual({
  2295. content: [{ type: 'text', text: 'read /x' }],
  2296. isError: false,
  2297. value: [{ type: 'text', text: 'read /x' }],
  2298. })
  2299. })
  2300. it('ToolArgsError carries a stable code and the violation list', () => {
  2301. const err = new ToolArgsError(['missing required property "a"', '"b" must be a number'])
  2302. expect(err).toBeInstanceOf(Error)
  2303. expect(err.name).toBe('ToolArgsError')
  2304. expect(err.code).toBe('INVALID_ARGS')
  2305. expect(err.violations).toEqual(['missing required property "a"', '"b" must be a number'])
  2306. expect(err.message).toBe('invalid arguments: missing required property "a"; "b" must be a number')
  2307. })
  2308. it('a schema-invalid call surfaces the structured error on the result', async () => {
  2309. const ctx = await setup()
  2310. ctx.tools.register(defineContentToolFixture({
  2311. name: 'reader',
  2312. description: 'reads a path',
  2313. parameters: { path: { type: 'string', required: true } },
  2314. async execute(args) {
  2315. return [{ type: 'text', text: args.path }]
  2316. },
  2317. }))
  2318. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'reader', arguments: {} })
  2319. expect(result.isError).toBe(true)
  2320. expect(result.error).toEqual({
  2321. message: 'invalid arguments: missing required property "path"',
  2322. info: { name: 'ToolArgsError', code: 'INVALID_ARGS' },
  2323. })
  2324. })
  2325. it('a tool throwing a HarnessError surfaces its name and code', async () => {
  2326. const { HarnessError } = await import('@deepseek-ai/dsh-llm')
  2327. const ctx = await setup()
  2328. ctx.tools.register({
  2329. ...echoTool,
  2330. name: 'coded',
  2331. async execute() {
  2332. throw new HarnessError('disk full', 'ENOSPC')
  2333. },
  2334. })
  2335. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'coded', arguments: {} })
  2336. expect(result.isError).toBe(true)
  2337. expect(result.error).toEqual({ message: 'disk full', info: { name: 'HarnessError', code: 'ENOSPC' } })
  2338. expect(result.content[0]).toMatchObject({ text: 'Error: disk full' })
  2339. })
  2340. it('a non-HarnessError throw retains only its message', async () => {
  2341. const ctx = await setup()
  2342. ctx.tools.register({
  2343. ...echoTool,
  2344. name: 'plain',
  2345. async execute() {
  2346. throw new Error('just a message')
  2347. },
  2348. })
  2349. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'plain', arguments: {} })
  2350. expect(result.isError).toBe(true)
  2351. expect(result.error).toEqual({ message: 'just a message' })
  2352. expect(result.content[0]).toMatchObject({ text: 'Error: just a message' })
  2353. })
  2354. it('raw-registered tools are NOT validated by defineTool (MCP keeps its own)', async () => {
  2355. const ctx = await setup()
  2356. // A raw ToolDefinition: no defineTool wrapping, so no validateArgs guard.
  2357. ctx.tools.register({
  2358. name: 'raw',
  2359. description: 'raw tool',
  2360. parameters: { type: 'object', properties: { path: { type: 'string' } }, required: ['path'] },
  2361. output: {
  2362. schema: { type: 'string' },
  2363. render: (_args, value) => [{ type: 'text', text: value as string }],
  2364. },
  2365. async execute(args: unknown) {
  2366. return typeof args
  2367. },
  2368. })
  2369. // Missing the "required" path — but raw tools validate their own input, so
  2370. // this reaches execute rather than being rejected by the harness.
  2371. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'raw', arguments: {} })
  2372. expect(result.isError).toBe(false)
  2373. })
  2374. it('attaches a positive-finite timeoutMs to the definition', () => {
  2375. const tool = defineContentToolFixture({
  2376. name: 'x', description: 'd', parameters: {}, timeoutMs: 30_000,
  2377. async execute() { return [{ type: 'text' as const, text: 'ok' }] },
  2378. })
  2379. expect(tool.timeoutMs).toBe(30_000)
  2380. })
  2381. it('omits timeoutMs when not declared', () => {
  2382. const tool = defineContentToolFixture({
  2383. name: 'x', description: 'd', parameters: {},
  2384. async execute() { return [{ type: 'text' as const, text: 'ok' }] },
  2385. })
  2386. expect(tool.timeoutMs).toBeUndefined()
  2387. })
  2388. it('throws when timeoutMs is zero or negative', () => {
  2389. const make = (ms: number) => defineContentToolFixture({
  2390. name: 'x', description: 'd', parameters: {}, timeoutMs: ms,
  2391. async execute() { return [{ type: 'text' as const, text: 'ok' }] },
  2392. })
  2393. expect(() => make(0)).toThrow('timeoutMs must be a positive finite number')
  2394. expect(() => make(-5)).toThrow('positive finite number')
  2395. })
  2396. it('throws when timeoutMs is non-finite', () => {
  2397. expect(() => defineContentToolFixture({
  2398. name: 'x', description: 'd', parameters: {}, timeoutMs: Infinity,
  2399. async execute() { return [{ type: 'text' as const, text: 'ok' }] },
  2400. })).toThrow('positive finite number')
  2401. })
  2402. })
  2403. describe('defineTool presentation (presentCall / presentResult)', () => {
  2404. it('preserves inline enum and const literals in inferred arguments', () => {
  2405. defineTool({
  2406. name: 'literal-args',
  2407. description: 'literal arguments',
  2408. parameters: {
  2409. mode: { type: 'string', enum: ['read', 'write'], required: true },
  2410. attempt: { type: 'integer', const: 1 },
  2411. },
  2412. output: {
  2413. schema: { type: 'null' },
  2414. render: () => [],
  2415. },
  2416. async execute(args) {
  2417. expectTypeOf(args).toEqualTypeOf<{ mode: 'read' | 'write'; attempt?: 1 }>()
  2418. return null
  2419. },
  2420. })
  2421. })
  2422. it('threads presentCall/presentResult onto the ToolDefinition with typed args', () => {
  2423. const tool = defineContentToolFixture({
  2424. name: 'demo',
  2425. description: 'demo',
  2426. parameters: { path: { type: 'string', required: true }, n: { type: 'number' } },
  2427. async execute() { return [{ type: 'text', text: 'ok' }] },
  2428. presentCall(args) {
  2429. // args is typed { path: string; n?: number } — zero casts.
  2430. expectTypeOf(args).toEqualTypeOf<{ path: string; n?: number }>()
  2431. return { card: 'generic', title: `Open ${args.path}`, kind: 'read', rawInput: args.path }
  2432. },
  2433. presentResult(args, result) {
  2434. return { card: 'generic', title: `Opened ${args.path}`, content: result.content }
  2435. },
  2436. })
  2437. expect(tool.presentCall!({ path: '/a', n: 2 })).toEqual({ card: 'generic', title: 'Open /a', kind: 'read', rawInput: '/a' })
  2438. expect(tool.presentResult!({ path: '/a' }, { content: [{ type: 'text', text: 'x' }], isError: false }))
  2439. .toEqual({ card: 'generic', title: 'Opened /a', content: [{ type: 'text', text: 'x' }] })
  2440. })
  2441. it('a tool without presentCall/presentResult leaves them undefined (UI falls back generically)', () => {
  2442. const tool = defineContentToolFixture({
  2443. name: 'plain',
  2444. description: 'plain',
  2445. parameters: { x: { type: 'string', required: true } },
  2446. async execute() { return [] },
  2447. })
  2448. expect(typeof tool.presentCall).toBe('undefined')
  2449. expect(typeof tool.presentResult).toBe('undefined')
  2450. })
  2451. it('presentCall/presentResult validate softly: malformed args return undefined, never throw (display runs on replay)', () => {
  2452. const tool = defineContentToolFixture({
  2453. name: 'demo',
  2454. description: 'demo',
  2455. parameters: { path: { type: 'string', required: true } },
  2456. async execute() { return [] },
  2457. presentCall: args => ({ card: 'generic', title: args.path }),
  2458. presentResult: (args, result) => ({ card: 'generic', title: args.path, content: result.content }),
  2459. })
  2460. // Unlike execute (which throws ToolArgsError on a mismatch), the display
  2461. // methods soft-validate and fall back to undefined so a UI never crashes
  2462. // replaying an old/foreign log entry. The ToolDefinition methods take
  2463. // `unknown`, so malformed shapes pass without a cast.
  2464. expect(tool.presentCall?.({})).toBeUndefined()
  2465. expect(tool.presentResult?.({ wrong: 1 }, { content: [], isError: false })).toBeUndefined()
  2466. })
  2467. })