UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

316 lines (315 loc) • 23.2 kB
import { REFUSES_NO_WHOLE_TOOL, toolPolicyWholeToolRefusals } from "../tool-policy.js"; import { persistedRuleMandateOf, ruleClearanceOf } from "../ask-origin.js"; import {} from "../hooks.js"; import { runsOnBash, startedShellOfCall } from "../call-shell.js"; import { addStampsOf as stampsOf, adjudicatePersistedDomainRules, adjudicatePersistedNameRules, adjudicatePersistedPathRules, adjudicatePersistedRulesIn, adjudicatePersistedToolRules, callPathFaceOf, cardRuleFormOf, eligiblePersisted, escapeForDisclosure, faceRowsSpeakFor, parseRuleText, ruleWordsOf, nameRuleSubjectOf, ruleToolGrammarOf, segmentCoverageOf, suggestRuleForHost, suggestRuleForName, suggestRuleForTool, suggestRulesForCommand, wholeToolRuleReaches } from "../permission-rule-model.js"; import { callHostTargetOf } from "../host-target.js"; import { callTargetViewsOf, validatePath } from "../effective-path-target.js"; import { bindPathRules, persistedRowAnchors, projectScopeIdentity } from "../path-rule-binding.js"; import { heldBy, seatOf, wireOf } from "../tool-name-readings.js"; import { describeUnreadableOrgRows, readOrgRules, settleOrgVerdictWithin } from "../permission-rule-org.js"; import { ASK_USER_QUESTION_TOOL_NAME } from "../ask-question.js"; import { routesContent } from "../tool-catalog-entries.js"; import { ownerStoreOf } from "../permission-rule-provider.js"; import { storedAllowRowRead } from "../auto-strip.js"; import { storeFormAnswer, unreadableRowsInScope, unreadableRowsReaching } from "./unreadable-person-rows.js"; import { readPrincipal } from "../principal-name.js"; import { thrownText } from "../thrown-value.js"; import { strongestAnswer } from "../persisted-rule-arms.js"; import { ORG_ADJUDICATION_TIMEOUT_MS } from "../permission-rule-org.js"; import { insidePeerOfferOf } from "../a2a-bound-grant.js"; import { refuseUnreadAncestorBuckets } from "../persisted-rule-buckets.js"; import { callGrantRowAdmitting } from "../session-call-grant.js"; const NO_LEADS = new Map(); export function inheritedAskRuleEvidence(provider, heard) { const org = provider?.partitions.org === true ? "not_adjudicated" : "not_wired"; const absent = heard === undefined ? (provider?.partitions.durable === true ? "not_adjudicated" : "not_wired") : heard.unreadable === true ? "unavailable" : "no_match"; const rules = heard?.unreadable !== true ? heard?.hit?.rules : undefined; const dots = rules?.every((r) => r.dots !== undefined && r.dots.length > 0) === true ? [...new Map(rules.flatMap((r) => r.dots ?? []).map((d) => [JSON.stringify([d.actor, d.counter]), d])).values()] : undefined; const personal = rules === undefined ? { personalRuleDotsAbsent: absent } : dots !== undefined ? { personalRuleDots: dots } : { personalRuleDotsAbsent: "not_reported" }; return Object.freeze({ orgRevisionAbsent: org, orgRuleAbsent: org, ...personal }); } export function orgRevisionEvidenceOf(resolution, onDefect) { let reported; try { reported = resolution.revision; } catch (err) { onDefect(`the org rule partition's revision could not be read (${thrownText(err)}) — the adjudication stands, but the ask carries no revision evidence for this call`); return {}; } if (reported === undefined) return {}; if (typeof reported === "number" && Number.isFinite(reported)) return { revision: reported }; onDefect(`the org rule partition reported revision ${typeof reported === "string" ? `"${escapeForDisclosure(reported)}"` : escapeForDisclosure(reported)} — a snapshot revision is a finite number; ` + `the adjudication stands, but the ask carries no revision evidence for this call`); return {}; } export function persistedRuleHitOf(verdict) { return verdict === undefined ? undefined : { behavior: verdict.behavior, rules: verdict.rules.map((r) => ({ rule: r.rule, dots: r.adds.map((a) => ({ actor: a.dot.actor, counter: a.dot.counter })), ...stampsOf(r.adds) })), ...(verdict.denial !== undefined ? { denial: { ...verdict.denial } } : {}) }; } export function persistedRuleAnswerOf(verdict) { if (verdict?.unreadable !== undefined) return { unreadable: true, reason: verdict.unreadable }; return persistedRuleHitOf(verdict); } export function pathRuleLaneAnswer(table, req, ctx) { const tighten = callTargetViewsOf(req, "tighten"); const allow = callTargetViewsOf(req, "allow"); if (tighten === undefined && allow === undefined) return undefined; return persistedRuleAnswerOf(adjudicatePersistedPathRules(table, { tool: req.toolName, cwd: ctx.root, sessionId: ctx.sessionId, face: callPathFaceOf(req), ...(ctx.scopeIdentity !== undefined ? { scopeIdentity: ctx.scopeIdentity } : {}) }, { ...(tighten !== undefined ? { tighten } : {}), ...(allow !== undefined ? { allow } : {}) }, ctx.anchorsOf, ctx.leads)); } export function orgRuleLane(cfg) { const questionToolExempt = (call) => wireOf("offer.orgQuestionExemption", call) === cfg.questionToolName && cfg.questionToolMounted; return { adjudicate: async (req) => { if (questionToolExempt(req)) return { status: "available" }; let resolution; try { resolution = (await cfg.read(req.toolCallId, req.args)).org; } catch (err) { return { status: "unavailable", disclosures: [`the permission-rule store threw while resolving the org partition: ${thrownText(err)}`] }; } if (resolution.status === "unavailable" || resolution.status === "ungoverned") { return { status: "unavailable", disclosures: resolution.status === "ungoverned" ? ["the store reports no org partition while the provider declares one — unreadable governance, never an empty one"] : resolution.disclosures }; } const reading = readOrgRules(resolution.rules); if ("refused" in reading) return { status: "unavailable", disclosures: [`the store's org resolution cannot be read (${reading.refused}) — unreadable governance, never an empty one`] }; const command = req.args?.command; const face = callPathFaceOf(req); const call = { tool: ruleWordsOf(req, "deny"), ...(face !== undefined ? { face } : {}) }, verdict = reading.verdictFor(typeof command === "string" ? { ...call, command, shell: startedShellOfCall(req) } : call); const revisionCell = orgRevisionEvidenceOf(resolution, cfg.onRevisionDefect); const degraded = describeUnreadableOrgRows(reading.unreadable, revisionCell.revision); if (degraded !== undefined) cfg.onDegraded(degraded); return verdict === undefined ? { status: "available", ...revisionCell } : { status: "available", verdict, ...revisionCell }; }, refusesWholeOver: (resolution) => { const reading = resolution.status === "unavailable" || resolution.status === "ungoverned" ? undefined : readOrgRules(resolution.rules); if (reading === undefined || "refused" in reading) return REFUSES_NO_WHOLE_TOOL; return (tool) => !questionToolExempt(tool) && reading.verdictFor({ tool: ruleWordsOf(tool, "deny"), face: callPathFaceOf({ ...tool, args: undefined }) })?.behavior === "deny"; }, }; } export function orgVerdictBeforeClaim(cfg, req) { const unreadable = { status: "unavailable", disclosures: [] }; const read = () => { const store = ownerStoreOf(cfg.provider, cfg.principal, cfg.localOwnerDeclared); return orgRuleLane({ read: () => store.effective({ sessionId: cfg.sessionId }), questionToolMounted: true, questionToolName: ASK_USER_QUESTION_TOOL_NAME, onRevisionDefect: () => undefined, onDegraded: () => undefined }).adjudicate(req); }; return settleOrgVerdictWithin(Promise.resolve().then(read).catch(() => unreadable), unreadable, { timeoutMs: ORG_ADJUDICATION_TIMEOUT_MS, ...(cfg.signal !== undefined ? { signal: cfg.signal } : {}) }); } export function createPermissionRuleLanes(cfg) { const provider = cfg.provider; if (cfg.home !== undefined && validatePath(cfg.home, { intent: "validate-coordinate" }) === undefined) { const e = new Error(`the execution environment declares homeDir ${JSON.stringify(cfg.home)}, which is not an absolute path — a \`~/\` permission rule could not be resolved against it; declare an absolute home directory or none`); e.code = "config.execution_env_home_dir_invalid"; throw e; } if (cfg.localOwnerDeclared) { if (provider === undefined || !provider.partitions.durable) { throw new Error("RunnerDeps.localOwnerRules is declared but no durable permission-rule partition is wired — there is no bucket for the local owner to hold rules in; refusing rather than running as if the declaration were absent"); } if (provider.forLocalOwner === undefined) { throw new Error("RunnerDeps.localOwnerRules is declared but the wired permission-rule provider implements no forLocalOwner() face — a provider without a local-owner bucket cannot honor the declaration; refusing rather than silently resolving zero rules"); } } refuseUnreadAncestorBuckets(cfg.ancestorRuleBuckets, cfg); if (provider === undefined) return { personal: undefined, org: undefined, wholeToolRefusals: undefined }; const anonymous = readPrincipal(cfg.principal).kind === "absent"; const reader = cfg.rows; const orgViewOf = async (toolCallId, judged) => { const read = await reader.pin(toolCallId, judged); if (read.org === undefined) throw new Error(read.unreadable ?? "the store did not answer"); return { org: read.org }; }; const org = provider.partitions.org ? orgRuleLane({ read: orgViewOf, questionToolMounted: cfg.questionToolMounted, questionToolName: cfg.questionToolName, onRevisionDefect: cfg.onRevisionDefect, onDegraded: cfg.onDisclosure }) : undefined; const personalAdjudicate = async (req) => { if (anonymous && !cfg.localOwnerDeclared) return undefined; const judged = ruleWordsOf(req, "deny").map((n) => [n, ruleToolGrammarOf(n), ruleWordsOf(req, "allow").includes(n)]); if (!judged.some(([, g, grants]) => g === "path" && grants) && faceRowsSpeakFor(callPathFaceOf(req))) judged.push([req.toolName, "path", true]); const view = await reader.pin(req.toolCallId, req.args); const storeUnreadable = (rows = [], ask) => storeFormAnswer(view.unreadableFaults, rows, ask); const ownRow = (r) => judged.some(([n]) => n === r.tool) || wholeToolRuleReaches(r.tool, req, r.behavior); const judgesPath = judged.some(([, g]) => g === "path"); const reached = unreadableRowsReaching(view.unreadableRows, { req, words: judged.map(([n]) => n), judgesPath }); if (judged.length === 0 && !view.rules.some(ownRow) && reached.length === 0) return view.unreadable !== undefined ? storeUnreadable() : undefined; try { const strips = new Map(); for (const r of view.rules) { const reason = r.behavior === "allow" ? cfg.stripsAllow?.(r, req) : undefined; if (reason !== undefined) strips.set(r, reason); } const stripped = view.rules.filter((r) => !strips.has(r)); const readsRow = (r) => ownRow(r) || (judgesPath && (r.match === "path" || r.match === "subpath")); const noRule = []; const table = stripped.filter((r) => { const read = readsRow(r) ? parseRuleText(r.rule, r.behavior) : undefined; if (read !== undefined && "reject" in read) noRule.push({ row: r, why: read.reject.message }); return read === undefined || !("reject" in read) || r.behavior !== "allow"; }); const leads = judgesPath ? await cfg.leads.resolve(bindPathRules(table.filter((r) => r.match === "path" || r.match === "subpath").map((r) => ({ parsed: r, ruleText: r.rule, rule: r })), (spec) => anchorsOf(spec.rule))) : NO_LEADS; const scopeIdentity = await projectScopeIdentity([...table, ...reached.flatMap((u) => (u.scope !== undefined ? [{ scope: u.scope }] : []))], cfg.rootCanonical, cfg.leads); const judgeTable = (rows) => strongestAnswer([ ...judged.map(([n, grammar, grants]) => judgeAgainst(grants ? rows : rows.filter((r) => r.behavior !== "allow"), { ...req, toolName: n }, grammar, leads, scopeIdentity)), persistedRuleAnswerOf(adjudicatePersistedToolRules(rows, { request: req, cwd: cfg.root, sessionId: cfg.sessionId, ...(scopeIdentity !== undefined ? { scopeIdentity } : {}) })), ]); const judgedAnswer = judgeTable(table); const unjudged = noRule.find(({ row }) => (row.behavior === "deny" || row.behavior === "ask") && eligiblePersisted(row, { tool: row.tool, cwd: cfg.root, sessionId: cfg.sessionId, ...(scopeIdentity !== undefined ? { scopeIdentity } : {}) }, row.behavior)); const answer = unjudged !== undefined && !(judgedAnswer !== undefined && "behavior" in judgedAnswer && judgedAnswer.behavior === "deny") ? unjudgedRowAnswer(unjudged.row, unjudged.why, req.toolName) : judgedAnswer; if (cfg.onAutoStripped !== undefined && strips.size > 0) await tellStrips(strips, req, judged, cfg.onAutoStripped); const unread = unreadableRowsInScope(reached, req.toolName, { cwd: cfg.root, sessionId: cfg.sessionId, ...(scopeIdentity !== undefined ? { scopeIdentity } : {}) }); const stands = answer !== undefined && (("behavior" in answer && answer.behavior === "deny") || "unreadable" in answer); if ((view.unreadable !== undefined || unread.length > 0) && !stands) return storeUnreadable(unread, answer !== undefined && "behavior" in answer && answer.behavior === "ask" ? answer : undefined); if (answer === undefined || "segmentCoverage" in answer) { const granted = await callGrantOf(stripped, req, judged); if (granted !== undefined) return persistedRuleAnswerOf({ behavior: "allow", rules: [granted] }); } if (answer === undefined || !("behavior" in answer) || answer.behavior !== "allow") return answer; const bound = table.flatMap((r) => { try { const alone = r.behavior === "allow" && readsRow(r) && stampsOf(r.adds).peerFingerprints !== undefined ? judgeTable([r]) : undefined; return alone !== undefined && "behavior" in alone && alone.behavior === "allow" ? alone.rules : []; } catch { return []; } }); return bound.length > 0 ? { ...answer, bound } : answer; } catch (err) { const why = `judging this call against the rows threw: ${thrownText(err)}`; cfg.onDisclosure(`the persisted rule lane could not judge a ${req.toolName} call against the rows it read — ${why}`); return { unreadable: true, reason: why }; } }; const callGrantOf = (rows, req, judged) => callGrantRowAdmitting(rows, { words: judged.flatMap(([n, g, grants]) => (grants && g === "command" ? [n] : [])), sessionId: cfg.sessionId, command: req.args?.command, judge: cfg.callGrantAdmits && ((binding, command) => cfg.callGrantAdmits(binding, command, req)) }); const unjudgedRowAnswer = (row, refusal, tool) => { const why = `the stored ${row.behavior} rule ${escapeForDisclosure(row.rule)} is no rule this engine reads (${refusal})`; cfg.onDisclosure(`the persisted rule lane could not judge a ${tool} call against the rows it read — ${why}`); return { unreadable: true, reason: why }; }; const anchorsOf = (rule) => persistedRowAnchors(rule.scope, cfg.chainTop); const tellStrips = async (strips, req, judged, told) => { try { const grantNames = judged.flatMap(([n, , grants]) => (grants ? [n] : [])); const grantsPath = judged.some(([, g, grants]) => g === "path" && grants); const read = [...strips].filter(([r]) => (grantNames.includes(r.tool) || (r.match === "tool" && wholeToolRuleReaches(r.tool, req, "allow")) || (grantsPath && (r.match === "path" || r.match === "subpath"))) && storedAllowRowRead(r) !== undefined); if (read.length === 0) return; const scopeIdentity = await projectScopeIdentity(read.map(([r]) => r), cfg.rootCanonical, cfg.leads); for (const [r, reason] of read) if (eligiblePersisted(r, { tool: r.tool, cwd: cfg.root, sessionId: cfg.sessionId, ...(scopeIdentity !== undefined ? { scopeIdentity } : {}) }, "allow")) told(r, reason, req); } catch (err) { cfg.onDisclosure(`the account of the stored allow rows auto mode set aside for a ${req.toolName} call could not be given: ${thrownText(err)}`); } }; const judgeAgainst = (table, req, grammar, leads, scopeIdentity) => { const liveCwd = cfg.liveCwd(); const scope = scopeIdentity !== undefined ? { scopeIdentity } : {}; if (grammar === "path") return pathRuleLaneAnswer(table, req, { root: cfg.root, sessionId: cfg.sessionId, anchorsOf, leads, ...scope }); if (grammar === "name") return persistedRuleAnswerOf(adjudicatePersistedNameRules(table, { tool: req.toolName, request: req, cwd: cfg.root, sessionId: cfg.sessionId, ...scope })); if (grammar === "domain") return persistedRuleAnswerOf(adjudicatePersistedDomainRules(table, { tool: req.toolName, hosts: { tighten: callHostTargetOf(req, "tighten"), grant: callHostTargetOf(req, "grant") }, cwd: cfg.root, sessionId: cfg.sessionId, ...scope })); const command = req.args?.command; if (typeof command !== "string") return undefined; const execCwd = liveCwd !== undefined ? { execCwd: liveCwd } : {}; const verdict = adjudicatePersistedRulesIn(table, { tool: req.toolName, command, shell: startedShellOfCall(req), cwd: cfg.root, sessionId: cfg.sessionId, ...execCwd, ...scope }); if (verdict !== undefined) return persistedRuleAnswerOf(verdict); const coverage = runsOnBash(req) ? segmentCoverageOf(command, { persisted: table }, { tool: req.toolName, cwd: cfg.root, sessionId: cfg.sessionId, ...execCwd, ...scope }) : undefined; return coverage !== undefined ? { segmentCoverage: coverage } : undefined; }; const personalRefusesWholeOver = async (rules) => { const deny = anonymous && !cfg.localOwnerDeclared ? [] : rules.filter((r) => r.behavior === "deny" && r.match === "tool"); const scopeIdentity = deny.length === 0 ? undefined : await projectScopeIdentity(deny, cfg.rootCanonical, cfg.leads); return deny.length === 0 ? REFUSES_NO_WHOLE_TOOL : (tool) => !routesContent(tool.face) && adjudicatePersistedToolRules(deny, { request: tool, cwd: cfg.root, sessionId: cfg.sessionId, ...(scopeIdentity !== undefined ? { scopeIdentity } : {}) })?.behavior === "deny"; }; const personal = provider.partitions.durable ? { adjudicate: personalAdjudicate } : undefined; let inFlight; const viewRead = () => (inFlight ??= reader.forRequest().finally(() => (inFlight = undefined))); const wholeToolRefusals = toolPolicyWholeToolRefusals([ personal !== undefined ? { wholeToolRefusals: async () => personalRefusesWholeOver((await viewRead()).rules) } : undefined, org !== undefined ? { wholeToolRefusals: async () => ((read) => (read.org !== undefined ? org.refusesWholeOver(read.org) : REFUSES_NO_WHOLE_TOOL))(await viewRead()) } : undefined, ]); return { personal, org, wholeToolRefusals }; } export function createRuleOffersOf(cfg) { return (call, args, ask) => { const toolName = wireOf("offer.laneTool", call); if (!cfg.laneArmed || (readPrincipal(cfg.principal).kind === "absent" && !cfg.localOwnerDeclared) || routesContent(call.face)) return {}; const form = cardRuleFormOf(toolName, call); const tierSeat = seatOf("offer.marks", cfg.irreversibilityTier, call); const closedDoor = ruleClearanceOf(ask, { egress: heldBy("offer.marks.egress", cfg.egressTools, call), irreversibility: tierSeat?.value, shellGated: tierSeat?.shellGated(cfg.shellGatedTools, cfg.toolMarkSources) === true, }).word; if (closedDoor !== undefined) return { ruleOffersAbsence: closedDoor }; if (ask?.classes?.includes("sandbox_override") === true) return { ruleOffersAbsence: "lane_cannot_speak" }; if (ask?.classes?.includes("a2a_inside") === true) { let offer; try { offer = insidePeerOfferOf(cfg.a2aPeers, toolName); } catch { offer = undefined; } return offer !== undefined ? { ruleOffers: [offer] } : { ruleOffersAbsence: "lane_cannot_speak" }; } if (form === "tool") { const offer = suggestRuleForTool(toolName); return offer !== undefined ? { ruleOffers: [offer] } : { ruleOffersAbsence: "lane_cannot_speak" }; } if (form === undefined) return { ruleOffersAbsence: "lane_cannot_speak" }; if (form === "name") { const offer = suggestRuleForName(toolName, nameRuleSubjectOf(toolName, args, "allow") ?? ""); return offer !== undefined ? { ruleOffers: [offer] } : { ruleOffersAbsence: "lane_cannot_speak" }; } if (form === "domain") { const host = callHostTargetOf({ toolName: call.toolName, args, face: call.face }, "grant"); const offer = host !== undefined && "host" in host ? suggestRuleForHost(toolName, host.host) : undefined; return offer !== undefined ? { ruleOffers: [offer] } : { ruleOffersAbsence: "lane_cannot_speak" }; } const command = args?.command; if (typeof command !== "string" || !runsOnBash(call)) return { ruleOffersAbsence: "lane_cannot_speak" }; const offers = suggestRulesForCommand(command, { ...(ask?.segmentCoverage !== undefined ? { coverage: ask.segmentCoverage } : {}), ...(cfg.taskRoot !== undefined ? { scope: { kind: "project", root: cfg.taskRoot }, cwd: cfg.taskRoot } : {}), ...(cfg.cwdRef?.current !== undefined ? { execCwd: cfg.cwdRef.current } : {}), ...(cfg.deniesDirectoryRead !== undefined ? { deniesDirectoryRead: cfg.deniesDirectoryRead } : {}), }); return offers.length > 0 ? { ruleOffers: offers, ...(cfg.cwdRef?.current !== undefined ? { execCwd: cfg.cwdRef.current } : {}) } : { ruleOffersAbsence: "lane_cannot_speak" }; }; }