@sema-agent/core
Version:
Stateless, task-oriented AI agent core
379 lines (378 loc) • 20.1 kB
JavaScript
import { describeRejectedValue } from "./tool-search-setting.js";
import { createFsWriteGatePolicy } from "./fs-write-gate-policy.js";
import { isProtectedWrite } from "./tool-registry.js";
import { answeredFor } from "./tool-policy.js";
import { attest } from "./engine-attestation.js";
import { rosterEntryNamed, toolCallFaceOf } from "./tool-roster.js";
import { wireOf } from "./tool-name-readings.js";
import { clampPermissionMode, isPermissionMode, PERMISSION_MODES } from "./ask-origin.js";
import { SHELL_LEX_DIALECT, argvOf, lexShellText } from "../shell/lex.js";
import { COMMAND_RULE_TOOL } from "./permission-rule-model.js";
import { createSafeNotifier } from "./safe-notify.js";
import { CheckpointError, isCheckpointConfigRefusalCode } from "./checkpoint-features.js";
import { configInputOfRefusal, enterConfigDoor, refusalAbout } from "./config-refusal-input.js";
import { approvalRequestsPlanExit } from "./plan-review-facts.js";
import { markTightenMessage } from "./safety-axis-vocab.js";
export const PERMISSION_MODE_FOLD_REASONS = Object.freeze(["operator_deny", "face_absent", "inherited_ceiling"]);
export const ACCEPT_EDITS_FILE_COMMANDS = Object.freeze(["mkdir", "touch", "rm", "rmdir", "mv", "cp", "sed"]);
const MODE_POLICY_TABLE = {
plan: { enablePlanMode: true, writeGate: "plan", fileCommands: [], writeFace: undefined, unstated: "ask" },
acceptEdits: { enablePlanMode: false, writeGate: "accept_root", fileCommands: ACCEPT_EDITS_FILE_COMMANDS, writeFace: undefined, unstated: "ask" },
default: { enablePlanMode: false, writeGate: "ask", fileCommands: [], writeFace: undefined, unstated: "ask" },
auto: { enablePlanMode: false, writeGate: "ask", fileCommands: [], writeFace: undefined, unstated: "ask" },
dontAsk: { enablePlanMode: false, writeGate: "ask", fileCommands: [], writeFace: undefined, unstated: "ask" },
bypassPermissions: { enablePlanMode: false, writeGate: "none", fileCommands: [], writeFace: "open", unstated: "none" },
};
export function modePolicyOf(mode) {
return MODE_POLICY_TABLE[mode];
}
export function withModeSeats(spec, mode) {
return modePolicyOf(mode).enablePlanMode && spec.enablePlanMode !== true ? { ...spec, enablePlanMode: true } : spec;
}
export function modeAcceptsFileCommand(mode, toolName, args) {
return modeAcceptsFileCommandIn(SHELL_LEX_DIALECT, mode, toolName, args);
}
export function modeAcceptsFileCommandIn(shell, mode, toolName, args) {
const commands = modePolicyOf(mode).fileCommands;
if (commands.length === 0 || toolName !== COMMAND_RULE_TOOL)
return false;
const command = args?.command;
if (typeof command !== "string" || args.run_in_background === true)
return false;
const lexed = lexShellText(shell, command);
if ("reject" in lexed || lexed.segments.length === 0 || lexed.substitutions.length > 0)
return false;
return lexed.segments.every((segment) => {
if (segment.connector === "|" || segment.connector === "&" || segment.tokens.some((t) => t.kind !== "word"))
return false;
const head = argvOf(segment)[0];
return head !== undefined && head.assignment === undefined && head.expansions.length === 0 && head.raw === head.folded && commands.includes(head.raw);
});
}
export function mountedToolDeclaresReadOnly(tools, toolName) {
return tools.findLast((t) => t.name === toolName)?.mcpReadOnlyHint === true;
}
export function asksUnstated(d, call, runs, seat, mode, insidePeer) {
return d.action === "allow" && seat === "passthrough" && mode !== undefined && (modePolicyOf(mode).unstated === "ask" || insidePeer) && !answeredFor(d, call, runs);
}
export const unstatedAskMessage = (toolName) => `The agent requested permission to use ${toolName}, but it has not been granted yet.`;
export function permissionSeatAt(input, args) {
if (input.permissionSeatOf !== undefined)
return input.permissionSeatOf(args);
return input.permissionSeat === "passthrough" ? { seat: "passthrough", ...(input.permissionQuestion !== undefined ? { question: input.permissionQuestion } : {}) } : undefined;
}
export function seatInputsOfCall(inputs, continuationCall) {
if (!continuationCall)
return inputs;
const { permissionSeat: _seat, permissionQuestion: _question, permissionSeatOf: _reader, ...rest } = inputs;
return rest;
}
export function editInteractionTighten(decision, input, editArgs, answered, toolName) {
const edited = decision.action === "allow" ? permissionSeatAt(input, editArgs) : undefined;
if (edited?.requiresUserInteraction !== true)
return decision;
const shown = answered === undefined ? undefined : permissionSeatAt(input, answered.bytes);
if (shown?.requiresUserInteraction === true && shown.question === edited.question)
return decision;
return { action: "ask", message: edited.question ?? markTightenMessage(toolName, "interaction"), decisionReason: "safety" };
}
export function mountedToolPermissionSeat(tools, toolName) {
return tools.findLast((t) => t.name === toolName)?.permissionSeat === "passthrough" ? "passthrough" : undefined;
}
export function mountedToolPermissionQuestion(tools, toolName) {
return tools.findLast((t) => t.name === toolName)?.permissionQuestion;
}
export function readPermissionQuestion(value) {
if (value === undefined)
return undefined;
if (typeof value === "string" && value.trim().length > 0)
return value;
const got = typeof value === "string" ? "a string with no visible character" : value === null ? "null" : `a value of type ${typeof value}`;
throw Object.assign(new Error(`runToolGate: ToolGateInput.permissionQuestion is the sentence a passthrough seat puts — a string with a visible character, or absent (got ${got})`), { code: "config.invalid_argument" });
}
export function mountedToolRequiresUserInteraction(tools, toolName) {
return tools.findLast((t) => t.name === toolName)?.mcpRequiresUserInteraction === true;
}
const ENGINE_ROSTER_SOURCES = new Set(["builtin", "synthetic"]);
export function planRefusesWrite(req, roster, readOnlyDeclared) {
if (isProtectedWrite(req))
return true;
const row = roster === undefined ? undefined : rosterEntryNamed(roster, wireOf("mode.planRosterRow", req));
return row !== undefined && !ENGINE_ROSTER_SOURCES.has(row.source) && row.effect !== "read" && !(row.effectProvenance === "default" && readOnlyDeclared?.(row.name) === true);
}
export function modeQuestionReaches(mode, roster, toolName, seat) {
const policy = modePolicyOf(mode);
if (policy.unstated === "ask" && seat === "passthrough")
return true;
if (policy.writeGate === "none")
return false;
const face = toolCallFaceOf(roster, toolName);
const call = { toolName, args: {}, toolCallId: "", ...(face !== undefined ? { face } : {}) };
return policy.writeGate === "plan" ? planRefusesWrite(call, roster) : isProtectedWrite(call);
}
const planAsk = (message, call, generic) => {
const asked = { action: "ask", message, decisionReason: "mode" };
return generic !== undefined ? attest(asked, call, { sentence: { text: message, generic: true, ...generic } }) : asked;
};
export function acceptEditsWriteGate(seats) {
const acceptSeat = seats.acceptDirs;
const acceptDirs = typeof acceptSeat === "function" ? acceptSeat : acceptSeat !== undefined && acceptSeat.length > 0 ? [...acceptSeat] : [seats.rootPath];
return createFsWriteGatePolicy({ env: seats.env, rootPath: seats.rootPath, acceptDirs, defaultWrite: "ask" });
}
export function createModeGatePolicy(modeRef, seats) {
const askGate = createFsWriteGatePolicy({ env: seats.env, rootPath: seats.rootPath, defaultWrite: "ask" });
const acceptRootGate = acceptEditsWriteGate(seats);
const planGate = createFsWriteGatePolicy({ env: seats.env, rootPath: seats.rootPath, defaultWrite: "ask", defaultAsk: (path, note, call) => planAsk(`Cannot write to ${path} while in plan mode.${note ?? ""}`, call, note === undefined ? { echoed: [Object.freeze({ kind: "path", value: path })] } : undefined) });
return {
async check(req, signal) {
const gate = modePolicyOf(modeRef.current).writeGate;
if (gate === "none")
return { action: "allow" };
if (gate === "plan") {
if (!planRefusesWrite(req, seats.roster?.current, seats.readOnlyDeclared))
return { action: "allow" };
if (!isProtectedWrite(req))
return planAsk(`Cannot call ${req.toolName} while in plan mode.`, req, {});
return planGate.check(req, signal);
}
return (gate === "ask" ? askGate : acceptRootGate).check(req, signal);
},
};
}
export function modeRequestAfterResume(seat, recorded, outcome, parentModeUnknown) {
const approved = outcome !== undefined && outcome.decision !== "reject";
const unnamed = !approved || !approvalRequestsPlanExit(outcome.gate, recorded.permissionMode) ? (seat ?? recorded.permissionMode) : seat !== undefined && seat !== "plan" ? seat : recorded.prePlanMode;
const named = approved ? outcome.permissionMode : undefined;
if (named === undefined)
return unnamed;
return parentModeUnknown !== true || clampPermissionMode(named, unnamed ?? "default").effective === named ? named : unnamed;
}
export function withheldApprovalMode(seat, recorded, outcome, parentModeUnknown) {
const named = outcome !== undefined && outcome.decision !== "reject" ? outcome.permissionMode : undefined;
return named !== undefined && modeRequestAfterResume(seat, recorded, outcome, parentModeUnknown) !== named ? named : undefined;
}
export function refusePermissionModeDoors(spec) {
const mode = spec.permissionMode;
if (mode !== undefined && !isPermissionMode(mode)) {
const e = new Error(`permissionMode must be one of ${PERMISSION_MODES.map((w) => JSON.stringify(w)).join(", ")} when present (got ${describeRejectedValue(mode)}) — omit it for the default mode; an unrecognized word is refused rather than read as any mode.`);
e.code = "config.permission_mode_invalid";
throw e;
}
const floor = spec.shellGate;
if (floor !== undefined && floor !== "always") {
const e = new Error(`shellGate must be the floor word "always" when present (got ${describeRejectedValue(floor)}) — the doctrine values "off" / "classify" are retired: the shell's shape tier is installed on every full shell and the permission mode (permissionMode) decides what its asks become; omit shellGate for no operator floor.`);
e.code = "config.shell_gate_value_retired";
throw e;
}
return mode;
}
export function asResumeConfigRefusal(input, screen) {
try {
return enterConfigDoor(input, screen);
}
catch (e) {
if (e instanceof Error && "code" in e && isCheckpointConfigRefusalCode(e.code)) {
const reason = e.detail?.reason;
const field = configInputOfRefusal(e) ?? input;
throw refusalAbout(field, new CheckpointError("checkpoint.config_refused", e.message, { field, code: e.code, ...(reason !== undefined ? { reason } : {}) }));
}
throw e;
}
}
export const PERMISSION_MODE_START_WORDS = Object.freeze(["default", "auto"]);
function autoModeArmFactOf(word, a) {
if (word !== "auto")
return { armed: false, reason: "no_intent" };
if (!a.autoFacePresent)
return { armed: false, reason: "no_face" };
if (a.caps?.autoMode === false) {
if (a.capsFaulted === true)
return { armed: false, reason: "resolver_fault" };
return { armed: false, reason: "denied", ...(a.caps.autoModeDenySource !== undefined ? { deniedSource: a.caps.autoModeDenySource } : {}) };
}
return { armed: true, reason: "armed" };
}
function refuseFoldModeWord(field, value, allowed) {
const e = new Error(`foldPermissionMode: ${field} must be one of ${allowed.map((w) => JSON.stringify(w)).join(", ")} when present (got ${describeRejectedValue(value)}) — omit it to leave it unset.`);
e.code = "config.permission_mode_invalid";
e.detail = { field };
throw e;
}
export function foldPermissionMode(input) {
const { requested, ceiling, whenUnset, arming } = input;
if (requested !== undefined && !isPermissionMode(requested))
refuseFoldModeWord("requested", requested, PERMISSION_MODES);
if (ceiling !== undefined && !isPermissionMode(ceiling))
refuseFoldModeWord("ceiling", ceiling, PERMISSION_MODES);
if (whenUnset !== undefined && !PERMISSION_MODE_START_WORDS.includes(whenUnset))
refuseFoldModeWord("whenUnset", whenUnset, PERMISSION_MODE_START_WORDS);
const { effective: word, clamped } = ceiling === undefined ? { effective: requested ?? whenUnset ?? "default", clamped: false } : clampPermissionMode(requested, ceiling);
const base = requested !== undefined ? { requested } : {};
const autoMode = arming === undefined ? undefined : autoModeArmFactOf(word, arming);
const armed = autoMode !== undefined ? { autoMode } : {};
const armingFold = arming === undefined
? undefined
: word === "bypassPermissions" && arming.caps?.bypassPermissions === false
? "operator_deny"
: autoMode !== undefined && word === "auto" && !autoMode.armed
? autoMode.reason === "no_face"
? "face_absent"
: "operator_deny"
: undefined;
if (armingFold !== undefined) {
if (requested === undefined && ceiling === undefined)
return { receipt: { effective: "default" }, declared: "default", ...armed };
return { receipt: { ...base, effective: "default", foldedBy: armingFold }, folded: word, declared: word, ...armed };
}
if (clamped)
return { receipt: { ...base, effective: word, foldedBy: "inherited_ceiling" }, folded: requested ?? word, declared: word, ...armed };
return { receipt: { ...base, effective: word }, declared: word, ...armed };
}
export function screenPermissionModeWhenUnset(word) {
if (word === undefined || PERMISSION_MODE_START_WORDS.includes(word))
return word;
const e = new Error(`RunnerDeps.permissionModeWhenUnset must be one of ${PERMISSION_MODE_START_WORDS.map((w) => JSON.stringify(w)).join(", ")} when present (got ${describeRejectedValue(word)}) — omit it to start a leg that declares no mode under "default"; a task that needs another mode declares it.`);
e.code = "config.permission_mode_invalid";
throw e;
}
export function autoModeFaceOf(deps, inherited) {
return deps.autoMode ?? inherited?.autoModeFace;
}
export class PermissionModeController {
requestedBySpec;
ceiling;
steers = [];
arming;
onFold;
whenUnset;
prePlan;
constructor(requestedBySpec, ceiling, opts) {
this.requestedBySpec = requestedBySpec;
this.ceiling = ceiling;
this.onFold = opts?.onFold;
this.whenUnset = opts?.whenUnset;
if (requestedBySpec === "plan")
this.prePlan = opts?.prePlanMode;
}
get prePlanMode() {
return this.declared === "plan" ? this.prePlan : undefined;
}
get prePlanModeObserved() {
const word = this.answerOf(true).declared === "plan" ? this.prePlan : undefined;
if (word === undefined)
return undefined;
return foldPermissionMode({ requested: word, ...(this.arming !== undefined ? { arming: this.arming } : {}) }).receipt.effective;
}
get requested() {
return this.steers.at(-1)?.word ?? this.requestedBySpec;
}
ceilingNow(observe) {
if (this.ceiling === undefined || typeof this.ceiling === "string")
return this.ceiling;
return observe ? (this.ceiling.observed ?? this.ceiling.current) : this.ceiling.current;
}
get declared() {
return this.answerOf(false).declared;
}
autoModeArmFact() {
const fact = this.answerOf(true).autoMode;
if (fact === undefined)
throw new Error("the auto-mode arming fact was read before the deployment's arming facts were bound");
return fact;
}
armedForAuto = false;
faultSeat = createSafeNotifier();
get current() {
const effective = this.receipt().effective;
const arming = this.arming;
if (effective === "auto" && !this.armedForAuto && arming?.armAuto !== undefined) {
this.armedForAuto = true;
void new Promise((resolve) => resolve(arming.armAuto?.())).catch((e) => {
this.armedForAuto = false;
this.faultSeat.notifyAsync(() => arming.onArmFault?.(e), "permissionMode.onArmFault");
});
}
return effective;
}
get observed() {
return this.receiptOf(true).effective;
}
armsAs(word) {
const ceiling = this.ceilingNow(true);
return foldPermissionMode({ requested: word, ...(ceiling !== undefined ? { ceiling } : {}), ...(this.whenUnset !== undefined ? { whenUnset: this.whenUnset } : {}), ...(this.arming !== undefined ? { arming: this.arming } : {}) }).receipt.effective;
}
receipt() {
return this.receiptOf(false);
}
receiptOf(observe) {
return this.answerOf(observe).receipt;
}
answerOf(observe) {
const ceiling = this.ceilingNow(observe);
const requested = this.requested;
return foldPermissionMode({ ...(requested !== undefined ? { requested } : {}), ...(ceiling !== undefined ? { ceiling } : {}), ...(this.whenUnset !== undefined ? { whenUnset: this.whenUnset } : {}), ...(this.arming !== undefined ? { arming: this.arming } : {}) });
}
announce(answer) {
if (answer.receipt.foldedBy !== undefined && answer.folded !== undefined)
this.onFold?.(answer.receipt, answer.folded);
}
announceStart() {
const answer = this.answerOf(false);
this.announce(answer);
return answer.receipt;
}
ceilingRebound(before) {
const after = this.answerOf(false);
if (after.receipt.foldedBy === "inherited_ceiling" && (before.foldedBy !== "inherited_ceiling" || before.effective !== after.receipt.effective))
this.announce(after);
}
bindArming(arming) {
const before = this.receipt();
this.arming = arming;
const answer = this.answerOf(false);
if (answer.receipt.foldedBy !== before.foldedBy)
this.announce(answer);
for (const then of this.awaitingArming.splice(0))
this.faultSeat.notify(then, "permissionMode.whenArmed");
return answer.receipt;
}
awaitingArming = [];
whenArmed(then) {
if (this.arming === undefined)
this.awaitingArming.push(then);
else
this.faultSeat.notify(then, "permissionMode.whenArmed");
}
async steer(mode) {
const entry = { word: mode };
const before = this.declared;
this.steers.push(entry);
const answer = this.answerOf(false);
const receipt = answer.receipt;
const arming = this.arming;
if (receipt.effective === "auto" && arming?.armAuto !== undefined) {
this.armedForAuto = true;
try {
await arming.armAuto();
}
catch (e) {
this.armedForAuto = false;
const at = this.steers.indexOf(entry);
if (at >= 0)
this.steers.splice(at, 1);
throw e;
}
}
const at = this.steers.indexOf(entry);
if (at > 0)
this.steers.splice(0, at);
if (this.steers.at(-1) === entry) {
if (mode !== "plan")
this.prePlan = undefined;
else if (before !== "plan")
this.prePlan = before;
}
this.announce(answer);
return receipt;
}
}