Skip to content

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

fix(plugin-net): support bounded binary responses

鱼骨头TO702170eaa24e
diff --git a/apps/desktop/electron/main/plugin-net-fetch.ts b/apps/desktop/electron/main/plugin-net-fetch.ts
index f6a074ac5..0147dd17a 100644
--- a/apps/desktop/electron/main/plugin-net-fetch.ts
+++ b/apps/desktop/electron/main/plugin-net-fetch.ts
@@ -1,16 +1,60 @@
import type { PluginNetFetchInput, PluginNetFetchResult } from "@pi-desktop/plugin-sdk";
+export const MAX_PLUGIN_BINARY_RESPONSE_BYTES = 16 * 1024 * 1024;
+
/** A single HTTP exchange. Transports must honor manual redirects and abort. */
export type PluginFetchTransport = (url: string, init: RequestInit) => Promise<Response>;
+function failure(code: string, message: string): Error & { code: string } {
+ return Object.assign(new Error(message), { code });
+}
+
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 });
+function parseResponseType(value: unknown): "text" | "base64" {
+ if (value === undefined || value === "text") return "text";
+ if (value === "base64") return "base64";
+ throw failure("INVALID_ARGUMENT", "responseType must be text or base64");
+}
+
+function parseResponseLimit(value: unknown, responseType: "text" | "base64"): number {
+ if (value === undefined) return MAX_PLUGIN_BINARY_RESPONSE_BYTES;
+ if (responseType !== "base64" || !Number.isSafeInteger(value) || value < 1 || value > MAX_PLUGIN_BINARY_RESPONSE_BYTES) {
+ throw failure("INVALID_ARGUMENT", "maxResponseBytes is only supported for bounded base64 responses");
+ }
+ return value;
+}
+
+async function readBinaryBody(response: Response, limit: number): Promise<Buffer> {
+ const declared = response.headers.get("content-length");
+ if (declared !== null && (!/^\d+$/.test(declared) || Number(declared) > limit)) {
+ await response.body?.cancel();
+ throw failure("RESPONSE_TOO_LARGE", "binary response exceeds the declared size limit");
+ }
+ if (!response.body) return Buffer.alloc(0);
+ const reader = response.body.getReader();
+ const chunks: Buffer[] = [];
+ let total = 0;
+ try {
+ for (;;) {
+ const next = await reader.read();
+ if (next.done) break;
+ const chunk = Buffer.from(next.value);
+ total += chunk.length;
+ if (total > limit) {
+ await reader.cancel();
+ throw failure("RESPONSE_TOO_LARGE", "binary response exceeds the size limit");
+ }
+ chunks.push(chunk);
+ }
+ } finally {
+ reader.releaseLock();
+ }
+ return Buffer.concat(chunks, total);
}
/** One deadline and one policy owner for every transport and redirect hop. */
@@ -20,6 +64,8 @@ export async function pluginNetFetch(
transport: PluginFetchTransport = fetch,
): Promise<{ url: string; result: PluginNetFetchResult }> {
const redirect = parseFetchRedirect(input.redirect);
+ const responseType = parseResponseType(input.responseType);
+ const maxResponseBytes = parseResponseLimit(input.maxResponseBytes, responseType);
if (!/^https?:\/\//i.test(input.url)) {
throw failure("INVALID_ARGUMENT", "only http(s) URLs allowed");
}
@@ -51,6 +97,10 @@ export async function pluginNetFetch(
}
const headers: Record<string, string> = {};
res.headers.forEach((value, key) => { headers[key] = value; });
+ if (responseType === "base64") {
+ const bytes = await readBinaryBody(res, maxResponseBytes);
+ return { url, result: { status: res.status, headers, bodyText: "", bodyBase64: bytes.toString("base64"), contentType: headers["content-type"] ?? "application/octet-stream", byteLength: bytes.length } };
+ }
const bodyText = await res.text();
return { url, result: { status: res.status, headers, bodyText } };
}
diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.ts
index 4a7d09ae1..5159e1ff0 100644
--- a/apps/desktop/electron/main/plugin-runtime.ts
+++ b/apps/desktop/electron/main/plugin-runtime.ts
@@ -2660,6 +2660,8 @@ 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,
+ responseType: payload?.responseType === undefined ? undefined : String(payload.responseType) as "text" | "base64",
+ maxResponseBytes: typeof payload?.maxResponseBytes === "number" ? payload.maxResponseBytes : undefined,
redirect: payload?.redirect,
});
case "plugin.getSettings":
@@ -6646,13 +6648,15 @@ export class PluginRuntime {
closeOutput: async () => this.refuseAudio(loaded, "audio.closeOutput"),
},
net: {
- getCapabilities: async () => ({ fetchRedirectModes: ["follow", "error", "manual"] }),
+ getCapabilities: async () => ({ fetchRedirectModes: ["follow", "error", "manual"], binaryResponseBody: true, maxResponseBodyBytes: 16 * 1024 * 1024 }),
fetch: async (input: {
url: string;
method?: string;
headers?: Record<string, string>;
body?: string;
timeoutMs?: number;
+ responseType?: "text" | "base64";
+ maxResponseBytes?: number;
redirect?: unknown;
}) => {
this.assertPermission(loaded, "net.fetch");
diff --git a/apps/desktop/test/plugin-fetch-redirect.test.mjs b/apps/desktop/test/plugin-fetch-redirect.test.mjs
index 900948a85..a9bbd9c0f 100644
--- a/apps/desktop/test/plugin-fetch-redirect.test.mjs
+++ b/apps/desktop/test/plugin-fetch-redirect.test.mjs
@@ -124,10 +124,12 @@ test("the timeout aborts a pending response", async (t) => {
await assert.rejects(call({ url, redirect: "manual", timeoutMs: 25 }), { code: "TIMEOUT" });
});
-test("capability query exposes supported policies without making a request", async (t) => {
+test("capability query exposes text and bounded binary response support without making a request", async (t) => {
const { runtime } = await fixture(t);
assert.deepEqual(await runtime.invokePanelBridge("test.redirect", "net.getCapabilities"), {
fetchRedirectModes: ["follow", "error", "manual"],
+ binaryResponseBody: true,
+ maxResponseBodyBytes: 16 * 1024 * 1024,
});
});
@@ -177,3 +179,15 @@ test("net.anyHost does not override a no-follow policy", async (t) => {
assert.equal((await call({ url, redirect: "manual" })).bodyText, "original");
assert.equal(hits, 2);
});
+test("base64 response preserves bytes and enforces the requested response limit", async (t) => {
+ const bytes = Buffer.from([0, 1, 2, 127, 128, 254, 255]);
+ const url = await server(t, (_req, res) => res.writeHead(200, { "content-type": "image/png" }).end(bytes));
+ const { call } = await fixture(t);
+ const result = await call({ url, responseType: "base64", maxResponseBytes: bytes.length });
+ assert.equal(result.bodyBase64, bytes.toString("base64"));
+ assert.equal(result.contentType, "image/png");
+ assert.equal(result.byteLength, bytes.length);
+ assert.equal(result.bodyText, "");
+ await assert.rejects(call({ url, responseType: "base64", maxResponseBytes: bytes.length - 1 }), { code: "RESPONSE_TOO_LARGE" });
+ await assert.rejects(call({ url, responseType: "binary" }), { code: "INVALID_ARGUMENT" });
+});
diff --git a/docs/adr/README.md b/docs/adr/README.md
index f3e91394d..34109a912 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -34,6 +34,7 @@ git history.
| append-only-review-state | [Append-only review state](append-only-review-state.md) | Implemented candidate |
| lossless-tool-image-storage | [Lossless tool-image storage and bounded history mutations](lossless-tool-image-storage.md) | Implemented candidate |
| plugin-remote-workspace-reads | [Plugin reads in remote workspaces](plugin-remote-workspace-reads.md) | Implemented candidate |
+| plugin-net-fetch-binary-response | [Bounded binary response mode for plugin net.fetch](plugin-net-fetch-binary-response.md) | Accepted |
| browser-background-lifecycle | [Browser page execution outlives side-panel presentation](browser-background-lifecycle.md) | Accepted |
| asktool-draft-survives-session-switch | [AskTool drafts survive a card remount](asktool-draft-survives-session-switch.md) | Accepted |
| tool-abort-abandons-host-call | [A user stop ends the turn even when the running tool cannot be cancelled](tool-abort-abandons-host-call.md) | Accepted for implementation |
diff --git a/docs/adr/plugin-net-fetch-binary-response.md b/docs/adr/plugin-net-fetch-binary-response.md
new file mode 100644
index 000000000..16be63a4b
--- /dev/null
+++ b/docs/adr/plugin-net-fetch-binary-response.md
@@ -0,0 +1,18 @@
+# ADR: Bounded binary response mode for plugin net.fetch
+
+- Status: accepted
+- Date: 2026-11-20
+
+## Context
+
+Plugins that integrate media services sometimes receive result bytes through an HTTP endpoint. The existing `pi.net.fetch` contract returns `bodyText`, which is suitable for JSON and text APIs but corrupts arbitrary media bytes. Reading remote files through a plugin's local filesystem or direct Node networking would bypass the host's permission and egress controls.
+
+## Decision
+
+Add an optional `responseType: "base64"` mode to the host-mediated `pi.net.fetch` API. The host reads the response stream with a bounded byte limit, returns canonical Base64 together with the response content type and byte length, and rejects oversized responses before returning partial data. The default text mode remains unchanged.
+
+The host advertises `binaryResponseBody` and `maxResponseBodyBytes` through `pi.net.getCapabilities`. Plugins must check these capabilities before requesting binary responses. Existing URL validation, egress allowlists, permission checks, redirect handling, timeout ownership and audit behavior apply to both response modes.
+
+## Consequences
+
+Media plugins can download bounded result bytes through the same audited host boundary used for JSON requests. The host owns allocation and size enforcement. Older hosts remain compatible with existing text requests and must be treated as unable to download binary results when the capability is absent. Plugins still own media-type validation, hash verification, persistence and retry semantics.
diff --git a/docs/spec/07-plugins/03-plugin-api.md b/docs/spec/07-plugins/03-plugin-api.md
index 15bf741f6..10c6b7950 100644
--- a/docs/spec/07-plugins/03-plugin-api.md
+++ b/docs/spec/07-plugins/03-plugin-api.md
@@ -1242,10 +1242,32 @@ pi.net.fetch(input: {
headers?: Record<string, string>
body?: string
timeoutMs?: number
+ responseType?: "text" | "base64"
+ maxResponseBytes?: number
redirect?: "follow" | "error" | "manual"
-}): Promise<{ status: number; headers: Record<string, string>; bodyText: string }>
-```
+}): Promise<{
+ status: number
+ headers: Record<string, string>
+ bodyText: string
+ bodyBase64?: string
+ contentType?: string
+ byteLength?: number
+}>
+```
+`responseType` defaults to `text` and preserves the existing bodyText response.
+`responseType: "base64"` reads the response body as bounded bytes and returns
+canonical standard Base64 in `bodyBase64`, with `contentType` and `byteLength`.
+The host enforces a maximum of 16 MiB and accepts a smaller positive integer in
+`maxResponseBytes`. A response over the limit fails with
+`RESPONSE_TOO_LARGE`; no partial bytes are returned. Binary response mode is
+intended for bounded media downloads and does not grant filesystem access.
+
+Before using binary mode on a potentially older host, query
+`pi.net.getCapabilities(): Promise<{ fetchRedirectModes: ("follow" | "error" | "manual")[]; binaryResponseBody?: true; maxResponseBodyBytes?: number }>`
+and require `binaryResponseBody` plus a sufficient `maxResponseBodyBytes`.
+This read-only query needs no network permission and performs no network I/O.
+When the capability is absent, do not send a base64 request.
`redirect` is optional: omitted or `follow` preserves the existing policy (up to
five followed 3xx responses with Location, relative to the current URL, each
@@ -1264,22 +1286,10 @@ 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: ("follow" | "error" | "manual")[] }>` 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.
-Current source implements this query; older hosts may 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
-re-issue the request: retry and backoff after a `429` are your plugin's own
-policy, and the response headers are the only backoff signal you get. A failed
-call (`status >= 400`) is audited as `ok: false`, together with the
-`retryAfter` it advertised when the response states one (§7).
+`fetch` answers with the upstream response unchanged — `status`, `headers`,
+and either text or bounded Base64 body data — 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 re-issue the request.
```ts
pi.net.websocket.connect(input: {
diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.ts
index 3679b1675..365090e82 100644
--- a/packages/plugin-sdk/src/index.ts
+++ b/packages/plugin-sdk/src/index.ts
@@ -24,6 +24,10 @@ export type PluginNetFetchInput = {
headers?: Record<string, string>;
body?: string;
timeoutMs?: number;
+ /** Defaults to text. Base64 returns bounded binary response bytes. */
+ responseType?: "text" | "base64";
+ /** Required upper bound for base64 responses when supplied. */
+ maxResponseBytes?: number;
/** Defaults to follow. error refuses any 3xx; manual returns it unchanged. */
redirect?: "follow" | "error" | "manual";
};
@@ -32,6 +36,16 @@ export type PluginNetFetchResult = {
status: number;
headers: Record<string, string>;
bodyText: string;
+ /** Present only when responseType is base64. */
+ bodyBase64?: string;
+ contentType?: string;
+ byteLength?: number;
+};
+
+export type PluginNetCapabilities = {
+ fetchRedirectModes: ("follow" | "error" | "manual")[];
+ binaryResponseBody?: true;
+ maxResponseBodyBytes?: number;
};
/**