UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

641 lines (640 loc) • 28.9 kB
import { createHash } from "node:crypto"; import { types } from "node:util"; import { SdkErrorCode, SdkHttpError } from "@modelcontextprotocol/client"; import { canonicalize } from "./canonical-json.js"; import { readCredentialRef } from "@sema-agent/primitives"; import { noteAdmittedSend } from "./plaintext-origins-watch.js"; import { callerKey, callerText } from "./caller-text.js"; import { optionKeys, strayMembersOf } from "./own-property-receipt.js"; import { readMember, readOwnMembers } from "./thrown-value.js"; import { assertEndpointBound, httpTrimmed, resolveProtocolHttpHeaders } from "./protocol-http-auth.js"; import { askCarriedRevocation, mcpRevocationTarget, openingQuestion } from "./protocol-revocation.js"; import { credentialHeaderValues, entryLooksLikeCredential, holdOwnCredentialValues, namesASecret } from "./secret-env.js"; import { inlineUntrusted } from "./untrusted-text.js"; const PEER_SEAT_MEMBERS = Object.freeze(["answer", "hold", "release"]); const RECEIVED = new WeakMap(); export function receivePeerSeat(raw, subject) { if (raw === undefined) return undefined; const refuse = (problem) => Object.assign(new Error(`${subject} ${problem} — the peer seat is an object { answer(question, signal), hold(ref), release(ref) }`), { code: "config.invalid_argument" }); if (typeof raw === "function") throw refuse("is a function (the answer alone): put it under `answer` and add `hold` / `release`"); if (typeof raw !== "object" || raw === null || types.isProxy(raw)) throw refuse(raw === null ? "is null" : typeof raw !== "object" ? `is a ${typeof raw}` : "is a Proxy"); const read = Object.create(null); for (const name of PEER_SEAT_MEMBERS) { let member; try { member = Reflect.get(raw, name); } catch { throw refuse(`threw while its \`${name}\` was read`); } if (typeof member !== "function") throw refuse(`has no \`${name}\` function`); read[name] = member; } const held = RECEIVED.get(raw); if (held !== undefined && PEER_SEAT_MEMBERS.every((name) => held.members[name] === read[name])) return held.copy; const copy = Object.freeze({ answer: (question, signal) => Reflect.apply(read.answer, raw, [question, signal]), hold: (ref) => Reflect.apply(read.hold, raw, [ref]), release: (ref) => Reflect.apply(read.release, raw, [ref]), }); RECEIVED.set(raw, { members: read, copy }); return copy; } const SEAT_IDENTITIES = new WeakMap(); let seatsKeyed = 0; export function peerSeatIdentityOf(seat) { if (seat === undefined) return null; let id = SEAT_IDENTITIES.get(seat); if (id === undefined) SEAT_IDENTITIES.set(seat, (id = ++seatsKeyed)); return id; } export const PEER_ANSWER_LANES = Object.freeze({ http: "headers", a2a: "headers", stdio: "env" }); export const PEER_SEAT_WAIT_MS = 30_000; export const AUTHORIZATION_URL_MAX = 2048; export function authorizationUrlOf(raw) { if (typeof raw !== "string" || /[\u0000-\u001f\u007f]/.test(raw)) return undefined; let url; try { url = new URL(raw); } catch { return undefined; } if ((url.protocol !== "https:" && url.protocol !== "http:") || url.username !== "" || url.password !== "") return undefined; const kept = url.origin + `${url.pathname}${url.search}${url.hash}`.replace(/[[\]()<>`"'{}|^\\]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`); return kept.length <= AUTHORIZATION_URL_MAX ? kept : undefined; } export function bearerChallengeParams(header) { if (header === null) return undefined; const token = /[!#$%&'*+.^_`|~0-9A-Za-z-]+/y; const readToken = (at) => ((token.lastIndex = at), token.exec(header)?.[0]); let i = 0; let scheme; let params = new Map(); let bearer; let bareScheme = false; const space = () => void (i += /^[ \t]*/.exec(header.slice(i))[0].length); while (i < header.length) { space(); const name = readToken(i); if (name === undefined) { if (header[i] === ",") bareScheme = false; i++; continue; } i += name.length; space(); if (header[i] !== "=") { if (bareScheme) { bareScheme = false; continue; } if (scheme?.toLowerCase() === "bearer") bearer ??= params; scheme = name; params = new Map(); bareScheme = true; continue; } bareScheme = false; i++; space(); let value = ""; if (header[i] === '"') { for (i++; i < header.length && header[i] !== '"'; i++) value += header[i] === "\\" ? (header[++i] ?? "") : header[i]; i++; } else { value = readToken(i) ?? ""; i += value.length; } if (scheme !== undefined && !params.has(name.toLowerCase())) params.set(name.toLowerCase(), value); } if (scheme?.toLowerCase() === "bearer") bearer ??= params; return bearer; } async function bodyHead(res, max) { const reader = res.body?.getReader(); if (reader === undefined) return undefined; const decoder = new TextDecoder(); let text = ""; try { while (text.length < max) { const { done, value } = await reader.read(); if (done) break; text += decoder.decode(value, { stream: true }); } } catch { } finally { void reader.cancel().catch(() => undefined); } return text.slice(0, max); } export class PeerSeatFailure extends Error { reason; authorizeUrl; code; constructor(reason, peerLabel, problem, extra) { super(`the deployment's peer seat ${problem} for ${peerLabel} — the request was not sent`); this.name = "PeerSeatFailure"; this.reason = reason; this.authorizeUrl = extra?.authorizeUrl; this.code = extra?.code ?? (reason === "answer_invalid" ? "config.peer_answer_invalid" : undefined); } } export class PeerAuthorizationRefused extends SdkHttpError { reason; resourceMetadataUrl; authorizeUrl; renewed; constructor(reason, facts) { const lead = reason === "scope" ? "the endpoint refused the request for insufficient scope (HTTP 403)" : "the endpoint refused the request's authorization (HTTP 401)"; const text = facts.body !== undefined && facts.body !== "" ? `${lead}: ${facts.body}` : lead; super(reason === "scope" ? SdkErrorCode.ClientHttpForbidden : SdkErrorCode.ClientHttpAuthentication, text, { status: reason === "scope" ? 403 : 401 }); this.name = "PeerAuthorizationRefused"; this.reason = reason; this.resourceMetadataUrl = facts.resourceMetadataUrl; this.authorizeUrl = facts.authorizeUrl; this.renewed = facts.renewed === true; } } export const REFUSAL_BODY_MAX = 4096; export function refusedThenRenewed(err) { let at = err; for (let depth = 0; depth < 6 && at instanceof Error; depth++) { if (at instanceof PeerAuthorizationRefused) return at.renewed; at = at.cause; } return false; } const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/; const VALUE_LAW = Object.freeze({ headers: Object.freeze({ refuses: /[^\t\x20-\x7e\x80-\xff]/, holds: "a character an HTTP header value cannot carry" }), env: Object.freeze({ refuses: /[\r\n\0]|\p{Surrogate}/u, holds: "a line break, a NUL or a lone surrogate (encode it on one line, e.g. base64, or answer the path of a file that holds it)" }), }); const ANSWER_MEMBERS = Object.freeze({ carry: optionKeys()({ kind: 0, headers: 0, env: 0, expiresAt: 0 }), unauthorized: optionKeys()({ kind: 0, authorizeUrl: 0 }), }); const digestOf = (pieces) => { const rows = (m) => Object.entries(m ?? {}).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)); return createHash("sha256").update(JSON.stringify([rows(pieces.headers), rows(pieces.env)])).digest("hex"); }; export const NO_PIECES = Object.freeze({ digest: digestOf({}) }); function nameValues(raw, member) { const members = readOwnMembers(raw); if (members === undefined) return `its ${member} is not a record of names to strings`; const out = Object.create(null); const folded = new Map(); const names = Object.keys(members); const at = (i) => `#${i + 1} of ${names.length}`; for (const [i, name] of names.entries()) { const value = members[name]; if (typeof value !== "string") return `its ${member} member ${at(i)} (${callerText(name)}) is not a string`; if (!(member === "headers" ? HEADER_NAME : ENV_NAME).test(name)) return `its ${member} member ${at(i)} (${callerText(name)}) is not a ${member === "headers" ? "header" : "variable"} name`; if (VALUE_LAW[member].refuses.test(value)) return `its ${member} member ${at(i)} (${callerText(name)}) holds ${VALUE_LAW[member].holds}`; if (member === "headers") { const first = folded.get(name.toLowerCase()); if (first !== undefined) return `its headers members ${at(first)} and ${at(i)} are one header name (header names are case-insensitive)`; folded.set(name.toLowerCase(), i); } out[name] = value; } return Object.freeze(out); } export function readPeerAnswer(raw, lane) { try { if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return { problem: "answered something that is not an answer record" }; const record = raw; const memberOf = (name) => (Object.hasOwn(record, name) ? record[name] : undefined); const kind = memberOf("kind"); if (kind !== "carry" && kind !== "unauthorized") return { problem: `answered the kind ${callerText(kind)}, which is neither "carry" nor "unauthorized"` }; const extra = strayMembersOf(record, { subject: "the peer seat's answer", unit: "member", moment: "when the answer is read" }, ANSWER_MEMBERS[kind])?.names[0]; if (extra !== undefined) return { problem: `answered the member ${callerKey(extra)}, which a "${kind}" answer does not have — its members are ${ANSWER_MEMBERS[kind].map((m) => JSON.stringify(m)).join(", ")}` }; if (kind === "unauthorized") { const given = memberOf("authorizeUrl"); if (given === undefined) return { unauthorized: {} }; const url = authorizationUrlOf(given); if (url === undefined) return { problem: `answered an authorizeUrl that is not an absolute http(s) URL without user-info, of at most ${AUTHORIZATION_URL_MAX} characters, without control characters` }; return { unauthorized: { authorizeUrl: url } }; } const own = PEER_ANSWER_LANES[lane]; const other = own === "headers" ? "env" : "headers"; if (memberOf(other) !== undefined) return { problem: `answered ${other} for a ${lane} peer, which carries ${own} only` }; const expiresAt = memberOf("expiresAt"); if (expiresAt !== undefined && (typeof expiresAt !== "number" || !Number.isFinite(expiresAt) || expiresAt < 0)) return { problem: "answered an expiresAt that is not a finite, non-negative epoch-millisecond number" }; const carried = memberOf(own); const values = carried === undefined ? undefined : nameValues(carried, own); if (typeof values === "string") return { problem: `answered ${values}` }; const lanePieces = values === undefined ? {} : { [own]: values }; return { carry: Object.freeze({ ...lanePieces, ...(expiresAt !== undefined ? { expiresAt } : {}), digest: digestOf(lanePieces) }) }; } catch { return { problem: "answered a record whose members could not be read" }; } } function dataMember(holder, key) { if (typeof holder !== "object" || holder === null || types.isProxy(holder)) return undefined; const descriptor = Object.getOwnPropertyDescriptor(holder, key); return descriptor !== undefined && Object.hasOwn(descriptor, "value") ? descriptor.value : undefined; } function declaredReferences(declared) { const refs = []; for (const [list, path] of [[dataMember(declared, "mcp"), CREDENTIALS_MEMBER.mcp], [dataMember(declared, "a2a"), CREDENTIALS_MEMBER.a2a]]) { if (!Array.isArray(list) || types.isProxy(list)) continue; const length = dataMember(list, "length"); for (let index = 0; typeof length === "number" && index < length; index++) { let at = dataMember(list, String(index)); for (const key of path) at = dataMember(at, key); if (at === undefined || (typeof at === "object" && at !== null && types.isProxy(at))) continue; const read = readCredentialRef(at); if (read.ok) refs.push(read.ref); } } return refs; } export function holdPeerDeclarations(seat, declared, onFault) { let released = false; const holds = []; const fault = (member, ref) => onFault(new Error(`the deployment's peer seat threw from \`${member}\` for a "${ref.kind}" reference${member === "hold" ? " — the reference is not held" : ""}`)); const call = (member, ref) => { let returned; try { returned = seat[member](ref); } catch { fault(member, ref); return false; } if (typeof returned?.then !== "function") return true; return Promise.resolve(returned).then(() => true, () => (fault(member, ref), false)); }; if (seat !== undefined) { const seen = new Set(); for (const ref of declaredReferences(declared)) { const key = canonicalize(ref); if (seen.has(key)) continue; seen.add(key); const outcome = call("hold", ref); if (outcome === false) continue; if (outcome === true) { holds.push(() => void call("release", ref)); continue; } let releaseAsked = false; let fulfilled = false; void outcome.then((ok) => { fulfilled = ok; if (ok && releaseAsked) void call("release", ref); }); holds.push(() => { releaseAsked = true; if (fulfilled) void call("release", ref); }); } } return { release() { if (released) return; released = true; for (const releaseOne of holds.splice(0)) releaseOne(); }, }; } async function askBounded(seat, question, signal) { signal?.throwIfAborted(); const wait = new AbortController(); const timer = setTimeout(() => wait.abort(), PEER_SEAT_WAIT_MS); timer.unref(); const stop = signal === undefined ? wait.signal : AbortSignal.any([signal, wait.signal]); try { const stopped = new Promise((_, reject) => stop.addEventListener("abort", () => reject(stop.reason), { once: true })); stopped.catch(() => undefined); return { answer: await Promise.race([seat.answer(question, stop), stopped]) }; } catch (err) { if (signal?.aborted === true) throw signal.reason; return { failed: wait.signal.aborted ? "timed_out" : "threw" }; } finally { clearTimeout(timer); } } export class PeerCarrier { seat; identity; principal; lane; sent = []; credentials = []; expiresAt; renewed = false; asked = false; waiting; rejection; constructor(seat, identity, principal, lane, principalSent) { this.seat = seat; this.identity = identity; this.principal = principal; this.lane = lane; if (principalSent && principal !== undefined && principal !== "") this.sent.push(principal); } get label() { return this.identity.protocol === "mcp" ? `MCP server "${inlineUntrusted(this.identity.server, 120)}"` : `A2A peer "${inlineUntrusted(this.identity.peer, 120)}"`; } async next(signal, destination) { const waiting = this.waiting; if (waiting !== undefined) { this.waiting = undefined; this.last = waiting; return waiting; } const cause = this.asked ? "request" : "connect"; this.asked = true; this.last = await this.ask(cause, signal, destination); return this.last; } last; async rejected(carried, signal, destination) { this.rejection ??= this.ask("rejected", signal, destination) .then((pieces) => { this.waiting = pieces; this.renewed = pieces.digest !== carried.digest; return { renewed: this.renewed }; }, (err) => { this.renewed = false; if (!(err instanceof PeerSeatFailure && err.reason === "unauthorized") || err === signal?.reason) return { renewed: false, seatUnavailable: true }; return err.authorizeUrl !== undefined ? { renewed: false, authorizeUrl: err.authorizeUrl } : { renewed: false }; }) .finally(() => { this.rejection = undefined; }); return this.rejection; } expired(now = Date.now()) { return this.expiresAt !== undefined && now >= this.expiresAt; } async ask(cause, signal, destination) { const identity = this.identity; if (this.seat === undefined || (identity.protocol === "mcp" && identity.transport === "host")) return NO_PIECES; const peer = identity.protocol === "a2a" && destination !== undefined ? { ...identity, destination } : identity; const asked = await askBounded(this.seat, { peer, ...(this.principal !== undefined ? { principal: this.principal } : {}), cause }, signal); if ("failed" in asked) throw new PeerSeatFailure(asked.failed, this.label, asked.failed === "timed_out" ? `did not answer within ${PEER_SEAT_WAIT_MS} ms` : "threw"); this.holdAnswered(asked.answer); const read = readPeerAnswer(asked.answer, this.lane); if ("problem" in read) throw new PeerSeatFailure("answer_invalid", this.label, read.problem); if ("unauthorized" in read) throw new PeerSeatFailure("unauthorized", this.label, "answered that this principal is not authorized", read.unauthorized.authorizeUrl === undefined ? undefined : { authorizeUrl: read.unauthorized.authorizeUrl }); const pieces = read.carry; this.holdAnswered(pieces); for (const [name, value] of Object.entries(pieces.env ?? {})) if (entryLooksLikeCredential(name, value)) this.remember(value); if (this.lane === "stdio") this.expiresAt = pieces.expiresAt; for (const value of Object.values(pieces.headers ?? {})) this.remember(value); return pieces; } holdAnswered(answer) { let refused; for (const value of answeredCredentialValues(answer)) { try { holdOwnCredentialValues([value]); } catch (err) { refused ??= err instanceof Error ? err.message : "the value of a variable every child on this host is handed"; } if (namesASecret(value) && !this.credentials.includes(value)) this.credentials.push(value); } if (refused !== undefined) throw new PeerSeatFailure("answer_invalid", this.label, `answered a credential value the engine cannot withhold (${inlineUntrusted(refused, 240)})`); } remember(value) { if (value !== "" && !this.sent.includes(value)) this.sent.push(value); } } function answeredCredentialValues(answer) { const found = new Set(); const members = readOwnMembers(answer) ?? {}; for (const [name, value] of stringMembers(members["headers"])) { for (const sent of new Set([value, httpTrimmed(value)])) for (const credential of credentialHeaderValues({ [name]: sent })) found.add(credential); } for (const [name, value] of stringMembers(members["env"])) if (entryLooksLikeCredential(name, value)) found.add(value); return [...found]; } function stringMembers(record) { return Object.entries(readOwnMembers(record) ?? {}).filter((entry) => typeof entry[1] === "string"); } export function carriedHttpHeaders(protocol, carrier, pieces, principalHeader, principal) { try { return resolveProtocolHttpHeaders(protocol, { ...(pieces.headers !== undefined ? { headers: { ...pieces.headers } } : {}), ...(principalHeader !== undefined ? { principalHeader } : {}) }, principal); } catch (err) { if (pieces.headers === undefined) throw err; const message = err instanceof Error ? err.message : ""; const code = err?.code; throw new PeerSeatFailure("answer_invalid", carrier.label, `answered headers the engine cannot send (${inlineUntrusted(message, 240)})`, typeof code === "string" ? { code } : undefined); } } export function peerFetch(carrier, principalHeader, principal, bound) { const about = mcpRevocationTarget({ name: bound.server, fingerprint: bound.fingerprint }); const opened = openingQuestion(about); return async (url, init) => { const signal = init?.signal ?? undefined; const pieces = await carrier.next(signal); const own = carriedHttpHeaders("mcp", carrier, pieces, principalHeader, principal); const target = typeof url === "string" ? url : url instanceof URL ? url.href : url.url; assertEndpointBound("mcp", bound.server, target, bound.declared, own === undefined ? undefined : { ...own }, bound.plaintextOrigins); askCarriedRevocation(opened, about); const headers = new Headers(init?.headers); for (const [name, value] of Object.entries(own ?? {})) headers.set(name, value); if (own !== undefined && Object.keys(own).length > 0) noteAdmittedSend(bound.plaintextOrigins, new URL(target)); const res = await fetch(url, { ...init, headers, redirect: "manual" }); if (res.status !== 401 && res.status !== 403) return res; const challenge = bearerChallengeParams(res.headers.get("www-authenticate")); if (res.status === 403 && challenge?.get("error") !== "insufficient_scope") return unchallenged(res); const resourceMetadataUrl = authorizationUrlOf(challenge?.get("resource_metadata")); const body = init?.method === "POST" ? await bodyHead(res, REFUSAL_BODY_MAX) : void (await res.body?.cancel().catch(() => undefined)); const reask = res.status === 401 ? await carrier.rejected(pieces, signal) : undefined; throw new PeerAuthorizationRefused(res.status !== 401 ? "scope" : reask?.seatUnavailable === true ? "seat_unavailable" : "rejected", { ...(resourceMetadataUrl !== undefined ? { resourceMetadataUrl } : {}), ...(reask?.authorizeUrl !== undefined ? { authorizeUrl: reask.authorizeUrl } : {}), renewed: reask?.renewed === true, ...(body !== undefined ? { body } : {}), }); }; } function unchallenged(res) { if (!res.headers.has("www-authenticate")) return res; const headers = new Headers(res.headers); headers.delete("www-authenticate"); return new Response(res.body, { status: res.status, statusText: res.statusText, headers }); } export const RETIRED_VALUE_MEMBERS = Object.freeze({ mcp: Object.freeze([Object.freeze(["transport", "headers"]), Object.freeze(["transport", "env"])]), a2a: Object.freeze([Object.freeze(["headers"])]) }); export function retiredValueMember(copy, at) { for (const path of RETIRED_VALUE_MEMBERS[at]) { let holder = copy; for (const key of path.slice(0, -1)) holder = typeof holder === "object" && holder !== null && Object.hasOwn(holder, key) ? holder[key] : undefined; const last = path[path.length - 1]; if (typeof holder === "object" && holder !== null && Object.hasOwn(holder, last) && holder[last] !== undefined) return path; } return undefined; } export const CREDENTIALS_MEMBER = Object.freeze({ mcp: Object.freeze(["transport", "credentials"]), a2a: Object.freeze(["credentials"]) }); export function declaredCredentials(copy, at) { let value = copy; for (const key of CREDENTIALS_MEMBER[at]) value = typeof value === "object" && value !== null && Object.hasOwn(value, key) ? value[key] : undefined; if (value === undefined) return {}; const read = readCredentialRef(value); if (read.ok) return { ref: read.ref }; const p = read.problem; return { problem: `${p.reason}${"kind" in p && p.kind !== undefined ? ` (kind ${callerText(p.kind)})` : ""}${"field" in p ? ` at ${JSON.stringify(p.field)}` : ""}` }; } export function referencedVariables(ref) { return ref.kind === "env" ? [...Object.values(ref.headers ?? {}), ...Object.values(ref.env ?? {})] : []; } export function peerSeatMissing(subject, credentials, seat) { if (credentials === undefined || seat !== undefined) return undefined; return Object.assign(new Error(`${subject} declares a credential reference (kind "${credentials.kind}") but the deployment wires no peer seat (RunnerDeps.peerSeat) to answer it — not dialed`), { code: "config.peer_seat_missing" }); } export function mcpPeerTarget(spec, kind) { const t = spec.transport; if (kind === "host") return { protocol: "mcp", server: spec.name, transport: "host" }; const fingerprint = typeof spec.fingerprint === "string" ? { fingerprint: spec.fingerprint } : {}; const credentials = "credentials" in t && t.credentials !== undefined ? { credentials: t.credentials } : {}; if (kind === "stdio" && "command" in t) return { protocol: "mcp", server: spec.name, transport: "stdio", command: t.command, args: [...(t.args ?? [])], ...credentials, ...fingerprint }; return { protocol: "mcp", server: spec.name, transport: "http", url: "url" in t ? t.url : "", ...credentials, ...fingerprint }; } export function answeredUnauthorized(err) { let at = err; for (let depth = 0; depth < 6 && at instanceof Error; depth++) { if (at instanceof SdkHttpError && at.status === 401) return true; at = at.cause; } return false; } export function resendUndelivered(err) { const details = readMember(err, "details"); return typeof details === "object" && details !== null && readMember(details, "delivered") === "no"; } export function resendSeatLost(err) { const details = readMember(err, "details"); return typeof details === "object" && details !== null && readMember(details, "code") === "credential_unavailable"; } export class Reauthorized { error; seatLost; constructor(error, seatLost) { this.error = error; this.seatLost = seatLost; } } export async function sentOnceMore(attempt, mayResend) { const first = await attempt(false); if (!(first instanceof Reauthorized)) return first; if (!mayResend()) throw first.error; const again = await attempt(true).catch((err) => { if (!resendUndelivered(err)) throw err; throw first.seatLost !== undefined && resendSeatLost(err) ? first.seatLost() : first.error; }); if (again instanceof Reauthorized) throw again.error; return again; } const IN_FLIGHT = new WeakMap(); export function inFlight(client, run) { let calls = IN_FLIGHT.get(client); if (calls === undefined) IN_FLIGHT.set(client, (calls = new Set())); const call = run(); const held = call.then(() => undefined, () => undefined); calls.add(held); void held.then(() => calls.delete(held)); return call; } export async function settledInFlight(client) { await Promise.all([...(IN_FLIGHT.get(client) ?? [])]); } const CARRIERS = new WeakMap(); export function recordCarrier(client, carrier) { CARRIERS.set(client, carrier); } export function carrierOf(client) { return CARRIERS.get(client); }