/** * OpenAI-compatible proxy in front of cursor-agent CLI (ACP transport). * * Endpoints: * GET /v1/models List supported models * POST /v1/chat/completions Chat completion (streaming or not) * GET /health Liveness probe * * Every request uses cursor-agent ACP (`agent acp`): * - session/new with in-process MCP server for client tools[] * - session/prompt with text + image ContentBlocks * - session/request_permission denies built-in tools, allows MCP client tools * - Tool invocations park until HTTP client returns role:"tool" * - In-cluster callers authenticate with PROXY_INTERNAL_TOKEN; Authentik outpost via X-Authentik-Username * * No external dependencies. Uses only Node built-ins. */ import { createServer } from "node:http"; import { randomUUID } from "node:crypto"; import { allModelIds, normalizeModel } from "./models.mjs"; import { createSession, findSessionForFollowUp, destroyAllSessions, startWarmPool, getWarmPoolStats, getActiveSessionCount, nowMs, fmtMs, } from "./session-manager.mjs"; import { messageContentToText, hasImageParts, openAiMessagesToAcpBlocks, normalizeToolChoice, toolDirectiveBlock, toolNudgeBlock, noToolsDirectiveBlock, } from "./message-converter.mjs"; import { textChunk, reasoningChunk, toolCallChunk, finishChunk, nonStreamResponse, } from "./stream-translator.mjs"; const PORT = parseInt(process.env.PORT || "4646", 10); const EDGE_PORT = parseInt(process.env.EDGE_PORT || "4647", 10); const SHUTDOWN_TIMEOUT_MS = parseInt(process.env.SHUTDOWN_TIMEOUT_MS || "10000", 10); const MAX_BODY_BYTES = parseInt(process.env.PROXY_MAX_BODY_BYTES || String(24 * 1024 * 1024), 10); const INTERNAL_TOKEN = process.env.PROXY_INTERNAL_TOKEN || ""; /** @param {import("node:http").ServerResponse} res */ function sendJson(res, status, obj) { const body = JSON.stringify(obj); res.statusCode = status; res.setHeader("Content-Type", "application/json"); res.setHeader("Content-Length", Buffer.byteLength(body)); res.end(body); } function readJsonBody(req, maxBytes = MAX_BODY_BYTES) { return new Promise((resolve, reject) => { const chunks = []; let size = 0; req.on("data", (chunk) => { size += chunk.length; if (size > maxBytes) { reject(new Error(`request body exceeds ${maxBytes} bytes`)); req.destroy(); return; } chunks.push(chunk); }); req.on("end", () => { const buf = Buffer.concat(chunks); if (buf.length === 0) { resolve({}); return; } try { resolve(JSON.parse(buf.toString("utf8"))); } catch (e) { reject(new Error(`invalid JSON body: ${e.message}`)); } }); req.on("error", reject); }); } function extractBearerToken(req) { const auth = req.headers.authorization || ""; if (auth.startsWith("Bearer ")) { return auth.slice(7).trim(); } return ""; } function isPublicPath(pathname) { return pathname === "/health" || pathname === "/"; } /** * Internal port (4646): in-cluster / mesh callers. ONLY PROXY_INTERNAL_TOKEN * is accepted (Bearer or X-Proxy-Internal-Token). The Authentik trust * header is NOT honored here — it is trivially forgeable by any in-cluster * client and must never grant access to the token-checked surface. */ function isAuthorizedInternal(req) { if (!INTERNAL_TOKEN) return true; const url = new URL(req.url, "http://internal"); if (isPublicPath(url.pathname)) return true; const bearer = extractBearerToken(req); if (bearer === INTERNAL_TOKEN) return true; const headerToken = req.headers["x-proxy-internal-token"]; if (typeof headerToken === "string" && headerToken === INTERNAL_TOKEN) return true; return false; } /** * Edge port (4647): reached only through the Authentik proxy outpost, which * authenticates the user and injects X-Authentik-Username. NetworkPolicy * restricts this port to the outpost; requiring the header adds defense in * depth (a direct in-cluster hit without the outpost cannot pass). */ function isAuthorizedEdge(req) { const url = new URL(req.url, "http://internal"); if (isPublicPath(url.pathname)) return true; return typeof req.headers["x-authentik-username"] === "string" && req.headers["x-authentik-username"].length > 0; } function sendUnauthorized(res) { sendJson(res, 401, { error: { message: "unauthorized", type: "authentication_error", code: "invalid_internal_token", }, }); } // --------------------------------------------------------------------------- // Route handlers // --------------------------------------------------------------------------- async function handleModels(req, res, edge) { if (!(edge ? isAuthorizedEdge(req) : isAuthorizedInternal(req))) { sendUnauthorized(res); return; } const now = Math.floor(Date.now() / 1000); sendJson(res, 200, { object: "list", data: allModelIds().map((id) => ({ id, object: "model", owned_by: "cursor", created: now })), }); } function handleHealth(_req, res) { sendJson(res, 200, { status: "ok", timestamp: new Date().toISOString(), sessions: getActiveSessionCount(), warmPool: getWarmPoolStats(), }); } function openSse(res, requestId) { if (res.headersSent) return; res.setHeader("Content-Type", "text/event-stream"); res.setHeader("Cache-Control", "no-cache"); res.setHeader("Connection", "keep-alive"); res.setHeader("X-Request-Id", requestId); res.flushHeaders(); res.write(":ok\n\n"); } function writeSseError(res, message) { if (res.writableEnded) return; try { res.write( `data: ${JSON.stringify({ error: { message, type: "server_error", code: null } })}\n\n` ); res.write("data: [DONE]\n\n"); res.end(); } catch { try { res.end(); } catch { /* ignore */ } } } async function handleChatCompletions(req, res, edge) { if (!(edge ? isAuthorizedEdge(req) : isAuthorizedInternal(req))) { sendUnauthorized(res); return; } const requestId = randomUUID().replace(/-/g, "").slice(0, 24); const tReq = nowMs(); let body; try { body = await readJsonBody(req); } catch (e) { sendJson(res, 400, { error: { message: e.message, type: "invalid_request_error", code: "invalid_body" }, }); return; } const tBody = nowMs(); if (!Array.isArray(body.messages) || body.messages.length === 0) { sendJson(res, 400, { error: { message: "messages is required and must be a non-empty array", type: "invalid_request_error", code: "invalid_messages", }, }); return; } const stream = body.stream === true; const model = normalizeModel(body.model); const toolChoice = normalizeToolChoice(body.tool_choice); const toolsCount = Array.isArray(body.tools) ? body.tools.length : 0; const imageCount = hasImageParts(body.messages) ? body.messages.reduce((n, m) => { if (!Array.isArray(m.content)) return n; return n + m.content.filter((p) => p.type === "image_url").length; }, 0) : 0; const followUp = findSessionForFollowUp(body); if (followUp) { const { session, toolResults } = followUp; console.error( `[chat] id=${requestId} transport=acp model=${model} FOLLOWUP session=${session.sessionId} pending=${toolResults.length} stream=${stream}` ); for (const tr of toolResults) { const ok = session.resolveToolCall(tr.tool_call_id, messageContentToText(tr.content)); if (!ok) { console.error( `[chat] id=${requestId} tool_call_id=${tr.tool_call_id} not pending in session ${session.sessionId}` ); } } await streamSessionTurn({ res, session, requestId, stream, blocks: null, tReq }); return; } console.error( `[chat] id=${requestId} transport=acp model=${body.model} -> ${model} tools=${toolsCount} images=${imageCount} stream=${stream}` ); // Open SSE before createSession so clients see TTFB while ACP boots. if (stream) { openSse(res, requestId); console.error(`[timing] id=${requestId} sse_open=${fmtMs(nowMs() - tReq)} (before createSession)`); } let blocks; try { blocks = await openAiMessagesToAcpBlocks(body.messages); } catch (e) { if (stream && res.headersSent) { writeSseError(res, e.message); } else { sendJson(res, 400, { error: { message: e.message, type: "invalid_request_error", code: "invalid_messages" }, }); } return; } const tConvert = nowMs(); let session; try { session = await createSession({ tools: body.tools || [], model, log: (...args) => console.error(`[chat:${requestId}]`, ...args), }); } catch (e) { console.error(`[chat] id=${requestId} createSession error: ${e.message}`); if (e.code === "too_many_sessions") { if (stream && res.headersSent) { writeSseError(res, e.message); } else { sendJson(res, 429, { error: { message: e.message, type: "rate_limit_error", code: "too_many_sessions", }, }); } return; } if (stream && res.headersSent) { writeSseError(res, e.message); } else if (!res.headersSent) { sendJson(res, 500, { error: { message: e.message, type: "server_error", code: null } }); } else { try { res.end(); } catch { /* ignore */ } } return; } const tSession = nowMs(); const fromWarm = Boolean(session.fromWarmPool); console.error( `[timing] id=${requestId} body=${fmtMs(tBody - tReq)} convert=${fmtMs(tConvert - tBody)} create_session=${fmtMs(tSession - tConvert)} from_warm=${fromWarm} pre_prompt=${fmtMs(tSession - tReq)}` ); // tool_choice enforcement: prepend directive blocks before user content. if (toolChoice && toolChoice.kind !== "none" && (body.tools || []).length > 0) { blocks.unshift(toolDirectiveBlock(toolChoice)); } else if (toolChoice && toolChoice.kind === "none") { blocks.unshift(noToolsDirectiveBlock()); } await streamSessionTurn({ res, session, requestId, stream, blocks, toolChoice, tReq }); } async function streamSessionTurn({ res, session, requestId, stream, blocks, toolChoice = null, tReq = nowMs(), }) { if (!stream) { let result = await collectSessionTurn(session, blocks); // tool_choice enforcement (non-streaming): retry internally when the // model answered in plain text despite a required/named tool choice. if (toolChoice && toolChoice.kind !== "none" && result.finishReason !== "tool_calls" && result.text.trim()) { for (let attempt = 0; attempt < 2; attempt++) { result = await collectSessionTurn(session, [toolNudgeBlock()]); if (result.finishReason === "tool_calls") break; } } if (!res.headersSent) { res.setHeader("Content-Type", "application/json"); res.end( JSON.stringify( nonStreamResponse({ id: requestId, model: session.detectedModel || "auto", text: result.text, reasoning: result.reasoning, toolCalls: result.calls, finishReason: result.finishReason, usage: result.usage, }) ) ); } console.error( `[timing] id=${requestId} nonstream_total=${fmtMs(nowMs() - tReq)} finish=${result.finishReason}` ); if (result.finishReason !== "tool_calls") { await session.destroy(); } return; } openSse(res, requestId); const tSse = nowMs(); let isFirst = true; let finished = false; let firstTokenLogged = false; // tool_choice enforcement (streaming): buffer text deltas while a // required/named choice is active; flush only when a tool call arrives or // the turn finishes. On plain-text-only turn, retry with a nudge instead // of emitting the violating text. const enforceToolChoice = Boolean(toolChoice && toolChoice.kind !== "none"); let textBuffer = ""; let sawToolCall = false; let enforcementRetries = 0; const MAX_ENFORCEMENT_RETRIES = 2; const markFirstToken = (kind) => { if (firstTokenLogged) return; firstTokenLogged = true; const now = nowMs(); console.error( `[timing] id=${requestId} first_${kind}=${fmtMs(now - tReq)} since_sse=${fmtMs(now - tSse)} from_warm=${Boolean(session.fromWarmPool)}` ); }; const flushText = () => { if (!textBuffer) return; markFirstToken("token"); const chunk = textChunk({ id: requestId, model: session.detectedModel || "auto", delta: textBuffer, isFirst, }); isFirst = false; res.write(`data: ${JSON.stringify(chunk)}\n\n`); textBuffer = ""; }; const handlers = { onAssistantDelta: (delta) => { if (res.writableEnded || finished) return; if (enforceToolChoice) { textBuffer += delta; return; } markFirstToken("token"); const chunk = textChunk({ id: requestId, model: session.detectedModel || "auto", delta, isFirst, }); isFirst = false; res.write(`data: ${JSON.stringify(chunk)}\n\n`); }, onReasoningDelta: (delta) => { if (res.writableEnded || finished) return; markFirstToken("reasoning"); const chunk = reasoningChunk({ id: requestId, model: session.detectedModel || "auto", delta, isFirst, }); isFirst = false; res.write(`data: ${JSON.stringify(chunk)}\n\n`); }, onToolCall: (call) => { if (res.writableEnded || finished) return; sawToolCall = true; flushText(); markFirstToken("tool_call"); const chunk = toolCallChunk({ id: requestId, model: session.detectedModel || "auto", call, isFirst, }); isFirst = false; res.write(`data: ${JSON.stringify(chunk)}\n\n`); }, onFinish: async (reason, _usage) => { if (finished) return; // Enforcement retry: plain-text-only turn under required tool choice. if ( enforceToolChoice && !sawToolCall && reason === "stop" && enforcementRetries < MAX_ENFORCEMENT_RETRIES && !res.writableEnded ) { enforcementRetries += 1; console.error( `[chat] id=${requestId} tool_choice enforcement retry ${enforcementRetries}/${MAX_ENFORCEMENT_RETRIES}` ); textBuffer = ""; session.runTurn([toolNudgeBlock()], handlers); return; } finished = true; if (!res.writableEnded) { if (reason !== "error" || !enforceToolChoice) flushText(); const chunk = finishChunk({ id: requestId, model: session.detectedModel || "auto", finishReason: reason, }); res.write(`data: ${JSON.stringify(chunk)}\n\n`); res.write("data: [DONE]\n\n"); res.end(); } console.error( `[timing] id=${requestId} turn_done=${fmtMs(nowMs() - tReq)} finish=${reason}` ); if (reason === "stop" || reason === "error") { await session.destroy(); } }, }; session.runTurn(blocks, handlers); } function collectSessionTurn(session, blocks) { return new Promise((resolve) => { let text = ""; let reasoning = ""; const calls = []; let finishReason = "stop"; let usage = null; session.runTurn(blocks, { onAssistantDelta: (d) => { text += d; }, onReasoningDelta: (d) => { reasoning += d; }, onToolCall: (c) => { calls.push(c); }, onFinish: (reason, u) => { finishReason = reason; usage = u; resolve({ text, reasoning, calls, finishReason, usage }); }, }); }); } // --------------------------------------------------------------------------- // Server bootstrap & graceful shutdown // --------------------------------------------------------------------------- // Shared request handler. `edge` selects the auth surface: edge traffic is // pre-authenticated by the Authentik outpost, internal traffic must present // PROXY_INTERNAL_TOKEN. async function requestHandler(req, res) { res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization"); if (req.method === "OPTIONS") { res.statusCode = 204; res.end(); return; } const edge = req.socket.localPort === EDGE_PORT; const url = new URL(req.url, "http://internal"); try { if (req.method === "GET" && url.pathname === "/v1/models") { await handleModels(req, res, edge); } else if (req.method === "POST" && url.pathname === "/v1/chat/completions") { await handleChatCompletions(req, res, edge); } else if (req.method === "GET" && (url.pathname === "/health" || url.pathname === "/")) { handleHealth(req, res); } else { sendJson(res, 404, { error: { message: `not found: ${req.method} ${url.pathname}` } }); } } catch (e) { console.error(`[server] unhandled error: ${e.stack || e.message}`); if (!res.headersSent) { sendJson(res, 500, { error: { message: e.message, type: "server_error" } }); } else { try { res.end(); } catch { /* ignore */ } } } } const server = createServer(requestHandler); const edgeServer = createServer(requestHandler); server.listen(PORT, () => { console.error(`[server] cursor-agent-api-proxy (ACP) internal :${PORT} (token-gated)`); startWarmPool((...args) => console.error("[warm-pool]", ...args)); const warm = getWarmPoolStats(); console.error(`[server] warm pool target=${warm.target} (ready=${warm.ready} warming=${warm.warming})`); }); // Edge listener: separate server instance on EDGE_PORT. Requests there are // pre-authenticated by the Authentik outpost in front of them (defense in // depth: header required + NetworkPolicy restricts to the outpost). edgeServer.listen(EDGE_PORT, () => { console.error(`[server] edge :${EDGE_PORT} (authentik outpost only)`); }); let shuttingDown = false; async function shutdown(signal) { if (shuttingDown) return; shuttingDown = true; console.error(`[server] ${signal} received, shutting down...`); server.close(); edgeServer.close(); const force = setTimeout(() => { console.error("[server] shutdown timeout, forcing exit"); process.exit(1); }, SHUTDOWN_TIMEOUT_MS); try { await destroyAllSessions(); } catch (e) { console.error(`[server] error during shutdown: ${e.message}`); } clearTimeout(force); process.exit(0); } process.on("SIGTERM", () => shutdown("SIGTERM")); process.on("SIGINT", () => shutdown("SIGINT"));