UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

350 lines (349 loc) • 24.2 kB
import { SdkHttpError } from "@modelcontextprotocol/client"; import { type CredentialRef, type PlaintextOrigins, type ProtocolId } from "@sema-agent/primitives"; import type { McpServerSpec, McpTransportKind } from "./mcp-server-spec.js"; /** Why the seat is asked: the first send of a connection, any later send, or the send after a 401. */ export type PeerAskCause = "connect" | "request" | "rejected"; /** * Who the request goes to, as the declaration names it — the whole of it, so the seat can bind an answer to the reference, the * principal, the protocol and the destination (or the whole start command): an http MCP server's url, a stdio one's command and * arguments, an A2A peer's declared urls and THIS send's destination. */ export type PeerSeatTarget = { readonly protocol: "mcp"; readonly server: string; readonly transport: "http"; readonly url: string; readonly credentials?: CredentialRef; readonly fingerprint?: string; } | { readonly protocol: "mcp"; readonly server: string; readonly transport: "stdio"; readonly command: string; readonly args: readonly string[]; readonly credentials?: CredentialRef; readonly fingerprint?: string; } | { readonly protocol: "a2a"; readonly peer: string; readonly url: string; readonly cardUrl?: string; readonly destination: string; readonly credentials?: CredentialRef; }; /** One question to the seat. `principal` is part of the connection's identity; the session is not. */ export interface PeerQuestion { readonly peer: PeerSeatTarget; readonly principal?: string; readonly cause: PeerAskCause; } /** * The seat's answer: the pieces to carry (`headers` for an http request and an A2A send, `env` for a stdio child — the member of the * other lane is refused; `expiresAt`, a non-negative epoch-millisecond number, is read by a stdio child only; a header value is held to the HTTP request grammar and an env value to what a spawn hands the child unchanged), or that the principal is not authorized here. */ export type PeerAnswer = { readonly kind: "carry"; readonly headers?: Readonly<Record<string, string>>; readonly env?: Readonly<Record<string, string>>; readonly expiresAt?: number; } | { readonly kind: "unauthorized"; readonly authorizeUrl?: string; }; /** * The deployment's peer seat (`RunnerDeps.peerSeat`, TRUSTED): one object, three members, all required. * · `answer` — what one send carries. It owes the binding the engine cannot judge: answer only for the reference, principal, * protocol and destination (or start command) it was asked about — never one token for every peer. * · `hold` / `release` — an engine object started / stopped keeping a declaration that names `ref` (see the module note): called * once each per keeper and distinct reference, `release` only for a `hold` that succeeded (it returned, or the promise it returned * fulfilled — a release due before then is sent then); the reference is a frozen copy, never a value, never a session. A seat that * keeps no state per reference makes both no-ops. A throw or a rejection is reported (`onError`, phase `config`) and changes * nothing else: a `hold` that failed is not held and gets no `release`. */ export interface PeerSeat { answer(question: PeerQuestion, signal: AbortSignal): Promise<PeerAnswer>; hold(ref: CredentialRef): void; release(ref: CredentialRef): void; } /** * The one reader of a peer seat handed to the engine (`new Runner`, the three library entrances): absent ⇒ `undefined`; else an * object whose three members are functions, each read once per receipt and kept bound to that object in a frozen copy — or refused * (`config.invalid_argument`) naming what does not fit. A function is the form before 7.60.0: refused with the form that replaced it. * * ONE COPY PER SEAT AT A TIME: a seat object received again whose members read the same functions (by reference) as at its LAST * receipt is handed the copy it was handed then; one whose members read otherwise (a member replaced between two receipts, or a * getter that builds a new function on every read) is a new copy that replaces the record — and putting the original member back * is another new copy, which does not rejoin the first (only the last receipt is remembered). The copy is the credential source a * connection is dialled under ({@link peerSeatIdentityOf}): Runners holding one copy share connections and the memory of a failed * attempt; Runners holding two copies — two objects, or one object across a member change — never do. */ export declare function receivePeerSeat(raw: unknown, subject: string): PeerSeat | undefined; /** * The credential source a connection is dialled under, as a key reads it: `null` for no seat (every seatless leg reads one source: * none), else the seat object's own identity — the copy {@link receivePeerSeat} handed the leg's Runner or entrance. A connection is * one seat's asks ({@link PeerCarrier}), so two seats never share one, nor the memory of an attempt at one. */ export declare function peerSeatIdentityOf(seat: PeerSeat | undefined): number | null; /** Which answer member each transport carries. */ export declare const PEER_ANSWER_LANES: Readonly<{ readonly http: "headers"; readonly a2a: "headers"; readonly stdio: "env"; }>; export type PeerLane = keyof typeof PEER_ANSWER_LANES; /** How long one ask may take before the send goes without it (`credential_unavailable`). */ export declare const PEER_SEAT_WAIT_MS = 30000; /** The longest URL an authorization record keeps (the seat's `authorizeUrl`, the endpoint's `resource_metadata`). */ export declare const AUTHORIZATION_URL_MAX = 2048; /** * The one URL law of the authorization record (`McpAuthorization`, mcp-failure.ts): an absolute http(s) URL with no user-info, within * {@link AUTHORIZATION_URL_MAX} code units, as the URL parser serializes it with every markup-significant character after the host * (brackets, parentheses, angle brackets, quotes, backtick, braces, pipe, caret, backslash) percent-encoded — so the text a model or a * host renders is one plain link — else * `undefined`. A string carrying a control character is refused before parsing (the parser would silently drop a tab or a line break * and keep the rest). */ export declare function authorizationUrlOf(raw: unknown): string | undefined; /** * The `Bearer` challenge's auth-params in a `WWW-Authenticate` value (RFC 7235 §4.1: a comma-separated list of challenges, each a * scheme and its `name=value` params, a value a token or a quoted string) — names lower-cased, the first of a repeated name kept — or * `undefined` when no Bearer challenge is there. A param belongs to the challenge it follows, so `not_error=…`, an `error=` inside a * quoted description and another scheme's params are never the Bearer `error`. A malformed character is stepped over. */ export declare function bearerChallengeParams(header: string | null): ReadonlyMap<string, string> | undefined; /** Why a send went without its pieces. */ export type PeerSeatFailureReason = "threw" | "timed_out" | "answer_invalid" | "unauthorized"; /** * A send the seat did not furnish: nothing was sent. The text names the peer and the reason, never a value and never the seat's own * error text (deployment code may put a credential in it); `authorizeUrl` is the seat's own, when it answered `unauthorized` (read by * {@link authorizationUrlOf}). An MCP failure reads `reason: "unauthorized"` as `unauthorized` (reason `none`), every other reason as * `credential_unavailable` (mcp-failure.ts). */ export declare class PeerSeatFailure extends Error { readonly reason: PeerSeatFailureReason; readonly authorizeUrl: string | undefined; /** An answer the engine cannot carry is the deployment's configuration fault: `config.peer_answer_invalid`, or the ownership law's * own code (`config.protocol_header_collision`) when it names a header it may not. A seat that threw, timed out or refused has none. */ readonly code: string | undefined; constructor(reason: PeerSeatFailureReason, peerLabel: string, problem: string, extra?: { authorizeUrl?: string; code?: string; }); } /** * An MCP HTTP request the endpoint refused for its authorization — a 401, or a 403 whose Bearer challenge says `insufficient_scope` * (RFC 6750 §3.1) — raised by the one fetch ({@link peerFetch}) in place of the SDK's status error, which keeps no header. It IS the * SDK's status error (same class, same `status`), so every structural reader of a status reads it unchanged; it adds what the response * said and what the re-ask after a 401 answered: * · `reason` — `rejected` (401), `seat_unavailable` (401 whose re-ask the seat could not answer: {@link PeerReask.seatUnavailable}) or `scope` * (403); the words are `MCP_AUTHORIZATION_REASONS` minus `none`, which is the seat's own answer and sends nothing; * · `resourceMetadataUrl` — the Bearer challenge's `resource_metadata` ({@link bearerChallengeParams}), the REMOTE's claim, read by * {@link authorizationUrlOf}; * · `authorizeUrl` — the seat's, when it answered the re-ask after a 401 `unauthorized`; * · `renewed` — the re-ask after a 401 answered pieces other than the refused send's: a credential this server has not refused yet * exists, and a new send carries it (the call layer sends a repeat-safe call again on it). It is NOT "the user owes nothing": a seat * that mints a fresh assertion on every ask renews every time, so only a refusal of the credential it renewed to says more. * The text is the engine's sentence followed by the response body as the SDK's own error would have carried it (bounded to * {@link REFUSAL_BODY_MAX} characters) — REMOTE text, read by every face through the one remote-words reading like any status body. */ export declare class PeerAuthorizationRefused extends SdkHttpError { readonly reason: "rejected" | "scope" | "seat_unavailable"; readonly resourceMetadataUrl: string | undefined; readonly authorizeUrl: string | undefined; readonly renewed: boolean; constructor(reason: "rejected" | "scope" | "seat_unavailable", facts: { resourceMetadataUrl?: string; authorizeUrl?: string; renewed?: boolean; body?: string; }); } /** How much of a refusal's response body its text keeps. */ export declare const REFUSAL_BODY_MAX = 4096; /** Whether a failure is an authorization refusal after which the deployment furnished a fresh credential ({@link PeerAuthorizationRefused.renewed}). */ export declare function refusedThenRenewed(err: unknown): boolean; /** What one send carries, as the engine took it from an answer, and its digest (whether a re-ask changed anything). */ export interface CarriedPieces { readonly headers?: Readonly<Record<string, string>>; readonly env?: Readonly<Record<string, string>>; readonly expiresAt?: number; readonly digest: string; } /** The pieces a send carries when the seat answered none (or there is no seat). */ export declare const NO_PIECES: CarriedPieces; /** The seat's answer for `lane`, read once: the pieces, the `unauthorized` answer, or the problem (which member did not fit). The * answer's members are its OWN members (a member its prototype would supply is not read), and each value is judged by the grammar of * the send that will carry it ({@link VALUE_LAW}). */ export declare function readPeerAnswer(raw: unknown, lane: PeerLane): { readonly carry: CarriedPieces; } | { readonly unauthorized: { readonly authorizeUrl?: string; }; } | { readonly problem: string; }; /** Declarations as a keeper holds them: its `mcp` and `a2a` lists, read as given — the keeper reading (agents/agent-definition.ts * `heldDeclarationsOf`) puts into `mcp` the servers of every definition the keeper carries beside its own. */ export interface PeerDeclarations { readonly mcp?: unknown; readonly a2a?: unknown; } /** One keeper's hold on the references its declarations name (see the module note), taken when it is made. */ export interface PeerDeclarationHold { /** Release every reference this keeper holds, each once. A second call does nothing. */ release(): void; } /** * A keeper's hold: `seat.hold` once for each distinct reference (by its canonical form) `declared` names, now, and one `seat.release` * for each hold that succeeded, at `release`. A hold succeeds when it returns — or, when it returns a promise, when that promise * fulfils (a release asked for before then is sent then). No seat ⇒ nothing is held (a declared reference is refused at the door). A * seat member that throws or whose promise rejects reaches `onFault` as the engine's own sentence (the seat's error is not repeated: * deployment code may put a value in it); a hold that failed is not held and gets no release. */ export declare function holdPeerDeclarations(seat: PeerSeat | undefined, declared: PeerDeclarations, onFault: (err: Error) => void): PeerDeclarationHold; /** What the re-ask after a 401 said: whether it answered other pieces than the refused send carried, the seat's `authorizeUrl` when it * answered `unauthorized`, and `seatUnavailable` when the seat did not answer at all (it threw, did not answer within * {@link PEER_SEAT_WAIT_MS}, answered something the engine cannot carry, or the ask was aborted). */ export interface PeerReask { readonly renewed: boolean; readonly authorizeUrl?: string; readonly seatUnavailable?: true; } /** * One connection's (or one A2A peer's) asks of the seat. `next` answers each send: a 401's re-ask answer when one is waiting (carried * once), else the seat's answer to this send. `rejected` is the one re-ask after a 401 (concurrent rejections share it); `renewed` says * whether that re-ask answered pieces that differ from what the rejected send carried — the call layer sends a repeat-safe call again * only then. `sent` is every value a send carried and the principal sent beside them, read by the failure, error, redirect and failed-task paths. */ export declare class PeerCarrier { private readonly seat; private readonly identity; private readonly principal; private readonly lane; readonly sent: string[]; /** Every credential value the seat's answers handed this connection, accepted or refused ({@link answeredCredentialValues}), that the * withheld table holds (one that names a secret, `namesASecret`: never a blank one, a placeholder or a short dev key) — the needle a * remote's account of itself is read without. */ readonly credentials: string[]; /** When the pieces a stdio child was started with stop being good; `undefined` when the answer said nothing. */ expiresAt: number | undefined; renewed: boolean; private asked; private waiting; private rejection; constructor(seat: PeerSeat | undefined, identity: PeerCarrierIdentity, principal: string | undefined, lane: PeerLane, principalSent: boolean); /** The peer as the refusal sentences name it. */ get label(): string; /** The pieces the next send carries (see the class note). A seat failure throws {@link PeerSeatFailure}. */ next(signal?: AbortSignal, destination?: string): Promise<CarriedPieces>; /** The pieces the latest send carried (`undefined` before the first). */ last: CarriedPieces | undefined; /** A send that carried `carried` was answered 401: ask once more (`rejected`); the next send carries that answer. Never throws — * a re-ask that fails leaves `renewed` false, so the 401 is the call's answer, and the next send asks afresh. Resolves to what the * re-ask said (concurrent rejections share one flight and its answer): whether it renewed, the seat's `authorizeUrl` when it answered * `unauthorized`, and `seatUnavailable` when it did not answer — the one word for every way the ask failed but an `unauthorized` * answer, which is an answer. */ rejected(carried: CarriedPieces, signal?: AbortSignal, destination?: string): Promise<PeerReask>; /** Whether the pieces a stdio child was started with have stopped being good. */ expired(now?: number): boolean; private ask; /** * THE one intake of a seat's answer: every credential value it hands ({@link answeredCredentialValues}) is a value the engine now * holds — no child spawned on this host inherits a variable holding it — and a credential of this connection's sends * ({@link PeerCarrier.credentials}). Asked of the answer as given, before it is judged, and of the judge's copy of an accepted answer * (the pieces that are sent). Each value is held on its own, so one that cannot be withheld (the value of a variable every child is * handed) does not keep the others out; the answer is then refused, after the rest were held. */ private holdAnswered; private remember; } /** * The http request headers one send carries: the seat's pieces and the principal under `principalHeader`, judged by the one ownership * law ({@link resolveProtocolHttpHeaders}: one owner per name; an MCP request's protocol-owned names are the SDK's). A collision of the * answer is the seat's fault ({@link PeerSeatFailure}); the declaration's own principal header was judged when the peer was dialed. */ export declare function carriedHttpHeaders(protocol: ProtocolId, carrier: PeerCarrier, pieces: CarriedPieces, principalHeader: string | undefined, principal: string | undefined): Readonly<Record<string, string>> | undefined; /** * The MCP HTTP transport's `fetch` under the seat: every request the transport makes (the POST, the SSE GET, the DELETE) asks the * carrier first, carries what it answered, goes only to the endpoint the declaration named (no redirect is followed — a 3xx is the * answer; a request carrying anything is judged by {@link assertEndpointBound} before it is sent: over https or plain http to this * machine, to the declared origin `bound.declared`), then — for every send, a request's own bytes, a notification, an answer, the receive * stream and the session end alike — asks the revocation question the send carries, else the one this connection was opened under, after * the seat answered (protocol-revocation.ts `askCarriedRevocation`) and, answered 401, has the carrier ask once more for the next send. A refusal of * the authorization — 401, or 403 whose challenge says `insufficient_scope` — is raised here as {@link PeerAuthorizationRefused} * carrying the challenge, the re-ask's answer and the bounded body (the SDK would raise its status error from the same response with * no header kept). */ export declare function peerFetch(carrier: PeerCarrier, principalHeader: string | undefined, principal: string | undefined, bound: { readonly server: string; readonly declared: readonly string[]; readonly fingerprint?: unknown; readonly plaintextOrigins?: PlaintextOrigins; }): typeof fetch; /** The member of a declaration that would carry a value (retired: values come from the seat). */ export declare const RETIRED_VALUE_MEMBERS: Readonly<{ readonly mcp: readonly (readonly string[])[]; readonly a2a: readonly (readonly string[])[]; }>; /** The first retired value member a received copy holds (a member holding `undefined` is absent), as its path. */ export declare function retiredValueMember(copy: Readonly<Record<string, unknown>>, at: keyof typeof RETIRED_VALUE_MEMBERS): readonly string[] | undefined; /** Where a declaration's credential reference sits on each surface. */ export declare const CREDENTIALS_MEMBER: Readonly<{ readonly mcp: readonly string[]; readonly a2a: readonly string[]; }>; /** The credential reference a received copy holds (absent ⇒ `undefined`), judged by the one reader; a problem as a sentence. */ export declare function declaredCredentials(copy: object, at: keyof typeof CREDENTIALS_MEMBER): { readonly ref?: CredentialRef; } | { readonly problem: string; }; /** The variables of the resolver's environment a reference points at: an `env` reference's `headers` map (header name → variable) and * `env` map (child variable → variable), by their values; a reference of any other kind names none the engine can see. */ export declare function referencedVariables(ref: CredentialRef): string[]; /** A declaration that names a credential reference while no seat is wired: nobody would answer it (`config.peer_seat_missing`). */ export declare function peerSeatMissing(subject: string, credentials: CredentialRef | undefined, seat: PeerSeat | undefined): (Error & { code: string; }) | undefined; /** A carrier's identity: the peer the seat is asked about, or a server on a host-supplied transport — whose host seat carries its own * pieces, so the peer seat is never asked about it (its carrier carries nothing). */ export type PeerCarrierIdentity = PeerSeatTarget | { readonly protocol: "mcp"; readonly server: string; readonly transport: "host"; }; /** Who an MCP server is, as the seat is asked about it: its name, the whole start command or endpoint, its reference, its mount identity. */ export declare function mcpPeerTarget(spec: McpServerSpec, kind: McpTransportKind | undefined): Extract<PeerCarrierIdentity, { readonly protocol: "mcp"; }>; /** Whether a failure is the HTTP endpoint answering 401 (the SDK's status error, on the thrown value or its cause chain). Structure only. */ export declare function answeredUnauthorized(err: unknown): boolean; /** The one reading of a re-send's failure: its record says it was not delivered (`details.delivered === "no"` — the seat could not * furnish it, the endpoint refused the connection, the revocation ledger stopped it at the request door). Such a re-send does not speak * for a call whose earlier attempt was sent: the call answers that attempt's failure (a 401's re-send here, a lost session's in * mcp-server-link.ts `callThroughLink`). */ export declare function resendUndelivered(err: unknown): boolean; /** Whether a re-send's failure is the seat's own: its record's word is `credential_unavailable` (the deployment's seat did not furnish it — * mcp-failure.ts reads no other failure so). Such a re-send is undelivered too ({@link resendUndelivered}). */ export declare function resendSeatLost(err: unknown): boolean; /** A call answered 401 after which the seat's re-ask answered other pieces: its failure as it would have been thrown then. `seatLost` * makes the same refusal's failure as the call's answer when the re-send, which carries those pieces, is one the seat could not furnish * ({@link resendSeatLost}): the refusal read as `seat_unavailable`, with the delivery verdict the first send gives it. */ export declare class Reauthorized { readonly error: unknown; readonly seatLost?: (() => unknown) | undefined; constructor(error: unknown, seatLost?: (() => unknown) | undefined); } /** * The call layer's one re-send after a 401: `attempt(false)` once; when it answers {@link Reauthorized} and `mayResend` * (`reach`, asked again) holds, `attempt(true)` once more, carrying what the re-ask answered — the flag says whether this is the last * attempt (its refusal is the call's answer). A re-send that was not delivered ({@link resendUndelivered}) ends with the first * attempt's failure, whose delivery verdict stands for the call (one of its attempts was sent) — read as the seat's loss * ({@link Reauthorized.seatLost}) when the re-send was undelivered because the seat did not furnish it. */ export declare function sentOnceMore<R>(attempt: (last: boolean) => Promise<R | Reauthorized>, mayResend: () => boolean): Promise<R>; export declare function inFlight<T>(client: object, run: () => Promise<T>): Promise<T>; export declare function settledInFlight(client: object): Promise<void>; export declare function recordCarrier(client: object, carrier: PeerCarrier): void; export declare function carrierOf(client: object): PeerCarrier | undefined;