UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

247 lines (246 loc) • 14.6 kB
import { effectivePathSpellingOf, effectivePathSpellingsOf } from "../../core/effective-path-target.js"; import { declaredReadSlotOf, PATH_TARGET_ELEMENTS_MAX, pathTargetOf } from "../../core/tool-registry.js"; import { judgedReadsOf as portOf } from "./judged-reads.js"; import { fitMiddle, READ_DENY_SENTENCE_PART_MAX, seatForCall } from "./read-deny.js"; import { resolveKey, violationDetails, violationText, withinAnyRoot } from "./safety.js"; import { readStationMemberOf, readTargetsRefusedDetails as readTargetsRefusedCard, unestablishedDetails as unestablishedCard } from "./shell-read-check.js"; import { decideShellRead, grantOfferFor, parentDirLexically } from "./shell-read-judge.js"; const ADMISSION_MAX = 1024; export function outsideReadDisposition(leg) { if (leg.readBlock) return "refusal"; return leg.readOnlyMount ? "tool_fence" : "question"; } export const READ_BLOCK_REMEDY = "This task refuses reads outside its directories (blockReadsOutsideRoots); ask the user to add the directory to the task's directories."; export function declaredReadOf(call) { return declaredReadSlotOf(call); } const VOUCH = { disposition: "vouch", finding: "none" }; function setBounded(map, key, value) { map.delete(key); if (map.size >= ADMISSION_MAX) { const oldest = map.keys().next().value; if (oldest !== undefined) map.delete(oldest); } map.set(key, value); } function namedTargets(targets) { if (targets.length === 1) return `"${fitMiddle(targets[0], READ_DENY_SENTENCE_PART_MAX)}"`; const shown = []; for (const t of targets) { const next = [...shown, `"${t}"`].join(", "); if (next.length > READ_DENY_SENTENCE_PART_MAX) break; shown.push(`"${t}"`); } if (shown.length === targets.length) return shown.join(", "); return `${shown.length > 0 ? `${shown.join(", ")} and ` : ""}${targets.length - shown.length} more (${targets.length} in all)`; } export function createFileReadStation(opts) { const admissions = new Map(); const declaredCalls = new Map(); const pendingDeclared = new Map(); const tables = { env: opts.env, rootCanonical: opts.rootCanonical, roots: opts.roots, ...(opts.readDeny !== undefined ? { readDeny: opts.readDeny } : {}), ...(opts.readFace !== undefined ? { readFace: opts.readFace } : {}), ...(opts.excluded !== undefined ? { excluded: opts.excluded } : {}), ...(opts.exempt !== undefined ? { exempt: opts.exempt } : {}), ...(opts.outsideReads === "refusal" ? { outsideRemedy: READ_BLOCK_REMEDY } : {}), }; const refuse = (sentence, finding, details) => ({ disposition: "refuse", finding, sentence, ...(details !== undefined ? { details } : {}) }); const judgeTargets = async (j, signal) => { const only = (verdict) => ({ verdict }); const { toolName } = j; const extra = seatForCall(opts.roots, j.toolCallId)(); const deny = seatForCall(opts.readDeny, j.toolCallId); const roots = [opts.rootCanonical, ...extra]; const allowed = fitMiddle(roots.join(", "), READ_DENY_SENTENCE_PART_MAX); const outside = []; const keys = []; for (const t of j.targets) { const r = await resolveKey(opts.env, opts.rootCanonical, t.spelled, signal, t.base, extra, undefined, deny, opts.readFace); if (r.ok) { keys.push(r.key); continue; } const v = r.violation; const outsideTarget = v.code === "path_not_in_root" ? v.target : undefined; if (outsideTarget !== undefined && opts.exempt?.(outsideTarget) === true) { keys.push(outsideTarget); continue; } const details = violationDetails(v); if (opts.outsideReads === "refusal") { if (outsideTarget === undefined) return only(refuse(violationText(toolName, v), v.code === "read_path_denied" ? "deny_hit" : "none", details)); return only(refuse(`Error (${toolName}): "${fitMiddle(outsideTarget, READ_DENY_SENTENCE_PART_MAX)}" is outside the directories this task may read (${allowed}). ${READ_BLOCK_REMEDY}`, "outside_roots", details)); } if (outsideTarget !== undefined && opts.outsideReads !== "tool_fence" && opts.excluded?.(outsideTarget) !== true) { outside.push({ target: outsideTarget, v }); keys.push(outsideTarget); continue; } if (j.declared) return only(refuse(violationText(toolName, v), v.code === "read_path_denied" ? "deny_hit" : "none", details)); return only(VOUCH); } if (outside.length === 0) return { verdict: VOUCH, keys }; const targets = outside.map((o) => o.target); const named = namedTargets(targets); const first = violationDetails(outside[0].v); const details = first !== undefined && first.code === "path_not_in_root" && targets.length > 1 ? { ...first, targets } : first; const disposition = decideShellRead("outside_roots", j.seat === "rejudge" ? "rejudge" : "file_tool"); const are = targets.length === 1 ? "is" : "are"; if (disposition === "refuse") { return only(refuse(j.seat === "rejudge" ? `Error (${toolName}): the approved edit reads ${named}, outside the directories allowed for this session (${allowed}) — re-submit it as a fresh call and answer its card.` : `Error (${toolName}): ${named} ${are} outside the directories allowed for this session (${allowed}).`, "outside_roots", details)); } const head = targets[0]; const info = j.mayBeDirectory ? await opts.env.fileInfo(head, signal) : undefined; const proposed = grantOfferFor(info?.ok === true && info.value.kind === "directory" ? head : parentDirLexically(head), targets.length === 1 ? head : undefined, { roots, ...(opts.homeDir !== undefined ? { homeDir: opts.homeDir } : {}) }); const offer = proposed !== undefined && targets.every((t) => withinAnyRoot([proposed.dir], t)) ? proposed : undefined; return { verdict: { disposition, finding: "outside_roots", sentence: `reads outside the allowed directories for this session: ${named} ${are} not under ${allowed}`, ...(details !== undefined ? { details } : {}), ...(offer !== undefined ? { readRootCandidate: { dir: offer.dir, ...(offer.covers !== undefined ? { covers: offer.covers } : {}), clearsThisAsk: true } } : {}), ...(j.declared ? { cause: { code: "read.outside_roots", roots: { shown: targets, total: targets.length } } } : {}), admit: () => j.admit(targets), }, keys, }; }; const judgeDeclared = (call, pt, args, cwd, signal, callOpts) => { const toolName = call.toolName; const toolCallId = callOpts.toolCallId; const mine = {}; if (toolCallId !== undefined) { declaredCalls.delete(toolCallId); setBounded(pendingDeclared, toolCallId, mine); } let judged; const landed = (verdict) => { if (toolCallId === undefined || pendingDeclared.get(toolCallId) !== mine) return verdict; pendingDeclared.delete(toolCallId); if (verdict.disposition !== "refuse" && judged !== undefined) setBounded(declaredCalls, toolCallId, judged); return verdict; }; const sels = effectivePathSpellingsOf({ toolName, args, ...(call.face !== undefined ? { face: call.face } : {}) }, pt, { root: opts.rootCanonical, cwd }) ?? []; if (sels.length > PATH_TARGET_ELEMENTS_MAX) return Promise.resolve(landed(refuse(`Error (${toolName}): this call names ${sels.length} paths; a call may name at most ${PATH_TARGET_ELEMENTS_MAX}. Split it into calls of at most ${PATH_TARGET_ELEMENTS_MAX}; the call was not run.`, "none", readTargetsRefusedCard("read_targets_over_limit")))); const targets = []; for (const sel of sels) { if ("refused" in sel) return Promise.resolve(landed(refuse(`Error (${toolName}): a path this call names is one this environment refuses (${String(sel.refused)}); the call was not run.`, "none"))); const spelled = "malformed" in sel ? undefined : (sel.spelled ?? sel.base); if ("malformed" in sel || spelled === undefined) return Promise.resolve(landed(refuse(`Error (${toolName}): a value of "${pt.param}" is not a path (the slot takes a non-empty string${pt.each === true ? " or a list of them" : ""}); the call was not run.`, "none", readTargetsRefusedCard("read_target_not_a_path")))); targets.push({ spelled, base: sel.spelled !== undefined ? sel.base : undefined }); } mine.targets = targets.length; const admitted = new Set(); return judgeTargets({ toolName, targets, toolCallId, seat: callOpts.seat, declared: true, mayBeDirectory: true, admit: (outside) => outside.forEach((o) => admitted.add(o)) }, signal).then(({ verdict, keys }) => { if (verdict.disposition !== "refuse" && keys !== undefined) judged = { toolName, elements: targets.map((t, i) => ({ spelled: t.spelled, base: t.base, key: keys[i] })), admitted }; return landed(verdict); }); }; const check = { judge(call, args, cwd, signal, callOpts) { const declared = declaredReadOf(call); if (declared !== undefined) return judgeDeclared(call, declared, args, cwd, signal, callOpts); const member = readStationMemberOf(call, opts.tools)?.name; if (member === undefined) return null; const selection = effectivePathSpellingOf({ toolName: call.toolName, args }, pathTargetOf(member), { root: opts.rootCanonical, cwd }); if (selection === undefined || "refused" in selection || selection.spelled === undefined) return null; const toolCallId = callOpts.toolCallId; return judgeTargets({ toolName: call.toolName, targets: [{ spelled: selection.spelled, base: selection.base }], toolCallId, seat: callOpts.seat, declared: false, mayBeDirectory: pathTargetOf(member)?.absent === "base", admit: (outside) => { if (toolCallId !== undefined && outside[0] !== undefined) setBounded(admissions, toolCallId, outside[0]); }, }, signal).then(({ verdict }) => verdict); }, unanswered: (call, cause) => { const id = call.toolCallId; const named = id !== undefined ? pendingDeclared.get(id)?.targets : undefined; if (id !== undefined) { pendingDeclared.delete(id); declaredCalls.delete(id); } const remedy = named !== undefined && named > 1 ? `This call names ${named} paths: split them into several calls, each naming fewer.` : "Try the call again."; if (declaredReadOf(call) !== undefined) return { disposition: "refuse", finding: "unanswered", environmentSilent: true, sentence: `Error (${call.toolName}): where this call reads could not be established (${cause}), and nothing after the read station judges what this tool reads, so the call was not run. ${remedy}`, details: unestablishedCard() }; return opts.outsideReads === "refusal" ? { disposition: "refuse", finding: "unanswered", environmentSilent: true, sentence: `Error (${call.toolName}): where this call reads could not be established (${cause}), and this task refuses reads it cannot place inside its directories (blockReadsOutsideRoots). Try the call again.` } : VOUCH; }, }; const admitted = (toolCallId, key) => { if (toolCallId === undefined || admissions.get(toolCallId) !== key) return false; admissions.delete(toolCallId); return true; }; const judgedReadsOf = (toolCallId) => { const judged = declaredCalls.get(toolCallId); return judged === undefined ? undefined : portOf(tables, toolCallId, judged); }; return { check, tools: opts.tools, admitted, judgedReadsOf, declares: (call) => declaredReadOf(call) !== undefined }; } export function readStationsHold(stations, call) { return stations.some((s) => readStationMemberOf(call, s.tools) !== undefined || s.declares?.(call) === true); } export function composeReadChecks(stations) { if (stations.length === 0) return undefined; if (stations.length === 1) return stations[0].check; const byName = new Map(); for (const s of stations) for (const n of s.tools) if (!byName.has(n)) byName.set(n, s); const stationOf = (call) => stations.find((s) => s.declares?.(call) === true) ?? readStationMemberOf(call, byName)?.value; return { judge: (call, args, cwd, signal, callOpts) => stationOf(call)?.check.judge(call, args, cwd, signal, callOpts) ?? null, unanswered: (call, cause, args) => (stationOf(call) ?? stations[0]).check.unanswered(call, cause, args), writeAskRowsUncounted: (toolCallId) => stations.some((s) => s.check.writeAskRowsUncounted?.(toolCallId) === true), }; } export function unjudgedReadsMember(ported) { const declares = (call) => declaredReadOf(call) !== undefined && !ported(call.toolName); const refusal = (call) => ({ disposition: "refuse", finding: "unanswered", environmentSilent: true, sentence: `Error (${call.toolName}): this leg has no execution environment, so nothing can judge the paths this tool declares it reads, and the tool opens them itself; the call was not run. Give the Runner an execution environment (executionEnv or executionEnvFactory), or drop the tool's read declaration (its pathTarget).`, details: unestablishedCard(), }); return { tools: new Set(), declares, check: { judge: (call) => (declares(call) ? Promise.resolve(refusal(call)) : null), unanswered: (call) => (declares(call) ? refusal(call) : VOUCH) }, }; }