The API Surface

Hale programs declare their external RPC and streaming interfaces as API surfaces (api blocks and @rpc annotations). From a surface declaration, the…

Hale programs declare their external RPC and streaming interfaces as API surfaces (api blocks and @rpc annotations). From a surface declaration, the compiler generates strict request/response codecs, computes cryptographic contract digests, serves self-describing endpoints over multiple transports (unix::Rpc, http::Rpc, http::Rest, mcp::Rpc, grpc::Rpc, ws::Hub), and produces typed clients and OpenAPI/Protobuf specifications.

role trader;
unit cent;
type Money = quantity Int in cent;
type OrderId = distinct Int;
type OrderRequest { symbol: String; qty: Int; limit: Money; }
type OrderResponse { order: OrderId; notional: Money; }
type CancelRequest { order: OrderId; }
type CancelResponse { order: OrderId; was_open: Bool; }
type OrderError { code: String; reason: String; }
api Public {
rpc Orders::place;
rpc Orders::cancel requires: [trader];
}
locus Orders {
params {
next: Int = 41;
open: Int = 0;
}
fn place(req: OrderRequest) -> OrderResponse fallible(OrderError) {
if req.qty > 10000 {
fail OrderError { code: "over_limit", reason: "qty is over 10000" };
}
let id = OrderId(self.next);
self.next = self.next + 1;
self.open = self.open + 1;
return OrderResponse { order: id, notional: req.limit * req.qty };
}
fn cancel(req: CancelRequest, ctx: std::api::Context) -> CancelResponse fallible(OrderError) {
let n = Int(req.order);
if n < 41 || n >= self.next {
fail OrderError { code: "unknown_order", reason: "no order " + to_string(n) };
}
return CancelResponse { order: req.order, was_open: true };
}
}
fn main() { }

For a step-by-step tutorial, see Build an API. For guidance on designing wire types and evolving schemas safely, see Designing API Messages.


Ecosystem Overview

Section titled “Ecosystem Overview”
Area Construct / Tool Purpose
Declaring Surfaces api <Name> { rpc Locus::fn; }
@rpc / @rpc(requires: [...])
Declares a table of callable operations, their required roles, and optional HTTP REST routes.
Serving Exposures api::serve(Surface, Transport, ...) Binds a surface to a listener (unix::Rpc, http::Rpc, http::Rest, mcp::Rpc, grpc::Rpc, ws::Hub, or std::api::test::Rpc).
Streaming Hubs ws::Hub, udp::Hub
bindings { Topic: self.hub ... }
Streams internal bus topics to external WebSocket or UDP subscribers with role checks and bounded queues.
Auth & Context role, std::api::Context,
BearerSource, RoleSource, StaticRoles
Authenticates callers (Unix kernel credentials or bearer tokens), checks role grants, and passes caller metadata to handlers.
CLI Inspection & Driving hale check --api, hale describe,
hale call, hale watch, hale admin, hale mcp
Inspects static inventories, queries live descriptions, calls endpoints, tails streams, serves a web admin UI, or bridges to MCP.
Spec & Client Codegen hale api export
hale api client --lang hale|ts|js
Exports OpenAPI, JSON Schema, MCP, and .proto specs, or generates zero-dependency Hale, TypeScript, and JavaScript clients.
Consuming External APIs hale api import, api::client,
VaultPrincipals, hale api drift
Imports external OpenAPI (JSON/YAML) or MCP specs into typed api::Client handles tracked by the client(Surface) effect class.

Surfaces

Section titled “Surfaces”

Declaring api Blocks and @rpc Methods

Section titled “Declaring api Blocks and @rpc Methods”

An api block names a surface and lists its operations as rpc rows. Each row references a locus method and optionally specifies role requirements (requires: [...]) or HTTP routes (at "METHOD /path").

Instead of writing a separate api block, you can annotate locus methods with @rpc to add them to the seed’s default surface (named after the seed):

locus Orders {
@rpc
fn place(req: OrderRequest) -> OrderResponse fallible(OrderError) { … }
@rpc(requires: [trader])
fn cancel(req: CancelRequest) -> CancelResponse fallible(OrderError) { … }
}

Both forms compile to the same internal surface representation. A single handler method can appear in multiple api surfaces (for example, to expose different role requirements or versioned surfaces over the same implementation).

Surface-Level Default Roles & Cross-Seed Roles

Section titled “Surface-Level Default Roles & Cross-Seed Roles”

When most rows in a surface share the same role requirement, declare requires: on the api header. Rows without an explicit requires: inherit the surface default; a row with requires: [] overrides the default to allow any authenticated caller:

api Admin requires: [operator] {
rpc Ledger::rebalance; // requires operator
rpc Orders::cancel; // requires operator
rpc Orders::status requires: []; // requires no role (any authenticated caller)
}

This produces the exact same surface table and contract digest as spelling requires: [operator] on each row.

Roles form a single program-wide vocabulary across seeds. A role declared in an imported library is referenced via its import alias (requires: [lib::reader], @rpc(requires: [lib::writer]), or role boss includes lib::writer;) and appears in descriptions and refusals under its base name (reader, writer).

Compile-Time Surface Validation

Section titled “Compile-Time Surface Validation”

hale check validates every api row at compile time and rejects:

rpc `Orders::plcae`: `Orders` declares no fn `plcae`; did you mean `place`?
rpc `Orders::cancel` requires `tradr`, which no `role` declares; did you mean `trader`?
rpc `Ledger::dump`: its response `Export` has a field `raw: Bytes`, which the JSON codec does not carry
rpc `Orders::flush` may violate (`violate stale`) and returns nothing: an rpc handler that may violate is `fallible(ClosureViolation)`, so its caller receives the server error instead of a result

