@sema-agent/core
Version:
Stateless, task-oriented AI agent core
387 lines (386 loc) • 21.8 kB
JavaScript
import { notANameShape, readIncarnationCell, sameOccupant } from "../../engine/session/repo-utils.js";
import { readMember } from "../thrown-value.js";
import { principalNameOf, readPrincipal, recordedPrincipalNameOf } from "../principal-name.js";
import { settleTeardownLeg, teardownLegBudget } from "./teardown-bounded.js";
import { gateWaitFailureOf, withGateTimeout } from "../gate-bounded-await.js";
import { runAbortedError } from "../terminal-cause.js";
import { rootReadThrough } from "../root-head-read.js";
export function delegationOwnerSeat(owner) {
const named = owner === null ? null : principalNameOf(owner);
if (named === undefined)
throw Object.assign(new Error(`delegationOwnerSeat: the owner must be a principal name or null (anonymous), got ${notANameShape(owner)}`), { code: "config.invalid_argument" });
return boundSeat(Object.freeze({ bound: true, owner: named }));
}
const ANSWERS_ONCE = new WeakSet();
function onceSeat(bind) {
let settled;
let inFlight;
const seat = Object.freeze({
read() {
if (settled !== undefined)
return Promise.resolve(settled);
inFlight ??= bind().then((reading) => {
settled = reading;
return reading;
}, (err) => {
inFlight = undefined;
throw err;
});
return inFlight;
},
});
ANSWERS_ONCE.add(seat);
return seat;
}
function boundSeat(reading) {
const seat = Object.freeze({ read: () => Promise.resolve(reading) });
ANSWERS_ONCE.add(seat);
return seat;
}
export function answeringOnce(seat) {
return ANSWERS_ONCE.has(seat) ? seat : onceSeat(async () => seat.read());
}
function ownerCellReading(sessionId, head) {
const owner = head.owner;
if (owner === null)
return { bound: true, owner };
const name = recordedPrincipalNameOf(owner);
if (name !== undefined)
return { bound: true, owner: name };
if (typeof owner === "string")
return { bound: false, reason: `the session ${sessionId}'s row answers an owner cell that names nobody (${notANameShape(owner)})` };
return { bound: false, reason: `the session ${sessionId}'s row answers an owner that is neither a name nor anonymous (${owner === undefined ? "none" : typeof owner})` };
}
export function ownRowDelegationOwner(sessions, sessionId, acquiredIncarnation, declaredRoot) {
return onceSeat(async () => {
const headOf = sessions.headOf;
if (typeof headOf !== "function")
return { bound: true, owner: null };
const [head, acquired] = await Promise.all([headOf.call(sessions, sessionId), acquiredIncarnation()]);
if (head === undefined)
return { bound: false, reason: `the session ${sessionId} this run acquired has no row any more` };
if (!sameOccupant(head.incarnation, acquired))
return { bound: false, reason: `the session ${sessionId} this run acquired now holds another occupant` };
const reading = ownerCellReading(sessionId, head);
if (!reading.bound)
return reading;
const root = Object.freeze({ ...(declaredRoot ?? { sessionId, incarnation: acquired }) });
return Object.freeze({ ...reading, root: declaredRoot === undefined ? rootReadThrough(root, sessions) : root });
});
}
export const DELEGATION_OWNER_UNBOUND = "delegation.owner_unbound";
export function delegationOwnerUnbound(reason) {
return Object.assign(new Error(`the delegation tree's owner does not bind: ${reason}`), { code: DELEGATION_OWNER_UNBOUND });
}
export const DELEGATION_OWNER_MISMATCH = "delegation.owner_mismatch";
export async function delegatedTreeOwner(seat, signal) {
const tree = await settled(() => seat.read(), signal);
if (!tree.bound)
throw Object.assign(delegationOwnerUnbound(tree.reason), tree.fault !== undefined ? { cause: tree.fault } : {});
return { owner: tree.owner };
}
export function ownerToJudge(tree) {
return tree.owner ?? undefined;
}
export async function verifiedAtBirth(seat, signal) {
const tree = await delegationOwnerOf(seat, signal).catch(() => undefined);
return tree !== undefined && tree.bound && ownerToJudge(tree) === undefined;
}
export function judgedOwnerSeat(internals) {
return internals?.delegationOwner;
}
export function createForm(input) {
if (input.placement === undefined && input.owner === undefined)
return undefined;
return { ...(input.placement !== undefined ? { placement: input.placement } : {}), ...(input.owner !== undefined ? { owner: input.owner } : {}) };
}
export function claimUnavailable() {
return storeFault("config.invalid_session_store", "it records no owner, and the session store this deployment runs on has no conditional owner write (recordOwner) to record this tree's owner on it — a run with an owner runs on, or reads, a row that records none only after recording its owner there; give the deployment's session store recordOwner");
}
const OPEN = Object.freeze({ open: true, claimed: false });
const refused = (why) => ({ open: false, kind: "not_ours", why });
const storeFault = (code, why, fault) => ({ open: false, kind: "store", code, why, ...(fault !== undefined ? { fault } : {}) });
export function rowStoreFaultError(sessionId, verdict) {
return Object.assign(new Error(`the session row ${sessionId} could not be shown to record this delegation tree's owner: ${verdict.why}`), { code: verdict.code }, verdict.fault !== undefined ? { cause: verdict.fault } : {});
}
export async function judgeRowForTree(sessions, row, tree, signal) {
const { sessionId } = row;
if (!tree.bound)
return storeFault(DELEGATION_OWNER_UNBOUND, `the delegation tree's owner does not bind: ${tree.reason}`, tree.fault);
const owner = tree.owner;
if (owner === null && row.minted === true)
return OPEN;
const headOf = sessions.headOf;
if (typeof headOf !== "function")
return owner === null ? OPEN : storeFault("config.invalid_session_store", "the session store has no by-id read (headOf) to show it does — a store that records session owners answers headOf for the row");
const occupant = row.occupant;
let read;
try {
read = await boundedOwnerRead(() => Promise.all([Promise.resolve().then(() => headOf.call(sessions, sessionId)), occupant === undefined ? undefined : Promise.resolve().then(occupant)]), signal, "delegation owner read");
}
catch (err) {
if (ownerReadEnd(err) === "stopped")
throw runAbortedError();
return storeFault("storage", `the row could not be read back (${ownerReadEnd(err) === "unanswered" ? "the session store did not answer in time" : "the session store's read failed"})`, err);
}
const [head, held] = read;
if (head === undefined)
return occupant === undefined ? { open: true, claimed: false, head: null } : refused("the row is not there any more");
if (occupant !== undefined && !sameOccupant(head.incarnation, held))
return refused("the row now holds another occupant than the one this leg acquired");
if (head.owner !== null && recordedPrincipalNameOf(head.owner) === undefined)
return storeFault("storage", `its owner cell cannot be read (it holds ${notANameShape(head.owner)})`);
if (head.owner === owner)
return { open: true, claimed: false, head };
if (head.owner !== null)
return refused("it records another owner — a delegated leg never runs on, or reads, another principal's session");
if (owner === null || row.runsOn !== true)
return { open: true, claimed: false, head };
const recordOwner = sessions.recordOwner;
if (typeof recordOwner !== "function")
return claimUnavailable();
if (row.writes === false)
return { open: true, claimed: false, head };
let answered;
try {
answered = await boundedOwnerRead(() => Promise.resolve().then(() => recordOwner.call(sessions, sessionId, owner, { row: { owner: null, ...(head.incarnation !== undefined ? { incarnation: head.incarnation } : {}) } })), signal, "delegation owner claim");
}
catch (err) {
if (ownerReadEnd(err) === "stopped")
throw runAbortedError();
if (readMember(err, "code") === "conflict")
return refused("the row now holds another occupant than the one this leg acquired");
return storeFault("storage", `it records no owner, and this tree's owner could not be recorded on it (${ownerReadEnd(err) === "unanswered" ? "the session store did not answer in time — the outcome is unknown" : "the session store's write failed"})`, err);
}
if (answered === undefined)
return refused("the row is not there any more");
if (answered.owner !== owner || !sameOccupant(answered.incarnation, head.incarnation))
return refused("it records another owner — a delegated leg never runs on, or reads, another principal's session");
return { open: true, claimed: true, head: answered };
}
export async function readJudgedRow(sessions, sessionId, verdict, read, signal) {
const judged = verdict.head;
const value = await read(await sessions.acquire(sessionId, { requireExisting: true }));
const headOf = sessions.headOf;
if (judged === undefined || typeof headOf !== "function")
return { read: value };
let now;
try {
now = await boundedOwnerRead(() => Promise.resolve().then(() => headOf.call(sessions, sessionId)), signal, "delegation owner re-read");
}
catch (err) {
if (ownerReadEnd(err) === "stopped")
throw runAbortedError();
return { refused: storeFault("storage", `the row could not be read back after the read (${ownerReadEnd(err) === "unanswered" ? "the session store did not answer in time" : "the session store's read failed"})`, err) };
}
if (readStandsAsJudged(judged, now))
return { read: value };
await forgetHeld(sessions, sessionId);
return { refused: rowNotTheOneJudged() };
}
export function rowNotTheOneJudged() {
return { open: false, kind: "not_ours", why: "the row is not the one judged — it changed hands, was laid down again, or was not there when it was judged" };
}
export async function judgeRowForSeat(sessions, row, seat, signal) {
return judgeRowForTree(sessions, row, await delegationOwnerOf(seat, signal), signal);
}
export async function birthTree(sessions, record, signal) {
const rootId = record.rootSessionId;
const rootIncarnation = record.rootSessionIncarnation;
const anonymous = { seat: ANONYMOUS_TREE, reading: ANONYMOUS_READING };
if (rootId === undefined || rootIncarnation === undefined)
return anonymous;
if (rootId === record.sessionId)
return { refused: "the agent's record names its own session as its tree's root — the tree it runs in cannot be read off the row it re-opens" };
const headOf = sessions.headOf;
if (typeof headOf !== "function")
return anonymous;
let head;
try {
head = await boundedOwnerRead(() => Promise.resolve().then(() => headOf.call(sessions, rootId)), signal, "delegation owner read");
}
catch (err) {
if (ownerReadEnd(err) === "stopped")
throw runAbortedError();
return { refused: "the tree it was started in does not bind: the row that names it could not be read", fault: err };
}
if (head === undefined || !sameOccupant(head.incarnation, rootIncarnation))
return anonymous;
const cell = ownerCellReading(rootId, head);
if (!cell.bound)
return { refused: `the tree it was started in does not bind: ${cell.reason}` };
const reading = Object.freeze({ ...cell, root: rootReadThrough(Object.freeze({ sessionId: rootId, incarnation: rootIncarnation }), sessions) });
return { seat: boundSeat(reading), reading };
}
const CYCLE_TREE_OF = new WeakMap();
export function holdCycleTree(claim, seat) {
CYCLE_TREE_OF.set(claim, seat);
}
export function heldCycleTree(claim) {
return CYCLE_TREE_OF.get(claim);
}
export async function revivalTreeSeat(sessions, records, claim, signal) {
let stored;
try {
stored = await records.get(claim.row.handle, claim.row.scope);
}
catch (err) {
return { refused: "the agent's record could not be read again (the record store's read failed)", fault: err ?? "the record store's read failed" };
}
if (stored === null)
return { refused: "the agent's record is not there any more" };
const same = (k) => stored[k] === claim.row[k];
if (!same("sessionId") || !same("rootSessionId") || !same("rootSessionIncarnation") || !same("owner") || !same("scope")) {
return { refused: "the claim does not match the agent's record as the store holds it (other identity cells) — re-read the record and claim it again", identity: true };
}
if (stored.rev !== claim.rev)
return { refused: "the claim is no longer seated on the agent's record (another revision) — re-read the record and claim it again" };
if (claim.parked)
return birthTree(sessions, stored, signal);
const held = heldCycleTree(claim.row);
return held !== undefined
? { seat: held }
: { refused: "this revival does not carry the tree its message entry admitted it on (the claim handed to the delegation tool is not the object the entry handed out) — hand the request's row on as it was given" };
}
export function treeReaches(tree, caller) {
return tree.bound && caller.bound && (tree.owner === null || tree.owner === caller.owner);
}
export async function birthTreeAdmission(sessions, record, row, caller, signal) {
if (!caller.bound)
return storeFault(DELEGATION_OWNER_UNBOUND, `the delegation tree's owner does not bind: ${caller.reason}`, caller.fault);
const born = await birthTree(sessions, record, signal);
if ("refused" in born)
return storeFault(born.fault !== undefined ? "storage" : DELEGATION_OWNER_UNBOUND, `the tree this agent was started in cannot be read: ${born.refused}`, born.fault);
if (!treeReaches(born.reading, caller))
return refused("the agent was started in another principal's tree — a revival runs in the tree it was born in");
const verdict = await judgeRowForTree(sessions, row, born.reading, signal);
return verdict.open ? { open: true, tree: born.seat, row: verdict } : verdict;
}
export function recordedRootAnchor(ctx, tree) {
const linkage = ctx.rootSessionId ?? ctx.sessionId;
if (linkage === undefined)
return {};
const root = tree !== undefined && tree.bound ? tree.root : undefined;
return root !== undefined && root.sessionId === linkage && root.incarnation !== undefined ? { rootSessionId: linkage, rootSessionIncarnation: root.incarnation } : { rootSessionId: linkage };
}
const ANONYMOUS_READING = Object.freeze({ bound: true, owner: null });
const ANONYMOUS_TREE = boundSeat(ANONYMOUS_READING);
export async function judgeLegRow(sessions, held, leg, report) {
let verdict;
try {
verdict = await judgeRowForTree(sessions, { sessionId: held.sessionId, occupant: async () => (await held.session.getMetadata()).incarnation, minted: leg.minted, runsOn: true }, { bound: true, owner: leg.owner }, leg.signal);
}
catch (err) {
await forgetHeld(sessions, held.sessionId, report);
throw err;
}
if (verdict.open)
return;
await forgetHeld(sessions, held.sessionId, report);
throw legRowRefusal(held.sessionId, verdict);
}
export function legRowRefusal(sessionId, verdict) {
if (verdict.kind === "store")
return rowStoreFaultError(sessionId, verdict);
return Object.assign(new Error(`the session row ${sessionId} does not record this delegation tree's owner: ${verdict.why}`), { code: DELEGATION_OWNER_MISMATCH });
}
export function judgedLegOf(spec, internals, treeOwner) {
if (treeOwner === undefined)
return undefined;
return { owner: treeOwner.owner, minted: spec.requireExistingSession !== true && (spec.sessionId === undefined || internals?.sessionIdMintedBySpawner === true), ...(spec.signal !== undefined ? { signal: spec.signal } : {}) };
}
export function readStandsAsJudged(judged, now) {
return judged !== null && now !== undefined && (now.owner ?? null) === (judged.owner ?? null) && sameOccupant(now.incarnation, judged.incarnation);
}
function forgetHeld(sessions, sessionId, report) {
return settleTeardownLeg(() => Promise.resolve(sessions.forget ? sessions.forget(sessionId) : undefined).catch(() => undefined), "forget (acquire-reconcile owner judgement leg)", report && ((e) => report(e, sessionId)));
}
export async function forkedRowNotOurs(sessions, forkedId, source) {
const drop = () => Promise.resolve(sessions.forget?.(forkedId)).catch(() => undefined);
let meta;
try {
meta = await (await sessions.acquire(forkedId, { requireExisting: true })).session.getMetadata();
}
catch {
await drop();
return `the forked session ${forkedId} could not be read (the session store's read failed) — nothing runs on it, and it is not released`;
}
if (meta.forkedFrom !== source.sessionId || (source.occupant !== null && !sameOccupant(meta.forkedFromIncarnation, source.occupant))) {
await drop();
return `the session ${forkedId} the store's fork answered is not a copy of this run's session as this run holds it — nothing runs on it, and it is not released`;
}
return undefined;
}
export function namesVerifiedSession(result) {
return result.sessionId !== "";
}
class OwnerReadStopped extends Error {
}
function boundedOwnerRead(read, signal, label) {
const stop = new AbortController();
const onStop = () => stop.abort(runAbortedError());
if (signal?.aborted === true)
onStop();
else
signal?.addEventListener("abort", onStop, { once: true });
return withGateTimeout(Promise.resolve().then(read), teardownLegBudget(), stop.signal, label)
.catch((err) => {
throw stop.signal.aborted ? new OwnerReadStopped() : err;
})
.finally(() => signal?.removeEventListener("abort", onStop));
}
function ownerReadEnd(err) {
return err instanceof OwnerReadStopped ? "stopped" : gateWaitFailureOf(err) === "timeout" ? "unanswered" : "faulted";
}
async function settled(read, signal) {
try {
return await boundedOwnerRead(read, signal, "delegation owner read");
}
catch (err) {
if (ownerReadEnd(err) === "stopped")
throw runAbortedError();
return { bound: false, reason: "the row that names it could not be read", fault: err };
}
}
export function readRootOccupant(internals, onError, sessionId) {
if (internals === undefined)
return undefined;
const { rootSessionId: rawRootId, placementRoot: rawPlacementRoot, rootSessionIncarnation: raw, rootSessionScope: rawScope, rootPrincipal: rawPrincipal, ...rest } = internals;
const rootSessionId = rootIdMember("rootSessionId", rawRootId);
const placementRoot = rootIdMember("placementRoot", rawPlacementRoot);
const disclose = (member, detail) => {
try {
onError?.(Object.assign(new Error(`RunInternals.${member}: ${detail}`), { code: "config.invalid_argument" }), { phase: "config", sessionId: sessionId ?? "(pre-session)", classification: "root-occupant" });
}
catch {
}
};
const token = readIncarnationCell(raw, (detail) => disclose("rootSessionIncarnation", detail));
const scope = typeof rawScope === "string" && rawScope !== "" ? rawScope : undefined;
if (scope === undefined && rawScope !== undefined && rawScope !== null)
disclose("rootSessionScope", `holds ${notANameShape(rawScope)} — read as no recorded box scope`);
const principal = rawPrincipal === null ? { kind: "absent" } : readPrincipal(rawPrincipal);
if (principal.kind === "invalid")
disclose("rootPrincipal", `is not a principal name (${principal.fault}) — read as no stated root principal: no leg below shares the root's session rules`);
const { delegationOwner, ...others } = rest;
return { ...others, ...(delegationOwner !== undefined ? { delegationOwner: answeringOnce(delegationOwner) } : {}), ...(rootSessionId !== undefined ? { rootSessionId } : {}), ...(placementRoot !== undefined ? { placementRoot } : {}), ...(token !== undefined ? { rootSessionIncarnation: token } : {}), ...(scope !== undefined ? { rootSessionScope: scope } : {}), ...(principal.kind === "name" ? { rootPrincipal: principal.name } : {}) };
}
function rootIdMember(member, raw) {
if (raw === undefined || raw === null)
return undefined;
if (typeof raw === "string" && raw !== "")
return raw;
throw Object.assign(new Error(`internals.${member} carries ${notANameShape(raw)} — a placement root is a session id (a non-empty string), and a malformed fixed point cannot key a placement lookup; fix the spawning lane instead of defaulting around it.`), { code: "config.placement_root_invalid" });
}
export function delegationOwnerOf(seat, signal) {
return seat === undefined ? Promise.resolve({ bound: true, owner: null }) : settled(() => seat.read(), signal);
}
export function rowOwnerReading(sessions, sessionId) {
return settled(async () => {
const headOf = sessions.headOf;
if (typeof headOf !== "function" || sessionId === undefined)
return { bound: true, owner: null };
const head = await headOf.call(sessions, sessionId);
return head === undefined ? { bound: true, owner: null } : ownerCellReading(sessionId, head);
});
}