@sema-agent/core
Version:
Stateless, task-oriented AI agent core
447 lines (446 loc) • 21.8 kB
JavaScript
import { createHash } from "node:crypto";
import { isFiniteNumber, isListOf, isRecord, isRowCorrupt, isString, optional, required, rowShapeReader, takesExit, via } from "./row-shape.js";
import { receiveRetentionPolicy } from "./retention-policy.js";
import { readMemberGroup } from "./member-group.js";
import { PRINCIPAL_NAME_MAX_CHARS, hasVisibleContent } from "./principal-name.js";
export const MAILBOX_DECISIONS = Object.freeze(["held", "approved", "delivered", "denied", "expired", "refused", "dropped"]);
export function readStoredMailboxDecision(raw) {
if (raw === undefined)
return undefined;
return isMailboxDecision(raw) ? raw : "held";
}
export const MAILBOX_INVALID_DECISION_MOVE_CODE = "mailbox.invalid_decision_move";
export const MAILBOX_INVALID_LEASE_OWNER_CODE = "mailbox.invalid_lease_owner";
const CONTROL_CHARACTER = /\p{Cc}/u;
const FORMAT_CHARACTER = /(?![\u200c\u200d])\p{Cf}/u;
export function isMailboxNameSpelling(raw) {
return typeof raw === "string" && hasVisibleContent(raw) && raw.length <= PRINCIPAL_NAME_MAX_CHARS && !CONTROL_CHARACTER.test(raw) && !FORMAT_CHARACTER.test(raw);
}
export function assertMailboxLeaseOwner(owner) {
if (!isMailboxNameSpelling(owner)) {
throw new MailboxStoreError(MAILBOX_INVALID_LEASE_OWNER_CODE, `MailboxStore.claimLease: owner must be a string with a non-blank character and no control character, no format character, and at most ${PRINCIPAL_NAME_MAX_CHARS} characters`);
}
}
export function isMailboxDecision(value) {
return typeof value === "string" && MAILBOX_DECISIONS.includes(value);
}
export function isMailboxDecisionFinal(state) {
return state === "denied" || state === "expired" || state === "refused" || state === "dropped";
}
export function isMailboxDecisionDeliverable(state) {
return state === "approved" || state === "delivered";
}
export function mailboxDecisionEdgeAllowed(from, to) {
if (from === undefined)
return to === "held";
if (from === "held")
return to === "approved" || to === "delivered" || to === "denied" || to === "expired" || to === "refused";
if (from === "approved")
return to === "delivered" || isMailboxDecisionFinal(to);
if (from === "delivered")
return to === "dropped";
return false;
}
export function mailboxDecisionMoveFenced(expect, leaseOwner, holder) {
return expect === "delivered" && (holder === undefined || leaseOwner !== holder);
}
export async function moveMailboxDecision(store, scope, handle, seq, expect, next, holder) {
assertMailboxDecisionScope(scope);
try {
return await store.moveDecision(scope, handle, seq, expect, next, holder);
}
catch {
const again = await store.moveDecision(scope, handle, seq, expect, next, holder);
return !again.ok && again.current === next ? { ok: true } : again;
}
}
export function assertMailboxDecisionScope(scope) {
if (typeof scope === "string" && scope !== "")
return;
throw new MailboxStoreError(MAILBOX_INVALID_DECISION_MOVE_CODE, `MailboxStore.moveDecision: scope must be a non-empty string — the scope of the box the record is in (got ${scope === "" ? "the empty string" : typeof scope})`);
}
export function assertMailboxDecisionMove(seq, expect, next, holder) {
const refuse = (why) => {
throw new MailboxStoreError(MAILBOX_INVALID_DECISION_MOVE_CODE, `MailboxStore.moveDecision: ${why}`);
};
if (typeof seq !== "number" || !Number.isInteger(seq) || seq < 1)
refuse(`seq must be a positive integer (got ${String(seq)})`);
if (holder !== undefined && !isMailboxNameSpelling(holder))
refuse(`holder must be absent or a lease owner spelling — a string with a non-blank character and no control character, no format character, and at most ${PRINCIPAL_NAME_MAX_CHARS} characters (got ${typeof holder === "string" ? "a string that is not one" : typeof holder})`);
if (expect !== undefined && !isMailboxDecision(expect))
refuse(`expect must be absent or one of ${MAILBOX_DECISIONS.join("|")}`);
if (!isMailboxDecision(next))
refuse(`next must be one of ${MAILBOX_DECISIONS.join("|")}`);
if (!mailboxDecisionEdgeAllowed(expect, next))
refuse(`${String(expect ?? "unset")} → ${String(next)} is not a decision move (a decision only moves forward)`);
}
export const MAILBOX_PEER_FROM_MODES = Object.freeze(["bypass", "prompting"]);
export const MAILBOX_PEER_RECORD_KINDS = Object.freeze(["peer_message", "idle_notice", "delivery_notice", "idle_subscription", "engine_frame"]);
export const MAILBOX_PEER_NOTICE_STATES = Object.freeze(["held", "denied", "expired", "delivered", "refused", "dropped", "idle", "exited", "unavailable", "held_by_policy"]);
export const MAILBOX_INVALID_PEER_META_CODE = "mailbox.invalid_peer_meta";
export const MAILBOX_CROSS_PROCESS_UNSAFE_CODE = "mailbox.cross_process_unsafe";
const PEER_META_STRING_KEYS = ["fromSession", "fromRoot", "senderKey", "fromScope", "gateReceiptId", "occupant", "fromOccupant"];
export function readMailboxPeerMeta(raw) {
if (raw === undefined)
return undefined;
const refuse = (why) => {
throw new MailboxStoreError(MAILBOX_INVALID_PEER_META_CODE, `MailboxStore.append: peerMeta ${why}`);
};
if (raw === null || typeof raw !== "object" || Array.isArray(raw))
return refuse("must be a plain object");
const proto = Object.getPrototypeOf(raw);
if (proto !== Object.prototype && proto !== null)
return refuse("must be a plain object (a class instance, Date, Map or similar is not)");
const out = {};
for (const key of Reflect.ownKeys(raw)) {
if (typeof key !== "string")
return refuse("carries a symbol-keyed member");
const k = key;
const v = raw[k];
if (v === undefined)
continue;
if (k === "fromMode") {
if (!MAILBOX_PEER_FROM_MODES.includes(v))
return refuse(`fromMode must be one of ${MAILBOX_PEER_FROM_MODES.join("|")}`);
out.fromMode = v;
}
else if (k === "kind") {
if (!MAILBOX_PEER_RECORD_KINDS.includes(v))
return refuse(`kind must be one of ${MAILBOX_PEER_RECORD_KINDS.join("|")}`);
out.kind = v;
}
else if (PEER_META_STRING_KEYS.includes(k)) {
if (typeof v !== "string" || v === "")
return refuse(`${k} must be a non-empty string`);
out[k] = v;
}
else if (k === "notice") {
out.notice = readMailboxPeerNoticeMeta(v, refuse);
}
else if (k === "urgent") {
if (typeof v !== "boolean")
return refuse("urgent must be a boolean");
out.urgent = v;
}
else {
return refuse(`carries an unknown key ${JSON.stringify(k)}`);
}
}
return out;
}
function readMailboxPeerNoticeMeta(raw, refuse) {
if (raw === null || typeof raw !== "object" || Array.isArray(raw))
return refuse("notice must be a plain object");
const proto = Object.getPrototypeOf(raw);
if (proto !== Object.prototype && proto !== null)
return refuse("notice must be a plain object (a class instance, Date, Map or similar is not)");
const out = {};
for (const key of Reflect.ownKeys(raw)) {
if (typeof key !== "string")
return refuse("notice carries a symbol-keyed member");
const v = raw[key];
if (v === undefined)
continue;
if (key === "state") {
if (!MAILBOX_PEER_NOTICE_STATES.includes(v))
return refuse(`notice.state must be one of ${MAILBOX_PEER_NOTICE_STATES.join("|")}`);
out.state = v;
}
else if (key === "recipient" || key === "dropReason" || key === "detail" || key === "target") {
if (typeof v !== "string" || v === "")
return refuse(`notice.${key} must be a non-empty string`);
out[key] = v;
}
else if (key === "refSeq" || key === "finishedAt") {
if (typeof v !== "number" || !Number.isFinite(v) || v < 0)
return refuse(`notice.${key} must be a non-negative finite number`);
out[key] = v;
}
else {
return refuse(`notice carries an unknown key ${JSON.stringify(key)}`);
}
}
if (out.state === undefined)
return refuse("notice.state is required");
return out;
}
export function cloneMailboxPeerMeta(meta) {
return meta === undefined ? undefined : { ...meta, ...(meta.notice !== undefined ? { notice: { ...meta.notice } } : {}) };
}
export const MAILBOX_TOMBSTONED_RECIPIENT_CODE = "mailbox.recipient_tombstoned";
export const MAILBOX_ROW_MALFORMED_CODE = "mailbox.row_malformed";
export class MailboxStoreError extends Error {
code;
constructor(code, message) {
super(message);
this.code = code;
this.name = "MailboxStoreError";
}
}
export const MAILBOX_INVALID_RECORD_ID_CODE = "mailbox.invalid_record_id";
export const MAILBOX_DUPLICATE_RECORD_ID_CODE = "mailbox.duplicate_record_id";
export const MAILBOX_RECORD_ID_MAX_CHARS = 1024;
export const MAILBOX_REPLAY_FACETS = Object.freeze(["from", "content", "hopChain", "peerMeta"]);
export const MAILBOX_CONSUMED_ID_WINDOW = 256;
export function mailboxReplayDigests(record) {
const out = {};
for (const f of MAILBOX_REPLAY_FACETS)
out[f] = createHash("sha256").update(facetSpelling(record[f])).digest("hex");
return out;
}
export function foldMailboxConsumed(window, removed) {
const entered = removed.flatMap((m) => (m.id !== undefined ? [{ id: m.id, seq: m.seq, digests: mailboxReplayDigests(m) }] : []));
const next = [...window, ...entered].sort((a, b) => a.seq - b.seq);
return next.length > MAILBOX_CONSUMED_ID_WINDOW ? next.slice(next.length - MAILBOX_CONSUMED_ID_WINDOW) : next;
}
export function readMailboxRecordId(raw) {
if (raw === undefined)
return undefined;
if (typeof raw !== "string" || raw === "" || raw.length > MAILBOX_RECORD_ID_MAX_CHARS) {
throw new MailboxStoreError(MAILBOX_INVALID_RECORD_ID_CODE, `MailboxStore.append: id must be a non-empty string of at most ${MAILBOX_RECORD_ID_MAX_CHARS} characters`);
}
return raw;
}
export function readMailboxAppend(msg) {
const peerMeta = readMailboxPeerMeta(msg.peerMeta);
const id = readMailboxRecordId(msg.id);
const from = msg.from;
const content = msg.content;
const sentAt = msg.sentAt;
const hopChain = msg.hopChain;
const record = {
...(id !== undefined ? { id } : {}),
...(from !== undefined ? { from } : {}),
content,
sentAt,
...(hopChain !== undefined ? { hopChain } : {}),
...(peerMeta !== undefined ? { peerMeta } : {}),
};
const answer = MAILBOX_MESSAGE_ROW_SHAPE.admit(record, { key: "" }, ["members"]);
if (isRowCorrupt(answer))
throw new MailboxStoreError(MAILBOX_ROW_MALFORMED_CODE, `MailboxStore.append: ${MAILBOX_MESSAGE_ROW_SHAPE.refusalText(answer)}`);
return { ...record, ...(hopChain !== undefined ? { hopChain: [...hopChain] } : {}) };
}
const isChainHop = (v) => (v === undefined || v === null || typeof v === "string" ? undefined : "is not a string");
export const MAILBOX_MESSAGE_ROW_SHAPE = rowShapeReader({
family: "mailbox",
code: MAILBOX_ROW_MALFORMED_CODE,
sentence: "This mailbox holds a record that does not read the way this engine reads a parked message — an earlier engine release wrote it, or it was changed in storage. Delivery stops in front of it: the records before it are delivered, and nothing at or after it is leased, acknowledged or counted until the box is dropped or the record repaired.",
exit: "block",
segments: [
{ name: "rowKey", entries: [required("seq", isFiniteNumber)] },
{
name: "members",
entries: [
required("content", isString),
required("sentAt", isFiniteNumber),
via("id", readMailboxRecordId),
optional("from", isString),
optional("hopChain", isListOf(isChainHop)),
optional("peerMeta", isRecord),
via("decision", readStoredMailboxDecision),
],
},
],
});
export function mailboxReadablePrefix(messages) {
const prefix = [];
for (const m of messages) {
const answer = MAILBOX_MESSAGE_ROW_SHAPE.read(m, { key: String(m.seq) });
if (!isRowCorrupt(answer)) {
prefix.push(answer.row);
continue;
}
takesExit(answer, "block", "mailbox delivery");
return { prefix, blocked: { seq: m.seq, corrupt: answer } };
}
return { prefix };
}
export function mailboxBlockedSentence(scope, handle, blocked) {
return `mailbox (${JSON.stringify(scope)}, ${JSON.stringify(handle)}): the record at seq ${blocked.seq} does not read (${blocked.corrupt.why}) — delivery stops in front of it`;
}
export function mailboxAckBlockedRefusal(blocked) {
return new MailboxStoreError(MAILBOX_ROW_MALFORMED_CODE, `MailboxStore.ack: ${MAILBOX_MESSAGE_ROW_SHAPE.refusalText(blocked.corrupt)} Nothing was consumed: an ack stops before seq ${blocked.seq}.`);
}
export function mailboxDecisionOnUnreadableRefusal(corrupt) {
return new MailboxStoreError(MAILBOX_ROW_MALFORMED_CODE, `MailboxStore.moveDecision: ${MAILBOX_MESSAGE_ROW_SHAPE.refusalText(corrupt)}`);
}
function facetSpelling(v) {
if (v === undefined || v === null)
return "-";
if (typeof v !== "object")
return JSON.stringify(v);
if (Array.isArray(v))
return `[${Array.from(v, facetSpelling).join(",")}]`;
return `{${Object.keys(v).filter((k) => v[k] !== undefined).sort().map((k) => `${JSON.stringify(k)}:${facetSpelling(v[k])}`).join(",")}}`;
}
export function judgeMailboxAppendById(box, msg) {
if (msg.id === undefined)
return undefined;
const holding = box.held.find((m) => m.id === msg.id);
const prior = holding !== undefined ? { seq: holding.seq, digests: mailboxReplayDigests(holding) } : box.consumed.find((c) => c.id === msg.id);
if (prior === undefined)
return undefined;
const asked = mailboxReplayDigests(msg);
const differs = MAILBOX_REPLAY_FACETS.filter((f) => prior.digests[f] !== asked[f]);
if (differs.length === 0)
return prior.seq;
throw new MailboxStoreError(MAILBOX_DUPLICATE_RECORD_ID_CODE, `MailboxStore.append: the box already ${holding !== undefined ? "holds" : "received"} a different record under this id (it differs in: ${differs.join(", ")}) — a new message takes a new id; an identical repeat would have been a replay`);
}
export function mailboxRecipientLifecycleOf(store) {
return readMemberGroup("MailboxStore", store, ["retireRecipient", "listRetiredRecipients"]);
}
export function mailboxCrossProcessMountVerdict(store) {
const declared = store.crossProcessSafe;
if (declared === true)
return { ok: true };
const reason = declared === undefined
? "the mailbox backend does not declare cross-process safety (crossProcessSafe is absent): several terminal sessions would share one session box on luck"
: declared === false
? "the mailbox backend declares crossProcessSafe: false (process-local by design): it cannot serve a session box shared across OS processes"
: `the mailbox backend's crossProcessSafe declaration is malformed (${typeof declared}, expected a boolean)`;
return { ok: false, code: MAILBOX_CROSS_PROCESS_UNSAFE_CODE, reason };
}
export function sessionBoxMountVerdict(mailbox, sessions) {
const store = mailboxCrossProcessMountVerdict(mailbox);
if (!store.ok)
return store;
if (typeof sessions?.headOf === "function")
return { ok: true };
return {
ok: false,
code: MAILBOX_CROSS_PROCESS_UNSAFE_CODE,
reason: "the session store has no by-id read (SessionStore.headOf): a session box outlives its session's occupant, and without that read a drain cannot confirm that its run's session still holds the occupant it acquired before it discards a record addressed to another, so a box shared across runs would hand one occupant's records to another on luck",
};
}
export function newestSentAt(messages) {
let newest;
for (const m of messages) {
if (!Number.isFinite(m.sentAt))
return undefined;
if (newest === undefined || m.sentAt > newest)
newest = m.sentAt;
}
return newest;
}
export function detachMailboxMessage(m) {
return {
...m,
...(m.hopChain !== undefined ? { hopChain: [...m.hopChain] } : {}),
...(m.peerMeta !== undefined ? { peerMeta: cloneMailboxPeerMeta(m.peerMeta) } : {}),
};
}
export const MAILBOX_REAP_KNOBS = Object.freeze(["maxAgeMs"]);
export class InMemoryMailboxStore {
crossProcessSafe = false;
boxes = new Map();
key(scope, handle) {
if (handle.includes("\u0000")) {
throw new Error(`MailboxStore: unsafe handle ${JSON.stringify(handle)} — a NUL byte makes the composite key ambiguous`);
}
return `${scope}\u0000${handle.toLowerCase()}`;
}
box(scope, handle) {
const k = this.key(scope, handle);
let b = this.boxes.get(k);
if (!b) {
b = { scope, messages: [], nextSeq: 1, consumed: [] };
this.boxes.set(k, b);
}
return b;
}
async append(scope, handle, msg) {
if (scope === undefined || scope === "")
throw new Error("MailboxStore.append: refusing a message without a scope");
const record = readMailboxAppend(msg);
const b = this.box(scope, handle);
const held = judgeMailboxAppendById({ held: b.messages, consumed: b.consumed }, record);
if (held !== undefined)
return held;
const seq = b.nextSeq++;
b.messages.push({ seq, ...record });
return seq;
}
async replayOf(scope, handle, msg) {
if (scope === undefined || scope === "")
throw new Error("MailboxStore.replayOf: refusing a message without a scope");
const record = readMailboxAppend(msg);
const b = this.boxes.get(this.key(scope, handle));
return judgeMailboxAppendById({ held: b?.messages ?? [], consumed: b?.consumed ?? [] }, record);
}
async claimLease(scope, handle, owner, ttlMs, now = Date.now()) {
assertMailboxLeaseOwner(owner);
const b = this.boxes.get(this.key(scope, handle));
if (!b)
return null;
const { prefix } = mailboxReadablePrefix(b.messages);
if (prefix.length === 0)
return null;
if (b.lease !== undefined && b.lease.expiresAt > now && b.lease.owner !== owner)
return null;
const maxSeq = prefix[prefix.length - 1].seq;
b.lease = { owner, expiresAt: now + ttlMs, maxSeq };
return { messages: prefix.map((m) => detachMailboxMessage(m)), maxSeq };
}
async ack(scope, handle, owner, upToSeq) {
const b = this.boxes.get(this.key(scope, handle));
if (!b)
return { acked: false };
if (b.lease === undefined || b.lease.owner !== owner)
return { acked: false };
const { blocked } = mailboxReadablePrefix(b.messages);
if (blocked !== undefined && upToSeq >= blocked.seq)
throw mailboxAckBlockedRefusal(blocked);
b.consumed = foldMailboxConsumed(b.consumed, b.messages.filter((m) => m.seq <= upToSeq));
b.messages = b.messages.filter((m) => m.seq > upToSeq);
if (b.lease.maxSeq <= upToSeq)
b.lease = undefined;
return { acked: true };
}
async moveDecision(scope, handle, seq, expect, next, holder) {
assertMailboxDecisionScope(scope);
assertMailboxDecisionMove(seq, expect, next, holder);
const b = this.boxes.get(this.key(scope, handle));
const m = b?.messages.find((x) => x.seq === seq);
if (m === undefined)
return { ok: false, current: "gone" };
const read = MAILBOX_MESSAGE_ROW_SHAPE.read(m, { key: String(m.seq) });
if (isRowCorrupt(read))
throw mailboxDecisionOnUnreadableRefusal(read);
if (m.decision !== expect)
return { ok: false, current: m.decision ?? "unset" };
if (mailboxDecisionMoveFenced(expect, b?.lease?.owner, holder))
return { ok: false, current: m.decision ?? "unset" };
m.decision = next;
return { ok: true };
}
async releaseLease(scope, handle, owner) {
const b = this.boxes.get(this.key(scope, handle));
if (b?.lease?.owner === owner)
b.lease = undefined;
}
async peekCount(scope, handle) {
const b = this.boxes.get(this.key(scope, handle));
return b === undefined ? 0 : mailboxReadablePrefix(b.messages).prefix.length;
}
async drop(scope, handle) {
this.boxes.delete(this.key(scope, handle));
}
async reap(scope, now, opts) {
const policy = receiveRetentionPolicy("MailboxStore.reap", opts, MAILBOX_REAP_KNOBS);
if (policy.maxAgeMs === undefined)
return 0;
let dropped = 0;
for (const b of this.boxes.values()) {
if (b.scope !== scope)
continue;
const newest = newestSentAt(b.messages);
if (newest !== undefined && newest < now - policy.maxAgeMs) {
b.messages = [];
b.lease = undefined;
dropped++;
}
}
return dropped;
}
}