Documentation

Guides for installing, setting up, and using Karakuri. The same guides ship inside the server and open under Help in the web interface.

Getting started

Flows

Dashboards

Devices and integrations

Administration

Installing Karakuri

Karakuri is one server program with a built-in web interface. Install it once, create an admin account, and open http://<host>:8080. This guide covers each way to install it and how to point it at SQLite, PostgreSQL, or MySQL.

Choosing a method

Method Use it when
Docker Compose You run containers. One file, restarts after a reboot, updates with a pull.
Docker Compose with PostgreSQL The same, with a PostgreSQL container instead of SQLite.
Release archive Linux or macOS without containers. Installs a system service that updates itself.
Unpacked, without installing Windows, or trying Karakuri from a directory.
From source You work on Karakuri itself.

Every method listens on port 8080 for the web interface and API, and on 9443 for remote agents. Each starts on SQLite unless you configure another database.

Docker Compose

Save the compose.yaml from the repository into an empty directory:

services:
  karakuri:
    image: grmrgecko/karakuri:latest
    container_name: karakuri
    restart: unless-stopped
    ports:
      - "8080:8080" # Web interface and API.
      - "9443:9443" # Remote agents dial this port.
    volumes:
      - karakuri-data:/var/lib/karakuri
      - karakuri-config:/etc/karakuri

volumes:
  karakuri-data:
  karakuri-config:

Start it and create the first admin account:

docker compose up -d
docker compose exec karakuri karakuri user create admin [email protected] <password> --admin

The first start writes /etc/karakuri/config.yaml into the karakuri-config volume with fresh secrets. The database and files live in karakuri-data. Keep both volumes: the encryption key in the config is the only key the stored connection credentials open with.

To update, pull the new image and recreate the container:

docker compose pull
docker compose up -d

A container never updates itself; the pull is the update. The image runs on amd64 and arm64 and includes Chromium for dashboard renders.

Docker Compose with PostgreSQL

Save compose.postgres.yaml as compose.yaml in an empty directory. It runs a postgres:17-alpine container beside Karakuri and points Karakuri at it with environment variables. Both containers read the database password from a .env file beside the compose file:

echo "KARAKURI_DB_PASSWORD=$(openssl rand -hex 24)" > .env
docker compose up -d
docker compose exec karakuri karakuri user create admin [email protected] <password> --admin

Karakuri waits for PostgreSQL to answer before it starts, and creates its tables on the first start. The database lives in the karakuri-postgres volume. Back up .env with the volumes: PostgreSQL keeps the password it started with, so a new .env locks Karakuri out of the old database.

Use a hex password like the one above. The connection string separates its settings with spaces, so a password with spaces or quotes breaks it.

docker run

Without Compose, the same container starts with:

docker run -d --name karakuri --restart unless-stopped -p 8080:8080 -p 9443:9443 \
  -v karakuri-data:/var/lib/karakuri -v karakuri-config:/etc/karakuri \
  grmrgecko/karakuri
docker exec -it karakuri karakuri user create admin [email protected] <password> --admin

Release archive on Linux or macOS

Download the server archive for your platform from GitHub releases. Archives are built for Linux and macOS on amd64 and arm64. Unpack it and run the installer:

tar xzf karakuri-<version>.linux-amd64.tar.gz
cd karakuri-<version>.linux-amd64
sudo ./install.sh
sudo karakuri service install
sudo karakuri service start
sudo -u karakuri karakuri user create admin [email protected] <password> --admin

install.sh puts the binary in /usr/local/bin, plugins and themes in /usr/share/karakuri, a configuration with fresh secrets in /etc/karakuri, and the database in /var/lib/karakuri. The service runs as the karakuri account. Run install.sh without sudo to install under your home directory instead, then run the karakuri service commands as yourself.

karakuri service also takes stop, restart, status, and uninstall, and works with systemd, OpenRC, SysV, and launchd.

macOS refuses to start a binary unpacked from a browser download until its quarantine flag is cleared:

xattr -dr com.apple.quarantine karakuri-<version>.darwin-arm64

A system install checks for a newer release once a day from a root timer, installs it, and rolls back if the new version will not start. sudo karakuri update installs a newer release now.

Unpacked, without installing

On Windows (amd64), or to run Karakuri from a directory on any platform, unpack the archive and start it from there:

mkdir etc
./karakuri config gen --env=prod > etc/config.yaml
./karakuri user create admin [email protected] <password> --admin
./karakuri serve

config gen writes placeholder secrets that every generated file shares. Before anyone else can reach the server, replace security.jwt_secret and security.encryption_key in etc/config.yaml with the output of openssl rand -hex 32, one run for each. Set encryption_key before saving any connection; changing it later makes stored credentials unreadable.

karakuri service install registers the same directory with the Windows service manager when you want it to run in the background.

From source

Building needs Go (the version in go.mod) and Node.js with npm. Every build goes through the Makefile:

make                 # optimized build into build/
sudo make install    # runs install.sh on build/, as for a release

make docker builds the server image from the checkout.

Databases

Karakuri stores flows, dashboards, devices, users, and run history in one database. The database section of config.yaml chooses it:

Key Default Meaning
type sqlite sqlite, postgres, or mysql.
path <data directory>/karakuri.db The SQLite file.
dsn unset The PostgreSQL or MySQL connection string.
max_open_conns / max_idle_conns 25 / 5 The connection pool.
conn_max_lifetime 300 Seconds one connection is reused.

Every key can also come from an environment variable: KARAKURI_DATABASE_TYPE, KARAKURI_DATABASE_DSN, and so on. An environment variable wins over the file, which is how the PostgreSQL compose file switches a container to PostgreSQL without editing its generated config. Karakuri creates and updates its tables itself on start, so the database only needs to exist and be empty.

SQLite

SQLite needs no setup and is the default. The whole database is one file in the data directory: /var/lib/karakuri/karakuri.db for a system install and in the Docker image. It suits one house. Choose PostgreSQL or MySQL when you already run one and back it up, or want the database on another machine.

PostgreSQL

Create a user and a database it owns:

CREATE USER karakuri WITH PASSWORD '<password>';
CREATE DATABASE karakuri OWNER karakuri;

Then set the database in config.yaml and restart the server:

database:
  type: postgres
  dsn: "host=db.example port=5432 user=karakuri password=<password> dbname=karakuri sslmode=disable"

The URL form works too: postgres://karakuri:<password>@db.example:5432/karakuri?sslmode=disable. Use sslmode=require or verify-full when the database is on another machine.

MySQL and MariaDB

Create a database and a user with every privilege on it:

CREATE DATABASE karakuri CHARACTER SET utf8mb4;
CREATE USER 'karakuri'@'%' IDENTIFIED BY '<password>';
GRANT ALL PRIVILEGES ON karakuri.* TO 'karakuri'@'%';

Then set the database in config.yaml and restart the server:

database:
  type: mysql
  dsn: "karakuri:<password>@tcp(db.example:3306)/karakuri?charset=utf8mb4&parseTime=True&loc=UTC"

Keep parseTime=True. Without it the driver hands times back as text and the server cannot read its own records.

Moving an existing install to another database

Pointing a running install at an empty database starts it over with nothing in it. To keep your flows and devices, take a backup under Settings, Backup, change the config to the new database, and restore the backup into it. A backup holds rows rather than a database file, so it restores from SQLite into PostgreSQL or MySQL and back. The Backup guide covers restoring.

First sign-in

Open http://<host>:8080 and sign in with the account you created. For anyone reaching the server from another machine, set server.base_url to the address they use, such as http://karakuri.lan:8080, so links and dashboard renders point at it. Help in the web interface has every guide, including this one.

Home and overview

/ is each user's start page. The Karakuri name in the navigation goes there, and so does sign-in. The flow list is at /flows.

Start page

Each user picks a start page in Settings, Profile:

Choice / opens
Default The overview for anyone who can read flows. Someone who cannot gets their only dashboard, or the dashboard list when they can see several.
Overview The overview, whatever the user can read.
A dashboard That dashboard.

A chosen dashboard that was deleted, or is no longer shared with the user, shows in the profile as "Unavailable dashboard", without its name, and / falls back to the default. An API client sets the choice as the start_page preference through PUT /api/auth/preferences. The value is absent, overview, or a dashboard ID.

Overview

The overview shows whether anything is broken and what runs next. It refreshes every 30 seconds while the tab is visible, and again when the window regains focus. A user sees a section only when they can read what it lists:

Section Shows Needs
Needs attention The items below, or one all-clear line naming what was checked. Any of the source permissions below.
Coming up Schedule triggers firing and wait deadlines in the next 12 hours, soonest first, up to 20. A wait can be cancelled from here. api:flows:read. Waits also need api:runs:read, and cancelling needs api:runs:cancel and edit on the flow.
Running now Active runs, with cancel. Hidden when nothing runs. api:runs:read.
Unfinished work Up to 10 flows and 10 dashboards with undeployed draft changes or never deployed, newest change first. Hidden when empty. Edit on each item, and api:flows:write or api:dashboards:write.
Quick launch Pinned dashboards as tiles, in pin order. api:dashboards:read.
Recent problems The newest 8 warnings and errors of the last 24 hours, linked to Activity filtered to those levels. api:events:read.

The overview leaves out flows, waits, runs, and failures of a flow the user holds no share on, as every other page does.

Pin a dashboard with the pin button in the dashboard list, or unpin it there or from its tile. Tiles reorder with their arrow buttons. Pins are private to each user; over the API they are the pinned_dashboards preference, an ordered list of dashboard IDs.

What needs attention

Source Item Severity Needs
Connections An enabled connection in the error state, with its error and how long it has been down. error api:connections:read
An enabled connection still connecting after two minutes. warning
A connected connection that went down 3 or more times in the last hour, counted from the event log's connection failures. warning
Agents An enabled agent without a live session, with when it was last seen. error api:agents:read
Flows Failed runs of the last 24 hours, one item per flow and distinct error, with the count and a link to the flow. A flow whose newest finished run succeeded shows its failures as warnings. A run whose failure an error branch handled succeeded and is not counted. error or warning api:runs:read and view on the flow
Backups The newest finished backup failed, or its archive failed verification. error api:backups:read
The schedule is enabled and its first time after the newest successful backup passed more than an hour ago. warning
History A writable time-series connection whose history writer is failing to deliver. warning api:connections:read

Errors come first, then the newest. A disabled connection or agent is not an item, because disabling it was a choice. A device that went offline is not an item either. Battery devices report offline routinely and would bury real failures, so device availability stays in the event log and reaches recent problems. Having no backup schedule is not an item.

When a source cannot be read, for example because the agent hub is not running, the section says so by name instead of claiming all clear. The unstable-connection check reads the event log, so it finds nothing when an administrator stopped recording the connection category.

REST and MCP

Route MCP tool Returns
GET /api/home/attention get_attention items, checked, unchecked, and summary with the all-clear figures.
GET /api/home/upcoming?hours=12 list_upcoming items with kind (schedule or wait), at, the flow, the node, and for waits the key and can_cancel. hours is 1 to 24.
GET /api/home/unfinished list_unfinished_work flows and dashboards, each with id, name, updated_at, and deployed.

The routes need a signed-in user or API key. Each source inside checks its own permission, so a limited key sees only the sources its permissions cover. Cancel a wait from list_upcoming with cancel_flow_wait, using its node_id and key.

Authoring flow graphs

A flow is a JSON graph document of nodes wired by edges. This page is the reference for writing one programmatically, over the MCP tools or the REST API. The editor produces the same document; nothing here is MCP-specific.

Lifecycle

A flow always has a draft, and the draft is what you edit. Saving the draft validates leniently. Required config fields may be missing or empty, so you can store half-finished work. A draft can also keep types from unavailable plugins. Deploy strictly validates the branches reachable from every trigger, including their value dependencies, then freezes the whole draft as an immutable numbered version. Disconnected unfinished fragments do not block a working flow. Deploy validates shared subflows and graphs without triggers in full. Enable arms the deployed version's triggers. A test run strictly validates the branch reachable from its selected start and executes it from the draft, so you can try a graph without deploying it. validate_flow_graph with strict validates the whole submitted document.

Browser and MCP edits share the same stored draft, and open editors refresh when another client changes it. A refresh with the same draft revision keeps the selected node and its configuration panel open, including after autosave or a reconnect. Loading a different graph revision clears selection. get_flow returns draft_revision. Pass it as expected_revision when saving a whole graph, so your save cannot overwrite a concurrent edit. For focused edits, patch_flow_graph applies an atomic, revision-checked batch of node and edge changes. Before deploying, read diff_flow to compare the draft's graph and settings with the current deployment. Restore replaces the whole draft, including its name, description, and error routing, with a stored version. It does not deploy or change enable state.

Work in this loop. Save the graph, run validate_flow_graph with strict set to check the whole document, run run_flow_test, then read per-node results with get_flow_run. Deploy and enable once the run behaves.

Ownership and sharing

Whoever creates a flow owns it. The owner shares it with people or user groups at one of four levels, each including the ones below it:

Level Allows
faceplate The flow's faceplate tabs only. No graph.
view The graph, versions, run history, live runs, pending waits, export, and the flow's event log entries. Nothing that changes or runs it.
edit Saving, testing, deploying, enabling, running, and cancelling runs and waits.
admin Sharing and deleting. The owner holds admin.

Holders of api:flows:manage hold admin on every flow; the Admin role has it through api:*. api:flows:read, write, and deploy say whether a user may read, author, and deploy flows at all. The share level says which flows they may act on. A flow the user holds no level on answers not found.

Share from the share button on the flow list or the editor toolbar, or with POST /api/flows/{id}/shares and {"username": "...", "permission": "edit"} or {"group_name": "...", ...}. The event log records each change. Shares are not versioned, so restoring a version leaves them alone. Only a manage holder may move a flow to another owner, with owner_id on PUT /api/flows/{id}.

Folders share the same way. A folder's owner and shares reach its subfolders and every flow inside them, and a flow's level is the highest of its own shares and those of every folder above it. Share a folder from its share button in the flow list, or with POST /api/folders/{id}/shares. Renaming a folder needs edit; moving, deleting, and sharing it need admin. Putting a flow or folder into a folder needs edit on the destination. Moving a flow also needs admin on the flow, since the destination's shares will reach it. The flow list omits folders a user cannot see and shows a flow shared out of one at the user's root.

Flow names need not be unique across owners. Karakuri refuses a new name only when a flow you can already see uses it. A flow's ID is its address. A slug such as /flows/porch-light opens the one flow you can read with it, and offers a choice when you can read several. GET /api/flows/by_slug/{slug} lists them.

A few rules reach across flows:

  • Subflows. A save may add a reference to a shared subflow only when the user may view it. References the draft already holds keep saving. An imported flow has no draft, so the import checks every reference in it. A deployed flow keeps running after its author loses access to a subflow, because runs resolve subflows as the system.
  • Copying another flow's graph. Export and import_subflow need view on every subflow they copy. A copy made by import_subflow saves like any other draft, so the shared subflows it calls need view as well.
  • Error flow. A new error flow must be one the user may view.
  • Widget triggers. Pressing one through api:flows:trigger needs edit on the flow. A dashboard binding a trigger deploys only for someone with edit on that flow. Its viewers then press through the dashboard, as dashboard security describes.
  • Connections and agents. A flow reaches only the connections and agents its user may use. Tests and draft runs act as the user who starts them. A deployed flow acts as whoever deployed it, and keeps doing so after a faceplate change. A deploy is refused when it names a connection or agent node the deployer cannot use. At run time a node fails, before it contacts anything, when the connection it names, including one wired in over a value edge or picked by a script, or the agent it runs on is not shared with the run's user. Remove someone's share and the flows they deployed stop reaching that connection on their next run.

The default User role can create and deploy its own flows but cannot open or change anyone else's until the owner shares them. On a server with several accounts, share the flows other people work on.

The graph document

{
  "nodes": [
    {"id": "n1", "type": "manual", "position": {"x": 0, "y": 0},
     "config": {"payload": {"value": 42}}},
    {"id": "n2", "type": "switch", "position": {"x": 240, "y": 0},
     "config": {"property": "payload.value",
                "rules": [{"id": "high", "operator": "gt", "value": "10"}]}},
    {"id": "n3", "type": "debug", "position": {"x": 480, "y": 0}}
  ],
  "edges": [
    {"id": "e1", "source": "n1", "source_handle": "out",
     "target": "n2", "target_handle": "in"},
    {"id": "e2", "source": "n2", "source_handle": "high",
     "target": "n3", "target_handle": "in"}
  ],
  "viewport": {"x": 0, "y": 0, "zoom": 1}
}

Node IDs and edge IDs are free-form strings that must be unique within the document. viewport is where the editor's camera sits, and {"x": 0, "y": 0, "zoom": 1} is fine for a generated graph. On entry, the editor centers the measured node bounds in the canvas at 100% zoom, including when entering a subflow. Large graphs stay at 100%; use the fit-to-view control to show the whole graph. Returning through a subflow breadcrumb restores the parent camera position.

Focused draft patches

patch_flow_graph takes the flow id, its current draft_revision as expected_revision, and operations. For example:

{"op":"update_node","id":"n2","value":{"config":{"_label":"Kitchen"}}}

Operations use node or edge IDs, not JSON Pointer paths or array indices. The operations are add_node, update_node, remove_node, add_edge, update_edge, and remove_edge. Adds take the new item's fields. Updates merge objects, replace arrays, and remove fields set to null. Removing a node removes its incident edges. The optional subgraph_path array names local subgraph keys from the root to the graph being edited. The batch validates and saves once, and an invalid operation or stale revision saves nothing. Validation errors include the node or edge ID and the failed constraint. Successful patches and whole-graph saves return validation with strict diagnostics. validation.valid: false means the draft saved but would not pass strict validation yet. To check the stored draft without resending it, call validate_flow_graph with flow_id and strict: true.

Switch rules is an array of {id, operator, value, label} objects. The rule's id is its output port ID. operator names the comparison, such as eq, gt, or expression. value is a string, including for numeric comparisons, and only exists and otherwise omit it. property selects the tested message path. With HA State, payload.new is the new state or selected attribute value, and payload.new_state is the full state object. Rules that name each state explicitly keep unknown and unavailable from counting as off. The trigger's to filter can also select one state directly without a switch.

Nodes

A node is {id, type, position, config}. The catalog lists what exists. list_node_types returns the summaries, and get_node_type returns one type's config field schema (config_spec), its ports, and its port type rules. Numeric editor inputs accept fractional values; each node enforces its own range and integer requirements. Structured fields may include a value_schema JSON Schema. Output ports may include a payload_schema describing the payload inside the message envelope. Config is an object whose keys are the field IDs from config_spec, and validation rejects a field the spec does not declare.

Optional node fields:

  • retry overrides the type's retry policy: {"max_attempts": 3, "delay_ms": 1000, "backoff": 2, "max_delay_ms": 30000, "jitter": 0.2}. Only retryable types accept one.
  • bypass disables the node without unwiring it. The node does not run, and each output receives the message from the input whose payload type matches it.
  • params lists config field IDs exposed as value input ports (see Value edges).
  • width, height, collapsed are canvas presentation and do not affect runs.

