@sema-agent/core
Version:
Stateless, task-oriented AI agent core
279 lines (278 loc) • 18.4 kB
JavaScript
import { callerText } from "../caller-text.js";
import { listedNamesOf } from "../mcp-producer-facts.js";
import { A2A_NAMESPACE, MCP_NAMESPACE, mintNamespacePrefix, mintNamespacedToolName } from "@sema-agent/primitives";
import { RESERVED_APPROVAL_CARDS, TOOL_APPROVAL_CARDS, TOOL_FAMILIES, TOOL_PATH_ABSENCES, TOOL_PATH_ACCESSES, TOOL_PATH_BASES, RENDER_HINT_ACTIVITY_MAX_CHARS, RENDER_HINT_MAX_CHARS, RENDER_HINT_MAX_LIST, TOOL_KEY_MAX_CHARS, } from "../tool-face.js";
import { engineCardOf, inputKeysOf, offendingResultCard, protocolToolOf, rosterCardId } from "../tool-roster.js";
import { engineCardTypes, hostTargetingToolNames } from "../tool-registry.js";
import { deliverEngineNotice } from "../engine-notice.js";
import { inlineUntrusted } from "../untrusted-text.js";
export const APPROVAL_CARD_REQUIRED_KEYS = Object.freeze({
"file-edit": ["file_path"],
"file-write": ["file_path"],
"notebook-edit": ["notebook_path"],
shell: ["command"],
fetch: ["url"],
skill: ["skill"],
workflow: [],
plan: [],
question: [],
generic: [],
"computer-access": ["apps"],
"computer-control": [],
network: ["host"],
});
export function toolFaceProblem(face, schema, tool) {
return faceProblem(face, schema, tool);
}
function schemaPropertyOf(schema, name) {
const props = schema?.properties;
return props !== null && typeof props === "object" && Object.hasOwn(props, name) ? props[name] : undefined;
}
function schemaTakesOnlyStrings(node) {
if (node === null || typeof node !== "object")
return false;
const s = node;
const t = s["type"];
const listOnly = (v, each) => Array.isArray(v) && v.length > 0 && v.every(each);
return (t === "string" ||
listOnly(t, (x) => x === "string") ||
(Array.isArray(s["allOf"]) && s["allOf"].some(schemaTakesOnlyStrings)) ||
listOnly(s["anyOf"], schemaTakesOnlyStrings) ||
listOnly(s["oneOf"], schemaTakesOnlyStrings) ||
typeof s["const"] === "string" ||
listOnly(s["enum"], (e) => typeof e === "string"));
}
export function faceProblem(face, schema, tool) {
const bound = schema === undefined ? undefined : inputKeysOf(schema);
const top = bound === undefined ? undefined : new Set(bound.keys.map((k) => k.name));
const outside = (label, value, words) => value === undefined || words.includes(value) ? undefined : `${label} ${callerText(value)} is outside the closed set (${words.join(" | ")})`;
const family = outside("family", face.family, TOOL_FAMILIES);
if (family !== undefined)
return family;
const overlong = (label, values) => {
const k = values.find((v) => v.length > TOOL_KEY_MAX_CHARS);
return k === undefined ? undefined : `${label} has a key of ${k.length} characters; a roster key is at most ${TOOL_KEY_MAX_CHARS}`;
};
const vocabulary = new Set(bound?.scalar);
if (face.pathTarget !== undefined) {
if (top !== undefined && (typeof face.pathTarget.param !== "string" || !top.has(face.pathTarget.param)))
return `pathTarget.param ${callerText(face.pathTarget.param)} is not a top-level property of the tool's schema`;
const access = outside("pathTarget.access", face.pathTarget.access, TOOL_PATH_ACCESSES);
if (access !== undefined)
return access;
const base = face.pathTarget.base;
const baseWord = outside("pathTarget.base", base, TOOL_PATH_BASES);
if (baseWord !== undefined)
return baseWord;
if (base === "root" && face.pathTarget.access !== "read")
return `pathTarget.base "root" needs pathTarget.access "read" — two write guards (the session-transcript directory guard and the frozen-spec deny) resolve a write target against the call's working directory only, so a write face declaring a root base can be judged on two different files; declare a write face with base "cwd" (or no base), and only for a tool that resolves its relative paths against the call's working directory`;
const absent = face.pathTarget.absent;
const absentWord = outside("pathTarget.absent", absent, TOOL_PATH_ABSENCES);
if (absentWord !== undefined)
return absentWord;
if (absent === "base" && face.pathTarget.access !== "read")
return `pathTarget.absent "base" needs pathTarget.access "read" — it says the call is about the whole base directory when the slot is empty, which is a search SCOPE; a write with no path names no file, and the containment fences judge a write on its own target`;
const patternParam = face.pathTarget.patternParam;
if (patternParam !== undefined) {
if (top !== undefined && (typeof patternParam !== "string" || !top.has(patternParam)))
return `pathTarget.patternParam ${callerText(patternParam)} is not a top-level property of the tool's schema`;
if (absent !== "base")
return `pathTarget.patternParam is declared but pathTarget.absent is ${JSON.stringify(absent ?? "none")} — the pattern base is only ever read for an absent slot, so this declaration would be inert`;
}
const each = face.pathTarget.each;
if (each !== undefined && typeof each !== "boolean")
return `pathTarget.each is ${typeof each}, not a boolean (true, or absent)`;
if (each === true && face.pathTarget.access !== "read")
return `pathTarget.each needs pathTarget.access "read" — a slot that names several targets is a read's; a write names one file`;
const slotType = bound?.keys.find((k) => k.name === face.pathTarget.param)?.type;
if (each === true && slotType !== undefined && slotType !== "array" && slotType !== "mixed")
return `pathTarget.each is declared but the schema types pathTarget.param as ${slotType}: a slot that names several targets takes a string or a list of strings`;
if (each !== true && face.pathTarget.access === "read" && schema !== undefined) {
for (const name of [face.pathTarget.param, ...(face.pathTarget.aliases ?? [])]) {
const node = schemaPropertyOf(schema, name);
if (node === undefined || schemaTakesOnlyStrings(node))
continue;
const t = bound?.keys.find((k) => k.name === name)?.type;
if (t === "array")
return `pathTarget ${callerText(name)} is a list in the tool's schema but pathTarget.each is not declared: the slot would never be read as a target — declare each: true to have every element judged`;
if (t === "mixed")
return `pathTarget ${callerText(name)} may carry a value that is not a string in the tool's schema (a union, an untyped slot, or a form this door does not read as strings only) but pathTarget.each is not declared — a read target that names one file takes a string: type it a string, or declare each: true for a string or a list of strings`;
return `pathTarget ${callerText(name)} is typed ${t ?? "something other than a string"} in the tool's schema, but a read target names a file by a string — type it a string`;
}
}
const long = overlong("pathTarget.param", [face.pathTarget.param]) ??
overlong("pathTarget.aliases", face.pathTarget.aliases ?? []) ??
overlong("pathTarget.patternParam", patternParam === undefined ? [] : [patternParam]);
if (long !== undefined)
return long;
vocabulary.add(face.pathTarget.param);
for (const a of face.pathTarget.aliases ?? [])
vocabulary.add(a);
}
if (face.hostTarget !== undefined) {
const hostNames = hostTargetingToolNames();
if (tool === undefined) {
return `hostTarget is not accepted on an MCP tool — host rules are written for ${[...hostNames].join(", ")} only, so the slot would never be read; write a rule for the whole tool (mcp__<server>__<tool>) or the whole server (mcp__<server>) instead`;
}
if (!hostNames.has(tool.toolName)) {
return `hostTarget is declared on a tool whose name host rules are not written for (they are written for ${[...hostNames].join(", ")}) — a host rule's grammar belongs to the rule's tool name, so the slot would never be read; declare it only on a tool of that name`;
}
if (face.pathTarget !== undefined)
return `hostTarget and pathTarget are both declared — a face names one protected target, the URL a call reaches or the path it touches`;
if (top !== undefined && (typeof face.hostTarget.param !== "string" || !top.has(face.hostTarget.param)))
return `hostTarget.param ${callerText(face.hostTarget.param)} is not a top-level property of the tool's schema`;
const long = overlong("hostTarget.param", [face.hostTarget.param]);
if (long !== undefined)
return long;
}
const hints = face.renderHints;
if (hints !== undefined) {
const card = hints.approvalCard;
if (card !== undefined) {
const cardWord = outside("renderHints.approvalCard", card, TOOL_APPROVAL_CARDS);
if (cardWord !== undefined)
return cardWord;
if (RESERVED_APPROVAL_CARDS.includes(card) && (tool === undefined || engineCardOf(tool) !== card))
return `renderHints.approvalCard ${JSON.stringify(card)} is reserved for the engine's own tool that owns it; a declared tool takes another card or none`;
const missing = top === undefined ? [] : APPROVAL_CARD_REQUIRED_KEYS[card].filter((k) => !top.has(k));
if (missing.length > 0)
return `renderHints.approvalCard ${JSON.stringify(card)} needs ${missing.join(", ")} on the tool's schema`;
}
if (hints.userFacingName !== undefined && hints.userFacingName.length > RENDER_HINT_MAX_CHARS)
return `renderHints.userFacingName is ${hints.userFacingName.length} characters; the bound is ${RENDER_HINT_MAX_CHARS}`;
if (hints.activity !== undefined && hints.activity.length > RENDER_HINT_ACTIVITY_MAX_CHARS)
return `renderHints.activity is ${hints.activity.length} characters; the bound is ${RENDER_HINT_ACTIVITY_MAX_CHARS}`;
if ((hints.summaryParams?.length ?? 0) > RENDER_HINT_MAX_LIST)
return `renderHints.summaryParams lists ${hints.summaryParams.length} entries; the bound is ${RENDER_HINT_MAX_LIST}`;
if ((hints.resultCards?.length ?? 0) > RENDER_HINT_MAX_LIST)
return `renderHints.resultCards lists ${hints.resultCards.length} entries; the bound is ${RENDER_HINT_MAX_LIST}`;
const long = overlong("renderHints.summaryParams", hints.summaryParams ?? []) ?? overlong("renderHints.resultCards", hints.resultCards ?? []);
if (long !== undefined)
return long;
const foreignCard = tool?.cardId === undefined ? undefined : offendingResultCard(hints, tool.cardId, engineCardTypes());
if (foreignCard !== undefined)
return `renderHints.resultCards names ${callerText(foreignCard)}, outside the tool's own card namespace "${tool.cardId}/<card>" (engine cards and other contracts' namespaces are reserved)`;
const stray = top === undefined ? undefined : (hints.summaryParams ?? []).find((p) => !top.has(p));
if (stray !== undefined)
return `renderHints.summaryParams names ${callerText(stray)}, which is not a top-level property`;
}
if (top !== undefined) {
for (const p of face.ruleFace?.params ?? [])
if (!vocabulary.has(p))
return `ruleFace.params names ${callerText(p)}, which is neither a scalar top-level property nor the declared path target`;
for (const p of face.ruleFace?.primaryParams ?? [])
if (!vocabulary.has(p))
return `ruleFace.primaryParams names ${callerText(p)}, which is neither a top-level property nor the declared path target`;
}
const long = overlong("ruleFace.params", face.ruleFace?.params ?? []) ?? overlong("ruleFace.primaryParams", face.ruleFace?.primaryParams ?? []);
if (long !== undefined)
return long;
return undefined;
}
function mintedKeyHint(table, target, named) {
return named !== undefined ? ` — ${table} is keyed by the ${target}: write "${named}"` : "";
}
function announceUndeclaredKeys(table, listedNames, server, onNotice, announced, sessionId, runId, describe) {
if (table === undefined)
return;
for (const raw of Object.keys(table)) {
if (listedNames.has(raw))
continue;
const { key, message } = describe(raw);
if (announced.has(key))
continue;
announced.add(key);
deliverEngineNotice(onNotice, {
code: "config.tool_face_undeclared",
message,
detail: { server, tool: raw, sessionId, runId },
});
}
}
export function announceA2aUndeclaredToolAxes(input) {
for (const peer of input.peers) {
const listed = listedNamesOf(input.statuses.find((s) => s.name === peer.name));
if (listed === undefined)
continue;
const allowed = peer.allowSkills === undefined ? [...listed] : [...listed].filter((id) => peer.allowSkills.includes(id));
announceUndeclaredKeys(peer.toolAxes, listed, peer.name, input.onNotice, input.announced, input.sessionId, input.runId, (raw) => {
const matches = allowed.filter((id) => mintNamespacedToolName(A2A_NAMESPACE, peer.name, id) === raw);
const hint = mintedKeyHint("toolAxes", "id on the peer's agent card", matches.length === 1 ? matches[0] : undefined);
return {
key: `undeclared-a2a-axis:${JSON.stringify([peer.name, raw])}`,
message: `A2A peer "${peer.name}": toolAxes declares an axis for "${raw}", which the peer's agent card does not carry — the declaration is inert${hint}`,
};
});
}
}
export function applyMcpToolFaces(input) {
const faces = input.server.toolFaces;
const axes = input.server.toolAxes;
const prefix = mintNamespacePrefix(MCP_NAMESPACE, input.server.name);
const listed = input.listed;
if (listed !== undefined) {
const rawNameOfMinted = (raw) => input.tools.find((t) => t.name === raw && t.name.startsWith(prefix))?.mcpRemoteName;
announceUndeclaredKeys(faces, listed, input.server.name, input.onNotice, input.announced, input.sessionId, input.runId, (raw) => {
const hint = mintedKeyHint("toolFaces", "name the server lists", rawNameOfMinted(raw));
return {
key: `undeclared:${JSON.stringify([input.server.name, raw])}`,
message: `MCP server "${input.server.name}": toolFaces declares a face for "${raw}", which the server's tool listing does not carry — the declaration is inert${hint}`,
};
});
announceUndeclaredKeys(axes, listed, input.server.name, input.onNotice, input.announced, input.sessionId, input.runId, (raw) => {
const hint = mintedKeyHint("toolAxes", "name the server lists", rawNameOfMinted(raw));
return {
key: `undeclared-axis:${JSON.stringify([input.server.name, raw])}`,
message: `MCP server "${input.server.name}": toolAxes declares an axis for "${raw}", which the server's tool listing does not carry — the declaration is inert${hint}`,
};
});
}
if (faces === undefined)
return [...input.tools];
return input.tools.flatMap((t) => {
const stamped = stampOne(t);
return stamped === undefined ? [] : [stamped];
});
function stampOne(t) {
const raw = t.mcpRemoteName;
const face = raw !== undefined && t.name.startsWith(prefix) ? faces?.[raw] : undefined;
if (raw === undefined || face === undefined)
return t;
const hit = { raw, face };
const problem = toolFaceProblem(hit.face, t.parameters, { toolName: t.name, cardId: rosterCardId("mcp", t.name, input.server.name, protocolToolOf(t.name), "") });
if (problem !== undefined) {
const key = `invalid:${t.name}`;
if (!input.announced.has(key)) {
input.announced.add(key);
deliverEngineNotice(input.onNotice, {
code: "config.tool_face_invalid",
message: `The tool "${hit.raw}" of MCP server "${inlineUntrusted(input.server.name, 160)}" is not available in this session — the deployment's setting for it ` +
`does not fit the tool as the server lists it, so the tool is withheld rather than run without the protection that setting declares; the run goes on ` +
`without it. Ask whoever runs this deployment to correct that setting.`,
detail: { server: input.server.name, tool: hit.raw, sessionId: input.sessionId, runId: input.runId },
});
if (input.onError !== undefined) {
const diagnostic = Object.assign(new Error(`MCP server "${input.server.name}": toolFaces overlay for "${hit.raw}" does not fit its schema — ${problem}`), { code: "config.tool_face_invalid", server: input.server.name, tool: hit.raw, problem, runId: input.runId });
try {
const ret = input.onError(diagnostic, { phase: "mcp", sessionId: input.sessionId });
if (ret !== null && ret !== undefined && typeof ret.then === "function") {
Promise.resolve(ret).then(undefined, () => undefined);
}
}
catch {
}
}
}
return undefined;
}
const f = hit.face;
return {
...t,
...(f.family !== undefined ? { family: f.family } : {}),
...(f.pathTarget !== undefined ? { pathTarget: f.pathTarget } : {}),
...(f.hostTarget !== undefined ? { hostTarget: f.hostTarget } : {}),
...(f.renderHints !== undefined ? { renderHints: f.renderHints } : {}),
...(f.ruleFace !== undefined ? { ruleFace: f.ruleFace } : {}),
};
}
}