From 09baf5de793df67186cb21ba9a8d0ef180cfbd99 Mon Sep 17 00:00:00 2001 From: "Stanislav (Stas) Katkov" Date: Mon, 30 Nov 2026 13:57:21 +0100 Subject: [PATCH 1/2] Add opt-in Lightpanda backend for WebFetch --- README.md | 16 ++++++++++ bun.lock | 52 ++++++++---------------------- lightpanda.test.ts | 69 ++++++++++++++++++++++++++++++++++++++++ lightpanda.ts | 53 ++++++++++++++++++++++++++++++ package.json | 2 +- test/fixtures/lightpanda | 2 +- 6 files changed, 153 insertions(+), 41 deletions(-) diff --git a/README.md b/README.md index 1cdda64..25f6302 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,22 @@ lightpanda({ Available formats are `markdown`, `json`, and `semantic_tree`. +### Experimental WebFetch backend + +On OpenCode V2.4.3 or later, opt in through the plugin options: + +```jsonc +{ + "plugins": [ + { "package": "opencode-lightpanda", "options": { "webfetch": true } } + ] +} +``` + +In this mode, `webfetch` tries Lightpanda first for Markdown page requests. It uses native WebFetch for `text` and `html`, and falls back to native WebFetch if the browser fails or returns a non-page content type. The browser attempt has a three-second rendering cap and shares the request's timeout budget. + +OpenCode checks the requested URL against `webfetch` permissions, then checks the separate `lightpanda` permission for browser access. The browser can follow public redirects and load public subresources under that permission; those requests are not checked against the native WebFetch URL rules. Leave this option off if your WebFetch rules must apply to every redirect. The standalone `lightpanda` tool remains available either way. + ## Local Development ```sh diff --git a/bun.lock b/bun.lock index 8b13a72..9298a04 100644 --- a/bun.lock +++ b/bun.lock @@ -5,7 +5,7 @@ "": { "name": "opencode-lightpanda", "dependencies": { - "@opencode/plugin": "^2.0.18", + "@opencode/plugin": "^2.4.3", "zod": "^4.1.8", }, "devDependencies": { @@ -66,11 +66,11 @@ "@aws/lambda-invoke-store": ["@aws/lambda-invoke-store@0.3.0", "", {}, "sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ=="], - "@effect/opentelemetry": ["@effect/opentelemetry@4.0.0-rc.112", "", { "peerDependencies": { "@opentelemetry/api": ">=1.9.0 <2.0.0", "@opentelemetry/api-logs": ">=0.203.0 <0.300.0", "@opentelemetry/resources": ">=2.0.0 <3.0.0", "@opentelemetry/sdk-logs": ">=0.203.0 <0.300.0", "@opentelemetry/sdk-metrics": ">=2.0.0 <3.0.0", "@opentelemetry/sdk-trace-base": ">=2.0.0 <3.0.0", "@opentelemetry/sdk-trace-node": ">=2.0.0 <3.0.0", "@opentelemetry/sdk-trace-web": ">=2.0.0 <3.0.0", "@opentelemetry/semantic-conventions": ">=1.33.0 <2.0.0", "effect": "^4.0.0-rc.112" }, "optionalPeers": ["@opentelemetry/api", "@opentelemetry/api-logs", "@opentelemetry/resources", "@opentelemetry/sdk-logs", "@opentelemetry/sdk-metrics", "@opentelemetry/sdk-trace-base", "@opentelemetry/sdk-trace-node", "@opentelemetry/sdk-trace-web"] }, "sha512-OTRv1DxTHUmnakgJ6XVM8wVgF1KgZH4UXnOemwSLUwUjXO+RCikzF8oR/rlVmOGq81KtQzj1URM4M4nchlQOuQ=="], + "@effect/opentelemetry": ["@effect/opentelemetry@4.1.0", "", { "peerDependencies": { "@opentelemetry/api": ">=1.9.0 <2.0.0", "@opentelemetry/api-logs": ">=0.203.0 <0.300.0", "@opentelemetry/resources": ">=2.0.0 <3.0.0", "@opentelemetry/sdk-logs": ">=0.203.0 <0.300.0", "@opentelemetry/sdk-metrics": ">=2.0.0 <3.0.0", "@opentelemetry/sdk-trace-base": ">=2.0.0 <3.0.0", "@opentelemetry/sdk-trace-node": ">=2.0.0 <3.0.0", "@opentelemetry/sdk-trace-web": ">=2.0.0 <3.0.0", "@opentelemetry/semantic-conventions": ">=1.33.0 <2.0.0", "effect": "^4.1.0" }, "optionalPeers": ["@opentelemetry/api", "@opentelemetry/api-logs", "@opentelemetry/resources", "@opentelemetry/sdk-logs", "@opentelemetry/sdk-metrics", "@opentelemetry/sdk-trace-base", "@opentelemetry/sdk-trace-node", "@opentelemetry/sdk-trace-web"] }, "sha512-j9bNzQaoQvcnimBFMG0i3piEW20E8HjkXAQHTJN/XqG2e4uJ9zCv53/HCNzD7+ooFn5S4nwQy/BOXeNReMIe+A=="], - "@effect/platform-node": ["@effect/platform-node@4.0.0-rc.112", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-rc.112", "mime": "^4.1.0", "undici": "^8.10.0" }, "peerDependencies": { "effect": "^4.0.0-rc.112", "redis": ">=5.0.0 <7.0.0" } }, "sha512-/BMAcdNGQQskLmI0Zoa95KfTZkr9HV9N4NSxaSrusG6GeW6Ulp9KvZ+Rlaiw8lnOt43CXjFLdfll5/k5rxL4hQ=="], + "@effect/platform-node": ["@effect/platform-node@4.1.0", "", { "dependencies": { "@effect/platform-node-shared": "^4.1.0", "undici": "^8.12.2" }, "peerDependencies": { "effect": "^4.1.0", "redis": ">=5.0.0 <7.0.0" } }, "sha512-v+X7moGVF9k5oMVvz0slA+NgtEod+W+oygeI285MDJgSlUCW3JcqElj+cD3rlijFZtpKhC7RLkU1GuCxjGHTpA=="], - "@effect/platform-node-shared": ["@effect/platform-node-shared@4.0.0-rc.112", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.21.3" }, "peerDependencies": { "effect": "^4.0.0-rc.112" } }, "sha512-ttjz0xKamFN7vL8pNDYVwddJLjZvqKePc05djlz2VcdaKbLsnYbtMnL1rbOfHgEnIUSHGh7FkjaN4DM1Ov81sQ=="], + "@effect/platform-node-shared": ["@effect/platform-node-shared@4.1.0", "", { "dependencies": { "@types/ws": "^8.18.2", "ws": "^8.22.0" }, "peerDependencies": { "effect": "^4.1.0" } }, "sha512-uYQfFRoxWLo8fIhiSeBcmz/R1ooOfE3HF3cWHFgxz82tZMk2Wn02BGABcdLmaAch9VpDLbtWnuhSxNyBsGMUFg=="], "@gar/promise-retry": ["@gar/promise-retry@1.0.3", "", {}, "sha512-GmzA9ckNokPypTg10pgpeHNQe7ph+iIKKmhKu3Ob9ANkswreCx7R3cKmY781K8QK3AqVL3xVh9A42JvIAbkkSA=="], @@ -80,18 +80,6 @@ "@isaacs/string-locale-compare": ["@isaacs/string-locale-compare@1.1.0", "", {}, "sha512-SQ7Kzhh9+D+ZW9MA0zkYv3VXhIDNx+LzM6EJ+/65I3QY+enU6Itte7E5XX7EWrqLW2FN4n06GWzBnPoC3th2aQ=="], - "@msgpackr-extract/msgpackr-extract-darwin-arm64": ["@msgpackr-extract/msgpackr-extract-darwin-arm64@3.0.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-LCkGo6JDfaBhgST7UpPWgNgLINpcpabaHfyz5OBx75nUYxBsaEPxjnyNjWpeb/xBup/682QnBfRBy2/LvPutZQ=="], - - "@msgpackr-extract/msgpackr-extract-darwin-x64": ["@msgpackr-extract/msgpackr-extract-darwin-x64@3.0.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-zExlW9zUJKZH/tOtVMttwjKa4Xm/3KcNjnE3dPN92uCktwavMxpgCA3MoJK/DOnTWsQgo224OaST27/mPNAf+w=="], - - "@msgpackr-extract/msgpackr-extract-linux-arm": ["@msgpackr-extract/msgpackr-extract-linux-arm@3.0.4", "", { "os": "linux", "cpu": "arm" }, "sha512-Tg3yX65f5GbtXLkrYEHE5oibZG9epyYWas7FogTTEJeDEF9JlXJzKgXaNhT3UXlTOeA+AfZpYZYZ0uPj7Cfquw=="], - - "@msgpackr-extract/msgpackr-extract-linux-arm64": ["@msgpackr-extract/msgpackr-extract-linux-arm64@3.0.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-dgX0P/9wGPJeHFBG+ZmhgE6bmtMt7NP5CRBGyyktpopdk/mW4POnrpQsSLtKI1dwpc+pPLuXHDh6vvskyQE/sw=="], - - "@msgpackr-extract/msgpackr-extract-linux-x64": ["@msgpackr-extract/msgpackr-extract-linux-x64@3.0.4", "", { "os": "linux", "cpu": "x64" }, "sha512-8TNXMEjJc3QEy7R/x1INhgiU+XakDAFUzBhaz7+Rbrs8NH5UQeHQxxmzsSBJGyV6I1jW79undiQm8tOI+D+8FQ=="], - - "@msgpackr-extract/msgpackr-extract-win32-x64": ["@msgpackr-extract/msgpackr-extract-win32-x64@3.0.4", "", { "os": "win32", "cpu": "x64" }, "sha512-CmCXPQrkbwExx3j946/PtHWHbYJiCRBRDl4BlkRQcJB/YOwQxJRTpoo7aTsortjgoJ1x7opzTSxn7C+ASSLVjQ=="], - "@npmcli/agent": ["@npmcli/agent@4.0.2", "", { "dependencies": { "agent-base": "^7.1.0", "http-proxy-agent": "^7.0.0", "https-proxy-agent": "^7.0.1", "lru-cache": "^11.2.1", "socks-proxy-agent": "^8.0.3" } }, "sha512-EUEuWAxnL07Sp5/iC/1X6Xj+XThUvnbei9zfRWZdEXa7lss9RTHMhAHBeg+MZ5To9s/gGaSI+UwZTPdYMvKSeg=="], "@npmcli/arborist": ["@npmcli/arborist@9.4.0", "", { "dependencies": { "@isaacs/string-locale-compare": "^1.1.0", "@npmcli/fs": "^5.0.0", "@npmcli/installed-package-contents": "^4.0.0", "@npmcli/map-workspaces": "^5.0.0", "@npmcli/metavuln-calculator": "^9.0.2", "@npmcli/name-from-folder": "^4.0.0", "@npmcli/node-gyp": "^5.0.0", "@npmcli/package-json": "^7.0.0", "@npmcli/query": "^5.0.0", "@npmcli/redact": "^4.0.0", "@npmcli/run-script": "^10.0.0", "bin-links": "^6.0.0", "cacache": "^20.0.1", "common-ancestor-path": "^2.0.0", "hosted-git-info": "^9.0.0", "json-stringify-nice": "^1.1.4", "lru-cache": "^11.2.1", "minimatch": "^10.0.3", "nopt": "^9.0.0", "npm-install-checks": "^8.0.0", "npm-package-arg": "^13.0.0", "npm-pick-manifest": "^11.0.1", "npm-registry-fetch": "^19.0.0", "pacote": "^21.0.2", "parse-conflict-json": "^5.0.1", "proc-log": "^6.0.0", "proggy": "^4.0.0", "promise-all-reject-late": "^1.0.0", "promise-call-limit": "^3.0.1", "semver": "^7.3.7", "ssri": "^13.0.0", "treeverse": "^3.0.0", "walk-up-path": "^4.0.0" }, "bin": { "arborist": "bin/index.js" } }, "sha512-4Bm8hNixJG/sii1PMnag0V9i/sGOX9VRzFrUiZMSBJpGlLR38f+Btl85d07G9GL56xO0l0OZjvrGNYsDYp0xKA=="], @@ -122,17 +110,17 @@ "@npmcli/run-script": ["@npmcli/run-script@10.0.4", "", { "dependencies": { "@npmcli/node-gyp": "^5.0.0", "@npmcli/package-json": "^7.0.0", "@npmcli/promise-spawn": "^9.0.0", "node-gyp": "^12.1.0", "proc-log": "^6.0.0" } }, "sha512-mGUWr1uMnf0le2TwfOZY4SFxZGXGfm4Jtay/nwAa2FLNAKXUoUwaGwBMNH36UHPtinWfTSJ3nqFQr0091CxVGg=="], - "@opencode/ai": ["@opencode/ai@2.0.18", "", { "dependencies": { "@aws-sdk/credential-providers": "3.1057.0", "@opencode/schema": "2.0.18", "@smithy/eventstream-codec": "4.2.14", "@smithy/util-utf8": "4.2.2", "aws4fetch": "1.0.20", "effect": "4.0.0-rc.112", "google-auth-library": "10.5.0" } }, "sha512-zzd01WCh4rdvA29DwUVhG3n8rnn4y8jAobBE34ot5ueRmljO8AZ61/fq0+89tcm2OtEkGoMiAoBALJqd2LaWtQ=="], + "@opencode/ai": ["@opencode/ai@2.4.3", "", { "dependencies": { "@aws-sdk/credential-providers": "3.1057.0", "@opencode/schema": "2.4.3", "@smithy/eventstream-codec": "4.2.14", "@smithy/util-utf8": "4.2.2", "aws4fetch": "1.0.20", "effect": "4.1.0", "google-auth-library": "10.5.0" } }, "sha512-HFN2RzEK/fmTVLEkqMdBMgjeqKE8V1CdBdPciqFtQSS+x0TA/Z608NpYq3UEGEiTxyzkEmp2Ts77XuUWzCmYdA=="], - "@opencode/client": ["@opencode/client@2.0.18", "", { "dependencies": { "@opencode/protocol": "2.0.18", "@opencode/schema": "2.0.18" }, "peerDependencies": { "effect": "4.0.0-rc.112", "solid-js": ">=1.9.0" }, "optionalPeers": ["effect", "solid-js"] }, "sha512-N74FNdXkTTC1Re5T+PNxH6fsVf1tZiV3kESu3UWL/545oAkBRXoiikMmDszuuHZ4AxGwtr9NiQjKrHiMdnLVYQ=="], + "@opencode/client": ["@opencode/client@2.4.3", "", { "dependencies": { "@opencode/protocol": "2.4.3", "@opencode/schema": "2.4.3" }, "peerDependencies": { "effect": "4.1.0", "solid-js": ">=1.9.0" }, "optionalPeers": ["effect", "solid-js"] }, "sha512-R3hec2CO9EyRbOZM4xvbCetp2lmbCb7+I3AgmjSqOeKBF7xj7pRL3lTamEHwiyMGdk2vFzzily3SgsOVk8sghg=="], - "@opencode/plugin": ["@opencode/plugin@2.0.18", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@opencode/ai": "2.0.18", "@opencode/client": "2.0.18", "@opencode/protocol": "2.0.18", "@opencode/schema": "2.0.18", "@opencode/util": "2.0.18", "@standard-schema/spec": "1.1.0", "effect": "4.0.0-rc.112", "zod": "4.1.8" }, "peerDependencies": { "@opencode/theme": "2.0.18", "@opentui/core": ">=0.5.12", "@opentui/solid": ">=0.5.12", "solid-js": ">=1.9.0" }, "optionalPeers": ["@opencode/theme", "@opentui/core", "@opentui/solid", "solid-js"] }, "sha512-jokYYdAGd/L+WY0GbEE1Bh1/F8tG98UaTlvvyBriOuVDyeadHFdTL9QoXx+u7pAWwJRTEMOESxxifS/blGPjyg=="], + "@opencode/plugin": ["@opencode/plugin@2.4.3", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@opencode/ai": "2.4.3", "@opencode/client": "2.4.3", "@opencode/protocol": "2.4.3", "@opencode/schema": "2.4.3", "@opencode/util": "2.4.3", "effect": "4.1.0" }, "peerDependencies": { "@opencode/theme": "2.4.3", "@opentui/core": ">=0.8.0", "@opentui/solid": ">=0.8.0", "electron": "*", "solid-js": ">=1.9.0", "vite": ">=6", "vite-plugin-solid": ">=2.11" }, "optionalPeers": ["@opencode/theme", "@opentui/core", "@opentui/solid", "electron", "solid-js", "vite", "vite-plugin-solid"] }, "sha512-d8NrtkvIb1HYB+UyM5D9KjKxfD8DivkquCCx5e/wVsihDl1FefGiI6N9xvwQdJiqza5l8W59iCSq0k4Aq3bPzQ=="], - "@opencode/protocol": ["@opencode/protocol@2.0.18", "", { "dependencies": { "@opencode/schema": "2.0.18", "effect": "4.0.0-rc.112" } }, "sha512-IhzzlCz/hAlFvBLWQ+kDceX0/CkYOrjVyTPwYJYvWwKze5AHzVxxDYxkhCqLJj0hn/wtdNL10nhjVothuHcaBQ=="], + "@opencode/protocol": ["@opencode/protocol@2.4.3", "", { "dependencies": { "@opencode/schema": "2.4.3", "effect": "4.1.0" } }, "sha512-SBWqrDzC2su/ZdkpbAMokME9vy58RcEVqe98bra0F8q+OaGGmzBGpFMvldFmW+76fiV2n7vsRYQA4gqlb+JeQg=="], - "@opencode/schema": ["@opencode/schema@2.0.18", "", { "dependencies": { "@standard-schema/spec": "1.1.0", "effect": "4.0.0-rc.112" } }, "sha512-f+lp6f+kxhygdeSxjqkiu6vk9t0onH/6OVBghSNyo9ZUUFP9BU/2JKthMgy9kHGyFu2vp0lg01H9umXn76u52A=="], + "@opencode/schema": ["@opencode/schema@2.4.3", "", { "dependencies": { "@standard-schema/spec": "1.1.0", "effect": "4.1.0" } }, "sha512-+LJ+ARX5cmbqNfATqtyj14Bzhh/+o7qfwv/t0/23QBj8L3mj4Mg3HPq/JFUdWfzMkBZdH7nRepl8BbXUtYtUlg=="], - "@opencode/util": ["@opencode/util@2.0.18", "", { "dependencies": { "@effect/opentelemetry": "4.0.0-rc.112", "@effect/platform-node": "4.0.0-rc.112", "@effect/platform-node-shared": "4.0.0-rc.112", "@npmcli/arborist": "9.4.0", "@npmcli/config": "10.8.1", "@opentelemetry/api": "1.9.0", "@opentelemetry/api-logs": "0.219.0", "@opentelemetry/context-async-hooks": "2.8.0", "@opentelemetry/exporter-trace-otlp-http": "0.219.0", "@opentelemetry/resources": "2.8.0", "@opentelemetry/sdk-logs": "0.219.0", "@opentelemetry/sdk-metrics": "2.8.0", "@opentelemetry/sdk-trace-base": "2.8.0", "@opentelemetry/sdk-trace-node": "2.8.0", "cross-spawn": "7.0.6", "effect": "4.0.0-rc.112", "glob": "13.0.5", "mime-types": "3.0.2", "minimatch": "10.2.5", "npm-package-arg": "13.0.2", "open": "11.0.4", "pacote": "21.5.1" } }, "sha512-PmrOwB3k9nlubvM9ZIj08uann/SpPAfBt6fPI4OiRCnNKBNkEbU4d3CZIFL3QtxTCn1OPzF/AfRDQUuE4Tf+Mg=="], + "@opencode/util": ["@opencode/util@2.4.3", "", { "dependencies": { "@effect/opentelemetry": "4.1.0", "@effect/platform-node": "4.1.0", "@effect/platform-node-shared": "4.1.0", "@npmcli/arborist": "9.4.0", "@npmcli/config": "10.8.1", "@opentelemetry/api": "1.9.0", "@opentelemetry/api-logs": "0.219.0", "@opentelemetry/context-async-hooks": "2.8.0", "@opentelemetry/exporter-trace-otlp-http": "0.219.0", "@opentelemetry/resources": "2.8.0", "@opentelemetry/sdk-logs": "0.219.0", "@opentelemetry/sdk-metrics": "2.8.0", "@opentelemetry/sdk-trace-base": "2.8.0", "@opentelemetry/sdk-trace-node": "2.8.0", "cross-spawn": "7.0.6", "effect": "4.1.0", "glob": "13.0.5", "mime-types": "3.0.2", "minimatch": "10.2.5", "npm-package-arg": "13.0.2", "open": "11.0.4", "pacote": "21.5.1" } }, "sha512-8RvfsaEuK9fN8960CF3keENgnLB9mK4OrZYpUmL8KpLPBOuX8c7CetKZQNZf16Ubw6JVef6U4b0ANW6z0kj48w=="], "@opentelemetry/api": ["@opentelemetry/api@1.9.0", "", {}, "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg=="], @@ -218,7 +206,7 @@ "@types/node": ["@types/node@26.1.1", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw=="], - "@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="], + "@types/ws": ["@types/ws@8.18.2", "", { "dependencies": { "@types/node": "*" } }, "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w=="], "@typescript/typescript-aix-ppc64": ["@typescript/typescript-aix-ppc64@7.0.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ=="], @@ -320,13 +308,11 @@ "define-lazy-prop": ["define-lazy-prop@3.0.0", "", {}, "sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg=="], - "detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], - "eastasianwidth": ["eastasianwidth@0.2.0", "", {}, "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA=="], "ecdsa-sig-formatter": ["ecdsa-sig-formatter@1.0.11", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ=="], - "effect": ["effect@4.0.0-rc.112", "", { "dependencies": { "fast-check": "^4.9.0", "msgpackr": "^2.0.5" } }, "sha512-wXxwuh1Ywnv4cPRM3Wfa0vDwuOHnZ1TsTgHJkG9XgzND6inhBH9n1vBxhg3iIXOia/OrpmvVmd3lrD4vq6bF3A=="], + "effect": ["effect@4.1.0", "", {}, "sha512-lGx2MJJyrXA8RZb2UpQ/0Nkb5Utaimby7oD92+18noBxLPE85IFOvptdzau8dvcxAOwfwHo9iqapbKeFzqQM/Q=="], "emoji-regex": ["emoji-regex@9.2.2", "", {}, "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="], @@ -336,8 +322,6 @@ "extend": ["extend@3.0.2", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="], - "fast-check": ["fast-check@4.9.0", "", { "dependencies": { "pure-rand": "^8.0.0" } }, "sha512-7ms6T7SybUev/PQITciI0yLM2pOSFy5zpG8Ty7tQofcVaQUvrMXp6CBwqF6fThLCLOrfBtuHAtwq6Yu4XPCllg=="], - "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], "fetch-blob": ["fetch-blob@3.2.0", "", { "dependencies": { "node-domexception": "^1.0.0", "web-streams-polyfill": "^3.0.3" } }, "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ=="], @@ -414,8 +398,6 @@ "make-fetch-happen": ["make-fetch-happen@15.0.6", "", { "dependencies": { "@gar/promise-retry": "^1.0.0", "@npmcli/agent": "^4.0.0", "@npmcli/redact": "^4.0.0", "cacache": "^20.0.1", "http-cache-semantics": "^4.1.1", "minipass": "^7.0.2", "minipass-fetch": "^5.0.0", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", "negotiator": "^1.0.0", "proc-log": "^6.0.0", "ssri": "^13.0.0" } }, "sha512-Je0fLJ0F5atA7F+eIlLzk+Wkcl57JDf4kf+EW8xiP5E31xOQxkIxTbgf1Oi1Lw9tRI9UEMRdI5Vz2xTzoNU1Jw=="], - "mime": ["mime@4.1.0", "", { "bin": { "mime": "bin/cli.js" } }, "sha512-X5ju04+cAzsojXKes0B/S4tcYtFAJ6tTMuSPBEn9CPGlrWr8Fiw7qYeLT0XyH80HSoAoqWCaz+MWKh22P7G1cw=="], - "mime-db": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="], "mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="], @@ -438,10 +420,6 @@ "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], - "msgpackr": ["msgpackr@2.1.0", "", { "optionalDependencies": { "msgpackr-extract": "^3.0.4" } }, "sha512-p/pBCVO63CsvvpkomUnNNag6+n38rULuDA6HHe70o2gtC8ODI52foF/4ko2qQcp6OiErJXTmrZeXmsGGHsIQNQ=="], - - "msgpackr-extract": ["msgpackr-extract@3.0.4", "", { "dependencies": { "node-gyp-build-optional-packages": "5.2.2" }, "optionalDependencies": { "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.4", "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.4", "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.4", "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.4", "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.4", "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.4" }, "bin": { "download-msgpackr-prebuilds": "bin/download-prebuilds.js" } }, "sha512-4kmO/MdyUIkLIvTPr8VHLil4AtoKIoniWPIEk5+CDy0xnWC84azhSFmuJ7PxZdsYtiP5kEeQsORAVIeMgxT+Hw=="], - "negotiator": ["negotiator@1.1.0", "", { "dependencies": { "content-type": "^2.1.0" } }, "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg=="], "node-domexception": ["node-domexception@1.0.0", "", {}, "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ=="], @@ -450,8 +428,6 @@ "node-gyp": ["node-gyp@12.4.0", "", { "dependencies": { "env-paths": "^2.2.0", "exponential-backoff": "^3.1.1", "graceful-fs": "^4.2.6", "nopt": "^9.0.0", "proc-log": "^6.0.0", "semver": "^7.3.5", "tar": "^7.5.4", "tinyglobby": "^0.2.12", "undici": "^6.25.0", "which": "^6.0.0" }, "bin": { "node-gyp": "bin/node-gyp.js" } }, "sha512-OMcPNvqTCFUnNaBlmdgq+lfNqY7gTiSmNRDjY3uAXRyudeKZEZxu3CLtjMQrx4zZxCX2b/mpNqTtwuCJgXhHkw=="], - "node-gyp-build-optional-packages": ["node-gyp-build-optional-packages@5.2.2", "", { "dependencies": { "detect-libc": "^2.0.1" }, "bin": { "node-gyp-build-optional-packages": "bin.js", "node-gyp-build-optional-packages-optional": "optional.js", "node-gyp-build-optional-packages-test": "build-test.js" } }, "sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw=="], - "nopt": ["nopt@9.0.0", "", { "dependencies": { "abbrev": "^4.0.0" }, "bin": { "nopt": "bin/nopt.js" } }, "sha512-Zhq3a+yFKrYwSBluL4H9XP3m3y5uvQkB/09CwDruCiRmR/UJYnn9W4R48ry0uGC70aeTPKLynBtscP9efFFcPw=="], "npm-bundled": ["npm-bundled@5.0.0", "", { "dependencies": { "npm-normalize-package-bin": "^5.0.0" } }, "sha512-JLSpbzh6UUXIEoqPsYBvVNVmyrjVZ1fzEFbqxKkTJQkWBO3xFzFT+KDnSKQWwOQNbuWRwt5LSD6HOTLGIWzfrw=="], @@ -496,8 +472,6 @@ "promise-call-limit": ["promise-call-limit@3.0.2", "", {}, "sha512-mRPQO2T1QQVw11E7+UdCJu7S61eJVWknzml9sC1heAdj1jxl0fWMBypIt9ZOcLFf8FkG995ZD7RnVk7HH72fZw=="], - "pure-rand": ["pure-rand@8.4.2", "", {}, "sha512-vvuOGgcuPJAirlHvuQw1TrOiw7ptaIXXmIbNuiNOY6lNGJJH49PQ1Kj4nd783nPdQhQdicgOjVI2yI/9BD6/Ng=="], - "read-cmd-shim": ["read-cmd-shim@6.0.0", "", {}, "sha512-1zM5HuOfagXCBWMN83fuFI/x+T/UhZ7k+KIzhrHXcQoeX5+7gmaDYjELQHmmzIodumBHeByBJT4QYS7ufAgs7A=="], "redis": ["redis@6.2.1", "", { "dependencies": { "@redis/bloom": "6.2.1", "@redis/client": "6.2.1", "@redis/json": "6.2.1", "@redis/search": "6.2.1", "@redis/time-series": "6.2.1" } }, "sha512-Z9VHtgYs48PiQC77X9O2Er8Hj4T+5BtFjT91/vi5Is1D04N72cA946ZslM1ImJw8ZctFBZWAVjM7S5wJNeHMpg=="], @@ -554,7 +528,7 @@ "typescript": ["typescript@7.0.2", "", { "optionalDependencies": { "@typescript/typescript-aix-ppc64": "7.0.2", "@typescript/typescript-darwin-arm64": "7.0.2", "@typescript/typescript-darwin-x64": "7.0.2", "@typescript/typescript-freebsd-arm64": "7.0.2", "@typescript/typescript-freebsd-x64": "7.0.2", "@typescript/typescript-linux-arm": "7.0.2", "@typescript/typescript-linux-arm64": "7.0.2", "@typescript/typescript-linux-loong64": "7.0.2", "@typescript/typescript-linux-mips64el": "7.0.2", "@typescript/typescript-linux-ppc64": "7.0.2", "@typescript/typescript-linux-riscv64": "7.0.2", "@typescript/typescript-linux-s390x": "7.0.2", "@typescript/typescript-linux-x64": "7.0.2", "@typescript/typescript-netbsd-arm64": "7.0.2", "@typescript/typescript-netbsd-x64": "7.0.2", "@typescript/typescript-openbsd-arm64": "7.0.2", "@typescript/typescript-openbsd-x64": "7.0.2", "@typescript/typescript-sunos-x64": "7.0.2", "@typescript/typescript-win32-arm64": "7.0.2", "@typescript/typescript-win32-x64": "7.0.2" }, "bin": { "tsc": "bin/tsc" } }, "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA=="], - "undici": ["undici@8.11.2", "", {}, "sha512-u4UB2/IrKdU6lFxumHmmo1a3fCQO5tzQllRorfoRS63txhrB7xTpSn1PftwC4qEHkOaqP95fCWW4lJzwErwzhQ=="], + "undici": ["undici@8.14.0", "", {}, "sha512-MqM6wqORYo0jb1WFUwFKZTFWFz6VeBMPj9op5Hq+RvlrQjISQCyLEfx5+/iqOLWC/LL1HliJ5t0NP1BgYpXeVQ=="], "undici-types": ["undici-types@8.3.0", "", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="], diff --git a/lightpanda.test.ts b/lightpanda.test.ts index 31fc5b4..31df0a5 100644 --- a/lightpanda.test.ts +++ b/lightpanda.test.ts @@ -118,6 +118,72 @@ test("reports the exit status when neither JSON nor stderr has a diagnostic", () ) }) +test("uses Lightpanda for WebFetch Markdown and keeps the native fallback", async () => { + const permissions: { action: string; resources: readonly string[] }[] = [] + const nativeCalls: unknown[] = [] + let deniedAction: string | undefined + const webfetch: Info = { + name: "webfetch", + description: "Native WebFetch", + input: { type: "object" }, + async execute(input) { + nativeCalls.push(input) + return { content: "native" } + }, + } + await plugin.setup({ + options: { webfetch: true }, + permission: { + async assert(request: (typeof permissions)[number]) { + permissions.push(request) + if (request.action === deniedAction) throw new Error("permission denied") + }, + }, + tool: { + async transform(callback: (editor: ToolEditor) => void) { + callback({ + add() {}, + update(id, update) { + expect(id).toBe("webfetch") + update(webfetch) + }, + list: () => [], + get: () => undefined, + namespace() {}, + remove() {}, + }) + return { async dispose() {} } + }, + }, + } as unknown as Plugin.Context) + + const url = "https://example.test/webfetch" + expect(await webfetch.execute({ url: `${url}#heading` }, makeContext())).toMatchObject({ + content: "fixture content", + output: { contentType: "text/html", output: "fixture content" }, + metadata: { backend: "lightpanda" }, + }) + expect(permissions.map(({ action, resources }) => ({ action, resources }))).toEqual([ + { action: "webfetch", resources: [url] }, + { action: "lightpanda", resources: ["*"] }, + ]) + expect(nativeCalls).toHaveLength(0) + + const textInput = { url, format: "text" } + expect(await webfetch.execute(textInput, makeContext())).toEqual({ content: "native" }) + expect(nativeCalls[0]).toBe(textInput) + expect(permissions).toHaveLength(2) + + const failedUrl = "https://example.test/tls-error" + expect(await webfetch.execute({ url: failedUrl, timeout: 5 }, makeContext())).toEqual({ content: "native" }) + expect(nativeCalls[1]).toMatchObject({ url: failedUrl }) + expect((nativeCalls[1] as { timeout: number }).timeout).toBeLessThan(5) + + deniedAction = "lightpanda" + await expect(webfetch.execute({ url }, makeContext())).rejects.toThrow("permission denied") + expect(nativeCalls).toHaveLength(2) +}) + function makeContext(signal = new AbortController().signal): ToolContext { return { sessionID: "test" as ToolContext["sessionID"], @@ -126,5 +192,8 @@ function makeContext(signal = new AbortController().signal): ToolContext { id: "test" as ToolContext["id"], signal, async progress() {}, + tool: { + call() { throw new Error("Unexpected nested tool call") }, + }, } } diff --git a/lightpanda.ts b/lightpanda.ts index 5a352a3..9b32b9f 100644 --- a/lightpanda.ts +++ b/lightpanda.ts @@ -6,6 +6,8 @@ const MAX_RESPONSE_SIZE = 5 * 1024 * 1024 const MAX_TIMEOUT_SECONDS = 120 const PROCESS_GRACE_MS = 1_000 const MAX_ERROR_EXCERPT = 300 +const WEBFETCH_DEFAULT_TIMEOUT_SECONDS = 30 +const WEBFETCH_BROWSER_TIMEOUT_SECONDS = 3 const responseSchema = z.object({ url: z.string(), @@ -20,6 +22,7 @@ const failureSchema = z.object({ }) type FetchInput = { url: string; format?: "markdown" | "json" | "semantic_tree"; timeout?: number } +type WebFetchInput = { url: string; format?: "markdown" | "text" | "html"; timeout?: number } export default Plugin.define({ id: "opencode-lightpanda", @@ -56,6 +59,56 @@ For web searches, use html.duckduckgo.com instead of Google because Google block options: { permission: "lightpanda", codemode: false }, execute: fetchPage, }) + + if (ctx.options?.webfetch !== true || typeof ctx.permission?.assert !== "function") return + editor.update("webfetch", (tool) => { + const nativeFetch = tool.execute + tool.execute = async (input, context) => { + const { url: rawUrl, format = "markdown", timeout = WEBFETCH_DEFAULT_TIMEOUT_SECONDS } = input as WebFetchInput + const browserTimeout = Math.min(WEBFETCH_BROWSER_TIMEOUT_SECONDS, timeout / 2 - PROCESS_GRACE_MS / 1000) + if (format !== "markdown" || browserTimeout <= 0) return nativeFetch(input, context) + + const url = rawUrl.split("#")[0]! + if (!URL.canParse(url)) return nativeFetch(input, context) + const parsed = new URL(url) + if (!["http:", "https:"].includes(parsed.protocol) || parsed.username || parsed.password) { + return nativeFetch(input, context) + } + + const invocation = { + sessionID: context.sessionID, + agent: context.agent, + source: { type: "tool" as const, messageID: context.messageID, id: context.id }, + metadata: { url, format, timeout }, + } + await ctx.permission.assert({ + ...invocation, + action: "webfetch", + resources: [url], + save: [parsed.origin, `${parsed.origin}/*`], + }) + // Browser navigation and subresources require separate approval from the requested URL. + await ctx.permission.assert({ ...invocation, action: "lightpanda", resources: ["*"], save: ["*"] }) + context.signal.throwIfAborted() + + const started = performance.now() + try { + const result = await fetchPage({ url, timeout: browserTimeout }, context) + const { contentType } = result.metadata + const mime = contentType.split(";")[0]?.trim().toLowerCase() + if (["text/html", "application/xhtml+xml", "text/markdown", "text/x-markdown"].includes(mime ?? "")) { + return { ...result, output: { contentType, output: result.content } } + } + } catch { + // Retry with the native executor when the browser cannot fetch the page. + } + + context.signal.throwIfAborted() + const remaining = timeout - (performance.now() - started) / 1000 + if (remaining <= 0) throw new Error("Request timed out") + return nativeFetch({ ...(input as WebFetchInput), timeout: remaining }, context) + } + }) }) }, }) diff --git a/package.json b/package.json index b7512bc..32bf43c 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,7 @@ "url": "git+https://github.com/skatkov/opencode-lightpanda.git" }, "dependencies": { - "@opencode/plugin": "^2.0.18", + "@opencode/plugin": "^2.4.3", "zod": "^4.1.8" }, "devDependencies": { diff --git a/test/fixtures/lightpanda b/test/fixtures/lightpanda index 00e140f..aab4c50 100755 --- a/test/fixtures/lightpanda +++ b/test/fixtures/lightpanda @@ -28,7 +28,7 @@ if (url.pathname === "/tls-error" || url.pathname === "/dns-error") { JSON.stringify({ url: url.href, http_status: url.pathname === "/not-found" ? 404 : 200, - headers: [{ name: "Content-Type", value: "text/plain" }], + headers: [{ name: "Content-Type", value: url.pathname === "/webfetch" ? "text/html" : "text/plain" }], content: url.pathname === "/command" ? JSON.stringify(args) : "fixture content", }), ) From 81c4195f694bb74db698bc8eb3c7477d7fd3020f Mon Sep 17 00:00:00 2001 From: "Stanislav (Stas) Katkov" Date: Mon, 30 Nov 2026 17:31:29 +0100 Subject: [PATCH 2/2] Use Lightpanda for raw WebFetch responses and images --- README.md | 2 +- lightpanda.test.ts | 25 ++++++--- lightpanda.ts | 106 +++++++++++++++++++++++++++++++++------ test/fixtures/lightpanda | 17 +++++++ 4 files changed, 125 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 25f6302..bb1bffc 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,7 @@ On OpenCode V2.4.3 or later, opt in through the plugin options: } ``` -In this mode, `webfetch` tries Lightpanda first for Markdown page requests. It uses native WebFetch for `text` and `html`, and falls back to native WebFetch if the browser fails or returns a non-page content type. The browser attempt has a three-second rendering cap and shares the request's timeout budget. +In this mode, `webfetch` tries Lightpanda first for `markdown`, `text`, and `html`. Markdown renders pages, while HTML returns the original response and text extracts text from HTML. Plain text, JSON, and XML are returned without wrapping or reformatting. PNG, JPEG, GIF, and WebP can be returned as image attachments. Raw responses require a Lightpanda build that supports `lightpanda run`; other binary formats and failed browser attempts fall back to native WebFetch. The Lightpanda attempt is bounded and shares the request's timeout budget. OpenCode checks the requested URL against `webfetch` permissions, then checks the separate `lightpanda` permission for browser access. The browser can follow public redirects and load public subresources under that permission; those requests are not checked against the native WebFetch URL rules. Leave this option off if your WebFetch rules must apply to every redirect. The standalone `lightpanda` tool remains available either way. diff --git a/lightpanda.test.ts b/lightpanda.test.ts index 31df0a5..874dfcf 100644 --- a/lightpanda.test.ts +++ b/lightpanda.test.ts @@ -118,7 +118,7 @@ test("reports the exit status when neither JSON nor stderr has a diagnostic", () ) }) -test("uses Lightpanda for WebFetch Markdown and keeps the native fallback", async () => { +test("uses Lightpanda for rendered and raw WebFetch results and keeps the native fallback", async () => { const permissions: { action: string; resources: readonly string[] }[] = [] const nativeCalls: unknown[] = [] let deniedAction: string | undefined @@ -169,19 +169,28 @@ test("uses Lightpanda for WebFetch Markdown and keeps the native fallback", asyn ]) expect(nativeCalls).toHaveLength(0) - const textInput = { url, format: "text" } - expect(await webfetch.execute(textInput, makeContext())).toEqual({ content: "native" }) - expect(nativeCalls[0]).toBe(textInput) - expect(permissions).toHaveLength(2) + expect(await webfetch.execute({ url, format: "text" }, makeContext())).toMatchObject({ + content: "raw fixture content", + metadata: { backend: "lightpanda", format: "text" }, + }) + expect(await webfetch.execute({ url: "https://example.test/raw-json" }, makeContext())).toMatchObject({ + content: '{"raw":true}', + metadata: { backend: "lightpanda", contentType: "application/json" }, + }) + expect(await webfetch.execute({ url: "https://example.test/image.png" }, makeContext())).toMatchObject({ + content: [{ type: "file", mime: "image/png", uri: "data:image/png;base64,aW1hZ2U=" }], + output: { contentType: "image/png" }, + }) + expect(nativeCalls).toHaveLength(0) const failedUrl = "https://example.test/tls-error" expect(await webfetch.execute({ url: failedUrl, timeout: 5 }, makeContext())).toEqual({ content: "native" }) - expect(nativeCalls[1]).toMatchObject({ url: failedUrl }) - expect((nativeCalls[1] as { timeout: number }).timeout).toBeLessThan(5) + expect(nativeCalls[0]).toMatchObject({ url: failedUrl }) + expect((nativeCalls[0] as { timeout: number }).timeout).toBeLessThan(5) deniedAction = "lightpanda" await expect(webfetch.execute({ url }, makeContext())).rejects.toThrow("permission denied") - expect(nativeCalls).toHaveLength(2) + expect(nativeCalls).toHaveLength(1) }) function makeContext(signal = new AbortController().signal): ToolContext { diff --git a/lightpanda.ts b/lightpanda.ts index 9b32b9f..bea38f8 100644 --- a/lightpanda.ts +++ b/lightpanda.ts @@ -8,6 +8,7 @@ const PROCESS_GRACE_MS = 1_000 const MAX_ERROR_EXCERPT = 300 const WEBFETCH_DEFAULT_TIMEOUT_SECONDS = 30 const WEBFETCH_BROWSER_TIMEOUT_SECONDS = 3 +const IMAGE_MIMES = ["image/png", "image/jpeg", "image/gif", "image/webp"] const responseSchema = z.object({ url: z.string(), @@ -66,7 +67,7 @@ For web searches, use html.duckduckgo.com instead of Google because Google block tool.execute = async (input, context) => { const { url: rawUrl, format = "markdown", timeout = WEBFETCH_DEFAULT_TIMEOUT_SECONDS } = input as WebFetchInput const browserTimeout = Math.min(WEBFETCH_BROWSER_TIMEOUT_SECONDS, timeout / 2 - PROCESS_GRACE_MS / 1000) - if (format !== "markdown" || browserTimeout <= 0) return nativeFetch(input, context) + if (browserTimeout <= 0) return nativeFetch(input, context) const url = rawUrl.split("#")[0]! if (!URL.canParse(url)) return nativeFetch(input, context) @@ -92,13 +93,19 @@ For web searches, use html.duckduckgo.com instead of Google because Google block context.signal.throwIfAborted() const started = performance.now() + const browserSignal = AbortSignal.any([ + context.signal, + AbortSignal.timeout(Math.ceil(browserTimeout * 1000) + PROCESS_GRACE_MS), + ]) try { - const result = await fetchPage({ url, timeout: browserTimeout }, context) - const { contentType } = result.metadata - const mime = contentType.split(";")[0]?.trim().toLowerCase() - if (["text/html", "application/xhtml+xml", "text/markdown", "text/x-markdown"].includes(mime ?? "")) { - return { ...result, output: { contentType, output: result.content } } + if (format === "markdown") { + const result = await fetchPage({ url, timeout: browserTimeout }, { ...context, signal: browserSignal }) + const { contentType } = result.metadata + if (["text/html", "application/xhtml+xml", "text/markdown", "text/x-markdown"].includes(mimeType(contentType))) { + return { ...result, output: { contentType, output: result.content } } + } } + return await fetchRaw(url, format, browserSignal) } catch { // Retry with the native executor when the browser cannot fetch the page. } @@ -126,15 +133,9 @@ async function fetchPage(input: unknown, context: ToolContext) { const timeoutMs = Math.ceil(timeout * 1000) const dump = format === "json" ? "semantic_tree" : format - const binary = process.env.LIGHTPANDA_BIN || Bun.which("lightpanda") - if (!binary) { - throw new Error("Lightpanda is not installed or is not on PATH. Set LIGHTPANDA_BIN to its executable path.") - } - const timeoutSignal = AbortSignal.timeout(timeoutMs + PROCESS_GRACE_MS) const signal = AbortSignal.any([context.signal, timeoutSignal]) - const command = [ - binary, + const args = [ "fetch", url, "--dump", @@ -144,6 +145,25 @@ async function fetchPage(input: unknown, context: ToolContext) { "networkalmostidle", "--terminate-ms", timeoutMs.toString(), + ] + try { + const result = await runLightpanda(args, url, signal) + return { ...result, metadata: { ...result.metadata, format } } + } finally { + if (context.signal.aborted) throw new Error("Request aborted") + if (timeoutSignal.aborted) throw new Error(`Request timed out after ${timeout} seconds`) + } +} + +async function runLightpanda(args: string[], url: string, signal: AbortSignal, stdin?: Blob) { + const binary = process.env.LIGHTPANDA_BIN || Bun.which("lightpanda") + if (!binary) { + throw new Error("Lightpanda is not installed or is not on PATH. Set LIGHTPANDA_BIN to its executable path.") + } + signal.throwIfAborted() + const command = [ + binary, + ...args, "--http-max-response-size", MAX_RESPONSE_SIZE.toString(), "--block-private-networks", @@ -153,6 +173,7 @@ async function fetchPage(input: unknown, context: ToolContext) { "note", ] const child = Bun.spawn(command, { + stdin: stdin ?? "ignore", stderr: "pipe", signal, env: { @@ -165,8 +186,7 @@ async function fetchPage(input: unknown, context: ToolContext) { (child.stderr as typeof child.stderr & { text(): Promise }).text(), child.exited, ]) - if (context.signal.aborted) throw new Error("Request aborted") - if (timeoutSignal.aborted) throw new Error(`Request timed out after ${timeout} seconds`) + signal.throwIfAborted() if (Buffer.byteLength(stdout) > MAX_RESPONSE_SIZE) { throw new Error("Response too large (exceeds 5MB limit)") } @@ -188,8 +208,62 @@ async function fetchPage(input: unknown, context: ToolContext) { const contentType = response.headers.find((header) => header.name.toLowerCase() === "content-type")?.value ?? "" return { content: response.content, - metadata: { backend: "lightpanda", format, httpStatus: response.http_status, url: response.url, contentType }, + metadata: { backend: "lightpanda", httpStatus: response.http_status, url: response.url, contentType }, + } +} + +function mimeType(contentType: string) { + return contentType.split(";", 1)[0]!.trim().toLowerCase() +} + +async function fetchRaw(url: string, format: NonNullable, signal: AbortSignal) { + signal.throwIfAborted() + // Fetch from a fresh, inert page so arbitrary response scripts cannot run or receive credentials. + const pageScript = `(async () => { + const response = await fetch(${JSON.stringify(url)}, { credentials: "omit" }); + const contentType = (response.headers.get("content-type") || "").split(";", 1)[0].trim().toLowerCase(); + const image = ${JSON.stringify(IMAGE_MIMES)}.includes(contentType); + let content = ""; + if (response.ok) { + if (image) { + content = new Uint8Array(await response.arrayBuffer()).toBase64(); + } else { + content = await response.text(); + if (${format === "text"} && contentType === "text/html") { + const document = new DOMParser().parseFromString(content, "text/html"); + for (const element of document.querySelectorAll("script,style,noscript,iframe,object,embed")) element.remove(); + content = document.documentElement.textContent.trim(); + } + } + } + return { + url: response.url, + http_status: response.status, + headers: [{ name: "content-type", value: response.headers.get("content-type") || "" }], + content, + }; + })()` + const script = `const page = new Page(); + await page.goto("data:text/html,"); + return JSON.parse(await page.evaluate(${JSON.stringify(pageScript)}));` + const result = await runLightpanda(["run", "-", "--disable-features", "cors"], url, signal, new Blob([script])) + const metadata = { ...result.metadata, format } + const { contentType } = metadata + const mime = mimeType(contentType) + if (IMAGE_MIMES.includes(mime)) { + const output = `Fetched ${mime} image.` + return { + content: [{ type: "file" as const, mime, uri: `data:${mime};base64,${result.content}` }], + output: { contentType, output }, + metadata, + } + } + + if (mime && !mime.startsWith("text/") && !mime.endsWith("+json") && !mime.endsWith("+xml") && + !["application/json", "application/xml", "application/javascript", "application/x-javascript"].includes(mime)) { + throw new Error(`Unsupported fetched file content type: ${mime}`) } + return { content: result.content, output: { contentType, output: result.content }, metadata } } function parseResponse(output: string) { diff --git a/test/fixtures/lightpanda b/test/fixtures/lightpanda index aab4c50..af5a8b1 100755 --- a/test/fixtures/lightpanda +++ b/test/fixtures/lightpanda @@ -1,6 +1,23 @@ #!/usr/bin/env bun const args = process.argv.slice(2) +if (args[0] === "run") { + const script = await Bun.stdin.text() + const url = /https:\/\/example\.test\/[\w.-]+/.exec(script)?.[0] + if (!url) throw new Error("Expected a fixture URL in the script") + const responses = { + "/raw-json": { type: "application/json", body: '{"raw":true}' }, + "/image.png": { type: "image/png", body: "aW1hZ2U=" }, + } + const response = responses[new URL(url).pathname] ?? { type: "text/html", body: "raw fixture content" } + process.stdout.write(JSON.stringify({ + url, + http_status: 200, + headers: [{ name: "Content-Type", value: response.type }], + content: response.body, + })) + process.exit(0) +} const url = new URL(args[1]) if (url.pathname === "/tls-error" || url.pathname === "/dns-error") {