Open History to see the last commit
1import { lookup } from 'node:dns/promises'
2import * as http from 'node:http'
3import * as https from 'node:https'
4import { BlockList, isIP } from 'node:net'
5import { toolDefinition } from '@tanstack/ai'
6import { isRecord } from '../../utils'
7import { boundText } from '../bound-output'
8import { optionalString, stringArg } from './backend'
9import type { IncomingMessage } from 'node:http'
10import type { LookupFunction } from 'node:net'
11
12const DEFAULT_TIMEOUT_MS = 30_000
13const MAX_TIMEOUT_MS = 120_000
14/** `webfetch` stops reading a body after this many bytes. */
15const MAX_BYTES = 5 * 1024 * 1024
16/**
17 * The model gets at most this many bytes of a page: its start. The result
18 * stays in the transcript, so each model call after it sends it again.
19 */
20const MAX_RESULT_BYTES = 256 * 1024
21const MAX_REDIRECTS = 5
22/** A NUL byte in this many first bytes marks a binary body. */
23const BINARY_CHECK_BYTES = 8 * 1024
24const DEFAULT_RESULTS = 8
25const MAX_RESULTS = 20
26
27const FORMATS = ['markdown', 'text', 'html'] as const
28type Format = (typeof FORMATS)[number]
29
30const HTML_TYPES = /^(text\/html|application\/xhtml\+xml)$/
31const TEXT_TYPES = /^text\/|[/+](json|xml)$|javascript$/
32
33/** The part of `turndown` that `webfetch` uses. It ships no types. */
34type TurndownClass = new (options: {
35 headingStyle: 'atx'
36 codeBlockStyle: 'fenced'
37}) => {
38 remove: (tags: Array<string>) => unknown
39 turndown: (html: string) => string
40}
41
42const ENTITIES: Record<string, string> = {
43 amp: '&',
44 lt: '<',
45 gt: '>',
46 quot: '"',
47 apos: "'",
48 nbsp: ' ',
49}
50
51/** The addresses that are not on the public internet. */
52const PRIVATE = new BlockList()
53// This network. 0.0.0.0 reaches this machine.
54PRIVATE.addSubnet('0.0.0.0', 8)
55PRIVATE.addSubnet('10.0.0.0', 8)
56// Shared address space. Some clouds keep metadata here.
57PRIVATE.addSubnet('100.64.0.0', 10)
58PRIVATE.addSubnet('127.0.0.0', 8)
59// Link-local, with the cloud metadata address 169.254.169.254.
60PRIVATE.addSubnet('169.254.0.0', 16)
61PRIVATE.addSubnet('172.16.0.0', 12)
62PRIVATE.addSubnet('192.168.0.0', 16)
63// Multicast and reserved.
64PRIVATE.addSubnet('224.0.0.0', 3)
65// `::`, `::1`, and IPv4 in the old `::a.b.c.d` form. The IPv4 rules above
66// also match the `::ffff:a.b.c.d` form.
67PRIVATE.addSubnet('::', 96, 'ipv6')
68PRIVATE.addSubnet('fc00::', 7, 'ipv6')
69PRIVATE.addSubnet('fe80::', 10, 'ipv6')
70PRIVATE.addSubnet('ff00::', 8, 'ipv6')
71
72/** A search engine for the `websearch` tool. */
73export interface SearchProvider {
74 /** At most `options.limit` results for `query`. */
75 search: (
76 query: string,
77 options: { limit: number; signal?: AbortSignal },
78 ) => Promise<Array<{ title: string; url: string; snippet?: string }>>
79}
80
81export interface WebToolsOptions {
82 /**
83 * The `fetch` that `webfetch` uses. Default: a request with `node:http`
84 * and `node:https` that checks the address of each connection. A custom
85 * `fetch` looks up host names itself. Then a DNS server that changes its
86 * answer after the check (DNS rebinding) can reach a private host.
87 */
88 fetch?: typeof fetch
89 /**
90 * Let `webfetch` read localhost and private network hosts. Default:
91 * `false`. Turn it on only when the model may reach your network.
92 */
93 allowPrivateHosts?: boolean
94 /** Adds the `websearch` tool. Without it, there is no `websearch` tool. */
95 search?: SearchProvider
96}
97
98/** The `turndown` class, or `undefined` when that optional peer is missing. */
99async function loadTurndown() {
100 try {
101 // @ts-expect-error -- turndown ships no types. TurndownClass is the part we use.
102 const turndown: { default: TurndownClass } = await import('turndown')
103 return turndown.default
104 } catch {
105 return undefined
106 }
107}
108
109/** Decode `&`, `<`, `'`, `A`, and the other common entities. */
110function decodeEntities(text: string) {
111 return text.replace(
112 /&(#x[\da-f]+|#\d+|[a-z]+);/gi,
113 (entity, name: string) => {
114 if (!name.startsWith('#')) return ENTITIES[name.toLowerCase()] ?? entity
115 const isHex = name[1] === 'x' || name[1] === 'X'
116 const code = Number.parseInt(name.slice(isHex ? 2 : 1), isHex ? 16 : 10)
117 return code <= 0x10ffff ? String.fromCodePoint(code) : entity
118 },
119 )
120}
121
122/** The text of an HTML page: no tags, scripts, or styles. One block a line. */
123function htmlToText(html: string) {
124 const text = html
125 .replace(/<(script|style|noscript|template)\b[\s\S]*?<\/\1\s*>/gi, '')
126 .replace(/<!--[\s\S]*?-->/g, '')
127 .replace(/<\/?(br|p|div|li|tr|h[1-6])\b[^>]*>/gi, '\n')
128 .replace(/<[^>]*>/g, '')
129 return decodeEntities(text)
130 .replace(/[^\S\n]+/g, ' ')
131 .replace(/ *\n\s*/g, '\n')
132 .trim()
133}
134
135/** `html` in the format the model asked for. */
136async function convert(html: string, format: Format | undefined) {
137 const Turndown = await loadTurndown()
138 const wanted = format ?? (Turndown ? 'markdown' : 'text')
139 switch (wanted) {
140 case 'html':
141 return html
142 case 'text':
143 return htmlToText(html)
144 case 'markdown': {
145 if (!Turndown) {
146 throw new Error(
147 'Install turndown to get markdown (npm install turndown), or ask for format "text".',
148 )
149 }
150 const service = new Turndown({
151 headingStyle: 'atx',
152 codeBlockStyle: 'fenced',
153 })
154 service.remove(['script', 'style', 'noscript', 'template'])
155 return service.turndown(html)
156 }
157 }
158}
159
160/** The `format` argument, or `undefined` when the model did not set it. */
161function formatArg(args: unknown) {
162 const value = optionalString(args, 'format')
163 if (value === undefined) return undefined
164 const format = FORMATS.find((item) => item === value)
165 if (format === undefined) {
166 throw new Error('Argument "format" must be markdown, text, or html.')
167 }
168 return format
169}
170
171/** True when `address`, an IP address, is not on the public internet. */
172function isPrivateAddress(address: string) {
173 return PRIVATE.check(address, isIP(address) === 6 ? 'ipv6' : 'ipv4')
174}
175
176/** The error for a host that `webfetch` does not read. */
177function refused(host: string) {
178 return new Error(`webfetch does not read private or local hosts: ${host}`)
179}
180
181/**
182 * Throws unless `url` is http or https. Unless `allowPrivateHosts` is set,
183 * it also throws for a private or local host: the host as written, and
184 * every address that DNS gives for it. The default request checks the
185 * addresses again when it connects.
186 */
187async function checkUrl(url: URL, allowPrivateHosts: boolean) {
188 const isWeb = url.protocol === 'http:' || url.protocol === 'https:'
189 if (!isWeb) {
190 throw new Error(
191 `webfetch reads http and https URLs only, not ${url.protocol}`,
192 )
193 }
194 if (allowPrivateHosts) return
195 // The URL keeps IPv6 hosts in brackets. A name can end with a dot.
196 const host = url.hostname.replace(/^\[|\]$/g, '').replace(/\.$/, '')
197 const isLocalName = host === 'localhost' || host.endsWith('.localhost')
198 if (isLocalName) throw refused(url.hostname)
199 if (isIP(host) !== 0) {
200 if (isPrivateAddress(host)) throw refused(url.hostname)
201 return
202 }
203 const addresses = await lookup(host, { all: true }).catch(() => {
204 throw new Error(`Could not resolve ${host}.`)
205 })
206 const isPrivate = addresses.some(({ address }) => isPrivateAddress(address))
207 if (isPrivate) throw refused(url.hostname)
208}
209
210/**
211 * A `lookup` for Node sockets. It refuses `hostname` when any of its
212 * addresses is private, unless `allowPrivateHosts` is set. The socket
213 * connects only to the addresses that were checked here, so a DNS answer
214 * that changes after `checkUrl` cannot reach a private host.
215 */
216function checkedLookup(allowPrivateHosts: boolean) {
217 const checked: LookupFunction = (hostname, options, callback) => {
218 void lookup(hostname, { ...options, all: true }).then(
219 (addresses) => {
220 const isPrivate =
221 !allowPrivateHosts &&
222 addresses.some(({ address }) => isPrivateAddress(address))
223 const [first] = addresses
224 if (isPrivate) callback(refused(hostname), [])
225 else if (options.all) callback(null, addresses)
226 else if (first) callback(null, first.address, first.family)
227 else callback(new Error(`Could not resolve ${hostname}.`), [])
228 },
229 (error) => callback(error, []),
230 )
231 }
232 return checked
233}
234
235/**
236 * A Node response as a fetch `Response`. Only the headers that `webfetch`
237 * reads are copied. The body is read from the socket on demand.
238 */
239function toResponse(response: IncomingMessage) {
240 const status = response.statusCode ?? 500
241 const headers = new Headers()
242 const { location, 'content-type': type } = response.headers
243 if (location !== undefined) headers.set('location', location)
244 if (type !== undefined) headers.set('content-type', type)
245 const hasNoBody = status === 204 || status === 205 || status === 304
246 if (hasNoBody) {
247 response.resume()
248 return new Response(null, { status, headers })
249 }
250 // The chunks are Buffers, so the stream gives Uint8Array chunks.
251 const chunks = response[Symbol.asyncIterator]()
252 const body = new ReadableStream({
253 pull: async (controller) => {
254 const next = await chunks.next()
255 if (next.done) controller.close()
256 else controller.enqueue(next.value)
257 },
258 cancel: () => {
259 response.destroy()
260 },
261 })
262 return new Response(body, { status, headers })
263}
264
265/**
266 * GET `url` with `node:http` or `node:https`. It never follows redirects.
267 * Each request gets its own connection (`agent: false`), so every
268 * connection goes through `checkedLookup`.
269 */
270async function request(
271 url: URL,
272 options: { signal: AbortSignal; allowPrivateHosts: boolean },
273) {
274 const settings = {
275 agent: false,
276 signal: options.signal,
277 lookup: checkedLookup(options.allowPrivateHosts),
278 }
279 const response = await new Promise<IncomingMessage>((resolve, reject) => {
280 const sent =
281 url.protocol === 'https:'
282 ? https.get(url, settings, resolve)
283 : http.get(url, settings, resolve)
284 sent.on('error', reject)
285 })
286 return toResponse(response)
287}
288
289/**
290 * Fetch `start` with `send` and follow at most 5 redirects. Each URL is
291 * checked before it is sent, so a redirect cannot lead to a private host.
292 */
293async function follow(
294 start: URL,
295 options: {
296 send: (url: URL) => Promise<Response>
297 allowPrivateHosts: boolean
298 },
299) {
300 let url = start
301 for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
302 await checkUrl(url, options.allowPrivateHosts)
303 const response = await options.send(url)
304 const location = response.headers.get('location')
305 const isRedirect =
306 response.status >= 300 && response.status < 400 && location !== null
307 if (!isRedirect) return { response, url }
308 await response.body?.cancel()
309 url = new URL(location, url)
310 }
311 throw new Error(`${start.href} redirected more than ${MAX_REDIRECTS} times.`)
312}
313
314/** The body bytes, at most 5 MB. `isCut` is true when there was more. */
315async function readBody(response: Response) {
316 const reader = response.body?.getReader()
317 const chunks: Array<Uint8Array> = []
318 let size = 0
319 let isCut = false
320 while (reader) {
321 const { done, value } = await reader.read()
322 if (done) break
323 chunks.push(value)
324 size += value.length
325 if (size > MAX_BYTES) {
326 isCut = true
327 await reader.cancel()
328 break
329 }
330 }
331 return { bytes: Buffer.concat(chunks).subarray(0, MAX_BYTES), isCut }
332}
333
334/** The page as the model gets it: HTML converted, text and JSON as they are. */
335async function readPage(
336 response: Response,
337 url: URL,
338 format: Format | undefined,
339) {
340 if (!response.ok) {
341 await response.body?.cancel()
342 throw new Error(`${url.href} answered with HTTP ${response.status}.`)
343 }
344 const header = response.headers.get('content-type') ?? ''
345 const type = (header.split(';', 1)[0] ?? '').trim().toLowerCase()
346 const isHtml = HTML_TYPES.test(type)
347 const binary = `${url.href} is ${type || 'binary'}. webfetch reads HTML, text, and JSON only.`
348 // A missing type is checked on the bytes below.
349 const isKnownBinary = type !== '' && !isHtml && !TEXT_TYPES.test(type)
350 if (isKnownBinary) {
351 await response.body?.cancel()
352 throw new Error(binary)
353 }
354 const { bytes, isCut } = await readBody(response)
355 if (type === '' && bytes.subarray(0, BINARY_CHECK_BYTES).includes(0)) {
356 throw new Error(binary)
357 }
358 // ponytail: reads every page as UTF-8. Decode the charset of the
359 // content type if other charsets matter.
360 const text = new TextDecoder().decode(bytes)
361 const page = isHtml ? await convert(text, format) : text
362 const kept = boundText(page, {
363 maxLines: Number.MAX_SAFE_INTEGER,
364 maxBytes: MAX_RESULT_BYTES,
365 })
366 if (!kept.truncated && !isCut) return page
367 const notRead = isCut ? ' The page is over 5 MB. The rest was not read.' : ''
368 return `${kept.text}\n[webfetch gives at most the first 256 KB of a page.${notRead} To see more, save the page to a file with bash, then use grep or read_file with an offset.]`
369}
370
371/**
372 * The web tools for a coding agent:
373 *
374 * - `webfetch` reads a URL. HTML comes back as Markdown when the optional
375 * `turndown` package is installed, else as text. Text and JSON come back
376 * as they are. Other content types are refused. The model gets the
377 * first 256 KB of the page, with a note when there is more. It reads at
378 * most 5 MB, stops after 30 seconds (the model can ask for up to 120),
379 * and follows at most 5 redirects.
380 * - `websearch` searches with `options.search`. Without a provider, there
381 * is no `websearch` tool.
382 *
383 * `webfetch` fetches URLs that the model picks. So it reads only http and
384 * https, and it refuses localhost, loopback, link-local (with cloud
385 * metadata), and private network hosts, unless `allowPrivateHosts` is set.
386 * Without `options.fetch`, it checks the address of each connection, so a
387 * DNS answer that changes after the check cannot reach a private host.
388 *
389 * @example
390 * ```ts
391 * const tools = webTools({
392 * search: { search: (query, { limit }) => mySearch(query, limit) },
393 * })
394 * ```
395 */
396export function webTools(options: WebToolsOptions = {}) {
397 const { allowPrivateHosts = false, search } = options
398
399 const webfetch = toolDefinition({
400 name: 'webfetch',
401 description:
402 'Read a web page by its http or https URL. HTML comes back as Markdown by default, or set format to text or html. Text and JSON come back as they are. You get at most the first 256 KB of the page.',
403 inputSchema: {
404 type: 'object',
405 properties: {
406 url: { type: 'string' },
407 format: { type: 'string', enum: ['markdown', 'text', 'html'] },
408 timeoutMs: {
409 type: 'number',
410 description: 'Stop after this many milliseconds. At most 120000.',
411 },
412 },
413 required: ['url'],
414 },
415 replay: 'safe',
416 }).server(async (args: unknown, context) => {
417 const url = new URL(stringArg(args, 'url'))
418 const format = formatArg(args)
419 const requested = isRecord(args) ? args.timeoutMs : undefined
420 // A timeout of 0 would stop at once, so it gets the default.
421 const isTimeout = typeof requested === 'number' && requested > 0
422 const timeoutMs = isTimeout
423 ? Math.min(requested, MAX_TIMEOUT_MS)
424 : DEFAULT_TIMEOUT_MS
425 const timeout = AbortSignal.timeout(timeoutMs)
426 const runSignal = context?.abortSignal
427 const signal = runSignal ? AbortSignal.any([timeout, runSignal]) : timeout
428 const customFetch = options.fetch
429 const send = customFetch
430 ? (target: URL) =>
431 customFetch(target.href, { redirect: 'manual', signal })
432 : (target: URL) => request(target, { signal, allowPrivateHosts })
433 try {
434 const fetched = await follow(url, { send, allowPrivateHosts })
435 return await readPage(fetched.response, fetched.url, format)
436 } catch (error) {
437 if (timeout.aborted) {
438 throw new Error(`${url.href} timed out after ${timeoutMs} ms.`)
439 }
440 throw error
441 }
442 })
443
444 if (!search) return [webfetch]
445
446 const websearch = toolDefinition({
447 name: 'websearch',
448 description:
449 'Search the web. You get a numbered list of results: title, URL, and a short snippet. Read a result with webfetch.',
450 inputSchema: {
451 type: 'object',
452 properties: {
453 query: { type: 'string' },
454 limit: {
455 type: 'number',
456 description: `Most results to get. Default ${DEFAULT_RESULTS}, at most ${MAX_RESULTS}.`,
457 },
458 },
459 required: ['query'],
460 },
461 replay: 'safe',
462 }).server(async (args: unknown, context) => {
463 const query = stringArg(args, 'query')
464 const requested = isRecord(args) ? args.limit : undefined
465 const isLimit = typeof requested === 'number' && requested >= 1
466 const limit = isLimit
467 ? Math.min(Math.floor(requested), MAX_RESULTS)
468 : DEFAULT_RESULTS
469 const results = await search.search(query, {
470 limit,
471 signal: context?.abortSignal,
472 })
473 if (results.length === 0) return `No results for "${query}".`
474 return results
475 .slice(0, limit)
476 .map((result, index) => {
477 const lines = [`${index + 1}. ${result.title}`, ` ${result.url}`]
478 if (result.snippet) lines.push(` ${result.snippet}`)
479 return lines.join('\n')
480 })
481 .join('\n\n')
482 })
483
484 return [webfetch, websearch]
485}