Files
cursor-agent-api-proxy/src/server.mjs
T
Ubuntu b467998ba4
build-and-push / build (push) Successful in 4m59s
feat(api): enforce OpenAI tool_choice contract (required/named/none)
- normalizeToolChoice maps OpenAI tool_choice values to internal shapes
- required/named: prepend a mandatory-tool directive block; buffer text
  deltas and only flush when a tool call actually arrives; on plain-text
  turn, retry in-process with a nudge block (max 2 retries) instead of
  emitting the violating text (streaming + non-streaming paths)
- none: prepend a no-tools directive
- unit tests for all new mapping/directive helpers (32 passing)

Verified live against cursor-agent ACP with model=auto: image+required
yields clean tool_calls chunks with no text pollution; follow-up turns
resolve parked MCP tool calls and retry on invalid observations.
2026-09-27 12:02:40 +00:00

471 lines
14 KiB
JavaScript

/**
* 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,
normalizeToolChoice,
toolDirectiveBlock,
toolNudgeBlock,
noToolsDirectiveBlock,
} 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 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 });
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;
}
// 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 });
}
async function streamSessionTurn({ res, session, requestId, stream, blocks, toolChoice = null }) {
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,
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;
// 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 flushText = () => {
if (!textBuffer) return;
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;
}
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;
sawToolCall = true;
flushText();
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();
}
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"));