Getting started
From nothing to a plugin installed on a Niles, in Rust.
Interface 0.6.
niles plugin dev,niles plugin check, installing from GitHub, and the plugin's setup panel, log, pages and widgets in the app are built. Not yet:niles plugin dev --live.
From nothing to a plugin installed on a Niles, in Rust, starting from the template. For JavaScript and Python, see other languages at the end.
1. What you need
-
Rust (stable, 1.85 or later, for edition 2024) with the WebAssembly target:
rustup target add wasm32-wasip2 -
The
nilesbinary, forniles plugin devandniles plugin check. Either from a Niles release, or built from source:cargo install --locked --git https://github.com/MarkNygaard/niles niles-bin -
Optional:
wasm-tools(cargo install wasm-tools) to look inside a component:wasm-tools component wit integration.wasmprints what it imports and exports.
2. Start from the template
On MarkNygaard/niles-addon-template,
press Use this template and make your repo, then clone it. You get:
niles-integration.toml # the manifest: id, name, settings, permissions
logo.svg # 24x24 mark shown on the Add-ons page
wit/niles-integration.wit # the interface, copied from Niles (0.6.0)
src/lib.rs # the add-on, with every export
Cargo.toml # crate-type = ["cdylib"], wit-bindgen
build.sh, build.ps1 # build and copy the component to integration.wasm
dev-settings.example.toml # copy to dev-settings.toml (gitignored) for local runs
.github/workflows/ci.yml # fmt, clippy, build and `niles plugin check` on each PR
.github/workflows/release.yml # a v* tag builds and publishes the releaseThe add-on in it keeps count of something: "add one" and "how many so far?" by voice, and a Count page in the menu with a button. That is one setting (what is counted), one tool, storage for the count, and one page with two buttons. It needs no account and no network, so it runs as soon as it's installed. Read it once, then keep what you need and delete the rest.
Make it yours:
- In the manifest, change
id(lowercase letters, digits and_, starting with a letter: it becomes your device source, tool prefix and secret namespace, so pick it once),name,description,authors,homepageandkeywords. - Change the crate
nameinCargo.toml. The build scripts read it. - Replace
logo.svg, the README and the LICENSE (the template's is MIT-0, so you owe it no notice).
The manifest says interface = "0.6" and min_niles = "0.6.0", the interface
the copied WIT is. Don't edit the WIT. To move to a newer interface later, copy
it from schemas/
and raise both.
src/lib.rs starts with
wit_bindgen::generate!({
world: "plugin",
path: "wit",
});which reads wit/ and writes, inside your crate:
Guest, the trait with one method per export, andexport!, which wires your type to it;- one module per import, under
niles::integration:::log,config,storage,http,devices,timers,events,notify,ui,mqtt,secrets,inbound,websocket,speech_stream; - the types the exports use (
DeviceState,Event,ToolDef,RenderContext,UiTree,ActionValue,ActionResult, and so on) at the crate root. Other types come from their interface, e.g.niles::integration::types::Device.
Every export must be there. The template's unused ones return nothing or an
error; the host API says what each one is for.
To see the generated code, cargo doc --target wasm32-wasip2 --open.
3. Build
./build.sh # or ./build.ps1 on Windowsbuilds the release component and copies it to integration.wasm, where a
release carries it and where niles plugin dev and niles plugin check look
first. Plain Rust with serde_json comes out around 150 KB.
4. Run it locally
Put values for your settings in dev-settings.toml (copy
dev-settings.example.toml), keyed like the manifest:
thing = "cups of coffee"
# secrets too, for local runs only; the template gitignores this file
api_key = "..."Then:
niles plugin dev .This builds nothing; it reads niles-integration.toml and a component, and
runs it in the same sandbox and with the same limits as a real Niles, against
a stand-in house. The component is the .wasm you name, or from a directory
the newer of integration.wasm and the newest
target/wasm32-wasip2/release/*.wasm; when both are there it says which it
took ("using …integration.wasm, which is newer than …"), so a stale
integration.wasm from your last release build never hides the build you
just made.
-
initruns, and log lines print as they happen; -
devices the plugin reports print as they change;
-
storage is kept in
.niles-dev/storage.json, so restarts keep it (the template gitignores.niles-dev/); -
timers fire on time;
-
HTTP goes out for real, checked against your manifest's permissions, so a missing permission fails here exactly as it would at home.
At its prompt:
> tools list the tools as the model sees them
> tool count {"add":1} call one, print the result
> set system/lamp {"on":true} call set-device
> event device_state office/door {"open":true}
> event presence away something happening elsewhere
> render count draw a page as text
> action count add press a control
> restart stop, new instance, initThe template's add-on answers like this:
> tool count {"add":2}
{"count":2,"of":"cups of coffee"}
> render count
Stack
Reading So far: 2 cups of coffee
Row
Button add "Add one" (primary)
Button reset "Reset" (secondary)
Text Or ask Niles: "add one", "how many so far?" (muted)Settings on the command line go over dev-settings.toml, typed by your
manifest: niles plugin dev . --settings thing=pancakes.
For a script or CI, --call count '{"add":1}' and --render count do the same as the prompt once init has run, and --dry-run
exits after them instead of staying up for timers and the prompt. A plugin
with MQTT brokers is waited for first: until a connection reports its first
status (at most 10 s), then a second for the messages the broker kept.
--wait 5 waits five seconds after init instead, --wait 0 not at all.
Two more flags, for dev only:
--allow-loopbacklets the plugin reach this machine where a setting's address is127.0.0.1,::1orlocalhost, over HTTP and MQTT, so a fake device can run beside it. Without it, and always in an installed plugin, loopback is refused.--time-zone Europe/Copenhagenis whatconfig.time-zoneanswers; this machine's zone by default.
Planned, not built yet: niles plugin dev . --live https://niles.example.com --token $NILES_API_TOKEN would install it on a running Niles instead, as a
development plugin marked "Development" on its card, reinstall it each time the
.wasm changes, and stream its log to your terminal. Until then, try it in the
app by releasing it and installing it (steps 6 and 7).
5. Check it
niles plugin check .(or niles plugin check you/your-repo once it is released, to check the
release exactly as an install would download it) checks everything an install
would: the manifest (including its surfaces,
settings and permissions), the logo, that the component targets
the world its manifest's interface names (niles:integration/plugin@0.6.x)
and exports every function, and its tools'
names, descriptions and schemas, asked for with tools() before any init,
and that there are keywords if there are tools. Fix whatever it reports before
you publish; it exits non-zero while there is anything to fix.
6. Release
Bump version in the manifest (and in Cargo.toml), commit, then tag the
same version:
git tag v0.1.0
git push origin v0.1.0The template's release.yml checks the tag against the manifest's version,
builds, runs niles plugin check, and creates a GitHub release with
niles-integration.toml, integration.wasm, logo.svg and niles-installed
attached. Details in publishing.
7. Install
In the Niles app: Settings → Add-ons → Available → Add-on from GitHub (at the end of
the page), paste https://github.com/you/your-repo and press Preview.
Niles downloads your latest release, runs every check niles plugin check
runs, and shows the name, authors, repo, version, description, logo and the
permissions in plain words, with the settings it will ask for. Install
installs exactly the files that preview downloaded, and the plugin starts. It
is on the Connected tab, in its group with a Custom badge and a status
line; its panel has your repo, the version and install date, the settings form
generated from your manifest, where each widget goes, the last lines of its
log, and buttons to turn it off, check for updates, roll back an update and
remove it. Once your repo has the topic niles-addon, people also find it
under Browse (the add-on library).
Fill in the settings and press Save: the plugin restarts with them, and the status line says how that went ("Not set up: needs API key" until every required setting has a value). Secret settings are saved one at a time, each in its own field. Your pages are in the menu, and your widgets on the front page or their room; open one to see it drawn.
A script can do the same through the config API, which restarts the plugin
with the new values. $NILES_API_TOKEN here is the key from Settings → API
access:
curl -X PATCH https://niles.example.com/config \
-H "authorization: Bearer $NILES_API_TOKEN" -H "content-type: application/json" \
-d '{"plugins": {"my_addon": {"thing": "pancakes"}}}'and secret settings through PUT /secrets/plugins.<id>.<key> with
{"value": "…"}, which accepts only keys your manifest declares as secret.
The log is at GET /plugins/<id>/log.
A preview is kept for 15 minutes. Installing needs Niles's database; without
one the preview says so. The same flow is reachable without the app:
POST /plugins/install/preview with {"repo": "you/your-repo"}, then
POST /plugins/install with the token (and sha256) it answered.
Other languages
Any language that builds a WebAssembly component for the plugin world
works. Below is the template's tool in JavaScript and in Python, without its
page. Each takes the template's wit/ and manifest, minus [[ui.menu]] and
ui = true.
Both toolchains import every interface in the world, whether the code uses it or not. On interface 0.6 that needs Niles 0.7.0 or newer: 0.6.0 does not link
speech-stream@0.6.0and refuses them. Rust imports only what it calls, so the template works on 0.6.0. Both snippets were built (jco 1.39, componentize-py 0.25.1) and run underniles plugin dev.
Every export must exist, so the unused ones are stubbed. Both runtimes are
large, so the manifest needs memory_mb = 128.
JavaScript (jco componentize)
jco turns WIT names into camelCase: call-tool is callTool, timeout-ms
is timeoutMs. An export that returns result returns its ok value and
throws its err; an import that returns result throws on err, with the
error variant in e.payload. An option is the value or undefined, and a
variant is { tag, val }.
import { get as setting } from "niles:integration/config@0.6.0";
import { get, set } from "niles:integration/storage@0.6.0";
function thing() {
const value = setting("thing");
return value?.tag === "text" && value.val.trim() ? value.val : "cups of coffee";
}
function load() {
return Number.parseInt(get("count") ?? "0", 10) || 0;
}
export function tools() {
return [
{
name: "count",
description:
`Keeps count of ${thing()}. Adds to the count when asked to, and says what it is. ` +
`Use it for "add one", "how many have I had" and "reset the count".`,
schema: JSON.stringify({
type: "object",
properties: {
add: { type: "integer", minimum: 1 },
reset: { type: "boolean" },
},
additionalProperties: false,
}),
},
];
}
// A returned string is the tool's `ok`; a thrown string is its `err`.
export function callTool(name, argsJson) {
if (name !== "count") throw `There is no tool called ${name}.`;
const { add = 0, reset = false } = JSON.parse(argsJson);
const count = (reset ? 0 : load()) + add;
try {
set("count", String(count));
} catch (e) {
// An import that returns `result` throws on `err`; the variant is e.payload.
throw `Could not save the count (${e.payload?.tag ?? e}).`;
}
return JSON.stringify({ count, of: thing() });
}
// The other exports, empty in an add-on that only offers a tool.
export function init() {}
export function setDevice() {
throw "Nothing here can be switched.";
}
export function onTimer() {}
export function onEvent() {}
export function render() {
throw "No pages.";
}
export function onAction() {
throw "No pages.";
}
export function onMqttMessage() {}
export function onMqttStatus() {}
export function onWebsocketMessage() {}
export function onWebsocketStatus() {}
export function authorizeUrl() {
throw "No accounts to connect.";
}
export function onCallback() {
throw "No accounts to connect.";
}
export function onWebhook() {
return { status: 404, contentType: undefined, body: new Uint8Array() };
}
export function stop() {}npm install @bytecodealliance/jco @bytecodealliance/componentize-js
npx jco componentize plugin.js --wit wit/niles-integration.wit \
--world-name plugin --disable http --out integration.wasm--disable http leaves out the JavaScript runtime's own fetch, which needs
wasi:http/outgoing-handler, which Niles does not provide; use the http
import instead. The result is about 12 MB, with the JavaScript engine inside.
Python (componentize-py)
componentize-py generates a wit_world package: implement the class
WitWorld, with snake_case methods. Return the ok value; raise
componentize_py_types.Err(value) for err. Imports that return result
raise Err too, with the error variant in e.value. A field that is a Python
keyword gets a trailing underscore: a device's class is class_.
import json
import wit_world
from componentize_py_types import Err
from wit_world.imports import config, inbound, storage, types
def thing() -> str:
value = config.get("thing")
if isinstance(value, config.SettingValue_Text) and value.value.strip():
return value.value
return "cups of coffee"
def load() -> int:
try:
return int(storage.get("count") or 0)
except ValueError:
return 0
class WitWorld(wit_world.WitWorld):
def tools(self) -> list[types.ToolDef]:
return [
types.ToolDef(
name="count",
description=(
f"Keeps count of {thing()}. Adds to the count when asked to, and says "
'what it is. Use it for "add one", "how many have I had" and "reset the count".'
),
schema=json.dumps({
"type": "object",
"properties": {
"add": {"type": "integer", "minimum": 1},
"reset": {"type": "boolean"},
},
"additionalProperties": False,
}),
)
]
# A returned str is the tool's `ok`; raising Err(str) is its `err`.
def call_tool(self, name: str, args_json: str) -> str:
if name != "count":
raise Err(f"There is no tool called {name}.")
args = json.loads(args_json)
count = (0 if args.get("reset") else load()) + args.get("add", 0)
try:
storage.set("count", str(count))
except Err as e:
# An import that returns `result` raises Err; the variant is e.value.
raise Err(f"Could not save the count ({type(e.value).__name__}).")
return json.dumps({"count": count, "of": thing()})
# The other exports, empty in an add-on that only offers a tool.
def init(self) -> None:
pass
def set_device(self, id, desired) -> None:
raise Err("Nothing here can be switched.")
def on_timer(self, id) -> None:
pass
def on_event(self, event) -> None:
pass
def render(self, surface_id, context):
raise Err("No pages.")
def on_action(self, surface_id, control_id, value, context):
raise Err("No pages.")
def on_mqtt_message(self, conn, topic, payload) -> None:
pass
def on_mqtt_status(self, conn, status) -> None:
pass
def on_websocket_message(self, conn, message) -> None:
pass
def on_websocket_status(self, conn, status) -> None:
pass
def authorize_url(self, callback_url, state) -> str:
raise Err("No accounts to connect.")
def on_callback(self, callback_url, query, person) -> str:
raise Err("No accounts to connect.")
def on_webhook(self, request) -> inbound.InboundResponse:
return inbound.InboundResponse(status=404, content_type=None, body=b"")
def stop(self) -> None:
passpip install componentize-py
componentize-py -d wit/niles-integration.wit -w plugin componentize app -o integration.wasmPure-Python libraries are bundled from your environment; libraries with C extensions do not build. The result is about 18 MB, with the interpreter inside.