@sema-agent/core
Version:
Stateless, task-oriented AI agent core
795 lines (794 loc) • 46 kB
JavaScript
import { isAbsence, observeEnvironment } from "./shell-read-environment.js";
import { errorResult } from "../../core/tools.js";
import { BASH_READONLY_CONFINEMENT_NOTE, targetUnavailableCard, targetUnavailableSentence } from "./fs-shared.js";
import { envErrorDetail } from "./env-error-detail.js";
import { holdsProcSensitiveFile, isAbsoluteForFamily, isProcSensitiveFile, normalizeAbsPathLexically, pathFamilyOf, violationDetails, withinAnyRoot } from "./safety.js";
import { checkedReadDenyHomes, fitMiddle, READ_DENY_SENTENCE_PART_MAX, readDenyRefusal } from "./read-deny.js";
import { INLINE_TRUNCATION_MARK, INLINE_TRUNCATION_MARK_CODEPOINTS, inlineUntrusted, PROBE_REASON_MAX } from "../../core/untrusted-text.js";
import { NOT_AUTO_ALLOWED, declinedProgramReason } from "./bash-program-position.js";
import { bashClassifyDefaultAllow } from "./bash-readonly-classifier.js";
import { planShellReads } from "./shell-read-plan.js";
import { readOnlyShellCall, readStationAnswer } from "../../core/shell-read-silence.js";
import { startedShellOfCall } from "../../core/call-shell.js";
import { readModelShell } from "../../core/model-shell.js";
import { createShellReadEstablisher, establishShellReadsLexically, writtenOnLineBefore } from "./shell-read-establish.js";
import { readLandingsOf } from "./shell-read-identity.js";
import { declaredReadDenyHomes, homeViewsAt } from "./read-deny-home.js";
import { anyOptionWord, programArgs } from "./shell-read-write-targets.js";
import { shellReadFaceWords } from "./shell-read-face.js";
import { passesUnasked } from "./shell-read-device.js";
import { operandWriterNames, programKeyOf, programRow, selectedOptions } from "./program-read-model.js";
import { refusedByRemoval, SHELL_REMOVAL_COMMANDS } from "./removal-targets.js";
import { allFindings, anyFaceGuards, decideShellRead, denyRowAtOrBelow, foldShellReadFindings, judgeEstablishedPlan, readRootGrantCandidateOf, stationGuards, withWriteAskRows, writeFaceGuards, writesAnything, } from "./shell-read-judge.js";
import { seatOf } from "../../core/tool-name-readings.js";
import { normalizeReadRootCandidate } from "../../core/read-root-candidate.js";
import { assertNoRetiredShellReadBoundaryKeys } from "../../core/retired-keys.js";
function containmentDetails(paths) {
return { type: "readonly_out_of_root", code: "readonly_out_of_root", paths };
}
export function unestablishedDetails() {
return { type: "read_unestablished", code: "read_unestablished" };
}
export function readTargetsRefusedDetails(code) {
return { type: "read_targets_refused", code };
}
function findingDetails(finding, paths) {
return finding === "unestablishable" || finding === "declined" || finding === "unanswered" ? unestablishedDetails() : containmentDetails(paths);
}
const WRITES_BENEATH = {
cp: () => true,
mv: () => true,
rm: (s) => selectedOptions(programRow("rm"), programArgs(s).map((w) => w.spelled)).some((o) => o.selects === "traversal"),
};
const isPattern = (f) => f.read.candidate.expands !== false && f.read.candidate.expands !== "unresolvable";
const RESHAPES_TREE = new Set(["mv"]);
const UNPLACED_OPTIONS = {
rmdir: (ws) => selectedOptions(programRow("rmdir"), ws).some((o) => o.effect === "writes"),
sed: (ws) => selectedOptions(programRow("sed"), ws).some((o) => o.value?.kind === "program-file"),
cp: anyOptionWord,
mv: anyOptionWord,
};
function runOrderOf(judged) {
const runs = [];
const plans = [];
let concurrent = false;
const walk = (j) => {
plans.push(j);
for (const s of j.segments) {
s.nested.forEach(walk);
runs.push(s);
if (j.plan.shape.backgrounded || s.segment.connector === "|")
concurrent = true;
}
};
walk(judged);
return { runs, plans, concurrent };
}
function lineOrderPlaced(runs, concurrent) {
const reshapes = (s) => RESHAPES_TREE.has(programKeyOf(s.segment.verb?.basename ?? ""));
const writes = (s) => s.findings.some((f) => f.read.candidate.face === "write");
const stepsUp = (s) => s.findings.some((f) => f.read.candidate.spelled.split(/[\\/]/).includes(".."));
const reshaping = runs.map(reshapes), writing = runs.map(writes);
const total = { reshaping: reshaping.filter(Boolean).length, writing: writing.filter(Boolean).length };
const before = { reshaping: 0, writing: 0 };
return runs.every((later, j) => {
const reshapers = concurrent ? total.reshaping - (reshaping[j] ? 1 : 0) : before.reshaping;
const writers = concurrent ? total.writing - (writing[j] ? 1 : 0) : before.writing;
if (reshaping[j])
before.reshaping++;
if (writing[j])
before.writing++;
return reshapers === 0 && !(writers > 0 && stepsUp(later));
});
}
function writesPlacedOf(judged, boundary) {
const writeRoots = boundary.writeRoots;
if (writeRoots === undefined || writeRoots.length === 0)
return false;
const { runs, plans, concurrent } = runOrderOf(judged);
const placed = (s) => {
const verb = programKeyOf(s.segment.verb?.basename ?? "");
if (s.segment.reentry === "shell" || s.segment.unreadProgramText !== undefined)
return false;
if (UNPLACED_OPTIONS[verb]?.(programArgs(s.segment).map((w) => w.spelled)) === true)
return false;
const beneath = WRITES_BENEATH[verb]?.(s.segment) === true;
const removal = SHELL_REMOVAL_COMMANDS.includes(verb);
for (const f of s.findings) {
if (f.read.candidate.face !== "write")
continue;
const target = f.read.target;
if (f.read.established === "unestablishable" || target === undefined || isPattern(f) || f.kind !== "none" || (f.containment !== "inside" && f.containment !== "open"))
return false;
if (beneath && denyRowAtOrBelow(f.read, boundary, !removal))
return false;
if (removal && !refusedByRemoval(f.read) && writeRoots.some((root) => withinAnyRoot([target], root)))
return false;
}
return true;
};
return plans.every((p) => p.plan.unreadable === undefined) && runs.every(placed) && lineOrderPlaced(runs, concurrent);
}
function unplacedOptionsOf(judged) {
for (const s of judged.segments) {
const nested = s.nested.map(unplacedOptionsOf).find((u) => u !== undefined);
if (nested !== undefined)
return nested;
const verb = s.segment.verb === undefined ? undefined : programKeyOf(s.segment.verb.basename);
if ((verb === "cp" || verb === "mv") && anyOptionWord(programArgs(s.segment).map((w) => w.spelled)))
return { program: verb };
}
return undefined;
}
async function writeGuardsOf(judged, boundary, env, signal) {
const judge = boundary.writeTargetJudge;
if (judge === undefined)
return { unplaced: false, writeProtected: false, writeProtectedOnDisk: false };
const { runs, concurrent } = runOrderOf(judged);
const asKey = new Map();
const asSpelling = new Map();
const landingKeys = new Set();
const writtenBy = runs.map(() => []);
const targets = [];
const add = (into, view, child, at) => {
if (!isAbsoluteForFamily(pathFamilyOf({ root: view }), view))
return;
const seen = into.get(view);
into.set(view, seen === undefined ? { child, at } : { child: seen.child && child, at: Math.max(seen.at, at) });
};
runs.forEach((s, at) => {
for (const f of s.findings) {
const written = f.read.written;
if (written === undefined || f.read.established === "unestablishable" || f.read.target === undefined || passesUnasked(f.read.candidate))
continue;
const child = written.child === true;
const key = f.read.established === "canonical" || f.read.established === "expansion";
add(key ? asKey : asSpelling, f.read.target, child, at);
if (key && written.seat === "landing")
landingKeys.add(f.read.target);
const views = [[f.read.target, key]];
if (written.seat === "landing") {
for (const spelling of f.read.spellings) {
add(asSpelling, spelling, child, at);
views.push([spelling, false]);
}
}
writtenBy[at].push(f.read.target, ...f.read.spellings);
const derived = f.read.derivedSpellings ?? [];
targets.push({ views, text: f.read.established === "expansion" ? (f.read.origin !== undefined ? [f.read.origin] : []) : f.read.spellings.filter((s) => !derived.includes(s)) });
}
});
const probes = new Map();
const probe = (p) => {
let r = probes.get(p);
if (r === undefined) {
r = env.canonicalPath(p, signal).catch(() => undefined);
probes.set(p, r);
}
return r;
};
const parentOf = (view) => normalizeAbsPathLexically(`${view}/..`);
const writable = async (view, v) => {
const at = await probe(view);
if (at === undefined || at.ok)
return true;
if (at.error.code === "not_directory")
return false;
if (!v.child || at.error.code !== "not_found")
return true;
const dest = await probe(parentOf(view));
return dest === undefined || dest.ok || (dest.error.code !== "not_found" && dest.error.code !== "not_directory");
};
const changedBefore = (view, at) => writtenOnLineBefore(writtenBy, at, concurrent, parentOf(view));
const answer = async (view, key) => (await judge(view, { fs: env, ...(signal !== undefined ? { signal } : {}), ...(key ? { canonical: true } : {}) })) ?? "clear";
const asked = [...[...asKey].map(([view, v]) => [view, v, true]), ...[...asSpelling].filter(([view]) => !landingKeys.has(view)).map(([view, v]) => [view, v, false])];
const slotOf = (view, key) => `${key || landingKeys.has(view) ? "key" : "spelling"}\u0000${view}`;
const askable = new Map(asked.map(([view, v, key]) => [slotOf(view, key), { view, v, key }]));
const answers = new Map();
const answerAt = async (view, key) => {
const slot = slotOf(view, key);
const known = answers.get(slot);
if (known !== undefined)
return known;
const a = askable.get(slot);
const found = a === undefined || (!(await writable(a.view, a.v)) && !changedBefore(a.view, a.v.at)) ? "clear" : await answer(a.view, a.key);
answers.set(slot, found);
return found;
};
const textNamesRow = async (text) => {
for (const spelling of text) {
if (!isAbsoluteForFamily(pathFamilyOf({ root: spelling }), spelling))
continue;
if ((await judge(spelling, { fs: env, spellingOnly: true })) === "protected")
return true;
}
return false;
};
let unplaced = false;
let writeProtected = false;
let writeProtectedOnDisk = false;
for (const target of targets) {
let covered = false;
for (const [view, key] of target.views) {
const found = await answerAt(view, key);
if (found !== "clear")
unplaced = true;
if (found === "protected") {
covered = true;
break;
}
}
if (covered) {
if (await textNamesRow(target.text))
writeProtected = true;
else
writeProtectedOnDisk = true;
}
if (writeProtected && writeProtectedOnDisk)
break;
}
return { unplaced, writeProtected, writeProtectedOnDisk };
}
function commandSeatOf(seat) {
if (seat === "file_tool")
throw new TypeError(`shell read judgment: seat "file_tool" is the file tools' read station's — a shell command is judged on "full_shell", "readonly" or "rejudge"`);
return seat;
}
export function readStationMemberOf(call, members) {
return seatOf("fold.readStation", members, call);
}
const ADMISSION_MAX = 1024;
function withoutGrantOffer(v) {
if (v.disposition === "vouch" || v.readRootCandidate === undefined)
return v;
const { readRootCandidate: _offered, ...question } = v;
return question;
}
function shellCommandOf(args) {
const command = args?.command;
return typeof command === "string" ? command : undefined;
}
const ACCOUNT_PART_MAX = READ_DENY_SENTENCE_PART_MAX;
const CAUSE_SPELLING_MAX = 64;
const QUOTED_SEGMENT_MIN = 24;
const ACCOUNT_PATH_MAX = 44;
function unplacedReadReach(unchecked) {
return unchecked === "deny_list" ? "the read station cannot check what it reads against the read deny list" : "it may read files outside this session's folders";
}
const NOT_AUTO_ALLOWED_AFTER_REACH = "— it is not allowed through automatically";
const NOT_AUTO_ALLOWED_OPEN_STREAM = "— not auto-allowed";
const STREAM_PROGRAM_NAME_MAX = 24;
function fitAtWords(held, room) {
const cps = [...held];
if (cps.length <= room)
return held;
const keep = room - INLINE_TRUNCATION_MARK_CODEPOINTS;
if (keep <= 0)
return INLINE_TRUNCATION_MARK;
let at = 0;
for (let i = Math.min(keep, cps.length - 1); i > 0 && at === 0; i--)
if (/\s/.test(cps[i]))
at = i;
return `${cps.slice(0, at > 0 ? at : keep).join("").trimEnd()}${INLINE_TRUNCATION_MARK}`;
}
function fitCause(cause) {
return cause.replace(/^"([^"]*)"/, (_m, spelling) => `"${fitMiddle(spelling, CAUSE_SPELLING_MAX)}"`);
}
function faceOf(fold) {
return fold.witness?.read.candidate.face === "write" ? "write" : undefined;
}
function reenteredPrograms(fold) {
const names = [...new Set((fold.reentered ?? []).flatMap((s) => (s.verb !== undefined ? [s.verb.basename] : [])))];
const quoted = names.map((n) => `"${fitMiddle(n, CAUSE_SPELLING_MAX)}"`);
return quoted.length === 0 ? "the program it runs" : quoted.length === 1 ? quoted[0] : `${quoted.slice(0, -1).join(", ")} and ${quoted.at(-1)}`;
}
function findingAccount(fold, boundary, card) {
const w = fold.witness;
const face = faceOf(fold);
const { verb } = shellReadFaceWords(face);
const writes = w !== undefined && face === "write";
const roots = writes ? (boundary.writeRoots ?? []) : boundary.roots;
const fit = (s, max) => (card ? fitMiddle(s, max) : s);
const causeOf = (c) => (card ? fitCause(c) : c);
const allowed = fit(roots.length > 0 ? roots.join(", ") : "(none)", ACCOUNT_PART_MAX);
const reach = `, so ${unplacedReadReach(boundary.face === "open" ? "deny_list" : "roots")}`;
const unplaced = (account) => `${account}${reach} ${NOT_AUTO_ALLOWED_AFTER_REACH}`;
const pathOf = (p) => fit(p, ACCOUNT_PATH_MAX);
const quotedBefore = (text, rest) => {
const written = text.trim();
if (!card)
return `"${written}"${rest}`;
const room = Math.max(QUOTED_SEGMENT_MIN, PROBE_REASON_MAX - [...rest].length - [...reach].length - 2 - 2 * INLINE_TRUNCATION_MARK_CODEPOINTS);
const held = inlineUntrusted(written, Number.MAX_SAFE_INTEGER);
return [...held].length <= room ? `"${written}"${rest}` : `"${fitMiddle(held, room)}"${rest}`;
};
switch (fold.finding) {
case "outside_roots": {
const target = `"${pathOf(w?.read.target ?? "?")}"`;
const linked = w !== undefined && (w.read.hops?.length ?? 0) > 0 && w.read.target !== undefined && !w.read.spellings.includes(w.read.target) ? `"${pathOf(w.read.candidate.spelled)}" leads through a link to ${target}, which` : target;
return `${verb} outside the allowed directories for this session: ${linked} is not under ${allowed} ${NOT_AUTO_ALLOWED}`;
}
case "unestablishable":
case "unanswered":
if (w?.denyRowUnasked === true && w.read.cause !== undefined)
return `what this command ${verb} could not be checked against the deny list: ${causeOf(w.read.cause)} ${NOT_AUTO_ALLOWED_AFTER_REACH}`;
if (writes && boundary.writeRoots === undefined)
return `this command ${verb} "${fit(w.read.target ?? w.read.candidate.spelled, ACCOUNT_PART_MAX)}", and this session declares no directories it may write ${NOT_AUTO_ALLOWED}`;
if (writes)
return `where this command ${verb} could not be established${w.read.cause !== undefined ? `: ${causeOf(w.read.cause)}` : ""}, so it cannot be confirmed to write only inside the allowed directories for this session (${allowed}) ${NOT_AUTO_ALLOWED}`;
if (w?.read.cause !== undefined)
return unplaced(`where this command ${verb} could not be established: ${causeOf(w.read.cause)}`);
if (fold.cause !== undefined)
return unplaced(`where this command ${verb} could not be established: ${causeOf(fold.cause)}`);
if (fold.declined?.baseMove !== undefined)
return unplaced(quotedBefore(fold.declined.text, " moves the working directory somewhere this command's text does not settle"));
if (fold.declined?.unreadProgramText !== undefined)
return unplaced(quotedBefore(fold.declined.text, `: ${fold.declined.unreadProgramText}`));
if (fold.declined !== undefined)
return unplaced(`the text given to ${reenteredPrograms(fold)} — as an argument, on standard input, or in the file it names — runs as shell text this station does not parse`);
return unplaced(`where this command ${verb} could not be established`);
case "declined": {
const account = unplaced(fold.declined !== undefined ? declinedProgramReason(fold.declined.text, quotedBefore) : "the station could not read which program runs");
if (!card || boundary.face !== "open" || fold.declined?.declines.includes("stream_fed_operands") !== true || [...inlineUntrusted(account, Number.MAX_SAFE_INTEGER)].length <= PROBE_REASON_MAX)
return account;
const tail = `${reach} ${NOT_AUTO_ALLOWED_OPEN_STREAM}`;
const quoted = (text, rest) => {
const said = `${rest.slice(0, rest.length - rest.trimStart().length)}${inlineUntrusted(rest, Number.MAX_SAFE_INTEGER)}`;
return `"${fitAtWords(inlineUntrusted(text.trim(), Number.MAX_SAFE_INTEGER), PROBE_REASON_MAX - [...said].length - [...tail].length - 2)}"${said}`;
};
return `${declinedProgramReason(fold.declined.text, quoted, (name) => fitMiddle(name, STREAM_PROGRAM_NAME_MAX))}${tail}`;
}
case "identity_changed":
return `"${fit(w?.read.candidate.raw ?? "?", ACCOUNT_PART_MAX)}" resolves to "${fit(w?.read.target ?? "?", ACCOUNT_PART_MAX)}" now, not where it resolved when this call was judged`;
case "deny_hit":
case "target_unavailable":
case "none":
return "";
default: {
const exhaustive = fold.finding;
return exhaustive;
}
}
}
function outsidePathsOf(judged) {
const out = [];
for (const f of allFindings(judged)) {
if (f.kind === "outside_roots" && f.read.target !== undefined && !out.includes(f.read.target))
out.push(f.read.target);
}
return out;
}
function outsideFindingsAreRedirections(judged) {
const walk = (plan) => plan.segments.every((s) => {
const redirected = new Set(s.segment.redirects.flatMap((r) => (r.direction === "out" && r.target !== undefined ? [r.target.raw] : [])));
const slotWrites = new Set(s.segment.reads.filter((c) => c.provenance === "write_redirect_target").map((c) => c.raw));
for (const f of s.findings) {
if (f.kind !== "outside_roots")
continue;
if (f.read.written === undefined || f.read.candidate.provenance !== "write_redirect_target" || !redirected.has(f.read.candidate.raw) || slotWrites.has(f.read.candidate.raw))
return false;
}
return s.nested.every(walk);
});
return walk(judged);
}
function refusalOf(tool, fold, boundary, paths) {
if (fold.finding === "target_unavailable")
return { sentence: targetUnavailableSentence(tool, fold.cause ?? envErrorDetail(undefined)), details: targetUnavailableCard() };
const w = fold.witness;
if (fold.finding === "deny_hit" && w?.processPrivate !== undefined) {
const spelled = w.read.candidate.spelled;
const matched = w.processPrivate.matchedView;
const walk = !isProcSensitiveFile(matched);
const named = normalizeAbsPathLexically(spelled);
const via = (walk ? holdsProcSensitiveFile(named) : isProcSensitiveFile(named)) ? undefined : matched;
const at = `"${fitMiddle(spelled, READ_DENY_SENTENCE_PART_MAX)}" ${via !== undefined ? `(canonical target: "${fitMiddle(via, READ_DENY_SENTENCE_PART_MAX)}") ` : ""}`;
const what = walk ? `searching below ${at}is refused: that tree holds processes' private state under /proc` : `reading ${at}is refused: it is a process's private state under /proc`;
const sentence = `Error (${tool}): ${what} (a process directory's environ, cmdline, auxv, maps, mem or stat — its environment, command line, auxiliary vector, memory map, memory and status figures), and the file read tools refuse ${walk ? "those files" : "the same file"}. This holds in every permission mode, and no approval or setting lifts it. The command was not run, and nothing was read.`;
return { sentence, echoed: [{ kind: "path", value: spelled, ...(via !== undefined ? { canonical: via } : {}) }] };
}
if (fold.finding === "deny_hit" && w?.deny !== undefined) {
const target = w.read.target ?? w.deny.matchedView;
const write = w.deny.face === "write";
const under = w.deny.under === true;
const { sentence: core, echoed } = readDenyRefusal({ target, pattern: w.deny.pattern, matchedView: w.deny.matchedView, ...(write ? { face: "write" } : {}), ...(w.deny.readRow === true ? { readRow: true } : {}), ...(under ? { under: true } : {}), ...(w.deny.lookup !== undefined ? { lookup: w.deny.lookup, action: "removing" } : {}) });
const through = deniedThrough(w.read, boundary);
const sentence = `Error (${tool}): ${core} ${write ? writeDenyRefusalNote() : under ? DENY_UNDER_REFUSAL_NOTE : DENY_REFUSAL_NOTE}${through !== undefined ? ` ${DENIED_THROUGH_NOTE[through]}` : ""}`;
return { sentence, echoed, ...(write ? {} : { details: violationDetails({ code: "read_path_denied", message: sentence, target, pattern: w.deny.pattern }) }) };
}
const account = findingAccount(fold, boundary, false);
const sentence = `Error (${tool}): ${account}. ${BASH_READONLY_CONFINEMENT_NOTE}`;
return { sentence, details: findingDetails(fold.finding, paths) };
}
const DENIED_THROUGH_NOTE = {
home: "(The path was also checked with this environment's home directory standing in for ~ and HOME, because the command may " +
"change HOME first, or hand a literal ~ to a program that expands it itself.)",
floor: "(The command changes directory before this path in a way the engine cannot follow, so the path was also checked from " +
"where the command stood before that change; a bare cd counts as the home directory.)",
};
function deniedThrough(read, boundary) {
if (read.established === "unestablishable" && read.candidate.bases === "unmodelled")
return "floor";
const home = boundary.homeDir;
if (read.candidate.denyOnly === true && home !== undefined && withinAnyRoot([home], read.candidate.spelled) && /~|HOME/.test(read.candidate.raw))
return "home";
return undefined;
}
const DENY_OUTLET = "To get past it, the pattern has to be removed where it is set (this deployment's deny patterns, or a deny rule in the " +
"permission settings); the agent cannot lift it and no approval does.";
function writeDenyRefusalNote() {
const names = operandWriterNames();
return `The command was not run. Its output redirections and the files ${names.slice(0, -1).join(", ")} and ${names.at(-1)} write are checked against the write deny list. ${DENY_OUTLET}`;
}
const DENY_REFUSAL_NOTE = "The command was not run, and nothing was read. Paths a command names are checked against this list, as written and " +
"where they lead; a file it reaches without naming it, for example inside a folder it searches, is checked only where " +
`a deny rule covers that folder. ${DENY_OUTLET}`;
const DENY_UNDER_REFUSAL_NOTE = "The command was not run, and nothing was read. A search of a folder that holds none of the list's locations, or of files " +
`named one by one, is judged on its own. ${DENY_OUTLET}`;
function verdictOf(tool, seat, fold, judged, boundary) {
const redirectsOnly = fold.finding === "outside_roots" && fold.unestablished !== true && outsideFindingsAreRedirections(judged);
const disposition = decideShellRead(fold.finding, seat, { redirectsOnly, narrowedReadFace: fold.outsideOrUnresolved === true && boundary.face !== "open" });
if (disposition === "vouch")
return { disposition, finding: "none" };
const paths = outsidePathsOf(judged);
const unestablished = fold.unestablished === true ? { unestablished: true } : {};
const face = faceOf(fold);
const writes = face !== undefined ? { face } : {};
const by = fold.finding === "unanswered" ? { environmentSilent: true } : {};
if (disposition === "refuse") {
const r = refusalOf(tool, fold, boundary, paths);
return { disposition, finding: fold.finding, ...by, ...writes, sentence: r.sentence, ...(r.details !== undefined ? { details: r.details } : {}), ...(r.echoed !== undefined ? { echoed: r.echoed } : {}) };
}
const grant = fold.finding === "outside_roots" ? readRootGrantCandidateOf(judged, boundary) : undefined;
const containment = fold.finding === "outside_roots" || fold.finding === "unestablishable" || fold.finding === "unanswered";
return {
disposition,
finding: fold.finding,
...by,
...writes,
...unestablished,
sentence: findingAccount(fold, boundary, true),
...((disposition === "mandated" && containment) || (disposition === "ordinary" && fold.finding === "unestablishable") ? { details: findingDetails(fold.finding, paths) } : {}),
...(grant !== undefined ? { readRootCandidate: { dir: grant.dir, ...(grant.covers !== undefined ? { covers: grant.covers } : {}), clearsThisAsk: true } } : {}),
};
}
function withReadAsk(verdict, judged, fold) {
if (verdict.disposition === "refuse")
return verdict;
const ask = allFindings(judged).find((f) => f.ask !== undefined)?.ask;
const writeAsk = fold.writeAsk;
if (ask === undefined && writeAsk === undefined)
return verdict;
return {
...verdict,
...(ask !== undefined ? { askRule: ask.rule, ...(ask.policy === true ? { askRuleOfPolicy: true } : {}) } : {}),
...(writeAsk !== undefined ? { writeAskRule: writeAsk.rule, ...(writeAsk.policy === true ? { writeAskRuleOfPolicy: true } : {}) } : {}),
};
}
function declarationsOf(boundary, readers, cdPath, receivedEnvNames) {
const names = Array.isArray(receivedEnvNames) && receivedEnvNames.every((n) => typeof n === "string") ? { receivedEnvNames: receivedEnvNames } : {};
return { readers, cwd: boundary.cwd ?? boundary.roots[0] ?? "", roots: boundary.roots, cdPath, ...names, ...(boundary.homeDir !== undefined ? { homeDir: boundary.homeDir } : {}), ...(boundary.face !== undefined ? { face: boundary.face } : {}) };
}
function judgePlan(plan, established, boundary) {
return judgeEstablishedPlan(plan, established.reads, boundary, (n) => {
const nested = established.nested.get(n);
return nested === undefined ? { plan: n, segments: [], guards: stationGuards(boundary), writeGuards: writeFaceGuards(boundary) } : judgePlan(n, nested, boundary);
}, (n) => judgePlan(n, establishShellReadsLexically(n, boundary), boundary));
}
async function applyAlsoInside(judged, boundary) {
const alsoInside = boundary.alsoInside;
if (alsoInside === undefined)
return judged;
const outsideRead = (f) => f.kind === "outside_roots" && f.read.candidate.face !== "write" && f.read.target !== undefined;
const rescued = new Set();
for (const f of allFindings(judged)) {
if (!outsideRead(f) || rescued.has(f.read.target))
continue;
if (await alsoInside(f.read.target))
rescued.add(f.read.target);
}
if (rescued.size === 0)
return judged;
const rewrite = (j) => ({
plan: j.plan,
guards: j.guards,
writeGuards: j.writeGuards,
...(j.incomplete !== undefined ? { incomplete: j.incomplete } : {}),
segments: j.segments.map((s) => ({
segment: s.segment,
findings: s.findings.map((f) => (outsideRead(f) && rescued.has(f.read.target) ? { ...f, kind: "none", containment: "inside" } : f)),
nested: s.nested.map(rewrite),
printed: s.printed,
})),
});
return rewrite(judged);
}
export const SUBTREE_SEARCH_MS = 2_000;
export const SUBTREE_SEARCH_DIRS = 16_384;
async function searchSubtree(env, root, named, signal) {
const stop = new AbortController();
const timer = setTimeout(() => stop.abort(), SUBTREE_SEARCH_MS);
const onAbort = () => stop.abort();
signal?.addEventListener("abort", onAbort, { once: true });
const ended = new Promise((resolve) => stop.signal.addEventListener("abort", () => resolve("ended"), { once: true }));
const unfinished = (why) => ({ kind: "unfinished", why: signal?.aborted === true ? "the call was cancelled" : why });
const outOfTime = `the search ran past its ${SUBTREE_SEARCH_MS / 1000} s bound`;
try {
if (signal?.aborted === true)
return unfinished("");
const top = await Promise.race([env.fileInfo(root, stop.signal), ended]);
if (top === "ended")
return unfinished(outOfTime);
if (!top.ok)
return isAbsence(top.error.code) ? { kind: "clear" } : unfinished(`it could not be inspected (${top.error.code})`);
if (top.value.kind !== "directory")
return { kind: "clear" };
const queue = [root];
for (let listed = 0; queue.length > 0; listed++) {
if (listed >= SUBTREE_SEARCH_DIRS)
return unfinished(`it holds more than ${SUBTREE_SEARCH_DIRS} folders`);
const dir = queue.shift();
const entries = await Promise.race([env.listDir(dir, stop.signal), ended]);
if (entries === "ended")
return unfinished(outOfTime);
if (!entries.ok) {
if (isAbsence(entries.error.code))
continue;
return unfinished(`"${dir}" could not be listed (${entries.error.code})`);
}
for (const entry of entries.value) {
const at = `${dir.replace(/[\\/]+$/, "")}/${entry.name}`;
const pattern = named.ledBy(entry.name);
if (pattern !== null)
return { kind: "found", pattern, at };
if (entry.kind === "directory")
queue.push(at);
}
}
return { kind: "clear" };
}
catch {
return unfinished("the environment threw");
}
finally {
clearTimeout(timer);
signal?.removeEventListener("abort", onAbort);
}
}
function removesSubtree(f) {
const r = f.read;
return r.candidate.face === "write" && r.candidate.subtree === "removed" && r.written !== undefined && r.target !== undefined && (r.established === "canonical" || r.established === "expansion") && (f.kind === "none" || f.kind === "outside_roots");
}
async function applyRemovalSearch(judged, boundary, env, signal) {
const named = boundary.writeDenyNamed;
if (named === undefined || named.rows.length === 0)
return judged;
const searched = new Map();
const answered = new Map();
for (const f of allFindings(judged)) {
if (!removesSubtree(f))
continue;
const target = f.read.target;
let search = searched.get(target);
if (search === undefined)
searched.set(target, (search = searchSubtree(env, target, named, signal)));
const found = await search;
if (found.kind === "clear")
continue;
if (found.kind === "unfinished") {
const cause = `the folders below "${target}" could not all be searched for a name the deny rows ${named.rows.map((p) => `"${p}"`).join(", ")} start with: ${found.why}`;
answered.set(f, { read: { ...f.read, cause }, kind: "unanswered", denyRowUnasked: true, containment: f.containment });
continue;
}
const readRow = boundary.writeDenyGuardsReads?.(found.pattern) === true ? { readRow: true } : {};
answered.set(f, { ...f, kind: "deny_hit", deny: { pattern: found.pattern, matchedView: normalizeAbsPathLexically(target), face: "write", under: true, lookup: { found: found.at }, ...readRow } });
}
if (answered.size === 0)
return judged;
const rewrite = (j) => ({ ...j, segments: j.segments.map((s) => ({ ...s, findings: s.findings.map((f) => answered.get(f) ?? f), nested: s.nested.map(rewrite) })) });
return rewrite(judged);
}
const holdsBracket = (c) => c.bracket === true;
const bracketCause = (spelled) => `"${spelled}" holds a bracket expression, which the shell matches by its own collation and options, so it may reach names this station does not list`;
function bracketWordsUnvouched(tool, seat, run, verdict) {
if (readStationAnswer(verdict, { toolName: tool }).kind !== "vouch")
return verdict;
const unread = new Map();
for (const f of allFindings(run.judged)) {
if (f.kind === "none" && holdsBracket(f.read.candidate))
unread.set(f, { ...f, kind: "unestablishable", read: { ...f.read, cause: bracketCause(f.read.candidate.spelled) } });
}
if (unread.size === 0)
return verdict;
const rewrite = (j) => ({ ...j, segments: j.segments.map((s) => ({ ...s, findings: s.findings.map((f) => unread.get(f) ?? f), nested: s.nested.map(rewrite) })) });
const judged = rewrite(run.judged);
const fold = foldShellReadFindings(judged);
if (fold.finding === "none")
return verdict;
const question = withReadAsk(verdictOf(tool, seat, fold, judged, run.boundary), judged, fold);
if (question.disposition === "refuse")
return question;
const { disposition: _vouch, finding: _none, ...facts } = verdict;
return { ...facts, ...question };
}
async function runShellReadStation(tool, plan, declared, seat, establisher, env, signal) {
const door = observeEnvironment(env);
const established = await establisher.establish(plan, declared, signal, door);
const { writeAskRowsLed, ...declaredRows } = declared;
let boundary = { ...declaredRows, roots: established.roots };
let onPlan = await applyRemovalSearch(await applyAlsoInside(judgePlan(plan, established, boundary), boundary), boundary, env, signal);
if (writeAskRowsLed !== undefined && writesAnything(onPlan) && foldShellReadFindings(onPlan).finding !== "deny_hit") {
const led = await writeAskRowsLed();
boundary = { ...boundary, writeAskRows: led };
onPlan = withWriteAskRows(onPlan, led);
}
const judgedNow = () => {
const unfinished = door.incomplete();
return unfinished.length > 0 ? { ...onPlan, incomplete: unfinished } : onPlan;
};
let judged = judgedNow();
let judgedVerdict = verdictOf(tool, seat, foldShellReadFindings(judged), judged, boundary);
const guarded = judgedVerdict.disposition === "refuse" ? { unplaced: false, writeProtected: false, writeProtectedOnDisk: false } : await writeGuardsOf(judged, boundary, door.fs, signal);
judged = judgedNow();
const fold = foldShellReadFindings(judged);
judgedVerdict = verdictOf(tool, seat, fold, judged, boundary);
const unplaced = unplacedOptionsOf(judged);
const placed = judgedVerdict.finding !== "unanswered" && judgedVerdict.finding !== "target_unavailable" && writesPlacedOf(judged, boundary);
const unresolved = judgedVerdict.disposition !== "refuse" && runOrderOf(judged).runs.some((s) => s.findings.some((f) => f.read.written !== undefined && f.read.unresolved === true));
const facts = {
...withReadAsk(judgedVerdict, judged, fold),
...(guarded.writeProtected ? { writeProtected: true } : {}),
...(guarded.writeProtectedOnDisk ? { writeProtectedOnDisk: true } : {}),
...(unresolved ? { targetUnresolved: true } : {}),
};
const verdict = placed && !guarded.unplaced ? { ...facts, writesPlaced: true } : unplaced !== undefined ? { ...facts, unplacedOptions: unplaced } : facts;
return { plan, established, judged, boundary, verdict };
}
export async function judgeShellRead(input) {
assertNoRetiredShellReadBoundaryKeys(input.boundary);
const readers = input.readers ?? new Set(bashClassifyDefaultAllow());
const reading = await readModelShell(input.env);
const shell = reading.kind === "mounted" ? reading.shell : "unknown";
const plan = planShellReads(shell, input.command, declarationsOf(input.boundary, readers, input.env.cdPath, input.env.receivedEnvNames));
const tool = input.tool ?? "Bash";
const seat = commandSeatOf(input.seat);
const run = await runShellReadStation(tool, plan, input.boundary, seat, createShellReadEstablisher(input.env, input.boundary.roots, { homeViews: homeViewsAt(input.env, input.readDenyHomes === undefined ? declaredReadDenyHomes(input.env) : checkedReadDenyHomes(input.readDenyHomes)) }), input.env, input.signal);
const verdict = bracketWordsUnvouched(tool, seat, run, run.verdict);
const offer = normalizeReadRootCandidate(verdict.readRootCandidate);
return {
plan: run.plan,
establishment: allFindings(run.judged).map((f) => f.read),
verdict,
...(offer !== undefined ? { offer } : {}),
};
}
export function judgeShellReadLexically(shell, command, boundary, seat, opts) {
assertNoRetiredShellReadBoundaryKeys(boundary);
commandSeatOf(seat);
const readers = opts?.readers ?? new Set(bashClassifyDefaultAllow());
const plan = planShellReads(shell, command, declarationsOf(boundary, readers, []));
const established = establishShellReadsLexically(plan, boundary);
const judged = judgePlan(plan, established, boundary);
const fold = foldShellReadFindings(judged);
return withReadAsk(verdictOf(opts?.tool ?? "Bash", seat, fold, judged, boundary), judged, fold);
}
export function createShellReadStation(opts) {
const readers = opts.readers ?? new Set(bashClassifyDefaultAllow());
const establishers = new Map();
const establisherFor = (roots) => {
const key = roots.join("\0");
let e = establishers.get(key);
if (e === undefined) {
e = createShellReadEstablisher(opts.env, roots, { rootsCanonical: opts.rootsCanonical === true, ...(opts.homeViews !== undefined ? { homeViews: opts.homeViews } : {}) });
establishers.set(key, e);
}
return e;
};
const admissions = new Map();
const remember = (toolCallId, a) => {
admissions.delete(toolCallId);
if (admissions.size >= ADMISSION_MAX) {
const oldest = admissions.keys().next().value;
if (oldest !== undefined)
admissions.delete(oldest);
}
admissions.set(toolCallId, a);
};
const memberOf = (call) => readStationMemberOf(call, opts.tools)?.name;
const unansweredOver = (toolName, seat, cause, boundary, silence, writes = () => true) => {
if (boundary === undefined || (boundary !== "unread" && !(anyFaceGuards(boundary) || boundary.writeTargetJudge !== undefined || (boundary.writeAskRows !== undefined && writes()))))
return { disposition: "vouch", finding: "none" };
const disposition = decideShellRead("unanswered", seat);
const account = `${cause}, so where this command reads could not be established ${NOT_AUTO_ALLOWED}`;
const details = unestablishedDetails();
if (disposition === "refuse")
return { disposition, finding: "unanswered", ...silence, sentence: `Error (${toolName}): ${account}. ${BASH_READONLY_CONFINEMENT_NOTE}`, details };
return { disposition, finding: "unanswered", ...silence, sentence: account, details };
};
const check = {
judge(call, args, cwd, signal, callOpts) {
const member = memberOf(call);
if (member === undefined)
return null;
const command = shellCommandOf(args);
if (command === undefined)
return null;
const boundary = opts.boundaryOf(member, cwd, callOpts.toolCallId);
if (boundary === undefined)
return null;
const seat = callOpts.seat ?? opts.seatOf(member);
return (async () => {
const plan = planShellReads(startedShellOfCall(call), command, declarationsOf(boundary, readers, opts.env.cdPath, opts.env.receivedEnvNames));
const run = await runShellReadStation(call.toolName, plan, boundary, seat, establisherFor(boundary.roots), opts.env, signal);
if (run.verdict.disposition !== "refuse" && callOpts.toolCallId !== undefined)
remember(callOpts.toolCallId, { toolName: member, boundary: run.boundary, established: run.established, command });
const verdict = opts.offersReadRootGrant === false ? withoutGrantOffer(run.verdict) : run.verdict;
const answered = (() => {
if (boundary.unreadPartitions !== true)
return verdict;
if (verdict.disposition !== "vouch")
return { ...verdict, rowsUnread: true };
const unread = unansweredOver(call.toolName, seat, "the rules this check stands on could not all be read", boundary, { rowsUnread: true });
if (unread.disposition === "refuse")
return unread;
return {
...unread,
...(verdict.askRule !== undefined ? { askRule: verdict.askRule, ...(verdict.askRuleOfPolicy === true ? { askRuleOfPolicy: true } : {}) } : {}),
...(verdict.writeAskRule !== undefined ? { writeAskRule: verdict.writeAskRule, ...(verdict.writeAskRuleOfPolicy === true ? { writeAskRuleOfPolicy: true } : {}) } : {}),
};
})();
return bracketWordsUnvouched(call.toolName, seat, run, answered);
})();
},
...(opts.writeAskRowsUncounted !== undefined ? { writeAskRowsUncounted: opts.writeAskRowsUncounted } : {}),
unanswered(call, cause, args) {
const member = memberOf(call) ?? call.toolName;
const boundary = (() => {
try {
return opts.boundaryOf(member, undefined, undefined);
}
catch {
return "unread";
}
})();
const rowsUnread = boundary === "unread" || boundary?.unreadPartitions === true ? { rowsUnread: true } : {};
const writes = () => args === undefined || !readOnlyShellCall(startedShellOfCall(call), args, undefined).readOnly;
return unansweredOver(call.toolName, opts.seatOf(member), cause, boundary, { environmentSilent: true, ...rowsUnread }, writes);
},
};
const admit = async (toolName, toolCallId, command, signal) => {
if (toolCallId === undefined)
return undefined;
const a = admissions.get(toolCallId);
if (a === undefined)
return undefined;
admissions.delete(toolCallId);
const refused = (r, echoed) => {
opts.onAdmissionRefused?.(toolCallId, echoed);
return r;
};
if (a.toolName !== toolName || a.command !== command) {
return refused(errorResult(`Error (${toolName}): the command that would run is not the one the read station judged for this call — refused before the spawn; re-submit it as a fresh call.`, containmentDetails([])));
}
const establisher = establisherFor(a.boundary.roots);
const { changed } = await establisher.reestablish(a.established, a.boundary, signal);
if (changed.length === 0)
return undefined;
const again = await establisher.establish(a.established.plan, a.boundary, signal);
const judged = await applyAlsoInside(judgePlan(a.established.plan, again, a.boundary), a.boundary);
const fold = foldShellReadFindings(judged);
if (fold.finding === "deny_hit") {
const r = refusalOf(toolName, fold, a.boundary, outsidePathsOf(judged));
return refused(errorResult(r.sentence, r.details), r.echoed);
}
const moved = changed[0];
const identity = { finding: "identity_changed", witness: { read: moved, kind: "none", containment: "unknown" } };
const r = refusalOf(toolName, identity, a.boundary, []);
return refused(errorResult(r.sentence, containmentDetails(changed.map((c) => c.target).filter((t) => t !== undefined))));
};
const landings = (toolCallId) => {
const a = admissions.get(toolCallId);
return a !== undefined ? readLandingsOf(a.established) : undefined;
};
return { check, admit, landings };
}