@sema-agent/core
Version:
Stateless, task-oriented AI agent core
247 lines (246 loc) • 13 kB
JavaScript
import { valveLeaves, valveLeavesPeer } from "../agents/tool-filter.js";
import { judgePeerLaneMount } from "../agents/peer-session-drain.js";
import { resolveCheckpointStore } from "./checkpoint-store.js";
import { preflightLockedConfig } from "./locked-config.js";
import { memoryEngineOpens, normalizeMemorySpec } from "./memory.js";
import { refusePermissionModeDoors, withModeSeats } from "./mode-policy.js";
import { MCP_RESOURCE_FACES } from "./mounted-mcp.js";
import { A2A_NAMESPACE, MCP_NAMESPACE, mintNamespacePrefix } from "@sema-agent/primitives";
import { resolveTaskModel } from "./roles.js";
import { checkedPlanFileShape } from "./runner/advertised-writable-dirs.js";
import { normalizeSeatDeps } from "./runner/classifier-ladder.js";
import { rosterFaceOf } from "./runner/caller-roster.js";
import { readToolSelector } from "./runner/sub-agent-deny-lists.js";
import { legRetiredNameView } from "./tool-name-aliases.js";
import { StubExecutionEnv } from "./stub-env.js";
import { readToolFaceLists } from "./tool-face-lists.js";
import { applyToolModelGate } from "./tool-model-gate.js";
import { delegationHasBackgroundLane } from "./delegation-name.js";
import { envMountFacts, offloadSeatFact, offloadThresholdsOf, legSeatMountFacts, seatMountFacts, specMountFacts, startersWithheldFact, } from "./tool-mount-facts.js";
import { TOOL_MOUNT_FACTS, mountGroupNames, planToolMounts, readExecutionEnv, } from "./tool-mount-plan.js";
import { legBackingStore, OFFLOAD_TOOL_NAME } from "./tool-result-store.js";
import { listLegModSeats } from "./mods/host.js";
import { seatsReachEnv } from "./mods/kernel/registration.js";
import { legWriteProtectionTable } from "./runner/write-protection-station.js";
import { readSkillsSeat } from "./runner/skills-seat.js";
import { skillsThatLoad } from "./runner/synthetic-tools.js";
import { loadedSkills } from "./runner/loaded-skills.js";
import { readCallerSpec } from "./task-spec-members.js";
import { screenUserAttachments, userAttachmentsNeedWorkspace } from "./user-attachment.js";
import { workspaceDeclared } from "./session-checkout.js";
import { writesProtectedPath } from "./tool-registry.js";
import { callerMountSource, entryDelegates, planIdentityOf } from "./tool-roster.js";
import { withOwnLegHands } from "./child-clamp-seats.js";
function anyOf(values) {
if (values.includes(true))
return true;
return values.includes(undefined) ? undefined : false;
}
function callerEntries(deps, spec, lists) {
const handed = Array.isArray(spec.tools) ? spec.tools : [];
const faces = [];
handed.forEach((t, i) => {
const face = rosterFaceOf(t, i);
if (((typeof face === "object" && face !== null) || typeof face === "function") && typeof face.name === "string")
faces.push(face);
});
const catalogDeps = normalizeSeatDeps(deps);
const modelId = (() => {
if (spec.model !== undefined || spec.modelRole !== undefined)
return resolveTaskModel(spec, catalogDeps).model.id;
try {
return resolveTaskModel(spec, catalogDeps).model.id;
}
catch {
return undefined;
}
})();
if (modelId === undefined)
return faces.map((face) => ({ face, kept: face.modelGate === undefined ? true : undefined }));
const decision = applyToolModelGate({ tools: faces, modelId, depsSeat: deps.toolModelGate, restoreGated: lists.restoreGated, envRaw: process.env.SEMA_TOOL_MODEL_GATE });
const survivors = decision.survivors === undefined ? undefined : new Set(decision.survivors);
return faces.map((face) => ({ face, kept: survivors === undefined || survivors.has(face) }));
}
const entryIdentity = (face) => (face.aliases === undefined ? { name: face.name } : { name: face.name, aliases: face.aliases });
function callerMembers(entries, leaves) {
const rank = (e) => (leaves(entryIdentity(e.face)) ? 3 : 0) + (e.kept === true ? 2 : e.kept === undefined ? 1 : 0);
const byName = new Map();
for (const e of entries) {
const had = byName.get(e.face.name);
if (had === undefined || rank(e) >= rank(had)) {
byName.delete(e.face.name);
byName.set(e.face.name, e);
}
}
return [...byName.values()].map(({ face }) => ({
family: "caller",
identity: entryIdentity(face),
...planIdentityOf(face, callerMountSource(face)),
mountedBy: "scenario",
when: { kept: face.name },
...(face.pathTarget !== undefined ? { pathTarget: face.pathTarget } : {}),
...(entryDelegates(face) ? { delegates: true } : {}),
}));
}
function legFacts(deps, spec) {
const facts = { "runner.self": true, "leg.parentNotify": false, "leg.session": true, "leg.startersWithheld": false };
if (deps.peerDirectory === undefined || deps.mailboxStore === undefined)
facts["leg.peerLane"] = false;
else if (deps.sessionStore !== undefined) {
const verdict = judgePeerLaneMount(deps, spec.sessionId, deps.sessionStore);
if (verdict?.ok !== true)
facts["leg.peerLane"] = false;
else if (spec.sessionId !== undefined)
facts["leg.peerLane"] = true;
}
if (deps.mailboxStore === undefined)
facts["leg.taskNotification"] = false;
return facts;
}
function envFacts(deps) {
if (deps.executionEnvFactory !== undefined)
return deps.executionEnv !== undefined ? { "env.hands": true } : {};
return envMountFacts(deps.executionEnv !== undefined, deps.executionEnv ?? new StubExecutionEnv());
}
function seatFacts(deps, spec, leavesOffloadReader) {
const checkpoint = resolveCheckpointStore(spec, deps) !== undefined;
const hostNotResumable = spec.durableApproval === false;
const offload = offloadSeatFact(offloadThresholdsOf(spec, deps).effective) && leavesOffloadReader;
return {
"seat.checkpoint": checkpoint && !hostNotResumable,
"seat.offload": offload,
"seat.offloadBytes": offload && legBackingStore(deps.toolResultStore, "").bytesOf !== undefined,
...legSeatMountFacts(deps, spec, { parkStore: checkpoint, approvalParkNotResumable: hostNotResumable ? "host" : undefined }),
};
}
function protocolReading(preflight, leavesPeer) {
const families = [];
for (const s of preflight?.mcp ?? []) {
const prefix = mintNamespacePrefix(MCP_NAMESPACE, s.name);
if (!leavesPeer(prefix))
continue;
const writesPath = Object.entries(s.toolFaces ?? {}).some(([tool, face]) => writesProtectedPath([`${prefix}${tool}`], face.pathTarget));
const readsPath = Object.values(s.toolFaces ?? {}).some((face) => face.pathTarget?.access === "read");
families.push({ family: { source: "mcp", peer: s.name, state: "conditional", when: ["listing.mcp"] }, writesPath, ...(readsPath ? { readsPath } : {}) });
}
for (const p of preflight?.a2a ?? [])
if (leavesPeer(mintNamespacePrefix(A2A_NAMESPACE, p.name)))
families.push({ family: { source: "a2a", peer: p.name, state: "conditional", when: ["listing.a2a"] }, writesPath: false });
const members = (preflight?.mcp?.length ?? 0) > 0
? MCP_RESOURCE_FACES.map((name) => ({ family: "mcp-resources", identity: { name }, source: "mcp", mountedBy: "optional", when: { fact: "listing.mcp.resources" } }))
: [];
return { families, members };
}
function wordReading(deps, spec, attachments, mods) {
return {
asks: {
workspace: workspaceDeclared(spec.workspace),
attachment_paths: userAttachmentsNeedWorkspace(attachments),
plan_file: spec.planFile !== undefined,
restore_files: spec.restoreFiles === true || spec.rewindFilesTo !== undefined,
memory: memoryEngineOpens(normalizeMemorySpec(spec.memory), deps),
},
mods: seatsReachEnv(mods.admitted, "engine"),
};
}
export function readLegExecutionEnv(input) {
const tools = input.spec.tools ?? [];
const i = input.internals;
const protocol = protocolReading(input.preflight, input.leavesPeer);
const word = wordReading(input.deps, input.spec, input.userAttachments, input.mods);
const facts = { ...input.facts, ...startersWithheldFact(i) };
const src = {
fact: (f) => facts[f],
valve: input.leaves,
declared: (name, viaAlias) => tools.some((t) => t.name === name || (viaAlias && t.aliases?.includes(name) === true)),
kept: () => true,
retracted: () => undefined,
};
return readExecutionEnv({
src,
members: [...callerMembers(tools.map((face) => ({ face, kept: true })), input.leaves), ...protocol.members],
families: protocol.families,
writeProtected: legWriteProtectionTable(input.deps, input.spec).length > 0,
asks: {
...word.asks,
checkout: input.checkout,
restore: input.resume?.workspaceHandle !== undefined || input.resume?.seed.handsCwd !== undefined,
compaction_restore: input.compactionRestore,
caller_placement: [i?.requestedCwd, i?.isolation, i?.worktreeOffered, i?.placementTarget, i?.callerRoot, i?.callerCheckout].some((v) => v !== undefined),
},
mods: word.mods,
});
}
export function planStaticToolMounts(deps, handed, statement = {}) {
const read = readCallerSpec(handed);
if (read.refusal !== undefined)
throw read.refusal;
const caller = read.spec;
const mode = refusePermissionModeDoors(caller) ?? "default";
const spec = withOwnLegHands(caller);
const moded = withModeSeats(spec, mode);
checkedPlanFileShape(spec.planFile);
const lists = readToolFaceLists(spec);
const selector = readToolSelector({
retiredNames: legRetiredNameView(spec.tools ?? []),
layers: [{ ...(lists.allow !== undefined ? { allow: lists.allow } : {}), deny: lists.exclude ?? [] }],
where: undefined,
legs: spec.outputSchema !== undefined ? ["structured"] : [],
spec,
});
const leaves = valveLeaves(selector);
const preflight = spec.mcp !== undefined || spec.a2a !== undefined ? preflightLockedConfig(spec, deps) : undefined;
const entries = callerEntries(deps, spec, lists);
const protocol = protocolReading(preflight, valveLeavesPeer(selector));
const facts = new Map();
const state = (record) => {
for (const f of TOOL_MOUNT_FACTS) {
const v = record[f];
if (v !== undefined)
facts.set(f, v);
}
};
state(specMountFacts(moded));
state(seatMountFacts(deps, spec));
state(envFacts(deps));
state(legFacts(deps, spec));
state(seatFacts(deps, spec, leaves({ name: OFFLOAD_TOOL_NAME })));
state({ "spec.planFile": spec.planFile !== undefined });
const declared = (name, viaAlias) => anyOf(entries.filter((e) => e.face.name === name || (viaAlias && e.face.aliases?.includes(name) === true)).map((e) => e.kept));
const backgroundAgents = anyOf(entries.filter((e) => delegationHasBackgroundLane(e.face) && leaves(entryIdentity(e.face))).map((e) => e.kept));
if (backgroundAgents !== undefined)
facts.set("leg.backgroundAgents", backgroundAgents);
const skillsSeat = readSkillsSeat(spec.skills);
const src = {
fact: (f) => facts.get(f),
valve: (identity) => leaves(identity),
declared,
kept: (name) => {
const named = entries.filter((e) => e.face.name === name);
const left = named.filter((e) => leaves(entryIdentity(e.face)));
return anyOf((left.length > 0 ? left : named).map((e) => e.kept));
},
retracted: () => undefined,
};
const sessionNew = statement.session === "new" ? false : undefined;
const word = wordReading(deps, spec, screenUserAttachments(spec.userAttachments, { resumeLeg: false }), listLegModSeats({ spec, deps, skills: skillsThatLoad(skillsSeat) }));
const reading = {
src,
members: [...callerMembers(entries, leaves), ...protocol.members],
families: protocol.families,
writeProtected: legWriteProtectionTable(deps, spec).length > 0,
asks: { ...word.asks, checkout: sessionNew, restore: sessionNew, compaction_restore: sessionNew, caller_placement: sessionNew },
mods: word.mods,
};
const executionEnv = readExecutionEnv(reading);
state({ "spec.mcp": (preflight?.mcp?.length ?? 0) > 0 });
state({ "listing.skills": loadedSkills(skillsSeat).length > 0 });
const occupied = (names) => anyOf(names.map((n) => declared(n, true)));
const sharedOccupied = occupied(mountGroupNames("sharedMemory"));
const engineOccupied = occupied(mountGroupNames("memoryEngine"));
if (sharedOccupied !== undefined)
facts.set("names.occupied.sharedMemory", sharedOccupied);
if (engineOccupied !== undefined)
facts.set("names.occupied.memoryEngine", engineOccupied);
return planToolMounts(reading, executionEnv);
}