tools.spec.ts 105 KB

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