UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

222 lines (221 loc) • 11.7 kB
import { isAddStamp, readRowBehavior, RULE_ADD_ORIGINS } from "./permission-rule-model.js"; import { isValidConsentScope, normalizePersistedRule } from "./permission-rule-store.js"; import { readRuleOwner } from "./rule-owner.js"; export const SESSION_PARTITION_ADDRESSINGS = Object.freeze(["session-row-key"]); const KEY_TAG = "session-row"; const KEY_FORM = 1; function keyRefusal(message) { return Object.assign(new Error(message), { code: "config.invalid_argument" }); } export function sessionRowKeyOf(owner, sessionId) { const o = readRuleOwner(owner); if (o === undefined) throw keyRefusal("sessionRowKeyOf: the owner is neither a principal owner naming a principal name nor the local owner"); if (typeof sessionId !== "string" || sessionId === "") throw keyRefusal("sessionRowKeyOf: a session is named by a non-empty string id"); return JSON.stringify(o.kind === "principal" ? [KEY_TAG, KEY_FORM, "principal", o.principal, sessionId] : [KEY_TAG, KEY_FORM, "local-owner", sessionId]); } function isSessionRowKey(raw) { if (typeof raw !== "string") return false; let v; try { v = JSON.parse(raw); } catch { return false; } if (!Array.isArray(v) || v[0] !== KEY_TAG || v[1] !== KEY_FORM) return false; const owner = v[2] === "principal" && v.length === 5 ? { kind: "principal", principal: v[3] } : v[2] === "local-owner" && v.length === 4 ? { kind: "local-owner" } : undefined; if (owner === undefined) return false; try { return sessionRowKeyOf(owner, v[v.length - 1]) === raw; } catch { return false; } } function keyed(raw, verb) { if (!isSessionRowKey(raw)) throw keyRefusal(`InMemorySessionRulePartition.${verb} is addressed by a session row key (sessionRowKeyOf(owner, sessionId)), and was handed something else`); return raw; } function isValidOverlayAdd(add) { const a = add; if (typeof a?.dot?.actor !== "string" || a.dot.actor === "" || typeof a.dot.counter !== "number" || !Number.isFinite(a.dot.counter)) return false; if (!RULE_ADD_ORIGINS.some((word) => a.origin === word)) return false; if (a.peerFingerprint !== undefined && !isAddStamp(a.peerFingerprint)) return false; return typeof a.createdAt === "string"; } export class InMemorySessionRulePartition { rows = new Map(); sealed = new Set(); epochs = new Map(); revokedDots = new Map(); addressedBy = "session-row-key"; bumpEpoch(key) { this.epochs.set(key, (this.epochs.get(key) ?? 0) + 1); } async read(key) { keyed(key, "read"); return structuredClone(this.rows.get(key) ?? []); } async apply(key, add) { keyed(key, "apply"); if (this.sealed.has(key)) return { refused: "session_ended" }; add = structuredClone(add); if (this.sealed.has(key)) return { refused: "session_ended" }; if (!isValidOverlayAdd(add?.add)) { throw new Error("SessionRulePartition.apply was handed a malformed add (dot/origin/createdAt) — evidence this shape cannot vouch for must not install"); } const scope = { kind: "session", sessionId: key }; if (!isValidConsentScope(scope)) { throw new Error("SessionRulePartition.apply was addressed with an unusable session id — a session nobody can name is not a scope a grant can live under"); } const projected = { behavior: add.behavior, rule: add.rule, tool: add.tool, match: add.match, command: add.command, scope, adds: [add.add] }; if ("reject" in normalizePersistedRule(projected)) { throw new Error("SessionRulePartition.apply was handed a row whose text/metadata do not survive the canonical re-projection — a row the engine cannot re-project can never adjudicate, and would refuse its own restore"); } if (this.revokedDots.get(key)?.has(`${add.add.dot.actor}#${add.add.dot.counter}`) === true) return { landed: true }; const rows = this.rows.get(key) ?? []; if (!this.rows.has(key)) this.rows.set(key, rows); const sameDotAs = (a) => a.dot.actor === add.add.dot.actor && a.dot.counter === add.add.dot.counter; for (const [heldSession, heldRows] of this.rows) { const holder = heldRows.find((r) => r.adds.some(sameDotAs)); if (holder !== undefined && (heldSession !== key || holder.rule !== add.rule || holder.behavior !== add.behavior)) { throw new Error(`SessionRulePartition.apply: dot ${add.add.dot.actor}#${add.add.dot.counter} already vouches for another grant — a dot identifies one add of one (behavior, rule, session), ever`); } } const existing = rows.find((r) => r.rule === add.rule && r.behavior === add.behavior); if (existing === undefined) { rows.push({ behavior: add.behavior, rule: add.rule, tool: add.tool, match: add.match, command: add.command, scope, adds: [structuredClone(add.add)] }); this.bumpEpoch(key); return { landed: true }; } if (!existing.adds.some((a) => a.dot.actor === add.add.dot.actor && a.dot.counter === add.add.dot.counter)) { existing.adds.push(structuredClone(add.add)); this.bumpEpoch(key); } return { landed: true }; } endSession(key) { keyed(key, "endSession"); this.sealed.add(key); this.rows.delete(key); this.revokedDots.delete(key); this.bumpEpoch(key); } async revoke(key, target) { keyed(key, "revoke"); if (this.sealed.has(key)) return { refused: "session_ended" }; const t = structuredClone(target); if (this.sealed.has(key)) return { refused: "session_ended" }; const behavior = readRowBehavior(t?.behavior); if (behavior === undefined || t?.behavior === undefined || typeof t?.rule !== "string" || t.rule === "") { throw new Error("SessionRulePartition.revoke was handed a target that names no row (a behavior of deny/ask/allow and a rule text) — refusing rather than answering a revocation of nothing"); } const rows = this.rows.get(key) ?? []; const at = rows.findIndex((r) => r.behavior === behavior && r.rule === t.rule); if (at < 0) return { revoked: 0 }; const [gone] = rows.splice(at, 1); const revoked = this.revokedDots.get(key) ?? new Set(); for (const a of gone.adds) revoked.add(`${a.dot.actor}#${a.dot.counter}`); this.revokedDots.set(key, revoked); this.bumpEpoch(key); return { revoked: 1 }; } async snapshotSession(key) { return this.read(key); } async restoreSession(key, rows) { keyed(key, "restoreSession"); if (this.sealed.has(key)) { throw new Error(`session "${key}" has ended — a sealed session's authorizations cannot be restored (termination is one-way)`); } const epochBeforeRead = this.epochs.get(key) ?? 0; rows = structuredClone(rows); if (this.sealed.has(key)) { throw new Error(`session "${key}" has ended — a sealed session's authorizations cannot be restored (termination is one-way)`); } if ((this.epochs.get(key) ?? 0) !== epochBeforeRead) { throw new Error(`restoreSession("${key}") raced a landing on the same session — refusing the whole restore (this door replaces the session's rows, and a grant that already answered landed must not be erased by a resume)`); } for (const r of rows) { const behavior = readRowBehavior(r?.behavior); if (behavior !== undefined && r !== null && typeof r === "object") r.behavior = behavior; const scope = r?.scope; if (scope?.kind !== "session" || scope.sessionId !== key || !isValidConsentScope(scope)) { throw new Error(`restoreSession("${key}") was handed a row that is not a session row of that session — refusing the whole restore (a foreign-scope row through this door would reach adjudication)`); } if ("reject" in normalizePersistedRule(r)) { throw new Error(`restoreSession("${key}") was handed a row whose text/metadata do not survive the canonical re-projection — refusing the whole restore (a row the engine cannot re-project must not reach adjudication)`); } } const identityOf = (r) => `${r.behavior}|${r.rule}`; const ownDotRule = new Map(); for (const held of this.rows.get(key) ?? []) { for (const h of held.adds) ownDotRule.set(`${h.dot.actor}#${h.dot.counter}`, identityOf(held)); } const seenDots = new Map(); for (const r of rows) { if (!Array.isArray(r.adds) || r.adds.length === 0 || !r.adds.every(isValidOverlayAdd)) { throw new Error(`restoreSession("${key}") was handed a row with malformed add evidence — refusing the whole restore (an add whose dot/origin cannot be read is not a consent anyone can audit)`); } for (const a of r.adds) { const dotKey = `${a.dot.actor}#${a.dot.counter}`; const holder = seenDots.get(dotKey); if (holder !== undefined && holder !== identityOf(r)) { throw new Error(`restoreSession("${key}"): dot ${dotKey} vouches for two different rules — refusing the whole restore`); } seenDots.set(dotKey, identityOf(r)); const ownHolder = ownDotRule.get(dotKey); if (ownHolder !== undefined && ownHolder !== identityOf(r)) { throw new Error(`restoreSession("${key}"): dot ${dotKey} is live in this session under a different rule — a restore may replay a grant, never reassign its dot; refusing the whole restore`); } for (const [heldSession, heldRows] of this.rows) { if (heldSession === key) continue; if (heldRows.some((held) => held.adds.some((h) => h.dot.actor === a.dot.actor && h.dot.counter === a.dot.counter))) { throw new Error(`restoreSession("${key}"): dot ${dotKey} already vouches for another live session's grant — refusing the whole restore`); } } } } const restoredDots = new Set(rows.flatMap((r) => r.adds.map((a) => `${a.dot.actor}#${a.dot.counter}`))); const carried = []; for (const held of this.rows.get(key) ?? []) { if (held.behavior === "allow") continue; const adds = held.adds.filter((a) => !restoredDots.has(`${a.dot.actor}#${a.dot.counter}`)); if (adds.length === 0) continue; const same = rows.find((r) => r.behavior === held.behavior && r.rule === held.rule); if (same !== undefined) same.adds.push(...structuredClone(adds)); else carried.push({ ...structuredClone(held), adds: structuredClone(adds) }); } const revoked = this.revokedDots.get(key); const restored = revoked === undefined ? rows : rows.flatMap((r) => { const adds = r.adds.filter((a) => !revoked.has(`${a.dot.actor}#${a.dot.counter}`)); return adds.length === 0 ? [] : [{ ...r, adds }]; }); this.rows.set(key, [...restored, ...carried]); this.bumpEpoch(key); } }