Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 22 additions & 3 deletions bin/clef-proxy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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/<name>/endpoint.json
// (default ~/.local/state/<name>/endpoint.json), written on listen,
Expand Down Expand Up @@ -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;
};
Expand Down
24 changes: 24 additions & 0 deletions bin/design-code-proxy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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.`;

Expand Down Expand Up @@ -139,12 +145,20 @@ const server = http.createServer((req, res) => {
port: upstreamUrl.port || 443,
path: upstreamUrl.pathname + upstreamUrl.search,
method: 'POST',
agent: httpsAgent,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve environment proxy settings in the upstream agent

On Node 24 with NODE_USE_ENV_PROXY=1 and HTTPS_PROXY configured, explicitly supplying this agent bypasses the environment proxy: the previous request used https.globalAgent, which incorporates those settings, whereas the new httpsAgent has no proxyEnv. In environments requiring proxied egress, AMR requests now fail and unexpectedly fall back to local backends despite valid upstream credentials. This was reproduced with a local CONNECT proxy: the default agent contacted it, while the custom agent attempted direct DNS resolution. Preserve the configured proxy behavior when creating the keep-alive pool.

Useful? React with 👍 / 👎.

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);
});

Expand Down Expand Up @@ -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}`);
Expand Down
Loading