UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

633 lines • 51.4 kB
import { type RowCorrupt } from "./row-shape.js";
/** One parked message. `seq` is minted by the store, monotonic per (scope, handle), stable across
 *  lease/expiry cycles (a re-leased message keeps its number — dedup/ordering key). */
export interface MailboxMessage {
    /**
     * @contract mailbox.seq_visible_in_seq_order — when `append` answers the seq of a NEW record (one it writes, not an id-bearing
     * replay answered with the seq the box already gave), that record and every lower-seq record of the same box that reads are
     * already visible to `claimLease` (a claim no other owner's live lease turns away leases them), so no lower seq shows up after
     * a higher one was answered. It is about a record's first showing, and it stays inside the box's readable prefix (`claimLease`
     * and `peekCount` stop at a held record that does not read). `ack(upToSeq)` rests on it: the ack deletes every record at or
     * below that seq, which is only what a claim showed when no lower seq shows later. A store keeps it when the seq comes from a
     * counter on the box's own row, is taken inside that row's lock and is committed in the same transaction as the record's write:
     * appends to one box then run one at a time, so the order seqs show in is the seq order (the bundled stores do: the memory store
     * in one synchronous step, the file store under its box lock). A store does not keep it when the seq is drawn from a database
     * sequence or an auto-increment column, which hands the number out before its transaction commits, even if the draw and the
     * write share one transaction: the transaction that took the lower seq can commit after the one that took the higher. A lower
     * seq that shows after a higher one was leased and before the ack is deleted by that ack without being delivered, and the
     * producer's re-send under the same id is answered from the received window with the old seq, writing nothing. The engine
     * cannot see whether a store keeps it.
     */
    seq: number;
    /** The identity the PRODUCER gave this record ({@link MailboxAppendMessage.id}); absent = it stated none. */
    id?: string;
    /** Sender display name, when the sender had one (SendMessage `senderName` — display only). */
    from?: string;
    content: string;
    sentAt: number;
    /** design/176 — the peer-message forwarding chain (engine-minted hop tokens; typed side channel,
     *  never model-facing text). Presence — even an empty array — marks the record as written through
     *  the sema send gate; an absent field means a pre-176 or FOREIGN-engine record (a shared CC inbox
     *  has other writers): such records deliver with an empty chain and are never retro-admitted —
     *  cross-engine records sit outside the guard's promise domain by ruling. */
    hopChain?: string[];
    /** design/385 — typed peer metadata the drain point's authoritative judgments read (from-mode parity,
     *  reply routing, admission sender key, record kind, the cross-principal trust anchors). Typed side
     *  channel, never model-facing text — encoding it into `content` would let text reach authority.
     *  ABSENT = a pre-385 or foreign record (same semantics as an absent `hopChain`): the drain treats it
     *  as foreign, never retro-admits it. Validated at `append` ({@link readMailboxPeerMeta}). */
    peerMeta?: MailboxPeerMeta;
    /** The record's HOLD DECISION ({@link MailboxDecision}): absent = never held. Never appended — it
     *  starts absent and moves only through {@link MailboxStore.moveDecision}; every lease snapshot
     *  carries it, so every consumer of the box reads the same decision. */
    decision?: MailboxDecision;
}
/**
 * A parked record's hold decision — the durable answer about a record a recipient's setting put on
 * hold, kept ON the record so every consumer of the box (another terminal, another process, the session's
 * next run) reads the same answer. `held` — waiting for a person; `approved` — a person approved it, not yet
 * handed over; `delivered` — a consumer holding the lease took the move and handed it over (a later
 * answer about it learns that instead of claiming a decision); `denied` / `expired` / `refused` /
 * `dropped` — final: the record is never delivered and only waits for the ack that removes it.
 */
export declare const MAILBOX_DECISIONS: readonly ["held", "approved", "delivered", "denied", "expired", "refused", "dropped"];
export type MailboxDecision = (typeof MAILBOX_DECISIONS)[number];
/** A stored decision word as a reader takes it: a word this engine does not know (a newer engine's) reads
 *  as `held` — never delivered on a guess, and left for a person (or that newer engine) to decide. */
export declare function readStoredMailboxDecision(raw: unknown): MailboxDecision | undefined;
/** The refusal code of a malformed {@link MailboxStore.moveDecision} call (a word outside the
 *  closed set, a non-positive seq, a holder that is no lease-owner spelling, or an edge the decision law does not allow). */
export declare const MAILBOX_INVALID_DECISION_MOVE_CODE = "mailbox.invalid_decision_move";
/** The refusal code of a {@link MailboxStore.claimLease} whose `owner` is not a spelling a lease can be named by
 *  ({@link isMailboxNameSpelling}): the owner is the identity the lease fence ({@link mailboxDecisionMoveFenced}) and `ack`
 *  compare, so a blank or control-carrying one would make two different holders read as one. */
export declare const MAILBOX_INVALID_LEASE_OWNER_CODE = "mailbox.invalid_lease_owner";
/**
 * THE one spelling judge of a name the box keeps and compares by equality — a receipt id, a lease owner, a decision move's holder: a
 * string with visible content ({@link hasVisibleContent}: the one reading of "blank" a principal's name uses too — white space and the
 * format characters, the joiners included, count for nothing), at most {@link PRINCIPAL_NAME_MAX_CHARS} characters, and no control or
 * format character. A blank one names nothing (`"" === ""` reads two holders as the same one; so does a string of one joiner or
 * zero-width mark, which prints as nothing), a control character reads as another line wherever the name is printed, a format
 * character (zero-width, a direction override) prints as nothing or reorders what is printed, and a name of any length is kept in
 * every box record, log line and refusal sentence that carries it. The box keeps the name as an opaque key — it is not required to be
 * a principal's name. Read by the receipt id's mint (`mintCrossPrincipalRecord`), by {@link assertMailboxLeaseOwner} (`claimLease`) and
 * by {@link assertMailboxDecisionMove} (a move's `holder`); each refuses with the code of the call that was malformed.
 */
