@sema-agent/core
Version:
Stateless, task-oriented AI agent core
312 lines (311 loc) • 15.9 kB
JavaScript
import { SAFETY_AXIS_VOCABULARY } from "./safety-axis-vocab.js";
import { INLINE_TRUNCATION_MARK, inlineUntrusted } from "./untrusted-text.js";
import { callerKey, callerText, dataKind } from "./caller-text.js";
import { DECLARATION_RECEIPT_MODE } from "./own-property-receipt.js";
import { TOOL_AXES_SURFACES, isToolAxesSurface, toolAxesSurfaceList } from "./declaration-words.js";
import { isPlainRecord, receive } from "./mods/kernel/receive.js";
import { MODS_VALUE_DEPTH } from "./mods/kernel/site-rules.js";
export const MCP_TRANSPORT_KINDS = Object.freeze(["stdio", "http", "host"]);
const transportKindsLockstep = true;
void transportKindsLockstep;
export function transportKindOf(spec) {
try {
const transport = spec.transport;
const kind = (typeof transport === "object" && transport !== null) || typeof transport === "function" ? Reflect.get(transport, "kind") : undefined;
return MCP_TRANSPORT_KINDS.find((known) => known === kind);
}
catch {
return undefined;
}
}
function invalidArgument(message) {
const refusal = new Error(message);
refusal.code = "config.invalid_argument";
return refusal;
}
function toolAxesSurfaceOf(at) {
if (isToolAxesSurface(at))
return TOOL_AXES_SURFACES[at];
throw invalidArgument(`toolAxes is read for a surface, and the surfaces are ${toolAxesSurfaceList()} ` +
`(an MCP server's tools, an A2A peer's skills); the surface named is not one of them.`);
}
const TOOL_AXIS_MEMBERS = { effect: true, egress: true, irreversibility: true, boundaryFlow: true };
const TOOL_AXIS_MEMBER_NAMES = Object.keys(TOOL_AXIS_MEMBERS);
const TOOL_EFFECT_WORDS = SAFETY_AXIS_VOCABULARY.toolEffect;
const ENGINE_DERIVED_IRREVERSIBILITY = "maybe";
const IRREVERSIBILITY_POLE_WORDS = SAFETY_AXIS_VOCABULARY.irreversibility.filter((word) => word !== ENGINE_DERIVED_IRREVERSIBILITY);
const irreversibilityPolesLockstep = true;
void irreversibilityPolesLockstep;
const A2A_SKILL_AXIS_WORDS = {
effect: ["write"],
egress: [true],
irreversibility: ["always"],
};
const a2aSkillAxesAreTheTable = true;
const a2aSkillAxisMembersAreTheTable = true;
void a2aSkillAxesAreTheTable;
void a2aSkillAxisMembersAreTheTable;
const A2A_SKILL_AXIS_VALUES = A2A_SKILL_AXIS_WORDS;
const A2A_SKILL_AXIS_MEMBER_NAMES = Object.keys(A2A_SKILL_AXIS_WORDS);
const A2A_SKILL_AXIS_TAKES = Object.entries(A2A_SKILL_AXIS_WORDS)
.flatMap(([member, words]) => words.map((word) => `"${member}": ${JSON.stringify(word)}`))
.join(", ");
export function declarationPath(path, words, base = "") {
let rendered = base;
for (const key of path) {
if (rendered.length > 120 + base.length)
return `${rendered}${INLINE_TRUNCATION_MARK}`;
const name = typeof key === "number" ? `[${key}]` : words.has(key) ? key : callerText(key);
rendered += typeof key === "number" || rendered === "" ? name : `.${name}`;
}
return rendered;
}
const DECLARATION_ENTRY_MEMBERS = {
name: true,
source: true,
transport: true,
allowTools: true,
elicitation: true,
toolAxes: true,
toolFaces: true,
contentOrigin: true,
fingerprint: true,
startupTimeoutMs: true,
sessionMetaKey: true,
callerMeta: true,
kind: true,
command: true,
args: true,
url: true,
credentials: true,
principalHeader: true,
cardUrl: true,
allowSkills: true,
boundary: true,
displayName: true,
ownerTeam: true,
respond: true,
};
export const DECLARATION_ENTRY_WORDS = new Set(Object.keys(DECLARATION_ENTRY_MEMBERS));
const RECEIPT_FAULT_PROBLEMS = {
proxy: "it is a Proxy, whose traps would run as it is read; copy it into plain data (a spread or a JSON round trip)",
"not-data": "it is not plain data (a function, a bigint, a symbol, or an object whose prototype is neither Object.prototype nor null: a class instance, " +
"a map, `process.env`, a record built on a prototype or in another realm — a `vm` context, a worker); copy it into plain data (a spread " +
"or a JSON round trip), writing out any member it inherits",
"getter-threw": "its getter threw while it was read",
"prototype-moved": "its prototype changed while it was read",
cycle: "it contains itself; declare it as plain data",
"too-deep": `it is nested past ${MODS_VALUE_DEPTH} levels`,
uncopyable: "it could not be copied whole",
accessor: "it is an accessor",
hidden: "it is a member that is not an enumerable data property",
};
export function declarationFaultOf(fault) {
return { path: fault.path.map((key) => (/^(?:0|[1-9]\d*)$/.test(key) ? Number(key) : key)), problem: RECEIPT_FAULT_PROBLEMS[fault.kind] };
}
export const DECLARATION_PATH_RULES = Object.freeze({
mcp: Object.freeze([
{ path: ["name"], holds: "a string", required: true },
].map((rule) => Object.freeze({ ...rule, path: Object.freeze([...rule.path]) }))),
a2a: Object.freeze([
{ path: ["name"], holds: "a string", required: true },
].map((rule) => Object.freeze({ ...rule, path: Object.freeze([...rule.path]) }))),
});
export const NO_DECLARATION_PATH_RULES = Object.freeze([]);
const PROTO_MEMBER = `it is a member named "__proto__", which a copy by assignment would turn into a prototype — not a name a declaration can carry`;
function declarationVocabularyFault(root, rules) {
const asked = new Set();
const path = [];
const stack = [];
const ruleAt = () => rules.find((rule) => rule.path.length === path.length && rule.path.every((key, i) => key === path[i]));
const onRuleRoute = () => rules.some((rule) => rule.path.length > path.length && path.every((key, i) => key === rule.path[i]));
const ruleProblem = (_rule, value) => (typeof value === "string" ? undefined : `it is ${dataKind(value)}, not a string`);
const meet = (value) => {
if (typeof value !== "object" || value === null || (asked.has(value) && !onRuleRoute()))
return undefined;
asked.add(value);
if (Array.isArray(value)) {
for (let index = 0; index < value.length; index++) {
const own = Object.hasOwn(value, index);
if (own && typeof value[index] === "string")
continue;
path.push(index);
return `it is ${own ? dataKind(value[index]) : "a hole"}, not a string: every list a declaration carries is a list of names`;
}
const named = Object.keys(value).find((key) => !(/^(?:0|[1-9]\d*)$/.test(key) && Number(key) < value.length));
if (named === undefined)
return undefined;
path.push(named);
return "it is a list member that is not an index: a list declares its names at its indices only";
}
stack.push({ members: Object.entries(value), next: 0 });
return undefined;
};
for (const rule of rules) {
if (rule.required !== true)
continue;
let at = root;
for (const key of rule.path)
at = isPlainRecord(at) && Object.hasOwn(at, key) ? at[key] : undefined;
if (at === undefined)
return { path: [...rule.path], problem: `it is missing: a declaration carries ${rule.holds} here` };
}
let problem = meet(root);
while (problem === undefined && stack.length > 0) {
const frame = stack[stack.length - 1];
if (frame.next === frame.members.length) {
stack.pop();
if (stack.length > 0)
path.pop();
continue;
}
const [key, member] = frame.members[frame.next++];
path.push(key);
const rule = key === "__proto__" || member === undefined ? undefined : ruleAt();
if (key === "__proto__")
problem = PROTO_MEMBER;
else if (rule !== undefined)
problem = ruleProblem(rule, member);
else {
const depth = stack.length;
problem = meet(member);
if (problem === undefined && stack.length > depth)
continue;
}
if (problem === undefined)
path.pop();
}
return problem === undefined ? undefined : { path, problem };
}
export function receiveDeclaration(declared, rules) {
if (!Array.isArray(rules)) {
throw invalidArgument(`a declaration is received with the path rules of its surface (${Object.keys(DECLARATION_PATH_RULES).map((s) => `DECLARATION_PATH_RULES[${JSON.stringify(s)}]`).join(" | ")}), ` +
`or an empty list when it fixes no path; what was passed is ${dataKind(rules)}, not a list of rules.`);
}
const received = receive(declared, DECLARATION_RECEIPT_MODE);
if (!received.ok)
return { ok: false, fault: declarationFaultOf(received.fault) };
const fault = isPlainRecord(received.value) ? declarationVocabularyFault(received.value, rules) : undefined;
return fault === undefined ? { ok: true, value: received.value } : { ok: false, fault };
}
function isToolEffectWord(value) {
return typeof value === "string" && TOOL_EFFECT_WORDS.includes(value);
}
function isIrreversibilityPoleWord(value) {
return typeof value === "string" && IRREVERSIBILITY_POLE_WORDS.includes(value);
}
const MCP_AXIS_TAKES = {
effect: isToolEffectWord,
egress: (value) => typeof value === "boolean",
irreversibility: isIrreversibilityPoleWord,
boundaryFlow: (value) => value === "engine",
};
const A2A_REFUSAL_ENDINGS = {
lowering: ` — on an A2A peer an axis only raises, and it takes ${A2A_SKILL_AXIS_TAKES}`,
foreign: ` — not a value an A2A axis takes; it takes ${A2A_SKILL_AXIS_TAKES}`,
};
function readToolAxisEntry(raw, at) {
if (!isPlainRecord(raw))
return `the declaration is ${dataKind(raw)}, not an object of axes`;
const listed = Object.keys(raw);
const unknown = listed.find((member) => !TOOL_AXIS_MEMBER_NAMES.includes(member));
if (unknown !== undefined)
return `an unknown member ${callerKey(unknown)} (the members are ${(at === "a2a" ? A2A_SKILL_AXIS_MEMBER_NAMES : TOOL_AXIS_MEMBER_NAMES).join(", ")})`;
const declared = Object.create(null);
for (const member of TOOL_AXIS_MEMBER_NAMES) {
const value = raw[member];
if (value !== undefined && !listed.includes(member))
return `member "${member}" is a hidden member: its name answers a value the declaration does not list as its own`;
declared[member] = value;
}
if (at === "a2a") {
const held = TOOL_AXIS_MEMBER_NAMES.filter((member) => declared[member] !== undefined);
const refused = held.filter((member) => !(Object.hasOwn(A2A_SKILL_AXIS_VALUES, member) ? A2A_SKILL_AXIS_VALUES[member] : []).includes(declared[member]));
const lowering = refused.some((member) => MCP_AXIS_TAKES[member](declared[member]));
if (refused.length > 0)
return `drop ${refused.map((member) => `"${member}"`).join(", ")}${lowering ? A2A_REFUSAL_ENDINGS.lowering : A2A_REFUSAL_ENDINGS.foreign}`;
return Object.fromEntries(held.map((member) => [member, declared[member]]));
}
const { effect, egress, irreversibility, boundaryFlow } = declared;
if (effect !== undefined && !MCP_AXIS_TAKES.effect(effect))
return `member "effect" is not one of ${TOOL_EFFECT_WORDS.join(" | ")}`;
if (egress !== undefined && !MCP_AXIS_TAKES.egress(egress))
return `member "egress" is not a boolean`;
if (irreversibility !== undefined && !MCP_AXIS_TAKES.irreversibility(irreversibility))
return `member "irreversibility" is not one of ${IRREVERSIBILITY_POLE_WORDS.join(" | ")}`;
if (boundaryFlow !== undefined && !MCP_AXIS_TAKES.boundaryFlow(boundaryFlow))
return `member "boundaryFlow" is not "engine"`;
if (boundaryFlow === "engine" && egress !== false)
return `member "boundaryFlow": "engine" needs "egress": false in the same entry — add it, or drop "boundaryFlow" (${egress === true ? '"egress": true contradicts it' : 'with no "egress", the server hint or the peer default stays in force'})`;
return {
...(effect !== undefined ? { effect } : {}),
...(egress !== undefined ? { egress } : {}),
...(irreversibility !== undefined ? { irreversibility } : {}),
...(boundaryFlow !== undefined ? { boundaryFlow } : {}),
};
}
const PER_TOOL_DECLARATIONS = {
toolAxes: { plural: "axes", singular: "axis" },
toolFaces: { plural: "faces", singular: "face" },
};
export function receivePerToolDeclaration(declared, field, unit, words) {
const received = receiveDeclaration(declared, NO_DECLARATION_PATH_RULES);
if (!received.ok) {
const [key, ...member] = received.fault.path;
if (key === undefined)
return { ok: false, problem: `${field} cannot be read: ${received.fault.problem}` };
const where = member.length > 0 ? `member ${declarationPath(member, words)}: ` : "";
return { ok: false, problem: perToolEntryRefusal(field, unit, String(key), `${where}${received.fault.problem}`) };
}
const perTool = received.value;
if (!isPlainRecord(perTool))
return { ok: false, problem: `${field} is ${dataKind(perTool)}, not an object of per-${unit} ${PER_TOOL_DECLARATIONS[field].singular} declarations` };
return { ok: true, perTool };
}
export function perToolEntryRefusal(field, unit, key, detail, at) {
const place = at === undefined ? "" : `, entry ${at.index + 1} of ${at.of},`;
return `the ${PER_TOOL_DECLARATIONS[field].plural} declared for the ${unit} ${callerText(key)}${place} do not fit: ${detail}`;
}
export const TOOL_AXIS_WORDS = new Set(TOOL_AXIS_MEMBER_NAMES);
export function perToolEmptyName(field, unit) {
return `${field} has an empty ${unit} name`;
}
export function readToolAxes(declared, at) {
const unit = toolAxesSurfaceOf(at).key;
if (declared === undefined)
return { ok: true };
const received = receivePerToolDeclaration(declared, "toolAxes", unit, TOOL_AXIS_WORDS);
if (!received.ok)
return { ok: false, problem: received.problem };
const entries = [];
const declaredEntries = Object.entries(received.perTool);
for (const [index, [key, raw]] of declaredEntries.entries()) {
if (key.length === 0)
return { ok: false, problem: perToolEmptyName("toolAxes", unit) };
let entry;
try {
entry = readToolAxisEntry(raw, at);
}
catch {
entry = "a member threw while it was read";
}
if (typeof entry === "string")
return { ok: false, problem: perToolEntryRefusal("toolAxes", unit, key, entry, { index, of: declaredEntries.length }) };
if (Object.keys(entry).length > 0)
entries.push([key, entry]);
}
return entries.length > 0 ? { ok: true, toolAxes: Object.fromEntries(entries) } : { ok: true };
}
export function readMcpToolAxes(declared) {
return readToolAxes(declared, "mcp");
}
export function declarerWord(at) {
return toolAxesSurfaceOf(at).declarer;
}
export function toolAxesRefusal(at, name, problem, loweredWhole = false) {
const surface = toolAxesSurfaceOf(at);
const afterLowering = "afterLowering" in surface && Object.hasOwn(surface, "afterLowering") && problem.endsWith(A2A_REFUSAL_ENDINGS.lowering) && !loweredWhole ? ` ${surface.afterLowering}` : "";
const shownName = "nameMax" in surface && Object.hasOwn(surface, "nameMax") ? inlineUntrusted(name, surface.nameMax) : name;
return invalidArgument(`${surface.declarer} ${shownName} declares toolAxes ${surface.refused}: ${inlineUntrusted(problem, 240)}.${afterLowering} ${surface.standing}, so it is refused ` +
`rather than partly applied — dropping one key or defaulting one word would leave a declaration that reads as in force while it is not.`);
}