UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

161 lines (160 loc) • 17.2 kB
import { SessionError, type SessionHead, type SessionLogMark, type SessionMetadata, type SessionPlacementRecord, type SessionRowExpectation, type SessionStorage, type SessionTreeEntry } from "../harness/types.js"; import type { Session } from "../harness/types.js"; export declare function createSessionId(): string; /** The {@link SessionMetadata.incarnation} cell for a write laying a row's metadata down — the bundled repos' ONE mint point. `existing` * = the row before the write (`undefined`: none). Four cells, `tokenless` deciding only the last: * - no row (`undefined`): a random v4 (no time, no host) followed by the address-epoch mark `.2` ({@link fileHistoryScopeOf}) — call it with * `undefined` only in the write that CREATES the row; * - a row holding a token: exactly that token; * - a row with no token, `tokenless` `"keep"` (the default): `{}` — the row stays an unknown occupant, nothing is backfilled; * - a row with no token, `tokenless` `"mint"`: a random v4 WITHOUT the mark — a token outside the address epoch, so the row's file-history * scope stays its bare id and the history recorded there is still read, restored and deleted. * * `"mint"` is for a host whose own occupant test needs every row to hold a token, giving one to a row that already holds engine state; it * changes the row's occupant cell, never where its history lives. Any other `tokenless` is refused whatever the row * (`config.invalid_argument`), never read as the default. */ export declare function incarnationCell(existing: Pick<SessionMetadata, "incarnation"> | undefined, tokenless?: "keep" | "mint"): Pick<SessionMetadata, "incarnation">; /** The base64url characters of the occupant token's SHA-256 an address's tail holds: the one place the tail's length is written (the mint * cuts the digest to it, both readers match exactly it). A host sizing a column for scopes reads {@link FILE_HISTORY_SCOPE_SUFFIX_LENGTH}. */ export declare const FILE_HISTORY_SCOPE_TAIL_LENGTH = 22; /** How much longer an address is than the session id before it: the separator and the tail (UTF-16 units, as `String.length` counts the id; all ASCII). The longest scope * {@link fileHistoryScopeOf} mints is the id's length plus this, and the function sets no bound on the id itself: a host adds this to its own bound on the ids it accepts. */ export declare const FILE_HISTORY_SCOPE_SUFFIX_LENGTH: number; /** Does `sessionId` end in a scope tail (the separator, a tail of {@link FILE_HISTORY_SCOPE_TAIL_LENGTH} base64url characters, any `!`s)? Then it has no bare history scope ({@link fileHistoryScopeOf} * refuses it) and, as a string, reads as the shorter id's address ({@link readFileHistoryScope}): the one predicate behind both, for a host's census of its ids (KL-3996-a). */ export declare function sessionIdHasScopeTail(sessionId: string): boolean; /** * THE file-history scope of a session row `(sessionId, occupant)`, `occupant` being its {@link SessionMetadata.incarnation}. A token the * mint point minted ({@link incarnationCell}: a v4 then `.2`, matched whole) names a row born at its address: `sessionId~` + the first * {@link FILE_HISTORY_SCOPE_TAIL_LENGTH} base64url characters of the token's SHA-256 — two occupants of one id never share a scope, and the token never appears in it. Any * other occupant (none, a token from before the mark, a host's own — {@link incarnationCell}'s `"mint"` gives a row without one) reads as the id, where its history has always been — unless the id * itself ends like an address (`~` + a tail of that length; `!`s after it, one rule for the shape): its bare id could be another row's * address, so the call is refused (`config.invalid_argument`) and nothing is read, written or deleted for it; the way out is a new id. * No scope is ever two rows'. Every seat naming a history scope (record, boundary, restore, carry, cascade, a host's erase / sync) asks this. * * Grammar: `scope = sessionId | sessionId "~" tail`, `tail` exactly {@link FILE_HISTORY_SCOPE_TAIL_LENGTH} of `[A-Za-z0-9_-]` ending the scope; an id may carry `~` `%` `_`, so a scope is read * from its end ({@link readFileHistoryScope}). Engine-minted scopes are unambiguous; a pre-epoch bare scope of a tail-ended id is not (KL-3996-a; INTEGRATION-CORE). A minted scope is at most the id's length plus {@link FILE_HISTORY_SCOPE_SUFFIX_LENGTH}; the function does not bound the id itself. */ export declare function fileHistoryScopeOf(sessionId: string, occupant: string | undefined): string; /** {@link readFileHistoryScope}'s answer: the session id, and for an address its tail (a digest of the occupant's token, which cannot be read back). */ export interface FileHistoryScopeParts { readonly sessionId: string; readonly tail?: string; } /** * The inverse of {@link fileHistoryScopeOf}: `{ sessionId, tail? }`, `undefined` for a string no scope is (empty, a tail with no id, a tail then `!`s). It CANNOT * tell a tail-ended string meant as a bare id from an address and reads it as the shorter id's: the engine never mints one ({@link sessionIdHasScopeTail}); a host's * pre-epoch stock is the host's census (KL-3996-a). A store enumerates a session id's scopes with it, never by prefix. */ export declare function readFileHistoryScope(scope: string): FileHistoryScopeParts | undefined; /** The one decoding of a stored {@link SessionMetadata.incarnation} cell read back by a backend (header line, SQL column): * a non-empty string is the occupant token; a cell that is not there (`undefined`, or `null` = SQL NULL) is an unknown * occupant, silently; a cell that is there but is not a token (`""`, a non-string) is an unknown occupant too and `disclose` * is told once with the cell's shape (never its value). The cell never makes this throw; a throw from `disclose` propagates. */ export declare function readIncarnationCell(raw: unknown, disclose: (detail: string) => void): string | undefined; /** What a value that is not a name (a non-empty string) is, said by its shape — an empty string, or a non-string by its kind. A * disclosure of a bad cell or member says this, never the value (the value may be a secret and always reaches a log). */ export declare function notANameShape(raw: unknown): string; /** What an incarnation value must be to name an occupant: a non-empty string. Anything else names nobody. */ export declare function isOccupantToken(raw: unknown): raw is string; /** * THE reading of "do two readings of one session id's occupant cell (`SessionMetadata.incarnation`) name one occupant": each side is * decoded as {@link readIncarnationCell} decodes a stored cell — a non-empty string is the token, anything else (absent, `""`, a * non-string) is no token — and the two are one occupant when they hold the same token, or no token on either side (a row written before * occupants were minted, taken as it reads: every write that creates a row mints a token, so a row created again under the id never reads * as the one before it). A token on one side only is another occupant. Every occupant question in the engine asks this one predicate: * a run's own seats (the tree owner, the session address a frame or a notice is delivered to, a box record's addressee) directly, and a * comparison of two heads through {@link compareOccupants}. */ export declare function sameOccupant(held: string | undefined, current: string | undefined): boolean; /** * Whether two heads of one session id name the same occupant (each side a {@link SessionHead}, or a row's {@link SessionMetadata}): * `"unknown"` when either side has no row, otherwise {@link sameOccupant} of their occupant cells — `"same"` or `"different"`. Unknown * is never `"same"`, so a caller that may only proceed on the same occupant refuses on it. */ export declare function compareOccupants(before: { readonly incarnation?: SessionHead["incarnation"]; } | undefined, after: { readonly incarnation?: SessionHead["incarnation"]; } | undefined): "same" | "different" | "unknown"; /** * THE judge of a conditional row write ({@link SessionRowExpectation}), called by the repo inside the write's own atomic step with the * row as it stands there — its owner and occupant cell (`undefined` = no row) and a reading of its log's mark, asked for only when the * log binds: no expectation ⇒ no precondition; `row: null` ⇒ the row must be absent; otherwise the row must be there with the same owner * and the same occupant cell and — when `log` is given — a log of the same mark ({@link sessionLogMarkOf}). The occupant cell is compared * as written, an absent token equal to an absent one: this asks whether any write changed the row since the read the expectation came * from, not whether two parties name one occupant ({@link sameOccupant}, where an empty or non-string cell names nobody) — and since every write * that creates a row mints a token, a row without one cannot be created again, so an absent cell is one generation. An expectation that * is not of this shape is refused (a `TypeError` naming the member), never read as no precondition. */ export declare function sessionRowMatches(expect: SessionRowExpectation | undefined, row: { readonly owner?: string | null; readonly incarnation?: string | undefined; } | undefined, logNow: () => SessionLogMark): boolean; /** The one shape reading of a {@link SessionRowExpectation} — the judge above reads through it, and so does a door that takes one from a * caller before any write: a value not of the shape is a `TypeError` naming the member. */ export declare function readRowExpectation(expect: unknown): SessionRowExpectation; /** The refusal of a conditional row write whose expectation the row does not meet: nothing was written. */ export declare function rowExpectationMissed(sessionId: string, what: string): SessionError; /** The {@link SessionHead} of a row: the metadata's owner and occupant and the given leaf — the bundled repos' ONE construction of a head. The * occupant key is laid down only when the row has a token: a host-held row and a row that predates the cell answer a head with no * `incarnation` member at all (not one holding `undefined`), so "has the key" and "has an occupant" are one reading. */ export declare function sessionHeadOf(meta: Pick<SessionMetadata, "owner" | "incarnation">, leafId: string | null): SessionHead; /** The {@link SessionHead} a session object shows: its metadata's owner and occupant and its storage's leaf, off that one object. */ export declare function headOfSession(session: Session): Promise<SessionHead>; /** The {@link SessionMetadata.owner} cell a row-creating write records: a principal name, or `null` (anonymous). Anything else — * `undefined` (it is no `null`) and a blank string (it names nobody) included — is refused before the write, so no cell reads as * neither; a face whose owner is optional reads its absence first by its documented default and hands this judge a value. */ export declare function ownerCell(owner: unknown): Pick<SessionMetadata, "owner">; /** The metadata an import lays down, and the import's refusals — one reading for every repo that replaces a log. An import replaces * the log, never the row: an absent id is a new row recording `owner` and a fresh occupant; an existing row keeps its metadata whole * (its creation time, lineage, placement, occupant and owner were recorded by the write that created it), and only a row that is * already the importer's takes the log — owners compared null-safe, `undefined` naming `null` — so another owner's row is refused * `conflict` and a placed row `placement_refused`, before anything is written. `owner` is judged either way. */ export declare function importRowCells(sessionId: string, owner: unknown, existing: SessionMetadata | undefined, createdAt: string): SessionMetadata; /** The owner a {@link import("../harness/types.js").SessionRepo.recordOwner} call records: a principal name, read by the one name reading; * anything else (`null` included — a row that records none is the row this write is for) is refused `config.invalid_argument` before the * row is read. */ export declare function recordedOwnerName(owner: unknown): string; /** The one write law of `recordOwner`, judged on the row as the repo holds it in the write's own step: a row that records a name is left * as it is (`undefined`: nothing to write — the caller answers its head as read); a row that records none and is the row `expect` names * ({@link sessionRowMatches}, asked through `matches`) takes `name` as its owner and nothing else; any other row is refused `conflict`. * `expect` is read for its shape first, whatever the row. */ export declare function recordedOwnerCells(sessionId: string, name: string, existing: SessionMetadata, expect: SessionRowExpectation, matches: () => boolean): SessionMetadata | undefined; /** The one decoding of a stored owner cell: a stored name ({@link recordedPrincipalNameOf}) is the owner; absence (`undefined`, `null`) is anonymous. A cell that is * there but is neither (a blank string included) cannot be read as anyone's, and reading it as anonymous would admit every * principal — the row is refused as `corrupt_session` instead (a read fault, never an answer). */ export declare function readOwnerCell(raw: unknown, sessionId: string): string | null; /** The one decoding of a stored {@link SessionMetadata.placement} cell read back by a backend (header line, SQL column): `undefined` is no * placement; an object whose `kind` is a placement kind, whose `placedAt` is a finite number (a negative or fractional one included) * and whose `scope`, `handle`, `rootSessionId` and `parentSessionId` are each a string (an empty one included) when it is there, * answered as a copy holding the members as stored (a tuple missing a join half is a legal tuple, read by consumers as incomplete; * a member this reader does not know is an additive one an older reader tolerates and the copy keeps). Anything else — * no object (an array included), `null` (a backend whose absent cell reads `null` maps it to `undefined` first), a kind outside the * set (an empty string included) or missing, a `placedAt` that is missing or no finite number (a numeric string included), a member of the * wrong form — is neither a placement nor none: the row is refused `SessionError("corrupt_session")` (`detail.form` `bad_cell`), naming * the cell and the shape it holds, never the value. */ export declare function readPlacementCell(raw: unknown, sessionId: string): SessionPlacementRecord | undefined; /** The placement cell a write that lays a row down records: `given` (`undefined` is none and answers `undefined`; a `null`, an array or any * other non-tuple is refused), its `placedAt` stamped with `now` when it names none (absent or `null`), judged by the very judgment * {@link readPlacementCell} reads back with — so no row is written that a reader would refuse. A tuple that fails it is refused before * anything is written, with an `Error` whose `code` is `config.invalid_argument` (no `SessionError`), naming the cell and the shape it * holds, never the value. The answer is a copy: the caller's object is not touched. */ export declare function placementCellToWrite(given: unknown, sessionId: string, now: number): SessionPlacementRecord | undefined; /** A fork lands on a row OTHER than its source: onto its own id it would mint a new occupant over the source's transcript and erase the lineage that carries the source's records. */ export declare function assertForkTarget(sourceId: string, targetId: string | undefined): void; /** The refusal of a fork onto an id a row stands on (another writer was there first; nothing written) — every bundled repo's one sentence. */ export declare function forkTargetTaken(targetId: string): SessionError; /** A fork row's cells, minted from the SOURCE row as it stands at fork time — the same row the fork copies its history from: the lineage * (`forkedFrom` + the occupant copied), a fresh occupant of its own, and its owner — `owner` when one is named, otherwise (absent or `null`) * the source row's, so a copy of an owned history is never anonymous and never another generation's. */ export declare function forkRowCells(source: SessionMetadata, owner?: string | null): Pick<SessionMetadata, "forkedFrom" | "forkedFromIncarnation" | "incarnation" | "owner">; /** A row's metadata as the bundled repos hold it: frozen (its placement tuple too), so a caller holding the object `getMetadata()` or * `list()` returns cannot rewrite the row's identity cells — the owner, the occupant, the placement, the lineage — without a write. */ export declare function frozenRow<T extends SessionMetadata>(meta: T): T; export declare function createTimestamp(): string; export declare function toSession<TMetadata extends SessionMetadata>(storage: SessionStorage<TMetadata>): Session<TMetadata>; export declare function getEntriesToFork(storage: SessionStorage, options: { entryId?: string; position?: "before" | "at"; }): Promise<SessionTreeEntry[]>;