export declare function isMailboxNameSpelling(raw: unknown): raw is string;
/** The validator `claimLease` runs BEFORE touching storage, in every backend: a malformed owner has zero side effects. */
export declare function assertMailboxLeaseOwner(owner: unknown): void;
export declare function isMailboxDecision(value: unknown): value is MailboxDecision;
/** Final states: the record is never delivered again, by any consumer. */
export declare function isMailboxDecisionFinal(state: MailboxDecision | undefined): boolean;
/** Deliverable states: a consumer holding the lease delivers the record (a setting that now refuses still wins). */
export declare function isMailboxDecisionDeliverable(state: MailboxDecision | undefined): boolean;
/**
 * THE decision law — a decision only moves forward, and every hand-over of a held record is itself a move:
 * absent → `held`; `held` → `approved` / `delivered` / `denied` / `expired` / `refused`; `approved` →
 * `delivered` or a final state; `delivered` → `dropped` (the handed-over frame was refused by policy inside a lease-holding pass) only,
 * and only by the box's lease holder ({@link mailboxDecisionMoveFenced}); a final state never moves.
 */
export declare function mailboxDecisionEdgeAllowed(from: MailboxDecision | undefined, to: MailboxDecision): boolean;
/**
 * THE lease fence of the decision law, the one every backend reads after the record's state matched `expect`:
 * `true` = the move must not happen. A record in `delivered` was handed over — its injection is owed by the consumer
 * that holds the box — so an edge out of `delivered` is taken only by that consumer: the box's current lease must name
 * `holder`, the fence {@link MailboxStore.ack} takes (a lease that lapsed and nobody claimed since is still its holder's;
 * a box with no lease, or a caller that names no holder, holds nothing). Every other edge is a person's or a policy's
 * answer about a held record, which any process may give: the lease is not asked.
 */
export declare function mailboxDecisionMoveFenced(expect: MailboxDecision | undefined, leaseOwner: string | undefined, holder: string | undefined): boolean;
/** What {@link MailboxStore.moveDecision} answers: the move happened, or the record's actual state
 *  (`unset` = never held, `gone` = no such record any more — acked, reaped or dropped). The state is what the caller
 *  expected exactly when the lease fence refused it ({@link mailboxDecisionMoveFenced}: `current: "delivered"`). */
export type MailboxDecisionOutcome = {
    readonly ok: true;
} | {
    readonly ok: false;
    readonly current: MailboxDecision | "unset" | "gone";
};
/**
 * THE caller-side reading of {@link MailboxStore.moveDecision}: a fault can arrive AFTER the move
 * committed (a lock release that failed, a reply lost on the wire), so a call that throws is asked once
 * more, and a store that already holds `next` answers the first call's success. A second fault throws.
 * Every engine-side decision move goes through this one function. `holder` = the lease owner the caller
 * claims the box with (see {@link MailboxStore.moveDecision}).
 */
export declare function moveMailboxDecision(store: Pick<MailboxStore, "moveDecision">, scope: string, handle: string, seq: number, expect: MailboxDecision | undefined, next: MailboxDecision, holder?: string): Promise<MailboxDecisionOutcome>;
/** The scope a decision move names: a non-empty string — the box's scope (work with no principal is filed under `ANONYMOUS_SCOPE`).
 *  An absent or empty one names no box and is refused by the move's own code ({@link MAILBOX_INVALID_DECISION_MOVE_CODE}) before any
 *  storage is touched: {@link moveMailboxDecision} and the bundled backends judge it, so no caller reads an uncoded fault of a path. */
export declare function assertMailboxDecisionScope(scope: unknown): void;
/** The one validator every backend runs BEFORE touching storage: a malformed call has zero side effects. */
export declare function assertMailboxDecisionMove(seq: unknown, expect: unknown, next: unknown, holder?: unknown): void;
/** design/385 — the typed peer-metadata record on a parked message. ONE optional object, one-time
 *  contract extension; every field optional. Bundled backends persist it verbatim and hand back a
 *  detached copy. */
export interface MailboxPeerMeta {
    /** The sending session's id (reply routing). */
    fromSession?: string;
    /** The delegation-tree ROOT the sender belongs to, stamped by the park seat of a session that
     *  received the frame through its own child uplink — never by the sender. A recipient whose
     *  session IS this root reads the record as a teammate's words (same tree = same admission as the
     *  live uplink: the admission gate runs, the cross-session parity hold does not). */
    fromRoot?: string;
    /** The sender's permission-mode class at send time — the drain judges parity against the RECEIVER. */
    fromMode?: MailboxPeerFromMode;
    /** The admission gate's sender key (rate/dedup axis). */
    senderKey?: string;
    /** Record kind: a peer message runs the parity judgment; notices bypass it and land on the notice face. */
    kind?: MailboxPeerRecordKind;
    /** Cross-principal delivery only — the SENDER's scope, the typed trust anchor for attribution. */
    fromScope?: string;
    /** Cross-principal delivery only — the delivery gate's receipt id (audit back-reference). */
    gateReceiptId?: string;
    /** Notice-kind records only (design/385 §4.4 / §5.2): the typed notice the requester's drain renders
     *  — a delivery receipt's state (`kind: "delivery_notice"`) or an idle notice's kind
     *  (`kind: "idle_notice"`). The record's `content` is a human-readable mirror; THIS is the authority. */
    notice?: MailboxPeerNoticeMeta;
    /** `peer_message` only — the SENDER marked it urgent. The recipient's drain presents an urgent record
     *  ahead of the non-urgent ones of the same pass and counts it on the inbox notice; it never changes
     *  WHEN the recipient reads (the recipient's setting decides that, never the sender). */
    urgent?: boolean;
    /**
     * WHO the record is for: the occupant (`SessionMetadata.incarnation`) of the session the writer addressed, as the writer
     * resolved that address — a park seat from its leg's address, a sender from the recipient's directory row, a notice from the
     * reply address it answers. A session box outlives its occupant (the id can be deleted and created again, the box stays), so a
     * drain hands a record only to the occupant it names ({@link import("../engine/session/repo-utils.js").sameOccupant}: absent on
     * both sides is one occupant — a deployment whose store mints no tokens; absent on one side only is another occupant). A
     * record for another occupant is discarded with an account, never delivered. An addressing fact, not a secret and not a
     * credential: it proves nothing about who wrote the record.
     */
    occupant?: string;
    /** The occupant of the SENDING session, beside `fromSession`: what a notice answering this record (a receipt, an idle notice)
     *  is addressed to ({@link occupant} of that notice). Absent = the sender stated none. */
    fromOccupant?: string;
}
/** design/385 — the typed body of a notice-kind record. `state` is drawn from the receipt states on a
 *  `delivery_notice` (`held|denied|expired|delivered|refused|dropped|held_by_policy`) and from the idle kinds on an
 *  `idle_notice` (`idle|exited|unavailable|expired`); the validator admits the union, the drain checks
 *  the pairing (a state that does not fit its kind is settled `notice_unrouted`, never rendered). */
