UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

236 lines • 9.66 kB
import { collectServerCatalogForCache, writeMcpCachedServer } from "./catalog-cache.js"; import { markMcpConnectionNeedsAuth } from "./health.js"; import { createMcpLogger } from "./log.js"; import { ensureMcpResourceSubscriptions } from "./resources.js"; import { SharedMcpLease } from "./shared-lease.js"; import { safeTimer } from "./wrap.js"; export const MCP_STARTUP_RACE_MS = 250; export const MCP_STARTUP_TIMEOUT_ENV = "SENPI_MCP_STARTUP_TIMEOUT_MS"; /** * How long a consumer that must OBSERVE the attach waits for the connects this * race backgrounded. Each connect is itself bounded by the server's * `connectTimeoutMs` (15s default), so this is the earlier point at which the * user's turn stops waiting and the server's catalog lands on a later turn. */ export const MCP_ATTACH_SETTLE_TIMEOUT_MS = 5_000; /** * Resolve the startup-race window (ms) a server's attach connect is bounded by. * Precedence: the `SENPI_MCP_STARTUP_TIMEOUT_MS` env override (a global escape * hatch) beats the per-server `startupTimeoutMs`, which beats the default. A * non-numeric or negative env value is ignored; `0` is honored and makes the * startup window non-blocking (connect is backgrounded immediately). */ export function resolveMcpStartupTimeoutMs(configured) { const raw = process.env[MCP_STARTUP_TIMEOUT_ENV]?.trim(); if (raw !== undefined && raw.length > 0) { const value = Number(raw); if (Number.isFinite(value) && value >= 0) return value; } return configured ?? MCP_STARTUP_RACE_MS; } /** * Completion signal for the connects `raceMcpStartupConnect` backgrounds. * session_start deliberately returns before a slow connect finishes; anything * that assembles session state from the catalog - the first turn's system * prompt build - awaits this instead of assuming the attach already landed. */ export class McpDeferredAttach { #pending = new Set(); track(settled) { // A failed connect still SETTLES the attach, which is what the barrier // asks about; this is also the one place that failure is finally handled, // so it is logged here rather than surfacing as an unhandled rejection. const tracked = settled.then(() => undefined, (error) => { createMcpLogger("startup").warn("Deferred MCP attach failed", { error: error instanceof Error ? error.message : String(error), }); }); this.#pending.add(tracked); void tracked.then(() => this.#pending.delete(tracked)); } async wait(timeoutMs) { const pending = [...this.#pending]; if (pending.length === 0) return "settled"; return await waitForMcpStartupRace(Promise.all(pending).then(() => undefined), timeoutMs); } clear() { this.#pending.clear(); } } export async function raceMcpStartupConnect(options) { const { entry, pi } = options; const claim = { cachedCatalog: entry.cachedCatalog, ownsRegistration: () => pi !== undefined && options.shouldRefreshTools(), settled: () => connect, }; entry.startupCatalogClaim = claim; const releaseClaim = () => { if (entry.startupCatalogClaim === claim) entry.startupCatalogClaim = undefined; }; const connect = ignoreStartupNeedsAuth(entry, connectAndRefreshMcpCatalog(entry, options.serverConfig)).finally(releaseClaim); const result = await waitForMcpStartupRace(connect, options.deadlineMs); if (result === "settled" || options.pi === undefined) return; options.onDeferred(connect.then(() => refreshMcpToolsAfterStartupRace(options))); } const catalogRefreshes = new WeakMap(); export function connectAndRefreshMcpCatalog(entry, serverConfig) { const pending = catalogRefreshes.get(entry); if (pending !== undefined) return pending; const refresh = refreshConnectedMcpCatalog(entry, serverConfig); catalogRefreshes.set(entry, refresh); const finish = () => { if (catalogRefreshes.get(entry) === refresh) catalogRefreshes.delete(entry); }; void refresh.then(finish, finish); return refresh; } /** Reconcile the grant before health recovery without attempting a transport connection. */ export async function prepareMcpAuthentication(entry) { if (entry.isCurrent?.() === false) return false; try { await entry.authPlan?.refresh?.ensureFresh(); } catch (error) { if (entry.isCurrent?.() === false || entry.connection.state === "disabled") return false; const authError = markMcpConnectionNeedsAuth(entry.connection, error); if (authError !== undefined) { entry.logger.warn(authError.message); throw authError; } throw error; } if (entry.isCurrent?.() === false) return false; if (entry.credentialsCurrent?.() === false) { await entry.onCredentialsChanged?.(); return false; } return true; } async function refreshConnectedMcpCatalog(entry, serverConfig) { if (serverConfig === undefined || !(await prepareMcpAuthentication(entry))) return; await connectMcpServer(entry.connection, entry.logger); if (entry.connection.state !== "connected" || entry.isCurrent?.() === false) return; const generation = entry.connection.generation; const ownsCatalog = () => entry.isCurrent?.() !== false && entry.credentialsCurrent?.() !== false && entry.connection.state === "connected" && entry.connection.generation === generation; if (entry.connection instanceof SharedMcpLease) { let catalog; try { catalog = await entry.connection.catalog(); } catch (error) { if (!ownsCatalog()) return; throw error; } if (!ownsCatalog()) { if (entry.credentialsCurrent?.() === false) await entry.onCredentialsChanged?.(); return; } entry.cachedCatalog = catalog; entry.catalogGeneration = generation; entry.cacheRefreshedAfterConnect = true; return; } if (entry.cacheRefreshedAfterConnect && entry.catalogGeneration === generation) return; try { const catalog = await collectServerCatalogForCache(entry.connection, serverConfig, entry.generationHash ?? entry.configHash, entry.credentialIdentity); if (!ownsCatalog()) { if (entry.credentialsCurrent?.() === false) await entry.onCredentialsChanged?.(); return; } entry.cachedCatalog = catalog; entry.catalogGeneration = generation; entry.cacheRefreshedAfterConnect = true; await writeMcpCachedServer(entry.agentDir, entry.name, catalog, ownsCatalog); // Per-resource subscriptions (todo 39): only when the server declares // resources.subscribe; best-effort, failures are non-fatal. if (ownsCatalog()) await ensureMcpResourceSubscriptions(entry.connection.client, catalog.resources ?? []); } catch (error) { if (!ownsCatalog()) return; entry.logger.warn("Failed to refresh MCP catalog cache", { error: error instanceof Error ? error.message : String(error), }); } } async function connectMcpServer(connection, logger) { const generation = connection.generation; try { await connection.connect(); } catch (error) { // Dispose/disable or a renew superseded this attempt: its transport can close after that returned, so the late // rejection is our own teardown, not a server failure, and must neither degrade nor log (senpi#4013). // The generation check relies on reconnect being timer-scheduled (reconnect.ts scheduleReconnect): a degrade // raised inside this attempt cannot bump the generation before this catch runs and hide a real failure. if (connection.state === "disabled" || connection.generation !== generation) return; const failure = error instanceof Error ? error : new Error(String(error)); if (connection.lastError === undefined) connection.markDegraded(failure); logger?.warn(failure.message); } } export async function ignoreStartupNeedsAuth(entry, connect) { try { await connect; } catch (error) { if (entry.connection.state === "needs_auth") return; throw error; } } async function refreshMcpToolsAfterStartupRace(options) { if (options.pi === undefined || !options.shouldRefreshTools()) return; try { await options.registerDirectTools(options.pi); } catch (error) { createMcpLogger("service").warn("Failed to refresh MCP tools after startup race", { error: error instanceof Error ? error.message : String(error), }); } } export async function waitForMcpStartupRace(connect, deadlineMs = MCP_STARTUP_RACE_MS) { let timeout; try { return await Promise.race([ connect.then(() => "settled"), new Promise((resolve) => { timeout = safeTimer("startup.race", deadlineMs, () => resolve("timeout"), { logger: createMcpLogger("startup"), }); }), ]); } finally { if (timeout !== undefined) clearTimeout(timeout); } } export function shouldRaceMcpStartup(lifecycle) { return lifecycle === "eager" || lifecycle === "keep-alive"; } //# sourceMappingURL=startup-race.js.map