UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

193 lines (192 loc) • 10.6 kB
import { refusalAbout } from "./config-refusal-input.js"; import { strayMembersOf } from "./own-property-receipt.js"; export function checkpointRevOf(cp) { return cp.rev ?? 0; } export function checkpointOccMatches(cp, expect) { return expect === undefined || checkpointRevOf(cp) === expect.rev; } export function checkpointClaimRevOf(read) { return checkpointRevOf(read) + 1; } export function readHolderJudge(subject, value) { if (value === undefined || typeof value === "function") return value; const e = new Error(`${subject} must be a function (the deployment's synchronous grant judge) when given (got ${value === null ? "null" : `a ${typeof value}`})`); e.code = "config.invalid_argument"; throw e; } export function joinHolderJudge(judges, authority, judge, kind, what) { const mine = judge ?? null; if (!judges.has(authority)) { judges.set(authority, mine); return; } const theirs = judges.get(authority) ?? null; if (theirs === mine) return; const said = (j) => (j === null ? "no holder judge" : "a holder judge"); throw storeRefusal(kind, `${what}: this store joins an authority already built with ${theirs === null || mine === null ? said(theirs) : "another holder judge"}, but it brings ${theirs === null || mine === null ? said(mine) : "a different function"} — the judge belongs to the shared authority, so every store over it must be built with the same judge (one function object, or none beside none); nothing was joined.`); } const STORE_CODE = { checkpoint: "config.invalid_checkpoint_store", session: "config.invalid_session_store" }; function storeRefusal(kind, message) { const e = new Error(message); e.code = STORE_CODE[kind]; return e; } export function holderJudgedCurrent(holder, holderIsCurrent, kind) { if (holder === undefined) return true; if (holderIsCurrent === undefined) return false; let answer; try { answer = holderIsCurrent(holder); } catch (err) { throw withoutHolderText(err, holder); } if (typeof answer !== "boolean") { const said = answer === null ? "null" : typeof answer === "object" ? "an object (an async judge answers a promise)" : `a ${typeof answer}`; throw storeRefusal(kind, `the ${kind} store's \`holderIsCurrent\` judge must answer \`true\` or \`false\` synchronously (it answered ${said}) — any other answer is a wiring error, not a judgement; the write did not run and nothing was written. Make the judge a synchronous read of the grant table.`); } return answer === true; } function withoutHolderText(err, holder) { if (holder === "" || err === null || typeof err !== "object") return err; for (const member of ["message", "stack"]) { try { const text = err[member]; if (typeof text === "string" && text.includes(holder)) err[member] = text.split(holder).join("<holder>"); } catch { } } return err; } export function checkpointHolderMatches(expect, holderIsCurrent) { return holderJudgedCurrent(expect?.holder, holderIsCurrent, "checkpoint"); } const FENCE_KEYS = new Set(["holder", "requireHolder"]); export function readStoreFence(kind, seat, store, member = "fence") { let fence; try { fence = store === null || store === undefined ? undefined : store[member]; } catch { throw storeRefusal(kind, `${seat}: the store's \`${member}\` declaration could not be read (its accessor threw) — a declaration that does not answer is no declaration; fix the store.`); } if (fence === undefined) return undefined; const refuse = (what) => { throw storeRefusal(kind, `${seat}: the store's \`${member}\` declaration ${what} — a store that judges the holder of every write it is handed that carries one declares \`fence = { holder: "writes" }\` (optionally \`requireHolder: true\`), and a store that judges none declares nothing.`); }; if (fence === null || typeof fence !== "object") return refuse("is not an object"); let holder; let requireHolder; let keys; let isArray; try { isArray = Array.isArray(fence); keys = Reflect.ownKeys(fence).map(String); holder = fence.holder; requireHolder = fence.requireHolder; } catch { return refuse("could not be read (an accessor threw)"); } if (isArray) return refuse("is not an object"); if (holder === true) return refuse("is the retired `{ holder: true }`, which promised the holder of `resolve` alone; the one declaration is now `holder: \"writes\"` — the store judges the holder on every write (session append and leaf move; card put, steer, expire and resolve), and a store declaring the old value is refused rather than trusted with writes it never judged"); if (holder !== "writes") return refuse(`has \`holder\` ${typeof holder === "string" ? "set to another word" : holder === undefined ? "missing" : `of type ${holder === null ? "null" : typeof holder}`}, not "writes"`); if (requireHolder !== undefined && typeof requireHolder !== "boolean") return refuse(`has \`requireHolder\` of type ${requireHolder === null ? "null" : typeof requireHolder}, not a boolean`); const stray = keys.filter((k) => !FENCE_KEYS.has(k)); if (stray.length > 0) return refuse(`carries ${stray.length === 1 ? "a member" : "members"} it does not take (${stray.map((k) => JSON.stringify(k)).join(", ")})`); return Object.freeze(requireHolder === true ? { holder: "writes", requireHolder: true } : { holder: "writes" }); } export function assertStoreJudgesHolder(kind, seat, store, holder, startedBy) { if (store === undefined) return undefined; const fence = readStoreFence(kind, seat, store); const named = kind === "checkpoint" ? "CheckpointStore" : "SessionStore"; if (holder === undefined) { if (fence?.requireHolder !== true || startedBy === "engine") return fence; throw storeRefusal(kind, `${seat}: the wired ${named} declares \`requireHolder: true\` — this store requires every run or verb the host starts to carry a grant holder, and this one carries none, so it was refused before anything was written. Pass the grant the run acts under as \`RunInternals.holder\` (a session verb: the request's \`holder\`).`); } if (fence !== undefined) return fence; throw storeRefusal(kind, `${seat}: the run carries a grant holder, but the wired ${named} does not declare \`fence = { holder: "writes" }\` — a store that does not judge the holder on its writes would ignore it, and the fence would hold nothing. Wire a store that judges holders (the in-tree stores take \`holderIsCurrent\`) or stop passing one.`); } export function assertHolderValue(holder, seat = "RunInternals.holder") { if (holder === undefined || (typeof holder === "string" && holder !== "")) return; const kind = holder === "" ? "an empty string" : holder === null ? "null" : `a ${typeof holder}`; const what = seat === "RunInternals.holder" ? "the claim grant the run acts under" : "the session tree the run works in"; const e = new Error(`${seat} must be a non-empty string when present (got ${kind}) — it is the deployment's credential for ${what}; omit it for a run that acts under none.`); e.code = "config.invalid_argument"; throw e; } export function assertSessionSeatJudgesHolder(store, holder, startedBy) { const seat = "RunnerDeps.sessionStore"; if (holder !== undefined && startedBy === "engine" && store !== undefined && readStoreFence("session", seat, store) === undefined) { const routed = readStoreFence("session", seat, store, "durableFence"); if (routed !== undefined) return routed; } return assertStoreJudgesHolder("session", seat, store, holder, startedBy); } const RESIDENCE_WORDS = { subject: "a storage's residence", unit: "member", moment: "at station 2" }; export function sessionStorageJudges(store, storage) { const seat = "RunnerDeps.sessionStore"; if (readStoreFence("session", seat, store) !== undefined) return true; const refusal = (what) => refusalAbout("deps", storeRefusal("session", `${seat}: the leg carries a tree holder and the session store declares \`durableFence\` (each storage it hands out answers for itself), but the storage it handed out ${what} — a storage that cannot say where it lives and whether it judges is not written under a holder; the leg wrote nothing. Answer \`getResidence()\` synchronously with { durability: "durable" | "process-local", fence? }.`)); const answer = (() => { try { const read = storage === null || storage === undefined ? undefined : storage.getResidence; if (typeof read !== "function") return { why: "does not answer `getResidence()`" }; const residence = read.call(storage); if (residence === null || typeof residence !== "object" || Array.isArray(residence)) return { why: "answered `getResidence()` with no object" }; const then = residence.then; if (typeof then === "function") { Promise.resolve(residence).catch(() => undefined); return { why: "answered `getResidence()` with a promise" }; } const stray = strayMembersOf(residence, RESIDENCE_WORDS, ["durability", "fence"])?.names.length ?? 0; if (stray > 0) return { why: `answered ${stray} member(s) outside \`durability\` and \`fence\`` }; return { residence }; } catch { return { why: "could not be read (`getResidence()` threw, or its answer did)" }; } })(); if ("why" in answer) throw refusal(answer.why); let durability; let fence; try { durability = answer.residence.durability; fence = readStoreFence("session", `${seat} (the handed storage's residence)`, answer.residence); } catch { throw refusal("answered a `durability` or a `fence` that could not be read or is malformed"); } if (durability !== "durable" && durability !== "process-local") throw refusal("answered a durability outside the two words"); if (fence !== undefined) return true; if (durability === "process-local") return false; throw refusal("answered durable and declares no fence"); }