export interface MailboxPeerNoticeMeta {
    state: string;
    /** delivery_notice: the box seq of the SENDER'S message this receipt is about. */
    refSeq?: number;
    /** delivery_notice: the recipient's display label (as its directory row spells it). */
    recipient?: string;
    /** delivery_notice `dropped`: the ingress guard's reason. */
    dropReason?: string;
    /** idle_notice `idle`/`exited`: when the target finished its turn (epoch ms). */
    finishedAt?: number;
    /** idle_notice `idle`: the target's one-line detail (already bounded by the producer). delivery_notice `refused`: who refused the
     *  message there; `delivered`: what released the held message (`approved` | `rejudge`, the peer-notices `PEER_RELEASE_CAUSES`). */
    detail?: string;
    /** idle_notice `expired` (the requester answering ITSELF): the label the ask carried for the target
     *  that never answered — the record's author is the requester, so the target must be named here. */
    target?: string;
}
export declare const MAILBOX_PEER_FROM_MODES: readonly ["bypass", "prompting"];
export type MailboxPeerFromMode = (typeof MAILBOX_PEER_FROM_MODES)[number];
/**
 * design/385: `peer_message` runs the parity judgment; `idle_subscription` registers the sender as an
 * idle subscriber of the box owner (§5.2, the store form of CC's `notify_when_idle` frame);
 * `idle_notice` / `delivery_notice` land on the notice face (rendered, never enveloped as a peer's words).
 *
 * @contract mailbox.engine_frame_is_not_a_peers_words — an `engine_frame` record is the ENGINE's own
 * task-notification frame parked durably (a child's terminal, a monitor batch, a workflow settle),
 * written by the park seat of the session that owns the box and only over a deployment that vouches
 * every drainer of the box reads the codec (`RunnerDeps.sessionBoxEngineFrames`). Its `content` is the
 * versioned codec text (`encodeEngineFrame`), never a message: the drain decodes it and re-injects the
 * frame through the engine's own notification lane — no parity judgment, no admission gate, no peer
 * envelope — and a codec version this engine does not read STOPS the drain at that record (the box
 * waits for an engine that reads it) rather than rendering engine speech as a peer's words. Only the
 * engine's own lanes (`background_agent` / `monitor` / `workflow`) may be parked this way; an
 * `external` event never is.
 */
export declare const MAILBOX_PEER_RECORD_KINDS: readonly ["peer_message", "idle_notice", "delivery_notice", "idle_subscription", "engine_frame"];
export type MailboxPeerRecordKind = (typeof MAILBOX_PEER_RECORD_KINDS)[number];
/** The `notice.state` vocabulary the validator admits (the union of both notice families; the drain
 *  checks the kind↔state pairing). Spelled here, beside the record kinds, so the store contract is
 *  self-contained — the lane's two closed sets (`PEER_DELIVERY_RECEIPT_STATES`, `PEER_IDLE_NOTICE_KINDS`)
 *  are spelled beside their renderers and together equal this one (a pin holds the two spellings together). */
export declare const MAILBOX_PEER_NOTICE_STATES: readonly ["held", "denied", "expired", "delivered", "refused", "dropped", "idle", "exited", "unavailable", "held_by_policy"];
export type MailboxPeerNoticeState = (typeof MAILBOX_PEER_NOTICE_STATES)[number];
/** The `append` refusal code for a malformed `peerMeta` (design/385): a garbage record is refused up
 *  front with this code, never silently stripped or stored — a drain that reads a half-typed record
 *  would judge on fabricated inputs. */
export declare const MAILBOX_INVALID_PEER_META_CODE = "mailbox.invalid_peer_meta";
/** The lane-mount refusal code: the cross-session lane asked for a backend that does not declare
 *  cross-process safety ({@link mailboxCrossProcessMountVerdict}). */
export declare const MAILBOX_CROSS_PROCESS_UNSAFE_CODE = "mailbox.cross_process_unsafe";
/**
 * Validate + detach an appended `peerMeta`. `undefined` ⇒ `undefined` (absent record). Anything else
 * must be a plain object whose keys are all known, whose present values are non-empty strings, with
 * `fromMode`/`kind` drawn from their closed sets; an `undefined`-valued key counts as absent. Any other
 * shape throws {@link MailboxStoreError} with {@link MAILBOX_INVALID_PEER_META_CODE} — every bundled
 * backend calls this BEFORE touching storage, so a refused append has zero side effects. Unknown keys
 * are refused on purpose: the object is the contract's one typed slot, and a key nobody declared is
 * either a typo or a newer schema this engine cannot judge on — both are loud, not silent.
 */
export declare function readMailboxPeerMeta(raw: unknown): MailboxPeerMeta | undefined;
/** A detached copy of a persisted record's `peerMeta` (absent stays absent) — the read-side twin of
 *  {@link readMailboxPeerMeta}, so a lease consumer's mutation never reaches the stored record. */
export declare function cloneMailboxPeerMeta(meta: MailboxPeerMeta | undefined): MailboxPeerMeta | undefined;
/** The enqueue refusal code of the pre-delete clause (see {@link MailboxStore} and
 *  {@link MailboxStoreError}) — the ONE place it is spelled, so an out-of-repo store twin imports it
 *  instead of value-copying the string (same posture as `STALE_RUNNING_REAP_ATTRIBUTION`: a shared
 *  symbol makes drift impossible rather than merely caught). */
