Skip to content

Commit c148f10

Browse files
committed
core: improve webfetch tool content negotiation and format handling
1 parent 06495ea commit c148f10

1 file changed

Lines changed: 27 additions & 8 deletions

File tree

packages/opencode/src/tool/webfetch.ts

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -44,12 +44,29 @@ export const WebFetchTool = Tool.define("webfetch", {
4444
const controller = new AbortController()
4545
const timeoutId = setTimeout(() => controller.abort(), timeout)
4646

47+
// Build Accept header based on requested format with q parameters for fallbacks
48+
let acceptHeader = "*/*"
49+
switch (params.format) {
50+
case "markdown":
51+
acceptHeader = "text/markdown;q=1.0, text/x-markdown;q=0.9, text/plain;q=0.8, text/html;q=0.7, */*;q=0.1"
52+
break
53+
case "text":
54+
acceptHeader = "text/plain;q=1.0, text/markdown;q=0.9, text/html;q=0.8, */*;q=0.1"
55+
break
56+
case "html":
57+
acceptHeader = "text/html;q=1.0, application/xhtml+xml;q=0.9, text/plain;q=0.8, text/markdown;q=0.7, */*;q=0.1"
58+
break
59+
default:
60+
acceptHeader =
61+
"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8"
62+
}
63+
4764
const response = await fetch(params.url, {
4865
signal: AbortSignal.any([controller.signal, ctx.abort]),
4966
headers: {
5067
"User-Agent":
5168
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
52-
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
69+
Accept: acceptHeader,
5370
"Accept-Language": "en-US,en;q=0.9",
5471
},
5572
})
@@ -75,12 +92,14 @@ export const WebFetchTool = Tool.define("webfetch", {
7592
const contentType = response.headers.get("content-type") || ""
7693

7794
const title = `${params.url} (${contentType})`
95+
96+
// Handle content based on requested format and actual content type
7897
switch (params.format) {
79-
case "text":
98+
case "markdown":
8099
if (contentType.includes("text/html")) {
81-
const text = await extractTextFromHTML(content)
100+
const markdown = convertHTMLToMarkdown(content)
82101
return {
83-
output: text,
102+
output: markdown,
84103
title,
85104
metadata: {},
86105
}
@@ -91,17 +110,17 @@ export const WebFetchTool = Tool.define("webfetch", {
91110
metadata: {},
92111
}
93112

94-
case "markdown":
113+
case "text":
95114
if (contentType.includes("text/html")) {
96-
const markdown = convertHTMLToMarkdown(content)
115+
const text = await extractTextFromHTML(content)
97116
return {
98-
output: markdown,
117+
output: text,
99118
title,
100119
metadata: {},
101120
}
102121
}
103122
return {
104-
output: "```\n" + content + "\n```",
123+
output: content,
105124
title,
106125
metadata: {},
107126
}

0 commit comments

Comments
 (0)