@sema-agent/core
Version:
Stateless, task-oriented AI agent core
141 lines (140 loc) • 7.16 kB
JavaScript
import { strayMembersOf } from "./own-property-receipt.js";
const GRANT_HOLDER_PREFIX = "g1";
const PART = /^[A-Za-z0-9_-]+$/;
const UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
function wellFormed(s) {
for (let i = 0; i < s.length; i++) {
const c = s.charCodeAt(i);
if (c >= 0xd800 && c <= 0xdbff) {
const next = s.charCodeAt(i + 1);
if (!(next >= 0xdc00 && next <= 0xdfff))
return false;
i++;
}
else if (c >= 0xdc00 && c <= 0xdfff) {
return false;
}
}
return true;
}
function codedError(code, message) {
const e = new Error(message);
e.code = code;
return e;
}
function malformed(why) {
const e = codedError("holder.malformed", `grant holder is malformed: ${why} — it was not minted by encodeGrantHolder; the write it rode did not run`);
e.name = "GrantHolderMalformedError";
return e;
}
function partToEncode(name, value, codec = "encodeGrantHolder") {
if (typeof value !== "string" || value === "" || !wellFormed(value)) {
const kind = typeof value !== "string" ? (value === null ? "null" : `a ${typeof value}`) : value === "" ? "an empty string" : "a string with a lone surrogate";
throw codedError("config.invalid_argument", `${codec}: ${name} must be a non-empty, well-formed string (got ${kind})`);
}
return Buffer.from(value, "utf8").toString("base64url");
}
export function encodeGrantHolder(parts) {
const taskId = partToEncode("taskId", parts?.taskId);
const legId = partToEncode("legId", parts?.legId);
return `${GRANT_HOLDER_PREFIX}.${taskId}.${legId}`;
}
function decodePart(part, name, fail = malformed) {
if (!PART.test(part))
throw fail(`its ${name} part is not base64url`);
const bytes = Buffer.from(part, "base64url");
if (bytes.toString("base64url") !== part)
throw fail(`its ${name} part is not in the one encoding of its bytes`);
let text;
try {
text = UTF8.decode(bytes);
}
catch {
throw fail(`its ${name} part is not UTF-8`);
}
if (text === "")
throw fail(`its ${name} part is empty`);
return text;
}
export function decodeGrantHolder(holder) {
if (typeof holder !== "string")
throw malformed(`it is ${holder === null ? "null" : `a ${typeof holder}`}, not a string`);
const parts = holder.split(".");
if (parts.length !== 3 || parts[0] !== GRANT_HOLDER_PREFIX)
throw malformed(`it is not \`${GRANT_HOLDER_PREFIX}.<taskId>.<legId>\``);
return Object.freeze({ taskId: decodePart(parts[1], "taskId"), legId: decodePart(parts[2], "legId") });
}
const COMPOSITE_HOLDER_PREFIX = "h1";
function compositeMalformed(why) {
const e = codedError("holder.malformed", `composite holder is malformed: ${why} — it was not minted by encodeCompositeHolder; the write it rode did not run`);
e.name = "GrantHolderMalformedError";
return e;
}
function memberToEncode(of, key, where) {
try {
return of[key];
}
catch {
throw codedError("config.invalid_argument", `encodeCompositeHolder: ${where}${key} could not be read`);
}
}
const ENCODER_INPUT_WORDS = { subject: "encodeCompositeHolder's input", unit: "member", moment: "at encode" };
function objectToEncode(of, keys, where) {
let stray;
try {
stray = of !== null && typeof of === "object" && !Array.isArray(of) ? (strayMembersOf(of, ENCODER_INPUT_WORDS, keys)?.names.length ?? 0) : -1;
}
catch {
stray = -1;
}
if (stray === -1)
throw codedError("config.invalid_argument", `encodeCompositeHolder: ${where || "its input"} must be a plain object`);
if (stray > 0)
throw codedError("config.invalid_argument", `encodeCompositeHolder: ${where || "its input"} carries ${stray} member(s) outside ${keys.join(", ")}`);
}
export function encodeCompositeHolder(parts) {
objectToEncode(parts, ["grant", "occupancy"], "");
const grant = memberToEncode(parts, "grant", ""), occupancy = memberToEncode(parts, "occupancy", "");
if (grant === undefined && occupancy === undefined)
throw codedError("config.invalid_argument", "encodeCompositeHolder: a composite holder carries a grant half, an occupancy half, or both — got neither");
const part = (of, key, where) => partToEncode(key, memberToEncode(of, key, where), "encodeCompositeHolder");
if (grant !== undefined)
objectToEncode(grant, ["taskId", "legId"], "grant");
if (occupancy !== undefined)
objectToEncode(occupancy, ["rootSessionId", "owner", "incarnation"], "occupancy");
const g = grant === undefined ? ["", ""] : [part(grant, "taskId", "grant."), part(grant, "legId", "grant.")];
const o = occupancy === undefined ? ["", "", ""] : [part(occupancy, "rootSessionId", "occupancy."), memberToEncode(occupancy, "owner", "occupancy.") === null ? "" : part(occupancy, "owner", "occupancy."), part(occupancy, "incarnation", "occupancy.")];
return [COMPOSITE_HOLDER_PREFIX, ...g, ...o].join(".");
}
export function decodeCompositeHolder(holder) {
if (typeof holder !== "string")
throw compositeMalformed(`it is ${holder === null ? "null" : `a ${typeof holder}`}, not a string`);
const parts = holder.split(".");
if (parts.length !== 6 || parts[0] !== COMPOSITE_HOLDER_PREFIX)
throw compositeMalformed(`it is not \`${COMPOSITE_HOLDER_PREFIX}.<taskId>.<legId>.<rootSessionId>.<owner>.<incarnation>\``);
const [, taskId, legId, rootSessionId, owner, incarnation] = parts;
if ((taskId === "") !== (legId === ""))
throw compositeMalformed("its grant half carries only one of its two parts");
if ((rootSessionId === "") !== (incarnation === "") || (rootSessionId === "" && owner !== ""))
throw compositeMalformed("its occupancy half carries only some of its parts");
if (taskId === "" && rootSessionId === "")
throw compositeMalformed("it carries neither half");
const grant = taskId === "" ? undefined : Object.freeze({ taskId: decodePart(taskId, "taskId", compositeMalformed), legId: decodePart(legId, "legId", compositeMalformed) });
const occupancy = rootSessionId === "" ? undefined : Object.freeze({ rootSessionId: decodePart(rootSessionId, "rootSessionId", compositeMalformed), owner: owner === "" ? null : decodePart(owner, "owner", compositeMalformed), incarnation: decodePart(incarnation, "incarnation", compositeMalformed) });
return Object.freeze({ ...(grant !== undefined ? { grant } : {}), ...(occupancy !== undefined ? { occupancy } : {}) });
}
export function holderSupersededError(what) {
const e = codedError("holder.superseded", `${what}: the run's grant is no longer current (another leg holds the run, or the run has ended) — nothing was written; stop this leg, do not retry`);
e.name = "HolderSupersededError";
return e;
}
export function isHolderSuperseded(err) {
if (err === null || (typeof err !== "object" && typeof err !== "function"))
return false;
try {
return err.code === "holder.superseded";
}
catch {
return false;
}
}