@sema-agent/core
Version:
Stateless, task-oriented AI agent core
58 lines (57 loc) • 3 kB
JavaScript
import { readPrincipal } from "./principal-name.js";
const KINDS = ["named", "localOwner", "org"];
const NAMES = {
named: "a named person's rule bucket",
localOwner: "the local owner's rule bucket",
org: "the org rule partition",
};
export function bucketsReadableBy(seats) {
const provider = seats.provider;
const durable = provider?.partitions.durable === true;
return bucketsFrom({ named: durable, localOwner: durable && seats.localOwnerDeclared && provider?.forLocalOwner !== undefined, org: provider?.partitions.org === true });
}
export function persistedRuleBucketsOf(owner) {
const can = bucketsReadableBy(owner);
const principal = readPrincipal(owner.principal).kind;
return bucketsFrom({ named: can?.named === true && principal === "name", localOwner: can?.localOwner === true && principal === "absent", org: can?.org === true });
}
export function readRuleBuckets(value, record) {
if (value === undefined)
return undefined;
let held = [];
try {
if (value !== null && typeof value === "object")
held = Reflect.ownKeys(value).map((k) => [k, value[k]]);
}
catch {
held = [];
}
if (held.length > 0 && held.every(([k, v]) => KINDS.includes(k) && v === true)) {
return bucketsFrom({ named: held.some(([k]) => k === "named"), localOwner: held.some(([k]) => k === "localOwner"), org: held.some(([k]) => k === "org") });
}
throw refusal(`the record of the persisted-rule buckets the legs above this leg read, carried on its ${record}, cannot be read (it is not an object naming one or more of named, localOwner, org, each true); refusing rather than judging this leg's Runner against it`, { unreadable: record });
}
export function joinRuleBuckets(a, b) {
return bucketsFrom({ named: a?.named === true || b?.named === true, localOwner: a?.localOwner === true || b?.localOwner === true, org: a?.org === true || b?.org === true });
}
function bucketsFrom(has) {
const kinds = KINDS.filter((k) => has[k]);
return kinds.length === 0 ? undefined : Object.freeze(Object.fromEntries(kinds.map((k) => [k, true])));
}
export function refuseUnreadAncestorBuckets(ancestors, seats) {
if (ancestors === undefined)
return;
const own = bucketsReadableBy(seats);
const missing = KINDS.filter((k) => ancestors[k] === true && own?.[k] !== true);
if (missing.length === 0)
return;
const give = missing.includes("localOwner") ? "`permissionRuleStore` and `localOwnerRules: true`" : "`permissionRuleStore`";
throw refusal(`this leg's Runner cannot read ${missing.map((k) => NAMES[k]).join(" and ")} that the legs above it read; give the Runner used for delegation the same ${give} ` +
"(refusing rather than running it without the person's stored deny and ask rules)", { missing });
}
function refusal(message, detail) {
const e = new Error(message);
e.code = "config.persisted_rule_bucket_missing";
e.detail = detail;
return e;
}