UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

180 lines (179 loc) • 6.36 kB
import { SessionError, } from "../harness/types.js"; import { LineageBreak, pathToRoot, replayLossText } from "./path-to-root.js"; import { uuidv7 } from "./uuid.js"; import { holderJudgedCurrent, readHolderJudge } from "../../core/checkpoint-generation.js"; import { holderSupersededError } from "../../core/grant-holder.js"; import { refusalAbout } from "../../core/config-refusal-input.js"; export function entryParentLinks(byId) { return { read: (id) => byId.get(id), idOf: (entry) => entry.id, parentOf: (entry) => entry.parentId || null }; } function updateLabelCache(labelsById, entry) { if (entry.type !== "label") { return; } const label = entry.label?.trim(); if (label) { labelsById.set(entry.targetId, label); } else { labelsById.delete(entry.targetId); } } function buildLabelsById(entries) { const labelsById = new Map(); for (const entry of entries) { updateLabelCache(labelsById, entry); } return labelsById; } function generateEntryId(byId) { for (let i = 0; i < 100; i++) { const id = uuidv7().slice(-8); if (!byId.has(id)) { return id; } } return uuidv7(); } export function leafIdAfterEntry(entry) { return entry.type === "leaf" ? entry.targetId : entry.id; } export function sessionLogMarkOf(entries) { return { length: entries.length, lastEntryId: entries.length === 0 ? null : entries[entries.length - 1].id }; } export function resolveLeafId(entries) { let leafId = null; for (const entry of entries) { leafId = leafIdAfterEntry(entry); } return leafId; } function storageJudgeOf(readSlot) { let judge; try { judge = readSlot(); } catch { judge = undefined; } if (judge === null || typeof judge === "function") return judge; const e = new Error("The session storage's grant judge (`holderIsCurrent`, set when the storage was built) could not be read as a function or `null` through the object it was read from — a wrapper hid, replaced or broke it; nothing was written through it."); e.code = "config.invalid_session_store"; throw refusalAbout("deps", e); } export function storageBuiltWithJudge(storage) { return storageJudgeOf(() => storage.holderIsCurrent) !== null; } export class BaseSessionStorage { metadata; entries; byId; labelsById; leafId; floorId; replayLoss; holderIsCurrent; constructor(metadata, entries, leafId = resolveLeafId(entries), opts) { this.metadata = metadata; this.entries = entries; this.byId = new Map(entries.map((entry) => [entry.id, entry])); this.labelsById = buildLabelsById(entries); this.leafId = leafId; this.floorId = opts?.floorEntryId ?? null; this.replayLoss = opts?.replayLoss !== undefined && opts.replayLoss.dropped > 0 ? opts.replayLoss : undefined; this.holderIsCurrent = readHolderJudge("the session storage's holderIsCurrent", opts?.holderIsCurrent) ?? null; this.assertLeafHeld(); if (this.floorId !== null && !this.byId.has(this.floorId)) { throw new SessionError("corrupt_session", `Floor entry ${this.floorId} not loaded — the bounded window names a floor the loaded log does not hold${this.lostText()}`, undefined, "floor_missing"); } } lostText() { return this.replayLoss !== undefined ? ` (${replayLossText(this.replayLoss)})` : ""; } assertLeafHeld() { if (this.leafId !== null && !this.byId.has(this.leafId)) { throw new SessionError("corrupt_session", `Entry ${this.leafId} not found — the log's leaf names an entry the log does not hold${this.lostText()}`, undefined, "leaf_missing"); } } getFloorId() { return this.floorId; } getReplayLoss() { return this.replayLoss; } async getMetadata() { return this.metadata; } async getLeafId() { this.assertLeafHeld(); return this.leafId; } logMarkNow() { return sessionLogMarkOf(this.entries); } leafNow() { return this.leafId; } adoptRecordedOwner(metadata) { this.metadata = metadata; } createLeafEntry(leafId) { if (leafId !== null && !this.byId.has(leafId)) { throw new SessionError("not_found", `Entry ${leafId} not found`); } return { type: "leaf", id: generateEntryId(this.byId), parentId: this.leafId, timestamp: new Date().toISOString(), targetId: leafId, }; } async createEntryId() { return generateEntryId(this.byId); } assertExpectedLeaf(opts, what = "appendEntry") { const holder = opts?.holder; if (holder !== undefined && !holderJudgedCurrent(holder, storageJudgeOf(() => this.holderIsCurrent) ?? undefined, "session")) throw holderSupersededError(what); if (opts?.expectedLeafId !== undefined && opts.expectedLeafId !== this.leafId) { throw new SessionError("conflict", `Stale write: expected leaf ${opts.expectedLeafId ?? "(empty)"}, but current leaf is ${this.leafId ?? "(empty)"}`); } } recordEntry(entry) { this.entries.push(entry); this.byId.set(entry.id, entry); updateLabelCache(this.labelsById, entry); this.leafId = leafIdAfterEntry(entry); } async getEntry(id) { return this.byId.get(id); } async findEntries(type) { return this.entries.filter((entry) => entry.type === type); } async getLabel(id) { return this.labelsById.get(id); } async getPathToRoot(leafId) { if (leafId === null) { return []; } const leaf = this.byId.get(leafId); if (!leaf) { throw new SessionError("not_found", `Entry ${leafId} not found`); } try { return pathToRoot(leaf, entryParentLinks(this.byId), this.floorId); } catch (err) { if (err instanceof LineageBreak && this.replayLoss !== undefined) throw new LineageBreak(err.missingParentId, err.childId, this.replayLoss); throw err; } } async getEntries() { return [...this.entries]; } }