@sema-agent/core
Version:
Stateless, task-oriented AI agent core
154 lines (153 loc) • 11.4 kB
JavaScript
import { callerToolMembership } from "../../agents/inherited-tool-pool.js";
import { judgeExtraBody } from "../../brain/request-params.js";
import { MODEL_CAPABILITIES, capabilityOf } from "../../brain/model-capability.js";
import { screenAllowedToolsValue } from "../allow-entry.js";
import { clampPermissionMode } from "../ask-origin.js";
import { checkpointSeatOf } from "../checkpoint-seat.js";
import { recordedModeSeed } from "../checkpoint-row-verdict.js";
import { resolveCheckpointStore } from "../checkpoint-store.js";
import { assertCompactionReserve, contextOverlayFor } from "../context-settings.js";
import { isolationScopeOf } from "../isolation-scope.js";
import { modeRequestAfterResume, refusePermissionModeDoors, withModeSeats } from "../mode-policy.js";
import { screenOutputStyle } from "../output-style.js";
import { approvalParkNotResumableOf, engineLaneLegOf, notResumableSaysOf } from "../park-resumability.js";
import { refuseUserAttachmentPathsWithoutWorkspace, screenUserAttachments } from "../user-attachment.js";
import { checkedPlanFileShape } from "./advertised-writable-dirs.js";
import { resolveFileHistoryRequest } from "./file-history-request.js";
import { screenLanguageSeat } from "./language-frame.js";
import { receiptAtPrepare } from "./leg-receipt.js";
import { checkpointStoreSeat, prepareConfigDoors } from "./prepare-config-doors.js";
import { enterConfigDoor, LIVE_OVER_ROW, resolveSeatValue } from "../config-refusal-input.js";
import { envOfAssembly, workspaceOfAssembly } from "./prepare-execution-env.js";
import { compileReadDeny, readDenyBuiltinConfigOf } from "../../tools/fs/read-deny.js";
import { readDenyFloorRefusal } from "../../tools/fs/read-floor.js";
import { unionAddOnly, withOwnLegHands } from "../child-clamp-seats.js";
import { assertManagerApprovesDeclaration, assertRunLedgerDeclaration } from "../run-ledger.js";
import { prepareSafetyScan } from "./prepare-safety-scan.js";
import { boundOwnToolLists, boundToolListsJudgment, judgeHostToolCeiling, ownListsWhereOf, readToolSelector, refuseNonListToolCeiling } from "./sub-agent-deny-lists.js";
import { legRetiredNameView, selectorLayerUnderView } from "../tool-name-aliases.js";
export function effectiveDelegationFacts(internals, seedIsDelegatedChild) {
const isDelegatedChild = internals?.isDelegatedChild !== undefined ? internals.isDelegatedChild === true : seedIsDelegatedChild === true;
return { isDelegatedChild, isNonForkChild: isDelegatedChild && internals?.insideFork !== true };
}
function refuseRequireExistingWithoutSession(spec) {
if (spec.requireExistingSession && !spec.sessionId) {
const e = new Error(`requireExistingSession requires a sessionId — cannot require an existing session without one; pass the sessionId of the session to continue, or run without requireExistingSession to start a fresh session`);
e.code = "resume.session_not_found";
throw e;
}
}
function refuseRegistryScopeMismatch(spec, internals) {
const registryScope = internals?.registryScope;
const own = isolationScopeOf(spec);
if (registryScope === undefined || own === undefined || registryScope === own)
return;
const [named, domain] = spec.isolationScope ? [`isolation scope "${own}"`, "isolation scope"] : [`principal "${own}"`, "principal"];
const e = new Error(`registry scope mismatch: ${named} vs RunInternals.registryScope "${registryScope}" — a delegated run's registry domain is its ${domain}, so the two must be equal (or only one given)`);
e.code = "config.registry_scope_mismatch";
throw e;
}
export function taskStartDoors(input) {
const { request, sessions, resume, internals } = input;
let deps = input.deps;
const { receipt, callerRoster } = enterConfigDoor("taskConfig", () => receiptAtPrepare(internals?.receivedPeers, request, deps));
const mountsCallerTool = callerToolMembership(callerRoster.roster.handed);
const callerSpec = callerRoster.spec;
const readRefusal = callerRoster.refusal;
if (readRefusal !== undefined)
enterConfigDoor("taskConfig", () => { throw readRefusal; });
const permissionModeSeat = enterConfigDoor("taskConfig", () => refusePermissionModeDoors(callerSpec));
const doors = prepareConfigDoors({ spec: callerSpec, deps, sessions, resume, internals, receipt, ...(input.refusalSink !== undefined ? { refusalSink: input.refusalSink } : {}) });
let spec = doors.spec;
deps = doors.deps;
const checkpointStore = enterConfigDoor(checkpointStoreSeat(spec), () => resolveCheckpointStore(spec, deps)), checkpointSeat = checkpointSeatOf(spec, checkpointStore);
const outputStyleSeat = enterConfigDoor("taskConfig", () => screenOutputStyle(spec.outputStyle));
const languageDeclared = enterConfigDoor("taskConfig", () => screenLanguageSeat(spec.language));
const allowedTools = enterConfigDoor("taskConfig", () => screenAllowedToolsValue(spec.allowedTools, "TaskSpec.allowedTools"));
const userAttachmentsSeat = enterConfigDoor("taskConfig", () => screenUserAttachments(spec.userAttachments, { resumeLeg: resume !== undefined }));
const delegation = effectiveDelegationFacts(internals, resume?.seed.isDelegatedChild);
const declaredModeAtDoor = (() => {
const live = internals?.inheritedGate?.permissionModeCeiling;
const ceiling = live !== undefined ? (live.observed ?? live.current) : internals?.inheritedGate?.permissionMode;
const requested = modeRequestAfterResume(permissionModeSeat, recordedModeSeed(resume?.seed.inheritedGate), resume?.outcome, delegation.isDelegatedChild && ceiling === undefined ? true : undefined);
return ceiling === undefined ? (requested ?? "default") : clampPermissionMode(requested, ceiling).effective;
})();
spec = withModeSeats(spec, declaredModeAtDoor);
enterConfigDoor("taskConfig", () => assertRunLedgerDeclaration(spec.runLedger));
enterConfigDoor("taskConfig", () => assertManagerApprovesDeclaration(spec));
spec = enterConfigDoor("taskConfig", () => withOwnLegHands(spec));
const planFile = spec.planFile;
enterConfigDoor("taskConfig", () => checkedPlanFileShape(planFile));
const scanned = spec;
const safety = enterConfigDoor("taskConfig", () => prepareSafetyScan({ spec: scanned, deps }));
refuseRequireExistingWithoutSession(spec);
enterConfigDoor("taskConfig", () => refuseRegistryScopeMismatch(scanned, internals));
const { toolFaceLists } = doors;
const ownListsRecord = resolveSeatValue(internals?.ownToolLists, () => resume?.seed.ownToolLists, LIVE_OVER_ROW);
const ownToolLists = enterConfigDoor(ownListsRecord.input, () => boundOwnToolLists(ownListsRecord.value, toolFaceLists));
const approvalParkNotResumable = approvalParkNotResumableOf({ engineLaneLeg: engineLaneLegOf(internals), parkLaneHeld: internals?.parkLaneHeld === true, hostDeclaredNotResumable: doors.hostApprovalParksNotResumable });
const notResumableSays = notResumableSaysOf(approvalParkNotResumable, doors.hostApprovalParksNotResumable);
const overlay = enterConfigDoor("deps", () => contextOverlayFor(deps.contextSettings, doors.resolvedRole.modelRef, deps));
assertCompactionReserve(spec.compaction?.reserveTokens, overlay, doors.model, delegation.isDelegatedChild);
const toolLegs = [
...(delegation.isDelegatedChild ? ["delegated"] : []),
...(internals?.explicitAgentName !== undefined ? ["teammate"] : []),
...(internals?.goalMode === true ? ["goal"] : []),
...(internals?.observerLeg === true ? ["observer"] : []),
...(spec.outputSchema !== undefined ? ["structured"] : []),
];
const ceilingSeat = resolveSeatValue(internals?.toolCeiling, () => resume?.seed.toolCeiling, LIVE_OVER_ROW);
const toolCeiling = ceilingSeat.value;
const hostCeiling = resume === undefined && toolCeiling != null && !engineLaneLegOf(internals);
if (hostCeiling)
refuseNonListToolCeiling(toolCeiling, "RunInternals.toolCeiling");
const judgedSeat = resolveSeatValue(internals?.toolListsJudged, () => resume?.seed.toolListsJudged, LIVE_OVER_ROW);
const toolListsJudged = enterConfigDoor(judgedSeat.input, () => boundToolListsJudgment(judgedSeat.value, toolFaceLists));
const retiredNames = legRetiredNameView(spec.tools ?? []);
const selectorLayers = [
...[...(toolCeiling ?? [])].map((layer) => ({ layer, input: ceilingSeat.input })),
...(internals?.definitionToolLists !== undefined ? [{ layer: enterConfigDoor("deps", () => selectorLayerUnderView(internals.definitionToolLists.layer, retiredNames)), input: "deps" }] : []),
{ layer: { ...(toolFaceLists.allow !== undefined ? { allow: toolFaceLists.allow } : {}), deny: toolFaceLists.exclude ?? [] }, input: "taskConfig" },
];
const toolFaceSnapshot = Object.freeze({
selector: readToolSelector({ retiredNames, layers: selectorLayers.map((l) => l.layer), inputs: selectorLayers.map((l) => l.input), where: ownListsWhereOf(ownToolLists), legs: toolLegs, spec }),
defer: toolFaceLists.defer,
alwaysLoad: toolFaceLists.alwaysLoad,
restoreGated: toolFaceLists.restoreGated,
});
const toolCeilingRead = toolCeiling === undefined && internals?.definitionToolLists === undefined ? undefined : toolFaceSnapshot.selector.layers.slice(0, -1);
if (hostCeiling)
judgeHostToolCeiling(toolFaceSnapshot.selector.layers.slice(0, internals?.definitionToolLists !== undefined ? -2 : -1), spec, [], { seat: "RunInternals.toolCeiling", legs: toolLegs });
enterConfigDoor(doors.modelInput, () => {
const extraBodyRefusal = judgeExtraBody(doors.model.extraBody, doors.model.id).refused;
if (extraBodyRefusal !== undefined)
throw Object.assign(new Error(extraBodyRefusal.sentence), { code: extraBodyRefusal.code, ...(extraBodyRefusal.field !== undefined ? { detail: { field: extraBodyRefusal.field } } : {}) });
for (const cap of MODEL_CAPABILITIES)
capabilityOf(doors.model, cap);
});
const fileHistoryRequest = enterConfigDoor("deps", () => resolveFileHistoryRequest(spec, deps));
if (workspaceOfAssembly(deps) === false)
enterConfigDoor("taskConfig", () => refuseUserAttachmentPathsWithoutWorkspace(userAttachmentsSeat));
refuseUnkeptReadFloorAtAssembly(spec, deps);
return {
callerRoster, mountsCallerTool, permissionModeSeat, doors, spec, deps,
checkpointStore, checkpointSeat, outputStyleSeat, languageDeclared, allowedTools, userAttachmentsSeat,
safety, ownToolLists, delegation, approvalParkNotResumable, notResumableSays,
toolLegs, toolCeiling, toolListsJudged, toolFaceSnapshot, toolCeilingRead, fileHistoryRequest, retiredNames,
};
}
function refuseUnkeptReadFloorAtAssembly(spec, deps) {
const env = envOfAssembly(deps);
if (env === undefined || deps.readDenyFloorRequired !== true)
return;
let rows = 0;
try {
rows = compileReadDeny(unionAddOnly("readDenyPatterns", deps.readDenyPatterns, spec.readDenyPatterns), "readDenyPatterns", readDenyBuiltinConfigOf({ tiers: deps.readDenyBuiltinTiers, exclude: deps.readDenyBuiltinExclude })).entries.length;
}
catch {
return;
}
const refusal = readDenyFloorRefusal({ env, required: true, rows });
if (refusal !== undefined)
throw refusal;
}