/**
 * Frozen type contract for the protocol bridge.
 *
 * The protocol bridge connects this agent to external Model Context Protocol
 * servers and grafts their tools into the kernel's {@link ToolRegistry}. This
 * module owns the *vocabulary* of that subsystem — the fault model, the endpoint
 * lifecycle, the per-server configuration shapes, and the small handles the
 * endpoint, fleet, and host pass between one another. It declares no behaviour;
 * every executable part of the bridge imports its nouns from here so there is a
 * single source of truth.
 *
 * Three deliberate design choices distinguish this contract:
 *
 *   - Faults are a *discriminated kind on an Error*, not an enum of numeric
 *     codes with a factory per code. A caller branches on {@link FaultKind};
 *     the underlying cause rides the native {@link Error.cause} chain.
 *   - An endpoint advertises an explicit {@link EndpointPhase} state machine
 *     rather than a scatter of `isConnected` / `connectionPromise` booleans.
 *   - A server's configuration is a discriminated union on its transport
 *     {@link ServerConfig.kind}, so a stdio server and an SSE server cannot be
 *     confused at the type level.
 */
import type { ToolDescriptor } from "../../llmgateway/contract";
import type { ToolBox } from "../../runtime/contract";
/**
 * The class of failure the bridge can surface.
 *
 * A small, closed vocabulary chosen so a caller can branch on the *cause class*
 * without inspecting message text:
 *
 *   - `transport`     — the underlying byte stream failed (socket dropped, pipe
 *     broke, HTTP request errored).
 *   - `protocol`      — a message arrived but violated the MCP / JSON-RPC
 *     contract (malformed envelope, unexpected method, bad result shape).
 *   - `timeout`       — a request was issued but no reply arrived in time.
 *   - `tool_error`    — a remote tool ran and reported its own failure.
 *   - `not_connected` — an operation was attempted on an endpoint that is not in
 *     the {@link EndpointPhase} `ready` state.
 *   - `spawn_failed`  — a stdio server subprocess could not be started.
 */
export type FaultKind = "transport" | "protocol" | "timeout" | "tool_error" | "not_connected" | "spawn_failed";
/**
 * A normalized, discriminable failure raised anywhere inside the bridge.
 *
 * The failure class lives on {@link ProtocolFault.kind}; the triggering value
 * (an SDK error, a thrown string, a rejected promise) rides the standard
 * {@link Error.cause} chain rather than a bespoke field. Construct one with
 * {@link protocolFault}.
 */
export declare class ProtocolFault extends Error {
    /** Discriminates the failure class. */
    readonly kind: FaultKind;
    constructor(kind: FaultKind, message: string, cause?: unknown);
}
/**
 * Construct a {@link ProtocolFault}. Convenience over the constructor that keeps
 * call sites terse and uniform.
 */
export declare function protocolFault(kind: FaultKind, message: string, cause?: unknown): ProtocolFault;
/** Narrowing guard: true when `value` is a {@link ProtocolFault}. */
export declare function isProtocolFault(value: unknown): value is ProtocolFault;
/**
 * The lifecycle states of a single {@link ServerEndpoint}.
 *
 * An endpoint advances through this machine rather than juggling loose boolean
 * flags. The legal progression is:
 *
 *   idle ──▶ connecting ──▶ ready ──▶ closing ──▶ closed
 *              │              │          │
 *              └──────────────┴──────────┴──────▶ faulted
 *
 *   - `idle`       — constructed but no connection has been attempted.
 *   - `connecting` — a connection attempt is in flight.
 *   - `ready`      — initialized and able to serve tool calls.
 *   - `closing`    — a graceful shutdown is in progress.
 *   - `closed`     — shut down cleanly; terminal.
 *   - `faulted`    — a fault aborted the endpoint; terminal.
 */
export type EndpointPhase = "idle" | "connecting" | "ready" | "closing" | "closed" | "faulted";
/** True when an endpoint in this phase can accept tool calls. */
export declare function isUsablePhase(phase: EndpointPhase): boolean;
/** True when an endpoint in this phase has reached a terminal state. */
export declare function isTerminalPhase(phase: EndpointPhase): boolean;
/** A server reached by spawning a subprocess and speaking JSON-RPC over stdio. */
export interface StdioServerConfig {
    /** Stable identifier; namespaces this server's tools and keys it in the fleet. */
    readonly id: string;
    /** Transport discriminant. */
    readonly kind: "stdio";
    /** The executable to launch (e.g. `npx`, `node`, an absolute binary path). */
    readonly command: string;
    /** Arguments passed to {@link command}, in order. */
    readonly args?: readonly string[];
    /** Extra environment variables for the spawned process. */
    readonly env?: Readonly<Record<string, string>>;
}
/** A server reached over HTTP using Server-Sent Events for the inbound stream. */
export interface SseServerConfig {
    /** Stable identifier; namespaces this server's tools and keys it in the fleet. */
    readonly id: string;
    /** Transport discriminant. */
    readonly kind: "sse";
    /** The endpoint URL to connect to. */
    readonly url: string;
    /** Extra HTTP headers sent with the connection (e.g. authorization). */
    readonly headers?: Readonly<Record<string, string>>;
}
/**
 * One server's connection description, discriminated by its transport `kind`.
 *
 * Branch on `kind` to recover the transport-specific fields; the two variants
 * share only `id` and `kind`.
 */
