diff --git a/internal/multiagent/pi_integration_test.go b/internal/multiagent/pi_integration_test.go index 7804d142..6b5bfc87 100644 --- a/internal/multiagent/pi_integration_test.go +++ b/internal/multiagent/pi_integration_test.go @@ -820,12 +820,17 @@ func TestPiReportsIncompleteModelStreamRetries(t *testing.T) { } func TestPiTransportFailureClassifiesTLSHandshakeReset(t *testing.T) { - err := fmt.Errorf("Pi runtime error: Connection error.: Client network socket disconnected before secure TLS connection was established (ECONNRESET)") + err := fmt.Errorf("Pi runtime error: Connection error.: Client network socket disconnected before secure TLS connection was established (ECONNRESET) [endpoint=api.openai.com, route=direct]") fields := ClientRunErrorFields(err) if fields["errorKind"] != "model_transient" || fields["reasonCode"] != "model_tls_reset" { t.Fatalf("unexpected error fields: %+v", fields) } - if msg := ClientRunErrorMessage(err); !strings.Contains(msg, "TLS") { - t.Fatalf("expected localized TLS error message, got %q", msg) + msg := ClientRunErrorMessage(err) + if !strings.Contains(msg, "TLS") || !strings.Contains(msg, "api.openai.com") || !strings.Contains(msg, "直连未走代理") { + t.Fatalf("expected localized TLS error message with endpoint and route hint, got %q", msg) + } + proxied := ClientRunErrorMessage(fmt.Errorf("Pi runtime error: Connection error.: Client network socket disconnected before secure TLS connection was established [endpoint=api.example.com:8443, route=proxy http://127.0.0.1:7890]")) + if !strings.Contains(proxied, "api.example.com:8443") || !strings.Contains(proxied, "http://127.0.0.1:7890") { + t.Fatalf("expected proxied route hint, got %q", proxied) } } diff --git a/internal/multiagent/runtime_errors.go b/internal/multiagent/runtime_errors.go index 08ab3aab..0b100427 100644 --- a/internal/multiagent/runtime_errors.go +++ b/internal/multiagent/runtime_errors.go @@ -4,7 +4,9 @@ import ( "context" "cyberstrike-ai/internal/config" "errors" + "fmt" "math/rand/v2" + "regexp" "strings" "time" ) @@ -12,6 +14,29 @@ import ( const defaultRunRetryMaxBackoff = 30 * time.Second const modelOutputRecoveryKey = "_cyberstrike_model_output_recovery" +var modelRouteTagPattern = regexp.MustCompile(`(?i)\[endpoint=([^,\]]+),\s*route=([^\]]+)\]`) + +func formatModelEndpointHint(raw string) string { + m := modelRouteTagPattern.FindStringSubmatch(raw) + if len(m) != 3 { + return "" + } + endpoint := strings.TrimSpace(m[1]) + route := strings.TrimSpace(m[2]) + if endpoint == "" { + return "" + } + lowerRoute := strings.ToLower(route) + switch { + case lowerRoute == "direct": + return fmt.Sprintf("(%s,当前直连未走代理)", endpoint) + case strings.HasPrefix(lowerRoute, "proxy "): + return fmt.Sprintf("(%s,经代理 %s)", endpoint, strings.TrimSpace(route[len("proxy "):])) + default: + return fmt.Sprintf("(%s)", endpoint) + } +} + func transientRetryBackoff(attempt int, maxBackoff time.Duration) time.Duration { if attempt < 0 { attempt = 0 @@ -42,26 +67,27 @@ func ClientRunErrorMessage(err error) string { func piModelTransportFailure(raw string) (code, detail string) { text := strings.ToLower(raw) + hint := formatModelEndpointHint(raw) switch { case strings.Contains(text, "und_err_headers_timeout"): - return "model_headers_timeout", "等待模型服务响应头超时" + return "model_headers_timeout", "等待模型服务" + hint + "响应头超时" case strings.Contains(text, "und_err_body_timeout"): - return "model_stream_timeout", "模型响应流长时间未收到新数据" + return "model_stream_timeout", "模型" + hint + "响应流长时间未收到新数据" case strings.Contains(text, "stream ended without finish_reason"): - return "model_stream_incomplete", "模型响应流提前关闭,未收到结束标记" + return "model_stream_incomplete", "模型" + hint + "响应流提前关闭,未收到结束标记" case strings.Contains(text, "before secure tls connection was established") || strings.Contains(text, "tls handshake"): - return "model_tls_reset", "与模型服务的 TLS 握手中断,连接被重置" + return "model_tls_reset", "与模型服务" + hint + "的 TLS 握手中断,连接被重置" case strings.Contains(text, "und_err_connect_timeout") || strings.Contains(text, "connecttimeouterror") || strings.Contains(text, "etimedout"): - return "model_connect_timeout", "连接模型服务超时" + return "model_connect_timeout", "连接模型服务" + hint + "超时" case strings.Contains(text, "econnrefused") || strings.Contains(text, "connection refused"): - return "model_connection_refused", "模型服务拒绝连接" + return "model_connection_refused", "模型服务" + hint + "拒绝连接" case strings.Contains(text, "eai_again") || strings.Contains(text, "getaddrinfo"): - return "model_dns_failure", "模型服务域名解析暂时失败" + return "model_dns_failure", "模型服务" + hint + "域名解析暂时失败" case strings.Contains(text, "econnreset") || strings.Contains(text, "econnaborted") || strings.Contains(text, "connection reset") || strings.Contains(text, "socket disconnected") || strings.Contains(text, "socket hang up") || strings.Contains(text, "other side closed") || strings.Contains(text, "und_err_socket") || strings.Contains(text, "connection error"): - return "model_connection_reset", "与模型服务的网络连接中断" + return "model_connection_reset", "与模型服务" + hint + "的网络连接中断" default: return "", "" } diff --git a/runtime/pi/src/network.ts b/runtime/pi/src/network.ts index e6a50aae..70048c35 100644 --- a/runtime/pi/src/network.ts +++ b/runtime/pi/src/network.ts @@ -1,18 +1,202 @@ +import { execFileSync } from "node:child_process"; import { EventEmitter } from "node:events"; +import { isIP } from "node:net"; import { Client, EnvHttpProxyAgent, Pool, install, setGlobalDispatcher, type Dispatcher } from "undici"; // Model credentials may use arbitrary custom header names. Fetch's default // redirect handling only protects selected standard headers, so the isolated // worker follows redirects explicitly and only within the original origin. const redirects = new Set([301, 302, 303, 307, 308]); -const PRE_TLS_RETRY_DELAYS_MS = [200, 600]; +const PRE_TLS_RETRY_DELAYS_MS = [150, 350, 600]; const AUTO_SELECT_FAMILY_TIMEOUT_MS = 2_000; +const CONNECT_TIMEOUT_MS = 20_000; +// OpenSSL 3.5+/4.x sends a >1.6KB post-quantum (X25519MLKEM768) TLS 1.3 ClientHello +// that fragments across TCP segments and triggers deterministic ECONNRESET on many +// middleboxes, SNI routers, SLBs, and proxy tunnels. Classic ECDH curves keep the +// ClientHello ~386B in a single TCP segment. +const CLASSIC_ECDH_CURVES = "X25519:prime256v1:secp384r1"; + +interface ProxySettings { + httpProxy?: string; + httpsProxy?: string; + noProxy?: string; + source: "env" | "os" | "none"; +} + +interface TransportProfile { + id: "default" | "ipv4-h2" | "ipv4-tls12" | "os-proxy"; + allowH2: boolean; + ipv4Only: boolean; + tls12Compat: boolean; + disableSessionReuse: boolean; + useOsProxy?: boolean; +} + +const BASE_PROFILES: readonly TransportProfile[] = [ + { id: "default", allowH2: false, ipv4Only: false, tls12Compat: false, disableSessionReuse: false }, + { id: "ipv4-h2", allowH2: true, ipv4Only: true, tls12Compat: false, disableSessionReuse: true }, + { id: "ipv4-tls12", allowH2: false, ipv4Only: true, tls12Compat: true, disableSessionReuse: true }, +]; + +const OS_PROXY_PROFILE: TransportProfile = { + id: "os-proxy", + allowH2: false, + ipv4Only: false, + tls12Compat: false, + disableSessionReuse: true, + useOsProxy: true, +}; + +const dispatcherCache = new Map(); +const preferredProfileByOrigin = new Map(); +let cachedOsProxy: { expiresAt: number; value: ProxySettings | undefined } | undefined; function blocked(message: string): Response { return new Response(JSON.stringify({ error: { type: "invalid_request_error", message: "Local model transport: " + message } }), { status: 400, headers: { "Content-Type": "application/json" } }); } +export function normalizeProxyUrl(raw: string | undefined, defaultScheme = "http"): string | undefined { + const trimmed = raw?.trim(); + if (!trimmed) return undefined; + let candidate = trimmed; + if (/^socks5h:\/\//i.test(candidate)) { + candidate = "socks5://" + candidate.slice("socks5h://".length); + } else if (/^socks4a?:\/\//i.test(candidate)) { + candidate = "socks://" + candidate.replace(/^socks4a?:\/\//i, ""); + } else if (!/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(candidate)) { + candidate = `${defaultScheme}://${candidate}`; + } + if (!URL.canParse(candidate)) return undefined; + const parsed = new URL(candidate); + if (parsed.protocol !== "http:" && parsed.protocol !== "https:" && parsed.protocol !== "socks5:" && parsed.protocol !== "socks:") { + return undefined; + } + return candidate; +} + +export function resolveEnvProxySettings(env: NodeJS.ProcessEnv = process.env): ProxySettings { + const allProxy = normalizeProxyUrl(env.all_proxy ?? env.ALL_PROXY); + const httpProxy = normalizeProxyUrl(env.http_proxy ?? env.HTTP_PROXY) ?? allProxy; + const httpsProxy = normalizeProxyUrl(env.https_proxy ?? env.HTTPS_PROXY) ?? httpProxy ?? allProxy; + const noProxy = env.no_proxy ?? env.NO_PROXY; + return { + httpProxy, + httpsProxy, + noProxy, + source: httpProxy || httpsProxy ? "env" : "none", + }; +} + +export function isLoopbackOrPrivateHost(rawHostname: string): boolean { + const host = rawHostname.replace(/^\[(.+)\]$/, "$1").replace(/\.$/, "").toLowerCase(); + if (!host || host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal")) { + return true; + } + const family = isIP(host); + if (family === 4) { + const parts = host.split(".").map(Number); + if (parts[0] === 127 || parts[0] === 10 || parts[0] === 0) return true; + if (parts[0] === 169 && parts[1] === 254) return true; + if (parts[0] === 192 && parts[1] === 168) return true; + if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) return true; + return false; + } + if (family === 6) { + return host === "::1" || host === "::" || host.startsWith("fc") || host.startsWith("fd") || host.startsWith("fe80:"); + } + return false; +} + +export function parseDarwinScutilProxy(output: string): ProxySettings | undefined { + const field = (name: string): string | undefined => { + const match = output.match(new RegExp(`^\\s*${name}\\s*:\\s*(.+?)\\s*$`, "m")); + return match?.[1]?.trim(); + }; + let httpProxy: string | undefined; + let httpsProxy: string | undefined; + if (field("HTTPEnable") === "1" && field("HTTPProxy")) { + const port = field("HTTPPort") || "80"; + httpProxy = normalizeProxyUrl(`${field("HTTPProxy")}:${port}`, "http"); + } + if (field("HTTPSEnable") === "1" && field("HTTPSProxy")) { + const port = field("HTTPSPort") || "443"; + httpsProxy = normalizeProxyUrl(`${field("HTTPSProxy")}:${port}`, "http"); + } + if (!httpProxy && !httpsProxy && field("SOCKSEnable") === "1" && field("SOCKSProxy")) { + const port = field("SOCKSPort") || "1080"; + const socks = normalizeProxyUrl(`socks5://${field("SOCKSProxy")}:${port}`); + httpProxy = socks; + httpsProxy = socks; + } + if (!httpProxy && !httpsProxy) return undefined; + return { httpProxy: httpProxy ?? httpsProxy, httpsProxy: httpsProxy ?? httpProxy, source: "os" }; +} + +export function parseWindowsRegProxy(output: string): ProxySettings | undefined { + const enabledMatch = output.match(/^\s*ProxyEnable\s+REG_DWORD\s+(0x[0-9a-fA-F]+|\d+)\s*$/m); + if (!enabledMatch || Number(enabledMatch[1]) !== 1) return undefined; + const serverMatch = output.match(/^\s*ProxyServer\s+REG_SZ\s+(.+?)\s*$/m); + const rawServer = serverMatch?.[1]?.trim(); + if (!rawServer) return undefined; + let httpProxy: string | undefined; + let httpsProxy: string | undefined; + let socksProxy: string | undefined; + if (rawServer.includes("=")) { + for (const part of rawServer.split(";")) { + const [k, v] = part.split("=", 2).map(s => s?.trim()); + if (!k || !v) continue; + const lower = k.toLowerCase(); + if (lower === "http") httpProxy = normalizeProxyUrl(v, "http"); + else if (lower === "https") httpsProxy = normalizeProxyUrl(v, "http"); + else if (lower === "socks") socksProxy = normalizeProxyUrl(v, "socks5"); + } + } else { + httpProxy = normalizeProxyUrl(rawServer, "http"); + httpsProxy = httpProxy; + } + httpProxy = httpProxy ?? httpsProxy ?? socksProxy; + httpsProxy = httpsProxy ?? httpProxy ?? socksProxy; + if (!httpProxy && !httpsProxy) return undefined; + const overrideMatch = output.match(/^\s*ProxyOverride\s+REG_SZ\s+(.+?)\s*$/m); + const noProxy = overrideMatch?.[1] + ?.split(";") + .map(s => s.trim()) + .filter(s => s && s.toLowerCase() !== "" && !s.includes("*")) + .join(","); + return { httpProxy, httpsProxy, noProxy: noProxy || undefined, source: "os" }; +} + +function readOsSystemProxy(): ProxySettings | undefined { + const override = process.env.CYBERSTRIKE_OS_SYSTEM_PROXY_OVERRIDE; + if (override !== undefined) { + const normalized = normalizeProxyUrl(override); + return normalized ? { httpProxy: normalized, httpsProxy: normalized, source: "os" } : undefined; + } + if (process.env.CYBERSTRIKE_DISABLE_OS_PROXY === "1") return undefined; + const now = Date.now(); + if (cachedOsProxy && now < cachedOsProxy.expiresAt) return cachedOsProxy.value; + let detected: ProxySettings | undefined; + try { + if (process.platform === "darwin") { + const out = execFileSync("scutil", ["--proxy"], { encoding: "utf8", timeout: 1_500, stdio: ["ignore", "pipe", "ignore"] }); + detected = parseDarwinScutilProxy(out); + } else if (process.platform === "win32") { + const out = execFileSync("reg", ["query", "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"], { + encoding: "utf8", + timeout: 1_500, + stdio: ["ignore", "pipe", "ignore"], + windowsHide: true, + }); + detected = parseWindowsRegProxy(out); + } + } catch { + detected = undefined; + } + cachedOsProxy = { expiresAt: now + 30_000, value: detected }; + return detected; +} + // Only retry errors that provably occurred before TLS handshake completion or // TCP/CONNECT tunnel setup, where zero HTTP request bytes reached the origin. export function isPreResponseConnectError(error: unknown): boolean { @@ -30,6 +214,7 @@ export function isPreResponseConnectError(error: unknown): boolean { if ( message.includes("before secure tls connection was established") || message.includes("tls handshake") || + message.includes("ssl routines") || message.includes("reset before headers") || message.includes("upstream connect") || code === "und_err_connect_timeout" || @@ -64,6 +249,141 @@ function abortableDelay(ms: number, signal?: AbortSignal | null): Promise }); } +const ignoreUndiciDispatcherError = () => {}; + +function withUndiciErrorListener(dispatcher: T): T { + if (dispatcher instanceof EventEmitter) { + EventEmitter.prototype.on.call(dispatcher, "error", ignoreUndiciDispatcherError); + } + return dispatcher; +} + +function createUndiciClient(origin: URL | string, options: Client.Options): Dispatcher { + return withUndiciErrorListener(new Client(origin, options)); +} + +function createUndiciOriginDispatcher(origin: URL | string, options: Pool.Options): Dispatcher { + if (options.connections === 1) { + return createUndiciClient(origin, options); + } + return withUndiciErrorListener(new Pool(origin, { + ...options, + factory: createUndiciClient, + })); +} + +function getDispatcherForProfile(profile: TransportProfile, proxy: ProxySettings): Dispatcher { + const key = `${profile.id}|${proxy.httpProxy ?? ""}|${proxy.httpsProxy ?? ""}|${proxy.noProxy ?? ""}`; + const existing = dispatcherCache.get(key); + if (existing) return existing; + + const directConnectOpts = { + autoSelectFamilyAttemptTimeout: AUTO_SELECT_FAMILY_TIMEOUT_MS, + ecdhCurve: CLASSIC_ECDH_CURVES, + ...(profile.ipv4Only ? { family: 4, autoSelectFamily: false } : {}), + ...(profile.allowH2 ? { preferH2: true } : {}), + ...(profile.tls12Compat ? { maxVersion: "TLSv1.2" as const, ciphers: "DEFAULT:@SECLEVEL=1" } : {}), + ...(profile.disableSessionReuse ? { maxCachedSessions: 0 } : {}), + }; + + // Used by ProxyAgent / Socks5ProxyAgent when upgrading a tunnel socket to TLS. + const requestTlsOpts = { + ecdhCurve: CLASSIC_ECDH_CURVES, + ALPNProtocols: profile.allowH2 ? ["h2", "http/1.1"] : ["http/1.1"], + ...(profile.allowH2 ? { preferH2: true } : {}), + ...(profile.tls12Compat ? { maxVersion: "TLSv1.2" as const, ciphers: "DEFAULT:@SECLEVEL=1" } : {}), + ...(profile.disableSessionReuse ? { maxCachedSessions: 0 } : {}), + } as unknown as EnvHttpProxyAgent.Options["requestTls"]; + + // Never set proxyTls unless the proxy itself uses https://. Undici's Socks5ProxyAgent + // treats any truthy proxyTls object as "connect to the SOCKS5 proxy over TLS". + const usesHttpsProxyServer = Boolean( + proxy.httpProxy?.toLowerCase().startsWith("https://") || + proxy.httpsProxy?.toLowerCase().startsWith("https://"), + ); + const proxyTlsOpts = usesHttpsProxyServer + ? ({ autoSelectFamilyAttemptTimeout: AUTO_SELECT_FAMILY_TIMEOUT_MS, ecdhCurve: CLASSIC_ECDH_CURVES } as unknown as EnvHttpProxyAgent.Options["proxyTls"]) + : undefined; + + const created = withUndiciErrorListener(new EnvHttpProxyAgent({ + allowH2: profile.allowH2, + proxyTunnel: true, + connectTimeout: CONNECT_TIMEOUT_MS, + headersTimeout: 300_000, + bodyTimeout: 300_000, + httpProxy: proxy.httpProxy, + httpsProxy: proxy.httpsProxy, + ...(proxy.noProxy !== undefined ? { noProxy: proxy.noProxy } : {}), + connect: directConnectOpts as unknown as EnvHttpProxyAgent.Options["connect"], + requestTls: requestTlsOpts, + ...(proxyTlsOpts ? { proxyTls: proxyTlsOpts } : {}), + clientFactory: (origin, opts) => createUndiciOriginDispatcher(origin, opts as Pool.Options), + factory: createUndiciOriginDispatcher, + })); + dispatcherCache.set(key, created); + return created; +} + +function matchesNoProxy(hostname: string, port: number, noProxy?: string): boolean { + if (!noProxy?.trim()) return false; + const host = hostname.replace(/^\[(.+)\]$/, "$1").replace(/\.$/, "").toLowerCase(); + for (const raw of noProxy.split(/[,\s]+/)) { + if (!raw) continue; + if (raw === "*") return true; + const m = raw.match(/^\*?\.?([^:]+?)(?::(\d+))?$/); + if (!m) continue; + const entryHost = m[1].replace(/\.$/, "").toLowerCase(); + const entryPort = m[2] ? Number(m[2]) : 0; + if (entryPort && entryPort !== port) continue; + if (!raw.startsWith("*.") && host === entryHost) return true; + if (host.endsWith("." + entryHost)) return true; + } + return false; +} + +function describeRoute(target: URL, proxy: ProxySettings): string { + const defaultPort = target.protocol === "https:" ? 443 : 80; + if (matchesNoProxy(target.hostname, Number(target.port) || defaultPort, proxy.noProxy)) { + return "direct"; + } + const chosen = target.protocol === "https:" ? proxy.httpsProxy : proxy.httpProxy; + if (!chosen) return "direct"; + try { + const parsed = new URL(chosen); + return `proxy ${parsed.protocol}//${parsed.host}`; + } catch { + return "proxy"; + } +} + +function annotateConnectError(error: unknown, target: URL, proxy: ProxySettings): unknown { + if (!(error instanceof Error)) return error; + const tag = `[endpoint=${target.host}, route=${describeRoute(target, proxy)}]`; + if (error.message.includes("[endpoint=")) return error; + const causeText = error.cause instanceof Error && error.cause.message && !error.message.includes(error.cause.message) + ? `: ${error.cause.message}` + : ""; + const wrapped = new Error(`${error.message}${causeText} ${tag}`, { cause: error }); + const code = (error as NodeJS.ErrnoException).code ?? (error.cause as NodeJS.ErrnoException | undefined)?.code; + if (code) (wrapped as NodeJS.ErrnoException).code = code; + return wrapped; +} + +function candidateStages(url: URL, envProxy: ProxySettings): { profile: TransportProfile; proxy: ProxySettings }[] { + const stages: { profile: TransportProfile; proxy: ProxySettings }[] = BASE_PROFILES.map(profile => ({ profile, proxy: envProxy })); + if (envProxy.source === "none" && !isLoopbackOrPrivateHost(url.hostname)) { + const osProxy = readOsSystemProxy(); + if (osProxy) { + stages.push({ profile: OS_PROXY_PROFILE, proxy: osProxy }); + } + } + const preferred = preferredProfileByOrigin.get(url.origin); + if (!preferred) return stages; + const idx = stages.findIndex(s => s.profile.id === preferred); + if (idx <= 0) return stages; + return [stages[idx], ...stages.slice(0, idx), ...stages.slice(idx + 1)]; +} + async function fetchHop( upstreamFetch: typeof fetch, url: URL, @@ -72,8 +392,14 @@ async function fetchHop( body: ArrayBuffer | undefined, signal: AbortSignal | undefined, ): Promise { - for (let attempt = 0; ; attempt++) { + const envProxy = resolveEnvProxySettings(); + const stages = candidateStages(url, envProxy); + let lastProxy = envProxy; + for (let attempt = 0; attempt < stages.length; attempt++) { signal?.throwIfAborted?.(); + const { profile, proxy } = stages[attempt]; + lastProxy = proxy; + const dispatcher = getDispatcherForProfile(profile, proxy); const request = new Request(url, { method, headers, @@ -82,14 +408,23 @@ async function fetchHop( redirect: "manual", }); try { - return await upstreamFetch(request); + const response = await upstreamFetch(request, { dispatcher } as RequestInit); + if (profile.id !== "default") { + preferredProfileByOrigin.set(url.origin, profile.id); + } + return response; } catch (error) { - if (signal?.aborted || attempt >= PRE_TLS_RETRY_DELAYS_MS.length || !isPreResponseConnectError(error)) { + if (signal?.aborted || !isPreResponseConnectError(error)) { throw error; } - await abortableDelay(PRE_TLS_RETRY_DELAYS_MS[attempt], signal); + if (attempt >= stages.length - 1) { + throw annotateConnectError(error, url, lastProxy); + } + const delay = PRE_TLS_RETRY_DELAYS_MS[Math.min(attempt, PRE_TLS_RETRY_DELAYS_MS.length - 1)]; + await abortableDelay(delay, signal); } } + throw new Error(`Model connection failed [endpoint=${url.host}, route=${describeRoute(url, lastProxy)}]`); } async function modelFetch(upstreamFetch: typeof fetch, input: string | URL | Request, init?: RequestInit): Promise { @@ -118,43 +453,9 @@ async function modelFetch(upstreamFetch: typeof fetch, input: string | URL | Req return blocked("redirect limit exceeded"); } -const ignoreUndiciDispatcherError = () => {}; - -function withUndiciErrorListener(dispatcher: T): T { - if (dispatcher instanceof EventEmitter) { - EventEmitter.prototype.on.call(dispatcher, "error", ignoreUndiciDispatcherError); - } - return dispatcher; -} - -function createUndiciClient(origin: URL | string, options: Client.Options): Dispatcher { - return withUndiciErrorListener(new Client(origin, options)); -} - -function createUndiciOriginDispatcher(origin: URL | string, options: Pool.Options): Dispatcher { - if (options.connections === 1) { - return createUndiciClient(origin, options); - } - return withUndiciErrorListener(new Pool(origin, { - ...options, - factory: createUndiciClient, - })); -} - export function installModelFetchPolicy(): void { - const tlsConnectOpts = { autoSelectFamilyAttemptTimeout: AUTO_SELECT_FAMILY_TIMEOUT_MS }; - const proxyConnectorOpts = tlsConnectOpts as unknown as EnvHttpProxyAgent.Options["proxyTls"]; - setGlobalDispatcher(withUndiciErrorListener(new EnvHttpProxyAgent({ - allowH2: false, - proxyTunnel: true, - headersTimeout: 300_000, - bodyTimeout: 300_000, - connect: tlsConnectOpts, - proxyTls: proxyConnectorOpts, - requestTls: proxyConnectorOpts, - clientFactory: (origin, opts) => createUndiciOriginDispatcher(origin, opts as Pool.Options), - factory: createUndiciOriginDispatcher, - }))); + const envProxy = resolveEnvProxySettings(); + setGlobalDispatcher(getDispatcherForProfile(BASE_PROFILES[0], envProxy)); // The Pi SDK does not run its CLI dispatcher setup. Install npm Undici's // fetch and matching web types before wrapping fetch for the model SDKs. install(); diff --git a/runtime/pi/test/worker.test.mjs b/runtime/pi/test/worker.test.mjs index 72f8edb9..791d9cac 100644 --- a/runtime/pi/test/worker.test.mjs +++ b/runtime/pi/test/worker.test.mjs @@ -1,15 +1,23 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { createServer } from "node:http"; -import { connect } from "node:net"; -import { spawn } from "node:child_process"; +import { createServer as createHttpsServer } from "node:https"; +import { connect, createServer as createTcpServer } from "node:net"; +import { execFileSync, spawn } from "node:child_process"; import { once } from "node:events"; import { mkdtemp, rm, readFile, readdir, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { basename, join } from "node:path"; import { fileURLToPath } from "node:url"; import { SessionManager } from "@earendil-works/pi-coding-agent"; -import { isPreResponseConnectError } from "../dist/network.js"; +import { + isLoopbackOrPrivateHost, + isPreResponseConnectError, + normalizeProxyUrl, + parseDarwinScutilProxy, + parseWindowsRegProxy, + resolveEnvProxySettings, +} from "../dist/network.js"; import { RecordReader } from "../dist/protocol.js"; test("JSONL preserves Unicode separators and fragmented UTF-8", () => { @@ -814,3 +822,132 @@ test("generateOnly retries transient socket resets and fails over to backup chan assert.ok(records.some(r => r.event?.type === "auto_retry_start")); assert.ok(records.some(r => r.event?.type === "model_failover")); }); + +test("proxy normalization covers ALL_PROXY, socks5h, schemeless host:port, and OS proxy parsers", () => { + assert.equal(normalizeProxyUrl("socks5h://127.0.0.1:7890"), "socks5://127.0.0.1:7890"); + assert.equal(normalizeProxyUrl("127.0.0.1:7890"), "http://127.0.0.1:7890"); + const envResolved = resolveEnvProxySettings({ ALL_PROXY: "socks5h://127.0.0.1:7890" }); + assert.equal(envResolved.httpsProxy, "socks5://127.0.0.1:7890"); + assert.equal(envResolved.source, "env"); + assert.equal(isLoopbackOrPrivateHost("localhost"), true); + assert.equal(isLoopbackOrPrivateHost("192.168.1.10"), true); + assert.equal(isLoopbackOrPrivateHost("api.openai.com"), false); + + const darwin = parseDarwinScutilProxy("{\n HTTPEnable : 1\n HTTPPort : 7890\n HTTPProxy : 127.0.0.1\n HTTPSEnable : 1\n HTTPSPort : 7890\n HTTPSProxy : 127.0.0.1\n}\n"); + assert.equal(darwin?.httpsProxy, "http://127.0.0.1:7890"); + + const win = parseWindowsRegProxy("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\n ProxyEnable REG_DWORD 0x1\n ProxyServer REG_SZ 127.0.0.1:7890\n"); + assert.equal(win?.httpsProxy, "http://127.0.0.1:7890"); +}); + +test("TLS handshake keeps single-packet ClientHello, falls back to IPv4 on IPv6 TLS reset, and supports ALL_PROXY socks5h", { timeout: 45000 }, async t => { + const certDir = await mkdtemp(join(tmpdir(), "csai-pi-tls-cert-")); + t.after(() => rm(certDir, { recursive: true, force: true })); + const keyPath = join(certDir, "key.pem"); + const certPath = join(certDir, "cert.pem"); + execFileSync("openssl", [ + "req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1", + "-keyout", keyPath, "-out", certPath, "-days", "1", "-nodes", + "-subj", "/CN=localhost", + "-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1", + ], { stdio: "ignore" }); + const key = await readFile(keyPath); + const cert = await readFile(certPath); + + const httpsOrigin = createHttpsServer({ key, cert }, (_req, res) => sse(res, { role: "assistant", content: "tls-verified" }, "stop")); + httpsOrigin.listen(0, "127.0.0.1"); + await once(httpsOrigin, "listening"); + t.after(() => { httpsOrigin.closeAllConnections(); httpsOrigin.close(); }); + const originPort = httpsOrigin.address().port; + + // 1) Middlebox that sends TCP RST if ClientHello exceeds 600 bytes (rejects 1.6KB PQ ClientHello). + let clientHelloBytes = 0; + const middlebox = createTcpServer(client => { + client.once("data", firstChunk => { + clientHelloBytes = firstChunk.length; + if (firstChunk.length > 600) { + client.resetAndDestroy(); + return; + } + const upstream = connect(originPort, "127.0.0.1", () => { + upstream.write(firstChunk); + client.pipe(upstream).pipe(client); + }); + client.on("error", () => upstream.destroy()); + upstream.on("error", () => client.destroy()); + }); + }); + middlebox.listen(0, "127.0.0.1"); + await once(middlebox, "listening"); + t.after(() => middlebox.close()); + + const tlsEnv = { ...fixtureEnv, NODE_EXTRA_CA_CERTS: certPath, NO_PROXY: "localhost,127.0.0.1", no_proxy: "localhost,127.0.0.1" }; + const compactRun = await invoke(t, { ...request(`https://localhost:${middlebox.address().port}/v1`), generateOnly: true, tools: [] }, undefined, tlsEnv); + assert.equal(compactRun.result.status, "completed", compactRun.result.error); + assert.equal(compactRun.result.response, "tls-verified"); + assert.ok(clientHelloBytes > 0 && clientHelloBytes <= 600, `expected compact ClientHello <=600B, got ${clientHelloBytes}B`); + + // 2) Dual-stack localhost where IPv6 (::1) accepts TCP then resets TLS, while IPv4 (127.0.0.1) serves HTTPS. + const v6Reset = createTcpServer(sock => sock.once("data", () => sock.resetAndDestroy())); + let ipv6Bound = true; + try { + v6Reset.listen(0, "::1"); + await once(v6Reset, "listening"); + } catch { + ipv6Bound = false; + } + if (ipv6Bound) { + t.after(() => v6Reset.close()); + const dualPort = v6Reset.address().port; + const v4Https = createHttpsServer({ key, cert }, (_req, res) => sse(res, { role: "assistant", content: "ipv4-fallback-ok" }, "stop")); + v4Https.listen(dualPort, "127.0.0.1"); + await once(v4Https, "listening"); + t.after(() => { v4Https.closeAllConnections(); v4Https.close(); }); + + const dualRun = await invoke(t, { ...request(`https://localhost:${dualPort}/v1`), generateOnly: true, tools: [] }, undefined, tlsEnv); + assert.equal(dualRun.result.status, "completed", dualRun.result.error); + assert.equal(dualRun.result.response, "ipv4-fallback-ok"); + } + + // 3) Minimal SOCKS5 server exercised via ALL_PROXY=socks5h://127.0.0.1: over HTTPS. + let socksConnections = 0; + const socksServer = createTcpServer(sock => { + socksConnections++; + sock.once("data", greeting => { + assert.equal(greeting[0], 0x05); + sock.write(Buffer.from([0x05, 0x00])); + sock.once("data", cmd => { + assert.equal(cmd[0], 0x05); + assert.equal(cmd[1], 0x01); // CONNECT + const atyp = cmd[3]; + let offset = 4; + if (atyp === 0x01) offset += 4; + else if (atyp === 0x03) offset += 1 + cmd[4]; + else if (atyp === 0x04) offset += 16; + const targetPort = cmd.readUInt16BE(offset); + const upstream = connect(targetPort, "127.0.0.1", () => { + sock.write(Buffer.from([0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0, 0])); + sock.pipe(upstream).pipe(sock); + }); + sock.on("error", () => upstream.destroy()); + upstream.on("error", () => sock.destroy()); + }); + }); + }); + socksServer.listen(0, "127.0.0.1"); + await once(socksServer, "listening"); + t.after(() => socksServer.close()); + + const socksEnv = { + ...process.env, + NODE_EXTRA_CA_CERTS: certPath, + HTTP_PROXY: "", http_proxy: "", HTTPS_PROXY: "", https_proxy: "", + ALL_PROXY: `socks5h://127.0.0.1:${socksServer.address().port}`, + all_proxy: `socks5h://127.0.0.1:${socksServer.address().port}`, + NO_PROXY: "", no_proxy: "", + }; + const socksRun = await invoke(t, { ...request(`https://localhost:${originPort}/v1`), generateOnly: true, tools: [] }, undefined, socksEnv); + assert.equal(socksRun.result.status, "completed", socksRun.result.error); + assert.equal(socksRun.result.response, "tls-verified"); + assert.ok(socksConnections >= 1); +});