export declare const MAILBOX_TOMBSTONED_RECIPIENT_CODE = "mailbox.recipient_tombstoned";
/**
 * Typed store error so callers branch on `code` (mirrors `BackgroundAgentStoreError`).
 *
 * `recipient_tombstoned` is the ENQUEUE refusal a backend raises when the recipient it addresses is
 * in a deployment's PRE-DELETE state — the window a retention/deletion cascade opens when it has
 * decided a session (and every row hanging off it) is going away but has not finished removing the
 * rows. An `append` accepted in that window returns a seq to the sender — a durable receipt — for a
 * message the cascade then deletes before any consumer could ever lease it. The refusal is what
 * turns that into a fact the sender can act on.
 *
 * A backend may raise the same code with a plain `Error` carrying `.code`; consumers branch on the
 * string, not on this class (a cross-process/out-of-repo store cannot hand back an instance).
 */
export type MailboxStoreErrorCode = typeof MAILBOX_TOMBSTONED_RECIPIENT_CODE | typeof MAILBOX_INVALID_PEER_META_CODE | typeof MAILBOX_CROSS_PROCESS_UNSAFE_CODE | typeof MAILBOX_INVALID_DECISION_MOVE_CODE | typeof MAILBOX_INVALID_LEASE_OWNER_CODE | typeof MAILBOX_INVALID_RECORD_ID_CODE | typeof MAILBOX_DUPLICATE_RECORD_ID_CODE | typeof MAILBOX_ROW_MALFORMED_CODE;
/** A parked record (or an append's record) that does not read as {@link MAILBOX_MESSAGE_ROW_SHAPE}: an append refuses it before
 *  any side effect; on a held record, an `ack` that would consume past it and a decision move on it are refused. */
export declare const MAILBOX_ROW_MALFORMED_CODE = "mailbox.row_malformed";
export declare class MailboxStoreError extends Error {
    readonly code: MailboxStoreErrorCode;
    constructor(code: MailboxStoreErrorCode, message: string);
}
/** A leased batch: the messages a claim winner owns for delivery, plus the ack cursor. */
export interface MailboxLease {
    messages: MailboxMessage[];
    /** Ack everything ≤ this seq once the revived cycle has durably received the batch. */
    maxSeq: number;
}
/** REF-D18: one appended mailbox message — the SINGLE shape the interface method and both the
 *  In-Memory and File implementations reference. */
export interface MailboxAppendMessage {
    /**
     * The record's identity, minted by its producer — a re-park of the same message carries the same
     * one. While the box holds a record under this id, or has it in its received window
     * ({@link MAILBOX_CONSUMED_ID_WINDOW}), an append under it is that record: identical on every
     * {@link MAILBOX_REPLAY_FACETS} facet ⇒ that record's `seq`, nothing written; any facet different ⇒
     * refused with {@link MAILBOX_DUPLICATE_RECORD_ID_CODE}. Absent = the producer states no identity and
     * every append is a new record (its `seq` is all it is known by). Validated by {@link readMailboxRecordId}.
     */
    id?: string;
    from?: string;
    content: string;
    sentAt: number;
    /** design/176 — see {@link MailboxMessage.hopChain}. */
    hopChain?: string[];
    /** design/385 — see {@link MailboxMessage.peerMeta}; validated by {@link readMailboxPeerMeta}. */
    peerMeta?: MailboxPeerMeta;
}
/** An `id` that is not a non-empty string of at most {@link MAILBOX_RECORD_ID_MAX_CHARS} characters. */
export declare const MAILBOX_INVALID_RECORD_ID_CODE = "mailbox.invalid_record_id";
/** An append under an `id` the box holds or has received, whose record differs from that one. */
export declare const MAILBOX_DUPLICATE_RECORD_ID_CODE = "mailbox.duplicate_record_id";
export declare const MAILBOX_RECORD_ID_MAX_CHARS = 1024;
/**
 * What a record SAYS — the facets a repeat under one id is compared on. `sentAt` is not one of them: it
 * is when a write happened, and a re-park of the same message happens later. Closed, in refusal order.
 */
export declare const MAILBOX_REPLAY_FACETS: readonly ["from", "content", "hopChain", "peerMeta"];
export type MailboxReplayFacet = (typeof MAILBOX_REPLAY_FACETS)[number];
/**
 * How many id-bearing records a box remembers after consuming them — its RECEIVED WINDOW, kept at exactly this size by
 * every backend (an out-of-repo backend imports the constant, never a copy of the number). An `ack` that deletes
 * id-bearing records enters each one; the window keeps the newest by `seq`; a record with no id never takes a place.
 * `drop` ends the window with the box's lifetime; `reap` keeps it, as it keeps the high-water mark (what it clears was
 * never received).
 */
export declare const MAILBOX_CONSUMED_ID_WINDOW = 256;
/** One record of a box's received window: the producer's id, the `seq` the record held, and its
 *  {@link mailboxReplayDigests} — what a later append under the id is judged against. */
export interface MailboxConsumedRecord {
    readonly id: string;
    readonly seq: number;
    readonly digests: Readonly<Record<MailboxReplayFacet, string>>;
}
/** One digest per {@link MAILBOX_REPLAY_FACETS} facet (sha-256 of the facet's one spelling): the form a held record, a
 *  received one and an incoming append are compared in. */
export declare function mailboxReplayDigests(record: Partial<Pick<MailboxAppendMessage, MailboxReplayFacet>>): Record<MailboxReplayFacet, string>;
/** The received window once `removed` (the records an `ack` deleted) entered it — the one fold every bundled backend
 *  runs; the result holds the newest {@link MAILBOX_CONSUMED_ID_WINDOW} by `seq`. Module-level, not a root export. */
