@sema-agent/core
Version:
Stateless, task-oriented AI agent core
1,030 lines • 53.1 kB
JavaScript
import { AsyncLocalStorage } from "node:async_hooks";
import { describeRejectedValue } from "../core/tool-search-setting.js";
import { createHash } from "node:crypto";
import { BrainError } from "./errors.js";
import { reportCredentialRefusal } from "./status-sink.js";
import { receiptRefusal, receiveOwnProperties } from "../core/own-property-receipt.js";
import { credentialHeaderValues, holdOwnCredentialValues, isBlankCredential, isCredentialHeaderName, isSchemedCredentialHeader } from "../core/secret-env.js";
import { deliverEngineNotice } from "../core/engine-notice.js";
import { uuidv7 } from "../engine/session/uuid.js";
import { CREDENTIAL_VOCABULARY, REDACTION_MARKS, isRedactionMark } from "@sema-agent/primitives";
import { PROTOCOL_PLAINTEXT_CREDENTIALS_CODE, crossesNetworkInClear } from "../core/protocol-http-auth.js";
import { resolvePlaintextOrigins, screenPlaintextOrigins } from "@sema-agent/primitives";
import { noteAdmittedSend } from "../core/plaintext-origins-watch.js";
import { readMemberOrUnreadable, thrownText, UNREADABLE } from "../core/thrown-value.js";
import { headerBagOnce } from "./request-params.js";
const REDACTED_VALUE = REDACTION_MARKS.bare;
const REDACTED_USERINFO = REDACTION_MARKS.userinfo;
function servableParse(raw) {
let u;
try {
u = new URL(raw);
}
catch {
return undefined;
}
return u.protocol === "http:" || u.protocol === "https:" ? u : undefined;
}
function composableParse(raw) {
let u;
try {
u = new URL(raw);
}
catch {
return undefined;
}
return u.host !== "" || u.pathname.startsWith("/") ? u : undefined;
}
export function routeKeyOf(url) {
if (url === undefined)
return "";
if (typeof url !== "string") {
throw new TypeError(`route pairing: baseUrl must be a string (got ${typeof url})`);
}
const raw = url.trim();
if (raw === "")
return "";
const u = servableParse(raw);
if (u === undefined)
return raw.replace(/\/+$/, "");
return canonicalRootSpelling(u);
}
function canonicalRootSpelling(u) {
return `${u.protocol}//${u.host}${u.pathname.replace(/\/+$/, "")}${u.search}`;
}
const QUERY_PURE_TEXT = /^[A-Za-z0-9._~[\]\-+,*!'()$ ]*$/;
const QUERY_DECODE_ROUNDS = 3;
function decodedToFixedPoint(text) {
let cur = text;
for (let round = 0; round < QUERY_DECODE_ROUNDS; round++) {
if (!cur.includes("%"))
return cur;
let next;
try {
next = decodeURIComponent(cur);
}
catch {
return cur;
}
if (next === cur)
return cur;
cur = next;
}
return cur;
}
function readQuery(search) {
if (search === "" || search === "?")
return { pure: true, segments: [] };
const segments = search.replace(/^\?/, "").split("&").map((raw) => {
const eq = raw.indexOf("=");
return eq === -1 ? { raw } : { raw, name: raw.slice(0, eq), value: raw.slice(eq + 1) };
});
const pure = segments.every((sg) => {
if (sg.name === undefined)
return QUERY_PURE_TEXT.test(decodedToFixedPoint(sg.raw));
const name = decodedToFixedPoint(sg.name);
return name !== "" && QUERY_PURE_TEXT.test(name) && QUERY_PURE_TEXT.test(decodedToFixedPoint(sg.value ?? ""));
});
return { pure, segments };
}
export function displayUrlOf(url) {
const key = routeKeyOf(url);
if (key === "")
return "";
const u = composableParse(key);
if (u === undefined) {
const cut = key.search(/[?#]/);
const head = cut === -1 ? key : key.slice(0, cut);
const at = head.lastIndexOf("@");
const shown = at === -1 ? head : `${REDACTED_USERINFO}@${head.slice(at + 1)}`;
return cut === -1 ? shown : `${shown}${key[cut]}${REDACTED_VALUE}`;
}
const read = readQuery(u.search);
const query = read.segments.length === 0
? ""
: !read.pure
? `?${REDACTED_VALUE}`
: `?${read.segments.map((sg) => (sg.raw === "" ? "" : sg.name === undefined ? REDACTED_VALUE : `${sg.name}=${REDACTED_VALUE}`)).join("&")}`;
return `${u.protocol}//${u.host}${u.pathname}${query}`.replace(/\/+$/, "");
}
function queryDifferenceNote(requestKey, declaredKey) {
if (displayUrlOf(requestKey) !== displayUrlOf(declaredKey))
return "";
const names = new Set();
const ua = composableParse(requestKey);
const ub = composableParse(declaredKey);
if (ua !== undefined && ub !== undefined) {
const ra = readQuery(ua.search);
const rb = readQuery(ub.search);
if (!ra.pure || !rb.pure) {
if (ra.segments.length !== rb.segments.length) {
return ` (same rendering — the query differs in segment count (${ra.segments.length} vs ${rb.segments.length}); a value here is not plain text, so this line withholds every name)`;
}
const at = ra.segments.flatMap((sg, i) => (sg.raw === rb.segments[i]?.raw ? [] : [i + 1]));
return at.length === 0
? ` (same rendering — the difference is in a part this line withholds or folds)`
: ` (same rendering — the query differs at segment${at.length > 1 ? "s" : ""} ${at.join(", ")} of ${ra.segments.length}; a value here is not plain text, so this line withholds every name)`;
}
const a = ra.segments;
const b = rb.segments;
const valuesOf = (segs, n) => segs.filter((sg) => sg.name === n).map((sg) => sg.value).join("\u0000");
for (const n of new Set([...a, ...b].flatMap((sg) => (sg.name === undefined ? [] : [sg.name])))) {
if (valuesOf(a, n) !== valuesOf(b, n))
names.add(n);
}
}
return names.size > 0
? ` (same rendering — the query values differ under: ${[...names].sort().join(", ")})`
: ` (same rendering — the difference is in a part this line withholds or folds)`;
}
export function assertServableRequestRoot(url, seat) {
return judgeRequestRoot(url, seat)?.trimmed;
}
function judgeRequestRoot(url, seat) {
if (typeof url !== "string" || url.trim() === "")
return undefined;
const trimmed = url.trim();
const parsed = URL.canParse(trimmed) ? new URL(trimmed) : undefined;
if (parsed === undefined || (parsed.protocol !== "http:" && parsed.protocol !== "https:")) {
const named = parsed === undefined ? "it did not parse as a URL" : displayUrlOf(trimmed);
throw new BrainError("invalid_request", `${seat} is not a servable request root (${named}) — it must be an ABSOLUTE http(s) URL. Another scheme, ` +
`or a spelling that is not a URL at all, fails at the transport in a shape indistinguishable from an ` +
`outage, so it would be retried for the whole backoff ladder instead of refused here.`);
}
if (parsed.username !== "" || parsed.password !== "") {
throw new BrainError("invalid_request", `${seat} carries credentials in its authority (${parsed.protocol}//${REDACTED_USERINFO}@${parsed.host}${parsed.pathname}) — ` +
`a request cannot be built from a URL with userinfo, so every call through this brain would fail: put the ` +
`credential on the apiKey knob or an auth header and leave the URL bare`);
}
if (parsed.hash !== "") {
throw new BrainError("invalid_request", `${seat} carries a URL fragment (${displayUrlOf(trimmed)}#…) — a fragment is never sent on the wire, so the ` +
`request would silently target the root's own path and the endpoint suffix would land inside the discarded ` +
`part: drop everything from the "#" on. A per-deployment QUERY is kept and rides every request ` +
`(a gateway's \`?api-version=…\` is supported); a fragment cannot be.`);
}
return { trimmed, parsed };
}
export function joinRequestUrl(root, suffix) {
if (typeof suffix !== "string" || /[?#]/.test(suffix)) {
throw new TypeError(`request URL: the endpoint suffix must be a path (got ${describeRejectedValue(suffix)}) — ` +
`a request's query belongs to its ROOT, which declares it once for every request`);
}
const judged = judgeRequestRoot(root, "the request root");
if (judged === undefined) {
throw new BrainError("invalid_request", `no request root is declared, so no request URL can be built for "${suffix}" — set config.baseUrl or Model.baseUrl`);
}
const { parsed } = judged;
const tail = suffix.replace(/^\/+/, "");
if (tail === "")
return canonicalRootSpelling(parsed);
const base = parsed.pathname.replace(/\/+$/, "");
const composed = `${parsed.protocol}//${parsed.host}${base}/${tail}${parsed.search}`;
const reread = servableParse(composed);
if (reread === undefined || !reread.pathname.startsWith(base === "" ? "/" : `${base}/`)) {
throw new TypeError(`request URL: the endpoint suffix ${JSON.stringify(suffix)} does not stay under the request root's path ` +
`(${base === "" ? "/" : base}) — a suffix names an endpoint of that root, and one that walks out of it would ` +
`send the request, and the credential paired with that root, somewhere the pairing law never judged`);
}
return composed;
}
const AUTHORITY_USERINFO = (() => {
const row = CREDENTIAL_VOCABULARY.values.find((r) => r.id === "url-userinfo");
if (row === undefined)
throw new Error('route-adjudicator: the credential vocabulary has no "url-userinfo" row');
return new RegExp(row.match.source, row.match.flags);
})();
export function stripUrlCredentials(text) {
return text.replace(AUTHORITY_USERINFO, (match, scheme, userinfo) => isRedactionMark(userinfo.slice(0, -1)) ? match : `${scheme}${REDACTED_USERINFO}@`);
}
export function resolveRequestRoot(modelBaseUrl, configBaseUrl, laneDefault = "") {
return resolveRequestRootOf(modelBaseUrl, configBaseUrl, laneDefault).root;
}
export function resolveRequestRootOf(modelBaseUrl, configBaseUrl, laneDefault = "") {
const entry = judgeRequestRoot(modelBaseUrl, "Model.baseUrl");
const declared = judgeRequestRoot(configBaseUrl, "config.baseUrl");
const origin = entry !== undefined ? "model" : declared !== undefined ? "deployment" : "lane-default";
const chosen = (entry ?? declared)?.parsed ?? servableParse(laneDefault.trim());
return { root: chosen === undefined ? laneDefault : canonicalRootSpelling(chosen), origin };
}
export function hasAuthCarrier(headers) {
if (!headers)
return false;
return Object.keys(headers).some((name) => isCredentialHeaderName(name));
}
function credentialHeadersCarried(headers) {
return Object.entries(headers ?? {}).some(([name, value]) => isCredentialHeaderName(name) && typeof value === "string" && !isBlankCredential(value));
}
function routeOriginOf(rootKey) {
if (rootKey === "")
return "";
const u = servableParse(rootKey);
return u === undefined ? rootKey : `${u.protocol}//${u.host}`;
}
export function requestOriginOf(root) {
if (typeof root !== "string")
throw new TypeError(`route pairing: a request root must be a string (got ${typeof root})`);
return routeOriginOf(routeKeyOf(root));
}
const CREDENTIAL_ORIGIN_BINDINGS_MAX = 16_384;
const CREDENTIAL_ORIGIN_TABLE = Symbol.for("sema.core.credentialOriginTable");
function credentialOriginTable() {
const held = Reflect.get(globalThis, CREDENTIAL_ORIGIN_TABLE);
if (held instanceof Map)
return held;
const table = new Map();
Reflect.set(globalThis, CREDENTIAL_ORIGIN_TABLE, table);
return table;
}
export function __resetCredentialOriginBindings() {
credentialOriginTable().clear();
}
const resolvedCredentialFacts = new WeakMap();
const HEADER_VALUE_ENDS = /^[\t\n\r ]+|[\t\n\r ]+$/g;
const AUTH_SCHEME_CREDENTIALS = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+[\t ]+(\S[\s\S]*)$/;
function perModelCredential(base, apiKey, bag, conflict) {
const headers = {};
for (const [name, value] of Object.entries(bag?.headers ?? {})) {
if (isCredentialHeaderName(name) && typeof value === "string")
headers[name] = value;
}
const credential = bag !== undefined && Object.values(headers).some((value) => !isBlankCredential(value)) ? { ...base, headersBorne: true, carrierBag: bag.from } : base;
const headerValues = Object.entries(headers).map(([name, value]) => {
const wire = value.replace(HEADER_VALUE_ENDS, "");
return isSchemedCredentialHeader(name) ? (AUTH_SCHEME_CREDENTIALS.exec(wire)?.[1] ?? wire) : wire;
});
const values = apiKey !== undefined ? [apiKey, ...headerValues] : headerValues;
const secrets = [...new Set(values.map((v) => v.replace(HEADER_VALUE_ENDS, "")).filter((v) => !isBlankCredential(v)))];
if (secrets.length === 0 && Object.keys(headers).length === 0 && conflict === undefined)
return credential;
const proof = Object.freeze(credential);
resolvedCredentialFacts.set(proof, Object.freeze({
identities: Object.freeze(secrets.map((s) => createHash("sha256").update(s).digest("base64url"))),
headers: Object.freeze(headers),
...(conflict !== undefined ? { keyHeaderConflict: Object.freeze(conflict) } : {}),
}));
return proof;
}
function withAnswerOrigin(credential, answerOrigin, answered) {
return withAnswerFact(credential, () => ({ answerOrigin, ...(answered ? { identitiesAnswered: true } : {}) }));
}
function withOriginUnsettled(credential, answered) {
return withAnswerFact(credential, (base) => ({ originUnsettled: Object.freeze({ own: answered ? base.identities : Object.freeze([]) }) }));
}
function withAnswerFact(credential, fact) {
const facts = resolvedCredentialFacts.get(credential);
const proof = facts !== undefined ? credential : Object.freeze({ ...credential });
const base = facts ?? { identities: Object.freeze([]), headers: Object.freeze({}) };
resolvedCredentialFacts.set(proof, Object.freeze({ ...base, ...fact(base) }));
return proof;
}
function boundElsewhere(identities, requestOrigin) {
const table = credentialOriginTable();
return identities.map((id) => table.get(id)).find((bound) => bound !== undefined && bound !== requestOrigin);
}
function boundHere(identities, requestOrigin) {
const table = credentialOriginTable();
return requestOrigin !== "" && identities.length > 0 && identities.every((id) => table.get(id) === requestOrigin);
}
function bindCredentialOrigin(identities, requestOrigin) {
const table = credentialOriginTable();
for (const id of identities) {
table.delete(id);
if (table.size >= CREDENTIAL_ORIGIN_BINDINGS_MAX) {
const oldest = table.keys().next();
if (oldest.done !== true)
table.delete(oldest.value);
}
table.set(id, requestOrigin);
}
}
function routeHalves(model, config) {
const entry = routeKeyOf(model.baseUrl);
const declared = routeKeyOf(config.baseUrl);
const deploymentRoot = declared || routeKeyOf(config.laneDefault);
return { entry, declared, deploymentRoot, request: entry || deploymentRoot };
}
export function keyCarriedBy(apiKey) {
return apiKey !== undefined && !isBlankCredential(apiKey) ? apiKey : undefined;
}
export function credentialCarrierOf(credential) {
return keyCarriedBy(credential.apiKey) !== undefined ? "apiKey" : credential.headersBorne === true ? "header" : undefined;
}
function credentialRequiredBy(config) {
const declared = config.requireCredential;
if (declared === undefined || declared === false)
return false;
if (declared === true)
return true;
throw new TypeError(`route pairing: requireCredential must be a boolean (got ${describeRejectedValue(declared)})`);
}
function keyHeaderConflict(apiKey, headers, keyHeader) {
if (apiKey === undefined || keyHeader === undefined || headers === undefined)
return undefined;
const fold = keyHeader.toLowerCase();
const written = Object.keys(headers).find((name) => name.toLowerCase() === fold);
return written === undefined ? undefined : { header: written, keyHeader };
}
export function resolveRouteCredential(input) {
const answerOrigin = input.optionsCredentialOrigin === undefined ? undefined : requestOriginOf(input.optionsCredentialOrigin);
const { credential, answered } = resolveCredentialSource(input);
if (answerOrigin !== undefined)
return withAnswerOrigin(credential, answerOrigin, answered);
return input.optionsCredentialOriginUnsettled === true ? withOriginUnsettled(credential, answered) : credential;
}
function resolveCredentialSource(input) {
const { optionsApiKey, optionsHeaders, modelHeaders, configApiKey, configHeaders, keyHeader } = input;
holdOwnCredentialValues(credentialHeaderValues(modelHeaders));
const answerHeadersBorne = hasAuthCarrier(optionsHeaders);
if (optionsApiKey !== undefined || answerHeadersBorne) {
if (optionsApiKey !== undefined && typeof optionsApiKey !== "string")
throw new TypeError(`route pairing: apiKey must be a string (got ${typeof optionsApiKey})`);
const key = keyCarriedBy(optionsApiKey);
return {
answered: true,
credential: perModelCredential({ source: "per-model", ...(key !== undefined ? { apiKey: key } : {}) }, key, answerHeadersBorne ? { from: "options", headers: optionsHeaders } : undefined, keyHeaderConflict(key, optionsHeaders, keyHeader)),
};
}
return { answered: false, credential: resolveFallbackSource(modelHeaders, configApiKey, configHeaders) };
}
function resolveFallbackSource(modelHeaders, configApiKey, configHeaders) {
if (hasAuthCarrier(modelHeaders))
return perModelCredential({ source: "per-model" }, undefined, { from: "model", headers: modelHeaders });
const configHeadersBorne = hasAuthCarrier(configHeaders);
if (configApiKey !== undefined || configHeadersBorne) {
if (configApiKey !== undefined && typeof configApiKey !== "string") {
throw new TypeError(`route pairing: apiKey must be a string (got ${typeof configApiKey})`);
}
const key = keyCarriedBy(configApiKey);
return {
source: "deployment-config",
...(key !== undefined ? { apiKey: key } : {}),
...(credentialHeadersCarried(configHeaders) ? { headersBorne: true, carrierBag: "config" } : {}),
};
}
return { source: "absent" };
}
export const KEYLESS_EXIT = "hand it none — 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";
function plaintextRefusal(model, credential, request, shown, keylessDoorOpen, origins) {
const parsed = request === "" ? undefined : servableParse(request);
if (parsed === undefined || !crossesNetworkInClear(parsed, origins))
return undefined;
const carrier = credentialCarrierOf(credential);
if (carrier === undefined)
return undefined;
const carried = carrier === "apiKey" ? "its key" : "its credential header";
const without = !keylessDoorOpen
? ""
: `; if the endpoint takes no credential, ${credential.source === "deployment-config" ? "construct the brain with no apiKey and no credential header" : KEYLESS_EXIT}`;
return {
ok: false,
code: PROTOCOL_PLAINTEXT_CREDENTIALS_CODE,
detail: {
modelId: model.id,
entryBaseUrl: shown.entry,
requestBaseUrl: shown.request,
configBaseUrl: shown.declared,
fixHint: `model "${model.id}" targets ${shown.request}, which is not https and not this machine — the request would carry ${carried} ` +
`across a network in the clear: declare the root as an https url, or serve the endpoint on this machine (localhost, ` +
`127.0.0.0/8, ::1)${unlistedFact(parsed, origins)}${without}`,
},
};
}
const NO_PLAINTEXT_ORIGINS_FACT = "this call carried no plaintextOrigins value";
function unlistedFact(root, origins) {
if (origins !== undefined)
return "";
const defaults = resolvePlaintextOrigins({});
if (!defaults.ok || crossesNetworkInClear(root, defaults.origins))
return "";
return `; ${NO_PLAINTEXT_ORIGINS_FACT} — a private-network root is admitted only by the list the call hands the brain (StreamOptions.plaintextOrigins; a wrapper that rebuilds the options hands it on)`;
}
function plaintextOriginsOf(config) {
const given = config.plaintextOrigins;
if (given === undefined)
return undefined;
const read = screenPlaintextOrigins(given);
if (!read.ok)
throw new TypeError(`route pairing: plaintextOrigins is not a list resolvePlaintextOrigins returns (${read.problems.join("; ")})`);
return read.origins;
}
function originMismatch(model, boundOrigin, requestOrigin, shown, boundBy, keylessDoorOpen) {
const boundShown = displayUrlOf(boundOrigin);
const requestOriginShown = displayUrlOf(requestOrigin);
const fixHint = boundBy === "generation"
? `model "${model.id}" targets ${shown.request} (origin ${requestOriginShown}) but the host's per-model auth answer names no ` +
`origin (credentialOrigin), the seat it came from was handed in before a model catalog swap, and the entry this request carries ` +
`is not, member for member, an entry of both the catalog the seat was handed in under and the one in force now, and the ` +
`answer's credential is not bound at ${requestOriginShown}: name credentialOrigin in the answer (the ` +
`origin of the entry its key was read for), or start the run again (a new run takes the seat under the catalog in force)`
: boundBy === "declaration"
? `model "${model.id}" targets ${shown.request} (origin ${requestOriginShown}) but the host's per-model auth answer named ` +
`${boundShown} as the origin it is handed out for (credentialOrigin), and a request carrying that answer goes there or ` +
`nowhere: if the answer's key was read for this entry, spell credentialOrigin as the entry spells its baseUrl (another ` +
`scheme, port, trailing dot or host name for the same machine is another origin); a seat that reads its key by name ` +
`names the origin of the entry the key was read for, never the baseUrl of the entry it is handed (echoing it declares nothing)`
: `model "${model.id}" targets ${shown.request} (origin ${requestOriginShown}) but its own credential is bound to ${boundShown}, ` +
`where it was first sent, where an earlier answer named it, or where the host rebound it — a credential ` +
`does not follow its entry to another host: change ` +
`the entry's credential reference in the same step as its baseUrl (a new credential is a new binding), or point the entry ` +
`back at ${boundShown}; ` +
`${keylessDoorOpen ? `if the endpoint takes no credential, ${KEYLESS_EXIT}; ` : ""}` +
`a provider that only moved domains and accepts the same credential there needs the host's ` +
`explicit rebind (rebindCredentialOrigin) where the host offers one, otherwise an engine restart`;
return {
ok: false,
code: "route.credential_origin_mismatch",
detail: {
modelId: model.id,
entryBaseUrl: shown.entry,
requestBaseUrl: shown.request,
configBaseUrl: shown.declared,
boundOrigin: boundShown,
requestOrigin: requestOriginShown,
boundBy,
fixHint,
},
};
}
export function adjudicateModelRoute(model, credential, config) {
const { entry, declared, deploymentRoot, request } = routeHalves(model, config);
const entryShown = displayUrlOf(entry);
const declaredShown = displayUrlOf(declared);
const requestShown = displayUrlOf(request);
const shown = { entry: entryShown, request: requestShown, declared: declaredShown };
const required = credentialRequiredBy(config);
const origins = plaintextOriginsOf(config);
const facts = resolvedCredentialFacts.get(credential);
const requestOrigin = routeOriginOf(request);
if (facts?.answerOrigin !== undefined && facts.answerOrigin !== requestOrigin)
return originMismatch(model, facts.answerOrigin, requestOrigin, shown, "declaration", !required);
const unsettled = facts?.originUnsettled;
const unsettledRefusal = () => unsettled === undefined || boundHere(unsettled.own, requestOrigin) ? undefined : originMismatch(model, "", requestOrigin, shown, "generation", !required);
const servable = (posture) => required && credentialCarrierOf(credential) === undefined ? requiredCredentialMissing(model, shown) : { ok: true, posture };
if (credential.source === "per-model") {
const conflict = facts?.keyHeaderConflict;
if (conflict !== undefined) {
return {
ok: false,
code: "route.credential_answer_conflict",
detail: {
modelId: model.id,
entryBaseUrl: entryShown,
requestBaseUrl: requestShown,
configBaseUrl: declaredShown,
fixHint: `model "${model.id}": the request carries both an apiKey and a "${conflict.header}" header, and this lane writes the apiKey in ` +
`"${conflict.keyHeader}" — one header cannot hold two credentials; hand the key as apiKey or as the header, not both`,
},
};
}
const plaintext = plaintextRefusal(model, credential, request, shown, !required, origins);
if (plaintext !== undefined)
return plaintext;
const identities = facts?.identities;
const boundOrigin = identities === undefined || requestOrigin === "" || facts?.identitiesAnswered === true ? undefined : boundElsewhere(identities, requestOrigin);
if (boundOrigin !== undefined)
return originMismatch(model, boundOrigin, requestOrigin, shown, "table", !required);
return unsettledRefusal() ?? servable("per-model");
}
const unsettledOther = unsettledRefusal();
if (unsettledOther !== undefined)
return unsettledOther;
if (credential.source === "deployment-config") {
const plaintext = plaintextRefusal(model, credential, request, shown, !required, origins);
if (plaintext !== undefined)
return plaintext;
if (request !== "" && request === deploymentRoot)
return servable("paired");
const pairedWith = declared !== ""
? `is paired with ${declaredShown}`
: deploymentRoot !== ""
? `is paired with this brain's default endpoint ${displayUrlOf(deploymentRoot)} (config.baseUrl is unset)`
: `names no root of its own (config.baseUrl is unset)`;
return {
ok: false,
code: "route.credential_mismatch",
detail: {
modelId: model.id,
entryBaseUrl: entryShown,
requestBaseUrl: requestShown,
configBaseUrl: declaredShown,
fixHint: `model "${model.id}" targets ${requestShown || "no root"} but the deployment credential ${pairedWith}` +
`${queryDifferenceNote(request, deploymentRoot)}: ` +
`give the model its own credential (a per-model key via getApiKeyAndHeaders, or an auth header on Model.headers), ` +
`or serve it through a brain whose config.baseUrl is the model's own root`,
},
};
}
if (declared === "" || entry === "" || request === declared)
return servable("keyless");
return {
ok: false,
code: "route.credential_missing",
detail: {
modelId: model.id,
entryBaseUrl: entryShown,
requestBaseUrl: requestShown,
configBaseUrl: declaredShown,
fixHint: `model "${model.id}" targets ${requestShown} but no credential is configured for that endpoint ` +
`(the deployment credential root is ${declaredShown})${queryDifferenceNote(request, declared)}: supply a per-model credential ` +
`(getApiKeyAndHeaders, or an auth header on Model.headers), or serve it through a brain constructed for that root`,
},
};
}
function requiredCredentialMissing(model, shown) {
return {
ok: false,
code: "route.credential_missing",
detail: {
modelId: model.id,
entryBaseUrl: shown.entry,
requestBaseUrl: shown.request,
configBaseUrl: shown.declared,
fixHint: `model "${model.id}" targets ${shown.request || "no root"} but the request carries no credential — no key and no credential header ` +
`with a value (a blank one is none) — and this brain is constructed to send no request without one (requireCredential): give ` +
`the model its own credential (a per-model key via getApiKeyAndHeaders, or an auth header on Model.headers), or, for a model on ` +
`the brain's own root, a deployment credential (config.apiKey or a credential header in config.headers)`,
},
};
}
export function routeRefusalText(verdict) {
return `${verdict.code}: ${verdict.detail.fixHint}`;
}
export function routeRefusalError(verdict) {
const named = (value) => (typeof value === "string" ? value : undefined);
if (verdict.code === "route.credential_origin_mismatch") {
const { modelId } = verdict.detail;
const bound = named(verdict.detail.boundOrigin);
const request = named(verdict.detail.requestOrigin);
const boundBy = boundByOf(verdict.detail.boundBy);
if (bound !== undefined && request !== undefined) {
reportCredentialRefusal({ code: verdict.code, modelId, boundOrigin: bound, requestOrigin: request, ...(boundBy !== undefined ? { boundBy } : {}) });
}
}
else if (verdict.code === "route.credential_mismatch") {
const { modelId } = verdict.detail;
const requestBaseUrl = named(verdict.detail.requestBaseUrl);
const configBaseUrl = named(verdict.detail.configBaseUrl);
reportCredentialRefusal({ code: verdict.code, modelId, ...(requestBaseUrl !== undefined ? { requestBaseUrl } : {}), ...(configBaseUrl !== undefined ? { configBaseUrl } : {}) });
}
return new BrainError("invalid_request", routeRefusalText(verdict));
}
export const ROUTE_JUDGMENT_FAILED = "route.judgment_failed";
const REFUSAL_ROOTS = ["entryBaseUrl", "requestBaseUrl", "configBaseUrl", "boundOrigin", "requestOrigin"];
const BOUND_BY_WORDS = { declaration: true, table: true, generation: true };
function boundByOf(value) {
return typeof value === "string" && Object.hasOwn(BOUND_BY_WORDS, value) ? value : undefined;
}
export function settleUnread(answer) {
if (typeof answer !== "object" || answer === null)
return false;
let then;
try {
then = answer.then;
}
catch {
return false;
}
if (typeof then !== "function")
return false;
Promise.resolve()
.then(() => Reflect.apply(then, answer, [() => undefined, () => undefined]))
.catch(() => undefined);
return true;
}
export const UNREADABLE_MODEL_ID = "<unreadable model id>";
export function sayableModelId(model) {
const id = readMemberOrUnreadable(model, "id");
return id === UNREADABLE ? UNREADABLE_MODEL_ID : id;
}
export function readRouteJudgment(ask, judged) {
let said;
const modelIdOf = () => (said ??= sayableModelId(judged));
const failed = (how) => ({ code: ROUTE_JUDGMENT_FAILED, fixHint: `the deployment Brain's route judgment for "${modelIdOf()}" ${how}` });
let answer;
try {
answer = ask();
}
catch (e) {
return failed(`threw before anything was sent: ${thrownText(e)}`);
}
if (answer === undefined)
return undefined;
try {
if (settleUnread(answer)) {
return failed("answered a Promise — a route judgment must answer synchronously (a verdict, or undefined for no judgment); nothing was sent");
}
const ok = typeof answer === "object" && answer !== null ? answer.ok : undefined;
if (ok === true)
return undefined;
if (ok !== false) {
return failed(`answered ${describeRejectedValue(answer)}${ok === undefined ? "" : ` whose ok is ${describeRejectedValue(ok)}`} — not a verdict (ok true or false) nor undefined; nothing was sent`);
}
const code = answer.code;
const detail = answer.detail;
const member = (key) => (typeof detail === "object" && detail !== null ? detail[key] : undefined);
const fixHint = member("fixHint");
if (typeof code !== "string" || typeof fixHint !== "string") {
return { ...(typeof code === "string" ? { code } : {}), ...(typeof fixHint === "string" ? { fixHint } : {}) };
}
const named = member("modelId");
const roots = Object.fromEntries(REFUSAL_ROOTS.flatMap((k) => {
const v = member(k);
return typeof v === "string" ? [[k, v]] : [];
}));
const boundBy = boundByOf(member("boundBy"));
const verdict = {
ok: false,
code,
detail: { modelId: typeof named === "string" ? named : modelIdOf(), ...roots, ...(boundBy !== undefined ? { boundBy } : {}), fixHint },
};
return { code, fixHint, verdict };
}
catch (e) {
return failed(`answered a verdict whose members would not read: ${thrownText(e)}`);
}
}
export function admitRouteRequest(model, credential, config) {
const judged = { id: model.id, baseUrl: model.baseUrl };
const { baseUrl, laneDefault, requireCredential, plaintextOrigins } = config;
const pairing = {
...(baseUrl !== undefined ? { baseUrl } : {}),
...(laneDefault !== undefined ? { laneDefault } : {}),
...(requireCredential !== undefined ? { requireCredential } : {}),
...(plaintextOrigins !== undefined ? { plaintextOrigins } : {}),
};
const judgeOrRefuse = () => {
const verdict = adjudicateModelRoute(judged, credential, pairing);
if (!verdict.ok)
throw routeRefusalError(verdict);
};
judgeOrRefuse();
const identities = credential.source === "per-model" ? resolvedCredentialFacts.get(credential)?.identities : undefined;
const request = routeHalves(judged, pairing).request;
const requestOrigin = routeOriginOf(request);
const root = plaintextOrigins !== undefined && request !== "" && credentialCarrierOf(credential) !== undefined ? servableParse(request) : undefined;
const told = root === undefined ? undefined : () => noteAdmittedSend(plaintextOrigins, root);
if (identities === undefined || identities.length === 0 || requestOrigin === "")
return told ?? (() => { });
return () => {
judgeOrRefuse();
bindCredentialOrigin(identities, requestOrigin);
told?.();
};
}
export const CREDENTIAL_REBIND_OUTCOMES = Object.freeze(["rebound", "unchanged", "withheld", "none"]);
function rebindRefusal(modelId, why) {
return Object.assign(new Error(`rebindCredentialOrigin: model "${modelId}" — ${why}; nothing was rebound`), { code: "config.invalid_argument" });
}
function rebindReadingOf(model, perModelAuth, configs) {
const judged = { id: model.id, baseUrl: model.baseUrl };
if (typeof judged.id !== "string")
throw new TypeError(`rebindCredentialOrigin: model.id must be a string (got ${typeof judged.id})`);
const modelHeaders = headerBagOnce(model.headers);
const answerHeaders = headerBagOnce(perModelAuth?.headers);
const answerKey = perModelAuth?.apiKey;
const origins = [];
let noRoot;
for (const config of configs) {
const { baseUrl, laneDefault } = config;
credentialRequiredBy(config);
for (const [name, half] of [["baseUrl", baseUrl], ["laneDefault", laneDefault]]) {
if (half !== undefined && typeof half !== "string")
throw new TypeError(`rebindCredentialOrigin: config.${name} must be a string (got ${half === null ? "null" : typeof half})`);
}
const pairing = { ...(baseUrl !== undefined ? { baseUrl } : {}), ...(laneDefault !== undefined ? { laneDefault } : {}) };
const request = routeHalves(judged, pairing).request;
let root;
try {
const chosen = resolveRequestRootOf(judged.baseUrl, pairing.baseUrl, pairing.laneDefault);
root = chosen.root;
if (chosen.origin === "lane-default" && root.trim() !== "")
judgeRequestRoot(pairing.laneDefault, "config.laneDefault");
}
catch (e) {
if (!(e instanceof BrainError))
throw e;
noRoot ??= e.message.replace(/^\[[a-z_]+\] /, "");
continue;
}
if (root.trim() === "") {
noRoot ??= "it targets no root (the entry's baseUrl and the brain's root are both unset)";
continue;
}
const origin = routeOriginOf(request);
if (!origins.includes(origin))
origins.push(origin);
}
return { id: judged.id, origins, ...(noRoot !== undefined ? { noRoot } : {}), bags: { answerKey, answerHeaders, modelHeaders } };
}
function rebindIdentitiesOf(bags) {
return resolvedCredentialFacts.get(resolveRouteCredential({ optionsApiKey: bags.answerKey, optionsHeaders: bags.answerHeaders, modelHeaders: bags.modelHeaders }))?.identities ?? [];
}
function rebindAccountOf(reading) {
const table = credentialOriginTable();
const before = reading.identities.map((id) => table.get(id));
const changed = before.some((bound) => bound !== reading.origin);
const previous = [...new Set(before.filter((bound) => bound !== undefined && bound !== reading.origin))].map(displayUrlOf);
return Object.freeze({ origin: displayUrlOf(reading.origin), previous: Object.freeze(previous), changed });
}
function rebindNoticeOf(id, account) {
const { previous } = account;
return {
code: "route.credential_rebound",
message: `The host rebound the credential of model "${id}" to ${account.origin}` +
`${previous.length > 0 ? ` (it was bound to ${previous.join(", ")})` : ""}: a request carrying it is sent to ${account.origin} only — ` +
`any other entry that carries the same credential and still targets another host is refused.`,
detail: { modelId: id, origin: account.origin, previous: [...previous], occurrenceId: uuidv7() },
};
}
function applyRebind(identities, origin, notice, onNotice) {
deliverEngineNotice(onNotice, notice);
bindCredentialOrigin(identities, origin);
}
export function rebindCredentialOrigin(first, second, config, onNotice) {
if (Array.isArray(first))
return rebindGeneration(first, second);
const reading = rebindReadingOf(first, second, [config]);
const origin = reading.origins[0];
if (origin === undefined)
throw rebindRefusal(reading.id, reading.noRoot ?? "it targets no root");
const identities = rebindIdentitiesOf(reading.bags);
if (identities.length === 0) {
throw rebindRefusal(reading.id, "neither the hook's answer nor the entry carries a secret of its own (no per-model credential, or the keyless door) — only a per-model credential is bound to an origin");
}
const account = rebindAccountOf({ identities, origin });
if (account.changed)
applyRebind(identities, origin, rebindNoticeOf(reading.id, account), onNotice);
return account;
}
function rebindGeneration(entries, onNotice) {
const count = entries.length;
const slots = [];
for (let i = 0; i < count; i++)
slots.push(entries[i]);
const handed = [];
slots.forEach((entry, i) => {
const objectOr = (value, what) => {
if (typeof value !== "object" || value === null)
throw new TypeError(`rebindCredentialOrigin: entries[${i}]${what} must be an object (got ${value === null ? "null" : typeof value})`);
};
objectOr(entry, "");
const { model, perModelAuth, configs } = entry;
objectOr(model, ".model");
if (perModelAuth !== undefined)
objectOr(perModelAuth, ".perModelAuth");
const n = Array.isArray(configs) ? configs.length : 0;
if (n === 0)
throw new TypeError(`rebindCredentialOrigin: entries[${i}].configs must be a non-empty array of pairing configs`);
const own = [];
for (let c = 0; c < n; c++) {
const config = configs[c];
objectOr(config, `.configs[${c}]`);
own.push(config);
}
handed.push({ model, perModelAuth, configs: own });
});
const readings = handed.map(({ model, perModelAuth, configs }) => rebindReadingOf(model, perModelAuth, configs));
const identitiesOf = readings.map((reading) => rebindIdentitiesOf(reading.bags));
const originsOf = new Map();
const holdersOf = new Map();
const firstNamed = new Map();
readings.forEach((reading, i) => {
for (const origin of reading.origins)
if (!firstNamed.has(origin))
firstNamed.set(origin, firstNamed.size);
for (const id of identitiesOf[i] ?? []) {
holdersOf.set(id, (holdersOf.get(id) ?? new Set()).add(i));
for (const origin of reading.origins)
originsOf.set(id, (originsOf.get(id) ?? new Set()).add(origin));
}
});
const judged = [];
readings.forEach((reading, i) => {
const identities = identitiesOf[i] ?? [];
if (identities.length === 0 || reading.origins.length === 0) {
judged.push({ alignment: alignmentOf(reading.id, "none") });
return;
}
const spread = [...new Set(identities.flatMap((id) => [...(originsOf.get(id) ?? [])]))].sort((a, b) => (firstNamed.get(a) ?? 0) - (firstNamed.get(b) ?? 0));
if (spread.length > 1) {
const contested = identities.filter((id) => (originsOf.get(id)?.size ?? 0) > 1);
const peers = [...new Set(contested.flatMap((id) => [...(holdersOf.get(id) ?? [])]))].filter((j) => j !== i).sort((a, b) => a - b);
judged.push({ alignment: Object.freeze({ ...alignmentOf(reading.id, "withheld"), origins: Object.freeze(spread.map(displayUrlOf)), peers: Object.freeze(peers) }) });
return;
}
const origin = spread[0];
const account = rebindAccountOf({ identities, origin });
const alignment = Object.freeze({ ...alignmentOf(reading.id, account.changed ? "rebound" : "unchanged"), origin: account.origin, previous: account.changed ? account.previous : Object.freeze([]) });
judged.push(account.changed ? { alignment, write: { identities, origin, notice: rebindNoticeOf(reading.id, account) } } : { alignment });
});
for (const { write } of judged)
if (write !== undefined)
applyRebind(write.identities, write.origin, write.notice, onNotice);
return Object.freeze(judged.map(({ alignment }) => alignment));
}
function alignmentOf(modelId, outcome) {
return Object.freeze({ modelId, outcome, previous: Object.freeze([]) });
}
export function applyRouteCredentialHeaders(merged, credential) {
if (credential.source === "per-model") {
for (const k of Object.keys(merged)) {
if (isCredentialHeaderName(k))
delete merged[k];
}
Object.assign(merged, resolvedCredentialFacts.get(credential)?.headers);
}
dropBlankCredentialHeaders(merged);
}
export function dropBlankCredentialHeaders(headers) {
for (const [k, value] of Object.entries(headers)) {
if (isCredentialHeaderName(k) && isBlankCredential(value))
delete headers[k];
}
}
export function brainConfigSnapshot(given, subject) {
const words = { subject, unit: "member", moment: "at construction" };
const received = receiveOwnProperties(given, words);
const headers = received.headers;
if (headers !== undefined) {
if (headers === null || typeof headers !== "object")
throw receiptRefusal(`${subject}.headers must be an object of header names to values`);
Object.defineProperty(received, "headers", { value: Object.freeze(receiveOwnProperties(headers, { ...words, subject: `${subject}.headers`, unit: "header" })), enumerable: true });
}
const snapshot = Object.freeze(received);
holdOwnCredentialValues([snapshot.apiKey, ...credentialHeaderValues(snapshot.headers)]);
return snapshot;
}
export function createBrainRouteJudge(config) {
const requireCredential = credentialRequiredBy(config);
return (model, perModelAuth) => {
const routed = { id: model.id, baseUrl: model.baseUrl };
const modelHeaders = headerBagOnce(model.headers);
const optionsHeaders = headerBagOnce(perModelAuth?.headers);
const credential = resolveRouteCredential({
optionsApiKey: perModelAuth?.apiKey,
optionsHeaders,
optionsCredentialOrigin: perModelAuth?.credentialOrigin,
optionsCredentialOriginUnsettled: perModelAuth?.credentialOriginUnsettled === true,
modelHeaders,
configApiKey: config.apiKey,
configHeaders: config.headers,
keyHeader: config.keyHeader,
});
const plaintextOrigins = perModelAuth?.plaintextOrigins;
return adjudicateModelRoute(routed, credential, { baseUrl: config.baseUrl, laneDefault: config.laneDefault, requireCredential, ...(plaintextOrigins !== undefined ? { plaintextOrigins } : {}) });
};
}
export const ROUTE_PAIRING_STATUSES = Object.freeze([
"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",
]);
const BROKEN_PAIRING_STATUS = {
"route.credential_mismatch": "broken:credential_mismatch",
"route.credential_missing": "broken:credential_missing",
"route.credential_origin_mismatch": "broken:credential_origin_mismatch",
"route.credential_answer_conflict": "broken:credential_answer_conflict",
"config.protocol_plaintext_credentials": "broken:protocol_plaintext_credentials",
"route.model_unavailable": "broken:model_unavailable",
};
export function routePairingStatus(brain, model, perModelAuth) {
const verdict = brain.adjudicateRoute?.(model, perModelAuth);
if (verdict === undefined)
return "unknown";
if (verdict.ok)
return `ok:${verdict.posture}`;
return BROKEN_PAIRING_STATUS[verdict.code];
}
export const DERIVED_ROUTE_PREFLIGHT_HOOK_BOUND_MS = 5_000;
export async function askPerModelAuth(seat, model, receiver) {
if (seat === undefined || seat === null)
return undefined;
const ask = { unsettled: false };
const answer = await SEAT_ASK.run(ask, () => Reflect.apply(seat, receiver, [model]));
if (answer === undefined || answer === null)
return undefined;
const { apiKey, headers: given, credentialOrigin } = answer;
const headers = given === undefined ? undefined : Object.freeze(headerBagOnce(given));
const carries = (typeof apiKey === "string" && keyCarriedBy(apiKey) !== undefined) || headers !== undefined;
const unsettled = credentialOrigin === undefined && carries && ask.unsettled;
return {
...(apiKey !== undefined ? { apiKey } : {}),
...(headers !== undefined ? { headers } : {}),
...(credentialOrigin !== undefined ? { credentialOrigin: servableCredentialOrigin(credentialOrigin, model.id) } : {}),
...(unsettled ? { credentialOriginUnsettled: true } : {}),
};
}
const SEAT_ASK = new AsyncLocalStorage();
export function seatAskMarker() {
const ask = SEAT_ASK.getStore();
return ask === undefined ? undefined : () => void (ask.unsettled = true);
}
export class PerModelAuthRefusal extends Error {
code = "config.invalid_argument";
}
function servableCredentialOrigin(value, modelId) {
const refused = (why) => new PerModelAuthRefusal(`per-model auth for model "${modelId}": credentialOrigin ${why} — the answer is refused and nothing is sent; name the ` +
`http(s) origin the credential is handed out for (an entry's baseUrl may be given as it is), or leave the member out`);
if (typeof value !== "string" || value.trim() === "")
throw refused(`must be a non-empty string (got ${describeRejectedValue(value)})`);
let judged;
try {
judged = judgeRequestRoot(value, "credentialOrigin");
}
catch (e) {
throw refused(`is not a servable origin (${e instanceof Error ? e.message.replace(/^\[[a-z_]+\] /, "") : "refused"})`);
}
if (judged === undefined)
throw refused("is empty");
return requestOriginOf(judged.trimmed);
}
export async function adjudicateDerivedRoute(args) {
const judge = args.brain.adjudicateRoute;
if (judge === undefined)
return undefined;
let auth;
if (args.getApiKeyAndHeaders !== undefined) {
let timer;
const ABSTAIN = Symbol("preflight-abstain");
try {
const bound = new Promise((resolve) => {
timer = setTimeout(() => resolve(ABSTAIN), DERIVED_ROUTE_PREFLIGHT_HOOK_BOUND_MS);
});
const hookResult = askPerModelAuth(args.getApiKeyAndHeaders, args.model, args);
hookResult.catch(() => { });
const raced = await Promise.race([hookResult, bound]);
if (raced === ABSTAIN)
return undefined;
auth = raced;
}
catch {
return undefined;
}
finally {
if (timer !== undefined)
clearTimeout(timer);
}
}
return readRouteJudgment(() => judge(args.model, auth), args.model);
}
export function sameRouteIdentity(a, b) {
return a.id === b.id && routeKeyOf(a.baseUrl) === routeKeyOf(b.baseUrl);
}
export function fallbackToPrimaryNotice(args) {
return {
code: "route.fallback_to_primary",
message: `derived model "${args.from}" (${args.seat}) is not routable (${causeSaid(args.refusal)}) — ` +
`falling back to the primary model "${args.to}". ${fixSaid(args.refusal)}`,
detail: {
seat: args.seat,
from: args.from,
to: args.to,
...refusalDetail(args.refusal),
...(args.sessionId !== undefined ? { sessionId: args.sessionId } : {}),
...(args.runId !== undefined ? { runId: args.runId } : {}),
},
};
}
const causeSaid = (refusal) => refusal.code ?? "the refusal stated no code";
const fixSaid = (refusal) => refusal.fixHint ?? "(the refusal gave no fix)";
const refusalDetail = (refusal) => ({
...(refusal.code !== undefined ? { cause: refusal.code } : {}),
...(refusal.fixHint !== undefined ? { fixHint: refusal.fixHint } : {}),
});
export function unroutableSeatNotice(args) {
return {
code: "route.classifier_unroutable",
message: `derived model "${args.from}" (${args.seat}) is not routable (${causeSaid(args.refusal)}) and this deployment declared no fallback — ` +
`the seat is kept and its calls are refused rather than served by "${args.primary}". ${fixSaid(args.refusal)}`,
detail: {
seat: args.seat,
from: args.from,
...refusalDetail(args.refusal),
action: "refused",
...(args.sessionId !== undefined ? { sessionId: args.sessionId } : {}),
...(args.runId !== undefined ? { runId: args.runId } : {}),
},
};
}
export function seatDetachedNotice(args) {
return {
code: "route.seat_detached",
message: `derived model "${args.from}" (${args.seat}) is not routable (${causeSaid(args.refusal)}) — the seat is detached for this run and nothing serves it in its place. ${fixSaid(args.refusal)}`,
detail: {
seat: args.seat,
from: args.from,
...refusalDetail(args.refusal),
action: "detached",
...(args.sessionId !== undefined ? { sessionId: args.sessionId } : {}),
...(args.runId !== undefined ? { runId: args.runId } : {}),
},
};
}