UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

431 lines (430 loc) • 24.2 kB
import { hasWin32AliasedComponent, holdsProcSensitiveFile, isProcSensitiveFile, normalizeAbsPathLexically, withinAnyRoot } from "./safety.js"; import { globInWord } from "./bash-readonly-classifier.js"; import { removesTarget } from "./removal-actions.js"; import { pipedRemovalStarts } from "./piped-removal.js"; import { readOfText } from "./shell-read-word.js"; import { passesUnasked } from "./shell-read-device.js"; import { skipsRootsContainment } from "./containment-face.js"; import { judgeRuleRows } from "./read-deny.js"; export const SHELL_READ_FINDINGS = Object.freeze(["deny_hit", "outside_roots", "unestablishable", "declined", "identity_changed", "unanswered", "target_unavailable", "none"]); export const SHELL_READ_SEATS = Object.freeze(["full_shell", "readonly", "rejudge", "file_tool"]); export const SHELL_READ_FINDING_RANK = { identity_changed: 7, deny_hit: 6, target_unavailable: 5, unanswered: 4, outside_roots: 3, unestablishable: 2, declined: 1, none: 0, }; export function dispositionOfCell(cell, context = {}) { if (typeof cell === "string") return cell; if (context.redirectsOnly === true && cell.redirect !== undefined) return cell.redirect; return context.narrowedReadFace !== false ? cell.narrowed : cell.open; } export const SHELL_READ_DECISION = { deny_hit: { full_shell: "refuse", readonly: "refuse", rejudge: "refuse", file_tool: "refuse" }, outside_roots: { full_shell: { narrowed: "mandated", open: "mandated", redirect: "ordinary" }, readonly: "refuse", rejudge: "refuse", file_tool: "ordinary" }, unestablishable: { full_shell: { narrowed: "mandated", open: "ordinary" }, readonly: "refuse", rejudge: "refuse", file_tool: "refuse" }, declined: { full_shell: "ordinary", readonly: "refuse", rejudge: "refuse", file_tool: "refuse" }, identity_changed: { full_shell: "refuse", readonly: "refuse", rejudge: "refuse", file_tool: "refuse" }, unanswered: { full_shell: "mandated", readonly: "refuse", rejudge: "refuse", file_tool: "refuse" }, target_unavailable: { full_shell: "refuse", readonly: "refuse", rejudge: "refuse", file_tool: "refuse" }, none: { full_shell: "vouch", readonly: "vouch", rejudge: "vouch", file_tool: "vouch" }, }; export function decideShellRead(finding, seat, context = {}) { const row = Object.hasOwn(SHELL_READ_DECISION, finding) ? SHELL_READ_DECISION[finding] : undefined; const cell = row !== undefined && Object.hasOwn(row, seat) ? row[seat] : undefined; if (cell === undefined) { throw new Error(`shell read decision: no cell for finding ${JSON.stringify(finding)} on seat ${JSON.stringify(seat)} — the seats are ${SHELL_READ_SEATS.map((w) => JSON.stringify(w)).join(", ")} (a seat names the face a read is judged on)`); } return dispositionOfCell(cell, context); } export function dispositionsOfRow(finding) { const row = Object.hasOwn(SHELL_READ_DECISION, finding) ? SHELL_READ_DECISION[finding] : undefined; return new Set(Object.values(row ?? {}).flatMap((cell) => (typeof cell === "string" ? [cell] : [cell.narrowed, cell.open, ...(cell.redirect !== undefined ? [cell.redirect] : [])]))); } export function judgeRead(read, boundary) { const writeTarget = read.candidate.face === "write"; if (!writeTarget) { const walks = read.candidate.provenance === "traversal_root"; for (const view of read.target !== undefined ? [read.target] : read.spellings) { const folded = normalizeAbsPathLexically(view); if (isProcSensitiveFile(folded) || (walks && holdsProcSensitiveFile(folded))) return { read, kind: "deny_hit", processPrivate: { matchedView: folded }, containment: containmentOf(read, boundary) }; } } const deny = writeTarget ? boundary.writeDenyMatch : boundary.denyMatch; if (deny !== undefined) { const views = [...(read.target !== undefined ? [read.target] : []), ...read.spellings, ...(read.ancestorViews ?? []), ...(read.hops ?? [])]; for (const view of views) { const folded = normalizeAbsPathLexically(view); const pattern = writeTarget ? boundary.writeDenyMatch(folded) : boundary.denyMatch(folded); if (pattern !== null) return { read, kind: "deny_hit", deny: { pattern, matchedView: folded, ...(writeTarget ? { face: "write", ...(boundary.writeDenyGuardsReads?.(pattern) === true ? { readRow: true } : {}) } : {}) }, containment: writeTarget ? writeContainmentOf(read, boundary) : containmentOf(read, boundary) }; } const checksUnder = writeTarget ? read.candidate.subtree !== undefined && read.written !== undefined : read.candidate.provenance === "traversal_root"; const denyUnder = writeTarget ? boundary.writeDenyUnder : boundary.denyUnder; if (checksUnder && denyUnder !== undefined) { let unplaced; for (const view of [...(read.target !== undefined ? [read.target] : []), ...read.spellings, ...(read.hops ?? [])]) { const folded = normalizeAbsPathLexically(view); const under = denyUnder(folded); if (typeof under === "string") { return { read, kind: "deny_hit", deny: { pattern: under, matchedView: folded, under: true, ...(writeTarget ? { face: "write", ...(boundary.writeDenyGuardsReads?.(under) === true ? { readRow: true } : {}) } : {}), }, containment: writeTarget ? writeContainmentOf(read, boundary) : containmentOf(read, boundary), }; } if (under !== null && typeof under === "object") unplaced ??= under.unplaced; } if (unplaced !== undefined) { const cause = `the home-anchored deny row "${unplaced}" cannot be placed (no home directory is known for this environment), so "${read.target ?? read.candidate.spelled}" may hold it`; return { read: { ...read, cause }, kind: "unanswered", denyRowUnasked: true, containment: writeTarget ? writeContainmentOf(read, boundary) : containmentOf(read, boundary) }; } } } if (read.candidate.floorPastBound === true && deny !== undefined) { const cause = `the spellings "${read.candidate.raw}" may take pass the bound the station reads, so it may name a value no deny row was asked about`; return { read: { ...read, cause }, kind: "unanswered", denyRowUnasked: true, containment: writeTarget ? writeContainmentOf(read, boundary) : containmentOf(read, boundary) }; } if (writeTarget) { const written = judgeWrite(read, boundary); const writeAsk = writeAskOf(read, boundary); return writeAsk !== undefined ? { ...written, writeAsk } : written; } const containment = containmentOf(read, boundary); const provenance = read.candidate.provenance; const device = passesUnasked(read.candidate); const opened = !device && provenance !== "env_assignment" && !(provenance === "program_path" && read.candidate.expands !== "unresolvable"); const asked = readAskOf(read, boundary); const kept = (f) => (asked !== undefined ? { ...f, ask: asked } : f); if (read.candidate.denyOnly === true) return kept({ read, kind: "none", containment }); if (device) return kept({ read, kind: "none", containment: "open" }); if (!opened) return kept({ read, kind: "none", containment }); if (read.established === "unestablishable") return kept({ read, kind: "unestablishable", containment }); if (containment === "outside" && personAllowAdmits(read, boundary)) return kept({ read, kind: "none", containment: "inside" }); return kept({ read, kind: containment === "outside" ? "outside_roots" : "none", containment }); } function readViewsOf(read) { const views = []; const add = (path, kind) => { const folded = normalizeAbsPathLexically(path); if (!views.some((v) => v.path === folded)) views.push({ path: folded, kind }); }; if (read.target !== undefined) add(read.target, read.established === "canonical" || read.established === "expansion" ? "canonical" : "lexical"); for (const s of read.spellings) add(s, "lexical"); for (const s of read.ancestorViews ?? []) add(s, "lexical"); for (const h of read.hops ?? []) add(h, "hop"); return views; } function readAskOf(read, boundary) { const rows = boundary.readRuleRows?.ask; if (rows === undefined || rows.length === 0) return undefined; const row = judgeRuleRows(rows, { views: readViewsOf(read) }, "tighten")?.row; return row === undefined ? undefined : { rule: row.rule, ...(row.policy === true ? { policy: true } : {}) }; } function writeAskOf(read, boundary) { const rows = boundary.writeAskRows; if (rows === undefined || rows.length === 0 || read.written === undefined) return undefined; const subtreeViews = read.candidate.subtree === undefined ? [] : [...(read.target !== undefined ? [read.target] : []), ...read.spellings, ...(read.hops ?? [])].map((v) => normalizeAbsPathLexically(v)); const row = judgeRuleRows(rows, { views: readViewsOf(read) }, "tighten")?.row ?? rows.find((r) => subtreeViews.some((view) => ruleRowAtOrBelow(r, view))); return row === undefined ? undefined : { rule: row.rule, ...(row.policy === true ? { policy: true } : {}) }; } function ruleRowAtOrBelow(row, at) { const start = row.reachShape?.at ?? row.head; if (start === undefined) return row.reaches(at); const startFolded = normalizeAbsPathLexically(start); if (withinAnyRoot([at], startFolded)) return true; if (!withinAnyRoot([startFolded], at)) return false; const globs = row.reachShape?.globs; if (globs === undefined) return true; const base = at.replace(/[\\/]+$/, ""); for (let k = 0; k <= globs.length; k++) { const rest = globs.slice(k).filter((g) => g !== "**").map((g) => g.replaceAll("*", "x")); if (row.reaches(rest.length === 0 ? at : `${base}/${rest.join("/")}`)) return true; } return false; } function personAllowAdmits(read, boundary) { const rows = boundary.readRuleRows?.allow; if (rows === undefined || rows.length === 0 || read.target === undefined || read.unresolved === true || read.candidate.provenance === "traversal_root") return false; if (read.established !== "canonical" && read.established !== "expansion") return false; const hit = judgeRuleRows(rows, { views: readViewsOf(read) }, "allow"); return hit !== undefined && hit.unreadable === undefined; } export function denyRowAtOrBelow(read, boundary, carriesContent) { const views = [...(read.target !== undefined ? [read.target] : []), ...read.spellings]; if (boundary.writeDenyAtOrBelow !== undefined) { if (views.some((view) => boundary.writeDenyAtOrBelow(normalizeAbsPathLexically(view)) !== null)) return true; } else if (boundary.writeDenyMatch !== undefined) { return true; } if (!carriesContent) return false; const atOrBelow = boundary.denyAtOrBelow; if (atOrBelow === undefined) return false; return views.some((view) => atOrBelow(normalizeAbsPathLexically(view)) !== null); } export function denyFloorShadowsOf(candidates) { return candidates.flatMap((c) => (c.floorSpelled === undefined ? [] : [{ spelled: c.floorSpelled, raw: c.raw, provenance: c.provenance, expands: globInWord(readOfText(c.raw).word) ? "glob" : false, bases: [], denyOnly: true, ...(c.face !== undefined ? { face: c.face } : {}), ...(c.face === "write" && c.expands === "unresolvable" && !/[$`]/.test(c.floorSpelled) ? { twin: true } : {}) }])); } function containmentOf(read, boundary) { if (boundary.face === "open") return "open"; if (read.target === undefined) return "unknown"; return withinAnyRoot(boundary.roots, read.target) ? "inside" : "outside"; } function writeContainmentOf(read, boundary) { if (read.written === undefined || (read.candidate.denyOnly === true && (read.candidate.twin !== true || read.candidate.expands !== false)) || passesUnasked(read.candidate)) return "open"; const roots = boundary.writeRoots; if (roots === undefined || read.target === undefined) return "unknown"; return withinAnyRoot(roots, read.target) ? "inside" : "outside"; } function judgeWrite(read, boundary) { const containment = writeContainmentOf(read, boundary); if (containment === "open") return { read, kind: "none", containment }; if (read.candidate.twin === true) return { read, kind: containment === "outside" && !skipsRootsContainment(boundary.writeFace) ? "outside_roots" : "none", containment }; if (read.established === "unestablishable" || boundary.writeRoots === undefined) return { read, kind: "unestablishable", containment }; return { read, kind: containment === "outside" && !skipsRootsContainment(boundary.writeFace) ? "outside_roots" : "none", containment }; } export function stationGuards(boundary) { return boundary.face !== "open" || boundary.denyMatch !== undefined || boundary.unreadPartitions === true || (boundary.readRuleRows?.ask.length ?? 0) > 0; } export function writeFaceGuards(boundary) { return !skipsRootsContainment(boundary.writeFace) || boundary.writeDenyMatch !== undefined; } export function anyFaceGuards(boundary) { return stationGuards(boundary) || writeFaceGuards(boundary); } export function foldShellReadFindings(judged) { let best = { finding: "none" }; let unestablished = false; let outsideOrUnresolved = false; let writeAsk; const reentered = []; const raise = (next) => { if (next.finding === "unestablishable" || next.finding === "declined" || next.finding === "unanswered") { const face = next.witness?.read.candidate.face; if (!(next.witness === undefined ? judged.guards || judged.writeGuards : face === "write" ? judged.writeGuards : judged.guards)) return; unestablished = true; } const rank = SHELL_READ_FINDING_RANK[next.finding] - SHELL_READ_FINDING_RANK[best.finding]; if (rank > 0 || (rank === 0 && next.witness?.read.candidate.face === "write" && best.witness?.read.candidate.face !== "write")) best = next; }; const walk = (j, reading) => { const denyOnly = reading !== "full"; if (j.plan.unreadable !== undefined && !denyOnly) raise({ finding: "unestablishable", cause: j.plan.unreadable }); const planned = reading === "deny-relation" ? j.segments.map((s) => s.segment) : []; for (const [k, s] of j.segments.entries()) { const piped = reading === "deny-relation" ? pipedRemovalStarts(planned, k) : undefined; for (const f of s.findings) { writeAsk ??= f.writeAsk; if (f.kind === "outside_roots" || (f.kind === "unestablishable" && f.read.unresolved === true && f.read.candidate.face !== "write")) outsideOrUnresolved = true; const removed = removesTarget(s.segment, f.read.candidate) || (piped?.raws.has(f.read.candidate.raw) === true && f.read.written !== undefined); const removesOutside = reading === "deny-relation" && f.kind === "outside_roots" && f.read.candidate.face === "write" && removed; if (denyOnly && !removesOutside && f.kind !== "deny_hit" && (reading === "deny-hit" || f.kind !== "unanswered")) continue; if (f.kind !== "none") raise({ finding: f.kind, witness: f }); } if (!denyOnly) { if (s.segment.declines.length > 0) raise({ finding: "declined", declined: s.segment }); if (s.segment.reentry === "shell") { raise({ finding: "unestablishable", declined: s.segment }); reentered.push(s.segment); } if (s.segment.unreadProgramText !== undefined) raise({ finding: "unestablishable", declined: s.segment }); const move = s.segment.baseMove; if (move !== undefined && (typeof move.target === "string" || move.target.expands !== false)) raise({ finding: "unestablishable", declined: s.segment }); } for (const n of s.nested) walk(n, reading === "full" && (s.segment.reentry !== "shell" || n.plan.handed === true) ? "full" : reading === "deny-hit" ? "deny-hit" : "deny-relation"); for (const n of s.printed) walk(n, "deny-hit"); } }; walk(judged, "full"); const asked = writeAsk !== undefined ? { writeAsk } : {}; const refused = judged.incomplete?.find((r) => r.refusal !== undefined); if (refused?.refusal !== undefined && (judged.guards || judged.writeGuards) && SHELL_READ_FINDING_RANK.target_unavailable > SHELL_READ_FINDING_RANK[best.finding]) { return { finding: "target_unavailable", cause: refused.refusal, ...asked }; } const unfinished = judged.incomplete?.[0]; if (unfinished !== undefined && (judged.guards || judged.writeGuards) && SHELL_READ_FINDING_RANK.unanswered > SHELL_READ_FINDING_RANK[best.finding]) { unestablished = true; best = { finding: "unanswered", cause: unfinished.detail, ...(best.finding === "unestablishable" ? { ...(best.witness !== undefined ? { witness: best.witness } : {}), ...(best.declined !== undefined ? { declined: best.declined } : {}) } : {}) }; } return { ...best, ...(unestablished ? { unestablished: true } : {}), ...(outsideOrUnresolved ? { outsideOrUnresolved: true } : {}), ...(unestablished && reentered.length > 0 ? { reentered } : {}), ...asked }; } export function writesAnything(judged) { return judged.segments.some((s) => s.findings.some((f) => f.read.candidate.face === "write" && f.read.written !== undefined) || s.nested.some(writesAnything) || s.printed.some(writesAnything)); } export function withWriteAskRows(judged, rows) { const reread = (f) => { if (f.read.candidate.face !== "write" || f.kind === "deny_hit" || f.denyRowUnasked === true) return f; const { writeAsk: _was, ...rest } = f; const writeAsk = writeAskOf(f.read, { writeAskRows: rows }); return writeAsk !== undefined ? { ...rest, writeAsk } : rest; }; const walk = (j) => ({ ...j, segments: j.segments.map((s) => ({ ...s, findings: s.findings.map(reread), nested: s.nested.map(walk), printed: s.printed.map(walk) })) }); return walk(judged); } export function judgeEstablishedPlan(plan, established, boundary, nestedOf, printedOf) { return { plan, segments: plan.segments.map((segment, i) => ({ segment, findings: [...(established.get(segment) ?? []).map((r) => judgeRead(r, boundary)), ...pipedRemovalFindings(plan.segments, i, established.get(segment) ?? [], boundary)], nested: segment.nested.map(nestedOf), printed: (segment.printed ?? []).map(printedOf), })), guards: stationGuards(boundary), writeGuards: writeFaceGuards(boundary), }; } function pipedRemovalFindings(segments, at, reads, boundary) { const starts = pipedRemovalStarts(segments, at); if (starts === undefined) return []; const start = segments[at].programStart; const named = reads.filter((r) => starts.raws.has(r.candidate.raw) && r.candidate.face !== "write" && r.candidate.denyOnly !== true && r.target !== undefined); const implicit = starts.implicit && start !== undefined && start.bases !== "unmodelled" ? start.bases.map((base) => ({ candidate: start, established: "lexical", target: base, spellings: [base] })) : []; return [...named, ...implicit].flatMap((r) => { const write = { ...r, candidate: { ...r.candidate, face: "write" }, written: { seat: "landing" } }; return judgeRead(write, { ...boundary, writeDenyMatch: undefined }).kind === "outside_roots" ? [judgeRead(write, boundary)] : []; }); } export function allFindings(judged) { const out = []; const walk = (j) => { for (const s of j.segments) { out.push(...s.findings); for (const n of s.nested) walk(n); } }; walk(judged); return out; } export function parentDirLexically(p) { return normalizeAbsPathLexically(`${p}/..`); } export function deepestCommonDir(a, b) { if (a === b) return a; const shorter = Math.min(a.length, b.length); let end = 0; let i = 0; while (i < shorter && a[i] === b[i]) { if (a[i] === "/" || a[i] === "\\") end = i; i++; } if (i === shorter && (a[shorter] === "/" || a[shorter] === "\\" || b[shorter] === "/" || b[shorter] === "\\")) end = shorter; const cut = a.slice(0, end); const candidate = cut.includes("/") || cut.includes("\\") ? cut : a.slice(0, end + 1); if (candidate.length === 0 || !withinAnyRoot([candidate], a) || !withinAnyRoot([candidate], b)) return undefined; return candidate; } export function readRootGrantCandidateOf(judged, boundary) { const outside = allFindings(judged).filter((f) => f.kind === "outside_roots"); if (outside.length === 0) return undefined; const targets = [...new Set(outside.map((f) => f.read.target))]; const paths = targets.filter((p) => !targets.some((q) => q !== p && withinAnyRoot([p], q))); if (outside.some((f) => f.read.candidate.spelled.split(/[\\/]/).includes(".."))) return undefined; if (paths.some(hasWin32AliasedComponent)) return undefined; const readsDirectory = new Set(outside .filter((f) => (f.read.candidate.provenance === "traversal_root" && f.read.node !== "file") || f.read.candidate.provenance === "cd_target") .map((f) => f.read.target)); const dirOf = (path) => (readsDirectory.has(path) ? path : parentDirLexically(path)); let candidate = dirOf(paths[0]); for (const path of paths.slice(1)) { if (candidate === undefined) return undefined; const d = dirOf(path); if (d === undefined) return undefined; candidate = deepestCommonDir(candidate, d); } if (candidate === undefined) return undefined; const proposed = grantOfferFor(candidate, paths.length === 1 ? paths[0] : undefined, boundary); if (proposed === undefined) return undefined; const widened = { ...boundary, roots: [...boundary.roots, proposed.dir] }; const replay = rejudge(judged, widened); return foldShellReadFindings(replay).finding === "none" ? proposed : undefined; } export function grantOfferFor(candidate, single, bounds) { const tooWide = parentDirLexically(candidate) === candidate || (bounds.homeDir !== undefined && withinAnyRoot([candidate], bounds.homeDir)) || bounds.roots.some((root) => withinAnyRoot([candidate], root)); return tooWide ? (single !== undefined ? { dir: single, covers: "exact" } : undefined) : { dir: candidate }; } export function rejudge(judged, boundary) { return { plan: judged.plan, segments: judged.segments.map((s) => ({ segment: s.segment, findings: s.findings.map((f) => judgeRead(f.read, boundary)), nested: s.nested.map((n) => rejudge(n, boundary)), printed: s.printed.map((n) => rejudge(n, boundary)), })), guards: stationGuards(boundary), writeGuards: writeFaceGuards(boundary), ...(judged.incomplete !== undefined ? { incomplete: judged.incomplete } : {}), }; }