Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 26 additions & 3 deletions packages/opencode/src/tool/webfetch.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Effect, Schema } from "effect"
import { HttpClient, HttpClientRequest } from "effect/unstable/http"
import { Parser } from "htmlparser2"
import { DomUtils, Parser, parseDocument } from "htmlparser2"
import { NonNegativeInt } from "@opencode-ai/core/schema"
import { ToolFailure } from "@opencode-ai/llm"
import * as Tool from "./tool"
Expand All @@ -18,6 +18,16 @@ const MAX_LINE_SUFFIX = `... (line truncated to ${MAX_LINE_LENGTH} chars)`
const MAX_BYTES = 50 * 1024
const MAX_BYTES_LABEL = `${MAX_BYTES / 1024} KB`

// Boilerplate chrome that never carries the answer. These cover the equivalent
// of `nav, header, footer, aside, [role='navigation'], [role='banner'],
// [role='contentinfo'], [class*='cookie'], [class*='footer']`. htmlparser2's DOM
// has no selector engine of its own (`querySelectorAll` is provided by
// css-select, which is not a dependency), so each selector is matched
// structurally against the parsed tree instead.
const BOILERPLATE_TAGS = ["nav", "header", "footer", "aside"]
const BOILERPLATE_ROLES = ["navigation", "banner", "contentinfo"]
const BOILERPLATE_CLASSES = ["cookie", "footer"]

export const Parameters = Schema.Struct({
url: Schema.String.annotate({ description: "The URL to fetch content from" }),
format: Schema.Literals(["text", "markdown", "html"])
Expand Down Expand Up @@ -151,11 +161,11 @@ export const WebFetchTool = Tool.define<typeof Parameters, Metadata, HttpClient.
const converted = (() => {
switch (params.format) {
case "markdown":
if (contentType.includes("text/html")) return convertHTMLToMarkdown(content)
if (contentType.includes("text/html")) return convertHTMLToMarkdown(stripBoilerplate(content))
return content

case "text":
if (contentType.includes("text/html")) return extractTextFromHTML(content)
if (contentType.includes("text/html")) return extractTextFromHTML(stripBoilerplate(content))
return content

default:
Expand Down Expand Up @@ -249,6 +259,19 @@ function windowContent(content: string, rawOffset: number, rawLimit: number) {
return { ok: true as const, output: `${page.join("\n")}\n\n${notice}`, cut, more, truncated: cut || more }
}

function stripBoilerplate(html: string) {
const doc = parseDocument(html)
const boilerplate = DomUtils.findAll(
(element) =>
BOILERPLATE_TAGS.includes(element.name) ||
BOILERPLATE_ROLES.includes((element.attribs["role"] ?? "").toLowerCase()) ||
BOILERPLATE_CLASSES.some((name) => (element.attribs["class"] ?? "").toLowerCase().includes(name)),
doc.children,
)
for (const element of boilerplate) DomUtils.removeElement(element)
return DomUtils.getOuterHTML(doc.children)
}

function extractTextFromHTML(html: string) {
let text = ""
let skipDepth = 0
Expand Down
5 changes: 5 additions & 0 deletions packages/opencode/src/tool/webfetch.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,8 @@ Usage notes:
- Large results are windowed by line: use "offset" (1-indexed line to start from) and "limit" (maximum lines to return, defaults to 2000) to page through the converted content
- Windowed output ends with a notice showing the returned line range and the next offset to continue from
- When the converted body exceeds the output caps it is saved and the saved path is appended after the notice, so it does not need to be fetched again

HTML pages carry heavy navigation/footer chrome. For structured data, prefer
API endpoints or raw file URLs (raw.githubusercontent.com, api.github.com)
over rendered pages. A 404 from an API endpoint usually means authentication
is required — do not retry variants of the same unauthenticated request.
89 changes: 89 additions & 0 deletions packages/opencode/test/tool/webfetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,95 @@ describe("tool.webfetch", () => {
),
)

it.instance("strips navigation, header, footer and cookie boilerplate before markdown conversion", () =>
withFetch(
() =>
new Response(
[
"<html><body>",
"<nav>docs menu</nav>",
"<header>site header</header>",
"<main><h1>Real content</h1><p>keep this</p></main>",
"<aside>sidebar promo</aside>",
"<div role='navigation'>role menu</div>",
"<div role='banner'>role banner</div>",
"<div role='contentinfo'>role contentinfo</div>",
"<div class='cookie-banner'>accept cookies</div>",
"<div class='page-footer-notes'>footer note</div>",
"<footer>footer links</footer>",
"</body></html>",
].join(""),
{
status: 200,
headers: { "content-type": "text/html; charset=utf-8" },
},
),
(url) =>
Effect.gen(function* () {
const result = yield* exec({ url: new URL("/page.html", url).toString(), format: "markdown" })
expect(result.output).toContain("Real content")
expect(result.output).toContain("keep this")
for (const chrome of [
"docs menu",
"site header",
"sidebar promo",
"role menu",
"role banner",
"role contentinfo",
"accept cookies",
"footer note",
"footer links",
]) {
expect(result.output).not.toContain(chrome)
}
}),
),
)

it.instance("strips boilerplate from text output as well", () =>
withFetch(
() =>
new Response(
"<html><body><nav>docs menu</nav><main>Real content</main><div class='cookie-banner'>accept cookies</div></body></html>",
{
status: 200,
headers: { "content-type": "text/html; charset=utf-8" },
},
),
(url) =>
Effect.gen(function* () {
const result = yield* exec({ url: new URL("/page.html", url).toString(), format: "text" })
expect(result.output).toBe("Real content")
}),
),
)

it.instance("leaves raw html untouched when format is html", () =>
withFetch(
() =>
new Response("<html><body><nav>docs menu</nav><main>Real content</main></body></html>", {
status: 200,
headers: { "content-type": "text/html; charset=utf-8" },
}),
(url) =>
Effect.gen(function* () {
const result = yield* exec({ url: new URL("/page.html", url).toString(), format: "html" })
expect(result.output).toContain("<nav>docs menu</nav>")
expect(result.output).toContain("Real content")
}),
),
)

it.instance("tells the model to prefer API endpoints over rendered pages", () =>
Effect.gen(function* () {
const info = yield* WebFetchTool
const tool = yield* info.init()
expect(tool.description).toContain("HTML pages carry heavy navigation/footer chrome.")
expect(tool.description).toContain("A 404 from an API endpoint usually means authentication")
expect(tool.description).toContain("do not retry variants of the same unauthenticated request")
}),
)

it.instance("returns the full body unchanged when offset and limit are omitted", () =>
withFetch(
() => new Response("alpha\nbeta\ngamma\n", { status: 200, headers: { "content-type": "text/plain" } }),
Expand Down
Loading