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:
+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()));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user