Skip to content

Go SDK ​

sh
go get github.com/kernable/kernable/sdks/go

Go 1.26 or newer; no protoc (the generated protocol code is part of the module). A kernel to connect to: kernable start --dev (see Getting started).

A cart aggregate, a read model that answers a query, and a client that submits and reads back, in one process:

go
package main

import (
	"context"
	"fmt"
	"log"
	"sync"

	kernable "github.com/kernable/kernable/sdks/go"
)

type Cart struct {
	Items int `json:"items"`
}

type Item struct {
	Qty int `json:"qty"`
}

func main() {
	ctx := context.Background()
	shopDomain := kernable.NewDomain("shop")

	cart := kernable.NewAggregate(shopDomain, "cart", Cart{})
	kernable.Apply(cart, "ItemAdded", func(_ *kernable.ApplyContext, s *Cart, d Item) { s.Items += d.Qty })
	kernable.Handle(cart, "AddItem", func(_ *kernable.CommandContext, _ Cart, d Item) ([]kernable.NewEvent, error) {
		if d.Qty == 0 {
			return nil, kernable.Reject("", "qty must be at least 1")
		}
		return kernable.Events(kernable.Event("ItemAdded", d)), nil
	})

	// A listener handles one event at a time; its queries may run while another listener's
	// events are handled, so share state across listeners with a lock.
	var mu sync.Mutex
	rows := map[string]int{}
	carts := shopDomain.ReadModel("carts")
	kernable.On(carts, "ItemAdded", func(ctx *kernable.ListenerContext, d Item) error {
		mu.Lock()
		defer mu.Unlock()
		rows[ctx.Event.AggregateID] += d.Qty
		return nil
	})
	kernable.Answer(carts, "GetCart", func(_ *kernable.QueryContext, q struct{ ID string }) (Cart, error) {
		mu.Lock()
		defer mu.Unlock()
		return Cart{Items: rows[q.ID]}, nil
	})

	client, err := kernable.New(kernable.Options{Key: "app.key"})
	if err != nil {
		log.Fatal(err)
	}
	app, err := client.App(kernable.AppOptions{Service: "shop", Domains: []*kernable.Domain{shopDomain}})
	if err != nil {
		log.Fatal(err)
	}
	go func() { log.Fatal(app.Run(ctx)) }()
	<-app.Ready()

	if _, err := client.Submit(ctx, kernable.Command{Domain: "shop", AggregateType: "cart", AggregateID: "c1", Type: "AddItem", Data: Item{Qty: 2}}); err != nil {
		log.Fatal(err)
	}
	answer, err := client.Query(ctx, kernable.Query{Domain: "shop", Type: "GetCart", Data: map[string]string{"id": "c1"}})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(answer)) // {"items":2}
}

How the SDK works:

  • Context first. Every call that can block takes a context.Context first and ends when it is done. Handlers get a kernable context first (*CommandContext, *ListenerContext, *QueryContext, *MiddlewareContext), each a context.Context. Run of a worker, a listener or an app returns once its context ends: run it in a goroutine and wait for Ready().
  • Generics for typed payloads. Methods cannot have type parameters in Go, so typed handlers are registered with functions: Apply, Handle, On and Answer decode the data into the type of the handler's parameter (any type encoding/json reads, map[string]any or json.RawMessage). State, events and answers are encoded with encoding/json.
  • Definitions panic, calls return errors. Defining a domain, an aggregate or a listener panics on a programming error (a malformed name, a type defined twice), as regexp.MustCompile does. Calls to the kernel return an error.
  • Errors. Handlers return *Rejected (Reject(code, message)) to refuse; any other error rejects with handler_error. A rejected command is not an error: Submit returns it in its Outcome. A rejected query returns a *Rejected; *NotSettled and *NotDue are errors to check with errors.As. What the kernel refuses itself comes as a gRPC status (Errors).
  • Keepalive. gRPC for Go pings at most every 10 s: with two kernels (a pair), a kernel the network cut off is left within about 12 s, not within 4 s as with the other SDKs.

The rest of this page is generated from the doc comments in sdks/go.

Aggregate ​

Aggregate is how events change a state (Apply) and which events a command produces (Handle). Handlers must be deterministic and free of side effects; they may run again. The state must survive a JSON round trip, because snapshots store it as JSON. An aggregate belongs to a domain and produces events only of that domain.

A worker folds the aggregate's events (from the latest snapshot, if any) into the state, calls the command's handler, and sends the events it returns. The kernel commits them only on the version the state was folded from; if another command came first, the command runs again on the new state.

  • Domain *Domain: The domain it belongs to.

  • Name string: The aggregate type, unqualified: cart.

  • Initial S: The state every aggregate of this type starts from.

  • func NewAggregate[S any](d *Domain, name string, initial S, options ...AggregateOption) *Aggregate[S]: NewAggregate defines an aggregate type name (cart) of domain d, with the state initial every aggregate of it starts from. Add its event appliers and command handlers with Apply and Handle; run it with Client.Worker or Client.App. Panics if the domain has an aggregate of that name already.

  • func (a *Aggregate[S]) Fact(name string, fn func(S) bool) *Aggregate[S]: Fact declares a fact name this aggregate holds while fn(state) is true: what other aggregates' commands require (Requires). fn must be deterministic, as Apply must.

  • func (a *Aggregate[S]) Fold(history []FoldEvent) (S, error): Fold is the state after history, starting from Initial, as a worker computes it; no kernel needed, so it suits tests. Events are upcast first; events without an Apply are skipped.

  • func (a *Aggregate[S]) Handle(ctx *CommandContext, state S, commandType string, data any) ([]NewEvent, error): Handle runs the commandType handler on a copy of state, as a worker does, e.g. in a unit test, and returns the events it produces. data goes through JSON as it would on the wire.

  • func (a *Aggregate[S]) Index(state S) Index: Index is the unique keys and facts this aggregate holds in state, as a worker computes them after a command; no kernel needed, so it suits tests.

  • func (a *Aggregate[S]) Requirements(state S, commandType string, data any) ([]Requirement, error): Requirements is what a commandType command with data requires of other aggregates in state (Requires), as a worker computes it; no kernel needed, so it suits tests. None without Requires.

  • func (a *Aggregate[S]) SchemaOf(eventType string) uint32: SchemaOf is the payload version this aggregate writes eventType events at.

  • func (a *Aggregate[S]) Unique(name string, values func(S) []string, options ...UniqueOption[S]) *Aggregate[S]: Unique declares a unique key name: values(state) returns the values this aggregate holds (nil for none), and no other aggregate of this type holds the same value within the tenant (or in any tenant, Global). After every command the aggregate holds exactly the values its new state yields. A command that would leave the aggregate with a value another one holds is rejected with unique_taken. Normalise the value yourself; the kernel gets only its SHA-256.

AggregateOption ​

AggregateOption sets a snapshot option of NewAggregate.

  • func SnapshotEvery(n int) AggregateOption: SnapshotEvery sends a snapshot of the state every n events (default 100; 0 turns them off).
  • func StateSchema(schema string) AggregateOption: StateSchema is the version of the state format (default "1"). Change it when Apply produces differently shaped state; older snapshots are then ignored and the state is rebuilt.

AnyAggregate ​

AnyAggregate is any *Aggregate[S].

App ​

