What kd info prints.
kd — run and drive WebAssembly guest apps
STARTING A NEW PROJECT — USE `kd init`
New projects start from `kd init`. It is a CLI extension, not built in,
so add it once (from registry.knd.sh), then run it in an empty directory:
kd extension add init
mkdir my-game && cd my-game
kd init rust # a Rust guest; `cargo run` builds and plays it
kd init node # TypeScript that drives guests headlessly
kd init --list # every preset
If you are an AI agent or writing automation, do this rather than writing
the project's config by hand. It writes the Rust toolchain file, points
cargo and npm at kindling's registries, and picks the crate version — the
one fact that is easy to get wrong, and that fails late, at link or load
time, when it is. Nothing pins the runtime: `kd` runs a guest on a build
that provides what it was compiled against, fetching one if it must. It
writes into the working directory and refuses to overwrite anything that
is already there (`--force` overrides).
Libraries — 2D drawing, UI, and whatever else has been published — are
listed at https://registry.knd.sh, each with a page of its versions at
https://registry.knd.sh/crate/<name>. Look there before writing one
(see WRITING ONE IN RUST — THE GUEST CRATES).
WHAT A GUEST IS
A guest is a WebAssembly component that implements the kindling WIT
interfaces. Any language or toolchain that can produce a WebAssembly
component works. Note the distinction: kindling loads WASI-compatible
*components* (the WebAssembly component model — e.g. what a wasip2
target produces), not plain core wasm *modules*; a bare module will not
load. Print the interfaces with:
kd wit # the `guest` world
kd wit --out kindling.wit
kd wit --kindling-version 0.5.1
They are the build's, not kd's: the build a project pins, or the
default one (see INSTALLING A KINDLING BUILD), fetched the first time
and kept. Every build publishes its own beside it, at
knd.sh/<version>/kindling.wit.
Every guest exports an async `init()` — its main. It runs setup and
suspends at its first `.await`, and the host resumes its tasks as their
imports complete. A guest starts windowless; windows are spawned
explicitly, one or many, before or after init first stalls:
windows.spawn-window(config) -> result<window, string>
Spawn one and it is a *render* guest: the host drives each live window
through `render(window, target, dt)` (via WebGPU) and `on-window-event`,
both tagged with that window's id, delivering keyboard/mouse/touch/
gamepad input. Spawn none and it is a plain *worker*, its init task the
whole app, running headless until that task finishes. Neither mode is
declared up front — it is only whether a window exists.
Lifetime: the host tears a guest down once its init task has finished
*and* it holds no live window. Closing a window is a two-step handshake —
the host delivers `close-requested`, and the window actually closes when
the guest drops its resource — so closing the last window ends a guest
only if its main is also done. A windowed guest therefore keeps a task in
flight rather than returning from init; see FRAME LOOP below.
A render guest may also implement a `command(string) -> string` control
channel whose protocol is entirely guest-defined. Note: command() may be
called at any time, including BEFORE the first render — drivers rely on
this for deterministic setup (seeding, muting, enabling a fixed timestep),
so a guest should handle setup commands without assuming a frame has
already rendered (avoid lazily initializing that state inside render).
Both kinds share the same imports — the async ops (timers, fetch,
websocket, webrtc, the parent channel) work in either mode.
WRITING ONE IN RUST — THE GUEST CRATES
The crates a Rust guest is written against come from kindling's own
cargo registry, registry.knd.sh — so a project depends on them with
cargo, and installs nothing for them through `kd`:
# .cargo/config.toml
[registries.kindling]
index = "sparse+https://registry.knd.sh/crates/"
# Cargo.toml
[dependencies]
kindling = { version = "0.5.3", registry = "kindling" }
kindling-plus = { version = "0.5.3", registry = "kindling" }
EVERY CRATE THERE IS LISTED AT https://registry.knd.sh — look there
before writing something yourself. Each has a page of its own,
https://registry.knd.sh/crate/<name>, with every version and the
`kindling` each was built against. Among them:
kindling the world itself (below)
kindling-plus windows, input, preferences, project files
kindling-2d immediate-mode 2D: shapes, images, text, blending
kindling-egui egui, an immediate-mode UI, in a kindling window
`kindling` is the world itself: every imported interface, the generated
bindings, `kindling::value`, `kindling::path` (see PATHS ON WINDOWS), the
`app!`/`worker!` entry points, and `#[kindling::test]` (see TESTING A
GUEST FROM INSIDE ONE). Its version is the runtime's: `kindling` X.Y.Z is
what kindling runtime X.Y.Z provides, and it is the one crate whose
version names a runtime. A third
crate, `kindling-macros`, is published beside it and never named:
`kindling` depends on it and re-exports what it defines.
Every other crate is a library on a version of its own, built against
some `kindling` — which its page names for every version. Take versions
whose `kindling` is on your own `kindling`'s line (0.5.x with 0.5.x), or
cargo builds two worlds into one guest and their types will not meet.
`kindling-plus` is the ergonomic layer over the world — windows, input,
preferences, project files — and depends on `kindling`, so taking it
brings both. Then build the guest as a cdylib:
cargo build --target wasm32-wasip2 --release
They carry their WIT bindings ready-made, so this needs no `wit-bindgen`
and no copy of the interfaces. They also carry a `rust-version`: the
world's async exports need a toolchain whose `wasm-component-ld` knows
their intrinsics, and cargo says which one up front rather than leaving
it to the linker.
`kindling`'s version names a build, so a project stays on the kindling it
names until the version is changed — which is the point: a guest built against
one build's crates and run on another's runtime is a guest built against
a world its host does not have. `kd` runs it on a build that provides what
it imports (see INSTALLING A KINDLING BUILD).
FRAME LOOP
A guest keeps a task in flight by awaiting one of two per-frame signals.
Which one it picks decides whether its drawing lands a frame late, so it
matters:
runtime.tick resolves once per frame, AFTER the paint
runtime.next-frame -> f32 resolves BEFORE it, with that frame's dt
Draw *inside* `render` and `tick` is what you want — it is the async
heartbeat, and the thing that drives timers, channel recvs and tasks
spawned from render/command. Without some task looping on it, background
work never progresses.
Defer your drawing instead — record a frame in the async body, replay it
from `render`, which is how a macroquad-shaped loop maps onto this — and
await `next-frame`. Because it completes on the way *into* a paint, the
frame the body just recorded is the one `render` is then asked for. Await
`tick` for that and every frame reaches the screen one paint late.
Both resolve once per frame, on either side of the paint, and a guest may
await both. Nothing waits on `next-frame` unless a guest asks for it, and
a guest that doesn't pays nothing for it.
WASI SUPPORT
Guests get real WASI. Running natively (including `kd remote` and
the Node package's native mode), the WASI interfaces are fully hooked
up: stdin/stdout/stderr, clocks, random, environment, filesystem, and so
on all work. Ordinary language facilities that sit on WASI — printing to
stdout, reading the time, generating random numbers — behave normally;
there is no need to avoid them or stub them out. The host passes its true
working directory as PWD and the guest crate's export macros chdir to it,
so relative paths and current_dir() point where the host was invoked
(WASI itself has no cwd; raw-bindings guests can call adopt-host-cwd /
read PWD themselves).
PATHS ON WINDOWS. A guest names a file the way WASI does: `/`-separated,
under a root. On macOS and Linux that is the host's own path. Windows has
no single root, so every drive is mounted at `/<letter>`:
C:\Users\me\AppData\Roaming is /c/Users/me/AppData/Roaming
Everything kindling hands a guest is already in this form — PWD,
`dirs.data`/`config`/`cache`, the `fs` file dialogs and watch events,
`process.which` — so it works with `std::fs` and `kindling::fs` alike.
Everything a guest hands kindling may be in either form: `fs`, the
`process`/`pty` command and working directory, and `components` filesystem
roots take `/c/…` and `C:\…` both. `std::fs` takes only `/c/…`.
Paths that reach a guest any other way are still in the host's form: an
environment variable (`%APPDATA%`), a command-line argument, a config
file, text a user typed. Convert those before `std::fs` sees them, and
convert back for anything leaving kindling — a native program's arguments
(`process` passes `args` through untouched), text shown to a user:
let save = kindling::path::from_host(&typed); // C:\… -> /c/…
let arg = kindling::path::to_host(&save); // /c/… -> C:\…
Both are the identity on macOS and Linux, so call them unconditionally. A
UNC path (`\\server\share\…`) has no `/<letter>` to live under: `fs`
reaches it in its own form, `std::fs` does not reach it at all. Drives are
mounted when a guest starts; one attached later is reached through `fs`
but not `std::fs` until the guest restarts. `/` itself is not a directory
on Windows — `std::fs::read_dir("/")` finds nothing, and a drive-less
absolute path (`/tmp`) names no file — so start from a drive, `dirs`, or
the working directory.
A guest's `argv` is its own program name, then whatever followed `--` on
the command line — never the host's. `kd run guest.wasm` is one word,
`kd run guest.wasm -- a b` is three. That matters to the one kind of guest
that reads arguments: a test harness takes argv[1] as a filter, so a guest
handed the host's command line would see its own path there and match no
test at all.
Running in a browser (web mode), everything that can work does:
stdout/stderr go to the browser console, and stdin, clocks, random,
environment, and arguments are all available. Only capabilities the
platform genuinely lacks are missing — the filesystem, TCP/UDP sockets,
and outgoing HTTP — and a guest that actually calls one of those gets a
clear named error rather than silent misbehavior.
A guest that wants to adapt up front can query the `capabilities`
interface: a best-guess, OS-derived report of what the host supports —
filesystem (none / preopened-dirs / full), environment/arguments/clocks/
random/stdio/sockets, and which input-event kinds fire here (gestures are
macOS/iOS only, etc.). It also carries permission-gated capabilities
(`permission-status` / `request-permission`) for features like web device
orientation that need an explicit user grant.
HDR DISPLAY OUTPUT
HDR display output is opt-in at window creation:
window-config.dynamic-range = extended
Native macOS Metal negotiates rgba16float, enables EDR, and labels its
surface extended-linear-sRGB. Other backends and offscreen remote capture
currently fall back to SDR. The default remains standard range.
Read window.format() before building pipelines, then window.display-info()
before rendering. `extended` means the floating-point EDR output path is
configured; it does NOT mean the monitor currently has HDR headroom.
`current-headroom` and `potential-headroom` are relative to SDR white (1.0),
not nits. They refresh as the window moves or display brightness changes.
Clamp/tone-map linear output to current-headroom. Keep ordinary UI at or
below 1.0, preserve highlight values above 1.0, and do not gamma-encode an
extended-linear-sRGB target. A headroom of 1 is the SDR-display fallback.
The format is fixed for the window's lifetime, so moving across monitors
does not invalidate pipelines. Query each window's format/info separately;
getPreferredCanvasFormat remains the first window's format for compatibility.
The WebGPU canvas.configure import does not reconfigure host-owned windows;
use window-config for output negotiation.
Headless PNG screenshots are SDR and cannot verify physical HDR output.
Physical HDR output takes a real HDR display, and someone looking at it;
ordinary guest automation should still use remote.
AUDIO
The host owns the audio device; a guest queues interleaved f32 samples
through the `audio` interface. The guest must synthesize or resample to
the host's sample-rate() and channels() itself — the host does not
resample. Pace production with queued-frames(): on each render, read how
many frames are still buffered and queue only enough to top the buffer
up to a small target — around 120 ms ahead, i.e. roughly
sample-rate() * 0.12 frames. That keeps the device fed (no dropouts)
without growing latency without bound. Under the remote driver, audio is
disabled: queue() discards samples and queued-frames() reports 0, so the
same pacing code runs unchanged, just silently.
Each guest has its own buffer and they are mixed, so queueing never disturbs
another guest's. A guest plays only if its policy allows `audio:play`; without that `state` reads `unavailable`, and a
`media` player's pictures play without its sound.
POLICY
A policy document says what a guest may reach outside its sandbox, action by
action: which paths `fs` may read, which URLs `fetch` may ask for, which
programs `process` may start. Without one a guest has full access, as it
always has, so nothing here is needed to run anything.
It is a tool for integrators, not a security boundary. Kindling treats the
wasm it runs as trustworthy: a policy says what an app is meant to do, and
does not hold against code working to get around it (see LIMITS below).
WHERE A DOCUMENT GOES
The format is the same everywhere, and always arrives as JSON text. The `kd`
commands and `kd.*` options below need kd 0.9 or newer:
kd run app.wasm --policy policy.json a window or a worker
kd run app.wasm --web --policy policy.json the served page
kd run app.wasm --watch --policy policy.json kept across every reload
kd build app.wasm site/ --policy policy.json baked into the static site
// a driver: `kd remote`, `kd remote --web`, and the Node package in
// either mode. Only the named form of `instantiate` takes one.
const guest = await kd.instantiate("app.wasm", {
policy: JSON.stringify(document),
});
// an extension's script, as JSON text like `instantiate`'s
await kd.run("app.wasm", kd.args.slice(1), { policy: JSON.stringify(document) });
kd.serve("app.wasm", { policy: JSON.stringify(document) });
kd.build("app.wasm", "site", { policy: JSON.stringify(document) });
// a page of your own, loading the web runtime
const channel = await start_with_policy(bytes, forceWebgl, json);
// a guest, for what it starts: `None` keeps what the guest already holds
components::spawn(&wasm, &SpawnOptions {
policy: Some(json),
..SpawnOptions::open()
}, None);
runtime::replace(source, args, keep, Some(json)).await;
A document that cannot be read stops `kd run`, rejects the `instantiate` or
`start_with_policy` promise, and fails the spawn or `replace`. A guest never
starts with more than was meant.
These take no document yet, and run with full access: a compiled app (its
command line is the guest's own) and a command from `kd bin`. An extension's
`kd.remote` script can pass one, through `instantiate`.
`kd build` writes the document into `index.html`, and refuses a build whose page
would ignore it. It only checks that the document is JSON: the runtime reads the
rest when the page loads, so a wrong field shows up there, in the console, and
the guest does not start. The document is as editable as the rest of the site.
THE DOCUMENT
{
"version": 1,
"statements": [
{ "effect": "allow", "actions": ["fs:read", "fs:list"], "resources": ["/data/**"] },
{ "effect": "deny", "actions": ["fs:*"], "resources": ["/data/secrets/**"] },
{ "effect": "allow", "actions": ["net:http"], "resources": ["https://api.example.com/**"] },
{ "effect": "allow", "actions": ["clipboard:read"] }
],
"wasi": {
"filesystem": [{ "path": "/data", "read-only": true }],
"network": false,
"environment": false
},
"sealed": false
}
`version` is required and must be 1. Everything else may be left out.
A document allows nothing until a statement allows it, and a deny beats any
allow, in any order. That goes for windows too: a guest that opens one needs
`window:spawn`, so `{ "version": 1 }` is a guest that can compute and print,
and no more. Input to a window it has, drawing with `webgpu`, and talking over
`channels` are never gated.
`actions` holds action names, a family (`fs:*`), or `*`.
`resources` holds globs, and what they are matched against depends on the
action (see ACTIONS). Left out, the statement covers every resource, and also
the actions that have none. Given, it does not cover an action with no
resource, so `{ "effect": "allow", "actions": ["*"], "resources": ["/x/**"] }`
allows no `clipboard:read`.
* any run without a `/`
** any run at all
/x/** also `/x` itself, so a rule on a tree covers listing it
a/**/b also `a/b`: `/**/` may be no directories at all
A deny inside a tree holds for the tree: a listing or `fs.watch` leaves denied
names out, and `fs.remove` refuses a directory holding anything it may not
remove.
`sealed` freezes clocks, fixes randomness and hides machine identity, for a
guest whose runs should not differ. Once sealed, every child is too.
A mistyped ACTION is logged as a warning and ignored, the same as one newer
than this build, so look for `policy: ignoring action` in the output when a
rule seems to do nothing. A mistyped FIELD is an error, as is another
`version` or anything that is not JSON: a field could narrow a statement, and
ignoring it would widen what was written.
ACTIONS
A denied call answers `not-allowed-error`, or where an interface has no error,
the same absence as a platform without the thing. So code with a path that
reads the clipboard still loads, and pasting pastes nothing.
Files. The resource is a path:
fs:read fs.read, and a runtime.replace from a path
fs:list fs.read-dir
fs:stat fs.stat
fs:write fs.write
fs:create-dir fs.create-dir
fs:remove fs.remove
fs:watch fs.watch
opener:path opener.open-path
opener:reveal opener.reveal
Network and links. The resource is a URL:
net:http fetch, and a media url
net:websocket websocket.connect
opener:link opener.open-url
Programs. The resource is a command:
process:spawn process.spawn, process.output
process:which process.which
pty:open pty.open
Inside the guest's own storage. The resource is a path in the bundle, or a key:
bundle:read bundle
scratch:read scratch
scratch:write scratch
Everything else takes no resource, so only a statement with no `resources`
covers it:
fs:pick the fs file dialogs
dirs:data dirs
dirs:config dirs
dirs:cache dirs
net:webrtc webrtc.create-peer
clipboard:read input's clipboard
clipboard:write input's clipboard
storage:opfs opfs, and files dropped on a page
storage:local web-storage
storage:session web-storage
audio:play audio, and a media player's sound
media:open media.open, probe, snapshot
media:decode video-decoder.open
input:gamepad input.poll-gamepads, vibration
input:orientation device-orientation permission
window:spawn windows.spawn-window
window:position moving a window
window:level restacking a window
window:fullscreen going fullscreen
window:cursor-grab grabbing the cursor
window:keyboard-grab taking the keyboard's system shortcuts
window:capture-protection window.set-content-protected
window:app-presence windows.set-app-presence
component:spawn components.spawn
component:spawn-worker components.spawn-worker
runtime:replace runtime.replace
runtime:catch-exit runtime.catch-exit-requests
startup:configure startup
`webgpu`, `channels`, `capabilities` and `policy` itself have no actions. To
remove an import outright rather than answer it, see `kindling-trap`.
A guest can ask first. `policy::allowed(action, target)` asks about
one action, and `capabilities.supports` answers `denied` when no resource
could pass.
HOW RESOURCES ARE READ
A path is judged after resolving `..` and symlinks, so a rule on `/data/**` is
not escaped by `/data/../etc/passwd` or by a link out of `/data`. A relative
one, in a rule or a call, is relative to the launch directory. `fs.remove` is
judged by where the path is, since it removes the link rather than what it
points at. `fs.write` and `fs.create-dir` also need their action on any
directory they have to create on the way. Rules ignore case on macOS and
Windows. On Windows a guest's path reads `/c/Users/me`, and `C:\Users\me` in a
rule means the same.
A URL is compared in normal form, parsed as the network will parse it: scheme
and host lowercased, default port, credentials and a host's trailing dot gone,
`..` resolved. The scheme and host of a rule are lowercased to meet it. On the
web a relative URL is resolved against the page first. A URL the parser rejects
is refused.
A command must be allowed as written or where it resolves to on the host's
`PATH`, and must not be denied by its written name, its base name or that
path. Name programs bare or by absolute path: a relative one, or one holding
`..`, is refused, as is setting `PATH` for the program.
WASI
WASI is separate and answers only to the `wasi` block, which is coarse because
a preopen is a directory: denies and globs have nothing to map to. `statements`
never affect WASI, and the `wasi` block never affects a kindling interface, so
a guest using both `std::fs` and `kindling::fs` needs both written down.
filesystem directories to preopen, each { "path", "read-only" }
network sockets and name lookup
environment the host's environment variables
Left out, the block gives nothing: `std::fs` finds no files, sockets fail, and
the environment is empty but for `PWD`. A directory that does not exist is an
error. When the launch directory is outside every root, the guest's working
directory is its first root, so relative `std::fs` paths start there. The web
has no WASI filesystem or sockets; `environment` still applies.
CHILDREN AND REPLACEMENT
A guest holds a chain of documents, and a call goes through only if every one
allows it. A top-level document is the first link. So a guest can only hand on
less than it holds, never more:
policy: None exactly what the spawner holds
policy: Some(document) what both allow
A document starts from nothing, so a child's must name everything that child
may do, and it cannot add anything the spawner lacks. A spawner with no document
of its own is unlimited, and a child's document is then the whole of its limit.
`runtime.replace` follows the same rule, so an updater can hand over to what it
fetched with less than it has. `sealed` and `read-only` stick once set, WASI
directories intersect as subtrees, and `network` and `environment` must be true
at every link.
`SpawnOptions::open()`, `hosted(window)` and `sealed()` in the guest crate are
shorthands for these.
BUILDING ONE IN A GUEST
`policy.wit` (see `kd wit`) has a function per action, so a new action is a new
function and nothing compiled against the old ones changes:
use kindling::{components, policy};
let document = policy::new_document();
document.allow_essentials();
document.allow_fs_read("assets/**");
document.deny("fs:*", Some(&["assets/private/**".to_string()]));
document.allow_net_http("https://api.example.com/**");
document.wasi_filesystem("assets", true);
let child = components::spawn(&wasm, &components::SpawnOptions {
policy: Some(document.to_json()),
..components::SpawnOptions::open()
}, None);
`allow-essentials` is what an ordinary child needs and nothing that reaches
outside it: `window:*`, `component:*`, `scratch:*`, `media:*` and `input:*`.
`allow` and `deny` take any action by name, including one newer than the guest's
bindings. There are no per-action deny helpers. `parse-document` reads JSON back
into a document, and `wasi-filesystem`, `wasi-network`, `wasi-environment` and
`seal` set the rest.
EXAMPLES
A game: a window, sound and controllers, its own saves, and one API.
{
"version": 1,
"statements": [
{ "effect": "allow", "actions": ["window:spawn", "window:fullscreen", "window:cursor-grab"] },
{ "effect": "allow", "actions": ["audio:play", "media:open", "input:gamepad"] },
{ "effect": "allow", "actions": ["bundle:read", "scratch:*"] },
{ "effect": "allow", "actions": ["fs:read", "fs:write", "fs:list"], "resources": ["saves/**"] },
{ "effect": "allow", "actions": ["net:http"], "resources": ["https://api.example.com/**"] }
]
}
An editor: the whole project but its secrets, two named tools, and links that
open only as web or mail. `std::fs` sees `assets`, read-only, which must exist.
{
"version": 1,
"statements": [
{ "effect": "allow", "actions": ["window:*", "clipboard:*", "fs:pick"] },
{ "effect": "allow", "actions": ["fs:*"], "resources": ["project/**"] },
{ "effect": "deny", "actions": ["fs:*"], "resources": ["project/.git/**", "project/**/.env", "project/**/*.pem"] },
{ "effect": "allow", "actions": ["process:spawn", "process:which"], "resources": ["git", "rustfmt"] },
{ "effect": "allow", "actions": ["opener:link"], "resources": ["https://**", "mailto:*"] }
],
"wasi": { "filesystem": [{ "path": "assets", "read-only": true }] }
}
A blocklist: everything, less what was singled out. `net:webrtc` is denied on
its own because it has no URL for a resource rule to match.
{
"version": 1,
"statements": [
{ "effect": "allow", "actions": ["*"] },
{ "effect": "deny", "actions": ["process:*", "pty:*", "opener:*"] },
{ "effect": "deny", "actions": ["net:*"], "resources": ["https://internal.example.com/**", "wss://internal.example.com/**"] },
{ "effect": "deny", "actions": ["net:webrtc"] }
],
"wasi": { "filesystem": [{ "path": "/" }], "environment": true }
}
A plugin handed to a child: its own files in the bundle, nothing outside, and
the same result on every run.
{
"version": 1,
"statements": [
{ "effect": "allow", "actions": ["bundle:read"], "resources": ["plugins/formatter/**"] }
],
"sealed": true
}
A web page: no `wasi` block, since the browser has little to give it, and the
page's storage named one kind at a time.
{
"version": 1,
"statements": [
{ "effect": "allow", "actions": ["window:spawn", "window:fullscreen", "audio:play"] },
{ "effect": "allow", "actions": ["storage:opfs", "storage:local"] },
{ "effect": "allow", "actions": ["net:http", "net:websocket"], "resources": ["https://api.example.com/**", "wss://live.example.com/**"] }
]
}
LIMITS
A permitted program can do anything. `process:spawn` and `pty:open` start
programs with the user's whole authority, and arguments and environment are the
guest's to set (`git -c core.sshCommand=…`, `LD_PRELOAD`). `opener:path` is
the same, since opening a file runs its handler.
A redirect is judged after it happens. `net:http` checks the URL asked for and
where it ended up, so an off-list redirect's answer never reaches the guest, but
the request has been made by then, so an allowed server with an open redirect
can be used to send one elsewhere. On the web a `media` url's redirects cannot
be seen at all, so its pictures can come from off the list; natively they are
refused.
Paths are judged, then used. A guest that can swap a symlink between the check
and the call, through a writable WASI directory, can win that race. Give a
guest a writable WASI directory or path-scoped `fs` rules over the same tree,
not both.
`sealed` covers WASI's clocks and randomness, `runtime`'s clock and OS name, and
gamepads. A window's geometry, theme and display can still differ between
machines.
`opener:link` with no resources opens any scheme, and a link's handler is a
program. Name schemes to narrow it, as the editor above does. The web opens only
`http`, `https` and `mailto` regardless.
Unicode normalization is not considered. macOS treats composed and decomposed
accents as one name, and a deny written in one form does not match the other.
Keep denied names ASCII, or prefer allow rules.
On Windows, a path with no single name is refused under a policy: a stream
(`file.txt::$DATA`), a trailing dot or space, and any UNC path, since one can name
a local drive under another name. 8.3 short names are resolved when the file
exists. Windows behaviour has only been exercised under Wine.
A document is limited to 64 KiB and a resource pattern to 4 KiB. A call on a
resource over 16 KiB is refused, as is a path behind more than 32 dangling
symlinks.
MEDIA (VIDEO AND SOUND FILES)
The `media` interface plays files: the host demuxes and decodes, the
guest drives a player and draws its pictures wherever it likes.
let player = media::open(&Source::Bytes(mp4)); // or Url, or Feed
player.play(); // immediate, any time
while let Some(e) = player.recv().await { … } // ready, state, frame, …
player.copy_frame(&texture); // in render: the
// picture showing now
There are no ready-made controls: play, pause, seek, set-volume,
set-muted, set-rate and set-looping take effect at once, and position()
is exact between frames. copy-frame copies the current picture into a
texture of the guest's own — rgba8unorm or bgra8unorm, with copy-dst and
render-attachment usage, the video's size — and returns its time; a
`frame` event says a new one is showing (at most one waits).
A `feed` source is a file the guest hands over in pieces as the player
asks (`want` → provide(offset, bytes)), in any order: an MP4 with its
index at the end is asked for its end first, and an answer that never
comes is asked for again. Use it for a file too big to hold, or one
arriving over a connection.
Natively: MP4 with H.264 (every profile) and AAC-LC, decoded in pure
Rust on a thread per player; the sound is mixed into the same output as
the `audio` interface, with the sound as the clock. On the web the
browser plays it (`supports` says what it can); a feed is gathered whole
before it plays, and the player is `blocked` until the person's first
click or key if the browser will not start sound before one. probe and
snapshot read a file without playing it. Under the remote driver and in
a web worker there is no player (open fails, as `failed`).
kd run media-demo.wasm -- clip.mp4 the fixture: a player in a window
VIDEO DECODER (A LIVE STREAM, A PICTURE AT A TIME)
The `video-decoder` interface (since 0.5.12) decodes compressed
pictures the guest already has in hand — a remote desktop's window, a
camera, a game streamed from elsewhere — to show each as soon as it
lands. A file to play is `media`'s: this has no clock, no buffering, no
container, no sound.
let d = video_decoder::open(&Config { codec: "avc1.42E01F".into(), … })?;
d.decode(&Chunk { timestamp, key, data }); // one access unit
while let Some(e) = d.recv().await { … } // frame(info), failed
d.copy_frame(&texture); // the picture waiting
A chunk is a bare access unit (for H.264, Annex B, the SPS and PPS before
each key one; or set `description` to an avcC record and send them
length-prefixed). The first chunk after `open`, `reset` or `configure`
must be key — others before it are dropped. At most one picture waits:
the next replaces it, and `dropped` counts those never copied, so a guest
that falls behind shows the latest. `queued` is the chunks not yet
decoded — when it grows, skip to the next key one. A `failed` event
means `configure` again.
copy-frame takes the same textures `media`'s does (rgba8unorm or
bgra8unorm, copy-dst and render-attachment usage), and a picture stays
until the next: copying it again copies the same.
Every platform decodes H.264 (`avc1.*`): natively in pure Rust, on a
thread per decoder (under the remote driver too); on the web the
browser's WebCodecs `VideoDecoder`, in hardware where it has it, so also
whatever else it takes — `supports(config)` says. A browser without
WebCodecs fails `open`.
kd run decoder-demo.wasm the fixture: a stream decoded and checked
RUNNING A GUEST (interactive — for a human at the machine)
kd run path/to/guest.wasm native window (or a headless worker
run, if it spawns none)
kd run path/to/guest.wasm --web serve for a browser (prints a URL)
If you are an AI agent or writing automation: do NOT launch the native
window and do NOT try to control the `--web` page yourself — use the Node
package below (or `kd remote`). Remote drives the same guest code
headlessly and deterministically; if it works under remote, it works
when a human runs it natively.
A guest that opens no window is a *command*, and a command answers with an
exit code. `kd run` exits with whatever the guest asked for:
runtime.exit(code) the status this run ends with
It records rather than terminates — the run still ends when the guest's
`main` returns, so set it and then return. Say nothing and a clean finish
is 0 and a trap is 1.
Reach for it rather than `std::process::exit`: WASI's exit takes a
*result*, not a number, so on wasip2 every non-zero status collapses to 1
before it ever leaves the guest.
A guest with something to save can ask to hear about being asked to end,
rather than ending there and then:
runtime::catch_exit_requests(true);
spawn(async {
let reason = runtime::exit_requested().await;
save().await;
runtime::exit(0); // and return from init, holding no windows
});
quit Cmd+Q, the app menu, the Dock, a logout. macOS only
interrupt ctrl-c
terminate SIGTERM, SIGHUP, the Windows console closing. Be quick
A second request forces the exit whatever the guest is doing, so a hung guest
can't keep anyone in. Requests within 100 ms count as one, because one signal
can arrive by two routes. To stay after all, `runtime::decline_exit()` makes
the next one ask again. A logout that was asked is cancelled by asking.
Call it from `init` on, from the top-level guest. A child, a remote driver's
guest and the web never hear anything, and a guest arriving through
`runtime.replace` or `--watch` starts with it off. A guest that declines every
time can only be killed, so a policy has to allow `runtime:catch-exit`.
`kd run` and `kd.run` wait for the guest; a `kd` older than 0.9.1 hands the
shell back while it saves.
An ordinary `wasm32-wasip2` command runs too — anything exporting
`wasi:cli/run` rather than a guest world. That is what a crate with no
kindling dependency compiles to, so `kd run` works as cargo's runner for
a whole workspace and not only the guests in it (see `cargo test` below).
No window, no frame loop, nothing it could not ask for; and it is bound by
the same WASI `exit`, so it can only answer 0 or 1.
HOT RELOAD (`--watch`) AND WHAT SURVIVES IT
kd run guest.wasm --watch rebuild the file, the guest swaps in
kd run guest.wasm --web --watch same, by reloading the page
A reload is a *fresh guest*: new instance, new memory, `init` from the top,
windows closed and respawned. Nothing the old instance held survives —
which is what makes a reload trustworthy, and what loses your window
position, camera, and open panel every time you save.
The `scratch` interface is the exception: a small keyed byte store that
lives in the host, kept across a `--watch` reload (both natively and on
web, where the reload client hands it over the page reload) and dropped on
anything else — closing the app, a plain `kd run`, a manual refresh, a
deployed page. So it is a development convenience, and a `get` may always
come back `none`: keep a default, and put anything the user would miss in
a real store (`fs` under `dirs`, or `web-storage`) instead.
One store per process (per tab on web), shared with any components the
guest spawns, so keys are the only namespacing — take a prefix nobody else
will (`my-lib/thing`, or your app's reverse-DNS id).
`kindling-plus` wires the common case up for you, two calls — the string
names the window, so a multi-window guest keeps one geometry per window:
window::restore_geometry("main", &mut config); // in init, before open
window::remember_geometry("main", &event); // in on_window_event
RUNNING A GUEST AS A CHILD IN YOUR WINDOW
A guest can lend one of its windows to another guest, which runs unmodified
and need not know it is a child. Its `spawn-window` returns the lent window,
and it gets only what you allow:
let child = components::spawn(&wasm, &SpawnOptions {
policy: Some(document.to_json()), // optional: see below
..SpawnOptions::hosted(window.id())
}, None);
// in your render, once child.ready():
child.call("render", &encode_values(&[
Value::U64(id), Value::Resource(target.token()), Value::F32(dt),
]))?; // then draw over it, if you like
// in your on_window_event, for the events you pass on:
child.deliver_window_event(id, &event)?;
What its policy denies answers as it would on a platform without
them: `not-allowed-error`, or `none`. So a library with a path that reads the
clipboard still loads, and pasting pastes nothing. It may set the window's
title, cursor, IME and fullscreen; it cannot move or restack it, or take the
keyboard's system shortcuts. `child.finished()` says it has ended, which is
when you drop it. A trap comes back as an error from `call`, and yours carries
on. A child spins on your thread, so one that never returns still stalls you.
COMPOSING COMPONENTS INTO A GUEST (`--with`)
A guest may import interfaces the host doesn't provide — a physics engine,
a renderer, a plugin API of your own. Pass the components that export them
and kindling links them in before the guest runs:
kd run guest.wasm --with palette.wasm
kd run guest.wasm --with palette.wasm --with physics.wasm
kd run guest.wasm --with palette.wasm,physics.wasm (same thing)
Each component's exports are wired to the guest's matching imports (by
name, or by a semver-compatible one). Whatever neither side provides stays
a host import and is satisfied the usual way — so a plugged-in component
can itself import kindling interfaces and WASI, and gets them like the
guest does. Components are not linked to each other: compose those two
into one component first if one needs the other.
This works everywhere a guest is launched, and the same everywhere:
kd run guest.wasm --with p.wasm native window
kd run guest.wasm --with p.wasm --web served page (composed before
serving — the browser is handed
one finished guest)
kd build guest.wasm site/ --with p.wasm baked into the static site
kd.instantiate("guest.wasm", { components: ["p.wasm"] }) remote/Node
With `--watch`, the components are re-composed into every reload; rebuild
a component itself and restart. Composing into an archive guest composes
its `main.wasm` and leaves the rest of the zip alone.
In a browser, a composed edge is bridged by hand, so keep the interfaces
between components to ordinary WIT values (records, strings, lists,
resources) — a `future`/`stream` on that edge composes and runs natively
but traps on the web.
ARCHIVE GUESTS (a guest plus its files, in one zip)
Anywhere a guest `.wasm` is accepted — `kd run <path>`, `--web`, and the
remote `kd.instantiate(...)` — you can pass a zip archive instead. The
archive must contain `main.wasm` at its root (the component to run); every
other file becomes the guest's read-only `fs` tree, served from memory.
my-app.zip
├── main.wasm the component (required, at the root)
├── hello.txt reachable as fs::read("hello.txt")
└── data/nested.bin reachable as fs::read("data/nested.bin")
So `fs::read`/`fs::read-dir` return files from the archive instead of from
the launch directory — identically on native and in the browser (the web
runtime unzips in-page). Scoping is unchanged (relative paths only, no
`..`). The regular WASI filesystem is unaffected. A bare `.wasm` still runs
exactly as before, reading files relative to the working directory.
TESTING A GUEST FROM INSIDE ONE — `cargo test`
A guest's tests are ordinary Rust tests, run by ordinary `cargo test`.
One line of the guest changes:
#![cfg_attr(not(test), no_main)] // was: #![no_main]
and then:
#[cfg(test)]
mod tests {
#[test]
fn arithmetic_still_works() {
assert_eq!(2 + 2, 4);
}
#[kindling::test]
async fn reads_its_manifest() {
let bytes = kindling::fs::read("Cargo.toml".into()).await.unwrap();
assert!(!bytes.is_empty());
}
}
cargo test
`cargo test` builds the crate as a test binary — which is a component
like any other — and hands it to `kd run`, which runs it as a guest.
`app!` notices the test build and gives the run to libtest instead of to
the app, so `#[test]`, `#[ignore]`, `cargo test <filter>`, `-- --exact`
and `-- --list` all mean exactly what they always mean.
The `#![no_main]` line has to become conditional because a test build
*does* have a `main`: libtest's, which is the harness being run.
What makes this worth doing rather than testing on the host: a test can
await the world against the real host, not a mock. Write it `async` and
mark it `#[kindling::test]`, which is `#[test]` around
`kindling::test::block_on`. Blocking is legal because the tests run inside
the world's async `init`; a synchronous task (what a `wasi:cli/run`
command is, and so what libtest's `main` would otherwise be) traps
instead.
What a test can await is what the host finishes on its own: `fs`,
`fetch`, `runtime::sleep`, sockets. What it cannot await is a *frame* — a
blocked test is a guest the driver cannot step, so `runtime::tick` and
`runtime::next_frame` never resolve and the test hangs. Spawning a window
works; rendering into it does not. For frame stepping, synthetic input
and screenshots, drive the guest from outside with the Node package
(below) instead.
A test target with no `app!` of its own — an integration test under
`tests/`, or a library crate's unit tests — ends with one line instead:
kindling::test_main!();
A crate with no `kindling` dependency at all needs none of this. Its test
binary is an ordinary `wasi:cli/run` command, and `kd run` runs one as
readily as a guest — so `cargo test` works in the pure-logic crates of a
workspace without their taking a dependency they do not otherwise want.
What they give up is the reason for the above: a test that awaits the
real host.
Two things differ from libtest on a native target, both because
`wasm32-wasip2` compiles with `panic = "abort"`:
- A failing assertion ends the whole run rather than one test, so the
tests after it do not run and no summary prints. The run says so as
it goes down, and the name of the test that died is the last thing
printed before the panic; output is left uncaptured by default so its
message survives (`RUST_TEST_NOCAPTURE=0` to capture anyway).
`cargo test -- --skip <test>` carries on past a known-bad one, and a
test that would rather report a failure than end the run returns a
`Result`, as libtest has always allowed.
- `#[should_panic]` cannot work, and libtest reports those tests as
`ignored` rather than running them.
Tests run one after another: a guest is single-threaded, so there is no
`--test-threads` to raise.
AUTOMATED TESTING AND AI AGENTS — THE NODE PACKAGE (recommended)
The `@kindling/remote` Node package drives guests headlessly from
scripts: deterministic frame stepping, synthetic input, screenshots —
natively in the Node process, or inside a real browser.
It comes from kindling's own npm registry, so npm fetches it the way it
fetches anything else and `kd` is not involved:
# .npmrc
@kindling:registry=https://registry.knd.sh/npm/
# package.json
"dependencies": { "@kindling/remote": "^0.5.1" }
The version is the runtime's, not kd's (see VERSIONS, under INSTALLING A
KINDLING BUILD): the package drives the build of the same number.
To follow nightlies instead, mind the range: a plain `^0.5.1` matches no
nightly at all, because npm excludes prereleases from a range that has
none. `^0.5.1-alpha` is the form that keeps resolving to the newest
nightly of 0.5.1.
The package carries a compiled native addon, so it is really several
packages: a wrapper, plus one per platform (`@kindling/remote-darwin-arm64`
and friends) listed as optional dependencies. npm reads their `os`/`cpu`
from the registry and downloads only the one that matches. A platform no
build has been packed on yet gets a sentence saying so, not a crash.
The API — every method is async; write always-await scripts and they run
unchanged in both modes:
import { connect } from "@kindling/remote";
const session = await connect({
mode: "native", // or "web": drives a real browser (needs puppeteer)
root: ".", // base directory guest paths resolve against
});
const guest = await session.instantiate("guest.wasm", 640, 400);
// also accepts bytes: instantiate(arrayBufferOrTypedArray, w, h)
// and a named form, which is how you compose components in (`--with`):
// instantiate("guest.wasm", {
// width: 640, height: 400, components: ["palette.wasm"],
// policy: JSON.stringify(document), // see POLICY
// });
await guest.render(); // advance exactly one frame
await guest.render(90, 1 / 60); // 90 frames of 1/60 s each
await guest.input({ type: "key-down", key: "enter" });
await guest.input({ type: "pointer-moved", x: 100, y: 50 });
await guest.gamepads([{ id: 0, buttons: [1, 0], axes: [0.5, 0] }]);
const reply = await guest.command("..."); // guest-defined protocol
await guest.send("bytes or string"); // the guest's byte channel
const msg = await guest.tryRecv(); // Uint8Array | null
await guest.resize(320, 200);
await guest.screenshot("frame.png");
const ids = await guest.windows(); // live window ids, ascending
await guest.capabilities({ sockets: true }); // spoof what the guest sees
await guest.pumpIfWoken(); // see PACED LOOPS below
await guest.close();
await session.close(); // always, and before any process.exit()
Several windows: a guest can spawn as many as it likes, and
render/resize/screenshot/input take the id as an optional trailing
argument — omitted, they address the first live one, which is all most
scripts have. `windows()` lists them.
await guest.render(1, 1 / 60, 2); // render window 2
await guest.screenshot("w2.png", 2);
INPUT EVENTS (both the Node package and `kd remote`)
input() takes one event, or an array of them. `type` says which; every
other field is optional and defaults sensibly (a position to 0, a button
to "left", a touch to "moved"). The names are the WIT's, kebab-case:
key-down, key-up key, text, repeat, modifiers
keyboard-input the same, with state: "pressed" | "released"
cursor-moved x, y
mouse-down, mouse-up button, x, y, modifiers
mouse-input the same, with state: "pressed" | "released"
mouse-wheel deltaX, deltaY (or dx, dy), deltaMode:
0 pixels | 1 lines | 2 pages
mouse-motion deltaX, deltaY: raw movement, not a position
— what mouse-look reads with the pointer
grabbed
cursor-entered, cursor-left
touch phase: "started" | "moved" | "ended" |
"cancelled", id, x, y, force
focused focused (default true)
modifiers-changed modifiers
ime-commit text
ime-preedit text, activeRange: { start, end }
gamepad-connected, id — the gamepads themselves are
gamepad-disconnected gamepads([...]), not input()
cursor-grab-changed mode: "none" | "confined" | "locked"
key a WIT `key` name ("enter", "space", "arrow-up", "key-w",
"digit3", "shift-left" — `kd wit` lists them all), or one
letter or digit as sugar ("w", "3")
button "left" | "right" | "middle" | "back" | "forward"
modifiers { shift, ctrl, alt, logo, altGraph }, each a boolean
Older names still work: pointer-moved, pointer-button, pointer-entered,
pointer-left, scroll, keyboard, ime-text. There is no pointer-down —
pressing a button is mouse-down. An unknown type is refused with a
message listing these.
The Node package also ships all of this as TypeScript, in
node_modules/@kindling/remote/index.d.ts.
PACED LOOPS (both the Node package and `kd remote`)
A guest's network work (websocket, webrtc, fetch) completes on real
wall-clock time, and the guest only sees a completion when it is pumped.
render() pumps, so a tight loop of renders is usually enough — but an
arrival landing in the gap *between* your renders would otherwise wait out
the rest of the frame. `pumpIfWoken()` delivers it immediately and reports
whether it pumped, so a loop pacing itself at a real frame rate should call
it between frames. It is what a windowed host does when a socket wakes its
event loop, and it does not advance the frame clock — `runtime.tick` still
ticks once per render.
Determinism: frames advance only when you call render, with exactly the
dt you pass; input queued via input() is seen by the guest on its next
render. Replaying the same inputs and dts reproduces the same frames.
Corollary: command() mutates guest state immediately and input() queues
events, but neither draws anything — screenshot() captures the most
recently RENDERED frame. Call render() after commands/input, or the
screenshot will still show the old frame.
That is one render, not two — but only for a guest whose frame body runs
on `runtime.next-frame` (the pre-paint signal). A guest that instead draws
from a body looping on `runtime.tick` publishes its frame *after* the paint,
so its pixels trail what command() reports by one render; step it twice, or
move it to next-frame.
Screenshots: native mode reads back the render target; web mode captures
the guest's canvas. Both write a PNG to the given path, pixel-identical
for the same frames.
DRIVING WITHOUT NODE
kd remote script.js
Runs a driver JavaScript file directly, no Node needed. Same API without
connect(): the driving API is on a `kd` global, and
`kd.instantiate(source, width?, height?)` resolves to a guest handle
(handle methods are synchronous here, but an always-await script written
for the Node API runs unchanged). `screenshot(path)` writes a PNG, and
`input()` takes the events listed under INPUT EVENTS.
The whole API is TypeScript too, with no Node needed to get it:
kd remote --typings --out kd-remote.d.ts
Put it beside the script and start the script with
// @ts-check
/// <reference path="./kd-remote.d.ts" />
and an editor completes `kd`, the handle's methods and every event type,
and flags a misspelled one before it is a run.
The arguments after the source can be given as an options object instead —
`kd.instantiate(source, { width, height, root, components, policy })` — which
is how you compose components into the guest (see `--with` above), and how you
limit what it reaches (see POLICY):
await kd.instantiate("guest.wasm", { components: ["palette.wasm"] });
A guest's network work (websocket, webrtc, fetch) runs on a background
runtime and its results arrive between your calls — but this engine has no
event loop or timers, so a tight script can finish before a connection or
reply lands. Use `kd.sleep(ms)` to let real time pass, then step the guest
to pump what arrived:
const g = await kd.instantiate("guest.wasm");
kd.sleep(300); // give the connection time to establish
g.render(); // pump: deliver the completion to the guest
let msg; // poll for a reply (sleep is synchronous — no await)
for (let i = 0; i < 50 && !(msg = g.tryRecv()); i++)
{ kd.sleep(50); g.render(); }
`kd.sleep` is `kd remote`-only. In the Node package (and `--web`) there is
a real event loop, so wait with `await new Promise(r => setTimeout(r, ms))`
between renders instead. `pumpIfWoken()` (see PACED LOOPS) works here too,
and beats a bare render for delivering something that has just landed.
To time something, use `performance.now()`: milliseconds since the script
started, with sub-millisecond resolution, from a monotonic clock. It is the
same call as in Node and the browser, so a benchmark runs unchanged under
all three. `Date.now()` is whole milliseconds and follows the system clock.
const t0 = performance.now();
for (let i = 0; i < 1000; i++) g.render();
kd.print(`${((performance.now() - t0) / 1000).toFixed(3)} ms/frame`);
kd remote --web
Serves a page exposing the same `kd` global, to drive from the browser
devtools console or any browser automation tool. Each guest appears in a
canvas (id "guest-<n>") — screenshot it from your automation tool. Files
under the working directory are served by path, so kd.instantiate("...")
works with the same relative paths.
JUST RUNNING A GUEST — `kd-run`
`kd` is the developer's tool, and it does not run guests itself: it execs
the runtime from the installed build. That runtime is a binary you can
also use directly, and it is all you need if running guests is all you
do:
kd-run game.wasm # a window, or a headless worker
kd-run game.zip # an archive guest, files and all
kd-run game.wasm --with plug.wasm
kd-run game.wasm --watch
kd-run tests.wasm -- --nocapture # a plain wasip2 command runs too
This *is* what `kd run` runs — `kd` finds it in the installed build and
execs it, so the two behave identically. What it leaves out is everything
`kd` does *around* running a guest: serving for a browser, building static
sites, the Node package, CLI extensions, and installing builds.
It needs no installed build itself: it is the runtime, so there is nothing
for it to look up. It is a build's `run` component (`kd target add run`
puts one in the kindling directory).
`kd-remote <script>` is its sibling, carrying the JS engine that drives
guests from a script — what `kd remote <script>` execs. It is much the
larger of the two (V8), which is why they are separate: running a guest
should not mean downloading an engine to script it with. (`kd` itself
carries a much smaller JS engine for extension entry scripts — a different
job: a few lines of glue, where this one steps a guest frame by frame.)
HEADLESS MACHINES (CI, CONTAINERS, SERVERS)
Guests run on a machine with no sound card and no GPU — `kd run`, `cargo
test` through it, and `kd remote` alike.
Audio: with no sound card, or no ALSA installed at all (Linux), a guest
runs silent; what it queues is dropped. Nothing to install.
GPU: with no Vulkan or GL, guests run on a stub GPU that draws nothing,
and a warning on stderr says so. Everything else is real — resources are
created, shaders are parsed and validated, buffers hold what is written —
so workers, logic tests and the command channel behave as on a GPU. Render
passes do nothing, so a screenshot is blank. For real pixels without a
GPU, install Mesa's software Vulkan, which is found before the stub:
apt-get install mesa-vulkan-drivers # Debian, Ubuntu
For a job whose tests are about what is drawn, refuse the stub, so a
missing driver fails the run instead of passing it blank:
KINDLING_GPU=require cargo test
WAYLAND OR X11 (LINUX)
A Linux desktop can have two display servers. Windows go to Wayland when
`$WAYLAND_DISPLAY` is set, and to X11 otherwise. Some programs only see
X11 windows. Choose for one run:
KINDLING_DISPLAY=x11 ./game # through XWayland
KINDLING_DISPLAY=wayland kd run game.wasm
A display server that is not there (`x11` with no `$DISPLAY`) is warned
about and ignored. Other platforms have one, and ignore it.
A program that knows what it needs can ask for itself, from `pre-init`:
async fn pre_init(&self) {
let _ = kindling::startup::set_display_server(DisplayServer::X11);
}
`pre-init` runs before `init` and before the event loop exists, for the
top-level guest only. It may await things like reading a saved setting, but
there is nothing to draw on yet: no windows, no frames. `$KINDLING_DISPLAY`
outranks it, `auto` included, so whoever launches a program has the last word.
LOGGING
The host is quiet by default: warnings and errors, nothing else. Turn it
up with one directive, in the usual `RUST_LOG` syntax:
KINDLING_LOG=1 kd run guest.wasm # the host's own INFO chatter
KINDLING_LOG=debug kd run guest.wasm
KINDLING_LOG=kindling_host=trace,wgpu=warn kd run guest.wasm
KINDLING_LOG=off kd run guest.wasm # not even errors
`$RUST_LOG` works too, and a directive of your own sits on top of a `warn`
floor — naming one target does not silence errors from the others. A
guest's own stdout/stderr is not logging and is never filtered.
On the web there is no environment, so the same directive comes from the
page instead — a global set before the runtime loads, or the URL:
<script>globalThis.KINDLING_LOG = "debug";</script>
http://localhost:8080/?log=debug (bare `?log` means `?log=1`)
A web worker (`spawn-worker` on web) is its own realm with its own console
in devtools; it inherits the page's setting because the host tags the
worker script URL with it, so worker logs follow the page's verbosity
without being set separately.
TIPS
- Multiple guests can run side by side in one session; each is isolated.
- send()/tryRecv() drive the same byte channel a parent guest would (the
guest's `parent::recv`/`parent::send`), so a worker guest runs unchanged
under the remote driver — the driver plays the parent. Payloads are
opaque bytes; strings are sent as UTF-8.
- The command() channel is the intended hook for test-only controls in a
guest (e.g. switching to a fixed timestep, or dumping internal state).
Send setup commands before the first render() for deterministic runs —
guests are expected to handle that ordering.
- Network-driven guests (websocket/webrtc/fetch) are pumped only when you
step them (render/send/tryRecv), and their I/O completes on real wall-
clock time. Under `kd remote` interleave `kd.sleep(ms)` with steps (see
above); with the Node package, `await`ing between renders is enough since
Node's event loop keeps the I/O turning.
- Web mode prefers WebGPU (recent Chrome) and falls back to WebGL2 where
it is missing (e.g. many phones). Add `?webgl` to the page URL to force
WebGL2. The Node package passes the required flags to puppeteer
automatically.
INSTALLING A KINDLING BUILD
A **build** is what neither cargo nor npm can carry, published at knd.sh
under a version as three **components**, installed one at a time:
run kd-run, the native runtime that runs guests per platform
remote kd-remote, which drives guests from scripts per platform
web the web runtime a browser loads once
VERSIONS. There are two numbers, on two release cycles. `kd --version` is
the command line's own (0.4.0, say), and you upgrade it by reinstalling kd.
A build — the runtime — has its own (0.5.1), which `kd versions` lists and
`kd install` fetches, and the Rust crates and the npm package carry that
same number: `kindling = "0.5.1"` is the library for runtime 0.5.1. A kd
fetches and runs builds released after it as readily as before, so the
two numbers do not track each other — a newer kd is only needed for a
new command, or an extension that asks for one. A build can say which: it
names the oldest kd that can use everything it offers, and an older kd warns
when it picks that build, then carries on with what it can do.
A build carries its half of this guide, as it carries its WIT: everything
about guests and the runtime, kept beside the installed build and published
at https://knd.sh/<version>/kindling-info.txt. `kd info` prints that half for
the build this directory uses, chosen as `kd wit` chooses, and
`kd info --kindling-version 0.5.1` for another. For a build published without
one, or when it cannot be fetched, kd prints the copy it was built with, and
says so at the top.
A native component takes a platform — `run@linux-arm64`, or a Rust target
triple after the `@` — and without one means this machine's. `kd target`
manages them; the everyday commands are shortcuts over it:
kd install # every component for this machine, and
kd install 0.3.0 # make it the default
kd versions # what is installed here (= kd target ls)
kd versions --remote # what has been published
kd default 0.3.0 # switch the default
kd uninstall <version> # all of it (= kd target rm all)
kd target add web remote # components, for the default build
kd target add run@win32-x64 # another platform's, for kd compile
kd target rm remote --kindling-version 0.2.0
kd target ls --remote --kindling-version 0.3.0 # what one build offers
So a version can be partly installed, and that is fine: a command that
needs a component the chosen build lacks fetches it and says so.
SIGNED. A build's manifest — the list of its files and their SHA-256s —
is signed by one of kindling's release keys, and kd uses no build whose
manifest is not: a signature that does not match, or a key it does not
know, and nothing is installed. A version is signed once all of its
platforms are published, so the newest can be unsigned for a while after
it appears; kd says so. For a bucket of your own (KINDLING_DIST_URL),
KINDLING_ALLOW_UNSIGNED=1 lets an unsigned build through — never a
wrongly signed one.
Listings are newest first and show the ten most recent; `-n <N>` or
`--all` for more.
A version is one of three shapes, told apart by looking at it: a release
(`0.5.1`), a nightly (`0.5.1-alpha.202609261430.g6535cc6`, stamped in UTC
to the minute and tagged with its commit), or a git hash.
A nightly is a semver prerelease because the string does more than name a
directory: the `kindling` crate and the npm package published with that
build carry the same version. So a project that follows nightlies writes the shape once —
`0.5.1-alpha` — and keeps resolving to the newest nightly of that version
without editing it.
The **libraries a guest is written against are not in a build.** They
are on kindling's own cargo and npm registries, registry.knd.sh, so a
project depends on them with cargo and npm and installs nothing through
`kd`. The `kindling` crate and the Node package are published with each
build at its version; every other crate on its own (see WRITING ONE IN
RUST — THE GUEST CRATES):
# .cargo/config.toml
[registries.kindling]
index = "sparse+https://registry.knd.sh/crates/"
# Cargo.toml
kindling = { version = "0.5.3", registry = "kindling" }
kindling-plus = { version = "0.5.3", registry = "kindling" }
`kd init` writes these for the build this machine defaults to (see
STARTING A NEW PROJECT).
**Which build a command uses**, the first of these that applies:
1. `--kindling-version <v>`, or `$KINDLING_VERSION` for a whole shell or
CI job.
2. The project's `kindling-toolchain.toml` (see below) — unless it does
not provide what the guest imports (below).
3. For a guest: the default if it provides what the guest was compiled
against, else the newest installed build that does, else the newest
published build that does — fetched, and said so.
4. The default.
5. With nothing installed at all, the newest published build — fetched,
and made the default.
A compiled guest names the `kindling:core` it was built against in its
imports (`kindling:core/webgpu@0.1.0`), and a build of runtime X.Y.Z
provides `kindling:core@X.Y.Z` — except every build up to 0.2.3, which
provides 0.1.0. With KINDLING_AUTO_INSTALL=0, step 3 fetches nothing: if
no installed build fits, it stops and names one to install instead —
this guest imports kindling:core@0.1.0, and no installed kindling build
provides it — it needs runtime 0.2.3 or older.
install one: kd install 0.2.3
A version named in step 1 is used even if it does not provide what the
guest imports, with a warning: that is someone saying they know better. A
project's pin that does not is passed over for step 3, with a warning to
move it. That is a pin the crates have outgrown: `kindling = "0.5.2"` in
Cargo.toml lets cargo take 0.5.3 once it is published, and a guest built
against 0.5.3 may load on a 0.5.2 runtime natively and then fail in a
browser. `--any-runtime` skips step 3.
`kd` does not carry a runtime of its own and will not borrow one: a build
with no component for this machine's platform is an error naming what it
does publish.
THE PROJECT FILE — `kindling-toolchain.toml`
Like `rust-toolchain.toml`, for kindling. Commit one and the project runs
on the build it names, on any machine, whatever that machine's default:
[toolchain]
version = "0.3.0" # exactly this build
components = ["run", "web"] # installed the first time they're needed
targets = ["win32-x64"] # run@ these too, for kd compile --target
It is found by walking up from the working directory. The version is
exact, not a range: moving to a newer kindling is a commit. `kd install`
with no version, in a project, installs what the file names and leaves
the machine's default alone. `kd init` does not write one: a guest says
which `kindling:core` it was compiled against, and that chooses the build
(step 3), so a project only needs the file to hold a runtime still.
WHERE BUILDS LIVE
In this machine's data directory — `~/Library/Application
Support/kindling` (macOS), `~/.local/share/kindling` (Linux),
`%APPDATA%\kindling` (Windows), or `$KINDLING_HOME`. `kd home` prints
which:
versions/<version>/
manifest.json the build as published: what it offers
kindling.wit the WIT it implements (`kd wit`)
run/<platform>/ kd-run each component is a directory
remote/<platform>/ kd-remote with a component.json,
web/ the web runtime written last
Every downloaded file is checked against the SHA-256 its manifest records,
and a program's own hash is checked again before `kd compile` copies it
into an app.
Published, a build is `web.tgz`, `run/<platform>.tgz` and
`remote/<platform>.tgz` under `/<version>/`. The web files are also
published loose there, uncompressed — not for `kd`, which has the archive,
but so a page can import an older version's runtime straight from
`/<version>/kindling_web.js`. The manifest's `web_boot` says which calling
convention that runtime expects. Builds published before the components
were split are not installable.
From `web_boot` 2 on, the web runtime comes twice: `kindling_web`, which
runs on WebGPU alone, and `kindling_web_gl`, the same with the WebGL2
fallback — most of its size (about 0.67 MB against 1.1 MB, compressed).
A page asks the browser for a WebGPU adapter before downloading either,
and fetches the GL one only without it, or with `?webgl`. The pages `kd`
serves and `kd build` writes do this themselves; a page of your own
loading a runtime should too:
const webgpu = !!(await navigator.gpu?.requestAdapter().catch(() => null));
const { default: init, start } =
await import(webgpu ? "./kindling_web.js" : "./kindling_web_gl.js");
CLI EXTENSIONS (adding your own `kd` command)
An extension is a package that adds a command. Add one and it is part of
the command line from then on:
kd extension add rolly.zip # the manifest says its name
kd extension add init # by name, from registry.knd.sh
kd rolly build --fast # everything after the name is its
kd extension ls # what is installed
kd extension pack rolly # back out again, as ./rolly.zip
kd extension rm rolly
While building one, run it straight from its directory instead — same in
every respect, but nothing is installed:
kd extension run ./rolly build --fast
Extensions live in the shared kindling directory (one per machine, see
INSTALLING A KINDLING BUILD), one directory each. clap matches `kd`'s own
commands first and hands anything else to the extension untouched — so an
extension can never shadow a `kd` command, and `kd rolly --help` reaches
the extension rather than being read by `kd`.
A name instead of a path fetches the extension from kindling's registry,
registry.knd.sh — the newest version this kd can run, or `init@0.1.0` for
one — checked against the SHA-256 the registry lists. `./init` is always
the path. `kd publish` (itself an extension: `kd extension add publish`)
is how one gets there. $KINDLING_REGISTRY_URL names another registry.
THE PACKAGE
rolly.zip a zip, for handing to somebody
extension.json the manifest
main.js the entry
rolly.wasm the body: an ordinary kindling guest
anything else free-form; kd.dir names it
Distributed as a zip, installed unpacked — so every file in it has a real
path to hand to `kd run`. `kd extension pack` is `add` backwards, taking
an installed extension (or a directory you have just built) and writing
the one file to send: packing is deterministic, so the same package always
gives the same bytes and an archive can be named by its hash.
A plain directory is accepted directly too, which is the build-and-try
loop with no zipping step in it. `kd extension ls` reads one small JSON
file per extension, so a listing is instant however large the packages
are.
{
"name": "rolly",
"about": "roll a guest up into a static site",
"version": "0.1.0",
"main": "main.js",
"kd": "0.1"
}
An extension is always `kd rolly`. A command of its own, without the
`kd`, is a binary (see BINARIES).
TWO TIERS
The body of an extension is an ORDINARY KINDLING GUEST — not a component
in a world maintained only for extensions, but a guest like every app,
running against the same world `kd wit` prints. So it has fs, dirs, fetch,
process, pty, sockets, and every capability kindling gains from now on,
for free, because there is no second world to add them to.
// main.js — the whole of an extension whose work is a guest
kd.exit(await kd.run("rolly.wasm", kd.args.slice(1)));
Which build runs it is the guest's to say, in the kindling:core it
imports: kd.run picks one that provides that, the way `kd run` does, and
prints what it chose and anything it has to download first.
The JS is the tier that works with NOTHING INSTALLED. A guest needs a
runtime, which comes from an installed build — so an extension that is
only a guest is useless on a fresh machine, and that is not a corner case:
`kd init` is the first thing a person runs. The entry script runs on an
engine inside `kd` itself, and covers what `kd` can already do unaided:
kd.args, kd.dir, kd.cwd argv; the package; where kd ran
kd.cli(spec).parse() the arguments, parsed by clap
kd.version, kd.platform this kd; this machine
kd.print, kd.eprint, console.* output
kd.exit(code) the exit code, stopping there
kd.env(name) one environment variable
kd.fs.* read, text, write, mkdir,
readdir, stat, remove
kd.spawn({program, args, …}) -> Promise<code | captured>
kd.run(wasm, args, opts) -> Promise<code>; runs a guest
(opts: cwd, with, watch, policy)
kd.remote(script, opts) -> Promise<code>; drives guests
kd.serve(wasm, opts) -> {url, port, run()}
(opts: port, host, with, policy)
kd.build(wasm, out, opts) a static site for a guest
(opts: with, unpack, policy)
kd.wit({version}), kd.info() a build's guest world; this guide
kd.runtime.list() builds installed here
kd.runtime.published() builds published, to install
kd.runtime.default() / .setDefault() which one commands fall back on
kd.runtime.install() / .uninstall() add and remove them
kd.runtime.ensure() resolve one, downloading if none
The rule those follow: anything `kd` can do, an extension can do. The
bottom half of that list is `kd versions`, `kd install`, `kd uninstall`,
`kd default`, `kd build`, `kd remote`, `kd wit` and `kd info` — the same
library calls the commands make, under the extension's own name, so an
extension that manages runtimes or generates bindings does the work the
way `kd` does rather than shelling out to it.
The command line is parsed the way kd's own is — by clap — from a spec,
so an extension's help, errors and "did you mean" are every kd command's:
const m = kd.cli({
about: "roll a guest up into a static site",
args: {
guest: { positional: true, required: true, help: "the .wasm to roll" },
out: { short: "o", default: "site", help: "where to write it" },
watch: { short: "w", flag: true, help: "rebuild on every change" },
},
subcommands: { serve: { args: { port: { type: "integer" } } } },
}).parse();
m.guest, m.out, m.watch, m.$subcommand?.matches.port
parse() prints help, the version (the manifest's) or a mistake the way
clap does and ends the script with clap's code; tryParse() returns the
same instead. Arguments are keyed exactly as the spec writes them, typed
as it says (`type`, `flag`, `count`, `multiple`, `choices`), and checked
as they are parsed — ranges, requirements, conflicts, groups, `env`
fallbacks, and a `validate` function of the script's own. kd.d.ts has
every key, and types the matches from the spec.
kd extension typings --out kd.d.ts the whole of it, as TypeScript
That last one is worth doing once per extension: put the file beside
`main.js`, start the script with
/// <reference path="./kd.d.ts" />
and an editor completes the API and catches a typo before it is a run.
No HTTP, no hashing, no sockets: those are the guest's, where the world is
maintained anyway. Everything that starts a process is a promise, so two
guests can run at once — which a blocking `kd run` could never do:
const [a, b] = await Promise.all([
kd.run("rolly.wasm", ["serve"]),
kd.run("rolly.wasm", ["connect", target]),
]);
WHICH VERSION
The manifest names one: `kd`, the CLI's own version, which a person
installs and upgrades. It gates the whole `kd` global, and is checked both
when the extension is added and when it runs, because `kd` can be
downgraded under one already installed.
Which kindling *build* runs the extension's guest is not the manifest's
to say: the guest says it, in the kindling:core it imports, and kd.run
picks a build that provides that (fetching one if it must). Nothing is
looked for until a guest is about to run, so an extension that is only
JS works on a machine with nothing installed.
A requirement is a minimum, written plainly (`0.2`, `0.2.0`), and the
prerelease tag is ignored — so a nightly satisfies the line it is on.
The smallest extension is a manifest and a script, with no build step at
all. For one whose work is a guest, the loop is:
cargo build --target wasm32-wasip2 --release
cp target/wasm32-wasip2/release/rolly.wasm ./rolly/
kd extension run ./rolly -- --help
That `--` matters: `kd extension run` reads flags of its own, so a leading
`--help` is answered by `kd` rather than reaching the extension. Anything
after a plain argument is already the extension's (`kd extension run
./rolly build --fast` works), and once it is installed the question does
not arise — `kd rolly --help` is the extension's from the first word.
BINARIES (a guest as a command of its own)
A binary is a guest — a `.wasm` component or a `.zip` app, anything
`kd run` takes — installed under a name, with a shim that runs it:
kd bin add rolly.wasm # named for the file: `rolly`
kd bin add app.zip --name hello # or as you say
kd bin add rolly@0.2.0 # by name, from registry.knd.sh
kd bin ls # what is installed
kd bin rm hello
The guest is copied into `bins/<name>/` in the shared kindling directory,
and the shim into `bin/<name>` beside it: `kd run <guest> -- "$@"`, so
every argument reaches the guest and its exit code is the command's. Put
that directory on PATH and `rolly build` runs it:
export PATH="$(kd home)/bin:$PATH"
It runs on an installed build, chosen as `kd run` chooses. Unlike an
extension, there is no script and no `kd` in front: a binary is just the
guest.
INSTALLING `kd`
curl -fsSL https://knd.sh/install.sh | bash
On macOS and Linux, that is the whole of it: the newest `kd`, checked
against its published hash and kindling's signature (it needs ssh-keygen,
which those systems have), in ~/.local/bin. On Windows, download it from
https://knd.sh/builds. `kd` carries none of the runtime, so it needs
nothing else installed; it downloads what it needs on first use (see
INSTALLING A KINDLING BUILD).
There is deliberately no `kd npm` or project scaffolding. The crates and
the Node package come from registries now, so setting a project up is two
config files and a dependency line — the kind of thing a CLI extension can
write, without being part of `kd` itself.
SHIPPING AN APP — `kd compile`
`kd compile` turns a guest into one executable that runs it and nothing
else — the build's `kd-run` with the guest inside it:
kd compile game.zip # -> ./game
kd compile game.wasm -o dist/Game
kd compile game.wasm --with plug.wasm
The result needs no kindling install. It has no command line of its own:
every argument it is given is the guest's, `--help` included, and the
guest's exit code is the program's. `--with` components are composed in
when it is compiled.
It is made from the build `kd run` would use for the guest (or
`--kindling-version`), so the app behaves exactly as it did there. On
macOS it is signed ad hoc, which runs locally; sign it with your own
identity to hand it to anybody else.
For other platforms, name them — kindling's names or Rust target triples:
kd compile game.zip --target win32-x64 # -> ./game.exe
kd compile game.zip --target linux-x64,linux-arm64 -o dist
kd compile game.zip --target all -o dist # dist/game-<platform>
Each platform's runtime is the build's `run` component for it
(`run@win32-x64`), fetched the first time it is wanted and kept with the
rest of the build — see INSTALLING A KINDLING BUILD. A project's
`kindling-toolchain.toml` can list its `targets` to have them ready.