feat: warm-pool ACP sessions and stage TTFT timings
Pre-bootstrap two cursor-agent processes so createSession skips spawn/initialize on the hot path, open SSE before session setup, and log per-stage durations for first-token diagnosis.
This commit is contained in:
+108
-21
@@ -23,6 +23,11 @@ import {
|
||||
createSession,
|
||||
findSessionForFollowUp,
|
||||
destroyAllSessions,
|
||||
startWarmPool,
|
||||
getWarmPoolStats,
|
||||
getActiveSessionCount,
|
||||
nowMs,
|
||||
fmtMs,
|
||||
} from "./session-manager.mjs";
|
||||
import {
|
||||
messageContentToText,
|
||||
@@ -147,7 +152,39 @@ async function handleModels(req, res, edge) {
|
||||
}
|
||||
|
||||
function handleHealth(_req, res) {
|
||||
sendJson(res, 200, { status: "ok", timestamp: new Date().toISOString() });
|
||||
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) {
|
||||
@@ -157,6 +194,7 @@ async function handleChatCompletions(req, res, edge) {
|
||||
}
|
||||
|
||||
const requestId = randomUUID().replace(/-/g, "").slice(0, 24);
|
||||
const tReq = nowMs();
|
||||
let body;
|
||||
try {
|
||||
body = await readJsonBody(req);
|
||||
@@ -166,6 +204,7 @@ async function handleChatCompletions(req, res, edge) {
|
||||
});
|
||||
return;
|
||||
}
|
||||
const tBody = nowMs();
|
||||
|
||||
if (!Array.isArray(body.messages) || body.messages.length === 0) {
|
||||
sendJson(res, 400, {
|
||||
@@ -201,7 +240,7 @@ async function handleChatCompletions(req, res, edge) {
|
||||
);
|
||||
}
|
||||
}
|
||||
await streamSessionTurn({ res, session, requestId, stream, blocks: null });
|
||||
await streamSessionTurn({ res, session, requestId, stream, blocks: null, tReq });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -209,15 +248,26 @@ async function handleChatCompletions(req, res, edge) {
|
||||
`[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) {
|
||||
sendJson(res, 400, {
|
||||
error: { message: e.message, type: "invalid_request_error", code: "invalid_messages" },
|
||||
});
|
||||
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 {
|
||||
@@ -229,16 +279,22 @@ async function handleChatCompletions(req, res, edge) {
|
||||
} 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",
|
||||
},
|
||||
});
|
||||
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 (!res.headersSent) {
|
||||
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 {
|
||||
@@ -249,6 +305,11 @@ async function handleChatCompletions(req, res, edge) {
|
||||
}
|
||||
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) {
|
||||
@@ -257,10 +318,18 @@ async function handleChatCompletions(req, res, edge) {
|
||||
blocks.unshift(noToolsDirectiveBlock());
|
||||
}
|
||||
|
||||
await streamSessionTurn({ res, session, requestId, stream, blocks, toolChoice });
|
||||
await streamSessionTurn({ res, session, requestId, stream, blocks, toolChoice, tReq });
|
||||
}
|
||||
|
||||
async function streamSessionTurn({ res, session, requestId, stream, blocks, toolChoice = null }) {
|
||||
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
|
||||
@@ -286,21 +355,21 @@ async function streamSessionTurn({ res, session, requestId, stream, blocks, tool
|
||||
)
|
||||
);
|
||||
}
|
||||
console.error(
|
||||
`[timing] id=${requestId} nonstream_total=${fmtMs(nowMs() - tReq)} finish=${result.finishReason}`
|
||||
);
|
||||
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");
|
||||
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
|
||||
@@ -311,8 +380,18 @@ async function streamSessionTurn({ res, session, requestId, stream, blocks, tool
|
||||
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",
|
||||
@@ -331,6 +410,7 @@ async function streamSessionTurn({ res, session, requestId, stream, blocks, tool
|
||||
textBuffer += delta;
|
||||
return;
|
||||
}
|
||||
markFirstToken("token");
|
||||
const chunk = textChunk({
|
||||
id: requestId,
|
||||
model: session.detectedModel || "auto",
|
||||
@@ -344,6 +424,7 @@ async function streamSessionTurn({ res, session, requestId, stream, blocks, tool
|
||||
if (res.writableEnded || finished) return;
|
||||
sawToolCall = true;
|
||||
flushText();
|
||||
markFirstToken("tool_call");
|
||||
const chunk = toolCallChunk({
|
||||
id: requestId,
|
||||
model: session.detectedModel || "auto",
|
||||
@@ -383,6 +464,9 @@ async function streamSessionTurn({ res, session, requestId, stream, blocks, tool
|
||||
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();
|
||||
}
|
||||
@@ -462,6 +546,9 @@ 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
|
||||
|
||||
Reference in New Issue
Block a user