// Egress proxy for the pi-collab sandbox. // // The only network path from an agent container to the outside world. It // forwards to GreenPT and nothing else, streaming responses through without // buffering, and tees the `impact` payload (energy / emissions / inference // time) that opencode would otherwise drop. // // Design (from coding_club): // - The API key lives OUTSIDE the agent container. The proxy holds // GREENPT_API_KEY and injects `Authorization` on the way out; anything the // caller sent is dropped, never forwarded. A container is identified by the // network it is on (the internal network is its only egress), not by a key. // - Responses stream through line-by-line; parsing is side-effect-free. // - Attribution comes from request headers the caller stamps (x-club-session, // x-club-agent, x-club-user); if absent the fields are null. // // Usage: // node greenpt-proxy.mjs # serve on 0.0.0.0:8080 // Env: // UPSTREAM upstream base (default https://api.greenpt.ai) // PORT listen port (default 8080) // IMPACT_LOG append-only JSONL of impact records (default impact.jsonl) // GREENPT_API_KEY the real key; injected by this proxy (REQUIRED) import { createServer } from "node:http"; import { appendFileSync } from "node:fs"; const UPSTREAM = (process.env.UPSTREAM || "https://api.greenpt.ai").replace(/\/$/, ""); const PORT = Number(process.env.PORT || 8080); const IMPACT_LOG = process.env.IMPACT_LOG || "impact.jsonl"; const GREENPT_API_KEY = process.env.GREENPT_API_KEY; if (!GREENPT_API_KEY) { console.error("greenpt-proxy: GREENPT_API_KEY is required"); process.exit(1); } // Hop-by-hop headers we never forward. Host is rebuilt for the upstream. const DROP_HEADERS = new Set([ "host", "connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade", "content-length", "accept-encoding", ]); // Headers the caller may stamp for attribution. Forwarded as-is too. const ATTR_HEADERS = ["x-club-session", "x-club-agent", "x-club-user"]; function logImpact(record) { const line = JSON.stringify({ ts: Date.now() / 1000, ...record }); try { appendFileSync(IMPACT_LOG, line + "\n"); } catch (e) { console.error("[proxy] impact log write failed:", e.message); } } function parseImpactLine(line, ctx) { const text = line.trim(); if (!text.startsWith("data:")) return; const payload = text.slice(5).trim(); if (!payload || payload === "[DONE]") return; try { const obj = JSON.parse(payload); if (obj && typeof obj === "object" && obj.impact) { ctx.impact = obj.impact; ctx.usage = obj.usage; } } catch { /* not json, skip */ } } async function teeStream(upstream, out, ctx) { // upstream is a web ReadableStream (fetch body); consume it with a reader. let buf = ""; const reader = upstream.getReader(); const decoder = new TextDecoder(); for (;;) { const { done, value } = await reader.read(); if (done) break; const chunk = Buffer.from(value); out.write(chunk); buf += decoder.decode(value, { stream: true }); let idx; while ((idx = buf.indexOf("\n")) !== -1) { const line = buf.slice(0, idx); buf = buf.slice(idx + 1); parseImpactLine(line, ctx); } } if (buf) parseImpactLine(buf, ctx); } const server = createServer(async (req, res) => { const url = new URL(req.url, `http://127.0.0.1:${PORT}`); const ctx = { session: req.headers["x-club-session"] || null, agent: req.headers["x-club-agent"] || null, user: req.headers["x-club-user"] || null, }; if (req.method === "GET" && url.pathname === "/health") { res.writeHead(200, { "Content-Type": "application/json", "Content-Length": 11 }); res.end('{"ok":true}'); return; } if (req.method !== "POST" || !url.pathname.startsWith("/v1/")) { res.writeHead(404, { "Content-Type": "text/plain" }); res.end("only POST /v1/* is forwarded to GreenPT"); return; } // Read the body. let body = Buffer.alloc(0); for await (const chunk of req) body = Buffer.concat([body, chunk]); try { ctx.model = body.length ? JSON.parse(body.toString()).model : null; } catch { ctx.model = null; } // Identity: a request on this network is a container; the proxy knows no // container holds a key, so anything it sent is dropped and the real key is // injected here, outside the container boundary. if (req.headers.authorization) { console.error("[proxy] dropped Authorization from container (container must not hold a key)"); } const upstreamUrl = UPSTREAM + url.pathname + url.search; const reqHeaders = {}; for (const [key, value] of Object.entries(req.headers)) { if (DROP_HEADERS.has(key.toLowerCase()) || key.toLowerCase() === "authorization") continue; reqHeaders[key] = value; } reqHeaders["Accept-Encoding"] = "identity"; reqHeaders["Authorization"] = "Bearer " + GREENPT_API_KEY; let upstream; try { upstream = await fetch(upstreamUrl, { method: "POST", headers: reqHeaders, body: body.length ? body : undefined, redirect: "follow", }); } catch (e) { res.writeHead(502, { "Content-Type": "text/plain" }); res.end(`upstream unreachable: ${e.message}`); return; } const headers = { ...upstream.headers }; headers["Connection"] = "close"; res.writeHead(upstream.status, headers); await teeStream(upstream.body, res, ctx); res.end(); if (ctx.impact) logImpact(ctx); }); server.listen(PORT, "0.0.0.0", () => { console.log(`[proxy] forwarding ${UPSTREAM} -> :${PORT}; impact log ${IMPACT_LOG}`); });