Reeve Docs

Docs / Development

Plugin authoring guide

How to write a Reeve plugin. Read plugins first for the model: the lanes, the trust position, isolation and the multi-replica rules this guide assumes.

Common mistakes

These mistakes compile and fail silently or break the protocol.

Mistake What happens Do this instead
Bumping the SDK package version The release pipeline re-derives minBackendVersion from the resolved SDK version. Nothing fails at build or publish, and the plugin refuses to install on an older host. Bump the SDK only when you intend to raise your host floor, and say so in the release notes.
Marking a permission required: true It blocks the install when the code is not granted at first setup. It is not a hint. Mark it required only if the plugin cannot start without it.
Deriving the sensitive-field set from the static schema A config-flow plugin's static schema is typically empty, so every secret is written to the settings store in plaintext. Union the sensitive set from the per-step field declarations.
Keeping device state in plugin memory The cache goes stale and the plugin acts on wrong data. Read through the host and hold nothing.
Causing an effect from an observation observer The observer runs on every replica but the owner, so a device event or reply it emits happens once per replica, on top of the owner's. Apply state only and leave effects to the ingestor. See adapter frames on every replica.
Opening a long-lived connection without a lease Every replica opens its own socket to the same device. Take a connection-ownership lease, observe its Lost token or poll IsStillOwnedAsync, and close the connection on loss.
Reading a null lease as final The replica is not serving yet or is fenced, or a peer owns the resource. The connection never opens, or opens only at the next discovery scan. Retry the acquire on a bounded interval and after Lost or an eviction. See connection ownership.
Timestamping a broadcast reading with the replica's clock Each replica passes a different time for one message, so every replica stores its own telemetry row and a DeltaUsage meter bills it once per replica. Pass the device's clock, or the receipt time only where one replica hears each message. Otherwise leave it null.
Returning the Faulted health status Faulted is host-set and means "threw during start". Returning it destroys the only signal that separates a crash from "not started yet". Return degraded or unhealthy with a message.
Throwing on a missing capability An existing installation does not gain a newly requested permission on upgrade. Check for the capability and degrade to an actionable unhealthy state.
A device credential in a fixture Tests assert on shape, so a real secret produces a green suite and no signal. Keep credentials out of source, test constants, example configuration, published artifacts and diagnostics exports.
A static reference to a socket or native handle It blocks the load context from unloading, and an unload can orphan a live connection. Dispose in the unloading handler.
Parsing an operator-supplied address with the framework parser It accepts historical shorthand, so a three-part or zero-padded address resolves to a different host than the operator typed. Parse strictly.

Project setup

A plugin lives in its own repository. The product tree carries no plugin source. The versioned SDK package, the compatibility check and the publisher index keep plugins consistent with the host, so a breaking SDK change surfaces at your build, not at someone's runtime. A repository that holds several plugins still builds and tests every plugin on each change, and publishes each one on its own version bump.

Reference only the published packages: the plugin abstractions, the contracts, the authoring helpers, the sidecar wire-protocol contracts if you write a sidecar client, and NuGet packages. Never reference the product source tree. See what a plugin may reference.

The manifest

reeve-plugin.json travels with the artifact and is saved in the install directory. Field names are case-sensitive.

Field Required Notes
pluginTypeId yes Stable identity. It must equal the loaded factory's declared type id, or the instance start is refused. Install rejects leading or trailing whitespace (padded_plugin_type_id), an id containing : and the ids . and .. (reserved_storage_namespace, because the id is the plugin's object-storage namespace). The id system and the api/plugins route segments (types, instances, repositories, marketplace, config-flow, oauth, diagnostics) are reserved (reserved_plugin_type_id). reeve-plugindev validate refuses all of these too.
version yes Strict three-part semantic version.
displayName yes Shown to operators.
loader no native (default) or wasm.
dllAssetName yes (native) The entry assembly filename: a plain filename matching a strict pattern, with no path separators.
moduleAssetName yes (wasm) The module filename, ending in .wasm. A native manifest must not set it.
abiVersion yes (wasm) The WASM ABI the module targets. The host accepts major version 1 only. A native manifest must not set it.
capabilities no Strings naming what the plugin provides: input, output, notification, trigger or block. The preflight refuses a declared input, output or notification the factory's plugin type does not implement, and the marketplace filters on the list.
sha256 yes, unless builds Lowercase hex digest of the artifact.
builds no One entry per target framework, written by reeve-plugindev pack. See publishing builds.
signature no Base64 Ed25519 over the artifact hash. See distribution.
signedBy no Free-form publisher label.
permissions no See permissions.
compatibility no minAppVersion inclusive, maxAppVersion exclusive.
minBackendVersion no The minimum host version. Enforced, see compatibility. A value that is not a version is refused at install.
deployment no Sidecar workloads. See sidecar workloads.
discoveryMatchers no Prefill rules for discovery candidates.

Permissions

"permissions": ["http.outbound", { "code": "workloads.deploy", "required": true }],
"deviceTypes": ["Light", "Switch"],
"hosts": ["api.example.com", "*.example-cdn.com"]

deviceTypes and hosts sit at the manifest's root, beside permissions. An installed plugin is granted the manifest's hosts, and IPluginFactory.RequestedHosts mirrors that list.

  • Permission codes come from a closed list and match case-sensitively. An unknown code fails the parse.
  • deviceTypes are canonical stable names, parsed case-insensitively. Numeric strings and unknown names are rejected. Empty means all device types.
  • Empty hosts means deny-all outbound HTTP over the vended client. Declaring http.outbound without hosts is a validation error, and hosts without http.outbound are meaningless.
Host token Matches
api.example.com Exactly that host, any port
api.example.com:443 That host on that port
api.example.com:* That host on any port
*.example.com Exactly one DNS label
**.example.com One or more labels. ** must be the first label.
* (sole entry) Any host

A fixed entry is a DNS name in the host pattern grammar. A wildcard is allowed only as the first label, and a scheme or path is refused. An IP address (192.0.2.20, [2001:db8::20]:8443, ::ffff:192.0.2.20, or one written with non-ASCII digits) is refused as invalid_manifest by an install, an update, the index sync and reeve-plugindev pack. An address belongs to the owner's network, so request it through a config: token. A plugin already installed with such an entry keeps loading, but its next release is refused until it drops the entry.

A granted host may resolve to a private LAN address (RFC 1918 or fc00::/7) without an opt-in. Loopback, link-local, cloud metadata, carrier-grade NAT and multicast addresses are always refused at connect, whatever the grant. An installation can turn on Plugins:Egress:LanOnlyThroughOwnerAddresses, which refuses a LAN address reached through a fixed manifest name. Design a plugin that targets a local device to take its address from configuration through a config: token.

The vended client buffers at most 4 MiB of a response body by default (Plugins:Egress:MaxResponseContentBufferBytes). The cap applies only when the client itself buffers the body: GetStringAsync, GetByteArrayAsync, and GetAsync or SendAsync with the default HttpCompletionOption.ResponseContentRead fail with an HttpRequestException past it. After HttpCompletionOption.ResponseHeadersRead, or with GetStreamAsync, no read of the content is capped (including ReadAsStringAsync, ReadAsByteArrayAsync, LoadIntoBufferAsync and ReadFromJsonAsync), so a plugin that reads a body that way must bound how much it reads.

The host logs and traces every call through the vended client by method, host, status and duration, never by path, because the path may hold a credential. The path is recorded as a fingerprint. To get a readable record, name a route template on the request. The host keeps no text from the real path.

using var request = new HttpRequestMessage(HttpMethod.Post, webhookUrl);
request.Options.Set(PluginHttpRequestOptions.PathTemplate, "/api/webhooks/{id}/{token}");

Name the variable segments and never interpolate a value into the template (a template that repeats a long segment of the real path is discarded for the fingerprint). pack stamps the minBackendVersion that this option needs, so do not lower it by hand. WASM plugins cannot name a template, and their calls are always fingerprinted.

Hosts the owner types: config: tokens

A hosts entry config:{key}:{mode} requests "the host the owner typed into the config field named {key}". The owner grants the rule once per plugin type, and each instance reaches only the host its own config names. The host's rules are in Config host tokens.

