Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(network): apply system proxy to providers and marketplace
vastsa0473bc2106e1
diff --git a/apps/desktop/electron/main/bootstrap/shutdown.ts b/apps/desktop/electron/main/bootstrap/shutdown.tsindex cc753a5d5..855e15edc 100644--- a/apps/desktop/electron/main/bootstrap/shutdown.ts+++ b/apps/desktop/electron/main/bootstrap/shutdown.ts@@ -49,6 +49,7 @@ export type ShutdownDependencies = {confirmQuitDialog: () => Promise<boolean>;disposePowerSaveBlockers: () => void;liveCallService?: Pick<LiveCallService, "endForLifecycle">;+ disposeSystemProxyRelay?: () => Promise<void>;};/** Register the last-window and before-quit resource lifecycle handlers. */@@ -72,6 +73,7 @@ export function registerShutdownHandlers({confirmQuitDialog,disposePowerSaveBlockers,liveCallService,+ disposeSystemProxyRelay,}: ShutdownDependencies): void {app.on("window-all-closed", () => {// The D216 tray is resident on every platform, so its presence says nothing@@ -188,6 +190,7 @@ export function registerShutdownHandlers({mcpShutdown,remoteHostsShutdown,]);+ await disposeSystemProxyRelay?.();})();const releaseQuit = () => {diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.tsindex c07281e6d..6d9b18ca4 100644--- a/apps/desktop/electron/main/index.ts+++ b/apps/desktop/electron/main/index.ts@@ -9,6 +9,7 @@ import { join } from "node:path";import {applyNetworkProxyFromAppSettings,currentNetworkProxy,+ disposeSystemProxyRelay,testNetworkProxy,} from "./network-proxy";import { installInsecureEndpointNotice } from "./network-notice";@@ -1041,6 +1042,7 @@ registerShutdownHandlers({confirmQuitDialog,disposePowerSaveBlockers,liveCallService,+ disposeSystemProxyRelay,});registerApplicationActivation({diff --git a/apps/desktop/electron/main/ipc/settings-ipc.ts b/apps/desktop/electron/main/ipc/settings-ipc.tsindex c43310d78..2adec295e 100644--- a/apps/desktop/electron/main/ipc/settings-ipc.ts+++ b/apps/desktop/electron/main/ipc/settings-ipc.ts@@ -4,6 +4,7 @@ import type { HostProcess } from "../host-process";import type { IpcRegistrar } from "./types";import type { LiveCallService } from "../live-voice/call-service";import type { AppSettings } from "@pi-desktop/shared";+import { currentSystemProxyRelayUrl } from "../network-proxy";export type SettingsIpcDependencies = {registrar: IpcRegistrar;@@ -103,6 +104,7 @@ export function registerSettingsIpc({hostBinary: host.binaryPath,dataDir,networkProxy: currentNetworkProxy(),+ systemProxyRelayUrl: currentSystemProxyRelayUrl(),});} catch {// Sidecar will pick up PI_DESKTOP_PROXY_JSON on the next spawn.diff --git a/apps/desktop/electron/main/network-proxy.ts b/apps/desktop/electron/main/network-proxy.tsindex 9aff28871..3031ec6d0 100644--- a/apps/desktop/electron/main/network-proxy.ts+++ b/apps/desktop/electron/main/network-proxy.ts@@ -26,6 +26,10 @@ import {type AuthenticatedProxyRelay,} from "@pi-desktop/agent-runtime";import { applyUserEndpointPolicyFromAppSettings } from "./endpoint-policy";+import {+ startSystemProxyRelay,+ type SystemProxyRelay,+} from "./system-proxy-relay";const originalEnv = snapshotProxyEnv(process.env);let applied: NetworkProxySettings = { mode: "system" };@@ -33,6 +37,36 @@ let fetchPatched = false;let sessionHookInstalled = false;let activeRelay: AuthenticatedProxyRelay | null = null;let relayUpstreamHref: string | null = null;+let systemProxyRelay: SystemProxyRelay | null = null;+let systemProxyRelayStart: Promise<SystemProxyRelay> | null = null;++export async function ensureSystemProxyRelay(): Promise<string> {+ if (!systemProxyRelay) {+ const starting =+ systemProxyRelayStart ??+ (systemProxyRelayStart = startSystemProxyRelay((url) =>+ session.defaultSession.resolveProxy(url),+ ));+ try {+ systemProxyRelay = await starting;+ } finally {+ if (systemProxyRelayStart === starting) systemProxyRelayStart = null;+ }+ }+ return systemProxyRelay.url;+}++export function currentSystemProxyRelayUrl(): string | null {+ return systemProxyRelay?.url ?? null;+}++export async function disposeSystemProxyRelay(): Promise<void> {+ const pending = systemProxyRelayStart;+ const relay = systemProxyRelay ?? (pending ? await pending : null);+ systemProxyRelay = null;+ if (systemProxyRelayStart === pending) systemProxyRelayStart = null;+ await relay?.close();+}export function currentNetworkProxy(): NetworkProxySettings {return applied;diff --git a/apps/desktop/electron/main/runtime/host.ts b/apps/desktop/electron/main/runtime/host.tsindex ce5e05680..df55a029e 100644--- a/apps/desktop/electron/main/runtime/host.ts+++ b/apps/desktop/electron/main/runtime/host.ts@@ -1,6 +1,7 @@import { ErrorCodes, IPC, type AgentEventEnvelope, type PlanExecutionFinishStatus, type Risk } from "@pi-desktop/shared";import { assertLinuxGlibcSupported } from "../linux-glibc";import { HostProcess } from "../host-process";+import { ensureSystemProxyRelay } from "../network-proxy";import type { Logger } from "../logger";import type { PersistenceOutbox } from "../persistence-outbox";import type { PluginRuntime } from "../plugin-runtime";@@ -362,11 +363,15 @@ export function createHostRuntime({const startHost = async (): Promise<void> => {assertLinuxGlibcSupported();+ const systemProxyRelayUrl = await ensureSystemProxyRelay();const h = new HostProcess(dataDir, (text) => logger.child("host", text));wireHost(h);runtimeState.host = h;try {await h.handshake();+ await h.call("network.configureSystemProxyRelay", {+ url: systemProxyRelayUrl,+ });logger.app("runtime", "info", "host-core handshake ok", {data: { generation: h.generation },});diff --git a/apps/desktop/electron/main/runtime/sidecar.ts b/apps/desktop/electron/main/runtime/sidecar.tsindex 4cc39c34d..1d1388300 100644--- a/apps/desktop/electron/main/runtime/sidecar.ts+++ b/apps/desktop/electron/main/runtime/sidecar.ts@@ -24,6 +24,7 @@ import type { PluginRuntime } from "../plugin-runtime";import type { RuntimeState } from "./context";import type { FinishTurn } from "./plans";import { formatSkillToolContent, type LoadedSkillDocument } from "../skill-document";+import { currentSystemProxyRelayUrl } from "../network-proxy";export type SidecarRuntimeDependencies = {runtimeState: RuntimeState;@@ -674,6 +675,7 @@ export function createSidecarRuntime({hostBinary: runtimeState.host?.binaryPath,dataDir,networkProxy: currentNetworkProxy(),+ systemProxyRelayUrl: currentSystemProxyRelayUrl(),});logger.app("runtime", "info", "agent sidecar configured");};diff --git a/apps/desktop/electron/main/system-proxy-relay.ts b/apps/desktop/electron/main/system-proxy-relay.tsnew file mode 100644index 000000000..8ed7f5aaf--- /dev/null+++ b/apps/desktop/electron/main/system-proxy-relay.ts@@ -0,0 +1,272 @@+import { randomBytes, timingSafeEqual } from "node:crypto";+import { createServer, type Server, type Socket } from "node:net";+import { parseProxyUrl, type ParsedProxyUrl } from "@pi-desktop/shared";+import {+ connectTcp,+ connectViaProxy,+ SocketReader,+} from "@pi-desktop/agent-runtime/proxy-tunnel";++const MAX_PROXY_RESOLUTION_LENGTH = 8_192;++export type SystemProxyRelay = {+ url: string;+ close(): Promise<void>;+};++type ProxyRoute = { kind: "direct" } | { kind: "proxy"; proxy: ParsedProxyUrl };++/**+ * Resolve each destination through Electron's active system/PAC configuration,+ * then tunnel the connection through that route. The listener is loopback-only+ * and requires a per-process SOCKS credential before it will resolve a route.+ */+export async function startSystemProxyRelay(+ resolveProxy: (url: string) => Promise<string>,+): Promise<SystemProxyRelay> {+ const password = randomBytes(32).toString("hex");+ const clients = new Set<Socket>();+ const server = createServer((client) => {+ clients.add(client);+ const forget = () => clients.delete(client);+ client.once("close", forget);+ client.once("error", forget);+ void handleClient(client, password, resolveProxy);+ });+ server.on("error", (error) => {+ process.stderr.write(+ `[system-proxy-relay] listener error: ${error.message}\n`,+ );+ });++ const port = await listenLoopback(server);+ return {+ url: `socks5://system-auto:${password}@127.0.0.1:${port}`,+ close: () =>+ new Promise((resolve) => {+ for (const client of clients) client.destroy();+ clients.clear();+ if (!server.listening) {+ resolve();+ return;+ }+ server.close(() => resolve());+ }),+ };+}++function listenLoopback(server: Server): Promise<number> {+ return new Promise((resolve, reject) => {+ const onError = (error: Error) => {+ server.off("error", onError);+ reject(error);+ };+ server.once("error", onError);+ server.listen(0, "127.0.0.1", () => {+ server.off("error", onError);+ const address = server.address();+ if (!address || typeof address === "string") {+ server.close();+ reject(new Error("system proxy relay did not bind a TCP port"));+ return;+ }+ resolve(address.port);+ });+ });+}++async function handleClient(+ client: Socket,+ expectedPassword: string,+ resolveProxy: (url: string) => Promise<string>,+): Promise<void> {+ const reader = new SocketReader(client);+ try {+ const { host, port, scheme } = await acceptAuthenticatedConnect(+ reader,+ client,+ expectedPassword,+ );+ const destination = new URL(`${scheme}://${formatHost(host)}:${port}/`);+ const resolution = await resolveProxy(destination.href);+ const remote = await connectByResolvedRoute(+ parseProxyRoutes(resolution),+ host,+ port,+ );+ reader.dispose();+ client.write(Buffer.from([0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0, 0]));+ pipeSockets(client, remote);+ } catch {+ reader.dispose();+ if (!client.destroyed) {+ try {+ client.write(+ Buffer.from([0x05, 0x01, 0x00, 0x01, 0, 0, 0, 0, 0, 0]),+ );+ } catch {+ // The client may have closed while the route was being resolved.+ }+ client.destroy();+ }+ }+}++async function acceptAuthenticatedConnect(+ reader: SocketReader,+ client: Socket,+ expectedPassword: string,+): Promise<{ host: string; port: number; scheme: "http" | "https" }> {+ const hello = await reader.readExact(2);+ if (hello[0] !== 0x05 || hello[1] === 0) {+ throw new Error("invalid SOCKS5 greeting");+ }+ const methods = await reader.readExact(hello[1]);+ if (!methods.includes(0x02)) {+ client.write(Buffer.from([0x05, 0xff]));+ throw new Error("SOCKS5 authentication is required");+ }+ client.write(Buffer.from([0x05, 0x02]));++ const auth = await reader.readExact(2);+ if (auth[0] !== 0x01 || auth[1] === 0) {+ throw new Error("invalid SOCKS5 authentication frame");+ }+ const usernameBytes = await reader.readExact(auth[1]);+ const passwordLength = await reader.readExact(1);+ if (passwordLength[0] === 0) throw new Error("empty SOCKS5 password");+ const passwordBytes = await reader.readExact(passwordLength[0]);+ const username = usernameBytes.toString("utf8");+ const suppliedPassword = passwordBytes.toString("utf8");+ const passwordMatches = secureEqual(suppliedPassword, expectedPassword);+ const usernameAllowed =+ username === "system-auto" ||+ username === "system-http" ||+ username === "system-https";+ client.write(Buffer.from([0x01, passwordMatches && usernameAllowed ? 0x00 : 0x01]));+ if (!passwordMatches || !usernameAllowed) {+ throw new Error("SOCKS5 authentication failed");+ }++ const header = await reader.readExact(4);+ if (header[0] !== 0x05 || header[1] !== 0x01) {+ throw new Error("only SOCKS5 CONNECT is supported");+ }+ const host = await readSocksAddress(reader, header[3]);+ const portBytes = await reader.readExact(2);+ const port = portBytes.readUInt16BE(0);+ if (port === 0) throw new Error("invalid SOCKS5 destination port");+ const scheme =+ username === "system-http" ||+ (username === "system-auto" && port === 80)+ ? "http"+ : "https";+ return { host, port, scheme };+}++function secureEqual(left: string, right: string): boolean {+ const leftBytes = Buffer.from(left, "utf8");+ const rightBytes = Buffer.from(right, "utf8");+ return (+ leftBytes.length === rightBytes.length &&+ timingSafeEqual(leftBytes, rightBytes)+ );+}++function formatHost(host: string): string {+ return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;+}++async function readSocksAddress(+ reader: SocketReader,+ addressType: number,+): Promise<string> {+ if (addressType === 0x01) {+ return [...(await reader.readExact(4))].join(".");+ }+ if (addressType === 0x03) {+ const length = await reader.readExact(1);+ return (await reader.readExact(length[0])).toString("utf8");+ }+ if (addressType === 0x04) {+ const bytes = await reader.readExact(16);+ const parts: string[] = [];+ for (let index = 0; index < 16; index += 2) {+ parts.push(bytes.readUInt16BE(index).toString(16));+ }+ return parts.join(":");+ }+ throw new Error("invalid SOCKS5 destination address type");+}++function parseProxyRoutes(value: string): ProxyRoute[] {+ if (value.length > MAX_PROXY_RESOLUTION_LENGTH) {+ throw new Error("system proxy resolution is too large");+ }+ const routes: ProxyRoute[] = [];+ for (const candidate of value.split(";")) {+ const [kind, endpoint] = candidate.trim().split(/\s+/, 2);+ if (!kind) continue;+ const normalized = kind.toUpperCase();+ if (normalized === "DIRECT") {+ routes.push({ kind: "direct" });+ continue;+ }+ const scheme =+ normalized === "PROXY" || normalized === "HTTP"+ ? "http"+ : normalized === "HTTPS"+ ? "https"+ : normalized === "SOCKS" || normalized === "SOCKS5"+ ? "socks5"+ : null;+ if (!scheme || !endpoint) continue;+ const parsed = parseProxyUrl(`${scheme}://${endpoint}`);+ if (parsed.ok) routes.push({ kind: "proxy", proxy: parsed.value });+ }+ if (routes.length === 0) throw new Error("system proxy returned no usable route");+ return routes;+}++async function connectByResolvedRoute(+ routes: ProxyRoute[],+ host: string,+ port: number,+): Promise<Socket> {+ let lastError: unknown;+ for (const route of routes) {+ try {+ return route.kind === "direct"+ ? await connectTcp(host, port)+ : await connectViaProxy(route.proxy, host, port);+ } catch (error) {+ if (isProxyPolicyRejection(error)) throw error;+ lastError = error;+ }+ }+ throw lastError instanceof Error+ ? lastError+ : new Error("system proxy routes could not connect");+}++function isProxyPolicyRejection(error: unknown): boolean {+ if (!(error instanceof Error)) return false;+ return (+ /HTTP proxy CONNECT failed \(HTTP\/\d(?:\.\d)?\s+4\d\d\b/i.test(+ error.message,+ ) || error.message === "SOCKS5: authentication failed"+ );+}++function pipeSockets(left: Socket, right: Socket): void {+ const closeBoth = () => {+ left.destroy();+ right.destroy();+ };+ left.once("error", closeBoth);+ right.once("error", closeBoth);+ left.once("close", () => right.destroy());+ right.once("close", () => left.destroy());+ left.pipe(right);+ right.pipe(left);+}diff --git a/crates/host-core/src/network_proxy.rs b/crates/host-core/src/network_proxy.rsindex d0a8cf061..7e41580f9 100644--- a/crates/host-core/src/network_proxy.rs+++ b/crates/host-core/src/network_proxy.rs@@ -15,6 +15,7 @@ pub enum ProxyMode {}static MARKET_PROXY: RwLock<ProxyMode> = RwLock::new(ProxyMode::System);+static SYSTEM_PROXY_RELAY: RwLock<Option<String>> = RwLock::new(None);/// Mirrors `DEFAULT_NETWORK_PROXY_BYPASS` in `packages/shared`: loopback plus/// the private ranges a user's own LAN devices live in, so a custom proxy never@@ -29,6 +30,38 @@ pub fn apply_from_settings(value: Option<&Value>) {}}+/// Configure Electron's ephemeral, loopback-only system/PAC proxy relay.+/// This value is runtime-only and is never copied into host-core's environment.+pub fn set_system_proxy_relay(value: &str) -> Result<(), String> {+ let value = value.trim();+ if value.len() > PROXY_URL_MAX {+ return Err("system proxy relay URL is too long".into());+ }+ let Some((credentials, address)) = value.split_once('@') else {+ return Err("system proxy relay URL must contain local credentials".into());+ };+ let Some(token) = credentials.strip_prefix("socks5://system-auto:") else {+ return Err("system proxy relay must use the internal SOCKS5 route".into());+ };+ if token.len() != 64 || !token.bytes().all(|byte| byte.is_ascii_hexdigit()) {+ return Err("system proxy relay credential is invalid".into());+ }+ let Some(port) = address.strip_prefix("127.0.0.1:") else {+ return Err("system proxy relay must bind to IPv4 loopback".into());+ };+ let port = port+ .parse::<u16>()+ .map_err(|_| "system proxy relay port is invalid")?;+ if port == 0 {+ return Err("system proxy relay port is invalid".into());+ }+ let mut slot = SYSTEM_PROXY_RELAY+ .write()+ .map_err(|_| "system proxy relay state unavailable")?;+ *slot = Some(value.to_string());+ Ok(())+}+pub fn proxy_from_settings(value: Option<&Value>) -> ProxyMode {let Some(object) = value.and_then(Value::as_object) else {return ProxyMode::System;@@ -126,15 +159,20 @@ pub fn parse_proxy_url(raw: &str) -> Result<String, String> {Ok(trimmed.to_string())}-/// Extra curl arguments so marketplace downloads honor Custom/Direct without-/// mutating host-core process env (Bash must not inherit proxy credentials).+/// Extra curl arguments so marketplace downloads honor the selected route+/// without mutating host-core process env (Bash must not inherit credentials).pub fn curl_proxy_args() -> Vec<String> {let mode = MARKET_PROXY.read().map(|guard| guard.clone()).unwrap_or_default();match mode {- ProxyMode::System => Vec::new(),+ ProxyMode::System => SYSTEM_PROXY_RELAY+ .read()+ .ok()+ .and_then(|guard| guard.clone())+ .map(|url| vec!["--proxy".into(), url.replacen("socks5://", "socks5h://", 1)])+ .unwrap_or_default(),ProxyMode::Direct => vec!["--noproxy".into(), "*".into()],ProxyMode::Custom { url, bypass } => {let noproxy = bypassdiff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rsindex 8d94653aa..04b36480a 100644--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@ -4842,6 +4842,15 @@ async fn handle_request(Ok(json!({ "id": id, "enabled": enabled }))}+ "network.configureSystemProxyRelay" => {+ let url = params+ .get("url")+ .and_then(Value::as_str)+ .ok_or_else(|| rpc_err(1002, "url required", "INVALID_PARAMS"))?;+ crate::network_proxy::set_system_proxy_relay(url)+ .map_err(|message| rpc_err(1002, message, "INVALID_PARAMS"))?;+ Ok(json!({ "ok": true }))+ }"market.refresh" => {let force = params.get("force")diff --git a/docs/adr/0177-user-configurable-outbound-proxy.md b/docs/adr/0177-user-configurable-outbound-proxy.mdindex 299b2b2c7..badb57bf9 100644--- a/docs/adr/0177-user-configurable-outbound-proxy.md+++ b/docs/adr/0177-user-configurable-outbound-proxy.md@@ -17,10 +17,11 @@ Outbound HTTP is split across processes:- Chromium sessions — default session, `persist:work-browser`, plugin panels- electron-updater — Chromium / Electron net-None of those surfaces honored a product setting. Users behind Clash, V2Ray,-corporate HTTP proxies, or SOCKS5 had working OS/TUN proxies for the in-app-browser but silent failures on model calls, because Node's `fetch` does not-use the system proxy.+Custom proxy settings already covered these surfaces, but System mode did not+reach Node provider calls or host-core marketplace downloads. Users behind+Clash, V2Ray, corporate HTTP proxies, or SOCKS5 could use the in-app browser+while model and plugin downloads failed because Node `fetch` and `curl` do not+resolve Electron's system proxy or PAC configuration.A single Settings control should apply one proxy to app-owned traffic.@@ -32,9 +33,13 @@ A single Settings control should apply one proxy to app-owned traffic.`AppSettings.networkProxy` in the existing host settings blob. No protocolor storage schema version bump.-2. **System** (default): Chromium `session.setProxy({ mode: "system" })`.- Node sidecar stays direct unless the process already inherited proxy env- from the launching shell. This preserves today's GUI-app behavior.+2. **System** (default): Chromium uses+ `session.setProxy({ mode: "system" })`. Electron main owns a loopback-only,+ authenticated SOCKS relay that calls `session.defaultSession.resolveProxy`+ for each destination and follows the returned proxy fallback list, including+ PAC decisions. The sidecar's undici dispatcher and host-core marketplace+ `curl` use that relay, so provider and marketplace requests follow the same+ OS proxy policy without putting proxy settings in a process environment.3. **Direct**: Chromium `{ mode: "direct" }`. Proxy env keys are cleared inElectron main. host-core marketplace curl uses `--noproxy '*'`.@@ -57,21 +62,25 @@ A single Settings control should apply one proxy to app-owned traffic.action (`pi-desktop/network/testProxy`) runs one bounded Chromium fetchthrough the supplied config and does not persist it.-7. **Secrets.** Proxy userinfo lives in the settings JSON next to other- non-API-key preferences. Logs redact passwords. host-core never- `set_var`s the URL onto its process env. Chromium `proxyRules` cannot+7. **Secrets.** Custom proxy userinfo lives in the settings JSON next to other+ non-API-key preferences. Logs redact passwords. System relay credentials+ are random, ephemeral, and accepted only on its loopback listener. host-core+ never `set_var`s proxy URLs onto its process env. Chromium `proxyRules` cannotinclude userinfo (it fails with `net::ERR_NO_SUPPORTED_PROXIES`) andcannot speak SOCKS5 username/password, so Electron main points Chromium- at a `127.0.0.1` SOCKS5 relay that injects the stored credentials- (issue #490). Node, undici, and curl keep the canonical URL with- userinfo.+ at a `127.0.0.1` SOCKS5 relay that injects stored custom credentials+ (issue #490). In System mode, the relay resolves the route through+ Electron for each destination and tries PAC fallbacks in order. No proxy+ credentials are inherited by workspace Bash.## Consequences-- LLM, marketplace, updates, and the in-app browser share one proxy.-- System mode does not magically make Node follow the macOS/Windows system- proxy; users who need model calls through Clash still choose Custom- (typically `http://127.0.0.1:7890` or `socks5://127.0.0.1:1080`).+- LLM, marketplace, updates, plugin `net.fetch`, and the in-app browser honor+ the selected route. System mode uses Electron's OS/PAC resolution for+ provider and marketplace requests as well as Chromium-owned requests.+- System proxies that require an interactive or OS-integrated authentication+ challenge are not answered by the raw socket relay; those requests fail+ closed. Users can use Custom mode when they have explicit proxy credentials.- Adding `undici` to the sidecar bundle keeps the dispatcher and `fetch`implementation on one package.diff --git a/docs/spec/03-runtime/07-process-model.md b/docs/spec/03-runtime/07-process-model.mdindex 972eca48b..f89357085 100644--- a/docs/spec/03-runtime/07-process-model.md+++ b/docs/spec/03-runtime/07-process-model.md@@ -74,16 +74,18 @@ ordered shutdown as the Quit menu item.After host-core is up, Electron main reads `AppSettings.networkProxy` andapplies it before spawning the agent sidecar (D340). Chromium sessions use-`session.setProxy`; main-process `fetch` is `net.fetch`; the sidecar receives-the same config through `sidecar.configure` and `PI_DESKTOP_PROXY_JSON`.-HTTP(S) provider requests use undici's proxy dispatcher; SOCKS5 provider-requests use a buffered CONNECT tunnel so a proxy may coalesce the SOCKS-handshake response without stalling the request. Custom URLs with userinfo-keep credentials for Node and curl; Chromium is pointed at a loopback SOCKS5-relay that injects them, because `proxyRules` cannot carry userinfo (issue-#490).-host-core marketplace `curl` gets `--proxy` from the stored settings and does-**not** inherit proxy env, so workspace Bash cannot see proxy credentials.+`session.setProxy`; main-process `fetch` is `net.fetch`. In System mode, the+sidecar provider dispatcher and host-core marketplace `curl` use an+authenticated, loopback-only SOCKS5 relay. Electron resolves each destination+with `session.defaultSession.resolveProxy`, including PAC rules and their+ordered fallbacks. The relay's random credential is runtime-only and is sent+over sidecar configuration / host RPC, never through process environment.+Custom URLs with userinfo keep credentials for Node and curl; Chromium is+pointed at a loopback SOCKS5 relay that injects them, because `proxyRules`+cannot carry userinfo (issue #490). host-core marketplace `curl` gets explicit+proxy arguments and does **not** inherit proxy env, so workspace Bash cannot+see proxy credentials. Direct mode bypasses the System relay. TLS certificate+verification remains enabled on every route.Marketplace curl diagnostics prefer UTF-8 and fall back to the active WindowsANSI code page before crossing the UTF-8 RPC boundary, so localized Schannelerrors remain readable instead of becoming replacement characters.diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex a8508fce2..1705037c9 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -13032,7 +13032,9 @@ are withdrawn with ADR 0165.- **Preconditions**: A reachable local HTTP or SOCKS5 proxy, or a known-badport for the failure path. A configured provider/model whose endpoint is- reachable through the proxy is available for the model-request step.+ reachable through the proxy is available for the model-request step. For+ System mode, the OS has a local system proxy or PAC fixture with a capture+ endpoint and a direct fallback route.- **Steps**:1. Open Settings → General. Confirm a Network card with Proxy modesSystem, Direct, and Custom. System is selected on a profile that never@@ -13056,12 +13058,18 @@ are withdrawn with ADR 0165.TCP chunk. Confirm a subsequent marketplace refresh and a models.devcatalog refresh use the proxy (host-core curl `--proxy`, Electron`net.fetch`), and confirm a loopback URL in Bypass is not proxied.- 6. Switch to Direct, then System. Confirm Chromium returns to- `mode: "direct"` then `mode: "system"`, and the sidecar is reconfigured- without an app restart.+ 6. Switch to Direct. Confirm Chromium returns to `mode: "direct"`, provider+ and marketplace traffic bypass the System relay, and workspace Bash does+ not inherit proxy variables from the setting.+ 7. Switch to System. Confirm Chromium returns to `mode: "system"` and send a+ provider request and marketplace refresh. Confirm both follow the OS/PAC+ route selected for each destination, including ordered proxy-to-direct+ fallback, without restarting the app.- **Expected**: Custom covers model calls, marketplace, updates, plugin- `net.fetch`, and the in-app browser. Workspace Bash `env` does not show- `HTTP_PROXY` / `ALL_PROXY` from the setting. OAuth still opens the system+ `net.fetch`, and the in-app browser. System covers provider and marketplace+ requests through Electron's OS/PAC resolver. Workspace Bash `env` does not+ show `HTTP_PROXY` / `ALL_PROXY` from the setting. TLS verification remains+ enabled on all routes. OAuth still opens the systembrowser. Invalid schemes (`file:`, `ftp:`, and SOCKS4) and malformedpercent-encoded credentials are rejected. Authenticated HTTP and SOCKS5URLs Test and apply without `net::ERR_NO_SUPPORTED_PROXIES` (issue #490).@@ -13070,11 +13078,13 @@ are withdrawn with ADR 0165.`03-runtime/07-process-model.md`, ADR 0177, D340- **Acceptance**: B (settings), F (providers), Security- **Milestone**: M5-- **Status**: Unit-covered (`network-proxy.test.ts`, `node-proxy.test.ts`,- `authenticated-proxy-relay.test.ts`, `settings-general.test.mjs`,- host-core `network_proxy` tests); malformed credentials and unsupported- SOCKS4 schemes are covered by the shared parser tests; full UI journey- Draft (run only in a capable environment when this surface changes)+- **Status**: Custom-path unit coverage exists (`network-proxy.test.ts`,+ `node-proxy.test.ts`, `authenticated-proxy-relay.test.ts`,+ `settings-general.test.mjs`, host-core `network_proxy` tests); malformed+ credentials and unsupported SOCKS4 schemes are covered by shared parser+ tests. The System/PAC relay path does not yet have automated regression+ coverage. Full UI journey Draft (run only in a capable environment when+ this surface changes).#### E2E-191: Newly emitted AppError codes stay registereddiff --git a/docs/spec/07-plugins/07-plugin-marketplace.md b/docs/spec/07-plugins/07-plugin-marketplace.mdindex 3ef461f6a..5959f6a70 100644--- a/docs/spec/07-plugins/07-plugin-marketplace.md+++ b/docs/spec/07-plugins/07-plugin-marketplace.md@@ -57,6 +57,13 @@ still means CNB, so no persisted setting is migrated. The environment override`PI_DESKTOP_PLUGIN_MARKET_URL` stays above every channel so dev builds andtests can point at a local catalog without touching persisted settings.+Marketplace catalog and package downloads follow Settings → General → Network.+System mode sends host-core `curl` through Electron's authenticated loopback+SOCKS relay, which resolves each destination using the active OS proxy/PAC+configuration. Direct mode forces the marketplace request direct; Custom uses+the configured proxy and bypass list. The relay credential is runtime-only and+is not inherited by workspace shell commands.+The official channel is the plugin center: its catalog is the generated`catalog.json` the center publishes, and a package installed from it isresolved through the platform's download API instead of by joining a relativediff --git a/packages/agent-runtime/src/node-proxy.ts b/packages/agent-runtime/src/node-proxy.tsindex 882c77f16..e7145b5a6 100644--- a/packages/agent-runtime/src/node-proxy.ts+++ b/packages/agent-runtime/src/node-proxy.ts@@ -56,11 +56,13 @@ let activeDirectDispatcher: Dispatcher | null = null;export type NodeTransportRoute =| "direct"| "environment-proxy"+ | "system-proxy"| "http-proxy"| "socks5-proxy";/** Settings behind the installed pair, so a rebuild reproduces exactly them. */let activeCustomSettings: NetworkProxySettings | null = null;+let activeSystemProxyRelayUrl: string | null = null;/** Negative infinity: a process that has never rebuilt is never throttled. */let lastTransportRebuildAt = Number.NEGATIVE_INFINITY;@@ -79,9 +81,8 @@ function routeForSettings(settings: NetworkProxySettings): NodeTransportRoute {* identical in an errno (issue #234).*/export function activeNodeTransportRoute(): NodeTransportRoute {- return activeCustomSettings- ? routeForSettings(activeCustomSettings)- : defaultRoute();+ if (activeCustomSettings) return routeForSettings(activeCustomSettings);+ return activeSystemProxyRelayUrl ? "system-proxy" : defaultRoute();}function ensurePatched(): void {@@ -117,13 +118,25 @@ function restoreDefault(): void {export function applyNodeNetworkProxy(settings: NetworkProxySettings,env: Record<string, string | undefined> = process.env,+ systemProxyRelayUrl?: string,): void {ensurePatched();applyProxyEnvAssignments(proxyEnvAssignments(settings), env);if (settings.mode !== "custom") {+ activeSystemProxyRelayUrl = null;+ if (settings.mode === "system" && systemProxyRelayUrl) {+ const built = createSystemProxyDispatcher(systemProxyRelayUrl);+ if (built) {+ installCustomProxyDispatchers(built);+ activeCustomSettings = null;+ activeSystemProxyRelayUrl = systemProxyRelayUrl;+ return;+ }+ }restoreDefault();return;}+ activeSystemProxyRelayUrl = null;const built = createCustomProxyDispatchers(settings);if (!built) {restoreDefault();@@ -165,6 +178,22 @@ function createCustomProxyDispatchers(};}+/** Build an authenticated SOCKS dispatcher backed by Electron's system/PAC resolver. */+function createSystemProxyDispatcher(+ relayUrl: string,+): CustomProxyDispatchers | null {+ const parsed = parseProxyUrl(relayUrl);+ if (!parsed.ok || !parsed.value.isSocks) return null;+ const dispatcher: Dispatcher = new Agent({+ connect: socksConnector(parsed.value, true),+ });+ return {+ dispatcher,+ direct: new Agent(),+ route: "system-proxy",+ };+}+/*** Install a freshly built pair and retire the previous one.*@@ -229,7 +258,9 @@ export function rebuildNodeNetworkTransport(const customSettings = activeCustomSettings;const rebuilt = customSettings? createCustomProxyDispatchers(customSettings)- : null;+ : activeSystemProxyRelayUrl+ ? createSystemProxyDispatcher(activeSystemProxyRelayUrl)+ : null;if (rebuilt) {installCustomProxyDispatchers(rebuilt);return { rebuilt: true, route: rebuilt.route };@@ -368,11 +399,20 @@ export function proxyBypassMatcher(bypass: string): ProxyBypassMatcher {};}-function socksConnector(proxy: ParsedProxyUrl): buildConnector.connector {+function socksConnector(+ proxy: ParsedProxyUrl,+ relayResolvesSystemRoute = false,+): buildConnector.connector {return (options, callback) => {const hostname = options.hostname || options.host || "";const port = Number(options.port) || (options.protocol === "http:" ? 80 : 443);- void socks5Connect(proxy, hostname, port)+ const auth = relayResolvesSystemRoute+ ? {+ username: `system-${options.protocol === "https:" ? "https" : "http"}`,+ password: proxy.password,+ }+ : undefined;+ void socks5Connect(proxy, hostname, port, auth).then((socket) => {if (options.protocol === "https:") {const tlsSocket = tlsConnect({@@ -390,4 +430,3 @@ function socksConnector(proxy: ParsedProxyUrl): buildConnector.connector {.catch((error: Error) => callback(error, null));};}-diff --git a/packages/agent-runtime/src/sidecar.ts b/packages/agent-runtime/src/sidecar.tsindex cb40b97fc..7b10e4352 100644--- a/packages/agent-runtime/src/sidecar.ts+++ b/packages/agent-runtime/src/sidecar.ts@@ -371,7 +371,13 @@ async function handle(method: string, params: any): Promise<unknown> {case "sidecar.configure": {// Main owns host-core; sidecar only keeps config metadata.if (params && typeof params === "object" && "networkProxy" in params) {- applyNodeNetworkProxy(normalizeNetworkProxy(params.networkProxy));+ applyNodeNetworkProxy(+ normalizeNetworkProxy(params.networkProxy),+ process.env,+ typeof params.systemProxyRelayUrl === "string"+ ? params.systemProxyRelayUrl+ : undefined,+ );}return { ok: true, mode: "host-proxy" };}diff --git a/packages/agent-runtime/src/socks5.ts b/packages/agent-runtime/src/socks5.tsindex 6c7367c4b..3e67bee12 100644--- a/packages/agent-runtime/src/socks5.ts+++ b/packages/agent-runtime/src/socks5.ts@@ -33,12 +33,15 @@ export async function socks5Connect(proxy: ParsedProxyUrl,destHost: string,destPort: number,+ auth?: { username: string; password: string },): Promise<Socket> {const socket = await connectTcp(proxy.host, proxyListenPort(proxy));const reader = new SocketReader(socket);try {+ const username = auth?.username ?? proxy.username;+ const password = auth?.password ?? proxy.password;const methods =- proxy.username || proxy.password+ username || password? Buffer.from([0x05, 0x02, 0x00, 0x02]): Buffer.from([0x05, 0x01, 0x00]);socket.write(methods);@@ -47,8 +50,8 @@ export async function socks5Connect(throw new Error("SOCKS5: invalid version");}if (choice[1] === 0x02) {- const user = Buffer.from(proxy.username ?? "", "utf8");- const pass = Buffer.from(proxy.password ?? "", "utf8");+ const user = Buffer.from(username, "utf8");+ const pass = Buffer.from(password, "utf8");if (user.length > 255 || pass.length > 255) {throw new Error("SOCKS5: credentials too long");}