@sema-agent/core
Version:
Stateless, task-oriented AI agent core
155 lines (154 loc) • 7.32 kB
JavaScript
import { callerToolNameProblem } from "../caller-tool-name.js";
import { describeToolCatalog } from "../tool-registry.js";
import { describeRejectedValue } from "../tool-search-setting.js";
import { callerCardIdOf, rosterMemberBoundProblem, schemaKeyBoundProblem, survivorsByName } from "../tool-roster.js";
import { toolFaceProblem } from "./tool-face-overlay.js";
import { callerEngineContractProblem } from "./caller-roster.js";
const REPEAT_RISK = { read: 0, idempotent: 1, write: 2 };
const leastRepeatSafe = (a, b) => (REPEAT_RISK[a] >= REPEAT_RISK[b] ? a : b);
function engineCandidatesOf(spec, deps) {
const hands = Boolean(deps.executionEnvFactory || deps.executionEnv);
const readOnlyHands = spec.handsReadOnly === true;
const out = [];
for (const e of describeToolCatalog()) {
if (!e.mountedBy.some((t) => t !== "scenario" && (t !== "hands" || hands)))
continue;
if (e.mountedBy.includes("hands") && e.face.ruleFace?.grammar === "command" && (e.face.effect === "read") !== readOnlyHands)
continue;
const effect = e.face.effect ?? "write";
for (const name of [e.name, ...(e.face.aliases ?? [])])
out.push([name, effect]);
}
return out;
}
function wakeEffectsOf(table, claimed, candidates) {
const wakeEffects = new Map(table);
const claims = new Set(claimed);
for (const [name, effect] of candidates) {
const prior = wakeEffects.get(name) ?? (claims.has(name) ? "write" : undefined);
wakeEffects.set(name, prior === undefined ? effect : leastRepeatSafe(prior, effect));
}
return wakeEffects;
}
const tierOf = (t) => t.irreversibility ?? (t.reversibilityProbe ? "maybe" : undefined);
export function prepareSafetyScan(input) {
const { spec, deps } = input;
const declared = new Map();
const survivors = survivorsByName(spec.tools ?? []);
const claimedAliases = new Set();
const aliasClaims = [];
const egressTools = new Set();
const irreversibleTools = new Set();
const irreversibilityTier = new Map();
const axisExplicitNegatives = new Map();
const reversibilityProbes = new Map();
const toolMarkSources = new Map();
const markedBy = (name, source) => {
const set = toolMarkSources.get(name);
if (set !== undefined)
set.add(source);
else
toolMarkSources.set(name, new Set([source]));
};
for (const t of spec.tools ?? []) {
{
const bound = rosterMemberBoundProblem({
name: t.name,
aliases: t.aliases,
...(t.contract !== undefined ? { contractId: t.contract.contractId, implementationRevision: t.contract.implementationRevision } : {}),
...(typeof t.modelGate === "string" ? { modelGate: t.modelGate } : {}),
}) ?? callerEngineContractProblem(t);
if (bound !== undefined) {
const e = new Error(`A caller tool cannot ride a roster row: ${bound.message}.`);
e.code = bound.code;
throw e;
}
}
{
const keyProblem = schemaKeyBoundProblem(t.parameters);
if (keyProblem !== undefined) {
const e = new Error(`Tool "${t.name}" cannot ride a roster row: ${keyProblem}.`);
e.code = "config.tool_schema_bound";
throw e;
}
const declared = {
...(t.family !== undefined ? { family: t.family } : {}),
...(t.pathTarget !== undefined ? { pathTarget: t.pathTarget } : {}),
...(t.hostTarget !== undefined ? { hostTarget: t.hostTarget } : {}),
...(t.ruleFace !== undefined ? { ruleFace: t.ruleFace } : {}),
...(t.renderHints !== undefined ? { renderHints: t.renderHints } : {}),
};
const faceProblem = toolFaceProblem(declared, t.parameters, { toolName: t.name, cardId: callerCardIdOf(t) });
if (faceProblem !== undefined) {
const e = new Error(`Tool "${t.name}" declares a face its schema cannot carry: ${faceProblem}.`);
e.code = "config.tool_face_invalid";
throw e;
}
const perTurn = t.perTurn;
if (perTurn !== undefined && perTurn !== true) {
const e = new Error(`Tool "${t.name}" declares \`perTurn\` as ${describeRejectedValue(perTurn)}: it is \`true\` (the host mounts the tool on some turns only) or absent.`);
e.code = "config.tool_face_invalid";
throw e;
}
const startsAgents = t.startsAgents;
if (startsAgents !== undefined && startsAgents !== true) {
const e = new Error(`Tool "${t.name}" declares \`startsAgents\` as ${describeRejectedValue(startsAgents)}: it is \`true\` (a call of the tool starts another agent run) or absent.`);
e.code = "config.tool_face_invalid";
throw e;
}
}
for (const [what, n] of [["name", t.name], ...(t.aliases ?? []).map((a) => ["alias", a])]) {
const problem = callerToolNameProblem(n);
if (problem === undefined)
continue;
const e = new Error(`Tool ${what} ${JSON.stringify(n)}${what === "alias" ? ` (of ${JSON.stringify(t.name)})` : ""} is invalid: ${problem}.`);
e.code = "config.tool_name_invalid";
throw e;
}
if (t.effect && survivors.get(t.name) === t) {
declared.set(t.name, t.effect);
}
const tier = tierOf(t);
if (tier !== undefined) {
irreversibilityTier.set(t.name, tier);
if (tier === "always" || tier === "maybe") {
irreversibleTools.add(t.name);
markedBy(t.name, "deployment");
}
}
if (t.reversibilityProbe)
reversibilityProbes.set(t.name, t.reversibilityProbe);
if (t.egress) {
if (t.effect !== undefined && t.effect !== "write") {
const e = new Error(`Tool "${t.name}" declares egress:true with effect:"${t.effect}" — an egress tool (external write) must have effect:"write" (or omit effect; write is the default).`);
e.code = "config.egress_requires_write_effect";
throw e;
}
egressTools.add(t.name);
markedBy(t.name, "deployment");
}
}
const candidates = engineCandidatesOf(spec, deps);
for (const t of survivors.values()) {
for (const alias of t.aliases ?? []) {
if (alias === t.name || survivors.has(alias))
continue;
aliasClaims.push([alias, t.effect ?? "write"]);
if (claimedAliases.has(alias))
continue;
claimedAliases.add(alias);
if (t.effect)
declared.set(alias, t.effect);
}
}
return {
toolEffects: new Map(),
wakeEffects: wakeEffectsOf(declared, [...claimedAliases, ...survivors.keys()], [...aliasClaims, ...candidates]),
egressTools,
irreversibleTools,
irreversibilityTier,
axisExplicitNegatives,
reversibilityProbes,
toolMarkSources,
};
}