Runtime API
The runtime is the kernel of Kitsune. It’s framework-neutral and dependency-free.
import { createKitRuntime } from '@atheory-ai/kitsune'
const runtime = createKitRuntime()KitRuntime
Section titled “KitRuntime”type KitRuntime = { // events emit(event: KitEventInput): KitEvent on(eventType: string, handler: EventHandler): Unsubscribe
// commands command<T>(command: KitCommandInput): Promise<CommandResult<T>> handleCommand<T>(commandType: string, handler: CommandHandler<T>, descriptor?: KitOperationDescriptor): Unsubscribe
// queries and domain discovery query<T>(query: KitQueryInput): Promise<QueryResult<T>> handleQuery<T>(queryType: string, handler: QueryHandler<T>, descriptor?: KitOperationDescriptor): Unsubscribe discover(): KitDiscovery
// module lifecycle install(module: KitModule): Promise<void> start(): Promise<void> stop(): Promise<void>
// providers provide<T>(token: ProviderToken<T>, value: T): void inject<T>(token: ProviderToken<T>): T | undefined
// boundaries createBoundary(options: BoundaryOptions): BoundaryHandle
// diagnostics onDiagnostic(handler: DiagnosticHandler): Unsubscribe}emit(event)
Section titled “emit(event)”Emits an event synchronously. Returns the stamped event (with id and timestamp).
- Calls every handler subscribed to
event.type, then every handler subscribed to'*'. - Errors thrown by one handler do not stop others.
- Emits a
event.emitteddiagnostic.
const event = runtime.emit({ type: 'note.saved', context: { surface: 'editor' }, payload: { id: 'n_1' },})// event.id, event.timestamp are filled inon(eventType, handler)
Section titled “on(eventType, handler)”Subscribes a handler to an event type. Pass '*' to observe every event.
Returns an unsubscribe function.
const unsubscribe = runtime.on('note.saved', (event) => { console.log(event)})unsubscribe()command(command)
Section titled “command(command)”Dispatches a command. Returns a promise that resolves to a CommandResult<T>.
- The handler registered for
command.typeruns. - If no handler, returns
{ ok: false, error: Error }and emitscommand.unhandled. - If the handler throws, returns
{ ok: false, error }and emitscommand.failed. - On success, returns
{ ok: true, value }.
const result = await runtime.command<{ id: string }>({ type: 'draft.save', payload: { content: '...' },})
if (result.ok) { console.log('saved with id', result.value?.id)}handleCommand(commandType, handler)
Section titled “handleCommand(commandType, handler)”Registers a command handler. The latest registered handler wins (overrides previous ones).
Returns an unsubscribe function.
runtime.handleCommand('draft.save', async (command) => { await fetch('/api/drafts', { method: 'POST', body: JSON.stringify(command.payload) }) return { saved: true }})install(module)
Section titled “install(module)”Installs a module:
- Runs
module.setup?.(runtime). - Subscribes any
events. - Registers any
commands. - Registers any
queriesand declared contracts. Contract operations must have matching handlers; inputs are validated before dispatch. - Emits
module.installed.
Returns when setup completes.
query(query) and handleQuery(type, handler, descriptor?)
Section titled “query(query) and handleQuery(type, handler, descriptor?)”Queries expose domain reads independently of UI. Register them through module.queries or handleQuery(). Dispatch with runtime.query<T>({ type, payload }). Results use { ok: true, value } or { ok: false, error }; missing and failed handlers emit query.unhandled and query.failed diagnostics. A query dispatch does not emit a domain event. Query handlers are responsible for read behavior.
discover() and module contracts
Section titled “discover() and module contracts”discover() returns a detached, serializable snapshot with version: 1, declared entity/event schemas, and currently registered query/command operations. An operation descriptor supplies its version, description, input/output schemas, expected error codes, and emitted event names. Descriptors are optional so existing modules continue to work.
module.contract contains a version and optional entities, events, queries, and commands maps. handleQuery() and handleCommand() accept an operation descriptor as a third argument. Declared input schemas are checked before handlers run; output and event schemas are descriptive and can be checked explicitly with validateKitValue().
The supported schema vocabulary is intentionally bounded: string with minLength, safe integer with a safe-integer minimum, finite number with an inclusive finite minimum, boolean, array with items, and object with properties, required, and additionalProperties. It is not a full JSON Schema implementation. Invalid input produces a KitOperationError with code invalid_input. Domain handlers may throw the same error class with their own code and optional detail.
{ type: 'number' } accepts fractional JavaScript numbers while rejecting NaN, both infinities and numeric strings. Both numeric schema kinds infer TypeScript number; runtime validation remains required. Integer contracts keep safe-integer checks. Compatibility permits integer-to-number containment when bounds fit and rejects general number-to-integer narrowing. Native form parsing, units and rounding stay domain policy. Finite arithmetic can overflow, and result validation does not undo earlier effects. Use a compatible installed candidate at both endpoints; older readers reject the new vocabulary.
Discovery is local runtime metadata. Domain hosts enforce authority on operations; listing a command does not grant permission. See Quill Notes for a shared-domain implementation.
start()
Section titled “start()”Calls module.start?.(runtime) for every installed module, in order. Emits runtime.started.
The shell calls this on connectedCallback. Call manually if you create a runtime outside <kit-shell>.
stop()
Section titled “stop()”Calls module.stop?.(runtime) for every installed module, in reverse order. Emits runtime.stopped.
The shell calls this on disconnectedCallback.
provide(token, value)
Section titled “provide(token, value)”Registers a provider. If the token already has a value, emits a provider.overwritten diagnostic before replacing.
inject(token)
Section titled “inject(token)”Returns the value registered for the token, or undefined. No throw — the caller decides how to handle missing providers.
createBoundary(options)
Section titled “createBoundary(options)”Creates a runtime-level boundary handle (separate from <kit-boundary> DOM elements). Returns a BoundaryHandle with a destroy() method.
Useful when integrating with frameworks that want to manage boundary lifetimes manually. Most apps use the DOM boundary instead.
onDiagnostic(handler)
Section titled “onDiagnostic(handler)”Subscribes to the diagnostic stream. Returns an unsubscribe function.
runtime.onDiagnostic((d) => { console.debug('[kit]', d.type, d.detail)})Connection and restoration definitions
Section titled “Connection and restoration definitions”Core also exports createKitLocalConnection, createKitRemoteConnection, KitRemotePeer, createKitSurfaceRestoration, kitSurfaceRecordKey, KitEnvironmentConnection, KitConnectionOwner, readiness/outcome types, stable environment/object/operation references, and version 1 resume/draft record types. Wrap a host-prepared runtime with the local adapter to establish readiness and reconciled observations; createKitRuntime() itself does not implement this connection protocol.
readKitResumeRecord(input, scope) and readKitDraftRecord(input, scope) validate decoded JSON and return valid, empty, invalid, unsupported_version, or scope_mismatch. Accepted records are cloned. Scope identifies the application, environment, participant partition, and optional workspace; nested references must stay in that environment. Drafts include an opaque base revision and working values. The readers reject non-JSON/executable state and unknown envelope fields; they do not load storage, authenticate, migrate, apply drafts, or replay commands.
Connection readiness is separate from view restoration and query loading. The local adapter gates calls by phase/generation, starts/stops only owned runtimes, and reconciles snapshots through explicit query invalidating events. Host preparation resolves trusted scope and required domain/store restoration. Successful commands complete; post-dispatch failures are unknown unless an explicit domain normalization convention establishes another outcome. Transient events cannot replay cursors, and a lost response cannot establish safe retry. The remote adapter wraps a host-supplied peer with a scoped handshake and registered-stream observation barrier. Deterministic tests prove reconnect gating, cursor replay/gaps, late reply suppression, and receipt recovery; headless surface restoration now handles scoped references, draft conflicts, and pending receipts without commands or automatic draft clearing. Core component descriptors/sessions and app /host, /attachment, /lit entries now supply initial browser participation and native draft initialization. Core full envelopes and app /delivery now add metadata-only exact-version resolution, pre-import compatibility, immutable registration, and staged replacement/recovery. All eleven supplied renderers now expose participation entries; production storage/transport and live publication remain separate integration work. See the core adapter example.
KitEventInput / KitEvent
Section titled “KitEventInput / KitEvent”type KitEventInput = { type: string context?: KitContext source?: Record<string, unknown> entity?: Entity interaction?: Record<string, unknown> payload?: Record<string, unknown>}
type KitEvent = KitEventInput & { id: string // crypto.randomUUID() timestamp: number // Date.now()}KitCommandInput / CommandResult
Section titled “KitCommandInput / CommandResult”type KitCommandInput<TPayload = Record<string, unknown>> = { type: string context?: KitContext source?: Record<string, unknown> interaction?: Record<string, unknown> payload?: TPayload}
type CommandResult<T> = | { ok: true; value?: T } | { ok: false; error: Error }KitContext
Section titled “KitContext”type KitContext = { surface?: string surfaces?: string[] feature?: string entity?: Entity [key: string]: unknown // arbitrary additional fields are preserved}
type Entity = { type: string; id: string }KitModule
Section titled “KitModule”type KitModule = { name: string contract?: KitModuleContract setup?: (runtime: KitRuntime) => void | Promise<void> start?: (runtime: KitRuntime) => void | Promise<void> stop?: (runtime: KitRuntime) => void | Promise<void> events?: Record<string, EventHandler> commands?: Record<string, CommandHandler> queries?: Record<string, QueryHandler>}ProviderToken
Section titled “ProviderToken”type ProviderToken<T> = { id: symbol description: string readonly type?: T // for type inference; never set at runtime}KitDiagnostic
Section titled “KitDiagnostic”type KitDiagnostic = { type: string timestamp: number detail?: Record<string, unknown>}Handler signatures
Section titled “Handler signatures”type EventHandler = (event: KitEvent) => void | Promise<void>type CommandHandler<T = unknown> = (command: KitCommandInput) => T | Promise<T>type DiagnosticHandler = (diagnostic: KitDiagnostic) => voidtype Unsubscribe = () => voidHelpers
Section titled “Helpers”defineKitModule(module)
Section titled “defineKitModule(module)”import { defineKitModule } from '@atheory-ai/kitsune'
const module = defineKitModule({ name: 'my-module', events: { 'note.saved': (event) => {} },})Pure type helper — returns the input unchanged. Use it so editors infer module types correctly.
createProviderToken(description)
Section titled “createProviderToken(description)”const StorageToken = createProviderToken<StorageService>('storage')Creates a unique token. The description shows up in diagnostics.
normalizeMetadata(input)
Section titled “normalizeMetadata(input)”const { event, command } = normalizeMetadata({ eventType: 'note.saved', commandType: 'dialog.close', context: { surface: 'editor' }, payload: { target: 'confirm' },})Used internally by the boundary; exported for adapters that build their own metadata bridges.
Reading the source
Section titled “Reading the source”Runtime coordination lives in packages/kitsune/src/core/index.ts; schema and discovery types live in packages/kitsune/src/core/contracts.ts.
Host-owned draft resolution
Section titled “Host-owned draft resolution”Core exports createKitDraftResolution with load, edit, resolve, save, inspect, state subscriptions and disposal. The host supplies the trusted scope/object/view/draft identity, versioned authoritative read, domain save mapping and atomic compare-and-exchange store. Resolve explicitly keeps a draft, chooses authority, or supplies merged values against the presented revision; all choices retain a draft until acknowledged save.
The version 1 bundle couples the draft and pinned submission. Persist prepared before dispatch, retain accepted/unknown outcomes across reload, and inspect original receipts without retry. Equal query values and missing receipts do not establish success. A completed acknowledgment identifies object/revision and exact submitted values; only that exact draft clears atomically. Newer edits, rejected saves and failed cleanup retain recoverable working data. Generation/disposal cancels obsolete work. Pass the validated bundle’s active draft to surface restoration, which stays read-only. See the core usage guide for adapter obligations and evidence.