@sema-agent/core
Version:
Stateless, task-oriented AI agent core
297 lines (296 loc) • 17.7 kB
JavaScript
import { isPermissionMode } from "./ask-origin.js";
import { PERMISSION_MODE_FOLD_REASONS } from "./mode-policy.js";
import { createHash } from "node:crypto";
import { canonicalize } from "./canonical-json.js";
import { resolveCheckpointStore } from "./checkpoint-store.js";
import { isLiveQuestionFace } from "./ask-question.js";
import { AUTO_MODE_DENY_SOURCES, isAutoModeDenySource } from "./runtime-caps.js";
export const AUTO_MODE_ARM_REASONS = Object.freeze(["armed", "no_intent", "no_face", "denied", "resolver_fault"]);
export const LSP_LANES = Object.freeze(["tool", "diagnostics", "tool_and_diagnostics"]);
export function deriveHandsSeam(handsMounted) {
return handsMounted ? { mounted: true } : { mounted: false, reason: "no_execution_env" };
}
export const LSP_CONTRACT_ID = "core.lsp@1";
export function deriveLspSeam(mounted, diagnosticsLive) {
const lane = mounted ? (diagnosticsLive ? "tool_and_diagnostics" : "tool") : diagnosticsLive ? "diagnostics" : undefined;
return { mounted, ...(lane !== undefined ? { lane } : {}) };
}
export function resolveDeclaredDurability(store, storeName) {
const declared = store?.durability;
if (declared === undefined)
return "process-local";
if (declared === "durable" || declared === "process-local")
return declared;
const e = new Error(`${storeName}.durability declares ${JSON.stringify(declared)} — not a recognized StoreDurability ` +
`("durable" | "process-local"). Fix the declaration; an unparseable durability cannot be folded to either arm.`);
e.code = "config.store_durability_invalid";
throw e;
}
const manifestDurabilityOf = (d) => (d === "durable" ? "declared_durable" : "process_local");
export function resolveSubagentTranscriptTier(agentStoreWired, sessionStore) {
if (!agentStoreWired)
return "none";
const declared = sessionStore?.placements?.subagent?.durability;
if (declared === undefined)
return "rows";
if (declared === "durable")
return "full";
if (declared === "process-local")
return "rows";
const e = new Error(`sessionStore.placements.subagent.durability declares ${JSON.stringify(declared)} — not a recognized ` +
`StoreDurability ("durable" | "process-local"). Fix the declaration; an unparseable durability cannot be folded to either arm.`);
e.code = "config.store_durability_invalid";
throw e;
}
export function deriveAskEffective(form, parkEffective, mode) {
if (mode === "dontAsk")
return "auto_deny";
switch (form) {
case "callback":
return "human_reachable";
case "allow":
return parkEffective === true ? "park_only" : parkEffective === "unresolved" ? "unresolved" : "auto_allow";
case "deny":
return parkEffective === true ? "park_only" : parkEffective === "unresolved" ? "unresolved" : "auto_deny";
case "absent":
return parkEffective === true ? "park_only" : parkEffective === "unresolved" ? "unresolved" : "auto_deny";
default: {
const _exhaustive = form;
void _exhaustive;
throw new Error(`unreachable ask form ${String(form)}`);
}
}
}
export function askSeatEffective(manifest) {
return deriveAskEffective(manifest.ask.form, manifest.parkLane.effective);
}
export function askReachesPerson(ask) {
const effective = ask.effective ?? "unresolved";
switch (effective) {
case "human_reachable":
case "park_only":
return true;
case "auto_allow":
case "auto_deny":
case "unresolved":
return false;
default: {
const _exhaustive = effective;
void _exhaustive;
throw new Error(`unreachable ask effective ${String(effective)}`);
}
}
}
function deriveParkLane(facts) {
if (!facts.parkCapable) {
return { capable: false, effective: false, reasons: ["no_checkpoint_store"] };
}
const durability = facts.checkpointDurability !== undefined ? { checkpointDurability: manifestDurabilityOf(facts.checkpointDurability) } : {};
if (facts.parkDurableApprovalOptIn || facts.parkForceDurableGate === true || facts.parkSafetyVocabularyArmed === true) {
return { capable: true, effective: true, reasons: [], ...durability };
}
const reasons = ["no_durable_approval_opt_in"];
const unresolved = facts.parkForceDurableGate === undefined || facts.parkSafetyVocabularyArmed === undefined;
if (facts.parkForceDurableGate === undefined)
reasons.push("await_runtime_caps");
else
reasons.push("no_force_durable_gate");
if (facts.parkSafetyVocabularyArmed === undefined)
reasons.push("await_tool_vocabulary");
else
reasons.push("no_armed_safety_vocabulary");
return { capable: true, effective: unresolved ? "unresolved" : false, reasons, ...durability };
}
function readAutoModeFact(fact) {
const { armed, reason, deniedSource } = fact;
if (!AUTO_MODE_ARM_REASONS.includes(reason) || armed !== (reason === "armed")) {
throw new Error(`the auto-mode wiring fact is inconsistent (armed=${String(armed)}, reason=${JSON.stringify(reason)}) — armed must hold exactly when reason is "armed", and reason must be one of ${AUTO_MODE_ARM_REASONS.join("|")}`);
}
if (deniedSource !== undefined && (reason !== "denied" || !isAutoModeDenySource(deniedSource))) {
throw new Error(`the auto-mode wiring fact is inconsistent (reason=${JSON.stringify(reason)}, deniedSource=${JSON.stringify(deniedSource)}) — deniedSource may stand only beside reason "denied", as one of ${AUTO_MODE_DENY_SOURCES.join("|")}`);
}
return { armed, reason, ...(deniedSource !== undefined ? { deniedSource } : {}) };
}
function readPermissionModeFact(fact) {
const { requested, effective, foldedBy } = typeof fact === "object" && fact !== null ? fact : { requested: undefined, effective: undefined, foldedBy: undefined };
if (!isPermissionMode(effective) || (requested !== undefined && !isPermissionMode(requested)) || (foldedBy !== undefined && !PERMISSION_MODE_FOLD_REASONS.includes(foldedBy))) {
throw new Error(`the permission-mode wiring fact is inconsistent (${JSON.stringify(fact)}) — effective must be a permission mode, requested one or absent, foldedBy one of ${PERMISSION_MODE_FOLD_REASONS.join("|")} or absent`);
}
return { ...(requested !== undefined ? { requested } : {}), effective, ...(foldedBy !== undefined ? { foldedBy } : {}) };
}
function readHandsFact(fact) {
const { mounted, reason } = typeof fact === "object" && fact !== null ? fact : { mounted: undefined, reason: undefined };
if (typeof mounted !== "boolean" || (mounted ? reason !== undefined : reason !== "no_execution_env")) {
throw new Error(`the hands wiring fact is inconsistent (${JSON.stringify(fact)}) — mounted is a boolean, and reason stands exactly when it is false, as "no_execution_env"`);
}
return mounted ? { mounted } : { mounted, reason };
}
function readFileHistoryFact(word) {
if (word !== "on" && word !== "disabled")
throw new Error(`the file-history wiring fact ${JSON.stringify(word)} is not one of on|disabled`);
return word;
}
export function deriveWiringManifest(facts) {
if (facts.half === "static" && facts.leg !== undefined) {
throw new Error("a static wiring manifest has no leg — leg identity is an effective-half fact");
}
if (facts.half === "effective" && facts.leg === undefined) {
throw new Error("an effective wiring manifest requires its leg kind");
}
if (facts.half === "effective" && (facts.parkForceDurableGate === undefined || facts.parkSafetyVocabularyArmed === undefined)) {
throw new Error("an effective wiring manifest requires the resolved park atoms (parkForceDurableGate, parkSafetyVocabularyArmed) — " +
"`unresolved` is a static-half fact; report the static half instead, or resolve the atoms first.");
}
const parkLane = deriveParkLane(facts);
const questionChannel = facts.questionWired
? "wired"
: facts.half === "effective" && facts.questionStrippedByEngine === true
? "stripped_bg_lane"
: "absent";
const manifest = {
schemaVersion: 1,
...(facts.leg !== undefined ? { leg: { kind: facts.leg } } : {}),
ask: {
form: facts.askForm,
...(facts.askProvenance !== undefined ? { provenance: facts.askProvenance } : {}),
...(facts.half === "effective" ? { effective: deriveAskEffective(facts.askForm, parkLane.effective, facts.permissionMode?.effective) } : {}),
},
question: {
wired: questionChannel,
...(questionChannel === "wired" && facts.questionProvenance !== undefined ? { provenance: facts.questionProvenance } : {}),
...(facts.interactiveToolsWithoutDeliveryFace === true ? { interactiveToolsWithoutDeliveryFace: true } : {}),
},
interaction: { posture: facts.interactionPosture ?? "absent" },
elicit: { seamWired: facts.elicitSeamWired, serversOptedIn: facts.elicitServersOptedIn },
parkLane,
session: { store: manifestDurabilityOf(facts.sessionDurability) },
fleet: {
backgroundAgentStore: facts.backgroundAgentStoreWired,
hostChildEventSink: facts.hostChildEventSinkWired,
subagentTranscripts: facts.subagentTranscriptTier ?? (facts.backgroundAgentStoreWired ? "rows" : "none"),
},
permissionRules: {
storeWired: facts.permissionRuleStoreWired,
syncWired: facts.permissionRuleSyncWired,
orgGoverned: facts.permissionRuleOrgGoverned,
},
governance: {
audience: "operator",
lockedConfig: facts.lockedConfigWired,
compliance: facts.complianceWired,
memoryAdmission: facts.memoryAdmissionWired,
retention: facts.retentionPolicyWired,
},
...(facts.half === "effective" && facts.modelGate !== undefined ? { modelGate: { class: facts.modelGate.class, removed: [...facts.modelGate.removed], restore: facts.modelGate.restore } } : {}),
...(facts.half === "effective" && facts.autoMode !== undefined ? { autoMode: readAutoModeFact(facts.autoMode) } : {}),
...(facts.half === "effective" && facts.mcp !== undefined ? { mcp: facts.mcp.map((e) => ({ ...e })) } : {}),
...(facts.half === "effective" && facts.tools !== undefined ? { tools: facts.tools } : {}),
...(facts.half === "effective" && facts.hooks !== undefined && facts.hooks.length > 0 ? { hooks: facts.hooks.map((h) => ({ ...h })) } : {}),
...(facts.half === "effective" && facts.lsp !== undefined ? { lsp: { ...facts.lsp } } : {}),
...(facts.half === "effective" && facts.hands !== undefined ? { hands: readHandsFact(facts.hands) } : {}),
...(facts.half === "effective" && facts.permissionMode !== undefined ? { permissionMode: readPermissionModeFact(facts.permissionMode) } : {}),
...(facts.half === "effective" && facts.writeProtectionTargetView !== undefined ? { writeProtection: { targetView: facts.writeProtectionTargetView } } : {}),
...(facts.half === "effective" && facts.readDenyBuiltinTiersActive !== undefined && facts.readDenyBuiltinTiersActive.length > 0
? { readDeny: { builtinTiers: [...facts.readDenyBuiltinTiersActive] } }
: {}),
...(facts.half === "effective" && facts.autoConsolidationOnRecommendation === true ? { autoConsolidation: { onRecommendation: true } } : {}),
...(facts.half === "effective" && facts.fileHistory !== undefined ? { fileHistory: readFileHistoryFact(facts.fileHistory) } : {}),
...(facts.half === "effective" && facts.teamRole !== undefined ? { teamRole: facts.teamRole } : {}),
...(facts.half === "effective" && facts.peerPresence !== undefined && (facts.peerPresence.agent !== undefined || facts.peerPresence.intent !== undefined)
? { peerPresence: { ...(facts.peerPresence.agent !== undefined ? { agent: facts.peerPresence.agent } : {}), ...(facts.peerPresence.intent !== undefined ? { intent: facts.peerPresence.intent } : {}) } }
: {}),
};
if (facts.half === "effective") {
const { leg: _leg, mcp: _mcp, tools: _tools, lsp: _lsp, hooks: _hooks, teamRole: _teamRole, peerPresence: _peerPresence, fileHistory: _fileHistory, permissionMode: _permissionMode, ...assembly } = manifest;
const { provenance: _askSeat, ...askForHash } = assembly.ask;
const { provenance: _questionSeat, ...questionForHash } = assembly.question;
manifest.configFingerprint = createHash("sha256")
.update(canonicalize({ ...assembly, ask: { ...askForHash, effective: deriveAskEffective(facts.askForm, parkLane.effective) }, question: questionForHash }))
.digest("hex")
.slice(0, 16);
}
return manifest;
}
export function resolveAskSeamForm(spec, deps) {
const seat = spec.onAsk !== undefined ? { value: spec.onAsk, provenance: "spec" } : deps.onAsk !== undefined ? { value: deps.onAsk, provenance: "deps" } : undefined;
if (seat === undefined)
return { form: "absent" };
const v = seat.value;
const form = typeof v === "function" ? "callback" : v === "allow" ? "allow" : v === "deny" ? "deny" : undefined;
if (form === undefined) {
const e = new Error(`the resolved onAsk seat (${seat.provenance}) holds ${JSON.stringify(v)} — not an OnAsk ` +
`("allow" | "deny" | approver function); refusing to classify it.`);
e.code = "config.interaction_wiring";
throw e;
}
return { form, provenance: seat.provenance };
}
export function resolveQuestionSeam(spec, deps) {
const seat = spec.onQuestion !== undefined ? { value: spec.onQuestion, provenance: "spec" } : deps.onQuestion !== undefined ? { value: deps.onQuestion, provenance: "deps" } : undefined;
if (seat === undefined)
return { wired: false };
if (typeof seat.value !== "function") {
const e = new Error(`the resolved onQuestion seat (${seat.provenance}) holds ${seat.value === null ? "null" : typeof seat.value} — not an OnQuestion ` +
`callback; refusing to report it as a wired question channel (omit the key, or wire a function).`);
e.code = "config.interaction_wiring";
throw e;
}
if (!isLiveQuestionFace(seat.value))
return { wired: false };
return { wired: true, provenance: seat.provenance };
}
export function countElicitOptIns(spec) {
return (spec.mcp ?? []).filter((s) => s.elicitation === true).length;
}
export function resolveElicitSeam(deps) {
if (deps.onElicit === undefined)
return false;
if (typeof deps.onElicit !== "function") {
const e = new Error(`RunnerDeps.onElicit holds ${deps.onElicit === null ? "null" : typeof deps.onElicit} — not an OnElicit ` +
`callback; refusing to report it as a wired elicitation seam (omit the key, or wire a function).`);
e.code = "config.interaction_wiring";
throw e;
}
return true;
}
export function describeStaticWiring(deps, spec = {}) {
const ask = resolveAskSeamForm(spec, deps);
const question = resolveQuestionSeam(spec, deps);
const checkpointStore = resolveCheckpointStore(spec, deps);
const capable = checkpointStore !== undefined;
return deriveWiringManifest({
half: "static",
askForm: ask.form,
...(ask.provenance !== undefined ? { askProvenance: ask.provenance } : {}),
questionWired: question.wired,
...(question.provenance !== undefined ? { questionProvenance: question.provenance } : {}),
...(() => {
const posture = spec.interactionPosture ?? deps.interactionPosture;
if (posture === undefined)
return {};
if (posture !== "interactive" && posture !== "headless") {
const e = new Error(`interactionPosture ${JSON.stringify(posture)} is not a recognized posture ("interactive" | "headless") — ` +
`an unevaluable declaration is refused loudly, never folded to either posture (or to absent).`);
e.code = "config.interaction_posture";
throw e;
}
return { interactionPosture: posture };
})(),
elicitSeamWired: resolveElicitSeam(deps),
elicitServersOptedIn: countElicitOptIns(spec),
parkCapable: capable,
parkDurableApprovalOptIn: spec.durableApproval !== undefined,
...(capable ? { checkpointDurability: resolveDeclaredDurability(checkpointStore, "checkpointStore") } : {}),
sessionDurability: resolveDeclaredDurability(deps.sessionStore, "sessionStore"),
backgroundAgentStoreWired: deps.backgroundAgentStore !== undefined,
subagentTranscriptTier: resolveSubagentTranscriptTier(deps.backgroundAgentStore !== undefined, deps.sessionStore),
permissionRuleStoreWired: deps.permissionRuleStore?.partitions.durable === true,
permissionRuleSyncWired: deps.permissionRuleSyncWired === true,
permissionRuleOrgGoverned: deps.permissionRuleStore?.partitions.org === true,
hostChildEventSinkWired: deps.onBackgroundChildEvent !== undefined,
lockedConfigWired: deps.lockedConfig !== undefined,
complianceWired: deps.compliancePostureResolver !== undefined,
memoryAdmissionWired: deps.memoryScopeAdmission !== undefined,
retentionPolicyWired: deps.retentionPolicy !== undefined,
});
}