export declare function foldMailboxConsumed(window: readonly MailboxConsumedRecord[], removed: readonly MailboxMessage[]): MailboxConsumedRecord[];
/** Validate a record id at `append`, before any side effect. `undefined` = no identity stated. */
export declare function readMailboxRecordId(raw: unknown): string | undefined;
/**
 * ONE read of a caller's append: every member read once, validated (`peerMeta`, then `id`) and detached.
 * A backend judges and persists THIS snapshot — never the caller's object again — so an accessor, or a
 * mutation while the append waits for its lock, cannot make the record judged differ from the record stored.
 */
export declare function readMailboxAppend(msg: MailboxAppendMessage): MailboxAppendMessage;
/**
 * THE PARKED RECORD'S MEMBER-SHAPE TABLE (`rowShapeReader`, row-shape.ts). `rowKey` is the box replay's predicate for an `append`
 * event's record (an object with a finite `seq`); `members` is what a delivery reads: the content, the stamp, the producer's id
 * ({@link readMailboxRecordId}), the sender name, the forwarding chain (a list of hops, a hole being absence), the peer metadata
 * slot (an object — its words are validated at `append` by {@link readMailboxPeerMeta}; a stored slot whose words another writer
 * chose is the drain's foreign judgment, never this table's) and the hold decision ({@link readStoredMailboxDecision}, which reads
 * a word it does not know as `held`). The exit is `block`: a box is an ordered log, so its records before the first one that does not read are served and
 * nothing at or past that one is leased, acknowledged, counted or swept — the box visibly stops there, every claim tells it, and
 * the remedy is to drop the box or repair the record ({@link mailboxReadablePrefix}).
 */
export declare const MAILBOX_MESSAGE_ROW_SHAPE: import("./row-shape.js").RowShapeReader<MailboxMessage>;
/** A box's held records as a delivery reads them: the readable PREFIX, and — when one does not read — the record it stops at. */
export interface MailboxReadablePrefix {
    readonly prefix: readonly MailboxMessage[];
    readonly blocked?: {
        readonly seq: number;
        readonly corrupt: RowCorrupt;
    };
}
/**
 * The `block` exit over a box's held records (in seq order): the records before the first one that does not read
 * ({@link MAILBOX_MESSAGE_ROW_SHAPE}), and that one. Every bundled backend's lease, ack fence and count read this, so no face serves,
 * consumes or counts past a record nobody can read.
 */
export declare function mailboxReadablePrefix(messages: readonly MailboxMessage[]): MailboxReadablePrefix;
/** The sentence a box's disclosure carries when its delivery stops at a record that does not read. */
export declare function mailboxBlockedSentence(scope: string, handle: string, blocked: NonNullable<MailboxReadablePrefix["blocked"]>): string;
/** The refusal of an `ack` that would consume past a record that does not read: nothing is consumed. */
export declare function mailboxAckBlockedRefusal(blocked: NonNullable<MailboxReadablePrefix["blocked"]>): MailboxStoreError;
/** The refusal of a decision move on a held record that does not read: nothing moves. */
export declare function mailboxDecisionOnUnreadableRefusal(corrupt: RowCorrupt): MailboxStoreError;
/**
 * THE append-by-identity judgment, the one every backend runs inside its write critical section
 * (with `msg` already validated: `id` by {@link readMailboxRecordId}, `peerMeta` by {@link readMailboxPeerMeta}),
 * over the box's two sets: the records it HOLDS and its received window ({@link MAILBOX_CONSUMED_ID_WINDOW}).
 * Returns that record's `seq` when `msg` replays it (the caller writes nothing), `undefined` when neither set
 * has a record under `msg.id` (the caller appends), and throws {@link MAILBOX_DUPLICATE_RECORD_ID_CODE}
 * naming the facets when a different record claims the id. A third-party backend calls this function too.
 */