App is a service made of whole domains, ready to run: one worker for all their aggregates, one ListenerHandle per read model and reactor, and their business processes, registered once the worker and listeners are connected. Create it with Client.App, start it with Run.

  • func (a *App) MCP() *MCPServer: MCP is the app's MCP server, nil unless its MCP is on (AppOptions.MCP, KERNABLE_MCP).
  • func (a *App) Manifest() Manifest: Manifest is the membership Run applies.
  • func (a *App) Ready() <-chan struct{}: Ready is closed once every worker and listener of the app is connected, its deployment serves the service and its processes are registered (or registering failed: see Run's error).
  • func (a *App) Registered() []ProcessVersion: Registered is the app's processes as the kernel registered them, once Ready.
  • func (a *App) Run(ctx context.Context, options ...WorkerOptions) error: Run applies the membership (the key needs manage for the service), then runs the worker and the listeners until ctx ends, reconnecting when a connection drops. If another deployment serves the service, the kernel switches to this one only as AppOptions.Switch says: until then the app runs beside it and applies its membership again every second. Once all are connected and it serves, it registers the domains' processes and prints an overview of the app on stderr. It returns an error if the kernel refuses the membership for another reason than the switch, or if a process cannot be registered (it stops the app then, so the deploy fails); nil once ctx ends.
  • func (a *App) Serving() <-chan struct{}: Serving is closed once the app's membership is applied: its deployment serves the service.

AppOptions ​

AppOptions describe an app: one service made of whole domains, for Client.App. Version, Description and Metadata go into the membership's metadata and the app's overview.

  • Service string: The service's name. Default: this process's service (Options.Service); one is required.
  • Version string: The app's version, e.g. 1.0.0.
  • Description string: One line about the app.
  • Metadata map[string]string: More metadata.
  • Domains []*Domain: Every aggregate, read model and reactor defined on them runs in this app; their processes are registered.
  • Switch Switch: When the app's deployment takes the service over from another one that serves it. Default: KERNABLE_SWITCH, else CaughtUp.
  • MCP *MCPOptions: Offers the commands and queries declared with a tool to AI agents over MCP (see MCPOptions): off unless Enabled or KERNABLE_MCP switches it on. Run serves it alongside the worker and listeners.

ApplyContext ​

ApplyContext is what an Apply function gets first: the event's meta and the request context of the command that caused it. Nothing that differs between runs (no clock, no IDs), so a replay computes the same state.

  • EventMeta (embedded)
  • Request RequestContext: The request context of the command that caused the event.

ApprovalOptions ​

ApprovalOptions say who decides a held tool call (Approve, Decline) and where.

  • Note string: A note for the record and the model.
  • Context *RequestContext: The person who decides (SenderIdentity); your middleware decides who may.
  • Domain string: The approvals' domain; default mcp.
  • Tenant string: The approval's tenant; default the client's.

ApprovalRow ​

ApprovalRow is an approval as GetApproval answers it (and mcp_approval tells the model).

  • ID string
  • State string
  • Tool string
  • Reason string
  • RequestedBy *string
  • RequestedAt string
  • DecidedBy *string
  • Note *string
  • Result map[string]any

Cache ​

Cache is the shared cache of a domain: values of at most 1 MiB under (tenant, domain, key) that may expire. Needs a grant of cache for the domain. The cache lives in the kernel's memory: a restart empties it. Each request passes the middleware chain first, as <domain>.SetCache, .GetCache or .DeleteCache.

  • func (k *Cache) Delete(ctx context.Context, domain, key string, options ...DataOptions) (bool, error): Delete deletes the value under key and returns whether there was a live one.
  • func (k *Cache) Get(ctx context.Context, domain, key string, options ...DataOptions) ([]byte, error): Get returns the live value under key, or nil if there is none or it expired.
  • func (k *Cache) Set(ctx context.Context, domain, key string, value []byte, options ...DataOptions) error: Set stores value under key, replacing a value there.

CancelOnOptions ​

CancelOnOptions are the options of ProcessBuilder.CancelOn.

  • Key string: Where the case's key is in the event.
  • End string: The end step the case ends at.

CancelOptions ​

CancelOptions are the tenant and context of Client.Cancel.

  • Tenant string
  • Context *RequestContext
  • Timeout time.Duration

CancelOutcome ​

CancelOutcome is what came of Client.Cancel.

  • Cancelled bool
  • Code string: Not cancelled: too_late (due, running or done already), not_found, or a middleware's code.
  • Message string

CaseRow ​

CaseRow is a process case as GetCase and ListCases answer it, from its events.

  • Process string
  • CaseID string
  • Key string
  • State string
  • Step *string
  • WaitingUntil *string
  • Incident *Incident
  • End *string
  • StartedAt string
  • EndedAt *string
  • Steps []CaseStep

CaseStep ​

CaseStep is a step a case completed.

  • Step string
  • Outcome string
  • Next *string
  • At string

Check ​

Check is a request a middleware checks: a command or query, before the kernel accepts or routes it, or after; or a file or cache request, before it runs.

  • Kind string: command, query, data, cache or cancel.
  • ID string: The command or query ID; empty for a file or cache request.
  • Tenant string
  • Domain string
  • Type string: The type within the domain: the command or query type, or PutData, GetData, … for files and cache.
  • AggregateType, AggregateID string: Commands only.
  • TargetType, TargetID string: The aggregate the request is about, qualified (shop.order): a command's aggregate, or the one a query declares. Empty for queries that declare none, and for file and cache requests.
  • Key string: File and cache requests only: the file's or value's key.
  • Data json.RawMessage: The command's or query's data; nil for a file or cache request.
  • Request RequestContext: Who sends it: check permissions here.

Client ​

Client is a client of one kernel (or a pair, or partitions): it submits commands, asks queries, and runs workers and listeners over its connection. Create one per process with New; it connects on the first call. Every request is signed with the key; the kernel checks it against the key's grant.

Calls the kernel refuses itself (not signed, not granted, no read model for a query, the kernel unreachable) return the gRPC error, whose message says why. Business rejections come differently: Submit returns them in its Outcome, Query returns a *Rejected.

  • Data *Data: Files of a domain kept by the kernel; see Data.

  • Cache *Cache: The shared cache of a domain; see Cache.

  • func New(o Options) (*Client, error): New reads the key, grant and TLS files and returns a client; it connects on the first call. A missing key file, an explicitly named grant file that is missing or a missing TLS file is an error.

  • func (c *Client) App(o AppOptions) (*App, error): App is an app made of whole domains: Run applies the service's membership (its domains' aggregates as workers, their read models and reactors as listeners, those that check requests as middlewares, live ones not listed; and their processes), then runs all of them and, once they are connected, registers the processes. One service is one app.

  • func (c *Client) Apply(ctx context.Context, m Manifest) error: Apply replaces the membership of a service (default: this process's). Apply it once per deploy, not from every process: the newest apply wins. The key needs manage for the service.

  • func (c *Client) Cancel(ctx context.Context, commandID string, options ...CancelOptions) (CancelOutcome, error): Cancel cancels a scheduled command (Enqueue with At) before it is due: it completes as rejected cancelled. Needs submit for the command's type; middlewares check it as a cancel of that type.

  • func (c *Client) Close(): Close closes the connection; only needed in a long-running process that discards the client.

  • func (c *Client) Enqueue(ctx context.Context, cmd Command) (string, error): Enqueue stores the command in the kernel's queue and returns its ID without waiting for it to run. Submit it again with the same ID to get the outcome. With At, a scheduled command: it runs at that time.

  • func (c *Client) KeyID() string: KeyID is the ID of this client's key.

  • func (c *Client) Listener(l *Listener) *ListenerHandle: Listener runs a listener defined with Domain.ReadModel or Domain.Reactor over this connection: Listener(carts).Run(ctx).

  • func (c *Client) ProcessAct(ctx context.Context, name string, request RequestContext) (bool, error): ProcessAct sets as whom the process name (qualified: shop.fulfilment) acts: the sender tenant, identity and session of request go with every command and query the kernel's engine sends for it from now on. Idempotent: false if the process acted so already.

  • func (c *Client) Query(ctx context.Context, q Query) (json.RawMessage, error): Query asks the read model that answers q.Domain.q.Type and returns its answer as JSON. Queries always go through the kernel, also within one process, so grants and middleware apply. It returns a *Rejected if the read model or a middleware rejects it.

  • func (c *Client) RegisterProcess(ctx context.Context, p *ProcessBuilder) (ProcessVersion, error): RegisterProcess registers a business process with the kernel. A model equal to the newest version registers nothing (New false); a different one becomes the next version. Client.App registers the processes of its domains itself.

  • func (c *Client) Reindex(ctx context.Context, domain, aggregateType string, aggregateIDs []string, template ...Command) (map[string]Outcome, error): Reindex has these aggregates store the unique keys and facts their current state yields, e.g. after declaring a key on an aggregate type with existing aggregates: each runs the built-in reindex command of its type, which produces no events. It returns the outcome per ID, once committed.

  • func (c *Client) Submit(ctx context.Context, cmd Command) (Outcome, error): Submit runs a command and returns its outcome: committed with its events, or rejected with a code and message (a rejection is not an error). By default it returns once the command settled, so a query right after it sees the events. It returns a *NotSettled if the command committed but did not settle in time, a *NotDue for a scheduled command that is not due yet. Idempotent on the command's ID.

  • func (c *Client) Subscribe(ctx context.Context, s Subscription, handler func(ctx context.Context, event StoredEvent) error) error: Subscribe streams committed events after s.After (backlog first, then live) to handler, one at a time, until ctx ends; it reconnects and resumes after the last handled event; if the handler fails, that event is delivered again. Unlike a listener, a subscription is not registered: the kernel keeps no position, nobody waits for it, and events arrive as stored (not upcast, vault fields null). With partitions, one stream per partition, each from the start, in order within a partition. The key needs subscribe for the types.

  • func (c *Client) Use(domains ...*Domain) *Client: Use seals the vault fields of these domains' commands when submitting them, and sends the targets their queries declare; without it, those fields go into the signed log in clear.

  • func (c *Client) Worker(aggregates ...AnyAggregate) *Worker: Worker is a worker for these aggregates: Worker(cart).Run(ctx) executes their commands until ctx ends. Start as many workers as you like; the kernel spreads commands over them, one at a time per aggregate.

Command ​

Command is a command for Client.Submit and Client.Enqueue: the aggregate it goes to (domain, aggregate type and ID), the command type and its data.

  • Domain string: The domain of the aggregate and the command type: shop.
  • AggregateType string: The aggregate type within the domain: cart.
  • AggregateID string: Which aggregate: the stream the command's events go to.
  • Type string: The command type within the domain: AddItem.
  • Data any: The command's data, sent as JSON; fields declared with Domain.Command go to the vault.
  • Tenant string: Default: the client's tenant.
  • ID string: The command ID and idempotency key. Default: a new UUID.
  • Context *RequestContext: Replaces the client's default context; inside a listener, ctx.Follow(). Its CorrelationID defaults to the command ID.
  • Committed bool: Committed returns once the events are stored, instead of once every listener that counts processed them (the default).
  • Timeout time.Duration: How long to wait for the connection and the outcome; default Options.Timeout.
  • At time.Time: Enqueue only: a scheduled command, run at this time and not before.
  • Until time.Time: Enqueue only, with At: if it cannot run by this time, it is rejected expired.

CommandContext ​

CommandContext is what a command handler gets first: the command, who sends it, and the clock and IDs that are the same every time it runs. It is a context.Context, done at the command's deadline. Create one with NewCommandContext to call a handler directly, e.g. in a unit test with Aggregate.Handle.

  • context.Context (embedded)

  • CommandID string: The command's ID: the idempotency key (Submit.ID) or a generated UUID.

  • Type string: The command type within the domain.

  • Domain string

  • AggregateType string: The aggregate type, unqualified: cart.

  • AggregateID string

  • Tenant string

  • Request RequestContext: Who sends the command: check permissions here.

  • Deadline time.Time: When the kernel hands the command to another worker if this one has not answered.

  • func NewCommandContext(ctx context.Context, commandID string, request RequestContext, receivedAt time.Time) *CommandContext: NewCommandContext is a context for command commandID, sent with request and received at receivedAt; its deadline is 30 s after receivedAt.

  • func (c *CommandContext) ID() string: ID is a new ID that is the same every time the command runs (1st call, 2nd call, …). Use it instead of random IDs.

  • func (c *CommandContext) Now() time.Time: Now is when the kernel received the command: the same every time the command runs. Use it instead of time.Now().

CommandOption ​

CommandOption is an option of one command handler (Handle).

  • func Requires[S, D any](fn func(data D, state S) []Requirement) CommandOption[S, D]: Requires gives the facts other aggregates of the command's tenant must hold for the command to commit, from the command's data and the state before it. Checked by the kernel at commit, so no command in between can remove a fact unseen; a missing one rejects the command with requirement_missing.

CommandSchema ​

CommandSchema is how a command's payload is kept: which fields go to the vault instead of the signed log. Create it with Domain.Command. The submitting client seals the fields, so it needs the domain: Client.Use(domain).

  • Type string: The command type within its domain, unqualified.

  • func (s *CommandSchema) Personal(fields []string, subject Subject) *CommandSchema: Personal keeps these top-level fields in the vault as personal data of subject; see EventSchema.Personal.

  • func (s *CommandSchema) Secret(fields ...string) *CommandSchema: Secret keeps these top-level fields (passwords, one-time tokens) in the vault only until the command completed. The handler gets them in clear; the stored command keeps a reference.

  • func (s *CommandSchema) Tool(o ToolOptions) *CommandSchema: Tool offers the command to AI agents as an MCP tool, described for the model; served when the app's MCP is on (AppOptions.MCP).

CommandStep ​

CommandStep are the options of ProcessBuilder.Command.

  • Aggregate string: The aggregate the command goes to, a reference: case.orderId.
  • Data Mapping: The command's data, from the case.
  • Rejected map[string]string: The step to go to per rejection code; any other rejection is an incident.
  • Next string: The step after the command committed. Default: the next step written.

Data ​

Data is the files of a domain kept by the kernel under (tenant, domain, key), at most 16 MiB each (the kernel's --max-data-bytes). Reading needs a grant of data_read for the domain, putting and deleting one of data_write. Files are not part of the signed event log and are not erased with the vault. Each request passes the middleware chain first, as <domain>.PutData, .GetData, .DeleteData or .ListData; a refusal is a PERMISSION_DENIED error.

  • func (d *Data) Delete(ctx context.Context, domain, key string, options ...DataOptions) (bool, error): Delete deletes the file under key and returns whether there was one.
  • func (d *Data) Get(ctx context.Context, domain, key string, options ...DataOptions) (*File, error): Get returns the file under key, or nil if there is none.
  • func (d *Data) List(ctx context.Context, domain, prefix string, options ...DataOptions) (files []FileEntry, next string, err error): List lists the files whose keys start with prefix (needs data_read), in the order of their keys' bytes, up to 1,000 after options.After; next, if not empty, is the After of the next page.
  • func (d *Data) Put(ctx context.Context, domain, key string, data []byte, options ...DataOptions) (string, error): Put stores data under key, replacing a file there, and returns its SHA-256 (hex) as the kernel computed it: for an event to name.

DataOptions ​

DataOptions say which tenant's file or value, and who asks.

  • Tenant string: Default: the client's tenant.
  • Context *RequestContext: Who asks; signed, and what middlewares checking the request decide on.
  • ContentType string: Put: the content type stored with the file (default application/octet-stream).
  • After string: List: the Next of the page before.
  • TTL time.Duration: Cache set: how long until the value expires; default until deleted or the kernel restarts.

DecideCase ​

DecideCase is one case of a decision: if the condition When holds, go to Then.

  • When string
  • Then string

DecideStep ​

DecideStep are the options of ProcessBuilder.Decide: one condition (When, Then) or several in order (Cases, the first that holds wins); Otherwise if none holds, by default the step written next.

  • When string
  • Then string
  • Cases []DecideCase
  • Otherwise string

Domain ​

Domain is a name that scopes its aggregates, commands and events, lowercase by convention (orders) like aggregates, while message types are capitalized (orders.PlaceOrder). Types are unique within a domain; elsewhere they are named domain.Type.

Everything is defined on it: aggregates (NewAggregate), read models (ReadModel), reactors (Reactor), business processes (Process), event versions and vault fields (Event, Command). Client.App runs all of it; Client.Worker and Client.Listener run parts. Definitions panic on a programming error (a malformed name, a type defined twice), as regexp.MustCompile does.

  • Name string: The domain's name: shop.

  • func ApprovalsDomain(name string) *Domain: ApprovalsDomain is the approvals of an app's MCP tools (ToolOptions.Approval), as a domain of their own (default mcp): the aggregate approval (Request, Approve, Decline, Finish), the read model <name>-approvals (GetApproval {id}, ListApprovals {state}) and the reactor <name>-runner, which carries out an approved command (with its own command ID, so once) as the person who asked for it (their tenant, identity, account and session, as their request named them: a middleware decides it as theirs, and refuses it if their session ended meanwhile), and records how it went (the approver in attributes["<name>.approved_by"]). The view keeps each tenant's approvals apart. Client.App adds it when a tool asks for approval. The held command's data is kept in the vault and erased once it is carried out or declined: the command itself then holds it. Your middleware decides who may approve (<name>.Approve), and the approver also needs <name>.Finish: the runner records how it went in their name.

  • func EventsDomain(area string) *Domain: EventsDomain is the kernable read model: every event the app's key may read, in memory, with the vault's values left out (null, named in Redacted), answering GetEvents (one aggregate's history), FindEvents (the tenant's events by type and time), GetCase and ListCases (process cases, from their events). Each query is a query like any other: the kernel puts it through the middleware, which decides per person (the kit: tenant, identity, permission; GetEvents carries the aggregate as its target, so relations apply). Its tools come with MCP; without a middleware they are offered only over stdio or on a loopback address unless allowed (Allow: kernable). It rebuilds from the first event on every start. area: the tools' area ("" for none).

  • func NewDomain(name string) *Domain: NewDomain creates a domain named name: a letter, then letters, digits, _ or -. Processes that share a domain (a worker and a read model in another process) each create it with the same name and the same Event and Command declarations.

  • func (d *Domain) Command(commandType string) *CommandSchema: Command declares which fields of commandType commands (unqualified) the vault keeps, and whether it is an MCP tool (Tool). Only needed for commands with such fields or a tool. Declared already, it returns that declaration.

  • func (d *Domain) Event(eventType string, schema int) *EventSchema: Event declares the payload format of eventType events (unqualified): this domain writes them at version schema (from 1), with an Upcast per older version, and may keep fields in the vault (Personal) or erase a subject (Erases). Types not declared are at version 1.

  • func (d *Domain) Process(name string) *ProcessBuilder: Process defines a business process name (fulfilment, qualified shop.fulfilment): returns the ProcessBuilder to chain its start and steps on. Client.App registers the processes of its domains; Client.RegisterProcess registers one alone. Panics if the domain has a process of that name already, or for a name other than letters, digits, _ and -.

  • func (d *Domain) Query(queryType string) *QuerySchema: Query declares what queryType queries (unqualified) are about; chain Target or Tool on it. Clients that ask such queries need the domain: Client.Use(domain). Declared already, it returns that declaration.

  • func (d *Domain) Reactor(name string, options ...ListenerOption) *Listener: Reactor defines a reactor named name: a listener that triggers side effects and follow-up commands. It starts at the newest event when it is new, then resumes after the last acknowledged event (order 10), so it never reacts to what happened before it existed. Submit follow-ups with ListenerContext.Submit and a fixed command ID; a rejected one parks the event (see ParkAfter). Panics if the domain has a listener of that name already.

  • func (d *Domain) ReadModel(name string, options ...ListenerOption) *Listener: ReadModel defines a read model named name: a listener that builds a view from events (On) and answers queries from it (Answer). Without a store it is kept in memory and rebuilt from the first event on every start (order 0, start 0); with a Store it continues where it left off. Panics if the domain has a listener of that name already.

EventMeta ​

EventMeta is what Apply gets about an event besides its data: only fields known before the kernel stores the event, so a snapshot and a replay compute the same state.

  • Type string: The event type within its domain: ItemAdded.
  • Version uint64: The aggregate's version after this event: 1 for its first event.
  • Tenant string
  • Domain string: Always the domain of the command that caused the event.
  • AggregateType string: The aggregate type, unqualified: cart.
  • AggregateID string
  • CommandID string: The command that produced the event.

EventRow ​

EventRow is an event as the kernable read model answers it: its vault fields null, named in Redacted.

  • Position uint64
  • Type string
  • AggregateType string
  • AggregateID string
  • Data json.RawMessage
  • Redacted []string
  • At string
  • By *string: Who sent the command that caused it (SenderIdentity), if anyone.

EventSchema ​

EventSchema is the payload format of one event type: its current version, the steps that bring older payloads up to it, and which fields go to the vault. Create it with Domain.Event; its methods return it, so they chain. Events are stored as written and never changed; readers upcast them.

  • Type string: The event type within its domain, unqualified.

  • Schema uint32: The current payload version (from 1): what workers write and readers get.

  • func (s *EventSchema) Erases(subject Subject) *EventSchema: Erases makes this an erasing event: it deletes every vault value of the subject that subject returns, in every stream, and the snapshots that may hold them.

  • func (s *EventSchema) Personal(fields []string, subject Subject) *EventSchema: Personal keeps these top-level fields in the vault, as personal data of the subject that subject returns from the payload and the aggregate's ID. Events then hold only references; the kernel hands the values to workers and to listeners allowed to read them, until an event erases the subject.

  • func (s *EventSchema) Upcast(from int, fn Upcast) *EventSchema: Upcast turns a payload of version from into one of version from+1. Steps chain: version 1 reaches 3 through Upcast(1, …) and Upcast(2, …). Panics unless from is between 1 and Schema-1. A reader that lacks a step stops at such an event instead of misreading it.

File ​

File is a file as Data.Get returns it.

  • Data []byte
  • ContentType string
  • SHA256 string: SHA-256 of the data, hex.

FileEntry ​

FileEntry is a file as Data.List lists it.

  • Key string
  • ContentType string
  • Size uint64

FoldEvent ​

FoldEvent is an event to fold (Aggregate.Fold): type, payload version and data, plus as much of EventMeta and its request context as known.

  • EventMeta (embedded)
  • Schema uint32
  • Data any
  • Request RequestContext

HandlerOption ​

HandlerOption is an option of one event handler.

  • func Raw() HandlerOption: Raw gets events as stored, without upcasting, whatever their schema (for archives and exports).
  • func Sealed() HandlerOption: Sealed never gets the vault's values, even with vault_read: vault fields are null and named in Event.Redacted (for indexes that must not hold personal data).

HeldKey ​

HeldKey is a unique key an aggregate holds, as Aggregate.Index returns it.

  • Name string: The key's name, as declared with Aggregate.Unique.
  • Value string: The value, as the key's function returned it. The kernel gets only its SHA-256 hash.
  • Global bool
  • Subject string: For a personal key: the person the value belongs to.

Incident ​

Incident is why a case stopped.

  • Code string
  • Message string

Index ​

Index is the unique keys and facts an aggregate holds in a state.

  • Keys []HeldKey: In the order of declaration, the values of a key in the order its function returned them.
  • Facts []string: The facts that are true, in the order of declaration.

Key ​

Key is an Ed25519 signing key. Its ID is the lowercase hex public key.

  • ID string

  • func KeyFromFile(path string) (*Key, error): KeyFromFile reads a .key file.

  • func KeyFromHex(s string) (*Key, error): KeyFromHex reads a hex-encoded 32-byte seed (the content of a .key file).

Listener ​

Listener is the definition of a durable, named event listener: which events it handles (On), which queries it answers (Answer) and what it checks as a middleware (Middleware). Define it on a domain with Domain.ReadModel or Domain.Reactor and run it with Client.Listener or Client.App.

Type names without a domain (ItemAdded, GetCart) are of the listener's own domain; types of other domains are qualified (identity.AccountRegistered) or name a whole domain (identity.*). Handlers get event payloads upcast to the versions of the listener's own domain and of the domains it Uses.

  • Domain *Domain: The domain the listener is defined on.

  • Name string: The listener's name; the kernel tracks its position under it.

  • func (l *Listener) Middleware(options MiddlewareOptions, fn func(ctx *MiddlewareContext, check Check) error) *Listener: Middleware makes this listener a middleware: the kernel asks fn about every command, query, file and cache request of options.Types, before accepting or routing it (or after), in chain order, and only once this listener has caught up with the events. Return a *Rejected to refuse; any other error refuses too. A listener has at most one middleware before and one after. Panics for a live listener, a malformed type, or a second middleware at the same When.

  • func (l *Listener) Options() ListenerOptions: Options are the options the listener was defined with.

  • func (l *Listener) Use(domains ...*Domain) *Listener: Use upcasts the events of these other domains with their event schemas.

ListenerContext ​

ListenerContext is what an event handler gets first: the event, the listener's store, and follow-up commands and queries on the listener's connection.

  • context.Context (embedded)

  • Event StoredEvent: The event, its data upcast (unless the handler is Raw) and its vault fields filled in as far as this key may read them.

  • Replaying bool: The event was committed before this connection began: a read model rebuilding, and equally the backlog a reactor catches up on. A reactor must not skip side effects because of it; submit follow-ups with fixed command IDs instead.

  • Store *Store: The listener's store, if it has one.

  • func (c *ListenerContext) Client() *Client: Client is the listener's client: requests on it with this context as their ctx name the listener, as everything sent from a handler does (Client().Query(ctx, …) for a query with its own tenant and context).

  • func (c *ListenerContext) Follow() RequestContext: Follow is a request context for commands caused by this event: same sender and correlation, the event's command as causation, without ExpectedVersion and BypassAuthorization.

  • func (c *ListenerContext) ProcessAct(name string, request RequestContext) (bool, error): ProcessAct sets as whom the process name acts (Client.ProcessAct), on the listener's connection: how an authorization kit hands a process its identity.

  • func (c *ListenerContext) Query(queryType string, data any) (json.RawMessage, error): Query asks a query on the listener's connection: queryType is of the listener's domain (GetOrder) or qualified (crm.GetCustomer). The tenant defaults to the event's. It is the listener's own read: it keeps the client's context, not the event's sender.

  • func (c *ListenerContext) Submit(cmd Command) ([]StoredEvent, error): Submit submits a command this event causes, on the listener's connection, and returns its events. It needs a fixed ID (confirm-<order>), so a redelivered event runs it once. The domain defaults to the listener's, the context to Follow(), the tenant to the event's. A rejection returns a *Rejected (with the kernel's key or requirement): a reactor then parks the event at once.

ListenerHandle ​

ListenerHandle is a listener running over a connection: Client.Listener(definition). Events arrive in order, one at a time, after every listener with a lower order has processed them. Delivery is at least once: if a handler fails, the listener reconnects and the event is delivered again, until a reactor gives up on it and parks it. With a store, a batch's data and position are written together, so it takes effect once.

  • func (h *ListenerHandle) Listener() *Listener: Listener is the definition it runs.
  • func (h *ListenerHandle) Ready() <-chan struct{}: Ready is closed once the kernel accepted the listener (on every partition).
  • func (h *ListenerHandle) Run(ctx context.Context) error: Run opens the store (if any; trying again while it cannot be opened), connects, and processes events, queries and checks until ctx ends, reconnecting after the last handled event when the stream drops or a handler fails. It returns nil once ctx ends, having closed the store.
  • func (h *ListenerHandle) Skipped() int: Skipped is the number of events skipped because this code does not know them: a schema newer than the listener's domains declare, written by a newer deployment.

ListenerOption ​

ListenerOption changes a listener's options.

  • func Instance(name string) ListenerOption: Instance runs the listener as one instance of a group.
  • func Live() ListenerOption: Live makes the listener live: not registered, always from the newest event.
  • func Order(n int32) ListenerOption: Order sets the listener's place in the order.
  • func ParkAfter(n int) ListenerOption: ParkAfter sets how often a handler may fail on one event before the listener parks it.
  • func ReconnectAfter(d time.Duration) ListenerOption: ReconnectAfter sets the first pause before reconnecting.
  • func Single(single bool) ListenerOption: Single says whether a group's instances take turns.
  • func StartAfter(position uint64) ListenerOption: StartAfter starts the listener after position on its first connect (0: from the beginning).
  • func StartAtNewest() ListenerOption: StartAtNewest starts a new listener at the newest event (the default for reactors).
  • func StoreSchema(schema string) ListenerOption: StoreSchema sets the version of the stored data's format.
  • func WithStore(url string) ListenerOption: WithStore keeps the listener's state in a store: sqlite:<path> or memory:.

ListenerOptions ​

ListenerOptions say how a listener runs: its place in the order, where it starts, whether it is live, and where it keeps its state. Domain.ReadModel and Domain.Reactor set the defaults; the ListenerOption functions change them.

  • Order int32: Listeners with a lower order process each event first; equal orders run in parallel. Defaults: 0 for read models, 10 for reactors. Negative orders are reserved for the kits.
  • Start *uint64: Position to start after on the first connect: 0 rebuilds from the beginning (default for read models); nil, the kernel resumes after the last acknowledged event, and a new listener starts at the newest event (default for reactors).
  • Live bool: Not registered with the kernel: no stored position, always starts at the newest event, nobody waits for it, and it is forgotten when it disconnects. Cannot be a middleware.
  • Instance string: Runs this process's listener as one instance of a group under the listener's name. Default: KERNABLE_INSTANCE.
  • Single *bool: Whether the instances take turns (default for reactors), or every instance gets every event (default for read models).
  • Reconnect time.Duration: How long to wait before reconnecting after the stream ends (default 1 s).
  • Store string: Keeps the listener's state in a store (sqlite:<path> or memory:) instead of memory.
  • Schema string: Version of the stored data's format (default "1"); a change clears the store.
  • ParkAfter int: How often a handler may fail on one event before the listener parks it and moves on (default 5 for reactors, 0 for read models: never). A *Rejected parks at once; the kernel being unreachable or busy, NotSettled or the store failing never does.

Literal ​

Literal is a literal in a mapping, where a plain string would be a reference; build it with Value.

  • Value any

  • func Value(x any) Literal: Value is a literal for a mapping: Mapping{"reason": kernable.Value("unpaid")} sends the string unpaid, while "case.reason" sends the case's field.

MCPOptions ​

MCPOptions switch MCP on for an app (AppOptions.MCP): off by default. KERNABLE_MCP overrides Enabled, Transport, Host and Port: off, on, stdio, http, http:<port> or http:<host>:<port>, so operations switch it per environment without a code change.

Every call is a normal command or query, signed with the app's key; the agent's client is recorded in its context's Attributes (mcp.client, mcp.tool), the person in SenderIdentity, so middleware decides as for any request.

  • Enabled bool: Serve the app's tools.

  • Transport string: "stdio" (the agent starts the app and talks over stdin/stdout) or "http" (default).

  • Port int: HTTP: the port (default 7700).

  • Host string: HTTP: the address to listen on (default 127.0.0.1).

  • Path string: HTTP: the endpoint's path (default /mcp).

  • Name string: The server's name for clients (default: the app's service).

  • Instructions string: What the model should know about the tools as a whole.

  • Context *RequestContext: The request context of every call: with stdio, the person the agent works for.

  • Authenticate func(r *http.Request) (*RequestContext, error): HTTP: who the person is, from the request (its Authorization header, say): their request context, merged over Context. Return nil or an error to refuse the request (401).

  • Origins []string: HTTP: browser origins allowed to call; a request with any other Origin is refused.

  • Approvals string: The domain of the approvals (ToolOptions.Approval), default mcp.

  • Allow []string: Tools that need allowing (ToolOptions.Area), allowed by their area: the kit's writes that change who may do what (kit.groups, kit.invitations, kit.memberships; kit for all), or kernable for the event and process tools without a middleware on an open endpoint. Every other tool is offered as soon as MCP is on.

  • Checked *bool: A middleware checks every request per person (the kit's, or your own): the event and process tools are then offered on any endpoint. Detected when one of the app's listeners checks * or kernable.* (the kit does); set it when the middleware runs in another service.

  • func MCPSettings(o *MCPOptions, env string) (*MCPOptions, error): MCPSettings applies env (KERNABLE_MCP) over the app's options and the defaults: the settings, or nil when MCP is off.

MCPServer ​

MCPServer answers JSON-RPC messages with an app's tools (App.MCP); the transports call Handle.

  • Tools []MCPTool: Tools are the tools it offers.

  • func (s *MCPServer) Handle(ctx context.Context, message map[string]any, caller *mcpCaller) map[string]any: Handle answers one JSON-RPC message; nil for a notification or a response.

  • func (s *MCPServer) Where() string: Where is where it serves, for the app's overview: stdio, or the HTTP endpoint's URL.

MCPTool ​

MCPTool is a tool as offered: its MCP description and what it runs.

  • Name string

  • Title string

  • Description string

  • InputSchema map[string]any

  • OutputSchema map[string]any

  • Annotations map[string]any

  • Kind string

  • Domain string

  • Type string

  • AggregateType string

  • Once Once

  • Options ToolOptions

  • func ToolsOf(domains []*Domain, approvals string, allow ...string) ([]MCPTool, error): ToolsOf is the tools the domains declare, checked: unique names, a known aggregate for each command. The approvals' domain (default mcp) is left out; it adds the mcp_approval tool when a tool asks for approval.

Manifest ​

Manifest is what a service consists of, for Client.Apply: its membership, which tells the kernel what to wait for.

  • Service string: Default: this process's service.
  • Workers []AnyAggregate: The aggregates the service runs; the kernel waits for a worker of each.
  • Listeners []*Listener: The listeners the kernel waits for.
  • Middlewares []*Listener: The service's listeners that may check requests.
  • Metadata map[string]string: Free metadata, e.g. version.
  • Processes []string: The service's business processes, qualified (shop.fulfilment).
  • Deployment string: The deployment that serves the service. Default: this process's.
  • Switch Switch: When it switches (default CaughtUp).

Mapping ​

Mapping maps fields to references (strings: aggregateId, data.<path>, case.<path>, answer, answer.<path>) or literals (Value(…)). Paths are wire names, as the messages' fields.

MiddlewareContext ​

MiddlewareContext is what a middleware handler gets first. After a request, Outcome (a command) or QueryOutcome (a query) says what came of it.

  • context.Context (embedded)
  • Store *Store: The listener's store, if it has one.
  • Outcome *Outcome: After a command.
  • QueryOutcome *QueryOutcome: After a query.

MiddlewareOptions ​

MiddlewareOptions say what a middleware checks and where it sits in the chain.

  • Types []string: Request types it checks: * (all), a type of the listener's own domain (Type), another domain's type (domain.Type) or a whole domain (domain.*). These also cover the file and cache requests of a domain under the types PutData, GetData, DeleteData, ListData, SetCache, GetCache and DeleteCache.
  • When When: Before (default): checks a request before the kernel accepts it; an error refuses it. After: gets the request's outcome too.
  • Order int32: Position in the chain: lower runs first (default 0). Negative orders are reserved.

ModelCancelOn ​

ModelCancelOn is an event that ends a running case at once.

  • Event string
  • Key string
  • End string

ModelPath ​

ModelPath is one path of a query step.

  • Value any
  • Next string

ModelStart ​

ModelStart is a model's start.

  • On string
  • Key string
  • Data Mapping

ModelStep ​

ModelStep is one step of a model; every step but end names what comes next.

  • Name string
  • Kind string
  • Command string
  • Event string
  • Query string
  • Aggregate string
  • Key string
  • Data Mapping
  • Rejected map[string]string
  • TimeoutMs uint64
  • OnTimeout string
  • AfterMs uint64
  • At string
  • When []ModelWhen
  • Answer string
  • Paths []ModelPath
  • Into string
  • Otherwise string
  • Next string

ModelWhen ​

ModelWhen is one condition of a decide step.

  • If string
  • Next string

NewEvent ​

NewEvent is an event a command handler returns. The worker stores it at the payload version declared with Domain.Event (1 if not declared) and moves fields declared personal to the vault.

  • Type string: The event type within the aggregate's domain, unqualified: ItemAdded.

  • Data any: The payload; it must encode as JSON. Nil is stored as {}.

  • func Event(eventType string, data any) NewEvent: Event is a NewEvent: kernable.Event("ItemAdded", ItemAdded{SKU: "apple", Qty: 2}).

  • func Events(events ...NewEvent) []NewEvent: Events is a list of events, for a handler's return: return kernable.Events(kernable.Event(…)), nil.

NotDue ​

NotDue is returned by Submit for the ID of a scheduled command (Enqueue with At) that is not due yet: it has no outcome to wait for. Submit its ID again after its time.

  • CommandID string

  • func (e *NotDue) Error() string:

NotSettled ​

NotSettled is returned by a settling Submit (the default) when the command was committed but not every listener that counts processed its events within the kernel's --settle-timeout-ms (default 5 s). The command is not lost: do not submit it again under a new ID. Submitting again with the same ID returns the same outcome; a query with MinPosition waits for the events.

  • Outcome Outcome: The committed outcome, with the stored events.

  • func (*NotSettled) Error() string:

Once ​

Once is how an MCP tool keeps a command from running twice when an AI model calls it again (after a timeout, say).

go
const (
	// OnceField: the tool's input gets a request_id the model is told to reuse when it retries
	// the same request; the same request_id is the same command (the default for commands).
	OnceField Once = "field"
	// OnceArgs: the same arguments on the same day (UTC) are the same command.
	OnceArgs Once = "args"
	// OnceNone: every call is a new command (queries are always OnceNone).
	OnceNone Once = "none"
)

Options ​

Options say how a Client connects: kernel address, key, grant and defaults for its requests. Every option has a default, most from an environment variable, so New(Options{}) works with the files kernable start --dev creates.

  • URL string: Kernel address: http://host:port (host:port works too) or, on Unix, unix:/path/to.sock. For a pair of kernels with a standby, both, comma-separated. Default: KERNABLE_URL, else http://127.0.0.1:7233.
  • Key string: Path to this process's .key file. Default: KERNABLE_KEY, else app.key.
  • Grant string: Path to the key's grant (kernable grant), sent with every call. Default: KERNABLE_GRANT, else the key file's path with .grant for .key, if it exists.
  • Tenant string: Default tenant for requests. Default: default.
  • Service string: The service this process's workers and listeners belong to. Default: KERNABLE_SERVICE.
  • Deployment string: This process's code version, e.g. a build ID: 1 to 128 letters, digits, -, _ and .. Default: KERNABLE_DEPLOYMENT.
  • Context RequestContext: Default request context for requests; a request's own context replaces it as a whole.
  • TLS *TLSFiles: Mutual TLS for host:port URLs. Default: KERNABLE_TLS_CA, KERNABLE_TLS_CERT and KERNABLE_TLS_KEY, if set.
  • Insecure bool: Allows plain text to a kernel that is not on this machine. Default: KERNABLE_INSECURE=1.
  • Timeout time.Duration: How long a request waits in all, for the connection and its answer. Default 60 s.

Outcome ​

Outcome is what came of a command (Client.Submit): committed with the events it stored, or rejected with a code and message (by its handler, a middleware or the kernel, e.g. version_mismatch, unique_taken, requirement_missing). A rejection is a result, not an error: check Committed.

  • Committed bool

  • Events []StoredEvent: Committed: the stored events.

  • Code string: Rejected: why.

  • Message string

  • Key string: unique_taken: the key's name (never its value).

  • Requirement *Requirement: requirement_missing: the first requirement that does not hold.

  • func Approve(ctx context.Context, c *Client, id string, o ApprovalOptions) (Outcome, error): Approve approves a held tool call (ToolOptions.Approval): the command then runs. The outcome is rejected (decided) if it was decided already.

  • func Decline(ctx context.Context, c *Client, id string, o ApprovalOptions) (Outcome, error): Decline declines a held tool call: it never runs. See Approve.

PathPair ​

PathPair is an answer and the step it leads to, for answers Paths cannot say (a string that looks like a boolean or a number).

  • Value any
  • Next string

ProcessBuilder ​

ProcessBuilder is a business process of a domain, built in code and run by the kernel: a case starts when an event commits, and moves through steps (commands, waits for events, timers, decisions by the case's data or by a query) to an end. Create it with Domain.Process.

Steps run in the order written, unless a step names Next; branching steps (Decide, Query) and error paths (Rejected, OnTimeout) name their targets. Messages are names: an unqualified event or query is of the process's domain (OrderApproved), others qualified (payments.PaymentReceived); a command is aggregate.Type of the process's domain (order.Ship) or domain.aggregate.Type.

  • Domain string: The domain it belongs to: shop.

  • Name string: The process's name within its domain: fulfilment.

  • func (p *ProcessBuilder) CancelOn(event string, options CancelOnOptions) *ProcessBuilder: CancelOn ends a running case at once when an event of its key commits, whatever step it is at.

  • func (p *ProcessBuilder) Command(name, command string, options CommandStep) *ProcessBuilder: Command sends a command as the process, to the aggregate options.Aggregate names.

  • func (p *ProcessBuilder) Decide(name string, options DecideStep) *ProcessBuilder: Decide picks a path by the case's data. Conditions are references to the case, literals, == != < <= > >=, and, or, not and parentheses; anything more is a query.

  • func (p *ProcessBuilder) End(name string) *ProcessBuilder: End ends the case. A process may have several ends.

  • func (p *ProcessBuilder) Model() (model ProcessModel, err error): Model is the model the kernel registers: types qualified, durations in ms, the order written resolved into explicit nexts. It checks what it can before the kernel does.

  • func (p *ProcessBuilder) Qualified() string: Qualified is the name the kernel knows: shop.fulfilment.

  • func (p *ProcessBuilder) Query(name, query string, options QueryStep) *ProcessBuilder: Query asks a read model a query with options.Data built from the case; the answer (or its field options.Answer) picks the step.

  • func (p *ProcessBuilder) Start(event string, options StartOptions) *ProcessBuilder: Start starts a case when event commits.

  • func (p *ProcessBuilder) Timer(name string, options TimerStep) *ProcessBuilder: Timer waits for a time: After a duration from when the case reached the step, or until At.

  • func (p *ProcessBuilder) Wait(name, event string, options WaitStep) *ProcessBuilder: Wait waits for an event of this case and merges options.Data from it into the case's data.

ProcessModel ​

ProcessModel is a process model, as the kernel registers it.

  • Name string
  • Start ModelStart
  • Steps []ModelStep
  • CancelOn []ModelCancelOn

ProcessVersion ​

ProcessVersion is a process as the kernel registered it.

  • Name string: Qualified: shop.fulfilment.
  • Version uint32
  • New bool: Whether this registration made a new version.

Query ​

Query is a query for Client.Query: which query type to ask, with which data. The kernel routes it to the read model that answers domain.Type.

  • Domain string: The domain of the query type: shop.
  • Type string: The query type within the domain: GetCart.
  • Data any: The query's data, sent as JSON.
  • Tenant string: Default: the client's tenant.
  • Context *RequestContext: Replaces the client's default context.
  • MinPosition uint64: Answer only after the read model has processed this global position. Default 0.
  • Timeout time.Duration: How long to wait for the connection and the answer; default Options.Timeout.
  • AllPartitions bool: For a read model across tenants with partitions: answer only once the read model has processed every partition's events up to the query.

QueryContext ​

QueryContext is what a query handler gets first.

  • context.Context (embedded)
  • QueryID string: A new UUID per query.
  • Type string: The query type within the domain.
  • Domain string
  • Tenant string
  • Request RequestContext: Who asks: check permissions here.
  • Store *Store: The listener's store, if it has one.

QueryOutcome ​

QueryOutcome is what came of a query: its response or why it was rejected.

  • Answered bool
  • Data json.RawMessage
  • Code string
  • Message string

QuerySchema ​

QuerySchema is what a domain declares about a query type: the aggregate it is about.

  • Type string: The query type within its domain, unqualified.

  • func (s *QuerySchema) Target(aggregateType, field string) *QuerySchema: Target says the query is about one aggregate of aggregateType (order, or qualified shop.order), whose ID is in the data's field. The SDK sends it with the query, signed, and a middleware decides on it as on a command's aggregate.

  • func (s *QuerySchema) Tool(o ToolOptions) *QuerySchema: Tool offers the query to AI agents as a read-only MCP tool, described for the model (Output describes the answer).

QueryStep ​

QueryStep are the options of ProcessBuilder.Query.

  • Data Mapping: The query's data, from the case.
  • Answer string: For an answer that is an object: the path of the field to match against. Default: the answer.
  • Paths map[string]string: The step per answer: {"true": "approved", "false": "paid"}. Keys true and false stand for the booleans, numeric keys for numbers, others for strings.
  • Pairs []PathPair: Pairs instead of Paths, in order.
  • Into string: A case field to keep the answer in.
  • Otherwise string: The step for an answer no path matches. Without it, such an answer is an incident.

Rejected ​

Rejected is a refusal with a business reason: return it from a command handler, a query handler or a middleware. Code is a short machine-readable reason ("rejected" unless given), Message the text for people.

  • From a command handler: the command is rejected and stored as rejected, with no events;
go
Client.Submit returns an Outcome with Committed false, not an error.
  • From a query handler or a middleware: the request is refused; Client.Query returns a
go
*Rejected with the same code and message.

Any other error a handler returns rejects too, with the code handler_error (a middleware's: middleware_error).

  • Code string

  • Message string

  • Key string: For a rejected follow-up command (ListenerContext.Submit): the key the kernel named (unique_taken).

  • Requirement *Requirement: For a rejected follow-up command: the requirement the kernel named (requirement_missing).

  • func Reject(code, message string) *Rejected: Reject returns a *Rejected with code and message: return nil, kernable.Reject("exists", "Order already exists").

  • func (r *Rejected) Error() string:

RequestContext ​

RequestContext says who sends a request and in which context: signed with the command or query and stored with every event a command causes. Middleware decides on it; ListenerContext.Follow passes it on to follow-up commands. Every field is optional; Attributes are business data only, never security decisions.

  • SenderTenant string: The sender's tenant, as your application defines it.
  • SenderIdentity string: The person or system the request is for: who middleware checks.
  • SenderAccount string: The sender's account, as your application defines it.
  • SenderSession string: The sender's session, as your application defines it.
  • OnBehalfOf string: Authorize as this identity of the target tenant; the sender stays the real principal.
  • ExpectedVersion *uint64: Reject the command (version_mismatch) unless the aggregate is at this version.
  • CorrelationID string: Shared by everything one original request causes; defaults to the command ID.
  • CausationID string: The command that caused this one (Follow sets it).
  • TraceID string: Your tracing system's ID.
  • BypassAuthorization bool: Privileged: only keys granted privileged for bypass_authorization may set it.
  • Attributes map[string]string: Free key-value pairs for business data, never for security decisions.

Requirement ​

Requirement is a fact another aggregate of the command's tenant must hold (or, Absent, must not hold) when the command commits: what a command's Requires option returns. The kernel checks it atomically with the commit; if it does not hold, the command is rejected with requirement_missing. The aggregate is named by its ID, or by a unique key of its type (Key and Value), which the kernel resolves at commit.

  • Domain string: The domain of the aggregate; default: the command's own.
  • AggregateType string: The aggregate type within the domain, unqualified: Vehicle.
  • AggregateID string: The aggregate's ID; empty when it is named by Key.
  • Key string: A unique key of the aggregate type that names the aggregate instead of its ID.
  • Value string: The key's value, normalised as the key's function does: the kernel gets only its SHA-256.
  • Fact string: The fact it must hold, as declared with Aggregate.Fact: open.
  • Absent bool: The aggregate must not hold the fact.

StartOptions ​

StartOptions are the options of ProcessBuilder.Start.

  • Key string: Where the case's key is in the event: aggregateId or data.<field>. One case per key.
  • Data Mapping: The case's data, from the event.

Store ​

Store is a listener's store: JSON values under (namespace, key) in a SQLite file (or in memory), written in one transaction with the listener's position per batch of events. So after a crash every event has taken effect exactly once, and a restart continues after the stored position instead of rebuilding. Give a read model one with the Store option; its handlers get it as ctx.Store (also query handlers). The tables are the other SDKs': a store file is readable by each.

  • func (s *Store) All(ns string) ([]StoreEntry, error): All is every key and value of a namespace, ordered by key.
  • func (s *Store) Get(ns, key string, v any) (bool, error): Get reads the value under key in namespace ns into v; false if there is none.
  • func (s *Store) Remove(ns, key string) error: Remove removes the value under key in namespace ns, if there is one.
  • func (s *Store) Reset(ns ...string) error: Reset clears a namespace, or all data without one.
  • func (s *Store) Set(ns, key string, value any) error: Set stores value (as JSON) under key in namespace ns, replacing a value there.

StoreEntry ​

StoreEntry is a key and its value, as Store.All lists them.

  • Key string
  • Value json.RawMessage

StoredEvent ​

StoredEvent is an event as the kernel stored it: in a submit's Outcome, in a subscription (Client.Subscribe) and, as ListenerContext.Event, in a listener's handler.

  • EventMeta (embedded)

  • Position uint64: The event's global position: its place in the one order of all domains and tenants.

  • CreatedAt time.Time: When the kernel committed the event.

  • Schema uint32: The payload format's version. A listener's handler gets the data upcast to the version it knows (see Domain.Event); here it is as stored.

  • Data json.RawMessage: The payload as stored (in a listener: upcast, with the vault fields it may read).

  • Redacted []string: Fields kept in the vault whose value is not here (null in Data): erased, or not readable with this key.

  • Request RequestContext: The request context of the command that caused the event.

  • Deployment string: The code version of the worker that wrote it; empty if none.

  • func (e *StoredEvent) Decode(v any) error: Decode unmarshals the event's data into v.

Subject ​

Subject says whose personal data a payload holds: from the payload (as generic JSON) and the aggregate's ID. func(_ map[string]any, id string) string { return id } for the aggregate itself.

Subscription ​

Subscription says what Client.Subscribe streams.

  • After uint64: Global position of the last event already handled; 0 from the beginning.
  • Types []string: Qualified event types (orders.OrderPlaced) or domains (orders.*); empty: all the key may read.
  • Reconnect time.Duration: The first pause before reconnecting (default 1 s).

Switch ​

Switch says when a membership switches its service to its deployment while another one serves: "caught-up" (default), "now" or "never".

go
const (
	CaughtUp Switch = "caught-up"
	Now      Switch = "now"
	Never    Switch = "never"
)

TLSFiles ​

TLSFiles are PEM files for mutual TLS: the CA of the kernel's certificate, and this process's own certificate and key.

  • CA, Cert, Key string

TimerStep ​

TimerStep says when a timer step fires: After a duration (1d), or At a reference to a time in ms since epoch (case.dueAt); and where it goes then.

  • After string
  • At string
  • Next string: The step after the timer fired. Default: the next step written.

ToolOptions ​

ToolOptions offer a command or query to AI agents as an MCP tool (see AppOptions.MCP), declared on the domain: d.Command("Place").Tool(kernable.ToolOptions{...}). Only what is declared is offered.

  • Description string: What the tool does, for the model: when to use it, what it changes. Required.
  • Title string: A short name for people (clients show it).
  • Name string: The tool's name; default <domain>_<type> (shop_Place). Letters, digits, _ and -, up to 64.
  • Input map[string]any: The input as a JSON Schema of an object (default: no input). The SDK checks a call against it before anything is sent: type, properties, required, additionalProperties, enum, const, minimum, maximum, minLength, maxLength, pattern, items, minItems, maxItems; other keywords are passed on to the model but not checked.
  • Output map[string]any: Queries: the answer as a JSON Schema of an object, for the model.
  • Once Once: Commands: how a retried call stays one command; default OnceField.
  • Aggregate string: Commands: the aggregate type, if more than one of the domain's aggregates handles it.
  • AggregateIDField string: Commands: the input field that holds the aggregate's ID. Default: the input's id, if it has one; else a new aggregate whose ID comes from the command's ID, so a retried call reaches the same one.
  • AggregateID func(input map[string]any) string: Commands: the aggregate's ID from the input, instead of AggregateIDField.
  • Approval func(input map[string]any) string: Commands: when a person must approve the call first: return a reason to hold it, "" to run it at once. The tool answers "needs approval" with an ID, the model can ask mcp_approval how it stands, and the command runs once a person approves it (Approve). It decides before the command runs: hold only what a person may allow.
  • Destructive bool: Commands: the tool may destroy or overwrite something (a hint for clients).
  • Area string: The tool needs allowing: offered only when the app allows its area (MCPOptions.Allow). For tools that change who may do what (the kit's kit.groups, kit.invitations, kit.memberships) or that no middleware would check. Without an area a tool is offered as soon as MCP is on.

UniqueOption ​

UniqueOption is an option of a unique key (Aggregate.Unique).

  • func Global[S any]() UniqueOption[S]: Global makes a unique key unique in every tenant, not only within the tenant.
  • func PersonalKey[S any](subject func(S) string) UniqueOption[S]: PersonalKey makes the key personal: the person (subject) its values belong to, from the state. The kernel keeps the key in the vault, and erasing the subject frees it. An empty subject: the aggregate holds no value of the key.

Upcast ​

Upcast turns a payload of one version into one of the next (as generic JSON: objects are map[string]any, numbers json.Number).

WaitStep ​

WaitStep are the options of ProcessBuilder.Wait.

  • Key string: Where the case's key is in the awaited event.
  • Data Mapping: Merged into the case's data, from the event.
  • Timeout string: How long to wait (3d); with OnTimeout, the step to go to then.
  • OnTimeout string: The step after Timeout; required with it.
  • Next string: The step after the event came. Default: the next step written.

When ​

When is where a middleware sits: before a request (it may refuse it) or after it.

go
const (
	Before When = iota
	After
)

Worker ​

Worker runs the commands of its aggregates over a connection. Create it with Client.Worker (or let Client.App do it) and start it with Run. The kernel leases it one command at a time per aggregate, with the aggregate's events (and latest snapshot); the worker folds them, calls the command's handler, and sends back the signed events, or the rejection. A command whose handler returns a *Rejected is rejected with its code; any other error rejects with handler_error. An event whose schema the worker does not know ends the session instead (it logs and reconnects until it is updated).

  • func (w *Worker) Ready() <-chan struct{}: Ready is closed once the kernel accepted the worker (on every partition).
  • func (w *Worker) Run(ctx context.Context, options ...WorkerOptions) error: Run registers the aggregates and processes commands until ctx ends, reconnecting when the session drops. It returns nil once ctx ends.

WorkerOptions ​

WorkerOptions say how a worker runs: the argument of Worker.Run and App.Run.

  • Concurrency int: Commands executed in parallel, of different aggregates (default 16).
  • Reconnect time.Duration: How long to wait before reconnecting after the session ends (default 1 s); twice as long after each further failed attempt, at most 30 s.

Functions ​

  • func AlsoOn[D any](l *Listener, eventType string, fn func(ctx *ListenerContext, data D) error): AlsoOn adds a handler for eventType that runs after the one the listener has for it (if any), instead of replacing it: how a kit teaches an app's read model what it knows (visibility).
  • func Answer[D, R any](l *Listener, queryType string, fn func(ctx *QueryContext, data D) (R, error)): Answer answers the query type queryType, of the own domain (GetCart) or another one (orders.GetOrder), from this listener's state. The kernel delivers queries in order with the events, so an answer reflects every event handled before it. fn(ctx, data) returns the answer, sent as JSON; a *Rejected refuses, any other error refuses with handler_error. Panics for a malformed type.
  • func Apply[S, D any](a *Aggregate[S], eventType string, fn func(ctx *ApplyContext, state *S, data D)): Apply says how an event of eventType (unqualified, of the aggregate's domain) changes the state: fn(ctx, state, data) changes *state. state is a copy, so changing it never touches the state it came from; data is upcast to the version declared with Domain.Event. Events without an Apply leave the state as it is. Must be deterministic: no clock, no random values, no I/O.
  • func CheckSchema(value any, schema map[string]any, at string) []string: CheckSchema says what is wrong with value against schema (the keywords ToolOptions.Input lists); empty when nothing. Objects' fields are checked in the order of their names.
  • func Handle[S, D any](a *Aggregate[S], commandType string, fn func(ctx *CommandContext, state S, data D) ([]NewEvent, error), options ...CommandOption[S, D]): Handle says which events a commandType command (unqualified, of the aggregate's domain) produces: fn(ctx, state, data) gets the current state and the command's data and returns the events (possibly none). Return a *Rejected to reject the command. It may run more than once for the same command, so it must decide the same way every time: use ctx.Now() and ctx.ID() instead of the clock and random IDs, and leave side effects to reactors. Panics for a type starting with reindex, reserved for the built-in reindex commands.
  • func On[D any](l *Listener, eventType string, fn func(ctx *ListenerContext, data D) error, options ...HandlerOption): On handles events of eventType: a type of the own domain (ItemAdded), of another domain (identity.AccountRegistered) or a whole domain (identity.*): fn(ctx, data) gets the upcast payload as D, and the event in ctx.Event. A handler for the exact type wins over one for its domain; one handler per type. The listener acknowledges an event only after the handler returned; if it fails, the event is delivered again. Panics for a malformed type.
  • func QueryAs[T any](ctx context.Context, c *Client, q Query) (T, error): QueryAs asks a query like Client.Query and decodes the answer into T.
  • func ReindexType(aggregateType string) string: ReindexType is the command an aggregate type with unique keys or facts runs itself, one per aggregate type because command types are unique within a domain: _reindex_Customer. See Client.Reindex.
  • func WaitsForSwitch(err error) bool: WaitsForSwitch is whether the kernel refused a membership because it would switch its service to a deployment that has not caught up yet, back to one that served before, or at all with Never: applying it again may succeed later.

Constants ​

go
const ApprovalTool = "mcp_approval"

ApprovalTool is the tool the model asks how an approval stands.

Constants ​

go
const DefaultTimeout = 60 * time.Second

DefaultTimeout is how long a request waits, for the connection and the answer, unless told otherwise: above the kernel's own submit and settle timeouts.

Constants ​

go
const Protocol = 1

Protocol is the protocol version this SDK speaks; see "Protocol versions" in kernable.proto.