Three config keys are presentation state that runs and validation ignore: _label (a display name overriding the type's), _color (a card tint), and _rotation (degrees). Leave them out of generated graphs unless asked.

Edges and ports

An edge names its endpoints by node ID and port ID. source_handle is an output port of the source node, and target_handle an input port of the target. Port IDs come from the type's metadata (inputs and outputs in get_node_type). Most nodes read on in and emit on out, and a switch emits on its rule ports. A node with a failure branch has an error output that receives the message when the node fails and its retries are exhausted.

An input port accepts one incoming edge, and wiring two sources into one input is a validation error. Fan out from one output is fine. The one exception is a multi parameter port (multi on the port in get_node_type, such as the AI agent's tools input). It takes any number of value edges, and the pulled values reach the config field as an array in edge order. A source wired through a reroute, a set/get pair, or a subflow boundary keeps the position of the edge that enters the port.

A port's type describes its payload only; every port carries a full message (payload, topic, metadata). any is the wildcard and binary is real bytes. On the message path an any output may feed a typed input, because a webhook body is not knowable until the run. Validation rejects a declared mismatch, such as string into number. Karakuri never sniffs content. A source names its format (webhook.body_format, mqtt-in.format, http-request.response_format), and bytes that do not match it fail rather than arriving as something else. Nodes that only route or delay propagate their upstream type, so a delay behind a JSON parser reports object.

Value edges

A value edge ("kind": "value") binds a config field to another node's output. No message travels along it during a run. The consumer pulls the value when it executes, once per run. The source must be a pure node, marked pure in the catalog, such as manual, file-read, ha-get-state, and control-get. To supply a config field, list its ID in the node's params array and use param:<field> as the edge's target_handle. The field's literal in config stays as the fallback.

A trigger with a wired field reads the value once, when the flow is armed, and arms with it. A deploy rearms the flow and reads it again, which is how a new faceplate value reaches a schedule or a watched topic.

Some fields are port fields (port on the field spec). They are permanent value input ports rather than settings. Nobody types into them, they never appear in params, and a value edge to param:<field> is the only way to supply them. The AI agent's model and tools inputs are port fields, because they hold another node's output (a model handle, a tool set) that nobody could write by hand. A required port field must be wired to deploy. A multi port field takes several edges, as described in Edges and ports.

The AI Tool node adds one more wiring shape, and the ai guide covers it in full. Its out wires to an agent's param:tools as a value edge. Its call output starts the tool's branch with an ordinary message edge, and the branch's last node wires back into the tool's return input. That cycle is legal. Each argument declared in its tool_args config is an output port named arg:<id>. It wires to a branch node's param:<field> input as a value edge, read again for each call. Argument ports carry values only, never messages. Deploy requires call wired, return wired, and the tool name unique in the graph.

Script node calls

A JavaScript, Python, or Bash script node can invoke eligible catalog nodes through its language's node binding instead of wiring every step. Calls use the real node configuration and input message shapes, run synchronously inside the active run, and return output messages without delivering them to graph edges. See Scripting for function names, options, results, eligibility, state identity, and errors.

Strict validation, used by test runs and deploy, checks calls whose node type and configuration are written literally in the script, using the same rules that apply when the script runs. You can still save a script with diagnostics as a draft. Configuration the script computes cannot be checked ahead of time, so Karakuri validates it when the call is made, before the node acts. Validation never runs a node or touches an integration.

Run history gives each call a distinct invocation record with its parent script, node type, sequence, attempts, outputs, and failure. Caught failures can continue to a fallback. Once any call begins execution, Karakuri stops retrying the outer script, so a later failure cannot replay earlier calls. Pure value pulls can call only pure nodes.

Node calls are unavailable in the standalone script test. A flow-node test (test_flow_node) can call every eligible node and performs real actions, like other node tests.

Triggers and test runs

A run starts at a trigger (trigger in the catalog summary). A graph with no trigger can still be test-run from a pure source node, which is how you exercise a hand-driven flow. When a graph has several possible starts, run_flow_test needs trigger_node_id.

A test run seeds its message from the trigger. The manual trigger uses its configured payload, and a schedule synthesizes its tick. Every other trigger reads a test_params value from its config (for a webhook, the sample body), and run_flow_test refuses it without one. The payload argument of run_flow_test overrides the seed for one run without editing the node.

get_flow_run returns the last persisted run with node_states, which gives each node's latest state (pending, running, retrying, succeeded, failed, skipped), its attempt count, its error message, and whether an error branch handled its failure. Karakuri keeps the latest 100 completed runs per flow and every active run. Use list_flow_runs for history and pass run_id to get_flow_run to inspect one exact execution.

Before creating a flow, inspect a type with get_node_type (see Nodes). Passing config to get_node_type resolves its dynamic ports. test_node accepts a type, config, and input messages, and returns outputs and errors directly without creating a flow or saving history. It uses real connections with fresh, temporary node stores and variables. Its wall-clock timeout defaults to 30 seconds, including parked waits.

list_flow_nodes lists placed node IDs, types, labels, availability, and bypass state. Use get_flow_node for configuration and resolved ports, and list_flow_edges for wiring in a draft or deployment. test_flow_node executes only the selected draft node with explicit inputs keyed by its resolved message port IDs. Temporary config_overrides replace fields for that test without saving. Wired value parameters require overrides, because their producers do not execute. Triggers accept inputs.__trigger__ or their configured test payload. Neighboring nodes and the flow's error handler do not run, but the selected node still performs real actions and uses its retry policy. Use run_flow_test when routing or a subflow branch needs to execute. Inspect the returned run ID with get_flow_run and include_events: true for outputs.

Faceplates

A Faceplate node is one tab of settings on the flow's page. Its config holds a tab name, an ordered list of controls, the applied values, and an optional change script. Each control is a value output named by its ID; wire it into the parameter it drives. A pulled faceplate emits each control's applied value, or its default when none was applied. A faceplate has no message ports and never runs on its own.

Control type Value Output port
number a number, kept within min and max number
boolean true or false bool
string text, or one of options string
entity {"connection_id": "...", "entity_id": "sensor.lux"}; its live state shows beside the field object
array, object JSON, usually edited by a template object

A flow with faceplates opens on its first faceplate tab. The flow editor is the first tab, and editors reorder faceplate tabs with the arrows beside the selected tab. Apply checks every value against its control, saves, and deploys:

  • Edit access saves the draft with the values, draft edits included, and deploys it.
  • A faceplate-level share (see Ownership and sharing) sees only the faceplate tabs. Its Apply deploys the current version with only the new values, so an editor's unfinished draft stays undeployed, then writes the values into the draft.
  • A view share reads the tabs but cannot apply.

The REST routes are under /api/flows/{id}/faceplates: GET for the tabs, POST .../apply with {"values": {"<key>": {"<control>": value}}}, POST .../order with {"keys": [...]}, and GET .../readings for entity states. A key is the faceplate's node ID, subgraph/node inside a local subflow, or subflowNode>innerKey inside a shared subflow.

Templates. A control's template is HTML and JavaScript that draws a custom editor. It runs in a sandboxed frame with no same-origin access and a content policy that blocks network requests, and talks to the page through window.karakuri:

  • value, control, values (every faceplate value by key), reading (this control's entity state), readings (all of them), and theme;
  • onUpdate(fn) to redraw when any of them changes;
  • setValue(v) to set this control's value.

A template that fails or does not start falls back to the plain editor. The curve editor and color picker ship as templates written the same way.

Change scripts. A faceplate's script runs in the same kind of sandbox whenever any faceplate value in the flow changes:

faceplate.onChange((change) => {
  // change: { tab, control, value, old }; tab is the faceplate key.
  if (change.control === 'max') {
    faceplate.set('Advanced', 'curve', [{ x: 0, y: 10 }, { x: 100, y: change.value }]);
  }
});

faceplate.get(tab, control) reads a value and faceplate.set(tab, control, value) changes one, where tab is a tab name or key. Sets can trigger further changes. After 10 rounds Karakuri stops the scripts and the tab shows why.

Shared subflows. A Faceplate node inside a shared subflow shows as a tab of each flow that calls it, labelled with the calling node. Karakuri stores values applied there on that subflow node, so two callers keep their own settings. An export embeds the subflow as a local subgraph and writes each calling node's values into its own copy.

Subflows

A subflow node runs a nested graph. It references either a local subgraph, with "subgraph_id" naming a key in the document's subgraphs map, or a shared subflow, with "subflow_id" naming another flow created with is_subflow and resolved against its deployed version. Inside a subflow document, boundary port nodes declare the interface, and each declares its port_type. Validation checks the inside against that contract and checks nesting for cycles and depth.

Variables

Scripts and the variable nodes read and write four scopes. msg rides one message, run spans one run, flow persists per flow, and global persists server-wide. flow and global survive restarts. The default scope is msg and the default path is payload.

Failure handling

Only retryable node types accept a retry policy. When a node's retries are exhausted, a wired error output receives the message instead of the run failing. Value parameters are read before the node's first attempt, so a failed pull is not retried and does not reach the consumer's error output. Failures inside active tool-call branches return to the waiting AI agent as observations. A flow can also name an error_flow_id, a flow that starts when a run fails unhandled. Wire the failure path for any node whose failure matters instead of leaving the run to fail.

The run timeout counts elapsed time, excluding intervals while any node waits in a delay or a tool wait, even if another branch is active. Retry backoff does not pause it, so the run timeout is not a wall-clock cap. Zero disables it. A zero per-flow concurrent-run limit allows unlimited runs.

Cancellation starts no further nodes and asks active nodes to stop. The run finishes after they return, and a node that ignores cancellation can keep it running. An unhandled action failure starts no further nodes but lets active ones finish. On shutdown the server waits up to five seconds for active runs, then abandons them and logs that it did. A pure source that succeeds is read once per run. If it fails, the next node that pulls it tries it again.

The webhook endpoint accepts GET and POST. Armed triggers further filter their configured methods and IP allowlists, and can verify HMAC over the bytes read. With server.trust_proxy enabled, forwarding headers replace the address checked by that allowlist only on requests from a peer in server.trusted_proxies (loopback by default). The server reads X-Forwarded-For from the right, so a client cannot forge its address by prepending one. List your reverse proxy's address there. When two armed webhooks use the same token, the one armed last receives requests and the server logs a warning. A webhook reads at most 1 MiB and can accept a truncated text or binary body. A synchronous response wait defaults to 30 seconds. A disconnected caller or response timeout does not cancel the independent flow run.

Discovering inputs and inspecting state

Before configuring an HA action, use list_ha_services with its connection UUID and optional domain/service filters to read the available fields and targets. For MQTT triggers, capture_mqtt_messages collects payload samples from a topic filter for up to 30 seconds without publishing. preview_schedule validates a cron expression and lists upcoming times in the selected timezone without arming the trigger.

Use find_references before changing a shared flow, connection, or control. It finds the flow graphs and editable dashboard bindings that reference it, including nested deployed subflows. Read every source-document page and check incomplete. The search cannot find every dynamic reference or value a script constructs.

inspect_flow_state reads a flow's persisted variables or durable node store keys. It is read-only and can trail running nodes by a moment. Removed nodes may still have stored state. It excludes global, run, message, and transient node state. Use get_flow_run for execution events. With store: "waits" it lists the flow's pending waits instead.

Time windows

Time window (time-window, under Time) classifies incoming messages on inside or outside. It preserves the payload, topic, metadata, and group. Empty weekdays select every day. Set location to an IANA timezone, such as America/Chicago, or leave it empty for server-local time. Empty time uses the current time. Otherwise it names a message property containing a timestamp, such as payload.at. It accepts RFC3339 strings, Unix seconds, and Unix milliseconds, as Wait Until does.

Each endpoint independently selects clock or sun. Clock times use HH:MM, with defaults 08:00 and 18:00. Sun endpoints select a standard named event and an optional elapsed offset from -12h to 12h. Coordinates can be explicit or use the server's configured location. Custom solar elevation belongs to Schedule.

Start is inclusive and end exclusive. An end before the start continues into the next day. Weekdays belong to the nominal start date, so a Friday window from 22:00 to 06:00 includes early Saturday. Solar offsets can move an endpoint into an adjacent date without changing its weekday ownership. Identical endpoints fail. Clock comparisons follow local wall time. Both occurrences of a repeated DST hour match, and a skipped minute has no arriving event. If a required sun event does not occur, outside includes meta.time_window_reason: "no_sun_event". Invalid times, settings, or timestamps use error.

Connection status triggers

Connection status trigger (connection-status, under Network) observes one saved integration connection of any kind. Select any combination of connecting, connected, error, and disabled; empty selects every state change. A disconnect uses the integration's native error or connecting report, followed by connected on recovery. Saving an enabled connection restarts it through connecting without reporting disabled. Repeated reports of the same state do not start more runs.

emit_initial defaults to false. Enable it to emit the current selected status once on arming, including disabled connections and connections that failed to start. Standalone node tests read one status without subscribing. An optional test_params sample supplies a synthetic payload instead.

The output payload contains connection_id, connection_name, connection_kind, state, previous_state, error, since, and initial. Topic is the connection UUID. since is an RFC3339 timestamp for entry into the state, and repeated error details do not reset it. Initial events have empty previous_state. Filtered changes still update the baseline, so recovery identifies the actual preceding state. Payloads contain no connection configuration or credentials.

The trigger keeps watching when the connection is saved or restarted, and stops when the flow is disarmed. Karakuri does not store statuses, so after a server restart the trigger starts from the current state. A trigger that falls more than 64 reports behind drops the oldest and logs the loss, and the flow's concurrent-run limit can also drop runs. Use this trigger for alerts and recovery actions, not an audit log.

Device Availability (mqtt-device-availability) starts a run when a device goes online, offline, or unknown. It watches one device, or every device when device is empty, optionally only on changes to one value. The message carries device_id, name, availability, previous, source (connection, topic, interval, default, or entity), and at. Device Value and Device Changed add meta.availability, and Command Device fails on an offline device unless the device sends commands while offline. The MQTT device state script guide explains how availability is decided.

ESPHome Action (esphome-action) calls one of a node's own actions with arguments checked against their declared types, and ESPHome Node Action (esphome-node-action) starts a run when a node calls homeassistant.action or fires homeassistant.event. The ESPHome guide has the details.

NVR Event (nvr-event) starts a run when Frigate tracks an object, filtered by camera, label, sub label, zone entry, score, and stage. NVR Review (nvr-review) starts one on an alert or detection. NVR Image (nvr-image) reads a camera's latest frame or an event's snapshot as bytes and as an image. A Frigate switch whose camera receives no frames is offline with source entity. The Frigate guide has the details.

Energy Usage (energy-usage) reads the usage and cost of the house, a group, or a source over a span, optionally against the average of the same span on the previous four matching weekdays. Energy Price (energy-price) reads the price now or at a time, or finds the cheapest window. Energy Price Period (energy-price-period) starts a run at each price boundary, with the missed-deadline fields of the other resumable nodes. The energy guide has the details.

Log Event (log-event) adds an entry to the event log with an interpolated message, a level, and optionally the control or device it is about, naming the flow and run. Event Logged (event-logged) starts a run on new matching entries, filtered by category, level, subject, and message text. It never starts on entries its own flow caused or on folded repeats, and security entries need the owner's audit permission. The events guide has the details.

Back up (backup-create) writes an encrypted backup of the installation with the passphrase stored in Settings, Backup and waits for it to verify. It fails without retrying when no passphrase is stored. Backup finished (backup-result) starts a run when any backup fails, succeeds, or either, such as to send a notification after a failed night. The backup guide has the details.

Numeric transforms

Numeric transform (numeric-transform, under Logic) reads source and writes target, both defaulting to payload. Sources can be numeric payload or metadata properties. Destinations can replace payload or write payload.reading or meta.reading. Other message fields and group information stay intact.

Operation Settings and behavior
scale value * factor + offset; defaults factor 1 and offset 0.
map Map input endpoints to output endpoints. Reversed ranges are allowed; clamp limits the result to the output endpoints. Equal input endpoints fail.
clamp Bound the value between min and max, default 0 and 100. Minimum must not exceed maximum.
round Integer decimals from -12 to 12. rounding selects nearest with ties away from zero, floor, ceiling or truncation toward zero. Negative decimals round tens or larger places.
convert Convert compatible from_unit and to_unit values. Defaults Celsius to Fahrenheit.

Unit choices cover temperature, length, speed, pressure, power, energy, and angle. Use scale and offset for a calibration outside these dimensions. Missing or nonfinite readings, incompatible units, invalid settings, and numeric overflow use error. A scalar payload has Number ports, and a nested payload path derives Object. Metadata writes preserve the incoming payload type. The editor updates these types live, and graph validation uses the same rules.

Stateful node behavior

Hysteresis watches a numeric message property using separate lower and upper thresholds. High-active mode activates at or above upper and releases at or below lower; low-active mode reverses those conditions. Inside the band the node keeps its remembered state. Only transitions emit on active or inactive, and each key starts inactive. State is durable across redeploys and restarts. An optional key property, such as topic, isolates devices. A reset-only input clears that key without emitting. Lower must be below upper, and thresholds and readings must be finite numbers.

Condition wait polls an optional Observed value wire from any pure source, including HA Get State, Device Value, or Control Value. Each observation reads the source and its own value inputs again; other nodes in the run keep the values they already read. The boolean condition sees the observed value as payload and reads current flow and global variables. Without a value wire, it sees the original incoming payload and live variables. Held for requires matching observations for that duration, and a false observation restarts the interval. Connect a value-change trigger, such as Control Changed or HA State, to Check to request an immediate fresh observation. Check messages wake every active wait on this flow and node, including waits started by another run. The wait ignores the check payload. A check starts no wait, emits nothing, and leaves each wait's original message and deadline intact. Polling continues as a fallback. Change triggers still obey the per-flow concurrent-run limit, so a saturated limit can drop their runs. Repeated pending checks can coalesce, and the wait can miss changes between observations. Configure a positive timeout and poll interval, with held duration no greater than timeout. matched and timeout preserve the original message and include meta.condition_value and meta.condition_wait_ms. Cancellation emits nothing, and read or expression failures use error. A pending wait survives restarts and redeploys; see Pending waits.

Delay and Trigger accept key, a message property selecting independent state such as topic or payload.device_id. Empty keeps one shared state for every message. A message missing the configured key property fails. Trigger reset cancels only the selected arm. Delay reset clears the selected rate schedule and invalidates queued and debounced messages; fixed and random delays are unchanged. A queued message invalidated by reset emits on superseded when its wait wakes. Delay sends rate-limited messages to dropped, and a message replaced in a debounce leaves superseded once. Debounce max_wait bounds a window from its first arrival even when new messages keep extending its quiet period. A reset cancels the pending window, and its latest message later leaves superseded. A window started after the reset is unaffected.

Dedupe expiry forgets a value or higher/later watermark after the configured duration from its last admission. Duplicates never extend that deadline. Empty expiry keeps values until the history count or the watermark moves past them. When you add expiry to a dedupe that already has history, each remembered value starts its expiry clock the next time it is seen. Expiry deadlines survive restarts. duplicate forwards suppressed messages unchanged. A reset-only input clears every logic's history without emitting.

Pending waits

Trigger, Delay (every mode), Wait until, Condition wait, Join, Batch, Aggregate, and the sequence modes of Limit and Sort hold work between messages: a timer, a held message, or a partial group. In deployed runs Karakuri stores that work as a pending wait, so it survives a restart and a redeploy. Test runs of the draft keep their waits in memory.

After a restart, each wait resumes in a new run that starts at the waiting node. It fires at its original deadline, not the original duration measured from the restart, and resets, extensions, and keys behave as they would have without the restart. The new run carries the message the wait held, including binary payloads. Run variables and other branches of the original run do not come back. Messages it emits carry meta.resumed with from_run_id, the original deadline, and late_ms, and the run links back through resumed_from_run_id. Queued rate-limited messages whose slots passed while the server was down leave one interval apart from the restart, in their original order. A queued message whose slot has not passed moves back when it would otherwise leave less than an interval after them. A Condition wait resumes observing and restarts its hold, because nothing could observe stability while the server was down. When the hold is longer than the time left, it cannot finish, so the wait leaves on timeout at its original deadline.

Each of these nodes has two settings for a deadline that came due while the server was down. missed_deadline is deliver (the default), which sends the message as soon as the server is back, or drop, which discards it. With drop, missed_grace (default 30s) still sends a wait that is late by less than that, so the seconds a restart takes do not drop anything. Run history records both late and dropped waits. A dropped wait appears as a canceled run giving its original deadline and how late it was.

A crash at the moment a wait emits can lose the one message being delivered, but it never sends it twice. A normal shutdown loses nothing. A wait whose state cannot be stored, such as one holding more than 1 MiB, still runs but will not survive a restart, and its run says so.

A redeploy keeps the waits of nodes that keep their ID and type in the new version. They keep their deadlines, and a changed duration applies to the next message. The redeploy drops and records the waits of nodes that were removed or changed type. Disabling a flow drops all of its waits, and deleting it removes them.

The run panel in the editor lists pending waits with their countdown and a button to cancel one. Over REST, GET /api/flows/{id}/waits lists them and DELETE /api/flows/{id}/waits/{node_id}?key=… cancels one. Over MCP, use inspect_flow_state with store: "waits" and cancel_flow_wait. Listing needs api:runs:read and cancelling needs api:runs:cancel. Run history records a cancelled wait as a canceled run naming who cancelled it.

A house mode is a select control the flows set. To put guest mode back to home after four hours, feed the message that sets guest into a Trigger with a 4h duration whose Expired output sets home. A calendar event ending can send Reset to cancel it early. Because the Trigger's wait is stored, a restart or a redeploy in those four hours does not leave the house in guest mode. Keep anything the later branch needs in the message rather than in run variables.

Locations and presence

A location control (kind location) holds where a person or a tracked thing is. Its primary attribute is state (home, not_home, or a zone name), and it also holds latitude, longitude, accuracy in metres, and source. since is read-only. Karakuri sets it when state changes and leaves it alone when only the coordinates move. A Set Control with a bare value writes state. Writing an object merges, so a phone fix can update the coordinates without touching the zone. With restrict_zones on, the control refuses a state outside zones. A new location starts empty rather than claiming home or away.

Control Changed's ignore_writes decides which flow writes it skips. own_flow (the default) skips the writes of its own flow's Set Control nodes, so one flow can hand a control to another. any_flow skips every flow's writes, and none skips nothing. Dashboard, API, and MCP writes always fire. A flow's write puts flow_id and run_id in the payload. When flows start each other through controls, each handoff adds one to a chain. Past loop_limit (default 8) the trigger records a skipped start, control loop: Flow C set Y → Flow D set X → ..., instead of running. A run started any other way, by a timer, a delay, or another trigger, starts a new chain.

Control Changed with attribute: state fires once per change of zone, not once per fix. With an attribute set, it fires when that attribute's value differs from before, whichever part the write named, and the payload carries attribute_value and attribute_old. Without an attribute it fires on every change, coordinates included.

Karakuri has no built-in presence from several sources; you build it as a flow. This one marks a person home as soon as any source says home, and away only after every source has said away for ten minutes:

  1. One Control Changed watches every source, the first in control and the rest in also_watch. An input takes one wire, so one trigger is how several sources reach one decision. Each change carries its own control's name and value. Turn a Home Assistant or MQTT source into a control first, with a small flow per source that sets a toggle or a location control from its own trigger.

  2. A Script keeps each source's latest reading in a flow variable and routes on the result:

    const sources = get("presence_sources", "flow") || {};
    const v = payload.value;
    sources[payload.name] = v === true || v?.state === "home";
    set("presence_sources", sources, "flow");
    return Object.values(sources).some(Boolean) ? { home: "home" } : { away: "not_home" };
    

    Declare outputs home and away. A toggle counts as home when on, a location when its state is home. A source that has not reported yet counts as away. Flow variables are stored, so the readings survive a restart.

  3. home feeds a Set Control writing home to the person, and the Reset input of a Trigger.

  4. away feeds that Trigger's input. Set Send now to Nothing, Then wait to 10m, and A message while waiting to Is ignored, so later away readings keep the first deadline instead of extending it. Its Expired output feeds a Set Control writing not_home.

The Trigger's wait is stored, so a restart inside the ten minutes still sets not_home on time, and a home reading from any source in that window cancels it.

Home Assistant rooms

HA State, HA Get State, and HA Call Service take areas, floors, devices, and labels (area_id, floor_id, device_id, label_id, comma-separated registry IDs from get_ha_registry) as well as entities. HA State and HA Get State narrow them with domain and device_class. The nodes read membership from Home Assistant's registries at each change, so an entity added to a watched room counts with no redeploy. The trigger's payload carries the entity's area_id, area, and device_id. HA Get State with a group returns {states, count}. HA Call Service with only group targets fails when they reach no entity of the service's domain. You can also add Home Assistant entities as devices and drive them with the device nodes by kind attribute; the homeassistant guide has the details.

openHAB items

openHAB Item Changed watches items, group members at any depth, or every item in a location, narrowed by type and by from and to states. Its payload is {item, type, label, old, new, location}, with caught_up after a reconnect. openHAB Send Command sends a templated command to an item or group, and openHAB Get Item reads one. openHAB items added as devices are driven with the device nodes by kind attribute instead, held to the item's limits. The openhab guide has the item-type mapping.

Weather station overrides

Weather Override (weather-override, from the weather plugin) replaces a location's current conditions with readings from a local station. Forecasts served within radius_km of the override (default 10) show the readings in place of the provider's. That covers the dashboard weather widget, Weather Forecast, and Weather Changed, for either provider. Each reading expires on its own max_age after it was last set (default 15m, at most 24h), so a sensor that stops reporting returns to the provider's value while the others stay. Where radii overlap, the nearest override wins. operation: clear drops every reading for the location at once.

The location is a postal_code (with an ISO country, since codes repeat between countries) or latitude and longitude. A postal code resolves through Open-Meteo's geocoding to the centre of the place that lists the code, not the code's own centroid. US 35757 resolves to Madison, Alabama at 34.6993, -86.7483, so a widget at a house elsewhere in that code needs the radius to reach it.

The metric fields are temp, feels_like, dew_point, humidity, pressure (sea level), wind_speed, wind_deg, and uvi. Each takes a number or {{ }} text, read in units, which is metric (°C, m/s, hPa) or imperial (°F, mph, inHg). A blank field, or one rendering as empty, null, unknown, unavailable, or none, keeps the provider's value. Anything else that is not a number, or is outside the metric's physical range, fails the node. The output payload has the resolved latitude, longitude, the set readings, and every live reading with updated_at and expires_at, all in metric units.

A station publishing Weather Underground-style JSON, such as cotech-weather-station/state, needs MQTT In (format: json) into one override with units: imperial, temp: "{{ payload.tempf }}", feels_like: "{{ payload.windchillf }}", dew_point: "{{ payload.dewptf }}", humidity: "{{ payload.humidity }}", pressure: "{{ payload.baromin }}", wind_speed: "{{ payload.windspeedmph }}", and wind_deg: "{{ payload.winddir }}". A station reporting each sensor on its own topic can use one override per topic for the same location, and the readings merge. Overrides are not stored, so after a restart the provider's values show until the station's next report.

Media players

A media control (kind media) is a player. state is primary and one of off, on, idle, playing, paused, or buffering. volume is 0 to 100. muted, source, and position (seconds) are writable. title, artist, album, art, duration, position_at, and sources are reports. Options declare the player's features. volume, mute, skip, and stop are on by default, and seek, power, and source are off. The control refuses these writes before sending anything:

  • a write for a feature the player lacks;
  • buffering;
  • a volume outside 0 to 100;
  • a source the player does not list in sources or source_list;
  • a position past duration.

Writing idle stops; on and off need power.

Next and previous are writes of command (next or previous). A command is an action rather than a state. The write announces a change of command, so Control Changed with attribute: command fires on every press. Nothing is stored, so Control Value never returns a command. A whole-value write may report buffering and the read-only details, which is how a flow mirroring a player it drives over HTTP keeps the control in step. It may not include command.

ESPHome speakers and MQTT devices of kind media take the same writes through Command Device. An MQTT device's payload script receives field and value, command included. A Home Assistant player added as a device takes them too. Command one that is not added as a device with Call Service (media_player.media_pause, volume_set, and so on).

Calendars

Calendars are connections from the calendar plugin:

  • Calendar (ICS feed) for any ICS or webcal address, with optional basic or bearer authentication.
  • Calendar (CalDAV) for Nextcloud, iCloud, Fastmail, Radicale, and other CalDAV servers.
  • Calendar (Google) for Google calendars, public ones by API key and private ones through an oauth2 connection signed in to Google with the calendar.readonly scope.

Karakuri encrypts and masks their credentials like any other connection's. A connection's Test names the calendars it found and counts the coming week's events. CalDAV and Google connections read the calendars listed in calendars, or all of them when it is empty. Karakuri expands recurring events in their own time zone and honours excluded, moved, and cancelled occurrences. A failing refresh keeps serving the last good events for up to a day and shows the error on the connection.

Calendar Event (calendar-event) starts a run at events' starts, ends, or both. start_offset and end_offset move each moment earlier (negative) or later. It filters by match (title text), calendars, and all_day (include, exclude, or only), and fires once per occurrence of a recurring event. The message carries edge (start or end), event, moment, and fired_at. Each start or end fires once, and a restart or a redeploy never fires it again. The trigger catches up moments that came due while the server was down, up to a week back, under missed_deadline and missed_grace as described in Pending waits. Late runs carry meta.late_ms, and dropped ones appear as canceled runs naming the event. An event that already started when the trigger was first armed does not fire. A moved or deleted event fires at its new time, or not at all, from the next refresh (interval_s).

Calendar Events (calendar-events) is a value source returning in_progress (events under way now) and upcoming (events starting within window_days, at most limit), with the same filters. Wire it into a Condition or Switch to ask whether a vacation is on right now.

To drive a house mode from the calendar, feed a Calendar Event with edges: both and match: Vacation into a Set Control whose value is {{ payload.edge == "start" ? "away" : "home" }}. For overlapping overrides, keep the mode to return to in a flow variable. On start, save the current mode only when no override is active and count active overrides up. On end, count them down and restore the saved mode when the count reaches zero.

Home Assistant targets and observed confirmation

ha-call-service accepts comma-separated entity_id, area_id, device_id, and label_id targets. These fields support {{ }} expressions and may be combined. Area, device, and label fields take Home Assistant registry IDs. Dashboard invocation still enforces its allowed entity list, so broader registry targets require ordinary flow execution.

Set confirm: true to wait after an accepted service call. Choose exactly one confirmation_entity_id, an optional confirmation_attribute, and a text confirmation_value (expressions supported). The node reads fresh state every confirmation_interval (default 1s) until confirmation_timeout (default 30s). confirmation_stable_for requires matching samples for that duration. The node does not see changes between polls. The original message leaves out on a match, or timeout without a match. Metadata includes ha_result, confirmed, confirmation_entity, and confirmation_value. A timeout or failed observation does not resend an accepted command, and an observation error uses the error route.

ha-state.held_for delays a matching change until the selected state or attribute has held continuously in the observed event stream. Timers are independent per entity. Any contrary change cancels its timer before from/to filtering; unrelated attribute changes leave a state timer alone. Disarm, disconnect, reconnect, or a lost event invalidates the hold. Empty held_for keeps immediate triggering. Arming does not synthesize a change from the current state.

After Home Assistant reconnects, Karakuri reads every entity and reports each one that changed, appeared, or disappeared while the connection was down, once, with its latest state. It does not replay transitions that came and went during the outage. ha-state fires for these like any change, with caught_up: true in its payload and meta. ignore_caught_up fires only for changes seen as they happened. The first connection after the server starts reports nothing.

HTTP retry controls

http-request.retry_mode defaults to safe, which lets GET, HEAD, and OPTIONS retry. Choose all only for an endpoint that handles repeated commands safely, and none to disable retries. A node-level retry override changes timing and attempt limits but still respects this method setting and permanent failure decisions. retry_statuses selects comma-separated HTTP error codes from 400 to 599, defaulting to 408,429,500,502,503,504. Transport failures may retry. TLS certificate verification, invalid config, malformed response data, and response size failures do not. With fail_on_error_status: false, error statuses become ordinary output.

The HTTP default is three attempts with 500 ms initial delay, backoff 2, a 5 s maximum, and 20% jitter. Retry policy jitter is a fraction from 0 to 1, and the editor shows it as a percent. Omitted jitter keeps other nodes' existing timing. Retry-After accepts unsigned seconds or an HTTP date. The wait is the larger of the jittered backoff and the server's minimum, capped by max_delay_ms; a zero maximum means no configured cap. Invalid or past server values use backoff. Attempts must be from 1 to 1000, delays nonnegative and representable, and backoff zero (constant) or at least one. All settings must be finite.

Error routes retain the incoming payload, topic, metadata, and group. They add error, attempts, node_id, and, for classified failures, retryable, optional retry_after_ms, and error_details. HTTP details include the method, the URL without query or userinfo, the status, selected diagnostic headers (at most 1024 bytes each), and up to 64 KiB of response body with body_truncated. Run history records returned error bodies. The details exclude cookie and authorization headers. Pagination emits no partial output, and retries restart at page one.

SQL query

The SQL query node under Storage reads and writes an isolated SQLite database. Database scope defaults to This flow, where every SQL node in that flow shares its database, including nodes in called subflows. Global selects another database shared by all flows and authors.

Use one statement per execution. The node supports SELECT, INSERT, UPDATE, DELETE, RETURNING, and ordinary table, index, view, and trigger changes. Create a table with one node before querying it from another. Each statement commits on success, and transactions cannot span nodes or runs.

SQL is literal text. Parameters is an expression evaluated against the incoming message and bound separately, so message values never become SQL:

INSERT INTO readings (room, value) VALUES (?, ?)

Set Parameters to [payload.room, payload.value]. Named parameters also work, so WHERE room = :room takes {":room": payload.room}. Include the placeholder's :, @, or $ prefix in object keys. Every placeholder needs a value, and extra values are errors. Bind strings, finite numbers, booleans, null, or binary bytes. Encode structured data as JSON text upstream.

The output payload contains columns, rows, changes, and last_insert_id. Rows are objects keyed by column name. Use aliases when selected columns would have duplicate names. NULL stays null, and binary results are base64 strings. Topic, metadata, and message grouping survive.

Timeout defaults to 5 seconds and accepts whole seconds from 1 to 60, including time waiting for the database. Maximum rows defaults to 1000 and accepts 1 to 10000. Results are capped at 1 MiB, SQL at 64 KiB, and each database at 16 MiB. Four queries can execute concurrently, and queries to one database serialize. SQL execution failures, interrupted queries, and oversized results preserve the previous database and route to the error output. SQL failures never retry automatically, even with a retry override, because a disk error can leave a commit outcome uncertain.

Each database runs in memory, isolated from the host. It cannot open host files or Karakuri's application database. The node refuses ATTACH, DETACH, VACUUM, PRAGMA, extension loading, file functions, virtual tables, temporary objects, and authored transaction control. Ordinary built-in aggregate, date, window, and scalar JSON functions are available. JSON table functions use virtual tables and are unavailable.

Snapshots live under the installation data directory's sql/ directory as flow-<flow UUID>.db or global.db. Include that directory in backups. A successful write atomically replaces the snapshot before the node emits success. Databases survive restart and redeployment. Deleting a flow retains its file for operator cleanup, and a new flow with the same name does not reuse the deleted identity. Draft tests use the same data as deployed runs. Standalone node tests have a temporary private identity, while global tests change the shared database.

Sending notifications

The Network notification node selects a notification connection and one allowed endpoint ID configured in Settings, Notifications. Subject and message support incoming-message expressions and parameter ports. A successful send preserves the input envelope on out. Provider failures use error and never retry automatically. Timeout defaults to 30 seconds and may leave delivery uncertain. See notification services for configuration, secret handling, and the complete provider catalog.

Network sockets

The Network palette includes TCP In, TCP Out, TCP Request, UDP In, UDP Out, WebSocket In, and WebSocket Out. Select a TCP, UDP, or WebSocket connection from Settings, Connections. Input nodes decode text, binary, base64, or JSON and start runs. Outputs send once, preserve the input envelope, and route failures without automatic retry. TCP Request uses a private socket and replaces the payload with one bounded response.

Replies use the connection and session metadata from the input node, and replies to retired sessions fail. Listener broadcasts require explicit selection. The connection's settings hold TCP framing, UDP bind and multicast settings, and the WebSocket path, origin, and authentication. See network socket nodes for configuration and limits.

Browser questions on agents

browser-prompt holds its incoming message while the selected agent opens a Markdown question. Parallel branches continue. Configure agent, markdown, optional browser_base_url, buttons: [{id,label}], timeout (default 15m, 1s through 24h), and optional feedback/require_feedback. A button ID is its output handle, so labels and order do not change wiring. The selected output carries the original message with meta.browser_prompt holding id, label, text, request_id, and answered_at. Unwired choices end the branch. Timeouts and browser-launch failures route to error.

A button only selects its output, and any policy behind it is yours to wire. Route Retry to a new downstream action or an intentional new run; an already-dispatched node cannot execute again through a back-edge. Use Stop's branch to set a flow or global suppression variable if later requests should be gated. The Instructions editor attaches portable images and files in attachments and references them as attachment:key. See Browser prompts for storage limits, access, and lifecycle.

Scripting

The script node runs your code in an isolated interpreter, not in the language you have installed on the server. There is no package manager, no module loader, and no filesystem. A script sees the message it was given, the variables it is allowed to read, and mediated capabilities such as HTTP. A script running in a server flow can also call eligible nodes through its language's node binding.

A script can run any logic, but it cannot run programs on the host or reach connections and credentials directly. When it calls a node, the node runs with the same authority it has on the canvas.

Each language below is a complete reference on its own. Read the one you are writing in.

The sandbox

JavaScript Python Bash
Runtime built-in ECMAScript interpreter CPython 3.12 on WebAssembly (WASI) built-in bash interpreter
Always available yes when the CPython module is installed yes
Filesystem none only the interpreter's own scratch directory, without symbolic links none, except /dev/null
Processes none none no external commands at all
Sockets none none none
Environment none four PYTHON* variables the runtime sets only the message variables
Network http() only karakuri.get/post/http only http command only
Wall clock real frozen at 2022-01-01 none

Python runs on a 26 MB CPython WebAssembly module that releases, the Docker image, and builds from source include. An install built with PYTHON_SCRIPTS=0 leaves it out. Without it the language picker still lists Python, and the node fails with a message saying the module is missing. To add it to such an install, run make runtimes in a checkout and copy build/runtimes/python.wasm into the install's runtimes directory, or point script.python_wasm at the file.

Limits

Every execution is bounded. The defaults come from the server's script configuration, and the node's own Timeout field overrides the wall-clock time.

Limit Default Setting
Wall-clock time 30s script.timeout
Captured output 256 KiB script.max_output
Outbound requests 20 per execution script.max_http_requests
Each response body read 8 MiB script.max_http_response

Running out of time fails the node. Running out of output budget does not. The console keeps the lines it captured, appends ... output truncated, and drops the rest.

Network policy

script.network decides how far the script's own HTTP helper can reach. It does not restrict node functions.

  • full allows any destination the host can reach. This is the default.
  • bogons allows public addresses only. Loopback, private ranges, link-local, carrier-grade NAT, and the other reserved blocks are refused, which keeps scripts away from the LAN, from the server's own services, and from cloud metadata endpoints. The check runs against the resolved IP of every connection, so a hostname that points at 127.0.0.1 is rejected however it was spelled, and redirects are checked the same way.
  • none refuses every outbound request.

Only http:// and https:// URLs are accepted under any policy. Four redirect hops can be followed; the fifth is rejected.

The node

These sections apply to the script node in every language.

Declaring ports

A script node's ports come from the Inputs and Outputs lists in its config, not from the node type, so the canvas knows the shape of your script without running it. A port needs an ID; the label defaults to the ID and the type defaults to any. Declaring none leaves the node with one untyped input and one untyped output.

The editor enforces declared types. An output declared object cannot be wired to an input that wants a string. Use any when the payload depends on what arrives.

With more than one output declared, the return value is read as an object keyed by port ID, and a key you leave out is a branch not taken. Each key's value becomes the payload on that branch. Returning something that is not an object when several outputs are declared fails the node.

The error branch

A script node always carries an Error output, whatever you declared, unless you claimed the port ID err for yourself. A failed script routes there when something is wired to it, and fails the run when nothing is. On the message path, the node's retry policy applies first unless a node call has already begun execution; see Calling nodes.

A script pulled through a value edge is not retried. If it fails, the node that asked for its value fails before it runs, and that node's own error port is not used. Inside an AI agent's tool branch, the agent receives the failure as the tool's result instead.

Value edges

A script's output can be wired to another node's config field instead of to its input. The engine pulls the value when the consuming node runs and remembers it for the rest of the run, so a script feeding three parameters executes once. If that script makes an HTTP call, it makes one call, not three.

A pulled script runs when something asks for its value, which may not be when anything arrived on its input ports. A pulled script can call only pure nodes, the ones that compute a value without side effects. A call to an action node fails before the action starts.

Calling nodes

Scripts that the server flow engine runs receive a nodes global in JavaScript and Python, and a node builtin in Bash. Every eligible node type has a call target named by its exact type. Types also have a lower-camel alias when that alias is unambiguous. For example, all three of these JavaScript forms call the same Base64 Encode node:

const a = nodes["base64-encode"](config, { in: msg });
const b = nodes.base64Encode(config, { in: msg });
const c = nodes.call("base64-encode", config, { in: msg });

The logical argument list is the same in every language: call target, config, optional input messages, then optional invocation options. JavaScript and Python spell it:

nodes.<type>(config, inputs?, options?) -> outputs
nodes.call(type, config, inputs?, options?) -> outputs

To pass options without inputs, skip the inputs with undefined or null in JavaScript and None in Python.

Bash uses node <type> <config-json> [inputs-json [options-json]] and node call <type> ..., documented in the Bash section.

config is required but can be {}. Its keys are the same field IDs used by the node's config panel. inputs contains complete messages keyed by input port, so { in: msg } passes the current message to a node with an in port. options can contain:

  • id: a stable invocation ID, required by stateful nodes and contributed nodes whose state behavior has not been audited. Do not derive this ID from a source line or loop index when the node's state must survive a restart.
  • retry: the same max_attempts, delay_ms, backoff, max_delay_ms, and jitter policy a graph node accepts. A non-retryable node does not accept an override.
  • params: values for config fields that a graph would supply through value edges.

A successful call returns every ordinary output port as an array of messages. An output with no messages is an empty array. Payload, topic, metadata, and grouping survive. Error ports are not returned because a failed call throws instead:

const encoded = nodes.base64Encode(
  { property: "payload", target: "payload", encoding: "standard", padding: true },
  { in: msg },
);
return encoded.out[0]?.payload;

Calls are synchronous and do not execute downstream graph nodes. The engine resolves connections, checks configuration and inputs, enforces payload types, applies the call's retry policy, and records each invocation in run history. Repeated calls have different invocation sequences; attempts within one call keep the same sequence. A call returns at most 1000 messages and 1 MiB of JSON result data.

A failed call raises a NodeCallError in JavaScript and Python. Bash returns a structured error document with a nonzero status. The error includes the node type, invocation ID, sequence, attempt count, retry classification, and available details. Validation failures have zero attempts. Catch the exception or check the status to choose a fallback. Leave a JavaScript or Python exception uncaught, or propagate the Bash status as the script result, to fail the script node and use its normal error route:

try {
  return nodes.haGetState({ connection: ha, entity_id: "light.kitchen" }).out[0]?.payload;
} catch (error) {
  console.error("state read failed", error.nodeType, error.attempts, error.message);
  return { state: "unknown" };
}

Once any call begins execution, the engine no longer retries the outer script node, so a later error cannot replay earlier calls. Put retries on the individual call. Nothing rolls back the external effects of earlier calls.

A script execution admits at most 100 calls. Exhausting that budget fails the script even if the exception or command status is caught. The script's wall-clock timeout includes time spent inside calls, including waits. The flow's own run timeout is measured separately and does not count time a run spends parked in a durable wait.

Triggers, annotations, link and subflow routing, nested scripts, and fan-in nodes such as join, batch, and aggregate are not callable. Nodes whose inputs or outputs cannot be expressed as JSON or base64 text are also excluded. Plugin and agent nodes follow the same rules. A call to an unavailable type fails rather than reaching a different implementation.

The script.network policy applies only to the script's own http() helper. An HTTP node, server file node, plugin, or agent action called through nodes has the same network, file, and host authority it has on the canvas, and no more.

Called nodes can read and write run, flow, and global variables while the script is running. When the script finishes, only values the script itself changed are written back. Changes made by called nodes are preserved unless the script deliberately changed the same key. Called nodes see the script's initial variable snapshot, not uncommitted script writes.

Editor completion and checks

The flow JavaScript, Python, and Bash editors take node functions and documentation from the installed node types. They offer function and member completion, signature help, hover documentation, and diagnostics for syntax errors, wrong argument counts, missing or unknown options, incorrect values, and invalid output usage. Conditional fields stay optional in the editor, and the server checks them against their conditions.

Detailed output properties come from the node's payload schema. A node with only a broad output type falls back to any, so the editor neither invents properties nor rejects valid dynamic payloads. The server checks computed configuration, which the editor cannot check statically, before execution.

You can save a draft that has diagnostics. Test runs and deployment reject statically known errors in the executable script. Static verification never executes a node or integration, and some checks can only happen when the script runs.

These node functions and diagnostics appear only in supported server flow script editors. MQTT device scripts, payload transforms, remote-agent scripts, JSON documents, and Markdown do not receive them.

Testing a script

Test in the editor opens the message the script receives, as JSON you can edit:

{
  "payload": { "example": 1 },
  "topic": "sensors/office",
  "meta": {}
}

Add input for a script that reads named ports, and vars, flow, or global for one that reads a variable scope. Running shows what the script printed alongside what it returned.

It runs the real sandbox with the server's own limits and network policy, so what happens here is what happens in a run, with two differences: variable writes are reported, not saved, and nodes and node are unavailable. Use an isolated flow-node test or a flow test run for a script that calls nodes. Those tests can call every eligible node and can perform real actions.

Variable scopes

Four scopes, however your language spells the accessors. The name defaults to payload and the scope to msg.

Scope Lives for Notes
msg this message Reads resolve a dot path; a path starting with topic or meta addresses that field, anything else reads the payload
run the whole run Shared with nodes outside this message's path. Spelled vars as an object
flow across runs Persisted
global across runs and flows Persisted

The engine applies writes to flow and global when the script finishes, not at the moment of assignment, so two runs touching the same key settle last-writer-wins rather than serializing. A script that throws, exits non-zero, or times out discards these writes. Once the script itself finishes they are kept, even if the node then fails because its result has the wrong shape for its outputs.


JavaScript

Scripts run in a built-in ECMAScript interpreter. Your code is the body of a function, which is why a top-level return works.

What is available

Most of modern JavaScript through ES6 and beyond: let/const, arrow functions, template literals, classes, destructuring, spread, Map/Set, generators, Symbol, BigInt, optional chaining and ??, Object.entries, Array.prototype.flat, String.prototype.padStart. The standard globals JSON, Math, Date, RegExp, and encodeURIComponent are all there, and Date is the real clock.

Not available: require and import. There is no module system, so a script is one file with no dependencies. No fetch, setTimeout, or setInterval. No process, Buffer, atob/btoa, TextEncoder, or structuredClone.

Everything is synchronous. There is no event loop. Promise exists and async functions can be defined, but await is a syntax error and nothing would ever resolve them. http() blocks until the response arrives and returns it, so a request needs no await.

Globals installed for you: msg, payload, topic, meta, input, vars, flow, global, get, set, http, console. Scripts in a server flow also receive nodes.

The message

payload          // the payload on the first input port
topic            // the topic
meta             // the metadata object
msg              // { payload, topic, meta }
input.threshold  // the payload on a port declared "threshold"

Every declared input arrives in input under its ID, including the first. payload is the same value reached the short way. A port nothing is wired to is undefined, so read it with a fallback:

const limit = Number(input.threshold ?? 30);

These are a snapshot. Assigning to payload or msg.payload changes nothing outside the script.

Returning a value

return a value and it becomes the new payload. Return nothing and the payload passes through unchanged, which is what a script that only logs or only writes variables wants.

return { celsius: reading, hot: reading > 30 };

With several outputs declared, return an object keyed by port ID:

// Outputs: "hot", "cold"
return reading > 30 ? { hot: reading } : { cold: reading };

The value crosses the boundary as JSON, so objects, arrays, strings, numbers, booleans, and null survive; functions, classes, and cyclic references do not. A script that both returns a value and writes the payload with set() gets the return value, because the engine applies it last.

Variables

const count = get("count", "flow") || 0;   // read; scope defaults to "msg"
set("count", count + 1, "flow");           // write
const temp = get("payload.temperature");   // dot path into the message
set("payload.tag", "seen");                // writes the outgoing message
set("count", null, "flow");                // null clears

vars, flow, and global are also plain objects, and assigning into them is equivalent to calling set:

flow.count = (flow.count || 0) + 1;

HTTP

const res = http("https://api.example.com/status");
const res2 = http({
  method: "POST",
  url: "https://api.example.com/items",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "thing" }),
});
const res3 = http("https://api.example.com/items", { method: "DELETE" });

A response is { status, ok, headers, body, error }. ok is true for a 2xx status, headers have lower-cased names, and body is text. A refused or failed request does not throw. It comes back with error set, so check error before trusting the body.

if (res.error) throw new Error("request failed: " + res.error);
const data = res.json();   // throws when the body is not JSON

Logging

console.log, .info, .warn, .error, and .debug all capture to the node's run history, so a script's logs show up in the run panel without wiring a debug node. Objects render as JSON.

Binary payloads

A binary payload arrives as base64 text, because JSON cannot carry raw bytes. There is no atob and no Buffer here, so JavaScript cannot decode one. Put a base64 node before the script to hand it a decoded value, or pass the text through and let a node downstream decode it.

Failure

Throwing fails the node, as does running past the timeout. Syntax errors are reported against your own line numbers.

if (!payload.id) throw new Error("payload has no id");

Example

const reading = Number(payload.temperature ?? 0);
const limit = Number(input.threshold ?? 30);

if (reading > limit) {
  const res = http({
    method: "POST",
    url: "https://api.example.com/alert",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ topic, reading }),
  });
  if (res.error) throw new Error("alert failed: " + res.error);
  console.log("alerted", res.status);
}

set("last_reading", reading, "flow");
return { reading, limit, over: reading > limit };

Python

Scripts run on CPython 3.12 compiled to WebAssembly, under WASI. The interpreter is real CPython with the real standard library. WASI provides no sockets and no processes, and the only directories that exist are the interpreter's own.

What is available

The standard library: json, re, datetime, math, base64, hashlib, uuid, random, collections, itertools, functools, decimal, statistics, csv, io, textwrap, and the rest of the pure-Python modules.

Not available: socket raises OSError and subprocess reports that WASI has no processes. threading cannot start a thread. urllib imports and then fails at connect time, because it needs the sockets that are not there. Use karakuri.get and karakuri.post instead. There is no host filesystem to open.

The clock is frozen. Python has no access to the host clock, so time.time() and datetime.now() report 2022-01-01 in every run and advance by microseconds regardless of how long the script takes. Take the time from the message, from a variable, or from a node that knows it.

Four names are taken. input, vars, get, and set are the message and variable accessors inside your script. The Python builtins they shadow stay reachable as builtins.input, builtins.vars, and builtins.set. Scripts in a server flow also receive nodes.

The message

payload                     # the payload on the first input port
topic                       # the topic
meta                        # the metadata dict
msg                         # {"payload": ..., "topic": ..., "meta": ...}
input["threshold"]          # the payload on a port declared "threshold"

Every declared input arrives in input under its ID, including the first. payload is the same value reached the short way. A port nothing is wired to is missing from the dict, so read it with a fallback:

limit = float(input.get("threshold", 30))

These are a snapshot. Rebinding payload changes nothing outside the script.

Calling nodes

A script in a server flow receives nodes in its globals and as karakuri.nodes. Exact node types use item access, aliases use attributes, and nodes.call accepts a computed type:

import karakuri

config = {
    "property": "payload",
    "target": "payload",
    "encoding": "standard",
    "padding": True,
}
encoded = nodes.base64Encode(config, {"in": msg})
canonical = nodes["base64-encode"](config, {"in": msg})
same = nodes.call("base64-encode", config, {"in": msg})
result = encoded["out"][0]["payload"]

Inputs and outputs are dictionaries of complete messages. Every ordinary output is a list, including when it is empty. Config, input, and option field IDs are the same ones the node's config panel uses. To pass options without message inputs, use None for inputs. Binary payloads remain base64 text.

A failure raises karakuri.NodeCallError. Its attributes are message, node_type, invocation_id, sequence, attempts, retryable, retry_after_ms, details, and fatal:

try:
    state = nodes.haGetState({
        "connection": "home-assistant-uuid",
        "entity_id": "light.kitchen",
    })
    result = state["out"][0]["payload"]
except karakuri.NodeCallError as error:
    print(error.node_type, error.attempts, error.message)
    result = {"state": "unknown"}

An uncaught exception fails the script. Catching a call-budget exception does not let the script finish. Standalone tests, device scripts, and remote-agent Python scripts do not receive nodes.

Returning a value

Assign to result, or define handle(msg) and return from it. Leave result unset and the payload passes through unchanged, which is what a script that only logs or only writes variables wants.

result = {"celsius": reading, "hot": reading > 30}
def handle(msg):
    return {"topic": msg["topic"]}

With several outputs declared, set result to a dict keyed by port ID:

# Outputs: "hot", "cold"
result = {"hot": reading} if reading > 30 else {"cold": reading}

The value crosses the boundary as JSON, so dicts, lists, strings, numbers, booleans, and None survive; anything else is rendered as its string form. A script that both sets result and writes the payload with set() gets result, because the engine applies it last.

Variables

count = get("count", "flow") or 0     # read; scope defaults to "msg"
set("count", count + 1, "flow")       # write
temp = get("payload.temperature")     # dot path into the message
set("payload.tag", "seen")            # writes the outgoing message
set("count", None, "flow")            # None clears

vars, flow, and global are also plain dicts, and assigning into them is equivalent to calling set:

flow["count"] = flow.get("count", 0) + 1

The module attribute for the global scope is karakuri.global_, because global is a Python keyword, but your script's own namespace still calls it global.

HTTP

import karakuri

res = karakuri.get("https://api.example.com/status")
res = karakuri.post("https://api.example.com/items", {"name": "thing"})   # sends JSON
res = karakuri.http("PUT", url, headers={"X-Key": "..."}, body="raw text")

A Response carries status, ok (a 2xx status), headers with lower-cased names, and body as text, plus json() to decode it. A refused or failed request raises karakuri.HTTPError.

try:
    res = karakuri.get(url)
    data = res.json()
except karakuri.HTTPError as err:
    raise RuntimeError("request failed: %s" % err)

Logging

print() captures to the node's run history, so a script's logs show up in the run panel without wiring a debug node.

Binary payloads

A binary payload arrives as base64 text, because JSON cannot carry raw bytes. Python is the one language here that can decode it in the script:

import base64
raw = base64.b64decode(payload)
result = base64.b64encode(raw).decode()   # base64 text going back out

Failure

Raising fails the node, as does running past the timeout. The traceback shows only your own frames.

if "id" not in payload:
    raise ValueError("payload has no id")

Example

import karakuri

reading = float(payload.get("temperature", 0))
limit = float(input.get("threshold", 30))

if reading > limit:
    try:
        res = karakuri.post("https://api.example.com/alert", {"topic": topic, "reading": reading})
        print("alerted", res.status)
    except karakuri.HTTPError as err:
        raise RuntimeError("alert failed: %s" % err)

set("last_reading", reading, "flow")
result = {"reading": reading, "limit": limit, "over": reading > limit}

Bash

Scripts run in a built-in bash interpreter that never starts a process. The language is bash; the command set is not.

What is available

