Files
cursor-agent-api-proxy/src/server.mjs
T

406 lines
12 KiB
JavaScript
Raw Normal View History

/**
* 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,
} from "./session-manager.mjs";
import {
messageContentToText,
hasImageParts,
openAiMessagesToAcpBlocks,
} from "./message-converter.mjs";
import { textChunk, toolCallChunk, finishChunk, nonStreamResponse } from "./stream-translator.mjs";
const PORT = parseInt(process.env.PORT || "4646", 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 === "/";
}
/**
* When PROXY_INTERNAL_TOKEN is set, require it for API routes unless the
* request was already authenticated by an Authentik proxy outpost.
*/
function isAuthorized(req) {
if (!INTERNAL_TOKEN) return true;
const url = new URL(req.url, "http://internal");
if (isPublicPath(url.pathname)) return true;
if (req.headers["x-authentik-username"]) 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;
}
function sendUnauthorized(res) {
sendJson(res, 401, {
error: {
message: "unauthorized",
type: "authentication_error",
code: "invalid_internal_token",
},
});
}
// ---------------------------------------------------------------------------
// Route handlers
// ---------------------------------------------------------------------------
async function handleModels(req, res) {
if (!isAuthorized(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() });
}
async function handleChatCompletions(req, res) {
if (!isAuthorized(req)) {
sendUnauthorized(res);
return;
}
const requestId = randomUUID().replace(/-/g, "").slice(0, 24);
let body;
try {
body = await readJsonBody(req);
} catch (e) {
sendJson(res, 400, {
error: { message: e.message, type: "invalid_request_error", code: "invalid_body" },
});
return;
}
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 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 });
return;
}
console.error(
`[chat] id=${requestId} transport=acp model=${body.model} -> ${model} tools=${toolsCount} images=${imageCount} stream=${stream}`
);
let blocks;
try {
blocks = await openAiMessagesToAcpBlocks(body.messages);
} catch (e) {
sendJson(res, 400, {
error: { message: e.message, type: "invalid_request_error", code: "invalid_messages" },
});
return;
}
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") {
sendJson(res, 429, {
error: {
message: e.message,
type: "rate_limit_error",
code: "too_many_sessions",
},
});
return;
}
if (!res.headersSent) {
sendJson(res, 500, { error: { message: e.message, type: "server_error", code: null } });
} else {
try {
res.end();
} catch {
/* ignore */
}
}
return;
}
await streamSessionTurn({ res, session, requestId, stream, blocks });
}
async function streamSessionTurn({ res, session, requestId, stream, blocks }) {
if (!stream) {
const result = await collectSessionTurn(session, blocks);
if (!res.headersSent) {
res.setHeader("Content-Type", "application/json");
res.end(
JSON.stringify(
nonStreamResponse({
id: requestId,
model: session.detectedModel || "auto",
text: result.text,
toolCalls: result.calls,
finishReason: result.finishReason,
usage: result.usage,
})
)
);
}
if (result.finishReason !== "tool_calls") {
await session.destroy();
}
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");
let isFirst = true;
let finished = false;
const handlers = {
onAssistantDelta: (delta) => {
if (res.writableEnded || finished) return;
const chunk = textChunk({
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;
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;
finished = true;
if (!res.writableEnded) {
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();
}
if (reason === "stop" || reason === "error") {
await session.destroy();
}
},
};
session.runTurn(blocks, handlers);
}
function collectSessionTurn(session, blocks) {
return new Promise((resolve) => {
let text = "";
const calls = [];
let finishReason = "stop";
let usage = null;
session.runTurn(blocks, {
onAssistantDelta: (d) => {
text += d;
},
onToolCall: (c) => {
calls.push(c);
},
onFinish: (reason, u) => {
finishReason = reason;
usage = u;
resolve({ text, calls, finishReason, usage });
},
});
});
}
// ---------------------------------------------------------------------------
// Server bootstrap & graceful shutdown
// ---------------------------------------------------------------------------
const server = createServer(async (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 url = new URL(req.url, "http://internal");
try {
if (req.method === "GET" && url.pathname === "/v1/models") {
await handleModels(req, res);
} else if (req.method === "POST" && url.pathname === "/v1/chat/completions") {
await handleChatCompletions(req, res);
} 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 */
}
}
}
});
server.listen(PORT, () => {
console.error(`[server] cursor-agent-api-proxy (ACP) listening on :${PORT}`);
});
let shuttingDown = false;
async function shutdown(signal) {
if (shuttingDown) return;
shuttingDown = true;
console.error(`[server] ${signal} received, shutting down...`);
server.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"));