UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

567 lines (566 loc) • 48.7 kB
import type { Model, PerModelAuth } from "../internal/llm.js"; import type { AssertAllKeysHandled } from "../core/ask-origin.js"; import type { RouteAdjudication, RouteCredential, RoutePairingConfig, RoutePairingPosture, RouteRefusalCode } from "../internal/llm.js"; import type { Brain, EngineNotice } from "../core/types.js"; import { BrainError } from "./errors.js"; import type { RequestRootOrigin, RouteCarrier } from "./request-route.js"; /** What the pairing law answers: a servable posture or a CREDENTIAL refusal — never `route.model_unavailable`, which is a deployment's * word about a model it does not serve, not a fact of a credential and a root. */ export type PairingAdjudication = Exclude<RouteAdjudication, { code: "route.model_unavailable"; }>; /** A base URL's ROUTE KEY — the value the pairing law COMPARES, folded to WIRE equivalence: the * halves the wire itself treats as case-insensitive (scheme and host, RFC 9110) fold, the scheme's * default port elides, and PATH and QUERY ride byte-preserved apart from the trailing slashes the * request composition itself folds (a query selects the endpoint as surely as a path does; folding * anything the wire keeps would compare two different endpoints equal — the widening this module * exists to stop). An unparseable value keeps its raw trimmed spelling: fail-closed raw * comparison. Non-string input throws — see the module note on garbage. * * **Never render this.** Byte-preserving on the query means `?api_key=<secret>` rides it verbatim; * {@link displayUrlOf} is the one spelling allowed into text. */ export declare function routeKeyOf(url: string | undefined): string; /** A base URL's DISPLAY spelling — the only rendering of a request root allowed into text a human, * a log or a consumer sees. Composed from the PARSE (never edited out of raw bytes): userinfo * drops, EVERY query value becomes {@link REDACTED_VALUE}, and a query NAME rides only where it * really is a name. * - no secret-name list: a list has a blind spot at the name nobody listed. * - names ride because dropping the query WHOLE renders two roots differing only in query as one * string — exactly the pairs the law refuses, so its refusal would read "targets X … paired * with X". {@link queryDifferenceNote} closes the case where the names match too. * - a BARE token (`?<token>`) renders as one placeholder with NO name: `URLSearchParams` calls it a * name with an empty value, and that reading put the payload itself on screen. "Every value is * withheld" protects only what IS a value, so the raw segment decides what rides. * - a name rides only where {@link readQuery} finds the query PURE. A query holding any structured * value — a URL, an e-mail address, anything that is not plain text once decoded — owns the `&` * and `=` the split relies on, so the bytes left of an `=` are not names and are never spoken: * such a query renders as ONE placeholder. A deployment's ordinary names (`tenant`, `api-version`, * `x-request-id`, `filter[name]`, `x.y`) are unaffected, which is what keeps a refusal actionable. * Answers `""` for an undeclared root, like its key twin. */ export declare function displayUrlOf(url: string | undefined): string; /** * The bad-value refusal every base-URL seat owes: **a request root must be an absolute http(s) URL, it * may not carry the credential itself, and it may not carry a fragment.** * * The first two fail the same way if they are not caught here — as a TRANSPORT failure, indistinguishable * from an outage, retried for the whole backoff ladder. Measured: `file:`/`ftp:` reject with * `TypeError("fetch failed")` over a causeless "unknown scheme", the exact shell a refused connection uses. * Stripping userinfo instead of refusing would send an UNAUTHENTICATED request to the host the operator * thought they had authenticated to. A FRAGMENT fails worse than loudly: `fetch` never sends one, so a root * carrying it silently targets the root's own path and every endpoint suffix appended after it lands inside * the discarded part (`https://h/v1#note` + `/chat/completions` → a request to `/v1`). Refused where the * value ARRIVES — construction for `config.baseUrl`, request build for `Model.baseUrl` — and again where a * request URL is composed ({@link joinRequestUrl}), so a root that reached a builder by some other path * cannot compose a wrong URL in silence. An undeclared root is not this rule's question; the PAIRING law * keeps its tolerance for an unparseable spelling ({@link routeKeyOf}). Answers the value it judged. */ export declare function assertServableRequestRoot(url: string | undefined, seat: string): string | undefined; /** * The request URL itself: a request ROOT joined with the endpoint SUFFIX its lane speaks. The one * composition — `${root}${suffix}` put the suffix wherever the root's last character happened to leave it, * which for a root carrying a query (`https://h/v1?api-version=2024-06-01`, the gateway shape a deployment * really declares) appended it INSIDE the last query VALUE and sent the request to `/v1`. * * The rule, stated once for all four builders: the suffix joins the **path** (exactly one separator, * whatever trailing slashes the root carries); the **query** rides byte-preserved AFTER it, because a query * selects the endpoint as surely as a path does and a deployment declares it once for every request; a * **fragment** never reaches here ({@link assertServableRequestRoot} refuses the root, re-asked here so a * root that arrived by some other path is refused rather than composed). * * Composed from the same parse `fetch` itself would make, so the spelling carries no normalization the wire * would not have done anyway. A suffix carrying its own `?`/`#` is a programmer error, not an input: the * query belongs to the root, and the suffix names a path. */ export declare function joinRequestUrl(root: string | undefined, suffix: string): string; /** Remove the userinfo from every authority in free text, WHOLE — the general redactor keeps a short or * unprefixed username, and `TOKEN@host` / `TOKEN:x-oauth-basic@host` are the canonical PAT spellings. A userinfo that * is, exactly, a mark another layer wrote stands as written (a mark is atomic). */ export declare function stripUrlCredentials(text: string): string; /** The request ROOT a brain targets — `Model.baseUrl` else `config.baseUrl` else the lane's default, * in its canonical spelling ({@link canonicalRootSpelling}: trailing PATH slashes folded, query * byte-preserved) — with {@link assertServableRequestRoot} applied to both declared halves on the way. * The three brains each carried a copy of this coalesce-and-strip line, so a rule about base URLs had * three homes; now it has one. Answers `""` when nothing is declared and the lane has no default — * whether that is a refusal is the caller's. */ export declare function resolveRequestRoot(modelBaseUrl: string | undefined, configBaseUrl: string | undefined, laneDefault?: string): string; /** {@link resolveRequestRoot} with the knob that named the root beside it (`RequestRootOrigin`) — the one * resolution; the root a request build sends to and the root its route states cannot come from two readings. */ export declare function resolveRequestRootOf(modelBaseUrl: string | undefined, configBaseUrl: string | undefined, laneDefault?: string): { root: string; origin: RequestRootOrigin; }; /** Whether a header bag carries a credential header (any case) — the engine's one reading of which header carries a * credential ({@link isCredentialHeaderName}: `Authorization`, `X-Api-Key`, Azure's `api-key`, `x-goog-api-key`, * `Cookie`, …), the same reading the withheld-value intake keeps. */ export declare function hasAuthCarrier(headers: Record<string, string> | undefined): boolean; /** A request root's ORIGIN as the request gate folds it — the one fold the engine compares origins by (a request's, an answer's * declared `credentialOrigin`, a rebind's): scheme, host and port of its route key ({@link routeKeyOf}), the scheme's default * port elided. Exported for a host that compares two roots' origins itself (a credential has one origin). It folds, it does not * judge: a root the request-root judge refuses (userinfo, a fragment) folds to the origin of the URL it parses as; a spelling * that does not parse as an http(s) URL folds to its whole route key and so equals no parsed origin; `""` = no root; a * non-string throws (garbage, the module note). Like the route key it is a comparison value: **never render it** — {@link displayUrlOf}. */ export declare function requestOriginOf(root: string): string; /** Test seam: empties the process's credential-origin table — every per-model credential is unbound again, as at a * process start. Never called by production code (a deployment moves one credential with {@link rebindCredentialOrigin}, and a restart empties the table). A test * suite that sends one fixture credential to two local mock upstreams (two `listen(0)` ports are two origins) calls it * between cases, or gives each case its own fixture credential. */ export declare function __resetCredentialOriginBindings(): void; /** * The key a request carries in its lane's key header — THE one reading of which `apiKey` (the per-call one, or the * brain's construction-time one) writes that header: the key itself when it is not blank ({@link isBlankCredential}), * else `undefined`. A blank key (the empty string, or white space only) is the keyless door: its source keeps its rank, * and the credential {@link resolveRouteCredential} resolves carries no `apiKey` — so no lane writes a key header, no * identity is bound and no header of the request's own conflicts with it. Read where a credential is resolved, and by * the route a request states ({@link import("./request-route.js").requestRouteOf}); a host that sends a request itself * reads the resolved credential's `apiKey`, as the lanes do. */ export declare function keyCarriedBy(apiKey: string | undefined): string | undefined; /** * How a credential rides on the wire: its key in the lane's key header (`"apiKey"`), a credential header with a value (`"header"`), * or nothing (`undefined`) — the keyless door at whatever rank (a blank key, a bag of blank credential headers), or no source at all. * THE one reading of "does this request carry a credential": the route a request states * ({@link import("./request-route.js").requestRouteOf}), the law's "over what" question ({@link plaintextRefusal}) and a brain that * sends no request without a credential ({@link RoutePairingConfig.requireCredential}) all read it. */ export declare function credentialCarrierOf(credential: RouteCredential): RouteCarrier | undefined; /** * Resolve WHICH credential a request would carry, tagged with its source — the input half of the * adjudication. One rank per SOURCE, most-specific wins; within a rank the apiKey knob and the rank's * credential headers are ONE credential (they ride together and are bound together): * 1. the per-model auth hook's answer — `options.apiKey` (presence, not truthiness: a blank key is * the keyless door, {@link keyCarriedBy} — it keeps this rank, so no key header goes out and the * deployment's never rides in its place) and/or a credential header ({@link hasAuthCarrier}) in `options.headers` (a * gateway's own `Helicone-Auth` beside the key, or the key spelled as a header — not both: an `apiKey` * beside a header of the very name the lane writes the key in (`keyHeader`) is resolved all the same, with * that conflict recorded beside it for the law to refuse). The bag MUST be * per-model sourced (the hook's headers) — that provenance is what makes it a credential of THIS * entry, bound to its own origin below. A caller that folds run-wide headers into the per-call * options must strip credential headers first (the harness merge does), or a deployment * credential would ride here and be judged per-model, * 2. a credential header in `model.headers` (the ENTRY's own declared credential), * 3. the deployment config (`config.apiKey` and/or a credential header in `config.headers` — the * documented gateway dual-auth shape, both riding as they always have; the pairing gate judges * the pair as one deployment credential), * 4. absent. * 1–2 are `per-model`; 3 is `deployment-config`. The rank is the source's presence; the returned credential is what of * it rides: a blank key ({@link keyCarriedBy}) is no `apiKey` and a bag whose credential headers are all blank is no * `headersBorne` — the keyless door, at that rank (`{ source: "per-model" }` carries nothing, and no lower source * rides in its place). A per-model credential that carries a secret leaves * here with its identity beside it (a digest, held by this module and never a member of the returned * object), which {@link adjudicateModelRoute} reads against the origin table and {@link admitRouteRequest} * binds when its request is sent. Resolution does not judge the route: what it found — an identity, a key beside * its own header — is the law's to rule on, in one verdict shape for every caller. */ export declare function resolveRouteCredential(input: { optionsApiKey?: string; optionsHeaders?: Record<string, string>; modelHeaders?: Record<string, string>; configApiKey?: string; configHeaders?: Record<string, string>; /** The header the caller's lane writes a per-call `apiKey` in (`authorization`, `x-api-key`), when it has one. Per-call * options that carry an `apiKey` and a header of that name (any case) are two values for one header: the credential * is resolved with that conflict beside it, and the law refuses it (`route.credential_answer_conflict`) rather than * let the key win. Optional like every input here: a caller that does not know its lane leaves it out, and then no * conflict is recorded and none is refused. */ keyHeader?: string; /** The origin the per-call options (the per-model auth answer, {@link askPerModelAuth}) were handed out FOR — its * `credentialOrigin`. It binds the WHOLE request: one going elsewhere is refused whatever it carries and whichever source * its credential resolved from (a secret in a header outside the credential vocabulary is no credential here, and still the * answer's). The answer's own credential is judged by it in the table's place; one from the entry's headers or the brain's * config keeps its own law (the table, the pairing with the brain's root). */ optionsCredentialOrigin?: string; /** The per-call options' answer named no origin and the engine judged its seat's entry not settled across a catalog swap * ({@link PerModelAuth.credentialOriginUnsettled}): it binds the WHOLE request too — the request is carried only where the * answer's own credential is already bound to the origin it dials. Ignored beside {@link optionsCredentialOrigin}. */ optionsCredentialOriginUnsettled?: boolean; }): RouteCredential; /** The no-credential exit of a credential-origin refusal, in the one wording its fix hint and the run's announcement share. * An empty `apiKey` is a per-model answer with no secret, so it binds nothing and never falls back to the brain's own key or * root; leaving the answer out reaches the same place only where the brain has neither. A placeholder word is a credential. */ export declare const KEYLESS_EXIT = "hand it none \u2014 answer an empty apiKey and no credential header (this works under any brain; a brain configured with neither a baseUrl nor a credential of its own also accepts no apiKey at all), because a placeholder word handed in its place is still a credential and binds like any other"; /** * The pairing law (module note above). A READ: it judges against the engine's credential-origin table and writes * nothing, so a pre-flight, the read face ({@link routePairingStatus}) and any consumer may call it freely — same * inputs and same table, same verdict. A request whose answer named its origin goes there or nowhere, whatever it carries * (`route.credential_origin_mismatch`, that origin as the bound one). A per-model credential {@link resolveRouteCredential} * resolved with a key beside its own header is refused next (`route.credential_answer_conflict`, both header names in the * fix — the request itself is contradictory). Then, for a credential of either source, over what * ({@link plaintextRefusal}: a credential is never sent across a network in the clear); then to whom: the answer's own * credential belongs to the origin it named; any other per-model credential is judged against the origin it is bound to * (refused when that is another one); one not bound yet, or built by hand (no resolution facts — the published corpus * is such input), is servable. A route found servable that carries no credential is refused where the config declares * `requireCredential` (`route.credential_missing`). Every refusal is a verdict: the law throws on garbage alone. The table is written by a first-party brain's request gate ({@link admitRouteRequest}), when the engine commits the request to be sent, and by the * host's explicit rebind ({@link rebindCredentialOrigin}) — never by a judgment. The verdict reports nothing either: the * request gate's refusal is {@link routeRefusalError}. */ export declare function adjudicateModelRoute(model: Pick<Model, "id" | "baseUrl">, credential: RouteCredential, config: RoutePairingConfig): PairingAdjudication; /** Render a refusal as the one-line detail text the brains put in their thrown error (the machine * code leads so log/transcript consumers can grep it; the fix hint closes it). */ export declare function routeRefusalText(verdict: Extract<RouteAdjudication, { ok: false; }>): string; /** The refusal of a request — the ONE error a first-party brain throws when the pairing law refuses the request it is * building ({@link admitRouteRequest}), and the one the model lane answers a requested model with when the deployment's * judgment refused it before dispatch. The two refusals that keep a credential from a root it does not belong to — the * deployment credential paired with another root, a per-model credential bound to another origin — are also reported to the * run they happen in (the run announces the refusal's own code): here, at the request that is refused, and not in the law, * whose other callers only advise (a pre-flight, the read face) and leave the outcome to the seat that asked. */ export declare function routeRefusalError(verdict: Extract<RouteAdjudication, { ok: false; }>): BrainError; /** The code a seat records for a route judgment that did not answer one — it threw, or answered something that is not a verdict * (a Promise: a judgment answers synchronously; any other value), or a verdict whose members would not read. Every seat that * asks reads it as the route refused (nothing is sent on a judgment that did not show the route servable): the model lane's * `skipped[].code` and terminal, a derived seat's `cause`. Not a `RouteRefusalCode`: no judgment stated it. */ export declare const ROUTE_JUDGMENT_FAILED = "route.judgment_failed"; /** The cause a seat that asked the route judgment records when the route was refused: the refusal code the judgment stated, or * {@link ROUTE_JUDGMENT_FAILED}. */ export type RouteJudgmentCause = RouteRefusalCode | typeof ROUTE_JUDGMENT_FAILED; /** A route the deployment Brain's judgment refused, as the seat that asked holds it — every member read once, when it was asked: * the code it stated and its fix sentence (each absent when it gave none), and, when both read, the refusal as a verdict (its * `modelId` the judged model's when it names none, its credential roots kept where they are strings, what bound its credential * kept where it is one of the law's words) for the request gate's error. */ export interface JudgedRefusal { readonly code?: string; readonly fixHint?: string; readonly verdict?: Extract<RouteAdjudication, { ok: false; }>; } /** Whether a route judgment's answer is a Promise (any object whose `then`, read once, is a function): a judgment answers * synchronously, so a Promise is no verdict, and its own settlement belongs to nobody — it must not become an unhandled * rejection. That very `then` is handed two empty reactions, called with the answer as `this` (a throw of the call is absorbed * too). A plain answer is not touched beyond that one read; a `then` that will not read (a strict Proxy whose `get` throws) shows * no `then`, so the answer is no Promise and is read by the `ok` it gives — as 7.73.0 read an answer whose members read the same at * every read; reading `then` before `ok` is new (`KL-4241-d` (9)). */ export declare function settleUnread(answer: unknown): boolean; /** What a sentence says for a model whose `id` will not read (an accessor that throws, a revoked proxy). */ export declare const UNREADABLE_MODEL_ID = "<unreadable model id>"; /** A model's id for a sentence about it: one guarded read; an id that will not read is said as {@link UNREADABLE_MODEL_ID}. */ export declare function sayableModelId(model: { readonly id: string; }): string; /** * THE reading of a route judgment's answer — every seat that asks the deployment Brain's `adjudicateRoute` reads the answer here, * once (the model lane before each hop, a derived seat's pre-flight): `undefined` when the route goes ahead — the judgment * admitted it (`ok: true`) or gave none (`undefined`: no judgment) — else the route as refused. `ok: false` is a refusal, read * member by member; ANY other answer is a judgment that failed ({@link ROUTE_JUDGMENT_FAILED}, the sentence saying how): it * threw, answered a Promise, whatever `ok` it carries (a route judgment answers synchronously — a pending answer is no answer, and * reading it as one would admit every route it was asked about; its settlement is absorbed, {@link settleUnread}), answered a value that is not a verdict, or a verdict whose members would not read. * Never throws. `ask` is the call (so its throw is read here); `judged` is the judged model, whose id names it in the sentence — * read once, only when there is a refusal to say (a route that goes ahead costs no read of the model), and said as * {@link UNREADABLE_MODEL_ID} when it will not read ({@link sayableModelId}). */ export declare function readRouteJudgment(ask: () => unknown, judged: { readonly id: string; }): JudgedRefusal | undefined; /** * THE request gate of a first-party brain — the seat that binds a credential where it is first SENT (the table's other * writer is the host's explicit rebind, {@link rebindCredentialOrigin}, which sets a credential's origin by the host's * word). Judged while the * request is built ({@link adjudicateModelRoute}, the same law the pre-flight and the read face read): a refusal is * thrown here ({@link routeRefusalError}) before the body is built, and binds nothing — every refusal the law rules, * a key beside its own header included, leaves as that one error (`<code>: <fix>`); the gate rules nothing of its * own. An admitted request hands back its * ADMISSION, which the brain runs from `SSERequest.onCommitted` — the engine's one point at which THIS request is the one * that is sent: the law judged again and, admitted, the per-model credential bound to the request's origin, in ONE * synchronous step; refused (the credential went out to another origin since the build — caller code runs while a body * is built), the same refusal is thrown there, before anything is sent. A request built speculatively and declined (the * context-overflow recovery's candidate), or one whose build fails after the gate, never reaches its admission and binds * nothing. A request binds a credential to the origin it is SENT to, never to one it was only judged for. The request's * halves (the entry's id and root, the brain's root and lane default) are read ONCE, here: both judgments and the binding * are of the request this build is sending, whatever the caller's objects say by the time it is committed. * * Exported from the package root for a HOST that sends a request itself (its own `fetch`, outside a first-party brain): it * passes this same gate, so the binding does not depend on who sends first. Resolve the credential with * {@link resolveRouteCredential} (a credential built by hand carries no identity: it is judged and binds nothing), call this * before building, and run the admission it returns immediately before the request goes out; a refusal is the very error a * first-party brain throws for the same request. {@link adjudicateModelRoute} stays the read: it judges and binds nothing. */ export declare function admitRouteRequest(model: Pick<Model, "id" | "baseUrl">, credential: RouteCredential, config: RoutePairingConfig): () => void; /** What {@link rebindCredentialOrigin} did: the origin the credential is bound to now, the other origins it was bound to * before (both in display spelling — never a credential or a digest of one), and whether the table changed. */ export interface CredentialRebind { readonly origin: string; /** The origins one of the credential's secrets was bound to before, other than {@link CredentialRebind.origin}, each * once; empty when none was bound elsewhere. */ readonly previous: readonly string[]; /** `false` ⇒ every secret the credential carries was already bound to `origin`: nothing was written, nothing announced. */ readonly changed: boolean; } /** One entry of a catalog generation handed to {@link rebindCredentialOrigin} in its group form: the entry as it is in force, * the per-model hook's answer the request will get for it, and one pairing config per lane root its request may be judged * under (the brain that serves it, and each brain a failover may hand it to) — at least one. */ export interface CredentialRebindEntry { readonly model: Pick<Model, "id" | "baseUrl" | "headers">; readonly perModelAuth?: { apiKey?: string; headers?: Record<string, string>; }; readonly configs: readonly RoutePairingConfig[]; } /** What the group form of {@link rebindCredentialOrigin} did for one entry — one answer per entry, in the order and number handed: * - `"rebound"` — its secrets now bound to `origin` (the table changed; `route.credential_rebound` was announced for it); * - `"unchanged"` — every secret of it was already bound to `origin`; * - `"withheld"` — a secret of it goes to more than one origin across the group (`origins`, `peers`): one credential has one * root, so nothing is bound or announced on its account; * - `"none"` — nothing of it can be bound: it carries no secret of its own (no per-model credential, or the keyless door), or * none of its configs gives its request a servable root (that request is refused when it is built). * Origins in display spelling — never a credential or a digest of one. `modelId` is for display: two entries may share it. */ export interface CredentialRebindAlignment { readonly modelId: string; readonly outcome: CredentialRebindOutcome; /** `"rebound"` / `"unchanged"`: the one origin its secrets are bound to. */ readonly origin?: string; /** `"rebound"`: the other origins one of its secrets was bound to before; empty otherwise. */ readonly previous: readonly string[]; /** `"withheld"` only: every origin a secret of this entry goes to across the group, its own included — two or more, in the * order the group first names them. */ readonly origins?: readonly string[]; /** `"withheld"` only: the positions (in the group as handed) of the other entries that carry a secret of this entry that goes to * more than one origin — ascending; empty when this entry alone sends it to two (two configs, two roots). */ readonly peers?: readonly number[]; } /** The four outcomes of {@link CredentialRebindAlignment}. */ export declare const CREDENTIAL_REBIND_OUTCOMES: readonly ["rebound", "unchanged", "withheld", "none"]; export type CredentialRebindOutcome = (typeof CREDENTIAL_REBIND_OUTCOMES)[number]; /** * The host's explicit rebind — the one way a per-model credential's binding MOVES inside a process. The credential is * resolved here, from the entry and the per-model hook's answer for it, by the request's own resolution * ({@link resolveRouteCredential}: the answer's key and credential headers when it answers one, else the entry's own * credential headers — never the brain's deployment credential), so the secrets bound are the ones that request carries, * read off the bags once. Every one of them is bound to the origin the entry's request goes to, read as a first-party * brain reads it: its root through the brains' own root judge ({@link resolveRequestRootOf} — the entry's root, else the * brain's declared root, else the lane default) and its origin as the request gate folds it. From then on a request * carrying that credential to any other origin is refused, whichever entry it rides: a credential has one root, so an * entry still pointing at the old host is refused as well. A request the gate judged before the rebind and commits after * it is judged again at its commit and refused there. Nothing else moves a binding: a request, a catalog swap or an * entry's own members never do, and a restart empties the table. * * Hand the entry as it is in force now and the hook's answer the request will get: the target is that entry's origin * today, so a call made from a stale copy rebinds to a stale host. A hook that answers a new value on every call has * nothing to rebind (each value binds where it is first sent). A call that changed the table announces * `route.credential_rebound` (operator) once, to `onNotice` (else the process's default notice seat, else one process * line), naming the entry, the new origin and the previous ones — announced just before the write; the announcement never * throws, so the write always follows it. A call that found every secret already there writes and announces nothing. What the call did is also * its return value — the notice is the engine's account of its table, the record of * who asked is the host's. Refused, with nothing written (`config.invalid_argument`), two arms: no secret of the entry's * own to bind (no per-model credential — the deployment credential's one root is its brain's declared root, so it has no * binding to move — or an answer through the keyless door), and an entry whose request has no servable root (the lane * default the host hands is judged like the entry's and the brain's roots). A non-string * id, URL half or key throws a `TypeError`, as for every caller of the law. * * **The group form** — `rebindCredentialOrigin(entries, onNotice?)`, every entry of a catalog generation that carries a * credential of its own ({@link CredentialRebindEntry}: the entry, the hook's answer for it, one pairing config per lane root its * request may be judged under) — is the same rebind applied to a generation, and it answers the question a host aligning a * generation must otherwise answer itself: does one credential go to one origin across the catalog? Each entry is read as the * one-entry form reads it, once per config; the origins it can go to are the union over its configs. A secret that the group sends * to ONE origin is bound there (each entry that changed the table announced as above, in the order handed); a secret the group * sends to two or more origins has no one root to move to, so every entry carrying it is `"withheld"` — nothing is bound or * announced on its account, and its answer names those origins and the other entries carrying it. An entry with no secret of its * own, or whose configs give its request no servable root, answers `"none"`. **Returned ⇒ every entry has its answer, in the * order and number handed; thrown ⇒ nothing was bound**: every entry is read and judged, and every announcement built, before * anything is written, and only a bad value throws — a `TypeError` (an entry, answer or config that is not an object, an empty `configs`, a * non-string id / URL half / key, a non-boolean `requireCredential`), or the refusal (`config.invalid_argument`) the engine's * credential intake gives a secret it refuses on every request. A secret the group leaves out is not counted: hand the generation whole. */ export declare function rebindCredentialOrigin(entries: readonly CredentialRebindEntry[], onNotice?: (notice: EngineNotice) => void): readonly CredentialRebindAlignment[]; export declare function rebindCredentialOrigin(model: Pick<Model, "id" | "baseUrl" | "headers">, perModelAuth: { apiKey?: string; headers?: Record<string, string>; } | undefined, config: RoutePairingConfig, onNotice?: (notice: EngineNotice) => void): CredentialRebind; /** * Enforce "the resolved credential is the request's ONLY credential" on an already-merged header * bag — one source's credential rides, the other sources' credential headers do not: * - PER-MODEL winner → every credential header ({@link isCredentialHeaderName}) is stripped and the * winning bag's own credential headers written back — exactly the ones {@link resolveRouteCredential} * read and hashed ({@link ResolvedCredentialFacts}; the caller's bag is not read again): the hook's * answer (`options`) or the entry (`model`). The hook's answer is one credential — beside its apiKey, * which the brain then writes in its lane's key header (a request that also holds a header of that name * never gets here in a first-party brain: its request gate refused it first, `route.credential_answer_conflict`, * so the lock supersedes nothing the answer carried), its other credential headers ride (a gateway's `Helicone-Auth`); an * entry's credential survives a same- or variant-case deployment spelling that the plain merge order * would have let win. A credential header from any OTHER bag (the entry's under a hook answer, the * deployment's under either) never rides beside a per-model credential. Whether a header is stripped * is decided by its SOURCE, not its name. * - DEPLOYMENT-CONFIG winner → its own headers kept. A header-only config keeps its own spelling, and a * config carrying BOTH the apiKey knob and an auth header is the documented gateway dual-auth shape — * the knob's lock write plus the surviving header, both on the wire. * - absent → nothing to strip (no carriers exist). * Whatever the source, a credential header whose value is blank ({@link isBlankCredential}) is no credential and does * not ride — the header half of the keyless door the blank key is ({@link keyCarriedBy}). */ export declare function applyRouteCredentialHeaders(merged: Record<string, string>, credential: RouteCredential): void; /** * THE one reading of "a credential header whose value is blank is no credential and does not ride" ({@link isBlankCredential}): * every header of `headers` whose name is a credential header ({@link isCredentialHeaderName}) and whose value is blank is deleted * from it. Read by {@link applyRouteCredentialHeaders} on a request's merged bag, and by a judge that answers for the same bag * before a request is built (`anthropicCredentialHeadersOf`). A credential header's value is a string. */ export declare function dropBlankCredentialHeaders(headers: Record<string, string>): void; /** A brain's construction config, received ONCE by the engine's receipt law for caller objects * ({@link receiveOwnProperties}: a plain object, every own member read once): the request gate and the pre-flight * judge both read this frozen copy, so a config object mutated after construction moves neither and the two cannot * disagree about the root a credential is paired with. The header bag is a caller object too: it is received by the * same law from that one reading into a frozen bag of the copy's own. The copy's credential — `apiKey` and the * credential headers — is a credential the engine now holds: no child spawned on this host inherits a variable whose * value equals it (`holdOwnCredentialValues`). */ export declare function brainConfigSnapshot<T extends { apiKey?: string; headers?: Record<string, string>; }>(given: T, subject: string): Readonly<T>; /** * The first-party brains' `adjudicateRoute` face, closed over the brain's construction config — * EXACTLY the resolution + judgment the brain's own request build runs (single source, two call * sites), so a pre-flight verdict and the request-time verdict agree on the same inputs. A refusal is * always a verdict here, never a throw. The pre-flight sees the * per-model auth it is handed, nothing later: a header a provider-request hook adds afterwards reaches * the request build alone, which judges it by the same law. */ export declare function createBrainRouteJudge(config: { apiKey?: string; baseUrl?: string; headers?: Record<string, string>; /** The lane's own default endpoint (the brain's constant), when it has one. */ laneDefault?: string; /** The header the lane writes a per-call apiKey in ({@link resolveRouteCredential}'s `keyHeader`): the brain's own * constant, so the judge refuses the requests its request build refuses. */ keyHeader?: string; /** The brain sends no request without a credential ({@link RoutePairingConfig.requireCredential}); read here, when the brain is * built, so a value that is not a boolean is refused at construction rather than at the first request. */ requireCredential?: boolean; }): (model: Model, perModelAuth?: PerModelAuth) => RouteAdjudication; /** The words of {@link RoutePairingStatus}, spelled (the release manifest and a host's table read them): fenced both ways to the type below, so neither can gain a word the other lacks. */ export declare const ROUTE_PAIRING_STATUSES: readonly ["ok:per-model", "ok:paired", "ok:keyless", "broken:credential_mismatch", "broken:credential_missing", "broken:credential_origin_mismatch", "broken:credential_answer_conflict", "broken:protocol_plaintext_credentials", "broken:model_unavailable", "unknown"]; export type RoutePairingStatusesAllListed = AssertAllKeysHandled<Exclude<RoutePairingStatus, (typeof ROUTE_PAIRING_STATUSES)[number]>>; export type RoutePairingStatusesAllWords = AssertAllKeysHandled<Exclude<(typeof ROUTE_PAIRING_STATUSES)[number], RoutePairingStatus>>; /** * Per-entry pairing status — the read-face predicate a roster/diagnostic surface annotates entries * with, so a torn pair is visible at configuration time instead of on the first real request. * `judge` is a brain's optional `adjudicateRoute` face; absent ⇒ `"unknown"` (a custom brain core * cannot see into — never guessed at). */ export type RoutePairingStatus = `ok:${RoutePairingPosture}` | `broken:${"credential_mismatch" | "credential_missing" | "credential_origin_mismatch" | "credential_answer_conflict" | "protocol_plaintext_credentials" | "model_unavailable"}` | "unknown"; export declare function routePairingStatus(brain: { adjudicateRoute?: (model: Model, perModelAuth?: PerModelAuth) => RouteAdjudication | undefined; }, model: Model, perModelAuth?: PerModelAuth): RoutePairingStatus; /** * Pre-flight a DERIVED-leg model (one the engine resolved from a role/tier/system default rather * than an explicit caller `model`) against the deployment brain's pairing judge. The two-leg * disposition for a broken pairing: * - a NAMED model (explicit in the spec) refuses loudly at the brain's request gate — the caller * asked for that exact route and gets the refusal + fix hint; * - a DERIVED model must not sink the main-model task it serves — the seat falls back to the * primary model and announces `route.fallback_to_primary` (the notice IS the loudness; a silent * swap would hide the misconfiguration this whole surface exists to expose). * Returns the refusal ({@link readRouteJudgment}: a judgment that throws or answers no verdict is * the route refused, `route.judgment_failed` — the model lane refuses every request it would send on * it), or `undefined` when the route goes ahead or no judgment is possible (the brain has no judge * face, or the auth hook threw or outran the advisory bound — in which case the seat proceeds * unchanged and the failure/latency surfaces at its own request-time call site exactly as before). * * The hook call is BOUNDED. The pre-flight is advisory (the request gate re-runs the same law), so * it must never widen a slow secret manager's blast radius from "the derived call is slow" to "task * preparation is wedged": past the bound the pre-flight simply abstains. The eventual request still * resolves the hook itself (the pre-flight result is never reused as a credential — same-inputs * determinism of the law is what keeps the two calls' verdicts aligned, not a cached secret). */ export declare const DERIVED_ROUTE_PREFLIGHT_HOOK_BOUND_MS = 5000; /** A per-model auth seat, in every shape a caller declares one (a promise or a value; the task seat's key is required, the * side seats' optional — every one of them is a {@link PerModelAuth} to the reader). */ export type PerModelAuthSeat = (model: Model) => PerModelAuth | undefined | Promise<PerModelAuth | undefined>; /** * THE one reading of a per-model auth seat's answer: every engine site that asks the seat for a model's credential asks through * here and hands the brain what this returns (spread into the request's options, or to a brain's `adjudicateRoute`), so a member * of the answer reaches the request gate from every lane or from none — a scan of the source by name (pin F0) finds no other * call of the seat; a call it cannot spell (a renamed alias, `.call`) is not seen. The seat is asked with the model the request * will carry, as a method of `receiver` — the object the lane read the seat from (a spec, an options object, the harness), so a * seat written as a method sees the `this` it always saw; a lane that read it from no object passes none. A throw from it * propagates as it always did (the * request is not sent). The answer is read once: `apiKey` as given; `headers` into a frozen copy of its own enumerable entries * ({@link headerBagOnce}, as a request build reads a bag — a lane hands its judgment and its Brain that one reading, and a * getter in the bag that throws throws here); `credentialOrigin` judged — absent ⇒ absent, * an absolute http(s) URL (an entry's `baseUrl` may be handed as it is) ⇒ folded to its origin, anything else ⇒ refused * (`config.invalid_argument`, naming the model) before any request is built, never read as "no declaration". No seat (absent or * `null`) or no answer ⇒ `undefined`. `credentialOriginUnsettled` is the engine's own member: set when a seat the Runner took finds the entry not settled * across a catalog swap ({@link seatAskMarker}), for an answer that names no origin and carries a key or a header; a seat's own * member of that name is not read. The taken seat sees the ask only when it is itself called within this ask's asynchronous context — * directly, bound, from a function of the host's, or from a timer or promise chain the host starts inside the ask; a host wrapper that * runs it in a context set up before the ask (a pre-built `AsyncResource`, an `AsyncLocalStorage.snapshot()`, a `MessagePort` * listener, a timer queue or serial pool already running, a cache warmed before the ask) reaches it with no ask, and its answer is * carried as the released engine carried it. */ export declare function askPerModelAuth(seat: PerModelAuthSeat | null | undefined, model: Model, receiver?: unknown): Promise<PerModelAuth | undefined>; /** The mark of the ask a seat is being called in — the engine's one reader asking it, directly or through a function of the host's * that calls it — or `undefined` when host code calls it (a tool's context: no request rides on that answer). A seat the Runner took * marks its ask when the entry it was asked for is not settled across a catalog swap; the mark only ever sets. */ export declare function seatAskMarker(): (() => void) | undefined; /** A per-model auth answer the engine refused before anything was sent — its `credentialOrigin` is no servable origin, or (in * the agent loop) a provider-request hook rewrote the credential beside a declared answer. The class is how the one seat that * turns a loop throw into a failure message (which strips the error) keeps the typed refusal for the run's terminal. */ export declare class PerModelAuthRefusal extends Error { readonly code: "config.invalid_argument"; } export declare function adjudicateDerivedRoute(args: { brain: Brain; model: Model; getApiKeyAndHeaders?: PerModelAuthSeat | undefined; }): Promise<JudgedRefusal | undefined>; /** * Whether two resolved models denote the SAME route for pre-flight purposes: identical wire id AND * identical entry ROUTE KEY. `Model.id` alone is NOT route identity — two catalog entries can * legitimately share a wire id (the same model served from two endpoints), and a same-id guard * would silently skip the pre-flight for exactly the split the pairing law exists to judge. */ export declare function sameRouteIdentity(a: Pick<Model, "id" | "baseUrl">, b: Pick<Model, "id" | "baseUrl">): boolean; /** The `route.fallback_to_primary` announcement — one shared shape for every derived-leg seat, so * a consumer can rely on `detail.{seat, from, to, cause}` regardless of which seat fell back. * * `sessionId` (#433, additive): the swap happened while resolving ONE run's seats, so the run is * what an operator correlates the line against ("which task ran on the fallback model"). The * AUDIENCE stays `"operator"` — the fix is a credential/catalog fix, and no end user can act on it; * attribution is a routing key, not an entitlement. Omitted when a caller has no session in hand, * never fabricated. * * `runId` (#499, additive): the SESSION is not the unit this line is about — the fallback happened * while resolving ONE INVOCATION's seats, and two runs of one session each falling back on the same * seat used to mint byte-identical notices ("did the same task fall back twice, or two tasks once * each?" was unanswerable). Same posture as `sessionId`: a correlation key, omitted when the caller * has none, never fabricated. */ export declare function fallbackToPrimaryNotice(args: { seat: string; from: string; to: string; refusal: JudgedRefusal; sessionId?: string; runId?: string; }): EngineNotice; /** * The TWIN of {@link fallbackToPrimaryNotice}, for a seat whose deployment declared NO fallback * (`RunnerDeps.autoMode.classifierFallback: "none"`): the route is refused, nothing was swapped, and the * seat's own calls are refused before dispatch (the model lane asks the same judgment) — which is what that declaration asked for. Same `detail` * keys as its twin MINUS `to`, because nothing moved and a `to` naming a model that was not used is the one * lie a consumer cannot detect; `action` is the discriminator, so the posture is read rather than inferred * from an absence. `primary` is named in the SENTENCE (what was declined) and not in the detail. */ export declare function unroutableSeatNotice(args: { seat: string; from: string; primary: string; refusal: JudgedRefusal; sessionId?: string; runId?: string; }): EngineNotice; /** * The third twin, for a seat with nothing to fall back TO and nothing worth keeping (the advisor tool: serving it with * the primary model would advise the agent with itself, and keeping it would refuse every call the model makes): the * pairing is broken, so the seat is DETACHED for this run — not mounted, no model swapped. Same `detail` keys as * {@link unroutableSeatNotice}; `action: "detached"` is the discriminator. */ export declare function seatDetachedNotice(args: { seat: string; from: string; refusal: JudgedRefusal; sessionId?: string; runId?: string; }): EngineNotice;