@sema-agent/core
Version:
Stateless, task-oriented AI agent core
357 lines (356 loc) • 19.8 kB
JavaScript
import { readSuspendTargetGap } from "./unavailable-landing.js";
import { argsAsTheToolReads, stampArgsReading } from "./effective-path-target.js";
import { answerAsShown, extensionAuthors, noteRewrite, readRejudge, rewriteChasedSentence, screeningAuthorship, shownDigestOf } from "./rewrite-rejudge.js";
import { decisionText, describeThrown, extensionQuestionText, foldHookAsk, isEngineRefusal, ownArgs, ownedReading, refuseOutOfContractDecision } from "./tool-policy.js";
import { createSettlementLedger, engineFailClosedExit, hookDenyExit, settledScreen, settledScreenExit, takeInheritedScreen, unownedArgsExit } from "./runner/gate-exit.js";
import { composeCallSignal } from "./runner/abort-race.js";
import { classicEventBase, dispatchClassic, ENGINE_CORE_ANSWER, failedHandlerClause, judgedInputOf, observePermissionDenied } from "./mods/stations.js";
import { runGateFold } from "./gate-fold.js";
import { runGateLanes } from "./gate-lanes.js";
export { normalizeOrgGateVerdict, normalizePersistedRuleHit } from "./rule-lane-reads.js";
import { hookAskReasonOf, isAskOrigin, receiveAskReasons, screenAskClassMembers } from "./ask-origin.js";
import { isAutoModeFallbackCause } from "./auto-mode.js";
import { inlineUntrusted } from "./untrusted-text.js";
import { approvalMessageOf } from "./approval-display.js";
import { askCardMessageOf, askHeadlineMember } from "./ask-headline.js";
export { formatHookFeedback } from "./reminder-mint.js";
import { createSafeNotifier } from "./safe-notify.js";
import { wireOf } from "./tool-name-readings.js";
import { readPermissionQuestion } from "./mode-policy.js";
const reflectApply = Reflect.apply;
const getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
const getPrototypeOf = Object.getPrototypeOf;
const objectPrototype = Object.prototype;
function findEnvSlot(env, key) {
for (let o = env; o !== null && o !== objectPrototype; o = getPrototypeOf(o)) {
const desc = getOwnPropertyDescriptor(o, key);
if (desc !== undefined)
return { holder: o, desc };
}
return undefined;
}
function readEnvPrimitive(env, key) {
const slot = findEnvSlot(env, key);
if (slot === undefined)
return undefined;
return slot.desc.get !== undefined ? reflectApply(slot.desc.get, env, []) : slot.desc.value;
}
function createCwdReader(env) {
const slot = findEnvSlot(env, "cwd");
if (slot === undefined)
return undefined;
const getter = slot.desc.get;
const initial = getter !== undefined ? reflectApply(getter, env, []) : slot.desc.value;
if (typeof initial !== "string")
return undefined;
let last = initial;
return () => {
const desc = getOwnPropertyDescriptor(slot.holder, "cwd");
const value = desc === undefined
? undefined
: desc.get !== undefined
? desc.get === getter
? reflectApply(desc.get, env, [])
: undefined
: desc.value;
if (typeof value === "string")
last = value;
return last;
};
}
export function createHookEnvCapabilities(env) {
const face = Object.create(null);
const canonicalPath = readEnvPrimitive(env, "canonicalPath");
const exists = readEnvPrimitive(env, "exists");
const readLink = readEnvPrimitive(env, "readLink");
const cwd = createCwdReader(env);
if (typeof canonicalPath === "function") {
face.canonicalPath = (path, abortSignal) => reflectApply(canonicalPath, env, [path, abortSignal]);
}
if (typeof exists === "function") {
face.exists = (path, abortSignal) => reflectApply(exists, env, [path, abortSignal]);
}
if (typeof readLink === "function") {
face.readLink = (path, abortSignal) => reflectApply(readLink, env, [path, abortSignal]);
}
if (cwd !== undefined) {
face.cwd = cwd;
}
return Object.freeze(face);
}
const IDENTITY_AGENT_NAME_MAX = 80;
export function mintHookInvocationIdentity(facts) {
return Object.freeze(Object.assign(Object.create(null), {
sessionId: facts.sessionId,
...(facts.rootSessionId !== undefined ? { rootSessionId: facts.rootSessionId } : {}),
taskId: facts.taskId,
legKind: facts.legKind,
isDelegatedChild: facts.isDelegatedChild,
...(facts.insideFork === true ? { insideFork: true } : {}),
...(facts.agentName !== undefined ? { agentName: inlineUntrusted(facts.agentName.slice(0, 320), IDENTITY_AGENT_NAME_MAX) } : {}),
...(facts.spawnName !== undefined ? { spawnName: inlineUntrusted(facts.spawnName.slice(0, 320), IDENTITY_AGENT_NAME_MAX) } : {}),
...(facts.agentType !== undefined ? { agentType: inlineUntrusted(facts.agentType.slice(0, 320), IDENTITY_AGENT_NAME_MAX) } : {}),
...(facts.parentToolCallId !== undefined ? { parentToolCallId: facts.parentToolCallId } : {}),
}));
}
function screenPreToolUseResult(r) {
if (r === undefined || r === null || r === false)
return r;
return refuseOutOfContractDecision(r, { reasonIsNonInput: true });
}
function preToolUseAnswerViolation(answer) {
const r = screenPreToolUseResult(answer);
if (r === undefined || r === null || r === false || !isEngineRefusal(r))
return undefined;
return typeof r.message === "string" ? r.message : "the PreToolUse answer was refused by the engine";
}
const PRE_TOOL_USE_RANKS = Object.freeze({ of: (a) => { const r = a === ENGINE_CORE_ANSWER ? undefined : screenPreToolUseResult(a); return !r ? 0 : r.action === "deny" ? 3 : r.action === "ask" ? (r.requiresRealApproval === true ? 2 : 1) : 0; }, top: 3 });
function preToolUseRefusedReason(subject, failed) {
if (failed === undefined) {
return `the task was cancelled while a PreToolUse hook was still screening ${subject}; the call was NOT executed ` + `(fail-closed). No verdict was reached — this is the run ending, not the tool failing.`;
}
const tail = failed.cause === "threw"
? ` This is a failure of the deployment's hook, NOT of the tool itself — an identical retry reaches the same hook and fails the same way.`
: failed.cause === "timeout"
? ` This is a failure of the deployment's hook, NOT of the tool itself — the screening face never returned a verdict, so nothing was decided about this call either way.`
: "";
return `a PreToolUse hook ${failedHandlerClause(failed)} while screening ${subject}; the call was NOT executed (fail-closed).${tail}`;
}
function hookAskOf(r, answeredBy, toolName) {
const { questionCause, ...ask } = r;
const entry = hookAskReasonOf(answeredBy, questionCause ?? "asked", decisionText(ask));
return { ...ask, ...(answeredBy !== undefined ? { message: extensionQuestionText(toolName, entry) } : {}), askReasons: Object.freeze([entry]) };
}
export function createPreToolUseScreening(input, readSettled = (decision) => ({ decision })) {
const own = input.modBus !== undefined && input.modBus.hasHandlers("classic.PreToolUse") ? input.modBus : undefined;
const inherited = (input.inheritedInstallations ?? []).filter((i) => i.bus.hasHandlers("classic.PreToolUse", i.judges));
if (own === undefined && inherited.length === 0)
return undefined;
const { toolCallId, toolName } = input.event;
const screenedName = wireOf("gate.preToolUse", input.event);
const eventOf = (args, env) => {
const cwd = input.trackedCwd?.();
return {
...classicEventBase(input.identity, input.observedPermissionMode?.()),
tool: screenedName,
tool_use_id: toolCallId,
input: judgedInputOf(args),
...(typeof cwd === "string" ? { cwd } : {}),
...(env !== undefined ? { env } : {}),
};
};
const raise = async (bus, participant, env, args, subject, readAs, signal) => {
let outcome;
const authorship = screeningAuthorship(readAs);
try {
outcome = await dispatchClassic(bus, "classic.PreToolUse", eventOf(args, env), { ...(signal !== undefined ? { signal } : {}), ...(participant !== undefined ? { participant } : {}), checkAnswer: (a, e, by, below) => preToolUseAnswerViolation(a) ?? authorship.record(a, e, by, below), ranks: PRE_TOOL_USE_RANKS });
}
catch (err) {
return { kind: "refused", reason: preToolUseRefusedReason(subject, { kind: "failed", registration: "engine", cause: "threw", reason: `could not raise the screening: ${describeThrown(err)}`, skipped: [] }) };
}
if (outcome === undefined || outcome.kind === "aborted")
return { kind: "refused", reason: preToolUseRefusedReason(subject, undefined) };
if (outcome.kind === "failed")
return { kind: "refused", reason: preToolUseRefusedReason(subject, outcome), extension: outcome.registration };
const r = screenPreToolUseResult(outcome.answer);
const answer = r === null || r === false || r === undefined ? undefined : r.action === "ask" ? hookAskOf(r, outcome.answeredBy, toolName) : r;
const rewrittenBy = authorship.of(outcome.answer);
return { kind: "answered", answer, ...(outcome.answeredBy !== undefined ? { answeredBy: outcome.answeredBy } : {}), rewrittenBy: answer?.updatedInput === undefined ? [] : rewrittenBy.length > 0 || outcome.answeredBy === undefined ? rewrittenBy : [outcome.answeredBy] };
};
const seats = [
...(own !== undefined ? [{ look: ((args, subject, readAs, signal) => raise(own, undefined, input.hookEnv, args, subject, readAs, signal)) }] : []),
...inherited.map((installation) => ({ installation, look: ((args, subject, readAs, signal) => raise(installation.bus, installation.judges, installation.env, args, subject, readAs, signal)) })),
];
const deniedReason = (answer) => decisionText(answer) ?? `tool "${toolName}" blocked by a PreToolUse hook`;
const run = async (args, subject, readAs) => {
const as = readAs ?? {};
const signal = input.abortSignal !== undefined ? composeCallSignal(input.abortSignal, input.callSignal) : input.callSignal;
let bytes = args;
let form;
const authors = [];
const contexts = [];
let ownAnswer;
let ownBy;
const allowedBy = new Map();
const floated = new Map();
const answered = (answer, answeredBy, approved) => {
const shown = form !== undefined && answer?.action !== "deny" ? { ...answer, updatedInput: form.raw } : answer;
const asks = [...floated.values()];
return {
kind: "answered",
answer: shown,
...(answeredBy !== undefined ? { answeredBy } : {}),
...(form !== undefined && answer?.action !== "deny" ? { rewrittenBy: authors } : {}),
contexts,
...(inherited.length > 0 ? { inherited: { allowedBy: [...allowedBy.values()], ...(asks.length > 0 ? { floated: asks.reduce((a, b) => foldHookAsk(a, b)) } : {}), ...(approved !== undefined ? { approved } : {}) } } : {}),
};
};
const judgedOf = () => (bytes !== args ? { judged: bytes } : {});
const lookAt = async (i, second) => {
const seat = seats[i];
const r = await seat.look(bytes, subject, as, signal);
if (r.kind === "refused")
return { ...r, ...judgedOf() };
const a = r.answer;
if (a?.additionalContext)
contexts.push(a.additionalContext);
if (a?.action === "deny")
return { ...answered(a, r.answeredBy), ...judgedOf() };
const read = readRejudge(as, bytes, a);
if (second && read.kind === "rewritten")
return { kind: "refused", reason: rewriteChasedSentence(toolName), ...judgedOf() };
if (a?.updatedInput !== undefined) {
form = { raw: a.updatedInput };
authors.push(...r.rewrittenBy.filter((by) => !authors.includes(by)));
}
if (read.kind === "rewritten") {
bytes = read.form;
for (let j = 0; j < i; j++) {
const ended = await lookAt(j, true);
if (ended !== undefined)
return ended;
}
}
const verdict = a === undefined ? undefined : (({ updatedInput: _form, ...v }) => v)(a);
if (seat.installation === undefined) {
ownAnswer = verdict;
ownBy = r.answeredBy;
return undefined;
}
allowedBy.delete(i);
floated.delete(i);
const call = Object.freeze({ toolName, toolCallId, args: bytes, ...(as.face !== undefined ? { face: as.face } : {}) });
const standing = verdict?.action !== "ask" ? seat.installation.standing?.(call) : undefined;
if (standing !== undefined)
floated.set(i, standing);
else if (verdict?.action === "allow" && r.answeredBy !== undefined)
allowedBy.set(i, r.answeredBy);
if (verdict?.action !== "ask")
return undefined;
const ask = { action: "ask", message: decisionText(verdict) ?? `approval required for "${toolName}" (an inherited PreToolUse hook)`, decisionReason: "hook", ...(verdict.requiresRealApproval === true ? { requiresRealApproval: true } : {}), ...(verdict.askReasons !== undefined ? { askReasons: verdict.askReasons } : {}) };
const settled = readSettled(answerAsShown(shownDigestOf(call), await seat.installation.settle(ask, call, signal), call));
if (settled.decision.action === "deny")
return settledScreen(settled, judgedOf());
if (settled.decision.action === "allow" && settled.decision.updatedInput !== undefined)
return answered(ownAnswer, ownBy, { ...settled.decision, updatedInput: settled.decision.updatedInput });
if (settled.decision.action === "ask")
floated.set(i, settled.decision);
return undefined;
};
for (let i = 0; i < seats.length; i++) {
const ended = await lookAt(i, false);
if (ended !== undefined)
return ended;
}
return answered(ownAnswer, ownBy);
};
const { whileScreened } = input;
return {
screen: (args, subject, readAs) => (whileScreened === undefined ? run(args, subject, readAs) : whileScreened(toolCallId, () => run(args, subject, readAs))),
deniedReason,
};
}
export function askCarryRowMembers(carry, say) {
if (carry === undefined)
return {};
const origin = carry.origin;
const why = carry.classifierNoRuling;
const classed = screenAskClassMembers(carry.askClass, carry.classes);
const askReasons = receiveAskReasons(carry.askReasons);
const asked = carry.cardMessage, cardMessage = approvalMessageOf(typeof asked === "string" ? askCardMessageOf(asked, classed?.askClass, classed?.classes) : asked);
const rule = carry.cardAskRule;
return {
...(carry.denialLimitFallback !== undefined ? { denialLimitFallback: { ...carry.denialLimitFallback } } : {}),
...(isAutoModeFallbackCause(why) ? { classifierNoRuling: why } : {}),
...(isAskOrigin(origin) ? { origin } : {}),
...(classed !== undefined ? classed : {}),
...(askReasons !== undefined ? { askReasons } : {}),
...(cardMessage !== undefined ? { cardMessage } : {}),
...(typeof rule === "string" && rule.length > 0 ? { cardAskRule: rule } : {}),
...(carry.fromApprovalList === true ? { fromApprovalList: true } : {}),
...askHeadlineMember(classed?.askClass, say, classed?.classes),
};
}
export async function runToolGate(input) {
const { event, adjudicate, resolveAsk, suspendAsk } = input;
const { toolCallId, toolName } = event;
const callSignal = input.callSignal;
const suspendTargetGap = readSuspendTargetGap(input.suspendTargetGap);
readPermissionQuestion(input.permissionQuestion);
const modelInput = event.input;
const owned = ownArgs(modelInput);
const args = owned.ok ? owned.value : modelInput;
const notifier = createSafeNotifier(input.onNotifyError !== undefined ? { onError: input.onNotifyError } : undefined);
const notifyPermissionDeniedSeat = (payload) => {
const mode = input.observedPermissionMode?.();
const seen = mode !== undefined ? { ...payload, permissionMode: mode } : payload;
const onHostObserverFailure = (err) => void notifier.notify(() => { throw err; }, "toolGate.permissionDenied");
const host = input.permissionDenied;
return observePermissionDenied({ legBus: input.modBus, ...(host !== undefined ? { host: { observe: host, onFailure: onHostObserverFailure } } : {}), payload: seen, signal: input.abortSignal });
};
const ledger = createSettlementLedger({ toolCallId, toolName });
const screening = createPreToolUseScreening(input, (settled) => {
const read = ledger.fromDecision(settled);
const cause = ledger.causeOf(read.decision);
return { ...read, ...(cause !== undefined ? { cause } : {}) };
});
const pass = {
input,
event,
adjudicate,
resolveAsk,
suspendAsk,
toolName,
toolCallId,
callSignal,
notifier,
ledger,
notifyPermissionDenied: notifyPermissionDeniedSeat,
screening,
afterFold: runGateLanes,
currentInput: args,
rewrites: { entry: args, by: [] },
req: Object.freeze({ toolName, args, toolCallId, ...(() => { const f = input.toolFaceOf?.(toolName); const read = event.readArguments; if (f !== undefined && read !== undefined)
stampArgsReading(f, ownedReading(read)); return f !== undefined ? { face: f } : {}; })() }),
preToolContext: [],
hookAsk: undefined,
parkFailed: undefined,
suspendTargetGap,
deniedBy: undefined,
denyCause: undefined,
decision: { action: "allow" },
tightenedBy: undefined,
policyRewrite: undefined,
};
if (!owned.ok)
return await unownedArgsExit(pass, owned.reason);
if (screening !== undefined) {
const screened = await screening.screen(pass.currentInput, `this call to "${toolName}"`, pass.req);
if ((screened.kind !== "answered" || screened.answer?.action === "deny") && screened.judged !== undefined)
pass.currentInput = screened.judged;
if (screened.kind === "refused") {
return await engineFailClosedExit(pass, screened.reason, screened.extension);
}
if (screened.kind === "settled")
return await settledScreenExit(pass, screened);
pass.preToolContext.push(...screened.contexts);
const r = screened.answer;
if (r) {
if (r.action === "deny") {
return hookDenyExit(pass, screening.deniedReason(r), screened.answeredBy);
}
if (r.updatedInput !== undefined) {
const rewritten = argsAsTheToolReads(pass.req, r.updatedInput);
noteRewrite(pass.rewrites, pass.req, pass.currentInput, rewritten, extensionAuthors(screened.rewrittenBy ?? []));
pass.currentInput = rewritten;
}
if (r.action === "ask") {
pass.hookAsk = r;
}
if (r.action === "allow")
pass.hookAllowedBy = screened.answeredBy !== undefined ? [screened.answeredBy] : [];
}
takeInheritedScreen(pass, screened.inherited);
}
return await runGateFold(pass);
}