tool-web.spec.ts 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { Context } from '@deepseek-ai/cordis'
  3. import TurndownService from 'turndown'
  4. import { CallId } from '@deepseek-ai/dsh-llm'
  5. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  6. import ToolRuntime, { type ToolExecutionResult } from '@deepseek-ai/dsh-tools'
  7. import WebRuntime from '@deepseek-ai/dsh-web'
  8. import type { WebSearchProvider, WebSearchResult } from '@deepseek-ai/dsh-web'
  9. import * as ToolWeb from '@deepseek-ai/dsh-tool-web'
  10. import {
  11. formatSearchOutput,
  12. formatFetchOutput,
  13. parseFetchArgs,
  14. presentSearchCall,
  15. presentFetchCall,
  16. presentSearchResult,
  17. presentFetchResult,
  18. searchMetaFromValue,
  19. searchMetaFromResult,
  20. fetchMetaFromValue,
  21. fetchMetaFromResult,
  22. WEB_SEARCH_MAX_QUERIES,
  23. WEB_SEARCH_MAX_RESULTS,
  24. } from '@deepseek-ai/dsh-tool-web'
  25. import type { ContentBlock } from '@deepseek-ai/dsh-llm'
  26. import type { ToolResult } from '@deepseek-ai/dsh-tools'
  27. import { parseSearchArgs } from '../src/search.ts'
  28. const testToolSignal = new AbortController().signal
  29. const available = true
  30. function searchProvider(result: WebSearchResult, isAvailable = available): WebSearchProvider {
  31. return { id: 'stub-search', available: () => isAvailable, search: () => Promise.resolve(result) }
  32. }
  33. /** Mount the real registry, seam, and tool-web; return an executor helper. */
  34. async function mountTools(opts: {
  35. config?: ToolWeb.Config
  36. webConfig?: ConstructorParameters<typeof WebRuntime>[1]
  37. search?: WebSearchProvider
  38. fetchProvider?: import('@deepseek-ai/dsh-web').WebFetchProvider
  39. } = {}): Promise<{ ctx: Context; fiber: Awaited<ReturnType<Context['plugin']>>; call: (name: string, args: unknown) => Promise<ToolExecutionResult> }> {
  40. const ctx = new Context()
  41. await ctx.plugin(SystemPrompt)
  42. await ctx.plugin(ToolRuntime)
  43. await ctx.plugin(WebRuntime, opts.webConfig ?? {})
  44. if (opts.search) ctx.web.registerSearchProvider(opts.search)
  45. if (opts.fetchProvider) ctx.web.registerFetchProvider(opts.fetchProvider)
  46. const fiber = await ctx.plugin(ToolWeb, opts.config ?? {})
  47. let counter = 0
  48. const call = (name: string, args: unknown) => ctx.tools.execute({ signal: testToolSignal, callId: CallId(`call-${++counter}`), name, arguments: args })
  49. return { ctx, fiber, call }
  50. }
  51. describe('search formatting', () => {
  52. it('renders content, sources with titles/hostnames, snippets, and a citation reminder', () => {
  53. const out = formatSearchOutput({
  54. content: 'an answer', truncated: false,
  55. sources: [
  56. { url: 'https://a.test/x', title: 'A', snippet: 'about a', publishedAt: '2026-01-01' },
  57. { url: 'https://b.test/y' },
  58. ],
  59. })
  60. expect(out).toContain('an answer')
  61. expect(out).toContain('[A](https://a.test/x) — about a (2026-01-01)')
  62. expect(out).toContain('[b.test](https://b.test/y)')
  63. expect(out).toContain('Cite the relevant URLs')
  64. })
  65. it('reports no results when there is neither content nor sources', () => {
  66. expect(formatSearchOutput({ sources: [], truncated: false }))
  67. .toContain('No results found.')
  68. })
  69. it('renders content alone when there are no sources', () => {
  70. const out = formatSearchOutput({ content: 'just an answer', sources: [], truncated: false })
  71. expect(out).toContain('just an answer')
  72. expect(out).not.toContain('No results found.')
  73. expect(out).not.toContain('Sources:')
  74. })
  75. it('notes truncation', () => {
  76. const out = formatSearchOutput({ sources: [{ url: 'https://a.test' }], truncated: true })
  77. expect(out).toContain('Showing the first 1 sources')
  78. })
  79. it('validates queries', () => {
  80. expect(parseSearchArgs({ queries: ['hi'] }, WEB_SEARCH_MAX_QUERIES)).toEqual(['hi'])
  81. expect(parseSearchArgs({ queries: ['one', 'one', ' two '] }, WEB_SEARCH_MAX_QUERIES))
  82. .toEqual(['one', ' two '])
  83. expect(() => parseSearchArgs({ queries: [] }, WEB_SEARCH_MAX_QUERIES)).toThrow('at least one query')
  84. expect(() => parseSearchArgs({ queries: ['one', 'two'] }, 1)).toThrow('at most 1 query')
  85. expect(() => parseSearchArgs({ queries: ['one', 'two', 'three'] }, 2)).toThrow('at most 2 queries')
  86. expect(() => parseSearchArgs({ queries: ['ok', ' '] }, WEB_SEARCH_MAX_QUERIES)).toThrow('each query must be a non-empty string')
  87. })
  88. it('falls back to the raw URL as a source label when the URL is unparseable', () => {
  89. const out = formatSearchOutput({ truncated: false, sources: [{ url: 'not a url' }] })
  90. expect(out).toContain('[not a url](not a url)')
  91. })
  92. it('presents a search call with a joined query title', () => {
  93. expect(presentSearchCall({ queries: ['one', 'two'] })).toEqual({ card: 'generic', title: 'one, two', kind: 'search', rawInput: 'one, two' })
  94. })
  95. })
  96. /** Build a completed non-error tool result with the given meta and text content. */
  97. function toolResult(meta: unknown, text = 'body', isError = false): ToolResult {
  98. const content: ContentBlock[] = [{ type: 'text', text }]
  99. return { content, isError, ...meta !== undefined ? { meta: meta as never } : {} }
  100. }
  101. describe('web_search presentation meta and result view', () => {
  102. it('projects sources, answer, and truncation into meta, omitting absent optional fields', () => {
  103. const meta = searchMetaFromValue({
  104. content: 'an answer', truncated: true,
  105. sources: [
  106. { url: 'https://a.test/x', title: 'A', snippet: 'about a', publishedAt: '2026-01-01' },
  107. { url: 'https://b.test/y' },
  108. ],
  109. })
  110. expect(meta).toEqual({
  111. answer: 'an answer',
  112. truncated: true,
  113. sources: [
  114. { url: 'https://a.test/x', title: 'A', snippet: 'about a', publishedAt: '2026-01-01' },
  115. { url: 'https://b.test/y' },
  116. ],
  117. })
  118. })
  119. it('omits answer from meta when the provider returned none', () => {
  120. const meta = searchMetaFromValue({ truncated: false, sources: [{ url: 'https://a.test' }] })
  121. expect(meta).toEqual({ truncated: false, sources: [{ url: 'https://a.test' }] })
  122. })
  123. it('round-trips projected meta back to a typed search meta', () => {
  124. const value = {
  125. content: 'ans', truncated: false,
  126. sources: [{ url: 'https://a.test', title: 'A', snippet: 's', publishedAt: '2026-01-01' }],
  127. }
  128. expect(searchMetaFromResult(searchMetaFromValue(value))).toEqual({
  129. answer: 'ans', truncated: false,
  130. sources: [{ url: 'https://a.test', title: 'A', snippet: 's', publishedAt: '2026-01-01' }],
  131. })
  132. })
  133. it('presents a completed search as a web/search card carrying the structured sources, titled by the query', () => {
  134. const meta = searchMetaFromValue({
  135. content: 'an answer', truncated: true,
  136. sources: [{ url: 'https://a.test', title: 'A', snippet: 'snip', publishedAt: '2026-07-20' }],
  137. })
  138. expect(presentSearchResult({ queries: ['q'] }, toolResult(meta, 'rendered'))).toEqual({
  139. card: 'web',
  140. kind: 'search',
  141. title: 'q',
  142. answer: 'an answer',
  143. truncated: true,
  144. sources: [{ url: 'https://a.test', title: 'A', snippet: 'snip', publishedAt: '2026-07-20' }],
  145. })
  146. })
  147. it('omits the answer from the view when meta carries none', () => {
  148. const meta = searchMetaFromValue({ truncated: false, sources: [{ url: 'https://a.test' }] })
  149. const view = presentSearchResult({ queries: ['q'] }, toolResult(meta))
  150. expect(view).toBeDefined()
  151. expect(view && 'answer' in view).toBe(false)
  152. expect(view && 'content' in view).toBe(false)
  153. })
  154. it('falls back to the generic card on an error result', () => {
  155. const meta = searchMetaFromValue({ truncated: false, sources: [{ url: 'https://a.test' }] })
  156. expect(presentSearchResult({ queries: ['q'] }, toolResult(meta, 'body', true))).toBeUndefined()
  157. })
  158. it('falls back to the generic card on absent or malformed meta', () => {
  159. expect(presentSearchResult({ queries: ['q'] }, toolResult(undefined))).toBeUndefined()
  160. expect(searchMetaFromResult(undefined)).toBeUndefined()
  161. expect(searchMetaFromResult(null)).toBeUndefined()
  162. expect(searchMetaFromResult('nope')).toBeUndefined()
  163. expect(searchMetaFromResult([])).toBeUndefined()
  164. expect(searchMetaFromResult({})).toBeUndefined()
  165. expect(searchMetaFromResult({ sources: 'x', truncated: false })).toBeUndefined()
  166. expect(searchMetaFromResult({ sources: [], truncated: 'no' })).toBeUndefined()
  167. expect(searchMetaFromResult({ sources: [], truncated: false, answer: 1 })).toBeUndefined()
  168. expect(searchMetaFromResult({ sources: [null], truncated: false })).toBeUndefined()
  169. expect(searchMetaFromResult({ sources: [{ url: 1 }], truncated: false })).toBeUndefined()
  170. expect(searchMetaFromResult({ sources: [{ url: 'u', title: 2 }], truncated: false })).toBeUndefined()
  171. expect(searchMetaFromResult({ sources: [{ url: 'u', snippet: 2 }], truncated: false })).toBeUndefined()
  172. expect(searchMetaFromResult({ sources: [{ url: 'u', publishedAt: 2 }], truncated: false })).toBeUndefined()
  173. })
  174. it('accepts an empty source list as valid meta', () => {
  175. expect(searchMetaFromResult({ sources: [], truncated: false })).toEqual({ sources: [], truncated: false })
  176. })
  177. })
  178. describe('fetch formatting', () => {
  179. const NO_CAP = 1_000_000
  180. const HEADER = 'Fetched https://a.test (HTTP 200)\n\n'
  181. const renderHtml = (content: string) => formatFetchOutput({
  182. url: 'https://a.test', statusCode: 200, truncated: false,
  183. body: { kind: 'html', content },
  184. }, NO_CAP).slice(HEADER.length)
  185. it('renders an html body to markdown text with a status header', () => {
  186. const out = formatFetchOutput({
  187. url: 'https://a.test', statusCode: 200, truncated: false,
  188. body: { kind: 'html', content: '<h1>Title</h1><p>Body text</p>' },
  189. }, NO_CAP)
  190. expect(out).toContain('Fetched https://a.test (HTTP 200)')
  191. expect(out).toContain('# Title')
  192. expect(out).toContain('Body text')
  193. })
  194. it('passes a text body through and notes truncation', () => {
  195. const out = formatFetchOutput({
  196. url: 'https://a.test', statusCode: 200, truncated: true,
  197. body: { kind: 'text', content: 'plain' },
  198. }, NO_CAP)
  199. expect(out).toContain('plain')
  200. expect(out).toContain('Content truncated')
  201. })
  202. it('caps the complete output and notes truncation, even when markdown escaping expands the body', () => {
  203. // 1,000 underscores render as 2,000 escaped characters — conversion can
  204. // outgrow a provider-side body cap, so the bound applies to the output.
  205. const out = formatFetchOutput({
  206. url: 'https://a.test', statusCode: 200, truncated: false,
  207. body: { kind: 'html', content: `<p>${'_'.repeat(1000)}</p>` },
  208. }, 500)
  209. expect(out.length).toBeLessThanOrEqual(500)
  210. expect(out).toContain('Fetched https://a.test (HTTP 200)')
  211. expect(out).toContain('\\_\\_')
  212. expect(out).toContain('Content truncated')
  213. // Exact and tiny caps: the complete result is bounded, header and footer included.
  214. const exact = formatFetchOutput({
  215. url: 'https://a.test', statusCode: 200, truncated: false,
  216. body: { kind: 'text', content: 'abc' },
  217. }, 'Fetched https://a.test (HTTP 200)\n\nabc'.length)
  218. expect(exact).toBe('Fetched https://a.test (HTTP 200)\n\nabc')
  219. const tiny = formatFetchOutput({
  220. url: 'https://a.test', statusCode: 200, truncated: true,
  221. body: { kind: 'text', content: 'abcdef' },
  222. }, 10)
  223. expect(tiny.length).toBeLessThanOrEqual(10)
  224. expect(tiny).toBe('Fetched ht')
  225. })
  226. it('dispatches text and html bodies', () => {
  227. expect(formatFetchOutput({
  228. url: 'https://a.test', statusCode: 200, truncated: false,
  229. body: { kind: 'text', content: 'x' },
  230. }, NO_CAP)).toBe(`${HEADER}x`)
  231. expect(renderHtml('<p>y</p>')).toBe('y')
  232. })
  233. it('converts html via turndown: entities, links, tables, nesting; drops script/style/noscript', () => {
  234. expect(renderHtml('<style>.x{}</style><script>bad()</script><noscript>ns</noscript><p>Tom &amp; Jerry &copy; R&eacute;sum&eacute;</p><a href="https://a.test">link</a>'))
  235. .toBe('Tom & Jerry © Résumé\n\n[link](https://a.test)')
  236. expect(renderHtml('<h2>Heading</h2><ul><li>one</li><li>two</li></ul>'))
  237. .toBe('## Heading\n\n- one\n- two')
  238. expect(renderHtml('<table><tr><th>A</th><th>B</th></tr><tr><td>1</td><td>2</td></tr></table>'))
  239. .toBe('| A | B |\n| --- | --- |\n| 1 | 2 |')
  240. expect(renderHtml('<table><thead><tr><th align="left">L</th><th align="right">R</th><th style="text-align:center">C</th></tr></thead><tbody><tr><td>1</td><td>2</td><td>3</td></tr></tbody></table>'))
  241. .toBe('| L | R | C |\n| :--- | ---: | :---: |\n| 1 | 2 | 3 |')
  242. expect(renderHtml('<p><strong>bold <em>italic</em></strong></p><blockquote><p>quoted</p></blockquote>'))
  243. .toBe('**bold _italic_**\n\n> quoted')
  244. })
  245. it('does not expand numeric colspan attributes into unbounded output', () => {
  246. const table = '<table><thead><tr><th colspan="1000000">A</th></tr></thead><tbody><tr><td>B</td></tr></tbody></table>'
  247. expect(renderHtml(table)).toBe('| A |\n| --- |\n| B |')
  248. })
  249. it('passes deeply nested html through raw without attempting conversion', () => {
  250. // Unclosed-tag nesting makes the synchronous conversion superlinear
  251. // (seconds at 20k levels, during which the cooperative timeout cannot
  252. // fire), so the depth preflight skips conversion entirely; this must
  253. // return fast, not merely not-throw.
  254. const depth = 20_000
  255. const pathological = '<div>'.repeat(depth) + 'x' + '</div>'.repeat(depth)
  256. const started = Date.now()
  257. expect(formatFetchOutput({
  258. url: 'https://a.test', statusCode: 200, truncated: false,
  259. body: { kind: 'html', content: pathological },
  260. }, NO_CAP)).toBe(`${HEADER}${pathological}`)
  261. expect(Date.now() - started).toBeLessThan(2_000)
  262. })
  263. it('comments and mismatched closing tags cannot hide deep nesting from the preflight', () => {
  264. const pathological = '<div><!-- </div> --></span>'.repeat(600) + 'x'
  265. expect(formatFetchOutput({
  266. url: 'https://a.test', statusCode: 200, truncated: false,
  267. body: { kind: 'html', content: pathological },
  268. }, NO_CAP)).toBe(`${HEADER}${pathological}`)
  269. const abruptlyClosedComments = '<div><!-->'.repeat(600) + 'x'
  270. expect(formatFetchOutput({
  271. url: 'https://a.test', statusCode: 200, truncated: false,
  272. body: { kind: 'html', content: abruptlyClosedComments },
  273. }, NO_CAP)).toBe(`${HEADER}${abruptlyClosedComments}`)
  274. })
  275. it('the preflight accepts ordinary closed, void, self-closing, quoted, and raw-text markup', () => {
  276. const paragraphs = '<p title=\'>\'>x<br ><img src="x"><input/></p>'.repeat(600)
  277. const script = `<script>const invalid = '</scriptx>'; const template = '${'<div>'.repeat(600)}'</script >`
  278. expect(renderHtml(`<!doctype html><?pi><1bad>${paragraphs}${script}`))
  279. .not.toContain('<p')
  280. expect(renderHtml('plain text')).toBe('plain text')
  281. expect(renderHtml('<p>x</p><!-- unfinished')).toBe('x')
  282. expect(renderHtml('<script>unclosed')).toBe('')
  283. expect(renderHtml('<script>closed by slash</script/>')).toBe('')
  284. expect(renderHtml('<script>closed at end</script')).toBe('')
  285. })
  286. it('scans malformed unterminated tags in bounded time', () => {
  287. const malformed = '<a'.repeat(100_000)
  288. const started = Date.now()
  289. const out = formatFetchOutput({
  290. url: 'https://a.test', statusCode: 200, truncated: false,
  291. body: { kind: 'html', content: malformed },
  292. }, 200_000)
  293. expect(out.length).toBeLessThanOrEqual(200_000)
  294. expect(Date.now() - started).toBeLessThan(2_000)
  295. })
  296. it('falls back to the raw html when turndown throws despite a shallow depth scan', () => {
  297. const spy = vi.spyOn(TurndownService.prototype, 'turndown').mockImplementation(() => {
  298. throw new RangeError('Maximum call stack size exceeded')
  299. })
  300. try {
  301. expect(formatFetchOutput({
  302. url: 'https://a.test', statusCode: 200, truncated: false,
  303. body: { kind: 'html', content: '<p>x</p>' },
  304. }, NO_CAP)).toBe(`${HEADER}<p>x</p>`)
  305. } finally {
  306. spy.mockRestore()
  307. }
  308. })
  309. it('bounds source conversion work before rendering a custom provider body', () => {
  310. const spy = vi.spyOn(TurndownService.prototype, 'turndown').mockReturnValue('converted')
  311. try {
  312. const out = formatFetchOutput({
  313. url: 'https://a.test', statusCode: 200, truncated: false,
  314. body: { kind: 'html', content: `<p>${'x'.repeat(10_000)}</p>` },
  315. }, 500)
  316. expect(spy).toHaveBeenCalledWith(`<p>${'x'.repeat(497)}`)
  317. expect(out.length).toBeLessThanOrEqual(500)
  318. expect(out).toContain('Content truncated')
  319. } finally {
  320. spy.mockRestore()
  321. }
  322. })
  323. it('validates url (non-empty), no timeout parameter', () => {
  324. expect(() => parseFetchArgs({ url: ' ' })).toThrow('non-empty')
  325. expect(parseFetchArgs({ url: 'https://a.test' })).toEqual({ url: 'https://a.test' })
  326. })
  327. it('presents a fetch call as a fetch-kind card titled by the url', () => {
  328. expect(presentFetchCall({ url: 'https://a.test' })).toEqual({ card: 'generic', title: 'https://a.test', kind: 'fetch', rawInput: 'https://a.test' })
  329. })
  330. })
  331. describe('web_fetch presentation meta and result view', () => {
  332. const NO_CAP = 1_000_000
  333. it('projects url, status, and the provider truncation into meta', () => {
  334. expect(fetchMetaFromValue({ url: 'https://a.test', statusCode: 404, truncated: true, body: { kind: 'text', content: 'x' } }, NO_CAP))
  335. .toEqual({ url: 'https://a.test', statusCode: 404, truncated: true })
  336. })
  337. it('projects truncated: true when the output cap cut a body the provider did not, matching the render footer', () => {
  338. // The provider reports truncated: false, but conversion outgrows the cap, so
  339. // the render text carries the truncation footer. The meta must agree.
  340. const value = {
  341. url: 'https://a.test', statusCode: 200, truncated: false,
  342. body: { kind: 'html' as const, content: `<p>${'_'.repeat(1000)}</p>` },
  343. }
  344. const meta = fetchMetaFromValue(value, 500) as { truncated: boolean }
  345. expect(meta.truncated).toBe(true)
  346. expect(formatFetchOutput(value, 500)).toContain('Content truncated')
  347. })
  348. it('projects truncated: false when neither the provider nor the cap cut the body', () => {
  349. const value = {
  350. url: 'https://a.test', statusCode: 200, truncated: false,
  351. body: { kind: 'text' as const, content: 'short' },
  352. }
  353. const meta = fetchMetaFromValue(value, NO_CAP) as { truncated: boolean }
  354. expect(meta.truncated).toBe(false)
  355. expect(formatFetchOutput(value, NO_CAP)).not.toContain('Content truncated')
  356. })
  357. it('converts one HTML body once across the render and meta projections of the same result', () => {
  358. // The registry calls output.render and output.presentationMeta with the same
  359. // frozen result value; the memo must collapse them into one turndown walk so
  360. // a large or deeply nested page is not parsed and converted twice. A second
  361. // cap on the same result is a distinct entry, so it converts again.
  362. const spy = vi.spyOn(TurndownService.prototype, 'turndown')
  363. const value = {
  364. url: 'https://a.test', statusCode: 200, truncated: false,
  365. body: { kind: 'html' as const, content: '<p>hello</p>' },
  366. }
  367. try {
  368. formatFetchOutput(value, NO_CAP)
  369. fetchMetaFromValue(value, NO_CAP)
  370. expect(spy).toHaveBeenCalledTimes(1)
  371. formatFetchOutput(value, NO_CAP - 1)
  372. expect(spy).toHaveBeenCalledTimes(2)
  373. } finally {
  374. spy.mockRestore()
  375. }
  376. })
  377. it('presents a completed fetch as a web/fetch card carrying the summary, titled by the url, without content', () => {
  378. const meta = fetchMetaFromValue({ url: 'https://a.test', statusCode: 200, truncated: false, body: { kind: 'text', content: '# Title' } }, NO_CAP)
  379. expect(presentFetchResult({ url: 'https://a.test' }, toolResult(meta, '# Title'))).toEqual({
  380. card: 'web',
  381. kind: 'fetch',
  382. title: 'https://a.test',
  383. url: 'https://a.test',
  384. statusCode: 200,
  385. truncated: false,
  386. })
  387. })
  388. it('falls back to the generic card on an error result', () => {
  389. const meta = fetchMetaFromValue({ url: 'https://a.test', statusCode: 200, truncated: false, body: { kind: 'text', content: 'ok' } }, NO_CAP)
  390. expect(presentFetchResult({ url: 'https://a.test' }, toolResult(meta, 'body', true))).toBeUndefined()
  391. })
  392. it('falls back to the generic card on absent or malformed meta', () => {
  393. expect(presentFetchResult({ url: 'https://a.test' }, toolResult(undefined))).toBeUndefined()
  394. expect(fetchMetaFromResult(undefined)).toBeUndefined()
  395. expect(fetchMetaFromResult(null)).toBeUndefined()
  396. expect(fetchMetaFromResult('nope')).toBeUndefined()
  397. expect(fetchMetaFromResult([])).toBeUndefined()
  398. expect(fetchMetaFromResult({})).toBeUndefined()
  399. expect(fetchMetaFromResult({ url: 1, statusCode: 200, truncated: false })).toBeUndefined()
  400. expect(fetchMetaFromResult({ url: 'u', statusCode: 'x', truncated: false })).toBeUndefined()
  401. expect(fetchMetaFromResult({ url: 'u', statusCode: 200, truncated: 'no' })).toBeUndefined()
  402. })
  403. })
  404. describe('tool-web registration', () => {
  405. it('registers both tools by default', async () => {
  406. const { fiber, ctx } = await mountTools()
  407. const names = ctx.tools.schemas().map(s => s.name)
  408. expect(names).toContain('web_search')
  409. expect(names).toContain('web_fetch')
  410. expect(ctx.tools.executionMode({ signal: testToolSignal, callId: CallId('search-safe'), name: 'web_search', arguments: { queries: ['q'] } }))
  411. .toEqual({ kind: 'parallel' })
  412. expect(ctx.tools.executionMode({ signal: testToolSignal, callId: CallId('fetch-safe'), name: 'web_fetch', arguments: { url: 'https://a.test' } }))
  413. .toEqual({ kind: 'parallel' })
  414. await fiber.dispose()
  415. expect(ctx.tools.schemas().map(s => s.name)).not.toContain('web_search')
  416. })
  417. it('registers only enabled tools', async () => {
  418. const { fiber, ctx } = await mountTools({ config: { search: true, fetch: false } })
  419. const names = ctx.tools.schemas().map(s => s.name)
  420. expect(names).toContain('web_search')
  421. expect(names).not.toContain('web_fetch')
  422. await fiber.dispose()
  423. })
  424. it('registers only web_fetch when search is disabled', async () => {
  425. const { fiber, ctx } = await mountTools({ config: { search: false, fetch: true } })
  426. const names = ctx.tools.schemas().map(s => s.name)
  427. expect(names).not.toContain('web_search')
  428. expect(names).toContain('web_fetch')
  429. await fiber.dispose()
  430. })
  431. it('registers web_search even when no provider is available (schema follows enablement, not availability)', async () => {
  432. const { fiber, ctx, call } = await mountTools()
  433. expect(ctx.tools.schemas().map(s => s.name)).toContain('web_search')
  434. // No provider is registered: the schema stays visible and execution reports
  435. // the structured unavailability instead.
  436. const out = await call('web_search', { queries: ['q'] })
  437. expect(out.error?.info?.code).toBe('WEB_PROVIDER_UNAVAILABLE')
  438. await fiber.dispose()
  439. })
  440. it('contributes prompt sections for the enabled tools', async () => {
  441. const { fiber, ctx } = await mountTools()
  442. const prompt = await ctx.systemPrompt.assemble()
  443. const text = prompt.sections.map(s => s.text).join('\n')
  444. expect(text).toContain(`Use the web_search tool to discover current information on the web. The required queries array accepts 1–${WEB_SEARCH_MAX_QUERIES} non-empty search queries; use a one-item array for a single search. It returns an optional answer plus a list of source URLs. Follow up with web_fetch when you need the full content of a specific result, and cite the relevant URLs as markdown links.`)
  445. expect(text).toContain('Use the web_fetch tool to retrieve the content of a specific HTTP(S) URL')
  446. await fiber.dispose()
  447. })
  448. it('does not advertise web_fetch in search-only prompt guidance', async () => {
  449. const { fiber, ctx } = await mountTools({ config: { search: true, fetch: false } })
  450. const prompt = await ctx.systemPrompt.assemble()
  451. const text = prompt.sections.map(s => s.text).join('\n')
  452. expect(text).toContain('Use the returned source snippets when available')
  453. expect(text).not.toContain('web_fetch')
  454. await fiber.dispose()
  455. })
  456. })
  457. describe('tool-web execution through the real registry', () => {
  458. it('executes web_search and formats the result', async () => {
  459. const result: WebSearchResult = {
  460. content: 'answer', truncated: false,
  461. sources: [{ url: 'https://a.test', title: 'A', snippet: 'snip', publishedAt: '2026-07-20' }],
  462. }
  463. const { fiber, call } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: searchProvider(result) })
  464. const out = await call('web_search', { queries: ['q'] })
  465. expect(out.isError).toBe(false)
  466. expect(out.value).toEqual(result)
  467. expect(out.content.map(b => b.type === 'text' ? b.text : '').join('')).toContain('[A](https://a.test)')
  468. await fiber.dispose()
  469. })
  470. it('executes web_search with multiple queries concurrently and merges results', async () => {
  471. const seen: string[] = []
  472. let releaseFirst: (() => void) | undefined
  473. const firstResult = new Promise<WebSearchResult>((resolve) => {
  474. releaseFirst = () => {
  475. resolve({
  476. content: 'answer one', truncated: false,
  477. sources: [
  478. { url: 'https://a.test', title: 'A' },
  479. { url: 'https://shared.test' },
  480. ],
  481. })
  482. }
  483. })
  484. const provider: WebSearchProvider = {
  485. id: 'stub-search',
  486. available: () => available,
  487. search: (request) => {
  488. seen.push(request.query)
  489. if (request.query === 'one') return firstResult
  490. return Promise.resolve({
  491. content: 'answer two', truncated: false,
  492. sources: [
  493. { url: 'https://b.test', title: 'B' },
  494. { url: 'https://shared.test' },
  495. ],
  496. })
  497. },
  498. }
  499. const { fiber, call } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: provider })
  500. const pending = call('web_search', { queries: ['one', 'one', 'two'] })
  501. try {
  502. await vi.waitFor(() => { expect(seen).toEqual(['one', 'two']) })
  503. } finally {
  504. releaseFirst?.()
  505. }
  506. const out = await pending
  507. expect(out.isError).toBe(false)
  508. expect(out.value).toEqual({
  509. content: '### one\n\nanswer one\n\n### two\n\nanswer two',
  510. sources: [
  511. { url: 'https://a.test', title: 'A' },
  512. { url: 'https://b.test', title: 'B' },
  513. { url: 'https://shared.test' },
  514. ],
  515. truncated: false,
  516. })
  517. const body = out.content.map(b => b.type === 'text' ? b.text : '').join('')
  518. expect(body).toContain('### one')
  519. expect(body).toContain('### two')
  520. await fiber.dispose()
  521. })
  522. it('continues round-robin merging after a shorter result is exhausted', async () => {
  523. const provider: WebSearchProvider = {
  524. id: 'stub-search',
  525. available: () => available,
  526. search: request => Promise.resolve(request.query === 'one'
  527. ? { content: '', sources: [{ url: 'https://a.test' }], truncated: false }
  528. : { sources: [{ url: 'https://b.test' }, { url: 'https://c.test' }], truncated: false }),
  529. }
  530. const { fiber, call } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: provider })
  531. const out = await call('web_search', { queries: ['one', 'two'] })
  532. expect(out.isError).toBe(false)
  533. expect(out.value).toEqual({
  534. sources: [
  535. { url: 'https://a.test' },
  536. { url: 'https://b.test' },
  537. { url: 'https://c.test' },
  538. ],
  539. truncated: false,
  540. })
  541. await fiber.dispose()
  542. })
  543. it('aborts sibling searches and waits for them to settle before reporting a batch failure', async () => {
  544. let siblingAborted = false
  545. let releaseSibling: (() => void) | undefined
  546. const provider: WebSearchProvider = {
  547. id: 'stub-search',
  548. available: () => available,
  549. search: (request, signal) => {
  550. if (request.query === 'one') return Promise.reject(new Error('first search failed'))
  551. return new Promise((_resolve, reject) => {
  552. releaseSibling = () => { reject(new Error('sibling search stopped')) }
  553. signal?.addEventListener('abort', () => {
  554. siblingAborted = true
  555. }, { once: true })
  556. })
  557. },
  558. }
  559. const { fiber, call } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: provider })
  560. const pending = call('web_search', { queries: ['one', 'two'] })
  561. let callSettled = false
  562. void pending.then(() => { callSettled = true })
  563. try {
  564. await vi.waitFor(() => { expect(siblingAborted).toBe(true) })
  565. await Promise.resolve()
  566. expect(callSettled).toBe(false)
  567. } finally {
  568. releaseSibling?.()
  569. }
  570. const out = await pending
  571. expect(out.isError).toBe(true)
  572. expect(out.content).toEqual([{ type: 'text', text: 'Error: first search failed' }])
  573. await fiber.dispose()
  574. })
  575. it('caps combined multi-query results to searchMaxResults', async () => {
  576. const provider: WebSearchProvider = {
  577. id: 'stub-search',
  578. available: () => available,
  579. search: request => Promise.resolve({
  580. sources: request.query === 'one'
  581. ? [{ url: 'https://a.test' }, { url: 'https://b.test' }]
  582. : [{ url: 'https://c.test' }, { url: 'https://d.test' }],
  583. truncated: false,
  584. }),
  585. }
  586. const { fiber, call } = await mountTools({ config: { searchMaxResults: 2 }, webConfig: { searchProvider: 'stub-search' }, search: provider })
  587. const out = await call('web_search', { queries: ['one', 'two'] })
  588. expect(out.isError).toBe(false)
  589. expect(out.value).toEqual({
  590. sources: [{ url: 'https://a.test' }, { url: 'https://c.test' }],
  591. truncated: true,
  592. })
  593. const body = out.content.map(b => b.type === 'text' ? b.text : '').join('')
  594. expect(body).toContain('Showing the first 2 sources.')
  595. await fiber.dispose()
  596. })
  597. it('projects the search sources into the tool result meta and derives its web/search view', async () => {
  598. const result: WebSearchResult = {
  599. content: 'answer', truncated: true,
  600. sources: [{ url: 'https://a.test', title: 'A', snippet: 'snip', publishedAt: '2026-07-20' }],
  601. }
  602. const { ctx, fiber, call } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: searchProvider(result) })
  603. const out = await call('web_search', { queries: ['q'] })
  604. expect(out.meta).toEqual({
  605. answer: 'answer', truncated: true,
  606. sources: [{ url: 'https://a.test', title: 'A', snippet: 'snip', publishedAt: '2026-07-20' }],
  607. })
  608. const view = ctx.tools.get('web_search')?.presentResult?.({ queries: ['q'] }, { content: out.content, isError: out.isError, ...out.meta !== undefined ? { meta: out.meta } : {} })
  609. expect(view).toMatchObject({ card: 'web', kind: 'search', truncated: true, answer: 'answer' })
  610. await fiber.dispose()
  611. })
  612. it('projects the fetch summary into the tool result meta and derives its web/fetch view', async () => {
  613. const fetchProvider = {
  614. id: 'stub-fetch',
  615. available: () => available,
  616. fetch: (request: { url: string }) => Promise.resolve({
  617. url: request.url, statusCode: 200, body: { kind: 'text' as const, content: 'ok' }, truncated: true,
  618. }),
  619. }
  620. const { ctx, fiber, call } = await mountTools({ webConfig: { fetchProvider: 'stub-fetch' }, fetchProvider })
  621. const out = await call('web_fetch', { url: 'https://a.test' })
  622. expect(out.meta).toEqual({ url: 'https://a.test', statusCode: 200, truncated: true })
  623. const view = ctx.tools.get('web_fetch')?.presentResult?.({ url: 'https://a.test' }, { content: out.content, isError: out.isError, ...out.meta !== undefined ? { meta: out.meta } : {} })
  624. expect(view).toMatchObject({ card: 'web', kind: 'fetch', url: 'https://a.test', statusCode: 200, truncated: true })
  625. await fiber.dispose()
  626. })
  627. it('surfaces a structured WebError when no provider is available', async () => {
  628. const { fiber, call } = await mountTools()
  629. const out = await call('web_search', { queries: ['q'] })
  630. expect(out.isError).toBe(true)
  631. expect(out.error?.info?.code).toBe('WEB_PROVIDER_UNAVAILABLE')
  632. await fiber.dispose()
  633. })
  634. it('surfaces WEB_PROVIDER_AMBIGUOUS for multiple unconfigured providers', async () => {
  635. const { ctx, fiber, call } = await mountTools({ search: searchProvider({ sources: [], truncated: false }) })
  636. ctx.web.registerSearchProvider({ id: 'other', available: () => available, search: () => Promise.resolve({ sources: [], truncated: false }) })
  637. const out = await call('web_search', { queries: ['q'] })
  638. expect(out.isError).toBe(true)
  639. expect(out.error?.info?.code).toBe('WEB_PROVIDER_AMBIGUOUS')
  640. await fiber.dispose()
  641. })
  642. it.each([{}, { queries: [123] }])('rejects absent or wrongly typed queries with a structured INVALID_ARGS error', async (args) => {
  643. const { fiber, call } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: searchProvider({ sources: [], truncated: false }) })
  644. const out = await call('web_search', args)
  645. expect(out.isError).toBe(true)
  646. expect(out.error?.info?.code).toBe('INVALID_ARGS')
  647. await fiber.dispose()
  648. })
  649. it('has no default export (namespace plugin export shape)', () => {
  650. expect('default' in ToolWeb).toBe(false)
  651. })
  652. it('executes web_fetch, forwarding the url (no timeout param) and the abort signal to the seam', async () => {
  653. const seen: { request?: { url: string }; signal?: AbortSignal | undefined } = {}
  654. const fetchProvider = {
  655. id: 'stub-fetch',
  656. available: () => available,
  657. fetch: (request: { url: string }, signal?: AbortSignal) => {
  658. seen.request = request
  659. seen.signal = signal
  660. return Promise.resolve({ url: request.url, statusCode: 200, body: { kind: 'text' as const, content: 'ok' }, truncated: false })
  661. },
  662. }
  663. const { ctx, fiber } = await mountTools({ webConfig: { fetchProvider: 'stub-fetch' }, fetchProvider })
  664. const controller = new AbortController()
  665. const out = await ctx.tools.execute({ callId: CallId('fetch-1'), name: 'web_fetch', arguments: { url: 'https://a.test' }, signal: controller.signal })
  666. expect(out.isError).toBe(false)
  667. expect(out.value).toEqual({
  668. url: 'https://a.test',
  669. statusCode: 200,
  670. body: { kind: 'text', content: 'ok' },
  671. truncated: false,
  672. })
  673. // The model schema exposes no timeout: the tool forwards only the url; the
  674. // tool-call budget is owned by dsh-tool-call-timeout-policy over exec.signal.
  675. expect(seen.request).toEqual({ url: 'https://a.test' })
  676. expect(seen.signal).toBe(controller.signal)
  677. await fiber.dispose()
  678. })
  679. it('forwards the required caller signal to web_fetch', async () => {
  680. const seen: { signal?: AbortSignal | undefined; passedSignal?: boolean } = {}
  681. const fetchProvider = {
  682. id: 'stub-fetch',
  683. available: () => available,
  684. fetch: (request: { url: string }, signal?: AbortSignal) => {
  685. seen.passedSignal = signal !== undefined
  686. seen.signal = signal
  687. return Promise.resolve({ url: request.url, statusCode: 200, body: { kind: 'text' as const, content: 'ok' }, truncated: false })
  688. },
  689. }
  690. const { ctx, fiber } = await mountTools({ webConfig: { fetchProvider: 'stub-fetch' }, fetchProvider })
  691. const out = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('fetch-2'), name: 'web_fetch', arguments: { url: 'https://a.test' } })
  692. expect(out.isError).toBe(false)
  693. expect(out.value).toEqual({
  694. url: 'https://a.test',
  695. statusCode: 200,
  696. body: { kind: 'text', content: 'ok' },
  697. truncated: false,
  698. })
  699. expect(seen.passedSignal).toBe(true)
  700. expect(seen.signal).toBe(testToolSignal)
  701. await fiber.dispose()
  702. })
  703. it('executes web_search, forwarding the abort signal to the seam', async () => {
  704. const seen: { signal?: AbortSignal | undefined } = {}
  705. const provider: WebSearchProvider = {
  706. id: 'stub-search',
  707. available: () => available,
  708. search: (_request, signal) => { seen.signal = signal; return Promise.resolve({ sources: [], truncated: false }) },
  709. }
  710. const { ctx, fiber } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: provider })
  711. const controller = new AbortController()
  712. await ctx.tools.execute({ callId: CallId('search-1'), name: 'web_search', arguments: { queries: ['q'] }, signal: controller.signal })
  713. expect(seen.signal).toBe(controller.signal)
  714. await fiber.dispose()
  715. })
  716. it('cascades caller cancellation to every multi-query search', async () => {
  717. const signals: (AbortSignal | undefined)[] = []
  718. const provider: WebSearchProvider = {
  719. id: 'stub-search',
  720. available: () => available,
  721. search: (_request, signal) => {
  722. signals.push(signal)
  723. return new Promise((_resolve, reject) => {
  724. signal?.addEventListener('abort', () => { reject(new Error('search aborted')) }, { once: true })
  725. })
  726. },
  727. }
  728. const { ctx, fiber } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: provider })
  729. const controller = new AbortController()
  730. const pending = ctx.tools.execute({ callId: CallId('search-multi-1'), name: 'web_search', arguments: { queries: ['one', 'two'] }, signal: controller.signal })
  731. await vi.waitFor(() => { expect(signals).toHaveLength(2) })
  732. expect(signals[0]).toBe(signals[1])
  733. expect(signals[0]).not.toBe(controller.signal)
  734. controller.abort(new Error('caller cancelled'))
  735. await pending
  736. expect(signals.every(signal => signal?.aborted === true)).toBe(true)
  737. await fiber.dispose()
  738. })
  739. })
  740. describe('searchMaxResults is plugin config', () => {
  741. it('forwards the default cap to the seam when unconfigured', async () => {
  742. const seen: { maxResults?: number | undefined } = {}
  743. const provider: WebSearchProvider = {
  744. id: 'stub-search',
  745. available: () => available,
  746. search: (request) => { seen.maxResults = request.maxResults; return Promise.resolve({ sources: [], truncated: false }) },
  747. }
  748. const { fiber, call } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: provider })
  749. await call('web_search', { queries: ['q'] })
  750. expect(seen.maxResults).toBe(WEB_SEARCH_MAX_RESULTS)
  751. await fiber.dispose()
  752. })
  753. it('forwards a configured cap to the seam, which enforces it', async () => {
  754. const sources = Array.from({ length: 5 }, (_, i) => ({ url: `https://s${i}.test` }))
  755. const provider: WebSearchProvider = {
  756. id: 'stub-search',
  757. available: () => available,
  758. search: () => Promise.resolve({ sources, truncated: false }),
  759. }
  760. const { fiber, call } = await mountTools({ config: { searchMaxResults: 2 }, webConfig: { searchProvider: 'stub-search' }, search: provider })
  761. const out = await call('web_search', { queries: ['q'] })
  762. expect(out.isError).toBe(false)
  763. const body = out.content.map(b => b.type === 'text' ? b.text : '').join('')
  764. expect(body).toContain('https://s1.test')
  765. expect(body).not.toContain('https://s2.test')
  766. expect(body).toContain('Showing the first 2 sources.')
  767. await fiber.dispose()
  768. })
  769. it.each([
  770. ['zero', 0],
  771. ['negative', -3],
  772. ['fractional', 1.5],
  773. ])('rejects a %s searchMaxResults at load', async (_label, value) => {
  774. const ctx = new Context()
  775. await ctx.plugin(SystemPrompt)
  776. await ctx.plugin(ToolRuntime)
  777. await ctx.plugin(WebRuntime, {})
  778. await expect(ctx.plugin(ToolWeb, { searchMaxResults: value }))
  779. .rejects.toThrow(/tool-web: searchMaxResults must be a positive integer/)
  780. })
  781. })
  782. describe('searchMaxQueries is plugin config', () => {
  783. it('exposes the configured cap to the model and enforces it before provider calls', async () => {
  784. const seen: string[] = []
  785. const provider: WebSearchProvider = {
  786. id: 'stub-search',
  787. available: () => available,
  788. search: (request) => {
  789. seen.push(request.query)
  790. return Promise.resolve({ sources: [], truncated: false })
  791. },
  792. }
  793. const { fiber, ctx, call } = await mountTools({
  794. config: { searchMaxQueries: 2 },
  795. webConfig: { searchProvider: 'stub-search' },
  796. search: provider,
  797. })
  798. const schema = ctx.tools.schemas().find(item => item.name === 'web_search')
  799. expect(schema?.description).toContain('1–2 queries')
  800. const prompt = await ctx.systemPrompt.assemble()
  801. expect(prompt.sections.map(section => section.text).join('\n')).toContain('accepts 1–2 non-empty search queries')
  802. const out = await call('web_search', { queries: ['one', 'two', 'three'] })
  803. expect(out.isError).toBe(true)
  804. expect(out.content).toEqual([{ type: 'text', text: 'Error: queries must contain at most 2 queries' }])
  805. expect(seen).toEqual([])
  806. await fiber.dispose()
  807. })
  808. it.each([0, -1, 1.5])('rejects an invalid searchMaxQueries value %s at load', async (value) => {
  809. const ctx = new Context()
  810. await ctx.plugin(SystemPrompt)
  811. await ctx.plugin(ToolRuntime)
  812. await ctx.plugin(WebRuntime, {})
  813. await expect(ctx.plugin(ToolWeb, { searchMaxQueries: value }))
  814. .rejects.toThrow(/tool-web: searchMaxQueries must be a positive integer/)
  815. })
  816. })
  817. describe('tool-call timeout budget is plugin config', () => {
  818. it('attaches the default 30s budget to web_fetch and web_search', async () => {
  819. const { fiber, ctx } = await mountTools()
  820. expect(ctx.tools.get('web_fetch')?.timeoutMs).toBe(30_000)
  821. expect(ctx.tools.get('web_search')?.timeoutMs).toBe(30_000)
  822. await fiber.dispose()
  823. })
  824. it('honors per-tool timeout overrides from config', async () => {
  825. const { fiber, ctx } = await mountTools({ config: { fetchTimeoutMs: 60_000, searchTimeoutMs: 10_000 } })
  826. expect(ctx.tools.get('web_fetch')?.timeoutMs).toBe(60_000)
  827. expect(ctx.tools.get('web_search')?.timeoutMs).toBe(10_000)
  828. await fiber.dispose()
  829. })
  830. it.each([
  831. ['fetchTimeoutMs', { fetchTimeoutMs: 0 }],
  832. ['searchTimeoutMs', { searchTimeoutMs: -5 }],
  833. ])('rejects a non-positive-integer %s at load', async (key, config) => {
  834. const ctx = new Context()
  835. await ctx.plugin(SystemPrompt)
  836. await ctx.plugin(ToolRuntime)
  837. await ctx.plugin(WebRuntime, {})
  838. await expect(ctx.plugin(ToolWeb, config))
  839. .rejects.toThrow(new RegExp(`tool-web: ${key} must be a positive integer`))
  840. })
  841. })
  842. describe('fetchMaxOutputChars is plugin config', () => {
  843. it('bounds the rendered output of the registered web_fetch tool', async () => {
  844. const fetchProvider = {
  845. id: 'stub-fetch',
  846. available: () => available,
  847. fetch: (request: { url: string }) => Promise.resolve({
  848. url: request.url,
  849. statusCode: 200,
  850. body: { kind: 'html' as const, content: `<p>${'_'.repeat(1_000)}</p>` },
  851. truncated: false,
  852. }),
  853. }
  854. const { fiber, call } = await mountTools({
  855. config: { fetchMaxOutputChars: 100 },
  856. webConfig: { fetchProvider: 'stub-fetch' },
  857. fetchProvider,
  858. })
  859. const out = await call('web_fetch', { url: 'https://a.test' })
  860. expect(out.content.map(block => block.type === 'text' ? block.text : '').join('')).toHaveLength(100)
  861. await fiber.dispose()
  862. })
  863. it.each([0, -1, 1.5])('rejects an invalid fetchMaxOutputChars value %s at load', async (value) => {
  864. const ctx = new Context()
  865. await ctx.plugin(SystemPrompt)
  866. await ctx.plugin(ToolRuntime)
  867. await ctx.plugin(WebRuntime, {})
  868. await expect(ctx.plugin(ToolWeb, { fetchMaxOutputChars: value }))
  869. .rejects.toThrow(/tool-web: fetchMaxOutputChars must be a positive integer/)
  870. })
  871. })