@sema-agent/core
Version:
Stateless, task-oriented AI agent core
219 lines (218 loc) • 15.2 kB
TypeScript
import { type MemorySyncCursor } from "./sync.js";
import { type MemoryBackend, type MemoryEntry, type PatchReport } from "./types.js";
type CursorAxis = "scope" | "peer" | "store" | "incarnation";
/** The refusal of a sync whose baseline does not hold, raised before anything is written on either side: the cursor
* is not this sync's (`config.memory_sync_cursor_mismatch`, with `detail` naming the axis, what the cursor carried
* there and this sync's value on it) — judged here before any read or transport call on its scope, peer and store,
* and by the peer before any write on its incarnation, read off the peer's refusal before any local write — or the
* local store has nothing to bind a cursor to (`config.memory_sync_store`, no `detail`). `outs` are the two ways out
* its sentence names. */
type SyncRefusal = Error & {
code: "config.memory_sync_cursor_mismatch" | "config.memory_sync_store";
detail?: {
readonly axis: CursorAxis;
readonly found: "absent" | "other";
readonly want: string;
};
outs: readonly [string, string];
};
/** A thrown value read as a sync refusal this module minted, or `undefined` — the report's one reader of the refusal. */
export declare function readSyncRefusal(thrown: unknown): Pick<SyncRefusal, "code" | "detail" | "outs" | "message"> | undefined;
/**
* The identity a sync cursor is bound to — the one mint of {@link MemorySyncCursor.store}: the physical root of
* the local File store (the path its root anchor records). A store without a directory has no root to bind a
* baseline to and is refused as a sync plane (`config.memory_sync_store`).
*/
export declare function memorySyncStoreOf(backend: MemoryBackend): string;
/** The injected seam to ONE peer — core never bundles a fetch. */
export interface MemorySyncTransport {
/** The addressing identity of the peer `post` reaches (a central sync API: its normalized base URL) and the
* round's only source of its peer; another peer carries another identity. Rides the wire and the cursor
* verbatim — never a credential: an identity that is empty or only whitespace, a URL with userinfo, or one the
* same-principal egress pass would redact is refused before any read or request. Read once per call, and
* taken at its word: the engine cannot see where `post` actually sends. */
readonly peer: string;
/** Maps `path` (e.g. `/v2/memory/sync/user%3Aalice`) onto the peer, attaches auth, and returns the DECODED
* JSON body of a 2xx response — the answer to the call: its result, or the peer's refusal of it
* (`{ refused: "baseline_incarnation", incarnation }`, a 2xx answer like a result); any non-2xx / network
* failure should THROW (the call then aborts with zero local side effects — the transport runs before any
* local write). */
post(path: string, body: unknown): Promise<unknown>;
}
/** The wire REQUEST of one round (the server's `parseMemorySyncRequest` twin): the push
* half as computed against the client's own cursor. `deletes` ⊆ `Object.keys(baseRevs)` by
* construction (a delete is CAS'd on its baseline; an id never synced cannot be delete-propagated). */
export interface MemorySyncRequestBody {
/** The transport's {@link MemorySyncTransport.peer}. */
peer: string;
/** The claim of which state of the peer `baseRevs` was taken against: the cursor's
* {@link MemorySyncCursor.peerIncarnation} verbatim, present whenever the cursor carries one. The peer compares it
* with its own incarnation before any write and refuses — writing nothing — when they differ, or when
* `baseRevs` is not empty and no claim is made. */
peerIncarnation?: string;
/** id → rev at the last completed round (the cursor's baseRevs; empty = first round). */
baseRevs: Record<string, string>;
/** Full state of every entry new/changed here since the baseline. When
* {@link SyncMemoryScopeOptions.maxPushEntries} is set this is the id-ascending PREFIX of the
* full push set (batching — the remainder rides later rounds). */
entries: MemoryEntry[];
/** Ids deleted here since the baseline (tombstoned or gone from the local plane). Deletes are
* NEVER batched/split — they are id+baseRev pairs, weightless next to entry bodies. */
deletes: string[];
/** pull-half batching (wire contract; server implements the response side): ask the
* server to cap this round's pull half at `limit` items. Absent ⇔ unbatched (the prior
* wire shape byte-for-byte — old servers never see the key). */
pull?: {
limit?: number;
};
}
/** The wire RESPONSE of one round (server `MemorySyncResponse` twin: one RTT, both
* directions; `serverDeletes` is the delete-propagation leg [without it a central
* removal never crosses = livelock]; `cursor` is the server-computed next baseline with the
* retention discipline ALREADY applied to the pull half). A peer that refuses answers
* `{ refused: "baseline_incarnation", incarnation }` instead — its own incarnation, nothing written — which the
* sync raises as the cursor refusal on the incarnation axis. */
export interface MemorySyncResponseBody {
/** Ops the server actually landed from our push (empty on an idempotent replay). */
applied: PatchReport["applied"];
/** Server-side rejections/divergences: inbound-gate rejects, rev lies, CAS losses, both-sides
* divergence (resolve via the §3 ladder — loser minted as a sibling, never dropped). */
conflicts: Array<{
id: string;
reason: string;
baseRev?: string;
currentRev?: string;
}>;
/** The pull half: entries new/changed centrally since our baseline. */
serverEntries: MemoryEntry[];
/** The pull half's delete leg: centrally deleted, unchanged here since baseline (CAS baseRev). */
serverDeletes: Array<{
id: string;
baseRev: string;
}>;
/** The next baseline to persist AFTER the pull half lands (the client cannot compute it — it
* does not hold the central set). Pull-half ids are retained at the OLD baseline inside; the
* client advances the LANDED ones to their landed state before persisting (see ⑤ — otherwise
* every landed pull echoes back next round and a central delete can be resurrected).
* `incarnation` names the state that answered — the scope's partition on this peer, a value no other partition
* or state of it carries, every write of this exchange committed under it; it equals the request's claim when
* one was made, and the next cursor carries it as its `peerIncarnation`. */
cursor: {
peer: string;
incarnation: string;
baseRevs: Record<string, string>;
updatedAtMs: number;
};
/** pull-half batching (wire contract; server sets it): true ⇔ the server withheld part
* of the pull half under the requested `pull.limit` — the caller should run another round.
* The server MUST retain every withheld id at the OLD baseline inside `cursor` (the client
* refuses prefilled undelivered revs — see ⑤ defense — so violating this only costs the
* server an ignored advance plus a disclosed warning, never a permanently-missed pull). */
pullTruncated?: true;
}
/** One aggregated conflict: `server` = reported by the central half (its gate/CAS/divergence),
* `local` = produced landing the pull half here (our CAS refusals, inbound-gate rejects, rev
* lies). Nothing is hidden; the caller resolves via the §3 ladder (loser-as-sibling). */
export interface MemorySyncClientConflict {
side: "server" | "local";
id: string;
reason: string;
baseRev?: string;
currentRev?: string;
}
export interface SyncMemoryScopeOptions {
/** The LOCAL authority plane (TOC: the File backend). */
backend: MemoryBackend;
/** The scope this round syncs (one round = one scope, mirroring the server route). A scope that is not
* replicable ({@link isReplicableScope}: the `userlocal:` family) is refused with `config.memory_scope_key`
* before any read or request. */
scope: string;
/** The injected seam to the peer; its `peer` is the round's peer. */
transport: MemorySyncTransport;
/** The persisted cursor from the last completed sync with this transport's peer; absent = the first sync. A
* cursor for another scope, peer or local store — or one with no peer or store binding — is refused
* (`config.memory_sync_cursor_mismatch`) before any I/O; a cursor whose baseline was taken against another state of
* the peer — or one with a non-empty baseline and no incarnation — is refused by the peer before it writes, and the
* call raises the same refusal before any local write. The refusal carries `detail: { axis, found, want }` and the
* two ways out its sentence names (`outs`): for a scope, that partition's own cursor or none before its first
* completed sync; for a peer, re-bind over a transport that reaches the cursor's peer, or drop the cursor; for an
* incarnation, re-bind against the state the baseline was taken against (setting `peerIncarnation` to `want` only
* for a cursor that carries none, over that same state), or drop the cursor; for a store, rebind the cursor to this
* store (its `store` set to `memorySyncStoreOf(backend)`) when this store holds the entries its baseline was taken
* over, or delete it and sync from none, which brings back an entry deleted on either side since the last completed
* sync. The engine takes none of them on the host's behalf; `memorySyncReportOf` reads the refusal for a host. */
cursor?: MemorySyncCursor;
/** Caller-injected clock (engine precedent) — stamps the returned cursor's updatedAtMs. */
now?: () => number;
/** push-half batching: cap the number of push-half ENTRIES sent this round. The full
* push set is put in STABLE order (id ascending — deterministic across rounds/replicas) and the
* first `maxPushEntries` ride the wire; a cut round reports `pushTruncated: true`. Deletes are
* never split (id+baseRev pairs are weightless next to bodies). CALLER CONTRACT: on
* `pushTruncated`/`pullTruncated`, persist the returned cursor and run ANOTHER round until both
* flags clear — core deliberately never loops internally (the runner loop is the deployment's,
* server-side semantics apply); bound your loop (e.g. a fixed max-rounds cap ≥
* ⌈expected entries / limit⌉ + slack) so a misbehaving peer cannot spin it forever. Must be a
* POSITIVE integer (≥ 1 — C5: a 0 cap would flag pushTruncated forever and livelock the caller
* loop); absent ⇔ unbatched (prior behavior byte-for-byte). */
maxPushEntries?: number;
/** pull-half batching: forwarded verbatim as the wire request's `pull.limit`; a server
* that withholds part of its pull half answers `pullTruncated`, passed through on the result.
* Same caller contract as {@link maxPushEntries}: continue rounds (bounded) until it clears.
* Must be a POSITIVE integer (≥ 1 — C5, same livelock gate); absent ⇔ the request carries NO
* `pull` key (old-server compatible, pre- wire bytes). */
maxPullEntries?: number;
/** design/178 §3 — per-entry byte bound for the PUSH gate, matched against the entry's serialized
* file form (the same domain the harvest gate measures). Defaults to {@link MAX_MEMORY_BYTES},
* the engine's own per-file cap, so the wire cannot carry an entry the local gate would have
* refused: `scanMemoryWrite`'s size rung only runs when it is given a bound, and an entry that
* reached the backend out of band is exactly the population this gate exists for. */
maxEntryBytes?: number;
}
export interface MemorySyncClientResult {
/** True ⇔ the round was fully clean: cursor advanced AND zero conflicts on either side. */
ok: boolean;
/** What the push half contained (ids only — the bodies already went over the wire). */
pushed: {
entries: string[];
deletes: string[];
};
/** Ops the server landed from our push (response `applied` verbatim). */
serverApplied: PatchReport["applied"];
/** Ops we landed locally from the pull half. */
localApplied: PatchReport["applied"];
/** Aggregated server-reported + local conflicts (never hidden). */
conflicts: MemorySyncClientConflict[];
/** True ⇔ every pull-half item landed cleanly, so `cursor` is the NEW baseline to persist. */
cursorAdvanced: boolean;
/** The cursor the caller should now persist: advanced on full success, otherwise the INPUT
* cursor unchanged (undefined on a failed first round) — the retention discipline. */
cursor: MemorySyncCursor | undefined;
/** present (true) ⇔ `maxPushEntries` cut this round's push set — run another round off
* the persisted cursor until it clears (see the {@link SyncMemoryScopeOptions.maxPushEntries}
* caller contract). Never present on an uncut round (additive: old callers see no new key). */
pushTruncated?: true;
/** present (true) ⇔ the server reported its pull half was cut under `pull.limit` —
* same continue-until-clear caller contract. */
pullTruncated?: true;
/** Honest-disclosure channel for tolerated protocol violations (present only when non-empty).
* Today's single producer is the ⑤ cursor-prefill defense: a server that advances a
* NOT-DELIVERED-HERE id's rev inside the response cursor gets that advance REFUSED (old
* baseline kept / unknown id dropped) and disclosed here — silently swallowing it would turn
* the next round's pull judgment into a permanent miss (baseline == central rev ⇒ never
* pulled) or, for an unknown id, a spurious push-half DELETE of an entry never seen here. */
warnings?: string[];
}
/** Does a name a sync carries verbatim (a peer identity, a target, a scope key) hold a credential — a URL with userinfo
* (one holding a user or a password, a bare user name included: the slot is the credential's), or anything the same-principal egress pass would
* redact? Such a name is refused, never cleaned: a cleaned identity is another identity, and the cursor taken under it
* would not be this peer's. The userinfo is looked for wherever the string holds a URL's authority, not only at its head:
* a name that wraps a URL under another scheme (`proj:https://user@host/…`) parses as an opaque path, with no userinfo
* slot to read, yet it carries the same credential. The one test for the sync client and its report. */
export declare function carriesCredential(peer: string): boolean;
/**
* One full CLIENT sync round for one (scope, peer) against the central sync API — see the
* module header for the ①-⑤ flow and the cursor retention discipline. Pure orchestration: all I/O
* rides the injected backend/transport; the caller persists the returned cursor.
*/
export declare function syncMemoryScope(opts: SyncMemoryScopeOptions): Promise<MemorySyncClientResult>;
export {};