export declare function judgeMailboxAppendById(box: {
    readonly held: readonly MailboxMessage[];
    readonly consumed: readonly MailboxConsumedRecord[];
}, msg: MailboxAppendMessage): number | undefined;
/**
 * The pluggable mailbox seam (design/151 §7.1). Contract notes for implementations (file/pg):
 * - `append` is durable-first (a returned seq means the box has taken the message: it survives a crash, still
 *   parked or — an id-bearing replay — already consumed inside the received window); seq is monotonic
 *   per (scope, handle) and never reused WITHIN a box's lifetime (across lease/ack cycles the
 *   high-water mark persists). `drop` ENDS the lifetime — a later rebuild restarts at 1 (server[1523]
 *   定谳: the row died with the box, dedup keys carry the handle, and a* handles are 64-bit-random).
 *   RB-90 (2026-07-25, red probe) SPLITS `reap` back out of that sentence: the two were grouped, but
 *   only `drop` is preceded by the row's death. `reap` is an age-based sweep that runs while the
 *   recipient is alive and may hold a lease, so restarting seq there let a stale ack (up to the
 *   pre-sweep high-water) delete a brand-new message no consumer had ever been shown — the "a parked
 *   message is never lost" promise at the top of this file, broken silently. `reap` therefore CLEARS a
 *   box and KEEPS its high-water mark; both bundled impls do so.
 * - `claimLease` atomically marks every currently-visible (unleased or lease-expired) message as
 *   leased by `owner` until `now + ttlMs`, returning them in seq order. Empty mailbox → null.
 *   A second claim by a DIFFERENT owner while a live lease exists returns null (single consumer
 *   per window — the row claim-CAS already guarantees one revival winner; this is the belt); the
 *   SAME owner re-claiming RENEWS the lease and picks up any newer messages (the crash-retry form
 *   — server[1523] 定谳: both bundled impls behave so, the contract follows the implementations).
 *   `owner` is a NAME the box compares by equality (the lease fence, `ack`, `releaseLease`): a string with a non-blank character and no
 *   control character ({@link isMailboxNameSpelling}); anything else is refused with {@link MAILBOX_INVALID_LEASE_OWNER_CODE} before
 *   any read or write ({@link assertMailboxLeaseOwner}, which every backend calls first) — a blank owner would make two holders read as one.
 * - `ack` deletes every message with seq ≤ upToSeq (the winner calls it at ATTACH success, never
 *   before — §7.1: ack-late is what makes a crashed revival lossless). The range is safe only on a store that keeps the
 *   sentence on {@link MailboxMessage.seq}: no lower seq shows up after a higher one.
 * - A HELD RECORD THAT DOES NOT READ ({@link MAILBOX_MESSAGE_ROW_SHAPE}; the box's exit is `block`): `claimLease` serves the records
 *   before it and leases nothing at or past it (an empty prefix answers `null`); an `ack` whose `upToSeq` reaches it is refused with
 *   {@link MAILBOX_ROW_MALFORMED_CODE} and consumes nothing; `peekCount` counts the prefix; a decision move on it is refused in the
 *   same code. Nothing removes it but `drop` (or a repair of its bytes) — so a producer's retry under a later record's id is never
 *   absorbed by a received window the stuck record was folded past. {@link mailboxReadablePrefix} is the one reading.
 * - `releaseLease` (best-effort) returns a lease early (spawn preflight failed before delivery).
 * - `reap` ages out whole mailboxes by newest-message age (explicit policy). It is the BACKSTOP, not
 *   the only reclaim path: the winning-delete arm of `reapDurableAgents` calls {@link MailboxStore.drop}
 *   for the row it deletes, in the same sweep (F-13 — the row's mailbox dies with the row). That call
 *   is ADVISORY: a drop fault never blocks the reap, and a box orphaned that way still ages out here.
 *   `drop` therefore has a real caller — an implementation that stubs it strands mailboxes until the
 *   age policy catches them.
 * - PRE-DELETE STATE (optional capability, additive contract extension): a backend that can SEE its
 *   recipient's lifecycle — one whose rows live alongside the session rows a retention/deletion
 *   cascade removes — must refuse `append` for a recipient the cascade has already tombstoned,
 *   CODED: an `Error` whose `code` is `"mailbox.recipient_tombstoned"` ({@link MailboxStoreError} is
 *   the bundled shape; consumers branch on the string). Accepting is the failure this clause names:
 *   `append` is durable-first, so the returned seq is a receipt for a message the cascade deletes
 *   before any consumer can lease it — a delivery promised to the sender and kept to nobody, which
 *   no other face reports. The refusal is per RECIPIENT and enqueue-only: a tombstone belongs to one
 *   `(scope, handle)` — the same two-part identity every other method here is keyed by, so it says
 *   nothing about a sibling handle NOR about the same handle under another scope — and it is not a
 *   wipe (whatever is already parked stays under the same lease/ack rules until the cascade removes
 *   the box). A backend with NO view of that
 *   lifecycle (the two bundled ones, the CC inbox adapter) has nothing to refuse and keeps accepting
 *   — the clause fixes the SPELLING of the refusal, so a deployment reads one code instead of a
 *   per-backend dialect. A backend that keeps the state writes it through its own
 *   `retireRecipient` and lists it through `listRetiredRecipients` (one optional pair); a backend
 *   without the pair has its box dropped instead. Acceptance kit: `mailboxTombstonedRecipientContract`.
 * - PEER METADATA (design/385, additive): `append` takes an optional typed `peerMeta`; a backend
 *   persists it and hands it back on `claimLease` byte-for-byte (a detached copy), absent stays absent,
 *   and a malformed value is REFUSED with `"mailbox.invalid_peer_meta"` before any side effect
 *   (`readMailboxPeerMeta` is the one validator; bundled backends call it first). T1 cases in
 *   `mailboxStoreContract` cover the pass trip, the refusal and the aliasing.
 * - RECORD IDENTITY (every backend): `append` takes an optional producer-minted `id`, persists
 *   it and hands it back on `claimLease`. While the box holds a record under that id, an append under
 *   it is answered by {@link judgeMailboxAppendById} — the held `seq` for an identical record (nothing
 *   written), `"mailbox.duplicate_record_id"` for a different one — atomically with the seq allocation;
 *   a malformed id is refused with `"mailbox.invalid_record_id"` before any side effect. This is what
 *   makes re-asking a store whose reply was lost safe: a rejected append is not proof that nothing was
 *   written. The box answers for what it has RECEIVED, not only for what it holds: `ack` enters every
 *   id-bearing record it deletes into the box's received window — exactly the newest
 *   {@link MAILBOX_CONSUMED_ID_WINDOW} by seq, each kept as `{ id, seq, digests }`
 *   ({@link MailboxConsumedRecord}, {@link mailboxReplayDigests}) — persisted and shared like the
 *   high-water mark, and the same judgment answers from it: the consumed record's `seq` (nothing written),
 *   or the refusal. `drop` clears the window; `reap` keeps it. Acceptance: the window cases of
 *   `mailboxStoreContract` (T1) and `mailboxCrossProcessContract` (T2).
 *   {@link MailboxStore.replayOf} is the same judgment asked without writing: a caller that must know whether
 *   its record is a repeat BEFORE it spends anything on it (a delivery gate's quota, an inbox bound) asks that,
 *   and the answer is the one `append` would give.
 * - CROSS-PROCESS SAFETY (design/385, optional capability declared on the store): the session-box
 *   drain shares ONE box between several OS processes. A backend that is correct under that sharing —
 *   seq minted once across processes, lease/ack never crossing, one process's housekeeping never
 *   discarding another's durable append — declares `crossProcessSafe: true` AFTER passing
 *   `mailboxCrossProcessContract` (the T2 kit that pins those cross-process properties, not "has a
 *   lock"; it awaits appends before reading, so it does NOT judge seq-order visibility —
 *   {@link MailboxMessage.seq}, which a sequence-backed commit-order store can break while passing
 *   the kit). A backend that does not declare it is refused by the lane at mount time with a named
 *   reason ({@link mailboxCrossProcessMountVerdict}) — never silently mounted on luck.
 */
/** #1036 — what {@link MailboxStore.ack} answers: did this call actually consume the prefix?
 *  `false` = the lease fence refused it (this caller does not hold the box), so nothing was deleted
 *  and the records are still parked for whoever does. */
