tool-web.spec.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { CallId } from '@deepseek-ai/dsh-llm'
  4. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  5. import ToolRegistry from '@deepseek-ai/dsh-tools'
  6. import WebService from '@deepseek-ai/dsh-web'
  7. import type { WebSearchProvider, WebSearchResult, WebProviderStatus } from '@deepseek-ai/dsh-web'
  8. import * as ToolWeb from '@deepseek-ai/dsh-tool-web'
  9. import {
  10. formatSearchOutput,
  11. formatFetchOutput,
  12. parseSearchArgs,
  13. parseFetchArgs,
  14. presentSearchCall,
  15. presentFetchCall,
  16. renderBody,
  17. htmlToMarkdown,
  18. WEB_SEARCH_MAX_RESULTS,
  19. } from '@deepseek-ai/dsh-tool-web'
  20. const available: WebProviderStatus = { available: true }
  21. function searchProvider(result: WebSearchResult, status: WebProviderStatus = available): WebSearchProvider {
  22. return { id: 'stub-search', status: () => status, search: () => Promise.resolve(result) }
  23. }
  24. /** Mount the real registry, seam, and tool-web; return an executor helper. */
  25. async function mountTools(opts: {
  26. config?: ToolWeb.Config
  27. webConfig?: ConstructorParameters<typeof WebService>[1]
  28. search?: WebSearchProvider
  29. fetchProvider?: import('@deepseek-ai/dsh-web').WebFetchProvider
  30. } = {}): Promise<{ ctx: Context; fiber: Awaited<ReturnType<Context['plugin']>>; call: (name: string, args: unknown) => Promise<{ isError: boolean; content: { type: string; text?: string }[]; error?: { code: string } }> }> {
  31. const ctx = new Context()
  32. await ctx.plugin(SystemPrompt)
  33. await ctx.plugin(ToolRegistry)
  34. await ctx.plugin(WebService, opts.webConfig ?? {})
  35. if (opts.search) ctx.web.registerSearchProvider(opts.search)
  36. if (opts.fetchProvider) ctx.web.registerFetchProvider(opts.fetchProvider)
  37. const fiber = await ctx.plugin(ToolWeb, opts.config ?? {})
  38. let counter = 0
  39. const call = (name: string, args: unknown) => ctx.tools.execute({ callId: CallId(`call-${++counter}`), name, arguments: args }) as never
  40. return { ctx, fiber, call }
  41. }
  42. describe('search formatting', () => {
  43. it('renders content, sources with titles/hostnames, snippets, and a citation reminder', () => {
  44. const out = formatSearchOutput({
  45. providerId: 'p', query: 'q', content: 'an answer', truncated: false,
  46. sources: [
  47. { url: 'https://a.test/x', title: 'A', snippet: 'about a', publishedAt: '2026-01-01' },
  48. { url: 'https://b.test/y' },
  49. ],
  50. })
  51. expect(out).toContain('an answer')
  52. expect(out).toContain('[A](https://a.test/x) — about a (2026-01-01)')
  53. expect(out).toContain('[b.test](https://b.test/y)')
  54. expect(out).toContain('Cite the relevant URLs')
  55. })
  56. it('reports no results when there is neither content nor sources', () => {
  57. expect(formatSearchOutput({ providerId: 'p', query: 'q', sources: [], truncated: false }))
  58. .toContain('No results found.')
  59. })
  60. it('renders content alone when there are no sources', () => {
  61. const out = formatSearchOutput({ providerId: 'p', query: 'q', content: 'just an answer', sources: [], truncated: false })
  62. expect(out).toContain('just an answer')
  63. expect(out).not.toContain('No results found.')
  64. expect(out).not.toContain('Sources:')
  65. })
  66. it('notes truncation', () => {
  67. const out = formatSearchOutput({ providerId: 'p', query: 'q', sources: [{ url: 'https://a.test' }], truncated: true })
  68. expect(out).toContain('Showing the first 1 sources')
  69. })
  70. it('validates the query', () => {
  71. expect(() => parseSearchArgs({ query: ' ' })).toThrow('non-empty')
  72. expect(parseSearchArgs({ query: 'hi' })).toEqual({ query: 'hi' })
  73. })
  74. it('presents a search call as a search-kind card titled by the query', () => {
  75. expect(presentSearchCall({ query: 'find me' })).toEqual({ card: 'generic', title: 'find me', kind: 'search', rawInput: 'find me' })
  76. })
  77. })
  78. describe('fetch formatting', () => {
  79. it('renders an html body to markdown text with a status header', () => {
  80. const out = formatFetchOutput({
  81. providerId: 'p', url: 'https://a.test', statusCode: 200, truncated: false,
  82. body: { kind: 'html', content: '<h1>Title</h1><p>Body text</p>' },
  83. })
  84. expect(out).toContain('Fetched https://a.test (HTTP 200)')
  85. expect(out).toContain('# Title')
  86. expect(out).toContain('Body text')
  87. })
  88. it('passes a text body through and notes truncation', () => {
  89. const out = formatFetchOutput({
  90. providerId: 'p', url: 'https://a.test', statusCode: 200, truncated: true,
  91. body: { kind: 'text', content: 'plain' },
  92. })
  93. expect(out).toContain('plain')
  94. expect(out).toContain('Content truncated')
  95. })
  96. it('renderBody dispatches on kind', () => {
  97. expect(renderBody({ kind: 'text', content: 'x' })).toBe('x')
  98. expect(renderBody({ kind: 'html', content: '<p>y</p>' })).toBe('y')
  99. })
  100. it('validates url (non-empty), no timeout parameter', () => {
  101. expect(() => parseFetchArgs({ url: ' ' })).toThrow('non-empty')
  102. expect(parseFetchArgs({ url: 'https://a.test' })).toEqual({ url: 'https://a.test' })
  103. })
  104. it('presents a fetch call as a fetch-kind card titled by the url', () => {
  105. expect(presentFetchCall({ url: 'https://a.test' })).toEqual({ card: 'generic', title: 'https://a.test', kind: 'fetch', rawInput: 'https://a.test' })
  106. })
  107. })
  108. describe('htmlToMarkdown', () => {
  109. it('drops scripts/styles, keeps text, decodes entities, converts links', () => {
  110. const md = htmlToMarkdown('<style>.x{}</style><script>bad()</script><p>Tom &amp; Jerry</p><a href="https://a.test">link</a>')
  111. expect(md).not.toContain('bad()')
  112. expect(md).not.toContain('.x{}')
  113. expect(md).toContain('Tom & Jerry')
  114. expect(md).toContain('[link](https://a.test)')
  115. })
  116. it('decodes numeric entities and collapses whitespace', () => {
  117. expect(htmlToMarkdown('<p>a&#39;b</p>')).toBe("a'b")
  118. expect(htmlToMarkdown('<div>x</div>\n\n\n<div>y</div>')).toBe('x\n\ny')
  119. })
  120. it('decodes hex entities and named entities, and leaves unknown/out-of-range ones intact', () => {
  121. expect(htmlToMarkdown('<p>&#x41;&#X42;</p>')).toBe('AB')
  122. expect(htmlToMarkdown('<p>&copy; &mdash;</p>')).toBe('© —')
  123. expect(htmlToMarkdown('<p>&notareal;</p>')).toBe('&notareal;')
  124. // An out-of-range code point keeps the original entity text (fromCodePoint fallback).
  125. expect(htmlToMarkdown('<p>&#x110000;</p>')).toBe('&#x110000;')
  126. expect(htmlToMarkdown('<p>&#1114112;</p>')).toBe('&#1114112;')
  127. })
  128. it('renders a link with an empty label as its bare href', () => {
  129. expect(htmlToMarkdown('<a href="https://a.test"></a>')).toBe('https://a.test')
  130. })
  131. it('converts headings and list items to markdown', () => {
  132. expect(htmlToMarkdown('<h2>Heading</h2><p>after</p>')).toContain('## Heading')
  133. const list = htmlToMarkdown('<ul><li>one</li><li>two</li></ul>')
  134. expect(list).toContain('- one')
  135. expect(list).toContain('- two')
  136. })
  137. it('falls back to the raw URL as a source label when the URL is unparseable', () => {
  138. const out = formatSearchOutput({ providerId: 'p', query: 'q', truncated: false, sources: [{ url: 'not a url' }] })
  139. expect(out).toContain('[not a url](not a url)')
  140. })
  141. })
  142. describe('tool-web registration', () => {
  143. it('registers both tools by default', async () => {
  144. const { fiber, ctx } = await mountTools()
  145. const names = ctx.tools.schemas().map(s => s.name)
  146. expect(names).toContain('web_search')
  147. expect(names).toContain('web_fetch')
  148. await fiber.dispose()
  149. expect(ctx.tools.schemas().map(s => s.name)).not.toContain('web_search')
  150. })
  151. it('registers only enabled tools', async () => {
  152. const { fiber, ctx } = await mountTools({ config: { search: true, fetch: false } })
  153. const names = ctx.tools.schemas().map(s => s.name)
  154. expect(names).toContain('web_search')
  155. expect(names).not.toContain('web_fetch')
  156. await fiber.dispose()
  157. })
  158. it('registers only web_fetch when search is disabled', async () => {
  159. const { fiber, ctx } = await mountTools({ config: { search: false, fetch: true } })
  160. const names = ctx.tools.schemas().map(s => s.name)
  161. expect(names).not.toContain('web_search')
  162. expect(names).toContain('web_fetch')
  163. await fiber.dispose()
  164. })
  165. it('registers web_search even when no provider is available (schema follows enablement, not availability)', async () => {
  166. const { fiber, ctx, call } = await mountTools()
  167. expect(ctx.tools.schemas().map(s => s.name)).toContain('web_search')
  168. // No provider is registered: the schema stays visible and execution reports
  169. // the structured unavailability instead.
  170. const out = await call('web_search', { query: 'q' })
  171. expect(out.error?.code).toBe('WEB_PROVIDER_UNAVAILABLE')
  172. await fiber.dispose()
  173. })
  174. it('contributes prompt sections for the enabled tools', async () => {
  175. const { fiber, ctx } = await mountTools()
  176. const prompt = await ctx.systemPrompt.assemble()
  177. const text = prompt.sections.map(s => s.text).join('\n')
  178. expect(text).toContain('web_search')
  179. expect(text).toContain('web_fetch')
  180. await fiber.dispose()
  181. })
  182. })
  183. describe('tool-web execution through the real registry', () => {
  184. it('executes web_search and formats the result', async () => {
  185. const result: WebSearchResult = {
  186. providerId: 'stub-search', query: 'q', content: 'answer', truncated: false,
  187. sources: [{ url: 'https://a.test', title: 'A', snippet: 'snip' }],
  188. }
  189. const { fiber, call } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: searchProvider(result) })
  190. const out = await call('web_search', { query: 'q' })
  191. expect(out.isError).toBe(false)
  192. expect(out.content.map(b => b.text).join('')).toContain('[A](https://a.test)')
  193. await fiber.dispose()
  194. })
  195. it('surfaces a structured WebError when no provider is available', async () => {
  196. const { fiber, call } = await mountTools()
  197. const out = await call('web_search', { query: 'q' })
  198. expect(out.isError).toBe(true)
  199. expect(out.error?.code).toBe('WEB_PROVIDER_UNAVAILABLE')
  200. await fiber.dispose()
  201. })
  202. it('surfaces WEB_PROVIDER_AMBIGUOUS for multiple unconfigured providers', async () => {
  203. const { ctx, fiber, call } = await mountTools({ search: searchProvider({ providerId: 'stub-search', query: 'q', sources: [], truncated: false }) })
  204. ctx.web.registerSearchProvider({ id: 'other', status: () => available, search: () => Promise.resolve({ providerId: 'other', query: 'q', sources: [], truncated: false }) })
  205. const out = await call('web_search', { query: 'q' })
  206. expect(out.isError).toBe(true)
  207. expect(out.error?.code).toBe('WEB_PROVIDER_AMBIGUOUS')
  208. await fiber.dispose()
  209. })
  210. it('rejects invalid arguments with a structured INVALID_ARGS error', async () => {
  211. const { fiber, call } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: searchProvider({ providerId: 'stub-search', query: 'q', sources: [], truncated: false }) })
  212. const out = await call('web_search', { query: 123 })
  213. expect(out.isError).toBe(true)
  214. expect(out.error?.code).toBe('INVALID_ARGS')
  215. await fiber.dispose()
  216. })
  217. it('has no default export (namespace plugin export shape)', () => {
  218. expect('default' in ToolWeb).toBe(false)
  219. })
  220. it('executes web_fetch, forwarding the url (no timeout param) and the abort signal to the seam', async () => {
  221. const seen: { request?: { url: string; timeoutMs?: number }; signal?: AbortSignal | undefined } = {}
  222. const fetchProvider = {
  223. id: 'stub-fetch',
  224. status: () => available,
  225. fetch: (request: { url: string; timeoutMs?: number }, exec?: { signal?: AbortSignal }) => {
  226. seen.request = request
  227. seen.signal = exec?.signal
  228. return Promise.resolve({ providerId: 'stub-fetch', url: request.url, statusCode: 200, body: { kind: 'text' as const, content: 'ok' }, truncated: false })
  229. },
  230. }
  231. const { ctx, fiber } = await mountTools({ webConfig: { fetchProvider: 'stub-fetch' }, fetchProvider })
  232. const controller = new AbortController()
  233. const out = await ctx.tools.execute({ callId: CallId('fetch-1'), name: 'web_fetch', arguments: { url: 'https://a.test' }, signal: controller.signal })
  234. expect(out.isError).toBe(false)
  235. // The model schema exposes no timeout: the tool forwards only the url; the
  236. // tool-call budget is owned by dsh-timeout-policy over exec.signal.
  237. expect(seen.request).toEqual({ url: 'https://a.test' })
  238. expect(seen.signal).toBe(controller.signal)
  239. await fiber.dispose()
  240. })
  241. it('executes web_fetch with no caller signal (forwards undefined to the seam)', async () => {
  242. const seen: { signal?: AbortSignal | undefined; passedExec?: boolean } = {}
  243. const fetchProvider = {
  244. id: 'stub-fetch',
  245. status: () => available,
  246. fetch: (request: { url: string }, exec?: { signal?: AbortSignal }) => {
  247. seen.passedExec = exec !== undefined
  248. seen.signal = exec?.signal
  249. return Promise.resolve({ providerId: 'stub-fetch', url: request.url, statusCode: 200, body: { kind: 'text' as const, content: 'ok' }, truncated: false })
  250. },
  251. }
  252. const { ctx, fiber } = await mountTools({ webConfig: { fetchProvider: 'stub-fetch' }, fetchProvider })
  253. // No signal on the execution: the tool passes `undefined` (not `{ signal: undefined }`).
  254. const out = await ctx.tools.execute({ callId: CallId('fetch-2'), name: 'web_fetch', arguments: { url: 'https://a.test' } })
  255. expect(out.isError).toBe(false)
  256. expect(seen.passedExec).toBe(false)
  257. expect(seen.signal).toBeUndefined()
  258. await fiber.dispose()
  259. })
  260. it('executes web_search, forwarding the abort signal to the seam', async () => {
  261. const seen: { signal?: AbortSignal | undefined } = {}
  262. const provider: WebSearchProvider = {
  263. id: 'stub-search',
  264. status: () => available,
  265. search: (_request, exec) => { seen.signal = exec?.signal; return Promise.resolve({ providerId: 'stub-search', query: 'q', sources: [], truncated: false }) },
  266. }
  267. const { ctx, fiber } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: provider })
  268. const controller = new AbortController()
  269. await ctx.tools.execute({ callId: CallId('search-1'), name: 'web_search', arguments: { query: 'q' }, signal: controller.signal })
  270. expect(seen.signal).toBe(controller.signal)
  271. await fiber.dispose()
  272. })
  273. })
  274. describe('searchMaxResults is plugin config', () => {
  275. it('forwards the default cap to the seam when unconfigured', async () => {
  276. const seen: { maxResults?: number | undefined } = {}
  277. const provider: WebSearchProvider = {
  278. id: 'stub-search',
  279. status: () => available,
  280. search: (request) => { seen.maxResults = request.maxResults; return Promise.resolve({ providerId: 'stub-search', query: 'q', sources: [], truncated: false }) },
  281. }
  282. const { fiber, call } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: provider })
  283. await call('web_search', { query: 'q' })
  284. expect(seen.maxResults).toBe(WEB_SEARCH_MAX_RESULTS)
  285. await fiber.dispose()
  286. })
  287. it('forwards a configured cap to the seam, which enforces it', async () => {
  288. const sources = Array.from({ length: 5 }, (_, i) => ({ url: `https://s${i}.test` }))
  289. const provider: WebSearchProvider = {
  290. id: 'stub-search',
  291. status: () => available,
  292. search: request => Promise.resolve({ providerId: 'stub-search', query: request.query, sources, truncated: false }),
  293. }
  294. const { fiber, call } = await mountTools({ config: { searchMaxResults: 2 }, webConfig: { searchProvider: 'stub-search' }, search: provider })
  295. const out = await call('web_search', { query: 'q' })
  296. expect(out.isError).toBe(false)
  297. const body = out.content.map(b => b.text).join('')
  298. expect(body).toContain('https://s1.test')
  299. expect(body).not.toContain('https://s2.test')
  300. expect(body).toContain('Showing the first 2 sources.')
  301. await fiber.dispose()
  302. })
  303. it.each([
  304. ['zero', 0],
  305. ['negative', -3],
  306. ['fractional', 1.5],
  307. ])('rejects a %s searchMaxResults at load', async (_label, value) => {
  308. const ctx = new Context()
  309. await ctx.plugin(SystemPrompt)
  310. await ctx.plugin(ToolRegistry)
  311. await ctx.plugin(WebService, {})
  312. await expect(ctx.plugin(ToolWeb, { searchMaxResults: value }))
  313. .rejects.toThrow(/tool-web: searchMaxResults must be a positive integer/)
  314. })
  315. })
  316. describe('tool-call timeout budget is plugin config', () => {
  317. it('attaches the default 30s budget to web_fetch and web_search', async () => {
  318. const { fiber, ctx } = await mountTools()
  319. expect(ctx.tools.get('web_fetch')?.timeoutMs).toBe(30_000)
  320. expect(ctx.tools.get('web_search')?.timeoutMs).toBe(30_000)
  321. await fiber.dispose()
  322. })
  323. it('honors per-tool timeout overrides from config', async () => {
  324. const { fiber, ctx } = await mountTools({ config: { fetchTimeoutMs: 60_000, searchTimeoutMs: 10_000 } })
  325. expect(ctx.tools.get('web_fetch')?.timeoutMs).toBe(60_000)
  326. expect(ctx.tools.get('web_search')?.timeoutMs).toBe(10_000)
  327. await fiber.dispose()
  328. })
  329. it.each([
  330. ['fetchTimeoutMs', { fetchTimeoutMs: 0 }],
  331. ['searchTimeoutMs', { searchTimeoutMs: -5 }],
  332. ])('rejects a non-positive-integer %s at load', async (key, config) => {
  333. const ctx = new Context()
  334. await ctx.plugin(SystemPrompt)
  335. await ctx.plugin(ToolRegistry)
  336. await ctx.plugin(WebService, {})
  337. await expect(ctx.plugin(ToolWeb, config))
  338. .rejects.toThrow(new RegExp(`tool-web: ${key} must be a positive integer`))
  339. })
  340. })