@sema-agent/core
Version:
Stateless, task-oriented AI agent core
292 lines (291 loc) • 13.3 kB
JavaScript
import { deliverEngineNotice } from "../../core/engine-notice.js";
import { keepsReadFloor } from "../../core/remote-env.js";
import { seatbeltProfile } from "../../core/shell-confinement.js";
import { thrownText } from "../../core/thrown-value.js";
import { redactThenCut } from "../../core/untrusted-egress.js";
import { compileReadDeny, readDenySeat, seatForCall } from "./read-deny.js";
import { isAbsoluteForFamily } from "./safety.js";
export function readFloorSeat(table) {
if (table === undefined)
return undefined;
return (toolCallId) => readFloorOf(seatForCall(table, toolCallId));
}
function readFloorOf(seat) {
return floorOver(typeof seat.forCall === "function" ? seat.forCall(undefined) : seat);
}
function floorOver(table) {
const rows = Object.freeze([...readDenySeat(table).denyEntries]);
if (rows.length === 0)
return undefined;
const id = typeof table.id === "string" ? table.id : undefined;
const denies = (absolutePath) => {
if (typeof absolutePath !== "string" || !isAbsoluteForFamily("own", absolutePath))
return rows[0];
try {
return table.matchPath(absolutePath)?.pattern ?? null;
}
catch {
return rows[0];
}
};
let made;
const confinement = (dialect) => {
if (dialect !== "seatbelt")
return { ok: false, row: rows[0], reason: `no confinement dialect is named ${JSON.stringify(dialect)} (the one dialect is "seatbelt")` };
try {
table.matchPath("/");
const segments = table.compiledSegments;
const rules = table.ruleRows ?? NO_RULE_ROWS;
if (made === undefined || made.segments !== segments || made.rules !== rules)
made = { segments, rules, profile: seatbeltProfileOf(segments, rules, rows[0]) };
return made.profile;
}
catch (e) {
return { ok: false, row: rows[0], reason: `the read-deny table cannot be judged now (${redactThenCut(thrownText(e), 300)})` };
}
};
return Object.freeze({ ...(id !== undefined ? { id } : {}), rows, denies, confinement });
}
const SEATBELT_EXPRESSION_MAX = 900;
const SEGMENT_SEP = "[/\\\\]";
const NO_RULE_ROWS = Object.freeze([]);
let canonicalAliases;
function aliasesOf() {
if (canonicalAliases !== undefined)
return canonicalAliases;
const single = new Map();
const multi = new Set();
for (let c = 0; c < 0x30000; c++) {
if (c >= 0xd800 && c <= 0xdfff)
continue;
const ch = String.fromCodePoint(c);
const n = ch.normalize("NFC");
if (n === ch)
continue;
if ([...n].length === 1)
single.set(n, [...(single.get(n) ?? []), ch]);
else
multi.add(n);
}
return (canonicalAliases = { single, multi: [...multi] });
}
function codePointExpression(ch, foldAscii, exact) {
const c = ch.codePointAt(0);
const letter = (c >= 0x41 && c <= 0x5a) || (c >= 0x61 && c <= 0x7a);
const spellings = foldAscii && letter ? [ch.toLowerCase(), ch.toUpperCase()] : [ch];
const aliases = exact ? [] : spellings.flatMap((sp) => aliasesOf().single.get(sp) ?? []);
if (spellings.length === 1 && aliases.length === 0)
return escapeLiteral(ch);
if (letter)
return `[${[...spellings, ...aliases].join("")}]`;
return `(${[...spellings, ...aliases].map(escapeLiteral).join("|")})`;
}
function escapeLiteral(x) {
return x.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function seatbeltProfileOf(segments, rules, firstRow) {
if (segments === undefined)
return { ok: false, row: firstRow, reason: "the table carries no compiled rows to translate (a hand-built table)" };
const reads = new Set();
const holds = new Set();
const add = (row, e) => {
if ("untranslatable" in e)
return { ok: false, row, reason: e.untranslatable };
for (const x of [...e.reads, ...e.holds]) {
if (Buffer.byteLength(JSON.stringify(x)) - 2 > SEATBELT_EXPRESSION_MAX)
return { ok: false, row, reason: `its expression is longer than the ${SEATBELT_EXPRESSION_MAX} bytes a seatbelt profile reads` };
}
for (const x of e.reads)
reads.add(x);
for (const x of e.holds)
holds.add(x);
return undefined;
};
for (const pat of segments) {
const refused = add(pat.raw, segmentRowExpressions(pat));
if (refused !== undefined)
return refused;
}
for (const rule of rules) {
const refused = add(rule.rule, ruleRowExpressions(rule));
if (refused !== undefined)
return refused;
}
return { ok: true, profile: seatbeltProfile([...reads], [...holds]) };
}
function literalExpression(text, foldAscii, exact = false) {
let out = "";
for (const cluster of text.match(/\P{M}\p{M}*|\p{M}+/gu) ?? []) {
for (const ch of cluster) {
const c = ch.codePointAt(0);
if (c < 0x20 || c === 0x7f)
return { untranslatable: "it holds a control character" };
}
const composed = cluster.normalize("NFC");
const decomposed = cluster.normalize("NFD");
const cannotList = { untranslatable: `its name holds a character (${JSON.stringify(cluster)}) whose canonical spellings the dialect cannot list` };
if (!exact && aliasesOf().multi.some((m) => composed.includes(m)))
return cannotList;
if (exact || (composed === decomposed && cluster === composed)) {
for (const ch of cluster)
out += codePointExpression(ch, foldAscii, exact);
continue;
}
const parts = [...decomposed];
if (parts.length !== 2)
return cannotList;
const spell = (x) => [x, ...(aliasesOf().single.get(x) ?? [])];
const forms = new Set([...spell(composed)]);
for (const b of spell(parts[0]))
for (const m of spell(parts[1]))
forms.add(`${b}${m}`);
out += `(${[...forms].map(escapeLiteral).join("|")})`;
}
return out;
}
function segmentExpression(source, foldAscii) {
const parts = [];
const texts = source.split("*");
for (const [i, part] of texts.entries()) {
const last = [...part.normalize("NFD")].at(-1);
if ((i < texts.length - 1 && last !== undefined && /\p{M}/u.test(last)) || (i > 0 && /^\p{M}/u.test(part.normalize("NFD")))) {
return { untranslatable: `a marked character stands beside a wildcard in ${JSON.stringify(source)} (the marks the wildcard meets can reorder into it)` };
}
const lit = literalExpression(part, foldAscii);
if (typeof lit !== "string")
return lit;
parts.push(lit);
}
const trailing = /[*. ]$/.test(source) ? "" : "[. ]*";
return `${SEGMENT_SEP}${parts.join("[^/\\\\]*")}${trailing}`;
}
function segmentRowExpressions(pat) {
if (pat.fold === "unicode")
return { untranslatable: "its case fold is not the deny table's" };
const fold = pat.fold === "ascii";
const run = [];
for (const seg of pat.segments) {
const e = segmentExpression(seg.source, fold);
if (typeof e !== "string")
return e;
run.push(e);
}
if (pat.anchors !== undefined) {
const reads = [];
const holds = [];
for (const anchor of pat.anchors) {
const at = [];
for (const seg of anchor) {
const e = literalExpression(seg, fold);
if (typeof e !== "string")
return e;
at.push(`${SEGMENT_SEP}${e}${/[. ]$/.test(seg) ? "" : "[. ]*"}`);
}
const whole = `^${at.join("")}${run.join("")}(${SEGMENT_SEP}.*)?$`;
reads.push(whole);
holds.push(whole);
const located = [...at, ...run];
for (let k = 1; k < located.length; k++)
holds.push(`^${located.slice(0, k).join("")}$`);
}
return { reads, holds };
}
const whole = `^(/.*)?${run.join("")}(${SEGMENT_SEP}.*)?$`;
const holds = [whole];
for (let k = 1; k < run.length; k++)
holds.push(`^(/.*)?${run.slice(0, k).join("")}$`);
return { reads: [whole], holds };
}
function ruleRowExpressions(rule) {
const shape = rule.reachShape;
if (shape === undefined)
return { untranslatable: "the row's reach has no shape a profile can spell (a hand-built row, or one whose base is missing)" };
const at = [];
for (const seg of shape.at.split("/").filter(Boolean)) {
const e = literalExpression(seg, false, true);
if (typeof e !== "string")
return e;
at.push(`/${e}`);
}
const globs = [];
for (const glob of shape.globs) {
if (glob === "**") {
globs.push("(/[^/]+)*");
continue;
}
const parts = [];
for (const part of glob.split("*")) {
const lit = literalExpression(part, false, true);
if (typeof lit !== "string")
return lit;
parts.push(lit);
}
globs.push(`/${parts.join("[^/]*")}`);
}
const whole = `^${at.join("")}${globs.join("")}(/.*)?$`;
const holds = [whole];
for (let k = 1; k <= at.length; k++)
holds.push(`^${at.slice(0, k).join("")}$`);
return { reads: [whole], holds };
}
export function screenReadDenyFloorRequired(value, seat) {
if (value === undefined || typeof value === "boolean")
return value;
const e = new Error(`${seat} must be a boolean or absent (got ${value === null ? "null" : typeof value}) — a requirement that cannot be read is no requirement, so it refuses loudly instead of reading as one side.`);
e.code = "config.read_face_seat";
throw e;
}
export const READ_DENY_FLOOR_UNKEPT = "config.read_deny_floor_unkept";
export function readDenyFloorUnkeptNotice(platform = process.platform) {
const action = platform === "darwin"
? "enable this Mac's OS confinement where it applies"
: "run commands in an execution environment that keeps the floor";
return `Files on the read-deny list can still be opened by recursive command reads here; the deployment operator can ${action}.`;
}
export function readDenyFloorRefusal(facts) {
if (!facts.required || facts.rows === 0 || keepsReadFloor(facts.env))
return undefined;
const e = new Error("The run's read-deny table holds rows — the deployment's own rows (its built-in tiers and readDenyPatterns) count as well as the caller's, so a run that brings no rule of its own is refused too — and the execution environment does not declare that it keeps the byte floor (capabilities.keepsReadFloor is not true), while the deployment requires the floor (readDenyFloorRequired) — refused before any command starts. Run it on an environment that keeps the floor, or unset the requirement.");
e.code = READ_DENY_FLOOR_UNKEPT;
return e;
}
export function deploymentReadDenyEntries(patterns, builtin) {
return compileReadDeny(patterns ?? [], "readDenyPatterns", builtin).entries;
}
const entryKey = (e) => `${e.caseSensitive ? "s" : "i"}:${e.pattern}`;
function rowsOf(table, deployment) {
const named = new Set(deployment.map(entryKey));
const rowCount = readDenySeat(table).denyEntries.length;
const deploymentRowCount = table.entries.filter((e) => named.has(entryKey(e))).length;
return { rowCount, callerRowCount: rowCount - deploymentRowCount, deploymentRowCount };
}
export function judgeReadFloorKept(j) {
const rowCount = j.table === undefined ? 0 : readDenySeat(j.table).denyEntries.length;
if (j.table === undefined || rowCount === 0)
return false;
if (j.floor === undefined || j.floor.rows.length !== rowCount) {
throw new Error(`the read-deny table holds ${rowCount} row(s) but the floor its engine starts would carry holds ${j.floor?.rows.length ?? 0} — refused rather than start commands with fewer rows than the table refuses (an engine defect).`);
}
const refusal = readDenyFloorRefusal({ env: j.env, required: j.required, rows: rowCount });
if (refusal !== undefined)
throw refusal;
if (keepsReadFloor(j.env))
return false;
const rows = rowsOf(j.table, j.deployment);
if (rows.callerRowCount === 0)
return rows;
deliverEngineNotice(j.onNotice, {
code: READ_DENY_FLOOR_UNKEPT,
message: readDenyFloorUnkeptNotice(),
detail: { ...rows, ...(j.attribution?.sessionId !== undefined ? { sessionId: j.attribution.sessionId } : {}), ...(j.attribution?.runId !== undefined ? { runId: j.attribution.runId } : {}) },
}, undefined, j.told);
return rows;
}
export function latchReadFloor(held, judged) {
if (judged === false)
return held;
return held === false || judged.callerRowCount >= held.callerRowCount ? judged : held;
}
export function readDenyFloorSeat(latch) {
return latch === undefined || latch === false ? {} : { readDenyFloor: { kept: false, rowCount: latch.rowCount, callerRowCount: latch.callerRowCount, deploymentRowCount: latch.deploymentRowCount } };
}