@sema-agent/core
Version:
Stateless, task-oriented AI agent core
1,567 lines • 91.4 kB
JavaScript
import { createHash } from "node:crypto";
import { homedir } from "node:os";
import { argsReadFrom, carryArgsReadFrom, withArgsReading } from "./effective-path-target.js";
import { editRewrittenSentence, readRejudge, rewriteChasedSentence } from "./rewrite-rejudge.js";
import { brandPolicyAskClass } from "./ask-class.js";
import { ASK_CLASSES, DELEGATED_TOOL_USE_DENIED, decisionAskClassesOf, explainsRealApprovalBit, joinAskReasons, MODE_ARBITRATION, unresolvedAskDenialMessage, USER_REFUSED_TOOL_USE } from "./ask-origin.js";
import { attest, attestationOf, engineSentenceOf, isEngineAttestation, mergeAttestation, mintAttestation, withAttestation } from "./engine-attestation.js";
import { ownReadRootCandidate, readRootGrantSeat } from "./read-root-grant-screen.js";
import { ownSessionCallGrantOffer, sessionCallGrantSeat } from "./session-call-grant-screen.js";
import { liveWordsOf } from "./approval-words.js";
import { DECIDED_VIA, DECIDED_VIA_MAY_ALLOW, decidersNote, isDecidedVia, policyDeciderOf, settledByDecider } from "./gate-outcome.js";
import { unjudgedAllowRefused } from "./real-approval.js";
import { askCardMessageOf, withEngineCardWords } from "./ask-headline.js";
import { receiveMembers } from "./own-property-receipt.js";
import { isBlankInput } from "./input-author.js";
export { policyCannotAnswer, rowDemandsAPerson } from "./real-approval.js";
import { sanitizeAutoModeArmingRecipe } from "./auto-mode-arming.js";
import { join, normalize as normalizePath, sep } from "node:path";
import { dataRootSpelling } from "./data-root.js";
import { BASH_READONLY_DEFAULT_ALLOW } from "../tools/fs/index.js";
import { readOnlyCallVerdict } from "./read-only-shell.js";
import { DEFAULT_GATE_AWAIT_TIMEOUT_MS, withGateTimeout } from "./gate-bounded-await.js";
import { protectivePathTargetOf, shellFaceToolNames } from "./tool-registry.js";
import { heldBy } from "./tool-name-readings.js";
import { bindableValueOf, describeBindingFault, editOfAnswer, exactBoundInputHashOf } from "./canonical-json.js";
import { delimitUntrusted, inlineUntrusted, REVIEWER_NOTE_MAX_BODY } from "./untrusted-text.js";
import { foreignLine } from "./protocol-http-auth.js";
import { describeRejectedValue } from "./tool-search-setting.js";
import { egressText, egressThrownText } from "./untrusted-egress.js";
import { assertNoRetiredKeys, assertNoRetiredToolPolicyKeys, RETIRED_DECISION_MEMBERS, RETIRED_TOOL_POLICY_KEYS } from "./retired-keys.js";
import { DECISION_MEMBER_ARMS, HOOK_SEAT_MEMBER_ARMS, isEngineRefusal, nestedRecordsOf, receiveContract, receiveNestedRecords, refusedOutOfContract, screenContractValues } from "./decision-receipt.js";
export { isEngineRefusal } from "./decision-receipt.js";
import { isCoveringRuleName, ruleNameCovers } from "./namespaced-rule-name.js";
import { coarseCommandNameProblem, coarseCallVerdictOf, isRuleBehavior, ruleContentOf } from "./permission-rule-model.js";
import { grantWildcardRefusalOf, protocolOf, ruleSpellingOf } from "@sema-agent/primitives";
import { anchorSpelling, isAbsoluteForFamily, normalizeAbsPathLexically, pathFamilyOf, writeTargetPath } from "../tools/fs/safety.js";
import { KNOWN_SAFE_ROOTS, removalReadingOf } from "../tools/fs/removal-targets.js";
const nameListHolds = (set, req) => heldBy("policy.nameLists", set, req);
const shellToolsListHolds = (set, req) => heldBy("policy.shellToolsList", set, req);
export function advertisedWritableRootsSeat(seat) {
return seat === undefined ? {} : { advertisedWritableRoots: Object.freeze([...seat.roots]) };
}
export function exemptRootsSeat(exemptRoots) {
return { exemptRoots };
}
export function callFactsSeat(f) {
return {
...(f.cwd !== undefined ? { cwd: f.cwd } : {}),
...(f.root !== undefined ? { root: f.root } : {}),
...(f.face !== undefined ? { face: f.face } : {}),
...(f.budget !== undefined ? { budget: f.budget } : {}),
...advertisedWritableRootsSeat(f.advertisedWritableDirs),
...(f.exemptRoots !== undefined ? exemptRootsSeat(f.exemptRoots) : {}),
};
}
function settledByNobody(kind) {
return { kind, who: { party: "none" }, when: Date.now() };
}
export { attest, attestationOf, hostWindowUnanswered, isEngineAttestation, mergeAttestation, mintAttestation, withAttestation } from "./engine-attestation.js";
const UNASKED_SEAT_SETTLEMENTS = new Set(["task_aborted", "no_approver"]);
function seatNeverAsked(settlement) {
return settlement !== undefined && UNASKED_SEAT_SETTLEMENTS.has(settlement.kind);
}
function unaskedSeatDeny(req, kind, message, origin) {
return attest({ action: "deny", message }, req, { settlement: settledByNobody(kind), origin });
}
export function noApproverSeatDeny(req, message, origin) {
return unaskedSeatDeny(req, "no_approver", message, origin);
}
export function abortedSeatDeny(req, message, origin) {
return unaskedSeatDeny(req, "task_aborted", message, origin);
}
export function unaskedSeatAnswer(req, signal, say, origin) {
if (signal?.aborted === true)
return abortedSeatDeny(req, say.aborted, origin);
if (req.approvalReach === "none")
return noApproverSeatDeny(req, say.unreachable, origin);
return undefined;
}
export const APPROVER_ATTRIBUTION_MAX_CHARS = 256;
const APPROVER_REFUSED_CHARS_RE = /[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/u;
export function screenApproverAttribution(v) {
if (v === undefined || v === "")
return {};
if (typeof v !== "string") {
return { defect: `an approver attribution must be a plain string (got ${v === null ? "null" : typeof v})` };
}
if (v.length > 2 * APPROVER_ATTRIBUTION_MAX_CHARS || [...v].length > APPROVER_ATTRIBUTION_MAX_CHARS) {
return { defect: `an approver attribution is capped at ${APPROVER_ATTRIBUTION_MAX_CHARS} characters and this one is longer; it is refused rather than truncated, because a cut identifier names someone else` };
}
if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(v)) {
return { defect: "an approver attribution contains an unpaired surrogate; it is not well-formed text and would collapse to a replacement character in a UTF-8 sink, so two distinct approvers could converge into one record" };
}
if (APPROVER_REFUSED_CHARS_RE.test(v)) {
return { defect: "an approver attribution carries control characters, line separators or bidirectional overrides; an identifier whose bytes can forge a line — or reorder what a reader sees — in whatever renders it is refused" };
}
if (isBlankInput(v)) {
return { defect: "an approver attribution of only whitespace names nobody; give an identifier with a visible character, or none at all (an empty string reads as none)" };
}
return { approver: v };
}
export function screenDecidedVia(v, word, allows) {
if (v === undefined)
return {};
if (!isDecidedVia(v)) {
return {
defect: `decidedVia is outside the closed set (got ${v === null ? "null" : typeof v === "string" ? "a string that is not a member" : typeof v}) — it is exactly ${DECIDED_VIA.map((w) => `"${w}"`).join(" or ")}, or omitted`,
};
}
if (word !== "policy")
return { defect: `decidedVia names which machine seat answered for the deployment's policy, and this decision reports "${word}" — the member rides a "policy" decision only` };
if (allows && !DECIDED_VIA_MAY_ALLOW[v])
return { defect: `decidedVia "${v}" names a seat that only refuses — it cannot be what approved a call (report it on a refusal)` };
return { decidedVia: v };
}
export const ASK_EVIDENCE_ABSENCE_VALUES = ["not_wired", "not_adjudicated", "unavailable", "no_match", "not_reported"];
export function decisionText(d) {
return d.message;
}
export function licenseCovers(licensed, tool, runs) {
return licensed !== undefined && (licensed === exactBoundInputHashOf(tool, runs) || licensed === exactBoundInputHashOf(tool, argsReadFrom(runs)));
}
export function bindableArgsOf(toolName, args) {
const bound = bindableValueOf(args);
if (!bound.ok)
return { ok: false, refusal: bindingRefusalOf(toolName, args, bound.fault) };
if (typeof args === "object" && args !== null && OWNED_ARGS.has(args))
return { ok: true, value: args };
if (typeof bound.value === "object" && bound.value !== null)
OWNED_ARGS.add(bound.value);
return { ok: true, value: bound.value };
}
export function bindingRefusalOf(toolName, args, fault) {
return (`no approval can be bound to the arguments of "${toolName}": they hold ${inlineUntrusted(describeBindingFault(args, fault), 300)} — an approval binds arguments that are ` +
`a record of plain JSON data (records, dense lists, strings, finite numbers, booleans, null; no getter, hidden member, Proxy, ` +
`function, symbol, bigint or object of another kind; no cycle or shared object) nested at most 256 levels deep; denied fail-closed`);
}
export function answeredFor(d, call, runs) {
const record = attestationOf(d, call);
return record?.settlement !== undefined && licenseCovers(record.inputDigest, call.toolName, runs);
}
export const REFUSES_NO_WHOLE_TOOL = () => false;
export const TOOL_TABLE_VIEW_READ = "tool-table-view";
const TOOL_POLICY_CARRIED_MEMBERS = ["projection", "pathRules", "writeGuardRows", "nameSets", "wholeToolRefusals", "skippedRules"];
export function carriedMembersOf(p) {
assertNoRetiredKeys(p, RETIRED_TOOL_POLICY_KEYS, "ToolPolicy");
const out = {};
const carry = (k) => {
const v = p[k];
if (v !== undefined)
out[k] = v;
};
for (const k of TOOL_POLICY_CARRIED_MEMBERS)
carry(k);
return out;
}
export function wrapToolPolicy(inner, check) {
return { ...carriedMembersOf(inner), check };
}
export function toolPolicyPathRules(policies, anchors) {
return policies.flatMap((p) => (typeof p?.pathRules === "function" ? p.pathRules(anchors) : []));
}
export function toolPolicyWriteGuardRows(policies) {
const sources = policies.flatMap((p) => (typeof p?.writeGuardRows === "function" ? [p.writeGuardRows] : []));
if (sources.length === 0)
return undefined;
return async (at) => (await Promise.all(sources.map((rowsOf) => rowsOf(at)))).flat();
}
const FOLDED_WHOLE_TOOL_READS = new WeakMap();
function settledWholeToolRead(read, signal) {
return withGateTimeout(Promise.resolve().then(() => read(signal)), DEFAULT_GATE_AWAIT_TIMEOUT_MS, signal, "a whole-tool reading").then((judge) => (tool) => {
try {
return judge(tool) === true;
}
catch {
return false;
}
}, () => REFUSES_NO_WHOLE_TOOL);
}
export function toolPolicyWholeToolRefusals(holders) {
const sources = [...new Set(holders.flatMap((h) => {
const read = h?.wholeToolRefusals;
return typeof read === "function" ? (FOLDED_WHOLE_TOOL_READS.get(read) ?? [read]) : [];
}))];
if (sources.length === 0)
return undefined;
const combined = async (signal) => {
const judges = await Promise.all(sources.map((read) => settledWholeToolRead(read, signal)));
return (tool) => judges.some((refuses) => refuses(tool));
};
FOLDED_WHOLE_TOOL_READS.set(combined, sources);
return combined;
}
export function coveringRuleEntries(entries, behavior) {
return (entries ?? []).filter((entry) => isCoveringRuleName(entry, behavior));
}
export function coveringRuleHit(covering, call) {
return covering.length > 0 && nameListHolds({ has: (name) => covering.some((e) => ruleNameCovers(e, name)) }, call);
}
export function projectionToolNames(c) {
return c.kind === "shell_command" ? { member: "tools", list: c.tools } : { member: "names", list: c.names };
}
export function checkToolPolicyProjection(projection, req) {
const listed = (list) => heldBy("policy.projectionReplay", { has: (n) => list.includes(n) }, req);
for (const c of projection.components) {
if (c.kind === "tool_deny") {
if (listed(c.names) || coveringRuleHit(coveringRuleEntries(c.names, "deny"), req)) {
return { action: "deny", message: `tool "${req.toolName}" is denied by a frozen inherited policy projection` };
}
continue;
}
if (c.kind === "tool_allowlist") {
if (!listed(c.names) && !coveringRuleHit(coveringRuleEntries(c.names, "allow"), req)) {
return { action: "deny", message: `tool "${req.toolName}" is not in a frozen inherited policy projection's allowlist` };
}
continue;
}
if (!listed(c.tools))
continue;
const verdict = coarseCallVerdictOf(coarseListsOfComponent(c), req);
if (verdict.action !== "deny")
continue;
return {
action: "deny",
message: "listed" in verdict ? `command "${verdict.listed}" is denied by a frozen inherited policy projection` : `${verdict.cannotJudge} (frozen inherited policy projection)`,
};
}
return undefined;
}
function coarseListsOfComponent(c) {
return {
deny: c.deny,
ask: c.ask ?? [],
...(c.allow !== undefined ? { allow: c.allow } : {}),
unlisted: c.unmatchedAction === "deny" ? "deny" : "ask",
unreadable: c.unparseableAction === "deny" ? "deny" : "ask",
};
}
export const CONSTRAINT_LAYER_KINDS = Object.freeze(["installation", "taskPolicy", "deploymentPolicy"]);
export function constraintChainEntryOf(policy, meta) {
const m = {
...(meta?.autoModeArmed ? { autoModeArmed: true } : {}),
...(meta?.autoModeArming !== undefined ? { autoModeArming: meta.autoModeArming } : {}),
...(meta?.durableMandate ? { durableMandate: true } : {}),
...(meta?.contentMandate ? { contentMandate: true } : {}),
...(meta?.kind !== undefined ? { kind: meta.kind } : {}),
...(meta?.kind !== undefined && meta.rootLeg === true ? { rootLeg: true } : {}),
};
const p = policy?.projection;
if (p === undefined)
return { opaque: true, ...m };
return { components: p.components, requiresLiveRemainder: p.requiresLiveRemainder, ...m };
}
function chainEntryOfLayerCarrying(layer, carry) {
const arming = carry.arming ? sanitizeAutoModeArmingRecipe(layer.autoMode?.arming) : undefined;
return constraintChainEntryOf(layer.policy, {
...(layer.autoMode !== undefined ? { autoModeArmed: true } : {}),
...(arming !== undefined ? { autoModeArming: arming } : {}),
...(layer.durableMandate === true ? { durableMandate: true } : {}),
...(layer.contentMandate === true ? { contentMandate: true } : {}),
...(carry.facts && layer.kind !== undefined ? { kind: layer.kind, ...(layer.rootLeg === true ? { rootLeg: true } : {}) } : {}),
});
}
export function constraintChainEntryOfLayer(layer) {
return chainEntryOfLayerCarrying(layer, { arming: layer.autoMode?.arming !== undefined, facts: true });
}
export function constraintChainEntryOfSuppliedLayer(layer, recorded) {
return chainEntryOfLayerCarrying(layer, { arming: recorded?.autoModeArming !== undefined, facts: recorded?.kind !== undefined });
}
function stableJson(v) {
if (v === null || typeof v !== "object")
return JSON.stringify(v) ?? "null";
if (Array.isArray(v))
return `[${v.map(stableJson).join(",")}]`;
const keys = Object.keys(v).sort();
return `{${keys.map((k) => `${JSON.stringify(k)}:${stableJson(v[k])}`).join(",")}}`;
}
const CONSTRAINT_CHAIN_DIGEST_PREFIX = "cpv2:";
const EARLIER_CONSTRAINT_CHAIN_DIGEST_PREFIXES = Object.freeze({ "cpv1:": Object.freeze(["shell_command"]) });
const constraintChainDigestBody = (chain) => createHash("sha256").update(stableJson(chain)).digest("hex");
export function constraintChainDigest(chain) {
return `${CONSTRAINT_CHAIN_DIGEST_PREFIX}${constraintChainDigestBody(chain)}`;
}
export function constraintChainDigestReading(chain, recorded) {
const body = constraintChainDigestBody(chain);
if (recorded === `${CONSTRAINT_CHAIN_DIGEST_PREFIX}${body}`)
return "same";
const changed = Object.entries(EARLIER_CONSTRAINT_CHAIN_DIGEST_PREFIXES).find(([prefix]) => recorded === `${prefix}${body}`)?.[1];
if (changed === undefined)
return "different";
return chain.some((entry) => "components" in entry && entry.components.some((c) => changed.includes(c.kind))) ? "earlier" : "same";
}
const ALLOW = Object.freeze({ action: "allow" });
export const DECISION_MEMBERS = Object.keys(DECISION_MEMBER_ARMS);
const HOOK_RESULT_MEMBERS = [...DECISION_MEMBERS, ...Object.keys(HOOK_SEAT_MEMBER_ARMS)];
const HOOK_SEAM_UNREAD = new Set(["decisionReason"]);
const HOOK_SEAM_OPTIONAL = new Set(["action"]);
const HOOK_RECEIPTS = new WeakSet();
const ENGINE_RECEIPTS = new WeakSet();
function askOfAnotherCall(d, call) {
if (call === undefined || d.action !== "ask" || d.attestation === undefined || attestationOf(d, call) !== undefined)
return undefined;
return refusedOutOfContract(`a permission decision asks with the engine's record of another call — what the engine found about that call's question is not this call's; ` +
`a policy answers the call it is asked about (a cached or relayed ask is asked again); denied fail-closed rather than reading the findings as absent`);
}
export function refuseOutOfContractDecision(d, opts) {
const hookSeam = opts?.reasonIsNonInput === true;
if (hookSeam && (d === null || d === undefined || Object.is(d, false)))
return d;
if (typeof d !== "object" || d === null) {
return refusedOutOfContract(`a permission decision's "action" is absent (the decision is ${d === null || d === undefined ? String(d) : `a ${typeof d}`}, not an object) — the closed set is allow/deny/ask; denied fail-closed rather than reading a word outside it as an allow`);
}
if ((hookSeam ? HOOK_RECEIPTS : ENGINE_RECEIPTS).has(d) || isEngineRefusal(d))
return askOfAnotherCall(d, opts?.call) ?? d;
const decision = receiveContract(d, hookSeam ? HOOK_RESULT_MEMBERS : DECISION_MEMBERS, "", RETIRED_DECISION_MEMBERS);
if (decision.kind === "refused")
return decision.refused;
const contract = decision.held;
const refused = receiveNestedRecords(contract) ?? screenContractValues(contract, hookSeam ? { skip: HOOK_SEAM_UNREAD, optional: HOOK_SEAM_OPTIONAL } : undefined);
if (refused !== undefined)
return refused;
const attestation = contract.attestation;
if (attestation !== undefined && (hookSeam || !isEngineAttestation(attestation))) {
return refusedOutOfContract(hookSeam
? `a PreToolUse hook result carries an "attestation" — the member is an engine-minted record and a hook result carries none; denied fail-closed`
: `a permission decision carries an "attestation" the engine did not mint — the member is an engine record (who settled the call, ` +
`which question it answered); denied fail-closed rather than reading a caller's value as a settlement`);
}
const foreign = askOfAnotherCall({ action: contract.action, attestation }, opts?.call);
if (foreign !== undefined)
return foreign;
if (hookSeam && contract.additionalContext !== undefined && typeof contract.additionalContext !== "string") {
return refusedOutOfContract(`a PreToolUse hook result's "additionalContext" is not a string — the member is the text appended for the model; denied fail-closed rather than rendering a value this layer cannot classify`);
}
const { attestation: _record, ...members } = contract;
const detached = tryCloneArgs(members);
if (!detached.ok) {
return refusedOutOfContract(`a permission decision's members could not be detached from the layer that returned them (${detached.reason}) — ` +
`the engine keeps its own copy of what it read; denied fail-closed`);
}
const rewrite = detached.value.updatedInput;
const ownedRewrite = rewrite !== undefined ? ownedCopy(rewrite, "updatedInput") : undefined;
if (ownedRewrite !== undefined && !ownedRewrite.ok) {
return refusedOutOfContract(`a permission decision's members could not be detached from the layer that returned them (${ownedRewrite.reason}) — ` +
`the engine keeps its own copy of what it read; denied fail-closed`);
}
carryArgsReadFrom(contract.updatedInput, rewrite);
const held = detached.value;
const value = held.crossBoundaryMandated === true && held.requiresRealApproval !== true ? { ...held, requiresRealApproval: true } : held;
const receipt = Object.freeze(attestation !== undefined ? { ...value, attestation } : value);
for (const v of Object.values(receipt))
if (Array.isArray(v))
Object.freeze(v);
for (const record of nestedRecordsOf(receipt)) {
for (const v of Object.values(record))
if (Array.isArray(v))
Object.freeze(v);
Object.freeze(record);
}
(hookSeam ? HOOK_RECEIPTS : ENGINE_RECEIPTS).add(receipt);
return receipt;
}
const DEADLINE_ELAPSED = Symbol("approval.deadline_elapsed");
function withTimeout(p, ms, onTimeout) {
if (ms === undefined) {
return p;
}
return new Promise((resolve, reject) => {
let settled = false;
const settle = (fn, v) => {
if (settled)
return;
settled = true;
clearTimeout(timer);
fn(v);
};
const timer = setTimeout(() => {
if (settled)
return;
settle(resolve, onTimeout());
}, ms);
p.then((v) => settle(resolve, v), (e) => settle(reject, e));
});
}
export function toolPolicyNameSets(p) {
const sets = p?.nameSets;
return Array.isArray(sets) ? sets : [];
}
function screenToolNameList(entries, list, behavior, invalid) {
if (entries === undefined)
return undefined;
const kept = [];
const seen = new Set();
for (const entry of entries) {
const ns = protocolOf(entry);
if (ns !== undefined) {
const suffix = entry.slice(ns.prefix.length);
const sep = suffix.indexOf("__");
if (suffix.length === 0 || sep === 0 || (sep > 0 && suffix.length === sep + 2)) {
const lesson = `a malformed ${ns.id.toUpperCase()} tool name (empty peer or tool segment) — it can never match any mounted tool. ` +
`Use \`${ns.prefix}<peer>\` for every tool of a peer, or \`${ns.prefix}<peer>__<tool>\` for one tool.`;
invalid.push({ entry, list, message: `"${entry}" is ${lesson}`, lesson });
continue;
}
}
const spelled = ruleSpellingOf(entry);
if (spelled === undefined) {
const lesson = `a spelling no tool name can have — the rule syntax reads no tool name in it, so a name set never names a tool by it. Fix the entry.`;
invalid.push({ entry, list, message: `"${entry}" is ${lesson}`, lesson });
continue;
}
if (ruleContentOf(spelled) !== undefined) {
const lesson = `a rule CONTENT form, not a tool name — a name set matches raw tool names, so this entry ` +
`can never match any mounted tool (in an allow list it removes the tool entirely). Use the tool NAME here, ` +
`and route the narrowing through the lane that speaks this grammar: parameter rules via ` +
`createPermissionRulePolicy, Bash command prefixes via the persisted allow-rule lane.`;
invalid.push({ entry, list, message: `"${entry}" is ${lesson}`, lesson });
continue;
}
const wild = behavior === "allow" ? grantWildcardRefusalOf(spelled.toolName) : undefined;
if (wild !== undefined) {
invalid.push({ entry, list, message: `"${entry}": ${wild}`, lesson: wild });
continue;
}
if (!seen.has(spelled.toolName)) {
seen.add(spelled.toolName);
kept.push(spelled.toolName);
}
}
return kept;
}
function toolNameSetRefusal(who, invalid) {
const byLesson = new Map();
for (const i of invalid)
byLesson.set(i.lesson, [...(byLesson.get(i.lesson) ?? []), { entry: i.entry, list: i.list }]);
const e = new Error(`${who}: ${invalid.length} entr${invalid.length === 1 ? "y is" : "ies are"} not tool name(s):\n` +
[...byLesson.entries()].map(([lesson, group]) => ` Each of the following is ${lesson}\n` + group.map((g) => ` [${g.list}] "${g.entry}"`).join("\n")).join("\n"));
e.code = "config.invalid_tool_name_set";
e.issues = invalid;
return e;
}
export function createAllowDenyPolicy(opts) {
assertNoRetiredKeys(opts, RETIRED_ALLOW_DENY_POLICY_OPTIONS, "createAllowDenyPolicy");
const invalid = [];
const screenedAllow = screenToolNameList(opts.allow, "allow", "allow", invalid);
const screenedDeny = screenToolNameList(opts.deny, "deny", "deny", invalid);
if (invalid.length > 0) {
if ((opts.onInvalidName ?? "throw") === "throw")
throw toolNameSetRefusal("createAllowDenyPolicy", invalid);
for (const issue of invalid)
opts.onInvalidNameIssue?.(issue);
}
opts = { ...opts, ...(screenedAllow ? { allow: screenedAllow } : {}), ...(screenedDeny ? { deny: screenedDeny } : {}) };
const allow = opts.allow ? new Set(opts.allow) : undefined;
const deny = new Set(opts.deny ?? []);
const denyCovering = coveringRuleEntries(opts.deny, "deny");
const allowCovering = coveringRuleEntries(opts.allow, "allow");
const refusesWhole = (tool) => nameListHolds(deny, tool) || coveringRuleHit(denyCovering, tool);
return {
...(deny.size > 0 ? { wholeToolRefusals: () => Promise.resolve(refusesWhole) } : {}),
projection: {
components: [
...(opts.deny && opts.deny.length > 0 ? [{ kind: "tool_deny", names: [...opts.deny] }] : []),
...(opts.allow ? [{ kind: "tool_allowlist", names: [...opts.allow] }] : []),
],
requiresLiveRemainder: false,
},
nameSets: [{ ...(opts.allow ? { allow: [...opts.allow] } : {}), ...(opts.deny ? { deny: [...opts.deny] } : {}) }],
check(req) {
if (refusesWhole(req))
return { action: "deny", message: `tool "${req.toolName}" is denied by policy` };
if (allow && !nameListHolds(allow, req) && !coveringRuleHit(allowCovering, req)) {
return { action: "deny", message: `tool "${req.toolName}" is not in the allowlist` };
}
return ALLOW;
},
};
}
const RETIRED_ALLOW_DENY_POLICY_OPTIONS = Object.freeze({
scope: "an allow list is only ever a narrowing now (a tool it does not name is denied; a tool it names gets no objection, not consent) — drop the option, and put the consent in the allow layer: `RunnerDeps.allowedTools` for the deployment's, `TaskSpec.allowedTools` for a request's",
});
export function createApprovalPolicy(opts) {
if (opts.approvalTimeoutMs !== undefined && !Number.isFinite(opts.approvalTimeoutMs)) {
throw new Error(`createApprovalPolicy: approvalTimeoutMs must be a finite number of ms (got ${opts.approvalTimeoutMs}) — omit it to wait indefinitely`);
}
if (opts.approvalTimeoutMs !== undefined && opts.approvalTimeoutMs > 2_147_483_647) {
throw new Error(`createApprovalPolicy: approvalTimeoutMs must not exceed 2147483647ms (~24.8 days) (got ${opts.approvalTimeoutMs}) — a host timer truncates a larger delay and fires immediately, denying every request at once; omit it to wait indefinitely`);
}
const invalid = [];
const requireApproval = screenToolNameList(opts.requireApproval, "requireApproval", "ask", invalid) ?? [];
const denied = screenToolNameList(opts.deny, "deny", "deny", invalid);
const autoAllow = screenToolNameList(opts.autoAllow, "autoAllow", "allow", invalid);
if (opts.denyByDefault === true)
screenToolNameList(requireApproval, "requireApproval", "allow", invalid);
if (invalid.length > 0)
throw toolNameSetRefusal("createApprovalPolicy", invalid);
opts = { ...opts, requireApproval, ...(denied !== undefined ? { deny: denied } : {}), ...(autoAllow !== undefined ? { autoAllow } : {}) };
const need = new Set(opts.requireApproval);
const deny = new Set(opts.deny ?? []);
const auto = new Set(opts.autoAllow ?? []);
const needCovering = coveringRuleEntries(opts.requireApproval, "ask");
const denyCovering = coveringRuleEntries(opts.deny, "deny");
const autoCovering = coveringRuleEntries(opts.autoAllow, "allow");
const refusesWhole = (tool) => nameListHolds(deny, tool) || coveringRuleHit(denyCovering, tool);
return {
...(deny.size > 0 ? { wholeToolRefusals: () => Promise.resolve(refusesWhole) } : {}),
projection: {
components: [
...(opts.deny && opts.deny.length > 0 ? [{ kind: "tool_deny", names: [...opts.deny] }] : []),
...(opts.denyByDefault === true ? [{ kind: "tool_allowlist", names: [...opts.requireApproval, ...(opts.autoAllow ?? [])] }] : []),
],
requiresLiveRemainder: opts.requireApproval.length > 0,
},
nameSets: [
{
ask: [...opts.requireApproval],
...(opts.deny ? { deny: [...opts.deny] } : {}),
...(opts.autoAllow ? { allow: [...opts.autoAllow] } : {}),
},
],
async check(req, signal) {
if (refusesWhole(req))
return { action: "deny", message: `tool "${req.toolName}" is denied by policy` };
if (nameListHolds(need, req) || coveringRuleHit(needCovering, req)) {
const attestOver = (inputDigest) => (d, settlement, bindingRefusal) => ({ ...d, attestation: mintAttestation(req, { settlement, origin: "policy", ...(inputDigest !== undefined ? { inputDigest } : {}), ...(bindingRefusal !== undefined ? { bindingRefusal } : {}) }) });
const unasked = unaskedSeatAnswer(req, signal, { aborted: `approval aborted for "${req.toolName}" (run or turn interrupted)`, unreachable: `approval for "${req.toolName}" was not requested: nobody can be asked about this call` }, "policy");
if (unasked !== undefined)
return unasked;
const bound = bindableArgsOf(req.toolName, req.args);
if (!bound.ok)
return attestOver(undefined)({ action: "deny", message: bound.refusal }, settledByNobody("presentation_failed"), bound.refusal);
const shown = { value: structuredClone(bound.value) };
const askedDigest = exactBoundInputHashOf(req.toolName, shown.value);
const attest = attestOver(askedDigest);
const heldWhileWaiting = () => licenseCovers(askedDigest, req.toolName, req.args);
const changedWhilePending = () => attest({
action: "deny",
message: `the arguments of "${req.toolName}" changed while its approval was pending — denied fail-closed ` +
`(an approval answers the arguments it was shown; ask again over the arguments that will run)`,
}, settledByNobody("approver_contract"));
let ok;
try {
ok = await withTimeout(Promise.resolve(opts.approve({ ...req, args: shown.value }, signal)), opts.approvalTimeoutMs, () => DEADLINE_ELAPSED);
}
catch (err) {
return attest({ action: "deny", message: `approval errored for "${req.toolName}": ${describeThrown(err)}` }, settledByNobody("approver_error"));
}
if (ok === DEADLINE_ELAPSED) {
return attest({
action: "deny",
message: `no one answered the approval request for "${req.toolName}" — the approval window elapsed ` +
`(${opts.approvalTimeoutMs}ms) with no answer; denied fail-closed`,
}, { kind: "approval_window_expired", who: { party: "engine", window: "approval_factory" }, when: Date.now() });
}
if (signal?.aborted)
return abortedSeatDeny(req, `approval aborted for "${req.toolName}" (run or turn interrupted)`, "policy");
if (ok === false || (typeof ok === "object" && ok !== null)) {
const reading = readApproverOutcomeObject(ok, req.toolName, { editLane: "none", takesWords: false, isPolicy: isPolicyApprover(opts.approve), shown: askedDigest });
if (reading.kind === "refused")
return attest({ action: "deny", message: reading.message }, reading.settlement);
if (reading.kind === "deny") {
return attest({
action: "deny",
message: reading.word === "policy"
? policyRefusalMessage(req.toolName, undefined, reading.note, reading.via, false)
: reading.word === "timeout"
? `no one answered the approval request for "${req.toolName}" — the approver reported its own window elapsed with no answer; denied fail-closed${reading.note !== undefined ? `\nReviewer note:\n${delimitUntrusted("reviewer note", reading.note, REVIEWER_NOTE_MAX_BODY)}` : ""}`
: reading.word === "withdrawn"
? withdrawnAskMessage(req.toolName, undefined, reading.note)
: `approval denied for "${req.toolName}"${reading.note !== undefined ? `\nReviewer note:\n${delimitUntrusted("reviewer note", reading.note, REVIEWER_NOTE_MAX_BODY)}` : ""}`,
}, reading.settlement);
}
if (!heldWhileWaiting())
return changedWhilePending();
return attest({ action: "allow", decisionReason: "mode" }, reading.settlement);
}
const okRaw = ok;
if (okRaw === true)
return heldWhileWaiting() ? attest({ action: "allow", decisionReason: "mode" }, settledByDecider("person", "allowed", undefined)) : changedWhilePending();
return attest({
action: "deny",
message: `approval callback for "${req.toolName}" returned an out-of-contract value (${typeof ok}) — denied fail-closed ` +
`(this policy's \`approve\` returns true, false, or the {allow, settledBy?, reason?, approver?} outcome object)`,
}, settledByNobody("approver_contract"));
}
if (nameListHolds(auto, req) || coveringRuleHit(autoCovering, req))
return ALLOW;
if (opts.denyByDefault) {
return { action: "deny", message: `tool "${req.toolName}" requires explicit allow` };
}
return ALLOW;
},
};
}
export function combinePolicies(...policies) {
for (const member of policies)
assertNoRetiredToolPolicyKeys(member);
const nameSets = policies.flatMap(toolPolicyNameSets);
const pathRuled = policies.filter((p) => typeof p?.pathRules === "function");
const writeGuardRows = toolPolicyWriteGuardRows(policies);
const childProjections = policies.map((p) => p.projection);
const projectedComponents = [];
let combinedRemainder = false;
for (const p of childProjections) {
if (p === undefined) {
combinedRemainder = true;
break;
}
projectedComponents.push(...p.components);
if (p.requiresLiveRemainder) {
combinedRemainder = true;
break;
}
}
const combinedProjection = childProjections.some((p) => p !== undefined)
? { components: projectedComponents, requiresLiveRemainder: combinedRemainder }
: undefined;
const folded = {
projection: combinedProjection,
nameSets: nameSets.length > 0 ? nameSets : undefined,
pathRules: pathRuled.length > 0 ? (anchors) => toolPolicyPathRules(pathRuled, anchors) : undefined,
writeGuardRows,
wholeToolRefusals: toolPolicyWholeToolRefusals(policies),
skippedRules: ((s) => (s.length > 0 ? s : undefined))(policies.flatMap((p) => p.skippedRules ?? [])),
};
return {
...carriedMembersOf(folded),
async check(req, signal) {
let asked;
let current = Object.freeze({ ...req });
let rewrite;
let ruleAskText;
let probeMandateSeen = false;
let mandateSeen = false;
let fallbackSeen;
let noRulingSeen;
let authoredBySeen = false;
let fromListSeen = false;
const contributors = [];
const decisions = [];
const recordsExcept = (at) => decisions.reduce((acc, d, j) => (j !== at && d?.action === "allow" && d.attestation !== undefined ? mergeAttestation(req, acc, d.attestation) : acc), undefined);
const settleDeny = (d, at) => {
const out = rewrite !== undefined ? refusalOf(d, current.args) : d;
const records = recordsExcept(at);
if (records === undefined)
return out;
return { ...out, attestation: mergeAttestation(req, records, d.attestation) };
};
let seatDeny;
const denied = (d, at) => {
decisions[at] = undefined;
if (!seatNeverAsked(attestationOf(d, current)?.settlement))
return settleDeny(d, at);
seatDeny ??= settleDeny(d, at);
return undefined;
};
let emitter = -1;
let personWrote = false;
for (const [at, p] of policies.entries()) {
const d = refuseOutOfContractDecision(await p.check(current, signal), { call: req });
if (d.action === "deny") {
const ended = denied(d, at);
if (ended !== undefined)
return ended;
continue;
}
decisions[at] = d;
if (readRejudge(current, current.args, d).kind === "rewritten") {
if (personWrote)
return settleDeny({ action: "deny", message: `${editRewrittenSentence(req.toolName)}, which a later policy layer wrote over a person's edit — denied fail-closed` }, at);
current = Object.freeze(await withArgsReading(current, d.updatedInput, signal));
rewrite = d;
emitter = at;
personWrote = attestationOf(d, current)?.settlement?.who.party === "person" && answeredFor(d, req, current.args);
}
}
for (let at = 0; at < emitter; at++) {
const p = policies[at];
const d = refuseOutOfContractDecision(await p.check(current, signal), { call: req });
if (d.action === "deny") {
const ended = denied(d, at);
if (ended !== undefined)
return ended;
continue;
}
if (readRejudge(current, current.args, d).kind === "rewritten")
return settleDeny({ action: "deny", message: rewriteChasedSentence(req.toolName) }, at);
const { updatedInput: _sameBytes, ...asIs } = d;
const first = decisions[at];
decisions[at] = asIs.action === "allow" && first?.action === "allow" && first.attestation !== undefined ? withAttestation(asIs, mergeAttestation(req, first.attestation, asIs.attestation)) : asIs;
}
if (seatDeny !== undefined)
return seatDeny;
let records;
for (const d of decisions) {
if (d === undefined)
continue;
if (d.action === "allow" && d.attestation !== undefined)
records = mergeAttestation(req, records, d.attestation);
if (d.action === "ask" && (asked === undefined || (d.requiresRealApproval === true && asked.requiresRealApproval !== true))) {
asked = d;
}
if (d.action === "ask" && d.matchedAskRule !== undefined && ruleAskText === undefined) {
ruleAskText = d.matchedAskRule;
}
if (d.action === "ask" && d.probeMandated === true)
probeMandateSeen = true;
if (d.action === "ask" && d.mandated === true)
mandateSeen = true;
if (d.action === "ask" && d.denialLimitFallback !== undefined && fallbackSeen === undefined)
fallbackSeen = d.denialLimitFallback;
if (d.action === "ask" && d.classifierNoRuling !== undefined && noRulingSeen === undefined)
noRulingSeen = d.classifierNoRuling;
if (d.action === "ask" && d.authoredBy === "deployment")
authoredBySeen = true;
if (d.action === "ask" && d.fromApprovalList === true)
fromListSeen = true;
if (d.action === "ask")
contributors.push(d);
}
if (asked) {
const merged = rewrite?.updatedInput;
const withRuleAsk = ruleAskText !== undefined && asked.matchedAskRule === undefined ? { ...asked, matchedAskRule: ruleAskText } : asked;
const withMark = probeMandateSeen && withRuleAsk.probeMandated !== true ? { ...withRuleAsk, probeMandated: true } : withRuleAsk;
const withMandate = mandateSeen && withMark.mandated !== true ? { ...withMark, mandated: true } : withMark;
const withFallback = fallbackSeen !== undefined && withMandate.denialLimitFallback === undefined ? { ...withMandate, denialLimitFallback: fallbackSeen, requiresRealApproval: true } : withMandate;
const withNoRuling = noRulingSeen !== undefined && withFallback.classifierNoRuling === undefined ? { ...withFallback, classifierNoRuling: noRulingSeen, requiresRealApproval: true } : withFallback;
const withAuthored = authoredBySeen && withNoRuling.authoredBy === undefined ? { ...withNoRuling, authoredBy: "deployment" } : withNoRuling;
const withAuthor = fromListSeen && withAuthored.fromApprovalList !== true ? { ...withAuthored, fromApprovalList: true } : withAuthored;
const folded = new Set(attestationOf(asked, req)?.foldedClasses ?? []);
for (const c of contributors)
if (c !== asked)
for (const k of decisionAskClassesOf(c, req))
folded.add(k);
if (withNoRuling !== withMandate)
for (const k of decisionAskClassesOf(asked, req))
folded.add(k);
const out = merged !== undefined ? { ...withAuthor, updatedInput: merged } : withAuthor;
return folded.size > 0 ? attest(out, req, { foldedClasses: [...folded] }) : out;
}
const allowed = rewrite ?? ALLOW;
return records === undefined ? allowed : { ...allowed, attestation: records };
},
};
}
export const COARSE_SHELL_TOOLS = Object.freeze(["Bash", "Monitor"]);
function canonicalToolNameSet(tools) {
return new Set(tools ?? COARSE_SHELL_TOOLS);
}
export function createCoarseCommandNamePolicy(opts) {
const deny = coarseNameListOf(opts.deny, "deny") ?? [];
const ask = coarseNameListOf(opts.ask, "ask") ?? [];
const allow = coarseNameListOf(opts.allow, "allow");
const defaultAction = opts.defaultAction === undefined ? "ask" : opts.defaultAction;
if (!isRuleBehavior(defaultAction)) {
throw new TypeError(`createCoarseCommandNamePolicy: defaultAction must be "allow", "ask" or "deny" (got ${describeRejectedValue(defaultAction)})`);
}
if (allow !== undefined && defaultAction === "allow") {
throw new TypeError('createCoarseCommandNamePolicy: defaultAction "allow" cannot be written with an allow list — the list bounds what may run, and "allow" would let every command it does not list through; drop one of the two');
}
const shellTools = canonicalToolNameSet(opts.tools);
const unreadable = defaultAction === "allow" && (deny.length > 0 || ask.length > 0) ? "ask" : defaultAction;
const lists = { deny, ask, ...(allow !== undefined ? { allow } : {}), unlisted: defaultAction, unreadable };
const fallbackIsDeny = defaultAction === "deny";
const projection = {
components: [
{
kind: "shell_command",
tools: [...shellTools],
deny: [...deny],
...(ask.length > 0 ? { ask: [...ask] } : {}),
...(allow !== undefined ? { allow: [...allow] } : {}),
unmatchedAction: fallbackIsDeny ? "deny" : "none",
unparseableAction: unreadable === "deny" ? "deny" : "none",
},
],
requiresLiveRemainder: defaultAction === "ask" || ask.length > 0,
};
return brandPolicyAskClass({
projection,
check(req) {
if (!shellToolsListHolds(shellTools, req))
return ALLOW;
const verdict = coarseCallVerdictOf(lists, req);
if (verdict.action === "allow")
return ALLOW;
if (!("listed" in verdict)) {
return verdict.action === "deny" ? { action: "deny", message: verdict.cannotJudge, decisionReason: "rule" } : { action: "ask", message: verdict.cannotJudge, decisionReason: "rule" };
}
if (verdict.action === "deny")
return { action: "deny", message: `command "${verdict.listed}" is denied by policy`, decisionReason: "rule" };
return { action: "ask", message: `command "${verdict.listed}" is on the policy's ask list`, decisionReason: "rule", matchedAskRule: verdict.listed };
},
}, "sandbox_local");
}
function coarseNameListOf(list, member) {
if (list === undefined)
return undefined;
if (!Array.isArray(list))
throw new TypeError(`createCoarseCommandNamePolicy: ${member} must be a list of program names (got ${describeRejectedValue(list)})`);
const names = [];
for (let i = 0; i < list.length; i++) {
const entry = list[i];
const problem = coarseCommandNameProblem(entry);
if (problem !== undefined)
throw new TypeError(`createCoarseCommandNamePolicy: ${member}[${i}] (${describeRejectedValue(entry)}) ${problem}`);
names.push(entry);
}
return Object.freeze(names);
}
export function createUnverifiableDeletePolicy(opts) {
for (const name of opts?.safeVars ?? []) {
if (typeof name !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name))
throw new TypeError(`createUnverifiableDeletePolicy: safeVars entry ${JSON.stringify(name)} is not a shell variable name`);
if (name === "PWD" || name === "OLDPWD") {
const e = new Error(`createUnverifiableDeletePolicy: safeVars entry "${name}" is a reserved name — it is where the command stands, which the removal guard reads off the working-directory thread, not a root the shell provides. Drop the entry; to treat a fixed directory as a safe root, export it under a name of your own and list that name.`);
e.code = "config.safe_vars_reserved_name";
throw e;
}
}
const safeRoots = [...new Set([...KNOWN_SAFE_ROOTS, ...(opts?.safeVars ?? [])])];
const shellTools = canonicalToolNameSet(opts?.tools);
return brandPolicyAskClass({
check(req, signal) {
if (!shellToolsListHolds(shellTools, req))
return ALLOW;
const command = req.args?.command;
if (typeof command !== "string")
return ALLOW;
const removal = removalReadingOf(command, req, opts?.removalSeat, safeRoots);
return removal === undefined ? ALLOW : removal.judge(signal).then((found) => (found === undefined ? ALLOW : removalAsk(req, found)));
},
}, "external_authority");
}
function removalAsk(req, verdict) {
return attest({ action: "ask", decisionReason: "safety", ...(explainsRealApprovalBit([verdict.guard]) ? { requiresRealApproval: true } : {}), message: verdict.text }, req, { guards: [verdict.guard], sentence: { text: verdict.text, guard: verdict.guard } });
}
function pathSegments(p) {
return p.split(/[\\/]/).filter(Boolean);
}
const CASE_INSENSITIVE_FS = process.platform === "darwin" || process.platform === "win32";
const foldPathCase = (s) => (CASE_INSENSITIVE_FS ? s.toLowerCase() : s);
function lexicalPath(p, home) {
const norm = p.normalize("NFC");
const expanded = norm === "~" ? home : /^~[\\/]/.test(norm) ? join(home, norm.slice(2)) : norm;
return normalizePath(expanded);
}
const RELATIVE_TAIL_MIN_SEGMENTS = 2;
function relativeContinuesDirTail(segs, dirSegs) {
const from = Math.min(RELATIVE_TAIL_MIN_SEGMENTS, dirSegs.length);
for (let k = from; k <= Math.min(segs.length, dirSegs.length); k++) {
const tail = dirSegs.slice(dirSegs.length - k);
if (tail.every((s, i) => s === segs[i]))
return true;
}
return false;
}
export function createTranscriptIntegrityPolicy(opts) {
const home = homedir();
const defaultRoot = dataRootSpelling();
const dirs = (opts?.sessionsDirs ?? [join(defaultRoot, "sessions")]).map((d) => lexicalPath(d, home).replace(/(?<=.)[\\/]+$/, ""));
const textualForms = dirs.flatMap((d) => {
const forms = [d];
if (d.startsWith(home + sep)) {
const rel = d.slice(home.length);
forms.push(`~${rel}`, `$HOME${rel}`, `\${HOME}${rel}`);
}
return forms;
});
const readAllow = new Set(opts?.readAllow ?? BASH_READONLY_DEFAULT_ALLOW);
const shellTools = canonicalToolNameSet(opts?.tools);
const dirSegs = dirs.map((d) => pathSegments(d).map(foldPathCase));
const inProtectedDir = (p, liveCwd) => {
const tree = liveCwd === undefined ? undefined : pathFamilyOf({ root: liveCwd });
const family = tree ?? "own";
const rawRelative = !isAbsoluteForFamily(family, p);
const abs = liveCwd !== undefined && tree !== undefined && rawRelative ? lexicalPath(normalizeAbsPathLexically(anchorSpelling(tree, liveCwd, p)), home) : lexicalPath(p, home);
const segs = pathSegments(abs).map(foldPathCase);
if (isAbsoluteForFamily(family, abs) && dirSegs.some((d) => d.length <= segs.length && d.every((s, i) => s === segs[i])))
return true;
if (!rawRelative)
return false;
return dirSegs.some((d) => relativeContinuesDirTail(pathSegments(lexicalPath(p, home)).map(foldPathCase), d));
};
const referencesProtectedDir = (cmd) => {
const hay = foldPathCase(cmd);
if (textualForms.some((f) => hay.includes(foldPathCase(f))))
return true;
for (const raw of cmd.split(/[\s;&|<>()]+/)) {
if (raw === "")
continue;
const unquoted = raw.replace(/["'`]/g, "");
if (unquoted === "")
continue;
const expanded = unquoted.startsWith("${HOME}")
? home + unquoted.slice("${HOME}".length)
: unquoted.startsWith("$HOME")
? home + unquoted.slice("$HOME".length)
: unquoted;
if (inProtectedDir(expanded))
return true;
}
return false;
};
const askReason = (req, what) => {
const message = `Session-transcript write (fail-closed unless cleared): ${what}. Session transcripts (the .jsonl files ` +
`under the agent data dir's sessions/ directory) are harness-written session state, not agent working ` +
`files — modifying or deleting them tampers with the run's own audit trail. Reading them (ls/cat/grep ` +
`as a single simple command) is fine.`;
return attest({ action: "ask", decisionReason: "safety", requiresRealApproval: true, message }, req, { guards: ["transcript_write"], sentence: { text: message, guard: "transcript_write" } });
};
return brandPolicyAskClass({
check(req) {
if (shellToolsListHolds(shellTools, req)) {
const command = req.args?.command;
if (typeof command !== "string")
return ALLOW;
const cmd = command.normalize("NFC");
const cwdInsideProtected = req.cwd !== undefined && inProtectedDir(req.cwd);
if (!referencesProtectedDir(cmd) && !cwdInsideProtected)
return ALLOW;
const verdict = readOnlyCallVerdict(req, command, { cwd: req.cwd, readers: readAllow, knownValues: req.cwd !== undefined });
if (verdict.readOnly)
return ALLOW;
return askReason(req, `${cwdInsideProtected ? "the shell's working directory is inside the transcript directory" : "the command references the transcript directory"} and is not read-only: ${verdict.reason}`);
}
const writeTarget = protectivePathTargetOf(req);
if (writeTarget !== undefined && writeTarget.access !== "read") {
const p = writeTargetPath(req);
if (typeof p === "string" && inProtectedDir(p, req.cwd)) {
return askReason(req, `"${p}" is inside the session-transcript directory`);
}
}
return ALLOW;
},
}, "external_authority");
}
const APPROVER_SETTLED_BY = Object.freeze(["human", "timeout", "policy", "withdrawn"]);
const isApproverSettledBy = (v) => APPROVER_SETTLED_BY.some((w) => w === v);
const HOST_END_OF_WORD = Object.freeze({ timeout: "approval_window_expired", withdrawn: "approval_withdrawn" });
const namesNoDecider = (word) => Object.hasOwn(HOST_END_OF_WORD, word);
const hostEndOf = (word) => ({ kind: HOST_END_OF_WORD[word], who: { party: "host" }, when: Date.now() });
const delegatedApproverRoot = new WeakMap();
export function wrapApprover(onAsk, wrap) {
if (typeof onAsk !== "function")
return onAsk;
const wrapper = wrap(onAsk);
delegatedApproverRoot.set(wrapper, askApproverIdentity(onAsk));
return wrapper;
}
export function withDelegationProvenance(onAsk, delegation) {
return wrapApprover(onAsk, (approver) => (req, signal) => (req.delegation !== undefined ? approver(req, signal) : approver({ ...req, delegation }, signal)));
}
const policyApprovers = new WeakSet();
export function asPolicyApprover(fn) {
if (typeof fn !== "function")
throw new TypeError(`asPolicyApprover takes an approver function, not ${fn === null ? "null" : typeof fn}`);
policyApprovers.add(askApproverIdentity(fn));
return fn;
}
export function isPolicyApprover(v) {
return typeof v === "function" && policyApprovers.has(askApproverIdentity(v));
}
const classAnswerTables = new WeakMap();
const CLASS_ANSWER_KEYS = Object.freeze(["classes", "approver"]);
const CLASS_ANSWER_WORDS = Object.freeze({ subject: "declareClassAnswers's answers", unit: "member", moment: "at the declaration" });
export function declareClassAnswers(seat, answers) {
if (typeof seat !== "function")
throw new TypeError(`declareClassAnswers takes an approver function, not ${seat === null ? "null" : typeof seat}`);
if (typeof answers !== "object" || answers === null || Array.isArray(answers))
throw new TypeError(`declareClassAnswers takes { classes, approver }, not ${answers === null ? "null" : Array.isArray(answers) ? "an array" : typeof answers}`);
const { classes: declared, approver: named } = receiveMembers(answers, CLASS_ANSWER_WORDS, CLASS_ANSWER_KEYS, (message) => new TypeError(`declareClassAnswers: ${message}`));
if (!Array.isArray(declared) || declared.length === 0)
throw new TypeError("declareClassAnswers: `classes` must be a non-empty array of ask classes");
const listed = Array.from(declared);
for (const c of listed) {
if (typeof c !== "string" || !ASK_CLASSES.includes(c))
throw new TypeError(`declareClassAnswers: ${describeRejectedValue(c)} is not an ask class (ASK_CLASSES)`);
if (!MODE_ARBITRATION[c].ruleMayClear)
throw new TypeError(`declareClassAnswers: the ask class "${c}" is one no standing rule may clear (MODE_ARBITRATION.${c}.ruleMayClear is false); a class table may hold only the classes the allow layer itself may answer`);
}
const screened = screenApproverAttribution(named);
if (screened.defect !== undefined)
throw new TypeError(`declareClassAnswers: \`approver\` refused — ${screened.defect}`);
if (screened.approver === undefined)
throw new TypeError("declareClassAnswers: `approver` must name the seat that answers (a non-empty closed word the host owns)");
const table = Object.freeze({ classes: Object.freeze(ASK_CLASSES.filter((c) => listed.includes(c))), approver: screened.approver });
const minted = (req, signal) => declaredClassAnswer(minted, req.classes) ?? seat(req, signal);
classAnswerTables.set(minted, table);
return minted;
}
export function declaredClassAnswer(onAsk, classes) {
if (typeof onAsk !== "function")
return undefined;
const table = classAnswerTables.get(askApproverIdentity(onAsk));
if (table === undefined || !Array.isArray(classes) || classes.length === 0)
return undefined;
if (!classes.every((c) => table.classes.includes(c)))
return undefined;
return { allow: true, settledBy: "policy", approver: table.approver };
}
export function declaredAnswerClassesOf(onAsk) {
return typeof onAsk === "function" ? classAnswerTables.get(askApproverIdentity(onAsk))?.classes : undefined;
}
export function askApproverIdentity(onAsk) {
return typeof onAsk === "function" ? (delegatedApproverRoot.get(onAsk) ?? onAsk) : onAsk;
}
export function isAnsweringSeat(onAsk) {
return typeof onAsk === "function";
}
export const DURABLE_MANDATE_SOURCES = Object.freeze(["force_durable_gate", "durable_approval"]);
Object.freeze(DURABLE_MANDATE_SOURCES);
export function durableMandateSourceOf(args) {
if (args.forceDurableGate)
return "force_durable_gate";
if (args.durableApprovalDeclared && !isAnsweringSeat(args.onAsk))
return "durable_approval";
return undefined;
}
export function durableParkOptInDeclared(args) {
return args.approvalParkNotResumable === undefined && (args.durableApprovalDeclared || args.forceDurableGate);
}
export function effectiveDurableApprovalOf(args) {
if (!durableParkOptInDeclared({ forceDurableGate: args.forceDurableGate, durableApprovalDeclared: args.declared !== undefined, approvalParkNotResumable: args.approvalParkNotResumable }))
return undefined;
return args.declared ?? { scope: args.scope };
}
export function tryCloneArgs(v) {
try {
const value = structuredClone(v);
if (containsSharedMemory(value))
return { ok: false, reason: "the value carries shared memory (SharedArrayBuffer), which a clone still aliases" };
return { ok: true, value };
}
catch (err) {
return { ok: false, reason: describeThrown(err), cause: err };
}
}
export function refusalOf(deny, judged) {
return deny.action !== "deny" || deny.updatedInput !== undefined ? deny : { ...deny, updatedInput: judged };
}
export function extensionSpeaker(by, reason) {
return { who: by !== undefined ? extensionNamed(by) : "an extension", why: reason !== undefined ? `: ${foreignLine(reason, 500)}` : "" };
}
export function extensionNamed(registration) {
return `extension ${JSON.stringify(inlineUntrusted(registration, 80))}`;
}
export function extensionQuestionText(toolName, entry) {
const who = entry.registration !== undefined ? extensionNamed(entry.registration) : "an extension";
const why = entry.words !== undefined ? `: ${entry.words}` : "";
return `tool "${toolName}" needs approval (asked by ${who}${why})`;
}
export function foldHookAsk(verdict, hookAsk) {
if (verdict.action === "deny")
return verdict;
const mandate = { ...(hookAsk.requiresRealApproval === true ? { requiresRealApproval: true } : {}), ...(hookAsk.crossBoundaryMandated === true ? { crossBoundaryMandated: true } : {}) };
if (verdict.action === "allow") {
return { action: "ask", ...(hookAsk.message !== undefined ? { message: hookAsk.message } : {}), decisionReason: "hook", ...mandate, ...(hookAsk.updatedInput !== undefined ? { updatedInput: hookAsk.updatedInput } : {}), ...(hookAsk.askReasons !== undefined ? { askReasons: hookAsk.askReasons } : {}) };
}
const hookMessage = hookAsk.message;
const message = hookMessage !== undefined && hookMessage !== verdict.message ? `${verdict.message !== undefined ? `${verdict.message} ` : ""}(a PreToolUse hook also asks: ${hookMessage})` : verdict.message;
const askReasons = joinAskReasons(verdict.askReasons, hookAsk.askReasons);
return { ...verdict, decisionReason: "hook", ...(message !== undefined ? { message } : {}), ...mandate, ...(askReasons !== undefined ? { askReasons } : {}) };
}
const OWNED_ARGS = new WeakSet();
export function ownArgs(v, root = "args") {
if (v === null || (typeof v !== "object" && typeof v !== "function") || OWNED_ARGS.has(v))
return { ok: true, value: v };
const copy = tryCloneArgs(v);
return copy.ok ? ownedCopy(copy.value, root) : { ...copy, reason: `unclonable value: ${copy.reason}` };
}
export function ownedReading(read) {
return (args) => {
const out = read(args);
const owned = ownArgs(out);
return owned.ok ? owned.value : out;
};
}
function ownedCopy(fresh, root) {
const pending = [[fresh, root]];
for (let next = pending.pop(); next !== undefined; next = pending.pop()) {
const [x, at] = next;
if (typeof x !== "object" || x === null || Object.isFrozen(x))
continue;
const proto = Object.getPrototypeOf(x);
if (proto !== Object.prototype && proto !== Array.prototype && proto !== null) {
return { ok: false, reason: `${inlineUntrusted(at, 200)} is a ${Object.prototype.toString.call(x).slice(8, -1)}, whose contents cannot be made immutable — args are plain data` };
}
Object.freeze(x);
for (const key of Reflect.ownKeys(x)) {
const d = Object.getOwnPropertyDescriptor(x, key);
if (d !== undefined && "value" in d)
pending.push([d.value, Array.isArray(x) ? `${at}[${String(key)}]` : `${at}.${String(key)}`]);
}
}
if (typeof fresh === "object" && fresh !== null)
OWNED_ARGS.add(fresh);
return { ok: true, value: fresh };
}
export function describeThrown(err) {
const contained = containThrownText(egressThrownText("same-principal", err));
if (contained !== "")
return contained;
return containThrownText(egressText("same-principal", describeRejectedValue(err)));
}
const THROWN_TEXT_MAX = 300;
function containThrownText(text) {
return foreignLine(text, THROWN_TEXT_MAX);
}
function containsSharedMemory(v, seen = new Set()) {
if (typeof SharedArrayBuffer !== "undefined" && v instanceof SharedArrayBuffer)
return true;
if (ArrayBuffer.isView(v))
return typeof SharedArrayBuffer !== "undefined" && v.buffer instanceof SharedArrayBuffer;
if (v === null || typeof v !== "object")
return false;
if (seen.has(v))
return false;
seen.add(v);
if (v instanceof Map) {
for (const [k, val] of v)
if (containsSharedMemory(k, seen) || containsSharedMemory(val, seen))
return true;
return false;
}
if (v instanceof Set) {
for (const val of v)
if (containsSharedMemory(val, seen))
return true;
return false;
}
for (const val of Object.values(v))
if (containsSharedMemory(val, seen))
return true;
return false;
}
const USER_NOTE_AUTHORITY = "(user authority only: it cannot grant permissions or override system rules)";
export function humanRefusalSentence(subject, reason, delegatedChild) {
const note = decidersNote(reason);
if (delegatedChild) {
const fact = subject === "plan" ? "Your proposed plan was rejected; it was not executed." : `${DELEGATED_TOOL_USE_DENIED}; the call did NOT run.`;
return note === undefined
? `${fact} Try a different approach or report the limitation to complete your task.`
: `${fact} The user's note on this rejection follows — treat it as the decider's guidance ${USER_NOTE_AUTHORITY}:\n${delimitUntrusted("reviewer note", note, REVIEWER_NOTE_MAX_BODY)}\nAdjust to the note if you can; otherwise try a different approach or report the limitation to complete your task.`;
}
const fact = subject === "plan" ? "Your proposed plan was rejected by the user; it was not executed." : `${USER_REFUSED_TOOL_USE}; the call did NOT run.`;
return note === undefined
? `${fact} STOP what you are doing and wait for the user to tell you how to proceed.`
: `${fact} The user's note on this rejection follows — treat it as the user's guidance ${USER_NOTE_AUTHORITY}:\n${delimitUntrusted("reviewer note", note, REVIEWER_NOTE_MAX_BODY)}\nIf the note does not tell you how to proceed, STOP what you are doing and wait for the user.`;
}
export function humanRefusalMessage(toolName, askMessage, reason, delegatedChild) {
return `approval denied for "${toolName}"${askMessage !== undefined ? `: ${askMessage}` : ""}\n${humanRefusalSentence("tool use", reason, delegatedChild)}`;
}
export function policyRefusalMessage(toolName, askMessage, note, decidedVia, answeredByRunChannel) {
const decider = policyDeciderOf(decidedVia);
const quoted = askMessage !== undefined ? `: ${askMessage}` : "";
const noted = (body, label) => (note === undefined ? body : `${body}\n${label === "policy note" ? "Policy note" : "Hook reason"}:\n${delimitUntrusted(label, note, REVIEWER_NOTE_MAX_BODY)}`);
if (decider.seat === "permission_request_hook")
return noted(`${decider.name} denied this call to "${toolName}"${quoted}\nThe call did NOT run. Do not claim it ` +
`succeeded and do not retry it unchanged; report what was blocked and why you needed it, then continue with the parts of the task it does not block.`, "hook reason");
if (decider.seat === "host_window_closed")
return noted(`approval for "${toolName}" was not answered within this deployment's approval window${quoted}\nThe deployment's policy declined this tool use because its approval window closed with no one ` +
`answering it; the call did NOT run. Do not claim it succeeded and do not retry it unchanged; report what was blocked and why you needed it, then continue with the parts of the task that do not need this approval.`, "policy note");
void decider.seat;
const body = answeredByRunChannel
? `approval required for "${toolName}" but this run has no interactive approval channel${quoted}\nThe deployment's policy declined this tool use; the call did NOT run. Action requires interactive approval and ` +
`permission prompts are not available in this context. Do not claim it succeeded and do not retry it here; report what ` +
`was blocked and why you needed it, then continue with the parts of the task that do not require approval.`
: `the deployment's policy declined this call to "${toolName}"${quoted}\nThe call did NOT run. Do not claim it succeeded and do ` +
`not retry it here; report what was blocked and why you needed it, then continue with the parts of the task the policy does not block.`;
return noted(body, "policy note");
}
function withdrawnAskMessage(toolName, askMessage, note) {
const body = `approval for "${toolName}" was withdrawn before anyone answered it${askMessage !== undefined ? `: ${askMessage}` : ""}\n` +
`The approval system closed this request without an answer, so the call did NOT run. Nobody refused it, so this is not ` +
`the user's decision; ask again if it is still needed.`;
return note === undefined ? body : `${body}\nHost note:\n${delimitUntrusted("host note", note, REVIEWER_NOTE_MAX_BODY)}`;
}
const quotingQuestion = Object.freeze({ quotesQuestion: true });
export const BIDI_CONTROL_CHARS = "\\u061C\\u200E\\u200F\\u202A-\\u202E\\u2066-\\u2069";
const BIDI_CONTROL_RE = new RegExp(`[${BIDI_CONTROL_CHARS}]`, "u");
const BIDI_SCAN_MAX_NODES = 5_000;
const BIDI_SCAN_MAX_CHARS = 1_000_000;
export function carriesBidiControls(value, limits) {
let budget = limits?.maxNodes ?? BIDI_SCAN_MAX_NODES;
let charBudget = limits?.maxChars ?? BIDI_SCAN_MAX_CHARS;
const seen = new WeakSet();
const scan = (s) => {
if (charBudget <= 0)
return false;
const window = s.length <= charBudget ? s : s.slice(0, charBudget);
charBudget -= window.length;
return BIDI_CONTROL_RE.test(window);
};
const walk = (v) => {
if (budget-- <= 0)
return false;
if (typeof v === "string")
return scan(v);
if (typeof v !== "object" || v === null)
return false;
if (seen.has(v))
return false;
seen.add(v);
if (Array.isArray(v)) {
for (const el of v) {
if (walk(el))
return true;
if (budget <= 0)
return false;
}
return false;
}
if (v instanceof Map) {
for (const [k, val] of v) {
if (walk(k) || walk(val))
return true;
if (budget <= 0)
return false;
}
return false;
}
if (v instanceof Set) {
for (const el of v) {
if (walk(el))
return true;
if (budget <= 0)
return false;
}
return false;
}
for (const k in v) {
if (budget-- <= 0)
return false;
if (!Object.prototype.hasOwnProperty.call(v, k))
continue;
if (scan(k))
return true;
if (walk(v[k]))
return true;
if (budget <= 0 || charBudget <= 0)
return false;
}
return false;
};
try {
return walk(value);
}
catch {
return false;
}
}
export function cardCarriesBidiControls(card) {
return carriesBidiControls(card.args) || carriesBidiControls(card.preview) || carriesBidiControls(card.existingTarget);
}
export async function resolveAsk(req, onAsk, signal, onLateSettlement) {
return resolveAskFor(req, onAsk, signal, onLateSettlement, undefined);
}
export async function resolveAskFor(asRequested, onAsk, signal, onLateSettlement, asked, onApproverDefect, approvalWords, say, ifUnavailable) {
const { ifUnavailable: _claimedLanding, ...unlanded } = withEngineCardWords(asRequested, say);
const req = ifUnavailable !== undefined ? { ...unlanded, ifUnavailable } : unlanded;
const askedDigest = exactBoundInputHashOf(req.toolName, req.args);
const question = asked !== undefined ? engineSentenceOf(asked, req) : undefined;
const { settlement, bindingRefusal, quotesQuestion, unanswered, decidedVia, feedback: words, ...r } = await resolveAskArms(req, onAsk, signal, onLateSettlement, approvalWords !== undefined);
if (words !== undefined)
await approvalWords?.(words);
if (settlement === undefined)
return r;
if (onApproverDefect !== undefined && (settlement.kind === "approver_error" || settlement.kind === "approver_contract")) {
onApproverDefect({ cause: settlement.kind === "approver_error" ? "threw" : "out_of_contract", seat: isPolicyApprover(onAsk) ? "policy" : "approver" });
}
const echoed = quotesQuestion === true && question?.echoed !== undefined && req.message === askCardMessageOf(question.text, req.askClass, req.classes) && r.message !== undefined ? question.echoed : undefined;
const licensedDigest = r.action === "allow" && r.updatedInput !== undefined ? exactBoundInputHashOf(req.toolName, r.updatedInput) : r.presentedInput !== undefined ? exactBoundInputHashOf(req.toolName, r.presentedInput) : askedDigest;
return attest(r, req, { settlement, ...(decidedVia !== undefined ? { decidedVia } : {}), ...(req.origin !== undefined ? { origin: req.origin } : {}), ...(req.classes !== undefined ? { classes: req.classes } : {}), ...(licensedDigest !== undefined ? { inputDigest: licensedDigest } : {}), ...(bindingRefusal !== undefined ? { bindingRefusal } : {}), ...(unanswered !== undefined && r.message !== undefined ? { unanswered: { cause: unanswered, question: req.message, text: r.message } } : {}), ...(echoed !== undefined ? { sentence: { text: r.message, echoed } } : {}) });
}
function raceAskWaitAgainstSignal(wait, signal) {
const settledWait = wait.then((value) => ({ tag: "value", value }), (error) => ({ tag: "threw", error }));
if (signal === undefined)
return settledWait;
if (signal.aborted)
return Promise.resolve({ tag: "aborted" });
return new Promise((resolve) => {
let settled = false;
const finish = (r) => {
if (settled)
return;
settled = true;
signal.removeEventListener("abort", onAbort);
resolve(r);
};
const onAbort = () => finish({ tag: "aborted" });
signal.addEventListener("abort", onAbort, { once: true });
void settledWait.then(finish);
});
}
function detachLateAskWait(wait, onLate) {
const disclose = (late) => {
try {
onLate?.(late);
}
catch {
}
};
void wait
.then((late) => {
let approved = false;
try {
approved = late === true || (typeof late === "object" && late !== null && late.allow === true);
}
catch (err) {
disclose({ kind: "error", error: err });
return;
}
if (approved)
disclose({ kind: "approve" });
}, (error) => {
disclose({ kind: "error", error });
})
.catch(() => undefined);
}
function readApproverOutcomeObject(answer, toolName, seat) {
const ok = answer === false ? Object.assign(Object.create(null), { allow: false }) : answer;
const refused = (message, settlement) => ({ kind: "refused", message, settlement });
let supplied;
let allowed;
let suppliedEdit;
let suppliedApprover;
let suppliedVia;
let grant;
let feedback;
try {
supplied = ok.settledBy;
allowed = ok.allow;
suppliedEdit = ok.updatedInput;
suppliedApprover = ok.approver;
suppliedVia = ok.decidedVia;
grant = { dir: ok.readRootGrant, lasts: ok.readRootGrantLasts, call: ok.sessionCallGrant };
feedback = ok.feedback;
}
catch (err) {
return refused(`the approver's outcome for "${toolName}" could not be read (${describeThrown(err)}) — denied fail-closed`, settledByNobody("approver_contract"));
}
if (typeof allowed !== "boolean") {
return refused(`the approver for "${toolName}" returned an object whose allow is not a boolean ` +
`(got ${allowed === null ? "null" : typeof allowed}) — a verdict is exactly true or false; denied fail-closed`, settledByNobody("approver_contract"));
}
if (supplied !== undefined && !isApproverSettledBy(supplied)) {
const words = APPROVER_SETTLED_BY.map((w) => `"${w}"`);
return refused(`the approver for "${toolName}" reported settledBy "${typeof supplied === "string" ? containThrownText(supplied) : supplied === null ? "null" : typeof supplied}", which is outside what a synchronous ` +
`approver may self-report — it is exactly ${words.slice(0, -1).join(", ")} or ${words[words.length - 1]} (or omitted); denied fail-closed`, settledByNobody("approver_contract"));
}
const settledWord = supplied ?? (seat.isPolicy && allowed === false ? "policy" : "human");
const attribution = screenApproverAttribution(suppliedApprover);
if (attribution.defect !== undefined) {
return refused(`the approver for "${toolName}" reported an attribution this seam refuses: ${attribution.defect}; denied fail-closed`, settledByNobody("approver_contract"));
}
const via = screenDecidedVia(suppliedVia, settledWord, allowed);
if (via.defect !== undefined) {
return refused(`the approver for "${toolName}" reported a decidedVia this seam refuses: ${via.defect}; denied fail-closed`, settledByNobody("approver_contract"));
}
if (seat.editLane === "none" && (grant.dir !== undefined || grant.lasts !== undefined)) {
return refused(`the approver for "${toolName}" attached a ${grant.dir !== undefined ? "readRootGrant" : "readRootGrantLasts"} on a seat that offers no directory — denied fail-closed (a grant answers an approval card's readRootCandidate)`, settledByNobody("approver_contract"));
}
if (seat.editLane === "none" && grant.call !== undefined) {
return refused(`the approver for "${toolName}" attached a sessionCallGrant on a seat that offers none — denied fail-closed (a session call grant answers an approval card's sessionCallGrant)`, settledByNobody("approver_contract"));
}
const deciderParty = settledWord === "policy" ? "policy" : "person";
const decider = namesNoDecider(settledWord) ? undefined : deciderParty;
const live = liveWordsOf(feedback, { toolName, allowed, byPerson: decider === "person" && !seat.isPolicy, hasCarrier: seat.takesWords });
if (live.kind === "refused")
return refused(live.message, settledByNobody("approver_contract"));
const words = live.words;
if (allowed !== true) {
let reasonText;
try {
const suppliedReason = ok.reason;
if (suppliedReason !== undefined && typeof suppliedReason !== "string") {
return refused(`the approver for "${toolName}" attached a reason that is not a plain string ` +
`(got ${suppliedReason === null ? "null" : typeof suppliedReason}) — a deny note is the decider's plain text; denied fail-closed`, settledByNobody("approver_contract"));
}
reasonText = typeof suppliedReason === "string" ? suppliedReason : undefined;
}
catch (err) {
return refused(`the approver for "${toolName}" attached a reason that could not be read (${describeThrown(err)}) — denied fail-closed`, settledByNobody("approver_contract"));
}
const note = decidersNote(reasonText);
return {
kind: "deny",
word: settledWord,
note,
via: via.decidedVia,
grant,
settlement: namesNoDecider(settledWord) ? hostEndOf(settledWord) : settledByDecider(deciderParty, "refused", attribution.approver, note),
};
}
if (decider === undefined) {
return refused(`the approver for "${toolName}" returned an allow settled by "${settledWord}" — that word names a wait that ended ` +
`with nobody answering: it cannot be what approved a call; denied fail-closed ` +
`(report "${settledWord}" with allow:false; a person's allow is settledBy "human"/omitted, the deployment policy's is "policy")`, settledByNobody("approver_contract"));
}
if (editOfAnswer(toolName, seat.shown, suppliedEdit) === undefined)
return { kind: "allow", edit: undefined, settlement: settledByDecider(decider, "allowed", attribution.approver), grant, words };
if (seat.editLane === "none") {
return refused(`the approver for "${toolName}" attached an edit (updatedInput) on a seat that has no lane to adjudicate one — ` +
`this seat's answer is the deployment POLICY's verdict, and an edit arriving through it would execute without the ` +
`re-adjudication an approver's edit gets; denied fail-closed (approve or refuse what was shown, and route edits ` +
`through the run's approver seat)`, settledByNobody("approver_contract"));
}
const edit = bindableArgsOf(toolName, suppliedEdit);
if (!edit.ok)
return { kind: "refused", message: edit.refusal, settlement: settledByNobody("presentation_failed"), binding: true };
return { kind: "allow", edit: { value: edit.value }, settlement: settledByDecider(decider, "allowed", attribution.approver), grant, words };
}
async function resolveAskArms(req, onAsk, signal, onLateSettlement, takesWords = false) {
if (onAsk === "allow") {
if (req.requiresRealApproval === true)
return { ...unjudgedAllowRefused(req, "blanket"), ...quotingQuestion };
return { action: "allow", decisionReason: "mode" };
}
if (onAsk === undefined || onAsk === "deny") {
const bound = bindableArgsOf(req.toolName, req.args);
return {
action: "deny",
message: bound.ok ? unresolvedAskDenialMessage("no_approver_wired", req.message, false) : bound.refusal,
decisionReason: "mode",
settlement: settledByNobody("no_approver"),
...(bound.ok ? { ...quotingQuestion, unanswered: "no_approver_wired" } : { bindingRefusal: bound.refusal }),
};
}
if (signal?.aborted) {
return { action: "deny", message: `approval aborted for "${req.toolName}" (run or turn interrupted)`, decisionReason: "mode", settlement: settledByNobody("task_aborted") };
}
const presented = bindableArgsOf(req.toolName, req.args);
if (!presented.ok)
return { action: "deny", message: presented.refusal, decisionReason: "mode", settlement: settledByNobody("presentation_failed"), bindingRefusal: presented.refusal };
const offered = ownReadRootCandidate(req.readRootCandidate);
const offeredCall = ownSessionCallGrantOffer(req.sessionCallGrant);
const declared = declaredClassAnswer(onAsk, req.classes);
let ok;
if (declared !== undefined)
ok = declared;
else
try {
const approverView = { value: structuredClone(presented.value) };
const reconciliationHash = exactBoundInputHashOf(req.toolName, presented.value);
const bidi = cardCarriesBidiControls({ args: presented.value, preview: req.preview, existingTarget: req.existingTarget });
const { hasBidiControls: _carried, boundInputHash: _claimed, ...bare } = req;
const wait = Promise.resolve(onAsk({
...bare,
...(reconciliationHash !== undefined ? { boundInputHash: reconciliationHash } : {}),
args: approverView.value,
...(bidi ? { hasBidiControls: true } : {}),
...(offered !== undefined ? { readRootCandidate: { ...offered } } : {}),
...(offeredCall !== undefined ? { sessionCallGrant: { ...offeredCall } } : {}),
}, signal));
const windowMs = req.denialLimitFallback !== undefined && req.denialLimitFallback.autoDenyAfterMs > 0 ? req.denialLimitFallback.autoDenyAfterMs : undefined;
const raced = await withTimeout(raceAskWaitAgainstSignal(wait, signal), windowMs, () => DEADLINE_ELAPSED);
if (raced === DEADLINE_ELAPSED) {
detachLateAskWait(wait, onLateSettlement);
return {
action: "deny",
message: `no one answered the classifier denial-limit approval for "${req.toolName}" — the ${String(windowMs)}ms window ` +
`elapsed with no answer; auto-denied: ${req.message}`,
decisionReason: "mode",
settlement: { kind: "denial_limit_window_expired", who: { party: "engine", window: "denial_limit" }, when: Date.now() },
...quotingQuestion,
};
}
if (raced.tag === "aborted") {
detachLateAskWait(wait, onLateSettlement);
return { action: "deny", message: `approval aborted for "${req.toolName}" (run or turn interrupted)`, decisionReason: "mode", settlement: settledByNobody("task_aborted") };
}
if (raced.tag === "threw")
throw raced.error;
ok = raced.value;
}
catch (err) {
return {
action: "deny",
message: `approval errored for "${req.toolName}": ${describeThrown(err)}`,
decisionReason: "mode",
settlement: settledByNobody("approver_error"),
};
}
if (signal?.aborted) {
return { action: "deny", message: `approval aborted for "${req.toolName}" (run or turn interrupted)`, decisionReason: "mode", settlement: settledByNobody("task_aborted") };
}
if (ok === "unavailable" || ok === "window_expired") {
const cause = ok === "unavailable" ? "approver_unavailable" : "approval_window_expired";
return {
action: "deny",
message: unresolvedAskDenialMessage(cause, req.message, false), unanswered: cause,
decisionReason: "mode",
settlement: ok === "unavailable" ? settledByNobody("approver_unavailable") : hostEndOf("timeout"),
approverUnavailable: true,
...quotingQuestion,
};
}
const allowWithoutAPerson = (party) => req.requiresRealApproval === true && (party === "policy" || isPolicyApprover(onAsk));
if (ok === false || (typeof ok === "object" && ok !== null)) {
const reading = readApproverOutcomeObject(ok, req.toolName, { editLane: "readjudicated", takesWords, isPolicy: isPolicyApprover(onAsk), shown: exactBoundInputHashOf(req.toolName, presented.value) });
if (reading.kind === "refused")
return { action: "deny", message: reading.message, decisionReason: "mode", settlement: reading.settlement, ...(reading.binding === true ? { bindingRefusal: reading.message } : {}) };
if (reading.kind === "allow" && allowWithoutAPerson(reading.settlement.who.party)) {
return { ...unjudgedAllowRefused(req, "policy"), ...quotingQuestion };
}
if (reading.kind === "deny") {
return {
action: "deny",
message: reading.word === "timeout"
? `approval for "${req.toolName}" was not answered before the approver's own window elapsed: ${req.message}${reading.note !== undefined ? `\nReviewer note:\n${delimitUntrusted("reviewer note", reading.note, REVIEWER_NOTE_MAX_BODY)}` : ""}`
: reading.word === "withdrawn"
? withdrawnAskMessage(req.toolName, req.message, reading.note)
: reading.word === "policy"
? policyRefusalMessage(req.toolName, req.message, reading.note, reading.via, true)
: humanRefusalMessage(req.toolName, req.message, reading.note, req.isDelegatedChild === true),
decisionReason: "mode",
settlement: reading.settlement, ...(reading.via !== undefined ? { decidedVia: reading.via } : {}),
...quotingQuestion,
};
}
const words = reading.words !== undefined ? { feedback: reading.words } : {};
const byPerson = reading.settlement.who.party === "person" && !isPolicyApprover(onAsk);
const grantSeat = { ...readRootGrantSeat(reading.grant.dir, reading.grant.lasts, offered, byPerson), ...sessionCallGrantSeat(reading.grant.call, offeredCall, reading.edit !== undefined, byPerson) };
if (reading.edit === undefined)
return { action: "allow", decisionReason: "mode", presentedInput: presented.value, settlement: reading.settlement, ...grantSeat, ...words };
return { action: "allow", updatedInput: reading.edit.value, decisionReason: "mode", settlement: reading.settlement, ...grantSeat, ...words };
}
const okRaw = ok;
if (okRaw === true) {
if (allowWithoutAPerson("person"))
return { ...unjudgedAllowRefused(req, "policy"), ...quotingQuestion };
return { action: "allow", decisionReason: "mode", presentedInput: presented.value, settlement: settledByDecider("person", "allowed", undefined) };
}
return {
action: "deny",
message: outOfContractAnswerMessage(req.toolName, typeof ok, `true, false, "unavailable", "window_expired", or the {allow} object`),
decisionReason: "mode",
settlement: settledByNobody("approver_contract"),
};
}
const outOfContractAnswerMessage = (toolName, got, contract) => `the approver for "${toolName}" returned an out-of-contract value (${got}) — denied fail-closed (return ${contract})`;
export const RECEIVED_RESOLUTION_MEMBERS = Object.freeze(["action", "message", "decisionReason", "updatedInput", "presentedInput", "approverUnavailable", "attestation", "settlement"]);
export function receivedResolution(answer, toolName) {
let copy, member, unread;
if (typeof answer === "object" && answer !== null) {
copy = {};
try {
for (const name of RECEIVED_RESOLUTION_MEMBERS) {
member = name;
const value = answer[name];
if (value !== undefined)
Object.defineProperty(copy, name, { value, enumerable: true });
}
}
catch {
unread = { member: member };
}
Object.freeze(copy);
}
const action = unread === undefined ? copy?.action : undefined;
if (action === "allow" || action === "deny")
return copy;
const got = copy === undefined ? (answer === null ? "null" : typeof answer) : unread !== undefined ? `an object whose ${unread.member} could not be read` : action === undefined ? "an object with no action" : typeof action === "string" ? `action "${containThrownText(action)}"` : `action of type ${typeof action}`;
return { action: "deny", message: outOfContractAnswerMessage(toolName, got, `{ action: "allow" } or { action: "deny" }`), decisionReason: "mode" };
}