@sema-agent/core
Version:
Stateless, task-oriented AI agent core
795 lines • 63.4 kB
JavaScript
import { argsAsTheToolReads, withArgsReading } from "../effective-path-target.js";
import { readBoundaryRefusalOver } from "./read-block-judge.js";
import { outletAsk, readRejudge, rewriteChasedSentence, sameBytes } from "../rewrite-rejudge.js";
import { policyAskClassOf } from "../ask-class.js";
import { ASK_USER_QUESTION_TOOL_NAME, isEngineQuestionFace } from "../ask-question.js";
import { unavailableLandingOf } from "../unavailable-landing.js";
import { heldWhileClassifying } from "../auto-mode.js";
import { classifierUnavailableSeat } from "./classifier-ladder.js";
import { resolveCheckpointStore } from "../checkpoint-store.js";
import { chainJudges, inheritedInstallations, standsInFor } from "../mods/stations.js";
import { createHookEnvCapabilities } from "../hooks.js";
import { isCoveringRuleName, ruleNameCovers } from "../namespaced-rule-name.js";
import { isIsolated } from "../remote-env.js";
import { deliverEngineNotice } from "../engine-notice.js";
import { earlierGrammarNoticeSeat } from "./earlier-grammar-notice.js";
import { attest, attestationOf, checkToolPolicyProjection, combinePolicies, createTranscriptIntegrityPolicy, createUnverifiableDeletePolicy, durableParkOptInDeclared, isAnsweringSeat, mergeAttestation, refuseOutOfContractDecision, resolveAskFor, toolPolicyNameSets, withAttestation, wrapApprover, wrapToolPolicy } from "../tool-policy.js";
import { notResumableClause, notResumableRefusal } from "../park-resumability.js";
import { callUnderView, judgePolicyEntryName, mountedToolNames } from "../tool-name-aliases.js";
import { policyUnderRetiredView, retiredContentRefusal, tellReadAsSuccessor } from "./retired-name-policy.js";
import { approvalCardMemberOf } from "../tool-roster.js";
import { existingTargetOf } from "../existing-target.js";
import { NAMESPACED_NAME_SHAPES } from "../caller-tool-name.js";
import { emitTrace } from "../trace.js";
import { skillGrantBindingMembers } from "../skill-grant.js";
import { withArgsBinding } from "../skill-grant-binding.js";
import { SKILL_TOOL_NAME } from "./synthetic-tools.js";
import { delegationPoolReading, policyNameRefusal } from "./sub-agent-deny-lists.js";
import { POLICY_NAME_REFUSAL_CODE, retiredToolNameNotice } from "../retired-tool-name-account.js";
import { UNMATCHED_TOOL_NAMES_CODE } from "../unmatched-tool-names.js";
import { valveLeaves } from "../../agents/tool-filter.js";
import { allowRuleShadowOf, autoStripReasonOfRow, cardDisclosureOf, classifiesAllShell, inheritedAskFallbackMessage, rootFacingToolNames } from "../allow-entry.js";
import { ruleSourceOf } from "../permission-rule-provider.js";
import { allowMayClearOn, arbitrateByMode, askClassMembersOf, boundGrantMayClear, askFaceOf, askMandateMember, classifyAsk, INHERITED_STATION_FACTS, withFoldedOf } from "../ask-origin.js";
import { acceptEditsWriteGate, createModeGatePolicy, mountedToolDeclaresReadOnly } from "../mode-policy.js";
import { applyPersistedTightening, disclosedRuleSet } from "../persisted-rule-arms.js";
import { readPersistedRuleLane } from "../rule-lane-reads.js";
import { a2aInsidePeerReader, boundStoredGrantOf, standsOnWholePeerRow } from "../a2a-bound-grant.js";
import { floatedInheritedAsk, headlessDenyAtFold, headlessDenyAtRecheck, inheritedAskCarry, judgeInheritedClassifier, lateAskSettlementObserver, resolveInheritedAsk, settleDenialLimitFallback } from "./denial-limit-arms.js";
import { deferredAskOf, liftMark, markCall, standingOf, stationLook, stationMarkOf, windowMarkOf } from "./deferred-ask.js";
import { approverDefectAnnouncer } from "./approver-defect-announcer.js";
import { settleReadRootGrant } from "./read-root-grant.js";
import { frozenApproverRoute } from "../wiring-manifest.js";
import { askGrantShapeOf } from "./inherited-ask-grants.js";
import { createPermissionRuleLanes, inheritedAskRuleEvidence, createRuleOffersOf } from "./permission-rule-lanes.js";
import { createCallGrantDoorOf, settleUnofferedSessionCallGrant } from "./session-call-grant-station.js";
import { callGrantAdmits } from "../session-call-grant.js";
import { createLiveSessionRules, createSessionRulePolicy } from "./session-rule-policy.js";
import { policyThrowLine, reportPolicyThrow } from "./policy-throw.js";
import { heldBy, heldValues, seatOf, wireOf } from "../tool-name-readings.js";
import { startedShellOfCall } from "../call-shell.js";
import { hostFloorPolicy } from "../host-floor.js";
import { leavesByEscape } from "../command-sandbox.js";
import { deploymentBagOf } from "./model-lane-seat.js";
import { releasedReadRowWriteLayers } from "../released-read-row-write-policy.js";
export async function preparePolicyChain(input) {
const { destinationOf, spec, deps, sessionId, ruleSessionId, ruleSessionInTree, runId, hostTaskId, approvalWords, engineText, taskRootFinal, additionalRootsCanonical, writeLocation, executionEnv, lockedPreflight, pathRuleAnchors, headLeads, tools, harnessTools, selector, toolEffects, egressTools, irreversibilityTier, axisExplicitNegatives, shellGatedTools, toolMarkSources, envHandToolNames, handsCwdRef, readDenyMatcher, readBlockJudge, personRows, questionToolMounted, runtimeCaps, approvalParkNotResumable, notResumableSays, forcedGateNotResumable, inheritedAncestorRules, ancestorSessionRulesRef, inheritedParentConstraints, inheritedRuleBuckets, seedInheritedGate, skillGrants, skillSpecs, allowedToolTables, frozenOnAsk, hookEnvSource, notifyOwnHookCrash, modBus, ownModChain, autoModeDecider, whileHeld, readFace, permissionMode, autoStripNotice, toolRosterDeltas, stopForDenialLimit, askSource, parkRouteOf, abortController, now, ownSessionRulesRef, hostFloor, commandSandboxSideOf, sandboxPlanOf } = input;
const ancestorArbitrations = new Map(), ancestorRuleClears = new Map();
const ancestorFacts = (ask, call) => withFoldedOf({ ...(ask ?? {}), ...(ruleSessionInTree ? {} : { ancestorResolved: true }) }, attestationOf(ask, call));
const judgeHeld = (opts) => judgeInheritedClassifier({ ...opts, autoMode: opts.autoMode === undefined ? undefined : { ...opts.autoMode, decider: heldWhileClassifying(opts.autoMode.decider, (toolCallId, judge) => whileHeld(toolCallId, "classifier", judge)) } });
const heldApprover = (onAsk) => wrapApprover(onAsk, (inner) => (req, signal) => whileHeld(req.toolCallId, "approval", () => inner(req, signal)));
const unreadCardTarget = (toolName, args) => existingTargetOf(toolRosterDeltas.current, toolName, args, undefined);
const arbitrateInherited = (ask, call, judged) => {
const verdict = arbitrateByMode(permissionMode.current, judged.classification, { origin: judged.origin, ...askMandateMember(ancestorFacts(judged.ask.action === "ask" ? judged.ask : undefined, call), seatMandateMarksOf(call)) });
if (verdict.kind === "ask" || verdict.kind === "accepted")
return undefined;
ancestorArbitrations.set(call.toolCallId, verdict);
if (verdict.kind === "released")
return { action: "allow", message: `released by the ${verdict.mode} permission mode at an inherited ancestor layer (the ${verdict.askClass} ask was not put to anyone)`, decisionReason: "mode", ...(ask.updatedInput !== undefined ? { updatedInput: ask.updatedInput } : {}) };
return { action: "deny", message: `refused by the ${verdict.mode} permission mode at an inherited ancestor layer`, decisionReason: "mode" };
};
const policy = lockedPreflight.toolPolicy;
const retiredView = input.retiredNames;
const hostPolicyUnderView = (p) => policyUnderRetiredView(p, retiredView);
const readAsSuccessor = [];
const auditPolicyNames = (auditee, layer = "caller_policy") => {
const refused = [];
const retiredLeftOut = [];
const nameGroups = toolPolicyNameSets(auditee);
if (nameGroups.length > 0) {
const known = mountedToolNames(tools);
for (const t of harnessTools)
known.add(t.name);
const pool = delegationPoolReading(spec.tools ?? [], valveLeaves(selector));
const callerNames = mountedToolNames(spec.tools ?? []);
const rootFacing = rootFacingToolNames([...known, ...callerNames, ...pool.names]);
const universe = {
known,
rootFacing,
carrierOf: (spelling) => (known.has(spelling) || callerNames.has(spelling) ? "run" : pool.names.has(spelling) ? "pool" : "catalog"),
retiredNames: retiredView,
};
const unmatched = new Set();
for (const g of nameGroups) {
for (const [kind, list] of [["deny", g.deny], ["ask", g.ask], ["allow", g.allow]]) {
for (const n of list ?? []) {
const reading = judgePolicyEntryName(n, kind, universe, layer);
if (reading.kind === "read_as") {
if (g.content?.includes(n) === true)
refused.push(retiredContentRefusal(kind, n, reading.successor, layer));
else
readAsSuccessor.push(`"${n}" (${kind}) is read as "${reading.successor}"`);
continue;
}
if (reading.kind === "advised") {
unmatched.add(reading.stale.kind === "retired" ? `"${n}" (allow — a retired tool name: ${reading.stale.guidance})` : `"${n}" (allow — ${reading.stale.guidance}${reading.stale.currentName !== undefined ? ` Write "${reading.stale.currentName}".` : ""})`);
continue;
}
if (reading.kind === "left_out") {
retiredLeftOut.push({ field: reading.field, entry: n, layer, guidance: reading.guidance });
continue;
}
if (reading.kind === "refused") {
const stale = reading.stale;
const entry = `tool policy ${kind}-list entry "${n}"`;
let message;
switch (stale.kind) {
case "retired":
message = `${entry} is a RETIRED tool name (${stale.guidance}), but a tool of this deployment answers to it — a caller tool this run's lists take out, or one a delegation pool hands its children — so the entry means that tool${stale.currentName !== undefined ? `, not "${stale.currentName}"` : ""}, and this run cannot call a tool of that name: here it would guard nothing. ${stale.currentName !== undefined ? `To guard the engine's tool, write "${stale.currentName}"; to` : "To"} guard the deployment's own "${n}", name it in the lists of the agent that mounts it, or let this run mount it.`;
break;
case "unprefixed_namespace":
message = `${entry} carries the "__" namespace separator but no protocol prefix, and matches nothing in this run's roster — protocol tools are named ${NAMESPACED_NAME_SHAPES}, and names are not mapped to their prefixed form, so this entry would silently guard nothing. Write the entry as a protocol tool's full name in one of those shapes, or remove it.`;
break;
case "unmintable_segment":
message = `${entry} can match no tool, ever (${stale.guidance}), so it would silently guard nothing.${stale.currentName !== undefined ? ` Write "${stale.currentName}".` : ""}`;
break;
case "case_twin":
message = `${entry} differs from ${stale.carrier === "run" ? "the mounted tool" : stale.carrier === "pool" ? "the tool a delegation pool carries" : "the engine's catalog tool"} "${stale.twin}" only in case, and a policy compares tool names exactly, so it matches nothing in this run's roster and would silently guard nothing. Write "${stale.twin}".`;
break;
default: {
const exhaustive = stale;
return exhaustive;
}
}
refused.push({ message, problem: { code: POLICY_NAME_REFUSAL_CODE, field: kind, entry: n, reason: stale.kind === "case_twin" ? "near_miss" : stale.kind, layer } });
continue;
}
if (known.has(n))
continue;
if (isCoveringRuleName(n, kind) && [...known].some((k) => ruleNameCovers(n, k)))
continue;
unmatched.add(`"${n}" (${kind})`);
}
}
}
if (refused[0] !== undefined)
throw policyNameRefusal(refused[0], refused.slice(1));
if (retiredLeftOut.length > 0)
deliverEngineNotice(deps.onNotice, retiredToolNameNotice(layer, retiredLeftOut, sessionId));
const dedupeKey = [...unmatched].sort().join("|");
const advised = advisedPolicyNames.get(deploymentBagOf(deps)) ?? new Set();
if (unmatched.size > 0 && !advised.has(dedupeKey)) {
advised.add(dedupeKey);
if (advised.size > ADVISED_KEYS_CAP) {
const oldest = advised.values().next().value;
if (oldest !== undefined)
advised.delete(oldest);
}
advisedPolicyNames.set(deploymentBagOf(deps), advised);
try {
const e = new Error(`toolPolicy name audit: ${[...unmatched].join(", ")} match(es) no tool mounted this run (primary or alias) — the rule cannot fire here. Often a typo or a self-report/wire name skew (e.g. TodoWrite vs the mounted TaskCreate family; a "*" on a deny or ask list reaches every name its pattern matches). Advisory only: enforcement is unchanged, and a name can be legitimate for another scenario or a per-spawn tool.`);
e.code = UNMATCHED_TOOL_NAMES_CODE;
deps.onError?.(e, { phase: "config", sessionId });
}
catch {
}
}
}
};
auditPolicyNames(policy);
const announceSessionRulesUnreadable = (reason) => {
try {
const e = new Error(`session permission rules: ${reason} — the snapshot this leg already enforces stays in force (a failed read never loosens it)`);
e.code = "config.session_rules_unreadable";
deps.onError?.(e, { phase: "config", sessionId });
}
catch {
}
};
const announceEarlierGrammar = earlierGrammarNoticeSeat(deps.onNotice, sessionId, input.announced);
let sessionRulePolicy;
const lastReadUnread = { own: false, ancestors: new Map() };
if (deps.sessionPolicyStore && spec.sessionId) {
const store = deps.sessionPolicyStore;
const sessionRuleKey = { sessionId: spec.sessionId, ...(spec.principal ? { principal: spec.principal } : {}) };
const rules = await store.getRules(spec.sessionId, sessionRuleKey.principal);
const seed = rules ?? { rev: 0 };
const publishOwnRules = (row) => {
ownSessionRulesRef.current = {
sessionId: sessionRuleKey.sessionId,
...(sessionRuleKey.principal !== undefined ? { principal: sessionRuleKey.principal } : {}),
rev: row.rev,
...(row.gen !== undefined ? { gen: row.gen } : {}),
rules: row,
};
};
sessionRulePolicy = createSessionRulePolicy({ seed, read: createLiveSessionRules(store, { ...sessionRuleKey, seed }, { onUnreadable: announceSessionRulesUnreadable, onEnforced: publishOwnRules, onRead: (unread) => void (lastReadUnread.own = unread) }) }, { env: executionEnv, rootPath: taskRootFinal, toolEffects, anchors: pathRuleAnchors.leg, retiredNames: retiredView, onEarlierGrammar: announceEarlierGrammar(sessionRuleKey.sessionId) });
publishOwnRules(seed);
}
const ancestorRulePolicies = [];
for (const [position, snap] of (inheritedAncestorRules ?? []).entries()) {
const seed = { ...snap.rules, rev: snap.rev, ...(snap.gen !== undefined ? { gen: snap.gen } : {}) };
const publishAncestorRules = (row) => {
ancestorSessionRulesRef.current.set(position, {
sessionId: snap.sessionId,
...(snap.principal !== undefined ? { principal: snap.principal } : {}),
rev: row.rev,
...(row.gen !== undefined ? { gen: row.gen } : {}),
rules: row,
});
};
ancestorRulePolicies.push(createSessionRulePolicy({ seed, read: createLiveSessionRules(deps.sessionPolicyStore, { sessionId: snap.sessionId, ...(snap.principal !== undefined ? { principal: snap.principal } : {}), seed }, { onUnreadable: announceSessionRulesUnreadable, onEnforced: publishAncestorRules, onRead: (unread) => { lastReadUnread.ancestors.set(position, unread); } }) }, { env: executionEnv, rootPath: taskRootFinal, toolEffects, anchors: pathRuleAnchors.leg, retiredNames: retiredView, onEarlierGrammar: announceEarlierGrammar(snap.sessionId) }));
}
const frozenConstraintLayers = (seedInheritedGate?.constraintChain ?? [])
.filter((e) => !("opaque" in e))
.map((entry) => ({
check: (creq) => checkToolPolicyProjection(entry, callUnderView(creq, retiredView)) ?? { action: "allow" },
}));
const narrowingLayers = [hostFloor !== undefined ? hostFloorPolicy(hostFloor) : undefined, sessionRulePolicy, ...ancestorRulePolicies, ...frozenConstraintLayers].filter((p) => p !== undefined);
auditPolicyNames(sessionRulePolicy, "session_rules");
for (const layer of ancestorRulePolicies)
auditPolicyNames(layer, "ancestor_session_rules");
tellReadAsSuccessor(deps.onError, readAsSuccessor, sessionId);
const denyNarrowingPolicy = narrowingLayers.length === 0 ? undefined : narrowingLayers.length === 1 ? narrowingLayers[0] : combinePolicies(...narrowingLayers);
const resumeEditBase = lockedPreflight.basePolicyForResumeEdit ?? lockedPreflight.toolPolicy;
const basePolicyForResumeEdit = resumeEditBase !== undefined ? hostPolicyUnderView(resumeEditBase) : undefined;
const ownChainJudges = chainJudges(modBus);
const sameInstanceAncestorCount = policy === undefined ? 0 : (inheritedParentConstraints ?? []).reduce((n, pc) => (pc.policy === policy ? n + 1 : n), 0);
const sharedFirstDecision = new Map();
const SHARED_FIRST_DECISION_CAP = 256;
const staleArbitrations = new Map();
const noteArbitration = (toolCallId, arbitrate, stale) => {
const rest = (staleArbitrations.get(toolCallId) ?? []).filter((a) => a !== arbitrate);
if (stale)
rest.push(arbitrate);
if (rest.length > 0)
staleArbitrations.set(toolCallId, rest);
else
staleArbitrations.delete(toolCallId);
};
const inheritedUnavailableAsks = new Map();
const deferredAskIdentities = new Map();
const INHERITED_UNAVAILABLE_CAP = 256;
const markInheritedUnavailable = (station, creq, mark, deferred) => {
if (inheritedUnavailableAsks.size >= INHERITED_UNAVAILABLE_CAP && !inheritedUnavailableAsks.has(creq.toolCallId))
return false;
markCall(inheritedUnavailableAsks, station, creq.toolCallId, mark);
if (deferred !== undefined)
deferredAskIdentities.set(creq.toolCallId, deferred);
return true;
};
const inheritedLandingOf = (creq) => unavailableLandingOf({ ...parkRouteOf(creq.toolCallId), attemptFailed: false, question: false, durableQuestionFace: undefined });
const mandatedCallFloats = (station, creq, mark) => resolveCheckpointStore(spec, deps) !== undefined && durableParkOptInDeclared({ forceDurableGate: runtimeCaps?.forceDurableGate === true, durableApprovalDeclared: spec.durableApproval !== undefined, approvalParkNotResumable }) && parkRouteOf(creq.toolCallId).approvalParkWithheld !== true && markInheritedUnavailable(station, creq, mark);
const mandateUnreconstructibleDeny = (creq) => attest({
action: "deny",
message: notResumableSays !== undefined ? notResumableRefusal(`inherited parent policy requires durable approval for "${creq.toolName}"`, notResumableSays) : `inherited parent policy requires durable approval for "${creq.toolName}" — the parent's durable ask cannot be reconstructed in a delegated child; denied fail-closed (tighten-only)`,
}, creq, { unresolvableCause: "mandate_unreconstructible" });
const markerChannelFullDeny = (creq, routed) => attest({ action: "deny", message: `${windowMarkOf(routed, creq).windowExpired === true ? `the inherited approval of "${creq.toolName}" was not answered within the deployment's approval window` : `no approver is reachable for the inherited approval of "${creq.toolName}"`} and the marker channel is at capacity — denied fail-closed` }, creq, { unresolvableCause: windowMarkOf(routed, creq).windowExpired === true ? "approval_window_expired" : "approver_unavailable" });
const inheritedAskGrants = new Map();
const recordInheritedAskGrant = (toolCallId, approver, presented, waitMs, settled, classes) => {
if (typeof approver !== "function")
return;
if (presented === undefined)
return;
if (inheritedAskGrants.size >= INHERITED_UNAVAILABLE_CAP && !inheritedAskGrants.has(toolCallId))
return;
const argsJson = askGrantShapeOf(presented);
if (argsJson === undefined)
return;
inheritedAskGrants.set(toolCallId, { approver, argsJson, presented, waitMs, settled, classes });
};
const sandboxDeclared = isIsolated(executionEnv);
const sandboxAdmissionArmed = (() => {
if (!sandboxDeclared)
return false;
const store = resolveCheckpointStore(spec, deps);
const missing = [];
if (store === undefined)
missing.push("a wired CheckpointStore");
if (!durableParkOptInDeclared({ forceDurableGate: runtimeCaps?.forceDurableGate === true, durableApprovalDeclared: spec.durableApproval !== undefined, approvalParkNotResumable }))
missing.push(`a durable park (spec.durableApproval, or the forceDurableGate entitlement${approvalParkNotResumable !== undefined ? ` — neither counts on a leg nobody resumes: ${notResumableClause(approvalParkNotResumable)}` : ""})`);
if (missing.length === 0)
return true;
try {
const e = new Error(`sandbox admission mode NOT armed: the execution env declares an isolated sandbox (capabilities.isolation), but the mode's ` +
`park prerequisites are missing — ${missing.join("; ")}. Asks keep the conservative default chain (no auto-admission, no boundary park).`);
e.code = "config.sandbox_admission_unavailable";
deps.onError?.(e, { phase: "config", sessionId, classification: "sandbox-admission-unavailable" });
}
catch {
}
return false;
})();
const foldAskClasses = new Map();
const FOLD_ASK_CLASSES_CAP = 256;
const recordFoldAskClass = (toolCallId, cls, layer) => {
if (!foldAskClasses.has(toolCallId) && foldAskClasses.size >= FOLD_ASK_CLASSES_CAP)
return;
const list = foldAskClasses.get(toolCallId) ?? [];
list.push({ cls, layer });
foldAskClasses.set(toolCallId, list);
};
const isDelegatedQuestion = (creq) => isEngineQuestionFace(creq.face);
const sandboxBoundaryCapable = (call) => heldBy("gate.sandboxBoundary.egress", egressTools, call) || !envHandToolNames.has(wireOf("gate.sandboxBoundary.hand", call));
const emitSandboxAdmitted = (info) => {
emitTrace(deps.tracer, () => ({
kind: "permission.sandbox_admitted",
version: 1,
taskId: hostTaskId,
toolCallId: info.toolCallId,
toolName: info.toolName,
askClasses: info.askClasses.map((a) => a.cls),
sourceLayers: info.askClasses.map((a) => a.layer),
boundary: info.boundary,
ts: Date.now(),
}));
};
const ancestorSandboxAdmissions = new Map();
const recordAncestorSandboxAdmission = (toolCallId, toolName) => {
const list = ancestorSandboxAdmissions.get(toolCallId);
if (list !== undefined)
list.push({ cls: "sandbox_local", layer: "ancestor_constraint" });
else
ancestorSandboxAdmissions.set(toolCallId, [{ cls: "sandbox_local", layer: "ancestor_constraint" }]);
void toolName;
};
const callerPolicy = policy !== undefined ? hostPolicyUnderView(policy) : undefined;
const callerPolicyLayer = callerPolicy !== undefined && sameInstanceAncestorCount > 0
? wrapToolPolicy(callerPolicy, async (creq, csignal) => {
const decision = refuseOutOfContractDecision(await callerPolicy.check(creq, csignal ?? abortController.signal), { call: creq });
sharedFirstDecision.set(creq.toolCallId, { decision, judged: creq.args });
if (sharedFirstDecision.size > SHARED_FIRST_DECISION_CAP) {
const oldest = sharedFirstDecision.keys().next().value;
if (oldest !== undefined)
sharedFirstDecision.delete(oldest);
}
return decision;
})
: callerPolicy;
const seatMarksOf = (call) => {
const tierSeat = seatOf("report.riskAxes", irreversibilityTier, call);
return {
tier: tierSeat?.value,
egress: heldBy("report.riskAxes.egress", egressTools, call),
shellGated: tierSeat?.shellGated(shellGatedTools, toolMarkSources) === true,
sources: new Set(heldValues("report.markSources", toolMarkSources, call).flatMap((s) => [...s])),
};
};
const seatMandateMarksOf = (call) => ((s) => ({ egress: s.egress, shellGated: s.shellGated, irreversibility: s.tier }))(seatMarksOf(call));
const riskAxesOf = (call) => {
const seat = seatMarksOf(call);
const negatives = seatOf("report.riskAxes.negatives", axisExplicitNegatives, call)?.value;
const irreversible = seat.tier === "always" || seat.tier === "maybe" ? true : seat.tier === "never" ? false : negatives?.irreversible;
const egress = seat.egress ? true : negatives?.egress;
if (irreversible === undefined && egress === undefined)
return {};
return { riskAxes: { ...(irreversible !== undefined ? { irreversible } : {}), ...(egress !== undefined ? { egress } : {}) } };
};
const grantBindingOf = (call, args) => skillGrantBindingMembers(call, args, skillSpecs, SKILL_TOOL_NAME);
const insidePeerOf = a2aInsidePeerReader(lockedPreflight.a2a, deps.a2a?.isolatePeers === true);
const inheritedStationFacts = (call, args) => {
const seat = seatMarksOf(call), face = readFace();
return {
...INHERITED_STATION_FACTS, call: { toolCallId: call.toolCallId, toolName: call.toolName },
...(leavesByEscape(sandboxPlanOf({ toolName: call.toolName, toolCallId: call.toolCallId, args })) ? { leavesSandbox: true } : {}),
mandateMarks: { egress: seat.egress, shellGated: false, ...(seat.tier === "always" && !seat.shellGated ? { irreversibility: seat.tier } : {}) },
...(seat.sources.size > 0 ? { toolMarkSources: seat.sources } : {}), ...(insidePeerOf(call.toolName) !== undefined ? { a2aInside: true } : {}),
...(deps.a2a?.isolatePeers === true ? { a2aIsolatePeers: true } : {}),
...(face !== undefined ? { readFace: face } : {}),
askFace: askFaceOf(wireOf("inherited.askFace", call)),
};
};
const listFacts = { root: taskRootFinal, sessionId, liveCwd: () => handsCwdRef?.current, anchors: pathRuleAnchors.leg, classifyAllShell: classifiesAllShell(spec) };
const toldFrom = (source) => (s, call) => autoStripNotice({ entry: s.entry, source, reason: s.reason, ...(s.skill !== undefined ? { skill: s.skill } : {}) }, call);
const skillGrantLane = skillGrants.lane({ ...listFacts, onAutoStripped: toldFrom("skill") });
const allowEntryLanes = { request: allowedToolTables.request.lane({ ...listFacts, onAutoStripped: toldFrom("request") }), deployment: allowedToolTables.deployment.lane({ ...listFacts, onAutoStripped: toldFrom("deployment") }) };
const ruleLaneFacts = {
sessionId: ruleSessionId,
root: taskRootFinal,
rootCanonical: pathRuleAnchors.leg.root,
chainTop: pathRuleAnchors.chainTop,
leads: headLeads,
liveCwd: () => handsCwdRef?.current,
home: executionEnv.homeDir,
questionToolMounted,
questionToolName: ASK_USER_QUESTION_TOOL_NAME,
onRevisionDefect: (message) => deps.onError?.(new Error(message), { phase: "config", sessionId }),
onDisclosure: (message) => emitTrace(deps.tracer, () => ({ kind: "permission.rule_store_unreadable", version: 1, taskId: hostTaskId, message, ts: Date.now() })),
stripsAllow: (rule, req) => autoStripReasonOfRow(rule, req, permissionMode.current, listFacts.classifyAllShell),
};
const callBindingSeat = (call) => ({ env: executionEnv, shell: startedShellOfCall(call), cwd: handsCwdRef?.current ?? taskRootFinal, roots: [taskRootFinal, ...additionalRootsCanonical] });
const callGrantAdmitsHere = (binding, command, call, signal) => callGrantAdmits(binding, command, callBindingSeat(call), signal);
const laneOver = { provider: deps.permissionRuleStore, localOwnerDeclared: deps.localOwnerRules === true, principal: spec.principal, ancestorRuleBuckets: inheritedRuleBuckets, ...ruleLaneFacts, rows: personRows, callGrantAdmits: callGrantAdmitsHere };
const { personal: permissionRuleLane, org: permissionRuleOrgLane, wholeToolRefusals: storedRuleWholeToolRefusals } = createPermissionRuleLanes(laneOver);
const { personal: permissionRuleGateLane } = createPermissionRuleLanes({ ...laneOver, onAutoStripped: (rule, reason, req) => autoStripNotice({ entry: rule.rule, source: ruleSourceOf(rule.scope), reason }, req) });
const ruleOffersOf = createRuleOffersOf({
laneArmed: permissionRuleLane !== undefined,
principal: spec.principal,
localOwnerDeclared: deps.localOwnerRules === true,
egressTools,
irreversibilityTier,
shellGatedTools,
toolMarkSources,
taskRoot: taskRootFinal,
cwdRef: handsCwdRef,
deniesDirectoryRead: readDenyMatcher !== undefined ? (d) => readDenyMatcher.matchPath(d) !== null : undefined,
...(deps.permissionRuleStore?.a2aPeers !== undefined ? { a2aPeers: deps.permissionRuleStore.a2aPeers } : {}),
});
const callGrantDoorOf = createCallGrantDoorOf(ruleOffersOf);
const heardAtStation = async (ask, creq, args, csignal, record) => {
if (!ruleSessionInTree || permissionRuleLane === undefined)
return { ask };
const signal = csignal ?? abortController.signal, req = args === creq.args ? creq : await withArgsReading(creq, args, signal), heard = await readPersistedRuleLane(permissionRuleLane, req, signal);
const arms = applyPersistedTightening(ask, heard, req);
if (arms.decision.action !== "ask")
return { settled: arms.decision };
const tightened = arms.tightened === "store_unreadable" && arms.decision.ruleUnreadable === undefined ? { ...arms.decision, ruleUnreadable: "persisted_rows" } : arms.decision;
const allows = heard.unreadable !== true && heard.hit?.behavior === "allow" ? heard.hit.rules : undefined;
if (allows === undefined || heard.hit === undefined)
return { ask: tightened, heard };
const { classes, row } = classifyAsk(tightened, { ...inheritedStationFacts(creq, args), mandateMarks: seatMandateMarksOf(creq) }), peer = classes.has("a2a_inside") ? insidePeerOf(creq.toolName) : undefined;
const bound = peer !== undefined ? boundStoredGrantOf(allows, heard.hit.bound ?? [], peer.fingerprint, boundGrantMayClear(classes)) : undefined;
if (bound !== undefined ? !bound.clears : !allowMayClearOn(row, "rule") || standsOnWholePeerRow(allows))
return { ask: tightened, heard, shown: { allowRuleShadowed: [allowRuleShadowOf("persisted", bound?.entries ?? allows.map((r) => r.rule), bound?.clears === false ? bound.reason : undefined)] } };
const on = bound?.clears === true ? (bound.rules ?? allows) : allows;
if (record)
ancestorRuleClears.set(creq.toolCallId, { clearedBy: allowRuleShadowOf("persisted", on.map((r) => r.rule)), rules: on.map((r) => r.rule) });
return { settled: { action: "allow", message: on.length === 1 ? `a persisted allow rule (${disclosedRuleSet(on)}) covers this call` : `persisted allow rules (${disclosedRuleSet(on)}) cover every segment of this call`, decisionReason: "persisted_rule" } };
};
const readBoundaryRefusalOf = readBoundaryRefusalOver({ judge: readBlockJudge, cwd: () => handsCwdRef?.current, signal: abortController.signal });
const recheckApprovedEdit = async (pol, onAskOf, creq, edit, approved, csignal, ancestorAutoMode) => {
const ancestorDecider = ancestorAutoMode?.decider;
const ancestorTracker = ancestorAutoMode?.denialTracking;
let editArgs = argsAsTheToolReads(creq, edit);
let settledBy = approved;
const onApproval = (d) => withAttestation(d, mergeAttestation(creq, attestationOf(settledBy, creq), attestationOf(d, creq), "answer"));
const vetoed = onApproval;
for (let round = 0;; round++) {
if (round >= 3) {
return vetoed({
action: "deny",
message: `the approval-edit chain for "${creq.toolName}" exceeded the re-approval cap (inherited parent policy) — denied fail-closed; re-submit the edited action directly`,
});
}
let re;
try {
re = refuseOutOfContractDecision(await pol.check(await withArgsReading(creq, editArgs, csignal ?? abortController.signal), csignal ?? abortController.signal), { call: creq });
}
catch (err) {
reportPolicyThrow(notifyOwnHookCrash, "an inherited parent policy's re-check of the approved edit", creq, err, csignal ?? abortController.signal);
return vetoed({
action: "deny",
message: `inherited parent policy re-check of the approved edit errored for "${creq.toolName}": ${policyThrowLine(err)}`,
});
}
if (re.action === "deny")
return vetoed(re);
const read = readRejudge(creq, editArgs, re);
if (read.kind === "rewritten") {
editArgs = read.form;
const { updatedInput: _form, ...verdict } = re;
re = outletAsk(verdict, creq.toolName, editArgs);
}
else if (re.action === "allow") {
return onApproval(withAttestation({ action: "allow", updatedInput: editArgs, decisionReason: "mode" }, re.attestation));
}
const readRefused = await readBoundaryRefusalOf(creq, editArgs, csignal);
if (readRefused !== undefined)
return vetoed(readRefused);
const lane = read.kind === "rewritten" ? { ask: re } : await heardAtStation(re, creq, editArgs, csignal, false);
if ("settled" in lane)
return lane.settled.action === "allow" ? onApproval({ ...lane.settled, updatedInput: editArgs }) : vetoed(lane.settled);
re = lane.ask;
const judged = await judgeHeld({ liveMode: () => permissionMode.current, autoMode: read.kind === "rewritten" ? undefined : ancestorAutoMode, ask: re, req: withArgsBinding(creq, editArgs), signal: csignal ?? abortController.signal, subject: "the approved edit", allowRewrite: editArgs, facts: inheritedStationFacts(creq, editArgs), unavailableSeat: classifierUnavailableSeat({ station: "ancestor", ...(ancestorDecider?.timeoutMs !== undefined ? { budgetMs: ancestorDecider.timeoutMs } : {}), route: frozenApproverRoute(onAskOf), onNotice: deps.onNotice, sessionId, runId }) });
if (judged.kind === "allow") {
return onApproval(judged.result);
}
if (judged.kind === "deny")
return vetoed(judged.result);
const { ask: editAsk } = judged;
re = editAsk;
const editArbitrated = arbitrateInherited(re, creq, judged);
const outletReleased = read.kind === "rewritten" && editArbitrated?.action === "allow";
if (outletReleased)
ancestorArbitrations.delete(creq.toolCallId);
if (editArbitrated !== undefined && !outletReleased) {
return onApproval(editArbitrated.action === "allow" ? { action: "allow", updatedInput: editArgs, decisionReason: "mode" } : editArbitrated);
}
const editTarget = await unreadCardTarget(creq.toolName, editArgs);
const { resolved: rr, judged: settled, presentedAs } = await resolveInheritedAsk(judged, (j, checkpointId) => resolveAskFor({
toolName: creq.toolName,
toolCallId: creq.toolCallId,
checkpointId,
args: editArgs,
...editTarget,
...ruleOffersOf(creq, editArgs, { ...ancestorFacts({ ...j.ask, ...("shown" in lane ? lane.shown : {}) }, creq), classes: [...j.classification.classes] }),
...cardDisclosureOf({ ...j.ask, ...("shown" in lane ? lane.shown : {}) }, inheritedAskFallbackMessage(creq.toolName)),
...askSource,
...riskAxesOf(creq),
...commandSandboxSideOf(creq, editArgs),
...destinationOf(creq.toolName),
...approvalCardMemberOf(creq),
...grantBindingOf(creq, editArgs),
...(j.ask.requiresRealApproval === true ? { requiresRealApproval: true } : {}),
...askMandateMember(ancestorFacts(j.ask, creq), seatMandateMarksOf(creq)),
...inheritedAskCarry(j, isAnsweringSeat(onAskOf), ancestorTracker),
ruleEvidence: inheritedAskRuleEvidence(deps.permissionRuleStore, "heard" in lane ? lane.heard : undefined),
}, heldApprover(onAskOf), csignal ?? abortController.signal, lateAskSettlementObserver({ toolName: creq.toolName, toolCallId: creq.toolCallId, sessionId, runId, taskId: hostTaskId, onNotice: deps.onNotice, onError: deps.onError }), j.ask, approverDefectAnnouncer({ toolName: creq.toolName, toolCallId: creq.toolCallId, sessionId, runId, taskId: hostTaskId, onNotice: deps.onNotice }), approvalWords, engineText, "close"), ancestorTracker, creq, inheritedStationFacts(creq, editArgs));
const settleAt = { toolName: creq.toolName, toolCallId: creq.toolCallId, checkpointId: presentedAs, sessionId, runId, taskId: hostTaskId, onNotice: deps.onNotice };
void settleReadRootGrant(rr.readRootGrant, undefined, settleAt);
settleUnofferedSessionCallGrant(rr.sessionCallGrant, settleAt);
settleDenialLimitFallback({ fallback: settled.fallback, mintedHere: settled.mintedHere, tracker: ancestorTracker, resolved: rr, headless: headlessDenyAtRecheck, stop: stopForDenialLimit, toolName: creq.toolName, toolCallId: creq.toolCallId });
if (rr.action !== "allow")
return rr;
settledBy = rr;
if (rr.updatedInput === undefined)
return onApproval({ action: "allow", updatedInput: editArgs, decisionReason: "mode" });
editArgs = argsAsTheToolReads(creq, rr.updatedInput);
}
};
const settleInstallationAsk = async (pc, decision, creq, csignal) => {
const settledAs = (result) => ({ kind: "settled", result });
const presentedArgs = decision.updatedInput !== undefined ? argsAsTheToolReads(creq, decision.updatedInput) : creq.args;
const readRefused = await readBoundaryRefusalOf(creq, presentedArgs, csignal);
if (readRefused !== undefined)
return settledAs(readRefused);
if (isDelegatedQuestion(creq)) {
if (pc.contentMandate !== true || markInheritedUnavailable(pc, creq, stationMarkOf(decision, creq)))
return settledAs(decision);
return settledAs({
action: "deny",
message: `inherited parent policy requires durable handling of the question raised for "${creq.toolName}" and the marker channel is at capacity — ` +
`denied fail-closed (tighten-only)`,
});
}
const lane = await heardAtStation(decision, creq, presentedArgs, csignal, true);
if ("settled" in lane)
return settledAs(lane.settled.action === "allow" && decision.updatedInput !== undefined ? { ...lane.settled, updatedInput: decision.updatedInput } : lane.settled);
decision = lane.ask;
if (pc.durableMandate === true || forcedGateNotResumable) {
if (mandatedCallFloats(pc, creq, stationMarkOf(decision, creq)))
return settledAs(decision);
return settledAs(mandateUnreconstructibleDeny(creq));
}
const judged = await judgeHeld({ liveMode: () => permissionMode.current, autoMode: pc.autoMode, ask: decision, req: withArgsBinding(creq, presentedArgs), signal: csignal ?? abortController.signal, subject: "this call", allowRewrite: decision.updatedInput, facts: inheritedStationFacts(creq, presentedArgs), unavailableSeat: classifierUnavailableSeat({ station: "ancestor", ...(pc.autoMode?.decider.timeoutMs !== undefined ? { budgetMs: pc.autoMode.decider.timeoutMs } : {}), route: frozenApproverRoute(pc.onAsk), onNotice: deps.onNotice, sessionId, runId }) });
if (judged.kind === "allow")
return settledAs(judged.result);
if (judged.kind === "deny")
return settledAs(judged.result);
const { ask: inheritedAsk, fallback } = judged;
if (fallback === undefined && sandboxAdmissionArmed && pc.policy !== undefined && policyAskClassOf(pc.policy) === "sandbox_local" && !sandboxBoundaryCapable(creq) && judged.classification.row.sandboxAdmission) {
recordAncestorSandboxAdmission(creq.toolCallId, creq.toolName);
return settledAs(decision.updatedInput !== undefined ? { action: "allow", updatedInput: decision.updatedInput, decisionReason: "sandbox" } : { action: "allow", decisionReason: "sandbox" });
}
const arbitrated = arbitrateInherited(inheritedAsk.action === "ask" ? { ...inheritedAsk, ...(decision.updatedInput !== undefined ? { updatedInput: decision.updatedInput } : {}) } : inheritedAsk, creq, judged);
if (arbitrated !== undefined)
return settledAs(arbitrated);
const presentedTarget = await unreadCardTarget(creq.toolName, presentedArgs);
const askT0 = now();
const { resolved, judged: settled, presentedAs } = await resolveInheritedAsk(judged, (j, checkpointId) => resolveAskFor({
toolName: creq.toolName,
toolCallId: creq.toolCallId,
checkpointId,
args: presentedArgs,
...presentedTarget,
...ruleOffersOf(creq, presentedArgs, { ...ancestorFacts(j.ask.action === "ask" ? { ...j.ask, ...lane.shown } : undefined, creq), classes: [...j.classification.classes] }),
...cardDisclosureOf({ ...j.ask, ...lane.shown }, inheritedAskFallbackMessage(creq.toolName)),
...askSource,
...riskAxesOf(creq),
...commandSandboxSideOf(creq, presentedArgs),
...destinationOf(creq.toolName),
...approvalCardMemberOf(creq),
...grantBindingOf(creq, presentedArgs),
...(j.ask.action === "ask" && j.ask.requiresRealApproval === true ? { requiresRealApproval: true } : {}),
...askMandateMember(ancestorFacts(j.ask.action === "ask" ? j.ask : undefined, creq), seatMandateMarksOf(creq)),
...inheritedAskCarry(j, isAnsweringSeat(pc.onAsk), pc.autoMode?.denialTracking),
ruleEvidence: inheritedAskRuleEvidence(deps.permissionRuleStore, lane.heard),
}, heldApprover(pc.onAsk), csignal ?? abortController.signal, lateAskSettlementObserver({ toolName: creq.toolName, toolCallId: creq.toolCallId, sessionId, runId, taskId: hostTaskId, onNotice: deps.onNotice, onError: deps.onError }), j.ask, approverDefectAnnouncer({ toolName: creq.toolName, toolCallId: creq.toolCallId, sessionId, runId, taskId: hostTaskId, onNotice: deps.onNotice }), approvalWords, engineText, inheritedLandingOf(creq)), pc.autoMode?.denialTracking, creq, inheritedStationFacts(creq, presentedArgs));
const settleAt = { toolName: creq.toolName, toolCallId: creq.toolCallId, checkpointId: presentedAs, sessionId, runId, taskId: hostTaskId, onNotice: deps.onNotice };
void settleReadRootGrant(resolved.readRootGrant, undefined, settleAt);
settleUnofferedSessionCallGrant(resolved.sessionCallGrant, settleAt);
const askWaitMs = Math.max(0, now() - askT0);
if (resolved.action === "deny" && resolved.approverUnavailable === true) {
const floated = floatedInheritedAsk(settled, creq);
if (markInheritedUnavailable(pc, creq, { ...stationMarkOf(floated, creq, presentedArgs), ...windowMarkOf(resolved, creq) }, deferredAskOf(resolved, creq, presentedAs)))
return settledAs(floated);
return settledAs(markerChannelFullDeny(creq, resolved));
}
settleDenialLimitFallback({ fallback: settled.fallback, mintedHere: settled.mintedHere, tracker: pc.autoMode?.denialTracking, resolved, headless: headlessDenyAtFold, stop: stopForDenialLimit, toolName: creq.toolName, toolCallId: creq.toolCallId });
if (resolved.action !== "allow")
return settledAs(resolved);
liftMark(inheritedUnavailableAsks, pc, creq.toolCallId);
return { kind: "approved", resolved, askWaitMs, classes: askClassMembersOf(judged.classification).classes };
};
const legStandsIn = (pc) => standsInFor(pc, { chain: ownModChain, onAsk: frozenOnAsk, hookEnv: hookEnvSource, decider: autoModeDecider() }, ownChainJudges);
const parentConstraintWrappers = (inheritedParentConstraints ?? []).flatMap((pc) => {
const ancestorPolicy = pc.policy;
if (ancestorPolicy === undefined)
return [];
const ancestorUnderView = hostPolicyUnderView(ancestorPolicy);
return [
policy !== undefined && ancestorPolicy === policy
? {
check: async function arbitrate(creq, csignal) {
return stationLook(inheritedUnavailableAsks, pc, creq, async () => {
const recorded = sharedFirstDecision.get(creq.toolCallId);
const first = recorded?.decision;
const stale = recorded !== undefined && !sameBytes(creq, recorded.decision.updatedInput !== undefined ? recorded.decision.updatedInput : recorded.judged, creq.args);
if (recorded !== undefined)
noteArbitration(creq.toolCallId, arbitrate, stale);
if (stale)
return { action: "allow" };
if (first === undefined) {
return {
action: "deny",
message: `inherited parent policy could not be arbitrated for "${creq.toolName}" ` +
`(shared-instance first decision unavailable); denied fail-closed`,
};
}
if (first.action === "deny")
return first;
if (first.action === "allow")
return { action: "allow" };
const readRefused = await readBoundaryRefusalOf(creq, creq.args, csignal);
if (readRefused !== undefined)
return readRefused;
if (isDelegatedQuestion(creq)) {
if (pc.contentMandate !== true || markInheritedUnavailable(pc, creq, stationMarkOf(first, creq, creq.args)))
return first;
return {
action: "deny",
message: `inherited parent policy requires durable handling of the question raised for "${creq.toolName}" and the marker channel is at capacity — ` +
`denied fail-closed (tighten-only)`,
};
}
const lane = await heardAtStation(first, creq, creq.args, csignal, false);
if ("settled" in lane)
return lane.settled.action === "allow" ? { action: "allow" } : lane.settled;
const asked = lane.ask;
if (pc.durableMandate === true || forcedGateNotResumable) {
if (mandatedCallFloats(pc, creq, stationMarkOf(asked, creq, creq.args)))
return asked;
return mandateUnreconstructibleDeny(creq);
}
const judged = await judgeHeld({ liveMode: () => permissionMode.current, autoMode: pc.autoMode, ask: asked, req: creq, signal: csignal ?? abortController.signal, subject: "this call", facts: inheritedStationFacts(creq, creq.args), unavailableSeat: classifierUnavailableSeat({ station: "ancestor", ...(pc.autoMode?.decider.timeoutMs !== undefined ? { budgetMs: pc.autoMode.decider.timeoutMs } : {}), route: frozenApproverRoute(pc.onAsk), onNotice: deps.onNotice, sessionId, runId }) });
if (judged.kind === "allow")
return judged.result;
if (judged.kind === "deny")
return judged.result;
const { ask: inheritedAsk, fallback } = judged;
if (fallback === undefined && sandboxAdmissionArmed && policyAskClassOf(ancestorPolicy) === "sandbox_local" && !sandboxBoundaryCapable(creq) && judged.classification.row.sandboxAdmission) {
recordAncestorSandboxAdmission(creq.toolCallId, creq.toolName);
return { action: "allow", decisionReason: "sandbox" };
}
const arbitrated = arbitrateInherited(inheritedAsk, creq, judged);
if (arbitrated !== undefined)
return arbitrated;
const presentedArgs = creq.args;
const presentedTarget = await unreadCardTarget(creq.toolName, presentedArgs);
const askT0 = now();
const { resolved, judged: settled, presentedAs } = await resolveInheritedAsk(judged, (j, checkpointId) => resolveAskFor({
toolName: creq.toolName,
toolCallId: creq.toolCallId,
checkpointId,
args: presentedArgs,
...presentedTarget,
...ruleOffersOf(creq, presentedArgs, { ...ancestorFacts(j.ask.action === "ask" ? { ...j.ask, ...lane.shown } : undefined, creq), classes: [...j.classification.classes] }),
...cardDisclosureOf({ ...j.ask, ...lane.shown }, inheritedAskFallbackMessage(creq.toolName)),
...askSource,
...riskAxesOf(creq),
...commandSandboxSideOf(creq, presentedArgs),
...destinationOf(creq.toolName),
...approvalCardMemberOf(creq),
...grantBindingOf(creq, presentedArgs),
...(j.ask.action === "ask" && j.ask.requiresRealApproval === true ? { requiresRealApproval: true } : {}),
...askMandateMember(ancestorFacts(j.ask.action === "ask" ? j.ask : undefined, creq), seatMandateMarksOf(creq)),
...inheritedAskCarry(j, isAnsweringSeat(pc.onAsk), pc.autoMode?.denialTracking),
ruleEvidence: inheritedAskRuleEvidence(deps.permissionRuleStore, lane.heard),
}, heldApprover(pc.onAsk), csignal ?? abortController.signal, lateAskSettlementObserver({ toolName: creq.toolName, toolCallId: creq.toolCallId, sessionId, runId, taskId: hostTaskId, onNotice: deps.onNotice, onError: deps.onError }), j.ask, approverDefectAnnouncer({ toolName: creq.toolName, toolCallId: creq.toolCallId, sessionId, runId, taskId: hostTaskId, onNotice: deps.onNotice }), approvalWords, engineText, inheritedLandingOf(creq)), pc.autoMode?.denialTracking, creq, inheritedStationFacts(creq, presentedArgs));
const settleAt = { toolName: creq.toolName, toolCallId: creq.toolCallId, checkpointId: presentedAs, sessionId, runId, taskId: hostTaskId, onNotice: deps.onNotice };
void settleReadRootGrant(resolved.readRootGrant, undefined, settleAt);
settleUnofferedSessionCallGrant(resolved.sessionCallGrant, settleAt);
const askWaitMs = Math.max(0, now() - askT0);
if (resolved.action === "deny" && resolved.approverUnavailable === true) {
const floated = floatedInheritedAsk(settled, creq);
if (markInheritedUnavailable(pc, creq, { ...stationMarkOf(floated, creq, presentedArgs), ...windowMarkOf(resolved, creq) }, deferredAskOf(resolved, creq, presentedAs)))
return floated;
return markerChannelFullDeny(creq, resolved);
}
settleDenialLimitFallback({ fallback: settled.fallback, mintedHere: settled.mintedHere, tracker: pc.autoMode?.denialTracking, resolved, headless: headlessDenyAtFold, stop: stopForDenialLimit, toolName: creq.toolName, toolCallId: creq.toolCallId });
if (resolved.action !== "allow")
return resolved;
liftMark(inheritedUnavailableAsks, pc, creq.toolCallId);
if (resolved.updatedInput !== undefined) {
return recheckApprovedEdit(ancestorUnderView, pc.onAsk, creq, resolved.updatedInput, resolved, csignal, pc.autoMode);
}
recordInheritedAskGrant(creq.toolCallId, pc.onAsk, resolved.presentedInput, askWaitMs, resolved, askClassMembersOf(settled.classification).classes);
return { action: "allow", decisionReason: "mode" };
});
},
}
: wrapToolPolicy(ancestorUnderView, async (creq, csignal) => stationLook(inheritedUnavailableAsks, pc, creq, async () => {
let decision;
try {
decision = refuseOutOfContractDecision(await ancestorUnderView.check(creq, csignal ?? abortController.signal), { call: creq });
}
catch (err) {
reportPolicyThrow(notifyOwnHookCrash, "an inherited parent policy", creq, err, csignal ?? abortController.signal);
return {
action: "deny",
message: `inherited parent policy errored for "${creq.toolName}": ${policyThrowLine(err)}`,
};
}
if (decision.action !== "ask")
return decision;
const settled = await settleInstallationAsk(pc, decision, creq, csignal);
if (settled.kind === "settled")
return settled.result;
const { resolved } = settled;
if (resolved.updatedInput !== undefined) {
return recheckApprovedEdit(ancestorUnderView, pc.onAsk, creq, resolved.updatedInput, resolved, csignal, pc.autoMode);
}
recordInheritedAskGrant(creq.toolCallId, pc.onAsk, resolved.presentedInput, settled.askWaitMs, resolved, settled.classes);
if (decision.updatedInput === undefined)
return resolved;
return { ...resolved, updatedInput: decision.updatedInput };
})),
];
});
const installationsOnLeg = inheritedInstallations(inheritedParentConstraints ?? [], legStandsIn, (pc) => (typeof pc.hookEnv === "object" && pc.hookEnv !== null ? createHookEnvCapabilities(pc.hookEnv) : undefined), (pc) => async (ask, creq, csignal) => stationLook(inheritedUnavailableAsks, pc, creq, async () => {
const settled = await settleInstallationAsk(pc, ask, creq, csignal);
return settled.kind === "settled" ? settled.result : settled.resolved;
}), (pc) => (call) => standingOf(inheritedUnavailableAsks, pc, call));
const rewriteCapableChain = [
...(callerPolicyLayer !== undefined ? [callerPolicyLayer] : []),
...parentConstraintWrappers,
];
const callerSlotOffset = callerPolicyLayer !== undefined ? 1 : 0;
const instrumentedChain = rewriteCapableChain.map((layer, idx) => wrapToolPolicy(layer, async (creq, csignal) => {
const d = refuseOutOfContractDecision(await layer.check(creq, csignal), { call: creq });
if (d.action === "ask") {
recordFoldAskClass(creq.toolCallId, idx < callerSlotOffset ? policyAskClassOf(policy) : "mandate", idx < callerSlotOffset ? "caller_policy" : "ancestor_constraint");
}
return d;
}));
const modeGateSeats = { env: executionEnv, rootPath: taskRootFinal, acceptDirs: () => [writeLocation(), ...additionalRootsCanonical], roster: toolRosterDeltas, readOnlyDeclared: (name) => mountedToolDeclaresReadOnly(tools, name) };
const modeGateLayer = createModeGatePolicy(permissionMode, modeGateSeats), acceptEditsGate = acceptEditsWriteGate(modeGateSeats);
const policyLayers = [...narrowingLayers, ...instrumentedChain, ...(rewriteCapableChain.length > 0 ? narrowingLayers : [])];
const transcriptDirectory = deps.sessionStore?.transcriptDirectory;
const integrityGuardLayers = [createTranscriptIntegrityPolicy({ sessionsDirs: typeof transcriptDirectory === "string" ? [transcriptDirectory] : [] }), createUnverifiableDeletePolicy({ removalSeat: { env: executionEnv, additionalRoots: () => additionalRootsCanonical } }), ...releasedReadRowWriteLayers({ env: executionEnv, deps, spec, readDeny: readDenyMatcher, rootPath: taskRootFinal, sessionId })];
const guardedPolicyLayers = [...integrityGuardLayers, ...policyLayers, modeGateLayer];
const foldedPolicy = guardedPolicyLayers.length === 1 ? guardedPolicyLayers[0] : combinePolicies(...guardedPolicyLayers);
const effectivePolicy = foldedPolicy !== undefined && sameInstanceAncestorCount > 0
? wrapToolPolicy(foldedPolicy, async (req, signal) => {
let decision;
let stale;
try {
decision = await foldedPolicy.check(req, signal);
}
finally {
stale = staleArbitrations.get(req.toolCallId) ?? [];
staleArbitrations.delete(req.toolCallId);
}
if (decision.action === "deny" || stale.length === 0)
return decision;
const finalReq = decision.updatedInput !== undefined ? await withArgsReading(req, decision.updatedInput, signal) : req;
const carried = decision.updatedInput !== undefined ? { updatedInput: decision.updatedInput } : {};
let asked;
let revalidated;
try {
for (const arbitrate of stale) {
const d = refuseOutOfContractDecision(await arbitrate(finalReq, signal), { call: finalReq });
if (d.action === "deny")
return withAttestation({ ...d, ...carried }, mergeAttestation(req, attestationOf(decision, req), attestationOf(d, req), "answer"));
if (readRejudge(finalReq, finalReq.args, d).kind === "rewritten")
return { action: "deny", message: rewriteChasedSentence(req.toolName), ...carried };
if (d.action === "ask" && asked === undefined)
asked = d;
revalidated = mergeAttestation(req, revalidated, d.attestation);
}
}
finally {
staleArbitrations.delete(req.toolCallId);
}
if (asked !== undefined && decision.action === "allow")
return { ...asked, ...carried };
if (decision.action === "allow")
return withAttestation(decision, mergeAttestation(req, attestationOf(decision, req), revalidated));
return decision;
})
: foldedPolicy;
return { acceptEditsGate, basePolicyForResumeEdit, denyNarrowingPolicy, skillGrantLane, sessionRulesUnread: { own: () => lastReadUnread.own, ancestor: (position) => lastReadUnread.ancestors.get(position) === true }, allowEntryLanes, policyLayers, effectivePolicy, inheritedUnavailableAsks, deferredAskIdentities, inheritedAskGrants, riskAxesOf, ruleOffersOf, callGrantDoorOf, callBindingSeat, grantBindingOf, permissionRuleLane, permissionRuleGateLane, ruleLaneFacts, permissionRuleOrgLane, storedRuleWholeToolRefusals, sandboxAdmissionArmed, sandboxBoundaryCapable, emitSandboxAdmitted, foldAskClasses, ancestorSandboxAdmissions, ancestorArbitrations, ancestorRuleClears, inheritedInstallations: installationsOnLeg, hostPoliciesUnderView: { caller: callerPolicy, inherited: (inheritedParentConstraints ?? []).flatMap((c) => (c.policy === undefined ? [] : [c.policy === policy && callerPolicy !== undefined ? callerPolicy : hostPolicyUnderView(c.policy)])) } };
}
const advisedPolicyNames = new WeakMap();
const ADVISED_KEYS_CAP = 64;