diff --git a/bin/clef-proxy.mjs b/bin/clef-proxy.mjs index b61de077a8..ea250a6925 100755 --- a/bin/clef-proxy.mjs +++ b/bin/clef-proxy.mjs @@ -8,6 +8,17 @@ import { parseProxyPort } from './proxy-port.mjs'; const PORT = parseProxyPort('CLEF_PROXY_PORT', 18742); const HOST = process.env.CLEF_PROXY_HOST || '127.0.0.1'; +// Warm connections (#480): upstream calls go through fetch, whose bundled +// undici global dispatcher already pools and reuses keep-alive connections +// to the gateway — there is no per-request handshake to remove. A raw +// https.Agent swap was tried and reverted: https.request bypasses the +// HTTP(S)_PROXY environment (NODE_USE_ENV_PROXY applies to fetch only), so +// on hosts whose egress goes through a proxy the swap broke upstream calls +// outright (TLS to a plain-HTTP proxy port) — a behavior change, not a +// warm-up. Node does not expose undici as an importable module, so the +// dispatcher's pool settings are not configurable from here; the default +// pool is the keep-alive layer for this proxy. + // Publish the bound endpoint so other tools can find this proxy without // knowing its port in advance: $XDG_STATE_HOME//endpoint.json // (default ~/.local/state//endpoint.json), written on listen, @@ -41,12 +52,20 @@ const publishEndpoint = () => { } catch {} }; +// Config files were re-read from disk on every request (#480). Cache the +// contents and re-read only when the file's mtime changes, so a rotated +// token is still picked up without a restart but the hot path does a +// single stat instead of up to three full reads. +const configFileCache = new Map(); const readConfigFileSync = (filename, fallback = '') => { try { const fullPath = path.join(os.homedir(), '.config', 'cloudflare', filename); - if (fs.existsSync(fullPath)) { - return fs.readFileSync(fullPath, 'utf8').trim(); - } + const { mtimeMs } = fs.statSync(fullPath); + const cached = configFileCache.get(filename); + if (cached && cached.mtimeMs === mtimeMs) return cached.value; + const value = fs.readFileSync(fullPath, 'utf8').trim(); + configFileCache.set(filename, { mtimeMs, value }); + return value; } catch {} return fallback; }; diff --git a/bin/design-code-proxy.mjs b/bin/design-code-proxy.mjs index fb56fe7b9d..89e6a92752 100755 --- a/bin/design-code-proxy.mjs +++ b/bin/design-code-proxy.mjs @@ -10,6 +10,12 @@ const ANTIGRAVITY_LS_PORT = parseProxyPort('ANTIGRAVITY_LS_PROXY_PORT', 18745); const CODEX_PROXY_PORT = parseProxyPort('CODEX_PROXY_PORT', 18744); const AMR_UPSTREAM_URL = process.env.AMR_UPSTREAM_URL || 'https://amr-link.open-design.ai/v1'; +// Warm connections (#480): one keep-alive pool per scheme, shared by every +// backend/upstream call, so repeat requests reuse an open socket instead of +// paying a fresh TCP (and, for the AMR upstream, TLS) handshake per request. +const httpAgent = new http.Agent({ keepAlive: true, keepAliveMsecs: 1000, maxSockets: 32 }); +const httpsAgent = new https.Agent({ keepAlive: true, keepAliveMsecs: 1000, maxSockets: 32 }); + const DESIGN_SYSTEM_PROMPT = `You are an elite Code & Systems Design Architect. Your core expertise is in software architecture, clean code design, UI/UX design engineering, design tokens, component abstractions, domain-driven design, and maintainable systems patterns. Provide elegant, production-grade architectures and idiomatic design implementations.`; @@ -139,12 +145,20 @@ const server = http.createServer((req, res) => { port: upstreamUrl.port || 443, path: upstreamUrl.pathname + upstreamUrl.search, method: 'POST', + agent: httpsAgent, headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${upstreamKey}` } }, upstreamRes => { res.writeHead(upstreamRes.statusCode || 200, upstreamRes.headers); + // A mid-stream upstream error must not leave the client (or the + // pooled socket) hanging: tear the response down so the socket + // is released instead of stalling half-open. + upstreamRes.on('error', err => { + console.error(`[design-code-proxy] Upstream response error: ${err.message}`); + res.destroy(); + }); upstreamRes.pipe(res); }); @@ -204,11 +218,21 @@ const dispatchWithFallback = (body, clientRes) => { port: target.port, path: '/v1/chat/completions', method: 'POST', + agent: httpAgent, headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) } }, localRes => { + // A backend response error must not hang the client: fall back when + // nothing was sent yet, otherwise tear the response down so the + // pooled socket is released instead of stalling half-open. + localRes.on('error', err => { + console.warn(`[design-code-proxy] Error reading response from 127.0.0.1:${target.port}: ${err.message}`); + if (!clientRes.headersSent) onFail(err); + else clientRes.destroy(); + }); + // Check for quota exhaustion / error codes if (localRes.statusCode === 429 || localRes.statusCode >= 500) { console.warn(`[design-code-proxy] Target 127.0.0.1:${target.port} returned ${localRes.statusCode}`);