tools.spec.ts 106 KB

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