@sema-agent/core
Version:
Stateless, task-oriented AI agent core
532 lines (531 loc) • 34 kB
JavaScript
import { isPermissionMode } from "./ask-origin.js";
import { failureFields } from "./mcp-failure.js";
import { toolFieldsOfServer } from "./mounted-mcp.js";
import { foreignLine } from "./protocol-http-auth.js";
import { inlineUntrusted } from "./untrusted-text.js";
import { PERMISSION_MODE_FOLD_REASONS } from "./mode-policy.js";
import { FAST_MODE_COOLDOWN_REASONS, FAST_MODE_STATES, FAST_MODE_UNAVAILABLE_REASONS } from "../brain/fast-mode.js";
import { createHash } from "node:crypto";
import { canonicalize } from "./canonical-json.js";
import { resolveCheckpointStore } from "./checkpoint-store.js";
import { isEngineQuestionFace, isLiveQuestionFace } from "./ask-question.js";
import { AUTO_MODE_DENY_SOURCES, isAutoModeDenySource } from "./runtime-caps.js";
import { declaredAnswerClassesOf, isPolicyApprover } from "./tool-policy.js";
import { describeRejectedValue } from "./tool-search-setting.js";
import { RUN_ORIGINS } from "./run-origin.js";
import { engineLaneLegOf } from "./park-resumability.js";
import { planStaticToolMounts } from "./tool-mount-static.js";
import { EXECUTION_ENV_NEEDS } from "./tool-mount-plan.js";
import { enterConfigDoor } from "./config-refusal-input.js";
import { readCallerSpec } from "./task-spec-members.js";
import { PROJECT_MARKER_UNREADABLE_REASONS } from "./memory-engine/scope-contract.js";
import { codedDetailStringOf } from "./runner/terminal-account.js";
import { readLegInstanceFact, receiveHostInstance } from "./host-instance.js";
export function wiringLegKindOf(resumed, internals) {
return resumed ? "resume" : engineLaneLegOf(internals) ? "child" : "root";
}
export const ASK_SEAM_FORMS = Object.freeze(["callback", "policy_callback", "allow", "deny", "absent", "declared_none"]);
export const APPROVAL_REACH = Object.freeze(["none"]);
const APPROVAL_REACH_SET = new Set(APPROVAL_REACH);
export function isApprovalReach(v) {
return APPROVAL_REACH_SET.has(v);
}
export function screenApprovalReach(v) {
if (v === undefined)
return undefined;
if (isApprovalReach(v))
return v;
const e = new Error(`approvalReach ${describeRejectedValue(v)} is not a recognized declaration (${APPROVAL_REACH.map((w) => JSON.stringify(w)).join(" | ")}) — ` +
`omit it when a person may be asked; an unreadable declaration is refused, never folded to either reading.`);
e.code = "config.approval_reach_invalid";
throw e;
}
export const ASK_EFFECTIVE_VALUES = Object.freeze(["human_reachable", "policy_reachable", "auto_allow", "auto_deny", "park_only", "unresolved"]);
const seamInput = (provenance) => (provenance === "spec" ? "taskConfig" : "deps");
export const PARK_LANE_REASONS = Object.freeze(["no_checkpoint_store", "leg_not_resumable", "no_durable_approval_opt_in", "no_force_durable_gate", "no_armed_safety_vocabulary", "await_runtime_caps", "await_tool_vocabulary"]);
export { SUSPEND_LANE_REASONS } from "./suspend-lane-reasons.js";
export const AUTO_MODE_ARM_REASONS = Object.freeze(["armed", "no_intent", "no_face", "denied", "resolver_fault"]);
export const MCP_ENTRY_TOOL_NAMES_MAX = 64;
export const LSP_LANES = Object.freeze(["tool", "diagnostics", "tool_and_diagnostics"]);
export const HANDS_UNMOUNTED_REASONS = Object.freeze(["no_execution_env", "not_needed"]);
export function deriveHandsSeam(handsMounted, skippedFactory) {
return handsMounted ? { mounted: true } : { mounted: false, reason: skippedFactory ? "not_needed" : "no_execution_env" };
}
export const EXECUTION_ENV_SEATS = Object.freeze(["factory", "static", "none"]);
export function executionEnvSeatOf(deps) {
return deps.executionEnvFactory ? "factory" : deps.executionEnv !== undefined ? "static" : "none";
}
export const DEPLOYMENT_ASK_SEAT_FORMS = Object.freeze(ASK_SEAM_FORMS.filter((form) => form !== "declared_none"));
export function interactionSeatsOf(deps) {
const ask = resolveAskSeat({}, deps).form;
return { ask: ask === "declared_none" ? "absent" : ask, question: resolveQuestionSeam({}, deps).wired };
}
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, forcedGate) {
if (mode === "dontAsk")
return "auto_deny";
const own = seatAskEffective(form, parkEffective);
return forcedGate === true ? seatAskEffective("absent", parkEffective) : own;
}
function seatAskEffective(form, parkEffective) {
switch (form) {
case "callback":
return "human_reachable";
case "policy_callback":
return "policy_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":
case "declared_none":
return parkEffective === true ? "park_only" : parkEffective === "unresolved" ? "unresolved" : "auto_deny";
default: {
const _exhaustive = form;
void _exhaustive;
throw new Error(`unreachable ask form ${String(form)}`);
}
}
}
function forcedGateTakesAsks(facts, parkLane) {
return facts.forcedGateNotResumable === true || (facts.parkForceDurableGate === true && parkLane.effective === true);
}
export function askSeatEffective(facts) {
const parkLane = deriveParkLane(facts);
return deriveAskEffective(facts.askForm, askParkOf(facts, parkLane), undefined, forcedGateTakesAsks(facts, parkLane));
}
function askParkOf(facts, parkLane) {
return facts.approvalParkWithheld === true ? false : parkLane.effective;
}
export { APPROVAL_ROUTES, isApprovalRoute } from "./approval-route.js";
export function approvalRouteOf(ask) {
const effective = ask.effective ?? "unresolved";
switch (effective) {
case "human_reachable":
return "live_approver";
case "policy_reachable":
return "policy_seat";
case "park_only":
return "durable_park";
case "auto_allow":
case "auto_deny":
case "unresolved":
return "none";
default: {
const _exhaustive = effective;
void _exhaustive;
throw new Error(`unreachable ask effective ${String(effective)}`);
}
}
}
export function frozenApproverRoute(onAsk) {
return approvalRouteOf({ effective: deriveAskEffective(askSeamFormOf(onAsk) ?? "absent", false) });
}
export function askSeamFormOf(v) {
return typeof v === "function" ? (isPolicyApprover(v) ? "policy_callback" : "callback") : v === "allow" ? "allow" : v === "deny" ? "deny" : v === undefined ? "absent" : undefined;
}
export function reachSetsAside(form) {
return form === "callback";
}
export function approvalParkWithheldOf(leg) {
return leg.member && leg.form === "declared_none";
}
export function callMayTakeParkLane(seatWord, face) {
return seatWord !== "auto_deny" || isEngineQuestionFace(face);
}
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.parkLegNotResumable === true)
return { capable: true, effective: false, reasons: ["leg_not_resumable"], ...durability };
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 readToolPlanFact(plan, half) {
const planHalf = plan.half;
if (planHalf !== half)
throw new Error(`the tool mount plan is the ${JSON.stringify(planHalf)} reading, not the ${JSON.stringify(half)} half's — a plan is published only on the half that read it`);
readWordFact(plan.executionEnv?.state, EXECUTION_ENV_NEEDS, "tool plan's execution-env state");
return plan;
}
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 readFastModeFact(fact) {
const { state, reason, cooldown } = typeof fact === "object" && fact !== null ? fact : { state: undefined, reason: undefined, cooldown: undefined };
const cooldownOk = state === "cooldown"
? typeof cooldown === "object" && cooldown !== null && Number.isFinite(cooldown.until) && FAST_MODE_COOLDOWN_REASONS.includes(cooldown.reason)
: cooldown === undefined;
if (!FAST_MODE_STATES.includes(state) || (reason !== undefined && !FAST_MODE_UNAVAILABLE_REASONS.includes(reason)) || !cooldownOk) {
throw new Error(`the fast-mode wiring fact is inconsistent (${JSON.stringify(fact)}) — state must be one of ${FAST_MODE_STATES.join("|")}, reason one of ${FAST_MODE_UNAVAILABLE_REASONS.join("|")} or absent, cooldown present exactly with the cooldown state`);
}
return { state: state, ...(reason !== undefined ? { reason } : {}), ...(cooldown !== undefined ? { cooldown: { until: cooldown.until, reason: cooldown.reason } } : {}) };
}
function readHandsFact(fact) {
const { mounted, reason } = typeof fact === "object" && fact !== null ? fact : { mounted: undefined, reason: undefined };
if (typeof mounted !== "boolean" || (mounted ? reason !== undefined : !HANDS_UNMOUNTED_REASONS.some((word) => word === reason))) {
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 one of ${HANDS_UNMOUNTED_REASONS.join("|")}`);
}
return mounted ? { mounted } : { mounted, reason };
}
function readWordFact(word, words, label) {
if (!words.includes(word))
throw new Error(`the ${label} wiring fact ${JSON.stringify(word)} is not one of ${words.join("|")}`);
return word;
}
const DECLARED_PLACE_SOURCES = ["deployment", "task", "checkpoint"];
function declaredPlacesSection(fact) {
const list = (sources) => sources.map((from) => ({ from: from.map((w) => readWordFact(w, DECLARED_PLACE_SOURCES, "declared-place source")) }));
const section = {
...(fact.agentConfigDirs.length > 0 ? { agentConfigDirs: list(fact.agentConfigDirs) } : {}),
...(fact.agentHomeDirs.length > 0 ? { agentHomeDirs: list(fact.agentHomeDirs) } : {}),
};
return Object.keys(section).length > 0 ? { declaredPlaces: section } : {};
}
function readInteractionSeatsFact(fact) {
if (typeof fact.question !== "boolean")
throw new Error(`the interaction-seats wiring fact's question seat ${JSON.stringify(fact.question)} is not a boolean`);
return { ask: readWordFact(fact.ask, DEPLOYMENT_ASK_SEAT_FORMS, "deployment approval seat"), question: fact.question };
}
function readSessionRulesFact(fact) {
if (typeof fact !== "boolean")
throw new Error(`the session-rules wiring fact ${JSON.stringify(fact)} is not a boolean`);
return { childrenReadLive: fact };
}
function readProjectFact(fact) {
const { id, source } = typeof fact === "object" && fact !== null ? fact : { id: undefined, source: undefined };
if (typeof id !== "string" || id.length === 0 || (source !== "marker" && source !== "declared")) {
throw new Error(`the project wiring fact is inconsistent (${JSON.stringify(fact)}) — id must be a non-empty string and source "marker"|"declared"`);
}
return { id, source };
}
function readProjectMarkerUnreadableFact(fact) {
const { reason, markerPath } = typeof fact === "object" && fact !== null ? fact : { reason: undefined, markerPath: undefined };
if (typeof reason !== "string" || !PROJECT_MARKER_UNREADABLE_REASONS.includes(reason)) {
throw new Error(`the projectMarkerUnreadable wiring fact is inconsistent (${JSON.stringify(fact)}) — reason must be one of ${PROJECT_MARKER_UNREADABLE_REASONS.join("|")}`);
}
if (reason === "repo_root_unreadable") {
if (markerPath !== undefined) {
throw new Error(`the projectMarkerUnreadable wiring fact is inconsistent (${JSON.stringify(fact)}) — markerPath must be omitted for repo_root_unreadable`);
}
return { reason };
}
if (markerPath !== undefined && (typeof markerPath !== "string" || markerPath.length === 0)) {
throw new Error(`the projectMarkerUnreadable wiring fact is inconsistent (${JSON.stringify(fact)}) — markerPath must be a non-empty string or omitted`);
}
const shown = markerPath !== undefined ? codedDetailStringOf(markerPath) : undefined;
return shown !== undefined ? { reason: reason, markerPath: shown } : { reason: reason };
}
export function deriveWiringManifest(facts) {
if (facts.half === "static" && (facts.leg !== undefined || facts.legInstance !== undefined || facts.runOrigin !== undefined)) {
throw new Error("a static wiring manifest has no leg — leg identity (its kind, its instance and its run origin) 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.");
}
if (facts.forcedGateNotResumable === true && (facts.half !== "effective" || facts.parkLegNotResumable !== true)) {
throw new Error("the wiring facts are inconsistent (forcedGateNotResumable) — the forced gate's refusal stands only on an effective half whose leg cannot be resumed (parkLegNotResumable)");
}
if (facts.half === "effective" && facts.project !== undefined && facts.projectMarkerUnreadable !== undefined) {
throw new Error("the wiring facts are inconsistent (project and projectMarkerUnreadable) — a leg cannot carry both a project verdict and an unreadable-marker fact");
}
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, ...(facts.legInstance !== undefined ? { instance: readLegInstanceFact(facts.legInstance) } : {}), ...(facts.runOrigin !== undefined ? { runOrigin: readWordFact(facts.runOrigin, RUN_ORIGINS, "run origin") } : {}) } } : {}),
...(facts.host !== undefined ? { host: receiveHostInstance(facts.host, "WiringFacts.host") } : {}),
ask: {
form: facts.askForm,
...(facts.askProvenance !== undefined ? { provenance: facts.askProvenance } : {}),
...(facts.half === "effective" ? { effective: deriveAskEffective(facts.askForm, askParkOf(facts, parkLane), facts.permissionMode?.effective, forcedGateTakesAsks(facts, parkLane)) } : {}),
...(facts.askAnsweredClasses !== undefined ? { answeredClasses: facts.askAnsweredClasses } : {}),
},
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,
...(facts.half === "effective" && facts.suspendLaneReasons !== undefined
? {
suspendLane: {
ready: facts.suspendLaneReasons.length === 0,
reasons: [...facts.suspendLaneReasons],
recoverableAcrossProcesses: facts.suspendLaneReasons.length === 0 && facts.checkpointDurability === "durable" && facts.sessionDurability === "durable",
},
}
: {}),
session: { store: manifestDurabilityOf(facts.sessionDurability) },
...(facts.half === "effective" && facts.checkpointStoreWired !== undefined ? { checkpoint: { storeWired: facts.checkpointStoreWired } } : {}),
...(facts.half === "effective" && facts.interactionSeats !== undefined ? { interactionSeats: readInteractionSeatsFact(facts.interactionSeats) } : {}),
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.a2a !== undefined && facts.a2a.length > 0 ? { a2a: facts.a2a.map((e) => ({ ...e })) } : {}),
...(facts.half === "effective" && facts.tools !== undefined ? { tools: facts.tools } : {}),
...(facts.toolPlan !== undefined ? { toolPlan: readToolPlanFact(facts.toolPlan, facts.half) } : {}),
...(facts.half === "effective" && facts.mods !== undefined && facts.mods.length > 0 ? { mods: [...facts.mods] } : {}),
...(facts.half === "effective" && facts.lsp !== undefined ? { lsp: { ...facts.lsp } } : {}),
...(facts.half === "effective" && facts.hands !== undefined ? { hands: readHandsFact(facts.hands) } : {}),
...(facts.half === "effective" && facts.executionEnvSeat !== undefined ? { executionEnvSeat: readWordFact(facts.executionEnvSeat, EXECUTION_ENV_SEATS, "execution-env seat") } : {}),
...(facts.half === "effective" && facts.permissionMode !== undefined ? { permissionMode: readPermissionModeFact(facts.permissionMode) } : {}),
...(facts.half === "effective" && facts.fastMode !== undefined ? { fastMode: readFastModeFact(facts.fastMode) } : {}),
...(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.readDenyFloorUnkept === true ? { readDenyFloor: { kept: false } } : {}),
...(facts.half === "effective" && facts.declaredPlaces !== undefined ? declaredPlacesSection(facts.declaredPlaces) : {}),
...(facts.half === "effective" && facts.autoConsolidationOnRecommendation === true ? { autoConsolidation: { onRecommendation: true } } : {}),
...(facts.half === "effective" && facts.fileHistory !== undefined ? { fileHistory: readWordFact(facts.fileHistory, ["on", "disabled"], "file-history") } : {}),
...(facts.half === "effective" && facts.commandSandbox !== undefined && facts.commandSandbox.state !== "off"
? { commandSandbox: facts.commandSandbox.state === "unavailable" ? { state: "unavailable", reason: facts.commandSandbox.reason } : { state: facts.commandSandbox.state } }
: {}),
...(facts.half === "effective" && facts.projectMemory !== undefined ? { projectMemory: readWordFact(facts.projectMemory, ["on", "disabled", "absent"], "project-memory") } : {}),
...(facts.half === "effective" && facts.sessionRulesChildrenReadLive !== undefined ? { sessionRules: readSessionRulesFact(facts.sessionRulesChildrenReadLive) } : {}),
...(facts.half === "effective" && facts.advisor !== undefined ? { advisor: { ...facts.advisor, ...(facts.advisor.hold !== undefined ? { hold: { ...facts.advisor.hold } } : {}) } } : {}),
...(facts.half === "effective" && facts.hostFloor !== undefined ? { hostFloor: { onlyMode: facts.hostFloor.onlyMode, denyCount: facts.hostFloor.denyCount, onlyCount: facts.hostFloor.onlyCount } } : {}),
...(facts.half === "effective" && facts.project !== undefined ? { project: readProjectFact(facts.project) } : {}),
...(facts.half === "effective" && facts.projectMarkerUnreadable !== undefined ? { projectMarkerUnreadable: readProjectMarkerUnreadableFact(facts.projectMarkerUnreadable) } : {}),
...(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")
manifest.configFingerprint = createHash("sha256").update(canonicalize(deploymentPart(manifest))).digest("hex").slice(0, 16);
return manifest;
}
function deploymentPart(m) {
return {
schemaVersion: m.schemaVersion,
elicit: { seamWired: m.elicit.seamWired },
session: m.session,
fleet: m.fleet,
permissionRules: m.permissionRules,
governance: m.governance,
...(m.checkpoint !== undefined ? { checkpoint: m.checkpoint } : {}),
...(m.interactionSeats !== undefined ? { interactionSeats: m.interactionSeats } : {}),
...(m.executionEnvSeat !== undefined ? { executionEnvSeat: m.executionEnvSeat } : {}),
...(m.readDeny !== undefined ? { readDeny: m.readDeny } : {}),
...(m.autoConsolidation !== undefined ? { autoConsolidation: m.autoConsolidation } : {}),
...(m.hostFloor !== undefined ? { hostFloor: m.hostFloor } : {}),
};
}
export function resolveAskSeat(spec, deps) {
const specValue = spec.onAsk;
const seat = specValue !== undefined ? { value: specValue, provenance: "spec" } : ((v) => (v !== undefined ? { value: v, provenance: "deps" } : undefined))(deps.onAsk);
const reach = screenApprovalReach(spec.approvalReach);
if (seat === undefined)
return Object.freeze(reach === undefined ? { value: undefined, form: "absent" } : { value: undefined, form: "declared_none", reach });
const v = seat.value;
const form = askSeamFormOf(v);
if (form === undefined) {
return enterConfigDoor(seamInput(seat.provenance), () => {
const e = new Error(`the resolved onAsk seat (${seat.provenance}) holds ${describeRejectedValue(v)} — not an OnAsk ` +
`("allow" | "deny" | approver function); refusing to classify it.`);
e.code = "config.interaction_wiring";
throw e;
});
}
if (reach !== undefined && reachSetsAside(form))
return Object.freeze({ value: undefined, form: "declared_none", provenance: seat.provenance, reach });
return Object.freeze({ value: v, form, provenance: seat.provenance, ...(reach !== undefined ? { reach } : {}) });
}
export function resolveAskSeamForm(spec, deps) {
const seat = resolveAskSeat(spec, deps);
const answeredClasses = askAnsweredClassesOf(seat);
return { form: seat.form, ...(seat.provenance !== undefined ? { provenance: seat.provenance } : {}), ...(answeredClasses !== undefined ? { answeredClasses } : {}) };
}
export function askAnsweredClassesOf(seat) {
return declaredAnswerClassesOf(seat.value);
}
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") {
return enterConfigDoor(seamInput(seat.provenance), () => {
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 screenInteractionPostureWord(posture) {
if (posture === undefined || posture === "interactive" || posture === "headless")
return posture;
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;
}
export function describeStaticWiring(deps, handed = {}, statement = {}) {
const read = readCallerSpec(handed);
if (read.refusal !== undefined)
throw read.refusal;
const spec = read.spec;
const host = receiveHostInstance(deps.host, "RunnerDeps.host");
const ask = resolveAskSeamForm(spec, deps);
const question = resolveQuestionSeam(spec, deps);
const checkpointStore = resolveCheckpointStore(spec, deps);
const capable = checkpointStore !== undefined;
return deriveWiringManifest({
half: "static",
...(host !== undefined ? { host } : {}),
askForm: ask.form,
...(ask.provenance !== undefined ? { askProvenance: ask.provenance } : {}),
...(ask.answeredClasses !== undefined ? { askAnsweredClasses: ask.answeredClasses } : {}),
questionWired: question.wired,
...(question.provenance !== undefined ? { questionProvenance: question.provenance } : {}),
...(() => {
const posture = screenInteractionPostureWord(spec.interactionPosture ?? deps.interactionPosture);
return posture === undefined ? {} : { interactionPosture: posture };
})(),
elicitSeamWired: resolveElicitSeam(deps),
elicitServersOptedIn: countElicitOptIns(spec),
parkCapable: capable,
parkLegNotResumable: spec.durableApproval === false,
parkDurableApprovalOptIn: spec.durableApproval !== undefined && spec.durableApproval !== false,
...(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,
toolPlan: planStaticToolMounts(deps, spec, statement),
});
}
export function mcpManifestEntries(entries, statuses, rosterNames) {
return (entries ?? []).map((entry) => {
const status = statuses.find((s) => s.name === entry.name);
const source = typeof entry.source === "string" && entry.source.length > 0 ? { source: inlineUntrusted(entry.source, 80) } : {};
const liveness = status?.liveness !== undefined ? { liveness: { ...status.liveness } } : {};
if (status === undefined)
return { name: entry.name, ...source, status: "skipped", toolCount: 0 };
if (status.status === "connected")
return { name: entry.name, ...source, status: "connected", ...toolFieldsOfServer(rosterNames, entry.name, MCP_ENTRY_TOOL_NAMES_MAX), ...liveness };
if (status.status === "pending")
return { name: entry.name, ...source, status: "pending", toolCount: 0 };
return {
name: entry.name,
...source,
status: "failed",
...liveness,
...failureFields(status),
...(status.error !== undefined ? { error: foreignLine(status.error, 240) } : {}),
toolCount: 0,
};
});
}