export type ServerConfig = StdioServerConfig | SseServerConfig;
/** The transport kinds a {@link ServerConfig} may declare. */
export type TransportKind = ServerConfig["kind"];
/** The set of servers the bridge should connect on start-up. */
export interface BridgeConfig {
    /** The configured servers, in declaration order. */
    readonly servers: readonly ServerConfig[];
}
/**
 * A fully-qualified reference to one tool on one server.
 *
 * Remote tool names are only unique *within* a server, so a reference pairs the
 * owning server's {@link ServerConfig.id} with the tool's own name. The bridge
 * derives the agent-facing, collision-free name from this pair (see
 * {@link RemoteToolRef.qualifiedName} consumers and {@link QUALIFIER}).
 */
export interface RemoteToolRef {
    /** The id of the {@link ServerConfig} that owns the tool. */
    readonly server: string;
    /** The tool's name as the server advertises it, unqualified. */
    readonly name: string;
}
/**
 * The delimiter joining a server id and a remote tool name into the single,
 * collision-free name advertised to the model. A double underscore keeps the
 * qualified name a legal identifier across providers.
 */
export declare const QUALIFIER: "__";
/** Build the agent-facing qualified name for a {@link RemoteToolRef}. */
export declare function qualifyToolName(ref: RemoteToolRef): string;
/**
 * A remote tool as the bridge sees it: the descriptor advertised to the model,
 * paired with the {@link RemoteToolRef} the endpoint needs to route an
 * invocation back to the right server and tool.
 */
export interface RemoteTool {
    /** Where this tool lives. */
    readonly ref: RemoteToolRef;
    /** The model-facing descriptor (qualified name, description, parameters). */
    readonly descriptor: ToolDescriptor;
}
/**
 * A point-in-time projection of a single endpoint's health.
 *
 * Pure data — a snapshot the fleet aggregates and a host can render — carrying
 * the endpoint's current {@link EndpointPhase}, the count of tools it exposes,
 * and the fault that retired it, when one did.
 */
export interface EndpointStatus {
    /** The server this status describes. */
    readonly server: string;
    /** The endpoint's current lifecycle phase. */
    readonly phase: EndpointPhase;
    /** How many tools the endpoint currently exposes. */
    readonly toolCount: number;
    /** The fault that moved the endpoint to `faulted`, if it is faulted. */
    readonly fault?: ProtocolFault;
}
/**
 * The fleet's aggregate health: one {@link EndpointStatus} per configured
 * server, keyed by {@link ServerConfig.id}.
 */
export type FleetStatus = Readonly<Record<string, EndpointStatus>>;
/**
 * The outcome of mounting the bridge.
 *
 * The mount routine connects every configured server, grafts the surviving
 * remote tools into the host's registry, and returns the running fleet together
 * with the {@link ToolBox} the agent will run against and the count of tools
 * actually grafted.
 */
export interface MountedBridge {
    /** The running fleet of endpoints. */
    readonly fleet: ServerFleet;
    /** The tool box exposing every grafted remote tool to the agent. */
    readonly toolBox: ToolBox;
    /** The number of remote tools successfully grafted. */
    readonly toolCount: number;
}
/**
 * A live connection to one external MCP server.
 *
 * An endpoint owns a single
 * transport, advances through the {@link EndpointPhase} machine, and exposes the
 * two operations the bridge needs: enumerate the server's tools and invoke one.
 * Every failure surfaces as a {@link ProtocolFault}.
 */
export interface ServerEndpoint {
    /** The configuration that defines this endpoint. */
    readonly config: ServerConfig;
    /** The endpoint's current lifecycle phase. */
    readonly phase: EndpointPhase;
    /** Open the transport and initialize the session. Idempotent while connecting. */
    open(): Promise<void>;
    /** List the tools this server currently advertises. */
    listTools(): Promise<readonly RemoteTool[]>;
    /** Invoke a remote tool by name with the given arguments. */
    invoke(name: string, args: unknown): Promise<RemoteCallResult>;
    /** A point-in-time projection of this endpoint's health. */
    status(): EndpointStatus;
    /** Gracefully close the transport. */
    close(): Promise<void>;
}
/**
 * The raw result of one remote tool invocation, before it is projected onto the
 * runtime's {@link import("../../runtime/contract").ToolOutcome}.
 *
 * `content` is the ordered set of MCP content blocks the server returned;
 * `isError`, when true, marks the result a {@link FaultKind} `tool_error`
 * the model should be told about.
 */
export interface RemoteCallResult {
    /** The content blocks returned by the remote tool, opaque to this contract. */
    readonly content: readonly unknown[];
    /** True when the remote tool reported its own failure. */
    readonly isError: boolean;
}
/**
 * A name-keyed collection of {@link ServerEndpoint}s with a unified lifecycle.
 *
 * The fleet connects and
 * tears down every endpoint, isolates per-server failures so one bad server does
 * not sink the rest, and projects an aggregate {@link FleetStatus}.
 */
export interface ServerFleet {
    /** Connect every configured endpoint, isolating per-server failures. */
    spinUp(): Promise<void>;
    /** Gracefully close every endpoint. */
    tearDown(): Promise<void>;
    /** Look up a single endpoint by its server id. */
    endpoint(server: string): ServerEndpoint | undefined;
    /** Every endpoint currently held, in configuration order. */
    endpoints(): readonly ServerEndpoint[];
    /** The aggregate health of every endpoint. */
    status(): FleetStatus;
}
