tool-web.spec.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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 } 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 = true
  21. function searchProvider(result: WebSearchResult, isAvailable = available): WebSearchProvider {
  22. return { id: 'stub-search', available: () => isAvailable, 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. 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({ sources: [], truncated: false }))
  58. .toContain('No results found.')
  59. })
  60. it('renders content alone when there are no sources', () => {
  61. const out = formatSearchOutput({ 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({ 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. 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. 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({ 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. expect(ctx.tools.executionMode({ callId: CallId('search-safe'), name: 'web_search', arguments: { query: 'q' } }))
  149. .toEqual({ kind: 'parallel' })
  150. expect(ctx.tools.executionMode({ callId: CallId('fetch-safe'), name: 'web_fetch', arguments: { url: 'https://a.test' } }))
  151. .toEqual({ kind: 'parallel' })
  152. await fiber.dispose()
  153. expect(ctx.tools.schemas().map(s => s.name)).not.toContain('web_search')
  154. })
  155. it('registers only enabled tools', async () => {
  156. const { fiber, ctx } = await mountTools({ config: { search: true, fetch: false } })
  157. const names = ctx.tools.schemas().map(s => s.name)
  158. expect(names).toContain('web_search')
  159. expect(names).not.toContain('web_fetch')
  160. await fiber.dispose()
  161. })
  162. it('registers only web_fetch when search is disabled', async () => {
  163. const { fiber, ctx } = await mountTools({ config: { search: false, fetch: true } })
  164. const names = ctx.tools.schemas().map(s => s.name)
  165. expect(names).not.toContain('web_search')
  166. expect(names).toContain('web_fetch')
  167. await fiber.dispose()
  168. })
  169. it('registers web_search even when no provider is available (schema follows enablement, not availability)', async () => {
  170. const { fiber, ctx, call } = await mountTools()
  171. expect(ctx.tools.schemas().map(s => s.name)).toContain('web_search')
  172. // No provider is registered: the schema stays visible and execution reports
  173. // the structured unavailability instead.
  174. const out = await call('web_search', { query: 'q' })
  175. expect(out.error?.code).toBe('WEB_PROVIDER_UNAVAILABLE')
  176. await fiber.dispose()
  177. })
  178. it('contributes prompt sections for the enabled tools', async () => {
  179. const { fiber, ctx } = await mountTools()
  180. const prompt = await ctx.systemPrompt.assemble()
  181. const text = prompt.sections.map(s => s.text).join('\n')
  182. expect(text).toContain('web_search')
  183. expect(text).toContain('web_fetch')
  184. await fiber.dispose()
  185. })
  186. })
  187. describe('tool-web execution through the real registry', () => {
  188. it('executes web_search and formats the result', async () => {
  189. const result: WebSearchResult = {
  190. content: 'answer', truncated: false,
  191. sources: [{ url: 'https://a.test', title: 'A', snippet: 'snip' }],
  192. }
  193. const { fiber, call } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: searchProvider(result) })
  194. const out = await call('web_search', { query: 'q' })
  195. expect(out.isError).toBe(false)
  196. expect(out.content.map(b => b.text).join('')).toContain('[A](https://a.test)')
  197. await fiber.dispose()
  198. })
  199. it('surfaces a structured WebError when no provider is available', async () => {
  200. const { fiber, call } = await mountTools()
  201. const out = await call('web_search', { query: 'q' })
  202. expect(out.isError).toBe(true)
  203. expect(out.error?.code).toBe('WEB_PROVIDER_UNAVAILABLE')
  204. await fiber.dispose()
  205. })
  206. it('surfaces WEB_PROVIDER_AMBIGUOUS for multiple unconfigured providers', async () => {
  207. const { ctx, fiber, call } = await mountTools({ search: searchProvider({ sources: [], truncated: false }) })
  208. ctx.web.registerSearchProvider({ id: 'other', available: () => available, search: () => Promise.resolve({ sources: [], truncated: false }) })
  209. const out = await call('web_search', { query: 'q' })
  210. expect(out.isError).toBe(true)
  211. expect(out.error?.code).toBe('WEB_PROVIDER_AMBIGUOUS')
  212. await fiber.dispose()
  213. })
  214. it('rejects invalid arguments with a structured INVALID_ARGS error', async () => {
  215. const { fiber, call } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: searchProvider({ sources: [], truncated: false }) })
  216. const out = await call('web_search', { query: 123 })
  217. expect(out.isError).toBe(true)
  218. expect(out.error?.code).toBe('INVALID_ARGS')
  219. await fiber.dispose()
  220. })
  221. it('has no default export (namespace plugin export shape)', () => {
  222. expect('default' in ToolWeb).toBe(false)
  223. })
  224. it('executes web_fetch, forwarding the url (no timeout param) and the abort signal to the seam', async () => {
  225. const seen: { request?: { url: string }; signal?: AbortSignal | undefined } = {}
  226. const fetchProvider = {
  227. id: 'stub-fetch',
  228. available: () => available,
  229. fetch: (request: { url: string }, signal?: AbortSignal) => {
  230. seen.request = request
  231. seen.signal = signal
  232. return Promise.resolve({ url: request.url, statusCode: 200, body: { kind: 'text' as const, content: 'ok' }, truncated: false })
  233. },
  234. }
  235. const { ctx, fiber } = await mountTools({ webConfig: { fetchProvider: 'stub-fetch' }, fetchProvider })
  236. const controller = new AbortController()
  237. const out = await ctx.tools.execute({ callId: CallId('fetch-1'), name: 'web_fetch', arguments: { url: 'https://a.test' }, signal: controller.signal })
  238. expect(out.isError).toBe(false)
  239. // The model schema exposes no timeout: the tool forwards only the url; the
  240. // tool-call budget is owned by dsh-timeout-policy over exec.signal.
  241. expect(seen.request).toEqual({ url: 'https://a.test' })
  242. expect(seen.signal).toBe(controller.signal)
  243. await fiber.dispose()
  244. })
  245. it('executes web_fetch with no caller signal (forwards undefined to the seam)', async () => {
  246. const seen: { signal?: AbortSignal | undefined; passedSignal?: boolean } = {}
  247. const fetchProvider = {
  248. id: 'stub-fetch',
  249. available: () => available,
  250. fetch: (request: { url: string }, signal?: AbortSignal) => {
  251. seen.passedSignal = signal !== undefined
  252. seen.signal = signal
  253. return Promise.resolve({ url: request.url, statusCode: 200, body: { kind: 'text' as const, content: 'ok' }, truncated: false })
  254. },
  255. }
  256. const { ctx, fiber } = await mountTools({ webConfig: { fetchProvider: 'stub-fetch' }, fetchProvider })
  257. // No signal on the execution: the tool passes `undefined`.
  258. const out = await ctx.tools.execute({ callId: CallId('fetch-2'), name: 'web_fetch', arguments: { url: 'https://a.test' } })
  259. expect(out.isError).toBe(false)
  260. expect(seen.passedSignal).toBe(false)
  261. expect(seen.signal).toBeUndefined()
  262. await fiber.dispose()
  263. })
  264. it('executes web_search, forwarding the abort signal to the seam', async () => {
  265. const seen: { signal?: AbortSignal | undefined } = {}
  266. const provider: WebSearchProvider = {
  267. id: 'stub-search',
  268. available: () => available,
  269. search: (_request, signal) => { seen.signal = signal; return Promise.resolve({ sources: [], truncated: false }) },
  270. }
  271. const { ctx, fiber } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: provider })
  272. const controller = new AbortController()
  273. await ctx.tools.execute({ callId: CallId('search-1'), name: 'web_search', arguments: { query: 'q' }, signal: controller.signal })
  274. expect(seen.signal).toBe(controller.signal)
  275. await fiber.dispose()
  276. })
  277. })
  278. describe('searchMaxResults is plugin config', () => {
  279. it('forwards the default cap to the seam when unconfigured', async () => {
  280. const seen: { maxResults?: number | undefined } = {}
  281. const provider: WebSearchProvider = {
  282. id: 'stub-search',
  283. available: () => available,
  284. search: (request) => { seen.maxResults = request.maxResults; return Promise.resolve({ sources: [], truncated: false }) },
  285. }
  286. const { fiber, call } = await mountTools({ webConfig: { searchProvider: 'stub-search' }, search: provider })
  287. await call('web_search', { query: 'q' })
  288. expect(seen.maxResults).toBe(WEB_SEARCH_MAX_RESULTS)
  289. await fiber.dispose()
  290. })
  291. it('forwards a configured cap to the seam, which enforces it', async () => {
  292. const sources = Array.from({ length: 5 }, (_, i) => ({ url: `https://s${i}.test` }))
  293. const provider: WebSearchProvider = {
  294. id: 'stub-search',
  295. available: () => available,
  296. search: () => Promise.resolve({ sources, truncated: false }),
  297. }
  298. const { fiber, call } = await mountTools({ config: { searchMaxResults: 2 }, webConfig: { searchProvider: 'stub-search' }, search: provider })
  299. const out = await call('web_search', { query: 'q' })
  300. expect(out.isError).toBe(false)
  301. const body = out.content.map(b => b.text).join('')
  302. expect(body).toContain('https://s1.test')
  303. expect(body).not.toContain('https://s2.test')
  304. expect(body).toContain('Showing the first 2 sources.')
  305. await fiber.dispose()
  306. })
  307. it.each([
  308. ['zero', 0],
  309. ['negative', -3],
  310. ['fractional', 1.5],
  311. ])('rejects a %s searchMaxResults at load', async (_label, value) => {
  312. const ctx = new Context()
  313. await ctx.plugin(SystemPrompt)
  314. await ctx.plugin(ToolRegistry)
  315. await ctx.plugin(WebService, {})
  316. await expect(ctx.plugin(ToolWeb, { searchMaxResults: value }))
  317. .rejects.toThrow(/tool-web: searchMaxResults must be a positive integer/)
  318. })
  319. })
  320. describe('tool-call timeout budget is plugin config', () => {
  321. it('attaches the default 30s budget to web_fetch and web_search', async () => {
  322. const { fiber, ctx } = await mountTools()
  323. expect(ctx.tools.get('web_fetch')?.timeoutMs).toBe(30_000)
  324. expect(ctx.tools.get('web_search')?.timeoutMs).toBe(30_000)
  325. await fiber.dispose()
  326. })
  327. it('honors per-tool timeout overrides from config', async () => {
  328. const { fiber, ctx } = await mountTools({ config: { fetchTimeoutMs: 60_000, searchTimeoutMs: 10_000 } })
  329. expect(ctx.tools.get('web_fetch')?.timeoutMs).toBe(60_000)
  330. expect(ctx.tools.get('web_search')?.timeoutMs).toBe(10_000)
  331. await fiber.dispose()
  332. })
  333. it.each([
  334. ['fetchTimeoutMs', { fetchTimeoutMs: 0 }],
  335. ['searchTimeoutMs', { searchTimeoutMs: -5 }],
  336. ])('rejects a non-positive-integer %s at load', async (key, config) => {
  337. const ctx = new Context()
  338. await ctx.plugin(SystemPrompt)
  339. await ctx.plugin(ToolRegistry)
  340. await ctx.plugin(WebService, {})
  341. await expect(ctx.plugin(ToolWeb, config))
  342. .rejects.toThrow(new RegExp(`tool-web: ${key} must be a positive integer`))
  343. })
  344. })