@sema-agent/core
Version:
Stateless, task-oriented AI agent core
165 lines (164 loc) • 12.8 kB
JavaScript
import { askFallbackMessage, cardDisclosureOf } from "../allow-entry.js";
import { APPROVAL_DISPLAY_MAX_CHARS, sanitizeApprovalDisplay } from "../approval-display.js";
import { primaryActivityArg } from "../arg-summary.js";
import { observePermissionDenied } from "../mods/stations.js";
import { notResumableRefusal } from "../park-resumability.js";
import { callFactsSeat, attest, attestationOf, isAnsweringSeat, resolveAskFor } from "../tool-policy.js";
import { exactBoundInputHashOf } from "../canonical-json.js";
import { rowDeciderOf } from "../gate-outcome.js";
import { mintCheckpointId } from "../checkpoint-store.js";
import { deferredAskOf, markBinds, movedClause } from "./deferred-ask.js";
import { composeCallSignal, raceSettlementAgainstSignal } from "./abort-race.js";
import { failedJudgmentDeny, policyCheckAbortedDeny } from "./policy-throw.js";
import { askMandateMember, withFoldedOf } from "../ask-origin.js";
import { approvalCardMemberOf, survivorsByName } from "../tool-roster.js";
import { cardTargetFor, readsCardTarget } from "../existing-target.js";
import { toolNameIndex } from "../../internal/llm.js";
import { requestGrantBinding } from "../skill-grant-binding.js";
import { gateAskCarry, gateAskClassPair, lateAskSettlementObserver } from "./denial-limit-arms.js";
import { approverDefectAnnouncer } from "./approver-defect-announcer.js";
import { consumeInheritedAskGrant } from "./inherited-ask-grants.js";
import { requesterOf } from "../mods/extension-call.js";
import { settleReadRootGrant } from "./read-root-grant.js";
import { settleUnofferedSessionCallGrant } from "./session-call-grant-station.js";
function createDenyObserverNotifier(bus, signal) {
if (bus === undefined || !bus.hasHandlers("classic.PermissionDenied"))
return undefined;
return (payload) => observePermissionDenied({ legBus: bus, payload, signal });
}
function resolveApprovalPreview(tools, toolName, args) {
const t = toolNameIndex([...survivorsByName(tools).values()])(toolName);
if (t?.approvalPreview === undefined)
return {};
try {
const raw = t.approvalPreview(args);
if (raw === undefined)
return {};
const bytes = JSON.stringify(raw);
if (bytes === undefined)
return { withheld: "unavailable" };
if (bytes.length > APPROVAL_DISPLAY_MAX_CHARS) {
return { preview: { truncated: true, note: `approval preview exceeded 16KiB (${bytes.length} chars serialized)` }, withheld: "oversize" };
}
return { preview: sanitizeApprovalDisplay(raw) };
}
catch {
return { withheld: "unavailable" };
}
}
export function prepareAskLane(input) {
const { destinationOf, gateMachineryActive, abortController, effectivePolicy, budgetSnapshot, handsCwdRef, handsRoot, stampCallTarget, advertisedWritableDirs, exemptRoots, tools, inheritedUnavailableAsks, deferredAskIdentities, inheritedAskGrants, onAsk, humanReviewRef, now, ruleOffersOf, grantBindingOf, askSource, riskAxesOf, commandSandboxSideOf, autoModeDenialTracking, hostTaskId, deps, sessionId, runId, grantReadRoot, approvalWords, modBus, notifyOwnHookCrash, toolRosterDeltas, existingTargetSeat, forcedGateNotResumable, engineText, sessionCallGrants, managerStation } = input;
if (!gateMachineryActive)
return { askLane: undefined };
const composedCallSignal = (callSignal) => composeCallSignal(abortController.signal, callSignal);
const adjudicate = effectivePolicy
? async (req, callSignal) => {
const signal = composedCallSignal(callSignal);
const stampedReq = () => ({ ...req, ...callFactsSeat({ budget: budgetSnapshot, cwd: handsCwdRef?.current, root: handsRoot, advertisedWritableDirs, exemptRoots }), ...requestGrantBinding(grantBindingOf, req, req.args) });
const judged = (async () => {
const withReading = stampCallTarget?.(stampedReq(), signal);
return withReading === undefined ? effectivePolicy.check(stampedReq(), signal) : effectivePolicy.check(await withReading, signal);
})();
const raced = await raceSettlementAgainstSignal(judged, signal);
if (raced.tag === "value")
return raced.value;
if (raced.tag === "aborted")
return policyCheckAbortedDeny();
return failedJudgmentDeny(raced.error, undefined, notifyOwnHookCrash, "the tool policy chain", req);
}
: undefined;
const approvalPreviewOf = (toolName, args) => resolveApprovalPreview(tools, toolName, args);
const resolveAskBound = async (decision, req, callSignal) => {
const marks = inheritedUnavailableAsks.get(req.toolCallId);
if (marks !== undefined && inheritedUnavailableAsks.delete(req.toolCallId)) {
const moved = [...marks.values()].some((m) => !markBinds(m, req, req.args)), windowed = [...marks.values()].every((m) => m.windowExpired === true);
const intercepted = {
action: "deny",
message: `approval for "${req.toolName}" requires an ancestor task's approval that ${windowed ? "was not answered within the deployment's approval window" : "cannot be resolved here "}` +
`${windowed ? "" : "(no live approver reachable, or a durable-park mandate applies)"}${moved ? ` — ${movedClause(req.toolName)} —` : ","} and no durable approval park is ` +
`available — denied fail-closed (the inherited constraint stands).`,
decisionReason: "mode",
approverUnavailable: true,
};
const settlement = windowed ? { kind: "approval_window_expired", who: { party: "host" }, when: now() } : { kind: "approver_unavailable", who: { party: "none" }, when: now() }, cause = windowed ? { unresolvableCause: "approval_window_expired" } : {};
return decision.action === "ask"
? attest(intercepted, req, { settlement, ...cause, ...(decision.origin !== undefined ? { origin: decision.origin } : {}), ...(decision.classes !== undefined ? { classes: decision.classes } : {}), inputDigest: exactBoundInputHashOf(req.toolName, req.args) })
: attest(intercepted, req, { settlement, ...cause, inputDigest: exactBoundInputHashOf(req.toolName, req.args) });
}
if (forcedGateNotResumable) {
const message = notResumableRefusal(`approval for "${req.toolName}" is mandated to wait durably for this principal (forceDurableGate)`, forcedGateNotResumable);
const members = { settlement: { kind: "no_approver", who: { party: "none" }, when: now() }, unresolvableCause: "mandate_unreconstructible", inputDigest: exactBoundInputHashOf(req.toolName, req.args) };
const asked = decision.action === "ask" ? { ...(decision.origin !== undefined ? { origin: decision.origin } : {}), ...(decision.classes !== undefined ? { classes: decision.classes } : {}) } : {};
return attest({ action: "deny", message, decisionReason: "mode" }, req, { ...members, ...asked });
}
const grantReuse = consumeInheritedAskGrant(inheritedAskGrants, onAsk, humanReviewRef, decision, req);
if (grantReuse !== undefined)
return grantReuse;
const managed = managerStation !== undefined ? await managerStation(decision, req, callSignal) : undefined;
if (managed !== undefined)
return managed;
const personSeesCard = readsCardTarget(onAsk, decision.action === "ask" ? gateAskClassPair(decision).classes : undefined);
const existingTarget = await cardTargetFor(existingTargetSeat, toolRosterDeltas.current, req, req.args, personSeesCard, composedCallSignal(callSignal));
const offerFacts = decision.action === "ask" ? withFoldedOf(decision, attestationOf(decision, req)) : undefined;
const callGrant = sessionCallGrants !== undefined && personSeesCard && sessionCallGrants.door(req, req.args, offerFacts) ? await sessionCallGrants.station.mint(req.args?.command, req, composedCallSignal(callSignal)) : undefined;
const t0 = now();
const checkpointId = mintCheckpointId();
const resolved = await resolveAskFor({
toolName: req.toolName,
toolCallId: req.toolCallId,
checkpointId,
args: req.args,
...(() => {
const p = approvalPreviewOf(req.toolName, req.args);
return { ...(p.preview !== undefined ? { preview: p.preview } : {}), ...(p.withheld !== undefined ? { previewWithheld: p.withheld } : {}) };
})(),
...existingTarget,
...ruleOffersOf(req, req.args, offerFacts),
...(callGrant !== undefined ? { sessionCallGrant: callGrant.offer } : {}),
...grantBindingOf(req, req.args),
...cardDisclosureOf(decision, askFallbackMessage(req.toolName)),
...askSource,
...riskAxesOf(req),
...commandSandboxSideOf(req, req.args),
...destinationOf(req.toolName),
...approvalCardMemberOf(req),
...requesterOf(modBus, req.toolCallId),
...(decision.action === "ask" && decision.requiresRealApproval === true ? { requiresRealApproval: true } : {}),
...(decision.action === "ask" ? askMandateMember(decision) : {}),
...(decision.action === "ask" ? gateAskCarry(decision, isAnsweringSeat(onAsk), autoModeDenialTracking.current) : {}),
...(decision.action === "ask" && decision.probeReason !== undefined ? { probeReason: decision.probeReason } : {}),
...(decision.action === "ask" && decision.probeCause !== undefined ? { probeCause: decision.probeCause } : {}),
...(decision.action === "ask" && decision.probeReadRootCandidate !== undefined ? { readRootCandidate: { ...decision.probeReadRootCandidate, lasts: grantReadRoot?.lastsFor(decision.probeReadRootCandidate) ?? "run" } } : {}),
...(decision.action === "ask" && decision.ruleEvidence !== undefined ? { ruleEvidence: decision.ruleEvidence } : {}),
}, onAsk, composedCallSignal(callSignal), lateAskSettlementObserver({ toolName: req.toolName, toolCallId: req.toolCallId, sessionId, runId, taskId: hostTaskId, onNotice: deps.onNotice, onError: deps.onError }), decision, approverDefectAnnouncer({ toolName: req.toolName, toolCallId: req.toolCallId, sessionId, runId, taskId: hostTaskId, onNotice: deps.onNotice }), approvalWords, engineText, req.ifUnavailable);
const waitMs = Math.max(0, now() - t0);
const cardHash = resolved.readRootGrant?.verdict === "granted" && resolved.readRootGrant.lasts === "session" ? exactBoundInputHashOf(req.toolName, req.args) : undefined;
const granting = settleReadRootGrant(resolved.readRootGrant, grantReadRoot, { toolName: req.toolName, toolCallId: req.toolCallId, checkpointId, sessionId, runId, taskId: hostTaskId, onNotice: deps.onNotice, signal: composedCallSignal(callSignal), ...(cardHash !== undefined ? { boundInputHash: cardHash } : {}) });
if (granting !== undefined)
await granting;
const callAt = { toolName: req.toolName, toolCallId: req.toolCallId, checkpointId, sessionId, runId, taskId: hostTaskId, onNotice: deps.onNotice, signal: composedCallSignal(callSignal) };
const keeping = sessionCallGrants !== undefined ? sessionCallGrants.station.settle(resolved.sessionCallGrant, callGrant, callAt) : settleUnofferedSessionCallGrant(resolved.sessionCallGrant, callAt);
if (keeping !== undefined)
await keeping;
const deferred = deferredAskOf(resolved, req, checkpointId);
if (deferred !== undefined)
deferredAskIdentities.set(req.toolCallId, deferred);
const settlement = attestationOf(resolved, req)?.settlement;
if (settlement?.who.party !== "none" && resolved.approverUnavailable !== true) {
humanReviewRef.count += 1;
humanReviewRef.totalWaitMs += waitMs;
const toolArg = primaryActivityArg(req, req.args);
humanReviewRef.gates.push({
kind: "human",
waitMs,
decision: resolved.action === "allow" ? "allow" : "deny",
toolName: req.toolName,
toolCallId: req.toolCallId,
...(toolArg !== undefined ? { toolArg } : {}), ...rowDeciderOf(settlement),
});
}
return resolved;
};
const notifyPermissionDenied = createDenyObserverNotifier(modBus, abortController.signal);
return { askLane: { composedCallSignal, adjudicate, approvalPreviewOf, resolveAskBound, notifyPermissionDenied, notifyHookError: notifyOwnHookCrash } };
}