Skip to content

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()
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
}

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.emitted diagnostic.
const event = runtime.emit({
type: 'note.saved',
context: { surface: 'editor' },
payload: { id: 'n_1' },
})
// event.id, event.timestamp are filled in

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()

Dispatches a command. Returns a promise that resolves to a CommandResult<T>.

  • The handler registered for command.type runs.
  • If no handler, returns { ok: false, error: Error } and emits command.unhandled.
  • If the handler throws, returns { ok: false, error } and emits command.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)
}

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 }
})

Installs a module:

  1. Runs module.setup?.(runtime).
  2. Subscribes any events.
  3. Registers any commands.
  4. Registers any queries and declared contracts. Contract operations must have matching handlers; inputs are validated before dispatch.
  5. 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() 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.

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>.

Calls module.stop?.(runtime) for every installed module, in reverse order. Emits runtime.stopped.

The shell calls this on disconnectedCallback.

Registers a provider. If the token already has a value, emits a provider.overwritten diagnostic before replacing.

Returns the value registered for the token, or undefined. No throw — the caller decides how to handle missing providers.

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.

Subscribes to the diagnostic stream. Returns an unsubscribe function.

runtime.onDiagnostic((d) => {
console.debug('[kit]', d.type, d.detail)
})

Full diagnostic catalog →

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.

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()
}
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 }
type KitContext = {
surface?: string
surfaces?: string[]
feature?: string
entity?: Entity
[key: string]: unknown // arbitrary additional fields are preserved
}
type Entity = { type: string; id: string }
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>
}
type ProviderToken<T> = {
id: symbol
description: string
readonly type?: T // for type inference; never set at runtime
}
type KitDiagnostic = {
type: string
timestamp: number
detail?: Record<string, unknown>
}
type EventHandler = (event: KitEvent) => void | Promise<void>
type CommandHandler<T = unknown> = (command: KitCommandInput) => T | Promise<T>
type DiagnosticHandler = (diagnostic: KitDiagnostic) => void
type Unsubscribe = () => void
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.

const StorageToken = createProviderToken<StorageService>('storage')

Creates a unique token. The description shows up in diagnostics.

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.

Runtime coordination lives in packages/kitsune/src/core/index.ts; schema and discovery types live in packages/kitsune/src/core/contracts.ts.

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.