tools.spec.ts 105 KB

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