export interface MailboxAckResult {
    readonly acked: boolean;
}
export interface MailboxStore {
    /** design/385 — cross-process safety declaration (see the interface notes). `true` = this backend
     *  passed `mailboxCrossProcessContract` over real OS processes; `false` = deliberately process-local
     *  (the in-memory reference); absent = undeclared (the CC inbox adapter). Read by
     *  {@link mailboxCrossProcessMountVerdict}; any other value is a malformed declaration and refuses. */
    readonly crossProcessSafe?: boolean;
    /** WHICH boxes this store serves, as an opaque word: two store objects with the same identity read and write
     *  the same boxes (one backing directory, one database), in whichever process they live. Absent = the store
     *  cannot say — and then no peer may assume that a box it appends to here is one another session drains. */
    readonly identity?: string;
    /** Durably park one message. Refuses `"mailbox.recipient_tombstoned"` when the backend can see
     *  that its recipient is in the deployment's pre-delete state (see the interface notes above). */
    append(scope: string, handle: string, msg: MailboxAppendMessage): Promise<number>;
    /**
     * Would `append(scope, handle, msg)` be a REPEAT? The read-only form of the record-identity judgment: the `seq`
     * an append of `msg` would answer from a record the box holds or has received ({@link judgeMailboxAppendById}),
     * `undefined` when it would write a new record (`msg` states no `id`, or the box has none under it), and the
     * {@link MAILBOX_DUPLICATE_RECORD_ID_CODE} refusal an append would give when a different record holds the id.
     * Writes nothing, creates no box, mints no seq, and does not consult the recipient's pre-delete state: a record
     * the box already took is answered with its first `seq` whether or not its recipient is being deleted since. A
     * malformed `msg` is refused with the codes `append` refuses it with, before anything is read. An answer is a
     * snapshot: a repeat racing the first append can still read `undefined`, and its `append` then decides.
     */
    replayOf(scope: string, handle: string, msg: MailboxAppendMessage): Promise<number | undefined>;
    claimLease(scope: string, handle: string, owner: string, ttlMs: number, now?: number): Promise<MailboxLease | null>;
    /**
     * Consume the leased prefix up to `upToSeq` (the records are DELETED). Fenced by the current lease:
     * a caller that does not hold it consumes nothing.
     *
     * #1036 — the fence's verdict is REPORTED (`{acked:false}`), not silent. The fence itself is
     * older (MB1): it exists so a stale owner whose lease a live rival already took over cannot delete
     * the rival's messages. What was missing is that a no-op and a success were the same `void` to the
     * caller, so a drain that had lost its lease would clear its own watermark as if the store had
     * obeyed it — the one shape where "the records stay parked" turns into "the records are forgotten".
     * Implementations report `{acked:true}` only when they actually consumed the prefix.
     */
    ack(scope: string, handle: string, owner: string, upToSeq: number): Promise<MailboxAckResult>;
    /**
     * Move one record's hold decision from `expect` (absent = never held) to `next`, atomically
     * against every other transition, against `claimLease` and against `ack` — the compare-and-set every decision
     * about a held record goes through. A person's or a policy's answer about a held record is NOT fenced by the
     * lease: it comes from whichever process shows the record, whether or not it holds the box. An edge out of
     * `delivered` is: the record was handed over and its injection is owed by the box's lease holder, so the move
     * happens only when the box's CURRENT lease names `holder` (the lease owner the caller claims the box with —
     * the fence {@link ack} takes, read in the same atomic step as the record's state; {@link mailboxDecisionMoveFenced}
     * is the one reading). `holder` absent = the caller claims no lease; on every other edge it is not read. A state
     * that is not `expect` answers `{ ok: false, current }` and changes nothing; a move the lease fence refuses answers
     * `{ ok: false, current: "delivered" }` and changes nothing; a record no longer in the box answers
     * `current: "gone"`. A malformed call (see {@link assertMailboxDecisionMove}) is refused with
     * {@link MAILBOX_INVALID_DECISION_MOVE_CODE} before any side effect. The state is durable like the record, and
     * `ack` / `reap` / `drop` remove it with the record.
     */
    moveDecision(scope: string, handle: string, seq: number, expect: MailboxDecision | undefined, next: MailboxDecision, holder?: string): Promise<MailboxDecisionOutcome>;
    releaseLease(scope: string, handle: string, owner: string): Promise<void>;
    /** Observation face (the "N pending" receipt figure) — count of currently-visible messages. */
    peekCount(scope: string, handle: string): Promise<number>;
    /**
     * Drop the WHOLE mailbox for (scope, handle) — the row-deletion companion (F-13).
     *
     * @contract mailbox.session_box_outlives_its_occupant — deleting a session's row does not remove its box
     * `(scope, session.<id>)`: a deployment's deletion cascade clears it with this verb (retention is the deployment's). What
     * stays behind is never delivered to another occupant: every session-box record names the occupant it is for
     * ({@link MailboxPeerMeta.occupant}), and a drain hands a record only to that occupant — a record for an earlier occupant
     * of the id is discarded with an account (`delegation.delivery_discarded`) by the next occupant's drain — the next one whose
     * row holds a token: a leg whose row holds none drains no box, so the record stays where it is meanwhile.
     */
    drop(scope: string, handle: string): Promise<void>;
    /** Age out mailboxes whose newest message BY `sentAt` (not by array/insertion order — RB-250②)
     *  is older than maxAgeMs. Returns mailboxes dropped. */
    reap(scope: string, now: number, opts?: {
        maxAgeMs?: number;
    }): Promise<number>;
    /**
     * Put `(scope, handle)` into the PRE-DELETE state — the tombstone `append` refuses by
     * (`"mailbox.recipient_tombstoned"`). Marks only: the messages already parked, their seqs and any live lease are
     * untouched, so a deletion cascade retires the recipient first and drops the box after. Repeating it updates the
     * tombstone's time and label. The tombstone lives as long as the box: `drop` removes both, so an id registered
     * again later is a new recipient (there is no un-retire verb, and none is needed). `at` is the retirement time
     * (epoch ms); `label` the recipient's name before it went, when it had one.
     *
     * `true` = a tombstone was written. `false` = none was, and the recipient is still refused: the store keeps no
     * pre-delete state for this box and dropped it instead, or its key judge does not admit this handle (an `append`
     * to it is refused by that judge's own sentence).
     *
     * Optional, and one capability with {@link listRetiredRecipients}: a store carries both or neither (read through
     * {@link mailboxRecipientLifecycleOf}, which refuses half). Absent ⇒ the store has no view of its recipients'
     * lifecycle; a deletion cascade drops the box. Acceptance kit: `mailboxTombstonedRecipientContract`.
     */
    retireRecipient?(scope: string, handle: string, at: number, label?: string): Promise<boolean>;
    /** The tombstones under `scope` whose handle starts with `handlePrefix` — what a directory shows as a recipient
     *  being deleted. Optional, one capability with {@link retireRecipient}. */
    listRetiredRecipients?(scope: string, handlePrefix: string): Promise<readonly MailboxRecipientTombstone[]>;
}
/** One retired recipient ({@link MailboxStore.listRetiredRecipients}). */
export interface MailboxRecipientTombstone {
    /** The box handle (a session box is `session.<id>`). */
    readonly handle: string;
    /** When it was retired (epoch ms). */
    readonly retiredAt: number;
    /** Its name before it went; absent when it had none. */
    readonly label?: string;
}
/**
 * The store's recipient-lifecycle pair, read as one capability: `undefined` when the store carries neither member;
 * both, bound to the store, when it carries both; a refusal (`config.invalid_argument`) naming the missing one when
 * it carries one — half the pair is not a smaller capability.
 */
