@sema-agent/core
Version:
Stateless, task-oriented AI agent core
714 lines (713 loc) • 44.1 kB
JavaScript
import { attestationOf, engineSentenceOf } from "./engine-attestation.js";
import { isShellFaceToolName } from "./tool-registry.js";
import { inlineUntrusted } from "./untrusted-text.js";
import { foreignLine } from "./protocol-http-auth.js";
export const ASK_ORIGINS = Object.freeze(["content_question", "plan_review", "ancestor_marked", "org_unavailable", "org_rule", "rule_store_unavailable", "hook", "ask_rule", "denial_limit_fallback", "integrity_guard", "shell_gate_tighten", "safety_tighten", "policy"]);
const ASK_ORIGIN_SET = new Set(ASK_ORIGINS);
export function isAskOrigin(v) {
return ASK_ORIGIN_SET.has(v);
}
export const HOOK_QUESTION_CAUSES = Object.freeze(["asked", "verdict_unreadable", "verdict_unfinished"]);
const HOOK_QUESTION_CAUSE_SET = new Set(HOOK_QUESTION_CAUSES);
export const HOOK_CAUSE_WORDS = Object.freeze({
verdict_unreadable: "the hook's verdict could not be read",
verdict_unfinished: "the hook did not finish with a verdict",
});
export function isHookQuestionCause(v) {
return HOOK_QUESTION_CAUSE_SET.has(v);
}
export const ASK_REASON_WORDS_MAX = 500;
export const INHERITED_STATION_FACTS = { contentQuestion: false, markedUnresolvable: false, org: undefined, tightened: undefined, mandateMarks: {} };
export function hookAskReasonOf(registration, cause, reason) {
const words = cause === "asked" ? (reason !== undefined ? foreignLine(reason, ASK_REASON_WORDS_MAX) : undefined) : HOOK_CAUSE_WORDS[cause];
return Object.freeze({ by: "hook", ...(registration !== undefined ? { registration } : {}), cause, ...(words !== undefined ? { words } : {}) });
}
export function chainAskReasonsOf(receipt, call) {
const message = receipt.message;
const record = attestationOf(receipt, call);
if (record?.receivedAskReasons !== undefined)
return record.receivedAskReasons.length > 0 ? record.receivedAskReasons : undefined;
if (message === undefined || engineSentenceOf(receipt, call)?.generic === true)
return undefined;
const by = askOriginOf(receipt, { ...INHERITED_STATION_FACTS, call });
const words = inlineUntrusted(message, ASK_REASON_WORDS_MAX);
return Object.freeze([Object.freeze(by === "hook" ? { by, cause: "asked", words } : { by, words })]);
}
export function withChainAskReasons(d, call) {
if (d.action !== "ask")
return d;
const askReasons = chainAskReasonsOf(d, call);
return askReasons === undefined ? d : { ...d, askReasons };
}
export function joinAskReasons(standing, folded) {
const joined = [...(standing ?? [])];
for (const e of folded ?? [])
if (!joined.includes(e))
joined.push(e);
return joined.length > 0 ? Object.freeze(joined) : undefined;
}
export function askReasonsOf(d) {
return d.action === "ask" && d.askReasons !== undefined && d.askReasons.length > 0 ? { askReasons: d.askReasons } : {};
}
const BAD = Symbol("malformed");
function ownEntryMember(e, k) {
const d = Object.getOwnPropertyDescriptor(e, k);
if (d === undefined)
return undefined;
return "value" in d ? d.value : BAD;
}
function receivedEntry(e) {
if (typeof e !== "object" || e === null || Array.isArray(e))
return undefined;
const by = ownEntryMember(e, "by");
const words = ownEntryMember(e, "words");
if (by === "hook") {
const cause = ownEntryMember(e, "cause");
const registration = ownEntryMember(e, "registration");
if (!isHookQuestionCause(cause) || (registration !== undefined && typeof registration !== "string"))
return undefined;
if (words !== undefined && (typeof words !== "string" || (cause !== "asked" && words !== HOOK_CAUSE_WORDS[cause])))
return undefined;
return Object.freeze({ by: "hook", ...(registration !== undefined ? { registration } : {}), cause, ...(words !== undefined ? { words } : {}) });
}
if (!isAskOrigin(by) || typeof words !== "string")
return undefined;
return Object.freeze({ by: by, words });
}
export function receiveAskReasons(v) {
if (!Array.isArray(v) || v.length === 0)
return undefined;
const out = [];
for (let i = 0; i < v.length; i++) {
const entry = Object.prototype.hasOwnProperty.call(v, i) ? receivedEntry(v[i]) : undefined;
if (entry === undefined)
return undefined;
out.push(entry);
}
return Object.freeze(out);
}
export function askOriginOf(decision, facts) {
const origin = originLadder(decision, facts);
if (ORIGIN_IMPLIES_REAL_APPROVAL[origin] === "at_derivation" && decision.requiresRealApproval !== true) {
throw new Error(`ask origin "${origin}" requires the requiresRealApproval bit on the decision it was derived from, and the decision carries none — an engine mint site dropped the bit`);
}
return origin;
}
const TIGHTEN_ONLY_ORIGINS = new Set(["shell_gate_tighten", "safety_tighten"]);
export function stampAskOrigin(decision, facts, classification) {
const origin = askOriginOf(decision, facts);
const classed = { ...askClassMembersOf(classification), ...classWordsOf(classification, facts.call.toolName) };
const { mandate: _earlierStamp, ...unstamped } = decision;
const clearance = ruleClearanceOf(withFoldedOf(unstamped, attestationOf(decision, facts.call)), facts.mandateMarks);
const mandated = { ...unstamped, ...(clearance.mandated ? { mandated: true } : {}), ...(clearance.mandate !== undefined ? { mandate: clearance.mandate } : {}), ...(facts.mandateMarks.requiresUserInteraction === true ? { requiresRealApproval: true } : {}) };
if (mandated.probeReadRootCandidate === undefined || TIGHTEN_ONLY_ORIGINS.has(origin))
return { ...mandated, origin, ...classed };
const { probeReadRootCandidate: _withdrawn, ...kept } = mandated;
return { ...kept, origin, ...classed };
}
export const RULE_OFFERS_ABSENCES = Object.freeze(["mandated", "allow_outranked", "ask_rule_matched", "lane_cannot_speak"]);
const RULE_OFFERS_ABSENCE_SET = new Set(RULE_OFFERS_ABSENCES);
export function isRuleOffersAbsence(v) {
return RULE_OFFERS_ABSENCE_SET.has(v);
}
const RULE_SPEAKING_CLASSES = new Set(["ask_rule"]);
const BOUND_GRANT_CLASSES = new Set(["a2a_inside"]);
export function ruleClearanceOf(ask, marks) {
const marksWord = ask?.crossBoundaryMandated === true ? "cross_boundary_taint" : persistedRuleMandateOf({ ...marks, probeMandated: ask?.probeMandated === true });
const folded = ask?.foldedClasses ?? [];
const foldedDoor = folded.some((c) => !MODE_ARBITRATION[c].ruleMayClear && !BOUND_GRANT_CLASSES.has(c));
const doorOutsideTable = ask?.requiresRealApproval === true || ask?.decisionReason === "hook" || ask?.decisionReason === "mode" || folded.some((c) => !MODE_ARBITRATION[c].ruleMayClear && !RULE_SPEAKING_CLASSES.has(c) && !BOUND_GRANT_CLASSES.has(c)) || ask?.authoredBy === "deployment" || ask?.inheritedUnresolved === true || ask?.ancestorResolved === true;
const mandated = ask?.mandated === true || doorOutsideTable || foldedDoor || marksWord !== undefined;
const stampedWord = ask?.mandated === true && isPersistedRuleMandate(ask.mandate) ? ask.mandate : undefined;
const mandate = doorOutsideTable || (ask?.mandated === true && stampedWord === undefined) ? undefined : (stampedWord ?? marksWord);
const word = (() => {
if (ask?.requiresRealApproval === true)
return "mandated";
if (Array.isArray(ask?.allowRuleShadowed) && ask.allowRuleShadowed.some((s) => s.reason === undefined))
return "allow_outranked";
if (ask?.decisionReason === "hook")
return "mandated";
if (ask?.decisionReason === "mode" || foldedDoor)
return "mandated";
if (ask?.authoredBy === "deployment")
return "mandated";
if (ask?.matchedAskRule !== undefined)
return "ask_rule_matched";
if (ask?.inheritedUnresolved === true)
return "mandated";
if (ask?.ancestorResolved === true)
return "mandated";
return mandated ? "mandated" : undefined;
})();
return { ...(word !== undefined ? { word } : {}), mandated, ...(mandate !== undefined ? { mandate } : {}) };
}
export function standingRuleClearance(classes) {
const set = new Set(classes);
return allowMayClearOn(foldArbitrationRow(set), "rule") ? "any" : boundGrantMayClear(set) ? "bound" : "none";
}
export function withFoldedOf(facts, record) {
const folded = record?.foldedClasses;
return folded !== undefined && folded.length > 0 ? { ...facts, foldedClasses: [...folded] } : facts;
}
export function askMandateMember(ask, marks = {}) {
const { mandated, mandate } = ruleClearanceOf(ask, marks);
const authored = ask?.authoredBy === "deployment" ? { authoredBy: "deployment" } : {};
return mandated ? { mandated: true, ...(mandate !== undefined ? { mandate } : {}), ...authored } : authored;
}
export function withProbeMandate(decision, account) {
if (decision.probeMandated === true)
return decision;
const { probeReason: _arrivedWith, ...rest } = decision;
return { ...rest, probeMandated: true, ...(account !== undefined ? { probeReason: account } : {}) };
}
export function ownedClearanceFacts(d, call) {
const { mandated, requiresRealApproval, decisionReason, matchedAskRule, probeMandated, crossBoundaryMandated, authoredBy } = d;
return withFoldedOf({
...(crossBoundaryMandated === true ? { crossBoundaryMandated } : {}),
...(mandated === true ? { mandated } : {}),
...(authoredBy === "deployment" ? { authoredBy } : {}),
...(requiresRealApproval === true ? { requiresRealApproval } : {}),
...(decisionReason !== undefined ? { decisionReason } : {}),
...(typeof matchedAskRule === "string" ? { matchedAskRule } : {}),
...(probeMandated === true ? { probeMandated } : {}),
}, attestationOf(d, call));
}
function originLadder(decision, facts) {
if (facts.contentQuestion)
return "content_question";
if (facts.markedUnresolvable)
return "ancestor_marked";
if (facts.org === "unavailable")
return "org_unavailable";
if (facts.org === "rule")
return "org_rule";
if (facts.ruleCallUnreadable === true || facts.ruleStoreUnreadable === true)
return "rule_store_unavailable";
if (decision.decisionReason === "hook")
return "hook";
if (decision.matchedAskRule !== undefined)
return "ask_rule";
if (decision.denialLimitFallback !== undefined)
return "denial_limit_fallback";
if (engineSentenceOf(decision, facts.call)?.guard !== undefined)
return "integrity_guard";
if (facts.tightened === "shell_gate")
return "shell_gate_tighten";
if (facts.tightened === "safety")
return "safety_tighten";
return "policy";
}
export const ORIGIN_IMPLIES_REAL_APPROVAL = {
content_question: false,
plan_review: false,
ancestor_marked: false,
org_unavailable: "at_derivation",
org_rule: "at_derivation",
rule_store_unavailable: "at_derivation",
hook: false,
ask_rule: false,
denial_limit_fallback: "at_mint",
integrity_guard: false,
shell_gate_tighten: false,
safety_tighten: false,
policy: false,
};
export const PERSISTED_RULE_MANDATES = Object.freeze(["operator_always", "tool_marks", "probe_mandate", "probe_unanswered", "write_protection", "target_unresolved", "cross_boundary_taint"]);
const PERSISTED_RULE_MANDATE_SET = new Set(PERSISTED_RULE_MANDATES);
export function isPersistedRuleMandate(v) {
return PERSISTED_RULE_MANDATE_SET.has(v);
}
export const FINDING_ACCOUNT = Object.freeze({ reasonIs: "the account of the finding, carried on the ask as probeReason" });
export const MANDATE_DISCLOSURE = {
probe_mandate: FINDING_ACCOUNT,
probe_unanswered: "the reversibility check did not answer for this call (it timed out or failed), so whether the call is reversible is unknown",
operator_always: "this deployment mandates per-call confirmation for shell commands (shellGate: always)",
tool_marks: "this tool carries egress/irreversibility/interaction marks (a mandated confirmation)",
write_protection: "this write's target is on the deployment's write-protection table (the agent's own configuration is guarded one look per write)",
target_unresolved: "where this write leads on disk could not be determined (a link on the way could not be examined, or the environment could not resolve the target), so whether it lands on a guarded path is unknown; no automatic decider answers for it, though a wired approver seat can",
cross_boundary_taint: "this run executes on a device outside the deployment's trust boundary and the deployment is multi-tenant, so an org-side write — or, after an off-target read, a call bound for the device — is confirmed by the deployment's approver for this call: no automatic lane answers for it, and an allow the configuration gives (a blanket seat or a policy's answer) is refused",
};
export const ASK_RULE_DISCLOSURE = "an explicit ask rule matched this call (a person's or the deployment's ask-me-each-time outranks a standing allow rule)";
export function mandateDisclosureOf(mandate, account) {
if (mandate === undefined)
return ASK_RULE_DISCLOSURE;
const row = MANDATE_DISCLOSURE[mandate];
return typeof row === "string" ? row : account;
}
export function persistedRuleMandateOf(marks) {
if (marks.targetUnresolved === true)
return "target_unresolved";
const word = irreversibilityMandateOf(marks);
if (word === "probe_mandate" || word === "probe_unanswered")
return word;
if (marks.writeProtected === true || marks.writeProtectedOnDisk === true)
return "write_protection";
return marks.egress === true || marks.requiresUserInteraction === true ? "tool_marks" : word;
}
function irreversibilityMandateOf(marks) {
return marks.probeMandated === true
? "probe_mandate"
: marks.probeUnanswered === true
? "probe_unanswered"
: marks.shellGated === true
? marks.irreversibility === "always"
? "operator_always"
: undefined
: marks.irreversibility === "always" || marks.irreversibility === "maybe"
? "tool_marks"
: undefined;
}
export function safetyAxisOf(marks) {
const egress = marks.egress === true;
const raised = irreversibilityMandateOf(marks) !== undefined ||
(marks.shellGated === true && marks.irreversibility === "maybe" && marks.tightened === "shell_gate");
const shell = raised && marks.shellGated === true;
return egress || raised ? { egress, irreversible: raised && !shell, ...(shell ? { shell: true } : {}) } : undefined;
}
export const PERMISSION_MODES = Object.freeze(["default", "acceptEdits", "plan", "auto", "bypassPermissions", "dontAsk"]);
const PERMISSION_MODE_SET = new Set(PERMISSION_MODES);
export function isPermissionMode(v) {
return PERMISSION_MODE_SET.has(v);
}
export const PERMISSION_MODE_RANK = { plan: 0, default: 1, dontAsk: 1, acceptEdits: 2, auto: 3, bypassPermissions: 4 };
export function clampPermissionMode(declared, ceiling) {
if (declared === undefined)
return { effective: ceiling, clamped: false };
if (declared === ceiling)
return { effective: declared, clamped: false };
if (declared === "bypassPermissions")
return { effective: ceiling, clamped: true };
if ((declared === "acceptEdits" && ceiling === "auto") || (declared === "auto" && ceiling === "acceptEdits"))
return { effective: ceiling, clamped: true };
return PERMISSION_MODE_RANK[declared] <= PERMISSION_MODE_RANK[ceiling] ? { effective: declared, clamped: false } : { effective: ceiling, clamped: true };
}
export const ASK_CLASSES = Object.freeze([
"content_question",
"hook",
"ancestor",
"dangerous_delete",
"transcript_write",
"org_rule",
"org_unreadable",
"rule_unreadable",
"call_unreadable",
"ask_rule",
"denial_limit_fallback",
"classifier_no_ruling",
"requires_user_interaction",
"cross_boundary",
"operator_forced",
"shell_floor",
"target_unresolved",
"probe",
"write_protection_on_disk",
"write_protection",
"tool_marks_mcp",
"tool_marks_a2a",
"unfinished_check",
"policy_rra",
"artifact_shared_read",
"mode",
"a2a_inside",
"unverifiable_delete",
"unverifiable_shell_text",
"sandbox_override",
"sandbox_network",
"unstated",
"ordinary",
]);
const ASK_CLASS_SET = new Set(ASK_CLASSES);
export function isAskClass(v) {
return ASK_CLASS_SET.has(v);
}
export function sandboxOverrideMessage(toolName) {
return `Run outside of the sandbox: this ${toolName.slice(0, 64)} call sets dangerouslyDisableSandbox, so its command would run without the run's OS sandbox restrictions.`;
}
export function classWordsOf(classification, toolName) {
return classification.askClass === "sandbox_override" ? { message: sandboxOverrideMessage(toolName) } : {};
}
export function allowMayClearOn(row, kind) {
return row.ruleMayClear && (kind === "rule" || !row.hookAskFloor);
}
export function boundGrantMayClear(classes) {
if (![...classes].some((c) => BOUND_GRANT_CLASSES.has(c)))
return false;
return foldArbitrationRow(new Set([...classes].filter((c) => !BOUND_GRANT_CLASSES.has(c)))).ruleMayClear;
}
const A2A_INSIDE_GRANT_SENTENCE = "this peer is registered inside the trust boundary, and an allow-list entry bound to its current identity stamp (`{ rule: \"a2a__<peer>\", peerFingerprint: <the stamp its registration carries> }` in `RunnerDeps.allowedTools` / `TaskSpec.allowedTools`)";
const ORDINARY_ROW = Object.freeze({ bypassImmune: false, classifierEligible: true, sandboxAdmission: true, ruleMayClear: true, hookAskFloor: false });
export const MODE_ARBITRATION = {
content_question: { bypassImmune: true, classifierEligible: false, sandboxAdmission: false, ruleMayClear: false, hookAskFloor: true },
hook: { bypassImmune: true, classifierEligible: false, sandboxAdmission: false, ruleMayClear: false, hookAskFloor: false },
ancestor: { bypassImmune: true, classifierEligible: false, sandboxAdmission: false, ruleMayClear: false, hookAskFloor: false },
dangerous_delete: { bypassImmune: true, classifierEligible: false, sandboxAdmission: false, ruleMayClear: false, hookAskFloor: true },
transcript_write: { bypassImmune: false, classifierEligible: true, sandboxAdmission: false, ruleMayClear: false, hookAskFloor: true },
org_rule: { bypassImmune: true, classifierEligible: false, sandboxAdmission: false, ruleMayClear: false, hookAskFloor: false },
org_unreadable: { bypassImmune: true, classifierEligible: false, sandboxAdmission: false, ruleMayClear: false, hookAskFloor: false },
rule_unreadable: { bypassImmune: false, classifierEligible: true, sandboxAdmission: false, ruleMayClear: false, hookAskFloor: false },
call_unreadable: { bypassImmune: true, classifierEligible: false, sandboxAdmission: false, ruleMayClear: false, hookAskFloor: false },
ask_rule: { bypassImmune: true, classifierEligible: false, sandboxAdmission: false, ruleMayClear: false, hookAskFloor: true },
denial_limit_fallback: { bypassImmune: true, classifierEligible: false, sandboxAdmission: false, ruleMayClear: false, hookAskFloor: false },
classifier_no_ruling: { bypassImmune: true, classifierEligible: false, sandboxAdmission: false, ruleMayClear: false, hookAskFloor: false },
requires_user_interaction: { bypassImmune: true, classifierEligible: false, sandboxAdmission: false, ruleMayClear: false, hookAskFloor: true },
cross_boundary: { bypassImmune: true, classifierEligible: false, sandboxAdmission: false, ruleMayClear: false, hookAskFloor: false },
operator_forced: { bypassImmune: true, classifierEligible: true, sandboxAdmission: true, ruleMayClear: false, hookAskFloor: false },
shell_floor: { bypassImmune: true, classifierEligible: true, sandboxAdmission: true, ruleMayClear: false, hookAskFloor: false },
target_unresolved: { bypassImmune: true, classifierEligible: false, sandboxAdmission: true, ruleMayClear: false, hookAskFloor: true },
probe: { bypassImmune: false, classifierEligible: true, sandboxAdmission: false, ruleMayClear: false, hookAskFloor: false },
write_protection_on_disk: { bypassImmune: false, classifierEligible: true, sandboxAdmission: true, ruleMayClear: false, hookAskFloor: true },
write_protection: { bypassImmune: false, classifierEligible: true, sandboxAdmission: true, ruleMayClear: false, hookAskFloor: true },
tool_marks_mcp: { bypassImmune: false, classifierEligible: true, sandboxAdmission: true, ruleMayClear: false, hookAskFloor: false },
tool_marks_a2a: { bypassImmune: false, classifierEligible: true, sandboxAdmission: true, ruleMayClear: false, hookAskFloor: false },
unfinished_check: { bypassImmune: true, classifierEligible: false, sandboxAdmission: false, ruleMayClear: false, hookAskFloor: true },
policy_rra: { bypassImmune: true, classifierEligible: true, sandboxAdmission: false, ruleMayClear: false, hookAskFloor: false },
artifact_shared_read: { bypassImmune: false, classifierEligible: true, sandboxAdmission: false, ruleMayClear: false, hookAskFloor: true },
mode: { bypassImmune: false, classifierEligible: false, sandboxAdmission: false, ruleMayClear: false, hookAskFloor: false },
a2a_inside: { bypassImmune: false, classifierEligible: true, sandboxAdmission: false, ruleMayClear: false, hookAskFloor: false },
unverifiable_delete: ORDINARY_ROW,
unverifiable_shell_text: ORDINARY_ROW,
sandbox_override: { bypassImmune: false, classifierEligible: true, sandboxAdmission: false, ruleMayClear: true, hookAskFloor: true },
sandbox_network: { bypassImmune: false, classifierEligible: true, sandboxAdmission: false, ruleMayClear: true, hookAskFloor: false },
unstated: { bypassImmune: false, classifierEligible: true, sandboxAdmission: false, ruleMayClear: true, hookAskFloor: false },
ordinary: ORDINARY_ROW,
};
export const ASK_FACES = Object.freeze(["shell", "other"]);
export function askFaceOf(toolName) {
return isShellFaceToolName(toolName) ? "shell" : "other";
}
const RELEASED_ON_SHELL_FACE = new Set(["target_unresolved"]);
export const RELEASED_ON_CONFINED_RUNNER = Object.freeze(["unfinished_check"]);
const CONFINED_RELEASE = new Set(RELEASED_ON_CONFINED_RUNNER);
function bypassImmuneOn(c, face, confined = false) {
return MODE_ARBITRATION[c].bypassImmune && !(face === "shell" && RELEASED_ON_SHELL_FACE.has(c)) && !(confined && CONFINED_RELEASE.has(c));
}
function bypassImmuneOf(c, confined = false) {
return [...c.classes].some((k) => bypassImmuneOn(k, c.askFace, confined));
}
const CLASSIFIER_WITHHELD_ON_ROOTS = new Set(["probe"]);
function bareBit(d, classes) {
return d.requiresRealApproval === true && !explainsRealApprovalBit(classes);
}
export const RRA_EXPLAINERS = new Set(["dangerous_delete", "transcript_write", "org_rule", "org_unreadable", "rule_unreadable", "call_unreadable", "denial_limit_fallback", "classifier_no_ruling", "ancestor", "artifact_shared_read", "requires_user_interaction", "cross_boundary", "unfinished_check"]);
export function explainsRealApprovalBit(classes) {
for (const c of classes)
if (RRA_EXPLAINERS.has(c))
return true;
return false;
}
const releasableOn = (face, confined) => Object.freeze(ASK_CLASSES.filter((c) => !bypassImmuneOn(c, face, confined)));
const RELEASABLE_BY_FACE = Object.freeze({
shell: Object.freeze({ unconfined: releasableOn("shell", false), confined: releasableOn("shell", true) }),
other: Object.freeze({ unconfined: releasableOn("other", false), confined: releasableOn("other", true) }),
});
export function releasableAskClassesFor(face) {
return releasableListFor(face, "releasableAskClassesFor").unconfined;
}
export function confinedReleasableAskClassesFor(face) {
return releasableListFor(face, "confinedReleasableAskClassesFor").confined;
}
function releasableListFor(face, reader) {
if (!ASK_FACES.includes(face))
throw new TypeError(`${reader}: "${String(face)}" is not an ask face (${ASK_FACES.join(", ")})`);
return RELEASABLE_BY_FACE[face];
}
export const MODE_RELEASE_REASONS = Object.freeze(["target_unresolved"]);
const MODE_RELEASE_REASON_SET = new Set(MODE_RELEASE_REASONS);
export function isModeReleaseReason(v) {
return MODE_RELEASE_REASON_SET.has(v);
}
export function askClassMembersOf(c) {
return { askClass: c.askClass, classes: Object.freeze(ASK_CLASSES.filter((k) => c.classes.has(k))) };
}
function leadingAskClassOf(held) {
return ASK_CLASSES.find((k) => held.has(k));
}
export function screenAskClassMembers(askClass, classes) {
if (!isAskClass(askClass) || !Array.isArray(classes) || classes.length === 0 || !classes.every(isAskClass))
return undefined;
const held = new Set(classes);
const ordered = ASK_CLASSES.filter((k) => held.has(k));
if (ordered.length !== classes.length || !held.has(askClass))
return undefined;
return { askClass: leadingAskClassOf(held), classes: Object.freeze(ordered) };
}
export function ownAskClassesOf(d, record) {
const out = new Set();
for (const guard of record?.guards ?? [])
out.add(guard);
if (d.ruleUnreadable !== undefined)
out.add(d.ruleUnreadable === "persisted_rows" ? "rule_unreadable" : "call_unreadable");
if (d.matchedAskRule !== undefined)
out.add("ask_rule");
if (d.denialLimitFallback !== undefined)
out.add("denial_limit_fallback");
if (d.classifierNoRuling !== undefined)
out.add("classifier_no_ruling");
if (d.authoredBy === "deployment")
out.add("operator_forced");
if (d.probeMandated === true)
out.add("probe");
if (d.crossBoundaryMandated === true)
out.add("cross_boundary");
if (d.decisionReason === "hook")
out.add("hook");
if (d.decisionReason === "mode")
out.add("mode");
if (bareBit(d, out))
out.add("policy_rra");
if (out.size === 0 && d.mandated === true)
out.add("operator_forced");
return out;
}
export function decisionAskClassesOf(d, call) {
const record = attestationOf(d, call);
const out = ownAskClassesOf(d, record);
for (const c of record?.foldedClasses ?? [])
out.add(c);
return out;
}
export function foldArbitrationRow(classes, readFace, askFace) {
if (classes.size === 0)
return MODE_ARBITRATION.ordinary;
const withheld = readFace === "roots" && [...classes].some((c) => CLASSIFIER_WITHHELD_ON_ROOTS.has(c));
let bypassImmune = false, classifierEligible = !withheld, sandboxAdmission = true, ruleMayClear = true, hookAskFloor = false;
for (const c of classes) {
const row = MODE_ARBITRATION[c];
bypassImmune ||= bypassImmuneOn(c, askFace);
classifierEligible &&= row.classifierEligible;
sandboxAdmission &&= row.sandboxAdmission;
ruleMayClear &&= row.ruleMayClear;
hookAskFloor ||= row.hookAskFloor;
}
return { bypassImmune, classifierEligible, sandboxAdmission, ruleMayClear, hookAskFloor };
}
export function classifyAsk(d, facts) {
const record = attestationOf(d, facts.call);
const classes = ownAskClassesOf(d, record);
classes.delete("policy_rra");
if (facts.contentQuestion)
classes.add("content_question");
if (facts.markedUnresolvable)
classes.add("ancestor");
if (facts.org === "rule")
classes.add("org_rule");
if (facts.org === "unavailable")
classes.add("org_unreadable");
if (facts.ruleStoreUnreadable === true)
classes.add("rule_unreadable");
if (facts.ruleCallUnreadable === true)
classes.add("call_unreadable");
const marks = facts.mandateMarks;
if (marks.requiresUserInteraction === true)
classes.add("requires_user_interaction");
if (marks.shellGated === true && marks.irreversibility === "always")
classes.add("shell_floor");
const toolMarked = marks.egress === true || (marks.shellGated !== true && (marks.irreversibility === "always" || marks.irreversibility === "maybe"));
if (toolMarked) {
const sources = facts.toolMarkSources;
if (sources === undefined || sources.size === 0 || sources.has("deployment"))
classes.add("operator_forced");
if (sources?.has("mcp_annotation"))
classes.add("tool_marks_mcp");
if (sources?.has("a2a_default"))
classes.add(facts.a2aIsolatePeers === true ? "operator_forced" : "tool_marks_a2a");
}
if (marks.probeUnanswered === true)
classes.add("probe");
if (marks.targetUnresolved === true)
classes.add("target_unresolved");
if (marks.writeProtected === true)
classes.add("write_protection");
if (marks.writeProtectedOnDisk === true)
classes.add("write_protection_on_disk");
if (facts.leavesSandbox === true)
classes.add("sandbox_override");
if (facts.a2aInside === true)
classes.add("a2a_inside");
if (facts.tightened === "unstated")
classes.add("unstated");
for (const c of facts.ancestorClasses ?? [])
classes.add(c);
if (bareBit(d, classes))
classes.add("policy_rra");
for (const c of record?.foldedClasses ?? [])
classes.add(c);
if (classes.size === 0 && d.mandated === true)
classes.add("operator_forced");
if (classes.size === 0)
classes.add("ordinary");
const askClass = leadingAskClassOf(classes);
return { classes, askClass, row: foldArbitrationRow(classes, facts.readFace, facts.askFace), ...(facts.askFace !== undefined ? { askFace: facts.askFace } : {}) };
}
export const USER_REFUSED_TOOL_USE = "The user doesn't want to proceed with this tool use", DELEGATED_TOOL_USE_DENIED = "Permission for this tool use was denied";
export const PROCEED_ON_JUDGMENT = "Proceed with your best judgment: pick the most reasonable option, state the assumption you made, and continue.";
export function unansweredAskRefusal(ask) {
if (ask.cause === "question") {
const why = ask.noAttempt ? (ask.leg !== undefined ? ` (${ask.leg})` : "") : " (nothing here can keep it waiting for an answer, or setting it aside failed)";
return `This question was refused: it needs a person's answer, and no live face answered it${why}. It has NO answer. ${PROCEED_ON_JUDGMENT}`;
}
const wait = (one) => (ask.parkFailed ? "" : `, and nothing here can keep the request waiting for ${one}`);
const why = ask.cause === "no_approver_wired" ? "permission prompts are not available in this session"
: ask.cause === "approval_window_expired" ? `the approval window for it closed with no one answering it${wait("a person")}`
: `the approver reported that nobody can be reached to approve it${wait("one")}`;
const retry = ask.cause === "no_approver_wired" && !ask.parkFailed ? ", and do not retry it in this session" : "";
return `${DELEGATED_TOOL_USE_DENIED}: it requires interactive approval, and ${why}. The action was NOT performed. Do not claim it succeeded${retry} — report the limitation to the user, or suggest an alternative. What was requested: ${ask.question}`;
}
export function unresolvedAskDenialMessage(cause, question, parkFailed) {
return unansweredAskRefusal({ cause, question, parkFailed });
}
export const NOBODY_CAN_APPROVE = "nobody on this run can approve it, so do not ask for it again, and do not get the same effect another way to avoid the approval — go on with the work that does not need it, and say in your final result which step was skipped and still needs approval";
const REFUSED_CAPABILITY_GUIDANCE = "IMPORTANT: you may try to accomplish this with other tools that would naturally be used for it (for example `head` instead of `cat`), but do not work around this denial in malicious ways — for example, do not use your ability to run tests to run non-test actions; only work around it in reasonable ways that keep to the intent behind it. If you believe this capability is essential to complete the user's request, STOP and explain to the user what you were trying to do and why you need this permission, and let the user decide how to proceed.";
export function dontAskRefusalMessage(input) {
const remedy = headlessApprovalRemedy({ mode: "dontAsk", classification: input.classification, coveredWrite: input.coveredWrite, ruleShape: input.ruleShape }).sentence;
const question = input.question !== undefined ? inlineUntrusted(input.question, ASK_REASON_WORDS_MAX) : "";
return `Permission to use ${input.toolName} has been denied because this run is in the dontAsk permission mode (this call needed approval${question !== "" ? `: ${question}` : ""}). ${REFUSED_CAPABILITY_GUIDANCE} To let a call like this run: ${remedy}.`;
}
export const APPROVAL_REMEDY_KINDS = Object.freeze(["approver", "permission_mode", "park"]);
const APPROVAL_REMEDY_KIND_SET = new Set(APPROVAL_REMEDY_KINDS);
export function isApprovalRemedyKind(v) {
return APPROVAL_REMEDY_KIND_SET.has(v);
}
export function readApprovalRemedy(v) {
if (typeof v !== "object" || v === null || Array.isArray(v))
return undefined;
const keys = Object.keys(v);
const field = (k) => (keys.includes(k) ? v[k] : undefined);
const kind = field("kind");
if (!isApprovalRemedyKind(kind))
return undefined;
switch (kind) {
case "approver":
case "park":
return keys.length === 1 ? { kind } : undefined;
case "permission_mode": {
const value = field("value");
const disclosedOn = field("disclosedOn");
return keys.length === 3 && value === "bypassPermissions" && disclosedOn === "gate.disposition.released" ? { kind, value, disclosedOn } : undefined;
}
default: {
const _exhaustive = kind;
return _exhaustive;
}
}
}
const CROSS_BOUNDARY_EARLIER_YES = "an earlier yes from the policy or an approval factory does not answer this question";
const APPROVER_REMEDY = Object.freeze({ kind: "approver" });
const RELEASE_REMEDY = Object.freeze({ kind: "permission_mode", value: "bypassPermissions", disclosedOn: "gate.disposition.released" });
const PARK_REMEDY = Object.freeze({ kind: "park" });
export function withParkRemedy(headless, parkFailed) {
return {
sentence: `the durable approval park for this call could not be set aside (${parkFailed}) — once it can be, the ask waits for a person; or ${headless.sentence}`,
remedies: Object.freeze([PARK_REMEDY, ...headless.remedies]),
};
}
export function headlessApprovalRemedy(input) {
const way = (sentence, release = false) => ({ sentence, remedies: Object.freeze(release ? [APPROVER_REMEDY, RELEASE_REMEDY] : [APPROVER_REMEDY]) });
if (input.mode === "dontAsk") {
const c = input.classification;
const orMode = (head) => (input.approverSeat === "nobody" ? `${head}; ${NOBODY_CAN_APPROVE}` : `${head}, or run under a mode with an approver`);
if (c !== undefined && boundGrantMayClear(c.classes))
return way(orMode(`${A2A_INSIDE_GRANT_SENTENCE} answers it under dontAsk`));
return way(c?.row.ruleMayClear === true
? orMode(`an allow rule covering this call answers it under dontAsk — add one${input.ruleShape !== undefined ? ` in this tool's rule shape (\`${input.ruleShape}\`)` : ""} to the allow rules (a settings file's \`permissions.allow\`, or the request's or the deployment's allow list)`)
: input.approverSeat === "nobody"
? `no allow rule answers this ask — change the call; ${NOBODY_CAN_APPROVE}`
: `no allow rule answers this ask — only a person can: run under a mode with an approver, or change the call`);
}
const approver = input.approverSeat === "nobody"
? undefined
: input.notResumableWayOut !== undefined
? input.notResumableWayOut
: input.approverSeat === "unavailable"
? "make a person reachable through the approver that is wired (it answered `unavailable` for this ask)"
: input.approverSeat === "window_expired"
? "have a person answer it within the approval window of the approver that is wired (that window closed with no one answering this ask), or arm a durable approval park so the ask waits for a person"
: input.approverSeat === "policy"
? "the deployment's approval policy answered `unavailable` for this ask — arm a durable approval park so the ask waits for a person, or run it where a person can be asked"
: input.approverSeat === "declared_none"
? input.approvalParkWithheld === true
? 'run it where a person can be asked — this run declares `approvalReach: "none"` (nobody on it can be asked), and a workflow member\'s permission ask does not park under this declaration'
: 'run it where a person can be asked — this run declares `approvalReach: "none"` (nobody on it can be asked) — or arm a durable approval park so the ask waits for a person (a workflow member\'s permission ask does not park under this declaration: take that step on the leg that started the workflow)'
: "have whoever runs this host connect an approver that can put the question to a person (this run has none; an embedding application uses `onAsk`)";
const orApprover = (head, join = ", or ") => (approver !== undefined ? `${head}${join}${approver}` : `${head}; ${NOBODY_CAN_APPROVE}`);
const c = input.classification;
if (input.mode === "acceptEdits" && input.unplacedOptions !== undefined && (c === undefined || (c.classes.size === 1 && c.classes.has("ordinary"))))
return way(orApprover(`${fileCommandOptionsSentence(input.unplacedOptions.program)} Spell the ${input.unplacedOptions.program} without option words for the mode to answer it`));
const confinedRelease = c !== undefined && bypassImmuneOf(c) && releasedOnConfinedRunner(c, input.confined, input.mode) && input.confined?.bypassArmed() === true;
if (c !== undefined && bypassImmuneOf(c) && !confinedRelease) {
const rowAlone = input.writeAskRowOwnCard === true && writeAskRowsCountNow(input.mode) && c.classes.has("ask_rule") && [...c.classes].every((k) => k === "ask_rule" || !bypassImmuneOn(k, c.askFace));
const earlierYes = c.classes.has("cross_boundary") ? ` — ${CROSS_BOUNDARY_EARLIER_YES}` : rowAlone ? " (or take the written path out of the ask rule that asks it)" : "";
return way(approver !== undefined ? `no permission mode releases this ask: ${approver}, or change the call${earlierYes}` : `no permission mode releases this ask: change the call${earlierYes}; ${NOBODY_CAN_APPROVE}`);
}
if (input.mode === "plan" && c?.classes.has("mode") === true)
return way(orApprover(`the plan permission mode asks before every write and every call to a tool the engine does not define that is not read-only — leave plan mode (\`setPermissionMode\` to another mode${approver !== undefined ? ", or approve the plan" : ""}) to run it`), confinedRelease);
if (c !== undefined && boundGrantMayClear(c.classes))
return way(orApprover(`${A2A_INSIDE_GRANT_SENTENCE} answers it`), true);
if (c !== undefined && c.classes.size === 1 && c.classes.has("unstated"))
return way(orApprover(`no allow entry, stored allow rule or hook granted this tool, and it states no permission of its own — grant it with an allow entry for its name (\`RunnerDeps.allowedTools\` / \`TaskSpec.allowedTools\`)`), true);
const onlyOrdinary = c === undefined || (c.classes.size === 1 && c.classes.has("ordinary"));
if (input.coveredWrite && onlyOrdinary) {
if (input.mode === "acceptEdits")
return way(orApprover(`under \`permissionMode: "acceptEdits"\` the mode asks only for a write outside the working directories — if this target is outside them, add its directory to \`additionalDirectories\``, "; otherwise (or besides) "));
if (input.mode === undefined || input.mode === "default" || input.mode === "auto")
return way(orApprover(`the mode's write gate asks every write under \`default\`: \`permissionMode: "acceptEdits"\` lets writes inside the working directories (the task root and \`additionalDirectories\`) through without asking (a question another policy raised still stands)`));
}
return way(approver ?? NOBODY_CAN_APPROVE, true);
}
export function fileCommandOptionsSentence(program) {
return `${program} with flags requires manual approval to ensure path safety: the mode cannot automatically validate ${program} commands that use flags, as some flags like --target-directory=PATH can bypass path validation.`;
}
export const WRITE_FACE_ASK_ROW_COUNTS = Object.freeze({ default: false, acceptEdits: false, plan: false, auto: false, dontAsk: false, bypassPermissions: true });
export function writeAskRowsCountNow(mode) {
return mode !== undefined && WRITE_FACE_ASK_ROW_COUNTS[mode];
}
export function stationAskRowOf(verdict, mode) {
if (verdict.askRule !== undefined)
return { rule: verdict.askRule, policy: verdict.askRuleOfPolicy === true, face: "read" };
if (verdict.writeAskRule !== undefined && writeAskRowsCountNow(mode))
return { rule: verdict.writeAskRule, policy: verdict.writeAskRuleOfPolicy === true, face: "write" };
return undefined;
}
function releasedOnConfinedRunner(c, confined, mode) {
return confined !== undefined && bypassImmuneOf(c) && !bypassImmuneOf(c, true) && !confined.personAlreadyRequired() && confined.destinationOnHands() && confined.unseenGuardsNothing(mode);
}
export function modeAnswersUnasked(mode, c) {
return mode === "bypassPermissions" ? !bypassImmuneOn(c, undefined) : mode === "auto" ? MODE_ARBITRATION[c].classifierEligible : false;
}
export function arbitrateByMode(mode, c, disclosure, call) {
const has = (k) => c.classes.has(k);
const classes = ASK_CLASSES.filter((k) => c.classes.has(k));
switch (mode) {
case "dontAsk":
return has("hook") && !c.row.hookAskFloor ? { kind: "ask" } : { kind: "denied_by_mode", mode, askClass: c.askClass, classes };
case "bypassPermissions":
if (has("target_unresolved") && bypassImmuneOn("target_unresolved", c.askFace))
return { kind: "denied_by_mode", mode, askClass: c.askClass, classes };
const confined = releasedOnConfinedRunner(c, call?.confined, mode);
if (bypassImmuneOf(c) && !confined)
return { kind: "ask" };
if (call?.writeAskRow === true && writeAskRowsCountNow(mode))
return { kind: "ask", heldByWriteAskRow: true };
const reason = [...MODE_RELEASE_REASON_SET].find((r) => has(r));
return {
kind: "released",
mode,
askClass: c.askClass,
classes,
...(disclosure?.origin !== undefined ? { origin: disclosure.origin } : {}),
...(disclosure?.mandate !== undefined ? { mandate: disclosure.mandate } : {}),
...(reason !== undefined ? { reason } : {}),
...(confined ? { confined: true } : {}),
};
case "acceptEdits":
return call?.fileCommand === true && c.classes.size === 1 && c.classes.has("ordinary") ? { kind: "accepted", mode } : { kind: "ask" };
case "plan":
case "default":
case "auto":
return { kind: "ask" };
default: {
const _exhaustive = mode;
return _exhaustive;
}
}
}