UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

236 lines (235 loc) • 18 kB
import { type MailboxAppendMessage } from "../core/mailbox-store.js"; import type { CrossSessionInboundVerdict } from "./cross-session-judge.js"; import type { RunnerDeps } from "../core/runner-deps.js"; /** The prepare-time refusal code of a malformed {@link RunnerDeps.principalInboxConsumer} (and of a gate * minting in a deployment that declared no consumer — {@link mintCrossPrincipalRecord}; and of an assistant seat a host handed a * leg on which the leg cannot read its principal inbox — `detail.reason: "seat_unbound"`). */ export declare const PRINCIPAL_INBOX_CONSUMER_INVALID_CODE = "config.principal_inbox_consumer_invalid"; /** Who consumes a scope's principal inbox. `none` = the deployment declared no consumer (it mounts no * delivery gate): no lane anywhere. `assistant` = the leg the host hands {@link PrincipalInboxAssistantSeat} reads it (the * declaration names no leg: the seat does). */ export type PrincipalInboxConsumer = { kind: "none"; } | { kind: "terminals"; } | { kind: "assistant"; }; /** * The ASSISTANT SEAT a host hands ONE leg through its trusted internals (`RunInternals.principalInboxAssistant`) — never a * {@link RunnerDeps} member, never a `TaskSpec` field, never a tool argument: under the `"assistant"` declaration the leg it is * handed to, and that leg alone, reads the scope's principal inbox. The seat names the session it answers for: it counts only on a * leg whose session id is exactly {@link sessionId}; on any other leg — a leg that re-ran another leg's internals in a session of * its own — it is inert (no lane, no refusal, nothing said). A checkpoint never carries it: the host hands it on every leg it starts, * a resumed one included. */ export interface PrincipalInboxAssistantSeat { /** The session this seat answers for — the assistant leg's own session id, compared exactly. A string with a character that is neither whitespace nor a control character: a blank id names no session and is a malformed seat, refused. */ readonly sessionId: string; /** * The host's OBSERVER of the letters the leg's model is about to read: called once per `ReadInbox` pull with the page's * principal-inbox letters, in the order the page hands them over, after the pass is over and before the result goes back to the * model — and awaited. Resolved ⇒ the result carries them. Rejected, thrown, or the call aborted first (`ctx.signal` is the * call's own; a late answer is ignored) ⇒ the page's letters are withdrawn: out of the result, still in the box, handed over * again — and shown again — by a later pull; the session box's frames on the same page are handed over as made. At least once: * the same letter comes again after a withdrawal, a re-supply after a compaction, or a lease another leg took over — its key is * {@link principalInboxLetterKey} (recipient scope, {@link PrincipalInboxLetter.fromScope}, {@link PrincipalInboxLetter.gateReceiptId}), never `seq`. Handed * over is not read: a host hook that rewrites the result afterwards decides what the model sees. A letter that does not go to * the model this time — refused, consumed by the receiving station, still held — is not shown. Absent ⇒ no host step. */ onLetters?(letters: readonly PrincipalInboxLetter[], ctx: { signal: AbortSignal; }): Promise<void>; } /** One principal-inbox letter as {@link PrincipalInboxAssistantSeat.onLetters} receives it: the box record as the delivery gate * minted it, not the frame a receiving station rewrote. `content` is another principal's words — untrusted content. */ export interface PrincipalInboxLetter { /** The record's seq in the box: stable while the record lives, minted again after a drop — not a de-duplication key; the letter's key is {@link principalInboxLetterKey}. */ readonly seq: number; readonly fromScope: string; readonly gateReceiptId: string; readonly sentAt: number; /** The sender's display name, as the gate minted it. */ readonly from?: string; readonly urgent?: true; readonly content: string; } /** * THE consumer arbitration of a scope's principal inbox ({@link PRINCIPAL_INBOX_HANDLE}), * read off {@link RunnerDeps.principalInboxConsumer}: absent ⇒ `none` (no principal-inbox lane: a * deployment without a delivery gate claims no extra box, byte for byte as before); `"terminals"` ⇒ the * scope's terminal sessions, each draining it as a second box beside its own; `"assistant"` ⇒ the scope's assistant alone — the leg * the host hands {@link PrincipalInboxAssistantSeat} — and no terminal session drains the box (it does not claim and yield — it * never mints the lane). ANY other value is refused with {@link PRINCIPAL_INBOX_CONSUMER_INVALID_CODE}: * a malformed assistant configuration must never be read as "terminals", which would let terminal sessions * take the letters past the assistant. The retired form `{ assistant: "<handle>" }` is one of those values, refused by name with * the way to the current form (never read as `"assistant"`: the handle chose a leg, and the seat does that now). The one judgment * every reader calls: the drain binding (which lanes), the `ReadInbox` mount (its origin) and the record mint (a gate with no consumer). */ export declare function principalInboxConsumerOf(deps: Pick<RunnerDeps, "principalInboxConsumer">): PrincipalInboxConsumer; /** The one refusal shape of the consumer declaration: code {@link PRINCIPAL_INBOX_CONSUMER_INVALID_CODE}, * `detail.reason` naming which fact refused it (`malformed` / `no_consumer` / `seat_unbound`). Also the refusal of the `ReadInbox` face's copy of the * principal-inbox lane declaration (`coversPrincipalInbox`): the same subject, so the same code. */ export declare function consumerRefusal(message: string, reason: "malformed" | "no_consumer" | "seat_unbound"): Error; /** * The sender as the deployment's AUTHENTICATION context states it — an object the gate implementation * receives from its own auth layer, never a string a caller passes in. `scope` is the authenticated * principal's storage scope (it becomes the record's `fromScope`); `name` is the display label the * recipient sees. */ export interface OrgAuthenticatedSender { readonly scope: string; readonly name?: string; } /** What a sender asks the gate to carry. */ export interface CrossPrincipalBody { readonly content: string; /** The sender marked it urgent: the recipient presents it first; it never changes WHEN the recipient reads. */ readonly urgent?: boolean; } /** * The gate's refusal words (closed set). `not_member` — the two principals do not share an organization * (or the deployment cannot say they do); `rate_limited` — the cross-principal quota of the sender pair * or of the recipient is spent; `inbox_full` — the recipient's principal inbox is at its bound; * `recipient_tombstoned` — the recipient principal is being deleted (the store's own pre-delete code, * relayed); `receipt_id_reused` — the caller's receipt id ({@link OrgDeliveryOptions.receiptId}) already * names a DIFFERENT letter from this sender in this recipient's inbox. A refused delivery appends nothing * anywhere. */ export declare const ORG_DELIVERY_REFUSAL_CODES: readonly ["org_delivery.not_member", "org_delivery.rate_limited", "org_delivery.inbox_full", "org_delivery.recipient_tombstoned", "org_delivery.receipt_id_reused"]; export type OrgDeliveryRefusalCode = (typeof ORG_DELIVERY_REFUSAL_CODES)[number]; export declare function isOrgDeliveryRefusalCode(value: unknown): value is OrgDeliveryRefusalCode; /** The gate's synchronous answer: a receipt naming the appended record, or a coded refusal. */ export type OrgDeliveryOutcome = { ok: true; receipt: { receiptId: string; seq: number; }; } | { ok: false; code: OrgDeliveryRefusalCode; message: string; }; /** * What a caller may state about ONE delivery, beside the letter itself. * * `receiptId` is the CALLER's key for the letter: a deployment's outbound queue states it before the first * attempt and states the same one on every retry of that letter. Absent = the gate mints one, and the ask * cannot be recognised as a repeat. A malformed value (not a string with a non-blank character and no control * character, or one that cannot be a record identity — see {@link mintCrossPrincipalRecord}) makes the gate throw before * anything is spent or appended. * A retry states the SAME letter as the first attempt (the same sender name, content and urgency; when it was sent is * not compared): a key that returns with another display name or the urgency flipped is refused * `org_delivery.receipt_id_reused`, never answered with the first receipt, which would acknowledge a letter the box does * not hold. A deployment that changes either between attempts takes a new receipt id for the changed letter. */ export interface OrgDeliveryOptions { readonly receiptId?: string; } /** * THE contract a deployment implements. `toPrincipal` is the recipient as the deployment addresses * principals (its own directory resolves it to the recipient's scope); an unknown recipient and one the * sender may not reach answer the same refusal bytes (`not_member`), so the gate is never an existence * probe. * * IDEMPOTENCE on the caller's receipt id: the same key asked again answers the FIRST receipt, counted against no * bound and no quota. A letter's key is (the recipient's principal inbox, the sender's scope, the receipt id); the * one mint states it as the record's identity ({@link mintCrossPrincipalRecord}), so the inbox's own * append-by-identity judgment decides it — over the records the box holds and over its received window * ({@link import("../core/mailbox-store.js").MAILBOX_CONSUMED_ID_WINDOW}), atomically with the seq allocation, * in every backend. The order a gate keeps: mint the record (pure), then — before it records an attempt, judges * membership, reads the inbox bound or takes quota — ask the recipient's inbox store * {@link import("../core/mailbox-store.js").MailboxStore.replayOf} for it (an empty recipient scope is refused as * `append` refuses it; any other string is a box key, and a box that does not exist holds no letter and answers * `undefined`). A hit answers `{ ok: true, receipt: { receiptId, seq } }` with the key's own receipt id and the first `seq`, and nothing else happens; a different letter under the key * (what a letter says: the sender's name, the content, the urgency — not when it was sent) is refused * `org_delivery.receipt_id_reused`; a miss goes on through the gate's bounds to the append, which decides again * if the first ask was still in flight. The question carries the sender's own scope in its key, so it can only * meet a letter this sender sent — it is no existence probe — and a letter the box accepted stays acknowledged * after its recipient left the organization or began to be deleted. The protection reaches as far as the * box's memory: the records it holds and the newest `MAILBOX_CONSUMED_ID_WINDOW` it has received. Map a store's * `append` failure to the refusal it means with {@link orgDeliveryRefusalOfAppendFailure}. */ export interface OrgDeliveryGate { /** * @contract cross_session.gate_narrows_reach — A deployment may narrow, inside its gate, who can write to whom beyond organization * membership (for example a recipient's own list of the senders that may reach it). A narrowing refusal answers * `org_delivery.not_member` with the same code and the same message bytes as an unknown recipient or another organization, and it is * given at the membership step — before anything is appended and before any quota is spent; an attempt bound the deployment keeps on * membership refusals counts it as it counts one. The gate never writes a verdict on the record: every letter it appends is judged at * the recipient's drain by the principal arm, like every other. So passing the gate means "may be stored" and nothing more — it is not * `next-turn` or `wake` (a recipient who set nothing still holds the letter as `cross-principal-default`), it releases no letter a * setting holds (`managed-setting`, `explicit-setting`, `invalid-setting`, `cross-principal-default`), and the list has no reader in * the tool-question ladder: a sender on it mints no allow rule and clears no `mandated` question. */ deliverCrossPrincipal(authedFrom: OrgAuthenticatedSender, toPrincipal: string, body: CrossPrincipalBody, opts?: OrgDeliveryOptions): Promise<OrgDeliveryOutcome>; } /** * The refusal word an `append` failure of the recipient's principal inbox means, or `undefined` when the failure * is none of the gate's refusals (the gate rethrows it). Reads the failure's `code` only — a cross-process store * hands back no class instance: the store's pre-delete refusal ⇒ `org_delivery.recipient_tombstoned`; the * record-identity refusal (the letter under the caller's receipt id differs from the one the box already * has) ⇒ `org_delivery.receipt_id_reused`. The one mapping every gate implementation uses. */ export declare function orgDeliveryRefusalOfAppendFailure(err: unknown): OrgDeliveryRefusalCode | undefined; /** * The record the gate appends into `(recipientScope, PRINCIPAL_INBOX_HANDLE)` — the ONE mint, so every * gate implementation writes the same typed shape. Pure. Writes `peerMeta { kind: "peer_message", * fromScope, gateReceiptId }` (+ `urgent`) and the display `from`; writes NO `fromSession` (a sender's * session id addresses nothing in the recipient's scope), NO `fromMode` (the principal arm reads no * parity) and NO `hopChain` (the org gate owns the cross-principal quota; the same-principal admission * gate's chain does not apply). States the record's IDENTITY — `id` = the pair (`from.scope`, `receiptId`): with the * recipient's box it is the letter's key, the one every repeat of the letter carries (see {@link OrgDeliveryGate}). * Throws when the receipt id is not a name the box keeps ({@link isMailboxNameSpelling}), or when the pair is * no storable record identity (`mailbox.invalid_record_id` for both; the pair is bounded by * {@link import("../core/mailbox-store.js").MAILBOX_RECORD_ID_MAX_CHARS}), when the anchors cannot be stored, or when the * sender's scope cannot be spelled on the envelope (the gate maps that to its own failure; nothing has been appended yet). * * `consumer` is the deployment's declared principal-inbox consumer ({@link principalInboxConsumerOf} over * the same `RunnerDeps` the deployment runs its legs with). A gate in a deployment that declared NONE is a * half-configured deployment: the append would hand the sender a durable receipt for a letter no leg will * ever read — so the mint REFUSES it with `config.principal_inbox_consumer_invalid`, at the first delivery, * before anything is appended (the same coded refusal a malformed declaration gets; core holds no seat for * the gate itself, so the delivery is the first moment both facts meet). */ export declare function mintCrossPrincipalRecord(input: { from: OrgAuthenticatedSender; body: CrossPrincipalBody; receiptId: string; sentAt: number; consumer: PrincipalInboxConsumer; }): MailboxAppendMessage; /** Does this stored record carry the gate's two anchors as a peer message — i.e. was it minted by * {@link mintCrossPrincipalRecord}? The principal inbox serves nothing else. */ export declare function isGateMintedRecord(meta: { kind?: string; fromScope?: string; gateReceiptId?: string; } | undefined): boolean; /** * How a scope's assistant treats one principal-inbox letter, from the recipient's judgment of it. * `triage_readonly` — read and triage it, read-only tools only (replies, writes and spending still wait * for the owner); `draft_for_approval` — triage and DRAFT, the draft goes to the owner with the letter * and nothing leaves until the owner approves; `decline` — do not read it, decline on the owner's behalf. * An unset setting never reaches `triage_readonly` for a cross-principal letter: the judge holds it. */ export declare const PRINCIPAL_INBOX_TRIAGE_POLICIES: readonly ["triage_readonly", "draft_for_approval", "decline"]; export type PrincipalInboxTriagePolicy = (typeof PRINCIPAL_INBOX_TRIAGE_POLICIES)[number]; export declare function principalInboxTriagePolicy(verdict: CrossSessionInboundVerdict): PrincipalInboxTriagePolicy; /** * THE key of one letter — the one every repeat of it carries, and the one every side effect a consumer takes for it * (a draft, a decline, an audit row, a host's own copy) is keyed by. The principal inbox is consumed at least once — a * lease that lapses before its ack, a withdrawn page, a re-supply after a compaction, a record dropped and appended again * serve the letter again — so a consumer that finds an effect under this key already written skips it. The key is * (the recipient's scope, the sender's scope, the receipt id): what the delivery gate and the box keep for the letter * ({@link OrgDeliveryGate}), never the box `seq`, which a drop and a new append change. A JSON array, so two triples never * spell one key (`("a","bc")` is not `("ab","c")`) — the spelling {@link mintCrossPrincipalRecord} gives the record's identity, * the recipient's scope added. Total over every letter a box holds: the box guarantees the two anchors are non-empty strings, * and a receipt id an older mint accepted — blank, or carrying a control character — is a key like any other. Throws * `TypeError` when a part is not a non-empty string: a key that names no letter is refused, never made. */ export declare function principalInboxLetterKey(recipientScope: string, letter: { readonly fromScope: string; readonly gateReceiptId: string; }): string;