UNPKG

@code-yeongyu/senpi

Version:

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

1,280 lines • 67.7 kB
import { ConfigReferenceError } from "@earendil-works/pi-ai/utils/config-reference";
import { getAgentDir } from "../../../../config.js";
import { redactResolvedReferenceData } from "../../../config-reference-redaction.js";
import { getMcpMrtrPresentation } from "../../../mcp-mrtr-presentations.js";
import { getToolSearchService, getToolSearchServiceForExtension, resetToolSearchServiceForTests, ToolSearchService, } from "../tool-search/service.js";
import { mcpCredentialIdentity } from "./auth/catalog-identity.js";
import { resolveAuthMode } from "./auth/context.js";
import { cachedCatalogNeedsRefresh, readMcpCatalogCache } from "./catalog-cache.js";
import { adoptMcpCachedServer, legacyMcpCacheIdentity } from "./catalog-cache-adoption.js";
import { loadMcpConfig, mergeExtensionMcpServers, visitSpawnableMcpServers } from "./config.js";
import { mcpConnectionIdentity, resolveWantedMcpGenerations } from "./config-generation.js";
import { cleanupMcpOutputArtifacts, McpOutputArtifacts } from "./guard/output-guard.js";
import { HostMcpRegistry } from "./host-registry.js";
import { refreshMcpInstructionsForSession } from "./instructions.js";
import { createMcpLogger } from "./log.js";
import { prepareProjectSkillServer } from "./project-skill-policy.js";
import { reconnectMcpNow } from "./reconnect.js";
import { createMcpSessionConnection, disposeEntryConnection } from "./service-connection.js";
import { getMcpServiceExposureStatus } from "./service-exposure.js";
import { registerMcpServiceDirectTools } from "./service-register.js";
import * as scopes from "./service-scopes.js";
import { buildMcpServerSnapshot } from "./service-snapshot.js";
import { refreshMcpToolsOnListChanged, subscribeMcpToolsChanged } from "./service-tools-changed.js";
import { referenceRefusal, resolveSkillMcpServer } from "./skill-server.js";
import { MCP_ATTACH_SETTLE_TIMEOUT_MS, McpDeferredAttach, raceMcpStartupConnect, shouldRaceMcpStartup, waitForMcpStartupRace, } from "./startup-race.js";
import { McpStartupWindows } from "./startup-window.js";
import { safeTimer } from "./wrap.js";
export { registerToolsPreservingActiveSet } from "./active-set.js";
export class McpService {
    #disposed = false;
    #disposeCount = 0;
    #lastDisposeReason = null;
    #sessionContext = null;
    #sessionStartCount = 0;
    #lastSessionStartReason = null;
    #config = null;
    #elicitationUiProvider;
    #mcpInstructions = "";
    #pendingAuth = new Map();
    #interactiveAuthServers = new Set();
    #promptCommandNames = new Set();
    #registrationListeners = new Set();
    #wireStatusListeners = new Set();
    #wireStatusRefreshQueue = Promise.resolve();
    #startupWindows = new McpStartupWindows();
    #refreshActiveSetWhenNoTools = false;
    #bindings = new Map();
    // Attaches and release re-syncs queued or running: a release defers its dispose until none is left.
    #pendingSyncs = 0;
    // Sessions that quit while their own attach was still queued: that attach starts nothing (#2524 review, senpi#2597).
    #releasedSessions = new WeakSet();
    #deferredDisposeReason;
    // Releases waiting for the attaches that deferred their dispose: they settle once the last one does.
    #deferredDisposeWaiters = [];
    #skillServerWarnings = new Set();
    #attachQueue = Promise.resolve();
    #deferredAttach = new McpDeferredAttach();
    #latestWireStatus = { servers: [] };
    #wireStatusBySession = new Map();
    #connections = new Map();
    #connectionKeysByName = new Map();
    #outputArtifacts = new McpOutputArtifacts();
    /** Servers whose references failed in the latest sync; each one is reported, never connected (senpi#3858). */
    #referenceErrors = new Map();
    #registry;
    #shareConnections;
    #servesManySessions;
    /** `servesManySessions` marks the process-wide service every classic session attaches to. */
    constructor(options = {}) {
        this.#registry = options.mcpRegistry ?? new HostMcpRegistry();
        this.#shareConnections = options.mcpRegistry !== undefined;
        this.#servesManySessions = options.servesManySessions === true;
    }
    async attachSession(event, ctx, _pi, options = {}) {
        // RPC inventory changes of this session are held from now until the connects this attach starts settle (senpi#4828).
        const windowSessionId = shouldCaptureWireStatus(ctx) ? ctx.sessionManager?.getSessionId?.() : undefined;
        const startupWindow = windowSessionId === undefined ? undefined : this.#startupWindows.open(windowSessionId);
        const startupConnects = [];
        try {
            await this.#attachQueued(event, ctx, _pi, options, startupConnects);
        }
        finally {
            if (windowSessionId !== undefined && startupWindow !== undefined) {
                void startupWindow
                    .close(startupConnects, (release) => this.#refreshWireStatus(windowSessionId, () => this.#statusOwner(windowSessionId), release))
                    .catch((error) => {
                    createMcpLogger("service").error("Failed to announce the settled MCP startup inventory", error);
                });
            }
        }
    }
    async #attachQueued(event, ctx, _pi, options, startupConnects) {
        // Counted from the moment it queues, so a session's release cannot dispose the service
        // under an attach that has not bound yet.
        await this.#queueSync(async () => {
            if (this.#disposed) {
                throw new Error("The MCP service is disposed; attach the session to a live service instead.");
            }
            // A session that quit while this attach was queued is gone: it binds nothing, and adopting its config would
            // replace the servers its live peers use, with no re-sync to follow. A deferred dispose still runs after it.
            if (_pi !== undefined && this.#releasedSessions.has(_pi))
                return;
            this.#sessionContext = ctx;
            this.#skillServerWarnings.clear();
            this.#sessionStartCount += 1;
            this.#lastSessionStartReason = event.reason;
            // Bind the agent dir at attach time: the startup race can background
            // the catalog cache write past this point, and it must land in the
            // directory this attach resolved, never wherever the environment
            // points when the write finally runs.
            const sessionOptions = {
                ...options,
                agentDir: options.agentDir ?? getAgentDir(),
                projectTrusted: options.projectTrusted ?? ctx.isProjectTrusted(),
            };
            const config = loadMcpConfig({
                agentDir: sessionOptions.agentDir,
                cwd: ctx.cwd,
                env: sessionOptions.env,
                projectTrusted: sessionOptions.projectTrusted ?? ctx.isProjectTrusted(),
            });
            // An extension handling mcp_servers_change connects the registered servers; connecting them here too
            // would open a second connection per server (senpi#4597).
            if (ctx.extensionConnectsMcpServers?.() !== true) {
                mergeExtensionMcpServers(config, ctx.getRegisteredMcpServers?.() ?? []);
            }
            const previous = _pi === undefined ? undefined : this.#bindings.get(_pi);
            if (previous !== undefined &&
                previous.sessionId === ctx.sessionManager?.getSessionId?.() &&
                previous.options.agentDir === sessionOptions.agentDir &&
                previous.options.env === sessionOptions.env &&
                previous.options.projectTrusted === sessionOptions.projectTrusted) {
                // Administrative reattaches do not unload this session's skills.
                // Dropping them here can dispose a peer's in-flight reconnect.
                for (const [name, server] of Object.entries(previous.config.servers)) {
                    if (server.source === "skill")
                        config.servers[name] ??= server;
                }
            }
            const owner = { config, options: sessionOptions, context: ctx };
            const binding = _pi === undefined ? undefined : this.#bind(_pi, owner);
            const current = this.#effectiveConfig(config);
            this.#config = current;
            await this.#syncFromConfig(current, binding ?? owner, event.reason !== "reload", binding, startupConnects);
            if (binding !== undefined)
                await this.#registerDirectTools(binding);
            // Replay promotion markers from the (possibly resumed) session history
            // BEFORE the first turn: the request tool snapshot is taken before the
            // per-turn context event fires, so the context-event replay alone lands
            // one turn late. Doing it here puts restored tools on the very first
            // wire payload after a --continue/resume.
            if (binding !== undefined)
                this.#rehydrateFromSessionHistory(binding);
            // An unbound attach (no `pi`) still reports its own config; a session released while this attach ran reports
            // nothing, so no snapshot outlives its release.
            if (shouldCaptureWireStatus(ctx)) {
                await this.#refreshWireStatus(ctx.sessionManager?.getSessionId?.(), () => binding === undefined ? owner : this.#bindings.get(binding.pi) === binding ? binding : undefined);
            }
        });
    }
    /**
     * A further execution scope of the runtime that owns `pi` joins its binding (brain/hand S16c) without a rebind, a
     * config re-sync or an abort; only its own wire status is published. A `session_start` drops every joined scope.
     */
    async attachScope(ctx, pi) {
        const binding = this.#bindings.get(pi);
        const sessionId = binding === undefined ? undefined : scopes.joinBindingScope(binding, ctx)?.sessionId;
        if (sessionId !== undefined && shouldCaptureWireStatus(ctx))
            await this.refreshWireStatusSnapshot(sessionId);
    }
    /**
     * Run `body` on the attach queue, so it never interleaves with an attach or another sync, and count it as a pending
     * sync from the moment it queues: a release that empties the service defers its dispose until it settles instead of
     * disposing under it. Every attach, release re-sync, credential re-sync and skill attach runs through here.
     */
    async #queueSync(body) {
        this.#pendingSyncs += 1;
        const run = this.#attachQueue.then(body);
        this.#attachQueue = run.then(() => undefined, () => undefined);
        try {
            await run;
        }
        finally {
            this.#pendingSyncs -= 1;
            await this.#disposeIfDeferredAndIdle();
        }
    }
    /** A release that found syncs still pending leaves the dispose to the last of them, once no session is bound. */
    async #disposeIfDeferredAndIdle() {
        const reason = this.#deferredDisposeReason;
        if (reason === undefined || this.#pendingSyncs > 0)
            return;
        this.#deferredDisposeReason = undefined;
        // A session that attached meanwhile keeps the service; otherwise the deferred dispose runs now.
        if (this.#liveBindings().length === 0)
            await this.dispose(reason);
        for (const settle of this.#deferredDisposeWaiters.splice(0))
            settle();
    }
    /**
     * The config the shared connections follow: `preferred` (the attaching session's) plus every server another live
     * session declares and `preferred` does not, so a peer's attach never tears down a server a live session still
     * uses (senpi#2597). A name both declare follows `preferred`, as connections are one per server name.
     */
    #effectiveConfig(preferred) {
        const servers = { ...preferred.servers };
        for (const binding of this.#liveBindings()) {
            for (const [name, server] of Object.entries(binding.config.servers))
                servers[name] ??= server;
        }
        return { ...preferred, servers };
    }
    #bind(pi, owner) {
        const activationRuntime = {
            getActiveTools: () => pi.getActiveTools(),
            setActiveTools: (names) => pi.setActiveTools([...names]),
        };
        const previous = this.#bindings.get(pi);
        // A session-owned service serves exactly one session: a new attach takes over its binding.
        previous?.lifetime.abort();
        if (!this.#servesManySessions) {
            for (const binding of this.#bindings.values())
                binding.lifetime.abort();
            this.#bindings.clear();
        }
        let fallbackToolSearch;
        let holdsProcessFallback = false;
        const sessionToolSearch = getToolSearchServiceForExtension(pi);
        if (sessionToolSearch !== undefined) {
            sessionToolSearch.bindActivationRuntime(activationRuntime);
        }
        else if (this.#liveBindings().some((other) => other.pi !== pi && other.holdsProcessFallback)) {
            // The process-wide fallback already serves another live session; rebinding it would move that
            // session's activation runtime and catalog hook here, so this session gets its own (#2514).
            fallbackToolSearch = new ToolSearchService({ getAllTools: () => [], ...activationRuntime });
        }
        else {
            holdsProcessFallback = true;
            try {
                fallbackToolSearch = getToolSearchService();
                fallbackToolSearch.bindActivationRuntime(activationRuntime);
            }
            catch {
                fallbackToolSearch = getToolSearchService({ getAllTools: () => [], ...activationRuntime });
            }
        }
        const binding = {
            lifetime: new AbortController(),
            presentation: owner.context.ui === undefined ? undefined : getMcpMrtrPresentation(owner.context.ui),
            scopes: new Map(),
            ui: scopes.elicitationUiOf(owner.context),
            pi,
            fallbackToolSearch,
            holdsProcessFallback,
            ...owner,
            registeredIdentities: previous?.registeredIdentities ?? new Map(),
            registration: previous?.registration,
            sessionId: owner.context.sessionManager?.getSessionId?.(),
        };
        // Re-inserting keeps the most recent attach last, which is what a caller naming no session gets.
        this.#bindings.delete(pi);
        this.#bindings.set(pi, binding);
        return binding;
    }
    #toolSearchFor(binding) {
        return getToolSearchServiceForExtension(binding.pi) ?? binding.fallbackToolSearch;
    }
    #liveBindings() {
        for (const [pi, binding] of this.#bindings) {
            // A disposed session retires its own tool-search service; its binding goes with it.
            if (getToolSearchServiceForExtension(binding.pi)?.isDisposed === true) {
                binding.lifetime.abort();
                this.#bindings.delete(pi);
            }
        }
        return [...this.#bindings.values()];
    }
    /** The binding of the session that owns `pi`; without one, the most recently attached live session. */
    #bindingFor(pi) {
        return pi === undefined ? this.#liveBindings().at(-1) : this.#bindings.get(pi);
    }
    /**
     * Release the binding of the session that owns `pi` (#2514). The shared connections keep
     * serving every other live session; once none is left, `disposeReason` disposes the service
     * the way that last session's own exit would.
     */
    async releaseSession(pi, disposeReason) {
        const released = this.#bindings.get(pi);
        released?.lifetime.abort();
        this.#bindings.delete(pi);
        if (disposeReason !== undefined)
            this.#releasedSessions.add(pi);
        const live = this.#liveBindings();
        // A released session's status snapshot goes with it, unless a live binding still reports under its session id.
        const releasedId = released?.sessionId;
        if (releasedId !== undefined && !live.some((binding) => binding.sessionId === releasedId)) {
            this.#wireStatusBySession.delete(releasedId);
            // The id-less read falls back to #latestWireStatus once a single session is live, so rebind it to the
            // remaining session's own snapshot (senpi#3001): without this, the released session's status outlives
            // it whenever the release carries no reason and no re-sync re-captures.
            const remaining = live.at(-1);
            this.#latestWireStatus =
                remaining?.sessionId !== undefined
                    ? (this.#wireStatusBySession.get(remaining.sessionId) ?? { servers: [] })
                    : { servers: [] };
        }
        const latest = live.at(-1);
        if (latest !== undefined) {
            if (released !== undefined && this.#sessionContext === released.context)
                this.#sessionContext = latest.context;
            // Only a session that is gone (quit, or the builtin removed) re-syncs. A reload, new, resume or fork attaches
            // again next, and that attach drops what no live session declares without restarting the servers it keeps.
            // A gone session re-syncs even when an earlier release with no reason already dropped its binding: a reload
            // into a runtime without the builtin shuts the session down first, so its servers would otherwise outlive it.
            if (disposeReason !== undefined)
                await this.#resyncToLiveSessions();
            return;
        }
        // A session whose attach is still queued has not bound yet but will use this service.
        if (disposeReason === undefined)
            return;
        if (this.#pendingSyncs === 0) {
            await this.dispose(disposeReason);
            return;
        }
        // The release settles only once the pending attaches and re-syncs have, so a caller that awaits it
        // (session shutdown, builtin removal) sees the service disposed, not a dispose scheduled later.
        this.#deferredDisposeReason = disposeReason;
        const settled = new Promise((settle) => this.#deferredDisposeWaiters.push(() => settle("settled")));
        const deadlineMs = resolveMcpDeferredDisposeTimeoutMs();
        let timer;
        const outcome = await Promise.race([
            settled,
            new Promise((expire) => {
                timer = safeTimer("deferred-dispose", deadlineMs, () => expire("timeout"), {
                    logger: createMcpLogger("service"),
                });
            }),
        ]);
        clearTimeout(timer);
        if (outcome === "settled" || this.#deferredDisposeReason === undefined)
            return;
        // A hung attach must not hold a reload or a quit forever: dispose anyway once the
        // deadline passes, unless a session bound in the meantime, and say so.
        this.#deferredDisposeReason = undefined;
        createMcpLogger("service").warn("MCP attach or re-sync still pending at the dispose deadline; disposing anyway", {
            timeoutMs: deadlineMs,
            reason: disposeReason,
        });
        if (this.#liveBindings().length === 0)
            await this.dispose(disposeReason);
        for (const settle of this.#deferredDisposeWaiters.splice(0))
            settle();
    }
    /**
     * After a release, bring the shared connections in line with the sessions still live (senpi#2597): the effective
     * config of the most recent live binding, with its options, so a server no live session declares is stopped
     * instead of outliving its session. It runs on the attach queue, never interleaved with an attach's own sync; the
     * caller awaits it only when no sync of any kind is pending, because a hung attach must not hold a quit. It counts as
     * a pending sync like an attach, so a release that empties the service defers its dispose until the re-sync settles
     * instead of disposing under it. A credential change passes `fallbackOwner`, the owner of the sync that created the
     * connection, and re-syncs the current config instead, so it re-keys that connection and stops nothing; with no live
     * session (a connection an unbound attach started), it syncs with `fallbackOwner`'s options.
     */
    async #resyncToLiveSessions(fallbackOwner) {
        const awaited = this.#pendingSyncs === 0;
        const settled = this.#queueSync(async () => {
            if (this.#disposed)
                return;
            const latest = this.#liveBindings().at(-1);
            // A credential re-sync (with `fallbackOwner`) re-keys the current config and stops nothing: a session released
            // for a reload still declares its servers in it until its next attach, which keeps them running.
            const config = fallbackOwner === undefined && latest !== undefined ? this.#effectiveConfig(latest.config) : this.#config;
            const owner = latest ?? fallbackOwner;
            if (config === null || owner === undefined)
                return;
            // Compared by entry, not key: a connection re-created under its old key retires the offers made against it too.
            const before = new Set(this.#connections.values());
            this.#config = config;
            await this.#syncFromConfig(config, owner, true, latest);
            const unchanged = this.#connections.size === before.size &&
                [...this.#connections.values()].every((entry) => before.has(entry));
            if (this.#disposed || latest === undefined || unchanged)
                return;
            // A replaced connection retires the offers made against it; republish them in every live session.
            for (const live of this.#liveBindings()) {
                await this.#registerDirectTools(live);
                if (this.#disposed)
                    return;
            }
            if (shouldCaptureWireStatus(latest.context)) {
                await this.refreshWireStatusSnapshot(latest.context.sessionManager?.getSessionId?.());
            }
        });
        if (awaited) {
            await settled;
            return;
        }
        settled.catch((error) => {
            createMcpLogger("service").error("Failed to re-sync MCP servers", error);
        });
    }
    /**
     * Register skill-declared MCP servers (todo 37). Skill servers are forced
     * into search mode with no directTools, so their catalogs register with
     * ZERO active tools until activateSkillMcpTools reveals them. A name
     * collision with a system-configured server keeps the system config and
     * returns a warning (system wins). `${VAR}` expansion follows the declaring
     * skill's trust (skill-server.ts); each trust warning is returned once per session.
     */
    async attachSkillMcpServers(declared, pi) {
        const binding = this.#bindingFor(pi);
        if (this.#config === null || binding === undefined)
            return [];
        const config = binding.config;
        const warnings = [];
        const policyWarnings = new Map();
        // The declaring session's own trust and env, never those of whichever session attached last (senpi#2986).
        const projectTrusted = binding.options.projectTrusted ?? binding.context.isProjectTrusted();
        let added = 0;
        for (const [name, decl] of declared) {
            const existing = config.servers[name];
            if (existing !== undefined && existing.source !== "skill") {
                warnings.push(`MCP server '${name}' from skill ${decl.sourcePath} collides with the ${existing.source} config; system config wins.`);
                continue;
            }
            const project = decl.provenance === undefined ? decl.scope === "project" : decl.provenance.kind !== "user";
            // The project environment policy materializes plain strings only, so a project skill server that declares a
            // reference object is refused before any I/O, like an untrusted or remote one (senpi#3858).
            const refused = project
                ? referenceRefusal(name, decl.raw, `Skill '${decl.skillName}' MCP server '${name}'`)
                : undefined;
            if (refused !== undefined) {
                if (!this.#skillServerWarnings.has(refused)) {
                    this.#skillServerWarnings.add(refused);
                    warnings.push(refused);
                }
                continue;
            }
            const result = project
                ? await prepareProjectSkillServer(name, decl, {
                    context: binding.context,
                    options: binding.options,
                    ui: this.#elicitationProviderFor(binding),
                    notice: (identity, names) => {
                        // An untrusted project keeps the skill's references literal (senpi#2345); keep that fix in
                        // the one notice instead of a generic withheld line (senpi#3796).
                        const message = names.length === 0
                            ? ""
                            : projectTrusted
                                ? `Project MCP server ${name} (skill ${decl.skillName}) withheld ${names.length} environment name(s): ${names.join(", ")}.`
                                : `Skill '${decl.skillName}' MCP server '${name}': ${names.map((variable) => `\${${variable}}`).join(", ")} stays literal because the skill comes from an untrusted project; trust the project or move the server into your own mcp.json to expand it.`;
                        binding.pi.events?.emit("security_notice", {
                            category: "mcp-env-withheld",
                            path: identity,
                            message,
                            remove: names.length === 0,
                        });
                        if (names.length === 0) {
                            policyWarnings.delete(identity);
                            return;
                        }
                        if (!this.#skillServerWarnings.has(message)) {
                            this.#skillServerWarnings.add(message);
                            policyWarnings.set(identity, message);
                            createMcpLogger("skills").warn(message);
                        }
                    },
                }, existing).then((server) => ({ server, warning: undefined }), 
                // The skill file can gain a reference between the check above and the policy's re-read.
                (error) => {
                    if (!(error instanceof ConfigReferenceError))
                        throw error;
                    return {
                        server: undefined,
                        warning: `Skill '${decl.skillName}' MCP server '${name}' skipped: ${error.message}`,
                    };
                })
                : resolveSkillMcpServer(name, decl.raw, decl.sourcePath, {
                    env: binding.options.env,
                    skillName: decl.skillName,
                    trusted: decl.scope === "project" || decl.scope === undefined ? projectTrusted : true,
                });
            const { server: resolved, warning } = result;
            if (warning !== undefined && !this.#skillServerWarnings.has(warning)) {
                this.#skillServerWarnings.add(warning);
                warnings.push(warning);
            }
            if (resolved === undefined)
                continue;
            if (existing !== undefined && existing.configHash === resolved.configHash)
                continue;
            config.servers[name] = resolved;
            added += 1;
        }
        if (added > 0) {
            // Queued and counted like a re-sync: a release re-sync that runs meanwhile is never undone by servers this
            // sync wanted before it, and a session released or attached again since then starts nothing from this binding.
            await this.#queueSync(async () => {
                if (this.#disposed || !this.#liveBindings().includes(binding))
                    return;
                this.#config = this.#effectiveConfig(binding.config);
                await this.#syncFromConfig(this.#config, binding, false, binding);
                await this.#registerDirectTools(binding);
                if (shouldCaptureWireStatus(binding.context)) {
                    await this.refreshWireStatusSnapshot(binding.context.sessionManager?.getSessionId?.());
                }
            });
        }
        return [...warnings, ...policyWarnings.values()];
    }
    /** Registered searchable catalog (mapped name + server-side tool name),
     * used by the skills loader to compute activation targets. */
    getTierBSearchable(pi) {
        return this.#bindingFor(pi)?.registration?.searchable ?? [];
    }
    /** Connected servers that list prompts (todo 40), for slash registration. */
    getMcpPromptServers(pi) {
        return this.#bindingFor(pi)?.registration?.promptServers ?? [];
    }
    /** Connected servers that list resources (todo 39), for mention expansion. */
    getMcpResourceServers(pi) {
        return this.#bindingFor(pi)?.registration?.resourceServers ?? [];
    }
    /** Subscribe to completed catalog registrations. Consumers must inspect the
     * resulting snapshot because tool, resource, and prompt catalogs can become
     * available in different startup-race generations. */
    onMcpRegistrationChanged(listener) {
        this.#registrationListeners.add(listener);
        return () => this.#registrationListeners.delete(listener);
    }
    /**
     * Await the startup connects the race backgrounded, bounded by `timeoutMs`.
     * `attachSession` resolves at the race deadline, so code that must OBSERVE the
     * attach's catalog (tests, and hosts that watch the attach from outside; the
     * first turn itself awaits the attach promise in `before_agent_start`) calls
     * this. A `"timeout"` result means some connects are still running.
     *
     * An attach (or re-sync) still on the queue has not handed its backgrounded connects over yet, so the queue is
     * awaited first, within the same budget: an early call must never read an empty pending set as settled (senpi#4027).
     */
    async whenAttachSettled(timeoutMs = MCP_ATTACH_SETTLE_TIMEOUT_MS) {
        const startedAt = Date.now();
        if ((await waitForMcpStartupRace(this.#attachQueue, timeoutMs)) === "timeout")
            return "timeout";
        return this.#deferredAttach.wait(Math.max(0, timeoutMs - (Date.now() - startedAt)));
    }
    /** Subscribe to live MCP inventory transitions for session-scoped hosts. */
    onWireStatusChanged(listener) {
        this.#wireStatusListeners.add(listener);
        return () => this.#wireStatusListeners.delete(listener);
    }
    /** Refresh and return the current session-owned MCP wire inventory. */
    async refreshWireStatusSnapshot(sessionId) {
        // A caller that passes no session id gets no peer data while more than one session is live (senpi#3001);
        // capturing here would store the most recently attached session's status for it to read back.
        if (sessionId === undefined && this.#liveBindings().length > 1)
            return { servers: [] };
        return this.#refreshWireStatus(sessionId, () => this.#statusOwner(sessionId));
    }
    /** `owner` is resolved when the queued capture runs, so it sees the bindings current at that point. */
    async #refreshWireStatus(sessionId, owner, release) {
        const refresh = this.#wireStatusRefreshQueue.then(() => this.#captureWireStatus(sessionId, owner(), release));
        this.#wireStatusRefreshQueue = refresh.then(() => undefined, () => undefined);
        await refresh;
        return this.getWireStatusSnapshot(sessionId);
    }
    /** Reveal skill-owned tools (todo 37): activation is effective the next
     * turn, exactly like an tool_search promotion. Unknown names are ignored. */
    activateSkillMcpTools(names, pi) {
        this.#bindingFor(pi)?.registration?.activate(names);
    }
    #rehydrateFromSessionHistory(binding) {
        const entries = binding.context.sessionManager?.getEntries() ?? [];
        if (entries.length === 0)
            return;
        this.#toolSearchFor(binding)?.maybeRehydrateFromHistory(entries);
    }
    async handleSessionShutdown(event) {
        if (shouldDisposeMcpService(event.reason))
            await this.dispose(event.reason);
    }
    async dispose(reason) {
        if (this.#disposed)
            return;
        this.#disposed = true;
        this.#disposeCount += 1;
        this.#lastDisposeReason = reason;
        for (const binding of this.#bindings.values())
            binding.lifetime.abort();
        this.#bindings.clear();
        this.#sessionContext = null;
        this.#config = null;
        this.#elicitationUiProvider = undefined;
        this.#mcpInstructions = "";
        this.#pendingAuth.clear();
        this.#interactiveAuthServers.clear();
        this.#promptCommandNames.clear();
        this.#registrationListeners.clear();
        this.#wireStatusListeners.clear();
        this.#startupWindows.clear();
        this.#wireStatusBySession.clear();
        this.#latestWireStatus = { servers: [] };
        this.#deferredAttach.clear();
        const entries = [...this.#connections.values()];
        this.#connections.clear();
        this.#connectionKeysByName.clear();
        await Promise.all(entries.map((entry) => disposeEntryConnection(entry, this.#registry, this)));
        await cleanupMcpOutputArtifacts(this.#outputArtifacts);
    }
    getMcpOutputArtifacts() {
        return this.#outputArtifacts;
    }
    isDisposed() {
        return this.#disposed;
    }
    getConnection(name) {
        const key = this.#connectionKeysByName.get(name);
        const entry = key === undefined ? undefined : this.#connections.get(key);
        return entry?.credentialsCurrent?.() === false ? undefined : entry?.connection;
    }
    async reconnectServer(name) {
        const entry = this.#entryForName(name);
        if (entry === undefined)
            throw new Error(`Unknown MCP server: ${name || "<missing>"}`);
        if (await entry.generationChanged?.()) {
            await entry.onCredentialsChanged?.();
            return;
        }
        await reconnectMcpNow(entry.connection);
    }
    /**
     * The lifecycle-only server snapshots. Without a session id these still list the merged config of all live
     * sessions, as the /mcp command and the manager TUI expect. With one, only the servers that session declares
     * (senpi#3001): a caller that can name its session gets no peer data.
     */
    getServerSnapshots(sessionId) {
        if (sessionId !== undefined) {
            const owner = this.#statusOwner(sessionId);
            if (owner === undefined)
                return [];
            const names = new Set(Object.keys(owner.config.servers));
            return [...names]
                .sort()
                .map((name) => this.#serverSnapshot(name, owner.config.servers[name], this.#entryForName(name)));
        }
        const names = new Set(Object.keys(this.#config?.servers ?? {}));
        for (const entry of this.#connections.values())
            names.add(entry.name);
        return [...names]
            .sort()
            .map((name) => this.#serverSnapshot(name, this.#config?.servers[name], this.#entryForName(name)));
    }
    getLogLines(name, maxLines) {
        const key = this.#connectionKeysByName.get(name);
        const lines = key === undefined ? [] : (this.#connections.get(key)?.logger.getRingBuffer() ?? []);
        return lines.slice(Math.max(0, lines.length - maxLines));
    }
    async getServerExposureStatus(name) {
        return await getMcpServiceExposureStatus(name, this.#config, this.#entryForName(name));
    }
    recordCall(name, elapsedMs, failed) {
        const key = this.#connectionKeysByName.get(name);
        const entry = key === undefined ? undefined : this.#connections.get(key);
        if (entry === undefined)
            return;
        entry.counters.callCount += 1;
        entry.counters.totalLatencyMs += elapsedMs;
        if (failed)
            entry.counters.errorCount += 1;
    }
    getSnapshot() {
        return {
            disposed: this.#disposed,
            disposeCount: this.#disposeCount,
            lastDisposeReason: this.#lastDisposeReason,
            sessionStartCount: this.#sessionStartCount,
            lastSessionStartReason: this.#lastSessionStartReason,
            hasSessionContext: this.#sessionContext !== null,
            connectionCount: this.#connections.size,
        };
    }
    /**
     * Return the attach-time inventory captured for one session. This is the
     * handoff consumed by RPC's session-owned adapter; it deliberately
     * does not expose or derive from the lifecycle-only server snapshots.
     * A caller that passes no session id gets no peer data while more than
     * one session is live (senpi#3001): with a single live session the stored
     * snapshot is that session's own, so the id-less read keeps working.
     */
    getWireStatusSnapshot(sessionId) {
        if (sessionId === undefined && this.#liveBindings().length > 1)
            return { servers: [] };
        return sessionId === undefined
            ? this.#latestWireStatus
            : (this.#wireStatusBySession.get(sessionId) ?? { servers: [] });
    }
    /**
     * Bring the connections in line with `config`. Each server spawns with the options and cwd of a session that
     * declares it: `owner` (the attaching session) when it does, otherwise the live binding whose config
     * `#effectiveConfig` took it from, so one session's trust, env and credentials never decide another's (senpi#2986).
     */
    async #syncFromConfig(config, owner, useCache, binding, startupConnects) {
        const hadConnectionsBeforeSync = this.#connections.size > 0;
        this.#refreshActiveSetWhenNoTools = Object.keys(config.servers).length > 0 || hadConnectionsBeforeSync;
        const wanted = new Map();
        const credentialIdentities = new Map();
        const candidates = [owner, ...this.#liveBindings()];
        const declarers = new Map();
        visitSpawnableMcpServers(config, (name, server) => {
            wanted.set(name, server);
            const declarer = candidates.find((candidate) => declares(candidate.config, name, server.configHash)) ?? owner;
            declarers.set(name, declarer);
            if (server.config !== undefined) {
                const { agentDir, env } = declarer.options;
                credentialIdentities.set(name, mcpCredentialIdentity(server.config, name, agentDir, env));
            }
        });
        // The catalog caches are read first, as the sync's first await: resolving the generations (which may read
        // referenced files) comes after, so a release landing meanwhile still finds the cache read under way.
        const agentDirs = new Set([owner, ...declarers.values()].map((declarer) => declarer.options.agentDir));
        const caches = new Map();
        for (const agentDir of agentDirs) {
            caches.set(agentDir, await readMcpCatalogCache(agentDir));
            // A dispose that landed during an await closed every connection; one created now would never be closed.
            if (this.#disposed)
                return;
        }
        const generations = await resolveWantedMcpGenerations(wanted, (name) => (declarers.get(name) ?? owner).options, this.#referenceErrors);
        if (this.#disposed)
            return;
        const disposals = [];
        for (const entry of this.#connections.values()) {
            const server = wanted.get(entry.name);
            const key = server?.configHash === undefined
                ? undefined
                : `${entry.name}\0${mcpConnectionIdentity(server.configHash, generations.get(entry.name)?.configHash)}\0${credentialIdentities.get(entry.name) ?? "unknown"}`;
            // A connection whose credentials went stale is re-created with its declarer's options, never kept under an
            // unchanged key: kept, it would refuse every session sharing it until the service is disposed.
            if (key === entry.key && entry.credentialsCurrent?.() !== false)
                continue;
            this.#connections.delete(entry.key);
            this.#connectionKeysByName.delete(entry.name);
            disposals.push(disposeEntryConnection(entry, this.#registry, this));
        }
        await Promise.all(disposals);
        if (this.#disposed)
            return;
        const connects = [];
        for (const [name, server] of wanted) {
            const generation = generations.get(name);
            if (server.config === undefined || server.configHash === undefined || generation === undefined)
                continue;
            const serverConfig = server.config;
            const declarer = declarers.get(name) ?? owner;
            const options = declarer.options;
            const cache = caches.get(options.agentDir);
            const credentialIdentity = credentialIdentities.get(name);
            const identity = mcpConnectionIdentity(server.configHash, generation.configHash);
            const key = `${name}\0${identity}\0${credentialIdentity ?? "unknown"}`;
            if (this.#connections.has(key))
                continue;
            const cachedCatalog = useCache && credentialIdentity !== undefined && cache !== undefined
                ? await adoptMcpCachedServer({
                    cache,
                    agentDir: options.agentDir,
                    serverName: name,
                    current: { configHash: identity, credentialIdentity },
                    legacy: () => legacyMcpCacheIdentity(generation.config, name, options),
                })
                : undefined;
            if (this.#disposed)
                return;
            const entry = createMcpSessionConnection({
                registry: this.#registry,
                share: this.#shareConnections,
                owner: this,
                key,
                name,
                configHash: server.configHash,
                generation,
                declared: serverConfig,
                credentialIdentity,
                credentialsCurrent: () => mcpCredentialIdentity(serverConfig, name, options.agentDir, options.env) === credentialIdentity,
                // Re-key from the current live state, never the config this sync saw: any attach, release or skill attach
                // may have replaced `#config` since, and an OAuth token refresh still has to reach this connection.
                onCredentialsChanged: async () => {
                    if (this.#disposed || this.#entryForName(name) !== entry)
                        return;
                    await this.#resyncToLiveSessions(owner);
                },
                session: options,
                elicitationEnabled: declarer.context.mode !== "print" && declarer.context.mode !== "json",
                cwd: declarer.context.cwd,
                ui: this.#elicitationProviderFor(declarer),
                artifacts: this.#outputArtifacts,
                shouldReconnect: (current) => !this.#disposed &&
                    this.#entryForName(name) === current &&
                    this.#config?.servers[name]?.state === "enabled" &&
                    this.#config.servers[name]?.configHash === current.configHash,
            });
            entry.cachedCatalog = cachedCatalog;
            this.#connections.set(key, entry);
            this.#connectionKeysByName.set(name, key);
            this.#wireListChanged(entry);
            // Every startup connect is bounded by the startup race and continues in
            // the background past the deadline (eager/keep-alive always; a cold lazy
            // server that has no cached catalog also races so a slow/wedged server
            // never gates attachSession -> before_agent_start -> the first turn).
            // A fresh cached lazy server connects only on demand. An aged matching
            // catalog remains usable while its background refresh runs.
            if (shouldRaceMcpStartup(server.config.lifecycle) ||
                cachedCatalog === undefined ||
                cachedCatalogNeedsRefresh(cachedCatalog)) {
                connects.push(raceMcpStartupConnect({
                    entry,
                    pi: binding?.pi,
                    registerDirectTools: async () => {
                        // The catalog is shared, so it lands in every live session, not only the one that
                        // started the connect (#2514). One session's failure must not starve the others:
                        // each registers on its own, and the failures are reported together afterwards.
                        const failures = [];
                        for (const live of this.#liveBindings()) {
                            try {
                                await this.#registerDirectTools(live);
                                // A raced attach ran its history replay before this catalog
                                // existed; replay now so restored tools still land on the
                                // first turn's payload (idempotent: already-active names skip).
                                this.#rehydrateFromSessionHistory(live);
                            }
                            catch (error) {
                                failures.push(error);
                            }
                        }
                        // The session instructions block was likewise captured at attach
                        // time, before this server connected; rebuild it so the first
                        // turn carries this server's instructions after a raced connect.
                        refreshMcpInstructionsForSession(this);
                        if (failures.length > 0) {
                            throw new AggregateError(failures, `MCP ${name} catalog failed to register in ${failures.length} session(s)`);
                        }
                    },
                    serverConfig: server.config,
                    // A later attach does not supersede this catalog: it registers in every live session. Skip it only
                    // once the service is gone or this connection was replaced (#2524 review).
                    shouldRefreshTools: () => !this.#disposed && this.#entryForName(name) === entry,
                    deadlineMs: 0,
                    onDeferred: (settled) => {
                        this.#deferredAttach.track(settled);
                        startupConnects?.push(settled);
                    },
                }));
            }
        }
        await Promise.all(connects);
    }
    #wireListChanged(entry) {
        const sink = { logger: { error: (message, data) => entry.logger.error(message, data) } };
        entry.disposeListChanged = subscribeMcpToolsChanged(entry, (connectOnly) => this.#handleServerToolsChanged(entry, connectOnly), sink);
        const unsubscribeState = entry.connection.onStateChange(() => {
            const ctx = this.#sessionContext;
            if (ctx?.mode !== "rpc")
                return;
            void this.refreshWireStatusSnapshot(ctx.sessionManager?.getSessionId?.()).catch((error) => {
                entry.logger.error("Failed to refresh MCP control inventory", error);
            });
        });
        entry.disposeWireStatus = unsubscribeState;
    }
    async #handleServerToolsChanged(entry, connectOnly) {
        const config = this.#config;
        if (config === null || this.#liveBindings().length === 0)
            return;
        // Resolved when the refresh registers, not when it starts: a session that attaches while the
        // refresh is still listing tools must receive the refreshed catalog too.
        const targets = () => this.#liveBindings()
            .filter((binding) => offersConnection(binding, entry))
            .map((binding) => ({
            pi: binding.pi,
            registeredIdentity: () => binding.registeredIdentities.get(entry.key),
            register: () => this.#registerDirectTools(binding),
        }));
        await refreshMcpToolsOnListChanged(entry, targets, config, connectOnly);
    }
    async #registerDirectTools(binding) {
        if (this.#disposed)
            return;
        const config = binding.config;
        const toolSearchService = this.#toolSearchFor(binding);
        if (toolSearchService === undefined)
            return;
        binding.registration = await registerMcpServiceDirectTools(binding.pi, config, 
        // Only the connections this session's own config declares and its own credentials match; a peer's config or
        // credentials never decide its tools.
        [...this.#connections.values()].filter((entry) => offersConnection(binding, entry)), toolSearchService, {
            refreshActiveSetWhenEmpty: this.#refreshActiveSetWhenNoTools,
            onRegistered: (entry, identity) => binding.registeredIdentities.set(entry.key, identity),
            contextRequired: binding.context.mode !== undefined,
            sessionManager: binding.context.sessionManager,
            servesSession: (sessionManager) => scopes.bindingServesScope(binding, sessionManager),
            requestOrigin: (entry, caller) => this.#requestOrigin(binding, entry, caller),
            bindPresentation: (ui) => this.bindMcpMrtrPresentation(binding.pi, ui),
            // A new attach of this session replaces its binding (and with it its config); a peer's attach does not.
            isCurrent: (entry) => !this.#disposed &&
                this.#bindings.get(binding.pi) === binding &&
                this.#entryForName(entry.name) === entry,
            publishCurrent: async () => {
                if (this.#bindings.get(binding.pi) === binding)
                    await this.#registerDirectTools(binding);
            },
        });
        const ctx = binding.context;
        if (ctx.mode === "rpc") {
            await this.refreshWireStatusSnapshot(ctx.sessionManager?.getSessionId?.());
        }
        for (const listener of this.#registrationListeners)
            listener();
    }
    /** Route compatibility callers through the shared ownership-aware scanner. */
    rehydrateActiveToolsFromHistory(messages, pi) {
        return this.maybeRehydrateFromHistory(messages, pi);
    }
    /** Shared service memoization keeps this scan once-per-catalog-generation. */
    maybeRehydrateFromHistory(messages, pi) {
        const binding = this.#bindingFor(pi);
        return ((binding === undefined ? undefined : this.#toolSearchFor(binding)?.maybeRehydrateFromHistory(messages)) ?? []);
    }
    #serverSnapshot(name, server, entry) {
        const config = server?.config;
        const connection = entry?.credentialsCurrent?.() === false ? undefined : entry?.connection;
        connection?.refreshCapturedDiagnostics();
        const snapshot = buildMcpServerSnapshot(name, server, connection, entry);
        const referenceError = entry === undefined ? this.#referenceErrors.get(name) : undefined;
        if (referenceError !== undefined)
            return redactResolvedReferenceData({
                ...snapshot,
                lifecycleState: "degraded",
                lastError: referenceError.message,
            });
        if (config !== undefined &&
            entry?.connection.state === "needs_auth" &&
            mcpCredentialIdentity(config, name, entry.agentDir, entry.env) === undefined) {
            return redactResolvedReferenceData({
                ...snapshot,
                lifecycleState: "needs_auth",
                lastError: entry.connection.lastError?.message ?? null,
            });
        }
        return snapshot;
    }
    /**
     * The config a session's status reports: its own binding's, found by session id (senpi#2597). The merged config
     * decides only which connections live; a session's status lists only the servers it declares. Without a session
     * id, the most recently attached live session's.
     */
    #statusOwner(sessionId) {
        const live = this.#liveBindings();
        if (sessionId === undefined)
            return live.at(-1);
        return (live.findLast((binding) => binding.context.sessionManager?.getSessionId?.() === sessionId) ??
            // A further scope of a runtime reports the binding that serves it: one runtime declares one set of servers.
            live.findLast((binding) => scopes.bindingServesScopeSession(binding, sessionId)));
    }
    /** A `release` (a closing startup window) is announced even when unchanged; otherwise an open window holds it. */
    async #captureWireStatus(sessionId, owner, release) {
        if (this.#config === null || owner === undefined)
            return;
        const servers = await Promise.all(Object.keys(owner.config.servers)
            .sort()
            .map((name) => this.#captureWireStatusServer(name, owner)));
        const snapshot = redactResolvedReferenceData({ servers });
        const previous = this.getWireStatusSnapshot(sessionId);
        this.#latestWireStatus = snapshot;
        if (sessionId !== undefined)
            this.#wireStatusBySession.set(sessionId, snapshot);
        if (release === undefined && JSON.stringify(previous) === JSON.stringify(snapshot))
            return;
        if (release === undefined && this.#startupWindows.hold(sessionId))
            return;
        const startupSettled = release === "startup-settled";
        for (const listener of this.#wireStatusListeners)
            listener(sessionId, snapshot, startupSettled);
    }
    /** Only a connection resolving `owner`'s own credentials counts: a peer's catalog and login never show in its status. */
    async #captureWireStatusServer(name, owner) {
        const server = owner.config.servers[name];
        const shared = this.#entryForName(name);
        const entry = shared !== undefined && resolvesSameCredentials(owner, shared) ? shared : undefined;
        const connection = entry?.credentialsCurrent?.() === false ? undefined : entry?.connection;
        const connected = connection?.state === "connected";
        const diagnostic = this.#serverSnapshot(name, server, entry);
        const cached = entry?.credentialsCurrent?.() === false ? undefined : entry?.cachedCatalog;
        const tools = cached?.tools ?? [];
        const resources = cached?.resources ?? [];
        const resourceTemplates = cached?.resourceTemplates ?? [];
        let serverInfo = null;
        if (connected && connection !== undefined) {
            const client = connection.client;
            const version = client.getServerVersion();
            if (version !== undefined)
                serverInfo = mapWireServerInfo(version);
        }
        return {
            name,
            serverInfo,
            ...(diagnostic.lastError === null ? {} : { lastError: diagnostic.lastError }),
            tools: tools.map(mapWireTool),
            resources: resources.map(mapWireResource),
            resourceTemplates: resourceTemplates.map(mapWireResourceTemplate),
            authStatus: wireAuthStatus(entry, server, entry === undefined ? owner.options : { agentDir: entry.agentDir, env: entry.env }),
            ...(connection?.state === undefined && server?.state === undefined
                ? {}
                : {
                    status: !connected && diagnostic.lifecycleState === "needs_auth"
                        ? "needs_auth"
                        : entry === undefined && diagnostic.lifecycleState === "degraded"
                            ? "degraded"
                            : entry?.startupCatalogClaim?.ownsRegistration()
                                ? "connecting"
                                : (connection?.state ?? server?.state),
                }),
        };
    }
    #entryForName(name) {
        const key = this.#connectionKeysByName.get(name);
        return key === undefined ? undefined : this.#connections.get(key);
    }
    /**
     * The agent dir and env a server's credentials resolve with: those its connection spawned with, else those of a
     * live session that declares it, never the last attach's (senpi#2986).
     */
    #credentialOptions(name) {
        const entry = this.#entryForName(name);
        if (entry !== undefined)
            return { agentDir: entry.agentDir, env: entry.env };
        const configHash = this.#config?.servers[name]?.configHash;
        return this.#liveBindings().find((binding) => declares(binding.config, name, configHash))?.options;
    }
    setMcpInstructions(instructions) {
        this.#mcpInstructions = instructions;
    }
    getMcpInstructions() {
        if ([...this.#connections.values()].some((entry) => entry.credentialsCurrent?.() === false)) {
            refreshMcpInstructionsForSession(this);
        }
        return this.#mcpInstructions;
    }
    setMcpElicitationUiProvider(provider) {
        this.#elicitationUiProvider = provider;
    }
    bindMcpMrtrPresentation(pi, ui, sessionManager) {
        const binding = this.#bindings.get(pi);
        const presentation = getMcpMrtrPresentation(ui);
        if (binding && presentation)
            scopes.bindScopePresentation(binding, presentation, sessionManager);
    }
    #requestOrigin(binding, entry, caller) {
        return scopes.scopedRequestOrigin(binding, entry, caller, () => !this.#disposed &&
            !binding.lifetime.signal.aborted &&
            this.#bindings.get(binding.pi) === binding &&
            [...this.#connections.values()].includes(entry) &&
            declares(binding.config, entry.name, entry.configHash) &&
            entry.isCurrent?.() !== false &&
            entry.credentialsCurrent?.() !== false);
    }
    getMcpElicitationUi() {
        return this.#elicitationUiProvider?.();
    }
    #elicitationProviderFor(owner) {
        // Connections outlive their first declarer's extension context. Capture its host-owned
        // references while it is live; readiness must never read a released session's ctx.ui.
        const binding = [...this.#bindings.values()].find((candidate) => candidate === owner);
        const ui = owner.context.ui;
        const privateBinding = () => {
            // Keep observing presentation replacements on the binding, not just its initial grant.
            const presentation = binding
                ? binding.presentation
                : ui === undefined
                    ? undefined
                    : getMcpMrtrPresentation(ui);
            return presentation?.privateForms;
        };
        return Object.assign(() => this.getMcpElicitationUi(), {
            enforced: () => privateBinding() !== undefined,
            subscribe: (listener) => privateBinding()?.subscribe?.(listener) ?? (() => { }),
            eligible: () => {
                const binding = privateBinding();
                return binding === undefined || binding.capture()?.ready() === true;
            },
        });
    }
    isMcpPromptCommandRegistered(name) {
        return this.#promptCommandNames.has(name);
    }
    markMcpPromptCommandRegistered(name) {
        this.#promptCommandNames.add(name);
    }
    beginInteractiveAuth(serverName) {
        if (this.#interactiveAuthServers.has(serverName))
            return false;
        this.#interactiveAuthServers.add(serverName);
        return true;
    }
    endInteractiveAuth(serverName) {
        this.#interactiveAuthServers.delete(serverName);
    }
    getPendingAuth() {
        return this.#pendingAuth;
    }
    getAuthTarget(name) {
        const server = this.#config?.servers[name];
        if (server?.config === undefined)
            return undefined;
        const credentials = this.#credentialOptions(name);
        return {
            config: server.config,
            agentDir: credentials?.agentDir,
            env: credentials?.env,
            callbackUrl: this.#config?.settings.oauthCallbackUrl,
        };
    }
    /** Live auth status without fetching catalogs or exposing credentials. */
    getServerAuthStatus(name) {
        return wireAuthStatus(this.#entryForName(name), this.#config?.servers[name], this.#credentialOptions(name));
    }
    getCachedInstructions(name) {
        const entry = this.#entryForName(name);
        return entry?.credentialsCurrent?.() === false ? undefined : entry?.cachedCatalog?.instructions;
    }
    /** Resolved `settings.nativeToolSearch` (auto | true | false | undefined).
     * Drives the native provider tool-search adapter gate. */
    getNativeToolSearchSetting() {
        return this.#config?.settings.nativeToolSearch;
    }
}
/**
 * Whether `binding` may use `entry`: its own config declares the server with the connection's config hash, and its
 * own agent dir and env resolve the credential identity the connection spawned with (senpi#2986). An undefined
 * identity (no bearer token, no stored OAuth tokens) matches only another undefined one, as in the connection key,
 * so a connection holding no credentials is shared and one holding credentials never reaches a session without them.
 */
function offersConnection(binding, entry) {
    const server = binding.config.servers[entry.name];
    if (server?.config === undefined || server.configHash !== entry.configHash)
        return false;
    const { agentDir, env } = binding.options;
    return mcpCredentialIdentity(server.config, entry.name, agentDir, env) === entry.credentialIdentity;
}
/**
 * Whether `owner` declares `entry`'s server with its config hash and resolves, now, the credentials the connection's
 * own agent dir and env resolve. Unlike `offersConnection`, a connection whose credentials went stale (revoked or
 * rotated tokens) still matches its own session, so that session's status reports it as needing auth; a peer's
 * connection with other credentials never matches.
 */
function resolvesSameCredentials(owner, entry) {
    const server = owner.config.servers[entry.name];
    if (server?.config === undefined || server.configHash !== entry.configHash)
        return false;
    const { agentDir, env } = owner.options;
    return (mcpCredentialIdentity(server.config, entry.name, agentDir, env) ===
        mcpCredentialIdentity(server.config, entry.name, entry.agentDir, entry.env));
}
/** Whether `config` declares `name` as the same server, by config hash. */
function declares(config, name, configHash) {
    const server = config.servers[name];
    return server !== undefined && server.configHash === configHash;
}
function wireAuthStatus(entry, server, credentials) {
    const mode = entry?.authPlan?.mode ?? (server?.config === undefined ? "none" : resolveAuthMode(server.config));
    switch (mode) {
        case "none":
            return "unsupported";
        case "bearer":
            return entry?.connection.state === "needs_auth" ? "notLoggedIn" : "bearerToken";
        case "oauth":
            return server?.config === undefined ||
                mcpCredentialIdentity(server.config, server.name, credentials?.agentDir, credentials?.env) === undefined
                ? "notLoggedIn"
                : "oAuth";
        default:
            return assertNever(mode);
    }
}
function shouldCaptureWireStatus(ctx) {
    return ctx.mode === "rpc";
}
function mapWireServerInfo(info) {
    return {
        name: info.name,
        title: info.title ?? null,
        version: info.version,
        description: info.description ?? null,
        icons: info.icons?.map(toWireJsonValue) ?? null,
        websiteUrl: info.websiteUrl ?? null,
    };
}
function mapWireTool(tool) {
    return {
        name: tool.name,
        ...(tool.title === undefined ? {} : { title: tool.title }),
        ...(tool.description === undefined ? {} : { description: tool.description }),
        inputSchema: toWireJsonValue(tool.inputSchema),
        ...(tool.outputSchema === undefined ? {} : { outputSchema: toWireJsonValue(tool.outputSchema) }),
        ...(tool.annotations === undefined ? {} : { annotations: toWireJsonValue(tool.annotations) }),
        ...(tool.icons === undefined ? {} : { icons: tool.icons.map(toWireJsonValue) }),
        ...(tool._meta === undefined ? {} : { _meta: toWireJsonValue(tool._meta) }),
    };
}
function mapWireResource(resource) {
    return {
        uri: resource.uri,
        name: resource.name,
        ...(resource.title === undefined ? {} : { title: resource.title }),
        ...(resource.description === undefined ? {} : { description: resource.description }),
        ...(resource.mimeType === undefined ? {} : { mimeType: resource.mimeType }),
        ...(resource.size === undefined ? {} : { size: resource.size }),
        ...(resource.annotations === undefined ? {} : { annotations: toWireJsonValue(resource.annotations) }),
        ...(resource.icons === undefined ? {} : { icons: resource.icons.map(toWireJsonValue) }),
        ...(resource._meta === undefined ? {} : { _meta: toWireJsonValue(resource._meta) }),
    };
}
function mapWireResourceTemplate(template) {
    return {
        uriTemplate: template.uriTemplate,
        name: template.name,
        ...(template.title === undefined ? {} : { title: template.title }),
        ...(template.description === undefined ? {} : { description: template.description }),
        ...(template.mimeType === undefined ? {} : { mimeType: template.mimeType }),
        ...(template.annotations === undefined ? {} : { annotations: toWireJsonValue(template.annotations) }),
        ...(template.icons === undefined ? {} : { icons: template.icons.map(toWireJsonValue) }),
        ...(template._meta === undefined ? {} : { _meta: toWireJsonValue(template._meta) }),
    };
}
function toWireJsonValue(value) {
    if (value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string") {
        return value;
    }
    if (Array.isArray(value))
        return value.map(toWireJsonValue);
    if (isRecord(value)) {
        const object = {};
        for (const [key, child] of Object.entries(value))
            object[key] = toWireJsonValue(child);
        return object;
    }
    return null;
}
function isRecord(value) {
    return typeof value === "object" && value !== null && !Array.isArray(value);
}
function assertNever(value) {
    throw new Error(`Unhandled MCP auth mode: ${JSON.stringify(value)}`);
}
let service = null;
export function getMcpService() {
    if (service === null || service.isDisposed()) {
        service = new McpService({ servesManySessions: true });
    }
    return service;
}
export function shouldDisposeMcpService(reason) {
    return reason === "quit" || reason === "reload";
}
export function resetMcpServiceForTests() {
    service = null;
    resetToolSearchServiceForTests();
}
export const MCP_DEFERRED_DISPOSE_TIMEOUT_ENV = "SENPI_MCP_DEFERRED_DISPOSE_TIMEOUT_MS";
const MCP_DEFERRED_DISPOSE_TIMEOUT_MS = 15_000;
/** How long a release waits for pending attaches before it disposes anyway. */
function resolveMcpDeferredDisposeTimeoutMs() {
    const raw = process.env[MCP_DEFERRED_DISPOSE_TIMEOUT_ENV]?.trim();
    if (raw !== undefined && raw.length > 0) {
        const value = Number(raw);
        if (Number.isFinite(value) && value >= 0)
            return value;
    }
    return MCP_DEFERRED_DISPOSE_TIMEOUT_MS;
}
//# sourceMappingURL=service.js.map