UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

323 lines (322 loc) • 20.2 kB
import { inlineUntrusted, inlineUntrustedAtWord, PROBE_REASON_MAX } from "./untrusted-text.js"; import { markTightenMessage } from "./safety-axis-vocab.js"; import { normalizeProbeCause } from "./checkpoint-features.js"; import { normalizeReadRootCandidate } from "./read-root-candidate.js"; import { engineFailClosedExit, hookDenyExit, settledScreenExit, takeInheritedScreen } from "./runner/gate-exit.js"; import { noteRewrite, POLICY_AUTHOR, readRejudge, screenRewrite } from "./rewrite-rejudge.js"; import { traceHookCrash } from "./gate-crash-trace.js"; import { askWithTableSentence, writeProtectionMandated, writeProtectionReachOf, writeProtectionTightenDecision } from "./write-protect.js"; import { createGateDeadline, awaitWriteProtectionJudgment, gateWaitFailureOf, withGateTimeout } from "./gate-bounded-await.js"; import { shellReadFaceWords } from "../tools/fs/shell-read-face.js"; import { failedJudgmentDeny } from "./runner/policy-throw.js"; import { thrownText } from "./thrown-value.js"; import { argsAsTheToolReads, movedCallReading, stampedCallOf } from "./effective-path-target.js"; import { foldHookAsk, refuseOutOfContractDecision } from "./tool-policy.js"; import { sandboxOverrideMessage, stationAskRowOf, withChainAskReasons, withProbeMandate } from "./ask-origin.js"; import { applyUnansweredSilence, readStationAnswer, silencedBy } from "./shell-read-silence.js"; import { applyPersistedTightening } from "./persisted-rule-arms.js"; import { asksUnstated, permissionSeatAt, unstatedAskMessage } from "./mode-policy.js"; import { crossBoundaryQuestion } from "./cross-boundary-taint.js"; export async function runGateFold(pass) { const { input, toolName, toolCallId, callSignal, ledger, notifier, adjudicate } = pass; const boundedAwaitDeadlineMs = createGateDeadline(input, notifier); pass.req = Object.freeze({ toolName, args: pass.currentInput, toolCallId, ...(pass.req.face !== undefined ? { face: pass.req.face } : {}) }); let unread; try { const given = pass.req; const stamped = input.stampCallTarget?.(given, callSignal ?? input.abortSignal); if (stamped !== undefined) { const read = stampedCallOf(given, await stamped); if (read.moved === undefined) pass.req = Object.freeze(read.req); else unread = movedCallReading(read.moved); } } catch (error) { unread = { error }; } pass.decision = unread !== undefined ? failedJudgmentDeny(unread.error, callSignal ?? input.abortSignal, (e) => traceHookCrash(input, e, notifier), "the call's target reading", { toolName, toolCallId }, unread.said) : adjudicate ? refuseOutOfContractDecision(await (callSignal !== undefined ? adjudicate(pass.req, callSignal) : adjudicate(pass.req)), { call: pass.req }) : { action: "allow" }; { const read = ledger.fromDecision(pass.decision); pass.decision = read.decision; if (read.deniedBy !== undefined) pass.deniedBy = read.deniedBy; if (read.deniedBy !== undefined) pass.denyCause = ledger.causeOf(pass.decision); const attributed = ledger.classifierRoundOf(pass.decision); if (attributed !== undefined) { pass.classifierRound = attributed; pass.classifierAsked = ledger.classifierAskedOf(pass.decision); } } pass.decision = withChainAskReasons(pass.decision, pass.req); const rewritten = pass.screening !== undefined && pass.decision.action !== "deny" ? readRejudge(pass.req, pass.currentInput, pass.decision) : undefined; if (pass.screening !== undefined && rewritten?.kind === "rewritten") { const second = await screenRewrite(pass.screening, pass.req, rewritten.form, `the rewritten call to "${toolName}"`); if (second.kind === "refused" || second.kind === "settled") { pass.currentInput = second.judged !== undefined ? second.judged : rewritten.form; if (second.kind === "settled") return await settledScreenExit(pass, second); return second.by === "hook" ? hookDenyExit(pass, second.reason, second.extension) : await engineFailClosedExit(pass, second.reason, second.extension); } pass.preToolContext.push(...second.contexts); pass.hookAsk = second.answer?.action === "ask" ? second.answer : undefined; pass.hookAllowedBy = second.answer?.action === "allow" ? (second.answeredBy !== undefined ? [second.answeredBy] : []) : undefined; takeInheritedScreen(pass, second.inherited); } if ((pass.decision.action === "allow" || pass.decision.action === "ask") && pass.decision.updatedInput !== undefined) { pass.policyRewrite = argsAsTheToolReads(pass.req, pass.decision.updatedInput); noteRewrite(pass.rewrites, pass.req, pass.currentInput, pass.policyRewrite, POLICY_AUTHOR); } else if (pass.hookAsk?.updatedInput !== undefined) { pass.policyRewrite = argsAsTheToolReads(pass.req, pass.hookAsk.updatedInput); } if (pass.hookAsk !== undefined && pass.decision.action !== "deny") { pass.decision = foldHookAsk(pass.decision, pass.hookAsk); } if ((pass.decision.action === "allow" || pass.decision.action === "ask") && input.shellReadCheck !== undefined) { const station = input.shellReadCheck; const judged = station.judge(pass.req, pass.policyRewrite !== undefined ? pass.policyRewrite : pass.currentInput, input.trackedCwd?.(), pass.callSignal ?? input.abortSignal, { toolCallId }); if (judged !== null) { let verdict; try { verdict = await withGateTimeout(judged, boundedAwaitDeadlineMs(), pass.callSignal ?? input.abortSignal, "shellReadStation"); } catch (err) { const kind = gateWaitFailureOf(err); if (kind !== "aborted" && input.abortSignal?.aborted !== true) { traceHookCrash(input, new Error(`shell read station ${kind === "timeout" ? "timed out" : "threw"} for tool "${toolName}" (toolCallId ${toolCallId}) — where this call reads could not be established: ${thrownText(err)}`), notifier); } verdict = station.unanswered(pass.req, kind === "timeout" ? "the read station timed out" : "the read station could not answer", pass.policyRewrite !== undefined ? pass.policyRewrite : pass.currentInput); pass.shellReadFallback = true; } applyShellReadVerdict(pass, verdict, toolName, input.shellGated === true); } } const interactionSeat = input.requiresUserInteraction === true ? undefined : permissionSeatAt(input, pass.policyRewrite !== undefined ? pass.policyRewrite : pass.currentInput); if (interactionSeat?.requiresUserInteraction === true) pass.requiresUserInteraction = true; if ((input.requiresUserInteraction === true || pass.requiresUserInteraction === true) && pass.decision.action === "allow") [pass.decision, pass.tightenedBy] = [{ action: "ask", message: interactionSeat?.question ?? markTightenMessage(toolName, "interaction"), decisionReason: "safety" }, "safety"]; if (input.egress && pass.decision.action === "allow") { pass.decision = { action: "ask", message: markTightenMessage(toolName, "egress"), decisionReason: "safety", }; pass.tightenedBy = "safety"; } const alreadyAsking = pass.decision.action === "ask"; if ((pass.decision.action === "allow" || alreadyAsking) && (input.irreversibility === "always" || input.irreversibility === "maybe")) { let tighten = !alreadyAsking; const withdrawStationOffer = () => { if (alreadyAsking && pass.shellReadOffer === true && pass.decision.action === "ask" && pass.decision.probeReadRootCandidate !== undefined) { const { probeReadRootCandidate: _withdrawn, ...kept } = pass.decision; pass.decision = kept; } }; if (input.irreversibility === "always" || !input.reversibilityProbe) withdrawStationOffer(); let probeReason; let probeCause; let probeMandated; let probeReadRootCandidate; if (input.irreversibility === "maybe" && input.reversibilityProbe) { let reversible = false; const probeArgs = pass.policyRewrite !== undefined ? pass.policyRewrite : pass.currentInput; const probeTimeoutMs = boundedAwaitDeadlineMs(); try { const verdict = await withGateTimeout(Promise.resolve(input.reversibilityProbe(probeArgs)), probeTimeoutMs, input.abortSignal); reversible = verdict?.reversible === true; if (!reversible) { const raw = verdict?.reason; if (typeof raw === "string" && raw.trim().length > 0) probeReason = inlineUntrusted(raw, PROBE_REASON_MAX); probeCause = normalizeProbeCause(verdict?.cause); if (verdict?.mandated === true) probeMandated = true; if (verdict?.boundaryDeclined === true) pass.probeBoundaryDeclined = true; probeReadRootCandidate = normalizeReadRootCandidate(verdict?.readRootCandidate); withdrawStationOffer(); } } catch (err) { reversible = false; pass.probeUnanswered = true; withdrawStationOffer(); if (input.abortSignal?.aborted !== true) traceHookCrash(input, err, notifier); } tighten = !alreadyAsking && !reversible; } if (tighten) { pass.decision = { action: "ask", message: markTightenMessage(toolName, input.irreversibility === "always" ? "irreversible" : "unproven"), decisionReason: "safety", ...(probeReason !== undefined ? { probeReason } : {}), ...(probeCause !== undefined ? { probeCause } : {}), ...(probeMandated === true ? { probeMandated: true } : {}), ...(probeReadRootCandidate !== undefined ? { probeReadRootCandidate } : {}), }; pass.tightenedBy = input.shellGated === true ? "shell_gate" : "safety"; } else if (alreadyAsking && probeMandated === true && pass.decision.action === "ask") { pass.decision = withProbeMandate(pass.decision, probeReason); } } if (input.peerMessage === true && pass.decision.action === "allow" && input.autoMode !== undefined) { pass.decision = { action: "ask", message: `tool "${toolName}" sends a message to another agent — routed for classifier review in auto mode`, decisionReason: "safety", }; pass.tightenedBy = "safety"; } const writeProtectionStanding = pass.decision.action; if ((writeProtectionStanding === "allow" || writeProtectionStanding === "ask") && input.writeProtectionCheck !== undefined) { const check = input.writeProtectionCheck; const judgedArgs = pass.policyRewrite !== undefined ? pass.policyRewrite : pass.currentInput; const verdict = await awaitWriteProtectionJudgment((deadline) => check(toolName, judgedArgs, pass.req.face, input.trackedCwd?.(), deadline), boundedAwaitDeadlineMs, pass.callSignal ?? input.abortSignal, (err) => { const kind = gateWaitFailureOf(err); if (kind === "aborted" || input.abortSignal?.aborted === true) return; traceHookCrash(input, new Error(`write-protection judge ${kind === "timeout" ? "timed out" : "threw"} for tool "${toolName}" (toolCallId ${toolCallId}) — this call's write target could not be judged: ${thrownText(err)}`), notifier); }, input.confined !== undefined); if (verdict !== undefined && writeProtectionMandated(verdict)) pass[writeProtectionReachOf(verdict) === "spelling" ? "writeProtected" : "writeProtectedOnDisk"] = true; const decision = verdict === undefined ? undefined : writeProtectionTightenDecision(toolName, verdict); if (decision !== undefined && (writeProtectionStanding === "allow" || decision.action === "deny")) { pass.decision = decision; if (decision.action === "ask") pass.tightenedBy = "safety"; else pass.deniedBy = "write_protection"; } else if (decision?.action === "ask" && decision.message !== undefined && pass.decision.action === "ask") pass.decision = askWithTableSentence(pass.decision, decision.message, { toolCallId, toolName }); } const crossBoundary = pass.decision.action !== "deny" ? input.crossBoundaryCheck?.obligation({ toolName, args: pass.policyRewrite !== undefined ? pass.policyRewrite : pass.currentInput, toolCallId }) : undefined; if (crossBoundary?.mandate === true) { const marks = { requiresRealApproval: true, crossBoundaryMandated: true }; if (pass.decision.action === "ask") pass.decision = { ...pass.decision, ...marks }; else [pass.decision, pass.tightenedBy] = [{ action: "ask", message: crossBoundaryQuestion(toolName, crossBoundary.afterOffTargetRead), decisionReason: "safety", ...marks }, "safety"]; } if (pass.decision.action !== "deny" && input.leavesCommandSandbox?.(pass.policyRewrite !== undefined ? pass.policyRewrite : pass.currentInput) === true) { pass.leavesSandbox = true; if (pass.decision.action === "allow") [pass.decision, pass.tightenedBy] = [{ action: "ask", message: sandboxOverrideMessage(toolName), decisionReason: "safety" }, "safety"]; } const unstatedRuns = pass.policyRewrite !== undefined ? pass.policyRewrite : pass.currentInput; if (asksUnstated(pass.decision, pass.req, unstatedRuns, permissionSeatAt(input, unstatedRuns)?.seat, input.permissionMode?.(), input.a2aInsidePeer !== undefined)) { pass.decision = { action: "ask", message: permissionSeatAt(input, unstatedRuns)?.question ?? unstatedAskMessage(toolName), ...(pass.policyRewrite !== undefined ? { updatedInput: pass.policyRewrite } : {}) }; pass.tightenedBy = "unstated"; } return await pass.afterFold(pass); } function shellReadAskMessage(toolName, verdict) { const { verb, participle } = shellReadFaceWords(verdict.face); if (verdict.finding !== "outside_roots") return `tool "${toolName}" ${verb} where the session's read boundary could not establish what is ${participle} — explicit approval required`; return `tool "${toolName}" ${verb} outside the directories allowed for this session — explicit approval required`; } function applyShellReadVerdict(pass, answer, toolName, shellGated) { const reading = readStationAnswer(answer, { toolName, toolCallId: pass.toolCallId, report: (e) => traceHookCrash(pass.input, e, pass.notifier) }); applyStationDisposition(pass, reading, toolName, shellGated); if (reading.kind === "refuse") return; const written = reading.verdict.writeAskRule; const row = stationAskRowOf(reading.verdict, written !== undefined ? pass.input.permissionMode?.() : undefined); if (written !== undefined) pass.shellWriteAskRow = { rule: written, policy: reading.verdict.writeAskRuleOfPolicy === true, ownCard: row?.face === "write" && !(pass.decision.action === "ask" && pass.decision.matchedAskRule !== undefined) }; if (row !== undefined) pass.decision = applyPersistedTightening(pass.decision, { hit: { behavior: "ask", rules: [{ rule: row.rule }] } }, pass.req, row.policy ? "policy" : "persisted").decision; } function applyStationDisposition(pass, reading, toolName, shellGated) { const verdict = reading.verdict; const account = verdict.sentence !== undefined && verdict.sentence.trim().length > 0 ? inlineUntrustedAtWord(verdict.sentence, PROBE_REASON_MAX) : undefined; if (verdict.writesPlaced === true) pass.shellWritesPlaced = true; if (verdict.writeProtected === true) pass.writeProtected = true; if (verdict.writeProtectedOnDisk === true) pass.writeProtectedOnDisk = true; if (verdict.targetUnresolved === true) pass.targetUnresolved = true; if (verdict.unplacedOptions !== undefined) pass.shellUnplacedOptions = verdict.unplacedOptions; if (reading.kind === "silence" || verdict.finding === "unestablishable" || verdict.finding === "declined" || verdict.unestablished === true) pass.shellReadUnestablished = true; if (reading.kind === "refuse") { pass.decision = { action: "deny", message: verdict.sentence ?? `tool "${toolName}" reads what the session's read boundary refuses` }; pass.deniedBy = "read_boundary"; if (verdict.details !== undefined) pass.denyDetails = verdict.details; if (verdict.echoed !== undefined) pass.denyEchoed = verdict.echoed; return; } if (reading.kind === "silence") { applyUnansweredSilence(pass, verdict, { message: shellReadAskMessage(toolName, verdict), account, tightenedBy: shellGated ? "shell_gate" : "safety" }); return; } switch (reading.kind) { case "vouch": return; case "mandated": { if (verdict.details !== undefined) pass.shellReadDetails = verdict.details; if (pass.decision.action !== "allow") { if (pass.decision.action === "ask") pass.decision = silencedBy(withProbeMandate(pass.decision, account), verdict, pass.req, pass); return; } const candidate = normalizeReadRootCandidate(verdict.readRootCandidate); pass.decision = silencedBy({ action: "ask", message: shellReadAskMessage(toolName, verdict), decisionReason: "safety", probeMandated: true, ...(account !== undefined ? { probeReason: account } : {}), ...(candidate !== undefined ? { probeReadRootCandidate: candidate } : {}), }, verdict, pass.req, pass); if (candidate !== undefined) pass.shellReadOffer = true; pass.tightenedBy = shellGated ? "shell_gate" : "safety"; return; } case "ordinary": { verdict.admit?.(); if (verdict.details !== undefined) pass.shellReadDetails = verdict.details; const cause = verdict.cause !== undefined ? normalizeProbeCause(verdict.cause) : undefined; if (pass.decision.action === "ask") pass.decision = silencedBy(cause !== undefined && pass.decision.probeCause === undefined ? { ...pass.decision, probeCause: cause } : pass.decision, verdict, pass.req, pass); if (pass.decision.action === "allow") { const candidate = normalizeReadRootCandidate(verdict.readRootCandidate); pass.decision = silencedBy({ action: "ask", message: shellReadAskMessage(toolName, verdict), decisionReason: "safety", ...(account !== undefined ? { probeReason: account } : {}), ...(cause !== undefined ? { probeCause: cause } : {}), ...(candidate !== undefined ? { probeReadRootCandidate: candidate } : {}), }, verdict, pass.req, pass); if (candidate !== undefined) pass.shellReadOffer = true; pass.tightenedBy = shellGated ? "shell_gate" : "safety"; } if (verdict.finding === "declined" || verdict.finding === "unestablishable") pass.probeBoundaryDeclined = true; return; } default: { const exhaustive = reading.kind; return exhaustive; } } }