The plugin reaches Request
A fixed service, such as a vendor cloud Its host name: api.example.com, *.example-cdn.com
A device or service whose address the owner enters: a camera, a broker, a bridge A config: token
Targets it finds itself, with no field the owner types into, such as a Matter controller using operational discovery "*"

A token may sit beside fixed hosts. "*" stands alone. Build the token from the same name the config schema uses, so a renamed field cannot leave the token behind:

public sealed class CameraSettings
{
    public string OnvifHost { get; init; } = "";
}

public IReadOnlyList<string> RequestedHosts =>
    [PluginHostTokens.FromConfig(nameof(CameraSettings.OnvifHost), PluginConfigHostMode.Host)];

public IReadOnlyCollection<PluginConfigField> ConfigurationSchema =>
[
    new(nameof(CameraSettings.OnvifHost), "ONVIF address", PluginConfigFieldType.Text,
        Required: true, Sensitive: false, DefaultValue: null, Description: "Host name or IP, optionally host:port"),
];

The manifest lists the same string:

"minBackendVersion": "1.0.0",
"permissions": ["http.outbound"],
"hosts": ["config:OnvifHost:host"]

Mode.

  • PluginConfigHostMode.Url reads an absolute URL (http://192.0.2.20:8899/onvif) and allows its host on the port it names. Without a port, it allows the default port of http, https, ws, wss, mqtt or mqtts. A URL of any other scheme, such as rtsp://, needs an explicit port, so say so in the field's description.
  • PluginConfigHostMode.Host reads a host name or IP (camera.local, 192.0.2.20:8899) and allows that host on the given port, or on any port when none is given. A separate port field needs no token.
  • In both modes an IPv4 address is accepted only as four decimal numbers without leading zeros. 192.000.002.020, 0x7f.1 or 127.1 is refused rather than read as another address.
  • A field is read in one mode. Two tokens that read it as both a URL and a host are refused.

Field. The token names exactly one Text or Password field of the instance ConfigurationSchema. A field that only a config-flow step declares does not count, and Select is refused. A Password field works: the host reads it decrypted, with a secret reference resolved when the instance starts.

No default. Give the field no DefaultValue. The host never fills a declared default into a field a token reads. A required field left empty is refused. An optional one left empty adds no host, and the plugin should report itself not configured.

Config flows. A flow's result counts for the field only when the owner typed that value. Ask for the address in a Text (or default-less Password) step field named exactly like the config field, and return the owner's value unchanged: do not add a scheme, a port or a trailing slash. An address picked from a Select does not count. To offer a discovered address, prefill a Text field with it for the owner to submit. Otherwise the flow saves nothing and tells the owner the plugin must ask for the address.

Where it applies. Only a running instance reaches the host. A config or repair flow, a workflow block and an alert subscriber get no host from a token. Do not probe the address in a flow. Let the instance report an unreachable address through its health or a repair issue.

Changes. The plugin cannot change the field. The settings facade refuses a write that changes it, with code settings.config-host-field. The owner edits it, and the edit restarts the instance on the new address.

Release. reeve-plugindev pack loads each build to check that its factory backs every token with one Text or Password field, the check the host runs at install (CLI reference). A release that changes its hosts, for example from "*" to a token, is held for the owner's approval instead of updating automatically.

Every client that IHttpEgress.CreateHttpClient vends runs the same guarded, allow-listed and logged pipeline. PluginHttpClientOptions takes a Timeout and TrustedCertificates.

MQTT: request mqtt.outbound

A plugin that talks to an MQTT broker requests mqtt.outbound, takes IMqttEgress from the bag, and connects to the broker the owner types into its config: a broker field with no default, requested as a config: token. Reeve ships no broker of its own, so a plugin must never rely on one.

"minBackendVersion": "1.0.0",
"permissions": ["mqtt.outbound"],
"hosts": ["config:Host:host"]
var egress = host.TryGet<IMqttEgress>()
    ?? throw new InvalidOperationException("mqtt.outbound is not granted.");
await using var connection = egress.CreateMqttConnection(new MqttConnectionOptions(
    Role: "bridge", Host: settings.Host, Port: settings.Port, Username: settings.Username, Password: settings.Password));

A request that names no broker is refused. WASM device-driver and mqtt-subscribe plugins and mqtt_publish take mqtt.outbound and read the broker from the instance config field Host.

Compatibility is enforced

compatibility.minAppVersion is inclusive and maxAppVersion exclusive, and a root-level minBackendVersion is read as the minimum. By default an out-of-range plugin is not loaded and the refusal is audited, naming the range. The operator can switch enforcement to warn, which loads the plugin and audits a warning instead. The check runs at install, at reload and at cold start. A plugin that declares no compatibility loads everywhere.

Your release pipeline reads the resolved plugin-abstractions package version out of the build's dependency file and stamps it as minBackendVersion. The contract is therefore mechanical, and bumping the SDK raises your floor.

Publishing builds for several runtimes: reeve-plugindev pack

A plugin project lists its frameworks in <TargetFrameworks>, plural even for one entry. reeve-plugindev pack reads the evaluated list (a value set in Directory.Build.props counts), runs dotnet publish once per framework, and writes the OCI layer and the manifest that oras push uploads:

reeve-plugindev pack --project src/MyPlugin/MyPlugin.csproj [--manifest <path>] [--out reeve-plugin-pack] \
    (--key <ed25519-private-key.pem> [--signed-by <label>] | --unsigned) [--version <semver>]

The tool is the Reeve.PluginDev dotnet tool, published on nuget.org at the SDK's version. It needs the .NET 11 and ASP.NET Core 11 runtimes. Install and CI steps, including the release recipe that fetches the key and checks the signed manifest, are in the CLI reference.

  • Per build. Each framework lands in <tfm>/ of the layer. The manifest carries builds: one entry per framework with targetFramework, the sha256 of the entry assembly, signature when a key is given, and minBackendVersion. That is the greater of the Reeve.PluginAbstractions version in that build's deps.json and the floor committed in your manifest. A single-framework project gets a list of one build. The top-level sha256, signature and minBackendVersion are not written.
  • What it strips. Everything on the host-shared list the Reeve.PluginAbstractions targets resolve for that build, everything reachable only through a host-shared package (libsodium for every RID, for instance), and any reeve-plugin.json your project copies to its output. It then checks that every assembly your IL references is still in the layer, and refuses a layer of 50 MB or more, the backend's extraction cap.
  • What it refuses.
    • a manifest with a compatibility block or loader: wasm (a plugin that needs a version ceiling stays on the flat manifest)
    • a build that references a host-shared assembly the build's own shared framework provides at a lower version (the error names the package that pulled it in)
    • a project with no Reeve.PluginAbstractions reference (a workflow-block-only plugin references it too), or an SDK version too old to ship a host-shared list
    • a version that is not SemVer, including the committed REPLACED_BY_CI
    • a non-empty --out that is not a previous pack output
    • a written manifest the backend's own manifest parser refuses
    • a config: host token that a build's factory does not back (the CLI reference lists each check)
  • Signing. One of --key and --unsigned is required. pack refuses to produce an unsigned manifest by accident, and --unsigned says so on stderr. --key signs each build and needs a signer label, --signed-by or a committed signedBy. --signed-by writes the manifest's signedBy label (a committed one is kept otherwise). The label is not part of the signed payload, but the host matches it against the label of the trusted key and flags a release whose label changed.
  • Version. --version, else the GITHUB_REF_NAME environment variable on a tag build (GITHUB_REF_TYPE is tag), else the manifest's version. A leading path (cast/) and a leading v are removed. The result is stamped as the assembly Version and InformationalVersion.
  • Reproducible. The layer's entries are sorted with a fixed time and owner, so one commit packs to one digest.

Target framework and runtime moves

The SDK packages carry one framework, net11.0, the host's. A plugin targets net11.0, as the templates do, and compiles with runtime async (runtime-async=on in Features), as the host does.

When Reeve moves to a newer runtime, the same builds list carries the move. List both frameworks in <TargetFrameworks>, put code that needs the new APIs behind #if NET{N+1}_0_OR_GREATER, and release. pack writes both builds, and a host on N loads the first and a host on N+1 the second. Drop netN.0 once you no longer want to serve hosts on that runtime. A host still on it then refuses the release as needing a newer .NET runtime and keeps the version it runs. The templates write <TargetFrameworks> and carry no pin of Microsoft.Extensions.Logging.Abstractions, because the framework reference of Reeve.PluginAbstractions provides it at each framework's own version. If a dependency pulls a newer one than a framework provides, pack names that package and you drop it or pin it for that framework.

Factory, registration and lifecycle

An assembly that declares factories but no registration contributes nothing: the install is refused and the type never loads. A factory reaches the host only through a registration. An assembly with no factory types at all is unaffected, so a block-only or trigger-only plugin ships its own registration kind and installs normally.

The factory declares the plugin type id, display name, description, category and the flat configuration schema, and creates instances given the instance id, the persisted configuration and the host facade.

public sealed class MyPluginFactory : IPluginFactory
{
    public string PluginTypeId => "acme.thermostat";
    public string DisplayName  => "Acme Thermostat";
    public string Description  => "Controls Acme thermostats over the local network.";
    public PluginCategory Category => PluginCategory.InputOutput;

    public IReadOnlyCollection<PluginConfigField> ConfigurationSchema =>
    [
        new("Host",   "Hostname", PluginConfigFieldType.Text,     Required: true, Sensitive: false, DefaultValue: null, Description: null),
        new("ApiKey", "API key",  PluginConfigFieldType.Password, Required: true, Sensitive: true,  DefaultValue: null, Description: null),
    ];

    public IReevePlugin Create(Guid instanceId,
                               IReadOnlyDictionary<string, string> config,
                               IPluginHostServices host) => new MyPlugin(instanceId, config, host);
}

Declare PluginTypeId as a string literal or a const. Pre-flight (on reload and in reeve-plugindev validate) compares it with the manifest's pluginTypeId, case-insensitively, and refuses a mismatch with preflight_type_mismatch. A fresh install is refused when the instance starts. A computed value or an auto-property initialiser cannot be read without running the plugin, so pre-flight skips the comparison and logs that it did. The start-time check still refuses a mismatch.

Field types are text, integer, boolean, password, large text and select. Mark every secret Sensitive: sensitive values are encrypted at rest, masked in logs and decrypted when read back. The host withholds schema-declared sensitive fields from the guest config view. A field whose stored value is an encrypted envelope is sensitive even when this replica does not know the plugin type. It is masked on read, redacted in diagnostics, kept by a save that returns the mask, and withheld from the guest.

Implement start, stop, health and async disposal. StartAsync must observe its cancellation token. The host cancels it when an operator's edit restarts the instance, when the instance is stopped and when the host shuts down. A start that honours it returns promptly and the host discards it. One that ignores it keeps the instance's lifecycle busy until it returns, or for at most 30 s, after which the host abandons the call and faults the instance. StopAsync and DisposeAsync share one 30 s deadline the same way. At the deadline the host cancels the call's token, and it disposes the plugin only after the abandoned call returns. A call that never returns keeps that copy and everything it holds (ports, serial or radio adapters, MQTT client ids) until the backend restarts, and the instance cannot be started again until then. Pass the token to every connection attempt and await, and do not start background work after it fires.

Health status Meaning
Healthy Running normally. On a multi-replica deployment a non-owning follower is healthy with a follower annotation.
Degraded Running with reduced function: reconnecting, one facet missing.
Unhealthy A known error the operator can act on.
NotConfigured Required configuration is missing.
Unknown Registered but not running.
Faulted Host-set only. Threw during start.

HTTP routes

A native plugin serves HTTP by implementing IPluginRoutes on the plugin instance. The host calls MapRoutes after StartAsync returns and hands it an IPluginRouteBuilder. Each Map describes one route with a pattern relative to the instance prefix api/plugin/{instanceId}, its HTTP methods, a RequestDelegate and its access rules.

public sealed class MyPlugin : IReevePlugin, IPluginRoutes
{
    public void MapRoutes(IPluginRouteBuilder routes)
    {
        routes.Map("status", ["GET"], context => context.Response.WriteAsJsonAsync(_status));
        routes.Map("devices/{id}/name", ["PUT"], async context =>
        {
            var id = (string)context.Request.RouteValues["id"]!;
            var body = await context.Request.ReadFromJsonAsync<RenameRequest>();
            await RenameAsync(id, body!.Name);
        }, new PluginRouteOptions { RequiredPermission = "devices.manage" });
    }
}

The first route answers GET /api/plugin/<instance id>/status, with the id in the "D" GUID format.

Access. Without options a route requires a signed-in caller with an access token. AllowAnonymous serves any caller. RequiredPermission names a permission code the host guards its own routes with, and the authorization policy of that name checks it. The accepted codes are:

  • automations.manage, scenes.manage, helpers.manage
  • devices.view, devices.control, devices.manage
  • integrations.manage, secrets.bind, users.manage, home.manage
  • locations.view (which home.manage also grants), geofences.view, geofences.manage
  • utility.view, utility.manage
  • dashboards.view, dashboards.edit, dashboards.manage
  • notifications.send, audit.view
  • rooms.manage
  • blueprints.repositories.manage, blueprints.install, widgets.repositories.manage, widgets.install
  • cameras.media.view, cameras.media.manage, babymonitor.manage, workloads.approve

Any other code, such as rooms.view or scenes.control, which the host checks only inside its own handlers, is refused. The host keeps plugin routes out of the API description.

Writes. The host waits for the acknowledgement of the request's writes when the handler starts the response, or when the handler returns if it has not started it. Commit before writing, because a write made after the response started is not awaited. A commit the host refuses throws InvalidOperationException. When the host refuses or cannot confirm the write, the answer is the one a host route gets:

  • A handler that lets that exception propagate gets the error envelope: 503 with Retry-After and write_refused.
  • A handler that returns a status below 400 without writing a body gets that envelope, or 202 and write_unconfirmed, in place of the status and headers it set.
  • A handler that returns a status below 400 and has written a body keeps the body under 503 with Retry-After or 202. Its client reads the status, not the body.
  • A status of 400 or above stays. An unconfirmed write adds Reeve-Replication: unconfirmed to it.

Input. A handler reads route values from HttpRequest.RouteValues and a body with ReadFromJsonAsync<T>. There is no parameter binding.

Services. The handler's HttpContext is its own, and its RequestServices resolve no host service, during the handler and in any callback it registers (OnStarting, OnCompleted). They answer only what the ASP.NET Core helpers need, so WriteAsJsonAsync, ReadFromJsonAsync and an IResult you execute yourself (await Results.Ok(value).ExecuteAsync(context)) work, with the default web JSON options. Every other type, including the service provider, scope factory and keyed services, resolves to null or throws. The authentication results (Results.Forbid, Challenge, SignIn, SignOut, HttpContext.ForbidAsync) and a file result by virtual path throw, so set the status code instead. Reach the host through the instance's IPluginHostServices, and log through its Logger.

What a handler may rely on. The request (method, path, route values, query, headers and body), the response, the caller's claims in HttpContext.User, and HttpContext.RequestAborted. Connection details, request features and items that host middleware sets are not part of the contract, and Items starts empty. Do not replace Request.Body or Response.Body: the replacement lives only on the handler's context, so the host neither reads nor tracks what is written through it.

Refused route sets. The host refuses the whole set, logs an error and keeps the instance running without routes when MapRoutes throws or when a route:

  • has a rooted pattern (/… or ~/…), a . or .. segment, a pattern that does not parse, or a constraint the host does not know
  • has no handler, no method, or a method that is not an HTTP token
  • requires a permission the host has no policy for, or both allows anonymous callers and requires a permission

Every start maps the routes again and replaces the instance's set, so a reload or a configuration edit serves the new code at once. While the instance runs, a path or method under its prefix that the set does not map answers 404, a dropped route included. While it is stopped or reloading, every path under its prefix answers 503 if the instance has served routes on this replica since the host started, and 404 otherwise. A request routed just before a stop, a reload or a delete and handled after it gets that answer too, and never reaches the replaced instance's code.

Using the host facade

Fetch a gated capability from the bag and degrade when it is absent. Never catch an exception to discover a denial. The baseline capabilities are always present and need no declaration: logger, audit sink, own-device event sink, private memory cache, issue registry, instance-scoped data protector, replica id and connection-ownership lease.

IOutputPluginLocator is present in every facade and returns only the running output instances of your own plugin type: the instance's type, or the type your manifest declares for a type-level part such as an alert subscriber. A second plugin type exported from the same assembly is another type and is not returned, and the parts of an assembly installed without a manifest belong to its file name, so their locator returns nothing. To reach another plugin type, use IPeerPluginInvoke, which the plugins.invoke grant gates.

IHostTlsTrust is also baseline. A plugin that opens its own TLS connection passes its ValidationCallback (or IsTrusted, for a client that takes a predicate), so the connection trusts the system roots and then the operator's Tls__TrustedCaCertificates list. A wrong host name is never rescued by the list. The http.outbound and mqtt.outbound clients already apply it.

Connection ownership

Take a lease from IPluginConnectionOwnership before you open a long-lived connection to a resource, and dispose it when the connection closes.

A null lease means "not now", never "never": a peer owns the resource, or this replica is not serving (starting, fenced or draining). An exception from TryAcquireAsync is transient as well, because the mutex lets a database error propagate. A plugin retries on a bounded interval, and again after Lost fires or its connection is evicted. The host starts your instance only after the replica first serves, but a fence or a drain later on refuses leases again, and Lost fires then. Close the connection first, dispose the lease, and go back to acquiring. The connection and the retry loop belong to the plugin, and the host does not call you when a lease becomes free.

A command or resync can reach your instance on a replica that does not hold the lease. Pass it to the holder instead of opening a second connection:

public Task SendDeviceCommandAsync(string deviceSourceId, DeviceCommand command, CancellationToken ct) =>
    lease is not null
        ? SendOverMyConnectionAsync(deviceSourceId, command, ct)
        : ownership.SendDeviceCommandToHolderAsync(LeaseResourceFor(deviceSourceId), deviceSourceId, command, ct);

SendDeviceCommandToHolderAsync (typed and raw) and TriggerResyncOnHolderAsync look up the replica that holds the lease on the resource id, send it the call, and run your own instance's IInputPlugin method there. The plugin type and instance are the caller's own, so a plugin reaches only its own instance's leases. When the calling replica holds the lease itself, the call runs locally without a hop and the plugin's own exception comes back unchanged. Otherwise the outcome is one of these exceptions:

Exception Meaning Retry
PluginHolderUnavailableException (Reason: NoHolder, NotTaken, HolderMoved, AlreadyForwarded) The call ran nowhere Safe, also for a command that is not idempotent
PluginHolderCallUnconfirmedException The holder may have run it (no answer in time, the relay failed, or the answer could not be read) Only an idempotent command
PluginHolderCallFailedException (ReasonCode: not-supported, invalid-argument, timeout, forwarded-again, error) The holder answered with a failure: your plugin threw there, or the holder failed while handling it As for a local failure
OperationCanceledException Your token was cancelled. The call may have run Only an idempotent command

PluginHolderCallUnconfirmedException derives from TimeoutException, so a command log that records timeouts records an unconfirmed forward as timed out, not failed. No message text crosses replicas: the holder logs the plugin's exception and answers its reason code. The call does not wait for a new holder, so a button press during a failover fails at once. A holder that cannot read the call, because it carries a field or value that holder's host does not know, does not take it, and the call fails as NotTaken. The answer budget is the workload gateway's command timeout, Workloads:Gateway:CommandTimeoutSeconds, capped at Cluster:ActionTimeBudget minus 2 s.

One hop per async flow. While the holder runs a forwarded call, any holder member called on the same async flow throws PluginHolderUnavailableException with AlreadyForwarded. The mark flows with the async context, so work your plugin starts during a forwarded call (a Task.Run, a timer, a cancellation callback) inherits it. Start such work from your own loops, not from inside the command. Work handed to a loop that was already running does not carry the mark, so a connection worker that forwards a queued command again sends a second hop. Forward only from the method the host called. When your own method calls a holder member after it already acted, an AlreadyForwarded refusal does not mean nothing ran.

Reporting plugin issues

RaiseIssueAsync(code, severity, message, ...) and ClearIssueAsync(code, ...) report one issue per plugin instance and code. Use IssueReport to scope an issue to a device or node and attach a documentation link. The subject becomes part of the alert's identity, so clear the same subject with ClearIssueAsync(code, subject, cancellationToken). A code the host maps to a core alert kind (such as plugin.secret_unreadable, plugin.roll_incomplete or workload.diagnostic) has a fixed identity: a non-blank subject on it, raised or cleared, throws ArgumentException. A DocsUrl must be an absolute HTTPS URL, and other links are rejected with ArgumentException.

await context.HostServices.IssueRegistry.RaiseIssueAsync(
    new IssueReport
    {
        Code = "node_unavailable",
        Severity = IssueSeverity.Error,
        Message = "Node is unavailable.",
        Subject = nodeId,
        DocsUrl = "https://docs.example.test/node-unavailable",
    }, cancellationToken);
await context.HostServices.IssueRegistry.ClearIssueAsync("node_unavailable", nodeId, cancellationToken);

Replica id, cache and released resources

The replica id names the host process you run in. It differs between replicas, is stable for that process's lifetime, and is the same value the host puts in this process's MQTT client id. Set REPLICA_ID (typically the pod name) if you want to recognise it in logs. It is not your plugin instance id, which reaches you as the instanceId argument of Create and is identical on every replica. Tell replicas apart with the replica id, and use the instance id for anything that must agree across replicas, such as a shared-subscription group name.

The private memory cache holds at most Plugins:CacheMaxEntries entries (10,000 by default). An entry that states no Size counts as 1. Set Size to count an entry as more, in the same unit. A Set past the limit stores nothing and a later read is a miss, so treat the cache as a hint, never as the only copy.

The host releases the cache, the HTTP handler behind the clients you were vended, MQTT connections and device-state feed subscriptions when the instance stops and when a config-flow or action-flow step's SubmitAsync returns. Never keep any of those past that call, including from a background task you start. The audit sink, logger, issue registry, data protector and own-device event sink hold nothing to release and stay usable, so a background run may keep writing audit rows through context.HostServices.AuditSink. A client you were vended also stops working once its facade is released, for instance after a grant change rebuilds it.

The facade has no service provider, scope factory, raw data-protection provider, raw HTTP client factory or raw distributed-cache connection. Outbound HTTP goes through the vended, allowlisted client. The distributed cache is a narrow surface with a per-instance key namespace, string values and bounded expiry, and no compare-and-swap, so do not build a leader election on it.

Reporting device state

The framework stamps every write with its own clock, so you do not have to order or space out calls. Two things are worth knowing.

Timestamps. The canonical device's own last-update timestamp is observation metadata, not a write clock. It drives freshness labelling, orders current state across replicas, and decides the telemetry row a reading becomes. Every replica that hears one reading must pass the same time, so each derives the same row.

  • Pass the device's own clock when the producer sends one.
  • Pass the receipt time only for single-delivery ingest, where exactly one replica hears each message (a lease-gated subscription, a connection only the lease holder opens, a shared subscription). A relayed reading, such as a BLE advertisement a proxy forwards, is timed when the host received the relay, never when the peripheral broadcast, so it needs that same guarantee.
  • Never stamp a replica's clock on a broadcast path. Each replica would pass a different time for the same message and store its own row. Leave it null there, and the host claims the copy across replicas.
  • A WASM driver runs on every replica, so it must not set lastUpdateUtc from its own clock, or each replica builds a different fire key and the automation fires once per replica. Omit it, and the key is built from the canonical values, so what the driver emits must depend on the inbound message alone.

Ordering. State updates are buffered and availability is written immediately, so an availability verdict can reach the database before the state update it accompanied. Both land, and the order is unspecified.

Reported keys. CanonicalDevice.ReportedKeys (init-only) carries the canonical capability keys the arriving message carried, as opposed to values your driver re-sends from its cache (a merged device's other topics, a connect dump, a heartbeat). It decides one thing: a metric a DeltaUsage meter sums is stored even when equal to the last one, but only when the message reported it. Leave it null and every series is change-only, so equal consecutive deltas are one row. It is ingest metadata, never saved and never sent to a client. A broker replay reports nothing: MqttInboundMessage.Retain is true for a retained delivery, and the initial state a source dumps on connect or reconnect is the same re-sent cache, so name no keys for either. A WASM driver cannot follow that rule, because its guest ABI carries the topic and payload only. A retained delivery is indistinguishable there, and every summed series stays change-only.

Availability. A state update already implies online. If a device is reachable but has nothing new to say, publish state and leave availability alone. Report offline only when the source cannot be reached.

Session plugins. A session plugin's devices go Offline when its session is gone. A workload that declares health.mode: adapter-session means the host records every device of the instance Offline once the session has been absent for 180 s. Only your driver's reports lift that, or a start of the plugin while the session is up for the devices that session has reported. The snapshot you send on every connect must therefore report each device you know, from a real read, and a device you leave out stays Offline until you report it. Only a discovery or a health write in the current session counts as reported. A state-only report that changes no health does not, so that device stays Offline after a start until its next report. Report a device's health only from the session: a report made while it is absent clears the mark and the host sets it again on its next tick.

State feed.

  • Each handler you subscribe to the device-state or typed-state feed of IDeviceReadAccess gets its own queue of 256 snapshots and runs off the host's ingest path, one snapshot at a time, each device source's in order. When a handler falls behind and its queue is full, a newer snapshot of a device source replaces the one of that source still queued, so the handler loses only intermediate states, never a source's latest. The host logs a warning about it at most once a minute. The queue is bounded by count, not by size, and past 256 it holds at most one snapshot per device source. The token a handler receives is cancelled when its subscription is released. A plugin subscribed to both feeds gets no ordering between them.
  • The typed snapshot pushed to consumers of the state feed is a flat camelCase property map whose key names are a frozen contract: state for gang index 0 and state_l{index+1} beyond it, following the Zigbee2MQTT convention. Nothing type-checks them, so a rename breaks every consumer silently. Unmapped properties fill the gaps, re-typed to their declared JSON value kind and never overwriting a key a typed arm already set.

Reporting camera motion

Motion on a camera is an event, not a state, and the host decides when a stretch of it starts and ends. Send camera.motionDetected (DeviceEventTypeTokens.CameraMotionDetected) through DeviceEvents.DeviceEventOccurredAsync when motion starts and again at least every CameraMotionReporting.RepeatEvery (2 s) while it lasts. When it ends, or when you can no longer tell (your detector stopped, your broker dropped, you are shutting down), stop sending. There is no "cleared" event. The camera's motion ends CameraMotionReporting.Hold (6 s) after the last heartbeat from any source, which tolerates two lost repeats.

  • A plugin that does not own the camera sends it through devices.events.write, like any other detection. Nothing reads which plugin sent it, and heartbeats from several sources extend one stretch.
  • Only a device of type Camera accepts it. A heartbeat is never published or stored. It goes to the host's motion gate.
  • camera.motionStarted and camera.motionStopped are the host's alone, one pair per stretch with the stretch id as EventId. Both event paths refuse them from a plugin. Automations, the camera's history, the dashboard badge and the baby monitor follow them.
  • Pass the time the detector saw the motion as the observed-at when you have one. A heartbeat more than the hold behind its arrival is dropped.
  • The camera's owner state camera.motion stays what the owner says. A camera whose plugin reports motion as state needs no heartbeat code, because the host turns that state into heartbeats through the host adapter.
  • Heartbeats are dropped while Redis is unreachable, so no camera has motion then.

Write as if the plugin ran in its own process

Write a native plugin so that it does not depend on sharing a process with the host. The unit is one package. Every instance of the package and its type-level parts (trigger and workflow-block registrations, alert subscribers, config, repair and action flows) share it, and nothing else is guaranteed to share it, neither the host nor another package. Do not rely on static state either way: an instance loaded from its assembly runs in a load context of its own, while a built-in instance, or one the host falls back to the boot factory for, shares the boot context with the type-level parts. Keep shared state behind the host facade or in your storage.

  • Values in object? bags are JSON-shaped: a string, a boolean, a number, null or a JsonElement. That covers flow answers and ConfigFlowResult.Finish, trigger fire payloads, audit and issue metadata, diagnostics, discovery metadata and adapter message properties. The host already hands flow answers over as a string or a JsonElement, never as the CLR type a step's field suggests.
  • Only the SDK's own subtypes cross. Report CanonicalDevice and TypedDiscoveredDevice through the records Reeve.Contracts and the SDK define, never a subclass of your own. The host drops a state whose CanonicalDevice is not a Reeve.Contracts type and logs why. A discovered device of an unknown subtype is stored as Unknown.
  • A completed IDeviceEventSink call means accepted, not stored. A state change completes once the host has buffered it. The host applies one source's states in order and, under ingest pressure, keeps the latest and may drop the ones before it. The other calls complete once applied today, but do not depend on that.

Adapter frames on every replica

A plugin that runs a sidecar receives the sidecar's frames through two optional interfaces on the plugin object.

  • IAdapterDataFrameIngestor claims the DATA kinds private to your plugin. Without it they are discarded. The sidecar sends them with the session client's PublishAsync(payload, dataKind, typeInfo) (publishData in Node). That refuses a frame above the gateway's 1 MiB cap and, like every publish method of the client, throws when the payload cannot be serialized. The frames are best-effort, so a kind that holds current state is re-published from the observer's OnSnapshotSent.
  • IAdapterTelemetryIngestor runs your own parse of the typed discovered-device and device-state frames.

Both are called only on the replica holding the adapter's session, from its receive loop, and must not throw and must not block.

Every other replica's copy of your plugin hears nothing. If your plugin builds state from those frames (a registry of devices, an attribute cache, the key a peer announced), the other replicas' copies do not have it. Observation replication hands them the frames you ask for. It runs when Workloads:ObservationReplication:Enabled is true. When unset, it follows Coordination:Clustered.

Opting in: IAdapterObservationConsumer

ObservedDataKinds lists your private DATA kinds to replicate, and ObservedTelemetry the well-known frames (State, Discovered, Snapshot), each a separate opt-in. Both are read once per session and must be constant for a plugin version. A replica whose plugin version opts into something else reports the instance as not replicated. A kind you do not list never leaves the owner's process, so never list a correlated reply or a frame carrying a secret, such as a key-value store, credentials or signalling.

ObserveAsync is state application only. It receives the frames on every replica except the owner, in stream order, never concurrently with this instance's ingestor or observer.

  • It must not call a facade that causes an effect (device events, commands, replies to the adapter), because the owner's ingestor already did, once.
  • It must not read the local clock. Time-derived state uses ReceivedAtUtc, the owner's receive time, which is the same on every replica (and is not the device's time).
  • It must be idempotent. After a checkpoint restore, frames the checkpoint already contains may be delivered again.

Extract the state application from your ingestor and call it from both. The ingestor applies state and then acts, and the observer applies state and stops. Two copies drift, and the replicas then disagree with the owner silently.

An observer that throws has that one frame skipped and logged, and it is reported as a gap, ObserverFailed: your state now lacks a frame, so this replica's view of the instance reads incomplete until a checkpoint holding the frame is restored. A slow one fills its queue, which is reported as ReaderOverflow.

What a gap means

OnObservationGapAsync says that frames may be missing for that instance on this replica. It never says which. The reason tells an operator why. For your code every reason means the same: until a checkpoint covering the gap is restored, do not treat your state for that instance as complete. A gap can arrive on the owner too, as OwnerIncomplete: the session started cold, or took over from one that ended unclean, and frames it never received are lost. A plugin whose adapter re-announces its state only on request should re-read it then.

Checkpoints: IAdapterObservationCheckpointSource

CreateCheckpointAsync runs on the owner after a handover, every CheckpointIntervalSeconds when something new was ingested, and when a replica asks. Return your state for the instance as JSON, and Complete = true only if you vouch that it is whole. The owner's own incompleteness overrides your claim. The host records its position before calling you, so the checkpoint must contain everything ingested up to then, and it may contain more. Serialise it against your own state application. Never put a secret in it, because checkpoints are stored in Redis. One larger than half the instance's share is rejected. After OwnerIncomplete, the owner stays incomplete until you return Complete = true from a checkpoint created after that notification.

RestoreCheckpointAsync replaces this replica's state for the instance. It is never called while this process holds a live session for the instance, nor concurrently with its ingestor or observer, and replay continues from the checkpoint's position. It has the handover drain timeout to return. Past it the token is cancelled, the restore counts as failed and is retried with back-off once your call returns, and the instance's observations wait until then, so honour the token.

Without a checkpoint source, a gap on a replica never closes: its view stays incomplete, and your command paths stay on their fallback.

Proving your observer: reeve-plugindev observe replay

The two rules above (apply state and stop, and share the code with the ingestor) are discipline, and nothing in the host enforces them. The kit does, against a Redis of its own:

reeve-plugindev observe replay --plugin <your.dll> --frames <frames.jsonl> --redis <host:port> \
                               [--instance <guid>] [--timeout-seconds 30] \
                               [--batch-interval-ms 5] [--poll-ms 20] [--allow-shared-redis]

Never point it at a Redis anything else is using. The replay is not a simulation. It writes real observation entries under the real keys, adds its instance to the instances set (which shrinks every real instance's share, so the next append trims real history), and deletes its instance's stream, cursor and checkpoint when it ends. With --instance naming a real instance it writes into and then wipes that instance's state. It therefore refuses a Redis that already holds any observation key or instance. --allow-shared-redis overrides the refusal, and you own what happens next. Start a throwaway container and give it that.

It loads your plugin twice, as an owner and a follower, each with a host facade of its own, like two replicas holding two copies. The frames go through the owner's IngestAdapterDataFrameAsync and are appended by the host's own writer. The follower's ObserveAsync is called by the host's own reader reading them back out of Redis. The run fails when any of these happens:

  • The follower called a facade member that causes an effect (a device event, a command, a reply to the adapter, an issue, an audit row, a checkpoint hint). The verdict names the member. The refusal is recorded on the facade side as the call is made, so catching the exception in your observer does not hide it. The owner's facade allows the same calls, because the ingestor is meant to act.
  • The follower's state differs from the owner's. Both sides' CreateCheckpointAsync JSON is compared after the same frames, as data (property order and whitespace do not count), and the first differing path is printed with what each side had there.
  • The follower never received what the owner assigned within --timeout-seconds, or its observer threw on a frame instead of applying it. Every replicated frame has to have been observed before the run can pass.
  • The owner's checkpoint is empty, or the same before and after the replay, or the follower's is empty. A CreateCheckpointAsync returning a constant compares equal to itself on every run, so nothing it passes means anything. The two sides are not compared at all once one of these holds.

Exit 0 passes, 3 is one of the failures above, and 2 is a usage error. These are usage errors rather than verdicts, because a run that hits them certifies nothing:

  • A plugin with no IAdapterObservationCheckpointSource. Without one there is no state to compare, and nothing for a replica to close a gap with.
  • A frames file holding no kind the plugin replicates. A mistyped kind is the usual cause. The refusal prints the kinds the plugin opted into beside the kinds in the file.
  • Neither copy publishing a checkpoint at all. A source that answers null on both sides is the same hole as having no source. An owner that publishes something the follower cannot match is the verdict above, not this.

The frames file is JSON lines, one frame per line. A kind your plugin does not replicate reaches the owner's ingestor and goes no further, exactly as the gateway would treat it:

{"kind":"sensorReading","messageId":"m1","receivedAtMs":1726531200001,"payload":{"sensor":"kitchen","value":21}}

An ingestor that throws on a frame is logged as a warning and the replay carries on, as the gateway keeps a session whose sink threw. The frame is still replicated, so if your ingestor threw before applying it, the follower's state differs from the owner's and the run fails on that.

The replay holds a replica to the owner, so it catches a replica that drifts. It cannot tell whether the owner itself is whole: if your ingestor builds the wrong state, a follower that builds the same wrong state passes. Completeness still rests on what your checkpoint vouches for.

Reading freshness: IWorkloadObservationView

Fetch it with TryGet<IWorkloadObservationView>(). It comes with workloads.command, answers only for your own workload instances, and never throws. Anything it cannot answer is Unavailable.

Availability Meaning
Local This replica holds the session, so your own state is the owner's. Complete is the owner's completeness.
Replicated State arrives through replication. Complete, BehindOwner and OwnerPaused say how far to trust it. It stays Replicated while the adapter is offline.
Unavailable Nothing is replicated to this replica: one replica, replication off, a failed Redis read, an owner not replicating, or a plugin version mismatch. Behave exactly as a non-owner did without replication.

On a command path that translates against state, call CatchUpAsync with a short timeout. It waits until this replica has applied everything the owner had assigned when the call started. Use your state only when the result is Local, or Replicated with Complete and not OwnerPaused. Otherwise read what you translate against, as you would without replication. GetFreshnessAsync answers without waiting. RequestCheckpointAsync hints the owner to publish a checkpoint. It is lossy and rate-limited, so calling it in a loop costs one write.

Writing a canonical driver

If your plugin reports device state, it must translate onto the canonical model in both directions.

The canonical vocabulary (device types, capabilities, value kinds, enum tokens, units) is a closed, core-owned set. A plugin maps onto it and cannot invent a capability. Adding a new one is a core change. A vendor field with no canonical capability becomes a structured unmapped property, usable from workflows and never from typed features. Unmapped properties are read-only in practice, because a raw write is validated against capability rows that only the canonical descriptor creates.

A driver has three responsibilities, each a thin, testable translation:

  1. State. Parse the vendor payload into a canonical device record with canonical keys, units and enum tokens, and push it through the typed event sink along with the raw vendor payload.
  2. Commands. Declare typed command support and encode canonical intent onto the vendor wire.
  3. Availability. Declare a per-instance capability availability descriptor: presence, controllability, allowed tokens, unit, minimum, maximum and step.

CanonicalAvailability.For(deviceType) builds the per-instance capability descriptor. Declare a channel capability with Channels(key, controllable, channelDeclarations) and provide at least one ChannelDeclaration. An empty list is invalid, and the host rejects descriptors built without channel records.

Capability declaration is truth-only. The UI renders strictly from the descriptor. A capability absent from it is neither shown nor controllable even if the typed member has a value, and presence never comes from whether a value is null. Minimum, maximum and step are per instance and enforced server-side on commands. A triple outside the catalog range is silently dropped by the builder. Option metadata (CapabilityOption, passed to OpenEnum or TokenSet) only annotates tokens already in the option list. Metadata the builder cannot accept is dropped and named in DroppedOptionMetadata, and the capability itself is always kept. A non-controllable capability is exposed read-only, and its command handler returns an explicit unsupported status. It never silently does nothing.

The authoring helper package holds the reusable coercions (vendor-to-canonical value maps, enum token maps, unit converters, typed device builders, payload readers), so a driver stays thin.

CanonicalDeviceBuilder starts a typed record builder: Light, Outlet, Climate, MediaPlayer and Sensor. Each takes the device id, source id and friendly name. The base adds Online/Offline, LastUpdated and AddUnmapped, and Build() returns the real record. A builder takes canonical values only, so run a vendor reading through the converters first:

var ups = CanonicalDeviceBuilder.Sensor(deviceId, sourceId, "Rack UPS")
    .WithPower(
        watts: PowerMetricConverters.PowerToWatts(realPower, realPowerUnit),
        volts: PowerMetricConverters.VoltageToVolts(inputVoltage, "V"),
        amperes: PowerMetricConverters.CurrentToAmperes(outputCurrent, "A"))
    .WithBattery(levelPercent: batteryCharge, low: status.Contains("LB"))
    .AddUnmapped(new CanonicalUnmappedProperty("ups.status", UnmappedPropertyValueType.String, status))
    .Build();

SensorDeviceBuilder has one method per SensorDevice reading, named after the member, with the parameter named after its canonical unit (WithTemperature(celsius), WithCo2(partsPerMillion), WithRadon(becquerelsPerCubicMeter)). The energy readings are grouped as WithPower(watts, wattHours, volts, amperes), as on the outlet builder, and the battery as WithBattery(levelPercent, low). A null argument omits that reading.

See devices for the canonical model, and integrations for the driver traps that cost the most to rediscover.

When an operator removes your device sources

A plugin that must act when an operator removes a device in Reeve (release it on the vendor side, close a pairing, delete a credential) implements IDeviceSourceRemovalHandler (Reeve.PluginAbstractions.Devices):

public sealed class MyPlugin : IInputPlugin, IDeviceSourceRemovalHandler
{
    public string? DescribeSourceRemoval(string sourceId) =>
        "The device also leaves the bridge and must be paired again to return.";

    public async Task OnSourcesRemovedAsync(DeviceSourcesRemovedNotice notice, CancellationToken ct)
    {
        foreach (var node in notice.RemovedSourceIds.Select(NodeOf).Distinct())
            if (!notice.RemainingSourceIds.Select(NodeOf).Contains(node))
                await ReleaseAsync(node, ct);   // no source of this node is left in Reeve
    }
}

The host calls it after an operator's removal of a source or of a whole logical device has committed, on the replica that served the request. Every replica runs every instance of your plugin, so reach a connection that lives on another replica the way your other commands do. One call per instance carries all of its sources in that removal. RemainingSourceIds is every source the instance still has, read after the commit.

The host does not call it when the source went away because your plugin reported it (IDeviceEventSink.DeviceRemovedAsync), a merge or a detach moved it, or the removal was refused or rolled back. A source removed together with its plugin instance is not announced either. WASM plugins do not get the hook.

The call is best-effort and happens once. The host does not wait for the call, bounds it to 30 seconds, logs a failure and never retries. A replica that stops between the commit and the call loses the notice. Make the handler idempotent and treat a failure as "the device stays on the vendor side": log it, and let the source reappearing, if your plugin reports it again, be the operator's cue to retry. There is no persisted queue.

DescribeSourceRemoval returns what removing that source also does beyond deleting it in Reeve, or null. The removal dialogs of the physical device and of the logical device fetch it when they open (not with the device detail) and show it under your plugin's name as plain text, cut at 500 characters. The logical device's dialog shows a notice once per plugin, however many instances or sources repeat it. The host asks once per source, concurrently, and gives each call 2 seconds. An answer that is late, an exception (a cancellation included) or null shows nothing for that source, and the removal itself is never held up. Keep the method cheap and read local state only.

Multi-step configuration

The multi-step flow is opt-in: implement the config-flow factory and return a non-null first step. Returning null falls back to the flat form, and the plugin metadata endpoint reports whether the flow is supported, so the frontend dispatches without per-plugin branching.

Step kinds are form, informational message, polling, validate, OAuth, and client value (see client-gated flows). A submit returns one of: next step, finish with the final configuration, retry with a correctable message, error, or poll again.

public ConfigFlowStep? StartStep => ConfigFlowStep.Form("credentials", "Bridge address",
    [new("Host", "Hostname", PluginConfigFieldType.Text, Required: true, Sensitive: false, DefaultValue: null, Description: null)]);

public async Task<ConfigFlowResult> SubmitAsync(string stepId,
    IReadOnlyDictionary<string, object?> answers,
    ConfigFlowContext context, CancellationToken ct) => stepId switch
{
    "credentials" => await ProbeAsync(answers, context, ct),   // Retry or NextStep
    "pairing"     => new ConfigFlowResult.Poll("pairing", 2000),
    _             => new ConfigFlowResult.Error($"Unknown step '{stepId}'."),
};

Rules that bite:

  • The issue registry is a no-op during a flow. Surface a correctable error as a retry result and a fatal one as an error result.
  • The host facade during a flow is built from the requested set, so a setup wizard can test a connection with capabilities the operator is about to grant, and never beyond what the manifest declared. Steady-state and repair flows use the granted set.
  • Union the sensitive-field set from the per-step declarations, not from the static schema.
  • Prior-step answers are decrypted only for the duration of a submit call and are never saved in plaintext. Flow state carries a sliding expiry, so a slow interactive step does not expire an active flow. Back-navigation is enforced server-side against the recorded per-step history, not a single current-step flag.
  • A step re-emitted under the same id refreshes in place, and neither the recorded history nor the wizard's progress bar gains an entry. That is how a polling step shows live progress: return the step again with a new description, and return Poll when there is nothing new to say. Every step kind renders its own description, so that is where per-submit news belongs.
  • Flow state is ephemeral.
  • An options flow reconfigures an existing instance. On every submit, including after the operator goes back a step, context.PriorStepAnswers[OptionsFlow.PriorAnswersKey] holds the instance's current configuration keyed by field name. A sensitive field's value there is OptionsFlow.RedactedValue, and a field that your Finish returns with that value keeps its stored value.

Every submit of a flow runs on the process that started it, whichever replica the request reaches, so a flow's work may live in memory between submits (a commissioning run, an open connection), keyed by the flow id. If that process stops, the next submit runs on another one that holds none of it, exactly as after a restart on one replica. Treat a submit for a flow you hold nothing for as a fresh start from the answers in the context.

Choosing from a list: the Select field

PluginConfigFieldType.Select renders a labelled select in config forms, config flows and action flows. List the choices in Options, with unique values. The answer arrives as the chosen option's Value, and your plugin validates it, since a stale form can submit a value you no longer list. A field that is not required also offers "None" (an empty string).

new PluginConfigField("nodeId", "Device", PluginConfigFieldType.Select, Required: true, Sensitive: false, null, null)
{
    Options = nodes.Select(n => new PluginConfigFieldOption(n.Id.ToString(), $"{n.Name} ({n.Id})")).ToArray(),
}

Options are sent for Select fields only. The automation editor does not render trigger configuration from the field list, so a trigger field declared Select gets no select there. The companion app renders no config forms, so it needs nothing. WASM descriptors cannot declare options yet.

Client-gated flows and client-value steps

An action flow can name a client capability through RequiredClientCapability. Clients list the flow only when they support it, and the web application supports none. Such a flow can open on a ClientValue step, whose single answer field value the host encrypts at rest, decrypts only for SubmitAsync, and never logs. The host knows no capability and no kind. The plugin and the client own the strings. Repair flows refuse a ClientValue step. How to declare both, and the kind vocabulary, are in client-gated flows.

Action results

An action flow's Finish dictionary reaches the client as the action's result and is never stored. The web dialog renders Description as text, draws QrCode as a QR code and lists every other key (except Success) as a line. The phone lists every key as a key: value line. The web dialog's "shown once, not stored" warning follows the QrCode result.

When a flow ends without the plugin ending it

An action flow (IInstanceActionFlow) and a config flow (IConfigFlowFactory) can override OnFlowEndedAsync(flowId, reason, ct). The host calls it, at most once and best-effort, when it ends the flow for the plugin: the operator aborts, a step times out or throws, or the flow reaches its deadline. A flow whose end the plugin decided (Finish or Error) claims that end first, so a later abort or timeout never calls the hook. An abort that lands while a step still runs does call it, and what the step returns afterwards is discarded.

The call runs in the background without the end waiting for it, is time-bounded, and a throw is only logged. It can arrive after the operator started a new flow, so a hook that stops a shared resource checks that it still belongs to the flow. It goes to the replica that ran the steps when that replica answers, and otherwise runs on the replica that decided the end, so reach the work through something shared and ignore a flow id you hold nothing for. The default does nothing. The table of endings, the guarantees and the cases where the plugin is not told (host stopping, a long sweeper outage, a flushed Redis) are in the flow end hook.

OAuth

Reeve can play either side of an OAuth exchange, and the two are separate stores so a compromise of one cannot decrypt the other:

Surface Reeve's role
Client Authenticates at a third-party provider and holds their access and refresh tokens. This is what a config flow uses.
Issuer Issues tokens to a third party for account linking.

Declare an OAuth step with the authorization and token endpoints, the client credentials and the scopes. The host then owns everything between the popup opening and your next submit: state generation, PKCE derivation, the callback page, token exchange and persistence. You inherit these guarantees:

  • state is 32 random bytes, expires within minutes and is single-use through an atomic read-and-delete.
  • PKCE is on by default, and only the operator can permit a named plugin type to disable it.
  • Both endpoints must be HTTPS, validated at load and again when the URL is built.
  • The token endpoint's host must be among the hosts your manifest requests, because the exchange is your plugin's egress and passes the same host allowlist and address rule as your own HTTP calls. A config: host token does not admit it, because a configuration flow runs before the owner's values join the grant. Only "*" does.
  • The redirect URI is fixed by the host, so there is no open-redirect surface. Operators behind a reverse proxy must configure the externally visible base URL.
  • The callback page uses a strict content-security policy and posts to the exact origin, never a wildcard.
  • Client secrets never reach a browser-bound payload.
  • Stored tokens are encrypted at rest with the same primitive that protects sensitive config fields.

The tokens reach your submit of the OAuth step in ConfigFlowContext.OAuth and stay with the flow, so the flow may continue with more steps after the authorisation. Whichever step returns Finish saves them with the instance.

A token response without a positive expires_in counts as valid for 3600 seconds.

A background service refreshes tokens ahead of expiry and honours refresh-token rotation. When the provider rejects the refresh grant, or after repeated transient failures, it marks the instance as requiring re-authentication, audits plugin.oauth.reauth_required and raises the oauth.reauth_required issue on the instance. That is an Error alert that tells the operator to sign in again through Edit configuration. A successful refresh, or an options flow that saves new tokens, clears the flag and the alert.

Discovery matchers

A factory may declare matchers that prefill the install form from a discovery candidate. Matching is AND across criteria, case-insensitive, and the first match wins in registration order. An unknown matcher type rejects the whole plugin at load. Discovery never installs anything by itself: an operator always reviews.

Type Criteria keys
mdns Service type and TXT-record fields
ssdp serviceType (exact), serverPattern (regex over the server string)
usb vendor, product (four-digit hex, exact), serialPattern (regex)
ble manufacturerDataPrefix (hex prefix against any company id's data), serviceUuid, namePattern
dhcp vendorClassIdentifier, hostnamePattern, parameterRequestListContains
public IReadOnlyList<PluginDiscoveryMatcher> DiscoveryMatchers =>
[
    new(Type: "usb",
        Criteria: new Dictionary<string, string> { ["vendor"] = "1cf1", ["product"] = "0030" },
        Prefill:  new Dictionary<string, string> { ["SerialPort"] = "{{devicePath}}" }),
];

Declare more specific matchers before less specific ones. A candidate's source label is data, not a matcher type. Core holds no per-vendor discovery code, so claim candidates from any source by matching on the emitted metadata. Discovery metadata is allowlisted for privacy: raw hardware addresses are hashed or masked rather than stored. See discovery.

Device onboarding

In phone-driven onboarding the user scans a code in the mobile app and the device joins. To support it, implement IDeviceOnboardingProvider on the live plugin instance, never on the factory. That runtime type check is what makes an instance offerable. Listing onboarding in the manifest's capabilities affects marketplace filtering, not offerability. OnboardingKind is a wire string ("matter"), never a numeric ordinal. The host routes strictly on {kind, pluginInstanceId} and has no default provider.

public sealed class MyPlugin : IReevePlugin, IDeviceOnboardingProvider
{
    private ThreadOperationalDataset? _cached;

    public string OnboardingKind => "matter";
    public string DisplayName    => "Matter";

    // Reads what the border router serves now, and keeps it in memory. No mutation, no timer, no window opened.
    public async Task<OnboardingContext> GetContextAsync(CancellationToken ct)
    {
        _cached ??= await ReadBorderRouterDatasetAsync(ct);
        return new OnboardingContext { Thread = _cached };
    }

    public Task<CommissionResult> CompleteOnboardingAsync(
        OnboardingResult result, OnboardingContext context, CancellationToken ct)
        => CommissionByAddressAsync(result.NetworkLocation, result.Passcode, ct);
}

CompleteOnboardingAsync returns the commissioned node and does not create a Reeve device row. Device sync owns that, correlating the node it reports back to a device.

GetContextAsync must be idempotent

The host asks for a context three times in one onboarding flow: when it builds the offer list, when it validates the target at initiate, and when it commissions. It keeps no copy in between, because an OnboardingContext carrying a Thread dataset embeds the Thread network key, and a stored snapshot would put that credential in the database in plain jsonb. See secrets and audit.

GetContextAsync must therefore read the current state and nothing else. It must not mint or rotate a dataset, form or re-form a network, open a commissioning window, allocate an ephemeral credential, or start a timer. A provider that does any of those does it three times per flow, including at the commission, and the failure is silent: nothing in the manifest refuses such a plugin.

  • Be fast, and cache in memory. Offer enumeration calls every offerable instance and allows each only Onboarding:Service:ProviderContextTimeout (5 s by default) before reporting it unavailable. Holding the answer in a field is the expected shape. The first-party Matter plugin reads its Thread Border Router once and serves the cached dataset thereafter. Keep that cache in memory only, because this value must not be written down. Invalidate it when the underlying network identity actually changes, which for Matter means a fabric reset.
  • Decide what a transient fault does. Throwing is allowed, and the host degrades. The offer is shown disabled with a generic reason, initiate returns target-unavailable and creates no session, and the commission fails the session retryably while it is still pending, so it is never stranded mid-commission. Returning an empty OnboardingContext instead keeps the flow alive. That is right when the rest of onboarding works without the context (a Matter device already on the network commissions by address and never reads the Thread dataset). Do not pick one by accident: an empty context reaches CompleteOnboardingAsync, and if your commission needs the context to succeed, that is the path that fails confusingly.

User interface, diagnostics and telemetry

A plugin ships no frontend code. Expose server-driven views as a component kind plus a payload, and the frontend renders them generically. A new capability hangs off the live plugin instance, never off a new factory member.

Diagnostics are opt-in per instance and always rendered in the most restrictive sandbox. The host redacts the assembly path and internal hostnames before the payload leaves the server. Host configuration redaction is schema-driven and recursive, while plugin-supplied data is redacted by a key-suffix heuristic only. Absent plugin data means the key is omitted, not present and null. Diagnostics never return a server error because a plugin threw: the failure is enveloped and logged. Drain and diagnostics collection both use a bounded wait rather than cancellation alone, because an uncooperative plugin ignores the token. The runaway task is abandoned and its result discarded.

Limits on what you return:

  • The heuristic redacts, recursively into nested objects and arrays, any key ending in key, token, secret or password, case-insensitively. Name your fields to match it.
  • A serialised payload past one mebibyte is discarded whole, with a too-large marker, never truncated.
  • Collection runs on a thread-pool thread inside the HTTP request, not on your receive loop, so it must never block synchronously.

Name your meter Reeve.Plugins.<typeId>, within the plugin meter namespace Reeve.Plugins.*, and your instruments are exported to the same pipeline as core metrics with no host change. The host subscribes to the whole namespace by wildcard, so never add your meter name to host startup. Tag measurements with low-cardinality labels (outcome, result, operation), never with device ids or payloads.

Testing

  • Drive the real mapper end to end for every vendor wire-translation test.
  • Substitute the host facade, and assert that a missing capability degrades rather than throws.
  • Assert on secret shape, never on a real credential.
  • Cover the round trip: every controller-writable attribute needs an observer, every observed attribute must be reconciled by the state projection, and where one direction derives a value the other must use the identical rule.

The developer tool can watch (rebuild and call the reload endpoint), test against the authoring test kit, validate (run the host's pre-flight validator locally), and validate and render a deployment. It drives the host's existing endpoints and never a parallel hot-reload path.