export declare function mailboxRecipientLifecycleOf(store: MailboxStore): Readonly<{
    retireRecipient: NonNullable<MailboxStore["retireRecipient"]>;
    listRetiredRecipients: NonNullable<MailboxStore["listRetiredRecipients"]>;
}> | undefined;
/** The lane-mount verdict on a backend's cross-process declaration. */
export type MailboxCrossProcessVerdict = {
    ok: true;
} | {
    ok: false;
    code: typeof MAILBOX_CROSS_PROCESS_UNSAFE_CODE;
    reason: string;
};
/**
 * design/385 — may the cross-session lane (several OS processes draining one session box) mount over
 * this backend? `ok` only for an explicit `crossProcessSafe: true`. Every other shape refuses with a
 * named reason so the host can print it: absent (undeclared), `false` (process-local by design), or a
 * value of the wrong type (a malformed declaration is refused, not read as "probably fine").
 */
export declare function mailboxCrossProcessMountVerdict(store: MailboxStore): MailboxCrossProcessVerdict;
/**
 * THE mount verdict of the SESSION-BOX lane — a session's own `session.<id>` box, the drain that consumes it and every seat that
 * appends to it: the mailbox's cross-process declaration ({@link mailboxCrossProcessMountVerdict}) AND a session store that reads a
 * session's row by id (`SessionStore.headOf`). A box outlives its session's occupant (the id can be deleted and created again), and
 * a drain discards a record addressed to another occupant only after it has read, by id, that its run's session still holds the
 * occupant it acquired; over a store that cannot be read by id every such record is undecidable and the box would jam, so the lane
 * does not mount, and the reason names the missing read. One judgment, read by the drain mount, the peer-lane mount and the send
 * face, so where a record is parked and where it is drained cannot disagree. `sessions` absent = no session store at all: the same
 * refusal.
 */
export declare function sessionBoxMountVerdict(mailbox: MailboxStore, sessions: {
    readonly headOf?: unknown;
} | undefined): MailboxCrossProcessVerdict;
/** RB-250② (2026-07-28) class fix — the box age for `reap` is the MAX `sentAt`, not the
 *  last array element: `sentAt` is caller-supplied, so append order need not be time order, and taking
 *  the tail let a box whose freshest message was mid-array be swept — both bundled backends discarded
 *  a brand-new message. Non-finite `sentAt` ⇒ undefined ("unknown age ⇒ never reaped" — treating it as
 *  very old would let a malformed row delete a live box). Module-level export only; NOT re-exported
 *  from src/index.ts. */
export declare function newestSentAt(messages: readonly MailboxMessage[]): number | undefined;
/** A lease-facing copy of a stored record: every mutable member (hopChain, peerMeta) detached, so a
 *  consumer's mutation can never reach the record a redelivery serves. Shared by the bundled backends. */
export declare function detachMailboxMessage(m: MailboxMessage): MailboxMessage;
/**
 * In-process reference implementation (single-instance / tests). Same posture as
 * {@link import("./background-agent-store.js").InMemoryBackgroundAgentStore}: not default-mounted,
 * detached copies at both boundaries, single-event-loop atomicity.
 */
/** The retention knobs a mailbox `reap` takes (an age sweep only: a box is cleared, never trimmed by count). */
export declare const MAILBOX_REAP_KNOBS: readonly ["maxAgeMs"];
export declare class InMemoryMailboxStore implements MailboxStore {
    /** Process-local by construction (a Map): never a cross-process box, said so explicitly. */
    readonly crossProcessSafe = false;
    private boxes;
    private key;
    private box;
    append(scope: string, handle: string, msg: MailboxAppendMessage): Promise<number>;
    replayOf(scope: string, handle: string, msg: MailboxAppendMessage): Promise<number | undefined>;
    claimLease(scope: string, handle: string, owner: string, ttlMs: number, now?: number): Promise<MailboxLease | null>;
    ack(scope: string, handle: string, owner: string, upToSeq: number): Promise<MailboxAckResult>;
    moveDecision(scope: string, handle: string, seq: number, expect: MailboxDecision | undefined, next: MailboxDecision, holder?: string): Promise<MailboxDecisionOutcome>;
    releaseLease(scope: string, handle: string, owner: string): Promise<void>;
    peekCount(scope: string, handle: string): Promise<number>;
    drop(scope: string, handle: string): Promise<void>;
    reap(scope: string, now: number, opts?: {
        maxAgeMs?: number;
    }): Promise<number>;
}