@sema-agent/core
Version:
Stateless, task-oriented AI agent core
199 lines (198 loc) • 11.7 kB
JavaScript
import { readRecordedRuleOwner } from "./rule-owner.js";
import { isPlainRecord } from "./mods/kernel/receive.js";
import { strayMembersOf } from "./own-property-receipt.js";
import { PRINCIPAL_NAME_SPELLING, principalNameFault, principalNameOf, RECORDED_PRINCIPAL_NAME_SPELLING, recordedPrincipalNameOf } from "./principal-name.js";
export const REKEY_MODES = Object.freeze(["plan", "arrive", "leave", "withdraw"]);
export const ONE_STEP_REKEY_MODES = Object.freeze(["plan", "leave"]);
export function rekeyAnswerOf(mode, counts) {
switch (mode) {
case "plan":
return { kind: "plan", rows: counts.rows, conflicting: counts.conflicting };
case "arrive":
return counts.conflicting > 0 ? { kind: "conflict", mode, rows: counts.rows, conflicting: counts.conflicting } : { kind: "done", mode, rows: counts.rows };
case "leave":
case "withdraw":
return { kind: "done", mode, rows: counts.acted };
default: {
const unhandled = mode;
return unhandled;
}
}
}
export function agentScopeOf(raw) {
return typeof raw === "string" && raw !== "" ? raw : undefined;
}
function readRekeyRecord(entry, value, keys) {
if (!isPlainRecord(value))
throw new TypeError(`${entry}: the input must be a plain object { ${keys.join(", ")} }`);
const stray = strayMembersOf(value, { subject: `${entry}'s input`, unit: "member", moment: "when the call is made" }, keys);
if (stray !== undefined)
throw new TypeError(stray.sentence);
return Object.fromEntries(keys.map((k) => [k, value[k]]));
}
function readRekeyMode(entry, raw, modes) {
const mode = modes.find((m) => m === raw);
if (mode !== undefined)
return mode;
const offered = modes.map((m) => `"${m}"`).join(", ");
if (REKEY_MODES.some((m) => m === raw))
throw new TypeError(`${entry}: \`mode\` ${JSON.stringify(raw)} is a step this seat does not offer — it offers ${offered}`);
throw new TypeError(`${entry}: \`mode\` must be one of ${offered} (the step is the caller's to name), got ${typeof raw === "string" ? JSON.stringify(raw) : raw === null ? "null" : typeof raw}`);
}
export function readPrincipalRekeyInput(entry, value) {
const r = readRekeyRecord(entry, value, ["from", "toPrincipal", "mode"]);
const from = readRecordedRuleOwner(r.from);
if (from === undefined)
throw new TypeError(`${entry}: \`from\` must be a rule owner — { kind: "local-owner" } or { kind: "principal", principal: <a principal name> }`);
const toPrincipal = principalNameOf(r.toPrincipal);
if (toPrincipal === undefined)
throw new TypeError(`${entry}: \`toPrincipal\` must be a principal name (${PRINCIPAL_NAME_SPELLING}), got ${principalNameFault(r.toPrincipal)}`);
return Object.freeze({ from, toPrincipal, mode: readRekeyMode(entry, r.mode, REKEY_MODES) });
}
export function readScopeRekeyInput(entry, value) {
const r = readRekeyRecord(entry, value, ["fromScope", "toScope", "mode"]);
const fromScope = agentScopeOf(r.fromScope);
if (fromScope === undefined)
throw new TypeError(`${entry}: \`fromScope\` must be a non-empty string (the scope a row is filed under)`);
const toScope = agentScopeOf(r.toScope);
if (toScope === undefined)
throw new TypeError(`${entry}: \`toScope\` must be a non-empty string (the scope a row is filed under)`);
return Object.freeze({ fromScope, toScope, mode: readRekeyMode(entry, r.mode, REKEY_MODES) });
}
export function readIdentityRekeyInput(entry, value) {
const r = readRekeyRecord(entry, value, ["fromPrincipal", "toPrincipal", "scopes", "mode"]);
const fromPrincipal = recordedPrincipalNameOf(r.fromPrincipal);
if (fromPrincipal === undefined)
throw new TypeError(`${entry}: \`fromPrincipal\` must be ${RECORDED_PRINCIPAL_NAME_SPELLING}, got ${principalNameFault(r.fromPrincipal)}`);
const toPrincipal = principalNameOf(r.toPrincipal);
if (toPrincipal === undefined)
throw new TypeError(`${entry}: \`toPrincipal\` must be a principal name (${PRINCIPAL_NAME_SPELLING}), got ${principalNameFault(r.toPrincipal)}`);
if (!Array.isArray(r.scopes))
throw new TypeError(`${entry}: \`scopes\` must be a list of { fromScope, toScope } pairs (possibly empty)`);
const raw = r.scopes;
const scopes = raw.map((el, i) => {
const pair = readRekeyRecord(`${entry}: scopes[${i}]`, el, ["fromScope", "toScope"]);
const fromScope = agentScopeOf(pair.fromScope);
if (fromScope === undefined)
throw new TypeError(`${entry}: scopes[${i}].fromScope must be a non-empty string (the scope a row is filed under)`);
const toScope = principalNameOf(pair.toScope);
if (toScope === undefined)
throw new TypeError(`${entry}: scopes[${i}].toScope must be a name (${PRINCIPAL_NAME_SPELLING}) — it is written where an opt-in's scope is read by the name rule — got ${principalNameFault(pair.toScope)}`);
return Object.freeze({ fromScope, toScope });
});
const sources = new Set();
const targets = new Set();
for (const [i, p] of scopes.entries()) {
if (sources.has(p.fromScope))
throw new TypeError(`${entry}: scopes[${i}].fromScope names a source scope another pair names (a mapping moves each value once)`);
if (targets.has(p.toScope))
throw new TypeError(`${entry}: scopes[${i}].toScope names a target scope another pair names (two source scopes cannot become one)`);
sources.add(p.fromScope);
targets.add(p.toScope);
}
const chained = scopes.findIndex((p, i) => scopes.some((q, j) => j !== i && q.fromScope === p.toScope));
if (chained >= 0)
throw new TypeError(`${entry}: scopes[${chained}].toScope is another pair's fromScope — a chain of pairs is not one mapping; name each value's final scope`);
return Object.freeze({ fromPrincipal, toPrincipal, scopes: Object.freeze(scopes), mode: readRekeyMode(entry, r.mode, ONE_STEP_REKEY_MODES) });
}
const UNTOUCHED = Object.freeze({ kind: "untouched" });
export function rekeyOwnerIdentity(identity, map) {
const principal = identity.principal;
const partition = identity.isolationScope ?? principal;
const nextPrincipal = principal === map.fromPrincipal ? map.toPrincipal : principal;
const pair = partition === null ? undefined : map.scopes.find((p) => p.fromScope === partition);
const nextPartition = pair?.toScope ?? partition;
if (nextPrincipal === principal && nextPartition === partition)
return UNTOUCHED;
return {
kind: "rekeyed",
identity: { principal: nextPrincipal, ...(nextPartition !== null && nextPartition !== nextPrincipal ? { isolationScope: nextPartition } : {}) },
partitionLeft: nextPrincipal !== principal && partition !== null && pair === undefined,
};
}
export function oneStepRekeyAnswerOf(mode, verdicts) {
if (mode === "leave")
return { kind: "done", mode, rows: verdicts.filter((v) => v.kind === "rekeyed").length };
return {
kind: "plan",
rows: verdicts.filter((v) => v.kind !== "untouched").length,
conflicting: verdicts.filter((v) => v.kind === "unrekeyable").length,
unpairedScopeRows: verdicts.filter((v) => v.kind === "rekeyed" && v.partitionLeft).length,
};
}
const ZERO = Object.freeze({ rev: 0, gen: 0 });
const stampOf = (s) => ({ rev: s.rev, gen: s.gen });
export function stampMax(a, b) {
return { rev: Math.max(a.rev, b.rev), gen: Math.max(a.gen, b.gen) };
}
export function arrivalStampOf(row, targetMark) {
return targetMark === null ? stampOf(row) : stampMax(row, { rev: targetMark.rev + 1, gen: targetMark.gen });
}
export function eraseStepOf(mark, row) {
const m = mark ?? ZERO;
return { rev: Math.max(m.rev, row.rev), gen: Math.max(m.gen, row.gen) + 1 };
}
const sameStamp = (a, b) => a.rev === b.rev && a.gen === b.gen;
const atMost = (a, b) => a.rev <= b.rev && a.gen <= b.gen;
function rowWears(row, recorded) {
return recorded === "unreadable" ? !row.readable : row.readable && sameStamp(row, recorded);
}
const landedBy = (record) => (record.from === "unreadable" ? "unreadable" : record.at);
function thisMovesArrivalOf(key, to) {
const record = key.sourceMark?.arrival;
return record !== undefined && record.to === to && key.sourceRow !== null && rowWears(key.sourceRow, record.from) ? record : undefined;
}
function arriveJudgmentOf(key, to) {
if (key.sourceMark?.lineageLost === true || key.targetMark?.lineageLost === true)
return "conflict";
const target = key.targetMark?.stamp ?? null;
if (key.sourceRow === null) {
if (key.sourceMark === null)
return undefined;
const merged = target === null ? stampOf(key.sourceMark.stamp) : stampMax(target, key.sourceMark.stamp);
return target !== null && sameStamp(merged, target) ? undefined : { kind: "merge-marks", mark: merged };
}
const record = thisMovesArrivalOf(key, to);
if (key.targetRow !== null)
return record !== undefined && rowWears(key.targetRow, landedBy(record)) ? "arrived" : "conflict";
if (record !== undefined)
return target === null || atMost(target, record.at) ? { kind: "arrive", record, sourceMark: null } : "conflict";
const sourceMark = stampOf(key.sourceMark?.stamp ?? (key.sourceRow.readable ? key.sourceRow : ZERO));
const at = key.sourceRow.readable ? arrivalStampOf(key.sourceRow, target) : stampMax(target ?? ZERO, key.sourceMark?.stamp ?? ZERO);
return { kind: "arrive", record: { to, from: key.sourceRow.readable ? stampOf(key.sourceRow) : "unreadable", at }, sourceMark };
}
export function judgePrincipalRekey(mode, to, keys) {
const rows = keys.filter((k) => k.sourceRow !== null).length;
const none = keys.map(() => undefined);
switch (mode) {
case "plan":
case "arrive": {
const judged = keys.map((k) => arriveJudgmentOf(k, to));
const conflicting = judged.filter((j) => j === "conflict").length;
const writes = mode === "plan" || conflicting > 0 ? none : judged.map((j) => (j === "conflict" || j === "arrived" ? undefined : j));
return { answer: rekeyAnswerOf(mode, { rows, conflicting, acted: 0 }), writes };
}
case "leave": {
const writes = keys.map((k) => {
const record = thisMovesArrivalOf(k, to);
return record === undefined || k.sourceRow === null ? undefined : { kind: "leave", mark: eraseStepOf(k.sourceMark?.stamp ?? null, k.sourceRow), record };
});
return { answer: rekeyAnswerOf(mode, { rows, conflicting: 0, acted: writes.filter((w) => w !== undefined).length }), writes };
}
case "withdraw": {
const writes = keys.map((k) => {
const record = k.sourceMark?.arrival;
if (k.sourceMark === null || record === undefined || record.to !== to)
return undefined;
const landed = k.targetRow !== null && rowWears(k.targetRow, landedBy(record));
return { kind: "withdraw", targetMark: landed && k.targetRow !== null ? eraseStepOf(k.targetMark?.stamp ?? null, k.targetRow) : undefined, sourceMark: stampOf(k.sourceMark.stamp) };
});
const acted = writes.filter((w) => w?.kind === "withdraw" && w.targetMark !== undefined).length;
return { answer: rekeyAnswerOf(mode, { rows, conflicting: 0, acted }), writes };
}
default: {
const unhandled = mode;
return unhandled;
}
}
}