UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

169 lines (168 loc) • 14.2 kB
import { type ReceiptFault } from "./mods/kernel/receive.js"; /** * design/80 D-1 §2 (slice 1a.2) — the engine-only **vetted canonical serializer** used to mint a stable, * opaque {@link exactBoundInputHashOf | boundInputHash} over a pending tool call: its tool's name and its arguments. * * ## Why a bespoke serializer (and why engine-ONLY) * The package's only runtime deps are typebox + the MCP SDK — there is no canonical/stable JSON serializer, * and `JSON.stringify` is **not** canonical (object key order is insertion order, `-0`/`NaN`/`Infinity` are * mishandled, and it offers no type-tagging). The review r3 ruling (design/80 §7) is the load-bearing * constraint: **never let two runtimes each compute a canonical form and compare** — a `JSON.stringify` * divergence (or a serializer-version drift across a worker upgrade) would produce a false mismatch and * fail-closed a *legitimate* approval. So the boundInputHash is **server-minted opaque**: the engine computes * it ONCE at suspend-mint with THIS serializer, persists it on the checkpoint, and a resume verifies by * **opaque string equality** against the persisted value (it never re-serializes the resume-side args). This * serializer therefore only needs to be *internally deterministic* (same value → same bytes within one * runtime); it is deliberately NOT exported from the package index, so no cross-wire consumer (the SDK / * service) can be tempted to recompute it — they treat the hash as opaque and echo it verbatim. * * ## Canonical form * A total function (never throws) that emits a **type-tagged, length-prefixed** string so distinct values of * distinct types can never collide (`number 1` ≠ `string "1"` ≠ `boolean`, and `{"a":"b"}` ≠ `{"ab":""}`): * - `null` → `N`, `undefined` → `U`, at any depth: `{a:undefined}` and `{}` are two forms — the form a workflow call's journal * key, the rewrite judge, a file rule store's checksum, a wiring fingerprint and every other digest of a value taken here * read; a call's approval binding digests the arguments' JSON form ({@link exactBoundInputHashOf}) * - boolean → `b1` / `b0` * - number → `n:<canonical>`; finite via `String(x)` (shortest round-trippable, deterministic per value); * `-0` normalized to `0`; `NaN`/`±Infinity` get explicit distinct tokens (never collapsed to `null`) * - bigint → `i:<value>` * - string → `s<byteLen>:<raw>` — **length-prefixed, NOT normalized**: equal inputs map to equal output and * distinct inputs (e.g. a non-NFC string vs its NFC form) map to distinct output. The serializer never * silently Unicode-normalizes (that would let two different argument payloads share one hash). * - array → `a<len>:[<el>…]` — order preserved (semantic) * - object → `o<count>:{<keyLen>:<key>=<val>…}` — **own enumerable keys sorted** by UTF-16 code unit, so * `{a,b}` and `{b,a}` canonicalize identically. (Duplicate keys cannot exist on a live JS object — * last-wins already happened at parse/construction — so they need no special handling here.) * - function / symbol → tagged tokens (`fn` / `y:<desc>`) so the serializer stays total; these never appear * in design/37 post-hook tool args (which are JSON values), but encoding rather than throwing keeps a * weird arg from silently degrading a durable suspend to a non-durable fallback. * - non-JSON OBJECT brands (Date/Map/Set/RegExp/typed arrays/boxed primitives/…) → a **type-discriminator * token carrying their state** (see {@link encodeBranded}). Built-ins keep their state in internal slots, * so encoding them by own enumerable keys alone folded every one of them onto the SAME empty-object form: * `new Date(0)`, `new Date(9e12)`, a `Map`, a `Set` and `{}` all minted one hash, and an equality check * over that hash accepted a substituted payload (false-accept — the direction a binding cannot afford, * since a mismatch is visible and a match is not). Reachable only when a DEPLOYMENT supplies non-JSON * values (model-produced args are JSON; a hook / policy rewrite is the way in). * * ## Compatibility boundary of the brand tokens * JSON values (null/boolean/number/string/array/plain object) hash **byte-identically** to before the * discriminator existed — the brand is read from `Object.prototype.toString`, and everything that reports * `[object Object]` (including a class instance with no `Symbol.toStringTag`, and a cross-realm plain object * whose `Object.prototype` differs) keeps the own-enumerable-keys encoding. Only NEWLY minted hashes over * non-JSON values move. That is safe by construction for the persisted ones: the hash is opaque and * server-minted, a resume compares the persisted string and never re-serializes. */ export declare function canonicalize(value: unknown, standsAt?: number): string; /** What {@link canonicalize} returns when even its top level cannot be encoded — a reader that must never accept a * constant (the checkpoint row digest) refuses on it. */ export declare const UNCANONICALIZABLE = "<uncanonicalizable>"; /** * design/80 D-1 §2 — a SHA-256 (hex) over {@link canonicalize}: the engine's one digest of a value. A call's binding is this digest * over `{ tool, input }` ({@link exactBoundInputHashOf}); the other digests the engine takes of a value (a Skill card's lists, a * tool's declaration, a question batch) are this digest over that value. The hex digest is fixed-length and opaque — exactly * what the operator sees / the D-G signer signs. */ export declare function boundInputHashOf(value: unknown): string; /** The short digest the engine names an identity by: the first sixteen hex characters of the SHA-256 of `text`. The tool roster mints its * capability identity and its own digest through it; {@link isSha16} is the one reading of the form it mints. */ export declare function sha16(text: string): string; /** Does `value` read as a digest {@link sha16} mints — a string of exactly sixteen lowercase hex digits? */ export declare function isSha16(value: unknown): value is string; /** * The text form of one string's SHA-256: `sha256:` + the lowercase hex digest of the string's UTF-8 bytes (WHATWG encoding: * a lone surrogate encodes as U+FFFD), 71 characters, never truncated. The string is digested as it is handed in — no * newline, whitespace or Unicode normalization — so two strings share a value only when their UTF-8 bytes are equal. Every * `sha256:` value the package mints over a string goes through here: published prompt text, a locale row's source, an * artifact's members, a stored rule file's checksum over its canonical form, the plan shown at a plan pause. How a * caller builds the string it digests (a canonical form, fields joined by NUL) is the caller's; only this last step is shared. * Unsalted on purpose: the value is comparable across processes and by a reader who holds the same text — which is also why * a value over short private text must not reach a trace, a metric or a log line. */ export declare function textContentHashOf(text: string): string; /** Does `value` read as a value {@link textContentHashOf} mints — `sha256:` and exactly sixty-four lowercase hex digits? */ export declare function isTextContentHash(value: unknown): value is string; /** * THE digest an approval binds a CALL by: SHA-256 (hex) over the canonical form of the one record `{ tool, input }` — the tool's name as the * call spells it and the arguments in their JSON form ({@link capturedJsonOf}: a record member holding `undefined` absent), one * digest for the call in memory and after a durable store's JSON round trip — when an approval can be bound to the arguments * ({@link bindableValueOf}), else `undefined`. * Every binding of a call mints through it and every comparison of one reads it: the park row's `boundInputHash`, the live ask's * and the routed question's reconciliation hash, and an answer's licensed bytes (`inputDigest`, compared by `licenseCovers`) — so * one approval covers one tool over one set of bytes, and a call of another tool over the same bytes under the same call id is * another question. The name is read as given (no alias or case is resolved: the row, the ask and the record each carry the * call's own `toolName`). The record only HOLDS the two members (it is canonicalized at depth −1, {@link canonicalize}), so the * arguments count their containers as when digested alone and the form is exact over the whole bindable domain; key order is * the serializer's own (sorted), so the two members cannot be permuted. */ export declare function exactBoundInputHashOf(tool: string, input: unknown): string | undefined; /** * THE reading of whether an answer edits a call: its `updatedInput` is an edit only when it is other bytes than the arguments the * answer was handed, under the call's one binding — `shown` is their {@link exactBoundInputHashOf}, taken by the seat BEFORE it * waits (a value read afterwards could have been moved to match). Bytes the binding reads as shown — keys in another order, a * member holding `undefined` beside its absence, `-0` beside `0` — are the call handed back as shown: no edit, the same answer as * one that carried none. Bytes with no digest (outside the bindable domain), or shown bytes with none, are an edit, refused where * an edit is taken. Returns the edit, else `undefined`. Every reader of "did this answer edit the call" reads it. */ export declare function editOfAnswer(tool: string, shown: string | undefined, updatedInput: unknown): unknown; /** * Why a value is outside the bindable domain: its top is not the payload's shape, a refusal of the receipt it is read by, or one of * JSON's own five — a number that is not finite, a hole in a list, a named member on a list, an `undefined` list element, one * object met twice. */ export type BindingFault = ReceiptFault | { readonly kind: "not-container" | "not-finite" | "hole" | "list-member" | "undefined-element" | "shared"; readonly path: readonly string[]; }; /** * THE judge of the BINDABLE domain — the values an approval can be bound to, and so the only values with an exact digest: plain * JSON data (records, dense lists, strings, finite numbers, booleans, `null`; a record member holding `undefined` is legal and * kept on the copy as given) under a top of the payload's own shape (`top`: a call's arguments are a RECORD — the default, and the * only shape an exact digest is taken of; a question's answers are a LIST), a tree (no object met twice), at most 256 levels of * containers. Read by the engine's one receipt of a caller's value in {@link BINDING_RECEIPT} (nothing of the caller's runs: a * getter, a hidden or symbol-keyed member, a Proxy, a function, a symbol, a bigint, a Map / Set / Date / binary or any other kind * of object, a cycle, nesting past the levels — each refused), then JSON's own five on the receipt's frozen copy. Ok ⇒ that copy. */ export declare function bindableValueOf(value: unknown, top?: BindingTop): { readonly ok: true; readonly value: unknown; } | { readonly ok: false; readonly fault: BindingFault; }; /** The top a bound payload has: a call's arguments are a record, a question's answers a list. */ export type BindingTop = "record" | "list"; /** THE capture of a caller-supplied payload the engine persists and later compares (a durable decide's edit — a record —, a * question's answers — a list): the judge's receipt ({@link bindableValueOf}) kept in the form a durable store's JSON round trip * hands back ({@link jsonFormOf}) — the form a call's binding digests ({@link exactBoundInputHashOf}). */ export declare function capturedJsonOf(value: unknown, top?: BindingTop): { readonly ok: true; readonly value: unknown; } | { readonly ok: false; readonly fault: BindingFault; }; /** One clause naming a binding fault, its path rooted at `args` (`value` is what the judge was given: for a value that is not * data, its `typeof` is read at the fault's place). The text holds the value's own member names: contain it to show it. */ export declare function describeBindingFault(value: unknown, fault: BindingFault): string; /** * Recursion-depth ceiling. Makes {@link encode} TOTAL against the two ways a naive recursive walk throws: * a CIRCULAR reference (infinite recursion → `Maximum call stack size`) and pathological DEEP nesting (a * RangeError before the JS stack limit). At/below this depth a deterministic sentinel is emitted instead of * recursing — so {@link boundInputHashOf} can never throw. This is load-bearing (MAJOR-4): digests are read after a remote * VM is paused (the park's target mint compares one), where a throw would skip the unpause compensation and leak the VM. * 256 is far below the engine's stack limit yet far deeper than any real tool-arg payload. It is also the bindable domain's * bound ({@link BINDING_RECEIPT}), so no value with an exact digest meets the sentinel. */ export declare const MAX_DEPTH = 256; /** Canonical JSON (recursively sorted keys, no whitespace) — the erasure protocol's ONE comparison * and hash basis: `selectHash` complains bind to it, and evidence rows are written/compared in this * form so a re-serialized import (key order changed by a middle layer) still compares equal. The memory * export bundle's section hashes are sha256 over it, and a backend that hashes or compares the same * records calls this function — the bytes are the contract, so there is no second copy to keep in step. * * Not {@link canonicalize}: that one emits a type-tagged, length-prefixed form that is not JSON and is * never compared across runtimes; this one emits JSON text for JSON-shaped input (an `undefined` member * omitted, an `undefined` / function / symbol array element as `null`, a scalar through `JSON.stringify`, * an object read by its own enumerable keys with no `toJSON` call). The two answer different questions * and their outputs are not interchangeable. */ export declare function canonicalJsonStringify(value: unknown): string;