@sema-agent/core
Version:
Stateless, task-oriented AI agent core
297 lines (296 loc) • 20.8 kB
JavaScript
import { forkGovernanceDenial, resolveDelegationEntryCaps } from "../../agents/subagent.js";
import { isLiveQuestionFace } from "../ask-question.js";
import { parentSpecSeatOf } from "../parent-spec-seat.js";
import { createPreToolUseConstraintPolicy } from "../hooks.js";
import { chainJudges, sameInstallation } from "../mods/stations.js";
import { childClampSeats, clampSourceOf } from "../child-clamp-seats.js";
import { continuesLineage } from "../session-policy-store.js";
import { StubExecutionEnv } from "../stub-env.js";
import { durableMandateSourceOf } from "../tool-policy.js";
import { chainAnchorRecords } from "./child-tree.js";
import { deliverEngineNotice } from "../types.js";
import { PermissionModeController, autoModeFaceOf, modeRequestAfterResume } from "../mode-policy.js";
import { SessionModeSeats } from "./session-mode-seats.js";
import { recordedModeSeed } from "../checkpoint-store.js";
import { frozenSkillGrants } from "../skill-grant.js";
import { attachRebuiltDenialTrackers, createDenialLimitStop } from "./denial-limit-arms.js";
import { valveLeaves } from "../../agents/tool-filter.js";
export function prepareInheritedGate(input) {
const { spec, deps, askSeat, internals, resume, sessions, sessionId, runId, hostTaskId, taskRootFinal, executionEnv, ownedEnv, lockedPreflight, pathRuleAnchors, toolFaceSnapshot, mountsCallerTool, promptProfile, resolvedInteractionPosture, permissionModeSeat, handsEnabled, reportUsage, harnessRef, skillGrants, forwardEvent, subagentRetain, worktreeIsolation, requestReview, requestStopAfterTurn, enterPlanMode, reminderMark, reminderDisclosureCounts, fileHistoryEnabled, historyScope, historyRoot, historyFs, abortRun } = input;
const liveInheritedGate = internals?.inheritedGate;
const seedInheritedGate = resume?.seed.inheritedGate;
const inheritedAncestorRules = (() => {
const seedRules = seedInheritedGate?.ancestorRules;
const liveRules = liveInheritedGate?.ancestorRules;
if (seedRules === undefined || seedRules.length === 0) {
const only = liveRules ?? seedRules;
return only === undefined ? undefined : [...only];
}
if (liveRules === undefined || liveRules.length === 0)
return [...seedRules];
const merged = seedRules.map((s) => {
const live = liveRules.find((l) => l.sessionId === s.sessionId && l.principal === s.principal);
const sameLineage = live === undefined || continuesLineage(live, s);
return live !== undefined && sameLineage && live.rev >= s.rev ? live : s;
});
const extras = liveRules.filter((l) => !seedRules.some((s) => s.sessionId === l.sessionId && s.principal === l.principal));
return [...merged, ...extras];
})();
const modeSeed = recordedModeSeed(seedInheritedGate);
const inheritedShellGate = liveInheritedGate?.shellGate ?? modeSeed.shellGate;
const askView = askSeat.reach === "none" ? liveInheritedGate?.parentConstraints?.map((pc) => (typeof pc.onAsk === "function" ? ((({ onAsk: _person, ...rest }) => rest)(pc)) : pc)) : liveInheritedGate?.parentConstraints;
const chainView = askView?.map((pc, position) => {
const policy = pathRuleAnchors.onLeg(pc.policy, position);
return policy === pc.policy ? pc : { ...pc, policy };
});
const autoModeFace = autoModeFaceOf(deps, liveInheritedGate);
const inheritedParentConstraints = attachRebuiltDenialTrackers(chainView, autoModeFace?.denialLimit);
const parentSeat = liveInheritedGate?.permissionModeCeiling;
const ceiling = parentSeat ?? liveInheritedGate?.permissionMode;
const announceModeFold = (receipt, folded) => {
if (receipt.foldedBy === undefined)
return;
const because = receipt.foldedBy === "operator_deny" ? "the deployment denies it for this principal" : receipt.foldedBy === "face_absent" ? "no auto-mode classifier face is wired on this deployment" : `the parent leg's mode is the ceiling a child's declaration is clamped under`;
const message = `permission mode "${folded}"${receipt.requested === undefined ? " (inherited)" : ""} is not available on this leg (${because}) — it runs under "${receipt.effective}"`;
deliverEngineNotice(deps.onNotice, { code: "config.permission_mode_unavailable", message, detail: { requested: folded, effective: receipt.effective, by: receipt.foldedBy, sessionId, runId } });
if (parentSeat !== undefined) {
deliverEngineNotice(deps.onNotice, { code: "config.permission_mode_unavailable", message: `${message} (a child leg, ${sessionId})`, detail: { requested: folded, effective: receipt.effective, by: receipt.foldedBy, sessionId: parentSeat.sessionId, childSessionId: sessionId, runId } });
}
};
const permissionMode = new PermissionModeController(modeRequestAfterResume(permissionModeSeat, modeSeed, resume?.outcome), ceiling, { onFold: announceModeFold, ...(modeSeed.prePlanMode !== undefined ? { prePlanMode: modeSeed.prePlanMode } : {}) });
permissionMode.announceStart();
const { ceiling: legModeCeiling, commit: commitLegModeCeiling, end: endModeCeiling } = (internals?.sessionModeSeats ?? new SessionModeSeats()).legCeiling(sessionId, permissionMode);
const commitModeSeats = (legSignal) => {
commitLegModeCeiling();
parentSeat?.hold?.(permissionMode, legSignal);
};
const liveAdmittedOrg = liveInheritedGate?.admittedOrgScopes;
const seedAdmittedOrg = seedInheritedGate?.admittedOrgScopes;
const inheritedAdmittedOrgScopes = liveAdmittedOrg === undefined ? seedAdmittedOrg : seedAdmittedOrg === undefined ? liveAdmittedOrg : liveAdmittedOrg.filter((s) => seedAdmittedOrg.includes(s));
const inheritedOrgGoverned = liveInheritedGate?.orgAdmissionGoverned === true || seedInheritedGate?.orgAdmissionGoverned === true;
const checkpointOwnOrgVerdict = resume?.seed.inheritedGate?.ownAdmittedOrgScopes !== undefined
? { scopes: resume.seed.inheritedGate.ownAdmittedOrgScopes, writeScope: resume.seed.inheritedGate.ownAdmittedOrgWriteScope ?? null }
: undefined;
const refOwnOrgVerdict = internals?.ownOrgAdmissionRef?.current;
const priorOwnOrgVerdict = checkpointOwnOrgVerdict === undefined
? refOwnOrgVerdict
: refOwnOrgVerdict === undefined
? checkpointOwnOrgVerdict
: {
scopes: checkpointOwnOrgVerdict.scopes.filter((sc) => refOwnOrgVerdict.scopes.includes(sc)),
writeScope: checkpointOwnOrgVerdict.writeScope !== null && checkpointOwnOrgVerdict.writeScope === refOwnOrgVerdict.writeScope
? checkpointOwnOrgVerdict.writeScope
: null,
};
const orgGovernedProvenance = deps.memoryScopeAdmission !== undefined ||
(deps.deploymentMemoryScopes !== undefined && deps.deploymentMemoryScopes.length > 0) ||
deps.compliancePostureResolver !== undefined ||
inheritedOrgGoverned ||
priorOwnOrgVerdict !== undefined;
const effectiveShellGate = spec.shellGate ?? inheritedShellGate;
const ownSessionRulesRef = {};
const ancestorSessionRulesRef = { current: new Map() };
const ancestorRulesNow = () => inheritedAncestorRules === undefined ? undefined : inheritedAncestorRules.map((a, i) => ancestorSessionRulesRef.current.get(i) ?? a);
const memoryAdmittedOrgScopesRef = { current: [] };
const ownOrgVerdictRef = { current: undefined };
const faceCheckpointSection = () => {
const resolvedReadFace = input.resolvedReadFace();
const handsLessResolvedFace = input.handsLessResolvedFace();
const readDenyAdditionsNormalized = input.readDenyAdditionsNormalized();
if (resolvedReadFace === undefined && resume !== undefined) {
const seed = resume.seed.readFace;
if (seed === undefined)
return undefined;
return { face: handsLessResolvedFace ?? seed.face, ...(seed.denyEntries !== undefined ? { denyEntries: seed.denyEntries.map((e) => ({ ...e })) } : {}) };
}
const face = resolvedReadFace ?? handsLessResolvedFace;
if (face === undefined)
return undefined;
if (face === "open" || readDenyAdditionsNormalized.length > 0) {
return { face, ...(readDenyAdditionsNormalized.length > 0 ? { denyEntries: readDenyAdditionsNormalized.map((e) => ({ ...e })) } : {}) };
}
return undefined;
};
const writeFaceCheckpointSection = () => {
const seat = input.resolvedWriteFace() ?? input.handsLessResolvedWriteFace();
return seat === undefined ? undefined : seat.inForce() === "open" ? { face: "open" } : seat.fenced ? { face: "roots" } : undefined;
};
const skillGrantCheckpointSection = () => frozenSkillGrants(skillGrants);
const frozenOnAsk = askSeat.value;
const hookEnvSource = (ownedEnv ?? deps.executionEnv) != null ? executionEnv : undefined;
const frozenOnQuestion = spec.onQuestion ?? deps.onQuestion;
const parentSpecSeat = parentSpecSeatOf(spec, frozenOnQuestion);
const provenanceForChildrenRef = {};
const delegationProvenanceForChildren = () => provenanceForChildrenRef.current;
const delegationSettlementRef = {};
const delegationSettlementForChildren = () => delegationSettlementRef.current;
const inheritedGateForChildren = () => {
const autoModeDecider = permissionMode.current === "auto" ? input.autoModeDecider() : undefined;
const autoModeDenialTracking = input.autoModeDenialTracking();
const autoModeArming = input.autoModeArming();
const ancestorRules = [
...(ancestorRulesNow() ?? []),
...(ownSessionRulesRef.current !== undefined ? [ownSessionRulesRef.current] : []),
];
const ownCallerPolicy = lockedPreflight.toolPolicy;
const durableMandate = durableMandateSourceOf({ forceDurableGate: input.runtimeCaps()?.forceDurableGate === true, durableApprovalDeclared: spec.durableApproval !== undefined, onAsk: frozenOnAsk }) !== undefined;
const contentMandate = input.runtimeCaps()?.forceDurableGate === true ||
(spec.durableApproval !== undefined && !isLiveQuestionFace(frozenOnQuestion));
const ownInstallation = { chain: input.ownModChain, onAsk: frozenOnAsk, durableMandate, contentMandate, hookEnv: hookEnvSource, decider: autoModeDecider };
const hookConstraint = chainJudges(input.modBus) && !(inheritedParentConstraints ?? []).some((pc) => sameInstallation(pc, ownInstallation))
? [
{
policy: createPreToolUseConstraintPolicy(input.modBus, input.hookEnvFace()),
mods: input.ownModChain,
...(hookEnvSource !== undefined ? { hookEnv: hookEnvSource } : {}),
...(frozenOnAsk !== undefined ? { onAsk: frozenOnAsk } : {}),
...(durableMandate ? { durableMandate: true } : {}),
...(contentMandate ? { contentMandate: true } : {}),
...(autoModeDecider !== undefined
? { autoMode: { decider: autoModeDecider, ...(autoModeDenialTracking !== undefined ? { denialTracking: autoModeDenialTracking } : {}), ...(autoModeArming !== undefined ? { arming: autoModeArming } : {}), liveMode: legModeCeiling } }
: {}),
},
]
: [];
const parentConstraints = [
...(inheritedParentConstraints ?? []),
...hookConstraint,
...(ownCallerPolicy !== undefined
? [
{
policy: ownCallerPolicy,
...(frozenOnAsk !== undefined ? { onAsk: frozenOnAsk } : {}),
...(durableMandate ? { durableMandate: true } : {}),
...(contentMandate ? { contentMandate: true } : {}),
...(autoModeDecider !== undefined
? { autoMode: { decider: autoModeDecider, ...(autoModeDenialTracking !== undefined ? { denialTracking: autoModeDenialTracking } : {}), ...(autoModeArming !== undefined ? { arming: autoModeArming } : {}), liveMode: legModeCeiling } }
: {}),
},
]
: []),
];
return {
...(ancestorRules.length > 0 ? { ancestorRules } : {}),
...(effectiveShellGate !== undefined ? { shellGate: effectiveShellGate } : {}),
permissionMode: permissionMode.current,
permissionModeCeiling: legModeCeiling,
...(autoModeFace !== undefined ? { autoModeFace } : {}),
...(parentConstraints.length > 0 ? { parentConstraints } : {}),
...chainAnchorRecords(pathRuleAnchors.chainTop, parentConstraints),
admittedOrgScopes: memoryAdmittedOrgScopesRef.current,
...(orgGovernedProvenance ? { orgAdmissionGoverned: true } : {}),
};
};
const carrierReadFace = () => input.resolvedReadFace() ?? input.handsLessResolvedFace();
const carrierWriteFace = () => (input.resolvedWriteFace() ?? input.handsLessResolvedWriteFace())?.inForce();
const runClampSource = () => ({
...clampSourceOf(spec, "clamp"),
readFace: carrierReadFace(),
writeFace: carrierWriteFace(),
readDenyPatterns: input.readDenyAdditionsNormalized(),
approvalReach: askSeat.reach,
});
const fullShellReachable = handsEnabled &&
!(executionEnv instanceof StubExecutionEnv) &&
spec.handsReadOnly !== true &&
valveLeaves(spec, toolFaceSnapshot.selector)({ name: "Bash" });
const { gateStopRef, stopForDenialLimit } = createDenialLimitStop({ sessionId, runId, onNotice: deps.onNotice, abort: abortRun });
const delegationEntryCapsResolved = resolveDelegationEntryCaps(deps.delegationEntryCaps);
const enrichSpecToolCtx = (ctx) => {
const agentForkDenial = input.agentForkDenial();
const observersActive = input.observersActive();
const autoModeDecider = input.autoModeDecider();
const centerAdoption = input.centerAdoption();
return {
...ctx,
delegationEntryCaps: delegationEntryCapsResolved,
reportUsage,
model: harnessRef.current?.getModel(),
modelRef: harnessRef.current?.getModelRef(),
thinkingLevel: harnessRef.current?.getThinkingLevel(),
principal: spec.principal,
...(frozenOnAsk !== undefined ? { onAsk: frozenOnAsk } : {}),
...childClampSeats(runClampSource()),
...(frozenOnQuestion !== undefined ? { onQuestion: frozenOnQuestion } : {}),
oneShot: spec.oneShot,
mountsCallerTool,
...(input.mountedMcp !== undefined ? { mountedMcp: input.mountedMcp } : {}),
parentSpecSeat,
...(internals?.questionFaceStripped === true ? { questionFaceStripped: true } : {}),
toolSelector: toolFaceSnapshot.selector,
deferTools: toolFaceSnapshot.defer,
alwaysLoadTools: toolFaceSnapshot.alwaysLoad,
...(toolFaceSnapshot.restoreGated !== undefined ? { restoreGatedTools: toolFaceSnapshot.restoreGated } : {}),
promptProfile,
...(spec.memoryPersistenceCapable !== undefined ? { memoryPersistenceCapable: spec.memoryPersistenceCapable } : {}),
get memoryCaptureOptedOut() {
return input.memoryEngineSession()?.captureOptOut?.optedOut() ?? false;
},
get memoryCaptureIndeterminate() {
return input.memoryEngineSession()?.captureOptOut?.indeterminate() ?? false;
},
get memoryCaptureControlDir() {
return input.memoryEngineSession()?.engine.controlPlaneDir;
},
get memoryCaptureAncestors() {
const ctl = input.memoryEngineSession()?.engine.controlPlaneDir;
return [...(internals?.memoryCaptureAncestors ?? []), { sessionId, ...(ctl !== undefined ? { controlDir: ctl } : {}) }];
},
getApiKeyAndHeaders: spec.getApiKeyAndHeaders,
parentCwd: taskRootFinal,
...(fileHistoryEnabled ? { fileHistoryLineage: { scope: historyScope, root: historyRoot, fs: historyFs } } : {}),
reminderMark,
reminderDisclosureCounts,
...(centerAdoption !== undefined ? { centerArtifactDigest: centerAdoption.artifact.artifactDigest } : {}),
...(centerAdoption?.sourceRevision !== undefined ? { centerSourceRevision: centerAdoption.sourceRevision } : {}),
activeSkillGrants: () => skillGrants.records(),
activeRequestAllowedTools: () => input.requestAllowedTools.entries(),
inheritedGateForChildren,
delegationProvenanceForChildren,
delegationSettlement: delegationSettlementForChildren,
...(autoModeDecider ? { autoModeReview: { decider: autoModeDecider } } : {}),
...(spec.durableApproval !== undefined ? { durableApprovalForChildren: { ...spec.durableApproval } } : {}),
...(input.checkpointSeat !== undefined ? { checkpointStoreForChildren: input.checkpointSeat } : {}),
checkpointScopeForChildren: input.checkpointScope,
taskId: hostTaskId,
...(internals?.parentTaskId !== undefined ? { parentTaskId: internals.parentTaskId } : {}),
...(internals?.parentSessionId !== undefined ? { parentSessionId: internals.parentSessionId } : {}),
...(internals?.rootSessionId !== undefined ? { rootSessionId: internals.rootSessionId } : {}), ...(internals?.placementRoot !== undefined ? { placementRoot: internals.placementRoot } : {}),
...(internals?.explicitAgentName !== undefined ? { spawnedAgentName: internals.explicitAgentName } : {}),
...(internals?.peerSelfRef !== undefined ? { peerSelfRef: internals.peerSelfRef } : {}),
...(internals?.peerInboundChainRef !== undefined ? { peerInboundChainRef: internals.peerInboundChainRef } : {}),
...(deps.rosterStore !== undefined ? { roster: deps.rosterStore } : {}),
...(sessions.fork !== undefined
? {
hostSessionFork: async () => {
const forked = (await sessions.fork(sessionId, spec.principal ?? null)) ?? null;
if (forked === null)
return null;
return {
sessionId: forked,
release: async () => {
await sessions.release?.(forked);
},
};
},
}
: {}),
sessionId,
...(spec.backgroundScope !== undefined ? { backgroundScope: spec.backgroundScope } : {}),
...(resolvedInteractionPosture !== undefined ? { interactionPosture: resolvedInteractionPosture } : {}),
...(deps.onBackgroundChildEvent ? { onBackgroundChildEvent: deps.onBackgroundChildEvent } : {}),
...(internals?.onTaskNotification ? { onTaskNotification: internals.onTaskNotification } : {}),
...(forwardEvent ? { forwardEvent } : {}),
...(internals?.onSubagentSpawn ? { onSubagentSpawn: internals.onSubagentSpawn } : {}),
...(subagentRetain ? { subagentRetain } : {}),
...(worktreeIsolation ? { worktreeIsolation } : {}),
...(internals?.insideFork === true ? { insideFork: true } : {}),
...(agentForkDenial !== undefined ? { forkAccess: { denied: agentForkDenial } } : {}),
...(observersActive ? { observersAllowed: true } : {}),
requestReview,
requestStopAfterTurn,
...(spec.enablePlanMode === true ? { enterPlanMode } : {}),
};
};
return { liveInheritedGate, seedInheritedGate, inheritedAncestorRules, inheritedShellGate, inheritedParentConstraints, permissionMode, commitModeSeats, endModeCeiling, inheritedAdmittedOrgScopes, priorOwnOrgVerdict, orgGovernedProvenance, effectiveShellGate, ownSessionRulesRef, ancestorSessionRulesRef, ancestorRulesNow, memoryAdmittedOrgScopesRef, ownOrgVerdictRef, runClampSource, faceCheckpointSection, writeFaceCheckpointSection, skillGrantCheckpointSection, frozenOnAsk, hookEnvSource, frozenOnQuestion, parentSpecSeat, provenanceForChildrenRef, delegationSettlementRef, inheritedGateForChildren, carrierReadFace, carrierWriteFace, fullShellReachable, gateStopRef, stopForDenialLimit, enrichSpecToolCtx };
}