Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(plugins): add host-enforced fetch redirect policies

adoin3b0078904919
diff --git a/apps/desktop/electron/main/plugin-host-process.mjs b/apps/desktop/electron/main/plugin-host-process.mjs
index 9919b2dcd..d9d11e046 100644
--- a/apps/desktop/electron/main/plugin-host-process.mjs
+++ b/apps/desktop/electron/main/plugin-host-process.mjs
@@ -400,6 +400,7 @@ function buildApi() {
cdp: (input) => call("browser.cdp", [input]),
},
net: {
+ getCapabilities: () => call("net.getCapabilities"),
fetch: (input) => call("net.fetch", [input]),
// Real-time connections (`net.websocket`). Frames arrive back as
// `net:websocket:message` host events, so a plugin subscribes with
diff --git a/apps/desktop/electron/main/plugin-net-fetch.ts b/apps/desktop/electron/main/plugin-net-fetch.ts
new file mode 100644
index 000000000..f6a074ac5
--- /dev/null
+++ b/apps/desktop/electron/main/plugin-net-fetch.ts
@@ -0,0 +1,63 @@
+import type { PluginNetFetchInput, PluginNetFetchResult } from "@pi-desktop/plugin-sdk";
+
+/** A single HTTP exchange. Transports must honor manual redirects and abort. */
+export type PluginFetchTransport = (url: string, init: RequestInit) => Promise<Response>;
+
+export function parseFetchRedirect(value: unknown): "follow" | "error" | "manual" {
+ if (value === undefined) return "follow";
+ if (value === "follow" || value === "error" || value === "manual") return value;
+ throw failure("INVALID_ARGUMENT", "redirect must be follow, error, or manual");
+}
+
+function failure(code: string, message: string): Error & { code: string } {
+ return Object.assign(new Error(message), { code });
+}
+
+/** One deadline and one policy owner for every transport and redirect hop. */
+export async function pluginNetFetch(
+ input: PluginNetFetchInput,
+ assertEgress: (url: string) => void,
+ transport: PluginFetchTransport = fetch,
+): Promise<{ url: string; result: PluginNetFetchResult }> {
+ const redirect = parseFetchRedirect(input.redirect);
+ if (!/^https?:\/\//i.test(input.url)) {
+ throw failure("INVALID_ARGUMENT", "only http(s) URLs allowed");
+ }
+ assertEgress(input.url);
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), input.timeoutMs ?? 15000);
+ try {
+ let url = input.url;
+ for (let hop = 0; ; hop += 1) {
+ const res = await transport(url, {
+ method: input.method ?? "GET",
+ headers: input.headers,
+ body: input.body,
+ redirect: "manual",
+ signal: controller.signal,
+ });
+ const isRedirect = res.status >= 300 && res.status <= 399;
+ const location = res.headers.get("location");
+ if (isRedirect && redirect === "error") {
+ await res.body?.cancel();
+ throw failure("REDIRECT_DISALLOWED", "net.fetch redirect policy refused a 3xx response");
+ }
+ if (isRedirect && redirect === "follow" && location) {
+ await res.body?.cancel();
+ if (hop >= 5) throw failure("UNAVAILABLE", "too many redirects");
+ url = new URL(location, url).toString();
+ assertEgress(url);
+ continue;
+ }
+ const headers: Record<string, string> = {};
+ res.headers.forEach((value, key) => { headers[key] = value; });
+ const bodyText = await res.text();
+ return { url, result: { status: res.status, headers, bodyText } };
+ }
+ } catch (error) {
+ if (controller.signal.aborted) throw failure("TIMEOUT", "net.fetch timed out");
+ throw error;
+ } finally {
+ clearTimeout(timer);
+ }
+}
diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.ts
index 5891e468c..6011b9859 100644
--- a/apps/desktop/electron/main/plugin-runtime.ts
+++ b/apps/desktop/electron/main/plugin-runtime.ts
@@ -12,6 +12,7 @@ import type { Stats } from "node:fs";
import { open as openFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
+import { pluginNetFetch, parseFetchRedirect, type PluginFetchTransport } from "./plugin-net-fetch";
import type { LoadedSkillDocument } from "./skill-document";
import { getModuleDirectory } from "./module-path";
import {
@@ -355,13 +356,8 @@ export type PluginHostServices = {
readClipboardHistory: () => Promise<ClipboardHistoryEntry[]>;
openPanel: (request: PluginPanelRequest) => Promise<void>;
closePanel: (pluginId: string) => Promise<void>;
- fetch?: (input: {
- url: string;
- method?: string;
- headers?: Record<string, string>;
- body?: string;
- timeoutMs?: number;
- }) => Promise<{ status: number; headers: Record<string, string>; bodyText: string }>;
+ /** Single-hop transport; the runtime owns redirect and timeout policy. */
+ fetch?: PluginFetchTransport;
/** The reviewed desktop operation controller shared with MCP. */
desktopControl?: McpControlController;
/**
@@ -535,6 +531,7 @@ const HOST_API_ALLOWLIST = new Set([
"clipboard.getHistory",
"shell.openExternal",
"net.fetch",
+ "net.getCapabilities",
"bus.publish",
"bus.subscribe",
"bus.unsubscribe",
@@ -614,8 +611,6 @@ const PANEL_SKILL_CHANNELS = new Set([
]);
/** A plugin may teach at most this many skills; the rest are ignored. */
const MAX_SKILLS_PER_PLUGIN = 32;
-/** Redirect hops `pi.net.fetch` follows; each one is re-checked against egress. */
-const NET_FETCH_MAX_REDIRECTS = 5;
/**
* The delay a response advertises, verbatim — the value a plugin has to parse
@@ -2291,6 +2286,8 @@ export class PluginRuntime {
case "shell.openExternal":
await api.shell.openExternal(String(payload?.url ?? ""));
return { ok: true };
+ case "net.getCapabilities":
+ return api.net.getCapabilities();
case "net.fetch":
return api.net.fetch({
url: String(payload?.url ?? ""),
@@ -2298,6 +2295,7 @@ export class PluginRuntime {
headers: (payload?.headers as Record<string, string> | undefined) ?? undefined,
body: payload?.body ? String(payload.body) : undefined,
timeoutMs: typeof payload?.timeoutMs === "number" ? payload.timeoutMs : undefined,
+ redirect: payload?.redirect,
});
case "plugin.getSettings":
return api.plugin.getSettings();
@@ -5744,58 +5742,31 @@ export class PluginRuntime {
closeOutput: async () => this.refuseAudio(loaded, "audio.closeOutput"),
},
net: {
+ getCapabilities: async () => ({ fetchRedirectModes: ["follow", "error", "manual"] }),
fetch: async (input: {
url: string;
method?: string;
headers?: Record<string, string>;
body?: string;
timeoutMs?: number;
+ redirect?: unknown;
}) => {
this.assertPermission(loaded, "net.fetch");
- if (!/^https?:\/\//i.test(input.url)) {
- throw apiError("INVALID_ARGUMENT", "only http(s) URLs allowed");
- }
- this.assertEgress(loaded, input.url, "net.fetch");
- if (this.services.fetch) {
- const result = await this.services.fetch(input);
- this.services.audit?.(
- netFetchAuditEntry(pluginId, input.url, result.status, result.headers),
+ const redirect = parseFetchRedirect(input.redirect);
+ try {
+ const { url, result } = await pluginNetFetch(
+ { ...input, redirect },
+ (url) => this.assertEgress(loaded, url, "net.fetch"),
+ this.services.fetch,
);
+ this.services.audit?.(netFetchAuditEntry(pluginId, url, result.status, result.headers));
return result;
- }
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), input.timeoutMs ?? 15000);
- try {
- // Follow redirects by hand: an allowlisted host that 30x-es to an
- // undeclared one would otherwise carry the request straight out.
- let url = input.url;
- let res: Response;
- for (let hop = 0; ; hop += 1) {
- res = await fetch(url, {
- method: input.method ?? "GET",
- headers: input.headers,
- body: input.body,
- redirect: "manual",
- signal: controller.signal,
- });
- if (res.status < 300 || res.status > 399) break;
- const location = res.headers.get("location");
- if (!location) break;
- if (hop >= NET_FETCH_MAX_REDIRECTS) {
- throw apiError("UNAVAILABLE", `too many redirects: ${input.url}`);
- }
- url = new URL(location, url).toString();
- this.assertEgress(loaded, url, "net.fetch");
+ } catch (error) {
+ if (error instanceof Error && "code" in error && error.code === "REDIRECT_DISALLOWED") {
+ this.services.audit?.({ pluginId, api: "net.fetch", ok: false,
+ errorCode: error.code, ts: Date.now() });
}
- const headers: Record<string, string> = {};
- res.headers.forEach((value, key) => {
- headers[key] = value;
- });
- const bodyText = await res.text();
- this.services.audit?.(netFetchAuditEntry(pluginId, url, res.status, headers));
- return { status: res.status, headers, bodyText };
- } finally {
- clearTimeout(timer);
+ throw error;
}
},
},
diff --git a/apps/desktop/test/plugin-fetch-redirect.test.mjs b/apps/desktop/test/plugin-fetch-redirect.test.mjs
new file mode 100644
index 000000000..900948a85
--- /dev/null
+++ b/apps/desktop/test/plugin-fetch-redirect.test.mjs
@@ -0,0 +1,179 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { fork } from "node:child_process";
+import { createServer } from "node:http";
+import { mkdtempSync, writeFileSync, rmSync, readFileSync } from "node:fs";
+import { register } from "node:module";
+import { runInNewContext } from "node:vm";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+const { PluginRuntime } = await import("../electron/main/plugin-runtime.ts");
+const hostEntry = fileURLToPath(new URL("../electron/main/plugin-host-process.mjs", import.meta.url));
+
+async function fixture(t, services = {}, permissions = ["net.fetch"], main = "module.exports = {};") {
+ const dir = mkdtempSync(join(tmpdir(), "pi-fetch-redirect-"));
+ writeFileSync(join(dir, "manifest.json"), JSON.stringify({
+ schemaVersion: 1, id: "test.redirect", name: "Redirect", version: "0.1.0",
+ main: "main.js", permissions, net: { domains: ["127.0.0.1"] },
+ }));
+ writeFileSync(join(dir, "main.js"), main);
+ const audits = [];
+ const runtime = new PluginRuntime({
+ hostEntry, audit: (entry) => audits.push(entry), ...services,
+ spawnProcess: ({ entry }) => {
+ const child = fork(entry, [], { stdio: ["ignore", "pipe", "pipe", "ipc"] });
+ return {
+ postMessage: (message) => { if (child.connected) child.send(message); },
+ onMessage: (handler) => child.on("message", handler),
+ onExit: (handler) => child.on("exit", (code) => handler(code ?? 0)),
+ kill: () => child.kill(),
+ };
+ },
+ });
+ t.after(async () => {
+ await runtime.unload("test.redirect");
+ rmSync(dir, { recursive: true, force: true });
+ });
+ await runtime.loadFromPath(dir);
+ return { runtime, audits, call: (input) => runtime.invokePanelBridge("test.redirect", "net.fetch", input) };
+}
+
+async function server(t, handler) {
+ const instance = createServer(handler);
+ await new Promise((resolve) => instance.listen(0, "127.0.0.1", resolve));
+ t.after(() => new Promise((resolve) => { instance.close(resolve); instance.closeAllConnections(); }));
+ return `http://127.0.0.1:${instance.address().port}`;
+}
+
+for (const backend of ["default", "injected"]) {
+ test(`${backend}: redirect modes never request the target unless following`, async (t) => {
+ let targetHits = 0;
+ const target = await server(t, (_req, res) => { targetHits++; res.end("target"); });
+ const origin = await server(t, (req, res) => {
+ res.writeHead(Number(req.url.slice(1)), { location: `${target}/end`, "x-fixture": "redirect" });
+ res.end("original");
+ });
+ const services = backend === "injected" ? { fetch: (url, init) => {
+ assert.equal(init.redirect, "manual");
+ assert.ok(init.signal);
+ return fetch(url, init);
+ } } : {};
+ const { call, audits } = await fixture(t, services);
+ for (const status of [301, 302, 303, 307, 308]) {
+ await assert.rejects(call({ url: `${origin}/${status}`, redirect: "error" }), { code: "REDIRECT_DISALLOWED" });
+ assert.equal(targetHits, 0);
+ const manual = await call({ url: `${origin}/${status}`, redirect: "manual" });
+ assert.equal(manual.status, status);
+ assert.equal(manual.headers.location, `${target}/end`);
+ assert.equal(manual.bodyText, "original");
+ assert.equal(targetHits, 0);
+ }
+ assert.equal((await call({ url: `${origin}/302` })).bodyText, "target");
+ assert.equal((await call({ url: `${origin}/307`, redirect: "follow" })).status, 200);
+ assert.equal(targetHits, 2);
+ assert.ok(audits.some((entry) => entry.api === "net.fetch" && entry.status === 302));
+ });
+}
+
+test("invalid policies and missing permissions fail before any request", async (t) => {
+ let hits = 0;
+ const url = await server(t, (_req, res) => { hits++; res.end(); });
+ const { call } = await fixture(t);
+ for (const redirect of ["same-origin", "", null, false, 1, {}]) {
+ await assert.rejects(call({ url, redirect }), { code: "INVALID_ARGUMENT" });
+ }
+ const denied = await fixture(t, {}, []);
+ await assert.rejects(denied.call({ url, redirect: "manual" }), { code: "PERMISSION_DENIED" });
+ assert.equal(hits, 0);
+});
+
+test("relative redirects, missing Location and loops have bounded behavior", async (t) => {
+ let hits = 0;
+ const origin = await server(t, (req, res) => {
+ hits++;
+ if (req.url === "/relative") res.writeHead(302, { location: "done" }).end();
+ else if (req.url === "/missing") res.writeHead(302).end("missing");
+ else if (req.url === "/loop") res.writeHead(302, { location: "/loop" }).end();
+ else res.end("done");
+ });
+ const { call } = await fixture(t);
+ assert.equal((await call({ url: `${origin}/relative` })).bodyText, "done");
+ assert.equal((await call({ url: `${origin}/missing` })).status, 302);
+ await assert.rejects(call({ url: `${origin}/missing`, redirect: "error" }), { code: "REDIRECT_DISALLOWED" });
+ hits = 0;
+ await assert.rejects(call({ url: `${origin}/loop` }), { code: "UNAVAILABLE" });
+ assert.equal(hits, 6);
+});
+
+test("allowlist is checked on every injected transport hop", async (t) => {
+ let hits = 0;
+ const { call } = await fixture(t, { fetch: async () => {
+ hits++;
+ return new Response(null, { status: 302, headers: { location: "http://example.invalid/" } });
+ } });
+ await assert.rejects(call({ url: "http://127.0.0.1/" }), { code: "PERMISSION_DENIED" });
+ assert.equal(hits, 1);
+});
+
+test("the timeout aborts a pending response", async (t) => {
+ const url = await server(t, () => {});
+ const { call } = await fixture(t);
+ await assert.rejects(call({ url, redirect: "manual", timeoutMs: 25 }), { code: "TIMEOUT" });
+});
+
+test("capability query exposes supported policies without making a request", async (t) => {
+ const { runtime } = await fixture(t);
+ assert.deepEqual(await runtime.invokePanelBridge("test.redirect", "net.getCapabilities"), {
+ fetchRedirectModes: ["follow", "error", "manual"],
+ });
+});
+
+for (const backend of ["default", "injected"]) {
+ test(`${backend}: real example plugin queries capabilities and fetches across IPC`, async (t) => {
+ let hits = 0;
+ const target = await server(t, (_req, res) => { hits++; res.end("target"); });
+ const origin = await server(t, (_req, res) => res.writeHead(302, { location: target }).end("original"));
+ const main = readFileSync(new URL("../../../examples/plugins/fetch-redirect/main.js", import.meta.url), "utf8");
+ const services = backend === "injected" ? { fetch: (url, init) => fetch(url, init) } : {};
+ const { runtime, audits } = await fixture(t, services, ["net.fetch"], main);
+ const probe = (redirect) => runtime.invokePanelBridge("test.redirect", "probe.fetch", { url: origin, redirect });
+ await assert.rejects(probe("error"), { code: "REDIRECT_DISALLOWED" });
+ assert.equal(hits, 0);
+ assert.equal((await probe("manual")).status, 302);
+ assert.equal(hits, 0);
+ assert.equal((await probe("follow")).bodyText, "target");
+ assert.equal(hits, 1);
+ assert.ok(audits.some((entry) => entry.errorCode === "REDIRECT_DISALLOWED" && entry.ok === false));
+ });
+}
+
+test("the example refuses old hosts before sending a request", async () => {
+ const main = readFileSync(new URL("../../../examples/plugins/fetch-redirect/main.js", import.meta.url), "utf8");
+ let hits = 0;
+ for (const capabilities of [undefined, async () => ({ fetchRedirectModes: ["follow"] })]) {
+ const module = { exports: {} };
+ runInNewContext(main, { module, pi: { net: {
+ getCapabilities: capabilities, fetch: async () => { hits++; },
+ } } });
+ await assert.rejects(module.exports.onPanelInvoke("probe.fetch", {
+ url: "http://127.0.0.1/", redirect: "error",
+ }), { code: "UNSUPPORTED" });
+ }
+ assert.equal(hits, 0);
+});
+
+test("net.anyHost does not override a no-follow policy", async (t) => {
+ let hits = 0;
+ const url = await server(t, (_req, res) => {
+ hits++;
+ res.writeHead(302, { location: "/next" }).end("original");
+ });
+ const { call } = await fixture(t, {}, ["net.fetch", "net.anyHost"]);
+ await assert.rejects(call({ url, redirect: "error" }), { code: "REDIRECT_DISALLOWED" });
+ assert.equal(hits, 1);
+ assert.equal((await call({ url, redirect: "manual" })).bodyText, "original");
+ assert.equal(hits, 2);
+});
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 7a1b35696..5625817b5 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -363,3 +363,4 @@ Each ADR includes:
| 0319 | [Inline external imports in owning Settings destinations](0319-settings-inline-imports.md) | Accepted (D645) |
| 0320 | [Host-owned OAuth lifecycle for plugin providers](0320-plugin-oauth-provider-callbacks.md) | Accepted for implementation (D647; amends ADR 0259) |
| 0321 | [Pin an acceptable address for mixed direct DNS answers](0321-skill-market-direct-dns-pinning.md) | Accepted (D648; amends ADR 0272) |
+| plugin-fetch-redirect-policy | [Host-enforced plugin fetch redirect policy](plugin-fetch-redirect-policy.md) | Accepted (implementation candidate for #1475) |
diff --git a/docs/adr/plugin-fetch-redirect-policy.md b/docs/adr/plugin-fetch-redirect-policy.md
new file mode 100644
index 000000000..5cc1c111c
--- /dev/null
+++ b/docs/adr/plugin-fetch-redirect-policy.md
@@ -0,0 +1,35 @@
+# ADR: Host-enforced plugin fetch redirect policy
+
+- Status: Accepted (implementation candidate for #1475)
+- Date: 2026-10-08
+
+## Context
+
+Plugins connecting to user-selected endpoints need to refuse or inspect a
+redirect before the host contacts its destination. An optional request field
+alone is insufficient for old hosts that ignore unknown options. The existing
+injected fetch service also returns a fully materialized response, too late for
+the host to own redirect decisions.
+
+## Decision
+
+Add follow/error/manual to the existing SDK request and a read-only
+`net.getCapabilities` query. Keep omitted mode equivalent to legacy follow.
+Move the existing hop loop into a focused host module and make the internal
+injection seam a single-hop Fetch-compatible transport receiving manual redirect
+mode and the shared abort signal. There are no production callers of the old
+injection shape. Both plugin-child RPC and the panel bridge use the same policy.
+
+## Consequences
+
+- Post-response inspection cannot prevent a followed request and is rejected.
+- A release-version check alone cannot identify development hosts; capability
+ detection lets a plugin refuse unsupported hosts before sending anything.
+- A same-origin-only mode is optional in the issue and deferred to keep the
+ additive API small. This change does not alter grants or default request
+ rewriting, storage, process ownership, or sandbox boundaries.
+- The host must continue testing the injected transport as well as the default
+ path. Transports must honor manual redirect and abort semantics.
+
+The contract and acceptance live in the plugin API spec and
+E2E-PLUGIN-fetch-redirect-policy, not this decision record.
diff --git a/docs/plugin-development.md b/docs/plugin-development.md
index bcab60c41..14df50162 100644
--- a/docs/plugin-development.md
+++ b/docs/plugin-development.md
@@ -528,6 +528,25 @@ host never retries a request your plugin makes, so backoff after a rate limit is
your own policy rather than a hidden host behaviour. A call that comes back
`>= 400` is still audited, as `ok: false` with the delay the response advertised.
+### Fetch redirect policy (unreleased)
+
+Check host support before relying on a policy; old hosts can ignore unknown
+request fields. Never fall back to a raw network request.
+
+```js
+if (typeof pi.net.getCapabilities !== "function") throw new Error("Upgrade PI-Desktop");
+const capabilities = await pi.net.getCapabilities();
+if (!capabilities.fetchRedirectModes.includes("error")) throw new Error("Unsupported host");
+const response = await pi.net.fetch({ url: endpoint, redirect: "error" });
+```
+
+`error` rejects every 3xx with `REDIRECT_DISALLOWED` before accessing Location.
+`manual` returns the original status, headers and body. Omitted/`follow` retains
+the existing bounded, per-hop egress-checked behavior. Invalid modes are rejected
+before I/O. No mode expands network permissions. See the
+[complete contract](spec/07-plugins/03-plugin-api.md#net) and the
+local-only test plugin at `examples/plugins/fetch-redirect/README.md` in the repository.
+
### 6.7 Theme
Declare a CSS file and `ui.theme`:
diff --git a/docs/project/unreleased.md b/docs/project/unreleased.md
index 367d66664..d8c3950fa 100644
--- a/docs/project/unreleased.md
+++ b/docs/project/unreleased.md
@@ -1 +1,5 @@
# Unreleased changes
+
+- Plugins can query supported fetch redirect modes and explicitly refuse or
+ inspect redirects without following them. Existing calls keep following by
+ default; a local-only probe plugin demonstrates the new API.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 4f6b83bb3..66f1f3908 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -3376,6 +3376,25 @@ window; opening a normal panel afterward must still work.
- **Acceptance**: Security + G (plugin host services)
- **Status**: Unit/integration-covered; real drag gesture remains manual
+#### E2E-PLUGIN-fetch-redirect-policy
+
+- **Preconditions**: Current-main task candidate, built workspace packages,
+ real Node plugin child process and two loopback HTTP fixtures; no real user
+ profile, provider or credentials.
+- **Steps**: Load the example probe plugin and invoke its `probe.fetch` operation
+ through the production panel bridge. Query capabilities, request error/manual/
+ follow, and repeat against the injected single-hop transport. Exercise invalid
+ modes, missing grants, disallowed targets, relative/missing Location, loops,
+ and timeout. Test 301/302/303/307/308 and default compatibility.
+- **Expected**: Error returns REDIRECT_DISALLOWED and manual returns the original
+ response, both with zero target requests. Follow reaches the target only after
+ egress authorization. Error codes survive child IPC; refusals are audited.
+- **Specs linked**: `07-plugins/03-plugin-api.md`, `07-plugins/04-plugin-security.md`
+- **Acceptance**: G + Security
+- **Milestone**: Post-MVP plugin API
+- **Status**: Automated protocol E2E via `pnpm test:e2e:plugin-fetch-redirect`.
+ The sample panel's native-window gesture remains manual; no desktop is attached.
+
#### E2E-024E: High-risk plugin APIs require grants
- **Preconditions**: Notes plugin installed with explicit grants.
@@ -9550,6 +9569,7 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
| E — Tools & permissions | E2E-008a, E2E-014, E2E-015, E2E-016, E2E-017, E2E-018, E2E-019, E2E-024I, E2E-024K, E2E-040, E2E-049, E2E-074, E2E-093, E2E-097, E2E-099, E2E-100, E2E-101, E2E-102, E2E-102d, E2E-102e, E2E-102g, E2E-103, E2E-105, E2E-106, E2E-107, E2E-111, E2E-112, E2E-113, E2E-114, E2E-115, E2E-116, E2E-119, E2E-121, E2E-122, E2E-142, E2E-145, E2E-147, E2E-155, E2E-158, E2E-166, E2E-181, E2E-PLUGIN-imported-pi-package-skills |
| F — Persistence | E2E-020, E2E-021, E2E-021a, E2E-038, E2E-SETTINGS-inline-capability-imports, E2E-040, E2E-042, E2E-047, E2E-048, E2E-051, E2E-054, E2E-056, E2E-061, E2E-062, E2E-064, E2E-066, E2E-068, E2E-071, E2E-072, E2E-073, E2E-082, E2E-084, E2E-096, E2E-098, E2E-102, E2E-102b, E2E-102c, E2E-102d, E2E-102g, E2E-102i, E2E-103, E2E-AGENTS-001, E2E-061a, E2E-073a, E2E-104, E2E-106, E2E-107, E2E-108, E2E-109, E2E-110, E2E-112, E2E-118, E2E-119, E2E-120, E2E-121, E2E-123, E2E-142, E2E-146, E2E-146a, E2E-148, E2E-151, E2E-158, E2E-160, E2E-168, E2E-171, E2E-177, E2E-178, E2E-183, E2E-186, E2E-005J, E2E-PLUGIN-session-orchestrator-real-workers |
| F — Persistence (project ordering) | E2E-251 |
+| G / Security — Fetch redirect policy | E2E-PLUGIN-fetch-redirect-policy |
| G — Plugins | E2E-022, E2E-022A, E2E-022B, E2E-022C, E2E-023, E2E-024, E2E-024B, E2E-024C, E2E-024D, E2E-024AA, E2E-024E, E2E-024W, E2E-024F, E2E-024G, E2E-024H, E2E-024I, E2E-024J, E2E-024K, E2E-024L, E2E-024M, E2E-024N, E2E-024O, E2E-024P, E2E-025, E2E-026, E2E-105, E2E-117, E2E-120, E2E-122, E2E-123, E2E-024Q, E2E-148, E2E-152, E2E-153, E2E-PLUGIN-imported-pi-package-skills, E2E-PLUGIN-imported-pi-package-wrapper, E2E-PLUGIN-import-extension-installs-dependencies, E2E-PLUGIN-import-extension-reports-missing-dependency, E2E-PLUGIN-global-shortcut-owns-only-its-own-command, E2E-PLUGIN-permission-gate-for-real-time-capabilities, E2E-PLUGIN-background-audio-and-realtime-connection, E2E-PLUGIN-fs-root-follows-the-calling-session |
| H — Diagnostics | E2E-027, E2E-031, E2E-034, E2E-042, E2E-096, E2E-098, E2E-104, E2E-107, E2E-108, E2E-109, E2E-110, E2E-113, E2E-115, E2E-116, E2E-118, E2E-121, E2E-146, E2E-146a, E2E-155, E2E-159, E2E-176, E2E-194, E2E-195 |
| Security | E2E-SETTINGS-inline-capability-imports, E2E-028, E2E-029, E2E-030, E2E-024J, E2E-024K, E2E-024M, E2E-049, E2E-068, E2E-086, E2E-102c, E2E-102d, E2E-102e, E2E-105, E2E-106, E2E-107, E2E-108, E2E-109, E2E-110, E2E-112, E2E-113, E2E-115, E2E-116, E2E-117, E2E-119, E2E-121, E2E-122, E2E-123, E2E-142, E2E-148, E2E-151, E2E-153, E2E-158, E2E-187, E2E-196c, E2E-196b, E2E-196, E2E-PLUGIN-fs-root-follows-the-calling-session |
diff --git a/docs/spec/07-plugins/03-plugin-api.md b/docs/spec/07-plugins/03-plugin-api.md
index a393b39c7..c7c321b4d 100644
--- a/docs/spec/07-plugins/03-plugin-api.md
+++ b/docs/spec/07-plugins/03-plugin-api.md
@@ -785,9 +785,37 @@ pi.net.fetch(input: {
headers?: Record<string, string>
body?: string
timeoutMs?: number
+ redirect?: "follow" | "error" | "manual"
}): Promise<{ status: number; headers: Record<string, string>; bodyText: string }>
```
+
+`redirect` is optional: omitted or `follow` preserves the existing policy (up to
+five followed 3xx responses with Location, relative to the current URL, each
+checked against the granted egress policy). Existing method/header/body handling
+is unchanged; this is not a promise of browser Fetch redirect rewriting.
+`manual` returns the first response's status, headers (including Location) and
+body without visiting its target. `error` rejects **any 300–399 response** with
+`REDIRECT_DISALLOWED`, even without Location; it never visits the target. Other
+statuses, including 429, remain normal responses. In follow mode a 3xx without
+Location is returned unchanged; a loop exceeds the five-hop cap with
+`UNAVAILABLE`. One timeout covers the whole chain and response body (`TIMEOUT`).
+Invalid redirect values fail with `INVALID_ARGUMENT` before network I/O.
+
+The host owns redirect handling for both the default and injected single-hop
+transport. Every followed hop still passes the existing permission/egress
+checks; these modes grant no additional network access. Policy refusals are
+audited without response bodies or headers.
+
+Before using the option on a potentially older host, query
+`pi.net.getCapabilities(): Promise<{ fetchRedirectModes: string[] }>` and require
+the desired mode. This read-only query needs no network permission and performs
+no network I/O. A missing method, rejected query, or absent mode means
+unsupported: do not send the request. Older hosts may silently ignore unknown
+fetch options, so passing `redirect` alone is **not** capability detection.
+This API is unreleased; released 0.17.0 and older do not advertise it.
+No same-origin-only mode is introduced by this change.
+
`fetch` answers with the upstream response unchanged — `status`, `headers`, and
`bodyText` — so a `429` is data your plugin can read, `Retry-After` included,
rather than an error the host hides. The host does not retry, throttle, or
diff --git a/docs/spec/07-plugins/04-plugin-security.md b/docs/spec/07-plugins/04-plugin-security.md
index 5f3b2646f..09c5e0bfe 100644
--- a/docs/spec/07-plugins/04-plugin-security.md
+++ b/docs/spec/07-plugins/04-plugin-security.md
@@ -334,9 +334,11 @@ outbound path the host owns answers to it.
`window.open`, which would otherwise mint a window outside the filtered session
- **`pi.net.fetch`.** Checks the allowlist and follows redirects by hand, because
an allowed host that 30x-es to an undeclared one would carry the request out.
- The runtime's hop loop is the only fetch path: Electron main supplies no
- alternative `fetch` service, so nothing can follow a redirect without the
- per-hop re-check
+ The host's shared hop loop owns both default and injected single-hop
+ transports. `redirect: "error"` rejects 3xx without visiting the target;
+ `manual` returns the original response. The default remains `follow`, with
+ the per-hop re-check. See the [API contract](03-plugin-api.md#net) for
+ capability detection and error codes.
- **Remote MCP endpoints.** Answer to the same list, not to their permission alone.
HTTP endpoints may be on a trusted LAN, but plain HTTP is unencrypted and is
called out during configuration or plugin permission review. The MCP client
diff --git a/docs/zh-CN/plugin-development.md b/docs/zh-CN/plugin-development.md
index c3d887eb9..df61177ca 100644
--- a/docs/zh-CN/plugin-development.md
+++ b/docs/zh-CN/plugin-development.md
@@ -940,3 +940,22 @@ SHA-256 并发布该版本,再把目录与安装包同步到
- [开发者体验](/zh-CN/spec/07-plugins/10-plugin-devex)
- [权限](/zh-CN/spec/07-plugins/13-plugin-permissions-matrix)
- [Hello 参考插件](https://github.com/vastsa/PI-Desktop/tree/main/examples/plugins/hello)
+
+### Fetch redirect policy (unreleased)
+
+Check host support before relying on a policy; old hosts can ignore unknown
+request fields. Never fall back to a raw network request.
+
+```js
+if (typeof pi.net.getCapabilities !== "function") throw new Error("Upgrade PI-Desktop");
+const capabilities = await pi.net.getCapabilities();
+if (!capabilities.fetchRedirectModes.includes("error")) throw new Error("Unsupported host");
+const response = await pi.net.fetch({ url: endpoint, redirect: "error" });
+```
+
+`error` rejects every 3xx with `REDIRECT_DISALLOWED` before accessing Location.
+`manual` returns the original status, headers and body. Omitted/`follow` retains
+the existing bounded, per-hop egress-checked behavior. Invalid modes are rejected
+before I/O. No mode expands network permissions. See the
+[complete contract](/spec/07-plugins/03-plugin-api.md#net) and the
+local-only test plugin at `examples/plugins/fetch-redirect/README.md` in the repository.
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index 6308e2a23..ccbf5c201 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -5604,6 +5604,7 @@ eleven-tool-round desktop paths are verified by
| E——工具和权限 | E2E-008a、E2E-014、E2E-015、E2E-016、E2E-017、E2E-018、E2E-019、E2E-024I、E2E-024K、E2E-040、E2E-049、E2E-074、E2E-093、E2E-097、 E2E-099、E2E-100、E2E-101、E2E-102、E2E-103、E2E-105、E2E-106、E2E-107、E2E-111、E2E-112、E2E-113、E2E-114、E2E-115、E2E-116、 E2E-119、E2E-121、E2E-122、E2E-123、E2E-142、E2E-145、E2E-147、E2E-PLUGIN-imported-pi-package-skills、E2E-166 |
| F——坚持 | E2E-020、E2E-021、E2E-038、E2E-SETTINGS-inline-capability-imports、E2E-040、E2E-042、E2E-047、E2E-048、E2E-048c、E2E-051、E2E-054、E2E-056、E2E-061、E2E-062、 E2E-064、E2E-066、E2E-068、E2E-071、E2E-072、E2E-073、E2E-082、E2E-084、E2E-096、E2E-098、E2E-102、E2E-102b、E2E-103、E2E-代理-001、 E2E-061a、E2E-073a、E2E-104、E2E-106、E2E-107、E2E-108、E2E-109、E2E-110、E2E-112、E2E-118、E2E-119、E2E-120、E2E-121、E2E-123、E2E-142、E2E-146、E2E-148、E2E-151、E2E-171、E2E-005J |
| F——持久化(项目排序) | E2E-253 |
+| G / Security — Fetch redirect policy | E2E-PLUGIN-fetch-redirect-policy |
| G——插件 | E2E-022、E2E-022A、E2E-022B、E2E-022C、E2E-023、E2E-024、E2E-024B、E2E-024C、E2E-024D、E2E-024AA、E2E-024E、E2E-024W、E2E-024F、E2E-024G、E2E-024H、 E2E-024I、E2E-024J、E2E-024K、E2E-024L、E2E-024M、E2E-024N、E2E-024O、E2E-024P、E2E-025、E2E-026、E2E-105、E2E-117、E2E-120、E2E-122、E2E-123、E2E-148、E2E-153、E2E-PLUGIN-imported-pi-package-skills、E2E-PLUGIN-imported-pi-package-wrapper、E2E-PLUGIN-import-extension-installs-dependencies、E2E-PLUGIN-import-extension-reports-missing-dependency、E2E-PLUGIN-global-shortcut-owns-only-its-own-command、E2E-PLUGIN-permission-gate-for-real-time-capabilities、E2E-PLUGIN-background-audio-and-realtime-connection |
| H——诊断 | E2E-027、E2E-031、E2E-034、E2E-042、E2E-096、E2E-098、E2E-104、E2E-107、E2E-108、E2E-109、E2E-110、E2E-113、E2E-115、E2E-116、 E2E-118、E2E-121、E2E-146、E2E-194、E2E-195 |
| 安全性 | E2E-SETTINGS-inline-capability-imports、E2E-028、E2E-029、E2E-030、E2E-024J、E2E-024K、E2E-024M、E2E-049、E2E-068、E2E-086、E2E-105、E2E-106、E2E-107、E2E-108、E2E-109、 E2E-110、E2E-112、E2E-113、E2E-115、E2E-116、E2E-117、E2E-119、E2E-121、E2E-122、E2E-123、E2E-142、E2E-148、E2E-151、E2E-153 |
@@ -9445,3 +9446,22 @@ preload, API normalization, store events, ToolRow, and Markdown renderer.
No provider credentials or paid model calls are required. The fixture ends at
work-panel file-request routing; artifact bytes are verified from the real
host-created files. The full app's file-preview viewer is covered separately.
+
+#### E2E-PLUGIN-fetch-redirect-policy
+
+- **Preconditions**: Current-main task candidate, built workspace packages,
+ real Node plugin child process and two loopback HTTP fixtures; no real user
+ profile, provider or credentials.
+- **Steps**: Load the example probe plugin and invoke its `probe.fetch` operation
+ through the production panel bridge. Query capabilities, request error/manual/
+ follow, and repeat against the injected single-hop transport. Exercise invalid
+ modes, missing grants, disallowed targets, relative/missing Location, loops,
+ and timeout. Test 301/302/303/307/308 and default compatibility.
+- **Expected**: Error returns REDIRECT_DISALLOWED and manual returns the original
+ response, both with zero target requests. Follow reaches the target only after
+ egress authorization. Error codes survive child IPC; refusals are audited.
+- **Specs linked**: `07-plugins/03-plugin-api.md`, `07-plugins/04-plugin-security.md`
+- **Acceptance**: G + Security
+- **Milestone**: Post-MVP plugin API
+- **Status**: Automated protocol E2E via `pnpm test:e2e:plugin-fetch-redirect`.
+ The sample panel's native-window gesture remains manual; no desktop is attached.
diff --git a/docs/zh-CN/spec/07-plugins/03-plugin-api.md b/docs/zh-CN/spec/07-plugins/03-plugin-api.md
index a92091994..73d4c7f51 100644
--- a/docs/zh-CN/spec/07-plugins/03-plugin-api.md
+++ b/docs/zh-CN/spec/07-plugins/03-plugin-api.md
@@ -646,9 +646,36 @@ pi.net.fetch(input: {
headers?: Record<string, string>
body?: string
timeoutMs?: number
+ redirect?: "follow" | "error" | "manual"
}): Promise<{ status: number; headers: Record<string, string>; bodyText: string }>
```
+`redirect` is optional: omitted or `follow` preserves the existing policy (up to
+five followed 3xx responses with Location, relative to the current URL, each
+checked against the granted egress policy). Existing method/header/body handling
+is unchanged; this is not a promise of browser Fetch redirect rewriting.
+`manual` returns the first response's status, headers (including Location) and
+body without visiting its target. `error` rejects **any 300–399 response** with
+`REDIRECT_DISALLOWED`, even without Location; it never visits the target. Other
+statuses, including 429, remain normal responses. In follow mode a 3xx without
+Location is returned unchanged; a loop exceeds the five-hop cap with
+`UNAVAILABLE`. One timeout covers the whole chain and response body (`TIMEOUT`).
+Invalid redirect values fail with `INVALID_ARGUMENT` before network I/O.
+
+The host owns redirect handling for both the default and injected single-hop
+transport. Every followed hop still passes the existing permission/egress
+checks; these modes grant no additional network access. Policy refusals are
+audited without response bodies or headers.
+
+Before using the option on a potentially older host, query
+`pi.net.getCapabilities(): Promise<{ fetchRedirectModes: string[] }>` and require
+the desired mode. This read-only query needs no network permission and performs
+no network I/O. A missing method, rejected query, or absent mode means
+unsupported: do not send the request. Older hosts may silently ignore unknown
+fetch options, so passing `redirect` alone is **not** capability detection.
+This API is unreleased; released 0.17.0 and older do not advertise it.
+No same-origin-only mode is introduced by this change.
+
`fetch` 原样返回上游响应 —— `status`、`headers`、`bodyText` —— 所以 `429`
是插件能读到的数据(`Retry-After` 也在里面),而不是被主机藏起来的错误。宿主
不重试、不限流、也不重新发起请求:遇到 `429` 之后的重试与退避是插件自己的
diff --git a/docs/zh-CN/spec/07-plugins/04-plugin-security.md b/docs/zh-CN/spec/07-plugins/04-plugin-security.md
index faea1cad5..af5b60a81 100644
--- a/docs/zh-CN/spec/07-plugins/04-plugin-security.md
+++ b/docs/zh-CN/spec/07-plugins/04-plugin-security.md
@@ -421,3 +421,11 @@ PI-Desktop 自己当前占用(默认是 `Alt+Space` 与 `Alt+Shift+W`;用户
- 签名验证(仅对包进行 sha256 检查)
- 声明的清单权限在加载时自动授予
- `userSelected` root 不跨重启保留,插件每个会话都得重新问一次
+
+### Fetch redirect policy (unreleased)
+
+The host owns the same redirect loop for default and injected single-hop
+transports. `error` refuses every 3xx with REDIRECT_DISALLOWED; `manual` returns
+it without contacting its target. Default follow retains per-hop egress checks.
+See [the source API contract](/spec/07-plugins/03-plugin-api#net) for capability
+detection, deadline semantics and compatibility. No mode expands network grants.
diff --git a/examples/plugins/README.md b/examples/plugins/README.md
index 14816df8d..d21e1e086 100644
--- a/examples/plugins/README.md
+++ b/examples/plugins/README.md
@@ -80,3 +80,8 @@ Prefer the official warehouse template:
- https://github.com/vastsa/pi-desktop-plugins/tree/main/plugins/demo.workspace-summary
- Contribution guide: https://github.com/vastsa/pi-desktop-plugins/blob/main/CONTRIBUTING.md
+
+## Fetch redirect probe
+
+[fetch-redirect](fetch-redirect/README.md) is a local-only fixture plugin for
+host-enforced follow/error/manual policies and capability detection.
diff --git a/examples/plugins/fetch-redirect/README.md b/examples/plugins/fetch-redirect/README.md
new file mode 100644
index 000000000..d86f7336e
--- /dev/null
+++ b/examples/plugins/fetch-redirect/README.md
@@ -0,0 +1,29 @@
+# Fetch Redirect Probe
+
+A minimal plugin for issue #1475, confined to `127.0.0.1`. It does not use
+`net.anyHost`, credentials, raw network calls, or background requests.
+
+1. Run `node examples/plugins/fetch-redirect/fixture.mjs` from the repository.
+2. Load this directory through the plugin developer load-path workflow and
+ grant `net.fetch` and `ui.panel`. Run **Fetch Redirect: Open Probe** from
+ the command palette (or open it from the plugin launcher).
+3. Paste the fixture URL, choose `error`, and run: expect
+ `REDIRECT_DISALLOWED` and **zero** target requests in the fixture terminal.
+4. Choose `manual`: expect the original 302, Location and body, still zero
+ target requests. Choose `follow`: expect 200 and exactly one target request.
+5. Repeat with /301, /303, /307 and /308. Stop the fixture with Ctrl+C.
+
+The plugin queries `pi.net.getCapabilities()` before sending anything; an old
+host without this capability refuses the probe instead of silently following.
+The current unreleased host implements these capabilities; released 0.17.0
+and older must not be assumed to support them.
+
+Automated protocol E2E (real plugin child process and loopback HTTP, no desktop
+profile or paid provider):
+
+```sh
+pnpm test:e2e:plugin-fetch-redirect
+```
+
+The automated suite exercises the same `probe.fetch` operation and production
+plugin bridge. It does not claim to drive the panel's native window.
diff --git a/examples/plugins/fetch-redirect/fixture.mjs b/examples/plugins/fetch-redirect/fixture.mjs
new file mode 100644
index 000000000..1620ac727
--- /dev/null
+++ b/examples/plugins/fetch-redirect/fixture.mjs
@@ -0,0 +1,24 @@
+import { createServer } from "node:http";
+
+let targetHits = 0;
+const target = createServer((_req, res) => {
+ console.log(`Target requests: ${++targetHits}`);
+ res.end("target reached");
+});
+const origin = createServer((req, res) => {
+ const status = Number(req.url.slice(1));
+ if (![301, 302, 303, 307, 308].includes(status)) {
+ res.writeHead(400).end("Use /301, /302, /303, /307 or /308");
+ return;
+ }
+ res.writeHead(status, { location: `http://127.0.0.1:${target.address().port}/target` });
+ res.end("original redirect response");
+});
+await new Promise((resolve) => target.listen(0, "127.0.0.1", resolve));
+await new Promise((resolve) => origin.listen(0, "127.0.0.1", resolve));
+console.log(`Probe URL: http://127.0.0.1:${origin.address().port}/302`);
+console.log("error/manual: no target requests; follow: one target request per probe.");
+process.once("SIGINT", () => {
+ origin.close(); origin.closeAllConnections();
+ target.close(); target.closeAllConnections();
+});
diff --git a/examples/plugins/fetch-redirect/main.js b/examples/plugins/fetch-redirect/main.js
new file mode 100644
index 000000000..693257a4b
--- /dev/null
+++ b/examples/plugins/fetch-redirect/main.js
@@ -0,0 +1,24 @@
+// No network is accessed until the user explicitly runs a probe.
+module.exports = {
+ async onLoad() {
+ await pi.commands.register({
+ id: "redirect.open",
+ title: "Fetch Redirect: Open Probe",
+ run: () => pi.ui.openPanel(),
+ });
+ },
+ async onUnload() {
+ await pi.commands.unregister("redirect.open");
+ },
+ async onPanelInvoke(channel, input) {
+ if (channel !== "probe.fetch") throw new Error("Unknown probe operation");
+ if (typeof pi.net.getCapabilities !== "function") {
+ throw Object.assign(new Error("Host does not support fetch redirect policies"), { code: "UNSUPPORTED" });
+ }
+ const capabilities = await pi.net.getCapabilities();
+ if (!capabilities.fetchRedirectModes.includes(input.redirect)) {
+ throw Object.assign(new Error("Unsupported redirect policy"), { code: "UNSUPPORTED" });
+ }
+ return pi.net.fetch({ url: input.url, redirect: input.redirect, timeoutMs: 3000 });
+ },
+};
diff --git a/examples/plugins/fetch-redirect/manifest.json b/examples/plugins/fetch-redirect/manifest.json
new file mode 100644
index 000000000..69db14f19
--- /dev/null
+++ b/examples/plugins/fetch-redirect/manifest.json
@@ -0,0 +1,37 @@
+{
+ "schemaVersion": 1,
+ "id": "demo.fetch-redirect",
+ "name": "Fetch Redirect Probe",
+ "version": "0.1.0",
+ "description": "Local-only probe for host-enforced fetch redirect policies.",
+ "main": "main.js",
+ "permissions": [
+ "net.fetch",
+ "ui.panel"
+ ],
+ "net": {
+ "domains": [
+ "127.0.0.1"
+ ]
+ },
+ "ui": {
+ "panel": "panel.html",
+ "title": {
+ "en": "Fetch Redirect Probe",
+ "zh-CN": "重定向测试"
+ },
+ "width": 520,
+ "height": 440
+ },
+ "activationEvents": [
+ "onStartup"
+ ],
+ "contributes": {
+ "commands": [
+ {
+ "id": "redirect.open",
+ "title": "Fetch Redirect: Open Probe"
+ }
+ ]
+ }
+}
diff --git a/examples/plugins/fetch-redirect/panel.html b/examples/plugins/fetch-redirect/panel.html
new file mode 100644
index 000000000..5f4115d4e
--- /dev/null
+++ b/examples/plugins/fetch-redirect/panel.html
@@ -0,0 +1,37 @@
+<!doctype html>
+<html lang="en">
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Fetch Redirect Probe</title>
+<style>
+ body { font: 14px system-ui; padding: 16px; color-scheme: light dark; }
+ label { display: block; margin: 12px 0; }
+ input { width: 95%; } pre { white-space: pre-wrap; overflow-wrap: anywhere; }
+</style>
+<h1>Fetch Redirect Probe</h1>
+<p>Start fixture.mjs locally. No credentials or external services are needed.</p>
+<form id="probe">
+ <label>Fixture URL <input id="url" type="url" required placeholder="Paste the URL printed by fixture.mjs"></label>
+ <label>Redirect policy <select id="policy"><option>error</option><option>manual</option><option>follow</option></select></label>
+ <button id="run">Run probe</button>
+</form>
+<pre id="result" role="status" aria-live="polite"></pre>
+<script>
+ document.getElementById("probe").addEventListener("submit", async (event) => {
+ event.preventDefault();
+ const button = document.getElementById("run");
+ const result = document.getElementById("result");
+ button.disabled = true;
+ result.textContent = "Requesting…";
+ try {
+ const response = await window.pluginBridge.invoke("probe.fetch", {
+ url: document.getElementById("url").value,
+ redirect: document.getElementById("policy").value,
+ });
+ result.textContent = JSON.stringify(response, null, 2);
+ } catch (error) {
+ result.textContent = `${error.code ?? "ERROR"}: ${error.message}`;
+ } finally { button.disabled = false; }
+ });
+</script>
+</html>
diff --git a/package.json b/package.json
index a1c4005ac..43b711b7e 100644
--- a/package.json
+++ b/package.json
@@ -79,6 +79,7 @@
"test:e2e:mcp-market": "node scripts/e2e-mcp-market.mjs",
"test:e2e:skill-market": "node scripts/e2e-skill-market.mjs",
"test:e2e:capability-move": "node scripts/e2e-capability-move.mjs",
+ "test:e2e:plugin-fetch-redirect": "node --test apps/desktop/test/plugin-fetch-redirect.test.mjs",
"test:e2e:plugin-import-deps": "node scripts/e2e-plugin-import-deps.mjs",
"test:e2e:trusted-extensions": "node scripts/e2e-trusted-extensions.mjs",
"test:e2e:plugin-ui-slots": "node scripts/e2e-plugin-ui-slots.mjs",
diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.ts
index 4a577a299..445e58de7 100644
--- a/packages/plugin-sdk/src/index.ts
+++ b/packages/plugin-sdk/src/index.ts
@@ -17,6 +17,23 @@ import {
type PluginThemeVariableContrib,
} from "./theme-variables.js";
+/** Host-mediated HTTP request; redirect defaults to the legacy follow policy. */
+export type PluginNetFetchInput = {
+ url: string;
+ method?: string;
+ headers?: Record<string, string>;
+ body?: string;
+ timeoutMs?: number;
+ /** Defaults to follow. error refuses any 3xx; manual returns it unchanged. */
+ redirect?: "follow" | "error" | "manual";
+};
+
+export type PluginNetFetchResult = {
+ status: number;
+ headers: Record<string, string>;
+ bodyText: string;
+};
+
/**
* Manifest id shape frozen by docs/spec/07-plugins/02-plugin-manifest-schema.md:
* a lowercase dotted namespace such as `demo.hello` or `pi.browser`.
@@ -1301,13 +1318,9 @@ export type PluginHostApi = {
cdp: (input: { method: string; params?: unknown }) => Promise<unknown>;
};
net: {
- fetch: (input: {
- url: string;
- method?: string;
- headers?: Record<string, string>;
- body?: string;
- timeoutMs?: number;
- }) => Promise<{ status: number; headers: Record<string, string>; bodyText: string }>;
+ /** Query before using redirect on hosts that may predate this API. */
+ getCapabilities: () => Promise<{ fetchRedirectModes: ("follow" | "error" | "manual")[] }>;
+ fetch: (input: PluginNetFetchInput) => Promise<PluginNetFetchResult>;
/**
* Real-time bidirectional sockets (`net.websocket`). A connect is confined
* to `manifest.net.domains` exactly like `fetch`, and the host closes every