@sema-agent/core
Version:
Stateless, task-oriented AI agent core
527 lines (526 loc) • 25.9 kB
JavaScript
import { createHash } from "node:crypto";
import { posix } from "node:path";
import { canonicalJsonStringify } from "./canonical-json.js";
import { BARE_INTERPRETER_NAMES, COMMAND_RULE_TOOL, foldSpacing, formatRuleText, pathWithinRoot } from "./permission-rule-model.js";
import { readShellCommandIn } from "./shell-run-candidates.js";
import { thrownText } from "./thrown-value.js";
import { shellWordsOf } from "../shell/shell-words.js";
import { strayMembersOf } from "./own-property-receipt.js";
export const CALL_GRANT_MATCH = "call";
const MAX_COMMAND_CHARS = 4000;
const MAX_SEGMENTS = 8;
const MAX_SCRIPT_BYTES = 1024 * 1024;
const MAX_TREE_ENTRIES = 2000;
const MAX_TREE_FILES = 300;
const MAX_TREE_BYTES = 8 * 1024 * 1024;
const INTERPRETERS = Object.freeze({
node: { inline: ["-e", "--eval", "-p", "--print"], sources: [".js", ".mjs", ".cjs", ".json", ".node"], subcommands: ["inspect"] },
python: { inline: ["-c"], sources: [".py"] },
python2: { inline: ["-c"], sources: [".py"] },
python3: { inline: ["-c"], sources: [".py"] },
ruby: { inline: ["-e"], sources: [".rb"] },
perl: { inline: ["-e", "-E"], sources: [".pl", ".pm"] },
php: { inline: ["-r"], sources: [".php"] },
});
const RUNNER_NAMES = new Set([...Object.keys(INTERPRETERS), ...BARE_INTERPRETER_NAMES].map((n) => n.toLowerCase()));
const runnerRowOf = (name) => {
const folded = name.toLowerCase();
const bare = folded.replace(/[0-9][0-9.]*[a-z]*$/, "");
return RUNNER_NAMES.has(folded) || RUNNER_NAMES.has(bare) ? bare : undefined;
};
const OTHER_BUILTINS = new Set([
"alias", "bg", "bind", "break", "builtin", "caller", "command", "compgen", "complete", "compopt", "continue", "declare", "disown", "enable",
"eval", "exec", "exit", "export", "fc", "fg", "getopts", "hash", "help", "history", "jobs", "kill", "let", "local", "logout", "mapfile",
"read", "readarray", "readonly", "return", "set", "shift", "shopt", "source", ".", "suspend", "times", "trap", "type", "typeset",
"ulimit", "umask", "unalias", "unset", "wait",
]);
const STACK_WORDS = new Set([...shellWordsOf("stack_mover"), ...shellWordsOf("stack_editor")]);
const PRINTF_ASSIGNS = /%[-+ #'0-9.*hlLqjzt]*n/;
const PLAIN_BUILTINS = new Set(["echo", "printf", "test", "[", "true", "false", "pwd", ":"]);
const CONNECTORS = new Set(["&&", "||", ";", "|"]);
const FILE_REDIRECTIONS = new Set([">", ">>", "<", ">|", "&>", "&>>", "<>"]);
const DESCRIPTOR_REDIRECTIONS = new Set([">&", "<&"]);
const HOLE_WORD = /^[A-Za-z0-9._@%+,/][A-Za-z0-9._@%+,/-]*$/;
const sha256 = (data) => createHash("sha256").update(data).digest("hex");
export function callGrantCommandOf(binding) {
return canonicalJsonStringify(binding);
}
export function callGrantRuleTextOf(command) {
return formatRuleText(command, CALL_GRANT_MATCH, COMMAND_RULE_TOOL);
}
const no = (unbindable) => ({ unbindable });
const isAbs = (p) => p.startsWith("/");
const under = (at, word) => (isAbs(word) ? word : at === "/" ? `/${word}` : `${at}/${word}`);
const hasClimb = (word) => word.split("/").includes("..");
const inRoots = (path, roots) => roots.some((r) => pathWithinRoot(path, r));
async function canonical(seat, path, signal) {
const r = await seat.env.canonicalPath(path, signal);
if (r.ok)
return isAbs(r.value) ? { real: r.value } : no("a path resolved to no absolute path");
return r.error.code === "not_found" ? { missing: true } : no(`a path could not be resolved (${r.error.code})`);
}
async function programFileOf(seat, real, signal) {
const info = await seat.env.fileInfo(real, signal);
if (!info.ok)
return no(`a program file could not be read (${info.error.code})`);
if (info.value.kind !== "file")
return "not_executable";
if (info.value.mode === undefined)
return no("the environment does not say a program file's permission bits");
if ((info.value.mode & 0o111) === 0)
return "not_executable";
if (seat.env.fileIdentity === undefined)
return no("the environment cannot say a file's identity");
const id = await seat.env.fileIdentity(real, signal);
if (!id.ok)
return no(`a program file's identity could not be read (${id.error.code})`);
return { path: real, id: id.value, size: info.value.size, mtimeMs: info.value.mtimeMs };
}
async function programOf(seat, word, at, searchPath, signal) {
const candidates = word.includes("/") ? [under(at, word)] : searchPath.map((e) => under(e === "" ? at : under(at, e), word));
for (const c of candidates) {
const real = await canonical(seat, c, signal);
if ("unbindable" in real)
return real;
if ("missing" in real)
continue;
const file = await programFileOf(seat, real.real, signal);
if (file === "not_executable")
continue;
return file;
}
return no(`the program ${JSON.stringify(word)} resolves to no executable file`);
}
async function sourceTreeOf(seat, dir, sources, signal) {
const lines = [];
const files = [];
const stack = [dir];
let entries = 0;
while (stack.length > 0) {
const d = stack.pop();
const listed = await seat.env.listDir(d, signal);
if (!listed.ok)
return no(`the script's directory could not be listed (${listed.error.code})`);
for (const e of [...listed.value].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {
if (++entries > MAX_TREE_ENTRIES)
return no(`the script's directory tree holds more than ${MAX_TREE_ENTRIES} entries`);
const rel = posix.relative(dir, e.path);
if (e.kind === "directory")
stack.push(e.path);
else if (e.kind === "symlink") {
if (seat.env.readLink === undefined)
return no("the environment cannot read a link in the script's directory tree");
const t = await seat.env.readLink(e.path, signal);
if (!t.ok)
return no(`a link in the script's directory tree could not be read (${t.error.code})`);
lines.push(`L ${rel} ${t.value}`);
if (sources.some((x) => e.name.endsWith(x)))
files.push({ rel, path: e.path });
}
else if (sources.some((x) => e.name.endsWith(x)))
files.push({ rel, path: e.path });
}
}
if (files.length > MAX_TREE_FILES)
return no(`the script's directory tree holds more than ${MAX_TREE_FILES} source files`);
let total = 0;
for (const f of files) {
const bytes = await seat.env.readBinaryFile(f.path, signal, MAX_SCRIPT_BYTES + 1);
if (!bytes.ok)
return no(`a source file beside the script could not be read (${bytes.error.code})`);
total += bytes.value.length;
if (bytes.value.length > MAX_SCRIPT_BYTES || total > MAX_TREE_BYTES)
return no("the source files beside the script are past the size bound");
lines.push(`F ${f.rel} ${sha256(bytes.value)}`);
}
return sha256(lines.sort().join("\n"));
}
const literal = (w) => w !== undefined && w.expands === false;
const GAP = /^((?:[ \t\n]|&&|\|\||;|\|)*)(?:(\d*)(&>>|&>|>>|>&|>\||<>|<&|>|<)[ \t]*)?/;
const LEADING = /^[ \t\n]*$/;
function pieceNotCarried(command, shape) {
const notSeen = "a piece this reading does not see as a run (a test, `!`, an arithmetic command, a comment)";
let at = 0;
const gap = () => {
const g = GAP.exec(command.slice(at));
at += g[0].length;
return g;
};
for (const s of shape.segments) {
let w = 0;
let t = 0;
while (w < s.argv.length || t < s.redirections.length) {
const first = at === 0;
const g = gap();
if (first && !LEADING.test(g[0]))
return "a command that does not start with its program word";
if (g[2] !== "" && g[2] !== undefined && g[1] === "")
return notSeen;
const target = g[3] !== undefined;
if (target ? t >= s.redirections.length : w >= s.argv.length)
return notSeen;
const next = target ? s.redirections[t++].target.raw : s.argv[w++].raw;
if (next === "" || !command.startsWith(next, at))
return notSeen;
at += next.length;
}
}
const tail = gap();
return tail[3] === undefined && at === command.length ? undefined : notSeen;
}
function structuralRefusal(command, shape) {
if (shape.stopped !== undefined)
return "the command could not be read whole";
if (shape.grouped)
return "a group, subshell, control structure or function definition";
if (shape.backgrounded)
return "a background job";
if (shape.strayRedirection)
return "a redirection on a piece that runs no program";
if (shape.segments.length === 0 || shape.segments.length > MAX_SEGMENTS)
return `not 1 – ${MAX_SEGMENTS} runs`;
if (shape.connectors.some((c) => !CONNECTORS.has(c)))
return "a connector other than && || ; |";
for (const s of shape.segments) {
if (s.unreadable !== undefined || s.peelUnreadable !== undefined)
return "a run whose program cannot be named";
if (s.peeled.length > 0)
return "an assignment, wrapper or launcher in front of a program";
if (s.substituted !== undefined)
return "a substitution";
if (s.argv.length === 0 || !s.argv.every(literal))
return "an expansion in a run";
if (!s.redirections.every((r) => literal(r.target)))
return "an expansion in a redirection";
}
return pieceNotCarried(command, shape);
}
async function readCall(command, seat, holes, signal) {
if (typeof command !== "string" || command.length > MAX_COMMAND_CHARS)
return no("no command text within the bound");
if (command.includes("\\"))
return no("a backslash in the command");
const folded = foldSpacing(command);
if (folded === undefined)
return no("unbalanced quoting");
const shape = readShellCommandIn(seat.shell, command);
const refusal = structuralRefusal(command, shape);
if (refusal !== undefined)
return no(refusal);
const names = seat.env.receivedEnvNames;
if (names === undefined)
return no("the environment does not say which variables its shell child receives");
if (names.includes("BASH_ENV") || names.includes("ENV"))
return no("the shell child receives BASH_ENV or ENV (a file it runs first)");
if ((seat.env.configuredStartupFileNames ?? []).length > 0)
return no("the host configured BASH_ENV or ENV for the shell (a configured launcher may run that file first)");
if (seat.cwd === undefined || !isAbs(seat.cwd))
return no("no working directory");
const start = await canonical(seat, seat.cwd, signal);
if (!("real" in start))
return no("the working directory could not be resolved");
const declared = seat.env.searchPath;
const searchPath = Array.isArray(declared) ? declared : undefined;
const moves = shape.segments.some((s) => s.argv[0].text === "cd");
if (moves) {
const cdPath = seat.env.cdPath;
if (!Array.isArray(cdPath) || cdPath.length > 0)
return no("a cd while CDPATH is set or unknown");
if (searchPath?.some((e) => !isAbs(e)) === true)
return no("a cd while the search path holds a relative entry");
const isCd = (k) => shape.segments[k].argv[0].text === "cd";
if (shape.connectors.some((c, k) => c !== "&&" && !(c === "|" && !isCd(k) && !isCd(k + 1))))
return no("a cd bash may skip, or that does not move every run after it");
}
let at = start.real;
const segments = [];
let candidates = [];
let scriptRun = false;
for (let i = 0; i < shape.segments.length; i++) {
const s = shape.segments[i];
const head = s.argv[0].text;
if (head === "" || head.includes("="))
return no("an assignment");
if (OTHER_BUILTINS.has(head))
return no(`the builtin ${head} is no plain builtin`);
if (head === "printf" && (s.argv[1]?.text.startsWith("-") === true || PRINTF_ASSIGNS.test(s.argv[1]?.text ?? "")))
return no("printf that sets a variable (`-v`, `%n`)");
if (STACK_WORDS.has(head))
return no(`the builtin ${head} moves through the directory stack`);
const writes = [];
for (const r of s.redirections) {
if (FILE_REDIRECTIONS.has(r.op)) {
const abs = under(at, r.target.text);
const real = await canonical(seat, abs, signal);
if ("unbindable" in real)
return real;
if ("real" in real)
writes.push(real.real);
else {
const link = await seat.env.readLink?.(abs, signal);
if (link === undefined || link.ok || link.error.code !== "not_found")
return no("a redirection target that may be a link leading nowhere");
const parent = await canonical(seat, posix.dirname(abs), signal);
if (!("real" in parent))
return no("a redirection target's directory could not be resolved");
writes.push(posix.join(parent.real, posix.basename(abs)));
}
}
else if (DESCRIPTOR_REDIRECTIONS.has(r.op)) {
if (!/^(\d+|-)$/.test(r.target.text))
return no("a descriptor redirection onto a file");
}
else
return no(`the redirection ${r.op}`);
}
if (head === "cd") {
if (s.argv.length !== 2 || s.redirections.length > 0)
return no("a cd other than one literal directory");
const target = s.argv[1].text;
if (target === "" || target.startsWith("-") || hasClimb(target))
return no("a cd other than one literal directory");
segments.push({ at, program: { builtin: "cd" }, writes });
const moved = await canonical(seat, under(at, target), signal);
if (!("real" in moved))
return no("a cd target could not be resolved");
const info = await seat.env.fileInfo(moved.real, signal);
if (!info.ok || info.value.kind !== "directory")
return no("a cd target that is no directory");
at = moved.real;
continue;
}
if (PLAIN_BUILTINS.has(head)) {
segments.push({ at, program: { builtin: head }, writes });
continue;
}
const base = posix.basename(head);
const interpreter = Object.hasOwn(INTERPRETERS, base) ? INTERPRETERS[base] : undefined;
if (interpreter === undefined && BARE_INTERPRETER_NAMES.has(base))
return no(`${base} runs another program or shell code this reading does not bind`);
if (!head.includes("/") && searchPath === undefined)
return no("the environment declares no search path for a bare program name");
const program = await programOf(seat, head, at, searchPath ?? [], signal);
if ("unbindable" in program)
return program;
const rows = [runnerRowOf(base), runnerRowOf(posix.basename(program.path))];
if (interpreter === undefined ? rows.some((r) => r !== undefined) : rows[1] !== undefined && rows[1] !== rows[0])
return no(`${base} is an interpreter, shell or launcher under another name`);
if (interpreter === undefined) {
segments.push({ at, program, writes });
continue;
}
const first = s.argv[1];
if (first === undefined)
return no("an interpreter with no code");
if (interpreter.inline.includes(first.text)) {
const code = s.argv[2];
if (code === undefined)
return no("an inline-code flag with no code");
segments.push({ at, program, inline: sha256(code.text), writes });
continue;
}
if (first.text.startsWith("-") || first.text === "")
return no("an interpreter option this reading does not bind");
if (interpreter.subcommands?.includes(first.text) === true)
return no(`the interpreter subcommand ${first.text}`);
if (hasClimb(first.text))
return no("a script path through `..`");
const scriptAbs = under(at, first.text);
const script = await canonical(seat, scriptAbs, signal);
if (!("real" in script))
return no("the script could not be resolved");
if (!inRoots(script.real, seat.roots))
return no("the script lies outside the workspace roots");
const info = await seat.env.fileInfo(script.real, signal);
if (!info.ok || info.value.kind !== "file")
return no("the script is no regular file");
const bytes = await seat.env.readBinaryFile(script.real, signal, MAX_SCRIPT_BYTES + 1);
if (!bytes.ok || bytes.value.length > MAX_SCRIPT_BYTES)
return no("the script could not be read within the bound");
const tree = await sourceTreeOf(seat, posix.dirname(script.real), interpreter.sources, signal);
if (typeof tree !== "string")
return tree;
segments.push({ at, program, script: { path: script.real, sha256: sha256(bytes.value), tree }, writes });
if (shape.segments.length === 1 && s.redirections.length === 0) {
scriptRun = true;
for (let k = 2; k < s.argv.length; k++) {
const w = s.argv[k];
if (w.raw !== w.text || !HOLE_WORD.test(w.text) || hasClimb(w.text))
continue;
const real = await canonical(seat, under(at, w.text), signal);
if ("unbindable" in real)
return real;
if (!("real" in real) || !inRoots(real.real, seat.roots))
continue;
const f = await seat.env.fileInfo(real.real, signal);
if (f.ok && f.value.kind === "file")
candidates.push({ at: k, real: real.real });
}
}
}
let chosen;
if (holes === "choose")
chosen = candidates;
else {
if (holes.length > 0 && !scriptRun)
return no("the call is not the single script run its grant masks");
chosen = [];
for (const h of holes) {
const c = candidates.find((x) => x.at === h);
if (c === undefined)
return no("a masked operand names no file inside the roots");
chosen.push(c);
}
}
const argv = shape.segments[0].argv;
const digest = chosen.length > 0 ? sha256(canonicalJsonStringify({ argv: argv.map((w, k) => (chosen.some((c) => c.at === k) ? null : w.raw)) })) : sha256(folded);
const binding = {
v: 1,
cwd: start.real,
form: chosen.length > 0 ? "argv" : "text",
digest,
segments,
holes: chosen.map((c) => ({ at: c.at, dir: posix.dirname(c.real) })),
};
return { binding, holeReals: chosen.map((c) => c.real) };
}
export async function bindCall(command, seat, signal) {
try {
const read = await readCall(command, seat, "choose", signal);
return "unbindable" in read ? read : read.binding;
}
catch (err) {
return no(`the call could not be read (${thrownText(err)})`);
}
}
export async function callGrantAdmits(binding, command, seat, signal) {
try {
const read = await readCall(command, seat, binding.holes.map((h) => h.at), signal);
if ("unbindable" in read)
return false;
const now = read.binding;
if (now.form !== binding.form || now.digest !== binding.digest || now.cwd !== binding.cwd)
return false;
if (canonicalJsonStringify(now.segments) !== canonicalJsonStringify(binding.segments))
return false;
return binding.holes.every((h, k) => pathWithinRoot(read.holeReals[k], h.dir));
}
catch {
return false;
}
}
export async function callGrantRowAdmitting(rows, call) {
const judge = call.judge;
const command = call.command;
const sessionId = call.sessionId;
if (judge === undefined || typeof command !== "string" || sessionId === undefined)
return undefined;
for (const r of rows) {
if (r.match !== CALL_GRANT_MATCH || r.behavior !== "allow" || !call.words.includes(r.tool))
continue;
if (r.scope.kind !== "session" || r.scope.sessionId !== sessionId)
continue;
const binding = readCallGrantBinding(r.command);
if (binding === undefined || callGrantRuleTextOf(r.command) !== r.rule)
continue;
if (await judge(binding, command))
return r;
}
return undefined;
}
const isText = (v) => typeof v === "string" && v.length > 0 && v.length <= 4096;
const isAbsText = (v) => isText(v) && isAbs(v);
const isDigest = (v) => typeof v === "string" && /^[0-9a-f]{64}$/.test(v);
const BINDING_WORDS = Object.freeze({ subject: "a call grant row's binding", unit: "member", moment: "when the row is read" });
const ownKeys = (v, keys) => strayMembersOf(v, BINDING_WORDS, keys) === undefined;
function isProgram(v) {
if (v === null || typeof v !== "object")
return false;
const p = v;
if ("builtin" in p)
return ownKeys(p, ["builtin"]) && (p.builtin === "cd" || PLAIN_BUILTINS.has(p.builtin));
return ownKeys(p, ["path", "id", "size", "mtimeMs"]) && isAbsText(p.path) && isText(p.id) && Number.isFinite(p.size) && Number.isFinite(p.mtimeMs);
}
function isSegment(v) {
if (v === null || typeof v !== "object")
return false;
const s = v;
if (!ownKeys(s, ["at", "program", "script", "inline", "writes"]) || !isAbsText(s.at) || !isProgram(s.program))
return false;
if (!Array.isArray(s.writes) || !s.writes.every(isAbsText))
return false;
if (s.inline !== undefined && !isDigest(s.inline))
return false;
if (s.script !== undefined) {
const sc = s.script;
if (sc === null || typeof sc !== "object" || !ownKeys(sc, ["path", "sha256", "tree"]) || !isAbsText(sc.path) || !isDigest(sc.sha256) || !isDigest(sc.tree))
return false;
}
return true;
}
export function readCallGrantBinding(command) {
if (typeof command !== "string")
return undefined;
let v;
try {
v = JSON.parse(command);
}
catch {
return undefined;
}
return isBinding(v) && callGrantCommandOf(v) === command ? v : undefined;
}
function isBinding(v) {
if (v === null || typeof v !== "object" || Array.isArray(v))
return false;
const b = v;
if (!ownKeys(b, ["v", "cwd", "form", "digest", "segments", "holes"]) || b.v !== 1 || !isAbsText(b.cwd) || (b.form !== "text" && b.form !== "argv") || !isDigest(b.digest))
return false;
if (!Array.isArray(b.segments) || b.segments.length === 0 || b.segments.length > MAX_SEGMENTS || !b.segments.every(isSegment))
return false;
if (!Array.isArray(b.holes) || !b.holes.every((h) => h !== null && typeof h === "object" && ownKeys(h, ["at", "dir"]) && Number.isSafeInteger(h.at) && h.at >= 2 && isAbsText(h.dir)))
return false;
return (b.form === "text") === (b.holes.length === 0);
}
export function callGrantRowFault(r) {
if (r.behavior !== "allow" || r.tool !== COMMAND_RULE_TOOL || r.scope?.kind !== "session")
return "metadata_mismatch";
if (readCallGrantBinding(r.command) === undefined)
return "metadata_mismatch";
return r.rule === callGrantRuleTextOf(r.command) ? undefined : "invalid_rule_text";
}
const FINGERPRINT_DIGITS = 12;
function sentenceOf(o) {
const parts = [`this command (fingerprint ${o.fingerprint}) in ${o.cwd}`, `running ${o.programs.join(", ")}`];
if (o.scripts.length > 0)
parts.push(`the script ${o.scripts.join(", ")} as it is now, with the source files in its directory`);
if (o.inlineCode.length > 0)
parts.push(`inline code ${o.inlineCode.join(", ")}`);
if (o.writes.length > 0)
parts.push(`writing ${o.writes.join(", ")}`);
if (o.operandDirs.length > 0)
parts.push(`its file operands may be any file under ${o.operandDirs.join(", ")}`);
return `${parts.join("; ")} — for the rest of this session; it is asked again if one of these changes (a file the program loads from anywhere else is not one of them)`;
}
export function offerOfBinding(b) {
const command = callGrantCommandOf(b);
const members = {
fingerprint: b.digest.slice(0, FINGERPRINT_DIGITS),
cwd: b.cwd,
programs: Object.freeze(b.segments.map((s) => ("builtin" in s.program ? s.program.builtin : s.program.path))),
scripts: Object.freeze(b.segments.flatMap((s) => (s.script !== undefined ? [s.script.path] : []))),
inlineCode: Object.freeze(b.segments.flatMap((s) => (s.inline !== undefined ? [s.inline.slice(0, FINGERPRINT_DIGITS)] : []))),
writes: Object.freeze(b.segments.flatMap((s) => s.writes)),
operandDirs: Object.freeze([...new Set(b.holes.map((h) => h.dir))]),
};
return Object.freeze({ grant: callGrantRuleTextOf(command), sentence: sentenceOf(members), ...members });
}
export function sessionCallGrantOfRow(row) {
if (row.match !== CALL_GRANT_MATCH)
return undefined;
const b = readCallGrantBinding(row.command);
if (b === undefined)
return undefined;
const offer = offerOfBinding(b);
return offer.grant === row.rule ? offer : undefined;
}