Skip to content

WebFetch returns raw XHTML in Markdown and text modes #63888

Duplicate

Description

@Wang-Zephyr

Description

webfetch returns raw XHTML when format is markdown or text. The same page is converted as expected when served as text/html.

OpenCode version

dev at f0089856, Bun 1.4.4

Steps to reproduce

  1. Serve <html xmlns="http://www.w3.org/1999/xhtml"><body><h1>Guide</h1></body></html> with Content-Type: application/xhtml+xml; charset=utf-8.
  2. Call webfetch on that URL with format: "markdown". The result is the original markup instead of # Guide. With format: "text", it should return Guide.

I reproduced the markdown result through the registered tool with a synthetic HTTP response in packages/core/test/tool-webfetch.test.ts.

Operating System

Windows

Activity

  1. added
    area/core
    type/bug
    version/v2
    on Nov 14, 2026
  2. opencodejr commented on Nov 14, 2026

    @opencodejr
    Contributor

    Seen with a simulated model or a mock server, not a real provider; a maintainer should confirm.

    Thanks for the precise report. I reproduced this on opencode v2.2.7, and it also happens on the latest dev (f0089856).

    What I ran: a local server returned the page from your report, once as application/xhtml+xml; charset=utf-8 and once as text/html; charset=utf-8. I let the real built-in webfetch tool fetch it through opencode run. A local mock stood in for the model; its only job was to request the fetch. Results:

    • XHTML, format: "markdown": the raw <html xmlns="http://www.w3.org/1999/xhtml"><body><h1>Guide</h1></body></html>
    • XHTML, format: "text": the same raw markup
    • text/html, markdown: # Guide
    • text/html, text: Guide

    The cause looks like the one you found: convert() in packages/core/src/tool/plugin/webfetch.ts only converts when the header contains text/html. The script below reproduces it.

    Related:

    Reproduction script (repro.sh)
    #!/usr/bin/env bash
    # Reproduces anomalyco/opencode#63888: webfetch returns raw XHTML for format markdown/text.
    # A local Bun server acts as (a) an OpenAI-compatible model that asks for one webfetch call, and
    # (b) a web page served as application/xhtml+xml (/xhtml) or text/html (/html).
    # The real built-in webfetch tool runs; the tool result OpenCode sends back to the model is printed.
    # Usage: bash repro.sh            (uses `opencode` from PATH)
    #   from a source checkout (after `bun install`):
    #        BUN_OPTIONS="--conditions=browser --preload=$REPO/packages/tui/node_modules/@opentui/solid/scripts/preload.js" \
    #        OC="bun $REPO/packages/cli/src/index.ts" bash repro.sh
    set -euo pipefail
    OC="${OC:-opencode}"
    DIR="$(mktemp -d)"; cd "$DIR"; git init -q
    PORT=48731
    cat > server.ts <<'TS'
    const page = `<html xmlns="http://www.w3.org/1999/xhtml"><body><h1>Guide</h1></body></html>`
    const sse = (chunks: any[]) => new Response(chunks.map((c) => `data: ${JSON.stringify(c)}\n\n`).join("") + "data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } })
    const base = { id: "x", object: "chat.completion.chunk", created: 0, model: "m" }
    Bun.serve({
      port: Number(process.env.PORT),
      async fetch(req) {
        const url = new URL(req.url)
        if (url.pathname === "/xhtml") return new Response(page, { headers: { "content-type": "application/xhtml+xml; charset=utf-8" } })
        if (url.pathname === "/html") return new Response(page, { headers: { "content-type": "text/html; charset=utf-8" } })
        if (url.pathname.endsWith("/chat/completions")) {
          const body: any = await req.json()
          const last = body.messages.at(-1)
          if (last.role === "tool") {
            console.log(`TOOL RESULT: ${JSON.stringify(last.content)}`)
            return sse([{ ...base, choices: [{ index: 0, delta: { role: "assistant", content: "done" }, finish_reason: null }] }, { ...base, choices: [{ index: 0, delta: {}, finish_reason: "stop" }] }])
          }
          if (!body.tools) return sse([{ ...base, choices: [{ index: 0, delta: { content: "title" }, finish_reason: "stop" }] }])
          const text = JSON.stringify(body.messages)
          const m = text.match(/FETCH (\w+) (\w+)/)!
          const args = JSON.stringify({ url: `http://127.0.0.1:${process.env.PORT}/${m[1]}`, format: m[2] })
          return sse([
            { ...base, choices: [{ index: 0, delta: { role: "assistant", tool_calls: [{ index: 0, id: "call_1", type: "function", function: { name: "webfetch", arguments: args } }] }, finish_reason: null }] },
            { ...base, choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] },
          ])
        }
        return new Response("not found", { status: 404 })
      },
    })
    TS
    cat > opencode.json <<JSON
    {
      "permission": { "webfetch": "allow" },
      "providers": {
        "mock": {
          "name": "Mock",
          "env": ["MOCK_API_KEY"],
          "package": "@opencode/ai/providers/openai-compatible",
          "settings": { "baseURL": "http://127.0.0.1:$PORT/v1" },
          "models": { "m": { "name": "Mock" } }
        }
      }
    }
    JSON
    PORT=$PORT bun server.ts > server.log 2>&1 &
    SRV=$!; trap 'kill $SRV 2>/dev/null' EXIT; sleep 1
    export MOCK_API_KEY=x
    echo "opencode version: $($OC --version)"
    for c in "xhtml markdown" "xhtml text" "html markdown" "html text"; do
      set -- $c
      : > server.log
      $OC run --auto -m mock/m "FETCH $1 $2" > run.log 2>&1 || { echo "run failed:"; tail -20 run.log; }
      echo "Content-Type=$1 format=$2 -> $(grep -a 'TOOL RESULT' server.log | tr -d '\000' || echo '(no tool result seen)')"
    done

    Run it: bash repro.sh

  3. added
    status/repro-simulated
    on Nov 14, 2026
  4. Guembri01 commented on Nov 25, 2026

    @Guembri01

    Took this. The decision was a single substring test:

    if (!contentType.includes("text/html")) return content

    so application/xhtml+xml fell straight through. It now matches XHTML explicitly through mimeFrom, which also keeps ignoring the charset parameter.

    Test sits next to the existing HTML case in packages/core/test/tool-webfetch.test.ts and drives the real tool with your synthetic response: # Guide for markdown, Guide for text. Fails on dev (raw markup comes back), passes with the change; the file is 92 pass and typecheck-clean.

    Branch webfetch-xhtml. PR creation is refused for this account at the moment (FORBIDDEN on CreatePullRequest, masked as 404), so it waits as a branch with the body written.

  5. Guembri01 commented on Nov 27, 2026

    @Guembri01

    PR opened: #66871. Rebased on current dev after this comment; the test file now has 90 pass, 0 fail (upstream removed one test in the same area).

  6. neriousy commented on Dec 2, 2026

    @neriousy
    Member

    Thanks for the report! This looks like the same bug as #49322, so I'm closing this one to keep the discussion in one place. If yours turns out to be different, leave a comment and we'll reopen it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/coreplatform/windowsstatus/repro-simulatedtype/bugversion/v2

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions