Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

coding-web.test.ts

402 lines13.1 KB

1import { createServer } from 'node:http'
2import {
3 afterAll,
4 beforeAll,
5 beforeEach,
6 describe,
7 expect,
8 it,
9 vi,
10} from 'vitest'
11import { webTools } from '../src/first-party/coding/web'
12import type { AddressInfo } from 'node:net'
13import type {
14 SearchProvider,
15 WebToolsOptions,
16} from '../src/first-party/coding/web'
17​
18// DNS is the network boundary. Each lookup of a name takes its next
19// answer, and the last answer repeats.
20const dns = vi.hoisted(() => ({
21 answers: new Map<string, Array<Array<string>>>(),
22}))
23​
24vi.mock('node:dns/promises', () => ({
25 lookup: async (hostname: string) => {
26 const answers = dns.answers.get(hostname) ?? []
27 const addresses = answers.length > 1 ? answers.shift() : answers[0]
28 if (!addresses) throw new Error(`getaddrinfo ENOTFOUND ${hostname}`)
29 return addresses.map((address) => ({
30 address,
31 family: address.includes(':') ? 6 : 4,
32 }))
33 },
34}))
35​
36/** `host` resolves to `answers`, one answer a lookup. */
37function resolves(host: string, ...answers: Array<Array<string>>) {
38 dns.answers.set(host, answers)
40​
41const PUBLIC_IP = '93.184.216.34'
42const MB5 = 5 * 1024 * 1024
43/** The most of a page that the model gets. */
44const KB256 = 256 * 1024
45const REFUSED = 'webfetch does not read private or local hosts'
46​
47type Route = (init: RequestInit | undefined) => Response | Promise<Response>
48​
49/** A route that answers with `body` and the `content-type` `type`. */
50function page(body: BodyInit, type: string) {
51 return () => new Response(body, { headers: { 'content-type': type } })
53​
54/** A route that redirects to `location`. */
55function redirect(location: string) {
56 return () => new Response(null, { status: 302, headers: { location } })
58​
59/** A fetch that answers from `routes`, by URL. `urls` lists each fetch. */
60function fakeFetch(routes: Record<string, Route>) {
61 const urls: Array<string> = []
62 const fetch: typeof globalThis.fetch = async (input, init) => {
63 const url = String(input)
64 urls.push(url)
65 const route = routes[url]
66 if (!route) throw new Error(`No route for ${url}`)
67 return route(init)
68 }
69 return { fetch, urls }
71​
72/** Run the tool `name` from `webTools(options)` once. */
73async function run(name: string, args: object, options: WebToolsOptions = {}) {
74 const tool = webTools(options).find((item) => item.name === name)
75 if (!tool?.execute) throw new Error(`No ${name} tool`)
76 return tool.execute(args)
78​
79/** Fetch `url` with a fetch that knows `routes`. */
80function webfetch(
81 args: { url: string; format?: string; timeoutMs?: number },
82 routes: Record<string, Route>,
83 options: WebToolsOptions = {},
84) {
85 const { fetch } = fakeFetch(routes)
86 return run('webfetch', args, { fetch, ...options })
88​
89beforeEach(() => {
90 dns.answers.clear()
91 resolves('example.com', [PUBLIC_IP])
92})
93​
94describe('webfetch formats', () => {
95 const html =
96 '<html><head><title>Doc</title><style>p { color: red }</style></head><body><h1>Hello</h1><p>Tom &amp; <strong>Jerry</strong> &lt;3 &#x41;&#66;</p><script>alert("x")</script></body></html>'
97 const routes = {
98 'https://example.com/': page(html, 'text/html; charset=utf-8'),
99 }
100​
101 it('gives back HTML as markdown when turndown is installed', async () => {
102 const result = await webfetch({ url: 'https://example.com/' }, routes)
103 expect(result).toBe('Doc\n\n# Hello\n\nTom & **Jerry** <3 AB')
104 })
105​
106 it('gives back text without tags, scripts, or styles', async () => {
107 const result = await webfetch(
108 { url: 'https://example.com/', format: 'text' },
109 routes,
110 )
111 expect(result).toBe('Doc\nHello\nTom & Jerry <3 AB')
112 })
113​
114 it('gives back the HTML as is with format html', async () => {
115 const result = await webfetch(
116 { url: 'https://example.com/', format: 'html' },
117 routes,
118 )
119 expect(result).toBe(html)
120 })
121​
122 it('gives back JSON as it is', async () => {
123 const result = await webfetch(
124 { url: 'https://example.com/data' },
125 { 'https://example.com/data': page('{"ok":true}', 'application/json') },
126 )
127 expect(result).toBe('{"ok":true}')
128 })
129​
130 it('without turndown, refuses markdown and gives text by default', async () => {
131 vi.doMock('turndown', () => {
132 throw new Error('Cannot find package turndown')
133 })
134 try {
135 await expect(
136 webfetch({ url: 'https://example.com/', format: 'markdown' }, routes),
137 ).rejects.toThrow('Install turndown to get markdown')
138 const result = await webfetch({ url: 'https://example.com/' }, routes)
139 expect(result).toBe('Doc\nHello\nTom & Jerry <3 AB')
140 } finally {
141 vi.doUnmock('turndown')
142 }
143 })
144})
145​
146describe('webfetch limits', () => {
147 /** Fetch a text page of `body`. */
148 const fetchText = (body: string) =>
149 webfetch(
150 { url: 'https://example.com/big.txt' },
151 { 'https://example.com/big.txt': page(body, 'text/plain') },
152 )
153 const MORE =
154 'To see more, save the page to a file with bash, then use grep or read_file with an offset.]'
155​
156 it('gives the first 256 KB of a 1 MB page, and says how much was cut', async () => {
157 const result = await fetchText('a'.repeat(1024 * 1024))
158 expect(result).toBe(
159 `${'a'.repeat(KB256)}\n\n[Output cut. Showing the first 1 of 1 lines, 262144 of 1048576 bytes.]\n[webfetch gives at most the first 256 KB of a page. ${MORE}`,
160 )
161 })
162​
163 it('gives a page of 256 KB as it is', async () => {
164 expect(await fetchText('a'.repeat(KB256))).toBe('a'.repeat(KB256))
165 })
166​
167 it('stops reading at 5 MB and says the page was cut', async () => {
168 const result = await fetchText('a'.repeat(MB5 + 100))
169 expect(result).toBe(
170 `${'a'.repeat(KB256)}\n\n[Output cut. Showing the first 1 of 1 lines, 262144 of 5242880 bytes.]\n[webfetch gives at most the first 256 KB of a page. The page is over 5 MB. The rest was not read. ${MORE}`,
171 )
172 })
173​
174 it('stops after the timeout', async () => {
175 const hang: Route = (init) =>
176 new Promise((_, reject) => {
177 init?.signal?.addEventListener('abort', () =>
178 reject(new Error('aborted')),
179 )
180 })
181 await expect(
182 webfetch(
183 { url: 'https://example.com/slow', timeoutMs: 20 },
184 { 'https://example.com/slow': hang },
185 ),
186 ).rejects.toThrow('https://example.com/slow timed out after 20 ms.')
187 })
188​
189 it('refuses binary content', async () => {
190 const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47])
191 await expect(
192 webfetch(
193 { url: 'https://example.com/logo.png' },
194 { 'https://example.com/logo.png': page(png, 'image/png') },
195 ),
196 ).rejects.toThrow(
197 'https://example.com/logo.png is image/png. webfetch reads HTML, text, and JSON only.',
198 )
199 })
200​
201 it('refuses a body with no content type and a NUL byte', async () => {
202 const bytes = new Uint8Array([0x7f, 0x45, 0x4c, 0x46, 0x00, 0x01])
203 await expect(
204 webfetch(
205 { url: 'https://example.com/tool' },
206 { 'https://example.com/tool': () => new Response(bytes) },
207 ),
208 ).rejects.toThrow('https://example.com/tool is binary.')
209 })
210​
211 it('fails on an HTTP error status', async () => {
212 await expect(
213 webfetch(
214 { url: 'https://example.com/missing' },
215 {
216 'https://example.com/missing': () =>
217 new Response('gone', { status: 404 }),
218 },
219 ),
220 ).rejects.toThrow('https://example.com/missing answered with HTTP 404.')
221 })
222})
223​
224describe('webfetch hosts', () => {
225 it.each([
226 'http://localhost:3000/',
227 'http://127.0.0.1/',
228 'http://169.254.169.254/latest/meta-data/',
229 'http://10.0.0.8/',
230 'http://172.16.0.1/',
231 'http://192.168.1.1/',
232 'http://[::1]/',
233 'http://[fd00::1]/',
234 'http://[::ffff:127.0.0.1]/',
235 ])('refuses %s without fetching it', async (url) => {
236 const { fetch, urls } = fakeFetch({})
237 await expect(run('webfetch', { url }, { fetch })).rejects.toThrow(REFUSED)
238 expect(urls).toEqual([])
239 })
240​
241 it('refuses a name when DNS gives a private address', async () => {
242 resolves('intranet.example', [PUBLIC_IP, '10.1.2.3'])
243 const { fetch, urls } = fakeFetch({})
244 await expect(
245 run('webfetch', { url: 'https://intranet.example/' }, { fetch }),
246 ).rejects.toThrow(`${REFUSED}: intranet.example`)
247 expect(urls).toEqual([])
248 })
249​
250 it('refuses a name that DNS cannot resolve', async () => {
251 await expect(
252 webfetch({ url: 'https://nowhere.example/' }, {}),
253 ).rejects.toThrow('Could not resolve nowhere.example.')
254 })
255​
256 it('reads private hosts with allowPrivateHosts', async () => {
257 const result = await webfetch(
258 { url: 'http://localhost:3000/' },
259 { 'http://localhost:3000/': page('local', 'text/plain') },
260 { allowPrivateHosts: true },
261 )
262 expect(result).toBe('local')
263 })
264​
265 it('refuses a URL that is not http or https', async () => {
266 await expect(
267 webfetch({ url: 'file:///etc/passwd' }, {}, { allowPrivateHosts: true }),
268 ).rejects.toThrow('webfetch reads http and https URLs only, not file:')
269 })
270})
271​
272describe('webfetch redirects', () => {
273 it('follows a redirect to a public host', async () => {
274 const { fetch, urls } = fakeFetch({
275 'https://example.com/old': redirect('/new'),
276 'https://example.com/new': page('moved', 'text/plain'),
277 })
278 const result = await run(
279 'webfetch',
280 { url: 'https://example.com/old' },
281 { fetch },
282 )
283 expect(result).toBe('moved')
284 expect(urls).toEqual(['https://example.com/old', 'https://example.com/new'])
285 })
286​
287 it('refuses a redirect to a private host', async () => {
288 const { fetch, urls } = fakeFetch({
289 'https://example.com/go': redirect('http://169.254.169.254/latest/'),
290 })
291 await expect(
292 run('webfetch', { url: 'https://example.com/go' }, { fetch }),
293 ).rejects.toThrow(`${REFUSED}: 169.254.169.254`)
294 expect(urls).toEqual(['https://example.com/go'])
295 })
296​
297 it('stops after 5 redirects', async () => {
298 const { fetch, urls } = fakeFetch({
299 'https://example.com/loop': redirect('/loop'),
300 })
301 await expect(
302 run('webfetch', { url: 'https://example.com/loop' }, { fetch }),
303 ).rejects.toThrow('https://example.com/loop redirected more than 5 times.')
304 expect(urls).toHaveLength(6)
305 })
306})
307​
308describe('webfetch without a custom fetch', () => {
309 // A real server on 127.0.0.1. `paths` lists the requests that reach it.
310 const paths: Array<string> = []
311 const server = createServer((req, res) => {
312 paths.push(req.url ?? '')
313 if (req.url === '/old') {
314 res.writeHead(302, { location: '/new' }).end()
315 return
316 }
317 res.writeHead(200, { 'content-type': 'text/plain' }).end('hello')
318 })
319 let port = 0
320​
321 beforeAll(async () => {
322 await new Promise<void>((done) => server.listen(0, '127.0.0.1', done))
323 const address: AddressInfo | string | null = server.address()
324 port = typeof address === 'object' && address ? address.port : 0
325 })
326​
327 afterAll(async () => {
328 await new Promise<void>((done) => server.close(() => done()))
329 })
330​
331 beforeEach(() => {
332 paths.length = 0
333 })
334​
335 it('refuses a name whose answer turns private when it connects', async () => {
336 // The check sees a public address. The connection sees 127.0.0.1.
337 resolves('rebind.test', [PUBLIC_IP], ['127.0.0.1'])
338 await expect(
339 run('webfetch', { url: `http://rebind.test:${port}/` }),
340 ).rejects.toThrow(`${REFUSED}: rebind.test`)
341 expect(paths).toEqual([])
342 })
343​
344 it('reaches a private host with allowPrivateHosts and follows redirects', async () => {
345 resolves('rebind.test', ['127.0.0.1'])
346 const result = await run(
347 'webfetch',
348 { url: `http://rebind.test:${port}/old` },
349 { allowPrivateHosts: true },
350 )
351 expect(result).toBe('hello')
352 expect(paths).toEqual(['/old', '/new'])
353 })
354})
355​
356describe('websearch', () => {
357 /** A provider that gives back `results` and records each search. */
358 function provider(results: Awaited<ReturnType<SearchProvider['search']>>) {
359 const searches: Array<{ query: string; limit: number }> = []
360 const search: SearchProvider = {
361 search: async (query, { limit }) => {
362 searches.push({ query, limit })
363 return results
364 },
365 }
366 return { search, searches }
367 }
368​
369 it('gives back the results as a numbered list', async () => {
370 const { search, searches } = provider([
371 {
372 title: 'TanStack AI',
373 url: 'https://tanstack.com/ai',
374 snippet: 'Type-safe AI SDK',
375 },
376 { title: 'TanStack Query', url: 'https://tanstack.com/query' },
377 ])
378 const result = await run(
379 'websearch',
380 { query: 'tanstack', limit: 2 },
381 { search },
382 )
383 expect(result).toBe(
384 '1. TanStack AI\n https://tanstack.com/ai\n Type-safe AI SDK\n\n2. TanStack Query\n https://tanstack.com/query',
385 )
386 expect(searches).toEqual([{ query: 'tanstack', limit: 2 }])
387 })
388​
389 it('says when there are no results', async () => {
390 const { search } = provider([])
391 const result = await run('websearch', { query: 'nothing' }, { search })
392 expect(result).toBe('No results for "nothing".')
393 })
394​
395 it('exists only with a provider', () => {
396 const { search } = provider([])
397 const names = (options: WebToolsOptions) =>
398 webTools(options).map((tool) => tool.name)
399 expect(names({})).toEqual(['webfetch'])
400 expect(names({ search })).toEqual(['webfetch', 'websearch'])
401 })
402})