@sema-agent/core
Version:
Stateless, task-oriented AI agent core
697 lines (696 loc) • 32.7 kB
JavaScript
import { InMemorySessionRepo, ParentChainGuard, SessionError, findUnansweredToolBatch, compareOccupants, ownerCell, readSessionRepoRowCells, recordedOwnerName, sessionLogMarkOf, sessionRowMatches, uuidv7, } from "../internal/harness.js";
import { isSessionConflict, readSessionListQuery, readUnreadableDeleteId, rowUnreadableAt } from "./session.js";
import { readHolderJudge } from "./checkpoint-generation.js";
import { readRetentionDeclaration } from "./retention.js";
import { readMember, thrownText } from "./thrown-value.js";
import { principalNameFault, RECORDED_PRINCIPAL_NAME_SPELLING, recordedPrincipalNameOf } from "./principal-name.js";
import { DECLARATION_RECEIPT_MODE, optionKeys, receiptRefusal, receiveMembers, receiveOptions } from "./own-property-receipt.js";
import { describeFault, receive } from "./mods/kernel/receive.js";
import { describeRejectedValue } from "./tool-search-setting.js";
import { readIntegerOption, TIMER_DELAY_MS } from "./integer-option.js";
import { repoLogTransfer } from "./session-log-transfer.js";
import { readOccupantExpectation } from "./runner/session-verb-doors.js";
import { deliverEngineNotice } from "./engine-notice.js";
import { HolderLatch } from "./holder-latch.js";
import { isLegCloseRecord } from "./leg-close-records.js";
let ownerDeleteWithheldSaid = false;
export function __resetSessionDeleteWithheldNotice() {
ownerDeleteWithheldSaid = false;
}
const DAY_MS = 24 * 60 * 60 * 1000;
import { SESSION_DEFAULT_TTL_DAYS } from "../config/defaults.js";
export { SESSION_DEFAULT_TTL_DAYS };
export function admitSessionPlacement(sessionId, persisted, request, capability) {
if (persisted !== undefined && request.requireExisting !== true && request.placement === undefined) {
throw new SessionError("placement_refused", `session ${sessionId} belongs to the ${persisted.kind} placement partition — a claim-form acquire cannot attach to it (read it with requireExisting, or address the agent through its a* handle)`);
}
if (request.placement !== undefined && request.requireExisting !== true && capability.subagentPlacement) {
const want = request.placement;
if (persisted === undefined) {
throw new SessionError("placement_refused", `session ${sessionId} exists OUTSIDE the ${want.kind} placement partition it was declared into — refusing to run a subagent transcript on it (a concurrent claim-form create won this id, or the repo dropped the tuple)`);
}
if (persisted.kind !== want.kind || persisted.scope !== want.scope || persisted.handle !== want.handle) {
throw new SessionError("placement_refused", `session ${sessionId}'s persisted placement does not match the declared one (persisted ${persisted.kind}/${persisted.scope ?? "-"}/${persisted.handle ?? "-"} vs declared ${want.kind}/${want.scope ?? "-"}/${want.handle ?? "-"}) — refusing a cross-tuple attach`);
}
}
}
function createdCells(opts) {
const placement = opts?.placement, owner = opts?.owner;
return { ...(placement !== undefined ? { placement } : {}), ...(owner !== undefined ? { owner } : {}) };
}
const TTL_SESSION_STORE_OPTION_KEYS = optionKeys()({ defaultTtlDays: 0, sweepIntervalMs: 0, repo: 0, holderIsCurrent: 0, evict: 0, durability: 0, placements: 0, retention: 0, hooks: 0 });
export const STORE_HOOK_KEYS = optionKeys()({ beforeSessionDelete: 0 });
export class TtlSessionStore {
retention;
durability;
placements;
fence;
transcriptDirectory;
listPlaced;
headOf;
repoHead;
readRow;
logTransfer;
delete;
deleteUnreadable;
recordOwner;
judgesRows = false;
beforeRowDelete;
repo;
latch = new HolderLatch(this);
entries = new Map();
pending = new Map();
pendingPlacedDeletes = new Set();
releasing = new Map();
resolutions = new Map();
pinned = new Set();
defaultTtlMs;
evictPolicy;
sweepTimer;
constructor(options) {
const opts = receiveOptions(options, "TtlSessionStore", TTL_SESSION_STORE_OPTION_KEYS);
this.retention = readRetentionDeclaration("TtlSessionStoreOptions.retention", opts.retention);
const givenRepo = opts.repo;
const judge = readHolderJudge("TtlSessionStoreOptions.holderIsCurrent", opts.holderIsCurrent);
if (judge !== undefined && givenRepo !== undefined)
throw receiptRefusal("TtlSessionStoreOptions: `holderIsCurrent` and `repo` were both given — the judge has one place: the store's own default repo takes `holderIsCurrent`, a repo you supply takes it itself (`new InMemorySessionRepo({ holderIsCurrent })`, `FileSessionRepo(root, { holderIsCurrent })`)");
this.repo = givenRepo ?? new InMemorySessionRepo(judge !== undefined ? { holderIsCurrent: judge } : undefined);
if (readSessionRepoRowCells("TtlSessionStoreOptions.repo", this.repo.rowCells) === "host") {
throw receiptRefusal(`TtlSessionStoreOptions.repo holds no occupant cells (rowCells "host") and this layer has no occupant source — a repo whose host holds the occupant is served by the host's own session store, which puts the occupant on the metadata its sessions answer and on its head read`);
}
const durability = opts.durability !== undefined ? durabilityWord("TtlSessionStoreOptions.durability", opts.durability) : givenRepo === undefined ? "process-local" : undefined;
if (durability !== undefined)
this.durability = durability;
this.defaultTtlMs = ttlDays(opts.defaultTtlDays) * DAY_MS;
this.evictPolicy = opts.evict !== undefined ? evictWord(opts.evict) : givenRepo ? "forget" : "delete";
if (opts.placements !== undefined)
this.placements = placementsDeclaration(opts.placements);
const repoFence = this.repo.fence;
if (repoFence !== undefined)
this.fence = repoFence;
const repoTranscripts = this.repo.transcriptDirectory;
if (typeof repoTranscripts === "string" && repoTranscripts !== "")
this.transcriptDirectory = repoTranscripts;
const repoListPlaced = this.repo.listPlaced;
if (typeof repoListPlaced === "function") {
this.listPlaced = (kind, o) => repoListPlaced.call(this.repo, kind, o);
}
const repoHeadOf = this.repo.headOf;
if (typeof repoHeadOf === "function") {
const repoHead = (sessionId) => repoHeadOf.call(this.repo, sessionId);
this.repoHead = repoHead;
this.headOf = repoHead;
const { readRow, importEntries, deleteUnreadable, placementOf, recordOwner } = this.repo;
if (typeof readRow === "function")
this.readRow = (sessionId) => readRow.call(this.repo, sessionId);
if (typeof recordOwner === "function") {
this.recordOwner = async (sessionId, owner, expect) => {
this.latch.refuse("TtlSessionStore.recordOwner");
const name = recordedOwnerName(owner);
await this.settledHolds(sessionId);
return recordOwner.call(this.repo, sessionId, name, expect);
};
}
if (typeof deleteUnreadable === "function") {
const repoRemoval = (sessionId) => deleteUnreadable.call(this.repo, sessionId);
this.deleteUnreadable = (sessionId) => this.deleteUnreadableRow(sessionId, repoHead, repoRemoval);
}
if (typeof readRow === "function") {
this.judgesRows = true;
if (typeof placementOf === "function") {
const repoPlacement = (sessionId) => placementOf.call(this.repo, sessionId);
this.delete = (sessionId, guard) => this.deleteOwned(sessionId, guard, repoHead, repoPlacement);
}
else if (!ownerDeleteWithheldSaid) {
ownerDeleteWithheldSaid = true;
deliverEngineNotice(undefined, {
code: "config.session_delete_withheld",
message: "TtlSessionStore: the repo has a head read (headOf) and a row read (readRow) but no header-only placement read (placementOf), so this store offers no owner's delete (SessionStore.delete is absent): that delete is judged on the row's head, never on its log — give the repo a placementOf that answers the row's placement from its header",
detail: { missing: "placementOf" },
});
}
}
if (typeof readRow === "function" && typeof importEntries === "function") {
const transfer = repoLogTransfer({
readRow: (id) => readRow.call(this.repo, id),
importEntries: (id, owner, entries, options) => importEntries.call(this.repo, id, owner, entries, options),
holding: (id, work) => this.holdingId(id, () => {
this.entries.delete(id);
return work();
}),
});
this.logTransfer = {
...transfer,
beginReplace: (sessionId, options) => {
this.latch.refuse("TtlSessionStore.logTransfer.beginReplace");
return transfer.beginReplace(sessionId, options);
},
};
}
}
const hooks = opts.hooks;
const beforeRowDelete = readStoreHooks(hooks);
if (beforeRowDelete !== undefined)
this.beforeRowDelete = (sessionId) => Reflect.apply(beforeRowDelete, hooks, [sessionId]);
const sweepIntervalMs = readIntegerOption("TtlSessionStoreOptions.sweepIntervalMs", opts.sweepIntervalMs, TIMER_DELAY_MS, "milliseconds", "no background sweep");
if (sweepIntervalMs !== undefined) {
this.sweepTimer = setInterval(() => this.sweep(), sweepIntervalMs);
this.sweepTimer.unref?.();
}
}
async acquire(sessionId, opts) {
this.sweep();
if (sessionId) {
await this.settledHolds(sessionId);
const existing = this.entries.get(sessionId);
if (existing) {
if ((await this.standingRow(sessionId, existing)) !== undefined) {
this.assertPlacementAdmission(sessionId, existing.placement, opts);
existing.lastActiveAt = Date.now();
return { session: existing.session, sessionId };
}
if (this.entries.get(sessionId) === existing)
this.entries.delete(sessionId);
}
if (opts?.requireExisting) {
return { session: await this.openOrCreate(sessionId, true), sessionId };
}
const inflight = this.pending.get(sessionId);
if (inflight) {
const session = await inflight;
this.assertPlacementAdmission(sessionId, this.entries.get(sessionId)?.placement, opts);
return { session, sessionId };
}
const p = this.openOrCreate(sessionId, false, createdCells(opts));
this.pending.set(sessionId, p);
try {
const session = await p;
this.assertPlacementAdmission(sessionId, this.entries.get(sessionId)?.placement, opts);
return { session, sessionId };
}
finally {
this.pending.delete(sessionId);
}
}
const session = await this.createAndStore(undefined, createdCells(opts));
const meta = await session.getMetadata();
return { session, sessionId: meta.id };
}
viewStandsFor(shown, row) {
const verdict = compareOccupants(shown, row);
if (verdict === "different")
return false;
if (row !== undefined && (shown.owner ?? null) !== (row.owner ?? null))
return false;
return verdict === "same" || this.repoHead === undefined;
}
async standingRow(sessionId, cached) {
if (this.repoHead === undefined)
return null;
const storage = cached.session.getStorage();
const [shown, leaf, row] = await Promise.all([cached.session.getMetadata(), storage.getLeafId(), this.repoHead(sessionId)]);
if (!this.viewStandsFor(shown, row) || row === undefined || row.leafId !== leaf)
return undefined;
return storage.isViewOf === undefined || storage.isViewOf(row) ? row : undefined;
}
assertPlacementAdmission(sessionId, placement, opts) {
const store = this;
admitSessionPlacement(sessionId, placement, opts ?? {}, {
get subagentPlacement() {
return store.placements?.subagent !== undefined;
},
});
}
async openOrCreate(id, requireExisting = false, cells) {
for (;;) {
const watch = { overtaken: this.releasing.has(id) };
const watching = this.resolutions.get(id) ?? new Set();
watching.add(watch);
this.resolutions.set(id, watching);
let session;
try {
session = await this.resolveRow(id, requireExisting, cells);
}
finally {
watching.delete(watch);
if (watching.size === 0 && this.resolutions.get(id) === watching)
this.resolutions.delete(id);
}
if (!watch.overtaken)
return session;
if (this.entries.get(id)?.session === session)
this.entries.delete(id);
await this.settledHolds(id);
}
}
async resolveRow(id, requireExisting, cells) {
try {
const session = await this.repo.open({ id, createdAt: "" });
const meta = await session.getMetadata();
this.entries.set(id, { session, lastActiveAt: Date.now(), createdAt: meta.createdAt, ...(meta.forkedFrom !== undefined ? { forkedFrom: meta.forkedFrom } : {}), ...(meta.placement !== undefined ? { placement: meta.placement } : {}) });
return session;
}
catch (err) {
if (!isNotFound(err) && !isSessionConflict(err)) {
throw err;
}
if (requireExisting && isNotFound(err)) {
throw err;
}
return this.createAndStore(id, cells);
}
}
async createAndStore(id, cells) {
this.latch.refuse("TtlSessionStore.acquire");
let session;
try {
session = await this.repo.create({ ...(id !== undefined ? { id } : {}), ...cells });
}
catch (err) {
if (id === undefined || !isSessionConflict(err))
throw err;
session = await this.repo.open({ id, createdAt: "" });
}
const meta = await session.getMetadata();
this.entries.set(meta.id, { session, lastActiveAt: Date.now(), createdAt: meta.createdAt, ...(meta.forkedFrom !== undefined ? { forkedFrom: meta.forkedFrom } : {}), ...(meta.placement !== undefined ? { placement: meta.placement } : {}) });
return session;
}
async touch(sessionId) {
this.latch.refuse("TtlSessionStore.touch");
const e = this.entries.get(sessionId);
if (e) {
e.lastActiveAt = Date.now();
}
await this.repo.touch?.(sessionId);
}
noteTaskRun(sessionId, taskId, runId) {
const e = this.entries.get(sessionId);
if (e) {
e.lastTaskId = taskId;
if (runId !== undefined)
e.lastTaskRunId = runId;
else
delete e.lastTaskRunId;
e.lastActiveAt = Date.now();
}
}
async list(query) {
const q = readSessionListQuery(query);
const page = [];
for (const row of await this.repo.list()) {
if (row.placement !== undefined)
continue;
const owner = row.owner ?? null;
if (q.owner !== undefined && owner !== q.owner && !(q.includeUnowned && owner === null))
continue;
const summary = await this.summaryOf(row);
if (q.after !== undefined && newestFirst(q.after, summary) >= 0)
continue;
page.push(summary);
}
return page.sort(newestFirst).slice(0, q.limit);
}
async summaryOf(row) {
const cached = this.entries.get(row.id);
const view = cached !== undefined && this.viewStandsFor(await cached.session.getMetadata(), row) ? cached : undefined;
const recorded = row.lastActiveAt !== undefined && Number.isFinite(row.lastActiveAt) ? row.lastActiveAt : Date.parse(row.createdAt);
const lastActiveAt = Number.isFinite(recorded) ? recorded : 0;
const forkedFrom = row.forkedFrom ?? view?.forkedFrom;
return {
sessionId: row.id,
lastActiveAt,
...(row.createdAt !== "" ? { createdAt: row.createdAt } : {}),
...(view?.lastTaskId !== undefined ? { lastTaskId: view.lastTaskId } : {}),
...(view?.lastTaskRunId !== undefined ? { lastTaskRunId: view.lastTaskRunId } : {}),
...(forkedFrom !== undefined ? { forkedFrom } : {}),
incarnation: row.incarnation ?? null,
forkedFromIncarnation: row.forkedFrom !== undefined ? (row.forkedFromIncarnation ?? null) : null,
};
}
async fork(sourceId, owner, opts) {
this.latch.refuse("TtlSessionStore.fork");
const placement = opts?.placement;
const given = opts?.id;
if (given !== undefined && (typeof given !== "string" || given === "")) {
throw receiptRefusal(`TtlSessionStore.fork: opts.id must be a non-empty string (the id the fork lands on) or absent (a fresh one), got ${describeRejectedValue(given)} — refused before anything was read or written`);
}
if (given !== undefined)
await this.settledHolds(given);
let source;
try {
source = await this.repo.open({ id: sourceId, createdAt: "" });
}
catch (err) {
if (isNotFound(err)) {
return null;
}
throw err;
}
const forkOptions = await settledForkOptions(source);
const forked = await this.repo.fork(await source.getMetadata(), { ...forkOptions, id: given ?? uuidv7(), ...(owner !== undefined ? { owner } : {}), ...(placement !== undefined ? { placement } : {}) });
const meta = await forked.getMetadata();
if (placement !== undefined) {
try {
this.assertPlacementAdmission(meta.id, meta.placement, { placement });
}
catch (refusal) {
let left;
try {
const created = { row: { owner: meta.owner ?? null, incarnation: meta.incarnation } };
await this.deleteRow(meta, this.repoHead !== undefined ? async () => created : undefined);
}
catch (err) {
left = err;
}
if (left === undefined)
throw refusal;
throw new SessionError("placement_refused", `${refusal.message} — and the copy ${meta.id} this fork created could not be removed (${thrownText(left)}); delete it by id`, refusal);
}
}
this.entries.set(meta.id, {
session: forked,
lastActiveAt: Date.now(),
createdAt: meta.createdAt,
forkedFrom: meta.forkedFrom ?? sourceId,
...(meta.placement !== undefined ? { placement: meta.placement } : {}),
});
return meta.id;
}
async release(sessionId) {
this.latch.refuse("TtlSessionStore.release");
if (this.pinned.has(sessionId)) {
return;
}
const cached = this.entries.get(sessionId);
if (cached !== undefined)
this.entries.delete(sessionId);
if (cached !== undefined && cached.placement === undefined && this.evictPolicy !== "delete")
return;
if (cached === undefined && !this.releasing.has(sessionId) && !this.rowReadMatters(sessionId))
return;
return this.holdingId(sessionId, () => this.releaseRow(sessionId, cached));
}
async settledHolds(sessionId) {
const held = this.releasing.get(sessionId);
if (held !== undefined)
await held;
}
async holdingId(sessionId, work) {
for (const watch of this.resolutions.get(sessionId) ?? [])
watch.overtaken = true;
const prior = this.releasing.get(sessionId);
let settle;
const gate = new Promise((r) => (settle = r));
this.releasing.set(sessionId, gate);
try {
if (prior !== undefined)
await prior;
return await work();
}
finally {
if (this.releasing.get(sessionId) === gate)
this.releasing.delete(sessionId);
settle();
}
}
async releaseRow(sessionId, cached) {
if (cached?.placement !== undefined)
this.pendingPlacedDeletes.add(sessionId);
const standing = cached !== undefined ? await this.standingRow(sessionId, cached) : undefined;
const view = standing !== undefined ? cached : undefined;
const judged = view === undefined && this.repoHead !== undefined && this.rowReadMatters(sessionId) ? await this.repoHead(sessionId) : undefined;
const placed = view !== undefined ? view.placement !== undefined : await this.rowIsPlaced(sessionId);
if (view === undefined && !placed)
return;
if (!placed) {
await this.deleteRow(await view.session.getMetadata(), this.idleViewExpectation(standing, view));
return;
}
const meta = view !== undefined ? await view.session.getMetadata() : { id: sessionId, createdAt: "" };
const occupant = view !== undefined ? standing : (judged ?? null);
this.pendingPlacedDeletes.add(sessionId);
await this.deleteRow(meta, this.judgesRows ? async () => ({ row: occupant }) : undefined);
this.pendingPlacedDeletes.delete(sessionId);
}
idleViewExpectation(standing, view) {
if (!this.judgesRows || standing === null)
return undefined;
return async () => ({ row: standing, log: sessionLogMarkOf(await view.session.getStorage().getEntries()) });
}
deleteRow(meta, expect) {
return this.removeAfterHook(meta.id, async () => {
if (expect === undefined) {
await this.repo.delete(meta);
return true;
}
try {
await this.repo.delete(meta, await expect());
}
catch (err) {
if (isSessionConflict(err))
return false;
throw err;
}
return true;
});
}
async removeAfterHook(sessionId, remove) {
if (this.beforeRowDelete !== undefined)
await this.beforeRowDelete(sessionId);
return remove();
}
async deleteUnreadableRow(sessionId, readHead, removal) {
this.latch.refuse("TtlSessionStore.deleteUnreadable");
const id = readUnreadableDeleteId("SessionStore.deleteUnreadable", sessionId);
return this.holdingId(id, async () => {
this.entries.delete(id);
if (!(await rowUnreadableAt(() => readHead(id))))
return false;
if (!(await this.removeAfterHook(id, () => removal(id))))
return false;
this.pinned.delete(id);
this.pendingPlacedDeletes.delete(id);
return true;
});
}
async deleteOwned(sessionId, guard, readHead, readHeaderPlacement) {
this.latch.refuse("TtlSessionStore.delete");
const wants = readDeleteGuard(guard);
return this.holdingId(sessionId, async () => {
this.entries.delete(sessionId);
const head = await readHead(sessionId);
if (head === undefined || !wants(head))
return false;
if ((await readHeaderPlacement(sessionId)) !== undefined)
return false;
if (!(await this.deleteRow({ id: sessionId, createdAt: "" }, async () => ({ row: head }))))
return false;
this.pinned.delete(sessionId);
return true;
});
}
async rowMetadata(sessionId) {
try {
return await (await this.repo.open({ id: sessionId, createdAt: "" })).getMetadata();
}
catch (err) {
if (isNotFound(err))
return undefined;
throw err;
}
}
async readPlacement(sessionId) {
const probe = this.placementProbe();
if (probe !== undefined)
return probe(sessionId);
return (await this.rowMetadata(sessionId))?.placement;
}
placementProbe() {
const probe = this.repo.placementOf;
return typeof probe === "function" ? probe.bind(this.repo) : undefined;
}
rowReadMatters(sessionId) {
return this.pendingPlacedDeletes.has(sessionId) || (this.placements !== undefined && this.placementProbe() !== undefined);
}
async rowIsPlaced(sessionId) {
if (!this.rowReadMatters(sessionId))
return false;
let placement;
try {
placement = await this.readPlacement(sessionId);
}
catch (err) {
if (!isNotFound(err))
throw err;
}
this.pendingPlacedDeletes.delete(sessionId);
return placement !== undefined;
}
forget(sessionId) {
this.entries.delete(sessionId);
}
pin(sessionId) {
this.pinned.add(sessionId);
}
unpin(sessionId) {
this.pinned.delete(sessionId);
}
async register(sessionId, owner) {
this.latch.refuse("TtlSessionStore.register");
await this.settledHolds(sessionId);
if (await this.hasRow(sessionId))
return;
ownerCell(owner);
try {
await this.repo.create({ id: sessionId, owner });
}
catch (err) {
if (isSessionConflict(err))
return;
throw err;
}
}
async hasRow(sessionId) {
if (this.repoHead !== undefined)
return (await this.repoHead(sessionId)) !== undefined;
try {
await this.repo.open({ id: sessionId, createdAt: "" });
return true;
}
catch (err) {
if (isNotFound(err))
return false;
throw err;
}
}
sweep(now = Date.now()) {
for (const [id, e] of this.entries) {
if (this.pinned.has(id)) {
continue;
}
if (now - e.lastActiveAt > this.defaultTtlMs) {
this.entries.delete(id);
if (this.evictPolicy === "delete" && e.placement === undefined && !this.latch.closed) {
void this.holdingId(id, async () => {
const standing = await this.standingRow(id, e);
if (standing !== undefined)
await this.deleteRow({ id, createdAt: "" }, this.idleViewExpectation(standing, e));
}).catch(() => { });
}
}
}
}
get size() {
return this.entries.size;
}
dispose() {
if (this.sweepTimer) {
clearInterval(this.sweepTimer);
}
}
}
export async function settledForkOptions(source) {
const storage = source.getStorage();
let id = await storage.getLeafId();
const chain = new ParentChainGuard();
const answers = [];
while (id) {
chain.stepOnto(id);
const entry = await storage.getEntry(id);
if (entry !== undefined && isLegCloseRecord(entry)) {
id = entry.parentId;
continue;
}
if (!entry || entry.type !== "message") {
return {};
}
if (entry.message.role === "assistant") {
const open = findUnansweredToolBatch([entry.message, ...answers]) !== undefined;
return open && entry.parentId ? { entryId: entry.parentId, position: "at" } : {};
}
if (entry.message.role !== "toolResult") {
return {};
}
answers.push(entry.message);
id = entry.parentId;
}
return {};
}
function newestFirst(a, b) {
if (a.lastActiveAt !== b.lastActiveAt)
return b.lastActiveAt - a.lastActiveAt;
return a.sessionId < b.sessionId ? 1 : a.sessionId > b.sessionId ? -1 : 0;
}
function durabilityWord(name, value) {
if (value === "durable" || value === "process-local")
return value;
throw receiptRefusal(`${name} must be "durable" or "process-local" when given (got ${describeRejectedValue(value)})`);
}
function ttlDays(value) {
if (value === undefined)
return SESSION_DEFAULT_TTL_DAYS;
if (typeof value === "number" && Number.isFinite(value) && value >= 0)
return value;
throw receiptRefusal(`TtlSessionStoreOptions.defaultTtlDays must be a finite non-negative number of days when given (got ${describeRejectedValue(value)})`);
}
function evictWord(value) {
if (value === "delete" || value === "forget")
return value;
throw receiptRefusal(`TtlSessionStoreOptions.evict must be "delete" or "forget" when given (got ${describeRejectedValue(value)})`);
}
function placementsDeclaration(value) {
const got = receive(value, DECLARATION_RECEIPT_MODE);
if (!got.ok)
throw receiptRefusal(`TtlSessionStoreOptions.placements could not be read as plain data — ${describeFault(got.fault)}`);
const held = got.value;
if (typeof held !== "object" || held === null || Array.isArray(held))
throw receiptRefusal(`TtlSessionStoreOptions.placements must be a record when given (got ${describeRejectedValue(held)})`);
const subagent = held.subagent;
if (subagent !== undefined) {
if (typeof subagent !== "object" || subagent === null || Array.isArray(subagent))
throw receiptRefusal(`TtlSessionStoreOptions.placements.subagent must be a record when given (got ${describeRejectedValue(subagent)})`);
durabilityWord("TtlSessionStoreOptions.placements.subagent.durability", subagent.durability);
}
return held;
}
function readStoreHooks(hooks) {
if (hooks === undefined)
return undefined;
if (typeof hooks !== "object" || hooks === null)
throw receiptRefusal(`TtlSessionStoreOptions.hooks must be an object when given, got ${hooks === null ? "null" : typeof hooks}`);
const got = receiveMembers(hooks, { subject: "TtlSessionStoreOptions.hooks", unit: "hook", moment: "at construction" }, STORE_HOOK_KEYS);
const hook = got["beforeSessionDelete"];
if (hook !== undefined && typeof hook !== "function")
throw receiptRefusal(`TtlSessionStoreOptions.hooks.beforeSessionDelete must be a function when given, got ${hook === null ? "null" : typeof hook}`);
return hook;
}
function readDeleteGuard(guard) {
if (typeof guard !== "object" || guard === null)
throw new TypeError(`SessionStore.delete: the guard must be an object { owner } or { row: { owner, incarnation } }, got ${guard === null ? "null" : typeof guard}`);
let hasRow;
try {
hasRow = "row" in guard;
}
catch {
hasRow = true;
}
if (hasRow) {
const occupant = readOccupantExpectation(guard, (what) => {
throw new TypeError(`SessionStore.delete: the guard's ${what}`);
});
return (head) => sessionRowMatches(occupant, head, occupantBindsNoLog);
}
const owner = readMember(guard, "owner");
if (owner === null)
return (head) => head.owner === null;
const name = recordedPrincipalNameOf(owner);
if (name === undefined)
throw new TypeError(`SessionStore.delete: guard.owner must be null (anonymous) or the owner name a session row holds — ${RECORDED_PRINCIPAL_NAME_SPELLING} — got ${principalNameFault(owner)}`);
return (head) => head.owner === name;
}
function occupantBindsNoLog() {
throw new TypeError("SessionStore.delete: an occupant guard binds no log");
}
function isNotFound(err) {
return readMember(err, "code") === "not_found";
}