Files
cursor-agent-api-proxy/src/session-manager.mjs
T
Ubuntu 95e6a5f97e 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.
2026-11-06 08:32:36 +00:00

824 lines
26 KiB
JavaScript

/**
* Cursor-agent session manager (ACP transport).
*
* 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.
*
* Built-in cursor-agent tools are denied via session/request_permission.
* Images are sent as native ACP image ContentBlocks (not via Read).
*/
import { spawn } from "node:child_process";
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";
export const SESSION_TTL_MS = parseInt(process.env.PROXY_SESSION_TTL_MS || "120000", 10);
/** Hard deadline for a single in-flight turn (thinking-heavy vision turns
* legitimately run long; the idle TTL must not kill them mid-turn). */
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";
/**
* Env vars the cursor-agent child is allowed to see. Everything else from
* the proxy environment (notably PROXY_INTERNAL_TOKEN and any other pod
* secret) is stripped: the child executes model-directed code paths, so it
* must never hold proxy credentials. CURSOR_API_KEY is passed on explicitly.
*/
const CHILD_ENV_ALLOWLIST = new Set([
"PATH",
"HOME",
"LANG",
"LC_ALL",
"TERM",
"TZ",
"NODE_ENV",
"NO_OPEN_BROWSER",
"NO_COLOR",
"SSL_CERT_FILE",
"SSL_CERT_DIR",
// Egress plumbing (only route hints — not credentials). The child needs
// these to reach the Cursor API from egress-constrained environments.
"HTTP_PROXY",
"http_proxy",
"HTTPS_PROXY",
"https_proxy",
"ALL_PROXY",
"all_proxy",
"NO_PROXY",
"no_proxy",
]);
/** Build a minimal environment for the cursor-agent child process. */
export function buildChildEnv(parentEnv) {
const env = {};
for (const name of CHILD_ENV_ALLOWLIST) {
if (parentEnv[name] !== undefined) env[name] = parentEnv[name];
}
if (parentEnv.CURSOR_API_KEY !== undefined) {
env.CURSOR_API_KEY = parentEnv.CURSOR_API_KEY;
}
return env;
}
/**
* Pick the safest answer for a cursor/ask_question request we auto-answer.
* "Trust" / full-access prompts must never be answered affirmatively by
* picking the first option (that is how the deployed PVC config ended up
* with allow-all permissions). Prefer an explicit deny/reject-style option;
* fall back to the last option (dialogs list "Yes / No" style pairs where
* the safe answer is last).
*/
export function pickSafeQuestionOption(options) {
if (!Array.isArray(options) || options.length === 0) return null;
const denyish = options.find((o) => /deny|reject|no\b|don'?t/i.test(String(o.label ?? o.name ?? o.text ?? "")));
if (denyish) return denyish;
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
* @param {string} requested
*/
export function resolveModelId(sessionResult, requested) {
const available = sessionResult.models?.availableModels || [];
if (available.length > 0) {
if (!requested || requested === "auto") {
return sessionResult.models.currentModelId || available[0].modelId;
}
const exact = available.find((m) => m.modelId === requested || m.name === requested);
if (exact) return exact.modelId;
const byName = available.find((m) => m.name?.toLowerCase() === requested.toLowerCase());
if (byName) return byName.modelId;
const prefix = available.find(
(m) => m.modelId.startsWith(`${requested}[`) || m.modelId.startsWith(requested)
);
if (prefix) return prefix.modelId;
const contains = available.find((m) => m.modelId.includes(requested));
if (contains) return contains.modelId;
return sessionResult.models.currentModelId || available[0].modelId;
}
const modelOption = (sessionResult.configOptions || []).find(
(o) => o.id === "model" || o.category === "model"
);
return pickModelValueId(modelOption, requested);
}
/**
* Pick an ACP model config value for the requested OpenAI model id.
* @param {object} modelOption session/new config option with id "model"
* @param {string} requested e.g. "auto", "gpt-5.2"
*/
export function pickModelValueId(modelOption, requested) {
const options = modelOption?.options || [];
if (!options.length) return null;
if (!requested || requested === "auto") {
const auto = options.find((o) => o.value === "default[]" || o.name === "Auto");
return auto?.value || modelOption.currentValue || options[0].value;
}
const exact = options.find((o) => o.value === requested);
if (exact) return exact.value;
const byName = options.find((o) => o.name?.toLowerCase() === requested.toLowerCase());
if (byName) return byName.value;
const prefix = options.find(
(o) => o.value.startsWith(`${requested}[`) || o.value.startsWith(requested)
);
if (prefix) return prefix.value;
const contains = options.find((o) => o.value.includes(requested));
if (contains) return contains.value;
return null;
}
function pickPermissionOption(options, allow) {
if (!Array.isArray(options) || options.length === 0) return null;
const kindMatch = allow
? (o) => o.kind === "allow_once" || o.kind === "allow_always"
: (o) => o.kind === "reject_once" || o.kind === "reject_always";
return options.find(kindMatch) || (allow ? options[0] : options[options.length - 1]);
}
export function extractToolNameFromPermission(params) {
const tool = params?.toolCall;
if (!tool) return "";
if (tool.rawInput && typeof tool.rawInput === "object" && typeof tool.rawInput.name === "string") {
let name = tool.rawInput.name;
if (name.startsWith("mcp_client_")) {
name = name.slice("mcp_client_".length);
}
return name;
}
if (typeof tool.title === "string") {
const clientMcp = tool.title.match(/^client-([^:]+):\s*(\S+)/);
if (clientMcp) {
return clientMcp[2];
}
const m = tool.title.match(/^(\S+)/);
if (m) return m[1].replace(/:$/, "");
}
return "";
}
function mapStopReason(stopReason) {
if (stopReason === "end_turn") return "stop";
if (stopReason === "cancelled") return "error";
return "stop";
}
export class CursorSession {
constructor({ sessionId, tools, model, log }) {
this.sessionId = sessionId;
this.tools = tools || [];
this.clientToolNames = new Set(this.tools.map((t) => t.function?.name).filter(Boolean));
this.model = model || "auto";
this.log = log || console.error;
this.detectedModel = model || "auto";
this.createdAt = Date.now();
this.lastActivityAt = Date.now();
this.workDir = null;
this.cursorProc = null;
this.acp = null;
this.mcp = null;
this.acpSessionId = null;
this.timeoutHandle = null;
this._finishToolCallsTimer = null;
this.terminated = false;
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();
}
/** 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 args = ["acp"];
// Minimal env: the child executes model-directed code paths and must not
// hold proxy credentials (PROXY_INTERNAL_TOKEN etc.). See buildChildEnv.
const env = buildChildEnv(process.env);
// Dedicated agent HOME (uid 65533): the child's runtime state never
// lands in the proxy's PVC-mounted HOME, so a compromised child can
// neither poison the proxy's cursor config nor read its caches.
if (process.env.CURSOR_AGENT_HOME) {
env.HOME = process.env.CURSOR_AGENT_HOME;
}
// Run the child as a dedicated unprivileged uid (default 65533) so that
// even a fully compromised agent cannot read proxy-owned secrets
// (files 0400 proxy-uid) or /proc/<proxy-pid>/environ. The proxy itself
// keeps uid 65534 (nobody). Only meaningful when running as root-less
// with distinct uids available (Kubernetes runAsUser).
const childUid = parseInt(process.env.CURSOR_AGENT_UID || "65533", 10);
const spawnOptions = {
cwd: this.workDir,
env,
stdio: ["pipe", "pipe", "pipe"],
};
if (process.getuid && process.getuid() === 0) {
// Only root can setuid a child; in Kubernetes we are non-root, so the
// uid separation is achieved at pod level instead (securityContext).
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,
stdout: this.cursorProc.stdout,
log: (...a) => this.log(`[acp:${this.sessionId}]`, ...a),
});
this.acp.onSessionUpdate = (params) => this._onSessionUpdate(params);
this.acp.onIncomingRequest = (method, params) => this._onIncomingRequest(method, params);
this.cursorProc.stderr.on("data", (d) =>
this.log(`[cursor:${this.sessionId} stderr] ${d.toString().trim()}`)
);
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 = [
{
name: "client",
command: MCP_BRIDGE,
args: [socketPath],
env: [],
},
];
const tNew = nowMs();
let newSessionResult;
try {
newSessionResult = await this.acp.request("session/new", {
cwd: this.workDir,
mcpServers,
});
} catch (e) {
if (e.code === -32000) {
await this.acp.request("authenticate", { methodId: "cursor_login" });
newSessionResult = await this.acp.request("session/new", {
cwd: this.workDir,
mcpServers,
});
} else {
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,
configId: "model",
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);
const allow = this.clientToolNames.has(toolName);
const option = pickPermissionOption(params.options, allow);
if (!option) {
return { outcome: { outcome: "cancelled" } };
}
const optionId = option.optionId || option.id;
return { outcome: { outcome: "selected", optionId } };
}
if (method === "cursor/ask_question") {
// Auto-answer agent questions with the SAFE option only. The deployed
// config once drifted to allow-all because we blindly picked options[0]
// ("Yes, allow full access") on the trust dialog.
const first = params?.questions?.[0];
if (!first) return { answers: {} };
const safe = pickSafeQuestionOption(first.options);
return { answers: safe ? { [first.id]: safe.id } : {} };
}
if (method === "cursor/create_plan") {
return { approved: true };
}
if (
method === "cursor/update_todos" ||
method === "cursor/task" ||
method === "cursor/generate_image"
) {
return {};
}
this.log(`[acp] unhandled incoming method: ${method}`);
return {};
}
_onSessionUpdate(params) {
if (!this._handlers || params.sessionId !== this.acpSessionId) return;
const update = params.update;
if (!update) return;
if (update.sessionUpdate === "agent_message_chunk") {
const content = update.content;
if (content?.type === "text" && content.text) {
this._handlers.onAssistantDelta(content.text);
}
this._touchTimer();
return;
}
// agent_thought_chunk and other updates are ignored for OpenAI output.
this._touchTimer();
}
/**
* @param {Array<object>|null} blocks ACP ContentBlocks, or null for follow-up only
*/
runTurn(blocks, handlers) {
this._handlers = handlers;
this.lastActivityAt = Date.now();
if (blocks === null) {
// Follow-up after tool_calls: same session/prompt is still in flight.
this._hasToolCallInTurn = false;
this._resetTimer();
return;
}
this._hasToolCallInTurn = false;
this._promptInFlight = true;
this._resetTimer();
this.acp
.request("session/prompt", {
sessionId: this.acpSessionId,
prompt: blocks,
})
.then((result) => {
this._promptInFlight = false;
if (!this._handlers) return;
if (this.mcp.pending.size > 0 || this._hasToolCallInTurn) {
this._scheduleFinishToolCallsTurn();
return;
}
this._finishTurn(mapStopReason(result.stopReason), null);
})
.catch((e) => {
this._promptInFlight = false;
this.log(`[acp] session/prompt error: ${e.message}`);
if (this._handlers) this._finishTurn("error", null);
});
}
resolveToolCall(toolCallId, result) {
const ok = this.mcp.resolveToolCall(toolCallId, result);
if (ok) {
this.resolvedToolCalls.add(toolCallId);
this.lastActivityAt = Date.now();
this._resetTimer();
}
return ok;
}
_scheduleFinishToolCallsTurn() {
if (this._finishToolCallsTimer) clearTimeout(this._finishToolCallsTimer);
this._finishToolCallsTimer = setTimeout(() => {
this._finishToolCallsTimer = null;
if (!this._handlers || !this._hasToolCallInTurn) return;
if (this.mcp.pending.size === 0) return;
this._finishTurn("tool_calls", null);
}, TOOL_CALL_BATCH_MS);
}
async destroy() {
if (this.terminated) return;
this.terminated = true;
removeFromWarmPool(this);
if (this._finishToolCallsTimer) clearTimeout(this._finishToolCallsTimer);
if (this.timeoutHandle) clearTimeout(this.timeoutHandle);
try {
this.acp?.close();
if (this.cursorProc && this.cursorProc.exitCode === null) {
this.cursorProc.kill("SIGTERM");
await new Promise((r) => {
const kill = setTimeout(() => {
try {
this.cursorProc?.kill("SIGKILL");
} catch {
/* ignore */
}
r();
}, 5000);
this.cursorProc?.once("close", () => {
clearTimeout(kill);
r();
});
});
}
} catch {
/* ignore */
}
try {
await this.mcp?.stop();
} catch {
/* ignore */
}
try {
if (this.workDir) rmSync(this.workDir, { recursive: true, force: true });
} catch {
/* ignore */
}
SESSIONS.delete(this.sessionId);
}
_resetTimer() {
if (this.timeoutHandle) clearTimeout(this.timeoutHandle);
// While a turn is in flight the TTL acts as a hard turn-deadline
// (longer than idle): thinking-heavy turns legitimately run for many
// minutes without emitting chunks.
const timeout = this._promptInFlight ? TURN_DEADLINE_MS : SESSION_TTL_MS;
this.timeoutHandle = setTimeout(async () => {
this.log(`[cursor:${this.sessionId}] TTL expired (idle ${SESSION_TTL_MS}ms)`);
await this.destroy();
scheduleWarmPoolFill();
}, timeout);
}
/** Re-arm the TTL timer after observed activity (mid-turn chunks etc). */
_touchTimer() {
if (this.timeoutHandle) this._resetTimer();
}
_finishTurn(reason, usage) {
if (!this._handlers) return;
const handlers = this._handlers;
this._handlers = null;
this._promptInFlight = false;
this._resetTimer();
void Promise.resolve(handlers.onFinish(reason, usage));
}
}
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})`);
err.code = "too_many_sessions";
throw err;
}
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();
SESSIONS.delete(sessionId);
throw e;
}
}
export function findSessionForFollowUp(body) {
const allToolResults = (body.messages || []).filter((m) => m.role === "tool");
if (allToolResults.length === 0) return null;
// Only tool results that were never resolved in a candidate session can
// route the request. Re-sent history (results already resolved earlier in
// this session) must not match — otherwise every follow-up turn re-logs
// every historical id as "not pending".
const openToolResults = allToolResults.filter(
(tr) => tr.tool_call_id !== undefined && !sessionsHaveResolved(tr.tool_call_id)
);
if (openToolResults.length === 0) return null;
for (const session of SESSIONS.values()) {
if (!session.mcp) continue;
for (const tr of openToolResults) {
if (session.mcp.pending.has(tr.tool_call_id)) {
return { session, toolResults: openToolResults };
}
}
}
return null;
}
/** True if any live session already resolved this tool_call_id. */
function sessionsHaveResolved(toolCallId) {
for (const session of SESSIONS.values()) {
if (session.resolvedToolCalls?.has(toolCallId)) return true;
}
return false;
}
export function getSession(sessionId) {
return SESSIONS.get(sessionId);
}
export async function destroyAllSessions() {
const warm = WARM_POOL.splice(0, WARM_POOL.length);
const all = [...SESSIONS.values(), ...warm];
SESSIONS.clear();
await Promise.all(all.map((s) => s.destroy()));
}