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:
@@ -86,6 +86,8 @@ spec:
|
||||
value: "120000"
|
||||
- name: PROXY_MAX_CONCURRENT_SESSIONS
|
||||
value: "4"
|
||||
- name: PROXY_WARM_POOL_SIZE
|
||||
value: "2"
|
||||
- name: ACP_REQUEST_TIMEOUT_MS
|
||||
value: "1500000"
|
||||
- name: PROXY_INTERNAL_TOKEN
|
||||
|
||||
@@ -94,6 +94,8 @@ spec:
|
||||
value: "120000"
|
||||
- name: PROXY_MAX_CONCURRENT_SESSIONS
|
||||
value: "4"
|
||||
- name: PROXY_WARM_POOL_SIZE
|
||||
value: "2"
|
||||
- name: ACP_REQUEST_TIMEOUT_MS
|
||||
value: "1500000"
|
||||
- name: PROXY_INTERNAL_TOKEN
|
||||
|
||||
+2
-1
@@ -20,5 +20,6 @@ fi
|
||||
# agent child processes.
|
||||
chmod 1777 /tmp 2>/dev/null || true
|
||||
|
||||
# The HTTP server. Sessions spawn cursor-agent ACP subprocesses per request.
|
||||
# The HTTP server. A warm pool keeps bootstrapped ACP processes ready;
|
||||
# each request still opens session/new with request-specific MCP tools.
|
||||
exec node /app/src/server.mjs
|
||||
|
||||
+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
|
||||
|
||||
+267
-28
@@ -4,6 +4,10 @@
|
||||
* Each HTTP chat request creates an ACP session (`agent acp`):
|
||||
* initialize → session/new (MCP stdio bridge) → session/prompt
|
||||
*
|
||||
* Cold-start is split so a warm pool can pre-run bootstrap
|
||||
* (spawn + initialize + authenticate). Request-specific MCP tools and
|
||||
* session/new happen on acquire via openSession().
|
||||
*
|
||||
* Client tools are advertised via in-process ProxyMcpServer. MCP tools/call
|
||||
* parks until the HTTP client returns role:"tool" with the result.
|
||||
*
|
||||
@@ -16,6 +20,7 @@ import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { performance } from "node:perf_hooks";
|
||||
import { AcpClient } from "./acp-client.mjs";
|
||||
import { ProxyMcpServer } from "./mcp-server.mjs";
|
||||
|
||||
@@ -25,6 +30,8 @@ export const SESSION_TTL_MS = parseInt(process.env.PROXY_SESSION_TTL_MS || "1200
|
||||
export const TURN_DEADLINE_MS = parseInt(process.env.PROXY_TURN_DEADLINE_MS || "900000", 10);
|
||||
export const MAX_CONCURRENT_SESSIONS = parseInt(process.env.PROXY_MAX_CONCURRENT_SESSIONS || "4", 10);
|
||||
export const TOOL_CALL_BATCH_MS = parseInt(process.env.PROXY_TOOL_CALL_BATCH_MS || "50", 10);
|
||||
/** Number of pre-bootstrapped ACP processes kept ready (0 disables). */
|
||||
export const WARM_POOL_SIZE = parseInt(process.env.PROXY_WARM_POOL_SIZE || "2", 10);
|
||||
const REAL_AGENT = process.env.CURSOR_AGENT_BIN || "/usr/local/bin/agent.real";
|
||||
const MCP_BRIDGE = process.env.MCP_BRIDGE_BIN || "/app/scripts/mcp-stdio-bridge.sh";
|
||||
|
||||
@@ -85,9 +92,57 @@ export function pickSafeQuestionOption(options) {
|
||||
return options[options.length - 1];
|
||||
}
|
||||
|
||||
/** Monotonic ms clock for stage timings. */
|
||||
export function nowMs() {
|
||||
return performance.now();
|
||||
}
|
||||
|
||||
/** Format a duration in ms for logs (one decimal). */
|
||||
export function fmtMs(ms) {
|
||||
return `${Math.round(ms * 10) / 10}ms`;
|
||||
}
|
||||
|
||||
/** @type {Map<string, CursorSession>} */
|
||||
const SESSIONS = new Map();
|
||||
|
||||
/** Bootstrapped (initialize done) sessions waiting for openSession(). */
|
||||
/** @type {CursorSession[]} */
|
||||
const WARM_POOL = [];
|
||||
let warmInFlight = 0;
|
||||
let warmPoolLog = (...args) => console.error("[warm-pool]", ...args);
|
||||
let fillScheduled = false;
|
||||
|
||||
function newSessionId() {
|
||||
return `s_${randomUUID().replace(/-/g, "").slice(0, 16)}`;
|
||||
}
|
||||
|
||||
function removeFromWarmPool(session) {
|
||||
const idx = WARM_POOL.indexOf(session);
|
||||
if (idx >= 0) WARM_POOL.splice(idx, 1);
|
||||
}
|
||||
|
||||
function isWarmCandidateHealthy(session) {
|
||||
return (
|
||||
session &&
|
||||
!session.terminated &&
|
||||
!session.acpSessionId &&
|
||||
session.bootstrapped &&
|
||||
session.cursorProc &&
|
||||
session.cursorProc.exitCode === null &&
|
||||
!session.cursorProc.killed
|
||||
);
|
||||
}
|
||||
|
||||
function takeWarmSession() {
|
||||
while (WARM_POOL.length > 0) {
|
||||
const session = WARM_POOL.pop();
|
||||
if (isWarmCandidateHealthy(session)) return session;
|
||||
warmPoolLog(`discarding unhealthy warm session ${session?.sessionId}`);
|
||||
void session?.destroy();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve ACP model id from session/new response and requested OpenAI model id.
|
||||
* @param {object} sessionResult session/new result
|
||||
@@ -208,39 +263,36 @@ export class CursorSession {
|
||||
this._handlers = null;
|
||||
this._hasToolCallInTurn = false;
|
||||
this._promptInFlight = false;
|
||||
this.bootstrapped = false;
|
||||
this.fromWarmPool = false;
|
||||
/** Last start-stage timings (ms), for request logs. */
|
||||
this.lastTimings = null;
|
||||
/** tool_call_ids already resolved with a client-provided result in this
|
||||
* session — excluded from follow-up matching so re-sent history never
|
||||
* matches a session again (and never re-logs "not pending"). */
|
||||
this.resolvedToolCalls = new Set();
|
||||
}
|
||||
|
||||
async start() {
|
||||
/** Apply request-specific tools/model/log onto a warm bootstrap. */
|
||||
adoptRequest({ tools, model, log }) {
|
||||
this.tools = tools || [];
|
||||
this.clientToolNames = new Set(this.tools.map((t) => t.function?.name).filter(Boolean));
|
||||
this.model = model || "auto";
|
||||
this.detectedModel = this.model;
|
||||
if (log) this.log = log;
|
||||
}
|
||||
|
||||
/**
|
||||
* Spawn cursor-agent and run ACP initialize (+ optional authenticate).
|
||||
* Does not start MCP or session/new — that is openSession().
|
||||
*/
|
||||
async bootstrap() {
|
||||
if (this.bootstrapped) return this;
|
||||
const timings = {};
|
||||
const t0 = nowMs();
|
||||
|
||||
this.workDir = mkdtempSync(join(tmpdir(), `cursor-${this.sessionId}-`));
|
||||
|
||||
const mcpTools = this.tools.map((t) => ({
|
||||
name: t.function.name,
|
||||
description: t.function.description,
|
||||
inputSchema: t.function.parameters,
|
||||
}));
|
||||
|
||||
const socketPath = join(this.workDir, "mcp.sock");
|
||||
this.mcp = new ProxyMcpServer({
|
||||
socketPath,
|
||||
tools: mcpTools,
|
||||
onToolCall: ({ toolCallId, name, arguments: args }) => {
|
||||
if (!this._handlers) return;
|
||||
this._hasToolCallInTurn = true;
|
||||
this._handlers.onToolCall({
|
||||
id: toolCallId,
|
||||
name,
|
||||
arguments: JSON.stringify(args || {}),
|
||||
});
|
||||
this._scheduleFinishToolCallsTurn();
|
||||
},
|
||||
log: (...args) => this.log(`[mcp:${this.sessionId}]`, ...args),
|
||||
});
|
||||
await this.mcp.start();
|
||||
|
||||
const args = ["acp"];
|
||||
// Minimal env: the child executes model-directed code paths and must not
|
||||
// hold proxy credentials (PROXY_INTERNAL_TOKEN etc.). See buildChildEnv.
|
||||
@@ -269,7 +321,9 @@ export class CursorSession {
|
||||
spawnOptions.uid = childUid;
|
||||
}
|
||||
|
||||
const tSpawn = nowMs();
|
||||
this.cursorProc = spawn(REAL_AGENT, args, spawnOptions);
|
||||
timings.spawn = nowMs() - tSpawn;
|
||||
|
||||
this.acp = new AcpClient({
|
||||
stdin: this.cursorProc.stdin,
|
||||
@@ -285,15 +339,71 @@ export class CursorSession {
|
||||
);
|
||||
this.cursorProc.on("close", (code) => {
|
||||
this.log(`[cursor:${this.sessionId}] process exited code=${code}`);
|
||||
removeFromWarmPool(this);
|
||||
if (this._handlers) this._finishTurn("error", null);
|
||||
});
|
||||
this.cursorProc.on("error", (e) => {
|
||||
this.log(`[cursor:${this.sessionId}] spawn error: ${e.message}`);
|
||||
removeFromWarmPool(this);
|
||||
if (this._handlers) this._finishTurn("error", null);
|
||||
});
|
||||
|
||||
const tInit = nowMs();
|
||||
await this.acp.initialize();
|
||||
timings.initialize = nowMs() - tInit;
|
||||
|
||||
const tAuth = nowMs();
|
||||
await this.acp.authenticateIfNeeded();
|
||||
timings.authenticate = nowMs() - tAuth;
|
||||
|
||||
this.bootstrapped = true;
|
||||
timings.bootstrap_total = nowMs() - t0;
|
||||
this.lastTimings = { ...(this.lastTimings || {}), ...timings };
|
||||
this.log(
|
||||
`[timing] session=${this.sessionId} bootstrap spawn=${fmtMs(timings.spawn)} initialize=${fmtMs(timings.initialize)} authenticate=${fmtMs(timings.authenticate)} total=${fmtMs(timings.bootstrap_total)}`
|
||||
);
|
||||
this._resetTimer();
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start MCP bridge + session/new (+ optional model config) on a bootstrapped process.
|
||||
*/
|
||||
async openSession() {
|
||||
if (!this.bootstrapped) {
|
||||
await this.bootstrap();
|
||||
}
|
||||
if (this.acpSessionId) return this;
|
||||
|
||||
const timings = {};
|
||||
const t0 = nowMs();
|
||||
|
||||
const mcpTools = this.tools.map((t) => ({
|
||||
name: t.function.name,
|
||||
description: t.function.description,
|
||||
inputSchema: t.function.parameters,
|
||||
}));
|
||||
|
||||
const socketPath = join(this.workDir, "mcp.sock");
|
||||
this.mcp = new ProxyMcpServer({
|
||||
socketPath,
|
||||
tools: mcpTools,
|
||||
onToolCall: ({ toolCallId, name, arguments: args }) => {
|
||||
if (!this._handlers) return;
|
||||
this._hasToolCallInTurn = true;
|
||||
this._handlers.onToolCall({
|
||||
id: toolCallId,
|
||||
name,
|
||||
arguments: JSON.stringify(args || {}),
|
||||
});
|
||||
this._scheduleFinishToolCallsTurn();
|
||||
},
|
||||
log: (...args) => this.log(`[mcp:${this.sessionId}]`, ...args),
|
||||
});
|
||||
|
||||
const tMcp = nowMs();
|
||||
await this.mcp.start();
|
||||
timings.mcp_listen = nowMs() - tMcp;
|
||||
|
||||
const mcpServers = [
|
||||
{
|
||||
@@ -304,6 +414,7 @@ export class CursorSession {
|
||||
},
|
||||
];
|
||||
|
||||
const tNew = nowMs();
|
||||
let newSessionResult;
|
||||
try {
|
||||
newSessionResult = await this.acp.request("session/new", {
|
||||
@@ -321,10 +432,12 @@ export class CursorSession {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
timings.session_new = nowMs() - tNew;
|
||||
|
||||
this.acpSessionId = newSessionResult.sessionId;
|
||||
const modelId = resolveModelId(newSessionResult, this.model);
|
||||
const currentModelId = newSessionResult.models?.currentModelId;
|
||||
const tModel = nowMs();
|
||||
if (modelId && modelId !== currentModelId) {
|
||||
await this.acp.request("session/set_config_option", {
|
||||
sessionId: this.acpSessionId,
|
||||
@@ -332,12 +445,29 @@ export class CursorSession {
|
||||
value: modelId,
|
||||
});
|
||||
}
|
||||
timings.set_model = nowMs() - tModel;
|
||||
this.detectedModel = modelId || currentModelId || this.model;
|
||||
|
||||
timings.open_session_total = nowMs() - t0;
|
||||
this.lastTimings = { ...(this.lastTimings || {}), ...timings };
|
||||
this.log(
|
||||
`[timing] session=${this.sessionId} open_session mcp_listen=${fmtMs(timings.mcp_listen)} session_new=${fmtMs(timings.session_new)} set_model=${fmtMs(timings.set_model)} total=${fmtMs(timings.open_session_total)}`
|
||||
);
|
||||
this._resetTimer();
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Full cold start: bootstrap + openSession. */
|
||||
async start() {
|
||||
const t0 = nowMs();
|
||||
await this.bootstrap();
|
||||
await this.openSession();
|
||||
const total = nowMs() - t0;
|
||||
this.lastTimings = { ...(this.lastTimings || {}), start_total: total };
|
||||
this.log(`[timing] session=${this.sessionId} start_total=${fmtMs(total)}`);
|
||||
return this;
|
||||
}
|
||||
|
||||
async _onIncomingRequest(method, params) {
|
||||
if (method === "session/request_permission") {
|
||||
const toolName = extractToolNameFromPermission(params);
|
||||
@@ -455,6 +585,7 @@ export class CursorSession {
|
||||
async destroy() {
|
||||
if (this.terminated) return;
|
||||
this.terminated = true;
|
||||
removeFromWarmPool(this);
|
||||
if (this._finishToolCallsTimer) clearTimeout(this._finishToolCallsTimer);
|
||||
if (this.timeoutHandle) clearTimeout(this.timeoutHandle);
|
||||
try {
|
||||
@@ -501,6 +632,7 @@ export class CursorSession {
|
||||
this.timeoutHandle = setTimeout(async () => {
|
||||
this.log(`[cursor:${this.sessionId}] TTL expired (idle ${SESSION_TTL_MS}ms)`);
|
||||
await this.destroy();
|
||||
scheduleWarmPoolFill();
|
||||
}, timeout);
|
||||
}
|
||||
|
||||
@@ -523,6 +655,73 @@ export function getActiveSessionCount() {
|
||||
return SESSIONS.size;
|
||||
}
|
||||
|
||||
export function getWarmPoolStats() {
|
||||
return {
|
||||
ready: WARM_POOL.length,
|
||||
warming: warmInFlight,
|
||||
target: WARM_POOL_SIZE,
|
||||
};
|
||||
}
|
||||
|
||||
/** Set the logger used by background warm-pool fills. */
|
||||
export function setWarmPoolLogger(log) {
|
||||
if (typeof log === "function") warmPoolLog = log;
|
||||
}
|
||||
|
||||
async function fillWarmPoolOnce() {
|
||||
if (WARM_POOL_SIZE <= 0) return;
|
||||
if (WARM_POOL.length + warmInFlight >= WARM_POOL_SIZE) return;
|
||||
|
||||
warmInFlight += 1;
|
||||
const sessionId = newSessionId();
|
||||
const session = new CursorSession({
|
||||
sessionId,
|
||||
tools: [],
|
||||
model: "auto",
|
||||
log: (...args) => warmPoolLog(...args),
|
||||
});
|
||||
try {
|
||||
await session.bootstrap();
|
||||
if (!isWarmCandidateHealthy(session)) {
|
||||
await session.destroy();
|
||||
return;
|
||||
}
|
||||
WARM_POOL.push(session);
|
||||
warmPoolLog(`ready session=${sessionId} pool=${WARM_POOL.length}/${WARM_POOL_SIZE}`);
|
||||
} catch (e) {
|
||||
warmPoolLog(`bootstrap failed session=${sessionId}: ${e.message}`);
|
||||
try {
|
||||
await session.destroy();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
} finally {
|
||||
warmInFlight -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleWarmPoolFill() {
|
||||
if (WARM_POOL_SIZE <= 0) return;
|
||||
if (fillScheduled) return;
|
||||
fillScheduled = true;
|
||||
queueMicrotask(() => {
|
||||
fillScheduled = false;
|
||||
void maintainWarmPool();
|
||||
});
|
||||
}
|
||||
|
||||
async function maintainWarmPool() {
|
||||
while (WARM_POOL.length + warmInFlight < WARM_POOL_SIZE) {
|
||||
await fillWarmPoolOnce();
|
||||
}
|
||||
}
|
||||
|
||||
/** Start (or top up) the warm pool. Safe to call multiple times. */
|
||||
export function startWarmPool(log) {
|
||||
if (log) setWarmPoolLogger(log);
|
||||
scheduleWarmPoolFill();
|
||||
}
|
||||
|
||||
export async function createSession({ tools, model, log }) {
|
||||
if (SESSIONS.size >= MAX_CONCURRENT_SESSIONS) {
|
||||
const err = new Error(`too many concurrent sessions (max ${MAX_CONCURRENT_SESSIONS})`);
|
||||
@@ -530,11 +729,50 @@ export async function createSession({ tools, model, log }) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
const sessionId = `s_${randomUUID().replace(/-/g, "").slice(0, 16)}`;
|
||||
const session = new CursorSession({ sessionId, tools, model, log });
|
||||
const t0 = nowMs();
|
||||
const requestLog = log || ((...args) => console.error(...args));
|
||||
|
||||
const warm = takeWarmSession();
|
||||
if (warm) {
|
||||
warm.adoptRequest({ tools, model, log: requestLog });
|
||||
warm.fromWarmPool = true;
|
||||
SESSIONS.set(warm.sessionId, warm);
|
||||
try {
|
||||
await warm.openSession();
|
||||
const total = nowMs() - t0;
|
||||
warm.lastTimings = {
|
||||
...(warm.lastTimings || {}),
|
||||
create_session_total: total,
|
||||
from_warm_pool: true,
|
||||
};
|
||||
requestLog(
|
||||
`[timing] session=${warm.sessionId} create_session from_warm=true open=${fmtMs(warm.lastTimings.open_session_total || 0)} total=${fmtMs(total)}`
|
||||
);
|
||||
scheduleWarmPoolFill();
|
||||
return warm;
|
||||
} catch (e) {
|
||||
await warm.destroy();
|
||||
SESSIONS.delete(warm.sessionId);
|
||||
scheduleWarmPoolFill();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
const sessionId = newSessionId();
|
||||
const session = new CursorSession({ sessionId, tools, model, log: requestLog });
|
||||
SESSIONS.set(sessionId, session);
|
||||
try {
|
||||
await session.start();
|
||||
const total = nowMs() - t0;
|
||||
session.lastTimings = {
|
||||
...(session.lastTimings || {}),
|
||||
create_session_total: total,
|
||||
from_warm_pool: false,
|
||||
};
|
||||
requestLog(
|
||||
`[timing] session=${sessionId} create_session from_warm=false total=${fmtMs(total)}`
|
||||
);
|
||||
scheduleWarmPoolFill();
|
||||
return session;
|
||||
} catch (e) {
|
||||
await session.destroy();
|
||||
@@ -578,7 +816,8 @@ export function getSession(sessionId) {
|
||||
}
|
||||
|
||||
export async function destroyAllSessions() {
|
||||
const all = [...SESSIONS.values()];
|
||||
const warm = WARM_POOL.splice(0, WARM_POOL.length);
|
||||
const all = [...SESSIONS.values(), ...warm];
|
||||
SESSIONS.clear();
|
||||
await Promise.all(all.map((s) => s.destroy()));
|
||||
}
|
||||
|
||||
@@ -1,6 +1,30 @@
|
||||
import { describe, it } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { extractToolNameFromPermission } from "./session-manager.mjs";
|
||||
import {
|
||||
extractToolNameFromPermission,
|
||||
fmtMs,
|
||||
nowMs,
|
||||
WARM_POOL_SIZE,
|
||||
} from "./session-manager.mjs";
|
||||
|
||||
describe("fmtMs / nowMs", () => {
|
||||
it("formats durations to one decimal millisecond", () => {
|
||||
assert.equal(fmtMs(12.34), "12.3ms");
|
||||
assert.equal(fmtMs(0), "0ms");
|
||||
});
|
||||
|
||||
it("nowMs is monotonic numeric", () => {
|
||||
const a = nowMs();
|
||||
const b = nowMs();
|
||||
assert.equal(typeof a, "number");
|
||||
assert.ok(b >= a);
|
||||
});
|
||||
|
||||
it("exposes WARM_POOL_SIZE as a non-negative integer", () => {
|
||||
assert.equal(typeof WARM_POOL_SIZE, "number");
|
||||
assert.ok(WARM_POOL_SIZE >= 0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractToolNameFromPermission", () => {
|
||||
it("parses client MCP title format", () => {
|
||||
|
||||
Reference in New Issue
Block a user