Contract Digests (Surface and Member Digests)

Section titled “Contract Digests (Surface and Member Digests)”

The compiler hashes every surface into a 64-bit FNV-1a contract digest (fnv1a64:<hex>):

Because admission checks member digests, adding a new rpc row to a surface changes the surface digest without invalidating clients compiled against existing members. Modifying an existing member’s request/response types, error classes, route, or roles changes its member digest, causing outdated clients to be rejected with digest_mismatch.

Documenting a Surface (/// Doc Comments)

Section titled “Documenting a Surface (/// Doc Comments)”

A /// comment directly above a declaration is its doc comment, and every document generated from a surface carries it: the description, the OpenAPI, JSON Schema, MCP and .proto forms, and the TypeScript, JavaScript and Hale clients. Document the surface, its rows, the handlers and the types they name:

role clerk;
/// A request to place an order.
type PlaceOrder {
/// The instrument's ticker symbol.
symbol: String;
/// How many units to buy.
qty: Int;
}
/// Why an order was not placed.
type OrderError = enum {
/// No instrument has the symbol.
@not_found UnknownSymbol,
Rejected(String),
};
type Receipt { order: Int; }
locus Desk {
/// Place an order (the handler's doc; a row's own doc replaces it).
fn place(
/// The order to place.
o: PlaceOrder
) -> Receipt fallible(OrderError) {
return Receipt { order: o.qty };
}
}
/// The order desk's public surface.
api Orders {
/// Place an order.
/// It is filled at the limit or better.
rpc Desk::place requires: [clerk];
}

A /// comment that documents nothing (above a statement, a lifecycle hook or an import, at the end of a file, or after code on its own line) is a warning, not an error. Write // for a comment that is not a doc. hale fmt keeps every doc comment where it is.

Inspecting the Static API Inventory (hale check --api)

Section titled “Inspecting the Static API Inventory (hale check --api)”

Pass --api to hale check to emit the program’s complete API inventory as JSON (all surfaces, digests, exposures, and JSON Schemas) without running the program:

$ hale check --api desk.hl
{
"inventory": 1,
"app": "Desk",
"surfaces": [
{
"name": "Public",
"digest": "fnv1a64:a8930d6e7998e986",
"members": [ … ]
}
],
…
}

You can also simulate the filtered description a specific caller will receive on a named exposure, or export specification formats for a surface:

Terminal window
# Preview exposure description filtered by caller roles
hale check --api desk.hl --exposure public --caller bob
hale check --api desk.hl --exposure public --caller alice --holds trader
# Export surface specifications to stdout
hale check --api desk.hl --surface Public --openapi
hale check --api desk.hl --surface Public --json-schema
hale check --api desk.hl --surface Public --mcp
hale check --api desk.hl --surface Public --proto

Request/Response Codec & Wire Shapes

Section titled “Request/Response Codec & Wire Shapes”

Every type reachable from an rpc row is encoded and decoded strictly. Unknown fields in incoming JSON objects are ignored, while wrong field types, out-of-bounds lists, and missing required fields are rejected with malformed before the handler is invoked.

Hale Type / Pattern JSON Wire Format Protobuf (.proto) Format Refusal Conditions (malformed)
Int, Float, Bool, String Standard JSON primitives optional int64, double, bool, string wrong_type, missing_field (if no default)
Decimal<S> JSON number at scale S, every digit kept (12.34; schema {"type": "number", "x-hale-type": "Decimal<2>"}); a string holding a number ("12.34") reads the same; tagged `json:"price,string"` it is written as that string (schema "type": "string") optional string (its digits; // Hale: Decimal<2>) A nonzero digit past S, or a string holding no JSON number (wrong_type), never a truncation
I32, U32, I16, U16, I8, U8 A JSON number, its range held on read (schema {"type": "integer", "x-hale-type": "U8"}) optional int32 (a signed one) or optional uint32 (an unsigned one), range-checked on decode Past the type’s range, a fraction, or other text (wrong_type)
U64 Always a JSON string of its decimal digits ("18446744073709551615"), or 0x hex tagged `json:",hex"`; reads either, or an integer number that fits (schema {"type": "string", "x-hale-type": "U64"}) optional uint64 (// Hale: U64) A sign, a fraction, an exponent, past 2^64 - 1, or other text (wrong_type)
U256, I256 JSON string of its decimal digits ("1000000000000000000"), or 0x hex tagged `json:",hex"`; reads either, or an integer number that fits (schema {"type": "string", "x-hale-type": "U256"}) optional string (its digits; // Hale: U256) A fraction, an exponent, a value out of range, or other text (wrong_type)
Int tagged `json:",hex"` 0x hex in a JSON string ("0x4dc"), a negative value as its number; reads hex text or a number (schema {"type": "string", "x-hale-type": "Int"}) optional int64 No 0x, no digits, a sign, a space, past Int’s range (wrong_type)
distinct T / quantity Int in u Underlying scalar value (Int count for quantities) Underlying scalar (// Hale: Type, q(u)) wrong_type
Time UTC RFC 3339 string ending in Z ("2026-10-12T03:04:05.123456789Z") optional int64 (nanoseconds) Non-UTC offset, missing Z, or past year 2262 (wrong_type)
Duration Integer nanoseconds (1500000000 = 1.5s) optional int64 (nanoseconds) wrong_type
bounded[T; N] JSON array of 0..=N elements (optional on input; defaults to []) repeated T Length > N (too_long)
[T; N] Fixed JSON array of exactly N elements repeated T Length > N (too_long), length < N (too_short)
bounded[T; N] indexed_by k JSON object keyed by T.k ({"db": {"status": "up"}}) map<string, T> Length > N (too_long), repeated key (duplicate_key), a map that is no object or a member that is no record, such as an array (wrong_type)
bounded[T; N] indexed_by k -> v JSON object mapping T.k to T.v ({"db": "ok"}) map<string, V> Length > N (too_long), repeated key (duplicate_key)
std::json::Value Arbitrary well-formed JSON (<= 64 levels deep, <= 64 KiB) optional string Invalid JSON, depth > 64, or size > 64 KiB
Any field with a default null is the key omitted: the declared default, whatever its shape (a literal, an enum variant, a nested record’s declared default); a field with no default is missing_field Declared as-is A std::json::Value field alone holds null as its text
Optional field (x?: T, or x + has_x: Bool) Optional field; omitted or null sets has_x = false Both fields declared as-is wrong_type if non-null value fails to decode
Clear triple (x?: T clearable, or x + has_x + clear_x) Omitted -> neither; null -> clear_x = true; value -> has_x = true All three fields declared as-is wrong_type if non-null value fails to decode
enum { A, B(T), C(T, U) } "A", {"B": val}, {"C": [v1, v2]} enum (unit-only) or message with oneof Unknown variant, wrong payload shape/arity (wrong_type), missing_field
Type set (type U = A | B;) Tagged object by type name ({"B": {...}}) message with oneof Unknown variant or wrong inner shape (wrong_type)

Lists and Pagination

Section titled “Lists and Pagination”

Lists must be fields of a record and have a static bound (bounded[T; N] or fixed [T; N]). Unbounded [T] slices, nested lists, and top-level bare list requests/responses are rejected at compile time.

type Item { id: Int; title: String; }
type Page { items: bounded[Item; 50]; more: Bool; }
locus Shelf {
params { items: bounded[Item; 500]; }
fn list(q: ListQuery) -> Page {
let mut page = Page { more: false };
for item in self.items {
push(page.items, item) or { page.more = true; break; };
}
return page;
}
}

Keyed Maps (indexed_by)

Section titled “Keyed Maps (indexed_by)”

A bounded[T; N] list of structs containing a String key field can be serialized on the wire as a JSON object using indexed_by <key_field>:

type Check { name: String; status: String; }
type Health { checks: bounded[Check; 16] indexed_by name; }

On the wire, checks is encoded as {"db": {"status": "up"}, "cache": {"status": "down"}}—each element’s name field becomes its property key and is omitted from the inner object, then restored in order when decoded.

When the element struct has only two fields (the String key and a scalar, Time, or unit-enum value), use indexed_by <key> -> <value> to serialize the values directly without a wrapper object:

type Check { name: String; status: String; }
type Health { checks: bounded[Check; 16] indexed_by name -> status; }
// Wire format: {"db": "ok", "nats": "unavailable"}

In both Hale and generated TypeScript clients, an indexed_by field remains a list of Check records (Check[] in TypeScript), with the client converting to and from the wire map automatically.

Free-Form JSON (std::json::Value)

Section titled “Free-Form JSON (std::json::Value)”

Use std::json::Value for opaque JSON subtrees that your program passes through or inspects dynamically:

type Seat { name: String; config: std::json::Value; }

std::json::Value preserves the exact bytes sent by the caller (including key ordering, whitespace, and trailing decimal zeros like 2.50). It must be valid JSON at most 64 levels deep and 64 KiB long. Inside Hale, read .text using std::json cursor functions (std::json::find_field_raw(seat.config.text, "theme")), and construct new values using std::json::Value::parse(text) or ... or std::json::Value::null() (direct struct literals and mutating .text are rejected by the compiler).

Optional Fields (x?: T and clearable)

Section titled “Optional Fields (x?: T and clearable)”

Hale has no Option<T> wrapper type: optionality is a property of a record field. An optional wire field is a field with a companion boolean flag, which x?: T declares for you:

  1. Default Value (limit: Int = 50;): Use when omitting a field has the same meaning as passing a default value.
  2. Optional Field (text?: String;): Use when you must distinguish an omitted/null field from a default value (or distinguish an empty list [] from an omitted list). It declares text and a real flag has_text: Bool after it, the presence pair. When text is omitted or null, has_text is false. On output, text is only written when has_text is true, and has_text itself never appears on the wire. Writing text in the program sets has_text.
  3. PATCH Clear Field (note?: String clearable;): Use for PATCH endpoints that distinguish “leave unchanged” (omitted -> both flags false), “clear to null” ("note": null -> clear_note = true, encoded as null on output), and “set to value” ("note": "hi" -> has_note = true). It declares the presence triple note, has_note, clear_note. Marked "x-hale-null": "clear" in the schema and typed note?: string | null in TypeScript.

The flags can also be spelled by hand (text: String = ""; has_text: Bool = false;), as earlier programs do: the description, the .proto and the contract digest are byte for byte the same either way, so converting a hand-written pair to x? changes no shape hash. Only the mark makes a write of the field set its flag.

Enums and Type Sets

Section titled “Enums and Type Sets”

Enums serialize as a string for unit variants ("Open"), a single-key object for single-value variants ({"Renamed": "Q3 plan"}), and a single-key object holding an array for multi-value variants ({"Moved": [3, 7]}):

type Status = enum { Open, Closed };
type Change = enum { Renamed(String), Moved(Int, Int), Archived };

Type sets (type Inbound = NewOrder | Cancel;) serialize as enums keyed by each member’s type name ({"Cancel": {"id": 1}}).

Wire names and the catch-all

Section titled “Wire names and the catch-all”

A wire you do not own often spells its values in lowercase, with dashes, or adds values over time. Tag a variant with json: to give it a wire name, and mark one variant other to catch the strings no variant names:

type Side = enum { Buy `json:"buy"`, Sell `json:"sell"` };
type Event = enum { Fill(Int) `json:"fill"`, Cancel `json:"cancel"` };
type Venue = enum { Spot `json:"spot"`, Margin `json:"margin"`, Other(String) `json:",other"` };
type Kind = enum { Limit `json:"limit"`, Market `json:"market"`, Unknown `json:"unknown,other"` };

The description lists the wire names ("enum": ["spot", "margin"]) and adds x-hale-variants (each variant’s wire name) and x-hale-other (the catch-all). The tags are part of the contract digest. The TypeScript client types Venue as "spot" | "margin" | (string & {}), and the Hale client declares the same tags. Protobuf ignores the renames and keeps Venue_Spot-style identifiers; a lossy catch-all also takes an enum number no variant has. A lossless catch-all makes the enum one with payloads, so the codecs cannot yet carry a list of it, and it cannot be a map value or a route parameter. The bus carries such an enum as any other, by its variant’s tag and values, so the renames do not reach it.

Error Classes

Section titled “Error Classes”

When a handler’s error type in fallible(E) is an enum, its variants can carry an error class annotation to select the transport status code:

type OrderError = enum { @not_found Missing, @conflict Taken(String), Closed };
Error Class Annotation HTTP Status Code gRPC Status Code Hale-Error-Class Header
(unannotated) 422 Unprocessable Content FAILED_PRECONDITION (omitted)
@not_found 404 Not Found NOT_FOUND not_found
@conflict 409 Conflict ABORTED conflict
@invalid 422 Unprocessable Content INVALID_ARGUMENT invalid
@forbidden 403 Forbidden PERMISSION_DENIED forbidden
@unavailable 503 Service Unavailable UNAVAILABLE unavailable

Because HTTP status codes 403, 409, and 503 can also be returned by transport-level refusals, classified handler errors include the Hale-Error-Class HTTP header (and "class" field on Unix sockets). Error classes are recorded in the schema (x-hale-error-classes), passed to custom std::api::Rpc transports via std::api::Outcome::HandlerError(body, class), and folded into the contract digest.

Direct Codec Invocation (T::api_decode and T::api_encode)

Section titled “Direct Codec Invocation (T::api_decode and T::api_encode)”

You can call the compiler-generated wire codec directly on any API-eligible record or enum T, even outside api::serve:

let order = PlaceOrder::api_decode(body) or {
return std::http::Response { status: 400, body: err.kind + ": " + err.field };
};
let reply = PlaceReply::api_encode(desk.place(order));

T::api_decode applies the exact same validation rules as a served exposure (wrong_type, missing_field, too_long, too_short, duplicate_key), reporting the offending field name in err.field (or "payload" when decoding a top-level enum).

Positional Records (@positional)

Section titled “Positional Records (@positional)”

Another program’s API may send a table’s rows as arrays rather than objects: candles as [[1688666400, 2990.0, 3010.0, 2995.0, 3005.0, 100.5], ...], book levels as [["3000.40", "0.5", 1], ...]. A record marked @positional crosses JSON as an array of its fields in declaration order:

@positional type Level { px: Decimal<2>; qty: Decimal<4>; orders: Int = 1; }
type Depth { bids: bounded[Level; 50]; asks: bounded[Level; 50]; }
let depth = Depth::api_decode(body) or raise;
let text = Depth::api_encode(depth); // {"bids":[[3000.4,0.5,1],...],"asks":[...]}

Element i is read as field i would be, as strictly, so a Decimal from a string sits beside an Int from a number. Elements past the last field are skipped (a row that gains a column keeps decoding). A row that ends before a field leaves it absent: its default, an empty bounded list, or missing_field naming Level.qty; every error inside a row names its field <Type>.<field>, since a row has no keys. All fields are elements (a has_x flag is a plain Bool element), and the encoder writes them all in order. Protobuf carries the record as any other.

A positional record is the shape of a wire someone else defined, so a served surface does not carry one: a row whose request, response or error reaches it is refused by the check, because the description, the generated clients and MCP tools name a record’s fields as keys. Serve a keyed record and convert at the edge.


Serving Exposures (api::serve)

Section titled “Serving Exposures (api::serve)”

An exposure (api::Exposure) binds an api surface to a transport listener inside a locus’s params block:

params {
orders: Orders = Orders { };
fixture: std::api::test::Rpc = std::api::test::Rpc { };
public: api::Exposure = api::serve(Public, self.fixture, as: "public", receivers: { Orders: self.orders }, bound: 64, on_full: refuse);
}

Lifecycle, Receivers, and Execution Order

Section titled “Lifecycle, Receivers, and Execution Order”

Listener Placement and Child Server Loci

Section titled “Listener Placement and Child Server Loci”

Socket transport listeners (unix::Rpc, http::Rpc, http::Rest, mcp::Rpc, grpc::Rpc) run their accept and connection loops on an async_io coroutine pool:

locus AdminServer {
params {
cfg: LiveConfig = LiveConfig { };
tokens: Tokens = Tokens { };
api: api::Exposure = api::serve(AdminApi, http::Rpc { bind: "127.0.0.1:8080", codec: json, principals: self.tokens }, as: "web", receivers: { LiveConfig: self.cfg }, bound: 64, on_full: refuse);
}
}
main locus App {
params { admin: AdminServer = AdminServer { }; }
placement { admin: cooperative(pool = io) where async_io; }
}

When admin is placed on an async_io pool, the server locus, its receivers, and its transport listener all run on io. A server locus holding an exposure may only be instantiated once (instantiating it twice or with replicas is rejected).


RPC Transports

Section titled “RPC Transports”

1. Unix Domain Sockets (unix::Rpc)

Section titled “1. Unix Domain Sockets (unix::Rpc)”

unix::Rpc serves newline-delimited JSON over a local Unix stream socket and authenticates callers using kernel peer credentials (uid, gid, pid).

main locus Desk {
params {
admin_roles: Grants = Grants { operator: "uid:1000" };
orders: Orders = Orders { };
ledger: Ledger = Ledger { };
admin: api::Exposure = api::serve(Admin, unix::Rpc { path: "/run/desk/admin.sock", roles: self.admin_roles }, as: "admin", bound: 16, on_full: refuse);
}
run() {
self.admin.wait();
self.admin.stop();
}
}
{"call": "Orders::cancel", "payload": {"order": 41}, "id": "c-1", "digest": "fnv1a64:40381db6685c9f75"}
{"request_id": 1, "id": "c-1", "ok": true, "value": {"order": 41, "was_open": true}, "caller": {"mode": "unix", "name": "uid:1000", "uid": 1000, "gid": 1000, "pid": 4242}}
{"describe": true}

Sending {"describe": true} returns the caller-filtered JSON description document.

2. HTTP RPC (http::Rpc)

Section titled “2. HTTP RPC (http::Rpc)”

http::Rpc serves JSON RPC calls over HTTP/1.1 using bearer token authentication:

locus Tokens {
fn principal(token: String) -> std::api::Principal {
if token == "t-alice" { return std::api::Principal { mode: "bearer", name: "alice" }; }
return std::api::Principal { mode: "bearer", name: "" };
}
fn refused() -> String { return "no such token"; }
}
main locus Desk {
params {
bearer: Tokens = Tokens { };
public_roles: Grants = Grants { trader: "alice" };
partner_roles: Grants = Grants { trader: "carol" };
orders: Orders = Orders { };
partner_orders: Orders = Orders { next: 9001 };
public: api::Exposure = api::serve(Public, http::Rpc { bind: "127.0.0.1:8080", codec: json, principals: self.bearer, roles: self.public_roles }, as: "public", receivers: { Orders: self.orders }, bound: 64, on_full: refuse);
partner: api::Exposure = api::serve(Public, http::Rpc { bind: "127.0.0.1:8081", codec: json, principals: self.bearer, roles: self.partner_roles }, as: "partner", receivers: { Orders: self.partner_orders }, bound: 64, on_full: refuse);
}
placement { public: cooperative(pool = io) where async_io; }
run() {
self.public.wait();
self.public.stop();
self.partner.stop();
}
}
POST /call/Orders::place HTTP/1.1
Authorization: Bearer t-alice
Content-Type: application/json
Hale-Surface-Digest: fnv1a64:a8930d6e7998e986
{"symbol": "ACME", "qty": 10, "limit": 12500}
HTTP/1.1 200 OK
Content-Type: application/json
{"order":41,"notional":125000}

3. HTTP REST Routing (http::Rest and fallback)

Section titled “3. HTTP REST Routing (http::Rest and fallback)”

When external callers or load balancers expect custom HTTP methods and URL paths (GET /healthz, GET /v1/items/{id}, DELETE /v1/items/{id}), annotate surface rows with at "<METHOD> <path>" and optional status: <code>, then serve the surface using http::Rest:

type Health { status: String; }
type ItemKey { id: Int; }
api Gateway {
rpc Probe::live at "GET /healthz";
rpc Items::get at "GET /v1/items/{id}";
rpc Items::remove at "DELETE /v1/items/{id}" status: 204;
rpc Items::create at "POST /v1/items" status: 201;
}
locus Svc {
params {
bearer: Tokens = Tokens { };
grants: Grants = Grants { };
web: api::Exposure = api::serve(Gateway, http::Rest { bind: "0.0.0.0:8080", codec: json, principals: self.bearer, roles: self.grants, anonymous: "public" }, as: "web", receivers: { Probe: self.probe, Items: self.items }, bound: 64, on_full: refuse);
}
}

Custom Non-RPC Endpoints (fallback:)

Section titled “Custom Non-RPC Endpoints (fallback:)”

To serve raw HTTP endpoints (such as Server-Sent Events, raw streaming proxies, or custom WebSocket upgrades) on the same port and origin as http::Rest, pass a locus implementing std::http::Handler (fn handle(req: std::http::Request) -> std::http::Response) as fallback::

locus DataPlane {
fn handle(req: std::http::Request) -> std::http::Response {
if req.path == "/v1/events" {
let w = std::http::SseWriter { conn_fd: req.conn_fd };
w.event(std::http::SseEvent { event: "ready", data: "{}" }) or discard;
return w.end();
}
return std::http::Response { status: 404, body: "no such path" };
}
}
main locus Svc {
params {
bearer: Tokens = Tokens { };
data_plane: DataPlane = DataPlane { };
web: api::Exposure = api::serve(Gateway, http::Rest { bind: "0.0.0.0:8080", codec: json, principals: self.bearer, fallback: self.data_plane }, as: "web", receivers: { Probe: self.probe, Items: self.items }, bound: 64, on_full: refuse);
}
placement {
web: cooperative(pool = edge) where async_io;
data_plane: cooperative(pool = edge) where async_io;
}
}

Rules for fallback:

  1. Unmatched paths only: Any path claimed by a surface route stays owned by http::Rest for all HTTP methods (e.g., POST /healthz on a GET /healthz route returns 405, never reaching fallback).
  2. Independent authentication: fallback bypasses the exposure’s principals, anonymous, roles, and cors checks; it receives the raw std::http::Request and performs its own header inspection.
  3. Same pool placement: fallback executes directly on the listener’s connection coroutines and must be placed on the exact same async_io pool as the exposure (edge above).
  4. Field reference only: When used inside a child server locus, fallback: must reference a param field (self.front) or self, never a method call (self.make()).
  5. Concurrent, like std::http::Server: the fallback is not a receiver, so the one-call-per-receiver rule does not apply. Each connection calls handle on a coroutine of its own and calls interleave wherever one parks (a sleep, a socket read, an outbound request, an event sent to a slow client): fifty one-second requests, or fifty Server-Sent Event streams, finish in about a second, while the rows keep their per-receiver order. Calls never run in parallel (one pool, one thread), but a value the handler read from its own params before a park can be stale after it, so keep per-request state in locals. The bound is the listener’s: 256 connections served at once and as many waiting, shared with the rows. The exposure’s bound: counts only calls queued for rows, so a stream that lasts minutes never takes one of its slots.

4. Model Context Protocol Server (mcp::Rpc)

Section titled “4. Model Context Protocol Server (mcp::Rpc)”

mcp::Rpc exposes a surface directly as an MCP server over HTTP (POST /mcp speaking JSON-RPC 2.0):

public: api::Exposure = api::serve(Public, mcp::Rpc { bind: "127.0.0.1:8090", principals: self.bearer, roles: self.public_roles }, as: "public", receivers: { Orders: self.orders }, bound: 64, on_full: refuse);
POST /mcp HTTP/1.1
Authorization: Bearer t-alice
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"Orders__place","arguments":{"symbol":"ACME","qty":10,"limit":12500}}}
{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"{\"order\":41,\"notional\":125000}"}],"structuredContent":{"order":41,"notional":125000},"isError":false}}

5. gRPC over HTTP/2 (grpc::Rpc)

Section titled “5. gRPC over HTTP/2 (grpc::Rpc)”

grpc::Rpc serves unary RPCs over cleartext HTTP/2 (powered by built-in nghttp2 on the async_io pool), accepting both Protobuf (application/grpc or application/grpc+proto) and JSON (application/grpc+json) framing on the same listener:

public: api::Exposure = api::serve(Public, grpc::Rpc { bind: "127.0.0.1:8070", codec: json, principals: self.bearer, roles: self.public_roles }, as: "public", receivers: { Orders: self.orders }, bound: 64, on_full: refuse);
:method POST :path /Public/Orders__place content-type application/grpc+json
authorization Bearer t-alice hale-surface-digest fnv1a64:a8930d6e7998e986
message {"symbol": "ACME", "qty": 10, "limit": 12500}
:status 200 content-type application/grpc+json
message {"order":41,"notional":125000}
trailers grpc-status 0
service Public {
// rpc Orders::place
// requires no role
// a violation is the server error (ClosureViolation): status 13, no handler error
rpc Orders__place(OrderRequest) returns (OrderResponse);
}
message OrderRequest {
optional string symbol = 1;
optional int64 qty = 2;
optional int64 limit = 3; // Hale: Money, q(cent)
}

Streaming Hubs (ws::Hub and udp::Hub)

Section titled “Streaming Hubs (ws::Hub and udp::Hub)”

To stream internal bus topics to external subscribers, declare a ws::Hub (WebSocket) or udp::Hub (UDP datagrams) in params and bind topics to it in a bindings { } block:

main locus Desk {
params {
bearer: Tokens = Tokens { };
hub_roles: Grants = Grants { operator: "dave" };
hub: ws::Hub = ws::Hub { bind: "127.0.0.1:9000", principals: self.bearer, roles: self.hub_roles, as: "fills" };
}
bindings {
Fills: self.hub requires: [operator], bound: 64, on_full: drop_old;
}
}

The hub is built wherever its literal is written in the main locus’s params, with or without a bindings { } row or a surface served over it (api::serve(Public, self.hub, …)): a hub with no stream row listens and carries the rpcs served over it. A ws::Hub literal in any other locus is refused, naming the main locus as its place.

Hub Protocol and Queue Semantics

Section titled “Hub Protocol and Queue Semantics”
{"type": "subscribe", "topic": "Fills"}
{"type": "subscribed", "topic": "Fills"}
{"type": "event", "topic": "Fills", "seq": 1, "payload": {"order": 1, "qty": 1, "price": 10}}
{"type": "refusal", "topic": "Fills", "refusal": {"kind": "unauthorized", "reason": "Fills requires operator", "requires": ["operator"]}}

Mounting a Hub on an http::Rest Listener (hubs:)

Section titled “Mounting a Hub on an http::Rest Listener (hubs:)”

A ws::Hub does not need a port of its own. Leave out its bind: and list it in the hubs: of an http::Rest exposure, at a path. The exposure may be the main locus’s own, or held by a locus below it (see below). The REST surface, the hub, and any fallback: then share one address and one origin:

main locus Desk {
params {
bearer: Tokens = Tokens { };
hub_roles: Grants = Grants { operator: "dave" };
hub: ws::Hub = ws::Hub { principals: self.bearer, roles: self.hub_roles, as: "fills" };
web: api::Exposure = api::serve(Gateway, http::Rest { bind: "0.0.0.0:8080", codec: json, principals: self.bearer, roles: self.hub_roles, hubs: [("/admin/v1/hub", self.hub)] }, as: "web", bound: 64, on_full: refuse);
}
bindings {
Fills: self.hub requires: [operator], bound: 64, on_full: drop_old;
}
placement {
web: cooperative(pool = edge) where async_io;
}
}

A hub mounted on an exposure held below the main locus

Section titled “A hub mounted on an exposure held below the main locus”

When the http::Rest exposure lives in a sub-locus, for example so that the exposure, its receivers and its store share one async_io pool, the hub still belongs to the main locus. The sub-locus declares a ws::Hub param with no default, and the main locus passes its hub down:

locus Front {
params {
hub: ws::Hub;
bearer: Tokens = Tokens { };
grants: Grants = Grants { operator: "dave" };
web: api::Exposure = api::serve(Gateway, http::Rest { bind: "0.0.0.0:8080", codec: json, principals: self.bearer, roles: self.grants, hubs: [("/admin/v1/hub", self.hub)] }, as: "web", bound: 64, on_full: refuse);
}
}
main locus Desk {
params {
bearer: Tokens = Tokens { };
hub_roles: Grants = Grants { operator: "dave" };
hub: ws::Hub = ws::Hub { principals: self.bearer, roles: self.hub_roles, as: "fills" };
front: Front = Front { hub: self.hub };
}
bindings {
Fills: self.hub requires: [operator], bound: 64, on_full: drop_old;
}
placement {
front: cooperative(pool = edge) where async_io;
}
}

Authentication, Authorization & Refusals

Section titled “Authentication, Authorization & Refusals”

Refusal Kinds

Section titled “Refusal Kinds”

A transport refusal rejects a request before the handler runs:

{"request_id": 4, "id": 4, "ok": false, "refusal": {"kind": "malformed", "reason": "wrong_type: qty"}}
Refusal Kind HTTP Status gRPC Status Cause
malformed 400 INVALID_ARGUMENT Invalid JSON/frame, unknown member, missing required field (missing_field), wrong field type (wrong_type), list bound violation (too_long / too_short), or duplicate map key (duplicate_key).
unauthenticated 401 UNAUTHENTICATED Missing or unrecognized credential (bearer source returned empty name, or kernel peer credentials unavailable).
unauthorized 403 PERMISSION_DENIED Authenticated caller does not hold a role listed in the row’s requires: (includes "requires": [...]).
digest_mismatch 409 FAILED_PRECONDITION Client’s digest matches neither the surface digest nor the member’s digest (includes "served": "<digest>").
full 429 RESOURCE_EXHAUSTED Exposure has reached its bound of in-flight requests under on_full: refuse.
unavailable 503 UNAVAILABLE Target receiver is draining, restarting, replaced, or stopped after a failure; the call did not run.
shutting_down 503 UNAVAILABLE Exposure is stopping (stop() called); queued request did not run.

Caller Context (std::api::Context)

Section titled “Caller Context (std::api::Context)”

Any RPC handler can inspect the caller and transport by declaring a second parameter of type std::api::Context (or std::api::ServedContext to also read the exposure name and receiver generation):

type RefundRequest { order_id: Int; amount: Int; }
type RefundResponse { ok: Bool; by: String; }
locus Billing {
fn refund(req: RefundRequest, ctx: std::api::Context) -> RefundResponse {
// ctx.caller is the authenticated Principal;
// ctx.via is "unix", "http", "ws", "mcp", or "local" for direct in-process calls.
return RefundResponse { ok: true, by: ctx.caller.name };
}
}
fn main() { }

std::api::Context provides:

Role Sources (std::api::RoleSource and StaticRoles)

Section titled “Role Sources (std::api::RoleSource and StaticRoles)”

Role requirements (requires: [refund_support]) are declared on surface rows, while role hierarchy (role owner includes refund_support;) is declared at top level:

role refund_support;
role auditor;
role owner includes refund_support;
api Billing {
rpc Billing::refund requires: [refund_support];
rpc Billing::ledger requires: [auditor];
}

Who holds a role at runtime is determined by the roles: locus passed to the transport, which must satisfy std::api::RoleSource (fn holds(p: std::api::Principal, r: String) -> Bool; the exposure walks includes automatically):

locus RecordRoles { // satisfies std::api::RoleSource
params { root: String = "."; }
fn holds(p: std::api::Principal, r: String) -> Bool {
return r == "owner" && p.name == "uid:1000";
}
}
main locus Head {
params {
roles: RecordRoles = RecordRoles { };
local: api::Exposure = api::serve(Billing, unix::Rpc { path: "/run/head.sock", roles: self.roles }, as: "head", bound: 64, on_full: refuse);
}
run() {
self.local.wait();
self.local.stop();
}
}
fn main() { Head { }; }

For static or environment-driven deployments, use std::api::StaticRoles, which reads a semicolon-separated grant table (role=member,member;...) from its table parameter or the LOTUS_API_ROLES environment variable:

StaticRoles Member Pattern Matches
uid:<n> Unix socket peer with user ID <n>.
gid:<n> Unix socket peer with primary or supplementary group ID <n>.
user:<name> Unix socket peer with account <name> (resolved once at startup).
group:<name> Unix socket peer in group <name> (resolved once at startup).
bearer:<name> HTTP, MCP, or Hub caller whose BearerSource returned principal <name>.
* Any authenticated caller on any transport.

Unix account patterns (uid:, gid:, user:, group:) never match bearer callers, and bearer: patterns never match Unix socket peers.


CLI Driving & Client Code Generation

Section titled “CLI Driving & Client Code Generation”

Driving Live Exposures from the Terminal

Section titled “Driving Live Exposures from the Terminal”

Five built-in CLI commands interact with any live exposure by reading its self-description ({"describe": true} on Unix sockets, GET /.description on HTTP and WebSocket hubs):

Terminal window
# 1. Inspect caller-visible description
hale describe /run/desk/admin.sock
hale describe http://127.0.0.1:8080 --bearer t-alice
# 2. Invoke RPC members (flags per field, or raw JSON)
hale call /run/desk/admin.sock Orders::cancel '{"order": 41}'
hale call http://127.0.0.1:8080 Orders::place --symbol ACME --qty 10 --limit 12500 --bearer t-alice
echo '{"book": "desk"}' | hale api call unix:/run/desk/admin.sock Ledger::rebalance --json -
# 3. Call HTTP REST routes directly
hale api call http://127.0.0.1:8080 'GET /v1/items/42'
# 4. Subscribe to WebSocket hub streams
hale watch ws://127.0.0.1:9000 Fills --token t-dave
# 5. Launch loopback web dashboard or MCP stdio bridge
hale admin /run/desk/admin.sock
claude mcp add desk -- hale mcp --app http://127.0.0.1:8080 --token t-alice

Exporting Specification Bundles (hale api export)

Section titled “Exporting Specification Bundles (hale api export)”

hale api export writes all specification artifacts for a surface to a directory deterministically:

Terminal window
hale api export --surface Public --out api/public desk.hl
hale api export --surface Public --check api/public desk.hl # exits 1 on drift in CI

Generated files in api/public/:

Generating Typed Clients (hale api client)

Section titled “Generating Typed Clients (hale api client)”

Generate standalone, zero-dependency client modules for Hale, TypeScript, or JavaScript (ES module with JSDoc types):

Terminal window
hale api client --surface Public --lang hale --out client/desk.hl desk.hl
hale api client --surface Public --lang ts --out client/desk.ts desk.hl
hale api client --surface Public --lang ts --check client/desk.ts desk.hl # exits 1 on drift
hale api client --surface Public --lang js --out web/desk.js desk.hl
Target Supported Transports RPC Return Shape Stream Shape
Hale (--lang hale) unix:PATH, http://, ws:// <Member>Outcome enum: Result(T), HandlerError(E), Refusal(R), ServerError, Lost(String) Subscription locus (start(), next() -> Event(seq, payload) | Expired | Revoked | Closed)
TypeScript (--lang ts)
JavaScript (--lang js)
http://, ws:// Tagged union: result, handler_error, refusal, server_error (throws TransportError if connection drops mid-call) Async iterable (for await (const ev of ...))

Every generated client embeds the per-member digest on each call and exposes the surface digest as a constant.


Consuming External APIs

Section titled “Consuming External APIs”

Importing OpenAPI and MCP Specifications (hale api import)

Section titled “Importing OpenAPI and MCP Specifications (hale api import)”

Use hale api import to generate a typed Hale api declaration from an external OpenAPI 3.x document (JSON or YAML, local file or URL) or a live MCP server:

Terminal window
hale api import https://shelf.example/openapi.json --as Shelf --out shelf.hl
hale api import ./vendor/shelf.json --as Shelf
hale api import ./vendor/shelf.yaml --as Shelf
hale api import http://127.0.0.1:8931/mcp --as Tools

This generates a source file declaring the external surface and its wire types:

// Generated by `hale api import` from openapi ../shelf.json (OpenAPI 3.0.3: Shelf 1.0.0).
api Shelf from openapi "../shelf.json" {
rpc create_item(ShelfNewItem) -> ShelfItem wire: "POST /items";
rpc get_item(ShelfGetItemRequest) -> ShelfItem wire: "GET /items/{itemId}";
// response: std::json::Value, an array with no `maxItems`, and a record holds a bounded list only
rpc list_items() -> std::json::Value wire: "GET /items";
}
type ShelfGetItemRequest {
item_id: Int `json:"itemId"`;
}
type ShelfItem {
id: Int;
name: String;
state?: ShelfItemState;
}
type ShelfItemState = enum { open, held, gone };
type ShelfNewItem {
name: String;
}

Calling External Surfaces (api::client and VaultPrincipals)

Section titled “Calling External Surfaces (api::client and VaultPrincipals)”

Bind an imported api surface (or a Hale api surface served by another process) to an api::Client param using http::Client or mcp::Client:

locus Desk {
params {
creds: std::api::VaultPrincipals = std::api::VaultPrincipals { slots: "editor=shelf-editor, *=shelf-reader" };
shelf: api::Client = api::client(Shelf, http::Client { base: "https://shelf.example", principals: self.creds });
}
fn label(id: Int) -> String {
return match self.shelf.get_item(ShelfGetItemRequest { item_id: id }) {
ShelfGetItemOutcome::Result(item) -> item.name,
ShelfGetItemOutcome::HandlerError(f) -> "failed: " + f.class,
ShelfGetItemOutcome::Refusal(r) -> "refused: " + r.kind,
ShelfGetItemOutcome::ServerError -> "server error",
ShelfGetItemOutcome::Lost(why) -> "lost: " + why,
};
}
}
claims {
desks_stay_local: forbid reaches(desks, effects(client(Shelf)));
// Use `effects(client(*))` to forbid calls to any consumed API surface.
}

Detecting Upstream API Drift (hale api drift)

Section titled “Detecting Upstream API Drift (hale api drift)”

Run hale api drift in CI or a watcher to compare the upstream OpenAPI/MCP specification against your committed api rows by structural shape:

Terminal window
$ hale api drift .
drift Shelf added archive_item
drift Shelf removed create_item
drift Shelf changed get_item response
$ echo $?
1

Current Limitations

Section titled “Current Limitations”

Next: API Wire Schemas & Compatibility.