@sema-agent/core
Version:
Stateless, task-oriented AI agent core
116 lines (115 loc) • 8.08 kB
JavaScript
import { admitModChain, chainJudges } from "../mods/stations.js";
import { CheckpointError } from "../checkpoint-store.js";
import { resolveAskSeat } from "../wiring-manifest.js";
import { readingChangedRefusal } from "../checkpoint-row-verdict.js";
export function legConstraintLayers(leg) {
const whose = leg.rootLeg ? { rootLeg: true } : {};
return [
...(leg.installation !== undefined ? [{ installation: leg.installation.bus, kind: "installation", ...whose, ...(leg.installation.hookEnv !== undefined ? { hookEnv: leg.installation.hookEnv } : {}), ...leg.installation.regime }] : []),
...(leg.policy !== undefined ? [{ policy: leg.policy.policy, kind: leg.policy.kind, ...whose, ...leg.policy.regime }] : []),
];
}
export function chainRootLeg(inheritedChain, isDelegatedChild) {
return (inheritedChain?.length ?? 0) === 0 && !isDelegatedChild;
}
export const REVIVED_LEG_CLASSIFIER = Object.freeze({
decide: () => {
throw new Error("the revived leg's classifier stand-in was dispatched unbound — a rebuilt layer's classifier is bound by the leg that runs it");
},
});
export function bindRevivedLegClassifier(layer, own, mode) {
if (layer.autoMode?.decider !== REVIVED_LEG_CLASSIFIER)
return layer;
const decider = { decide: (input, signal) => own()?.decide(input, signal) ?? Promise.resolve({ kind: "unavailable", cause: "error" }) };
return { ...layer, autoMode: { ...layer.autoMode, decider, liveMode: { get current() { return mode(); } } } };
}
export function revivalParentConstraints(input) {
if ((input.handed?.length ?? 0) > 0)
return input.handed;
const live = input.registry.get(input.token);
if (live !== undefined)
return liveChainNow(live, input);
const record = input.record;
if (record?.requiresParentConstraint !== true)
return input.handed;
return rebuiltParentConstraints(input, record);
}
const isRootTaskLayer = (layer) => layer.kind === "taskPolicy" && layer.rootLeg === true;
const isRootTaskPolicy = (layer) => layer.policy !== undefined && isRootTaskLayer(layer);
function liveChainNow(live, input) {
if (!live.some(isRootTaskPolicy))
return live;
const now = input.rootPolicy;
if (now === undefined) {
input.onRootLayerUnrestated();
return live;
}
return live.map((layer) => (layer.policy !== undefined && isRootTaskPolicy(layer) ? { ...layer, policy: now } : layer));
}
export function revivalRootPolicyUnrestatedNotice(sessionId) {
return {
code: "permission.revival_root_policy_unrestated",
message: "a parked agent resumed on the runner that holds its inherited chain was handed no root task policy (`rootPolicy`), so the chain it runs under keeps the root task's layer as this runner registered it when the agent last parked here — a rule the root task gained since is not in it, and one it dropped since still holds; hand the root task's policy as it is now to resume under it (on another runner the same resume is refused for the missing policy)",
detail: { sessionId },
};
}
async function rebuiltParentConstraints(input, record) {
const recorded = record.constraintChain;
if (recorded === undefined || recorded.length === 0)
throw readingChangedRefusal("the row's inherited constraint chain was recorded by an earlier engine release as a count alone, with no layer this release can rebuild");
const approver = resolveAskSeat(input.leg, input.deps).value;
const regimeAt = (entry) => ({
...(approver !== undefined ? { onAsk: approver } : {}),
...(entry.durableMandate === true ? { durableMandate: true } : {}),
...(entry.contentMandate === true ? { contentMandate: true } : {}),
...(entry.autoModeArmed === true ? { autoMode: { decider: REVIVED_LEG_CLASSIFIER, ...(entry.autoModeArming !== undefined ? { arming: entry.autoModeArming } : {}) } } : {}),
});
let bus;
const installation = async () => (bus ??= await admitModChain({ ...(input.deps.mods !== undefined ? { deployment: input.deps.mods } : {}), ...(input.leg.mods !== undefined ? { task: input.leg.mods } : {}) }));
if (recorded.every((entry) => entry.kind === undefined))
return rebuildUnlabeled(input, recorded, await installation(), regimeAt);
const gaps = [];
const layers = [];
for (const [position, entry] of recorded.entries()) {
const regime = regimeAt(entry);
const rootLeg = entry.rootLeg === true;
if (entry.kind === "installation") {
const admitted = await installation();
if (chainJudges(admitted))
layers.push(...legConstraintLayers({ installation: { bus: admitted, regime }, rootLeg }));
else
gaps.push({ position, kind: entry.kind, lacks: "a handler that judges a tool call on this runner's `RunnerDeps.mods` or the seat's mods", field: "deps", supplied: true });
}
else if (entry.kind === "taskPolicy" && !isRootTaskLayer(entry)) {
gaps.push({ position, kind: entry.kind, lacks: "the task policy a delegated leg declared for itself (not the root task's: no input of a resume names it, and the root task's policy does not stand in for it)", field: "inheritedGate", supplied: false });
}
else if (entry.kind === "taskPolicy" || entry.kind === "deploymentPolicy") {
const policy = entry.kind === "taskPolicy" ? input.rootPolicy : input.deps.toolPolicy;
if (policy !== undefined)
layers.push(...legConstraintLayers({ policy: { policy, kind: entry.kind, regime }, rootLeg }));
else
gaps.push(entry.kind === "taskPolicy" ? { position, kind: entry.kind, lacks: "the root task's policy (`parkedResume.rootPolicy`), which this resume was not handed", field: "rootPolicy", supplied: true } : { position, kind: entry.kind, lacks: "this runner's `RunnerDeps.toolPolicy`", field: "deps", supplied: true });
}
else
gaps.push({ position, kind: undefined, lacks: "a kind (the row recorded the layer without one)", field: "inheritedGate", supplied: false });
}
if (gaps.length > 0) {
const wayOut = gaps.every((g) => g.supplied) ? "resume it with the missing input, or deny it (the agent is stopped)" : "no resume can rebuild it, whatever it is handed: deny it (the agent is stopped)";
throw new CheckpointError("resume.parent_constraint_unrebuildable", `the parked leg ran under ${recorded.length} inherited constraint layer(s) and this resume cannot rebuild ${gaps.length === 1 ? "one of them" : `${gaps.length} of them`}: ${gaps.map((g) => `layer ${g.position + 1} (${g.kind ?? "no kind"}) lacks ${g.lacks}`).join("; ")} — rejected before the claim (the checkpoint stays pending): ${wayOut}`, { field: gaps[0].field });
}
return layers;
}
const UNLABELED = "the row's inherited constraint chain was recorded without layer kinds (by an engine release before 7.70.0, or from a chain handed without them)";
function rebuildUnlabeled(input, recorded, bus, regimeAt) {
if (input.deps.toolPolicy !== undefined)
throw readingChangedRefusal(`${UNLABELED}, and this runner carries a deployment tool policy, so which recorded layer is the task's own cannot be told`);
const judges = chainJudges(bus);
const count = (judges ? 1 : 0) + (input.rootPolicy !== undefined ? 1 : 0);
if (count !== recorded.length)
throw readingChangedRefusal(`${UNLABELED}, and its ${recorded.length} layer(s) are not the root leg's own contribution on this runner (${count}: ${judges ? "an installation" : "no installation"}, ${input.rootPolicy !== undefined ? "the root task's policy" : "no root task policy handed"})`);
return legConstraintLayers({
installation: judges ? { bus, regime: regimeAt(recorded[0]) } : undefined,
policy: input.rootPolicy !== undefined ? { policy: input.rootPolicy, kind: "taskPolicy", regime: regimeAt(recorded[judges ? 1 : 0]) } : undefined,
rootLeg: true,
});
}