@sema-agent/core
Version:
Stateless, task-oriented AI agent core
294 lines (293 loc) • 28.3 kB
TypeScript
/**
* The HTTP headers one send to a protocol peer carries — the pieces the deployment's peer seat answered for it
* (src/core/peer-seat.ts) and the per-task principal header the declaration names (`principalHeader`) — and the one
* rule they obey, for MCP and A2A alike: they travel only to the endpoints the declaration names, and every header name
* has exactly one owner, compared the way HTTP compares names (case-insensitively). The principal header's owner is the
* engine: it sends the task's principal under that name, or nothing under it when the task has none. A name a protocol's
* transport writes itself (an MCP request's session, protocol version, content type, accept and resume headers) is the
* protocol's: neither a seat's answer nor the principal header owns it. The hosted-connector assertion header
* ({@link MCP_ASSERTION_HEADER}) is the seat's to answer and never the principal header's name. A header the credential
* vocabulary reads as a credential is one the engine holds from the moment the seat answers it, before the answer is judged
* (the carrier's one intake, src/core/peer-seat.ts): no child spawned on this host inherits a variable whose value equals it.
*
* A principal header that breaks the rule is that peer's defect: the resolver throws inside the peer's own dial, so the
* peer is skipped with a coded warning and its siblings still mount; an answer that breaks it is the seat's, and that send
* is not made. Every send that carries pieces — an MCP request (the seat's fetch, `peerFetch`) and an A2A send, whose card may name
* another endpoint — is bound by the one judge {@link assertEndpointBound}: over https (or plain http to this machine) and to a
* declared origin. Neither follows a redirect while it carries them (the MCP fetch follows none; A2A's follow law reads
* {@link carriesDeclaredHeaders}).
*/
import { type Egress, type EgressTier } from "./untrusted-egress.js";
import { crossesNetworkInClear, type ProtocolId, type PlaintextOrigins } from "@sema-agent/primitives";
/**
* The HTTP header NAME a hosted connector reads the principal assertion from: the engine's one definition of that name, exported from
* the package root so a deployment, a host and a connector each read it here instead of spelling it again. The name only — the
* value (the assertion itself) is not minted or held by this constant: the deployment's peer seat answers it under this name, per
* send. It is never the principal header's name (in any letter case): a declaration naming it so is refused at its dial with
* `config.protocol_header_collision`.
*/
export declare const MCP_ASSERTION_HEADER = "connector-assertion";
/** The headers one send carries: the seat's answered `headers` and the declaration's `principalHeader` name. */
export interface ProtocolHttpAuth {
headers?: Record<string, string>;
principalHeader?: string;
}
/**
* The first header name (any case) one send to a `protocol` peer would give two owners, with both spellings: two spellings among the
* answered `headers`, an answered header under the principal header's name, a name the protocol's transport writes itself (`first` is
* then the protocol's spelling, `engineOwned` true), or a principal header named as the engine's {@link MCP_ASSERTION_HEADER}
* (`first` the engine's spelling, `engineOwned` true). The assertion header among the answered headers is the seat's to send.
*/
export declare function headerOwnershipCollision(t: ProtocolHttpAuth, protocol: ProtocolId): {
readonly first: string;
readonly second: string;
readonly engineOwned: boolean;
} | undefined;
/**
* Resolve the HTTP request headers of one send to a peer of `protocol`: the seat's answered headers, plus the
* principal under `principalHeader` when both are present. Throws `config.protocol_header_collision` when
* one header name would have two owners ({@link headerOwnershipCollision}: two spellings of one answered name, an
* answered header under the principal header's name — which would otherwise be sent merged beside the principal, or
* alone when the task has none — a name the protocol's transport writes, or a principal header named as the engine's
* {@link MCP_ASSERTION_HEADER}), and on a principal that was provided and is no principal name ({@link readPrincipal}: a CR/LF would
* split the request, white space at an end is trimmed off a header value by the peer — another person's name). Absence (`undefined`,
* the empty string) sends nothing under the principal header. Callers invoke it INSIDE their per-peer boundary.
*/
export declare function resolveProtocolHttpHeaders(protocol: ProtocolId, t: ProtocolHttpAuth, principal?: string): Readonly<Record<string, string>> | undefined;
/** The engine's default request headers under the declared ones: a declared name, in any case, owns that header
* (the default of the same name is not sent beside it). */
export declare function underDeclaredHeaders(defaults: Readonly<Record<string, string>>, declared: Record<string, string> | undefined): Record<string, string>;
/** A header value as the transport sends it: the HTTP whitespace at its two edges is not part of the value (WHATWG `Headers`). Read
* inward from each edge, so a run of it inside the value is never read (one read of the value, whatever white space it holds). */
export declare const httpTrimmed: (value: string) => string;
/** The part of a `<word> <rest>` value after its first word and the spaces that follow it (`Bearer x` → `x`), or undefined when the value does
* not read that way. The cut is made of the VALUE's shape, whatever the header is called. It lives here, beside the request-echo
* derivation that reads it, so this module's import closure stays small enough for a leaf to read the one-line form of foreign words
* ({@link foreignLine}) without reaching the tools that read that leaf. */
export declare function authSchemeCredentials(value: string): string | undefined;
/**
* A peer's error text with what the peer was SENT taken out of it. Both kinds of removal are found on the ORIGINAL text (so no marker is
* rescanned and no replacement can disturb what another one reads) and the ranges they take are merged, one marker per merged range (the
* bare mark: the place says what was there — a value the request carried, a cookie's value): every
* occurrence of a declared value in any spelling {@link requestEchoSpellings} derives from it (as declared and as sent, its credentials
* part, JSON-escaped with or without `\/` and ASCII-only, a JSON value written compactly, percent-encoded, form-urlencoded, `+` for a space), in any letter case, longest first, and every `Cookie` / `Set-Cookie` member
* whole — a header line to its end, a record member's string, array or object to its close. The two never disarm each other: a declared
* value that lies wholly inside a Cookie member's NAME leaves the name (and the member's value is still taken); one that overlaps the name
* from outside takes its own range and the member's value goes with it. A declared value that is also an ordinary word or number (`en`, `1`,
* `application/json`) goes wherever it occurs in the remote's words, in any case — a legibility cost, never a leak; the failure's closed
* fields (code, status, delivery) are not text. A declaration too large for one matcher (tens of thousands of characters, which no header
* carries) makes the whole text the marker: the pass never throws and never shows what it could not match. A mark the text already holds
* (a member of the marks table) is atomic, by the renderer's one law (`renderWithheld`): a hit that is exactly a mark is no hit, and one
* that reaches into a mark — or lies inside one: a declared value can be a piece of a mark's words — takes the whole mark with it, so the
* pass over its own output answers the same text.
*/
export declare function scrubRequestEcho(text: string, declared: readonly string[]): string;
/**
* Words that came back read without the credentials that were sent — THE one eraser of the credentials a party was handed, in what it
* answered: a remote's own account of itself after a successful dial or listing (an MCP server's `serverInfo`, instructions and tool
* listing; an A2A peer's card; the needle is the connection's credential values, `PeerCarrier.credentials`), and — a root export — what
* a process a host handed credentials to printed (a hook's output; read as it arrives through the stream form,
* {@link createSentCredentialStream}). Every occurrence of a credential of `credentials`, in any spelling the request-echo derivation
* gives it ({@link requestEchoSpellings}) and in any letter case, becomes the redaction mark in place, the way {@link scrubRequestEcho}
* takes a declared value out of a failure's words; where one starts inside another's hit both are found, and hits that overlap or touch
* are one mark. Nothing else is taken — no Cookie member, no vocabulary guess: the rest of the text is the party's own words, and only
* the credentials are the caller's to withhold. A text with no credential in it is returned as it was (the same string). The function
* is a fixed point where no credential holds `«` or `»` (a mark's own characters): a mark it writes, with the characters beside it,
* can spell a credential that holds them, which the text did not hold (KNOWN-LIMITS KL-4766-a). What it withheld is counted, by the
* same matcher, by {@link sentCredentialHits}.
*
* The list is read once, by the one reading the three doors share ({@link sentCredentialList}): a member that is not a string is a
* `TypeError`; an empty one is no needle; a value of one or two characters is withheld wherever it stands; a set too large for one
* matcher withholds the whole text (the `oversized` mark).
*/
export declare function eraseSentCredentials(text: string, credentials: readonly string[]): string;
/**
* How many hits of `credentials` `text` holds — the hits {@link eraseSentCredentials} withholds, found by the same matcher over the same
* spellings: every place a spelling of a credential starts (the longest there), so a credential that holds another counts once at each
* place one of them starts, and two that overlap count twice. The count is the matcher's, never a comparison of the text before and
* after erasing: a hit that is, exactly, a redaction mark the text already holds counts (the renderer writes that mark back as it was),
* and so does one that lies inside a mark (the renderer takes the whole mark) — a credential whose value is a mark, or a piece of a
* mark's words, is counted where the erased text cannot show it. A set too large for one matcher counts a non-empty text as one hit (the
* eraser withholds it whole). 0 for an empty text, an empty list, or a list of empty strings. For a reader that must not take as state
* words that held a credential (a hook's rewrite of a tool's input, serialized whole): more than 0 ⇒ not taken.
*/
export declare function sentCredentialHits(text: string, credentials: readonly string[]): number;
/** Like {@link sentCredentialHits}, reading each value as the transport sends it ({@link credentialParts}) and searching only the
* derived bases that `keep` accepts — one derivation ({@link requestEchoSpellings}), one matcher. */
export declare function sentSecretHits(text: string, credentials: readonly string[], keep: (base: string) => boolean): number;
/** What {@link createSentCredentialStream} answers: a stream eraser of the credentials it was made with. */
export interface SentCredentialStream {
/** The next bytes (a `Uint8Array`; a `Buffer` is one): the erased words that are final now, possibly none (`""`). */
push(bytes: Uint8Array): string;
/** The words still held, erased: the stream is done — a later `push` or `end` throws. */
end(): string;
/** The hits found so far, counted as {@link sentCredentialHits} counts; after `end()`, the count of the whole text. */
readonly hits: number;
/** The most decoded characters the stream holds between calls, fixed when it is made: the longest spelling of a credential less
* one, and the longest redaction mark less one more (that part is held only where the words hold a mark's head); the longest mark
* where the set is too large for one matcher; 0 when nothing is to be withheld. A character's bytes the decoder holds until the
* character is whole (at most three) are not counted. */
readonly holdback: number;
/** The decoded characters the stream holds now, not yet answered — never more than `holdback`. It moves with where a mark's head
* and a character's two halves stand, never with whether a credential was found. */
readonly held: number;
}
/**
* The stream form of {@link eraseSentCredentials}, for a host that reads what a process it handed `credentials` to prints (a hook's
* stdout or stderr) and hands the words on before the process is done. `push(bytes)` answers the erased words that are final, `end()`
* the rest. However the bytes are cut — byte by byte, inside a character, inside a credential, inside a mark — the answers joined are,
* character for character, `eraseSentCredentials(text, credentials)` of the bytes decoded, and after `end()` `hits` is
* `sentCredentialHits(text, credentials)`: one derivation of spellings, one matcher, one law of marks.
*
* The bytes are decoded as UTF-8 by the platform's decoder (`TextDecoder`: a malformed sequence reads U+FFFD, a byte-order mark is
* kept), the bytes of a character not yet whole held until it is. A decoded character is answered once nothing that can still arrive
* changes it: no spelling can still start at or before it (the last `longest spelling − 1` characters wait), and, where the words hold
* a mark's head, the mark is known and every hit that can reach into it is found (a mark goes whole or stays whole); the two halves of
* a character outside the Basic Multilingual Plane are answered together. A run of withheld characters is answered as its one mark the
* moment it starts, and its characters are not kept: what the stream holds is bounded by `holdback`, whatever it is fed.
*
* The list is read as the eraser reads it ({@link sentCredentialList}). An empty list, or one of empty strings, answers the decoded
* words as they are (`holdback` 0). A set too large for one matcher (a spelling longer than 32 767 UTF-16 units: some thousands of
* characters outside ASCII — the matcher compiles when the stream is made, so this is known before a byte is answered) withholds the
* whole text as the eraser does: nothing until the words are more than a mark could be, then the `oversized` mark once (a text that
* is, whole, a mark stays as it is) — that mark is the one sign. `push` takes bytes — any other value is a `TypeError`; a call after
* `end()` throws, and the stream has let its matcher go.
*/
export declare function createSentCredentialStream(credentials: readonly string[]): SentCredentialStream;
/** Where values the credential vocabulary found stand in `text`, read as {@link foundValueSpans} reads them, as [start, end) spans
* (the whole text where the spellings are too many for one matcher): for a reader that searches another spelling of the words
* {@link remoteWords} reads and hands it what it found as {@link FoundElsewhere} spans. */
export declare function foundValuePlaces(text: string, values: readonly string[]): Array<readonly [number, number]>;
/** What the vocabulary found in another spelling of the same words (a reader that carries the words in one spelling and read them in
* another), read onto these words: the spans it withheld there, in these words' coordinates — taken out where they stand — and the
* values it found there, taken out wherever else they stand as {@link foundValueSpans} reads them. */
export interface FoundElsewhere {
readonly spans: ReadonlyArray<readonly [number, number]>;
readonly values: readonly string[];
}
/**
* THE one form a remote endpoint's words take when the engine carries them in its own words — an MCP server's failure, a model
* provider's error body, frame or transport failure, a memory distiller seat's failure: what the request was declared with
* ({@link scrubRequestEcho}: `declared` is required, so no mint reads a remote's words without naming its request), then the credential
* vocabulary. Words with no declared value in them read exactly as the vocabulary renders them. Where a declared value is there, the
* values the vocabulary finds in the ORIGINAL words are taken out with it, so neither disarms the other: removing a declared `Bearer`
* cannot hide the token after it from the vocabulary, and the vocabulary rewriting part of a declared value cannot leave the rest. Each
* is written as its own member — a declared value the bare mark, a value the vocabulary found its row's — and a region they share as
* one, its widest span's (the renderer's one law; of a declared value and a vocabulary find over the same region, the find's: the member
* the words' other faces write there). `found` is what the vocabulary found in another spelling of the same words ({@link FoundElsewhere}),
* written as the bare mark; so is what the words' own one-line spelling finds that their written reading does not hold ({@link
* oneLineFinds}): the words keep their lines, and an exit that folds them later finds nothing left to join. What the vocabulary finds — here or in that other spelling — is taken out where it was found, and wherever
* else it stands where it can be a credential ({@link foundValueSpans}), a Cookie member's name included (only a declared value spares
* it). A caller that bounds the text for display cuts what this returns, never the remote's raw words, so a cut can leave no part of a
* value. The function is a fixed point (its own output answers the same text). A store, a log or an event lane that receives the result
* does not redact again: persistence is not an exit, the mint is.
*/
export declare function remoteWords(text: string, declared: readonly string[], found?: FoundElsewhere): Egress<"same-principal">;
/** What a mint knows beyond a foreign party's words themselves ({@link foreignLine}); all optional — a host seat's or an extension's
* words come with none. */
export interface ForeignReading {
/** The values the request was declared with: what a remote was SENT is taken out wherever it is echoed, in any spelling. */
readonly declared?: readonly string[];
/** Spans of the written words another reading of the same response withholds. */
readonly asSent?: ReadonlyArray<readonly [number, number]>;
/** The tier of the exit the words are written for (`same-principal` unless said). */
readonly tier?: EgressTier;
/** The words are read whole, never a window of their head ({@link boundedForeignReading}): the exit withholds a value its pass
* finds anywhere in the words wherever else it stands in them — a value written bare in the head and labeled only past a window
* included. The provider's sentence reads its words so (it answers to the raw-body reading of the same response, which reads all
* of the body, and before 7.69.0 it was read whole); its cost follows what arrived — words past `FOREIGN_WHOLE_MAX` are not read
* and are written as `pastWholeReading` says. */
readonly whole?: boolean;
}
/** A spelling a mint carries words in: the spelled words, where a span of the written words stands in them, and how a part of the
* written words is spelled there. */
export interface ForeignSpelling {
readonly read: (text: string) => {
readonly spelled: string;
readonly place: (start: number, end: number) => readonly [number, number];
};
readonly part: (text: string) => string;
}
/**
* `text` in `spelling`, with the credential pass taken on the written words and on the spelled ones: what the vocabulary finds in
* the written words (as written and without their format characters — `egressCredentialFinds`) and `reading.asSent` are taken out of
* the spelled words where they stand, and as values wherever else they stand; a part that a character which does not show, or white
* space a reading took into it, cuts is one value, read whole elsewhere ({@link elsewhereWhole}); then the spelled words' own reading
* and the declared values ({@link remoteWords}), then the tier's pass. No cut: the caller bounds what this returns, never the foreign
* words.
*/
export declare function foreignWords(text: string, spelling: ForeignSpelling, reading?: ForeignReading): string;
/**
* THE one form a FOREIGN party's words take when the engine writes them into its own sentence on one line — a remote's answer or
* error (an A2A peer, an MCP server, a model provider, an artifact host), a host seat's, a hook's, an extension's or a store's words,
* a thrown value's text: the credential pass first ({@link foreignWords}, on the words as written AND on the one-line spelling the
* sentence carries them in; on a window of their head when they are longer than `maxLen` and twice the window's margin —
* {@link boundedForeignReading}, so the cost follows the line, and such words end in the cut mark — unless the reading says the
* words are read whole, `reading.whole`), then {@link inlineUntrusted}'s
* fold, bound and tag neutralization, at most `maxLen` code points (and the
* cut mark) — the cut after the pass, so a cut leaves no part of a credential the pass withheld. Words with nothing to withhold read
* exactly as `inlineUntrusted` reads them. A later exit's pass is a fixed point on what this writes; no exit can undo a fold or a
* cut, so the mint is where the pass runs (a multi-line foreign text that is only cut takes `redactThenCut`).
*
* Why both spellings, read on unmasked words and their finds taken together (measured on synthetic keys):
* - the fold turns an invisible separator into a space, so a reading of the folded words alone no longer joins the key —
* `refused: sk-proj-<20 chars>` U+200B `<20 chars> is revoked`, folded and then passed, showed the 20 characters after the
* separator; `password=<6>` U+2060 `<18>` showed 18. The words as written, read without their format characters, hold each
* key whole;
* - the fold also puts a token beside the scheme word a line break kept it from — `Authorization: Negotiate` LF `<48 chars>`:
* the written words read the scheme word as the header's whole value and stop at the break, and the mark that pass writes
* hides the token from any later pass; passed as written and then folded, all 48 characters showed. The folded words read
* the token after its scheme word.
* So each reading finds on its own unmasked words, and what either finds is withheld in the carried spelling (where it stands,
* and — as a value — wherever else it stands there: {@link remoteWords}' found values).
*/
export declare function foreignLine(text: string, maxLen?: number, reading?: ForeignReading): string;
/**
* What {@link remoteWords} withholds of `text`, as [start, end) spans in the text's coordinates — THE answer to "which characters of
* these words does their remote-words reading not carry", for a reader that carries the same words in another spelling and must carry
* no less: the regions its echo pass withholds and the spans its vocabulary pass then withholds in those marked words
* ({@link egressCredentialReading}: the label a rendering keeps is not in the span), read back through the marks (a span that touches a
* mark reaches the whole region the mark stands for); the regions are the merge's own account of what it wrote ({@link mergeWithheldSpans}),
* and where a mark the text already held meets what is taken (see {@link writtenRegions}), the answer is the whole text; and checked against
* the reading's own output: where the text outside the spans does not stand in it as written
* ({@link carriesTheRest}), the spans missed a removal, and the answer is the whole text.
*/
export declare function remoteWordsSpans(text: string, declared: readonly string[], found?: FoundElsewhere): Array<readonly [number, number]>;
/** Whether `rendered` carries, as written and in order, every character of `text` outside `spans`: the text between the spans (merged)
* stands in `rendered` piece by piece — the first at its start, the last at its end, each other one after the one before. Exported for
* its pins; not on the package barrel. */
export declare function carriesTheRest(text: string, spans: ReadonlyArray<readonly [number, number]>, rendered: string): boolean;
/** Whether a resolved header set carries anything the declaration bound to its endpoints — a request that does follows no redirect (the
* next hop is not a declared endpoint; A2A's follow law reads this). */
export declare function carriesDeclaredHeaders(headers: Record<string, string> | undefined): boolean;
/** The code a send carrying a credential is refused with when its endpoint is reached in the clear across a network
* ({@link crossesNetworkInClear}): a protocol send carrying pieces (the peer seat's headers, the principal header;
* {@link assertEndpointBound}), a model request carrying a key or a credential header (the model lane's pairing law,
* `adjudicateModelRoute` in src/brain/route-adjudicator.ts, where it is a `RouteRefusalCode` word), and the memory distiller's
* chat seat (src/core/memory-engine/distiller.ts, refused when it is built). One code for the one question, wherever it is asked. */
export declare const PROTOCOL_PLAINTEXT_CREDENTIALS_CODE = "config.protocol_plaintext_credentials";
/**
* Would a request to this endpoint cross a network in the clear — the ONE "over what" question every credential-carrying send asks
* before it is made: `true` unless the scheme is `https:`, or the scheme is plain `http:` and the host is this machine
* (`isLoopbackHost`, the private-network floor's own loopback reading, over the host as `URL` normalizes it: no DNS, so a name other
* than `localhost` is not this machine whatever it resolves to, and RFC 1918 / cluster addresses are not exempt). A send that carries
* no credential does not ask it. Read by {@link assertEndpointBound} (the protocol chains), the model lane's pairing law, the
* memory distiller's chat seat and the registration check of an inside peer; exported from the package root for a host that sends a
* credential itself. Its one implementation is `@sema-agent/primitives`' (pure string readings, so a check that runs where no network
* module exists reads a host the same way).
*/
export { crossesNetworkInClear };
/**
* THE judge of where a send that carries pieces may go — the seat's answered headers and the principal under the principal header, as
* {@link carriesDeclaredHeaders} reads the resolved set — for MCP and A2A alike, judged at every send (each MCP request; each A2A card
* fetch and JSON-RPC send) and at an A2A card's advertised endpoint before its skills mount. Two questions, in this order:
* 1. over what ({@link crossesNetworkInClear}): `https:`, or plain `http:` to this machine; anything else is
* `config.protocol_plaintext_credentials` — the pieces would cross a network in the clear (a URL that names credentials is the
* hop judge's own refusal, not this one's);
* 2. to whom: an origin the declaration names (an MCP server's `url`; an A2A peer's `url` and `cardUrl`); anything else is
* `config.protocol_endpoint_unbound`.
* A send that carries none goes where it goes (the hop judge, host-floor.ts, judges every hop of every request either way).
* `plaintextOrigins` is the Runner's plain-http admission list (the one the model lane and the consolidation seat read): question 1 is
* asked over it, so on one Runner a credential-carrying plain-http send to a private origin gets one answer on every protocol.
*/
export declare function assertEndpointBound(protocol: ProtocolId, peer: string, endpoint: string, declared: readonly string[], headers: Record<string, string> | undefined, plaintextOrigins?: PlaintextOrigins): void;