UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

412 lines (411 loc) • 24.4 kB
import { types } from "node:util"; import { A2A_FINGERPRINT_MAX_CHARS, A2A_REGISTRATION_PROBLEM_GROUP, A2A_REGISTRATION_TEXT_MAX_CHARS, a2aRegistrationProblems } from "@sema-agent/primitives"; import { DECLARATION_ENTRY_WORDS, DECLARATION_PATH_RULES, MCP_TRANSPORT_KINDS, NO_DECLARATION_PATH_RULES, TOOL_AXIS_WORDS, declarationFaultOf, declarationPath, declarerWord, readToolAxes, receiveDeclaration, toolAxesRefusal, } from "./mcp-server-spec.js"; import { declarationSubject as entrySubject, declarerNameOf } from "./declaration-words.js"; import { callerKey, callerText } from "./caller-text.js"; import { isPlainRecord, receive } from "./mods/kernel/receive.js"; import { TOOL_FACE_WORDS, readToolFaces } from "./tool-face-reader.js"; import { judgeCallerMeta, judgeSessionMetaKey } from "./mcp-call-meta.js"; import { isMcpFaceWord } from "./mounted-mcp.js"; import { CONFIG_RECEIPT_MODE, optionKeys, strayMembersOf } from "./own-property-receipt.js"; import { isToolContentOrigin, TOOL_CONTENT_ORIGINS } from "./memory-engine/content-origin.js"; import { inlineUntrusted } from "./untrusted-text.js"; import { TOOL_WIRE_NAME_MAX_CHARS } from "./tool-face.js"; import { assertNoRetiredToolPolicyKeys } from "./retired-keys.js"; import { CREDENTIALS_MEMBER, RETIRED_VALUE_MEMBERS, declaredCredentials, peerSeatMissing, referencedVariables, retiredValueMember } from "./peer-seat.js"; import { holdPeerHeldNames } from "./secret-env.js"; import { a2aRespondProblem } from "./peer-task-lane.js"; import { enterConfigDoor, resolveSeatValue } from "./config-refusal-input.js"; export const LOCKED_KEY_REGISTRY = { mcp: { specFields: ["mcp"] }, a2a: { specFields: ["a2a"] }, toolPolicy: { specFields: ["toolPolicy", "basePolicyForResumeEdit"] }, compliancePosture: { specFields: [] }, retentionPolicy: { specFields: [] }, }; function codedError(code, message) { const e = new Error(message); e.code = code; return e; } export function resolveLockedKeys(config) { if (config === undefined) return new Set(); const keys = new Set(); const listed = declaredLockKeys(config); for (let index = 0; index < listed.length; index++) { const key = listed[index]; if (!Object.hasOwn(LOCKED_KEY_REGISTRY, key)) { throw lockDeclarationRefusal(`RunnerDeps.lockedConfig.keys[${index}]`, `is ${callerText(key)}, which is not a member of the locked-key registry (${Object.keys(LOCKED_KEY_REGISTRY).join(", ")})`); } keys.add(key); } return keys; } function declaredLockKeys(config) { const received = receiveDeclaration(config, NO_DECLARATION_PATH_RULES); if (!received.ok) throw lockDeclarationRefusal(declarationPath(received.fault.path, LOCK_DECLARATION_WORDS, "RunnerDeps.lockedConfig"), `cannot be read: ${received.fault.problem}`); const copy = received.value; if (!isPlainRecord(copy)) throw lockDeclarationRefusal("RunnerDeps.lockedConfig", `is ${callerText(copy)}, not an object with a \`keys\` list`); const keys = Object.hasOwn(copy, "keys") ? copy["keys"] : undefined; if (!Array.isArray(keys)) throw lockDeclarationRefusal("RunnerDeps.lockedConfig.keys", `is ${callerText(keys)}, not a list of locked keys`); return keys; } function lockDeclarationRefusal(member, problem) { return codedError("config.locked_registry", `${member} ${problem}. A lock that does not parse must not half-arm — fix the deployment's lock declaration.`); } export function snapshotMcpEntries(entries) { return entries.map((entry) => snapshotDeclaredEntry(entry, "mcp")); } const LOCK_DECLARATION_WORDS = new Set(["keys"]); const ENTRY_PATH_WORDS = new Set([...DECLARATION_ENTRY_WORDS, ...TOOL_AXIS_WORDS, ...TOOL_FACE_WORDS, ...Object.values(RETIRED_VALUE_MEMBERS).flat(2)]); function unreadableDeclaration(at, declarer, member, problem) { const refusal = codedError("config.invalid_argument", `${entrySubject(at, declarer)} declares ${inlineUntrusted(member, 80)} the engine cannot read: ${problem}. A declaration the engine cannot read is refused ` + `rather than partly applied — what the caller wrote and what the engine runs on would otherwise differ without anyone being told.`); if (declarer !== undefined) Object.defineProperty(refusal, "declarer", { value: declarer, enumerable: true, writable: false, configurable: false }); return refusal; } function ownDataString(holder, key) { const slot = Object.getOwnPropertyDescriptor(holder, key); const value = slot !== undefined && Object.hasOwn(slot, "value") ? slot.value : undefined; return typeof value === "string" ? value : undefined; } export function refusedDeclarer(refusal) { return typeof refusal === "object" && refusal !== null && !types.isProxy(refusal) ? ownDataString(refusal, "declarer") : undefined; } function capturedName(entry) { return typeof entry === "object" && entry !== null && !types.isProxy(entry) ? ownDataString(entry, "name") : undefined; } function entryFaultRefusal(at, declarer, path, problem) { return unreadableDeclaration(at, declarer, path.length === 0 ? "an entry" : declarationPath(path, ENTRY_PATH_WORDS), problem); } export function snapshotDeclaredEntry(entry, at) { const declared = entry; const declarer = capturedName(declared); const received = receiveDeclaration(declared, DECLARATION_PATH_RULES[at]); if (!received.ok) throw entryFaultRefusal(at, declarer, received.fault.path, received.fault.problem); if (!isPlainRecord(received.value)) throw unreadableDeclaration(at, declarer, "an entry", `it is ${callerText(received.value)}, not an object`); const retired = retiredValueMember(received.value, at); if (retired !== undefined) { throw declarationRefusal("config.credential_in_declaration", at, declarer, `declares ${retired.join(".")}, a member that carried values and is retired: a declaration names the peer and at most one opaque reference (${CREDENTIALS_MEMBER[at].join(".")}); the pieces a request carries are answered per send by the deployment's peer seat (RunnerDeps.peerSeat). The value is not repeated here.`); } const credentials = declaredCredentials(received.value, at); if ("problem" in credentials) { throw declarationRefusal("config.credential_ref_invalid", at, declarer, `declares ${CREDENTIALS_MEMBER[at].join(".")} that is not a credential reference (${inlineUntrusted(credentials.problem, 160)}).`); } if (credentials.ref !== undefined) holdPeerHeldNames(referencedVariables(credentials.ref), entrySubject(at, declarer)); return received.value; } function declarationRefusal(code, at, declarer, sentence) { const refusal = codedError(code, `${entrySubject(at, declarer)} ${sentence}`); if (declarer !== undefined) Object.defineProperty(refusal, "declarer", { value: declarer, enumerable: true, writable: false, configurable: false }); return refusal; } function assertPeerSeatFor(entries, at, seat) { for (const entry of entries ?? []) { const read = declaredCredentials(entry, at); const missing = "ref" in read ? peerSeatMissing(`${declarerWord(at)} ${declarerNameOf(entry.name)}`, read.ref, seat) : undefined; if (missing !== undefined) throw missing; } } export function judgeEntryToolAxes(copy, at) { const { toolAxes: declaredAxes, ...rest } = copy; const axes = readToolAxes(declaredAxes, at); if (!axes.ok) return { ok: false, error: toolAxesRefusal(at, declarerNameOf(copy.name), axes.problem, at === "a2a" && copy.boundary === "inside") }; if (axes.toolAxes !== undefined) { for (const perTool of Object.values(axes.toolAxes)) Object.freeze(perTool); Object.freeze(axes.toolAxes); } return { ok: true, entry: Object.freeze((axes.toolAxes === undefined ? rest : { ...rest, toolAxes: axes.toolAxes })) }; } export function judgeA2aEntryRegistration(copy) { const refuse = (member, problem) => ({ ok: false, error: codedError("config.invalid_argument", `${declarerWord("a2a")} ${declarerNameOf(copy.name)} declares ${member} ${problem}; the declaration is refused rather than read as if the member were absent.`), }); const first = a2aRegistrationProblems(copy).find((p) => A2A_REGISTRATION_PROBLEM_GROUP[p] === "member"); if (first === undefined) { const respond = a2aRespondProblem(copy.respond); return respond === undefined ? { ok: true } : refuse("respond", respond); } if (first === "boundary_unreadable") return refuse("boundary", `${callerText(copy.boundary)}, which is not "inside" or "outside"`); const row = A2A_TEXT_MEMBER_OF[first]; if (row === undefined) return refuse("a member", `the registration check cannot read (${first})`); const value = copy[row.member]; return refuse(row.member, typeof value !== "string" ? `that is ${callerText(value)}, not a string` : value.length > row.max ? `of ${value.length} characters (at most ${row.max})` : value.length === 0 ? "that is empty" : "that holds no visible character (only white space, control or format characters, or characters that do not show)"); } const A2A_TEXT_MEMBER_OF = { fingerprint_unreadable: { member: "fingerprint", max: A2A_FINGERPRINT_MAX_CHARS }, display_name_unreadable: { member: "displayName", max: A2A_REGISTRATION_TEXT_MAX_CHARS }, owner_team_unreadable: { member: "ownerTeam", max: A2A_REGISTRATION_TEXT_MAX_CHARS }, }; function deepFrozen(value) { if (typeof value === "object" && value !== null && !Object.isFrozen(value)) { Object.freeze(value); for (const member of Object.values(value)) deepFrozen(member); } return value; } const FACES_PROBLEM_MAX = 400; function toolFacesRefusal(name, problem) { return codedError("config.tool_face_invalid", `${declarerWord("mcp")} ${name} declares toolFaces the engine cannot read: ${inlineUntrusted(problem, FACES_PROBLEM_MAX)}. A per-tool face declaration is the deployment's own ` + `narrowing (which argument names a tool's path, how a write is confined, which approval card and rule vocabulary the tool wears), so it is refused ` + `rather than partly applied — a member dropped or a word defaulted would mount the tool without the protection its operator declared.`); } export function judgeEntryToolFaces(copy) { const { toolFaces: declared, ...rest } = copy; if (declared === undefined) return { ok: true, entry: copy }; const faces = readToolFaces(declared); if (!faces.ok) return { ok: false, error: toolFacesRefusal(declarerNameOf(copy.name), faces.problem) }; return { ok: true, entry: Object.freeze((faces.faces === undefined ? rest : { ...rest, toolFaces: deepFrozen(faces.faces) })) }; } export function judgeEntrySessionMetaKey(copy) { const read = judgeSessionMetaKey(copy.sessionMetaKey); if (!("problem" in read)) return { ok: true, entry: copy }; return { ok: false, error: codedError("config.invalid_argument", `${declarerWord("mcp")} ${declarerNameOf(copy.name)} declares ${inlineUntrusted(read.problem, 200)}. The key decides where the leg's session id rides on this server's requests, so it is refused rather than dropped or defaulted — a connector keyed on a session it never receives would share one state across every session.`) }; } export function judgeEntryCallerMeta(copy) { const read = judgeCallerMeta(copy.callerMeta); if (!("problem" in read)) return { ok: true, entry: copy }; return { ok: false, error: codedError("config.invalid_argument", `${declarerWord("mcp")} ${declarerNameOf(copy.name)} declares ${inlineUntrusted(read.problem, 200)}. The value decides whether this server is told which task, run and delegation tree each request comes from, so it is refused rather than read as either — a server keyed on a caller it never receives would fold every caller into one.`) }; } export function judgeEntryReservedKeys(copy) { const reservedKey = (declared) => (isPlainRecord(declared) ? Object.keys(declared).find(isMcpFaceWord) : undefined); const problem = (word) => `its key "${word}" is a reserved allowTools face word (a kind of read the engine makes of the server), never a tool name — no tool is ever mounted under it`; const axesWord = reservedKey(copy.toolAxes); if (axesWord !== undefined) return { ok: false, error: toolAxesRefusal("mcp", declarerNameOf(copy.name), problem(axesWord)) }; const facesWord = reservedKey(copy.toolFaces); if (facesWord !== undefined) return { ok: false, error: toolFacesRefusal(declarerNameOf(copy.name), problem(facesWord)) }; return { ok: true, entry: copy }; } export function judgeEntryTransportKind(copy) { const transport = copy.transport; if (!isPlainRecord(transport)) return { ok: true, entry: copy }; const kind = transport["kind"]; if (MCP_TRANSPORT_KINDS.some((word) => word === kind)) return { ok: true, entry: copy }; return { ok: false, error: codedError("config.invalid_argument", `${declarerWord("mcp")} ${declarerNameOf(copy.name)} declares a transport whose kind is ${callerText(kind)}, which is not one of ${MCP_TRANSPORT_KINDS.map((word) => `"${word}"`).join(" | ")} (spelled exactly). ` + `The kind decides how the engine reaches the server, so a word it cannot read is refused rather than dialed as one of the others — a server mounted over a transport nobody declared.`), }; } const HOST_TRANSPORT_KEYS = optionKeys()({ kind: 0 }); export function judgeEntryHostTransport(copy) { const transport = copy.transport; if (!isPlainRecord(transport) || transport["kind"] !== "host") return { ok: true, entry: copy }; const stray = strayMembersOf(transport, { subject: "a host-supplied transport", unit: "member", moment: "when the entry is read" }, HOST_TRANSPORT_KEYS)?.names[0]; const problem = stray !== undefined ? `a host-supplied transport with the member ${callerKey(stray)}: a host transport carries its kind alone — the host seat carries what each request needs, so a member here would read as in force while nothing carries it` : copy.elicitation === true ? `elicitation on a host-supplied transport: the server behind a host's pipe is the host's own code, so a question it has for the user goes through the host's own interface — the engine advertises no elicitation for it` : undefined; return problem === undefined ? { ok: true, entry: copy } : { ok: false, error: codedError("config.invalid_argument", `${declarerWord("mcp")} ${declarerNameOf(copy.name)} declares ${problem}.`) }; } export function judgeMcpEntryCopy(copy) { const axes = judgeEntryToolAxes(copy, "mcp"); const faces = axes.ok ? judgeEntryToolFaces(axes.entry) : axes; const reserved = faces.ok ? judgeEntryReservedKeys(faces.entry) : faces; const metaKey = reserved.ok ? judgeEntrySessionMetaKey(reserved.entry) : reserved; const callerMeta = metaKey.ok ? judgeEntryCallerMeta(metaKey.entry) : metaKey; const kind = callerMeta.ok ? judgeEntryTransportKind(callerMeta.entry) : callerMeta; return kind.ok ? judgeEntryHostTransport(kind.entry) : kind; } function judgeEntryContentOrigin(copy) { const declared = copy.contentOrigin; if (declared === undefined || isToolContentOrigin(declared)) return { ok: true, entry: copy }; return { ok: false, error: codedError("config.mcp_content_class", `MCP server ${declarerNameOf(copy.name)} declares contentOrigin ` + `${callerText(declared)}, which is not one of ` + `${TOOL_CONTENT_ORIGINS.map((v) => `"${v}"`).join(" | ")}. The declaration decides whether this server's tools ` + `mark the session's memory externally exposed — a value this engine cannot read is refused at the door rather ` + `than folded to a class, because folding it would let a deployment believe a declaration is in force while every ` + `call keeps writing a one-way durable mark.`), }; } export function judgeEntryNameBound(copy) { if (copy.name.length <= TOOL_WIRE_NAME_MAX_CHARS) return { ok: true, entry: copy }; return { ok: false, error: codedError("config.tool_name_too_long", `MCP server name ${JSON.stringify(copy.name.slice(0, 40) + "…")} is ${copy.name.length} characters; a peer rides every roster row of its tools and the roster's bound on a name is ${TOOL_WIRE_NAME_MAX_CHARS}.`), }; } function admitTaskMcpCopy(copy) { const origin = judgeEntryContentOrigin(copy); return origin.ok ? judgeMcpEntryCopy(origin.entry) : origin; } function admitTaskA2aCopy(copy) { const registration = judgeA2aEntryRegistration(copy); return registration.ok ? judgeEntryToolAxes(copy, "a2a") : registration; } function judgeAsTheDoorTakes(entry, at, admit) { const handed = entry; if (types.isProxy(handed) || !isPlainRecord(handed)) { return { ok: false, error: codedError("config.invalid_argument", `${declarerWord(at)} declaration must be a plain object of the ${at === "mcp" ? "server" : "peer"}'s members (it is ${typeof handed === "object" && handed !== null && !Array.isArray(handed) ? "an object that is not a plain record: a Proxy, or one that carries a prototype" : callerText(handed)}) — an entry the engine cannot read as one is refused rather than judged ok or let throw.`) }; } let copy; try { copy = snapshotDeclaredEntry(entry, at); } catch (refused) { const code = refused instanceof Error ? refused.code : undefined; return { ok: false, error: typeof code === "string" ? refused : codedError("config.invalid_argument", `${declarerWord(at)} declaration could not be read — an entry the engine cannot read as plain data is refused rather than judged ok or let throw.`) }; } return admit(copy); } export function judgeMcpEntryDeclarations(entry) { const admitted = judgeAsTheDoorTakes(entry, "mcp", admitTaskMcpCopy); return admitted.ok ? judgeEntryNameBound(admitted.entry) : admitted; } export function judgeA2aEntryDeclarations(entry) { return judgeAsTheDoorTakes(entry, "a2a", admitTaskA2aCopy); } function declaredEntriesOf(declared, at, where) { const field = at; const received = receive(declared, CONFIG_RECEIPT_MODE); let problem; if (received.ok) { const list = received.value; if (Array.isArray(list) && list !== declared) return Array.from({ length: list.length }, (_, index) => list[index]); problem = typeof list === "object" && list !== null ? "it is not an array" : `it is ${callerText(list)}`; } else { const fault = declarationFaultOf(received.fault); if (fault.path.length > 0) throw unreadableDeclaration(at, undefined, "an entry", fault.problem); problem = fault.problem; } throw codedError("config.invalid_argument", `${where ?? `TaskSpec.${field}`} must be a readable array of ${declarerWord(at)} declarations; ${problem}. A list the engine cannot read ` + `is refused rather than read as "no entries" — the declared ${declarerWord(at)}s would otherwise be dropped without anyone being told.`); } function validatedA2aEntries(entries) { if (entries.length === 0) return undefined; return entries.map((entry) => validatedA2aEntry(received(entry))); } function validatedA2aEntry(copy) { const judged = admitTaskA2aCopy(copy); if (!judged.ok) throw judged.error; return judged.entry; } export function snapshotAndValidateA2aEntries(declared, where) { return declaredEntriesOf(declared, "a2a", where).map((entry) => validatedA2aEntry(snapshotDeclaredEntry(entry, "a2a"))); } export const receiving = (read) => { try { return { read: read() }; } catch (refused) { return { refused }; } }; export const received = (r) => { if ("refused" in r) throw r.refused; return r.read; }; export function receivePeerDeclarations(spec, deps) { const locks = receiving(() => resolveLockedKeys(deps.lockedConfig)); if ("refused" in locks) return { locks }; const list = (at) => { if (locks.read.has(at)) return undefined; const declared = receiving(() => spec[at]); if ("refused" in declared) return declared; if (declared.read === undefined) return undefined; return receiving(() => declaredEntriesOf(declared.read, at).map((entry) => receiving(() => snapshotDeclaredEntry(entry, at)))); }; const mcp = list("mcp"); const a2a = list("a2a"); return { locks, ...(mcp !== undefined ? { mcp } : {}), ...(a2a !== undefined ? { a2a } : {}) }; } export function receivedDeclarations(receipt) { const copies = (r) => r === undefined || "refused" in r ? undefined : r.read.flatMap((entry) => ("read" in entry ? [entry.read] : [])); const mcp = copies(receipt.mcp); const a2a = copies(receipt.a2a); return { ...(mcp !== undefined ? { mcp } : {}), ...(a2a !== undefined ? { a2a } : {}) }; } export function snapshotAndValidateMcpEntries(declared, where) { return validatedMcpEntries(snapshotMcpEntries(declaredEntriesOf(declared, "mcp", where))); } function validatedMcpEntries(copies) { return copies.map((copy) => { const judged = admitTaskMcpCopy(copy); if (!judged.ok) throw judged.error; return judged.entry; }); } export function preflightLockedConfig(spec, deps, receipt) { const peers = receipt ?? receivePeerDeclarations(spec, { lockedConfig: deps.lockedConfig }); const lockedKeys = enterConfigDoor("deps", () => received(peers.locks)); enterConfigDoor("taskConfig", () => { for (const key of lockedKeys) { for (const field of LOCKED_KEY_REGISTRY[key].specFields) { if (spec[field] !== undefined) { throw codedError("config.locked_key", `TaskSpec.${field} is administratively locked by this deployment (locked key "${key}") — ` + `the task-supplied value is refused wholesale (locks are config-time; there is no request-time ` + `unlock). Remove the field from the task, or change the deployment's lock configuration.`); } } } }); const toolPolicyLocked = lockedKeys.has("toolPolicy"); const task = toolPolicyLocked ? {} : { toolPolicy: spec.toolPolicy, basePolicyForResumeEdit: spec.basePolicyForResumeEdit }; const seats = callerPolicySeatsOf(task, deps, toolPolicyLocked); enterConfigDoor(seats.toolPolicy.input, () => assertNoRetiredToolPolicyKeys(seats.toolPolicy.value)); enterConfigDoor(seats.basePolicyForResumeEdit.input, () => assertNoRetiredToolPolicyKeys(seats.basePolicyForResumeEdit.value)); const toolPolicyKind = seats.toolPolicy.value === undefined ? undefined : seats.toolPolicy.input === "taskConfig" ? "taskPolicy" : "deploymentPolicy"; const mcp = lockedKeys.has("mcp") || peers.mcp === undefined ? undefined : enterConfigDoor("taskConfig", () => validatedMcpEntries(received(peers.mcp).map(received))); const a2a = lockedKeys.has("a2a") || peers.a2a === undefined ? undefined : enterConfigDoor("taskConfig", () => validatedA2aEntries(received(peers.a2a))); enterConfigDoor("taskConfig", () => { assertPeerSeatFor(mcp, "mcp", deps.peerSeat); assertPeerSeatFor(a2a, "a2a", deps.peerSeat); }); return { lockedKeys, mcp, a2a, toolPolicy: seats.toolPolicy.value, toolPolicyKind, basePolicyForResumeEdit: seats.basePolicyForResumeEdit.value, }; } function callerPolicySeatsOf(spec, deps, toolPolicyLocked) { const seat = (key) => (toolPolicyLocked ? { value: deps[key], input: "deps" } : resolveSeatValue(spec[key], () => deps[key])); return { toolPolicy: seat("toolPolicy"), basePolicyForResumeEdit: seat("basePolicyForResumeEdit") }; } export function callerPolicySeats(spec, deps, toolPolicyLocked) { const seats = callerPolicySeatsOf(spec, deps, toolPolicyLocked); return { toolPolicy: seats.toolPolicy.value, basePolicyForResumeEdit: seats.basePolicyForResumeEdit.value }; }