@sema-agent/core
Version:
Stateless, task-oriented AI agent core
114 lines (113 loc) • 7.15 kB
JavaScript
import { judgeCheckpointRow } from "./checkpoint-row-verdict.js";
import { judgeCheckpointRequirements, stampCheckpointRequirements } from "./checkpoint-requirements.js";
import { checkpointVersionOf, MAX_SUPPORTED_CHECKPOINT_VERSION } from "./checkpoint-features.js";
import { checkpointRevOf } from "./checkpoint-generation.js";
import { isolationScopeRecordOf } from "./isolation-scope.js";
import { isPlainRecord } from "./mods/kernel/receive.js";
import { rekeyOwnerIdentity } from "./identity-rekey.js";
export const CHECKPOINT_IDENTITY_MEMBERS = Object.freeze({
principal: Object.freeze(["principal", "state.inheritedGate.ancestorRules[].principal"]),
scope: Object.freeze(["scope", "state.legScope", "durableApproval.scope", "state.legIdentity.rootSessionScope"]),
partition: Object.freeze(["isolationScope"]),
});
export const CHECKPOINT_NON_IDENTITY_MEMBERS = Object.freeze({
"state.inheritedGate.admittedOrgScopes": "an organization tenant key (`org:<tenant>`): a tenant is not a person, and the background-agent seat carries the same member as it stands",
"state.inheritedGate.ownAdmittedOrgScopes": "an organization tenant key the leg itself admitted: a tenant, not a person",
"state.inheritedGate.ownAdmittedOrgWriteScope": "the organization tenant key the leg may write: a tenant, not a person",
"state.skillScopes": "the names of the skills the leg ran under: never who they act for",
heldRows: "the conversation rows owed after the leaf: what was said and by whom is history, not a cell a move re-files",
"state.pendingSteerQueue": "queued instructions with their frozen attribution: who sent a steer is history",
resolvedOutcome: "the recorded decision: who decided and what is history",
executionOutcome: "the recorded execution and its settlement: who settled the decided action is history",
sourceSessionId: "a session id (the conversation the ask was raised in): an id, not an identity",
parentSessionId: "a session id (the spawning session): an id, not an identity",
rootSessionId: "a session id (the delegation tree's root): an id, not an identity",
checkpointId: "the row's non-secret id: an id, not an identity",
"state.compositionLeg": "a composition leg's own names and host session id: ids, not an identity",
"state.placementRootSessionId": "the placement root's session id: an id, not an identity",
"state.rowTaskId": "the task a resumed leg runs as: an id, not an identity",
"state.legIdentity.declaredTaskId": "the task id the leg's host declared: an id, not an identity",
"state.legIdentity.parentTaskId": "the task that spawned the leg: an id, not an identity",
"state.legIdentity.rootSessionId": "a session id (the delegation tree's root): an id, not an identity",
"state.legIdentity.rootSessionIncarnation": "the occupant the tree's root session held: an id, not an identity",
"state.legIdentity.spawnName": "the leg's explicit spawn name: a name the spawning model or host chose, not an identity",
"state.legIdentity.ruleSessionId": "a session id (where the leg read the person's session-scope rules): an id, not an identity — a re-key carries it as it stands",
"state.workspaceHandle": "the parked workspace's sandbox, snapshot and device ids: ids, not an identity",
"state.handsHome": "an operating-system path: renaming a person moves no path",
"state.inheritedGate.pathRuleAnchors": "operating-system paths the path rules anchor at: renaming a person moves no path",
"state.inheritedGate.constraintChain": "the frozen ancestor constraint recipe (its own digest covers it): no identity member",
"state.inheritedGate.ancestorRules[].rules": "an ancestor's rule snapshot body: rules and their origin words, no identity member",
"gate.realApproval": "the real-approval bit's origin and organization words: no identity member",
});
function mappedValue(axis, value, map) {
if (axis === "principal")
return value === map.fromPrincipal ? map.toPrincipal : value;
return map.scopes.find((p) => p.fromScope === value)?.toScope ?? value;
}
const AXES = Object.keys(CHECKPOINT_IDENTITY_MEMBERS);
function refiled(v, segments, axis, map) {
const seg = segments[0];
if (seg === undefined || !isPlainRecord(v))
return v;
const rest = segments.slice(1);
const list = seg.endsWith("[]");
const key = list ? seg.slice(0, -2) : seg;
if (!Object.hasOwn(v, key))
return v;
const held = v[key];
let next = held;
if (rest.length === 0)
next = typeof held === "string" ? mappedValue(axis, held, map) : held;
else if (!list)
next = refiled(held, rest, axis, map);
else if (Array.isArray(held)) {
const els = held.map((el) => refiled(el, rest, axis, map));
if (els.some((el, i) => el !== held[i]))
next = els;
}
return next === held ? v : { ...v, [key]: next };
}
function refiledRow(row, map) {
let next = row;
for (const axis of AXES)
for (const path of CHECKPOINT_IDENTITY_MEMBERS[axis])
next = refiled(next, path.split("."), axis, map);
return next;
}
function partitionVerdictOf(row, map) {
const recorded = row.isolationScope;
if (recorded !== undefined && typeof recorded !== "string")
return undefined;
const principal = typeof row.principal === "string" && row.principal !== "" ? row.principal : null;
return rekeyOwnerIdentity({ principal, ...(recorded !== undefined && recorded !== "" ? { isolationScope: recorded } : {}) }, map);
}
export function checkpointRekeySelects(row, map) {
return refiledRow(row, map) !== row || partitionVerdictOf(row, map)?.kind === "rekeyed";
}
export function rekeyCheckpointRow(row, map, fidelity) {
const moved = refiledRow(row, map);
const partition = partitionVerdictOf(row, map);
if (moved === row && partition?.kind !== "rekeyed")
return { kind: "untouched" };
if (judgeCheckpointRow(row).kind === "lacking")
return { kind: "unrekeyable" };
const stampsMatch = stampsJudgedOk(row);
const next = structuredClone(moved);
if (partition !== undefined) {
const identity = partition.kind === "rekeyed" ? partition.identity : undefined;
const principal = typeof next.principal === "string" ? next.principal : undefined;
const value = identity !== undefined ? (identity.isolationScope ?? identity.principal ?? undefined) : next.isolationScope;
delete next.isolationScope;
Object.assign(next, isolationScopeRecordOf({ ...(value !== undefined ? { isolationScope: value } : {}), ...(principal !== undefined ? { principal } : {}) }));
}
const stamped = stampsMatch && checkpointVersionOf(row) >= MAX_SUPPORTED_CHECKPOINT_VERSION ? stampCheckpointRequirements(next, fidelity) : next;
return { kind: "rekeyed", row: { ...stamped, rev: checkpointRevOf(row) + 1 }, partitionLeft: partition?.kind === "rekeyed" && partition.partitionLeft };
}
function stampsJudgedOk(row) {
try {
return judgeCheckpointRequirements(row).kind === "ok";
}
catch {
return false;
}
}