@sema-agent/core
Version:
Stateless, task-oriented AI agent core
261 lines (260 loc) • 14.2 kB
JavaScript
import { SessionError, } from "../harness/types.js";
import { StoredSession } from "./session.js";
import { uuidv7 } from "./uuid.js";
import { PRINCIPAL_NAME_SPELLING, principalNameFault, principalNameOf, recordedPrincipalNameOf } from "../../core/principal-name.js";
import { receiptRefusal } from "../../core/own-property-receipt.js";
import { createHash, randomUUID } from "node:crypto";
export function createSessionId() {
return uuidv7();
}
export function incarnationCell(existing, tokenless = "keep") {
if (tokenless !== "keep" && tokenless !== "mint") {
throw receiptRefusal(`incarnationCell: tokenless must be "keep" or "mint", got ${typeof tokenless === "string" ? "another string" : nonStringShape(tokenless)}`);
}
if (existing === undefined)
return { incarnation: `${randomUUID()}${ADDRESS_EPOCH_MARK}` };
if (existing.incarnation !== undefined)
return { incarnation: existing.incarnation };
return tokenless === "mint" ? { incarnation: randomUUID() } : {};
}
const ADDRESS_EPOCH_MARK = ".2";
const ADDRESS_EPOCH_TOKEN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.2$/;
const ADDRESS_SEPARATOR = "~";
const BASE64URL_CLASS = "[A-Za-z0-9_-]";
export const FILE_HISTORY_SCOPE_TAIL_LENGTH = 22;
export const FILE_HISTORY_SCOPE_SUFFIX_LENGTH = ADDRESS_SEPARATOR.length + FILE_HISTORY_SCOPE_TAIL_LENGTH;
const ADDRESS_TAIL = new RegExp(`${ADDRESS_SEPARATOR}${BASE64URL_CLASS}{${FILE_HISTORY_SCOPE_TAIL_LENGTH}}!*$`);
export function sessionIdHasScopeTail(sessionId) {
return ADDRESS_TAIL.test(sessionId);
}
export function fileHistoryScopeOf(sessionId, occupant) {
if (occupant !== undefined && ADDRESS_EPOCH_TOKEN.test(occupant)) {
return `${sessionId}${ADDRESS_SEPARATOR}${createHash("sha256").update(occupant).digest("base64url").slice(0, FILE_HISTORY_SCOPE_TAIL_LENGTH)}`;
}
if (sessionIdHasScopeTail(sessionId)) {
throw Object.assign(new Error(`fileHistoryScopeOf: session "${sessionId}" ends like a file-history address but its occupant was not minted in the address epoch — a caller-chosen id collides with the address epoch; re-id the session (its file history is not read, written or deleted)`), { code: "config.invalid_argument" });
}
return sessionId;
}
const ADDRESS_END = new RegExp(`${ADDRESS_SEPARATOR}(${BASE64URL_CLASS}{${FILE_HISTORY_SCOPE_TAIL_LENGTH}})$`);
export function readFileHistoryScope(scope) {
if (scope === "")
return undefined;
const address = ADDRESS_END.exec(scope);
if (address !== null)
return address.index === 0 ? undefined : { sessionId: scope.slice(0, address.index), tail: address[1] };
return sessionIdHasScopeTail(scope) ? undefined : { sessionId: scope };
}
export function readIncarnationCell(raw, disclose) {
if (isOccupantToken(raw))
return raw;
if (raw === undefined || raw === null)
return undefined;
disclose(`the incarnation cell holds ${notANameShape(raw)} — read as an unknown occupant`);
return undefined;
}
export function notANameShape(raw) {
return raw === "" ? "an empty string" : nonStringShape(raw);
}
export function isOccupantToken(raw) {
return typeof raw === "string" && raw !== "";
}
function nonStringShape(raw) {
return Array.isArray(raw) ? "a non-string value (array)" : `a non-string value (${typeof raw})`;
}
export function sameOccupant(held, current) {
return (isOccupantToken(held) ? held : undefined) === (isOccupantToken(current) ? current : undefined);
}
export function compareOccupants(before, after) {
if (before === undefined || after === undefined)
return "unknown";
return sameOccupant(before.incarnation, after.incarnation) ? "same" : "different";
}
export function sessionRowMatches(expect, row, logNow) {
if (expect === undefined)
return true;
const want = readRowExpectation(expect);
if (want.row === null)
return row === undefined;
if (row === undefined || (row.owner ?? null) !== want.row.owner || row.incarnation !== want.row.incarnation)
return false;
if (want.log === undefined)
return true;
const now = logNow();
return now.length === want.log.length && now.lastEntryId === want.log.lastEntryId;
}
export function readRowExpectation(expect) {
if (typeof expect !== "object" || expect === null)
throw new TypeError(`a session row expectation must be an object { row, log? }, got ${expect === null ? "null" : typeof expect}`);
const { row, log } = expect;
const mark = log === undefined ? undefined : readLogMark(log);
if (row === null)
return { row: null, ...(mark !== undefined ? { log: mark } : {}) };
if (typeof row !== "object" || row === undefined)
throw new TypeError(`a session row expectation's row must be the row's owner and occupant, or null (no row), got ${typeof row}`);
const { owner, incarnation } = row;
if (owner !== null && typeof owner !== "string")
throw new TypeError(`a session row expectation's row.owner must be a principal name or null, got ${typeof owner}`);
if (incarnation !== undefined && typeof incarnation !== "string")
throw new TypeError(`a session row expectation's row.incarnation must be a string or absent, got ${typeof incarnation}`);
return { row: { owner, incarnation }, ...(mark !== undefined ? { log: mark } : {}) };
}
function readLogMark(log) {
if (typeof log !== "object" || log === null)
throw new TypeError(`a session row expectation's log must be a log mark { length, lastEntryId }, got ${log === null ? "null" : typeof log}`);
const { length, lastEntryId } = log;
if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 0)
throw new TypeError(`a session row expectation's log.length must be an integer ≥ 0`);
if (lastEntryId !== null && typeof lastEntryId !== "string")
throw new TypeError(`a session row expectation's log.lastEntryId must be an entry id or null, got ${typeof lastEntryId}`);
if ((length === 0) !== (lastEntryId === null))
throw new TypeError(`a session row expectation's log is no log's mark: lastEntryId is null exactly when length is 0 (the empty log), got length ${length} with ${lastEntryId === null ? "no last entry" : "a last entry"}`);
return { length, lastEntryId };
}
export function rowExpectationMissed(sessionId, what) {
return new SessionError("conflict", `session ${sessionId} is not the row the ${what} expected (it was deleted, created again, or written since it was read) — nothing was written; read the row again`);
}
export function sessionHeadOf(meta, leafId) {
return { owner: meta.owner ?? null, ...(meta.incarnation !== undefined ? { incarnation: meta.incarnation } : {}), leafId };
}
export async function headOfSession(session) {
const meta = await session.getMetadata();
return sessionHeadOf(meta, await session.getStorage().getLeafId());
}
function notAnOwnerShape(raw) {
return typeof raw === "string" ? principalNameFault(raw) : nonStringShape(raw);
}
export function ownerCell(owner) {
if (owner === null)
return { owner: null };
const name = principalNameOf(owner);
if (name === undefined)
throw new TypeError(`session owner must be a principal name (${PRINCIPAL_NAME_SPELLING}) or null (anonymous), got ${notAnOwnerShape(owner)}`);
return { owner: name };
}
export function importRowCells(sessionId, owner, existing, createdAt) {
const named = ownerCell(owner === undefined ? null : owner);
if (existing === undefined)
return { id: sessionId, createdAt, ...incarnationCell(undefined), ...named };
if (existing.placement !== undefined)
throw new SessionError("placement_refused", `session ${sessionId} belongs to the ${existing.placement.kind} placement partition — an import cannot replace its log`);
if ((existing.owner ?? null) !== named.owner)
throw new SessionError("conflict", `session ${sessionId} is not the importer's row — an import replaces only a log whose row the importer owns (or an anonymous row, by an anonymous import); nothing was written`);
return existing;
}
export function recordedOwnerName(owner) {
const name = principalNameOf(owner);
if (name === undefined)
throw receiptRefusal(`recordOwner: the owner to record must be a principal name (${PRINCIPAL_NAME_SPELLING}), got ${notAnOwnerShape(owner)} — refused before the row was read, nothing written`);
return name;
}
export function recordedOwnerCells(sessionId, name, existing, expect, matches) {
readRowExpectation(expect);
if ((existing.owner ?? null) !== null)
return undefined;
if (!matches())
throw rowExpectationMissed(sessionId, "owner record");
return { ...existing, owner: name };
}
export function readOwnerCell(raw, sessionId) {
if (raw === undefined || raw === null)
return null;
const name = recordedPrincipalNameOf(raw);
if (name !== undefined)
return name;
throw new SessionError("corrupt_session", `session ${sessionId}'s owner cell holds ${notAnOwnerShape(raw)} — neither an owner nor anonymous; refusing to read the row`, undefined, "bad_cell");
}
const PLACEMENT_KINDS = ["subagent"];
const PLACEMENT_STRING_MEMBERS = ["scope", "parentSessionId", "rootSessionId", "handle"];
function isPlacementKind(raw) {
return PLACEMENT_KINDS.some((kind) => kind === raw);
}
function placementFaultSentence(sessionId, fault) {
const { cell, held, expected } = fault;
const shape = held === null ? "null" : Array.isArray(held) ? "an array" : held === "" ? "an empty string" : `a ${typeof held}`;
return `session ${sessionId}'s ${cell} ${held === undefined ? "is not there" : `holds ${shape}`} — ${expected}`;
}
function judgePlacementCell(raw) {
if (raw === undefined)
return { placement: undefined };
if (typeof raw !== "object" || raw === null || Array.isArray(raw))
return { fault: { cell: "placement cell", held: raw, expected: "a placement is a tuple (an object) or not there at all" } };
const cell = { ...raw };
const { kind, placedAt } = cell;
if (!isPlacementKind(kind))
return { fault: { cell: "placement.kind", held: kind, expected: `a placement names one of its kinds (${PLACEMENT_KINDS.join(", ")})` } };
for (const member of PLACEMENT_STRING_MEMBERS) {
if (cell[member] !== undefined && typeof cell[member] !== "string")
return { fault: { cell: `placement.${member}`, held: cell[member], expected: "a string when there" } };
}
if (typeof placedAt !== "number" || !Number.isFinite(placedAt))
return { fault: { cell: "placement.placedAt", held: placedAt, expected: "a finite number (epoch ms)" } };
return { placement: { ...cell, kind, placedAt } };
}
export function readPlacementCell(raw, sessionId) {
const judged = judgePlacementCell(raw);
if ("fault" in judged)
throw new SessionError("corrupt_session", `${placementFaultSentence(sessionId, judged.fault)}; refusing to read the row`, undefined, "bad_cell");
return judged.placement;
}
export function placementCellToWrite(given, sessionId, now) {
const tuple = typeof given === "object" && given !== null && !Array.isArray(given);
const judged = judgePlacementCell(tuple ? { ...given, placedAt: given["placedAt"] ?? now } : given);
if ("fault" in judged)
throw receiptRefusal(`${placementFaultSentence(sessionId, judged.fault)}; refused before anything was written`);
return judged.placement;
}
export function assertForkTarget(sourceId, targetId) {
if (targetId === sourceId)
throw new SessionError("invalid_fork_target", `cannot fork session ${sourceId} onto its own id — fork into a new id`);
}
export function forkTargetTaken(targetId) {
return new SessionError("conflict", `cannot fork onto session ${targetId}: a row already stands under that id — nothing was written; fork into a new id, or, to replace that row, delete it (expecting the row you mean) and fork again`);
}
export function forkRowCells(source, owner) {
return { forkedFrom: source.id, ...(source.incarnation !== undefined ? { forkedFromIncarnation: source.incarnation } : {}), ...incarnationCell(undefined), ...ownerCell(owner ?? source.owner ?? null) };
}
export function frozenRow(meta) {
if (meta.placement !== undefined)
Object.freeze(meta.placement);
return Object.freeze(meta);
}
export function createTimestamp() {
return new Date().toISOString();
}
export function toSession(storage) {
return new StoredSession(storage);
}
function rerootIfHeadless(storage, entries) {
const head = entries[0];
if (head === undefined || head.parentId === null)
return entries;
if (entries.some((e) => e.id === head.parentId))
return entries;
if (storage.getFloorId?.() !== head.id)
return entries;
return [{ ...head, parentId: null }, ...entries.slice(1)];
}
export async function getEntriesToFork(storage, options) {
if (!options.entryId) {
return rerootIfHeadless(storage, await storage.getEntries());
}
const target = await storage.getEntry(options.entryId);
if (!target) {
throw new SessionError("invalid_fork_target", `Entry ${options.entryId} not found`);
}
let effectiveLeafId;
if ((options.position ?? "before") === "at") {
effectiveLeafId = target.id;
}
else {
if (target.type !== "message" || target.message.role !== "user") {
throw new SessionError("invalid_fork_target", `Entry ${options.entryId} is not a user message`);
}
effectiveLeafId = target.parentId;
if (effectiveLeafId !== null && storage.getFloorId?.() === target.id) {
throw new SessionError("invalid_fork_target", `Entry ${options.entryId} is the floor of a bounded session window — forking "before" it would branch from history this session did not load. Fork "at" it, or wake the session unbounded first.`);
}
}
return rerootIfHeadless(storage, await storage.getPathToRoot(effectiveLeafId));
}