The shell itself, in full: functions, arrays, arithmetic, [[ ]], case, loops, parameter expansion (${v^^}, ${v:1:2}, ${#v}, ${v/a/b}), brace expansion, command substitution, pipes, redirects, heredocs, trap, local. Builtins such as echo, printf, read, test, export, and exit work as usual.

Not available: every external command. There is no cat, date, sed, awk, grep, jq, curl, sleep, or base64. The interpreter denies anything not in the table below, so a script cannot reach the host by spawning a process. /dev/null is the only path that opens, and $PATH and $HOME are empty. The script sees no files. A glob matches nothing and stays literal, file tests such as [ -e path ] are always false, and $PWD is the root.

Commands provided instead:

Command Does
log <message> Writes to the run log (stderr), leaving stdout clean
http <method> <url> [body] [header:value ...] Performs a request; body to stdout, status to stderr
jsonget <path> [json] Reads a dot path out of a JSON document, or out of stdin when the document is omitted. Numeric segments index arrays. An integer prints with the digits the document wrote, at any size
getvar [-s <scope>] [name] Prints a variable
setvar [-s <scope>] <name> [value] Writes a variable; a value that parses as JSON is stored decoded
node <type> <config> [inputs] [options] Server flows only: calls an eligible node through the engine and prints its output or error as JSON

The message

$PAYLOAD   # the payload on the first input port, as JSON, also on stdin
$TOPIC     # the topic
$META      # the metadata, as JSON
$INPUT     # every connected port, as JSON keyed by port ID
$MSG       # the complete first input message, as JSON

Read into any of them with jsonget. With no second argument it reads stdin:

reading=$(jsonget temperature "$PAYLOAD")
reading=$(jsonget temperature)              # same thing, from stdin
limit=$(jsonget threshold "$INPUT")         # a port declared "threshold"

A path that is not there prints nothing, so fill in a fallback:

[ -z "$limit" ] && limit=30

Scalars print bare so they interpolate cleanly; objects and arrays print as JSON.

Calling nodes

A script in a server flow receives a node builtin. It is part of the sandbox, not an external command. Use the exact type or an unambiguous alias as the first argument, followed by config, inputs, and options as JSON documents. node call accepts a computed type:

config='{"property":"payload","target":"payload","encoding":"standard","padding":true}'
inputs="{\"in\":$MSG}"
encoded=$(node base64Encode "$config" "$inputs")
canonical=$(node base64-encode "$config" "$inputs")
same=$(node call base64-encode "$config" "$inputs")
jsonget out.0.payload "$encoded"

MSG contains the complete first input message, which makes the common {"in": ...} envelope possible without a JSON encoder. Inputs and outputs contain complete messages keyed by port. Every ordinary output is an array, including when it is empty. To pass options without inputs, pass {} as the inputs argument.

A successful call prints its output object and exits zero. A failed call prints a structured error object and exits nonzero. The error fields are name, message, node_type, invocation_id, sequence, attempts, retryable, optional retry_after_ms, optional details, and fatal. Command substitution captures that document in both cases:

state_config='{"connection":"home-assistant-uuid","entity_id":"light.kitchen"}'
if state=$(node haGetState "$state_config"); then
  jsonget out.0.payload "$state"
else
  attempts=$(jsonget attempts "$state")
  node_type=$(jsonget node_type "$state")
  log "$node_type failed after $attempts attempts"
  printf '{"state":"unknown"}\n'
fi

Checking the status handles the failure. An unchecked status that becomes the script result fails the node under ordinary shell rules. A call-budget failure remains fatal even when its status is checked. Calls run as simple foreground commands; a node call in the background or in a pipeline is rejected before it runs. Computed or escaped command names, command wrappers, aliases, shopt, eval, traps, and duplicate function declarations are also rejected when node is available, because they could hide a node call from the check that runs before the script starts. Standalone tests, device scripts, and remote-agent Bash scripts do not receive node.

Returning a value

Standard output is the result: parsed as JSON when it parses, kept as trimmed text when it does not. Print nothing and the payload passes through unchanged, which is what a script that only logs or only writes variables wants.

printf '{"celsius": %s, "hot": %s}\n' "$reading" "$hot"

With several outputs declared, print an object keyed by port ID:

# Outputs: "hot", "cold"
# The shell test is integer-only, so trim any decimal before comparing.
if [ "${reading%%.*}" -gt 30 ]; then
  printf '{"hot": %s}\n' "$reading"
else
  printf '{"cold": %s}\n' "$reading"
fi

Logging goes to stderr for this reason. An echo meant as a progress message would corrupt the payload.

Variables

count=$(getvar -s flow count)        # read; scope defaults to msg
[ -z "$count" ] && count=0
setvar -s flow count $((count+1))    # write
temp=$(getvar payload.temperature)   # dot path into the message
setvar payload.tag seen              # writes the outgoing message
setvar -s flow count                 # no value clears

$VARS, $FLOW, and $GLOBAL hold the three non-message scopes as JSON documents to read with jsonget. They are a snapshot. Write with setvar.

HTTP

body=$(http GET https://api.example.com/status)
body=$(http POST https://api.example.com/items '{"name":"thing"}' Content-Type:application/json)

The response body goes to stdout and the status to stderr, so $(http ...) captures the body alone. A refused or failed request exits non-zero, so handle it explicitly:

body=$(http GET "$url") || exit 1

Logging

log <message> writes to the run log, so it shows up in the run panel without wiring a debug node. Anything else you send to stderr lands there too.

Binary payloads

A binary payload arrives as base64 text in $PAYLOAD, because JSON cannot carry raw bytes. There is no base64 command in the sandbox, so bash cannot decode one. Put a base64 node before the script to hand it a decoded value, or pass the text through and let a node downstream decode it.

Failure

Exiting non-zero fails the node, as does running past the timeout. Nothing else does. A command that fails mid-script leaves the script running unless you check it.

[ -n "$reading" ] || { log "payload has no temperature"; exit 1; }

Example

reading=$(jsonget temperature "$PAYLOAD")
[ -z "$reading" ] && reading=0
limit=$(jsonget threshold "$INPUT")
[ -z "$limit" ] && limit=30

# The shell test is integer-only, so trim any decimal before comparing.
if [ "${reading%%.*}" -gt "${limit%%.*}" ]; then
  http POST https://api.example.com/alert \
    "{\"topic\":\"$TOPIC\",\"reading\":$reading}" \
    Content-Type:application/json > /dev/null || exit 1
  log "alerted for $reading"
fi

setvar -s flow last_reading "$reading"
printf '{"reading": %s, "limit": %s}\n' "$reading" "$limit"

AI nodes

Karakuri talks to language models through the AI node set: a model node that names which provider and model to use, an agent node that sends a prompt and runs the tools the model calls, and tool nodes that define what those tools are. They connect in the flow editor through typed sockets. A model travels on an ai-model wire and a tool set on an ai-tool wire, and the editor rejects a misconnected graph before anything runs.

Provider connections

Configure a provider once under Settings, Connections, then use it in any number of flows. One AI Provider connection kind covers every provider. Its Provider field picks who the connection talks to, and Test checks the endpoint by listing its models. Plugins can add more providers to the picker.

Provider For Notes
OpenAI api.openai.com, or a ChatGPT subscription API key, or ChatGPT account sign-in (below).
OpenAI-compatible server LM Studio, llama-swap, vLLM, LocalAI, OpenRouter (https://openrouter.ai/api/v1) Base URL required, including the version prefix (http://localhost:1234/v1). Key optional.
Anthropic api.anthropic.com API key required. No embeddings API.
Google Gemini generativelanguage.googleapis.com API key required.
Ollama A local or remote Ollama Address only; the /v1 API path is appended automatically.
Hermes Agent A local or remote Hermes profile gateway API key required. Hermes runs its own tools, so its models do not accept Karakuri tool or memory wires.

Every provider connection has an optional Context window, the number of tokens a request may hold for its models. Leave it empty to detect it; Ollama needs it set. See Context compaction.

MCP servers are a separate connection kind, because an MCP connection provides tools rather than models.

Signing in with a ChatGPT account

The OpenAI provider's Authentication field offers ChatGPT account (Codex) beside the API key. Requests then bill a ChatGPT Plus or Pro subscription instead of platform credit. Click Sign in with ChatGPT, finish the OpenAI login in the new browser tab, then save the connection. When browser login is unavailable, use Import Codex auth file in the same panel and paste the contents of ~/.codex/auth.json. Saving either form tests the account before the dialog closes. Karakuri stores the sign-in encrypted and renews it. The model picker offers the models the subscription can use (gpt-5, gpt-5-codex, and others). If the connection stops authenticating after the server has been down for a long time, edit it and sign in again.

The AI Model node

AI Model names a provider connection, a model identifier, sampling settings (temperature and max tokens), and reasoning settings, and emits a model on its ai-model output. The model field completes from the connection's model list, which refreshes every few minutes. You can still type any model the provider accepts, because some providers serve models their listing omits. Wire the output into an agent's Model socket. One model node can feed any number of agents, so switching every agent to a new model is one edit.

Reasoning effort selects the provider's named reasoning depth. Reasoning budget sets a token budget for older Anthropic models and Gemini 2.5. Set one or the other, not both. Anthropic requires the budget to be below max tokens; with Max tokens empty, an Anthropic request asks for 4,096 tokens plus the budget. Empty fields leave the provider default in force. Reasoning carries across tool calls, so an agent can keep reasoning after it sees a tool result. Support depends on the selected model. A level or budget the model does not accept fails the model call; Karakuri never changes it silently.

Anthropic reasoning requests leave out temperature, because the API does not accept sampling controls with thinking. Karakuri also drops a configured temperature for Claude models newer than Opus 4.6, which no longer accept it. Older Claude models and non-Claude models behind a gateway still receive it.

Context window, Automatic compaction, and Compaction buffer control context compaction. Context window overrides the connection's setting and detection for this model. Automatic compaction is on by default. The buffer is a percentage such as 20% or a token count; a malformed buffer fails the model node.

The AI Agent node

AI Agent sends a prompt or conversation to the model and, when tools are attached, runs whatever the model calls until it settles on an answer.

When Tools or Memory is wired, the node rejects a model whose provider does not accept tools. Hermes models work when both sockets are empty, because the Hermes profile runs its own tools and memory.

  • Model is a permanent input socket taking exactly one ai-model wire.
  • Tools is a permanent input socket taking any number of ai-tool wires; every attached set is offered to the model.
  • Input selects where the request comes from. Prompt renders one configured user-message template. Transcript renders a configured list of User, Assistant, Tool, and System messages. Input reads the incoming message directly. A string payload becomes one user message, while an array of {role, text} entries or an object's transcript property becomes the conversation. System entries in incoming data are ignored; the node's System prompt always applies.
  • Prompt and System prompt support {{ }} expressions, so Summarize: {{ payload.text }} works as it does elsewhere.
  • Transcript mode shows an Add message editor, and every configured message supports {{ }} expressions. The Input selector and the configured Prompt and Transcript values never become parameter sockets. Transcript data received in Input mode is used as plain text, so {{ }} text written by a model is never evaluated.
  • Attach binary payload as image sends the incoming message's binary payload, such as a webhook's camera frame or an HTTP response, to the model as an image beside the prompt. Use it for bytes that arrive on the message path. The image type comes from what the producing node declared (meta.mime, meta.content_type, or the meta.format a screenshot node sets); bytes with no declared type fail the node.
  • Images is a permanent input socket taking any number of image wires, for prompts about more than one picture. Each wire comes from an Image node (folder Parsers, beside Document). Wire a screenshot or a binary file read into the Image node's Source socket and pick its image type there, because a value wire carries only the bytes. The model receives the payload image first, when attached, then the wired images in wire order. Images cannot be placed inside the prompt text, so refer to them by position: "image 1 is the driveway camera, image 2 the porch".
  • Response format set to JSON asks the model for a JSON object and emits it decoded (the output port reports object). If the first reply is not valid JSON, the node shows the model the error and gives it one chance to repair it.
  • Response schema (JSON only) is a JSON Schema the reply must match. OpenAI-compatible providers enforce it directly, Gemini does when no tools are attached, and other providers receive it in the system prompt. In every case Karakuri checks the reply against types, required, properties, items, and enum. A reply that still does not match after the repair attempt fails onto the error branch.
  • Max iterations bounds the tool loop. A model that never gives a final answer fails the node instead of running up the bill.

A tool failure is not a node failure. The error text goes back to the model as the tool's result, so the model can recover. Provider errors, such as a bad key, a missing model, or an unreachable endpoint, fail the node onto its error branch and are retryable.

The answer is the payload. The metadata carries model, accumulated usage (input and output tokens across every call of the loop), and tool_calls, a record of each call with its arguments and result. Run history keeps this metadata, so you can read back what a misbehaving loop did.

The node builds the Response output (port ID transcript) only when it is wired. Its object carries transcript, responses, and the state needed to continue the conversation. transcript is the replayable message history: earlier turns, the rendered prompt, each tool round (tool_calls on the assistant turn, tool_call_id/tool_name on the result), and the final answer. It leaves out the system prompt so the receiving node keeps its own instructions. responses holds every raw provider response in call order, including tool-loop and JSON-repair calls. A streamed response is stored as its list of events.

The object can also carry session_id when Hermes owns the conversation, cache_key for providers that cache prompts per conversation, and provider-specific reasoning state. Pass the whole object to the next AI node. Taking only the transcript array loses the session and reasoning state.

This output can go back to HA Assist through its Response input. Home Assistant keeps the complete object and appends the next user turn to its transcript array. Images are kept as a count in the history, so a screenshot-heavy conversation does not carry the image bytes twice.

HA Assist's AI decides follow-up mode reads a JSON response containing a response string and a continue_conversation boolean. Set the response format to JSON with a schema that requires both. HA Assist speaks the response string, sends the boolean to Home Assistant, and keeps the full object for the next turn. When streaming, HA Assist holds the text until the complete JSON object arrives, while tool progress still shows live.

Enable Stream to receive text as the provider generates it. This changes the Response output from object to ai-stream, so it can no longer be wired into nodes that only accept completed objects. The stream carries content.delta events and any provider progress events, then one response.completed event. Hermes emits tool.progress while its built-in tools run, with the tool call ID, name, label, and status. The final event carries both the completed output value and the full response object.

When a provider returns readable reasoning, the assistant entry carries it as reasoning_summary. Encrypted or signed reasoning stays on the assistant turn as opaque_state, and Karakuri sends it back only to the provider that produced it.

The usage metadata reports cached_input_tokens and cache_write_input_tokens beside input and output tokens. Karakuri uses OpenAI, Anthropic, and Gemini prompt caching automatically. A cache hit needs the same model, system prompt, tools, and earlier messages as the previous request.

Context compaction

When a conversation outgrows the model's context window, Karakuri summarizes older history instead of failing. This applies to AI Agent, node chat, and Kuri.

Before every model request, including tool rounds, Karakuri estimates the prompt size. When it passes the window minus a buffer, Karakuri summarizes older history. The default buffer keeps 15% of the window free, raised to 16,000 tokens or a quarter of the window, whichever is smaller. On a 32,768-token model that is 8,192 tokens. When the provider rejects a request as too long, Karakuri compacts and sends it once more. A second rejection fails the node with the provider's error, and its retry policy applies.

Compaction makes one extra request to the same model for a structured summary covering the objective, requirements, decisions, work state, next step, relevant items, and important context. The newest exchange is kept word for word, up to 15,000 tokens or a quarter of the window, and the summary replaces everything before it. The next compaction updates that summary. Compaction only runs when at least 1,000 tokens or 5% of the window can be removed, so a large system prompt near the limit does not cause a summary every round. The system prompt and tool definitions are never summarized, so when they alone nearly fill the window, only history can shrink.

The window comes from the AI Model node's Context window, then the connection's, then what the provider reports or what an overflow error stated. OpenRouter, vLLM, llama.cpp, llama-swap, and Gemini report windows. Ollama silently cuts requests down to its num_ctx instead of rejecting them, so set the Ollama connection's Context window. With no known window, only an overflow error triggers compaction.

Each compaction adds the summary request's tokens to usage, adds {reason, before_tokens, after_tokens} to the output's compactions metadata, and adds the summary to the Response object's compactions. A streamed agent emits context.compacted. The Response transcript starts from the summary, so continuing the conversation stays compacted. Providers that keep history in their own session, such as Hermes, are never compacted.

Testing an AI node in chat

Click Chat at the right of an AI Agent or AI Basic Chain canvas title. The chat window moves and resizes like Kuri's window, and the canvas stays usable behind it. It uses the node's configured model, tools, memory, images, and response settings. There is no model picker or execution switch.

Each message you type is sent as a string on In. In Prompt mode, the configured prompt renders against it; use {{ payload }} where your message belongs. Transcript mode renders the configured rows against it. Input mode sends your message directly. The configured system prompt applies on every turn, and each turn continues the conversation from the previous reply. New chat clears the conversation in the browser. It does not delete memory already saved by a wired AI Memory node.

Unsaved draft edits are saved before each turn. Only the selected node, the values it pulls, and its tool branches run. Ordinary output and error branches do not run, and chat does not replace the flow's last-run history or its deployment. Variables and node stores start empty for each turn. Tool actions and memory writes are real. A node inside a local subgraph can be tested directly, but values that need a caller or an upstream message need a full flow run.

Replies stream into the transcript, and completed tool calls show their arguments and results. When the model disclosed reasoning, a collapsed Reasoning section above the reply holds it once the turn completes. A Context compacted divider marks where compaction summarized earlier conversation. Stop, a disconnect, or the five-minute turn limit cancels the turn. Chat drops a failed or stopped turn from the conversation, so the next turn does not resend its partial tool rounds. Chat runs the node once even if the draft has a retry override; tool branches keep their own retry policies and the agent keeps its iteration limit. The text box cannot supply a binary image payload. Turn off Attach binary payload as image for chat, or test the flow from its normal image-producing start.

The AI Basic Chain node

AI Basic Chain sends one prompt or transcript to an AI Model without adding Karakuri tools or memory. It has the same prompt, transcript, system prompt, image, and structured-response controls as AI Agent, but no Tools, Memory, or Max iterations fields.

Use it for a Hermes profile, which keeps control of its own personality, skills, memory, MCP servers, and tools, or for any request that needs one model reply without a tool loop.

Hermes serves profiles through the API server attached to its gateway. Enable it in the profile's .env, give it a strong key, then restart that profile's gateway:

API_SERVER_ENABLED=true
API_SERVER_KEY=<a random secret>

Create an AI Provider connection in Karakuri with Provider set to Hermes Agent. Its default base URL is http://127.0.0.1:8642/v1; change the address when Hermes runs on another host. Paste the same key and test the connection. Each connection belongs to the profile that gateway serves, so the model node has no separate profile setting. Connect that AI Model to AI Basic Chain, or to AI Agent with no tools or memory attached.

The answer is the payload, and the metadata carries the configured model and token usage. The Response output has the same shape as AI Agent's. When it is wired, the transcript includes the tool calls Hermes made with its built-in tools, at the cost of one extra request to Hermes. The Hermes session ID is sent back on the next request so Hermes can continue the same session.

The Images socket accepts any number of image values and sends them beside the prompt in wire order. Attach binary payload as image uses the incoming message's bytes instead. That payload must declare an image MIME type; screenshot nodes already do. The selected model must support images.

Tool nodes

Tool nodes emit an ai-tool set, which holds what the model sees (name, description, and a JSON Schema for the arguments) and what runs when it calls the tool. The model decides when to call a tool from the description alone, so say in it when the tool applies.

  • MCP Tools offers an MCP server's whole catalog. It lists the connection's tools live, with an include/exclude filter and an optional name prefix for wiring two servers whose tool names collide.
  • Tool declares what the model sees and runs a branch of the canvas as the tool body, so anything a flow can do, such as a script, an HTTP request, a Home Assistant call, or a command on a remote agent, can become a tool.

Tool names must be unique across everything wired to one agent (and unique per graph for Tool nodes), and must be 1 to 64 characters of letters, digits, _, and -.

The Tool node

A Tool node has a name, the description the model decides by, and an argument list. Each argument has a name, a type, a description, and a required flag, and the node builds the JSON Schema the model sees from that list.

Three kinds of port make the body work:

  • Call (output) starts the branch. When the model calls the tool, a message with the arguments object as its payload leaves here, and whatever is wired downstream runs, on the server or on a remote agent.
  • Return (the socket on the node's bottom edge) receives the branch's result. Wire the branch's last node back into it; the message arriving there is what the model sees as the result. The loop this draws on the canvas is intended.
  • Each argument is an output port of its declared type. Branch nodes can bind config fields to them with value wires, and each call sees its own arguments, even when two calls happen in one run. The call message's payload also carries all of them, so a script node in the branch can read payload.city. Argument ports can only be read inside the branch.

A branch that returns a binary payload with a declared image type gives the model the picture itself, so a Tool node around an agent's screenshot node is a vision tool. Binary with no declared image type is reported to the model as an error.

Concurrent calls (two agents, or one agent calling twice) never share state, and every node in the branch records its run in run history, so you can trace a misbehaving tool node by node. When a branch node fails and has no error branch wired, the failure becomes the call's result for the model, not a run failure. To shape that result yourself, wire the node's error output into Return. Timeout bounds one call; a branch that never reaches Return reports timed out to the model.

Deploying requires a complete loop, with Call and Return wired and a tool name unique in the graph.

Memory

A memory store is a named bank of memories, defined under Settings, Memory. It holds the conversation transcripts an agent resumes and the facts it recalls. Flows share stores by name, like controls, so two flows naming the same store share one conversation and one set of facts.

Recall combines keyword matching, similarity search, and importance, and older memories count for less over time at the rate set by the store's halflife. Similarity search needs the store to name an embedding connection and model (any OpenAI-compatible server or Gemini connection; Anthropic has no embeddings API). Keyword search finds a new memory immediately, and similarity search finds it a few seconds later. Changing the embedding connection or model re-processes existing memories in the background. If the embedding provider fails, the affected memories stay searchable by keywords, and Karakuri processes them again the next time the store loads. Editing a memory's text or tags re-processes it.

AI Memory emits a memory on its ai-memory output; wire it into the agent's Memory socket. It configures:

  • Session is the conversation key, rendered against the agent's incoming message ({{ payload.user }}), so one store can hold a conversation per person, per room, or one shared conversation (leave it empty). Session-scoped memories never appear in another session's recall.
  • Transcript window sets how many past turns go ahead of the new prompt, which lets the agent resume a conversation. The replay always starts on a user turn, so when the window cuts an exchange in half, that exchange's answer is left out. The store caps transcripts per session and drops the oldest turns first.
  • Recalled memories sets how many memories to recall. The ones most relevant to the rendered prompt are added to the system prompt with their dates, so the model starts out knowing what matters. Recall from conversations also searches past transcripts.
  • Diversify results considers more candidates and drops near-duplicate memories, keeping each result's original relevance score.
  • Offer remember and recall tools gives the model a remember tool (text, importance, tags, session-only) and a recall tool (query, limit), so it can save facts worth keeping and search for context. No tool node is needed.
  • Save conversations adds each prompt and final answer to the session's transcript.

The output metadata carries memory (store, session, and how many memories were recalled). The settings page lets you browse, search, edit, and delete memories and clear sessions; its search ranks results the same way agent recall does. Clearing the shared session (the one with no name) removes its transcript and keeps the store's global facts.

Two flow nodes use a store without a model. Remember stores a text (with session, importance, tags, and an optional time to live in hours) and passes the message through. Recall searches and emits the matching memories as the payload, [{text, score, kind, importance, created_at, tags?, session?}], so a flow can route on whether anything was remembered. Both nodes have Diversify results; on AI Memory the setting also applies to the agent's recall tool.

The MCP Call node

MCP Call calls one tool on an MCP server directly from the flow, with no model involved. The arguments document supports {{ }} expressions rendered against the message. A tool failure fails the node onto its error branch.

Guardrails

Two nodes check the text moving through an AI flow. AI Guardrail checks it and routes, and AI Sanitize rewrites it. Both read the text named by their Text template ({{ payload.prompt }}), or the payload as text when the field is empty. Put one in front of an agent to check what reaches the model, or behind it to check what the model produced.

AI Guardrail routes the message to its Pass or Fail output. Pass emits it unchanged. Fail adds meta.guardrail.violations ([{check, kind?, match?, reason?, confidence?}]) and leaves the payload alone, so the failing branch can log, alert, or hand the text to a person. Failing a check is routing, not an error. The error branch is for a provider failure or an invalid pattern. The checks are:

  • Blocked keywords match case-insensitively anywhere in the text.
  • PII covers email, phone, credit card, SSN, IP address, and IBAN. Pick a subset, or leave the field empty for all of them. Card numbers must pass the Luhn check, so a random run of digits is not flagged.
  • Secret keys covers AWS access keys, GitHub, Slack, OpenAI, and Google tokens, JWTs, PEM private keys, and password:/api_key=-style assignments, plus long random-looking words that match no known format. Secrets sensitivity tunes that last check. Strict flags shorter and less random strings and also checks URL- and filename-shaped words; permissive flags only long, very random ones. The reported match is masked after its first characters.
  • URLs requires every URL to use an allowed scheme (default https, http) and, when a domain list is given, to be on a listed domain or one of its subdomains. evilexample.com never passes an example.com allowance.
  • Custom patterns takes Go regular expressions, one per line.
  • Model-scored checks are jailbreak, NSFW, and topic. They need judgment, so they ask a model for a verdict (one call covers every selected check) and fail the text when a check is flagged at or above the confidence threshold (default 0.7). Topic takes an allowed scope describing what the text may be about. Selecting any of these adds a Model socket that must be wired. A guardrail with only the other checks has no model input.

AI Sanitize emits the text with sensitive parts replaced by placeholders: [email] and similar for PII, [secret], [url], and [redacted] for keywords and custom patterns. PII and secret keys are on by default; URLs, keywords, and patterns are opt-in. One placeholder, named after the widest match, replaces overlapping matches together, so no part of a credential or URL is left behind. The sanitized text is the payload (the output port reports string), and meta.sanitized counts what each check removed without repeating it. AI Sanitize uses the same checks as AI Guardrail and never calls a model, so it is safe to put in front of one.

Extracting and classifying

These nodes handle one-off structured jobs that do not need an agent. Each takes a model on its Model socket and reads the text named by its Text template, or the payload as text when it is empty.

AI Extract pulls declared attributes out of text into a JSON object. The attributes list uses the same editor as a Tool node's arguments (name, type, description, required), and the node builds the JSON Schema from it. The model finds each attribute by its description. An optional attribute the text does not mention is left out; a required one the model cannot supply fails the node onto its error branch rather than producing a guess. The object is the payload (the output port reports object), with model and usage in the metadata.

AI Classify routes by meaning. Each entry in the categories field is an output port, the model picks one, and the message leaves on that port unchanged, with the verdict (category, confidence, reason) in meta.classification. Text that fits no category leaves on Other. The model decides from the category names and the instructions field, so describe what belongs where when the names alone are ambiguous. For sentiment analysis, use positive, neutral, negative as the categories.

AI Summarize handles documents too long for one model call. It splits the text into chunks, summarizes each chunk in order, then combines the partial summaries until one remains. Text defaults to the payload, Instructions states what the summary must keep, and Chunk size controls the size of each request. Calls run one at a time, with at most 64 calls and eight rounds of combining. The metadata reports the model, total token usage, chunk count, call count, and combining rounds.

For text that fits in one call, use AI Basic Chain.

Retrieval-augmented generation

A memory store becomes a knowledge base when you feed it documents instead of conversations. Create a store under Settings, Memory with an embedding connection and model (without one, recall falls back to keyword matching), recency weight 0 so reference material does not fade, and no fact cap.

Ingest splits a document into chunks and stores them. Paragraphs are packed up to the chunk size and longer ones are split at word boundaries. Each chunk starts with some overlap from the one before, so a fact on a boundary stays whole in at least one chunk. Every chunk carries the source name, and ingesting a source again replaces its chunks, so file-watch → file-read → Ingest keeps a store in step with a changing file without duplicates. Ingesting an empty document removes the source. A failed ingest leaves the previous version in place. Keyword search finds new chunks immediately, and similarity search finds them shortly after.

Chunk size and overlap are measured in bytes of text, with defaults of 1200 and 150. Overlap is limited to half the chunk size.

Run a PDF or Word file through the Document parser (folder Parsers) first. It takes binary and emits the extracted text, for pdf, docx, and odt. Left on From file type, it picks the format from the declared metadata (meta.mime, or the extension of the meta.path a file read sets) and refuses bytes with no declared type. It extracts text only, so a scanned PDF fails with a message that it needs OCR.

For example, to give a support agent a procedure document, drop sop.pdf where a Watch Files trigger sees it. Wire file-read (binary) into Document, and Document into Ingest, with the path as the source and a "Support docs" store as the target. Then give the support agent an AI Memory node on that store. Every edit to the file replaces its chunks, and the agent recalls the relevant procedure for each request.

To read the knowledge back:

  • To have an agent answer from it, wire an AI Memory node on the store into the agent's Memory socket. The chunks most relevant to the rendered prompt are added to the system prompt. Turn Save conversations off unless the store should also collect the chats.
  • To use the chunks in a flow, use Recall, which returns them as [{text, score, source, ...}] so a flow can route on them, build its own prompt, or cite source in an answer.

Wiring notes for generated graphs

This section is for writing flow graph JSON directly, for example through MCP.

The agent's model, tools, and memory inputs are port fields, which are permanent value input ports rather than settings. Nothing is typed into them, and they never appear in a node's params list. Supply them by wiring a value edge ("kind": "value") to param:model, param:tools, param:memory, or param:images. The tools and images ports accept several value edges, and the values arrive in edge order. The agent's transcript config field is an ordinary setting (an array of {role, text, ...} entries in the Response output's format) that may also be exposed as an object value input via params. A value edge must come from a node with no message ports, so another agent's Response output cannot be wired in directly. A required port field must be wired before the flow deploys. The memory port is optional and takes at most one ai-memory edge from an AI Memory node, whose config fields are store (a memory store's name or UUID), the session template, window, recall, recall_turns, tools, and save. The guardrail's param:model is a port field that exists only while its model_checks config names a check (jailbreak, nsfw, topic, comma-separated), and is required exactly then. The extractor's and classifier's param:model always exist and are required.

The classifier's category outputs come from its categories config, a comma-separated list of display names. A category's handle is cat: plus its lowercased name, so "categories": "Urgent, Newsletter" yields cat:urgent and cat:newsletter beside the fixed other and error outputs.

A Tool node's out port connects to the agent's param:tools with a value edge. Its call port connects to the branch with an ordinary message edge, and the branch's last node connects back into the tool's return input with another message edge. The graph allows this cycle. An argument declared as {"id": "city"} in the node's tool_args config adds the output port arg:city, which connects to a branch node's param:<field> input with a value edge. Argument ports carry values, never messages.

Editing dashboards and flows with AI

Kuri is the dashboard and flow editor assistant. Both editors show an Ask Kuri button when an enabled, connected AI provider accepts Karakuri tools and you can read connections. Hermes is not offered because it runs its own tools. A model that rejects tools reports that error in the chat. Choose a connection and a model, or type a model ID, then describe the changes. Karakuri saves your choice in your profile and reused in both editors, including after a reload, even when the provider's catalog does not list the model.

The window shows streamed replies and each tool call. Expand a call to see its arguments and result. Reasoning the model disclosed sits in a collapsed Reasoning section above that round's reply. Kuri's replies render Markdown, including lists, emphasis, links, tables, and highlighted code blocks; raw HTML and unsafe links are removed. If rendering fails, the plain reply stays visible with a notice. Your messages and tool arguments and results are shown as plain text. Successful changes refresh the editor behind the window, and you can keep working in the flow or dashboard while chat stays open. Both editors autosave drafts, and opening Kuri on a flow saves pending canvas edits first. Kuri edits the whole selected flow, including local subgraphs. Shared subflows must be opened in their own editor.

Kuri's persona is warm, cheerful, and organized. It sometimes jokes about stubborn bugs or tangled wiring, and it stays calm when something fails. Code, configuration, and error details stay precise. Configured AI nodes keep their own system prompts.

Kuri compacts long conversations as described in Context compaction, using the connection's Context window or the detected one. A Context compacted divider appears in the window, and the next message continues from the summary. Kuri's own instructions and tool definitions take about 18,000 tokens, so on a 32,768-token model there is little room left and compaction runs often.

Kuri acts with your permissions. It can inspect node catalogs, connections, Home Assistant states, controls, and MQTT devices, and it can change only the selected document. On dashboards it can place and configure widgets, edit grid geometry, choose a theme, and add, reorder, rename, or remove sections and pages. Removing a section also removes its widgets; removing a page moves its widgets to every page. On flows it can update metadata, validate graphs, and save the draft.

Allow deployment and execution is off by default. Kuri cannot deploy, enable or disable, test-run, or send dashboard commands until you turn it on. New chat and changing the model turn it off again. It does not grant permissions you lack. Restoring a version is a draft change and does not need it. Test runs perform real actions. Kuri cannot send device commands directly, change sharing, or edit connections.

Changes made in the browser, through MCP, and by Kuri all go to the same draft, and open editors refresh when another client edits, deploys, or restores it. The server refuses a browser save if someone else changed the draft first. Restoring replaces the whole draft with the selected version without publishing it.

On dashboards, render_dashboard returns a screenshot of the draft or deployed view at the requested size. A model that accepts images sees it, and the chat shows it under the tool result. Rendering does not publish the draft. Only the latest screenshot goes to the model on later turns.

Kuri can also make focused graph edits with patch_flow_graph, compare versions, inspect dependencies, validate dashboards, collect render diagnostics, and read agent status. Patches, comparisons, dependency checks, dashboard draft reads, and run and state inspection are limited to the selected document. General lookups, list_flows, get_flow, and find_references can read other documents you have access to. Node tests and flow test runs can still perform real device or host actions.

To diagnose a flow, Kuri can run the draft, inspect that run, list recent runs, and filter run events by node.

Drag the chat title to move the window, or the bottom-right handle to resize it. Focus either handle and use the arrow keys to move or resize; hold Shift for larger steps. Closing and reopening keeps the window's position and size, the scroll position, and expanded tool details until you leave or reload the editor. The window stays inside the browser window. Escape closes chat when focus is inside it and no turn is running. Editor shortcuts keep working when focus is in the editor.

You can type the next message while Kuri works. Sending waits until the current turn finishes or Stop has taken effect; the text you typed stays in the box.

Stop cancels the request. Changes already made stay in the draft, and the editor refreshes even when the stream fails. Close becomes available once the request settles. A turn may run at most 50 model rounds and five minutes. Each model response counts as one round, including lookups and failed tool calls. At the round limit, Kuri keeps the results and conversation so far. Send another message to continue. The conversation lasts only for the current editor tab; leaving the editor, changing models, or choosing New chat clears it. After an interrupted turn, Kuri does not see that turn's partial history, but the chat stays visible. Each turn reads the current draft again.

Review the result, then use Deploy, or ask Kuri to deploy, when it is ready. Deployed flows and dashboards keep their deployed version until then. A dashboard that has never been deployed shows its draft, as usual.

Editor turn traces

To record Kuri's turns for troubleshooting, set mcp.assistant_trace_dir to a local directory and restart the server. It is empty by default, which turns tracing off. Each turn writes one NDJSON file readable only by the server's user, and the server creates a missing directory with the same restriction. A trace holds the prompt and earlier history, the system instructions, tool definitions, the raw provider responses, tool calls and results, round timings, and how the turn ended. It never holds HTTP authorization headers. The trace records raw responses before tool calls run, so you can compare a malformed tool argument with what the provider sent. A request that fails before the provider returns a usable response records only its error.

Trace files contain private conversation and tool data, including returned images and provider reasoning state. Delete them yourself when done. Each file stops recording at 32 MiB with a trace.truncated entry, and the turn continues. The chat shows any error creating or writing a trace. Clear the setting when you no longer need traces.

Agent nodes

Agent nodes run with the operating-system permissions of the agent process. The server namespaces each type as agent.<agent id>.<type>. An operator can remove a type from an agent with its disable setting, and the agent then never advertises that type to the server.

Installing an agent

Downloading the agent

Download the agent from GitHub releases, using the same release as your server. Each release has one agent archive per platform, named karakuri-agent-<version>.<os>-<arch>:

Host Archive
Linux linux-amd64, linux-arm64, or linux-armv7 (32-bit ARM, such as older Raspberry Pi systems)
macOS darwin-arm64 (Apple silicon) or darwin-amd64 (Intel)
Windows windows-amd64 or windows-arm64, as a .zip
FreeBSD freebsd-amd64 or freebsd-arm64

Every archive except Windows is a .tar.gz. It holds the karakuri-agent binary and nothing else to install.

Installing for your user

Install the agent as the user it should act as, into your own binary directory, and run its service as that user. This is the recommended install: the agent can reach your desktop session, and it can update itself, which needs the service's account to own the binary.

On Linux and FreeBSD, unpack the archive into ~/.local/bin, which most distributions put on the PATH once it exists:

mkdir -p ~/.local/bin
tar xzf karakuri-agent-<version>.linux-amd64.tar.gz
install karakuri-agent-<version>.linux-amd64/karakuri-agent ~/.local/bin/

If karakuri-agent is not found afterwards, add ~/.local/bin to the PATH in your shell profile and open a new terminal. On macOS use the same directory and add it to the PATH in ~/.zprofile. macOS builds are not signed, so a binary unpacked from a browser download will not start until you clear its quarantine flag:

xattr -dr com.apple.quarantine karakuri-agent-<version>.darwin-arm64

On Windows, extract the .zip into %LOCALAPPDATA%\Programs\karakuri-agent and run karakuri-agent.exe from there, or add that folder to your user PATH.

Then mint a join token in Settings > Agents and run the command it shows, as yourself, without sudo. It enrolls the agent and registers a service for your account in one step:

karakuri-agent enroll --server karakuri.example:9443 --token <join token> --service

The service is a systemd --user unit on Linux, a launchd LaunchAgent on macOS, and a scheduled task that starts at logon on Windows. On Linux a user service stops when you log out, so run sudo loginctl enable-linger <user> once if the agent should keep running while nobody is logged in.

Without --service, run karakuri-agent run to try the agent in the foreground, and karakuri-agent service install and karakuri-agent service start to register it later. The service command also takes stop, restart, status, and uninstall. --scope=user and --scope=system override which service manager it uses.

To run the agent in Docker instead, see Running in a container.

Installing as root

Install as root only for a headless host, or when the agent must reach things your user account cannot. A root agent runs every command and script as root. Its desktop and GUI nodes still act in whichever user is signed in at the desktop, through a helper it starts as that user, so anyone who can build flows with the agent controls that person's desktop as well as the machine. On Windows the equivalent is a system service, whose desktop nodes act as the console user.

Put the binary in /usr/local/bin, and enroll and install the service with sudo too, so the identity and the service both belong to root:

sudo install karakuri-agent-<version>.linux-amd64/karakuri-agent /usr/local/bin/
sudo karakuri-agent enroll --server karakuri.example:9443 --token <join token> --service

The service is a system unit or launchd daemon. Manage it with sudo, as in sudo karakuri-agent service restart. On Windows, run the enroll command from an administrator prompt to get a system service.

Updating

An agent running as a service checks GitHub releases once a day and installs a newer one on its own: it downloads its archive, checks it against the release's checksums, makes sure the new binary runs, swaps it in, and restarts through its service manager. If the new version fails to stay up through three starts, the previous binary is put back. The account the service runs as must be able to write the binary, so a user install updates itself, a root install updates as root, and an agent installed by root but run as a user logs that it cannot update. Turn it off with auto_update: false in agent.yaml.

karakuri-agent update checks and installs now, then asks you to restart the service, and karakuri-agent update --check only reports whether a newer release exists. An agent in a container never updates itself; pull a newer image instead.

Who can use an agent

The user who minted the enrollment token owns the agent. Other users do not see it, and its nodes are missing from their palette, until the owner shares it from Share on its card. A use share lets someone run the agent's nodes in their flows; edit also lets them rename, describe, enable, and disable it; admin also lets them share, revoke, and delete it. Holders of api:agents:manage reach every agent. A flow deployed by someone who later loses access to the agent stops running its nodes. Enrollment tokens are listed only to whoever minted them.

Agent settings

The agent reads agent.yaml from the etc/ directory beside its binary, then ~/.config/karakuri/, then /etc/karakuri/. Keys are the agent's flags with dashes written as underscores, and a flag on the command line overrides the file.

Key Default Description
dir follows the config file Directory holding the agent's key, certificate, and identity.
server unset Server to dial, host:port. Required to enroll; overrides the enrolled address when running.
timeout 60 Default time limit for one node execution (seconds).
max_output 262144 Cap on one file, clipboard, or log-line read (bytes).
disable unset Node types this agent must not offer, as a list. A name that matches no node type stops the agent.
log_level info debug, info, warn, or error.
log_format json json, or console for human-readable output.
auto_update true Install newer releases automatically when running as a service.
update_prerelease false Also update to releases marked as pre-releases.
server: karakuri.example:9443
disable:
  - power
  - clipboard-write

The identity lives with the configuration file that names it: /etc/karakuri/agent.yaml keeps it in /var/lib/karakuri/agent, an etc/agent.yaml beside the binary keeps it in var/agent there, and a file anywhere else keeps it in an agent directory beside the file. With no configuration file it goes in ~/.config/karakuri/agent. A service records the directory and server address when it is installed.

The agent has no sandbox. Its nodes can read and change whatever the account it runs as can, so pick that account deliberately. To confine an agent to /srv, run it as a user who can only write there. To give two people on one machine their own nodes, run one agent as each of them.

Enrollment and renewal

Enrollment refuses a directory that contains agent.json. A directory without that file can hold files from a failed attempt, and retrying generates and overwrites the local key. The server uses up the join token as soon as it accepts it, so a failed or interrupted enrollment can need a new token even though the host has no complete identity.

The agent checks for renewal at startup and every six hours. A failed check retries at the next interval, so an unreachable server or a failed disk write can still let a certificate expire. Renewal keeps the private key, and a failed renewal leaves the previous certificate working. The agent uses the new certificate on its next connection. The server closes a live session when its certificate expires, and the agent reconnects with the renewed one.

When the server rotates its agent CA, an agent picks up a certificate from the new root on its next renewal check, and a later check repairs a failed one. A host that has not connected with a certificate from the new root before the old root's last 30 days must re-enroll.

Settings > Agents shows when the agent CA and its successor expire, and whether a rollover is in progress. Rotate CA starts a rollover early. Press it if the CA key may have been exposed. Connected agents move to the new CA as they renew.

A backup carries the agent CA and the server's identity, and a restore keeps them. Enrolled agents reconnect to the restored server without enrolling again, on the same machine or a new one. A new machine must answer at the address the agents enrolled against.

Running in a container

The grmrgecko/karakuri-agent image runs an agent in a container, on amd64 or arm64. Mint a join token in Settings > Agents, then start it with the server's agent address and the token:

docker run -d --name karakuri-agent \
  -e KARAKURI_SERVER=karakuri.example:9443 \
  -e KARAKURI_JOIN_TOKEN=<join token> \
  -v karakuri-agent:/var/lib/karakuri \
  grmrgecko/karakuri-agent

The first start enrolls and stores the identity on the volume. Later starts, including a new container on the same volume, reconnect as the same agent and ignore the token. Without the volume, a recreated container has no identity and needs a new token. KARAKURI_AGENT_NAME sets the agent's name, which is the container's hostname otherwise.

The agent's nodes act on the container, not on the machine running it. Commands and scripts run as the container's karakuri account and see its filesystem, processes, and network, plus whatever you mount or publish into it. Desktop and GUI nodes have no screen or session to reach, and fail with that error when a flow runs them. To keep them out of the palette, mount an agent.yaml over /etc/karakuri/agent.yaml that lists them under disable, keeping the image's dir: /var/lib/karakuri/agent line. For tools the image lacks, build your own on top of it:

FROM grmrgecko/karakuri-agent
USER root
RUN apt-get update && apt-get install -y --no-install-recommends curl jq && rm -rf /var/lib/apt/lists/*
USER karakuri

Execution and files

Script receives the message as JSON on stdin and in the PAYLOAD, TOPIC, META, VARS, and INPUT environment variables. A variable longer than 32,000 bytes is left unset and written to a file in the script's temporary directory instead, with PAYLOAD_FILE, META_FILE, and so on holding the path. Linux refuses to start a program when one environment string passes 128 KiB, and Windows caps a variable at 32,767 characters, so a large payload would otherwise stop the script from starting.

Script picks its interpreter from the first line's shebang. A full path (#!/usr/bin/env python3, #!C:\Python311\python.exe) runs that program, and a bare name (#!python3, #!node, #!powershell) is found on the PATH of the account the agent runs as, trying each PATHEXT extension on Windows. If the agent cannot find an interpreter, add it to that account's PATH or name it by full path. PowerShell and cmd get the arguments and file extension they need (-File with a .ps1 file, /c with a .bat file) whether the shebang names them bare, with .exe, by full path, or in another letter case, as in #!C:\Windows\System32\cmd.exe.

Run Command passes each argument to the program as written after {{ }} rendering, including leading and trailing whitespace, so a lone space is a valid argument. Open Application passes its arguments the same way, and Command and Script pass each environment value the same way.

Command and Script never retry automatically, because repeating a program can repeat its side effects. By default they return stdout and stderr, up to 32 MiB each. Each stream can instead use file mode with its output path, or discard mode. A file-only stream writes straight to the file without the return limit, and a discarded stream writes nothing. In return mode, stdout_path and stderr_path also mirror the streams to files on the agent host, and the 32 MiB return limit still applies. The agent buffers returned output on disk while the process runs, so a large stream does not have to fit in memory.

Canceling either node terminates its process tree. termination_grace (Termination grace) defaults to 0s, which forces termination immediately. Set a duration such as 500ms or 5s, up to 1m, to allow cleanup on Unix. The process and its descendants receive SIGTERM, and anything still running when the grace expires receives SIGKILL. Cleanup still reaches descendants when the parent exits first, including with file-only and discarded output, and descendants that started their own session with setsid. It does not reach a process that was already orphaned to init before cancellation. Exited descendants that nobody has reaped can use up the full grace period. Normal completion does not wait for grace.

Cancellation and timeout stay failures even if the process exits zero, or with an accepted code, during cleanup. An invalid grace fails before launch and before any output file changes. Windows has no general cooperative shutdown signal for service agents, so a positive grace fails before launch there. Use 0s on Windows. There, cancellation terminates every descendant, including ones whose parent already exited. If cleanup fails on any platform, the node's error says so and warns that descendants may still be running. Processes left behind by a command that completes normally keep running on every platform. A leftover process that keeps a mirrored stream or standard input open holds the node for up to five seconds after a zero exit, and the node then succeeds with the output written by then.

Accepted exit codes are a nonempty JSON integer list, [0] by default. An explicit list overrides Run Command's Ignore the exit code setting. Launch failures, cancellation, and timeouts still fail. The property result destination stores decoded stdout at a path under payload or meta, such as meta.command_result, and keeps the rest of the input. Existing parent values on that path must be objects. File-only or discarded stdout leaves the payload alone and skips decoding. Metadata keeps the exit code, returned stderr, and configured paths.

The 32 MiB limit applies only to returned streams. The on-disk buffer and file mirrors have no size limit, so watch disk space on the agent host. Every node execution has an overall deadline: its own timeout, or the default its timeout field declares when the configuration omits one, or the agent's default of 60 seconds, plus ten seconds for cleanup. Command and Script add their termination grace, and Service Control adds its confirmation timeout. When a run is canceled, the node stops waiting immediately while process cleanup continues for its grace. The agent abandons a node stuck in an operating-system call it cannot interrupt at the deadline instead of stopping it. Triggers run for the life of their subscription and have no execution deadline.

Write File in replace mode, and Copy or Move with overwrite enabled, write a complete staging file next to the target and then swap it into place. If the swap fails, the agent restores the previous target, and a failed restore reports both errors. A crash or power loss mid-replacement can still leave the target in an intermediate state. Append and delete act on the file directly. Write File also has a create-only mode, which fails if anything already exists at the path and never overwrites. Create-only needs a filesystem with hard links and fails on any other.

Copy and Move compare source and destination with symlinked directories resolved, so they refuse a path that reaches the source through a link just as they refuse the source itself. Copy refuses FIFOs, sockets, and device files, which have no content to read to an end.

Write File refuses to replace a directory, so a file name that renders empty cannot replace its parent directory and delete what was in it. It also refuses to replace a FIFO, socket, or device file, because the replacement would turn it into a regular file. Append mode writes into one. Delete mode removes files and links only and refuses any directory, empty or not. In replace mode Write File follows a symlinked path, replacing the file the link names and keeping the link. A link whose target is missing is replaced by the file. The agent removes staging and backup files even when a copied directory is read-only.

List Files and a recursive Watch Files descend into a directory named through a symlink and report paths under the name the node was given. They do not follow symlinks inside the tree, including one a watched tree gains after the watch starts.

Replacement keeps existing permissions by default. Disabling preserve_permissions sets mode 0644, as for a new file. On Unix a preserving replacement also keeps the file's owner and group. Only a root agent can keep another account's ownership. Any other agent keeps the group when it belongs to that group, and otherwise the replacement is owned by the agent. Copy and Move give each copied file its source's permission bits regardless of the agent's umask, and the copy belongs to the agent's account.

expected_sha256 requires an existing regular file with the given 64-digit digest. The agent checks before staging and again just before the swap, and rejects symlinks. This catches stale content but is not an atomic compare-and-swap. Another process that changes the file after the final check can still race the replacement.

Read File, Command, Script, and HTTP request return an empty array when text read as lines has no lines, as the server's Read File does.

File Details reports existence, type, size, modification time, mode, and permissions. SHA-256 is optional because calculating it reads the whole file.

Triggers

Tail Log follows truncation and rename-based rotation. It saves a checkpoint on the server with the file's identity, path, last complete-line position, and last activity, so it resumes where it left off after an agent or server restart. It saves every 15 seconds by default, and inactive records expire after 14 days. A crash can therefore replay up to one interval, and Tail Log reads an incomplete last line again after a restart. It reads a file from its beginning when the file was replaced while the agent was offline, or did not exist when the trigger was armed. An oversized line emits a prefix capped at the agent's max_output limit and discards the rest through the next newline, even when that line was not complete at the time of clipping.

A file that was truncated or rewritten in place is read again from its beginning, even when it has grown past the old position since the last poll. Tail Log detects this even when the rewrite happened while the agent was stopped. On rotation it keeps reading the old file until nothing is left, reports the old file's unterminated last line, and then reads the replacement. Lines a writer appends to the old file after that are lost, as are old-file lines left unread when the agent restarts during that drain. max_lines_per_poll, 1,000 by default, bounds each poll across both files.

Watch Processes compares process identity on each poll and can emit start and stop events. PID and creation time form the identity, so a reused PID counts as a new process.

Agent Connection is a server-side trigger. It emits authenticated connect and disconnect events with the agent id, name, state, and timestamp, and can filter by exact id or name.

System and network

Network Probe checks a TCP address or HTTP URL from the agent's network view. An unreachable target normally emits reachable: false and healthy: false. HTTP probes support GET and HEAD, headers, expected status codes or inclusive ranges such as 200-299,304, and a redirect policy. An optional case-sensitive body_contains requires GET and a complete response within the agent's max_output limit. An unexpected status or body reports reachable: true and healthy: false. With no expected statuses or body_contains set, any response counts as healthy, an HTTP 500 included. Enabling fail_if_unreachable also fails unmet health assertions. Invalid settings, incomplete body reads, and parent cancellation always fail.

HTTP request is an execution node in each agent's System palette. It sends GET, HEAD, OPTIONS, POST, PUT, PATCH, or DELETE from the agent's network. URL and header values accept interpolation. body_property selects message bytes, text, or JSON, and an empty value sends no body. Body format defaults to text for strings and JSON for objects and arrays. Select Binary to decode base64 binary message payloads into request bytes. JSON format also serializes scalar values. For these explicit formats the content type defaults to JSON or octet-stream, and configured headers override it. A configured Host header sets the host the request names, so a URL can address a server by IP and still select one of its virtual hosts. Responses use auto, JSON, text, lines, or binary format, replace the payload, and add status, response headers, and duration_ms to metadata. Empty HEAD, 204, and 205 responses decode as null in auto and JSON modes.

Request statuses default to 200-299. Configure 100-599 to accept every response. Timeout defaults to 30 seconds. max_output, or a smaller max_response_bytes, bounds the response body, and overflow fails instead of truncating. Requests never retry automatically, GET included. Both HTTP nodes validate TLS unless configured not to, follow at most ten redirects by default, and drop configured headers when a redirect changes origin. With redirects disabled, the node returns the redirect response. Requests go straight from the agent host and ignore proxy environment variables. Transport errors and debug metadata omit request URLs and headers, but response headers and bodies still appear in run history.

Service Status and Service Control use systemd on Linux, launchd on macOS, and the Service Control Manager on Windows. Control supports start, stop, restart, enable, and disable, and never retries automatically. Optional confirm polls the observed state after issuing the action once. Start and restart require running, stop requires stopped, and enable and disable require the matching startup configuration. Confirmation defaults to 30 seconds with a 250 ms interval and extends the node's deadline. An unknown or transitional state never counts as success. Metadata contains confirmed: true and the final service_status observation. Confirmation does not prove application health or that restart started a new process. On Windows a service counts as enabled when its startup type is not disabled, including manual start.

On Windows, Service Status reports state and running and has no raw details text. Read those fields to decide what to do.

Host Info includes address summaries and per-interface addresses, CIDRs, scope, MAC address, MTU, link state, and loopback state. It reports the default gateway when the platform exposes one, along with the selected desktop automation backends or their initialization error.

Desktop and GUI

Media Status reads playback state and track details from the desktop's media players on Linux and FreeBSD, the same players playerctl sees, and through Music or Spotify on macOS. On Windows it reports that media status is unavailable, and Media Control uses system media keys there.

Media Control's Set volume applies 50 when the configuration names no volume. An explicit 0 silences the output.

Window List includes geometry when the desktop backend exposes it. Screenshot can capture the active window when geometry is available. Mouse can move before clicking and can interpret coordinates relative to a selected window.

Read Clipboard caps its payload at max_output. Metadata includes the returned size, the original size, and whether the payload was truncated.

Dialogs have no secret-entry mode. Run history stores node output, so returning a password would persist it. Use credentials for secret material.

GUI flow nodes

The GUI palette has these execution nodes. Each accepts an input message and has an error output. Read nodes replace the payload with the current observation. Click Control and Invoke Menu keep the input payload and add result metadata. Mutating operations never retry automatically.

Node Behavior
UI Snapshot Captures the time, window metadata, backend names, and accessible elements.
Click Control Clicks a unique native label or invokes an accessible element ID.
Wait for Window Waits for an unambiguous window to appear, or for all matching windows to disappear.
Wait for UI State Waits for accessible text, role, ID, enabled state, absence, or stable pixels.
Menu List Reads the current native or accessible menu tree, IDs, paths, and reported state.
Invoke Menu Invokes one enabled menu path or command ID.
Display List Reads the current output geometry and modes reported by the backend.
Set Display Mode Requests a temporary primary-output width, height, and color depth.
Dialog List Lists application dialogs and their controls, with per-window inspection failures.
Screenshot Now Captures fresh pixels when the execution message arrives.
Window List Now Reads fresh window metadata when the execution message arrives.
Drag and drop Drags the pointer along a timed path and always releases the button.
Window placement Restores, moves, resizes, or sets bounds, and reports freshly observed geometry.
Image match Matches a same-scale reference and reports an RGB agreement percentage.

Screenshot and Window List are value sources, and a run reads each of them only once. Use the Now variants after an action when later steps need another observation. Screenshot variants support screen, region, active window, and selected window modes. Window capture first asks for the window's own pixels, which can capture a covered window without activating it, and falls back to the visible desktop rectangle, borders and overlapping windows included, when those are unavailable. Wayland always captures the visible rectangle and needs window geometry from the compositor. Region captures can use display-relative coordinates (the default) or desktop coordinates across displays, including negative origins.

Keyboard types its text as written after {{ }} rendering, including leading and trailing whitespace. A line break presses Return and a tab presses Tab wherever they appear. Keyboard can select a window with the same filters as Screenshot. A selected target must have focus before input is sent. Activate Target Window brings it forward and waits up to two seconds for observed focus. Without activation, an unfocused target fails immediately. With no selector, input goes to the current focus. Focus can still change after the check if another application or user acts.

A window ID overrides active-window selection, title and class patterns, and every other filter. Window match mode selects regular expressions (the default, in Go regular expression syntax), literal contains, or exact case-sensitive matching. Additional title and class constraints use the same mode, and PID and executable constrain the process. Executable accepts an exact path or filename when the provider reports it. Actions reject multiple matches, so narrow the pattern or select an ID when more than one window matches. Window List still returns every match. Window payloads include the executable image, a nullable enabled state, and geometry_known alongside optional geometry. Window and Mouse selectors, snapshot selectors, labels, menu targets, and evidence directories accept message interpolation with {{ }}.

UI Snapshot includes visible elements by default. Include Hidden Elements adds hidden ones, and Only Enabled Elements drops disabled ones. Source selects accessibility (the default), native controls, or both. Windows native controls carry HWND IDs, immediate parent HWND IDs, and native class names. Unix and macOS map their accessible controls. Role and Text Contains filter each source. Maximum Results limits each filtered source, zero returns every provider result, and truncated_sources reports which output was capped. The limit bounds returned output, not how long the provider takes to enumerate. IDs and roles keep the provider's spelling. Snapshots omit protected values, but screenshots can still show sensitive text.

Click Control prefers an exact label over a unique substring. Element ID overrides the label, and the node looks it up again just before the click. Role and Immediate Parent ID constrain the target before acting. Label Match selects exact-first (the default), exact, or contains matching, and keeps case sensitivity. Native Windows role constraints use class names, and clicks accept native control IDs from snapshots. Native Windows labels omit accelerator ampersands and shortcut suffixes.

Wait nodes default to 30 seconds and accept a positive timeout up to one day, including fractional seconds. Check Once returns matched: false for an unmet condition without polling. On Timeout can fail (the default) or return matched: false. Ambiguity, provider errors, and parent cancellation stay errors. Check Once cannot establish pixel stability. Enabled State selects either, enabled, or disabled. Without enabled_state, the node honors an enabled setting.

Wait for UI State selects an existing window and keeps waiting on that window. Text is a case-insensitive substring, and role is an exact case-insensitive provider role. Conditions apply to one visible element, and a positive match must be unique. Failed inspection never satisfies an absence condition. Pixel stability is a separate mode and cannot be mixed with element conditions. Region coordinates are relative to the selected window. Stable pixels do not prove that an application has finished its work.

By default, a failed state wait tries to capture evidence once a window has been selected. It saves snapshot.json and screenshot.png under the agent account's configuration directory at karakuri-agent/captures, or under the configured evidence parent. The error names that directory and any capture failure. Capture has an eight-second limit within the node's cleanup allowance. Run cancellation skips evidence. Captures stay until you remove them.

Dialog List recognizes Win32 #32770 dialogs, macOS accessibility dialogs and sheets, and Unix accessibility dialog and alert roles. Entries in its inspection_errors map are windows it could not inspect, so an empty dialogs list alone does not prove no dialog exists. Filter Windows applies the shared selector before inspection and allows multiple matching windows for discovery. Disable Include Controls to omit control details. Custom providers can omit menu paths, controls, or geometry.

Display mode changes affect the primary output only. On Unix, use the reported color depth. An unsupported mode fails without claiming a change.

Drag, placement, and image matching

Drag and drop holds the left, middle, or right button along a timed path. Duration runs from zero through thirty seconds and defaults to 0.5. Coordinates are absolute desktop coordinates. Coordinates are inside a window makes them relative to a uniquely matched window's reported origin. Other input actions from the same agent wait until the drag finishes, and the agent always tries to release the button, with two seconds allowed for the release. A canceled drag can still complete its path after the node reports cancellation. Separate agent processes on one host do not coordinate their input.

Window placement selects one window and by default restores it before setting position and size. Move, Resize, and Restore are also available. The output contains requested, freshly observed window geometry, and, for geometry requests, bounds_matched. Application minimum sizes and window-manager constraints can produce bounds_matched: false. Geometry follows the selected backend's window bounds. X11 reports client bounds, and Windows and macOS report native window bounds. macOS restores minimization and clears fullscreen and zoom state when the application exposes those attributes as writable. It cannot infer zoom state the application omits. Hyprland and Sway require the window to be floating already. Other Wayland compositors can restore a window but cannot move or resize it. A window known only through accessibility cannot be placed. Actions reject ambiguous targets.

Image match searches a fresh capture of the screen, a region, or the selected or active window, or a Binary image input value socket. Reference image selects a PNG or JPEG file on the agent host or a Binary reference input socket. A selected Binary socket needs a value edge. Reference paths accept {{ }} expressions. Matching needs no OCR, model, or extra software, and never clicks a result automatically.

Minimum match defaults to 98 percent and accepts values greater than zero through 100, fractions included. The score is 100 * (1 - mean absolute RGB difference / 255). It measures pixel agreement, not recognition probability, and 100 requires identical RGB pixels. Reference images must be opaque and at the same scale. Source alpha is ignored. Theme, display scale, and rendering changes affect the score.

Results report coordinate_space: "image_pixels", source dimensions, match bounds, match_percent, and truncated. Coordinates start at the captured image's top left. capture.mapping_known says whether the backend supplied a reliable mapping to desktop coordinates. When it did, capture.desktop_mapping gives the origin and desktop units per pixel for X and Y separately, capture.desktop_bounds gives the captured rectangle, and each match adds desktop_bounds and desktop_center. Windows and X11 screen and region captures use physical desktop pixels, and macOS maps image pixels to desktop points. Clipped regions report their actual origin. Binary inputs, portal captures, and window captures without reliable geometry report an unknown mapping and omit desktop coordinates.

An empty match list from a completed search is a success. Overlapping candidates merge at an intersection-over-union above 0.3. Maximum results defaults to ten and accepts one through 100. The scan runs top to bottom, left to right, and stops at the next distinct match past that limit. Returned candidates sort by score. A truncated search does not claim to have found the best matches across the whole image.

Encoded files and inputs are limited to 32 MiB, source images to 16 Mi pixels, references to one Mi pixels, and searches to 100 million pixel comparisons. Running out of that comparison budget is an error, never an empty no-match result. Shrink the capture region or the reference when that happens. Canceling the run stops a search in progress.

Automation command files in flows

Automation Script, in the Exec palette, runs an existing command file or inline commands through a configured karakuri-auto executable on the agent host. The executable field defaults to karakuri-auto in PATH. Command File and the optional Command Log take host-local paths and accept message interpolation. Working directory, environment, output mirrors, timeout, and process-tree cancellation work as in Run Command. Output is text, with the same 32 MiB cap per returned stream. A nonzero exit fails the node, and the node never retries automatically. Inline commands are literal text with no message interpolation. The agent writes them to a private temporary command file and removes it after success, failure, or cancellation.

Install the executable separately and configure its desktop access. The karakuri-auto README in its release archive covers its commands, command-file syntax, and desktop setup, and karakuri-auto help lists them on the host. Command files run their commands in sequence and stop at the first failure. A detached application launched by run can outlive the script. Use individual GUI nodes when steps need separate error branches or their own run-history observations.

Desktop session access

An agent running as a user attaches to that user's own graphical session, and an agent running as root acts in the logged-in user's session. An unprivileged agent can use only its own graphical session. The agent looks the session up again whenever it needs it, so an agent that started at boot before anyone logged in works once someone does, and it follows a logout and a new login. Until a user is at a desktop, desktop nodes fail with a message saying so, and session nodes keep working. On macOS, grant the agent Accessibility and Screen Recording under System Settings > Privacy & Security. Reaching the session does not bypass those grants.

When the agent acts in another user's session and loses contact with it mid-call, it retries the call once, so an action that completed before contact was lost can run twice. Canceling the node stops waiting, but an action already started in the session can still finish.

On Linux and FreeBSD an agent finds the session without any helper installed, and it ignores a stale or forwarded DISPLAY. On macOS it reaches the window server through a short-lived launchd job running the same executable.

On Windows only a process inside the interactive user's session, or one running as LocalSystem, can reach that session's desktop. An agent installed as a user-scope logon task already runs in the session. An agent installed as a system service reaches it too: the first time a flow uses a desktop node, it starts a helper as the console user, on that user's visible desktop, and stops the helper when it is no longer needed. Nothing beyond the service needs installing. Desktop actions run as the console user, not as SYSTEM. Session nodes, which list sessions, lock, switch, and unlock with credentials, run as SYSTEM. A signed-out console has no user to run the helper as, so a desktop node reports that until someone signs in.

Browser questions

The server's Browser prompt node uses an agent's Open URL capability to show Markdown instructions, attachments, and author-defined response buttons. The wait for a person's answer happens on the server and does not count against the agent's execution deadline. Configure a server URL the agent's browser can reach, and keep the agent in an interactive desktop session. No agent update is needed. See Browser prompts for authoring, buttons, timeouts, and access.

Browser prompts

Browser prompt is a server node under Utility. It opens a question in the selected agent user's default browser and holds the incoming message until someone presses a button. Parallel branches keep running. The held message leaves only through the pressed button's output, and an unwired output ends the branch.

Configure a question

Choose an agent that advertises Open URL. The agent needs an interactive desktop session. Set Browser base URL if server.base_url is not reachable from that machine. Use an http or https server origin without a path. For a remote host, use the server's LAN address or DNS name, not localhost. The node needs no agent update and no Karakuri browser login.

Title and Instructions accept {{ }} expressions against the incoming message:

# Pump needs attention

The action failed: {{meta.error}}

1. Check the cable shown below.
2. Reconnect it and choose Retry, or choose Bypass to continue without this step.

![Cable location](attachment:cable.jpg)

[Service instructions](attachment:service-guide.pdf)

Instructions opens the script editor with Markdown highlighting, line numbers, undo and redo, Find & replace, and Ctrl/Cmd+Enter to save. It highlights headings, emphasis, links, and code, and fenced JavaScript, JSON, Python, shell, and YAML blocks get their language's highlighting. Write and Preview share one document and keep the cursor and editing history.

Attach image or file inserts a reference at the cursor. Pasting or dropping a file also attaches it. Embed inserts an image, Link inserts a download, and Remove deletes the attachment and its references. PNG, JPEG, GIF, and WebP embed. Every other format, including SVG and HTML, downloads. An uploaded image's content must match its declared format.

Attachments live in the node config, so drafts, frozen deployments, and exported flows carry the same files. A node holds at most 20 files, each up to 8 MiB, with 32 MiB of decoded data in total. Rendered instructions are limited to 64 KiB and the title to 1024 UTF-8 bytes. Each saved version stores its own copy of these bytes.

Buttons and feedback

A new node has Retry, Bypass, and Stop buttons. Add your own or change the labels. Each button's Output ID is its stable graph handle, so changing a label or reordering buttons keeps the wiring. Changing an ID means rewiring it, and removing a wired button invalidates its edge. A node has 1 to 12 buttons. Error is reserved for failures.

A button's name does not decide what happens next. A Retry branch must lead to a new downstream action or an intentional new run. A back-edge to a node that already ran cannot retry it, because each node runs at most once per run. Bypass can lead to the next step, and an unwired Stop output ends that branch. To suppress later prompts, wire Stop to a flow or global variable setter and check that value before the next request.

Written feedback adds a text field, and Require feedback rejects a blank response. Feedback is limited to 4096 UTF-8 bytes. Outputs keep the payload, topic, metadata, message identity, and group, and add this record:

{"browser_prompt":{"id":"retry","label":"Retry","text":"Cable reconnected",
 "request_id":"...","answered_at":"2026-10-06T20:00:00Z"}}

The record is meta.browser_prompt. The original action's failure details stay in the message on every button output.

Timeouts and cancellation

Answer timeout defaults to 15m and accepts 1s through 24h. A timeout, invalid config, disconnected agent, or failed browser launch goes to Error. A browser process that starts has not necessarily loaded the page, and a page that cannot reach the server eventually times out. Closing the tab also leaves the question unanswered. A timeout never selects a default button.

A waiting question does not hold up other runs of the flow. Canceling the run, disabling or redeploying the flow, or restarting the server invalidates unanswered links, and requests do not resume after a restart. The wait happens on the server, so once the browser has opened, an agent disconnect alone does not cancel the request. A standalone node test still stops after at most two minutes, whatever Answer timeout says.

Request access

The browser URL holds a random single-use token. It grants access to that pending question, its attachments, and one response, and nothing else. It cannot sign in or call other APIs. Treat the link like a password while the question is open. The prompt page has no app navigation and no account session. Invalid, answered, expired, and canceled links return unavailable. Only that link serves the attachments, and an answer cannot submit a button ID the node does not declare. At most 128 questions can be pending at once, and requests past that fail through Error.

Network socket nodes

Add TCP, UDP, or WebSocket connections in Settings, Connections, then select one in a Network node. Several flows can share a connection. Disabling a flow removes its subscription. Disabling or editing the connection closes its sockets, and input triggers subscribe again when the replacement starts.

Node Behavior
TCP In Starts a run for each configured stream frame.
TCP Out Writes to a client peer, one incoming session, or all listener sessions.
TCP Request Opens a private socket, sends once, and reads one bounded response.
UDP In Starts a run for each datagram, including empty datagrams.
UDP Out Sends one datagram from the connection's bound socket.
WebSocket In Starts a run for each native text or binary message.
WebSocket Out Writes one native message to a client peer, an incoming session, or all listener sessions.

These nodes run on the server and can reach LAN endpoints. A successful write means the transport accepted the bytes, not that a device acted on them. Actions have out and error branches and never retry automatically, even with an authored retry policy. A write or broadcast that fails may already have reached some peers.

TCP settings and framing

Client mode connects to a remote host:port and reconnects after a disconnect. Listener mode binds the configured address. Request only mode stores the endpoint without opening an idle connection, for use with TCP Request. TCP In cannot use a request-only connection, and TCP Request cannot use a listener.

The connection sets the framing for its shared input stream:

  • chunks: each transport read is a message. Chunk boundaries are arbitrary.
  • delimiter: escaped bytes such as \n, \r\n, or \x00 end a frame. Include delimiter keeps those bytes in the payload. The byte limit counts the delimiter even when the payload omits it.
  • fixed: frame length counts bytes, not characters.
  • close: the peer's orderly end of stream ends one message.

Delimiter and fixed framing reject a partial frame at EOF. A frame over the byte limit closes the peer. TCP Out can append escaped delimiter bytes and close the session after sending. It does not queue sends while offline or replay them after a reconnect.

TCP Request opens a fresh socket for every execution, so concurrent requests cannot receive each other's responses. The response ends at a delimiter, a fixed length, peer close, or an idle gap after the first response bytes. One overall timeout covers connect, TLS handshake, send, and read, and an idle gap does not extend it. Close write side tells the peer the request is complete while the response side stays open. On success the node replaces the payload and socket metadata and keeps the input topic, other metadata, and group stack.

UDP settings

Select udp4 or udp6 and a bind address. The default is a loopback address with an assigned port. Input and output share that socket. Set a default destination on the connection or a host:port destination on UDP Out, where {{ }} expressions can pick a peer from the message.

Reply sends to the incoming remote address, after checking that the message's connection ID matches the selected connection, and keeps the bound source port. UDP has no session identity or delivery acknowledgement. Every payload is one datagram. An oversized datagram is dropped, never split, and adjacent datagrams are never joined.

For multicast, set a group IP, an optional interface name, TTL / hop limit, and loopback. The group must match the chosen address family. IPv4 broadcast requires Allow IPv4 broadcast. IPv6 has multicast and no broadcast. To receive multicast on an interface other than loopback, bind a wildcard address such as 0.0.0.0:9000.

WebSocket settings

Client mode uses a ws:// or wss:// URL, optional encrypted headers JSON, and subprotocols. The client refuses redirects. Put credentials in the headers JSON, not in the URL's user information. Listener mode binds a dedicated HTTP(S) port and an exact path, /ws by default. It does not use Karakuri's application event socket.

An optional listener bearer token requires Authorization: Bearer <token>. An empty origin list applies same-origin checks. Add permitted browser origin host patterns when another site needs access. Origin checks do not stop a client that sends no Origin header, so set a bearer token when the listener needs authentication. The listener negotiates subprotocols from the configured list. Its session limit counts clients still in the HTTP or TLS handshake along with connected sockets.

TLS takes inline PEM CA, certificate, and private key fields. Listener TLS needs both a certificate and a key. Client TLS verifies the server against system roots or the configured CA, and server name can override the name checked on the certificate. The minimum is TLS 1.2. Karakuri stores private keys, client headers, and listener tokens encrypted and shows them masked. Saving a masked value keeps the stored secret.

Payloads and replies

Input formats are Text, Binary, Base64, and JSON. Text returns a string, Binary returns bytes, Base64 returns a string, and JSON can return an object, array, or scalar. Invalid JSON logs an error and drops the frame. Remote JSON only becomes the payload. It cannot set the message's ID, its split and join grouping, or where the run continues.

Output formats use the same choices. Text requires a string, Binary requires bytes, Base64 decodes a string, and JSON serializes the payload. On WebSocket, Binary and Base64 send binary frames and Text and JSON send text frames. An input node's Test payload seeds a test run without network traffic. Binary test payloads are base64 strings.

Incoming messages carry these metadata keys:

Key Value
socket_connection_id Settings connection UUID.
socket_session_id Transient TCP or WebSocket session UUID. Empty for UDP and private requests.
socket_protocol tcp, udp, or websocket.
remote_address Peer address, including port.
local_address Bound address, including port.
socket_frame_type text or binary. TCP and UDP deliver bytes.

Keep these keys on the message to reply to the incoming session. Configured peer sends to a client connection's peer. Incoming peer / session checks this connection and the exact live session. All listener sessions broadcasts, and only when selected. A stale or foreign session fails. It never selects another peer or falls back to a broadcast.

Bounds and lifecycle

Frames and responses default to 64 KiB, with a 1 MiB ceiling. A TCP Request response limit above its connection's limit uses the connection's limit. The UDP ceiling is 65507 bytes. Connections default to 16 sessions and allow up to 64. Connect, write, and reconnect durations are positive and at most 120 seconds. TCP Request defaults to a 30-second overall timeout and a 200 ms idle gap.

Each connection admits at most 64 subscriptions. Each subscription queues at most 32 frames and 4 MiB. A full queue drops incoming frames and logs an error, so a slow flow never stops the connection from reading. The usual limits on concurrent runs still apply. Replacing a connection discards its pending frames and retires every session ID. Canceling a run interrupts its writes and closes its TCP Request socket. Sockets, subscriptions, and queues do not survive a server restart.

Authoring dashboards

Read get_dashboard with view: "draft" before editing. Widget placements and sections have their own UUIDs; a widget package name identifies its type, not a placement. Use list_widget_types for the installed packages. A node type is a flow component, so get_node_type does not describe dashboard widgets.

Addresses

A dashboard's ID is its address, and the app links by ID. Slugs are readable aliases and need not be unique. /dashboard/kitchen opens the one dashboard with that slug the viewer can see, counting public ones for anonymous viewers, and shows a choice when several match. Over the API, a slug that several visible dashboards share answers AMBIGUOUS with the matches by ID, and GET /api/dashboards/by_slug/{slug} lists them. A Dashboard Command node or notification naming a dashboard by slug resolves it only when exactly one dashboard uses that slug, so name dashboards by ID there.

Layout and themes

update_dashboard patches the name, description, grid, spacing, or theme. Choose a numeric theme_id from list_themes; zero clears it. Themes apply to the dashboard, not through a widget's config. Leave sharing settings as they are.

layout_mode: "fit" scales grid_cols and grid_rows to the viewport. layout_mode: "scroll" uses row_height in pixels and supports sections. layout_mode: "regions" anchors placements to named screen regions; see Region layout. Use add_dashboard_section to append a section, update_dashboard_section to change its title, collapsed default, or sort_order, and remove_dashboard_section to delete it and its widgets. Move widgets out first if they should survive. Switching from scroll to fit flattens the sections.

add_dashboard_widget takes a package name, dashboard ID, optional section ID, x, y, width, height, and a config object. Positions and sizes are grid units. Positions start at zero; sizes must be positive. Y is relative to the section, and an omitted section ID means the sectionless region. Keep widgets inside the grid and avoid overlaps. On a 12-column grid, a clock at x=0, y=0, width=4, height=2 is a good first size.

update_dashboard_widget patches placement fields. An empty section_id moves the placement to the sectionless region. Its config replaces the entire configuration, so merge changes into the current object before calling it, and pass the placement's config_revision as expected_config_revision. If someone replaced the config since you read it, the write fails with a conflict; read it again and reapply your change. update_dashboard takes expected_display_revision the same way for its display object, which holds the variables and screen settings. get_dashboard returns stored configs as JSON strings; parse them before editing and pass an object back. Do not save the dashboardId or dashboardWidgetId fields the browser injects.

Region layout

The region layout anchors placements to parts of the screen. A placement names a region instead of a grid cell, and each region stacks its placements by y, then x. A placement is height rows of row_height pixels tall and width of grid_cols of its region wide. Left regions align narrower placements to the start, right regions to the end, and the rest center them.

Region Where it draws
top_bar, bottom_bar Full width at the top and bottom
top_left, top_center, top_right Three columns under the top bar
upper_third, middle_center, lower_third The space between, split three ways; they align to its top, middle, and bottom
bottom_left, bottom_center, bottom_right Three columns over the bottom bar
fullscreen_below, fullscreen_above The whole viewport, behind or in front of every other region

A placement with no region draws in middle_center. The region layout ignores x positions and sections but keeps them, so switching back to fit or scroll restores the grid. In the editor, click a region's outline to choose where new widgets land, and use the Display panel to move a widget between regions or up and down in one. For a mirror, the mirror theme draws black, borderless tiles.

Pages

Pages divide a dashboard into views that take turns. add_dashboard_page, update_dashboard_page, and remove_dashboard_page manage them. A placement's page_id puts it on one page, and an empty page_id shows it on every page, like a clock that stays put. Removing a page moves its placements to every page rather than deleting them. Pages are part of the draft and deploy with the layout.

display.page_interval rotates pages every 5 to 3600 seconds; 0 leaves the page until a viewer or a command changes it. Each viewer runs its own timer, so two panels on one dashboard need not flip together. A page command restarts it.

Display settings

update_dashboard takes a display object, which replaces the stored one; an empty object clears it. It deploys with the layout.

Field Meaning
page_interval Seconds between automatic page changes, 0 or 5 to 3600
night_dim {from, to, level}. Dims to level percent between two HH:MM times in the viewer's clock; a window past midnight is allowed
idle_dim {after, level}. Dims to level percent after after seconds without a touch, key, or wheel
pixel_shift Moves the whole surface by up to this many pixels, 0 to 16, every two minutes to spread burn-in
variables Named values placements are templated on; see Variables

The darker of the night and idle levels applies. A dim command replaces both until undim. A touch, key, or wheel lifts dimming on that viewer for the idle timeout, or 30 seconds without one, and the first tap on a dimmed screen only wakes it. Renders ignore dimming, idle, pixel shift, rotation, and reload.

Placement display

A placement's display object holds how the dashboard shows it, separate from the widget's own config. update_dashboard_widget replaces it whole; an empty object clears it.

Field Meaning
name Label shown in pickers, such as the Dashboard Command node's widget list
hidden Start hidden under the lock start; see Commanding a live dashboard
conditions, match Show only while all (default) or any conditions pass
animate_in, animate_out, duration none, fade, slide-up, slide-down, slide-left, slide-right, or zoom, for up to 5000 ms; unset fades for 300 ms
style Tile look overriding the theme; see Tile style
cues Animated borders drawn while their conditions pass; see Status cues

A state condition names a source with the binding fields widgets use and compares one of its values:

{"kind":"state","source":"ha","connectionId":"<uuid>","entityId":"binary_sensor.garage_door",
 "attribute":"","operator":"equals","value":"on"}

source is ha, control, or mqtt (with controlId or deviceId). attribute reads a Home Assistant attribute, a composite control's attribute, or a device state field. Empty compares the state, the single value, or a composite control's primary attribute, such as a location's state or a thermostat's mode. operator is equals, not_equals, contains (all ignoring case), above, or below (numeric). A source that has not answered never matches, so the placement stays hidden while the page loads. Viewers may read a condition's source as they may a display-only row.

A time condition is {"kind":"time","from":"22:00","to":"06:00","days":[5,6]} in the viewer's clock. days are 0 (Sunday) to 6 and name the day the window starts; empty means every day. A window whose start equals its end covers the whole day.

A variable condition is {"kind":"variable","variable":"person","operator":"equals", "value":"sam"} and compares the viewer's current value of that variable with equals, not_equals, or contains. It reads no source and grants nothing.

Hidden placements keep their place in the grid layouts and give it up in the region layout. They stay loaded, so a page flip does not reload them.

Tile style

style changes one placement's tile without a theme. The dashboard applies it to the cell around the widget, so it works for every package:

{"style":{"background":"#1e3a5f","border_color":"#ff8800","border_width":3,
          "radius":0,"text_color":"#ffe08a","accent_color":""}}
Field Meaning
background A CSS color, or transparent to drop the tile's face, border, and shadow, which suits a mirror
border_color, border_width A border of 0 to 16 pixels; a color alone draws 1 pixel
radius Corner radius of 0 to 64 pixels; unset keeps the theme's, 0 is square
text_color, accent_color The colors widgets that follow the theme use for text and accents

Empty fields follow the theme, and an empty style is stored as no style. Colors are CSS color strings of up to 64 bytes. The server refuses a value holding ;, braces, angle brackets, quotes, a backslash, or url(.

Status cues

cues draw an animated border around the tile while something needs attention. Each cue has conditions and match in the same forms as visibility conditions, a color, and an animation, which is static (default), pulse, blink, breathe, comet, or ants. The first cue whose conditions pass draws, so order them from most to least urgent. A cue with no conditions always draws.

{"cues":[
  {"color":"#f38ba8","animation":"blink","conditions":[
     {"kind":"state","source":"ha","connectionId":"<uuid>","entityId":"cover.garage","operator":"equals","value":"open"},
     {"kind":"time","from":"22:00","to":"06:00"}]},
  {"color":"#f9e2af","animation":"breathe","conditions":[
     {"kind":"state","source":"ha","connectionId":"<uuid>","entityId":"cover.garage","operator":"equals","value":"open"}]}]}

A placement holds at most 8 cues. The dashboard's viewers may read a cue's state sources, as they may a visibility condition's, and never write them. A condition whose source has not answered does not pass, so a border does not flash while the page loads. Viewers that ask for reduced motion, and renders, draw the cue's color without motion. The editor canvas draws cues live.

Variables

Variables are named values placements are templated on. Widgets refer to one in their configuration, a viewer picks a value, and a flow or a Home Assistant helper can set it for everyone. A mirror can switch between two people's calendars, commutes, and sensors this way, with one widget for each instead of one per person.

{"variables":[
  {"name":"person","label":"Person","type":"query",
   "query":{"source":"ha_entities","connection_id":"<uuid>","pattern":"person.*",
            "regex":"^person\\.(?<value>.+)$"}},
  {"name":"range","label":"History","display":"menu","default":"24",
   "options":[{"value":"6","label":"6 hours"},{"value":"24","label":"24 hours"}]},
  {"name":"ha","type":"constant","value":"<uuid>"}]}

variables lives in the dashboard's display object and deploys with it. A dashboard has at most 8. A name is a letter followed by up to 31 letters, digits, or underscores. Every variable takes an optional label, a description shown as its picker's tooltip, and a display:

display Picker
above (default) In a bar above the dashboard, with its label
label_hidden In that bar without its label
menu Behind a button in the top right corner, which suits a mirror or wall panel
hidden None; only links, commands, and followed helpers set it

Types

type Values
custom (default) options, 1 to 50 of {value, label}, with unique values of up to 200 bytes. default must be one of them; empty means the first
constant value, never shown and never changed by a command. Use it for something many widgets repeat, such as a connection ID written as ${ha}
query query, resolved against Home Assistant or a time-series connection
time_range A span from,to that charts read. options are presets of {value, label}, up to 30, and the built-in quick ranges when empty. default is a range, now-6h,now when empty. Any value that parses is accepted, from a picker, link, or command
interval options are durations such as 1m, 5m, 1h. With auto: true an auto option resolves to the nearest of 1s to 30d at or above the range_variable's span divided by steps (30), never below min_interval

A query's source is ha_entities or ha_select, and connection_id names the Home Assistant connection.

  • ha_entities lists the entities whose IDs match pattern, where * stands for any run of characters and other characters are literal. The value is the entity ID and the label its friendly name.
  • ha_select lists the options attribute of entity_id, an input_select or select. With follow: true the dashboard-wide value is that entity's state, so a Home Assistant automation that sets the helper switches every viewer, and the server refuses variable commands. Viewers may read the helper's state.

Time-series sources read a Prometheus, InfluxDB, or PostgreSQL connection; see timeseries.md. Saving or previewing a new or changed time-series query needs api:connections:read, as a chart query does.

source Options
prometheus_label_values Values of label, optionally of the series match selects, such as up{job="node"}
prometheus_metrics Metric names, optionally of match
prometheus_query An instant query text; each result's label value, or its series name
influx_query The first column of text in language influxql (default), flux, or sql
sql_query __value and __text columns of text, else the first and second

Their text and match may refer to variables defined earlier, such as label_values(node_filesystem_size_bytes{nodename="${host}"}, mountpoint) as a prometheus_label_values with match. A viewer's pick re-resolves the variables that refer to it, and a value no longer offered falls back to the default. Time macros use the range_variable's value, or the last 6 hours. Viewers may read what a chained query offers for every value of the variables it refers to.

An optional regex extracts the value from each entity ID or option. The value is its value group, else its first group, else the whole match, and a text group becomes the label. The query drops items the regex does not match. sort is empty for Home Assistant's order, or asc or desc by label. A query keeps at most 50 options. A default the query does not return means the first option.

Viewers, commands, renders, and validation all see the same options, which GET /api/dashboards/{id}/variables returns. A new Home Assistant entity can take up to 30 seconds to appear among a query's options. A query that cannot reach Home Assistant has no options. Viewers refresh options when they load or reconnect; a followed helper's state is live. resolve_dashboard_variables returns the resolution and any query errors, and the editor's Run query previews an unsaved query.

References

In any string of a placement's config, ${person} becomes the current value and ${person:text} its label. That covers binding fields, as in "entityId":"sensor.${person}_steps", and text, as in "name":"${person:text}'s day". The source and comparison fields of state conditions take references too. Keys do not, and a reference to a variable the dashboard does not define stays as written. A string that is exactly one reference whose value is a number or true/false becomes that type, so "hours":"${range}" reaches a history graph as a number. Widgets receive the substituted configuration and rebind when a value changes, without reloading.

A time range's ends are ${range:from} and ${range:to}. In chart query text, a plain ${name} is escaped for the language's string literals, so a value cannot change the query. PromQL and Flux escape backslashes and double quotes, InfluxQL escapes backslashes and single quotes, and SQL escapes single quotes. Write the quotes yourself, as in {host="${host}"}. ${name:raw} inserts the value unchanged, ${name:regex} escapes regular-expression metacharacters, and ${name:sqlstring} writes a quoted SQL string. Outside query text these formats insert the plain value.

Time range values grant nothing. They decide when data is read, not which data. A time range picker offers the presets, a custom range for both ends, a step back and forward by the current span, and a zoom out. Links carry the range as var-range=now-7d,now, and dragging across a chart sets it as absolute Unix milliseconds.

Viewers may read what each option's substitution binds, and nothing else. A placement whose variables combine into more than 256 value combinations grants none of its bindings. validate_dashboard reports that, references to undefined variables, and queries that fail, return nothing, or are truncated. It checks each templated config against the widget's schema with every variable at its default. See what a dashboard exposes.

Values

Each viewer holds its own value of each variable. It starts from the address parameter var-<name>, as in /dashboard/mirror?var-person=sam, when that names an option; otherwise from the dashboard-wide value, which a followed helper or a variable command sets; otherwise from the default. After that the newer of the viewer's own pick and a dashboard-wide change wins. pin=person in the address keeps that viewer's value whatever the dashboard-wide value does, and pin=* pins every variable, so a kitchen panel opened as ?var-person=sam&pin=person stays on Sam. A pick changes only that viewer and records it in the address, so the link opens on it. The server refuses a command naming a value that is not an option.

Editing

The Variables tab of the editor's settings dialog lists variables grouped by where their picker is drawn. Select one to edit it; reorder it within its group, duplicate, or delete it. Custom options are one per line, written as value | label. A value that holds a bar, such as web|api, needs the spaces around the separator and a label, as in web|api | Front ends. Each variable shows which widgets use it. The toolbar's Preview button picks values for the canvas without changing what viewers see.

Widget settings panels know the dashboard's variables. Connection, control, and device lists offer each as ${name} below the real choices and show a stored reference as itself. An entity field takes a template such as person.${person}, suggests entities from the connection the current values name, and shows what the reference stands for, as in "Now person.james". The history graph's hours accept a reference such as ${range}.

Widgets that use variables

  • Variable Buttons (variable-buttons) draws a variable's options as buttons, for a touch screen where a dropdown is awkward. variable names it. scope is screen (default), which switches only that viewer like a pick, or dashboard, which sets the dashboard-wide value like a Dashboard Command. A dashboard-scope press needs the dashboard's control policy, which allows people you shared it with at view level or above, and anyone when public control is on. layout is row, column, or grid; size is small, medium, large, or fit; and showLabel draws the variable's label.
  • News Feed URLs may name variables, as in http://example.com/${topic}.xml. The server reads the feed URLs itself, so the widget sends the viewer's values and the server substitutes only values that are options.
  • Calendar sources take a tag in the widget's panel, such as james. showTags lists the tags to show, comma separated, and may name a variable, so "showTags": "${person}" shows one person's calendars. Empty shows every source.

Karakuri does not substitute other configuration a plugin reads on the server. Place one widget per value and show each with a variable condition instead.

Renders take variable values as variables on render_dashboard and POST /api/dashboards/{id}/renders, or as var-<name> parameters on the direct render address. The render refuses a value the rendered layout does not offer, and any value for a constant. Schedules render with the dashboard-wide values.

Commanding a live dashboard

Commands change what open viewers show without touching the draft or a deployment. They come from the Dashboard Command flow node, MCP command_dashboard, POST /api/dashboards/{id}/commands, and Karakuri dashboard notification endpoints. Read the resulting state with get_dashboard_live or GET /api/dashboards/{id}/live, and follow it on the dashboard:{id}:live topic.

Action Fields Effect
hide targets, lock Add the lock (default command) to each placement
show targets, lock, force Release the lock; force releases every lock, including start
page page Go to a page by ID, title, or 1-based number; empty returns to the first
next_page, previous_page Step every viewer from the page it is on
alert title, message, level, style, duration, speak Show a toast or fullscreen alert for duration seconds (default 10, 0 until cleared); speak reads it aloud on viewers open when it arrives
clear_alert alert_id Remove one alert, or all of them
dim, undim dim_level Override the dim level (default 100), or return to the schedule
reload Reload every viewer's page
content targets, value, format Push a value into placements for widgets that show it; no value clears it
variable variable, value Set a variable's value for every viewer; value is an option value or label, and an empty string returns to the default. Constants and followed variables are refused

A placement is visible only when it holds no locks, its conditions pass, and it is on the current page. Locks let several automations hide one widget without undoing each other. The widget reappears only after each has released its own lock. Targets must be placements of the served layout, which is the deployed version, or the draft of a dashboard never deployed.

The server holds this state in memory and does not save it. A restart returns every dashboard to its authored start: no locks beyond start, no alerts, no dim override, no pushed content, every variable at its default, and the first page. The server keeps at most five alerts and drops the oldest. Alert titles hold up to 200 bytes, messages up to 4 KiB, and pushed content up to 64 KiB of JSON.

Content format is text, markdown, or json. The server renders Markdown strings and escapes raw HTML in them.

Widget configuration

Use a package's config_schema and default_config when it has them. This section describes the bundled packages. Unspecified fields take the widget's defaults. Preserve unknown existing fields, and do not invent configuration keys for other plugins. Place a widget with {} to take every default, and configure it in its panel afterward.

Digital clock

Package digital-clock draws the time. It takes:

  • timezone: an IANA timezone, or an empty string for local time.
  • format: 24h or 12h; default 24h.
  • showSeconds: boolean, default true.
  • fontStyle: monospace, sans, or segmented; default monospace.
  • color: CSS color, or an empty string to follow the theme.
  • layout: standard-inline, stacked-vertical, big-date, world-list, retro-lcd, time-progress, or sidebar-date.
  • worldTimezones: array of {timezone, label} for the world-list layout.

For example:

{"timezone":"America/Chicago","format":"12h","showSeconds":false,"layout":"big-date"}

Entity control and entities card

Package entity-control draws one binding. It takes the binding plus showName and showState booleans, both default true. Package entities-card draws a list of bindings. It takes {"title":"Room","rows":[...]}, where each row is a binding with a string id unique within that card.

A binding names its source and the identifiers belonging to it:

source Required binding fields Discovery tool
control controlId list_controls
ha connectionId, entityId list_connections, get_ha_states
mqtt deviceId list_mqtt_devices
flow-trigger flowId, trigger, or triggers entries list_flows, then inspect the flow's widget triggers
nvr connectionId, camera (* for every camera), display only list_connections, list_nvr_cameras

Optional name overrides the source label. icon is a Line Awesome class such as la-lightbulb. displayOnly: true prevents operation; false lets the widget render the control its source supports. The source decides whether that is a switch, slider, button, or another control, so do not invent a control field to choose it.

Home Assistant person and device_tracker entities, location controls, and MQTT devices of kind location draw as a location. The widget shows the zone's label (home as Home, not_home as Away, any other zone as its name), how long it has been there, and, when shown, coordinates with accuracy. Home Assistant locations are read-only. A location control with manual on draws its zones as a picker. showCoordinates: true on a binding shows the coordinates whatever the source's own setting, and is the only coordinate setting a Home Assistant entity has.

openHAB items reach dashboards as devices. Add them under Settings, Devices, Add from openHAB and bind rows with source: "mqtt" and the device's deviceId.

The ha entity picker groups entities under floor and area headings and searches area, device, and label names. The entities card config's Add an area appends a row for each of an area's entities, leaving out hidden, diagnostic, and configuration entities and those already on the card. The card does not follow the area afterward.

Home Assistant media_player entities, media controls, and devices of kind media draw as a player. A card row shows the title or state, play and pause, and the volume. An Entity Control shows title, artist, progress, previous, next, stop, mute, volume, source, and power, each only when the player has the feature. A Home Assistant player's features come from its supported_features, and progress advances while it plays. Art shows in an Entity Control only from an absolute URL; the Now Playing widget relays a Home Assistant player's own art.

A flow-trigger binding may use triggers, an array of {id, label, flowId, trigger, payload, payloadFormat, confirmFirst}. Payload is a string and payloadFormat is json or yaml. These bindings describe buttons; editing the dashboard does not press them.

States and value formats

Entity Control, each Entities Card row, and Button take states, an ordered list of up to 16 looks the binding takes on according to its reading:

{"source":"control","controlId":"<uuid>","icon":"la-microphone",
 "states":[{"operator":"equals","value":"on","icon":"la-microphone-slash",
            "background":"#c0392b","color":"#ffffff","iconColor":"#ffffff","label":"Muted"},
           {"label":"Live"}]}

A state compares the binding's own reading with operator (equals, not_equals, contains, above, below) and value. attribute compares one part of a composite control, such as a light's brightness, and empty compares its main value. A state with no operator always matches, which makes it a fallback last entry. Text comparisons ignore case, a switch reads as on or off (true and false work too), and above and below fail on anything that is not a number. The first match sets any of icon, iconColor, background, color (text), and label; fields it leaves unset keep the binding's look. A label may hold {value}, the formatted reading, and {name}. No state applies while the source is unavailable or has not answered. States read only the binding, so they grant nothing beyond it. To style a tile from another source, use a status cue.

format draws a numeric reading as duration (seconds as 3:07, 3:07:42, or 1d 1:01:01), bytes (1536 as 1.5 KB, in 1024 steps), bytes_per_second (3.5 MB/s), percent (12.5 %), or number, which keeps the unit. precision sets the decimals of number and percent and overrides the ones the source reports. A reading that is not a number draws unchanged.

Button

Package button draws one binding as a square button with a large icon, the label, and with showValue the formatted reading. It takes the binding fields above, states, format, precision, showLabel (default true), showValue (default false), and confirmFirst.

Pressing anywhere on it sends the binding's single action. A switch, light, or fan toggles; a lock locks or unlocks; a scene, script, button entity, or buttons control with one action runs; a flow trigger fires its first press. Numbers, lists, text, display-only bindings, and viewers without the dashboard's control policy send nothing, and the button shows its reading. With confirmFirst, or a trigger press's own confirmFirst, the first press shows "Tap again" for 3 seconds and only a second press sends. A failure flashes the border and names the reason on hover.

Image and video

Package image draws images or a slideshow. It takes images, an array of URL entries {type: "url", url, label}. The default layout is static, fit is cover, refreshInterval is 0, slideInterval is 5, and transition is fade. Preserve existing uploaded-image entries when editing a list.

Package video plays a video. It takes a source URL, layout: "player", sizing: "contain", and autoplay, loop, and mute booleans, all default false. Upload files through the widget's panel.

Weather

Package weather draws a forecast. It takes latitude, longitude, and locationName. It defaults to provider: "openmeteo", which needs no API key. openweathermap needs a configured plugin key with access to its forecast API. The panel and renderer use the same provider default when it is omitted.

Use backgroundStyle: "image" for a built-in photo chosen from the current weather, gradient for a weather gradient, or none (default). Do not stack an image widget under the weather widget for its background. iconTheme is static (default) or animated; units is metric (default) or imperial; and language defaults to en. list_widget_types lists the supported layouts and the rest of the configuration.

For full-screen weather, use one weather widget covering the fit grid and set padding, gap, and widget_padding to zero. For example:

{"latitude":34.7304,"longitude":-86.5846,"locationName":"Huntsville, AL",
 "provider":"openmeteo","units":"imperial","layout":"current",
 "backgroundStyle":"image","iconTheme":"static"}

For an ESP32 image display, preview at the display's actual pixel dimensions. If those are unknown, ask before setting up a render schedule. Editing the dashboard does not deploy it or configure the device.

Changing provider, coordinates, units, or language clears the previous forecast, so the widget never shows the old selection's data. A failed refresh for the same selection keeps its last forecast with a visible error and Retry control.

Local station readings reach the widget through a flow's Weather Override node, not through the widget. A forecast whose coordinates lie within an override's radius shows the live readings in current and lists them under override, with when each was set and when it expires. An override's change or expiry refetches open widgets nearby.

Weather air quality

The weather widget's air-quality layout shows the air quality index with its category, the next 24 hours, particulates and gases, and pollen where Open-Meteo publishes it (Europe). aqiScale is us (default) or european. The widget reads Open-Meteo's free air-quality API alongside the forecast. OpenWeatherMap forecasts carry no air quality, and a failed air-quality fetch leaves the forecast intact.

Rotating message, flow text, and news feed

Package rotating-message shows one line at a time. It takes lists, an object of string arrays. Keys morning, afternoon, evening, and anytime follow morningStart (3), morningEnd (12), afternoonStart (12), and afternoonEnd (17). A YYYY-MM-DD key with . as a wildcard, such as ....-12-25, applies on matching dates, and a five-field cron key applies in matching minutes. Any other key matches the value of the optional weather binding, such as a Home Assistant weather.home entity reporting rainy; write the binding with displayOnly: true. specialDayUnique shows only the date and cron lines when one matches. interval is seconds between lines and fade the cross-fade in milliseconds. A content command with a string or a list of strings replaces the lines until it is cleared.

Package flow-text shows the content a flow pushes, as text, Markdown, or formatted JSON. It takes an optional title, and placeholder shows until content arrives. The widget removes Markdown images from other origins. A list of strings shows as lines. A list of objects shows as a table whose columns are the objects' keys. A flow's objects arrive with their keys sorted, so set columns to choose and order them, and columnLabels ({"key":"Header"}) to rename them. maxRows caps the rows, 0 for all.

Package news-feed shows headlines. It takes up to five feeds ([{"url":"https://example.com/rss","title":"Local"}]). The server fetches the URLs saved in the placement and caches each for five minutes; the widget never sends a URL. layout is ticker (one headline) or list (listSize headlines). interval, reload (minutes), maxItems, maxAgeHours, showDescription, showSource, and showTime tune it. A content command with next, previous, or details steps or expands the headline.

Camera, media, list, and graph widgets

These packages bind one Home Assistant entity, NVR camera, or media player, or several entities for the graph, with the binding fields in Entity control and entities card. Viewers may read only what they bind.

Package Binding Fields
camera A camera. entity, or an nvr camera with source: "nvr" and camera, at the config root, display only mode live (relayed MJPEG stream, default) or snapshot; interval seconds between snapshots (10); fit cover or contain; showName; bbox draws Frigate's object boxes for an NVR camera
nvr-events An nvr binding at the root; camera * lists every camera of the connection labels and zones (comma separated), limit (1 to 100, default 10), showThumbnails. Tapping an event plays its clip
media-player One binding at the root: a media_player. entity (source: "ha"), a media control (source: "control", controlId), or a device of kind media (source: "mqtt", deviceId) layout card or compact; showArt, showControls, showVolume. Controls follow the player's features and need a writable binding and the dashboard's control policy
todo-list A todo. entity at the root title (empty uses the list's name), showCompleted, allowAdd, maxItems (0 for all). Ticking and adding need a writable binding and the control policy
activity rows, a list of control, mqtt, or ha bindings with id and displayOnly: true categories and levels (comma separated), limit (1 to 50, default 10), showActor. Lists the event log entries of the bound subjects live; never security entries. See events.md
history-graph series, a list of rows with id, source, the source's IDs, name, color, and displayOnly: true hours (1 to 168, default 24), style line, area, or step, min, max, showLegend, showCurrent

A live Home Assistant camera keeps one stream open per viewing browser; an NVR camera shares one stream from Frigate among every viewer at the same height. Both fall back to snapshots while the stream reconnects. frigate.md has the NVR details. Karakuri relays cover art that Home Assistant hosts; art on another host loads from that host. ha series take their history from Home Assistant's recorder. Control and MQTT series keep no history and start when the page loads. Numbers plot directly, and on/off and true/false plot as 1 and 0.

Charts

Package chart draws the results of time-series queries. timeseries.md covers connections and query macros. For example:

{"viz":"timeseries","timeRange":"${range}","refresh":"30s",
 "queries":[{"refId":"A","connectionId":"<uuid>","language":"influxql",
   "text":"SELECT mean(\"value\") FROM \"temperature\" WHERE $timeFilter AND \"room\" = '${room}' GROUP BY time($__interval)",
   "legendFormat":"{{room}}"}],
 "fieldConfig":{"defaults":{"unit":"celsius","decimals":1},"overrides":[]},
 "transformations":[],"options":{"legend":{"displayMode":"table","calcs":["mean","max"]}}}
  • viz is timeseries, trend, barchart, stat, gauge, bargauge, table, piechart, state-timeline, status-history, heatmap, histogram, candlestick, or xychart.
  • queries holds 1 to 10 queries. Each has refId, connectionId, language (promql, influxql, flux, sql, ha_history, ha_statistics, energy), text, ha (entities, attribute, statistic_ids, period, types), or, on connection energy, energy (targets, measure, period; energy.md lists them), legendFormat, maxDataPoints (default the chart's width in pixels), minInterval, instant, format (time_series or table), and hide, which keeps a query for transformations without drawing it.
  • timeRange is from,to or a time range variable reference; empty is the last 6 hours. relativeTime (such as 1h) replaces it with the last span, and timeShift (such as 1d) moves it back. A zoom on the chart replaces the relative time until the viewer zooms out. refresh is a duration of at least 5s, off, or an interval variable reference.
  • fieldConfig sets units, decimals, min, max, display name, color schemes, thresholds, value mappings, no value, and overrides matched by name, regex, query, or type.
  • transformations organize, rename by regex, filter by name or value, reduce, calculate, join by field, merge, series to rows, labels to fields, group by, sort by, limit, and convert field type.

The settings panel offers each query language's editor with name suggestions, a preview, and a query inspector. Dragging across a time axis sets the chart's time range variable, or zooms that chart alone when its range is fixed; a double click zooms out. Renders wait for every chart's data. The package has no visualizations for logs, traces, maps, or free canvases.

Countdown and Wi-Fi QR

Package countdown counts down to dates. It takes events, a list of {label, date: "YYYY-MM-DD", time?, yearly?}. layout is single for the nearest event or list for up to maxItems. units is days or auto, which shows hours and minutes inside a day. A yearly event moves to next year once its day ends, and showPast keeps passed events as "N days ago".

Package wifi-qr draws a join-network QR code. It takes ssid, password, security (WPA, WEP, or nopass), and hidden, with an optional label and showPassword. colors is plain, black on white, which scans most reliably, or theme. The password is in the widget's config, so every viewer of the dashboard can read it, as they can from the code.

Other bundled widgets

These packages work with their defaults. The table lists their common settings.

Package Fields
analog-clock timezone, secondHand (default tick), faceStyle (default dark), accentColor, layout (default classic), secondTimezone
binary-clock timezone, format (24h or 12h), ledShape (circle or square), activeColor, inactiveColor, layout (default bcd-grid)
fuzzy-clock timezone, fuzziness (default 3), language (default en), typography (default serif), layout (default single-sentence)
stock symbols (array of ticker strings), provider (default yahoo), layout (default single-quote), interval (default 1D)
crypto pair (default BTC/USD), provider (default coingecko), layout (default price-card), quoteCurrency (default USD)
calendar layout (default monthly), startOfWeek (default 0), showTags. Sources are set in its panel and stored by the calendar plugin, not in the placement's config. Each source names a calendar connection (ICS, CalDAV, or Google) with its own name, color, tag, and optionally which of the connection's calendars to show; credentials stay in the connection

Ask for a location or source identifier when it is missing. Do not guess which Home Assistant entity, MQTT device, or calendar belongs to the user.

Drafts and deployment

Writes save the draft immediately. An existing deployed dashboard keeps its published version until you call deploy_dashboard, and an undeployed dashboard shows its draft. The editor chat can deploy when asked. A deployment freezes the name, description, and theme selection with the layout, while sharing and URL identity stay live. A theme or widget package updated later still changes how deployed dashboards look.

Browser and MCP edits share the same draft and appear in other open editors. restore_dashboard_version replaces the whole draft with a stored version; omitting the version discards all changes since the current deployment. It does not deploy the restored draft.

Use render_dashboard to inspect a screenshot of the draft before deployment. It uses the dashboard's real renderer at a requested width and height. Check spacing, clipping, and widget configuration in the image. A screenshot captures the requested viewport and does not interact with controls.

Before deployment, run validate_dashboard for geometry, schema, and binding checks, then render_dashboard with diagnostics: true for a screenshot with widget bounds, overflow, and browser errors. Widgets without config schemas produce a warning, so read their documentation and preview them. diff_dashboard shows draft changes against the deployment, including title and theme selection.

Validation runs only when you call it. Overlaps are warnings, and deployment snapshots the stored draft without running validate_dashboard. A config or display replacement that names its revision cannot overwrite a newer one; on a conflict the editor says so and reloads the other writer's change. The placement picker lists loaded packages, but direct writes can name a package whose plugin is unloaded and can save invalid geometry. validate_dashboard reports both, and a widget whose plugin is unloaded exposes nothing to viewers.

What a dashboard exposes

The people who look at a dashboard usually hold no permissions: a housemate you shared it with, a wall panel in the hallway, anyone with the link once it is public. They do not need api:connections:read, which would open the whole Home Assistant instance, every MQTT device, and every control. What the dashboard shows decides what they can see and press.

The layout is the grant. Placing a widget bound to light.lamps lets the dashboard's viewers read light.lamps, and nothing else on that connection. A dashboard with no widget on a connection exposes nothing on it. Everything below follows from that rule.

Which layout counts depends on deployment:

  • Once a dashboard is deployed, viewers get the deployed version's bindings. Draft changes expose nothing until you deploy them.
  • Authors with edit access also get their draft's bindings while editing.
  • A dashboard that was never deployed shows its draft. Edits to an undeployed public dashboard change what the public can read as soon as they are saved, so deploy a public dashboard before you start reworking it.
  • If the deployed version is damaged and cannot be loaded, viewers see an error. They never fall back to the draft.

Who can see and do what

Viewer Read what the dashboard shows Operate what it shows Anything it does not show
Anonymous visitor Only if the dashboard is public Only with public control on No
Signed-in user who sees it only because it is public Yes Only with public control on No
Read share (View only in the share dialog) Yes Only with public control on No
View, edit, or admin share, and the owner Yes Yes No
A render, including one opened with a render key Yes No No
Holder of the subsystem permission Yes Yes Yes, through that permission

Public control is off by default and sits beside Public dashboard in the dashboard's settings. Publishing a dashboard shows the house; it does not hand out the switches. Turn public control on only when anyone with the link should be able to press things.

Sharing with a named person at view level or above lets them operate the dashboard, and runs they start carry their name. Use a read share for someone who should watch without pressing, such as a guest or a panel in a shared room. Signing in alone creates no share.

Viewers who may not operate see readings in place of switches, sliders, and buttons. The server refuses their presses either way, so a modified page gains nothing.

Share levels

Share levels are read, view, edit, and admin. Each includes the ones below it. A share made without a level is view, and any other value is refused.

Action Needs
View the dashboard view (or read), public, or ownership
Edit, place widgets, deploy edit
Change sharing, delete admin
Create a dashboard in a group edit on the group
Move a dashboard to another group admin on the dashboard and edit on the target group
Reorder within a group edit on each dashboard

A dashboard inherits its group's shares, and a group's owner holds admin on every dashboard in it, so moving a dashboard between groups changes who can see it.

api:dashboards:write lets a user create dashboards of their own. It does not let them write into someone else's. api:dashboards:manage does, and the Admin role's api:* includes it; api:dashboard-groups:manage does the same for groups. A private dashboard is missing from the list of anyone without access, and opening its address answers not found.

Viewers who are not the owner and lack api:dashboards:read see the owner only as an ID and username. Publishing a dashboard does not reveal the owner's email address or preferences.

What each binding lets viewers read and operate

A binding is the source a widget row, tile, condition, or cue names. Viewers reach a binding's connection through the dashboard, so a dashboard deploys only when its deployer may use every connection its entity, device, camera, condition, variable, and chart bindings reach. Saving a chart query or a time-series variable query likewise needs the connection shared with you. Each source grants this much to the dashboard's viewers:

Source Viewers may read Viewers may operate, with the control policy above
ha The bound entity's state, and where a widget shows them its history, its to-do items, a camera's snapshots and live stream, and a media player's cover art Services of the entity's own domain, aimed at that entity only
control The bound control Setting the bound control
mqtt The bound device's name, controls, buttons, and current values Commands to the bound device
flow-trigger Nothing Firing the bound trigger names, each one separately
nvr The bound camera's images, stream, and events, or every camera of the connection with camera: "*" Nothing

Some consequences:

  • Lists are filtered, not refused. A viewer asking for the house's entities, controls, or devices gets only the ones the dashboard binds, so a public dashboard does not publish the inventory of the house.
  • Home Assistant calls stay on the bound entity. A dashboard can call light.turn_on on light.lamps, but it cannot call a service without a target, a service aimed at an area, device, floor, or label, or a service of another domain. Script services are limited to script.turn_on, script.turn_off, and script.toggle on the bound script. That keeps a viewer from turning a lamp binding into a whole-room call, running an unrelated script or shell command, or purging the entity's history.
  • MQTT device details stay private. Viewers do not see a device's state or payload scripts, its connection, or its topics.
  • Credentials stay on the server. Karakuri fetches camera images, streams, and Home Assistant-hosted cover art with the connection's own token and relays them. The viewer's browser loads cover art hosted elsewhere from that host.
  • Each viewer's camera holds a stream. A live Home Assistant camera keeps one stream open per viewing browser for as long as it is on screen. NVR cameras share one stream among viewers; see frigate.md.
  • Flow-trigger rows need flow access to deploy. Deploying a dashboard that holds a flow-trigger binding needs edit access to that flow. Deployment reports a flow you hold nothing on as missing. A version deployed earlier keeps working.
  • Raw MQTT is never exposed. Subscribing to broker topics and publishing to them always need the connection permission. Bind a device instead.

The activity widget reads the event log of the subjects it binds, and never security entries.

Display only

A row marked Display only (displayOnly: true) grants no write, however the dashboard is shared or published. The checkbox is the only part of a binding that decides whether it can be pressed. The source decides only how the row is drawn. Mark every row a viewer should only watch.

Conditions, status cues, and states

Visibility conditions and status cues name sources with the same fields as bindings. Each one lets viewers read its source and never write it, like a display-only row. Hiding a camera tile until the garage door opens therefore lets the dashboard's viewers read the door's state.

Time conditions and variable conditions read no source and expose nothing. A binding's states read only that binding, so they expose nothing beyond it.

Variables

A binding templated on a variable, such as "entityId":"sensor.${person}_steps", exposes what each of the variable's options substitutes into it: sensor.james_steps and sensor.sam_steps for two options, and nothing a value outside them could name. Viewers cannot type free values. The dashboard ignores a link naming a value that is not an option, and the server refuses a command naming one.

  • Every option is readable. Viewers may read every option's bindings whatever value they picked. Put data only one person should see on a dashboard of its own.
  • Query options follow the house. A Home Assistant query's options are what Home Assistant currently returns, so a new person.* entity becomes readable through a person.${person} binding within about 30 seconds. Write a regex or a narrower pattern when the set should not grow.
  • Too many combinations expose nothing. A placement whose variables combine into more than 256 values grants none of its bindings, and validate_dashboard reports it.
  • Followed helpers are readable. A variable that follows an input_select or select lets viewers read that entity's state.
  • Resolved options are visible. Anyone who may view the dashboard sees them. Previewing an unsaved query needs edit access. Saving or previewing a new or changed Prometheus, InfluxDB, or SQL query variable also needs api:connections:read, because it runs text on the connection.
  • Time ranges expose nothing. They decide when data is read, not which.

A Variable Buttons placement with scope: "dashboard" lets viewers set that one variable's dashboard-wide value, and like any press it needs the control policy. Editors may always set variables. A placement with scope: "screen" changes only the viewer's own screen and needs nothing. Variables covers defining them.

Charts and feeds

The server runs a chart's queries from the saved placement. Viewers never send query text, so they cannot run their own queries through a chart, and their variable values are used only when each is an option.

Anyone who may view the dashboard, including public, shared, and render viewers, reads its charts. Query text is part of the placement's config, so viewers can read it. Point charts at a database user that may read only what the dashboard shows. PostgreSQL queries run in read-only transactions regardless.

Saving a chart whose queries change, through the editor, MCP, or import, needs api:connections:read, and so does the editor's preview. A dashboard editor therefore cannot read a connection through a chart they could not query directly. Moving, resizing, or restyling a chart needs only edit access. See timeseries.md for connections.

The news feed fetches only the URLs saved in the placement, with variable values that are options. A viewer cannot make the server request another address.

What to keep out of a placement's config

Every viewer of a dashboard is served every placement's config, including widgets that are hidden or on another page. Do not put secrets there.

  • The Wi-Fi QR widget's password is readable by every viewer, as it is from the code itself.
  • Chart query text is readable, as Charts and feeds explains.
  • The calendar plugin stores calendar sources, including Google API keys, outside the config. Its panel shows whether a key is set but never returns it.

Plugin widgets

A plugin widget exposes only what its plugin declares. A widget that declares nothing, such as a clock or an image, reads nothing and exposes nothing. A widget whose plugin is unloaded exposes nothing either. Plugin authors declare what a widget may read in its manifest; see plugins.md.

A plugin may choose a broader boundary. A viewer of a dashboard holding the weather widget can read forecasts for other locations as well as the one shown.

Public controls and triggers

A control or widget trigger with Allow public set is public wherever it appears, including outside any dashboard. That is separate from everything above: display only, public control, and renders do not take it away. Use dashboard sharing for the general case, and Allow public only when you mean the object itself to be public.

Live display state and commands

Exactly the people who may view a dashboard, renders included, may read its live state. That covers hidden placements, the current page, alerts, the dim override, pushed content, and dashboard-wide variable values. An alert's title and message and any pushed content are shown to all of them, anonymous viewers of a public dashboard included.

Sending commands through REST or MCP needs edit access. A flow's Dashboard Command node can command any dashboard, the same reach flows already have over controls and connections, so the permission to deploy flows is what limits it. A Karakuri dashboard notification endpoint can also address any dashboard, and saving one needs the connection write permission. Commands never change what a dashboard exposes. They show and hide placements, add text, and pick among variable options the dashboard already has.

Renders

A render opens the dashboard in a headless browser and photographs it. The browser is not signed in as anyone, not even the owner. Each render can view only the dashboard it photographs, and only while the job runs. It can read what that dashboard's deployed layout shows and press nothing. Public controls and triggers stay callable, as they are for anyone.

An editor may render the draft through render_dashboard. That render reads only the dashboard's draft and the data its widgets bind, and it still presses nothing and opens no other dashboard. Adding view=draft to an ordinary render address does not show the draft.

Anyone who may view a dashboard may render its deployed layout. The server limits how many renders run at once with render.workers and render.max_queue_size, and refuses new requests while the queue is full.

Inspecting a render's diagnostics needs edit access for a draft and view access for the deployed layout. Diagnostics record no request headers or bodies and strip credentials, query strings, and fragments from URLs. Dependency inspection and validation need edit access, and they report references you cannot read as unchecked.

Render keys

Render addresses (/dashboard/{id}/render/... and a schedule's latest-render address) are often used by an <img> tag or a photo frame that cannot sign in, so they take a credential in the token query parameter. A private dashboard's render page offers a render key for that. A render key is an API key tied to the dashboard that holds no permissions.

  • A render key opens that dashboard's direct and schedule render addresses and nothing else. Everywhere else, including the API, viewer pages, plugins, and other dashboards, it counts as no credential.
  • It works only while its owner can view the dashboard as its owner, through a share, or because it is public. The dashboard manage permission does not count, so an administrator who sees a dashboard only through manage cannot create one.
  • Unsharing the dashboard from the key's owner or deleting the key stops every address that carries it. Deleting the dashboard deletes its keys.
  • Anyone holding a copied address can see the render, so treat the address as a password for that one picture.

The render page's Access keys table lists the dashboard's keys with their prefix, creation, and last use. Add key takes a name, so the key given to the hallway display can be deleted without breaking the kitchen frame's. Use puts a key into the copied render URL, embed snippet, and schedule addresses, and the trash button deletes a key.

Over the API, GET /api/api_keys?dashboard_id={id} lists your render keys for a dashboard, and POST /api/api_keys with dashboard_id creates one, which needs API key write permission and view access to the dashboard. GET /api/api_keys/{id}/value shows a render key's value again. It works only for render keys, only for their owner, and only when signed in, never with another key.

Uploaded files

Files uploaded to a widget, such as images and videos, are served at /widget/{placement}/{upload}/{filename} to whoever may view the placement's dashboard. A public dashboard's files load for anyone. A private dashboard's files stop loading when the dashboard is made private or unshared. A file on a placement that is not yet deployed needs edit access, and a render sees only its own dashboard's files. A file you may not see answers not found, so guessing addresses cannot confirm that it exists.

Taking access away

Unsharing a dashboard, making it private, removing a role, deleting a session, or unloading a plugin takes effect on open pages too, not only on the next load. Within about 30 seconds, and immediately after most changes made through the app or MCP, open viewers stop receiving updates they may no longer read.

Home Assistant

A Home Assistant connection reads entity states, calls services, and follows state changes over Home Assistant's WebSocket API. Karakuri also reads where each entity sits, so flows can target rooms, and its entities can be added as devices.

Connecting

Add a connection of kind Home Assistant under Connections:

Field Meaning
Base URL The instance's root URL, such as http://homeassistant.local:8123.
Access token A long-lived access token from the Home Assistant profile page.

Each time the connection signs in, including after a reconnect, it reads the registries described below before it reports the state changes it missed, so area and label triggers place those changes correctly.

Areas, floors, devices, and labels

Karakuri reads Home Assistant's floors, areas, devices, entities, and labels. A change made in Home Assistant, such as adding a device or moving an entity to another area, reaches karakuri about two seconds after Home Assistant finishes it. Karakuri writes nothing back. Manage areas, devices, and labels in Home Assistant.

Question Answer
Which area is an entity in? Its own area, or its device's area when it has none
Which floor? Its area's floor
Which labels? Its own and its device's. A label target also reaches every entity in an area that carries the label.
What is it called? Its friendly_name

Karakuri leaves out disabled entities and devices. It keeps hidden entities but leaves them out of pickers unless asked for.

Home Assistant older than 2024.4 has no floors or labels. When a registry cannot be read, karakuri leaves it empty and loads the rest. get_ha_registry and GET /api/connections/{id}/ha/registry report each registry as loaded or give the reason it is empty.

Pickers

Entity pickers in flow nodes and in dashboard widget settings group entities under floor and area headings and show each entity's device. A search matches the entity ID, its name, its device, its area and floor, and its labels. Entities in no area come last. The widget picker has a Show hidden switch.

Area, floor, device, and label fields complete against the registries and store comma-separated registry IDs, which read back as names under the field. Areas created in Home Assistant's interface have opaque IDs such as 761b686f283b4b77b5dfdf1bf9e4b394 rather than kitchen, so pick them or look them up with get_ha_registry instead of typing a name. You can also type a {{ }} expression.

Over MCP, get_ha_registry lists floors, areas, devices, and labels with their IDs. get_ha_states adds each entity's area, floor, device, and labels, and filters by area, floor, device, or label, by ID or name.

Entities as devices

Settings, Devices, Add from Home Assistant (or discover_entities and add_entities with the Home Assistant connection) lists entities by floor and area with the device kind each becomes. None is ticked by default. Object IDs are entity IDs, and devices take the entity's friendly name. To add entities without picking them, including ones added later, turn on auto import on the connection with an area or domain filter; the Device auto import guide under Help covers it.

The dashboard uses the same mapping to draw a Home Assistant entity, so a device and a card row bound to the same entity show the same face and value:

Domain Device kind
light Light, with brightness, colour, colour temperature, and effects as the entity supports
switch, input_boolean, siren, humidifier Toggle
fan Fan
cover Cover
climate, water_heater Thermostat
lock Lock
media_player Media player, with the features supported_features reports
number, input_number Number
select, input_select Dropdown
text, input_text Text
scene, script, automation, button, input_button Buttons, one press
person, device_tracker Location, read only
anything else Text reading, read only

A Home Assistant device works like any device: dashboard rows, conditions, history forwarding, the event log, and the Device Value, Command Device, Device Changed, and Device Availability nodes. Karakuri checks a command against the kind and the entity's features, then sends the matching service call, such as light.turn_on with brightness_pct or media_player.media_pause. The device's value changes when Home Assistant reports the new state, never before. A device is offline while its entity is unavailable or unknown.

A device follows its entity. When you rename the entity ID in Home Assistant, the device moves to the new ID. An entity that disappears marks its device missing until it returns.

Karakuri reads kind options when the device is added. When the entity gains or loses features in Home Assistant, edit the device's options, or delete the device and add it again.

Nodes

Nodes are in the Home Assistant folder.

HA Call Service targets entities, areas, floors, devices, and labels, in any combination, and Home Assistant acts on all of them. When the call names no entity and the registries are loaded, karakuri checks the target first. A call whose areas, floors, devices, and labels hold no entity of the service's domain fails with no light entities in Hallway instead of reporting success. A service whose domain has no entities of its own, such as homeassistant.turn_off, is not narrowed by domain.

HA State watches entities, or areas, floors, devices, and labels, optionally narrowed by domain and device_class:

{ "connection": "<home assistant>", "floor_id": "downstairs", "domain": "binary_sensor",
  "device_class": "motion", "to": "on" }

Karakuri matches each change against the registries as they are at that moment. A sensor added to a downstairs room next month fires the trigger from its first change, with no redeploy. The payload adds area_id, area, and device_id. A target that matches nothing yet still arms and logs watching on Downstairs: no matching entities yet.

HA Get State reads one entity, or, given an area, floor, device, or label, every matching entity as {states: [...], count}.

Service calls from a dashboard name entities only. Karakuri refuses an area target from a dashboard, because a dashboard's viewers are granted the entities it shows, not the rooms they sit in.

openHAB

An openHAB connection follows an openHAB server's items over its REST API and event stream. Its items can be added as devices, which cards draw and flows command like any device. Flows can also trigger on item changes, send commands, and read items. openHAB 4 and later are supported.

Connecting

Add a connection of kind openHAB under Connections:

Field Meaning
Base URL The server, such as http://openhab.local:8080, without /rest.
API token Optional. openHAB lets anonymous clients read and send commands unless that is turned off. When it is, create a token on the openHAB profile page under API tokens.

Test reports the version, the item count, and whether it authenticated, such as openHAB 5.2.3, 18 items, authenticated, or why it failed: unauthorized: check the API token, not found: is this an openHAB server?, or the network error.

The connection reads every item when it connects, then follows the event stream for item state changes and for items added, removed, or updated. When the stream goes silent for 30 seconds, the connection reports an error and reconnects, waiting 1 second and doubling up to 30. After a reconnect it reports each item whose state changed while the stream was down once, with its latest state, marked caught up. Items that did not change are not reported, and the first connect after the server starts does not count as an outage.

Locations

Karakuri reads locations from openHAB's semantic model. It places an item at its own location, else at the location of the equipment it is a point of, else at the nearest location group among the groups it belongs to. A location's floor is the floor it is part of. Item lists group by floor and location, with items in no location last. A house without semantic tags gets flat lists.

GET /api/connections/{id}/openhab/items and the MCP tool list_openhab_items list items with type, state, whether each is read only, and location and floor. list_openhab_items filters by location (a location group's name or label, including the rooms on a floor), type, and text. send_openhab_command sends a command to an item or group.

Items as devices

Settings, Devices, Add from openHAB (or discover_entities and add_entities with the openHAB connection) lists items by floor and location with the device kind each becomes. None is ticked by default. Object IDs are item names. To add items without picking them, including ones added later, turn on auto import on the connection with a location or item type filter; the Device auto import guide under Help covers it.

Item type Device kind Commands
Switch Toggle ON, OFF
Contact Toggle labelled Open and Closed, read only none
Dimmer Light with brightness a percent, ON, OFF
Color Light with brightness and colour h,s,b from the hex colour, a percent, ON, OFF
Rollershutter Cover with position position as 100 − position, UP, DOWN, STOP
Number, Number:Dimension Number with the item's minimum, maximum, and step, and its unit the number
String with options Dropdown of the options the option
String Text the text
DateTime Date and time RFC 3339
Player Media player with play, pause, next, and previous PLAY, PAUSE, NEXT, PREVIOUS
Location Location with latitude and longitude, read only none
Group with a base type As its base type sent to the group, which passes it to its members

openHAB counts a rollershutter at 0 as open and a karakuri cover counts 100 as open, so the device converts both ways. A colour's hue and saturation become the hex colour, and its brightness becomes the light's brightness. A number's unit, such as °C, becomes the device's unit. openHAB 4 and later report the unit even before the item has a state. Older versions report it only inside the state.

openHAB accepts commands outside an item's state description, such as a volume past its maximum or a string outside its options. A device refuses them before anything is sent: a value outside the description's minimum, maximum, or options, and any write to an item openHAB marks read only. A device made from a read-only item is a reading and takes no commands.

An openHAB device works like any device. The device's value changes when openHAB reports the new state, never before. An item whose state is NULL or UNDEF gives its device no value. A removed item marks its device missing until an item of that name returns. openHAB treats a rename as a removal and an addition, so add the renamed item again.

Groups without a base type, Image items, and Call items cannot be devices. Trigger on a group's members instead.

Nodes

Nodes are in the openHAB folder.

openHAB Item Changed starts a run when an item changes. It watches items by name, every member of groups at any depth, or every item in or inside a location, optionally narrowed by item type (Number matches dimensioned numbers too) and by from and to states. The payload is {item, type, label, old, new, location}, with caught_up: true for a change found after a reconnect. Ignore changes caught up after a reconnect skips those. Group and location membership is read at each change.

openHAB Send Command sends a command, templated from the message, to an item or group. When openHAB refuses it, the node fails with openHAB's reason.

openHAB Get Item is a value node. It returns {item, state, type, label, location} from the connection's current copy of the items.

Item fields complete against the connection's items, grouped by location.

ESPHome

An ESPHome connection talks to one ESPHome node over its native API, as Home Assistant does, so the node needs no change and Home Assistant can stay connected to it at the same time. The node's entities can be added as devices beside MQTT and Zigbee2MQTT devices, and flows can call the node's actions.

Connecting

Add a connection of kind ESPHome under Connections:

Field Meaning
Host The node's address or name, such as garage-controller.local. Find nodes lists the nodes announcing themselves on the server's network and fills host and port. Nodes on another subnet do not answer the search, so type their address.
Port 6053 unless the node's api: block sets another.
Encryption key The base64 key from the node's api: encryption: key:. Stored encrypted and never shown again.
Password The legacy API password, for nodes from before encryption keys. Leave it empty when the node uses a key.

Test connects once and reports the node's name, board, ESPHome version, MAC address, and entity count, or why it failed: connection refused when nothing listens, wrong key when the encryption handshake fails, the node requires an encryption key when the key is missing, or invalid password.

The connection stays open. It pings the node every 20 seconds and counts the node gone when a ping goes unanswered for 10. It then reconnects on its own, waiting 1 second and doubling up to a minute, and looks the node up by name on the network in case its address changed.

Entities as devices

Settings, Devices, Add from ESPHome (or discover_esphome_entities and add_esphome_entities with the ESPHome connection) lists a connected node's entities with the device kind each becomes. Every entity that can be added starts ticked. Devices are named after the node and the entity, such as garage Porch, and can be renamed. With auto import on the connection, every entity is added when the node connects, without opening the list; the Device auto import guide under Help covers it.

ESPHome entity Device kind Takes commands
switch Toggle yes
binary_sensor Toggle, labelled by device class (door: Open and Closed, motion: Detected and Clear) no
light Light, with brightness, colour, colour temperature, and effects as the node supports yes
cover Cover, with position and tilt when supported yes
fan Fan, with speed as a percentage of the node's speed steps, oscillation, direction, and presets yes
lock Lock yes, unless it needs a code
climate Thermostat, with modes, target or range, current temperature, action, and fan modes yes
number Number, with the node's bounds, step, and unit yes
select Dropdown yes
text Text yes
button Buttons, one button yes
sensor Number reading with the node's unit and precision no
text_sensor Text reading no
event Text reading of the last event type no
media_player Media player, with volume, mute, stop, and power as the node reports them yes

Alarm panels, sirens, valves, update entities, date and time entities, and cameras are listed but cannot be added yet. ESPHome's API carries a media player's state, volume, and mute but no track details, next or previous, seek, or source. Those controls are off, karakuri refuses a skip before sending it, and an announcement plays as playing.

An ESPHome device works like any device: dashboard rows, conditions, history forwarding, and the Device Value, Command Device, Device Changed, and Device Availability nodes. Karakuri checks a command against the kind, then sends it to the node. The device's value changes when the node reports the new state, never before.

A device follows its entity by object ID, which survives reflashing. When a node no longer lists an entity, the entity's device is marked missing and drawn as unavailable until the entity returns.

A device is online while its node is connected and unknown while it is not. The connection status trigger and Device Availability both see the change. After a restart, devices show their earlier values marked stale until the node reports.

Nodes

Nodes are in the ESPHome folder.

ESPHome Action calls one of the node's own actions, declared under api: actions: in its YAML. call_esphome_action does the same over MCP. Give arguments by name. Karakuri checks them against the declared types (bool, int, float, string, and lists of them). A string that is one whole {{ }} keeps the expression's type, so "times": "{{ payload.count }}" sends a number.

{ "connection": "<esphome connection>", "action": "beep", "args": { "times": "{{ payload.count }}" } }

ESPHome Node Action starts a run when a node calls homeassistant.action or fires homeassistant.event, which a node uses to ask Home Assistant to act. The message carries action, data, is_event, connection_id, and node. Set action to take only that name.

Limits

Limit Value
Entities per node 500

The integration has no Bluetooth proxy, voice assistant, camera streams, or firmware updates, and does not include the ESPHome dashboard or compiler.

Frigate NVR

A Frigate NVR connection talks to a Frigate server over Frigate's HTTP API and websocket. Frigate keeps doing the recording, detection, and storage. Karakuri shows its cameras on dashboards, starts flows on its detections, and switches its camera features. Nothing needs configuring on the Frigate side, and no MQTT broker is involved. Karakuri stores no video. It fetches every image, stream, and clip from Frigate when someone asks for it.

Connecting

Add a connection of kind Frigate NVR under Connections:

Field Meaning
URL Frigate's base address, such as http://frigate.local:5000. Port 5000 is Frigate's internal port and needs no login. Port 8971 needs one.
Username, Password A Frigate user, for a URL that needs a login. The password is stored encrypted and never shown again.
Skip TLS verification Accept any certificate, such as Frigate's self-signed one on port 8971.
CA certificate A PEM certificate to trust instead of the system's.

Test reports the version and cameras, such as Frigate 0.18.2, 5 cameras: doorbell, house_back, house_front, kitchen, living_room, or why it failed: login refused, frigate requires a login, or the network error.

The connection stays open on Frigate's websocket. Every 15 seconds it reads Frigate's stats to learn which cameras are receiving frames, and shows a camera at 0 fps as unavailable. A camera added to Frigate's config appears at the next stats read. When Frigate restarts or the network drops, the connection goes to error and reconnects on its own, waiting 1 second and doubling up to a minute. With a login, the connection renews an expired session on the next request.

Cameras on dashboards

The Camera widget takes NVR camera (Frigate) as its source. Pick the connection and a camera, choose a live stream or snapshots every few seconds, and optionally turn on Draw boxes around tracked objects. The widget asks for a live stream at a height that fits it, in steps of 180, 360, 480, 720, and 1080 pixels. All viewers of one camera at one step share a single stream from Frigate, so a wall of panels showing the doorbell costs Frigate one stream. That stream closes 10 seconds after its last viewer leaves.

The NVR Events widget lists recent events of one camera, or of every camera with Every camera, with label, zones, score, time, and a thumbnail. It refreshes when an event starts or ends. Tapping an event plays its clip.

A dashboard viewer reaches exactly the cameras its widgets show. A camera widget grants that one camera's snapshots, stream, events, and event media. An event list on every camera grants every camera of that connection. A viewer asking for another camera gets 403. A camera receiving no frames answers 503, and the widget says so.

Camera switches as devices

Settings, Devices, Add from Frigate (or discover_entities and add_entities with the Frigate connection) lists each camera's detect, record, snapshots, and motion switches. Each switch added becomes a toggle device named after the camera and feature, such as doorbell detect, with object ID doorbell/detect. Turning it on or off sends the change to Frigate. The device's value changes when Frigate reports the new state. With auto import on the connection, every camera's switches are added without picking them; the Device auto import guide under Help covers it.

A switch device is offline while its camera receives no frames and unknown while the Frigate server is unreachable. A camera removed from Frigate's config marks its switches missing until the camera returns.

Turning detection or recording off stops Frigate watching or recording that camera. Put such a switch on a dashboard only where that is wanted.

Nodes

Nodes are in the NVR folder.

NVR Event starts a run on a tracked object. It filters by:

Field Meaning
Cameras Only these cameras. Empty is every camera.
Labels Only these objects, such as person, car, dog.
Sub label contains A recognised face or plate name, case-insensitive.
Zones Only objects in any of these zones. Start and update fire when the object enters one. End fires when it had been in one.
Minimum score Frigate's score from 0 to 1.
Stages start when Frigate begins tracking, end when it stops, update on every change. Frigate sends updates several times a second for a moving object, so most flows want start, end, or a zone filter.

The payload looks like this:

{ "id": "1793910167.825535-bsyysr", "camera": "doorbell", "label": "person",
  "sub_label": null, "zones": ["driveway"], "entered_zones": ["driveway"],
  "score": 0.86, "stage": "start", "start_time": "2026-10-31T15:20:55Z",
  "end_time": null, "has_clip": true, "has_snapshot": true,
  "snapshot": "/api/connections/<id>/nvr/events/<event>/snapshot",
  "thumbnail": "/api/connections/<id>/nvr/events/<event>/thumbnail",
  "clip": "/api/connections/<id>/nvr/events/<event>/clip",
  "connection_id": "<id>" }

zones lists where the object is now, or, at the end, every zone it entered. entered_zones lists the zones it entered with this message. The media paths go through karakuri's relay, and anyone allowed to read the camera can read them.

NVR Review starts a run on Frigate's review items, each an alert or a detection that groups activity worth looking at. It filters by camera, severity (alert, detection, or any), and stage. Its payload is {id, camera, severity, objects, zones, stage, start_time, end_time}.

NVR Image reads a camera's latest frame, scaled to a height and with boxes if asked, or an event's snapshot. After an NVR Event trigger, set Event to {{ payload.id }}. The Bytes output carries the JPEG with meta.content_type, ready for a notification attachment. The Image output is a typed image for an AI agent's Images input. A camera receiving no frames or an unknown event fails through the node's error handling and can be retried.

Triggers fire only while connected. Karakuri does not replay events that happen while Frigate is unreachable.

MCP

  • list_nvr_cameras {connection_id} lists cameras with zones, objects, switches, and whether each receives frames.
  • list_nvr_events {connection_id, cameras?, labels?, zones?, limit?} lists recent events, newest first, with relay paths.
  • get_nvr_snapshot {connection_id, camera, height?, bbox?} returns the latest frame as an image.
  • discover_entities and add_entities add the camera switches as devices.

Limits

Limit Value
Snapshot 5 MB, 10 seconds
Thumbnail 1 MB
Event list 100 events
Clip Relayed for as long as the viewer's request lasts. Frigate builds the clip from its recordings and sends it whole.
Live stream 1 to 10 fps, default 5; one stream from Frigate per camera and height
Stats read Every 15 seconds
Reconnect 1 second, doubling to 60

Karakuri does not record, detect, transcode, or keep video, and does not serve WebRTC or the go2rtc restream. Frigate keeps those.

Device auto import

A connection with auto import on adds every device it reports as a karakuri device, including ones that appear later, and can remove the ones it stops reporting. MQTT, ESPHome, Frigate NVR, Home Assistant, and openHAB connections offer it. Connections without it keep the Add from buttons under Settings, Devices, where devices are picked one at a time.

Turning it on

Edit the connection under Connections and turn on Auto import devices. Saving reconnects the connection, and every device it reports is added straight away.

Field Kinds Meaning
Auto import devices all Add every device the connection reports.
Remove after all Remove an auto-imported device its source has not reported for this long, such as 12h or 7d. Empty never removes. At least 1h.
Discovery prefix MQTT The topic prefix devices publish Home Assistant MQTT discovery under. Default homeassistant.
Zigbee2MQTT base topic MQTT The Zigbee2MQTT instance to import from. Default zigbee2mqtt; off turns Zigbee2MQTT import off.
Only areas, Only domains Home Assistant Comma-separated area IDs, area names, or floors, and entity domains such as light, switch.
Only locations, Only item types openHAB Comma-separated location item names, labels, or floors, and item types. Number matches dimensioned numbers too.

An empty filter matches everything, and an entity must match every filter that is set. A Home Assistant install has hundreds of entities, most of them diagnostics, so set at least one filter there.

Editing the connection shows what auto import has done since the server started: how many devices it imported, which reported devices it skipped and why, and when it last imported or removed one. get_auto_import_status over MCP reports the same.

What each connection imports

Connection Imports
MQTT Every device announcing itself with Home Assistant MQTT discovery under the prefix, and every Zigbee2MQTT device that finished its interview.
ESPHome Every entity of the node. Entities a reflash adds arrive when the node reconnects.
Frigate NVR Every camera's switches. A camera added to Frigate arrives at the next stats read.
Home Assistant Every entity matching the filters, including ones added later.
openHAB Every item matching the filters, including ones added later.

Imported devices are the same devices the Add from buttons make, and work on dashboards and in flows the same way. They are marked auto in the device list. Editing an imported device's name, kind, or scripts is kept; a later discovery change moves only its topics and availability topic.

Home Assistant MQTT discovery

Tasmota, Shelly, ESPHome flashed for MQTT, Zigbee2MQTT, and many other firmwares announce their devices with retained configs on <prefix>/<component>/<object_id>/config. Home Assistant does not need to run. Karakuri reads each config, including abbreviated keys, the ~ base topic, and device-based configs that list several components, and writes the device's state and payload scripts from it.

Component Device kind
switch Toggle
binary_sensor Toggle, read only, labelled by device class (door: Open and Closed, motion: Detected and Clear)
sensor Number with its unit when it has a unit or state class, otherwise text
light Light, default and JSON schemas, with brightness, colour, colour temperature, and effects
cover Cover, with position and tilt
lock Lock
fan Fan, with speed, presets, oscillation, and direction
climate Thermostat, with modes, target or range, current temperature, action, and fan modes
number Number with its bounds, step, and unit
select Dropdown
button Buttons, one button
text Text

Value and command templates are translated to the scripts' JavaScript. Translation covers value and value_json paths, arithmetic, comparisons, and, or, not, inline if and else, and the filters float, int, round, default, lower, upper, string, trim, and abs. A config using {% %} blocks or anything else is skipped, and the import status says why. Other components, such as device triggers, cameras, and alarm panels, are skipped the same way.

A config published again with an empty payload marks its device missing. Zigbee2MQTT publishes discovery for its own devices too; while a Zigbee2MQTT base topic is set, those come from its bridge list instead, once.

Settings, Devices, Add from MQTT discovery (or discover_mqtt_discovery_devices and add_mqtt_discovery_devices) picks discovery devices by hand on a connection without auto import.

Removal

With Remove after set, an auto-imported device is removed, with its stored state, once its source has not reported it for that long. The event log records each removal with the time the device was last reported. Devices added by hand or through a picker are never removed this way.

A report is:

  • On MQTT, a live message: a discovery config, a state message, or an availability message saying online. Retained messages the broker replays on reconnect do not count.
  • On ESPHome, Frigate, Home Assistant, and openHAB, the device's entity being in the connection's list while it is connected.

The broker, Frigate, Home Assistant, or openHAB being unreachable says nothing about a device, so the clock for their devices starts again when the connection reconnects. An ESPHome connection is the node itself, so the time it is unreachable counts.

A device removed for not reporting comes back on its next live report, not from a retained config replayed on reconnect.

Deleting an imported device

Deleting an auto-imported device while its connection still imports it is temporary: the device is added again the next time its source reports it. The delete confirmation says so. To keep a device out, narrow the connection's filters or turn auto import off. Turning auto import off keeps every device it added as an ordinary device.

Notes

  • Deleting a connection leaves its devices, as with picked devices.
  • Several Zigbee2MQTT instances on one broker need one MQTT connection each for auto import, since a connection imports from one base topic.
  • Karakuri does not publish Home Assistant's birth message and never clears retained discovery configs on the broker.
  • New ESPHome nodes are not found automatically; each node still needs its own connection and key.

The state script

An MQTT device is the topics it listens on plus this script, which reads them. The server runs the script once per message, and what it returns is what the device knows. You can add Zigbee2MQTT devices with the script written for you; see Zigbee2MQTT devices. ESPHome nodes need no script. The ESPHome guide covers adding their entities as devices the node reads and commands, and the Frigate guide covers adding a Frigate server's camera switches the same way.

What it receives

topic The concrete topic this message arrived on, not the filter that matched it.
payload The message body as text.
meta.binary true when the body was not text. payload is then base64.
meta.state Everything the device knows so far, for a script that works out the new value from the old one.
meta.retained true when the broker delivered this message from its retained store as the device subscribed. false when it was published while the device was listening.

binary, state, and retained are also plain variables, so you can leave off meta..

What it returns

Return an object holding only the values this message carried. Any key you leave out keeps the value the device already had.

A device that reports its brightness in one message and its colour in the next says nothing about brightness in the second. Replacing the whole state with each message would lose the brightness.

const d = JSON.parse(payload);
return d;

Return nothing to ignore the message. A device watching a wildcard needs this, because not every topic under it is worth reading.

if (topic.endsWith("/lwt")) return null;   // not for me

Returning anything other than an object or nothing fails the message. The device reports the failure instead of storing a value it cannot use.

The keys the control reads

A device names a control kind, and that kind decides which keys a dashboard draws it from. Return those keys and every widget showing the device draws it correctly with nothing else configured. The editor lists the keys your kind uses under this script.

Control Keys
Toggle on
Number, Dropdown, Text, Date and time value
Buttons none; a set of actions has no state behind it
Lock state: locked, unlocked, locking, unlocking, or jammed
Light on, brightness, color, color_temp, effect
Cover state: open, opening, closed, closing, stopped; plus position and tilt
Thermostat mode, target, current, action, and fan_mode
Fan on, percentage, preset, oscillating, direction
Location state: home, not_home, or a zone name; plus latitude, longitude, accuracy in metres, and source
Media player state: off, on, idle, playing, paused, or buffering; plus volume, muted, title, artist, album, art (a URL), position and duration in seconds, position_at, source, and sources

Brightness, cover position, fan percentage, and player volume are percentages from 0 to 100, whatever the device counts in. A Zigbee light that counts to 254 converts here, so every light on a wall panel reads the same way. color is a hex string such as #ff8800, and color_temp is in kelvin. A player's position_at is the RFC 3339 time at which position was measured. Leave it out and the dashboard counts from when the position or the play state last changed, which drifts if the player reports rarely.

const d = JSON.parse(payload);
return {
  on: d.state === "ON",
  brightness: Math.round((d.brightness / 254) * 100),
};

The device keeps any other key you return, and a dashboard can show it on a row of its own. That is how a battery level or link quality sits beside the light it belongs to.

A phone over OwnTracks

OwnTracks publishes to owntracks/<user>/<device>. Make a device of kind Location on that topic with this script. Region enter and leave messages set the zone, and location updates move only the coordinates, so a GPS fix near a region boundary does not flip the zone.

const m = JSON.parse(payload);
if (m._type === "transition") {
  if (m.event === "leave") return { state: "not_home" };
  const zone = String(m.desc || "");
  return { state: zone.toLowerCase() === "home" ? "home" : zone };
}
if (m._type === "location") {
  return { latitude: m.lat, longitude: m.lon, accuracy: m.acc, source: "gps" };
}
return null;

Name the region at home Home in the app. Any other region's name becomes the zone as written, so list it in the device's zones to give it a label. A leave sets not_home even when the phone is still inside another region, so nest regions only if a flow sorts that out. Karakuri sets since itself when state changes and drops a since the script returns.

Availability

Every device is online, offline, or unknown. The device list shows it, dashboards draw a device that is not online as unavailable, and the server keeps it with the device's state across restarts. These decide it:

  • The connection. While the broker is down, every device on it is unknown.
  • An availability topic, usually the firmware's last-will topic. The device follows its online and offline payloads, which default to online and offline. A JSON object whose state is one of them also matches, which is how Zigbee2MQTT sends it. Matching is exact, so Tasmota's LWT needs Online and Offline. Any other payload changes nothing, and the device shows it. After the broker comes back, a device with a topic is unknown until the topic speaks. A retained last-will message does that at once.
  • An expected reporting interval (expect_every_s, at least 60 seconds), for firmware whose last-will never fires. A device that sends nothing for longer is offline until its next message. Any message counts, including ones the script ignores. The server checks every 15 seconds.
  • Otherwise the device is online whenever its connection is up. Removing the topic or the interval from a device drops what it had decided, so a rule the device no longer has cannot leave it offline.

The server refuses a command to an offline device and reports when it went offline. The exception is a device set to send commands while offline, for a sleeping battery device that picks up queued commands when it wakes. Commands to an unknown device go through. The Device Availability trigger starts a run when a device, or any device, changes availability.

Zigbee2MQTT devices

Add from Zigbee2MQTT in the device settings, or the discover_zigbee2mqtt_devices and add_zigbee2mqtt_devices MCP tools, read the device list Zigbee2MQTT retains on <base>/bridge/devices. The base topic is zigbee2mqtt unless yours differs. Reading publishes nothing. The list shows each device's model, power source, the kind it would be added as, and the other values it reports. It leaves out the coordinator, and you cannot add a device that is unsupported, still being interviewed, disabled, or already added. With auto import on the MQTT connection, every Zigbee2MQTT device and every device announcing itself with Home Assistant MQTT discovery is added without picking it; the Device auto import guide under Help covers it.

An added device is an ordinary MQTT device. Its kind comes from the device's main capability: a light, switch, cover, lock, fan, or thermostat first, then a contact, occupancy, leak, or similar sensor, then a button's last action, then the first reading Zigbee2MQTT does not mark as a setting or a diagnostic. The state keeps every other property, such as battery, power, energy, and link quality, under its own name, ready for a row of its own. The generated state script converts brightness to a percentage, mireds to kelvin, and xy colour to hex. The generated payload script publishes to <base>/<ieee address>/set, which Zigbee2MQTT accepts in place of the friendly name. The availability topic is <base>/<friendly name>/availability.

Turn on availability in Zigbee2MQTT's settings for its devices to report offline. Without it, set an expected reporting interval on the device instead.

Added devices follow Zigbee2MQTT. A rename moves the state and availability topics that use the old friendly name and keeps the karakuri name, the scripts, and topics you added. A device whose availability topic you cleared follows a rename made while the server is running. When a device leaves the list, karakuri marks it missing and shows it unavailable until it returns. It never deletes the device. Regenerate on the device, or regenerate_mqtt_device, rebuilds the kind, options, scripts, and topics from Zigbee2MQTT's current description, replacing your edits to them. A device with a second switch or socket gets the first as its control and the second as a field. To command the second one, add another device by hand.

Several topics

topic lets one device read everything it publishes, across as many topics as it uses.

if (topic.endsWith("/brightness")) return { brightness: Number(payload) };
if (topic.endsWith("/color")) return { color: payload };
if (topic.endsWith("/state")) return JSON.parse(payload);
return null;

Declare the topic as home/lamp/# and this one script covers all of them.

Working from the last value

meta.state is what the device holds right now, which a running total or a delta needs.

const { state } = meta;
return { total: (state.total || 0) + Number(payload) };

Binary payloads

A body that is not valid text arrives base64-encoded with meta.binary set. The sandbox has no atob or Buffer, so a device that sends bytes decodes them in the script.

function decodeBase64(text) {
  const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  const bytes = [];
  let bits = 0;
  let value = 0;
  for (const c of text.replace(/=+$/, "")) {
    value = (value << 6) | alphabet.indexOf(c);
    bits += 6;
    if (bits >= 8) {
      bits -= 8;
      bytes.push((value >> bits) & 0xff);
    }
  }
  return bytes;
}

if (meta.binary) {
  return { level: decodeBase64(payload)[0] };
}

Retained messages

A broker keeps the last retained message on a topic and hands it to every new subscriber. That is how a device that reports only changes still has a value after karakuri restarts. A device that reports events should not replay them. A bridge that publishes button presses retained would replay yesterday's press every time karakuri reconnects. Skip those messages with retained.

const d = JSON.parse(payload);
if (retained && d.action) return null;   // a replayed press, not a new one
return d;

Testing it

Test in the editor opens the message the script receives, as JSON you can edit:

{
  "topic": "zigbee2mqtt/lamp",
  "payload": "{\"state\":\"ON\",\"brightness\":128}",
  "retained": false
}

Set "retained" to true to test a message the broker replayed. Add a "state" object to stand in for what the device already holds, which is what meta.state reads. Running shows what the script printed and what it returned, so use console.log to see inside it. The test subscribes to nothing, changes no state, and leaves the running device untouched. A script that ignores the message reports { "action": "ignored" }, so you can tell it chose to ignore the message and did not fail.

When it goes wrong

A script that does not compile, throws, runs out of time, or returns something other than an object fails the message. The device's state does not change, so the last good values stay. The server logs the failure once, not once per message, and sends it to any dashboard watching the device.

Notes

The script is JavaScript, run on the server in the same sandbox a script node uses, with no network and no filesystem. It has 250 ms per message unless the device's State script limit says otherwise (50 to 5000 ms). It runs for every message on every topic the device declares, so keep it to reading, and raise the limit only for a device whose messages are large, such as an energy meter's full document.

A device asks the broker for its State QoS (0, 1, or 2) on its topics and availability topic. A broker may grant less, and the device editor shows when it did.

A device listens from the moment you save it, whether or not a dashboard is open. A device that reports only what changed cannot be caught up later.

The server stores a device's merged state at most every five seconds and restores it when the server starts. Until the device reports again, the restored values are stale. A device read through REST or MCP carries stale and reported_at, the mqtt-device-get node adds meta.stale and meta.reported_at, and dashboards label the value as last known. Restoring is not a report, so mqtt-device-changed does not fire for it, and meta.state in the next script run is the restored state. Changing a device's control kind discards its stored state, since values decoded for one kind may not fit another.

The payload script

This script builds a device's command payload on the device, not on the dashboard. The server runs it once per press. Every row that presses the device sends the same thing, and a viewer who cannot write a script can still press it. The browser sends the interaction, and the server builds the bytes.

What it receives

field The attribute of the device's control kind being set, such as on, brightness, position, or mode. These are the names the state script returns.
value The new value, already checked against the kind. A slider value outside its bounds never reaches the script.
on The direction, for an attribute that has two. Other attributes leave it unset instead of guessing.
previous What the device held before the press.

A control with one value to set sends that value's key in field. A Toggle sends on; a Number, Dropdown, or Text sends value; a Lock sends state. The state script lists the keys for every kind, and the payload script receives the same names.

What it returns

Return an object naming the topic to send on and the payload to send.

return { topic: "home/lamp/set", payload: on ? "ON" : "OFF" };

The script names the topic, not a field on the device, because a device that takes more than one kind of command usually takes them on more than one topic. field tells them apart, so a light can take one attribute at a time.

if (field === "brightness") {
  return { topic: "home/lamp/brightness/set", payload: String(value) };
}
return { topic: "home/lamp/set", payload: { state: on ? "ON" : "OFF" } };

The server sends a string payload as written and encodes anything else as JSON. The second branch above sends {"state":"ON"}.

Brightness, cover position, fan percentage, and player volume arrive as percentages from 0 to 100, whatever the device counts in, so convert them here.

if (field === "brightness") {
  return {
    topic: "zigbee2mqtt/lamp/set",
    payload: { brightness: Math.round((Number(value) / 100) * 254) },
  };
}

Return nothing to send nothing. The press succeeds with no error and no message, and the row shows nothing. An object with a payload but no topic does the same.

// This device has no "off": the remote only sends the on code.
if (!on) return null;
return { topic: "cmnd/obk1F39F2A9/IRSend", payload: "Samsung 0x707 0x99 1" };

QoS and retain

The server publishes a command at the device's Command QoS and retains it when Retain commands is on. Both settings are under Delivery in the device editor. A retained command stays on the broker, so a device that was asleep or rebooting picks it up when it reconnects. A thermostat's set-point is the usual case.

Return qos (0, 1, or 2) or retain (true or false) with the topic to change either for one message.

if (field === "target") return { topic: "hvac/set/target", payload: String(value), retain: true };
return { topic: "hvac/set/" + field, payload: String(value), retain: false };

Any other value for either fails the press. A retained command stays until something replaces it. To clear one, return an empty payload retained on the same topic.

return { topic: "hvac/set/target", payload: "", retain: true };

Buttons

A Buttons device declares a list of actions, each with its own label and value, and the script reads the pressed action's value from value. One action draws as one button and several draw as a row, which is how Up, Stop, and Down share one dashboard row. An infrared blaster needs only the actions and one line of script.

On Samsung 0x707 0x99 1
Off Samsung 0x707 0x98 1
return { topic: "cmnd/obk1F39F2A9/IRSend", payload: value };

The device keeps no state. Infrared is one-way, so nothing knows whether the television is on.

Media players

A Media player device sets field to one of these:

  • state: playing, paused, idle for stop, and on or off when the player has power control.
  • volume, from 0 to 100.
  • muted.
  • source.
  • position, in seconds.
  • command, with next or previous.

Only the features turned on in the device's options arrive. This script drives a Squeezebox-style bridge with one topic per action.

const base = "squeeze/kitchen/set/";
if (field === "state") return { topic: base + {playing: "play", paused: "pause", idle: "stop"}[value], payload: "" };
return { topic: base + field, payload: String(value) };

command is a one-off press. The state script never sees it come back and should not return it.

Testing it

Test in the editor opens the change the script receives, as JSON you can edit:

{
  "field": "on",
  "value": true,
  "on": true,
  "previous": false
}

Running shows what the script printed and what it would send, so use console.log to see inside it. The test publishes nothing. A script that sends nothing reports { "action": "none" }, so you can tell it chose to send nothing and did not fail.

When it goes wrong

A script that does not compile, throws, runs out of time, or returns something that is not {topic, payload} fails the press with the script's error message. The server publishes nothing. Returning nothing is not a failure; see What it returns.

Notes

The script is JavaScript, run on the server in the same sandbox a script node uses, with no network and no filesystem. It has 2 seconds per press unless the device's Payload script limit says otherwise (100 to 10000 ms). A press waits on the script.

Leave this script empty for a device that only reports. Its dashboard rows then draw a reading instead of a control, and the server refuses commands to it instead of publishing them.

Notification services

Settings, Notifications holds provider credentials and the destinations flows may send to. Add a service, fill in its credential fields, and add at least one endpoint. An endpoint has a stable ID, a label, and a provider target, and the form describes the target's format. A flow picks the service and one endpoint ID.

These services can deliver: Amazon SES, Amazon SNS, Bark, DingTalk, Discord, Firebase Cloud Messaging, Google Chat, HTTP webhook, Lark custom app, Lark webhook, LINE Messaging API, SMTP mail, Mailgun, Mailtrap, Matrix, Mattermost, Microsoft Teams, PagerDuty, Plivo SMS, Pushbullet, Pushbullet SMS, Pushover, Reddit, Rocket.Chat, SendGrid, Slack, Syslog, Telegram, TextMagic, Twilio SMS, Twitter / X, Viber, Web Push, and WeChat.

LINE Notify is listed as unavailable because LINE ended the service on March 31, 2025. Use LINE Messaging API instead. WhatsApp is listed as unavailable because it cannot deliver messages. Neither can be saved.

Karakuri dashboard

The catalog also lists Karakuri dashboard. Its endpoint target is a dashboard ID or slug. A send raises an alert on every open viewer of that dashboard, the same alert a Dashboard Command node shows, with the subject as the alert title and the message as its body. Its settings are:

  • style, toast by default, or fullscreen.
  • level, info by default, success, warning, or error.
  • duration in seconds, 0 to 86400, default 10. 0 keeps the alert until a command clears it.
  • speak, true to have open viewers read the alert aloud.

A send to a deleted dashboard fails with an error naming it. Anyone who may configure notification services can address any dashboard this way, the same reach a flow has, and everyone who may view the dashboard sees the alert text. See dashboard security.

Settings and secrets

A service is a connection of kind notification. The server's encryption key encrypts its credentials. The connection read, write, and invoke permissions govern discovery, configuration, and direct sends.

Reads mask secret credential fields and every endpoint target. Saving the mask keeps the stored value. Target masks follow endpoint IDs when rows are reordered. Changing an ID means entering its target again and updating the flows that reference it. Removing an endpoint revokes its old ID. The service type is fixed after creation, so create another service to use a different provider.

The connection APIs accept configuration of this shape:

{
  "service": "http",
  "credentials": {
    "method": "POST",
    "headers_json": "{\"Authorization\":\"Bearer token\"}"
  },
  "endpoints": [
    {"id": "alerts", "label": "Home alerts", "target": "https://example.com/notify"}
  ]
}
Limit Value
Endpoints 1 to 100 per service
Endpoint ID 1 to 64 letters, digits, underscores, or hyphens, unique within the service
Label 120 bytes
Target 32 KiB

Google services take inline service account JSON, not credential filenames or ambient credentials. SMTP uses host:port, uses STARTTLS when the server offers it, and takes one configured email recipient per endpoint. A Syslog endpoint gives an explicit network and address in JSON.

Send notification node

The notification node is in the Network folder. Pick a service and an allowed endpoint, and give an optional subject and a required message. Subject and message take {{ }} expressions and the editor's ordinary parameter-port bindings. An endpoint binding must still resolve to a configured ID. A raw URL or recipient cannot stand in for one.

For example, use subject Room {{ payload.room }} and message Temperature {{ payload.temperature }}. A successful send passes the input message to out. A failure goes to the ordinary error port. A provider accepting a message does not prove that a person received it.

Limit Value
Subject 4 KiB, no line breaks or NUL
Message 64 KiB
Timeout 1 to 120 whole seconds, default 30
Concurrent sends 4

Notification failures never retry automatically, even when a graph asks for retries. Karakuri replaces provider errors with public errors that contain no targets, credentials, response bodies, or message content.

A send reaches only the selected endpoint. Providers that send over HTTP do not follow redirects. Some providers cannot be interrupted once a send starts, so a timeout or failure can leave delivery uncertain. Do not treat a timeout as proof that no message was sent. A timed-out send keeps its place among the four until the provider call ends.

API and MCP

  • GET /api/notification_services returns the catalog and field metadata.
  • GET /api/connections/{id}/notifications/endpoints returns endpoint IDs and labels.
  • POST /api/connections/{id}/notifications/send takes endpoint, subject, message, and an optional integer timeout.

The MCP tools are list_notification_services, list_notification_endpoints, and send_notification. Create and edit services with the connection tools list_connections, save_connection, and delete_connection. Discovery needs api:connections:read, and direct sends need api:connections:invoke. A flow's Send notification node needs neither. Whoever may edit and deploy the flow decides what it sends, as with any node that uses a connection.

Time-series connections and history

Karakuri keeps no history of its own. It reads and writes the time-series databases you already run, and reads Home Assistant's recorder. Dashboard charts that draw these queries are covered in Charts.

Connections

Add them under Settings, Connections.

Kind Reads Writes Notes
prometheus PromQL Remote write, when Write enabled is on Also Thanos, Mimir, Cortex, and VictoriaMetrics. Prometheus needs --web.enable-remote-write-receiver. Extra headers, such as X-Scope-OrgID, apply to every request.
influxdb InfluxQL on 1, 2, and 3; Flux on 2; SQL on 3 Line protocol InfluxQL on 2 uses the bucket's DBRP mapping. VictoriaMetrics, QuestDB, and Telegraf accept its writes as version 1.
postgres SQL, in a read-only transaction Inserts into one table, karakuri_history by default The first write creates the table, as a TimescaleDB hypertable when the extension is installed.
homeassistant Recorder history and long-term statistics None The existing Home Assistant connection. History covers up to 31 days and 50 entities per query.
energy Energy rollups, language energy None Built in, with no settings. It reads the hourly usage, cost, and solar figures energy tracking records. The energy guide lists its targets, measures, and periods.

Every query takes a range (now-6h, now-1d/d, RFC 3339, or Unix milliseconds) and a maximum number of data points, which sets $__interval. Query text may use these macros:

Macro Languages Expands to
$__from, $__to All Range ends in Unix milliseconds
$__interval, $__interval_ms All The step: range / max data points, rounded
$__range, $__range_s, $__range_ms All The range's length
$__rate_interval All max(interval + scrape, 4 × scrape), where the scrape interval is a Prometheus setting, 15s by default
$__timeFilter(col), $__timeGroup(col, 5m), $__timeGroupAlias, $__timeFrom(), $__timeTo(), $__unixEpochFilter(col) SQL PostgreSQL expressions
$timeFilter InfluxQL time >= …ms and time <= …ms
v.timeRangeStart, v.timeRangeStop, v.windowPeriod Flux RFC 3339 times and a duration

A result is a list of series with typed fields, with times in Unix milliseconds. Karakuri cuts a result off at 100,000 values and marks it truncated. A query times out after the connection's timeout, 30 seconds by default.

Flow nodes

Time series query runs one query and outputs {series, value, truncated, interval_ms}. With a reduction (last, first, min, max, mean, sum, count, or delta), value is the first series reduced to one number. An unreachable database fails the node retryably. A refused query does not retry.

Time series write writes one point (metric, labels, value, and an optional timestamp) or a payload's points array. By default it succeeds once the points are queued. With Wait for delivery it succeeds only when the database accepts them, and otherwise fails retryably without buffering.

Scripts get both as functions through the script SDK.

History forwarding

Settings, History forwarding records values without a flow. A forward picks its sources and one or more writable destinations. Sources are:

  • specific controls or all controls;
  • specific MQTT devices or all devices;
  • the entities of one Home Assistant connection that match the include patterns and none of the exclude patterns (* matches any run of characters), with their state and the listed or all numeric attributes.

The control and MQTT device dialogs have a Record history shortcut that saves a forward for that one source.

Points are named so a dashboard query can find them:

Source Metric Labels
Control karakuri_control id, name, attribute
MQTT device karakuri_mqtt_device id, name, attribute
Home Assistant karakuri_ha_entity entity_id, domain, friendly_name, connection, attribute (state for the state), unit

A forward may rename the metric and add its own labels. Each attribute of a composite control or a device message is its own series. Numbers are stored as values, booleans as 1 and 0, and datetimes as Unix seconds, or as seconds since midnight for a time-only control. InfluxDB and PostgreSQL store text and select values as a text state. Prometheus stores numbers only, so a select becomes one series per option labelled state, 1 for the current option and 0 for the others, and plain text is skipped. Home Assistant unavailable and unknown states are not recorded.

Prometheus forgets a series that has no sample for five minutes, so karakuri re-sends each series' last value to Prometheus destinations every 60 seconds, the connection's Heartbeat. InfluxDB and PostgreSQL get writes on change unless a heartbeat is set. A destination that starts running after the forwards load, or gets a heartbeat later, receives every selected series' current value within 30 seconds.

Buffering

Forwards and write nodes share one queue per writable connection, sent in batches every second. While the database is unreachable, karakuri keeps the points on disk under history-spool/<connection> in the data directory and retries with backoff from 1 to 60 seconds. Buffered points survive a restart and are written oldest first. The buffer holds 64 MiB by default. Past that, karakuri discards the oldest points and counts them.

Karakuri discards a batch the database refuses as malformed and counts it as rejected. A refusal caused by the destination's state stays buffered and retries: an HTTP 401, 403, or 404 on a write, from a revoked token, a deleted bucket or database, or a disabled remote-write receiver, or a PostgreSQL role that lost its INSERT grant. A disabled connection, or one with writing off, receives nothing and buffers nothing. Deleting a connection deletes its buffer.

Delivery status shows buffered points and bytes, written, discarded, rejected, and skipped counts, and the last error and success. It appears on the connection, on the forwarding page, from MCP get_history_status, and in the karakuri_history_* server metrics. Delivery is at least once. PostgreSQL ignores duplicate rows, and InfluxDB and Prometheus overwrite identical samples.

REST and MCP

Purpose REST MCP
Query POST /api/connections/{id}/timeseries/query query_timeseries
Metadata GET /api/connections/{id}/timeseries/metadata?kind= list_timeseries_metadata
Forwards GET/POST /api/history/forwards, PUT/DELETE /api/history/forwards/{id} list_history_forwards, save_history_forward, delete_history_forward
Writer status GET /api/history/status get_history_status
Chart data POST /api/dashboards/{id}/widgets/{widgetId}/chart get_chart_data

Queries and lookups need connection read. Forwards need connection write.

Energy

Karakuri turns energy and power readings from plugs, meters, and Home Assistant sensors into usage per hour, prices each hour under the house's tariff, and shows the totals on charts and in flows. It keeps its own hourly figures, so it needs no time-series database. When a source's history is forwarded to one, or the source is a Home Assistant entity, karakuri fills the hours the server missed from that history.

Manage energy under Settings, Energy, or through the REST routes and MCP tools listed at the end.

Sources

A source reads one value:

Field Meaning
Reads A device (an attribute of its state, value by default), a control, or a Home Assistant entity (its state, or an attribute).
Measures Energy is a meter that counts up, in Wh, kWh, or MWh. Power is W, kW, or MW. Units match without regard to case, except that milliwatt units (mW, mWh) are refused instead of read as megawatts.
Role Consumer (a plug, circuit, or appliance), Whole house, Grid import, Grid export, or Solar production. Only one source can be the whole house.
Gap limit The longest silence bridged, 60 seconds to 7 days. 15 minutes for power and 6 hours for energy unless set.
Plausible maximum The most the source could draw, 25 kW unless set.

Suggest sources lists devices, number controls, and Home Assistant sensors whose unit is an energy or power unit, and Zigbee2MQTT-style devices with energy or power in their state.

How readings become usage

A meter's usage is the difference between readings, spread by time over the hours between them:

  • A drop of less than 1% of the reading, or less than 0.01 kWh, is noise and adds nothing.
  • A larger drop is a reset, such as a plug losing power. Karakuri counts the new reading from zero, and the source's state shows reset.
  • A rise faster than the plausible maximum is rejected as a glitch, and the source shows rejected. After three rejected readings in a row, the meter starts again from the new value, for a meter that was replaced.
  • A silence longer than the gap limit is filled from the source's history when that history can be read back. Karakuri fills the silent hours once they close, including the hours the silence starts and ends in. Otherwise the usage across the silence lands in the hour of the next reading, marked carried, since the meter kept counting.

A power sensor's usage is the average of each pair of readings times the time between them. A silence longer than the gap limit adds nothing. A reading of unavailable, or anything that is not a number, adds nothing and shows unavailable.

Karakuri writes hours and each meter's last reading every 30 seconds, so a restart in the middle of an hour loses no usage from a meter. It ignores readings stamped in the future or more than a day old.

The house

The house total is the whole-house source when there is one. Otherwise it is grid import plus production minus export, when those exist, and otherwise the sum of consumers. Untracked is the house total minus consumers, never below zero. Solar used at home is production minus export, and the solar share is that divided by the house total.

Groups

A group, such as a room or circuit, sums its sources. A change of members applies from that moment, and past hours keep the grouping they had.

Tariffs

A tariff has a currency, a start date, and a rate per kWh. The rate is one flat rate, time-of-use periods, or a number control a flow keeps current. Periods name ISO weekdays (Monday is 1) and local start and end times, and together they must cover every hour of the week once. An end of 00:00 means midnight, and a period crossing midnight is split in two. A tariff can add a fixed charge per day and a credit per exported kWh. Negative rates are allowed.

Karakuri prices each recorded hour at the rate in force then and stores the rate with the hour. Usage a meter counted while the server was down is spread over those hours, and each is priced the same way, except under a rate control, whose average was not recorded then. Saving, changing, or deleting a tariff reprices the recorded hours it covers and leaves usage alone.

Under a rate control, each hour is priced at the control's average over the hour. Future prices are unknown, so the cheapest window cannot be found.

A source's or group's cost is its usage times the rate. The house's cost is grid import times the rate when there is an import source, and otherwise house usage times the rate. The house's total cost subtracts the export credit and adds the daily charge.

Time

Hours, days, and tariff periods follow the energy time zone, which is the server's unless set. Weeks start on the configured day. A day with a daylight saving change has 23 or 25 hours.

Charts

The chart widget reads energy from the built-in Energy connection with the energy language:

{"refId":"A","connectionId":"energy","language":"energy",
 "energy":{"targets":["house","group:<id>","source:<id>","untracked","solar"],
           "measure":"usage","period":"day"},"format":"time_series"}

measure is usage, cost, total_cost, export_credit, daily_charge, import, export, production, self_consumption, or solar_share. period is hour, day, week, month, or auto, which follows the chart's range.

A range rounded to a calendar unit, such as now/d, is rounded in the energy time zone, and now/w starts on the configured first day of the week. A chart that reads only energy draws its axis over that range. Each target is one series. The table format gives one row per target with its total, for pie and bar charts. Units are kwatth, the currency, or percent. A placed chart grants its viewers its own queries, so a shared energy dashboard needs no permission on the sources.

Create energy dashboard makes an ordinary dashboard of charts:

  • today, this week, and this month, with usage and total cost;
  • 30 days of daily use;
  • a breakdown by group, or by source when there are no groups, with untracked use;
  • a table of sources;
  • production, import, export, and self-consumption by hour, when there is solar.

Flows

Nodes are in the Energy folder.

Energy Usage reads a target's kWh and cost over today, yesterday, this week, this month, the last hours, or a range. For the house, the cost includes charges and credit. A power source's current draw is power_w. With Compare with usual, the node adds usual_kwh, the average of the same span on the previous four matching weekdays, and ratio, the number an unusual-use alert compares.

Energy Price reads the price and period now or at a given time, with ends_at when the price next changes. It can instead find the cheapest window of a given length within a range, returning {start, end, average_rate, currency}. For a load that must finish by 07:00, ask for a window between now and 07:00.

Energy Price Period starts a run at each price boundary with {period, rate, currency, starts_at, ends_at, previous_period}. Boundaries passed while the server was down are caught up to a week back, following the node's missed-deadline setting, and none fire twice.

Filling and importing history

Home Assistant entities fill from Home Assistant's hourly statistics, using the change of an energy meter or the mean of a power sensor. Home Assistant keeps no statistics for attributes, so a source that reads an attribute has no history and carries its usage across a silence. Home Assistant's statistics hours start on the UTC hour, so in a time zone offset by 30 or 45 minutes, each is shared between the two local hours it overlaps.

Controls and devices fill by replaying, through the same meter rules, the series their history forward writes to a Prometheus or InfluxDB connection. Filling never overwrites hours recorded live, except the two hours a filled silence starts and ends in, which were heard for only part of the hour.

Import history on a source reads up to 400 days the same way, a day at a time in the background, and shows its progress on the source.

REST and MCP

Reading needs api:connections:read, changing needs api:connections:write, and the dashboard preset needs api:dashboards:write.

REST MCP
GET, POST /api/energy/sources, PUT, DELETE /api/energy/sources/{id} list_energy_sources, save_energy_source, delete_energy_source
GET /api/energy/candidates list_energy_candidates
POST /api/energy/sources/{id}/import import_energy_history
GET, POST /api/energy/groups, PUT, DELETE /api/energy/groups/{id} list_energy_groups, save_energy_group, delete_energy_group
GET, POST /api/energy/tariffs, PUT, DELETE /api/energy/tariffs/{id} list_energy_tariffs, save_energy_tariff, delete_energy_tariff
GET, PUT /api/energy/settings
GET /api/energy/rollups?target=&measures=&from=&to=&period= get_energy_rollups
GET /api/energy/price?at=, GET /api/energy/price/cheapest?hours=&from=&to= get_energy_price, find_cheapest_energy_window
POST /api/energy/preset create_energy_dashboard
POST /api/connections/energy/timeseries/query query_timeseries with connection_id energy

A deleted source keeps its hours for 30 days. Karakuri then removes them.

Limits

Limit Value
Sources 200
Groups 50
Writes Every 30 seconds
History import 400 days
Cheapest window 15 minutes to 48 hours, within 7 days
Rollup 10,000 periods

Energy tracking covers electricity only, not gas or water. Karakuri does not fetch supplier price feeds. A flow can feed a dynamic price through a rate control.

Server configuration

The server reads config.yaml from the first of these that exists:

  1. etc/config.yaml beside the karakuri binary
  2. ~/.config/karakuri/config.yaml
  3. /etc/karakuri/config.yaml

The installer and the Docker image write one with fresh secrets the first time. Restart the server after editing it.

Any key can also come from an environment variable named KARAKURI_ plus the section and key in capitals, joined by underscores. KARAKURI_SERVER_PORT=9090 sets server.port. An environment variable wins over the file.

Writing a configuration by hand

karakuri config gen --env=prod prints a complete configuration with the defaults below. Its two secrets, security.jwt_secret and security.encryption_key, are placeholders that every generated file shares, so replace both before the server is reachable by anyone else:

openssl rand -hex 32   # run once for each secret

Set encryption_key before saving any connection. Connection credentials are encrypted with it, so changing it later makes them unreadable. karakuri config rotate-key moves stored credentials to a new key.

Keys

Section Key Default Description
server host 0.0.0.0 Address the web interface and API listen on.
server port 8080 Port the web interface and API listen on.
server base_url http://localhost:8080 Address people and dashboard renders use to reach the server.
server read_timeout / write_timeout 30 HTTP timeouts (seconds).
server shutdown_timeout 15 How long a shutdown waits for requests to finish (seconds).
server cors_origins empty Other origins allowed to call the API from a browser, separated by commas.
server trust_proxy false Believe forwarding headers from the peers in trusted_proxies.
server trusted_proxies 127.0.0.1/32,::1/128 Reverse proxy addresses or CIDRs, separated by commas.
database type sqlite sqlite, postgres, or mysql.
database path data directory/karakuri.db SQLite database file.
database dsn unset Connection string for PostgreSQL or MySQL.
database max_open_conns / max_idle_conns 25 / 5 Database connection pool.
database conn_max_lifetime 300 How long one database connection is reused (seconds).
security jwt_secret generated Signs sign-in tokens.
security jwt_expiry 3600 How long a sign-in token lasts (seconds).
security refresh_expiry 86400 How long a session stays signed in without activity (seconds).
security bcrypt_cost 12 Password hashing cost.
security encryption_key generated Encrypts connection credentials.
security max_upload_size 1073741824 Largest file one dashboard widget upload may be (bytes).
logging level info debug, info, warn, or error.
logging format json json, or console for human-readable output.
engine max_parallel_nodes 4 Nodes one run executes at once. A node that is waiting gives its slot up.
engine max_concurrent_runs_per_flow 10 Runs one flow may have at once; 0 is unlimited.
engine default_run_timeout 300 Time limit for one run, not counting time spent waiting (seconds); 0 is none.
script network full What script HTTP requests may reach: full, bogons (public addresses only), or none.
script timeout 30 Time limit for one script (seconds).
script max_output 262144 Console output kept from one script (bytes).
script max_http_requests 20 HTTP requests one script may make.
script max_http_response 8388608 Bytes read from one HTTP response.
script memory_limit_mb 256 Memory one script may use, where the language allows a limit.
script python_enabled true Offer Python in the script node.
script python_wasm unset Path to the CPython WebAssembly module, when it is not in the runtimes directory.
storage roots data directory/files Directories the server's file nodes may use. An empty list allows none; ["/"] allows any.
storage max_read_size 8388608 Largest file one Read File node reads (bytes).
location latitude / longitude 0 / 0 Default position for sunrise and sunset schedules. At 0 and 0, each such node needs its own.
render workers 2 Dashboard renders that run at once.
render timeout 30 Time limit for one render (seconds).
render max_queue_size workers × 4 Renders that may wait; more are refused.
render browser_path unset Chrome or Chromium binary, when it is not in the usual places.
render storage_path data directory/renders Where rendered images are kept.
render retain 3600 How long a one-off render stays on disk (seconds). A scheduled render stays until the next one replaces it.
theme default catppuccin-mocha Dashboard theme for users and dashboards that pick none.
agents listen 0.0.0.0:9443 Address remote agents connect to. Empty turns agents off.
agents enroll_ttl 900 How long a join token stays valid (seconds).
agents cert_ttl 7776000 How long an agent's certificate lasts before it renews (seconds).
mcp enabled true Serve the Model Context Protocol at /mcp.
mcp assistant_trace_dir unset Directory for editor chat traces. They hold prompts and tool data, so leave it unset unless you are debugging.
update enabled true in new production configs, otherwise false Install newer releases automatically; see below.
update prerelease false Also update to releases marked as pre-releases.

Dashboard renders open the dashboard at server.base_url, so set it to an address the server itself can reach, not only one that works from your browser.

Automatic updates

With update.enabled, a server running as a service checks GitHub releases once a day. When a newer release exists, it downloads the archive for its platform, checks it against the release's checksums, makes sure the new binary runs, and replaces its binary together with the plugins, themes, and Python runtime beside it. It then shuts down and its service manager starts the new version. If that version fails to start three times, the previous files are put back and the old version starts again. The event log records each update and each failure.

An install under your home directory, or an unpacked archive, updates itself. A system install made with sudo ./install.sh belongs to root while its service runs as the karakuri account, which cannot write those files. For that install, sudo karakuri service install also adds karakuri-update.timer, which runs karakuri update --scheduled as root once a day. It does nothing while update.enabled is off, so turning updates on or off needs only the configuration change. When it installs a release, it restarts the service and watches it for 30 seconds. A version that does not start, or stops in that time, gets the previous files back and the service is restarted on them. journalctl -u karakuri-update shows what each run did. The timer needs systemd. On OpenRC or SysV, schedule karakuri update --scheduled from root's crontab instead.

karakuri update checks and installs now, and karakuri update --check only reports whether a newer release exists. Run it as the account that owns the install: yourself for a user install, or sudo karakuri update for a system install. With the service installed, it restarts the service on the new version the same way the timer does. A development build and the Docker image never update themselves.

Backup

A backup is one file holding everything an installation needs to come back on the same machine or a new one. It contains the encryption key, and with the key every stored credential and the agent CA, so the file is encrypted under a passphrase. Backups run while the server works. A restore runs from the command line with the server stopped.

Manage backups under Settings, Backup, with the karakuri backup commands, or through the REST routes and MCP tools listed at the end.

What an archive holds

Part Notes
The database Every table from one moment, including deleted rows that are kept.
Encryption key and JWT secret security.encryption_key and security.jwt_secret from the config file. Nothing else from the config is carried.
Agent server identity agents/server.pem and server-key.pem. The agent CA itself is in the database.
Widget uploads uploads/.
Flow SQLite databases sql/, each a whole database even when a flow was writing it.
Flow files Each storage.roots entry under the data directory, by default files/.
Undelivered history history-spool/, the points history forwarding has not yet written.

Every archive's manifest lists what is left out: rendered dashboard images, assistant traces, logs, the script runtime cache, flow file roots outside the data directory, and external plugin executables. Plugins are built for one platform, so the archive lists them by name and version, and a restore names the ones the new machine lacks. Their settings are in the database.

When a part is a symbolic link to a directory, such as uploads/ kept on another disk, the backup follows it and archives its files. Links inside a part are left out. A restore moves the link aside and puts a directory in its place.

Each part is copied consistently, but the database and the flow SQLite databases are not copied at the same instant. A flow that writes both in one run can restore with one write and not the other.

The file

Archives are named karakuri-<host>-<YYYYMMDDTHHMMSSZ>.tar.zst.age. Each is a tar stream, compressed with zstd and encrypted with age under a passphrase. Karakuri refuses an archive with a changed byte, a cut-off file, or a wrong passphrase. If karakuri itself will not start, the standard tools open one:

age -d karakuri-lab-20261106T030000Z.tar.zst.age | zstd -d | tar -x

manifest.json, the last entry, records the version, the time, the database engine, row counts, each part's size and SHA-256, the plugins, and what was left out.

A passphrase has at least 12 characters. A lost passphrase cannot be recovered, and without it the archive is unreadable. Keep a copy somewhere other than the server.

Command line

Every command reads the passphrase from --passphrase-file, the KARAKURI_BACKUP_PASSPHRASE variable, or a prompt. It never takes the passphrase as an argument, because other users can read arguments.

Command What it does
karakuri backup create [--output DIR] Writes and verifies an archive, with the server running or not. The directory defaults to the schedule's.
karakuri backup verify ARCHIVE Reads the whole archive and prints its manifest, or the part that does not match.
karakuri backup list [--dir DIR] Lists archives with size, time, and verification.
karakuri backup restore ARCHIVE [--replace] Restores into this installation.

Restoring

  1. Stop the server. A restore refuses while a server holds <data>/karakuri.lock.
  2. On a new machine, install karakuri and its config first. The restore keeps the target's addresses, ports, paths, and database settings.
  3. Run karakuri backup restore ARCHIVE. The restore refuses an installation that already has users unless --replace is given. With --replace, it first backs up the current state beside the archive under the same passphrase.
  4. Start the server. It upgrades an older archive's database as any upgrade does, and enrolled agents reconnect without enrolling again.

The restore unpacks and checks the whole archive before changing anything, and a failure at any later step puts everything back. Nothing is deleted. The replaced database, each replaced directory, and the config file stay beside the originals with a .pre-restore-<stamp> suffix. The kept config holds the replaced encryption key, the only key its data opens with.

Karakuri refuses an archive from a newer release, so upgrade first. Development builds have no order, so their archives restore with a warning.

Moving between database engines

The archive stores the database as rows, not as a database file, so an archive made on SQLite restores into PostgreSQL or MySQL and back. Point the target's config at the new database and restore. PostgreSQL loads in one transaction. MySQL commits schema changes as it goes, so on a failed load karakuri drops it and reloads the safety backup.

The local lock does not cover a PostgreSQL or MySQL server that karakuri uses on another machine. Stop that server too.

Schedule

Setting Meaning
Schedule Cron in the server's time zone, 0 3 * * * unless set.
Directory Absolute path, <data>/backups unless set. A directory on another disk survives this one failing.
Keep Archives kept, 1 to 365, 14 unless set.
Passphrase Stored sealed with the encryption key, so a scheduled backup needs nobody present. Required to turn the schedule on.

Saving creates the directory and writes a test file there, so an unwritable directory is refused at once. After each scheduled backup verifies, karakuri deletes the oldest of this installation's archives beyond the count. It leaves other installations' archives and other files in the directory alone, and a failed backup never removes one.

A server that was stopped at a scheduled time runs one backup two minutes after it starts. A server stopped during a backup marks that run failed and removes its partial file when it starts.

Backups run one at a time, and a second waits. Karakuri writes an archive as a hidden .partial file, renames it when complete, then reads it back and verifies it. An archive that does not verify is removed and the run fails.

Flows

Back up (backup-create) writes an archive with the stored passphrase, in the schedule's directory or its own, waits for it, and outputs archive, path, size, duration_ms, counts, and verified. Without a stored passphrase it fails without retrying. A disk error may succeed on retry. Retention applies only to scheduled backups.

Backup finished (backup-result) starts a run when a backup from any trigger fails (the default), succeeds, or either. The payload has status, trigger, archive, size, error, started_at, and finished_at. Pair it with a notification node to hear about a failed night.

Permissions, REST, and MCP

Permission Allows
api:backups:read Listing archives and runs, and reading the schedule.
api:backups:write Creating, verifying, and deleting archives, and changing the schedule.
api:backups:download Downloading an archive. It is separate because an archive and its passphrase hand over every credential. Each download is logged with its user.

Administrators hold all three.

Route Permission
GET /api/backups, GET /api/backups/runs, GET /api/backups/schedule read
POST /api/backups, POST /api/backups/{name}/verify, DELETE /api/backups/{name}, PUT /api/backups/schedule write
GET /api/backups/{name}/download download

Routes take archive names only, and anything else is not found. MCP has list_backups, get_backup_schedule, create_backup, verify_backup, delete_backup, and save_backup_schedule. Restore has no remote interface.

Event log

The event log records what happened in the house and in karakuri, what it happened to, and who or what did it: a person on a dashboard, an API key, a flow and its run, an agent, or karakuri itself. Read it under Activity in the navigation, on dashboards with the activity widget, in flows with the Log Event and Event Logged nodes, or through the REST routes and MCP tools listed at the end.

What is recorded

Category Entries
Device A control's value changing, with old and new values, and every press of a buttons control, including the same button again; a command sent to a device; a device going offline and coming back; state changes of the Home Assistant entities listed in the settings.
Connection A connection failing, with its error, connecting, reconnecting after a failure, and being stopped.
Flow A run failing, with its error and a link to the run; a flow deployed, enabled, or disabled.
Agent An agent enrolling, connecting, and disconnecting.
Security Sign-ins, failed sign-ins, sign-ins refused after repeated failures, sign-outs, revoked sessions, a refresh token used twice; users, passwords, groups, memberships, roles, permissions, role assignments, and API keys created, changed, or deleted; connections created, changed, or deleted; agents edited, deleted, or revoked, enrollment tokens, CA rotations; backups downloaded and restored; the encryption key rotated.
System Backups finishing or failing, the server starting and stopping.
Custom Entries flows add with Log Event.

The log leaves out sensor readings, so a temperature device reporting every few seconds adds nothing. It also leaves out device attributes other than availability, Home Assistant entities not listed in the settings, and controls excluded in the settings. Exclude a control that mirrors a busy sensor to keep it out of the log.

Secrets never appear. A failed sign-in records the username as typed, never the password. A change lists the names of the fields that changed, never their values, and a changed connection secret appears only as credentials.

Who did it

Every entry names its actor:

Actor Shown as
A signed-in user Their username, with on a dashboard for a dashboard and through MCP for MCP.
An API key The key's name with its owner, such as kitchen tablet (admin).
A flow The flow's name, with a link to the run.
An agent The agent's name.
karakuri Schedules, recovery, connection status, and the command line, named with the operating system user for config rotate-key and backup restore.
Someone An address that has not signed in, such as one making a failed sign-in.

Repeats

When the same thing happens to the same subject, by the same actor from the same address, within a minute, it folds into the subject's latest entry as a count, shown as ×12. A connection retrying every few seconds is one entry with a count. A change in between is never hidden. A light turned on, off, and on again is three entries, and the same change made by someone else, or a failed sign-in from another address, gets its own entry.

Activity

The page lists entries newest first. Filter by category, level, time range, subject (pick a subject's name in any entry), or text in the message, the subject, or the actor. New entries appear while the page is open, and older entries load a page at a time.

Only holders of api:events:audit see security entries.

Settings

Holders of api:events:write change these under Settings, Event log:

Setting Meaning
Keep entries for Days per category, 1 to 3650. 30 by default, and 365 for security.
Most entries kept 10,000 to 10,000,000, one million by default. Past it the oldest entries go first, never security entries, which only their own age removes.
Controls not logged Control IDs, one per line.
Home Assistant entities logged connection-id entity_id per line, at most 500. Each is logged when its state changes.

Karakuri removes old entries when the server starts and every six hours.

Dashboards

The Activity widget lists recent entries for the controls, devices, and Home Assistant entities its rows name, with who did it, and updates live. Each row is a display-only binding, so a viewer of a shared or public dashboard reads those subjects' entries and nothing else, and never security entries.

Flows

Log event (log-event) adds a custom entry. It takes a message, which interpolates message properties such as {{payload.room}}, a level, an optional control or device the entry is about, and optionally the payload as details. The entry names the flow and run, and the message passes through.

Event logged (event-logged) starts a run when a new matching entry is logged. It filters by categories, levels, a control or device, and text in the message. Folded repeats do not start another run. Entries the flow itself caused never start it, so a flow that writes a control and listens for control entries does not start itself. Without categories it matches everything except security, and naming security needs the flow's owner to hold api:events:audit. The payload is the entry, with category, level, message, subject_kind, subject_id, subject_name, actor_kind, actor_name, count, details, and at.

To hear about failed sign-ins, pair Event Logged on category security and level warning with a notification node.

Permissions, REST, and MCP

Permission Allows Held by default
api:events:read Every category except security, and reading the settings. Admin and User roles
api:events:audit Security entries. Admin
api:events:write Changing the settings. Admin
Route Permission
GET /api/events read, or a dashboard showing the subjects asked for
GET /api/events/settings read
PUT /api/events/settings write

GET /api/events takes these parameters and answers {events, next_before}:

  • category, level, and subject, each repeatable. A subject is kind:id, such as control:<uuid> or ha_entity:<connection>/<entity>.
  • actor, as kind or kind:id.
  • q, for text.
  • from and to, as RFC 3339 or now-24h.
  • before, the next_before of the previous page.
  • limit, 1 to 500.

Asking for security without audit is refused.

Karakuri publishes live entries on the WebSocket topics events (read), events:security (audit), and events:subject:{kind}:{id} (read, or a dashboard showing the subject). A new entry arrives as event, and a repeat folding into one arrives as event_update.

MCP has list_events, with the same filters, and get_event_settings. No tool writes the log. Flows write it with Log Event.

The log is in the database, so backups carry it, and a restore is the first entry of the restored installation.

MCP

Karakuri serves the Model Context Protocol at /mcp, so an AI agent (Claude Code, or any other MCP client) can operate the instance: author and deploy flows, run tests and read per-node failures, manage controls, connections, MQTT devices, and dashboards, and read the built-in guides. MCP tools follow the same rules and checks as the web interface and REST API, so both give the same answers.

The endpoint uses stateless streamable HTTP. Every request is an independent POST, there is no session header, and the server never sends messages on its own. Set mcp.enabled: false in the configuration to remove the endpoint.

Authentication and permissions

/mcp accepts the same bearer tokens as /api: a session token or an API key. Three checks decide what a caller may do.

  1. Using MCP at all requires the api:mcp:use permission. Only administrators hold it by default, through their api:* grant. Anyone else needs a role carrying api:mcp:use assigned to them or their group, so that role decides which groups may drive the server over MCP.
  2. Each tool requires the same api:* permission as the matching REST endpoint: list_flows needs api:flows:read, deploy_flow needs api:flows:deploy, set_control needs api:controls:set, and so on. A refusal names the missing permission.
  3. Each flow also checks the caller's access level on that flow, under the ownership and sharing rules. Reads need view, changes and runs need edit, and deletion needs admin. list_flows, list_active_runs, find_references, and list_events cover only flows the caller may read. get_document_dependencies reports a referenced flow the caller may not read as unchecked, without its name.
  4. Each connection and agent checks that it is shared with the caller, as connections and agents describes. A tool naming one the caller cannot use answers that it was not found, and the lists, node types, references, and dependencies leave it out.

Connections and agents

Whoever adds a connection, or mints the token an agent enrolls with, owns it. The owner shares it with people or groups from its share button in Settings > Connections or Settings > Agents, or with POST /api/connections/{id}/shares or POST /api/agents/{id}/shares and {"username": "...", "permission": "use"} or {"group_name": "...", ...}:

Level Allows
use Seeing it, using it in flows, dashboards, devices, history, energy, and memory stores, invoking it, and running an agent's nodes.
edit Also changing and testing a connection, or renaming, enabling, and disabling an agent.
admin Also sharing and deleting it, and revoking an agent.

Holders of api:connections:manage or api:agents:manage hold admin on every connection or agent; the Admin role has both through api:*. The role permissions still decide what a user may do with connections and agents at all, and the share decides which ones. To let ordinary users add their own, grant their role api:connections:write or api:agents:enroll.

For an agent, set up a dedicated user in its own group, a role granting api:mcp:use plus exactly the api:* permissions the agent should have, and an API key created for that user. The key is the one secret the agent's MCP configuration needs. For local development, create or retrieve an admin token from build/:

./karakuri token list admin --name=mcp --raw
./karakuri token create admin mcp   # when the list is empty

The create command prints the bearer token. The list command can show keys created by recent versions. Replace a key it cannot show with a new one.

Limiting a key

An API key can be limited to a set of permissions, written the way roles write them, wildcards included. Choose Settings, API keys, Create key, Only the permissions I choose, where paths complete as they do in a role, or send permissions to POST /api/api_keys. A limited key passes a permission check only when its user's roles grant the permission and one of the key's entries matches it, so it never holds more than its user and loses whatever a role loses. The limit applies everywhere: REST routes, MCP tools, plugin routes, and the manage permissions that open every flow, dashboard, and event. An administrator's key limited to api:mcp:use and api:flows:read therefore reads only the flows the administrator owns or was shared, not every flow through api:flows:manage. Ownership and shares need no permission and still apply.

You cannot give a key a permission you do not hold yourself, and a request made with a limited key can only create keys limited to what that key holds. A key without a limit holds all of its user's permissions. GET /api/api_keys/permissions lists the permissions you may give a key.

Connecting

claude mcp add --transport http karakuri http://localhost:8080/mcp \
  --header "Authorization: Bearer kk_..."

Any client that speaks streamable HTTP works the same way: point it at /mcp and have it send the bearer header. Clients running in a web browser are not supported.

Tools

Each tool's JSON schema, listed through tools/list, describes its inputs and outputs. The groups, and the permission each checks:

Group Tools Permission
Flows list_flows, get_flow, create_flow, update_flow, delete_flow, save_flow_graph, patch_flow_graph, diff_flow, validate_flow_graph, list_flow_versions, restore_flow_version, export_flow, import_flow api:flows:read / write
deploy_flow, set_flow_enabled api:flows:deploy
Nodes list_flow_nodes, get_flow_node, list_flow_edges api:flows:read
Runs run_flow_test, test_flow_node, test_node api:flows:write
get_flow_run, list_flow_runs, list_active_runs api:runs:read
cancel_run api:runs:cancel
Catalog list_node_types, get_node_type, list_port_types, preview_schedule api:flows:read
Controls list_controls, save_control, delete_control, set_control api:controls:read / write / set
list_control_kinds signed in
Connections list_connections, list_connection_kinds, get_ha_states, get_ha_registry, list_ha_services, list_openhab_items, capture_mqtt_messages api:connections:read
save_connection, delete_connection, test_connection api:connections:write
call_ha_service, publish_mqtt api:connections:invoke
Time series query_timeseries, list_timeseries_metadata, list_history_forwards, get_history_status api:connections:read
save_history_forward, delete_history_forward api:connections:write
Charts get_chart_data dashboard view access; editors read the draft
MQTT devices list_mqtt_devices api:connections:read
save_mqtt_device, delete_mqtt_device, test_mqtt_device_script, discover_zigbee2mqtt_devices, add_zigbee2mqtt_devices, regenerate_mqtt_device api:connections:write
command_mqtt_device, call_esphome_action, send_openhab_command api:connections:invoke
discover_esphome_nodes, discover_esphome_entities, add_esphome_entities, discover_entities, add_entities, discover_mqtt_discovery_devices, add_mqtt_discovery_devices api:connections:write
get_auto_import_status api:connections:read
NVR list_nvr_cameras, list_nvr_events, get_nvr_snapshot api:connections:read
Energy list_energy_sources, list_energy_candidates, list_energy_groups, list_energy_tariffs, get_energy_rollups, get_energy_price, find_cheapest_energy_window api:connections:read
save_energy_source, delete_energy_source, import_energy_history, save_energy_group, delete_energy_group, save_energy_tariff, delete_energy_tariff api:connections:write
create_energy_dashboard api:dashboards:write
Notifications list_notification_services, list_notification_endpoints api:connections:read
send_notification api:connections:invoke
Events list_events, get_event_settings; security entries need api:events:audit api:events:read
Backups list_backups, get_backup_schedule api:backups:read
create_backup, verify_backup, delete_backup, save_backup_schedule api:backups:write
Dashboards create_dashboard, import_dashboard api:dashboards:write
update_dashboard, widget placement, add_dashboard_section, update_dashboard_section, remove_dashboard_section, add_dashboard_page, update_dashboard_page, remove_dashboard_page, export_dashboard, deploy_dashboard, list_dashboard_versions, restore_dashboard_version owner, an edit share, or api:dashboards:manage
Live dashboards get_dashboard_live, command_dashboard, resolve_dashboard_variables owner, an edit share, or api:dashboards:manage
delete_dashboard owner, an admin share, or api:dashboards:manage
list_dashboards, get_dashboard, list_widget_types, list_themes signed in; the accessible set
Dashboard inspection diff_dashboard, validate_dashboard edit access
Faceplates get_flow_faceplates, apply_flow_faceplates faceplate access to the flow or higher; see faceplates
Dependencies get_document_dependencies flow read or dashboard edit; referenced subsystems checked separately
Reference search find_references referenced subsystem read; flow read / dashboard edit
Persisted state inspect_flow_state api:flows:read and api:runs:read
Pending waits cancel_flow_wait api:runs:cancel
Overview get_attention, list_upcoming, list_unfinished_work; see home.md signed in; each source checks its own permission
Agents list_agents, get_agent_status api:agents:read
Dashboard previews render_dashboard edit access for draft; view access for deployed
Plugins list_plugins, get_plugin_settings api:plugins:read
set_plugin_enabled, update_plugin_settings api:plugins:write
Guides read_guide signed in
Scripts test_script api:flows:write

timeseries.md describes time-series queries, history forwards, and chart data. query_timeseries returns typed series with times in Unix milliseconds.

Graph tools send and return graphs in the flow graph JSON format. The karakuri://guides/flow-authoring resource documents it, and the server tells agents to read it before writing a graph. The usual authoring loop is save_flow_graph, validate_flow_graph with strict, run_flow_test, then get_flow_run for the result of each node.

get_flow_faceplates lists a flow's faceplate tabs, controls, and values, and apply_flow_faceplates applies values and deploys, under the same rules as the faceplate tabs in the flow guide. To build a faceplate, add a faceplate node with the graph tools. Editor chat on a flow may use both.

Resources

Every guide in the app's Help pages is also a markdown resource at karakuri://guides/<name>, where the name is the guide's address under /help, such as karakuri://guides/flow-authoring. read_guide returns the same markdown by name.

What is deliberately absent

User, group, role, and API key administration work only through REST and the web interface, so an agent cannot change its own permissions. There is no rerun tool; use run_flow_test with a payload override to replay a run. Agent enrollment, revocation, and updates, and render schedules, are also not available over MCP. Agent status and capabilities can be read.

Editor chat

Kuri, the editor's AI assistant, uses these same tools with the signed-in author's identity and permissions. It can inspect, edit, deploy, restore, and test-run the selected document. It does not need api:mcp:use, because it is part of the signed-in editor, and it keeps working when mcp.enabled is false; that setting only turns off the external /mcp endpoint. See Editing dashboards and flows with AI for using it.

Widget and section changes must name a placement on the specified dashboard. update_dashboard accepts theme_id from list_themes; zero clears the theme. Editor chat can read a dashboard's live state with get_dashboard_live. It can call command_dashboard only with Allow deployment and execution on, because a command reaches every open viewer.

Shared drafts and deployment

REST, MCP, and editor chat all edit the same stored draft. After each change, editors that have the document open reload it, as they do after reconnecting. Only users who may read the flow, or edit the dashboard, are notified.

Tools that return a flow report the caller's access_level and leave out the folder when the caller cannot see it, as list_flows does.

get_flow returns draft_revision. Pass it as expected_revision to save_flow_graph to refuse the save if someone else changed the graph since you read it. The browser always does this. If another author changes the graph while you have unsaved edits in the browser, the editor keeps your edits and offers Reload shared draft instead of writing over the newer draft. MCP clients should read the flow again and reapply their edits after a conflict.

Saving a draft does not deploy it. deploy_flow fixes the graph, name, description, and error routing for the deployed flow; deploy_dashboard fixes layout, widgets, sections, name, description, and theme. Enabling and disabling apply to the deployed flow. Dashboard sharing and URL settings take effect immediately and are not part of a deployment.

restore_flow_version and restore_dashboard_version replace the whole draft with a stored version. Leaving out version restores the current deployment, discarding changes made since. Restoring never deploys or changes whether the flow is enabled. All open editors receive the restored draft.

Versions saved by older releases did not record presentation or error-routing settings. Restoring one of them keeps those settings as they were when you upgraded.

Testing and failure inspection

run_flow_test runs the draft, including real device actions, and returns a run_id. Pass that ID with the flow id to get_flow_run to inspect exactly that run, even if a trigger starts another one meanwhile. Without run_id, get_flow_run returns the latest run. list_flow_runs pages through stored runs and filters by status or had_failures. Each flow keeps its latest 100 completed runs and all active runs, and Karakuri removes older completed runs with their events.

get_flow_run always returns the state of each node. Set include_events for the raw events, optionally filtered by node_id, and page with after_event_id and limit (default 100, maximum 500). next_event_id and has_more_events describe the next page.

test_connection returns ok, an error when the test failed, and, for kinds that probe, a detail describing what it found, such as a calendar connection's calendar names and upcoming event count.

Visual dashboard inspection

render_dashboard returns a JPEG screenshot of a dashboard. It accepts view (draft by default, or deployed), width, and height (default 1280 by 800; each must be 100 to 2048 pixels). Draft previews require edit access. Karakuri takes the screenshot with temporary read-only access to that dashboard and none of your other permissions. Scheduled renders and render jobs still use the deployed layout.

Editor chat shows the image in the expandable tool entry and passes it to the model, which must accept images to see it. Only the latest screenshot is sent to the model on later turns; earlier ones stay visible in the chat. A render captures one screen, so request the size the dashboard is meant to fill.

Focused edits and comparison

patch_flow_graph applies 1 to 200 operations to the shared draft, all or nothing. Pass expected_revision from get_flow. Each operation has op, id, and, for adds and updates, value. Operations are add_node, update_node, remove_node, add_edge, update_edge, and remove_edge. Updates merge objects recursively; null removes a field and arrays are replaced. IDs cannot change. Removing a node also removes its edges. subgraph_path is an optional array of local subgraph keys locating the graph to edit. Edit a shared subflow through its own flow ID. Karakuri checks the whole batch before saving it, and a stale revision or an invalid operation leaves the draft unchanged.

diff_flow and diff_dashboard compare what a deployment would contain. from defaults to deployed and to to draft; either also accepts a version number as a string. deployed is empty when nothing has been deployed. Results contain changed and a changes array with op, path, before, and after. Paths use JSON Pointer escaping, with nodes, edges, widgets, and sections keyed by ID. The diff reports changes to flow edge order separately, because value inputs can depend on edge order. Widget config is compared as parsed JSON. Sharing, access settings, and whether a flow is enabled are not compared. Dashboard diffs require edit access even when comparing deployed versions.

Dependencies and validation

get_document_dependencies takes kind (flow or dashboard), id, and view (draft by default, or deployed). It lists what the document refers to, including local subgraphs, deployed shared subflows, error flows, and widget bindings. Each dependency gives its location in the document and a status: available, missing, unavailable, invalid, dynamic, or unchecked. Dynamic values cannot be resolved without running a flow. References to subsystems you cannot read are unchecked and reveal nothing about the referenced object. Connection credentials and control values are never returned. The listing stops after 32 nested graphs or 2,000 entries and reports truncated.

validate_dashboard checks the layout's geometry, section references, widget packages, widget configs, and bindings. Overlaps, disconnected services, and widgets without a config schema are warnings; malformed configs, placements outside the grid, and missing bindings are errors. valid means no errors were found; check warnings and truncated too. Configs are checked with the widget's defaults filled in. The check never changes the draft, deploys, or operates a device.

list_agents reports each enrolled host, whether it is connected, and how many capabilities it has registered. get_agent_status adds the node type IDs that host provides; use get_node_type for their schemas. Capabilities list what the host offers, not whether desktop permissions are granted or a node will succeed.

Render diagnostics

render_dashboard with diagnostics: true returns a screenshot plus a report from the same capture. Diagnostics are off by default, and access checks are the same either way. The report covers readiness, viewport and page size, widget IDs and positions, load state, widgets placed off screen, and content overflowing its container. Overflow can be intentional scrolling, so it does not by itself mean something looks wrong. Collapsed sections are not expanded, and some built-in widget internals cannot be inspected.

The report also lists uncaught errors, console errors, failed requests, and responses with status 400 or above. It strips credentials, query strings, and fragments from URLs, and it does not collect request bodies or headers. Reports list at most 100 browser issues, 500 placements, and 10,000 inspected elements, and say when they were cut short. Diagnostic renders are kept as long as other renders.

Nodes without a flow

list_node_types lists the available node types, including plugin and connected agent node types. get_node_type returns a type's configuration fields and ports. Supply an optional config object to get resolved_inputs and resolved_outputs for ports that depend on configuration. Neither tool needs a flow ID.

test_node runs a node type directly:

{
  "type": "script",
  "config": {"language": "javascript", "script": "return payload * 3;"},
  "inputs": {"in": {"payload": 11}},
  "timeout_seconds": 30
}

The response includes status, outputs (message arrays keyed by port), events (node states and debug messages), duration_ms, and any error. Results come back in the tool response, and no run is saved. A node failure is a result with status: "failed". Invalid configuration or inputs are tool errors. Outputs from successful attempts, and messages emitted before an attempt finishes, are included. Output stops at 1000 items or 1 MiB across outputs and events, with truncated: true. Values that cannot be converted to JSON are reported in capture_errors.

Tests use real node code and your configured connections, including remote agents, and can perform real actions. No flow, version, or run history is created. Node stores and variables start empty and are discarded after each test. The timeout includes time the node spends waiting, defaults to 30 seconds, and accepts 1 to 120 seconds. When it expires, Karakuri asks the node to stop. status: "canceling" means it had not stopped five seconds later. The response can therefore arrive up to five seconds after the timeout, and a system or plugin call that does not respond may keep running.

Triggers run once with the supplied sample and do not start listening. Inputs follow the same rules as test_flow_node. Message inputs use the resolved port IDs, binary payloads use base64, and triggers or nodes with no message inputs accept inputs.__trigger__. For an isolated test, supply permanent value-port fields in config, with base64 strings for binary data. Required fields are still required, and parameter ports are not message inputs. Subflow calls, graph tools, and routing nodes need a flow; use run_flow_test for them. The flow editor's AI chat can use test_node to try a configuration before adding it to the draft.

Placed nodes and isolated tests

list_flow_nodes returns short summaries with id, type, label, available, and bypass when set. Labels use the saved _label, or else the type's label or identifier. Use get_flow_node for the saved configuration, resolved ports, connected edges, and the full config schema. list_flow_edges returns the wiring in order, optionally filtered by node_id. All three accept view (draft or deployed) and subgraph_id (a key in the root's subgraphs map). Draft responses include the revision for a following patch. Nodes whose type is not installed are listed with available: false; ports that cannot be resolved have ports_known: false in get_flow_node.

test_flow_node runs one draft node with the inputs you supply:

{
  "id": "FLOW_UUID",
  "node_id": "transform",
  "inputs": {"in": {"payload": 42, "topic": "test"}},
  "config_overrides": {"script": "return payload * 2;"}
}

Read the node's resolved input IDs first. Every required message input needs a message, unless you are testing only an optional input such as reset. Binary inputs take base64 text. A trigger or a node with no message inputs accepts inputs.__trigger__, or uses its saved test payload when that is left out. config_overrides replace config fields for this run only. Each wired value input needs an override, because the nodes feeding it do not run. The draft and deployment are not changed.

The node performs real actions, with its normal retry policy. Nodes before and after it, and error-handler flows, do not run. Routing nodes, subflow calls, tools, annotations, and bypassed nodes cannot be tested alone. Use run_flow_test to test the branch instead. To test a regular node inside a local subgraph, supply subgraph_id. Its history and stored state use the returned node_id, prefixed with @subgraph/<key>/, and are kept apart from where the subgraph is used. Testing a top-level node shares its stored state with normal runs. Values that other nodes would normally supply, such as run variables and tool-call state, are absent.

Use the returned run_id with get_flow_run and include_events: true to see outputs and failures. History keeps the first message on each output port, with a count when there were more. Editor chat can use these tools too, limited to the selected flow.

Discovery and troubleshooting

list_ha_services reads the connected Home Assistant's service catalog. Pass connection_id and optional exact domain and service filters. Each entry includes its domain, service name, and the full service description under schema, including the fields, selectors, and targets that integration provides. Results are sorted and paged with offset and limit (default 50, maximum 100). Read has_more and next_offset for the next page. This uses Home Assistant's get_services WebSocket command and never calls a service.

capture_mqtt_messages records messages from an existing broker connection for a short time. It takes connection_id, topic_filter, optional duration_seconds (default 5, range 1 to 30), and max_messages (default 20, range 1 to 100). Topic filters accept + and #. The tool refuses shared subscriptions. The duration includes setting up the subscription. Flows and devices using the same connection are not affected, and cancelling the request stops the capture. Clients older than MCP protocol version 2026-07-28 cannot cancel by disconnecting and wait for the full duration.

The result's messages give topic, time received, payload, and encoding (utf8 or base64). Retained messages are included when the broker holds any, even if a flow or device already subscribes to the same filter. QoS and retained flags are not reported. stop_reason is timeout, message_limit, or byte_limit. A single payload over 128 KiB, or more than 1 MiB of output, stops the capture with truncated: true. subscription_active reports whether the subscription was still active at the end, and connection_state tells an empty sample apart from a disconnected broker. Capture never publishes and may miss messages. Both list_ha_services and capture_mqtt_messages require api:connections:read.

preview_schedule takes expr, an optional IANA location, an optional RFC3339 after, and count (default 5, range 1 to 20). It reads expressions the same way schedule nodes do: five fields, optional seconds, and descriptors. It returns valid, a description, field labels, and upcoming RFC3339 times with offsets. Invalid expressions and zones return valid: false with an error. It requires api:flows:read and never starts a trigger.

find_references finds what refers to something. Supply kind (connection, control, mqtt_device, flow, ha_entity, or agent) and ref. HA entities also need their connection UUID as owner. Controls match by UUID or name. view selects the draft (default) or deployed version of the documents searched; nested shared flows always use their deployment. The search requires read permission for the referenced subsystem. It searches flows only with api:flows:read, and dashboards only where you have edit access. It never reads live HA entity states.

Each page (starting at 1) searches up to 50 flows and 50 accessible dashboards. Keep paging while has_more is true, even if a page has no matches. Each result identifies its document and where the reference is. A page returns at most 2,000 matches. incomplete reports hitting a limit, dynamic references, unknown node or widget types, or documents that failed to load. issues names documents that could not be searched. The search covers declared references, not text inside scripts. Edits made during the search can shift the pages.

inspect_flow_state reads stored state for flow id. Choose store as variables (default), nodes, or waits; node state accepts an exact node_id filter. waits lists the flow's pending timers, held messages, and partial groups, with each wait's node, key, deadline, missed_deadline setting, the run_id that started it, and whether it is durable. Pass a wait's node_id and key to cancel_flow_wait to end it without delivering it. Run history records the cancellation. Both accept an exact key, limit (default 50, maximum 100), and after_id for paging with the returned next_id. Entries contain JSON values and update times. Values over 64 KiB, or beyond the page's 1 MiB total, are left out with value_omitted: true; their keys are still listed.

State inspection requires both api:flows:read and api:runs:read. It shows only that flow's stored variables and durable node state, including state left by removed nodes. It does not show global variables, temporary node state, or run and message variables. Results have source: persisted, so very recent changes may not appear yet, and pages of a running flow can change between requests. It never changes state. Whatever data a flow stores is returned as it is, so these permissions give access to that data.

Editor chat offers connection discovery, MQTT capture, and reference search in both editors. Flow chat also offers schedule preview and state inspection, which is limited to the selected flow.

Graph authoring diagnostics

Graph errors name the node or edge they concern. Successful save_flow_graph and patch_flow_graph calls include a separate validation result from a strict check. You can save an incomplete draft while that result is invalid. Fix the reported problems before treating the graph as finished. validate_flow_graph accepts flow_id without graph to check the stored draft. Use strict: true to check that the configuration can run.

get_node_type includes an optional value_schema on structured config fields and payload_schema on output ports. These JSON Schemas describe nested data. They do not change what the node accepts or which ports can connect.

Notification services

list_notification_services returns every notification provider with its credential fields, target examples, and the reason a provider is unavailable. list_notification_endpoints takes a connection id and returns only that connection's allowed endpoint IDs and labels. Both require api:connections:read.

send_notification takes connection_id, endpoint, an optional subject, a required message, and an optional integer timeout (1 to 120 seconds, default 30). It requires api:connections:invoke and sends only to an endpoint ID listed in that connection's settings. A successful result contains accepted: true. A failure or timeout may leave delivery uncertain and is never retried automatically. Use the connection tools to configure services. Reads mask secrets and targets, and saving with an unchanged mask keeps the stored target. The notification guide describes the configuration format.

Plugins

A plugin is one directory with a manifest.yaml and whichever contributions it makes. Every contribution is optional. The weather plugin brings nodes, a widget, settings, an HTTP API, a provider, and permissions; the clocks plugin brings three widgets and no Go code at all.

Contribution Declared by What it provides
Node types Registrar.RegisterNode Palette entries that validate, retry, and test-run like built-in nodes
Connection kinds Registrar.RegisterConnectionKind A connection type with its settings form, driver, validation, and test
Port types Registrar.RegisterPortType Edge compatibility, labels, colors, and value parameters
Field controls Registrar.RegisterFieldControl Config editors, with a fallback editor where the frontend lacks one
AI providers Registrar.RegisterAIProvider An entry in the AI connection's provider picker
Dashboard widgets widgets: in manifest.yaml Entries in the widget picker, served at /widgets/{package}/
What a widget exposes scope: under a widget in manifest.yaml What a dashboard's viewers may read and press through the widget
Settings Configurable.SettingsSchema A settings panel, stored as plugins.{name}.{key}
An HTTP API HTTPPlugin.HandleHTTP Routes under /api/plugins/{name}/*
Providers HostAPI.RegisterProvider A typed endpoint listed at /api/providers/{type}
Permissions HostAPI.RegisterPermission Permissions for roles and API keys

An AI provider is data only. The definition names one of the host's wire formats (chat-completions, anthropic, or gemini), a default endpoint, and whether its models accept tools. No calls cross back into the plugin.

A plugin with more than one widget should give each its own description. Otherwise they all inherit the plugin's and read identically in the picker.

Manage plugins under Settings, Plugins or at GET /api/plugins, gated on api:plugins:read and api:plugins:write. The built-in node sets (core, MQTT, Home Assistant) appear there too, read-only, because they are compiled into the server and cannot be unloaded.

Layout

plugins/weather/
  manifest.yaml
  main.go nodes.go handler.go openmeteo.go ...     # the executable
  widgets/weather/{package.json,src/,dist/}        # the widget it serves

plugins/clocks/
  manifest.yaml                                    # widget-only: no Go
  widgets/{analog-clock,binary-clock,fuzzy-clock}/
name: "weather"
version: "0.1.0"
description: "Weather forecasts for dashboards and flows."
author: "James Coleman"

# Optional: the executable contributing nodes, an API, and settings.
entryPoint: "weather"

# Optional: ship disabled until an operator enables it, for plugins most
# installs have no use for. Read only the first time the plugin is seen;
# the enable choice stored from the settings panel wins afterwards.
defaultDisabled: true

# Optional: widget packages. path defaults to widgets/<packageName>,
# entryPoint to index.js, and version/author/description to the plugin's own.
widgets:
  - name: "Weather"
    packageName: "weather"
    tagName: "weather-widget"
    configTagName: "weather-config"
    tags: ["weather", "forecast"]
    defaultProvider: "openmeteo"

Widget declarations may include configSchema (a JSON Schema written as a YAML object) and defaultConfig (a YAML object). list_widget_types shows both, and validate_dashboard checks against them. Validation overlays stored config fields on the defaults without changing either. Local schema references work, and external schemas are never fetched. validate_dashboard reports packages without schemas as unchecked for config validation.

Widget sources live at plugins/<name>/widgets/<package>/, so a manifest rarely needs a path. packageName is the widget's URL and its identity in stored dashboards. A plugin claiming a package name another plugin already registered is refused.

The server also refuses an AI provider name another plugin holds. Node types, connection kinds, port types, and field controls are instead replaced by name, so a second registration silently overwrites the first. Choose names that will not collide with another plugin's.

A plugin directory named after a built-in (plugins/core/, plugins/homeassistant/) holds a manifest with widgets: and no entryPoint. Its widgets attach to the built-in's catalog entry and cannot be disabled apart from it. Name a directory after a built-in only for that purpose. Anything else there is an error.

The server serves widget bundles from the plugin directory instead of compiling them into its binary, so a missing plugin directory means missing widgets.

Declaring a widget's scope

Dashboard viewers often hold no permissions of their own. A widget's scope tells the host what placing the widget on a dashboard lets that dashboard's viewers reach. A widget with no scope reads nothing from the host and grants nothing, which is right for a clock or an image.

The grant comes from the dashboard's deployed layout. A viewer may read what the widgets placed on it bind, and nothing else. A placement of a widget whose plugin is unloaded grants nothing.

Bindings

bindings names the config field that holds host bindings, the {source, connectionId, entityId, controlId, deviceId, flowId, trigger, displayOnly, triggers} shape that points at a Home Assistant entity, a control, an MQTT device, or a flow trigger. The field may hold one binding object or an array of them. "." means the whole config is one binding.

  - name: "Entities Card"
    packageName: "entities-card"
    scope:
      bindings: "rows"       # the field holding them
  - name: "Entity Control"
    packageName: "entity-control"
    scope:
      bindings: "."          # the config is itself one binding

The host reads only that shape from a widget's config. What each source lets a viewer read and press is described in What each binding lets viewers read and operate.

Topics and API routes

Data that comes from the plugin itself, such as a forecast, is not a host binding. Declare the topics the widget subscribes to and the plugin routes it calls:

    scope:
      topics:
        - "weather:forecast:*"
      api:
        - "GET /*/forecast/*"

A topic pattern uses : as the segment separator, and * matches one or more segments. It may contain {dashboard} and {widget}, which the host replaces with the placement's dashboard ID and placement ID. A topic keyed by them, such as myplugin:{dashboard}:{widget}:data, grants each placement exactly its own topic. A topic left as a namespace grants every topic under it, so a viewer of a dashboard with the weather widget can read forecasts for any location.

An api entry is METHOD /path/pattern. The path is the part after /api/plugins/{name}. * matches one path segment and ** matches all the remaining segments. The host ignores an entry missing the method or the path instead of widening it. Name only the routes the widget calls. Weather declares its forecast route and leaves out the geocoding routes beside it, which only its config panel uses, so a viewer cannot reach them through the dashboard.

Every topic the plugin publishes also needs a WebSocket gate. Register one in Init with HostAPI.RegisterTopicPermission. A topic that matches no registered gate is denied to everyone, so a plugin that publishes on an unregistered namespace finds its own widget cut off. The scope entry then lets viewers who lack that permission subscribe through the dashboard.

Keep secrets out of a widget's config. The host serves it to every viewer of the dashboard. Store credentials in the plugin's own settings and return them only through routes that check edit access with CheckDashboardAccess.

Load and unload

Loading a plugin applies its contributions. A widget-only plugin has no process to start, and enable and disable work the same way for both kinds.

Contribution On load On unload
Executable Start the process, register what it contributes, serve settings, HTTP, and messaging Stop the process; withdraw its nodes, connection kinds, permissions, providers, and topic gates; drop its subscriptions
Widgets Add them to the picker and serve them Stop serving them; existing placements keep their metadata

Port types and field controls stay registered after unload. Removing a port type would shift the color of every type registered after it.

Disabling a plugin is how a widget is disabled. There is no separate widget toggle. GET /widgets returns the packages a loaded plugin can serve, which is what the dashboard picker offers, and the list cannot be edited through the API. A placement of an unloaded widget keeps its config and works again when the plugin returns.

The enable choice survives restarts, and the panel shows the last load result for a plugin that is not running. When a plugin directory is deleted, the next scan removes its state, settings, and widget entries. A plugin that failed to load keeps all three.

Writing a plugin

type myPlugin struct{}

func (myPlugin) Manifest() plugin.Manifest {
    return plugin.Manifest{Name: "zigbee", Description: "Zigbee nodes and coordinator connection."}
}

func (myPlugin) Register(r plugin.Registrar) error {
    r.RegisterNode(MyTriggerNode{})
    r.RegisterNode(MyActionNode{})
    r.RegisterConnectionKind(integrations.ConnectionKind{
        Kind: "zigbee", Label: "Zigbee",
        ConfigSpec: []flow.FieldSpec{
            {ID: "serial_port", Label: "Serial port", Type: flow.FieldString, Required: true},
            {ID: "network_key", Label: "Network key", Type: flow.FieldString, Control: "password"},
        },
        Secrets: []string{"network_key"},
        Factory: newDriver,
        Test:    testConnection,
    })
    return nil
}

func main() { sdk.Serve(myPlugin{}) }

Nodes implement engine.NodeType exactly like the built-ins: Meta() returns the flow.NodeMeta (folder, ports, config spec, behavior flags) and Execute runs against engine.ExecContext. A trigger also implements engine.TriggerType.

Connection kinds

integrations.ConnectionKind carries the config schema ([]flow.FieldSpec), the fields to mask (Secrets), the driver Factory, and optional Validate, Test, and Probe hooks. Probe tests like Test and also returns a short description of what it found, such as the calendars an account holds, which the connection test shows beside its result. When a kind has both, tests call Probe. The server validates required fields from the schema, and the settings page renders the form from it, so a new kind needs no frontend changes.

Port types

flow.PortTypeDef is data with these fields:

  • Name and Label.
  • WidensTo, directional assignability. Integer widens to float and number.
  • Value, usable as a subflow value parameter.
  • Script, declarable on a script node's ports. The data types allow it, and a capability type like the AI plugin's ai-tool does not.

Compatibility checks, editor labels, tooltips, script port pickers, and edge and socket colors all come from the registered types, listed at GET /api/nodetypes/porttypes. Colors follow registration order, so add new types after existing ones and never reorder them.

Field controls

A config field's Type is its datatype, which validation checks and a value edge binds to. A field with Port set is a port field, a permanent value input port of that port type instead of an editable setting, supplied only by value edges. Multi lets several wires feed it as an array, as with the AI agent's model and tools inputs.

Control names the editor a normal field renders with, referencing a flow.FieldControlDef listed at GET /api/nodetypes/controls. Each control declares a Base type. A frontend that does not implement the control renders the base type's editor instead, so a custom control stays editable. The frontend implements password, list (string array), map (key/value object), and tokens (a comma-separated string edited as chips; the field's options are the vocabulary, and a field with no options takes typed entries) beyond the type-default editors.

External plugin processes

An external plugin is a separate executable that implements the same plugin.Plugin interface a built-in does. Its main calls sdk.Serve from pkg/plugin/sdk, which runs nodes, triggers, and drivers inside the plugin process and talks to the server over gRPC. A plugin node validates, retries, pulls values, and test-runs exactly like a compiled-in one.

The server looks for plugin directories in plugins.paths from the config. Unset, it searches plugins/ beside the binary, then /etc/karakuri and /usr/share/karakuri. An explicit empty list disables plugins entirely.

Behavior to know when writing an external plugin:

  • Execute. The node receives its merged config, resolved ports, and inputs, and returns outputs. Binary payloads survive the trip. A node error is reported as the node's failure, separate from a lost plugin process. One message in either direction is limited to 128 MiB.
  • Callbacks. Run state, variables in every scope, expressions, Debug, Emit, and Park all work through ExecContext as they do for built-ins. The clock is the server's. NodeStore.Update may run its function more than once when another update lands at the same time, so keep it free of side effects.
  • Missed events. An armed trigger can record an event it chose not to run, such as an occurrence missed while the server was down, through engine.TriggerRecorder. The run list shows a canceled run with the reason and the event's payload.
  • Waits. A plugin node that parks keeps its wait in memory. A server restart or a redeploy ends it, unlike the built-in timer and fan-in nodes, whose waits survive restarts.
  • Triggers. Each emitted message starts a run. The trigger is disarmed when its context is canceled.
  • Drivers. A plugin's connection kind builds its drivers inside the plugin process, and the connection shows the status they report. If the plugin process exits, its connections report an error. A plugin node's Connection(id) resolves only connections of kinds its own plugin registered; a plugin cannot use another plugin's or the server's drivers.
  • OAuth tokens. HostAPI.ConnectionAccessToken returns a current access token from a server oauth2 connection. It refuses connections that are stopped or do not issue tokens.

The server logs and skips a plugin directory it cannot use at startup, such as one whose manifest does not parse or names an entry point that is not on disk. The plugins beside it load as usual. While any directory is refused, nothing is removed for plugins missing from the scan, since the refused directory may be theirs.

make dev builds every plugins/<name>/ into build/plugins/<name>/: the Go executable when there is a main.go, each widgets/<package>/ bundle, and the manifest. To install a plugin elsewhere, copy that directory into one of the plugin paths. plugins/weather/ is a complete example with nodes, a widget, settings, an API, and scope declarations.

Settings, HTTP, and messaging

A plugin that does more than contribute nodes implements optional interfaces alongside plugin.Plugin. A missing interface means the plugin does not contribute that thing.

Interface Purpose
Initializer Init(ctx, host): read settings and register everything that is not a node type
Shutdowner Release what Init acquired
Configurable A JSON Schema describing the plugin's settings
HTTPPlugin Serve the plugin's own API
OpenAPIPlugin Publish those routes in the server's API document
MessagePlugin Receive broker messages on subscribed topics

Settings are read once, at Init, so saving them reloads the plugin. Every schema property with a default is stored on first load, so a fresh install starts configured. Keys are namespaced as plugins.{name}.{key}, so a plugin asks for api_key and cannot read or overwrite another plugin's settings. A "format": "password" property renders masked.

The HTTP API is served at /api/plugins/{name}/* with the prefix removed, so a plugin routes within its own namespace. The mount does not require authentication; each route decides who may reach it (see Securing plugin routes). pkg/plugin/sdk/httpsdk carries the boilerplate: NewService (an OpenAPI service using the server's error format), ServeHTTP (adapts a proxied request to the service), RequirePermission, Allowed, and OpenAPISpec. A plugin that only contributes nodes does not need to import it.

func (p *WeatherPlugin) HandleHTTP(_ context.Context, req *plugin.HTTPRequestParams) (*plugin.HTTPResponseResult, error) {
    return httpsdk.ServeHTTP(p.service, req)
}

func (p *WeatherPlugin) OpenAPISpec() string { return httpsdk.OpenAPISpec(p.service) }

plugin.HostAPI is what Init receives:

  • GetConfig/SetConfig: the plugin's own settings namespace.
  • Publish/Subscribe/Unsubscribe: the message broker. Subscribing to topic:<pattern>:count tells a plugin how many dashboards watch a topic; the weather, crypto, and stock plugins start polling when it rises above zero and stop when the last viewer leaves. Messages arrive one at a time in publish order, so the last count handled is the current one.
  • RegisterPermission/UnregisterPermission/SeedRoleDefaults/CheckPermission: define the plugin's permissions and give default roles access.
  • RegisterProvider/UnregisterProvider: advertise a typed endpoint (weather/openmeteo) that a widget's config panel discovers through /api/providers/{type}.
  • RegisterTopicPermission/UnregisterTopicPermission: gate WebSocket subscription to a topic pattern behind a permission.
  • CheckDashboardAccess: ask whether a user may act on one dashboard at a level: read to see it, view to also operate it, edit, or admin. Each level includes the ones below it. Ask for read to serve data a viewer watches; view refuses a user the dashboard was shared with read-only. A plugin storing per-widget configuration needs this rather than a blanket dashboard permission, which would let anyone holding it read another dashboard's stored credentials.
  • ConnectionAccessToken: a current token from a server oauth2 connection.

Securing plugin routes

The server authenticates the caller before forwarding a request, and passes the result with it. Read it with apiutil.PluginUserID(r) and apiutil.PluginUsername(r); both are empty for an anonymous caller.

httpsdk.RequirePermission(host, permission) gates a route on a permission:

s.With(httpsdk.RequirePermission(host, "api:weather:read")).
    Method(http.MethodGet, "/{provider}/forecast/{lat}:{lon}",
        nethttp.NewHandler(p.forecastInteractor()))

It answers 401 to an anonymous caller and 403 to a user without the permission. A request made with an API key limited to a set of permissions must also list that permission in the key, so a key cannot reach more through a plugin than it can through the server's own API.

To check a permission inside a handler, call httpsdk.Allowed(host, r, permission). It applies the same user and API key checks. Do not call host.CheckPermission directly for a request; it checks only the user and ignores the key's limit.

A request that matches an api route in a widget's scope arrives with a dashboard grant, the ID of the dashboard whose viewer made it. Read it with apiutil.PluginDashboardGrant(r). RequirePermission admits a request carrying a grant without asking for the permission, since a dashboard's viewers usually hold none. The client cannot forge the grant, because the server passes it separately from the request headers.

The grant names which dashboard authorized the request. A route keyed by dashboard, such as /{dashboardID}/{widgetID}/data, must compare apiutil.PluginDashboardGrant(r) with its own dashboard path parameter and refuse a mismatch. Without that check, a viewer of one public dashboard could ask the route about a private one.

func (p *myPlugin) widgetData(w http.ResponseWriter, r *http.Request) {
    dashboardID := chi.URLParam(r, "dashboardID")
    if grant := apiutil.PluginDashboardGrant(r); grant != "" && grant != dashboardID {
        http.Error(w, "forbidden", http.StatusForbidden)
        return
    }
    // Without a grant, the caller is a signed-in user: check access with
    // host.CheckDashboardAccess(r.Context(), apiutil.PluginUserID(r), dashboardID, "read").
}