@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
167 lines • 6.11 kB
JavaScript
import { AuthError, ConnectError, isMcpSessionExpiredError, isRetriableMcpError, SessionExpiredError, } from "./errors.js";
import { isMcpNeedsAuthError } from "./needs-auth.js";
import { reconnectMcpNow } from "./reconnect.js";
import { McpMrtrError } from "./modern/errors.js";
export const MCP_PING_STALE_MS = 30_000;
export const MCP_PING_TIMEOUT_MS = 2_000;
const healthByConnection = new WeakMap();
export async function ensureMcpToolCallConnection(connection, ensureFresh) {
await ensureFreshAuth(connection, ensureFresh);
const health = healthStateFor(connection);
if (connection.state !== "connected") {
if (connection.state === "idle" || connection.state === "connecting") {
try {
await connection.connect();
}
catch (error) {
if (isMcpNeedsAuthError(error))
throw headlessAuthError(connection, error);
throw error;
}
}
else if (connection.state === "needs_auth") {
throw headlessAuthError(connection);
}
else {
await renewConnection(connection, health);
return;
}
}
const lastSuccessfulPingAtMs = health.lastSuccessfulPingAtMs;
if (lastSuccessfulPingAtMs !== undefined && Date.now() - lastSuccessfulPingAtMs <= MCP_PING_STALE_MS) {
return;
}
if (health.pendingValidation !== undefined) {
await health.pendingValidation;
return;
}
const pendingValidation = pingOrRenew(connection, health).finally(() => {
if (health.pendingValidation === pendingValidation)
health.pendingValidation = undefined;
});
health.pendingValidation = pendingValidation;
await pendingValidation;
}
export async function withMcpSessionExpiryRetry(connection, operation) {
try {
return await operation();
}
catch (error) {
if (error instanceof McpMrtrError)
throw error;
if (!isMcpSessionExpiredError(error))
throw error;
connection.markDegraded(sessionExpiredError(connection, error, true));
await reconnectMcpNow(connection);
try {
return await operation();
}
catch (retryError) {
if (!isMcpSessionExpiredError(retryError))
throw retryError;
const expired = sessionExpiredError(connection, retryError, false);
connection.markSuspended(expired);
throw expired;
}
}
}
export async function withMcpRetriableFailedSendRetry(connection, operation) {
try {
return await operation();
}
catch (error) {
if (error instanceof McpMrtrError)
throw error;
if (!isRetriableFailedSendError(error))
throw error;
connection.markDegraded(failedSendError(connection, error, true));
await connection.renew();
try {
return await operation();
}
catch (retryError) {
if (isRetriableFailedSendError(retryError)) {
connection.markDegraded(failedSendError(connection, retryError, false));
}
throw retryError;
}
}
}
function healthStateFor(connection) {
let health = healthByConnection.get(connection);
if (health === undefined) {
health = { lastSuccessfulPingAtMs: undefined, pendingValidation: undefined };
healthByConnection.set(connection, health);
}
return health;
}
async function pingOrRenew(connection, health) {
try {
await connection.client.ping({ timeout: MCP_PING_TIMEOUT_MS });
health.lastSuccessfulPingAtMs = Date.now();
}
catch (error) {
connection.markDegraded(error instanceof Error ? error : new Error(String(error)));
await renewConnection(connection, health);
}
}
async function renewConnection(connection, health) {
try {
await connection.renew();
}
catch (error) {
if (isMcpNeedsAuthError(error))
throw headlessAuthError(connection, error);
throw error;
}
health.lastSuccessfulPingAtMs = Date.now();
}
async function ensureFreshAuth(connection, ensureFresh) {
if (ensureFresh === undefined)
return;
try {
await ensureFresh();
}
catch (error) {
const authError = markMcpConnectionNeedsAuth(connection, error);
if (authError !== undefined)
throw authError;
throw error;
}
}
export function markMcpConnectionNeedsAuth(connection, error) {
if (!isMcpNeedsAuthError(error))
return undefined;
const authError = headlessAuthError(connection, error);
connection.markNeedsAuth(authError);
return authError;
}
function isRetriableFailedSendError(error) {
return isRetriableMcpError(error) && !isMcpSessionExpiredError(error);
}
function failedSendError(connection, cause, retriable) {
const suffix = retriable
? "reconnecting once before retry"
: `post-reconnect retry also failed; run /mcp reconnect ${connection.serverName}`;
return new ConnectError(`MCP server ${connection.serverName} failed to send tool call; ${suffix}`, {
cause,
phase: "call",
retriable,
serverName: connection.serverName,
});
}
function sessionExpiredError(connection, cause, retriable) {
const suffix = retriable
? "reinitializing once"
: `reinitialize retry also expired; run /mcp reconnect ${connection.serverName}`;
return new SessionExpiredError(`MCP server ${connection.serverName} session expired; ${suffix}`, {
cause,
phase: "session",
retriable,
serverName: connection.serverName,
});
}
function headlessAuthError(connection, cause) {
return new AuthError(`MCP server ${connection.serverName} needs OAuth. Run senpi interactive, then /mcp auth-start ${connection.serverName} and /mcp auth-complete ${connection.serverName} <redirect-url>.`, { cause, phase: "auth", serverName: connection.serverName });
}
//# sourceMappingURL=health.js.map