@sema-agent/core
Version:
Stateless, task-oriented AI agent core
215 lines (214 loc) • 10.8 kB
JavaScript
import { posix, win32 } from "node:path";
import { isWithin } from "./session-rule-policy.js";
import { isWinFormPath, normalizeAbsPathLexically } from "../../tools/fs/safety.js";
import { validatePath } from "../effective-path-target.js";
import { inlineUntrusted } from "../untrusted-text.js";
import { envErrorDetail } from "../../tools/fs/env-error-detail.js";
import { readObjectAt } from "../../tools/fs/bound-open.js";
export const PLAN_FILE_INVALID_CODE = "config.plan_file_invalid";
export function planFileInvalid(value, why) {
let shown;
try {
shown = JSON.stringify(value) ?? String(value);
}
catch {
shown = typeof value;
}
const e = new Error(`TaskSpec.planFile ${shown} ${why} — the plan file must be the absolute path, in lexical normal form, of a regular file (or of a file not yet written) whose directory exists, on a leg whose file tools can write; ` +
`a plan file the gates cannot hold as declared would teach the model a file nobody can write, so the run is refused rather than started without it.`);
e.code = PLAN_FILE_INVALID_CODE;
e.detail = { planFile: value, reason: why };
return e;
}
export function checkedPlanFileShape(value) {
if (value === undefined)
return undefined;
if (typeof value !== "string")
throw planFileInvalid(value, `is a ${value === null ? "null" : typeof value}, not a string`);
if (value.length === 0)
throw planFileInvalid(value, "is an empty string");
if (validatePath(value, { intent: "validate-coordinate" }) === undefined)
throw planFileInvalid(value, "is not an absolute path");
if (normalizeAbsPathLexically(value) !== value)
throw planFileInvalid(value, `is not in lexical normal form (it reads as ${normalizeAbsPathLexically(value)})`);
if (inlineUntrusted(value, PLAN_PATH_MAX) !== value)
throw planFileInvalid(value, `cannot be told to the model verbatim (a control character, a run of whitespace, an envelope marker, or more than ${PLAN_PATH_MAX} characters)`);
return value;
}
export const PLAN_PATH_MAX = 4096;
export function planFileShown(path) {
return inlineUntrusted(path, PLAN_PATH_MAX);
}
export const PLAN_FILE_MAX_BYTES = 1024 * 1024;
export function swallowedFenceRoot(domainCanonical, fenceRootsCanonical) {
for (const root of fenceRootsCanonical) {
if (root && isWithin(domainCanonical, root))
return root;
}
return undefined;
}
export class AdvertisedWritableDirs {
env;
onSkipped;
declaredRootSpellings;
admitted = [];
heldFromCommands = new Set();
verdicts = new Map();
fenceRoots;
declaredRootsResolved;
declaredRootAnswers = new Map();
constructor(env, onSkipped, taskRootCanonical, declaredRootSpellings = []) {
this.env = env;
this.onSkipped = onSkipped;
this.declaredRootSpellings = declaredRootSpellings;
this.fenceRoots = [taskRootCanonical];
}
declareFenceRoot(canonical) {
if (canonical && !this.fenceRoots.includes(canonical))
this.fenceRoots.push(canonical);
}
async canonicalizeDeclaredRoot(spelled) {
const memo = this.declaredRootAnswers.get(spelled);
if (memo !== undefined)
return memo;
const c = await this.env.canonicalPath(spelled);
const first = this.declaredRootAnswers.get(spelled);
if (first !== undefined)
return first;
this.declaredRootAnswers.set(spelled, c);
if (c.ok)
this.declareFenceRoot(c.value);
return c;
}
resolveDeclaredRoots() {
this.declaredRootsResolved ??= (async () => {
for (const spelled of this.declaredRootSpellings) {
if (!spelled || !spelled.trim())
continue;
await this.canonicalizeDeclaredRoot(spelled);
}
})();
return this.declaredRootsResolved;
}
get roots() {
return this.admitted;
}
get commandRoots() {
return this.admitted.filter((r) => !this.heldFromCommands.has(r));
}
get planFile() {
return this.admittedPlanFile;
}
admittedPlanFile;
async admitPlanFile(spelled) {
const win = isWinFormPath(spelled);
const pathOps = win ? win32 : posix;
const parent = pathOps.dirname(spelled);
const name = pathOps.basename(spelled);
if (!name || parent === spelled)
throw planFileInvalid(spelled, "names no file below a directory");
const leaf = await this.env.fileInfo(spelled);
if (leaf.ok && leaf.value.kind !== "file")
throw planFileInvalid(spelled, leaf.value.kind === "symlink" ? "is a symbolic link (the plan file must be the file itself, not a link to one)" : `is a ${leaf.value.kind}, not a file`);
if (!leaf.ok && leaf.error.code !== "not_found")
throw planFileInvalid(spelled, `could not be examined (${leaf.error.code}: ${envErrorDetail(leaf.error.message)})`);
const parentCanonical = await this.env.canonicalPath(parent);
if (!parentCanonical.ok)
throw planFileInvalid(spelled, `has a directory that does not resolve (${parentCanonical.error.code}: ${envErrorDetail(parentCanonical.error.message)}) — the host creates the plan file's directory before the run`);
const parentInfo = await this.env.fileInfo(parentCanonical.value);
if (!parentInfo.ok || parentInfo.value.kind !== "directory")
throw planFileInvalid(spelled, `has a parent ${parentCanonical.value} that is not a directory`);
const own = leaf.ok ? await this.env.canonicalPath(spelled) : undefined;
if (own !== undefined && !own.ok)
throw planFileInvalid(spelled, `could not be resolved (${own.error.code}: ${envErrorDetail(own.error.message)})`);
const joined = own?.ok === true ? own : await this.env.joinPath([parentCanonical.value, name]);
if (!joined.ok)
throw planFileInvalid(spelled, `could not be joined below its directory (${joined.error.code}: ${envErrorDetail(joined.error.message)})`);
const key = joined.value;
await this.resolveDeclaredRoots();
const swallowed = swallowedFenceRoot(key, [...this.fenceRoots, ...this.admitted]);
if (swallowed !== undefined && swallowed !== key)
throw planFileInvalid(spelled, `resolves to ${key}, which holds the root ${swallowed}`);
if (!this.admitted.includes(key))
this.admitted.push(key);
this.admittedPlanFile = Object.freeze({ spelled, key });
this.verdicts.set("plan", "admitted");
return key;
}
async readPlanFile(signal) {
const planFile = this.admittedPlanFile;
if (planFile === undefined)
return { ok: false, reason: "this run admitted no plan file" };
const canonical = await this.env.canonicalPath(planFile.key, signal);
if (!canonical.ok)
return canonical.error.code === "not_found" ? { ok: true, text: undefined } : { ok: false, reason: `${canonical.error.code}: ${envErrorDetail(canonical.error.message)}` };
if (canonical.value !== planFile.key)
return { ok: false, reason: `it now resolves to ${canonical.value} (a link replaced it or one of its directories), which is not read through` };
const stillTheKey = async (s) => {
const now = await this.env.canonicalPath(planFile.key, s);
return now.ok && now.value === planFile.key;
};
const opened = await readObjectAt(this.env, planFile.key, stillTheKey, signal);
if (!opened.ok)
return opened.error.code === "not_found" ? { ok: true, text: undefined } : { ok: false, reason: `${opened.error.code}: ${envErrorDetail(opened.error.message)}` };
const object = opened.value;
let bytes;
try {
if (object.kind !== "file")
return { ok: false, reason: `it is now a ${object.kind}` };
const read = await object.readBytes(PLAN_FILE_MAX_BYTES, signal);
if (!read.ok)
return read.error.code === "not_found" ? { ok: true, text: undefined } : { ok: false, reason: `${read.error.code}: ${envErrorDetail(read.error.message)}` };
bytes = read.value;
}
finally {
await object.close();
}
const text = new TextDecoder("utf-8").decode(bytes);
return { ok: true, text: text.trim() === "" ? undefined : text };
}
verdictOf(advertiser) {
return this.verdicts.get(advertiser) ?? "not-asked";
}
async admit(dir) {
const key = await this.judge(dir);
this.verdicts.set(dir.advertiser, key !== undefined ? "admitted" : "skipped");
if (key !== undefined && dir.writesRefusedByOwnGate === true)
this.heldFromCommands.add(key);
return key !== undefined;
}
async judge(dir) {
if (!dir.path || !dir.path.trim()) {
this.onSkipped(dir, "empty path");
return undefined;
}
let c = await this.env.canonicalPath(dir.path);
if (!c.ok && c.error.code === "not_found" && dir.materializeMarker !== undefined) {
const marker = await this.env.joinPath([dir.path, dir.materializeMarker]);
const exclusiveCreate = this.env.writeFileExclusive?.bind(this.env);
if (marker.ok && exclusiveCreate) {
const w = await exclusiveCreate(marker.value, "");
if (w.ok || w.error.code === "already_exists")
c = await this.env.canonicalPath(dir.path);
}
}
if (!c.ok) {
this.onSkipped(dir, `${c.error.code}: ${c.error.message}`);
return undefined;
}
if (dir.expectCanonical !== undefined && c.value !== dir.expectCanonical) {
this.onSkipped(dir, `the execution environment resolves it to ${c.value} while the advertiser's gates key on ${dir.expectCanonical} — a fence hole those gates cannot see is not opened`);
return undefined;
}
if (this.admitted.includes(c.value))
return c.value;
await this.resolveDeclaredRoots();
const swallowed = swallowedFenceRoot(c.value, [...this.fenceRoots, ...this.admitted]);
if (swallowed !== undefined) {
this.onSkipped(dir, `it resolves to ${c.value}, which covers ${swallowed === this.fenceRoots[0] ? "task root" : "root"} ${swallowed} — a directory that holds a root is not a hole in the fence but the whole of it, and admitting it would auto-approve every write under that root`);
return undefined;
}
this.admitted.push(c.value);
return c.value;
}
}